agent

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 24 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 Admission added in v0.2.1

type Admission struct {
	Allowed   bool
	Reason    string
	Barrier   bool
	Key       string
	Delegated bool
	Grant     Grant
}

Admission is Authorize's answer for one call; Reason goes back to the model when it may not run. 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. Grant is opaque to the engine, which hands it to Execute unchanged.

type Approvals

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

Approvals records approval requests.

type AwaitSignals added in v0.2.1

type AwaitSignals struct {
	Steered bool
	Ended   bool
	Events  bool
}

AwaitSignals is what a run parked by await may wake for: the user wrote to it, a task the await names ended, a finished task's event is pending.

type AwaitWake added in v0.2.1

type AwaitWake int

AwaitWake is why a run parked by await goes on; AwaitParked keeps it parked.

const (
	AwaitParked AwaitWake = iota
	AwaitSteered
	AwaitEnded
	AwaitTimedOut
)

func AwaitOver added in v0.2.1

func AwaitOver(await tools.Await, now time.Time, signals AwaitSignals) AwaitWake

AwaitOver says whether and why a run parked by await goes on at now: the user wrote, a task it waits for ended (any task's event, for an await that names none), or its time ran out.

type Budget

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

Budget limits one run; a zero field is unlimited.

type CompactRequest added in v0.2.1

type CompactRequest struct {
	SessionID  string
	RunID      string
	Continues  []string
	WorkingDir string
	// Model summarises unless CompactModel is set and succeeds; a window of 0
	// is unknown.
	Model               Model
	WindowTokens        int
	CompactModel        Model
	CompactWindowTokens int
	// BaseTokens estimates what every request sends besides the history.
	BaseTokens int
}

CompactRequest asks Engine.Compact for a summary of everything the model sees of a session. RunID, when set, is the run whose steps record the summary's usage and whose user messages, with those of Continues, stay verbatim.

type Config

type Config struct {
	Journal   Journal
	Tools     Tools
	Approvals Approvals
	Inbox     Inbox
	Sink      Sink
	Prompts   Prompts
	Todos     Todos
	// Hooks runs the user's hooks; nil runs none.
	Hooks Hooks
	// Verifier checks the session goal when a run would end; nil checks none.
	Verifier    Verifier
	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 Decision

type Decision struct {
	ToolCallID string
	Pending    bool
	Denied     bool
	Reason     string
}

Decision is where the newest approval of a call stands: Pending until the user answers, then granted or Denied with the user's Reason.

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) ClearContext added in v0.2.1

func (e *Engine) ClearContext(ctx context.Context, sessionID string) (transcript.Message, error)

ClearContext starts the session's model context afresh with a boundary that covers every message so far.

func (*Engine) Compact added in v0.2.1

func (e *Engine) Compact(ctx context.Context, req CompactRequest) (transcript.Message, error)

Compact summarises the session's whole context into a new boundary outside a run, the way a run does when its context fills up. ErrNothingToSummarise means the context holds nothing a summary could keep.

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 Grant added in v0.2.1

type Grant any

Grant is the Tools port's own record of a call it authorized.

type Hooks added in v0.2.1

type Hooks interface {
	SessionStart(ctx context.Context, source string) string
	Stop(ctx context.Context, reply string, active bool) string
	PreCompact(ctx context.Context, trigger string)
}

Hooks runs the user's hooks at the engine's seams. SessionStart returns context for the model, Stop why a run that would end must go on ("" lets it end; active says a Stop hook already kept it going), PreCompact only observes.

type Inbox

type Inbox interface {
	Steers(ctx context.Context) ([]Steer, error)
	ConsumeSteers(ctx context.Context, ids []string) error
	Events(ctx context.Context) ([]TaskEvent, error)
	ConsumeEvents(ctx context.Context, taskIDs []string) error
	Decisions(ctx context.Context) ([]Decision, error)
	Finished(ctx context.Context, taskIDs []string) (bool, error)
}

Inbox delivers outside input to one run. Steers and events stay pending until the engine consumes them; Decisions lists the newest approval of each call that asked, oldest first. Finished reports whether any of the background tasks ended, even if its event went elsewhere.

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)
}

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. RecordStep is usage accounting: the adapter logs a failed write, the run goes on.

type LoopKind added in v0.2.1

type LoopKind string

LoopKind is the pattern the loop guard saw.

const (
	LoopSame    LoopKind = "same"
	LoopFailing LoopKind = "failing"
	LoopCycle   LoopKind = "cycle"
	LoopReply   LoopKind = "reply"
)

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
	Interrupted    bool
	StopReason     StopReason
	Assistant      *transcript.Message
	AssistantSaved bool
	Err            error
	MarkErrored    bool
	RunState       RunState
}

Outcome is applied by core. Interrupted is set when ctx stopped for a cause other than the user's cancel; Status is then what the last step reached, or empty when it reached nothing to commit. Assistant is the final reply (completed), the reply to seal (canceled, interrupted) or the errored reply (failed with MarkErrored). StopReason is set whenever the run completed, and for a context-exhausted failure. RunState is the run's state 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 Recovery added in v0.2.1

type Recovery struct {
	Settle  Settle
	Request tools.ApprovalRequest
	Result  tools.Result
}

Recovery settles one interrupted call: Request is what SettleAsk asks, Result what SettleAnswer journals.

type RunState added in v0.2.1

type RunState 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 and LoopReplies hold the loop guard's windows of calls and
	// long replies; LoopKind, LoopTool and LoopRepeats are what it saw.
	LoopRecent  string   `json:"loop_recent,omitempty"`
	LoopReplies string   `json:"loop_replies,omitempty"`
	LoopKind    LoopKind `json:"loop_kind,omitempty"`
	LoopTool    string   `json:"loop_tool,omitempty"`
	LoopRepeats int      `json:"loop_repeats,omitempty"`
	LoopWarned  bool     `json:"loop_warned,omitempty"`
	// Continuations counts replies in a row cut by the output limit; CallCut is
	// set until the model is told a cut dropped its tool call.
	Continuations int  `json:"continuations,omitempty"`
	CallCut       bool `json:"call_cut,omitempty"`
	OutputLimit   int  `json:"output_limit,omitempty"`
	// Malformed counts replies in a row whose tool call could not be decoded.
	Malformed     int   `json:"malformed,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"`
	// Unverified is set while files changed since the run's last successful
	// build, test or lint command; VerifyNudged once the model was asked to check.
	Unverified   bool `json:"unverified,omitempty"`
	VerifyNudged bool `json:"verify_nudged,omitempty"`
	// StopHooks counts the replies Stop hooks held back.
	StopHooks int `json:"stop_hooks,omitempty"`
	// GoalHolds counts the replies a failed goal check held back.
	GoalHolds int `json:"goal_holds,omitempty"`
	// Await is set while the run waits for what an await call asked for.
	Await *tools.Await `json:"await,omitempty"`
}

RunState is what a run has used and what the engine remembers between its steps: budget use, the loop guard's window, output-limit cuts, summaries, elision, learned prompt room, the notes already sent and what the run awaits. It is checkpointed so a parked or restarted run continues from it.

func (RunState) Carried added in v0.2.1

func (s RunState) Carried() RunState

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 Settle

type Settle string

Settle is how a resumed run settles a call its interrupted execution 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
	RunState RunState
}

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 RunState lets a parked or restarted run keep its budget.

type Status

type Status string

Status is what a Run call reached.

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

type Steer added in v0.2.1

type Steer struct {
	ID     string
	Text   string
	Images []transcript.MessagePart
}

Steer is input the user sent the running run: Text with the Images sent with it.

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              RunState
	// 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; the calls it left without a result are settled as
	// Tools.Recovery says.
	Recovering bool
}

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

type TaskEvent added in v0.2.1

type TaskEvent struct {
	TaskID string
	Text   string
}

TaskEvent says a background task ended; the model reads Text.

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) (Admission, error)
	Execute(ctx context.Context, grant Grant) (tools.Result, *tools.ApprovalRequest, error)
	Recovery(ctx context.Context, name string, call tools.Call) (Recovery, error)
}

Tools lists, authorizes and executes the tools of one run. Execute runs a call Authorize allowed and 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. Recovery says how a resumed run settles a call its interrupted execution left without a result.

type Verdict added in v0.2.1

type Verdict struct {
	Hold bool
	Note string
}

Verdict is what a goal check found.

type Verifier added in v0.2.1

type Verifier interface {
	Verify(ctx context.Context, sessionID, runID string) (Verdict, error)
}

Verifier checks the session's goal when a run would end with a reply. Hold keeps the run going with Note (a failed check); otherwise a Note (a passed check, a goal marked blocked) is journaled for the user and the run ends. A session without an active goal or check gets the zero Verdict.

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