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
impl Agent
Sourcepub async fn save_checkpoint(
&self,
id: impl Into<String>,
) -> Result<Checkpoint, Error>
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.
Sourcepub fn restore_from_checkpoint(
&mut self,
checkpoint: &Checkpoint,
) -> Result<(), Error>
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.
Sourcepub async fn load_and_restore_checkpoint(
&mut self,
id: &str,
) -> Result<Option<Checkpoint>, Error>
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.
Sourcepub fn checkpoint_store(&self) -> Option<&dyn CheckpointStore>
pub fn checkpoint_store(&self) -> Option<&dyn CheckpointStore>
Access the checkpoint store, if configured.
Sourcepub fn pause(&mut self) -> Option<LoopCheckpoint>
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.
Sourcepub async fn resume(
&mut self,
checkpoint: &LoopCheckpoint,
) -> Result<AgentResult, AgentError>
pub async fn resume( &mut self, checkpoint: &LoopCheckpoint, ) -> Result<AgentResult, AgentError>
Resume the agent loop from a previously captured crate::checkpoint::LoopCheckpoint.
Sourcepub fn resume_stream(
&mut self,
checkpoint: &LoopCheckpoint,
) -> Result<Pin<Box<dyn Stream<Item = AgentEvent> + Send>>, AgentError>
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
impl Agent
Sourcepub fn reset(&mut self)
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.
Sourcepub fn wait_for_idle(&self) -> impl Future<Output = ()> + Send + '_
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
impl Agent
Sourcepub fn subscribe(
&mut self,
callback: impl Fn(&AgentEvent) + Send + Sync + 'static,
) -> SubscriptionId
pub fn subscribe( &mut self, callback: impl Fn(&AgentEvent) + Send + Sync + 'static, ) -> SubscriptionId
Subscribe to agent events. Returns a subscription ID for later removal.
Sourcepub fn unsubscribe(&mut self, id: SubscriptionId) -> bool
pub fn unsubscribe(&mut self, id: SubscriptionId) -> bool
Remove a subscription. Returns true if the subscription existed.
Sourcepub fn add_event_forwarder(
&mut self,
f: impl Fn(AgentEvent) + Send + Sync + 'static,
)
pub fn add_event_forwarder( &mut self, f: impl Fn(AgentEvent) + Send + Sync + 'static, )
Add an event forwarder at runtime.
Sourcepub fn forward_event(&mut self, event: &AgentEvent)
pub fn forward_event(&mut self, event: &AgentEvent)
Dispatch an external event to all listeners and forwarders.
Used for cross-agent event forwarding.
Source§impl Agent
impl Agent
Sourcepub fn prompt_stream(
&mut self,
input: Vec<AgentMessage>,
) -> Result<Pin<Box<dyn Stream<Item = AgentEvent> + Send>>, AgentError>
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.
Sourcepub async fn prompt_async(
&mut self,
input: Vec<AgentMessage>,
) -> Result<AgentResult, AgentError>
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.
Sourcepub fn prompt_sync(
&mut self,
input: Vec<AgentMessage>,
) -> Result<AgentResult, AgentError>
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.
Sourcepub async fn prompt_text(
&mut self,
text: impl Into<String>,
) -> Result<AgentResult, AgentError>
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.
Sourcepub async fn prompt_text_with_images(
&mut self,
text: impl Into<String>,
images: Vec<ImageSource>,
) -> Result<AgentResult, AgentError>
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.
Sourcepub fn prompt_text_sync(
&mut self,
text: impl Into<String>,
) -> Result<AgentResult, AgentError>
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.
Sourcepub fn continue_stream(
&mut self,
) -> Result<Pin<Box<dyn Stream<Item = AgentEvent> + Send>>, AgentError>
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.
Sourcepub async fn continue_async(&mut self) -> Result<AgentResult, AgentError>
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.
Sourcepub fn continue_sync(&mut self) -> Result<AgentResult, AgentError>
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
impl Agent
Sourcepub fn set_system_prompt(&mut self, prompt: impl Into<String>)
pub fn set_system_prompt(&mut self, prompt: impl Into<String>)
Set the system prompt.
Sourcepub fn set_model(&mut self, model: ModelSpec)
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.
Sourcepub fn set_model_with_stream(
&mut self,
model: ModelSpec,
stream_fn: Arc<dyn StreamFn>,
)
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.
Sourcepub const fn set_thinking_level(&mut self, level: ThinkingLevel)
pub const fn set_thinking_level(&mut self, level: ThinkingLevel)
Set the thinking level on the current model.
Sourcepub fn add_tool(&mut self, tool: Arc<dyn AgentTool>)
pub fn add_tool(&mut self, tool: Arc<dyn AgentTool>)
Add a tool, replacing any existing tool with the same name.
Sourcepub fn remove_tool(&mut self, name: &str) -> bool
pub fn remove_tool(&mut self, name: &str) -> bool
Remove a tool by name. Returns true if a tool was found and removed.
Sourcepub const fn approval_mode(&self) -> ApprovalMode
pub const fn approval_mode(&self) -> ApprovalMode
Return the current approval mode.
Sourcepub const fn set_approval_mode(&mut self, mode: ApprovalMode)
pub const fn set_approval_mode(&mut self, mode: ApprovalMode)
Set the approval mode at runtime.
Sourcepub fn tools_matching(
&self,
predicate: impl Fn(&dyn AgentTool) -> bool,
) -> Vec<&Arc<dyn AgentTool>>
pub fn tools_matching( &self, predicate: impl Fn(&dyn AgentTool) -> bool, ) -> Vec<&Arc<dyn AgentTool>>
Return tools matching a predicate.
Sourcepub fn tools_in_namespace(&self, namespace: &str) -> Vec<&Arc<dyn AgentTool>>
pub fn tools_in_namespace(&self, namespace: &str) -> Vec<&Arc<dyn AgentTool>>
Return tools belonging to the given namespace.
Sourcepub fn set_messages(&mut self, messages: Vec<AgentMessage>)
pub fn set_messages(&mut self, messages: Vec<AgentMessage>)
Replace the entire message history.
Sourcepub fn append_messages(&mut self, messages: Vec<AgentMessage>)
pub fn append_messages(&mut self, messages: Vec<AgentMessage>)
Append messages to the history.
Sourcepub fn clear_messages(&mut self)
pub fn clear_messages(&mut self)
Clear the message history.
Source§impl Agent
impl Agent
Sourcepub fn steer(&mut self, message: AgentMessage)
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.
Sourcepub fn follow_up(&mut self, message: AgentMessage)
pub fn follow_up(&mut self, message: AgentMessage)
Push a follow-up message into the queue.
Sourcepub fn clear_steering(&mut self)
pub fn clear_steering(&mut self)
Clear all steering messages.
Sourcepub fn clear_follow_up(&mut self)
pub fn clear_follow_up(&mut self)
Clear all follow-up messages.
Sourcepub fn clear_queues(&mut self)
pub fn clear_queues(&mut self)
Clear both steering and follow-up queues.
Sourcepub fn has_pending_messages(&self) -> bool
pub fn has_pending_messages(&self) -> bool
Returns true if there are pending steering or follow-up messages.
Source§impl Agent
impl Agent
Sourcepub fn handle_stream_event(&mut self, event: &AgentEvent)
pub fn handle_stream_event(&mut self, event: &AgentEvent)
Processes a streaming event, updating Agent::state and notifying subscribers.
Source§impl Agent
impl Agent
Sourcepub async fn structured_output(
&mut self,
prompt: String,
schema: Value,
) -> Result<Value, AgentError>
pub async fn structured_output( &mut self, prompt: String, schema: Value, ) -> Result<Value, AgentError>
Run a structured output extraction loop.
Sourcepub fn structured_output_sync(
&mut self,
prompt: String,
schema: Value,
) -> Result<Value, AgentError>
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.
Sourcepub async fn structured_output_typed<T: DeserializeOwned>(
&mut self,
prompt: String,
schema: Value,
) -> Result<T, AgentError>
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.
Sourcepub fn structured_output_typed_sync<T: DeserializeOwned>(
&mut self,
prompt: String,
schema: Value,
) -> Result<T, AgentError>
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
impl Agent
Sourcepub fn new(options: AgentOptions) -> Self
pub fn new(options: AgentOptions) -> Self
Create a new agent from the given options.
Sourcepub const fn state(&self) -> &AgentState
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.
Sourcepub fn is_running(&self) -> bool
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.
Sourcepub const fn session_state(&self) -> &Arc<RwLock<SessionState>>
pub const fn session_state(&self) -> &Arc<RwLock<SessionState>>
Access the session key-value state (thread-safe, shared reference).
Sourcepub fn custom_message_registry(&self) -> Option<&CustomMessageRegistry>
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.