Agent class

Agent owns the current transcript, emits lifecycle events, executes tools, and exposes queueing APIs for steering and follow-up messages. Port of pi's Agent.

Constructors

Agent({Model? model, String? systemPrompt, List<Tool>? tools, List<Message>? messages, required StreamFunction streamFunction, ToolExecutor? toolExecutor, ToolRegistry? toolRegistry, BeforeToolCallHook? beforeToolCall, AfterToolCallHook? afterToolCall, TransformContextHook? transformContext, PrepareNextTurnHook? prepareNextTurn, QueuedMessagesSource? externalSteeringSource, Future<bool> externalSteeringProbe()?, QueueMode steeringMode = QueueMode.oneAtATime, QueueMode followUpMode = QueueMode.oneAtATime, ToolExecutionMode toolExecution = ToolExecutionMode.parallel, int maxEmptyRetries = 1, Duration runIdleTimeout = defaultRunIdleTimeout, void onRunIdleTimeout(Object error)?, int? contextWindowCap, bool wireDump = false, OverWindowRelief? overWindowRelief})
Creates an agent. See the library doc for the pi mapping.

Properties

afterToolCall AfterToolCallHook?
Called after a tool finishes; can override the result. See AfterToolCallHook.
getter/setter pair
beforeToolCall BeforeToolCallHook?
Called before a tool is executed; can block it. See BeforeToolCallHook.
getter/setter pair
cancelToken CancelToken?
Active cancel token for the current run, if any.
no setter
contextWindowCap int?
Owner-side effective context override (agent.contextWindowCap, issues #273/#729), threaded into every AgentLoopConfig the agent builds so the loop's over-window guard trips at the overridden window — clamped down under the catalog value, raised above it when the endpoint serves more than the catalog reports. null = the raw model window.
final
externalSteeringProbe Future<bool> Function()?
Non-draining probe paired with externalSteeringSource: returns true when the external source has messages pending. Polled on a slow timer during tool-call phases so external mail also triggers the soft-yield of long-running tools (steering delivery itself stays at the boundary).
getter/setter pair
externalSteeringSource QueuedMessagesSource?
External messages merged into the steering poll at every turn boundary (before the first turn and after each one) — e.g. the agent's inbox in the messaging fabric. Drained BEFORE the in-process steering queue. Contract: must not throw; return an empty list when nothing arrived.
getter/setter pair
followUpMode QueueMode
Controls how queued follow-up messages are drained.
getter/setter pair
hashCode int
The hash code for this object.
no setterinherited
hasSteering bool
Returns true when steering messages are still queued (e.g. they arrived after the run's last drain point — the host decides whether to run or drop them, but never silently).
no setter
maxEmptyRetries int
How many times a degenerate-empty assistant response is retried within the loop before the turn is accepted. Default: 1.
final
onRunIdleTimeout → void Function(Object error)?
Reports every run-idle watchdog fire (after runIdleTimeout of event silence); hosts log it for post-mortem "who held the busy row".
final
overWindowRelief OverWindowRelief?
Emergency relief for the loop's over-window guard (issue #387), threaded into every AgentLoopConfig. null = the guard keeps today's behavior (verbatim error, no mid-turn compaction).
final
prepareNextTurn PrepareNextTurnHook?
Adjusts context/model between turns. See PrepareNextTurnHook.
getter/setter pair
runIdleTimeout Duration
Backstop for wedged runs: when no AgentEvent arrives for this long outside tool execution (a stalled provider connection whose socket never errors, a hook future that never completes), the run's cancel token is cancelled with a TimeoutException reason and onRunIdleTimeout fires, so the turn ends as aborted instead of pinning the host's busy state forever. Streaming deltas and tool phases reset/disarm the timer — a long legitimate tool call (a full test gate) never trips it. Duration.zero disables the watchdog. Defaults to defaultRunIdleTimeout.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
state AgentState
Current agent state.
no setter
steeringArrived Stream<void>
Fires whenever a message is enqueued into the steering queue mid-run; the agent loop subscribes per tool-call phase to request soft-yields.
no setter
steeringMode QueueMode
Controls how queued steering messages are drained.
getter/setter pair
streamFunction StreamFunction
Provider adapter used for every model call. See StreamFunction.
getter/setter pair
toolExecution ToolExecutionMode
Tool execution strategy for assistant messages that contain multiple tool calls.
getter/setter pair
toolExecutor ToolExecutor
Executes tool calls requested by the model. See ToolExecutor.
getter/setter pair
transformContext TransformContextHook?
Rewrites the message list sent to the provider before each call. See TransformContextHook.
getter/setter pair
wireDump bool
Opt-in raw wire dumps (issue #385 F5, default off): when on, every ModelRequestEvent carries the raw serialized outbound payload for the host to redact, cap, and persist. OFF by default — payloads can carry secrets and bloat the session file.
final

Methods

abort() → void
Aborts the current run, if one is active. Also disarms the idle watchdog: it guards against a WEDGED stream going silent, not against a host that cancelled on purpose — keeping it armed after an explicit abort (or host teardown) leaks the timer past the run's grave.
clearAllQueues() → void
Remove all queued steering and follow-up messages.
clearFollowUpQueue() → void
Remove all queued follow-up messages.
clearSteeringQueue() → void
Remove all queued steering messages.
continueRun() Future<void>
Continue from the current transcript. The last message must be a user or tool-result message, unless queued steering/follow-up messages can start a fresh prompt run (pi's continue()).
drainSteeringQueue() List<Message>
Drain the steering queue and return its messages (abort path: the queued steers must land in the transcript, not vanish).
followUp(Message message) → void
Queue a message to run only after the agent would otherwise stop.
hasQueuedMessages() bool
Returns true when either queue still contains pending messages.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
pokeSteering() → void
Fires the steering-arrived notification WITHOUT queueing a message — the external-inbox fast path (issue #647): the owner of the external source (e.g. the task executor seeing mail land on a running child's handle) pokes the run so the tool-call phase's soft-yield fires instantly instead of waiting out the 2s external probe. Delivery itself still happens once, at the boundary drain.
prompt(String text) Future<void>
Start a new prompt from plain text.
promptMessage(Message message) Future<void>
Start a new prompt from a single message.
promptMessages(List<Message> messages) Future<void>
Start a new prompt from a batch of messages.
reset() → void
Clear transcript state, runtime state, and queued messages.
steer(Message message) → void
Queue a message to be injected after the current assistant turn finishes.
subscribe(AgentListener listener) → void Function()
Subscribe to agent lifecycle events. Returns an unsubscribe function.
toString() String
A string representation of this object.
inherited
waitForIdle() Future<void>
Resolves when the current run and all awaited event listeners have finished (after agent_end listeners settle).

Operators

operator ==(Object other) bool
The equality operator.
inherited