runner

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 16 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 runner is the Agent runtime: it loads history by session ID, builds the context of each run, drives the Agent, persists messages, manages queued messages and history compaction, and hands the events of a run to its caller.

A Runner holds one Agent and one store and serves any number of sessions: different sessions can run concurrently, and each session has at most one run at a time. That guarantee only holds within one Runner instance: when several processes or instances share a store, the caller must ensure mutual exclusion per session (for example by routing a session to a fixed instance, or with a distributed lock). Who the Agent is (instructions, model, tools) is defined on agent.Agent, what is stored is defined in the session package, and the Runner only runs them.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrBusy means the session already has a run in progress.
	ErrBusy = errors.New("runner: session is busy")
	// ErrNotRunning means the session has no run in progress, so messages cannot be queued.
	ErrNotRunning = errors.New("runner: session is not running")
	// ErrInvalidConfig means the Runner configuration is incomplete.
	ErrInvalidConfig = errors.New("runner: invalid config")
)

Functions

This section is empty.

Types

type CompactInput

type CompactInput struct {
	// Messages are the session messages currently in the model context, with earlier summaries applied:
	// when there is a summary it comes first, followed by the kept messages and those added since.
	Messages []session.Message
	// Tokens is the estimated context usage, and MaxInputTokens the model's context limit.
	Tokens         int
	MaxInputTokens int
	// Reason says how this compaction was triggered.
	Reason CompactReason
	// Instructions are the caller's extra requirements for the summary in a manual compaction; may be empty.
	Instructions string
	// Client is the model client of the session, which can be used to generate the summary.
	Client chat.Client
}

CompactInput is the input of one compaction decision.

type CompactReason

type CompactReason string

CompactReason says how a compaction was triggered.

const (
	// CompactAuto is the routine check before a run and after each turn; the Compactor decides from the usage whether to compact.
	CompactAuto CompactReason = "auto"
	// CompactOverflow means the model already failed because the context was exceeded; compact as much as possible regardless of the estimate.
	CompactOverflow CompactReason = "overflow"
	// CompactManual means the caller asked for compaction through Runner.Compact; compact as much as possible regardless of the estimate.
	// MaxInputTokens is 0 when the model declares no context limit.
	CompactManual CompactReason = "manual"
)

type CompactResult

type CompactResult struct {
	Summary string
	// FirstKeptID is the ID of the first kept message and must come from CompactInput.Messages.
	// It cannot be a tool result message, or its tool call would be summarized away and leave an orphan result.
	FirstKeptID string
	// Usage is the tokens consumed generating the summary, counted in the run result.
	Usage chat.Usage
}

CompactResult describes a compaction: the messages before FirstKeptID are replaced by Summary.

type Compactor

type Compactor interface {
	Compact(ctx context.Context, in CompactInput) (*CompactResult, error)
}

Compactor decides when and how to compact session history. Returning nil means no compaction this time.

The Runner calls it automatically at three points: before each run, after each turn of a run, and when the model reports a context overflow; callers can also trigger it manually with Runner.Compact; see CompactInput.Reason. The original messages always stay in the store; compaction only affects what enters the model context.

type Config

type Config struct {
	// Agent is the Agent to run.
	// Do not modify it after handing it to the Runner: every run of every session reads this one definition without synchronization.
	Agent *agent.Agent
	// Store is the session store; an in-memory store is used when nil.
	Store session.Store
	// Converter converts session messages into model-visible messages; DefaultConverter is used when nil.
	Converter MessageConverter
	// Compactor is the history compaction strategy; SummaryCompactor with defaults is used when nil.
	// There is no compaction when the model declares no context limit (ModelInfo.MaxInputTokens is 0).
	Compactor Compactor
	// DisableCompaction turns compaction off.
	DisableCompaction bool
	// Middlewares are the runtime middlewares, applied to every run on this Runner, including the sub-agents it spawns.
	// Steps every Agent must go through rather than ones belonging to a particular Agent, such as approval, auditing and tracing, go here.
	// They wrap the Agent's own middlewares, so an Agent can only add its own behavior inside them; history compaction is innermost.
	Middlewares []agent.Middleware

	// OnTaskStarted is called after a task starts running, exactly once per task and before the other callbacks.
	OnTaskStarted func(ctx context.Context, task tool.Task)
	// OnTaskProgressed is called every time a task reports progress, for live display. task is the snapshot with the progress merged;
	// for a sub-agent, update.Event is the Event of the run on the child session, the same as Stream hands to its caller,
	// and for a background command update.Output is the new output.
	OnTaskProgressed func(ctx context.Context, task tool.Task, update tool.TaskUpdate)
	// OnTaskFinished is called after a task ends and its result has been sent back to the session that spawned it, exactly once per task and last.
	// When delivery is ResultSavedToHistory the main Agent has not seen the result yet, and the business layer decides whether to wake it,
	// for example with r.Stream(ctx, task.SessionID, Input{}).
	OnTaskFinished func(ctx context.Context, task tool.Task, delivery TaskResultDelivery)
}

Config is the configuration for creating a Runner.

type ContextInput

type ContextInput struct {
	Text    string
	Content []chat.ContentBlock
	// Source and Kind describe where the context comes from and what it is, by the business layer's own convention, and may be empty; when set they become attributes of <app_context> visible to the model.
	Source string
	Kind   string
	// Scope defaults to session.ScopeRun: it only enters this run and is not written to the session.
	// session.ScopePersistent writes it to the session, keeping it visible to later runs.
	Scope   session.Scope
	Details any
	Visible bool
}

ContextInput is business context injected with a run, such as the page the user is on. It is merged into the user message as <app_context>, visible to the model but hidden from the user by default.

type DefaultConverter

type DefaultConverter struct{}

DefaultConverter is the default message converter: consecutive user messages and business context are merged into one model message, business context is wrapped in <app_context>, and summaries in <conversation_summary>.

func (DefaultConverter) ToChatMessages

func (DefaultConverter) ToChatMessages(_ context.Context, messages []session.Message) ([]chat.Message, error)

type Event

type Event struct {
	Type      EventType
	SessionID string
	RunID     string

	Message    *session.Message
	AgentEvent *agent.Event
	Queue      *Queue
	// Result carries the run result on run_end.
	Result *Result
}

Event is an event during a run.

func (Event) TextDelta

func (e Event) TextDelta() string

TextDelta returns the reply text delta of this event, or "" when it is not a text delta event.

func (Event) ThinkingDelta

func (e Event) ThinkingDelta() string

ThinkingDelta returns the thinking text delta of this event, or "" when it is not a thinking delta event.

type EventType

type EventType string

EventType is the type of an event during a run.

const (
	EventRunStart EventType = "run_start"
	// EventRunEnd is the last event of a run and carries the run result.
	EventRunEnd EventType = "run_end"
	// EventMessageSaved is emitted after a message has been stored.
	EventMessageSaved EventType = "message_saved"
	// EventQueueUpdate is emitted when the queued messages change.
	EventQueueUpdate EventType = "queue_update"
	// EventAgentEvent forwards events of the Agent run (model stream, tool execution and so on).
	EventAgentEvent EventType = "agent_event"
	// EventCompaction is emitted after the history was compacted; Message is the stored summary message.
	EventCompaction EventType = "compaction"
)

type Input

type Input struct {
	Content []chat.ContentBlock
}

Input is one user input: content blocks in order, which can only be text and media (chat.Media, chat.MediaURL).

func Parts

func Parts(blocks ...chat.ContentBlock) Input

Parts returns an input made of several content blocks, such as some text and a few images.

func Text

func Text(text string) Input

Text returns a plain text input.

type MessageConverter

type MessageConverter interface {
	ToChatMessages(ctx context.Context, messages []session.Message) ([]chat.Message, error)
}

MessageConverter converts session messages into messages visible to the model.

It also converts queued steer / follow-up messages, which can only become user messages (possibly merged into fewer messages).

type Queue

type Queue struct {
	Steer    []session.Message
	FollowUp []session.Message
}

Queue holds the messages waiting to be injected.

type Result

type Result struct {
	SessionID string
	RunID     string
	// Status is how the run ended; it is StatusFailed when infrastructure such as the store fails.
	Status agent.Status
	// Messages are all messages stored by this run, and Final is the last assistant message.
	Messages []session.Message
	Final    *session.Message
	// Usage includes the tokens consumed by model calls, inside tools and generating summaries.
	Usage chat.Usage
	// Pending are the steer / follow-up messages not yet injected when the run ended; they did not enter history.
	// Messages taken by Abort are returned by Abort, not here.
	Pending Queue
}

Result is the result of a run. It is still valid when Run returns an error and contains the messages produced so far.

type RunOption

type RunOption func(*runOptions)

RunOption adjusts a run.

func WithContext

func WithContext(inputs ...ContextInput) RunOption

WithContext injects business context into this run.

func WithDetails

func WithDetails(details any) RunOption

WithDetails attaches business data to this run's user message (session.Message.Details).

type Runner

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

Runner runs one Agent and serves many sessions. It is safe for concurrent use.

func New

func New(cfg Config) (*Runner, error)

New creates a Runner.

func (*Runner) Abort

func (r *Runner) Abort(sessionID string) Queue

Abort cancels the session's current run and returns the queued messages not yet injected (they do not enter history). It returns an empty queue when idle. It does not wait for the run to end; call Wait for that.

func (*Runner) Compact

func (r *Runner) Compact(ctx context.Context, sessionID, instructions string) (*session.Message, chat.Usage, error)

Compact immediately compacts the history of an idle session, for when the user asks for it, and returns the stored summary message and the tokens consumed generating it; the summary is nil when there is nothing to compact. On error the tokens already consumed are still returned. instructions are extra requirements for the summary and may be empty; see CompactInput.Instructions.

The session is occupied during compaction: Run returns ErrBusy, Steer / FollowUp return ErrNotRunning, Abort cancels the compaction, and background task results are written to history after it ends. It returns ErrBusy while the session is running, and an error when compaction is disabled.

func (*Runner) FollowUp

func (r *Runner) FollowUp(sessionID string, in Input) error

FollowUp queues a follow-up message, injected when the model gives its final reply and the run would end; the current task is not affected. It returns ErrNotRunning when the session is not running.

func (*Runner) ListTasks

func (r *Runner) ListTasks(sessionID string) []tool.Task

ListTasks returns the background tasks spawned by the session whose results have not been delivered, ordered by start time.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, sessionID string, in Input, opts ...RunOption) (*Result, error)

Run processes one user input in a session: it stores it, loads the history and drives the Agent to the end. The session is created if it does not exist; an empty sessionID generates a new one, see Result.SessionID. It returns ErrBusy when the session already has a run in progress.

An empty in (Input{}) appends no new input and continues from the existing history, for example to wake the main Agent after a background task's result was written to history; the history must then end with a user-side message or a tool result.

When a model call fails, the run is canceled or the turn limit is reached, a non-nil error is returned and Result is still valid: Status gives the end status and Messages the messages produced and stored so far.

func (*Runner) Running

func (r *Runner) Running(sessionID string) bool

Running reports whether the session currently has a run in progress.

func (*Runner) Steer

func (r *Runner) Steer(sessionID string, in Input) error

Steer interjects mid-run: the message is injected after the current turn's tools finish and before the next model call, to correct or add to the task in progress. It never interrupts tools that are executing. It returns ErrNotRunning when the session is not running.

func (*Runner) StopTask

func (r *Runner) StopTask(ctx context.Context, id string) error

StopTask stops a background task and waits for it to end. The result is still sent back to the session as a notice, with the stopped status. It returns tool.ErrTaskNotFound when the task does not exist or has already ended. Do not call it synchronously from this task's callbacks: they run on the task's goroutine and would wait on each other.

func (*Runner) Store

func (r *Runner) Store() session.Store

Store returns the underlying session store, for reading history.

func (*Runner) Stream

func (r *Runner) Stream(ctx context.Context, sessionID string, in Input, opts ...RunOption) iter.Seq2[Event, error]

Stream does the same as Run and hands the events of the run to the caller one by one.

The run follows the caller: it continues only after an event is taken, and stops when the caller stops iterating or ctx is canceled. To keep a run going after a client disconnects, or to fan events out to several receivers, iterate and forward in your own goroutine.

error appears at most once, in the last iteration, with the same meaning as Run's return value. Once the run has started, the last event is run_end and its Result is the run result; when it could not start (for example ErrBusy) the event is the zero value.

func (*Runner) Wait

func (r *Runner) Wait(ctx context.Context, sessionID string) error

Wait waits for the session's current run to end. It returns immediately when idle.

type SummaryCompactor

type SummaryCompactor struct {
	// TriggerRatio is the context usage ratio that triggers compaction, 0.8 by default.
	TriggerRatio float64
	// KeepRatio is the share of the context limit kept as recent messages after compaction, 0.2 by default.
	KeepRatio float64
	// Prompt is the system prompt for generating the summary; an empty one uses the built-in prompt.
	Prompt string
	// Client is the model that generates the summary; empty uses the session's model. A cheaper model can be used.
	Client chat.Client
	// Options are the parameters of the summary request, passed to the model as is. MaxTokens of 0 becomes 4096;
	// an empty CacheRetention disables caching, since the summary request's content is used only once.
	Options chat.Options
}

SummaryCompactor is the default compaction strategy: when context usage exceeds a threshold, it keeps the most recent messages as they are and has the model summarize the earlier part. The cut prefers user messages and never separates a tool call from its result. The zero value works.

func (SummaryCompactor) Compact

type TaskResultDelivery

type TaskResultDelivery string

TaskResultDelivery says how a background task's result was sent back to the session.

const (
	// ResultInjectedIntoRun means the session was running and the result was injected into that run, where the main Agent handles it.
	ResultInjectedIntoRun TaskResultDelivery = "injected_into_run"
	// ResultSavedToHistory means the session was idle and the result was only written to history; the main Agent has not seen it yet.
	ResultSavedToHistory TaskResultDelivery = "saved_to_history"
)

Jump to

Keyboard shortcuts

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