Skip to main content

strands/agent/
agent.rs

1//! The agent: construction, accessors and the public invocation API. The loop itself is in
2//! `event_loop.rs`.
3
4use std::collections::{BTreeMap, VecDeque};
5use std::fmt;
6use std::sync::atomic::{AtomicUsize, Ordering};
7use std::sync::{Arc, RwLock};
8
9use futures::StreamExt;
10
11use super::agent_delegation::{AGENT_DELEGATION_NAME, AgentDelegation};
12use super::config::{AgentBuilder, AgentConfig, InvokeOptions, ModelSource};
13#[cfg(not(feature = "bedrock"))]
14use super::default_model::DefaultModelSlot;
15use super::invocation_context::InvocationContext;
16use super::invocation_state::InvocationState;
17use super::invoke_args::InvokeArgs;
18use super::local_agent::LocalAgent;
19use super::mcp_tools::McpTools;
20use super::printer::{AgentPrinter, default_appender};
21use super::result::AgentResult;
22use super::snapshot::TakeSnapshotOptions;
23use super::stream::{AgentStream, Emitter};
24use crate::background_tasks::{BackgroundTasks, BackgroundTasksPlugin};
25use crate::cancel::{CancelHandle, CancelSignal};
26use crate::context_manager::modes::agentic::AgenticContext;
27use crate::context_manager::{ContextManager, ContextManagerStrategy};
28use crate::conversation_manager::{
29    ConversationManager, ConversationManagerPlugin, NullConversationManager, SlidingWindowConversationManager,
30};
31use crate::error::{Error, Result};
32use crate::hooks::{HookCallbackOptions, HookCleanup, HookEvent, IntoAsyncHook, IntoHookImpl, IntoSyncHook};
33use crate::interventions::InterventionRegistry;
34use crate::memory::{MemoryManager, MemoryManagerSource};
35use crate::middleware::{Middleware, MiddlewareCleanup, MiddlewareStage};
36use crate::models::Model;
37use crate::models::routing::{ModelRouter, ModelRouterPlugin, RouterAttachment};
38use crate::plugins::{ModelPlugin, Plugin, PluginRegistry};
39use crate::retry::{
40    DefaultModelRetryStrategy, ModelRetryPlugin, RetryStrategy, SleeperSlot, TokioSleeper,
41    warn_on_duplicate_retry_strategy_types,
42};
43use crate::sandbox::Sandbox;
44use crate::session::SessionManager;
45use crate::state_store::StateStore;
46use crate::storage::Storage;
47use crate::telemetry::{AgentMetrics, Tracer, with_baggage};
48use crate::tools::{Tool, ToolExecutorStrategy, ToolRegistry, ToolSource};
49use crate::types::{AgentMetadata, JsonSchema, JsonValue, Message, Snapshot, SystemPrompt, Toggle};
50
51pub(crate) const DEFAULT_AGENT_NAME: &str = "Strands Agent";
52const DEFAULT_AGENT_ID: &str = "agent";
53
54/// Work left over from a stream that was dropped mid-invocation: the hooks that could not run
55/// inside `Drop`. It runs at the start of the next `invoke`, `stream` or `shutdown`. Each
56/// counter is the number of callbacks of its event that already ran, so every callback runs
57/// once.
58pub(crate) struct PendingCleanup {
59    /// Messages already in history whose `MessageAddedEvent` has not finished, in order.
60    pub(crate) messages: VecDeque<Message>,
61    /// Callbacks that already ran for the first message.
62    pub(crate) message_progress: Arc<AtomicUsize>,
63    /// Callbacks that already ran for the due `AfterInvocationEvent`.
64    pub(crate) after_invocation: Option<Arc<AtomicUsize>>,
65    pub(crate) invocation_state: InvocationState,
66    pub(crate) invocation_context: Option<InvocationContext>,
67}
68
69/// What a running invocation needs if its stream is dropped.
70pub(crate) struct InFlight {
71    pub(crate) invocation_state: InvocationState,
72    pub(crate) invocation_context: InvocationContext,
73    pub(crate) after_invocation_due: bool,
74    pub(crate) structured_output_registered: bool,
75}
76
77/// Hook runs a dropped stream can cut short, kept on the agent so the next call resumes them.
78#[derive(Default)]
79pub(crate) struct HookProgress {
80    /// Messages already in history whose `MessageAddedEvent` has not finished, in order.
81    pub(crate) unfired: VecDeque<Message>,
82    /// Callbacks that already ran for the first unfired message.
83    pub(crate) message: Arc<AtomicUsize>,
84    /// Callbacks that already ran for the current `AfterInvocationEvent`.
85    pub(crate) after_invocation: Arc<AtomicUsize>,
86    /// Callbacks that already ran for `InitializedEvent`.
87    pub(crate) initialized: Arc<AtomicUsize>,
88}
89
90/// An agent: a model, tools and a conversation, run by the agent loop (`Agent`).
91///
92/// The agent is owned and its calls take `&mut self`, so invoking an agent while an invocation
93/// runs is a compile error. Share one across tasks with `Arc<tokio::sync::Mutex<Agent>>`.
94///
95/// ```
96/// use strands::Agent;
97/// use strands::testing::MockModel;
98///
99/// # tokio_test_run(async {
100/// let mut agent = Agent::builder()
101///     .model(MockModel::new().with_turn("Hello!"))
102///     .system_prompt("You are a concise assistant.")
103///     .printer(false)
104///     .build()?;
105/// let result = agent.invoke("Hi").await?;
106/// assert_eq!(result.to_string(), "Hello!");
107/// assert_eq!(agent.messages().len(), 2);
108/// # Ok::<(), strands::Error>(())
109/// # });
110/// # fn tokio_test_run<F: std::future::Future>(f: F) -> F::Output {
111/// #     tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(f)
112/// # }
113/// ```
114pub struct Agent {
115    pub(crate) local: LocalAgent,
116    pub(crate) plugins: PluginRegistry,
117    pub(crate) initialized: bool,
118    pub(crate) printer: Option<AgentPrinter>,
119    pub(crate) structured_output_schema: Option<JsonSchema>,
120    pub(crate) tool_executor: ToolExecutorStrategy,
121    pub(crate) pending_cleanup: Option<PendingCleanup>,
122    pub(crate) in_flight: Option<InFlight>,
123    pub(crate) hook_progress: HookProgress,
124    pub(crate) deferred_continuations: Vec<super::continuation::ContinuationInput>,
125    #[allow(dead_code, reason = "tests swap the sleeper retries wait on")]
126    pub(crate) retry_sleeper: SleeperSlot,
127    pub(crate) mcp: McpTools,
128    #[allow(dead_code, reason = "tests check which manager the agent resolved")]
129    pub(crate) conversation_manager: Arc<dyn ConversationManager>,
130    pub(crate) background_tasks: Option<Arc<BackgroundTasks>>,
131    pub(crate) model_router: Option<RouterAttachment>,
132    pub(crate) session_manager: Option<SessionManager>,
133    pub(crate) memory_manager: Option<MemoryManager>,
134}
135
136const STATEFUL_MANAGER_ERROR: &str = "contextManager and conversationManager cannot be used with a stateful model. The model manages conversation state server-side.";
137
138/// The conversation manager the agent uses: none for a stateful model, the configured one, or a
139/// 40-message sliding window.
140fn resolve_conversation_manager(
141    model: &Arc<dyn Model>,
142    configured: Option<Arc<dyn ConversationManager>>,
143    context_manager: Option<&ContextManagerStrategy>,
144) -> Arc<dyn ConversationManager> {
145    if model.stateful() {
146        return Arc::new(NullConversationManager::new());
147    }
148    match context_manager {
149        None => configured.unwrap_or_else(|| Arc::new(SlidingWindowConversationManager::default())),
150        Some(ContextManagerStrategy::Disabled) => {
151            configured.unwrap_or_else(|| Arc::new(NullConversationManager::new()))
152        }
153        Some(_) => {
154            if configured.is_some() {
155                tracing::warn!("contextManager is set, ignoring co-provided conversationManager");
156            }
157            Arc::new(NullConversationManager::new())
158        }
159    }
160}
161
162/// The plugins the agent registers itself, around the user's.
163struct BuiltInPlugins {
164    model_router: bool,
165    conversation_manager: Arc<dyn ConversationManager>,
166    retry_strategies: Vec<Arc<dyn Plugin>>,
167    user_plugins: Vec<Arc<dyn Plugin>>,
168    background_tasks: Option<Arc<BackgroundTasks>>,
169    memory_manager: Option<Arc<dyn Plugin>>,
170    context_manager: Option<Arc<dyn Plugin>>,
171    session_manager: Option<Arc<dyn Plugin>>,
172    model: Arc<dyn Model>,
173}
174
175impl BuiltInPlugins {
176    /// The registration order: model router, conversation manager, retry strategies, user plugins,
177    /// background tasks, delegation, memory manager, context manager, session manager, then the
178    /// model plugin. The model plugin is last so its `AfterInvocationEvent` hook, which runs in
179    /// reverse order, clears a stateful model's messages before a session manager saves them.
180    fn in_registration_order(self) -> Vec<Arc<dyn Plugin>> {
181        let mut plugins: Vec<Arc<dyn Plugin>> = Vec::new();
182        if self.model_router {
183            plugins.push(Arc::new(ModelRouterPlugin));
184        }
185        plugins.push(Arc::new(ConversationManagerPlugin::new(self.conversation_manager)));
186        plugins.extend(self.retry_strategies);
187        let has_delegation = self
188            .user_plugins
189            .iter()
190            .any(|plugin| plugin.name() == AGENT_DELEGATION_NAME);
191        plugins.extend(self.user_plugins);
192        if let Some(background_tasks) = self.background_tasks {
193            plugins.push(Arc::new(BackgroundTasksPlugin(background_tasks)));
194        }
195        if !has_delegation {
196            plugins.push(Arc::new(AgentDelegation::new()));
197        }
198        plugins.extend(self.memory_manager);
199        plugins.extend(self.context_manager);
200        plugins.extend(self.session_manager);
201        plugins.push(Arc::new(ModelPlugin::new(self.model)));
202        plugins
203    }
204}
205
206fn resolve_model(source: ModelSource) -> Result<Arc<dyn Model>> {
207    resolve_plain_model(
208        source,
209        "a ModelRouter is accepted only as the agent's configured model, not by set_model",
210    )
211}
212
213/// Resolves `aux_model` like `model`, rejecting a router.
214fn resolve_aux_model(source: ModelSource) -> Result<Arc<dyn Model>> {
215    resolve_plain_model(
216        source,
217        "auxModel must be a Model or a Bedrock model id, not a ModelRouter",
218    )
219}
220
221/// Resolves a model where a router is not accepted, failing with `router_error` for one.
222pub(crate) fn resolve_plain_model(source: ModelSource, router_error: &str) -> Result<Arc<dyn Model>> {
223    match source {
224        ModelSource::Model(model) => Ok(model),
225        ModelSource::Router(_) => Err(Error::other(router_error.to_owned())),
226        ModelSource::Id(model_id) => model_from_id(model_id),
227    }
228}
229
230#[cfg(feature = "bedrock")]
231fn model_from_id(model_id: String) -> Result<Arc<dyn Model>> {
232    Ok(Arc::new(crate::models::BedrockModel::new(
233        crate::models::BedrockModelConfig {
234            model_id: Some(model_id),
235            ..Default::default()
236        },
237    )))
238}
239
240#[cfg(feature = "bedrock")]
241fn default_model() -> Arc<dyn Model> {
242    crate::models::bedrock::default_bedrock_model()
243}
244
245#[cfg(not(feature = "bedrock"))]
246fn default_model() -> Arc<dyn Model> {
247    Arc::new(DefaultModelSlot::new(None))
248}
249
250#[cfg(not(feature = "bedrock"))]
251#[allow(
252    clippy::needless_pass_by_value,
253    reason = "shares the signature of the bedrock variant"
254)]
255fn model_from_id(model_id: String) -> Result<Arc<dyn Model>> {
256    Err(crate::error::DefaultNotConfiguredError::new(format!(
257        "model id \"{model_id}\" is a Bedrock model id, which requires the strands feature \"bedrock\""
258    ))
259    .into())
260}
261
262impl Agent {
263    /// Starts an agent builder; its setters are the [`AgentConfig`] keys.
264    ///
265    /// ```
266    /// use strands::Agent;
267    /// use strands::testing::MockModel;
268    ///
269    /// let agent = Agent::builder()
270    ///     .model(MockModel::new())
271    ///     .name("researcher")
272    ///     .printer(false)
273    ///     .build()?;
274    /// assert_eq!(agent.name(), "researcher");
275    /// # Ok::<(), strands::Error>(())
276    /// ```
277    pub fn builder() -> AgentBuilder {
278        AgentConfig::builder()
279    }
280
281    /// Creates an agent from its configuration (`new Agent(config)`).
282    ///
283    /// Without a model the agent uses the default Bedrock model, resolved when the agent first
284    /// calls it.
285    ///
286    /// # Errors
287    ///
288    /// A tool name that is invalid or registered twice, a Bedrock model id without the `bedrock`
289    /// feature, or a structured output schema that does not compile when first used.
290    pub fn new(mut config: AgentConfig) -> Result<Self> {
291        let (model, model_router) = match config.model.take() {
292            Some(ModelSource::Router(router)) => (router.default_model(), Some(router)),
293            Some(source) => (resolve_model(source)?, None),
294            None => (default_model(), None),
295        };
296        let aux_model = config.aux_model.take().map(resolve_aux_model).transpose()?;
297        if let Some(source) = config.memory_manager.take() {
298            config.memory_manager = Some(MemoryManagerSource::Manager(source.resolve()?));
299        }
300        let has_context_manager = !matches!(config.context_manager, None | Some(ContextManagerStrategy::Disabled));
301        if (config.conversation_manager.is_some() || has_context_manager) && model.stateful() {
302            return Err(Error::other(STATEFUL_MANAGER_ERROR));
303        }
304        let agentic = matches!(config.context_manager, Some(ContextManagerStrategy::Agentic));
305        if let Some(manager) = ContextManager::from_strategy(config.context_manager.clone())? {
306            config.context_manager = Some(ContextManagerStrategy::Instance(manager));
307        }
308        let background_tasks = config
309            .background_tasks
310            .take()
311            .and_then(Toggle::into_option)
312            .map(BackgroundTasks::new)
313            .transpose()?
314            .map(Arc::new);
315        let interventions = InterventionRegistry::new(std::mem::take(&mut config.interventions))?;
316        let mut parts = ToolSource::List(std::mem::take(&mut config.tools)).into_parts();
317        let mut agent = Self::assemble_with(model, aux_model, config, background_tasks, model_router);
318        interventions.register(agent.local.hooks());
319        agent.local.set_interventions(interventions.handlers());
320        agent.mcp = McpTools::take(&mut parts);
321        agent.local.tool_registry_mut().add(parts.tools)?;
322        if agentic {
323            let context = AgenticContext::default();
324            agent.local.tool_registry_mut().add(context.tools())?;
325            context.register(&agent.local);
326        }
327        Ok(agent)
328    }
329
330    /// Builds an agent from resolved models; `config.tools` is ignored.
331    pub(crate) fn assemble(model: Arc<dyn Model>, aux_model: Option<Arc<dyn Model>>, config: AgentConfig) -> Self {
332        Self::assemble_with(model, aux_model, config, None, None)
333    }
334
335    fn assemble_with(
336        model: Arc<dyn Model>,
337        aux_model: Option<Arc<dyn Model>>,
338        config: AgentConfig,
339        background_tasks: Option<Arc<BackgroundTasks>>,
340        model_router: Option<ModelRouter>,
341    ) -> Self {
342        let mut local = LocalAgent::new(config.id.unwrap_or_else(|| DEFAULT_AGENT_ID.to_owned()), model.clone());
343        local.set_name(
344            Some(config.name.unwrap_or_else(|| DEFAULT_AGENT_NAME.to_owned())),
345            config.description,
346        );
347        local.set_aux_model(aux_model);
348        local.set_cancel_handle(CancelHandle::for_agent());
349        local.set_system_prompt(config.system_prompt);
350        local.set_tracer(Tracer::new(
351            config.trace_attributes.unwrap_or_default(),
352            config.baggage_attributes.unwrap_or_default(),
353        ));
354        local.set_sandbox(config.sandbox);
355        local.set_printer(config.printer.unwrap_or(true));
356        local
357            .tool_registry_mut()
358            .set_sort_tool_specs(config.sort_tools.unwrap_or(false));
359        *local.messages_mut() = config.messages;
360        if let Some(app_state) = config.app_state {
361            local.app_state().load_json(JsonValue::Object(app_state));
362        }
363        if let Some(model_state) = config.model_state {
364            local.model_state().load_json(JsonValue::Object(model_state));
365        }
366        local.set_storage(config.storage);
367        if let Some(session_manager) = &config.session_manager {
368            let session_id = session_manager.session_id().to_owned();
369            local.set_agent_metadata(Some(AgentMetadata::new().with_session_id(&session_id)));
370            local.set_session_id(session_id);
371        }
372
373        let retry_sleeper: SleeperSlot = Arc::new(RwLock::new(Arc::new(TokioSleeper)));
374        let strategies = config
375            .retry_strategy
376            .unwrap_or_else(|| vec![RetryStrategy::model(DefaultModelRetryStrategy::default())]);
377        warn_on_duplicate_retry_strategy_types(&strategies);
378        let model_router = model_router.map(|router| RouterAttachment::attach(router, &local));
379        let conversation_manager =
380            resolve_conversation_manager(&model, config.conversation_manager, config.context_manager.as_ref());
381        let context_manager = ContextManager::from_strategy(config.context_manager).unwrap_or_else(|error| {
382            tracing::warn!("error=<{error}> | context manager did not resolve, continuing without it");
383            None
384        });
385        local.set_context_manager(context_manager.clone());
386        let memory_manager = config.memory_manager.and_then(MemoryManagerSource::into_manager);
387        let plugins = BuiltInPlugins {
388            model_router: model_router.is_some(),
389            conversation_manager: conversation_manager.clone(),
390            retry_strategies: strategies
391                .into_iter()
392                .map(|strategy| Arc::new(ModelRetryPlugin::new(strategy, retry_sleeper.clone())) as Arc<dyn Plugin>)
393                .collect(),
394            user_plugins: config.plugins,
395            background_tasks: background_tasks.clone(),
396            memory_manager: memory_manager
397                .clone()
398                .map(|manager| Arc::new(manager) as Arc<dyn Plugin>),
399            context_manager: context_manager.map(|manager| Arc::new(manager) as Arc<dyn Plugin>),
400            session_manager: config
401                .session_manager
402                .clone()
403                .map(|session_manager| Arc::new(session_manager) as Arc<dyn Plugin>),
404            model,
405        }
406        .in_registration_order();
407
408        let printer = config
409            .printer
410            .unwrap_or(true)
411            .then(|| AgentPrinter::new(default_appender()));
412        Self {
413            local,
414            plugins: PluginRegistry::new(plugins),
415            initialized: false,
416            printer,
417            structured_output_schema: config.structured_output_schema,
418            tool_executor: config.tool_executor.unwrap_or_default(),
419            pending_cleanup: None,
420            in_flight: None,
421            hook_progress: HookProgress::default(),
422            deferred_continuations: Vec::new(),
423            retry_sleeper,
424            conversation_manager,
425            background_tasks,
426            memory_manager,
427            mcp: McpTools::default(),
428            model_router,
429            session_manager: config.session_manager,
430        }
431    }
432
433    /// Invokes the agent and returns the final result (`invoke`); it drains
434    /// [`stream`](Self::stream).
435    ///
436    /// # Errors
437    ///
438    /// A model error that no retry resolved, a structured output failure, a hook error, a bad
439    /// resume input, or an invalid limit. An agent stopped for interrupts accepts only the
440    /// responses: invoke it with a `Vec<InterruptResponse>`.
441    pub async fn invoke(&mut self, args: impl Into<InvokeArgs>) -> Result<AgentResult> {
442        self.invoke_with(args, InvokeOptions::default()).await
443    }
444
445    /// Invokes the agent with per-invocation options.
446    ///
447    /// # Errors
448    ///
449    /// The same as [`invoke`](Self::invoke).
450    pub async fn invoke_with(&mut self, args: impl Into<InvokeArgs>, options: InvokeOptions) -> Result<AgentResult> {
451        let mut stream = self.stream_with(args, options);
452        while let Some(item) = stream.next().await {
453            item?;
454        }
455        stream
456            .take_result()
457            .ok_or_else(|| Error::other("agent stream ended without a result"))
458    }
459
460    /// Streams the invocation (`stream`): the loop runs as the stream is polled and yields the
461    /// event records, ending with [`AgentStreamEvent::AgentResult`](crate::AgentStreamEvent).
462    ///
463    /// History is always re-invokable: an assistant message with tool uses is appended only after
464    /// its tools finish. Dropping the stream early cancels the invocation.
465    pub fn stream(&mut self, args: impl Into<InvokeArgs>) -> AgentStream<'_> {
466        self.stream_with(args, InvokeOptions::default())
467    }
468
469    /// Streams the invocation with per-invocation options.
470    pub fn stream_with(&mut self, args: impl Into<InvokeArgs>, options: InvokeOptions) -> AgentStream<'_> {
471        let emitter = Emitter::default();
472        let args = args.into();
473        let loop_emitter = emitter.clone();
474        let baggage = self.local.tracer().baggage_attributes().clone();
475        AgentStream::new(
476            &emitter,
477            with_baggage(self.run_invocation(args, options, loop_emitter), baggage),
478        )
479    }
480
481    /// Initializes the agent's plugins and fires `InitializedEvent` (`initialize`). The first
482    /// invocation calls it; calling it again does nothing. When a dropped stream cuts it short,
483    /// the next call continues where it stopped: with the plugin it interrupted, and with the
484    /// `InitializedEvent` callbacks that have not run. When an `InitializedEvent` callback fails,
485    /// the next call fires every callback again.
486    ///
487    /// # Errors
488    ///
489    /// A plugin that failed to initialize (later calls fail with the same message), or an
490    /// `InitializedEvent` hook error.
491    pub async fn initialize(&mut self) -> Result<()> {
492        if self.initialized {
493            return Ok(());
494        }
495        self.mcp.initialize(self.local.tool_registry_mut()).await?;
496        self.register_sandbox_tools()?;
497        self.plugins.initialize(&mut self.local).await?;
498        let hooks = self.local.hooks().clone();
499        let progress = self.hook_progress.initialized.clone();
500        let mut event = crate::hooks::InitializedEvent::new(&mut self.local);
501        let invoked = hooks.invoke_tracked(&mut event, &progress).await;
502        if invoked.is_err() {
503            progress.store(0, Ordering::SeqCst);
504        }
505        invoked?;
506        self.initialized = true;
507        self.local.set_background_tasks(self.background_tasks.clone());
508        Ok(())
509    }
510
511    /// Registers the tools a configured sandbox vends; the host default vends none. A tool whose
512    /// name the user already registered is skipped.
513    fn register_sandbox_tools(&mut self) -> Result<()> {
514        let Some(sandbox) = self.local.configured_sandbox() else {
515            return Ok(());
516        };
517        let tools = sandbox.get_tools();
518        let registry = self.local.tool_registry_mut();
519        for tool in tools {
520            if registry.get(tool.name()).is_some() {
521                tracing::debug!(
522                    "tool_name=<{}> | sandbox-vended tool skipped, user already registered a tool with this name",
523                    tool.name()
524                );
525                continue;
526            }
527            registry.add(tool)?;
528        }
529        Ok(())
530    }
531
532    /// Runs the agent's shutdown procedures (`shutdown`): the cleanup a dropped stream left
533    /// pending, then cancels the background tasks that have not finished (dropping the agent
534    /// cancels them too) and flushes the memory manager. Safe to call
535    /// more than once.
536    ///
537    /// # Errors
538    ///
539    /// None today; cleanup hook errors are logged. The memory manager's
540    /// [`flush`](MemoryManager::flush) logs its store failures.
541    pub async fn shutdown(&mut self) -> Result<()> {
542        self.run_pending_cleanup().await;
543        if let Some(background_tasks) = &self.background_tasks {
544            background_tasks.shutdown();
545        }
546        if let Some(memory_manager) = &self.memory_manager {
547            memory_manager.flush().await;
548        }
549        Ok(())
550    }
551
552    /// The memory manager, if one is configured.
553    #[must_use]
554    pub fn memory_manager(&self) -> Option<&MemoryManager> {
555        self.memory_manager.as_ref()
556    }
557
558    /// Captures a point-in-time snapshot of the agent's state.
559    ///
560    /// ```
561    /// use strands::{Agent, SnapshotField, TakeSnapshotOptions};
562    /// use strands::testing::MockModel;
563    ///
564    /// let agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
565    /// let snapshot = agent.take_snapshot(TakeSnapshotOptions::session())?;
566    /// assert!(snapshot.data.contains_key("messages"));
567    ///
568    /// let partial = agent.take_snapshot(TakeSnapshotOptions {
569    ///     include: vec![SnapshotField::Messages, SnapshotField::State],
570    ///     ..Default::default()
571    /// })?;
572    /// assert_eq!(partial.data.len(), 2);
573    /// # Ok::<(), strands::Error>(())
574    /// ```
575    ///
576    /// # Errors
577    ///
578    /// When the options select no field, or a value fails to serialize.
579    pub fn take_snapshot(&self, options: impl Into<TakeSnapshotOptions>) -> Result<Snapshot> {
580        self.local.take_snapshot(options)
581    }
582
583    /// Restores the agent's state from a snapshot. Only the fields present in
584    /// `snapshot.data` are restored; the others stay as they are.
585    ///
586    /// # Errors
587    ///
588    /// A snapshot of another scope or schema version, data that does not decode, or background
589    /// tasks still tracked.
590    pub fn load_snapshot(&mut self, snapshot: &Snapshot) -> Result<()> {
591        self.local.load_snapshot(snapshot)
592    }
593
594    /// The agent's view as sequential hooks see it.
595    #[must_use]
596    pub fn local(&self) -> &LocalAgent {
597        &self.local
598    }
599
600    /// The agent's view as sequential hooks see it, mutably.
601    pub fn local_mut(&mut self) -> &mut LocalAgent {
602        &mut self.local
603    }
604
605    /// The agent's id (`id`).
606    #[must_use]
607    pub fn id(&self) -> &str {
608        self.local.id()
609    }
610
611    /// The agent's name (`name`).
612    #[must_use]
613    pub fn name(&self) -> &str {
614        self.local.name()
615    }
616
617    /// What the agent does (`description`).
618    #[must_use]
619    pub fn description(&self) -> Option<&str> {
620        self.local.description()
621    }
622
623    /// A stable id for the conversation session.
624    #[must_use]
625    pub fn session_id(&self) -> &str {
626        self.local.session_id()
627    }
628
629    /// The default storage backend for agent subsystems, if one is configured (`storage`).
630    #[must_use]
631    pub fn storage(&self) -> Option<&Arc<dyn Storage>> {
632        self.local.storage()
633    }
634
635    /// The session manager saving and restoring the agent, if one is attached.
636    #[must_use]
637    pub fn session_manager(&self) -> Option<&SessionManager> {
638        self.session_manager.as_ref()
639    }
640
641    /// The conversation history (`messages`).
642    #[must_use]
643    pub fn messages(&self) -> &[Message] {
644        self.local.messages()
645    }
646
647    /// The conversation history, to edit between invocations.
648    pub fn messages_mut(&mut self) -> &mut Vec<Message> {
649        self.local.messages_mut()
650    }
651
652    /// The system prompt.
653    #[must_use]
654    pub fn system_prompt(&self) -> Option<&SystemPrompt> {
655        self.local.system_prompt()
656    }
657
658    /// Replaces or clears the system prompt.
659    pub fn set_system_prompt(&mut self, system_prompt: Option<SystemPrompt>) {
660        self.local.set_system_prompt(system_prompt);
661    }
662
663    /// The model the agent calls (`model`).
664    #[must_use]
665    pub fn model(&self) -> &Arc<dyn Model> {
666        self.local.model()
667    }
668
669    /// Replaces the model the agent calls: a model instance, an `Arc<dyn Model>` or a Bedrock
670    /// model id, like the builder's `model(..)`.
671    ///
672    /// # Errors
673    ///
674    /// A Bedrock model id without the `bedrock` feature, and a [`ModelRouter`](crate::ModelRouter)
675    /// (`a ModelRouter is accepted only as the agent's configured model, not by set_model`): a
676    /// router is attached when the agent is built, so configure it there.
677    pub fn set_model(&mut self, model: impl Into<ModelSource>) -> Result<()> {
678        self.local.set_model(resolve_model(model.into())?);
679        Ok(())
680    }
681
682    /// The model for auxiliary side calls; the agent's model unless one was configured.
683    #[must_use]
684    pub fn aux_model(&self) -> &Arc<dyn Model> {
685        self.local.aux_model()
686    }
687
688    /// Sets the auxiliary model; `None` follows the agent's model again.
689    pub fn set_aux_model(&mut self, aux_model: Option<Arc<dyn Model>>) {
690        self.local.set_aux_model(aux_model);
691    }
692
693    /// Where the agent's tools run commands and touch files (`sandbox`): the configured sandbox,
694    /// or the shared [`NotASandboxLocalEnvironment`](crate::sandbox::NotASandboxLocalEnvironment)
695    /// when none is configured.
696    #[must_use]
697    pub fn sandbox(&self) -> &Arc<dyn Sandbox> {
698        self.local.sandbox()
699    }
700
701    /// App state shared with tools.
702    #[must_use]
703    pub fn app_state(&self) -> &StateStore {
704        self.local.app_state()
705    }
706
707    /// The model provider's runtime state.
708    #[must_use]
709    pub fn model_state(&self) -> &StateStore {
710        self.local.model_state()
711    }
712
713    /// The agent's tools.
714    #[must_use]
715    pub fn tool_registry(&self) -> &ToolRegistry {
716        self.local.tool_registry()
717    }
718
719    /// The agent's tools, to add or remove some.
720    pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry {
721        self.local.tool_registry_mut()
722    }
723
724    /// The registered tools (`tools`).
725    #[must_use]
726    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
727        self.local.tool_registry().list()
728    }
729
730    /// How the tool calls of one model turn run.
731    #[must_use]
732    pub fn tool_executor(&self) -> ToolExecutorStrategy {
733        self.tool_executor
734    }
735
736    /// Sets how the tool calls of one model turn run.
737    pub fn set_tool_executor(&mut self, tool_executor: impl Into<ToolExecutorStrategy>) {
738        self.tool_executor = tool_executor.into();
739    }
740
741    /// Accumulated loop metrics: cycles, token usage and tool statistics (`metrics`).
742    #[must_use]
743    pub fn metrics(&self) -> AgentMetrics {
744        self.local.metrics()
745    }
746
747    /// The OpenTelemetry baggage entries every invocation runs under.
748    #[must_use]
749    pub fn baggage_attributes(&self) -> &BTreeMap<String, String> {
750        self.local.tracer().baggage_attributes()
751    }
752
753    /// A handle that cancels the agent's current invocation (`agent.cancel`). Cancels while the
754    /// agent is idle do nothing; the invocation in progress ends with `StopReason::Cancelled`.
755    ///
756    /// ```
757    /// use strands::{Agent, CancelOptions};
758    /// use strands::testing::MockModel;
759    ///
760    /// let agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
761    /// let cancel = agent.cancel_handle();
762    /// std::thread::spawn(move || cancel.cancel(CancelOptions::default()));
763    /// # Ok::<(), strands::Error>(())
764    /// ```
765    #[must_use]
766    pub fn cancel_handle(&self) -> CancelHandle {
767        self.local.cancel_handle().clone()
768    }
769
770    /// The cancellation signal of the current invocation.
771    #[must_use]
772    pub fn cancel_signal(&self) -> CancelSignal {
773        self.local.cancel_signal()
774    }
775
776    /// Registers a hook closure; see [`HookRegistry::add_hook`](crate::hooks::HookRegistry::add_hook).
777    pub fn add_hook<K: HookEvent>(&self, callback: impl IntoSyncHook<K>) -> HookCleanup {
778        self.local.add_hook(callback)
779    }
780
781    /// Registers a hook closure with options.
782    pub fn add_hook_with<K: HookEvent>(
783        &self,
784        callback: impl IntoSyncHook<K>,
785        options: HookCallbackOptions,
786    ) -> HookCleanup {
787        self.local.add_hook_with(callback, options)
788    }
789
790    /// Registers an async hook closure; name the event type.
791    pub fn add_async_hook<K: HookEvent>(&self, callback: impl IntoAsyncHook<K>) -> HookCleanup {
792        self.local.add_async_hook::<K>(callback)
793    }
794
795    /// Registers an async hook closure with options.
796    pub fn add_async_hook_with<K: HookEvent>(
797        &self,
798        callback: impl IntoAsyncHook<K>,
799        options: HookCallbackOptions,
800    ) -> HookCleanup {
801        self.local.add_async_hook_with::<K>(callback, options)
802    }
803
804    /// Registers a [`Hook`](crate::hooks::Hook) implementation.
805    pub fn add_hook_impl<K: HookEvent>(&self, hook: impl IntoHookImpl<K>) -> HookCleanup {
806        self.local.add_hook_impl(hook)
807    }
808
809    /// Registers a [`Hook`](crate::hooks::Hook) implementation with options.
810    pub fn add_hook_impl_with<K: HookEvent>(
811        &self,
812        hook: impl IntoHookImpl<K>,
813        options: HookCallbackOptions,
814    ) -> HookCleanup {
815        self.local.add_hook_impl_with(hook, options)
816    }
817
818    /// Registers a middleware handler for its stage and phase; see
819    /// [`middleware`](crate::middleware).
820    ///
821    /// ```
822    /// use strands::Agent;
823    /// use strands::middleware::InvokeModelStage;
824    /// use strands::testing::MockModel;
825    ///
826    /// let agent = Agent::builder().model(MockModel::new()).printer(false).build()?;
827    /// let cleanup = agent.add_middleware(InvokeModelStage::output(|mut result| async move {
828    ///     result.result.message.content.retain(|block| block.as_text().is_some());
829    ///     Ok(result)
830    /// }));
831    /// cleanup.remove();
832    /// # Ok::<(), strands::Error>(())
833    /// ```
834    pub fn add_middleware<S: MiddlewareStage>(&self, middleware: Middleware<S>) -> MiddlewareCleanup {
835        self.local.add_middleware(middleware)
836    }
837
838    /// Prints through `appender` instead of stdout (tests).
839    #[cfg(test)]
840    #[allow(dead_code, reason = "used by the printer tests")]
841    pub(crate) fn set_printer_appender(&mut self, appender: super::printer::Appender) {
842        self.printer = Some(AgentPrinter::new(appender));
843    }
844
845    /// Makes retries wait on `sleeper` (tests).
846    #[cfg(test)]
847    #[allow(dead_code, reason = "used by the retry tests")]
848    pub(crate) fn set_retry_sleeper(&self, sleeper: Arc<dyn crate::retry::Sleeper>) {
849        *self
850            .retry_sleeper
851            .write()
852            .unwrap_or_else(std::sync::PoisonError::into_inner) = sleeper;
853    }
854}
855
856impl Drop for Agent {
857    fn drop(&mut self) {
858        if let Some(background_tasks) = &self.background_tasks {
859            background_tasks.shutdown();
860        }
861        if self.pending_cleanup.is_some() {
862            tracing::warn!(
863                "agent_id=<{}> | agent dropped with pending shutdown work, call shutdown().await before dropping it",
864                self.local.id()
865            );
866        }
867    }
868}
869
870impl fmt::Debug for Agent {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872        f.debug_struct("Agent")
873            .field("id", &self.local.id())
874            .field("name", &self.local.name())
875            .field("messages", &self.local.messages().len())
876            .field("tool_registry", self.local.tool_registry())
877            .finish_non_exhaustive()
878    }
879}