agent

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package agent provides the agent registry and the Turn/Step execution loop.

It follows upstream packages/core/agent and agent-loop. Input enters the Inbox turn queue; a background worker processes one turn at a time: turn/start, claim, pre-step, one or more steps, turn-stopping, and turn/end. Each step derives state, emits agent/request, consumes llm/stream and assistant/chunk events, runs tools through the M23 pipeline, and closes. Step or tool errors emit agent/error and interrupt the turn. A full pending turn queue rejects Run and Followup with ErrTurnQueueFull.

This file implements the five Agent cancellation categories (M18), following upstream packages/core/agent/Agent.ts. Cancellation is recorded as "cancel:<cause>" in turn-stopping; ExtractCancelCause recovers the category, and turn/end closes the turn as aborted.

This file follows upstream packages/core/agent/src/consumed-work.ts. It accounts for consumed work that Turn/Step events alone cannot distinguish: a turn aborted before its first step differs from a balanced no-op turn created by a rejected or empty claim. Inbox removedCount and canceled outcomes distinguish claimed input from work discarded before execution.

Inbox follows upstream packages/core/agent/src/inbox.ts. It incrementally projects two ordered pending-input lists owned by Agent: next-turn holds prompts awaiting a turn, and next-step holds input awaiting the next step boundary.

This file implements Agent Initiator attribution (M33), following the upstream agent initiator module. WithInitiator adds agent identity and operation to the context; RequireInitiator rejects anonymous calls with a structured Unauthorized error. WithoutInitiator explicitly removes identity when entering an uncontrolled execution scope.

This file follows upstream packages/core/agent/src/model-selection.ts. Upstream captures model selection before prompt assembly and applies that snapshot when routing the request, so concurrent changes affect only later steps. Omnix's synchronous assembler uses a thread-safe current/assembled state machine with explicit Capture and Apply calls instead of asynchronous Cordis waterfall events.

Agent configuration and runtime types follow upstream packages/core/agent/src/runtime-types.ts and types.ts.

This file implements the agent/request-error retry waterfall (M34), following upstream agent-loop. Actions are retry or abort. Middleware uses the M02 onion chain and may short-circuit; otherwise TerminalRetryDecision handles the error. After S15 exhausts LLM-level backoff retries and llm/retry events, this waterfall decides whether to retry again or abort. Exhausting the retry limit aborts the turn and records agent/error.

Index

Constants

This section is empty.

Variables

View Source
var ErrDisposed = errors.New("agent: disposed")

ErrTurnQueueFull indicates that the pending turn queue cannot accept Run or Followup.

View Source
var ErrTurnQueueFull = errors.New("agent: turn queue full, reject pending turn")

Functions

func RecordCancel

func RecordCancel(sl *session.SessionLog, cause CancelCause) error

RecordCancel records the cancellation cause in a turn-stopping event.

func RecordRequestError

func RecordRequestError(log *session.SessionLog, err error)

RecordRequestError writes agent/error to the session log for auditing. A nil log skips recording.

func ShouldRetryError

func ShouldRetryError(err error) bool

ShouldRetryError uses LLM classification: only overload and rate-limit qualify.

func WithInitiator

func WithInitiator(ctx context.Context, agentID brand.SessionID, op string) context.Context

WithInitiator returns a context carrying the initiator.

func WithoutInitiator

func WithoutInitiator(ctx context.Context) context.Context

WithoutInitiator returns a context with initiator identity removed.

Types

type Agent

type Agent struct {
	// ID is the session ID shared with SessionLog.
	ID brand.SessionID
	// contains filtered or unexported fields
}

Agent executes agent turns and steps.

func NewAgent

func NewAgent(id brand.SessionID, log *session.SessionLog, sys *sysprompt.Assembler, pipeline *tools.Pipeline, adapter llm.LLMAdapter, options ...AgentOptions) *Agent

NewAgent creates an agent. A nil adapter may be replaced before Start in tests. Nil options select the defaults.

func (*Agent) Cancel

func (a *Agent) Cancel(cause CancelCause)

Cancel aborts the active turn and discards queued work unless KeepInbox is set.

func (*Agent) CancelWithOptions

func (a *Agent) CancelWithOptions(cause CancelCause, opts CancelOptions)

func (*Agent) Dispose

func (a *Agent) Dispose()

Dispose permanently closes the agent and cancels active and pending work. Tool and adapter implementations must honor context cancellation.

func (*Agent) Followup

func (a *Agent) Followup(input string) error

Followup queues a subsequent turn.

func (*Agent) Inbox

func (a *Agent) Inbox() *Inbox

Inbox returns the agent's pending next-turn and next-step input queues.

func (*Agent) Log

func (a *Agent) Log() *session.SessionLog

Log returns the event-sourced log for tests and higher-level projections.

func (*Agent) Options

func (a *Agent) Options() AgentOptions

Options returns the agent configuration for read-only use.

func (*Agent) Run

func (a *Agent) Run(input string) error

Run queues a new turn. WhenIdle waits for all accepted work.

func (*Agent) SetRunContext

func (a *Agent) SetRunContext(parent context.Context, timeout time.Duration)

SetRunContext binds the parent context and an optional timeout budget (H01). A nonpositive timeout uses DefaultTimeout, or parent cancellation alone if both are zero.

func (*Agent) SetToolProvider

func (a *Agent) SetToolProvider(fn func(name string) *tools.Tool)

SetToolProvider installs the tool resolver.

func (*Agent) Status

func (a *Agent) Status() AgentStatus

Status returns the current lifecycle state: idle or running.

func (*Agent) WhenIdle

func (a *Agent) WhenIdle(ctx context.Context) error

WhenIdle waits until agent activity settles; it returns immediately if already idle.

type AgentOptions

type AgentOptions struct {
	// Provider names a registered adapter route; empty uses the adapter default.
	Provider string `json:"provider,omitempty"`

	// Model is interpreted by the selected provider; empty uses its default model.
	Model string `json:"model,omitempty"`

	// ReasoningEffort is provider/model-specific; empty uses adapter defaults.
	ReasoningEffort string `json:"reasoningEffort,omitempty"`

	// MaxTokens limits output tokens per model request; zero uses the adapter default.
	MaxTokens int `json:"maxTokens,omitempty"`

	// DefaultTimeout is the per-run timeout; zero disables the timeout.
	DefaultTimeout time.Duration `json:"defaultTimeout,omitempty"`
}

AgentOptions configures agent creation, matching upstream AgentOptions. Options are fixed at creation and immutable at runtime. Persona belongs to the system prompt and is not configured here.

type AgentStatus

type AgentStatus string

AgentStatus describes agent lifecycle state, matching upstream AgentStatus. Transitions emit agent/status. Idle means no active driver. Running begins when wake-up input starts cancellable pre-step processing and lasts until the driver drains, closes, or checkpoints turns. Disposal removes the agent from its registry; it is not a third observable state.

const (
	// StatusIdle indicates no active driver.
	StatusIdle AgentStatus = "idle"
	// StatusRunning indicates an active driver.
	StatusRunning AgentStatus = "running"
)

type CancelCause

type CancelCause string

CancelCause identifies one of the five cancellation categories (M18).

const (
	// CancelUser indicates an explicit user cancellation.
	CancelUser CancelCause = "user"
	// CancelParent indicates cancellation by a parent agent.
	CancelParent CancelCause = "parent"
	// CancelHook indicates cancellation after a hook rejects an operation.
	CancelHook CancelCause = "hook"
	// CancelDisposed indicates cancellation when the agent is disposed.
	CancelDisposed CancelCause = "disposed"
	// CancelLegacy identifies the legacy compatibility cancellation path.
	CancelLegacy CancelCause = "legacy"
)

Cancellation causes match the five upstream Agent.Cancel categories.

func AllCancelCauses

func AllCancelCauses() []CancelCause

AllCancelCauses returns all five causes for validation and tests.

func ExtractCancelCause

func ExtractCancelCause(events []session.SessionEvent) (CancelCause, bool)

ExtractCancelCause returns the last cancellation cause in the event log. The boolean reports whether a cancellation record was found.

type CancelOptions

type CancelOptions struct {
	// KeepInbox preserves queued and steering input instead of discarding it.
	// The active turn still aborts, but pending work remains for later turns
	// and no canceled inbox splice is recorded.
	KeepInbox bool `json:"keepInbox,omitempty"`
}

CancelOptions configures cancellation, matching upstream CancelOptions.

type ConsumedWork

type ConsumedWork struct {
	// End is the last closed turn that accounted for consumed work: it entered a
	// model step or claimed inbox input and then failed, aborted, or was blocked.
	// It is nil if no turn accounted for work.
	End *session.SessionEvent
	// DroppedUnrun reports accepted inbox work canceled after End without running.
	// No turn/end event exists for input canceled before a turn could start.
	DroppedUnrun bool
}

ConsumedWork accounts for work consumed by an agent log.

func FoldConsumedWork

func FoldConsumedWork(events []session.SessionEvent) ConsumedWork

FoldConsumedWork accounts for consumed work in one pass over an agent log or an owned suffix. It uses only persisted events, so callers need not sample live state before cancellation; teardown, parent interrupts, and plugin unloading all have the same interpretation.

type Inbox

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

Inbox incrementally projects persisted agent inbox events into next-turn and next-step lists, updated by splice operations.

func NewInbox

func NewInbox(log *session.SessionLog, notifications InboxNotifications) *Inbox

NewInbox creates an inbox and replays all agent/inbox/spliced events in the log.

func (*Inbox) Claim

func (inbox *Inbox) Claim(log *session.SessionLog, target session.InboxTarget, turn uint64) []UserMessage

Claim removes and returns the complete proposed step batch and publishes each claimed message. The persisted splice only deletes entries. Target determines whether to consume a queued turn as well; turn identifies the owning turn. Next-step inputs precede the queued turn, if requested.

func (*Inbox) Clear

func (inbox *Inbox) Clear(log *session.SessionLog)

Clear persists cancellation of all pending input, clearing next-step before next-turn.

func (*Inbox) HasPending

func (inbox *Inbox) HasPending() bool

HasPending reports whether either pending-input list contains work.

func (*Inbox) NextStep

func (inbox *Inbox) NextStep() []UserMessage

NextStep returns input awaiting the next step boundary for read-only use.

func (*Inbox) NextTurn

func (inbox *Inbox) NextTurn() []UserMessage

NextTurn returns pending turn input for read-only use.

func (*Inbox) Push

func (inbox *Inbox) Push(log *session.SessionLog, target session.InboxTarget, message UserMessage)

Push appends a message to the selected list and persists the change.

type InboxNotifications

type InboxNotifications struct {
	// Inserted publishes an inserted message.
	Inserted func(message UserMessage)
	// Discarded publishes a discarded message.
	Discarded func(message UserMessage)
	// Claimed publishes a claimed message within its owning turn.
	Claimed func(message UserMessage, turn uint64)
}

InboxNotifications publishes live inbox changes.

type Initiator

type Initiator struct {
	// AgentID is the initiating agent's session ID.
	AgentID brand.SessionID
	// Op names the operation, such as Run, Followup, or executeTool.
	Op string
}

Initiator identifies the agent initiating an operation.

func MustInitiator

func MustInitiator(ctx context.Context) *Initiator

MustInitiator panics if no initiator exists; use only where attribution is guaranteed.

func RequireInitiator

func RequireInitiator(ctx context.Context) (*Initiator, error)

RequireInitiator returns the initiator or UnauthorizedInitiatorError. Use it at operation boundaries requiring security attribution.

type ModelSelection

type ModelSelection struct {
	// Provider is the registered provider route.
	Provider string
	// Model is the provider-owned model identifier.
	Model string
	// ReasoningEffort is adapter-defined; empty selects provider defaults.
	ReasoningEffort string
}

ModelSelection identifies the provider, model, and optional reasoning effort for an active agent.

type ModelSelectionRef

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

ModelSelectionRef holds mutable selection and the snapshot captured for the current step.

func NewModelSelectionRef

func NewModelSelectionRef() *ModelSelectionRef

NewModelSelectionRef creates an empty selector.

func (*ModelSelectionRef) Apply

Apply follows upstream agent/request semantics. Without a captured selection, it preserves inherited configuration. Otherwise it clears inherited reasoning effort, applies provider/model, and uses the captured effort if present. An empty captured effort restores the selected provider's default behavior.

func (*ModelSelectionRef) Assembled

func (r *ModelSelectionRef) Assembled() *ModelSelection

Assembled returns a copy of the snapshot captured for this step.

func (*ModelSelectionRef) Capture

func (r *ModelSelectionRef) Capture() *ModelSelection

Capture freezes current into assembled at the prompt assembly boundary. A nil snapshot means this step does not specify a model.

func (*ModelSelectionRef) Current

func (r *ModelSelectionRef) Current() *ModelSelection

Current returns a copy of the current selection.

func (*ModelSelectionRef) Select

func (r *ModelSelectionRef) Select(sel *ModelSelection)

Select updates the next step's selection concurrently; nil restores defaults.

type PreStepDecision

type PreStepDecision struct {
	// Kind is either reject or enter.
	Kind string `json:"kind"`
	// Messages contains admitted user input when Kind is enter.
	Messages []UserMessage `json:"messages,omitempty"`
	// StartsRequestSeries optionally starts a distinct model-message series
	// before the admitted input when Kind is enter.
	StartsRequestSeries bool `json:"startsRequestSeries,omitempty"`
}

PreStepDecision determines whether to enter a proposed step and which messages it receives, matching upstream PreStepDecision.

func EnterPreStep

func EnterPreStep(messages ...UserMessage) PreStepDecision

EnterPreStep creates a decision admitting the supplied messages.

func RejectPreStep

func RejectPreStep() PreStepDecision

RejectPreStep creates a decision that does not enter the step.

type RequestConfig

type RequestConfig struct {
	Provider        string
	Model           string
	ReasoningEffort string
}

RequestConfig contains mutable request fields used for model routing.

type RequestErrorAction

type RequestErrorAction struct {
	// Kind identifies the action.
	Kind RequestErrorActionKind `json:"kind"`
	// Reason records the decision rationale for auditing.
	Reason string `json:"reason,omitempty"`
}

RequestErrorAction is the result of handling a request error.

func ResolveRequestError

func ResolveRequestError(chain *RequestErrorWaterfall, p *RequestErrorPayload) RequestErrorAction

ResolveRequestError returns the action set by middleware, or applies TerminalRetryDecision when the chain falls through without an action.

func TerminalRetryDecision

func TerminalRetryDecision(p *RequestErrorPayload) RequestErrorAction

TerminalRetryDecision retries eligible errors below the retry limit; otherwise it aborts so the turn can close with an error.

type RequestErrorActionKind

type RequestErrorActionKind string

RequestErrorActionKind identifies a request-error action.

const (
	ActionRetry RequestErrorActionKind = "retry"
	ActionAbort RequestErrorActionKind = "abort"
)

The only request-error actions are retry and abort.

type RequestErrorPayload

type RequestErrorPayload struct {
	// Err is the underlying request error.
	Err error
	// RetryCount counts retries already attempted.
	RetryCount int
	// MaxRetries limits retry attempts.
	MaxRetries int
	// RetryableError indicates overload or rate-limit errors that may be retried.
	RetryableError bool
	// Action is the final action selected by the waterfall.
	Action *RequestErrorAction
}

RequestErrorPayload is shared by request-error middleware.

func NewRequestErrorPayload

func NewRequestErrorPayload(err error, retryCount, maxRetries int) *RequestErrorPayload

NewRequestErrorPayload constructs the payload and computes retryability.

type RequestErrorWaterfall

type RequestErrorWaterfall = waterfall.Chain[RequestErrorPayload]

RequestErrorWaterfall handles request errors using the M02 waterfall.Chain. Middleware may set p.Action and stop the chain by not calling next.

func NewRequestErrorWaterfall

func NewRequestErrorWaterfall(handlers ...waterfall.Handler[RequestErrorPayload]) *RequestErrorWaterfall

NewRequestErrorWaterfall constructs the request-error chain.

type SessionStartSource

type SessionStartSource string

SessionStartSource identifies why a session lifecycle starts: startup creates a seed, resume loads persistence, clear restarts after clearing, and compact restarts after compaction.

const (
	// StartSourceStartup indicates seed creation.
	StartSourceStartup SessionStartSource = "startup"
	// StartSourceResume indicates loading persisted state.
	StartSourceResume SessionStartSource = "resume"
	// StartSourceClear indicates restarting after clearing.
	StartSourceClear SessionStartSource = "clear"
	// StartSourceCompact indicates restarting after compaction.
	StartSourceCompact SessionStartSource = "compact"
)

type UnauthorizedInitiatorError

type UnauthorizedInitiatorError struct {
	Op string
}

UnauthorizedInitiatorError indicates a RequireInitiator call without an initiator.

func (*UnauthorizedInitiatorError) Error

Error implements the error interface.

type UserMessage

type UserMessage struct {
	// ID identifies the message.
	ID string `json:"id"`
	// Content contains the message text.
	Content string `json:"content"`
	// Source identifies the origin, such as run, followup, or inbox.
	Source string `json:"source,omitempty"`
	// CreatedAt records creation time.
	CreatedAt time.Time `json:"createdAt,omitempty"`
}

UserMessage is a simplified representation of upstream UserMessage.

Jump to

Keyboard shortcuts

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