Skip to main content

Agent

Struct Agent 

Source
pub struct Agent { /* private fields */ }
Expand description

Stateful wrapper over the agent loop.

Owns conversation history, configuration, steering/follow-up queues, and subscriber callbacks. Provides prompt, continue, and structured output invocation modes.

Implementations§

Source§

impl Agent

Source

pub async fn save_checkpoint( &self, id: impl Into<String>, ) -> Result<Checkpoint, Error>

Create a checkpoint of the current agent state.

If a CheckpointStore is configured, the checkpoint is also persisted. Returns the checkpoint regardless of whether a store is configured.

Source

pub fn restore_from_checkpoint( &mut self, checkpoint: &Checkpoint, ) -> Result<(), Error>

Restore agent message history from a checkpoint.

Replaces the current messages with those from the checkpoint and updates the system prompt to match. If the checkpoint’s model matches one of the available_models, the stream function is rebound automatically; otherwise the current stream function is left in place. Persisted custom messages are restored when a CustomMessageRegistry has been configured on AgentOptions via with_custom_message_registry; otherwise they are dropped. Returns std::io::ErrorKind::WouldBlock if a loop is still active; callers must wait for the agent to become idle before restoring a checkpoint into it.

Source

pub async fn load_and_restore_checkpoint( &mut self, id: &str, ) -> Result<Option<Checkpoint>, Error>

Load a checkpoint from the configured store and restore state from it.

Returns the loaded checkpoint, or None if not found. Returns an error if no checkpoint store is configured. Returns std::io::ErrorKind::WouldBlock if the agent is still running.

Source

pub fn checkpoint_store(&self) -> Option<&dyn CheckpointStore>

Access the checkpoint store, if configured.

Source

pub fn pause(&mut self) -> Option<LoopCheckpoint>

Pause the currently running loop and capture its state as a crate::checkpoint::LoopCheckpoint.

Signals the loop to stop via the cancellation token and snapshots the agent’s messages, system prompt, and queued LLM messages into a serializable checkpoint. The checkpoint can later be passed to resume to continue the loop from where it left off.

The agent remains in the running state after this call. It becomes idle when the caller either drains the event stream to completion or drops the stream returned by prompt_stream. This prevents a new run from starting while the previous loop is still tearing down.

Returns None if the agent is not currently running.

Source

pub async fn resume( &mut self, checkpoint: &LoopCheckpoint, ) -> Result<AgentResult, AgentError>

Resume the agent loop from a previously captured crate::checkpoint::LoopCheckpoint.

Source

pub fn resume_stream( &mut self, checkpoint: &LoopCheckpoint, ) -> Result<Pin<Box<dyn Stream<Item = AgentEvent> + Send>>, AgentError>

Resume the agent loop from a checkpoint, returning an event stream.

Source§

impl Agent

Source

pub fn abort(&mut self)

Cancel the currently running loop, if any.

Source

pub fn reset(&mut self)

Reset the agent to its initial state, clearing messages, queues, and error.

If a loop is currently active, the abort token is cancelled and the generation counter is bumped so the stale LoopGuardStream cannot clear loop_active for any future run.

Source

pub fn wait_for_idle(&self) -> impl Future<Output = ()> + Send + '_

Returns a future that resolves when the agent is no longer running.

Uses the shared loop_active flag so the future correctly resolves even when the event stream is dropped without being drained to AgentEnd.

Source§

impl Agent

Source

pub fn subscribe( &mut self, callback: impl Fn(&AgentEvent) + Send + Sync + 'static, ) -> SubscriptionId

Subscribe to agent events. Returns a subscription ID for later removal.

Source

pub fn unsubscribe(&mut self, id: SubscriptionId) -> bool

Remove a subscription. Returns true if the subscription existed.

Source

pub fn add_event_forwarder( &mut self, f: impl Fn(AgentEvent) + Send + Sync + 'static, )

Add an event forwarder at runtime.

Source

pub fn forward_event(&mut self, event: &AgentEvent)

Dispatch an external event to all listeners and forwarders.

Used for cross-agent event forwarding.

Source

pub fn emit(&mut self, name: impl Into<String>, payload: Value)

Emit a custom named event to all subscribers and forwarders.

Source§

impl Agent

Source

pub fn prompt_stream( &mut self, input: Vec<AgentMessage>, ) -> Result<Pin<Box<dyn Stream<Item = AgentEvent> + Send>>, AgentError>

Start a new loop with input messages, returning an event stream.

§Errors

Returns AgentError::AlreadyRunning if the agent is already running.

Source

pub async fn prompt_async( &mut self, input: Vec<AgentMessage>, ) -> Result<AgentResult, AgentError>

Start a new loop with input messages, collecting to completion.

§Errors

Returns AgentError::AlreadyRunning if the agent is already running.

Source

pub fn prompt_sync( &mut self, input: Vec<AgentMessage>, ) -> Result<AgentResult, AgentError>

Start a new loop with input messages, blocking the current thread.

§Errors

Returns AgentError::AlreadyRunning if the agent is already running, or AgentError::SyncInAsyncContext if called from within a Tokio runtime.

Source

pub async fn prompt_text( &mut self, text: impl Into<String>, ) -> Result<AgentResult, AgentError>

Start a new loop from a plain text string, collecting to completion.

Convenience wrapper that builds a UserMessage from the string.

Source

pub async fn prompt_text_with_images( &mut self, text: impl Into<String>, images: Vec<ImageSource>, ) -> Result<AgentResult, AgentError>

Start a new loop from a text string with images, collecting to completion.

Convenience wrapper that builds a UserMessage from text and image blocks.

Source

pub fn prompt_text_sync( &mut self, text: impl Into<String>, ) -> Result<AgentResult, AgentError>

Start a new loop from a plain text string, blocking the current thread.

Convenience wrapper that builds a UserMessage from the string.

Source

pub fn continue_stream( &mut self, ) -> Result<Pin<Box<dyn Stream<Item = AgentEvent> + Send>>, AgentError>

Continue from existing messages, returning an event stream.

§Errors

Returns AgentError::AlreadyRunning, AgentError::NoMessages, or AgentError::InvalidContinue.

Source

pub async fn continue_async(&mut self) -> Result<AgentResult, AgentError>

Continue from existing messages, collecting to completion.

§Errors

Returns AgentError::AlreadyRunning, AgentError::NoMessages, or AgentError::InvalidContinue.

Source

pub fn continue_sync(&mut self) -> Result<AgentResult, AgentError>

Continue from existing messages, blocking the current thread.

§Errors

Returns AgentError::AlreadyRunning, AgentError::NoMessages, AgentError::InvalidContinue, or AgentError::SyncInAsyncContext.

Source§

impl Agent

Source

pub fn set_system_prompt(&mut self, prompt: impl Into<String>)

Set the system prompt.

Source

pub fn set_model(&mut self, model: ModelSpec)

Set the model specification, swapping the stream function if a matching model was registered via with_available_models.

If the model actually changes, a AgentEvent::ModelCycled event is dispatched to all subscribers.

Source

pub fn set_model_with_stream( &mut self, model: ModelSpec, stream_fn: Arc<dyn StreamFn>, )

Set the model specification and stream function explicitly, bypassing the available_models lookup.

Source

pub const fn set_thinking_level(&mut self, level: ThinkingLevel)

Set the thinking level on the current model.

Source

pub fn set_tools(&mut self, tools: Vec<Arc<dyn AgentTool>>)

Replace the tool set.

Source

pub fn add_tool(&mut self, tool: Arc<dyn AgentTool>)

Add a tool, replacing any existing tool with the same name.

Source

pub fn remove_tool(&mut self, name: &str) -> bool

Remove a tool by name. Returns true if a tool was found and removed.

Source

pub const fn approval_mode(&self) -> ApprovalMode

Return the current approval mode.

Source

pub const fn set_approval_mode(&mut self, mode: ApprovalMode)

Set the approval mode at runtime.

Source

pub fn find_tool(&self, name: &str) -> Option<&Arc<dyn AgentTool>>

Find a tool by name.

Source

pub fn tools_matching( &self, predicate: impl Fn(&dyn AgentTool) -> bool, ) -> Vec<&Arc<dyn AgentTool>>

Return tools matching a predicate.

Source

pub fn tools_in_namespace(&self, namespace: &str) -> Vec<&Arc<dyn AgentTool>>

Return tools belonging to the given namespace.

Source

pub fn set_messages(&mut self, messages: Vec<AgentMessage>)

Replace the entire message history.

Source

pub fn append_messages(&mut self, messages: Vec<AgentMessage>)

Append messages to the history.

Source

pub fn clear_messages(&mut self)

Clear the message history.

Source

pub fn enter_plan_mode(&mut self) -> (Vec<Arc<dyn AgentTool>>, String)

Enter plan mode: restrict to read-only tools and append plan instructions.

Source

pub fn exit_plan_mode( &mut self, saved_tools: Vec<Arc<dyn AgentTool>>, saved_prompt: String, )

Exit plan mode: restore previously saved tools and system prompt.

Source§

impl Agent

Source

pub fn steer(&mut self, message: AgentMessage)

Push a steering message into the queue.

The message is delivered to the agent at the next turn boundary — after the current LLM response or tool-execution batch completes. This preserves the agent’s in-progress work rather than aborting it mid-generation.

Source

pub fn follow_up(&mut self, message: AgentMessage)

Push a follow-up message into the queue.

Source

pub fn clear_steering(&mut self)

Clear all steering messages.

Source

pub fn clear_follow_up(&mut self)

Clear all follow-up messages.

Source

pub fn clear_queues(&mut self)

Clear both steering and follow-up queues.

Source

pub fn has_pending_messages(&self) -> bool

Returns true if there are pending steering or follow-up messages.

Source§

impl Agent

Source

pub fn handle_stream_event(&mut self, event: &AgentEvent)

Processes a streaming event, updating Agent::state and notifying subscribers.

Source§

impl Agent

Source

pub async fn structured_output( &mut self, prompt: String, schema: Value, ) -> Result<Value, AgentError>

Run a structured output extraction loop.

Source

pub fn structured_output_sync( &mut self, prompt: String, schema: Value, ) -> Result<Value, AgentError>

Run a structured output extraction loop, blocking the current thread.

§Errors

Returns AgentError::SyncInAsyncContext if called from within a Tokio runtime.

Source

pub async fn structured_output_typed<T: DeserializeOwned>( &mut self, prompt: String, schema: Value, ) -> Result<T, AgentError>

Run structured output extraction and deserialize into a typed result.

Source

pub fn structured_output_typed_sync<T: DeserializeOwned>( &mut self, prompt: String, schema: Value, ) -> Result<T, AgentError>

Run structured output extraction, deserialize into a typed result, blocking.

§Errors

Returns AgentError::SyncInAsyncContext if called from within a Tokio runtime.

Source§

impl Agent

Source

pub fn new(options: AgentOptions) -> Self

Create a new agent from the given options.

Source

pub const fn id(&self) -> AgentId

Returns this agent’s unique identifier.

Source

pub const fn state(&self) -> &AgentState

Access the current agent state.

Note: AgentState::is_running may lag behind the true loop lifecycle after a stream is dropped. Use Agent::is_running for an accurate real-time check.

Source

pub fn is_running(&self) -> bool

Returns whether a loop is currently active.

This reads an atomic flag that is cleared immediately when the event stream is dropped or drained to AgentEnd, making it accurate even in the window between dropping a stream and the next &mut self call.

Source

pub const fn session_state(&self) -> &Arc<RwLock<SessionState>>

Access the session key-value state (thread-safe, shared reference).

Source

pub fn custom_message_registry(&self) -> Option<&CustomMessageRegistry>

Access the custom message registry, if one was configured.

Useful for passing to SessionStore::load (from swink-agent-memory) so that persisted custom messages are deserialized instead of silently dropped.

Trait Implementations§

Source§

impl Debug for Agent

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

§

impl !UnwindSafe for Agent

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more