1use 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
54pub(crate) struct PendingCleanup {
59 pub(crate) messages: VecDeque<Message>,
61 pub(crate) message_progress: Arc<AtomicUsize>,
63 pub(crate) after_invocation: Option<Arc<AtomicUsize>>,
65 pub(crate) invocation_state: InvocationState,
66 pub(crate) invocation_context: Option<InvocationContext>,
67}
68
69pub(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#[derive(Default)]
79pub(crate) struct HookProgress {
80 pub(crate) unfired: VecDeque<Message>,
82 pub(crate) message: Arc<AtomicUsize>,
84 pub(crate) after_invocation: Arc<AtomicUsize>,
86 pub(crate) initialized: Arc<AtomicUsize>,
88}
89
90pub 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
138fn 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
162struct 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 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
213fn 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
221pub(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 pub fn builder() -> AgentBuilder {
278 AgentConfig::builder()
279 }
280
281 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 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 pub async fn invoke(&mut self, args: impl Into<InvokeArgs>) -> Result<AgentResult> {
442 self.invoke_with(args, InvokeOptions::default()).await
443 }
444
445 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 pub fn stream(&mut self, args: impl Into<InvokeArgs>) -> AgentStream<'_> {
466 self.stream_with(args, InvokeOptions::default())
467 }
468
469 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 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 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 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 #[must_use]
554 pub fn memory_manager(&self) -> Option<&MemoryManager> {
555 self.memory_manager.as_ref()
556 }
557
558 pub fn take_snapshot(&self, options: impl Into<TakeSnapshotOptions>) -> Result<Snapshot> {
580 self.local.take_snapshot(options)
581 }
582
583 pub fn load_snapshot(&mut self, snapshot: &Snapshot) -> Result<()> {
591 self.local.load_snapshot(snapshot)
592 }
593
594 #[must_use]
596 pub fn local(&self) -> &LocalAgent {
597 &self.local
598 }
599
600 pub fn local_mut(&mut self) -> &mut LocalAgent {
602 &mut self.local
603 }
604
605 #[must_use]
607 pub fn id(&self) -> &str {
608 self.local.id()
609 }
610
611 #[must_use]
613 pub fn name(&self) -> &str {
614 self.local.name()
615 }
616
617 #[must_use]
619 pub fn description(&self) -> Option<&str> {
620 self.local.description()
621 }
622
623 #[must_use]
625 pub fn session_id(&self) -> &str {
626 self.local.session_id()
627 }
628
629 #[must_use]
631 pub fn storage(&self) -> Option<&Arc<dyn Storage>> {
632 self.local.storage()
633 }
634
635 #[must_use]
637 pub fn session_manager(&self) -> Option<&SessionManager> {
638 self.session_manager.as_ref()
639 }
640
641 #[must_use]
643 pub fn messages(&self) -> &[Message] {
644 self.local.messages()
645 }
646
647 pub fn messages_mut(&mut self) -> &mut Vec<Message> {
649 self.local.messages_mut()
650 }
651
652 #[must_use]
654 pub fn system_prompt(&self) -> Option<&SystemPrompt> {
655 self.local.system_prompt()
656 }
657
658 pub fn set_system_prompt(&mut self, system_prompt: Option<SystemPrompt>) {
660 self.local.set_system_prompt(system_prompt);
661 }
662
663 #[must_use]
665 pub fn model(&self) -> &Arc<dyn Model> {
666 self.local.model()
667 }
668
669 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 #[must_use]
684 pub fn aux_model(&self) -> &Arc<dyn Model> {
685 self.local.aux_model()
686 }
687
688 pub fn set_aux_model(&mut self, aux_model: Option<Arc<dyn Model>>) {
690 self.local.set_aux_model(aux_model);
691 }
692
693 #[must_use]
697 pub fn sandbox(&self) -> &Arc<dyn Sandbox> {
698 self.local.sandbox()
699 }
700
701 #[must_use]
703 pub fn app_state(&self) -> &StateStore {
704 self.local.app_state()
705 }
706
707 #[must_use]
709 pub fn model_state(&self) -> &StateStore {
710 self.local.model_state()
711 }
712
713 #[must_use]
715 pub fn tool_registry(&self) -> &ToolRegistry {
716 self.local.tool_registry()
717 }
718
719 pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry {
721 self.local.tool_registry_mut()
722 }
723
724 #[must_use]
726 pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
727 self.local.tool_registry().list()
728 }
729
730 #[must_use]
732 pub fn tool_executor(&self) -> ToolExecutorStrategy {
733 self.tool_executor
734 }
735
736 pub fn set_tool_executor(&mut self, tool_executor: impl Into<ToolExecutorStrategy>) {
738 self.tool_executor = tool_executor.into();
739 }
740
741 #[must_use]
743 pub fn metrics(&self) -> AgentMetrics {
744 self.local.metrics()
745 }
746
747 #[must_use]
749 pub fn baggage_attributes(&self) -> &BTreeMap<String, String> {
750 self.local.tracer().baggage_attributes()
751 }
752
753 #[must_use]
766 pub fn cancel_handle(&self) -> CancelHandle {
767 self.local.cancel_handle().clone()
768 }
769
770 #[must_use]
772 pub fn cancel_signal(&self) -> CancelSignal {
773 self.local.cancel_signal()
774 }
775
776 pub fn add_hook<K: HookEvent>(&self, callback: impl IntoSyncHook<K>) -> HookCleanup {
778 self.local.add_hook(callback)
779 }
780
781 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 pub fn add_async_hook<K: HookEvent>(&self, callback: impl IntoAsyncHook<K>) -> HookCleanup {
792 self.local.add_async_hook::<K>(callback)
793 }
794
795 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 pub fn add_hook_impl<K: HookEvent>(&self, hook: impl IntoHookImpl<K>) -> HookCleanup {
806 self.local.add_hook_impl(hook)
807 }
808
809 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 pub fn add_middleware<S: MiddlewareStage>(&self, middleware: Middleware<S>) -> MiddlewareCleanup {
835 self.local.add_middleware(middleware)
836 }
837
838 #[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 #[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}