Skip to main content

strands/agent/
local_agent.rs

1//! The mutable agent view that sequential hook events and plugins see (`LocalAgent`).
2
3use std::fmt;
4use std::sync::{Arc, Mutex, OnceLock, PoisonError};
5
6use super::tool_agent::{ChildInheritance, ToolAgent};
7use crate::background_tasks::BackgroundTasks;
8use crate::cancel::{CancelHandle, CancelOptions, CancelSignal};
9use crate::context_manager::{AgentArchive, ContextManager};
10use crate::hooks::{
11    HookCallbackOptions, HookCleanup, HookEvent, HookRegistry, IntoAsyncHook, IntoHookImpl, IntoSyncHook,
12};
13use crate::interrupt::InterruptState;
14use crate::interventions::InterventionHandler;
15use crate::middleware::{Middleware, MiddlewareCleanup, MiddlewareRegistry, MiddlewareStage};
16use crate::models::Model;
17use crate::models::model_proxy::{CallTools, CallToolsRecord};
18use crate::sandbox::{Sandbox, default_sandbox};
19use crate::state_store::StateStore;
20use crate::storage::Storage;
21use crate::telemetry::{AgentMetrics, Meter, Tracer};
22use crate::tools::ToolRegistry;
23use crate::types::{AgentMetadata, Message, SystemPrompt};
24
25/// The agent as sequential hook events and plugins see it (`LocalAgent`).
26///
27/// It holds everything those callbacks may change: the conversation, the system prompt, the
28/// tools and the state, plus the agent's identity, models and hooks. Hook events lend it out as
29/// `&mut LocalAgent` while the loop is paused at the event.
30#[non_exhaustive]
31pub struct LocalAgent {
32    id: String,
33    name: Option<String>,
34    description: Option<String>,
35    session_id: OnceLock<String>,
36    app_state: StateStore,
37    model_state: StateStore,
38    messages: Vec<Message>,
39    system_prompt: Option<SystemPrompt>,
40    model: Arc<dyn Model>,
41    aux_model: Option<Arc<dyn Model>>,
42    agent_metadata: Option<AgentMetadata>,
43    tool_registry: ToolRegistry,
44    cancel_handle: CancelHandle,
45    cancel_signal: CancelSignal,
46    meter: Arc<Mutex<Meter>>,
47    tracer: Arc<Tracer>,
48    hooks: Arc<HookRegistry>,
49    middleware: Arc<MiddlewareRegistry>,
50    interrupt_state: InterruptState,
51    background_tasks: Option<Arc<BackgroundTasks>>,
52    sandbox: Option<Arc<dyn Sandbox>>,
53    printer: bool,
54    storage: Option<Arc<dyn Storage>>,
55    context_manager: Option<ContextManager>,
56    context_archive: Option<AgentArchive>,
57    latest_call_tools: CallToolsRecord,
58    interventions: Arc<[Arc<dyn InterventionHandler>]>,
59}
60
61impl LocalAgent {
62    /// Creates a view with an id and a model, and empty state otherwise.
63    pub(crate) fn new(id: impl Into<String>, model: Arc<dyn Model>) -> Self {
64        let cancel_handle = CancelHandle::new();
65        Self {
66            id: id.into(),
67            name: None,
68            description: None,
69            session_id: OnceLock::new(),
70            app_state: StateStore::new(),
71            model_state: StateStore::new(),
72            messages: Vec::new(),
73            system_prompt: None,
74            model,
75            aux_model: None,
76            agent_metadata: None,
77            tool_registry: ToolRegistry::new(),
78            cancel_signal: cancel_handle.signal(),
79            cancel_handle,
80            meter: Arc::new(Mutex::new(Meter::new())),
81            tracer: Arc::new(Tracer::default()),
82            hooks: Arc::new(HookRegistry::new()),
83            middleware: Arc::new(MiddlewareRegistry::new()),
84            interrupt_state: InterruptState::new(),
85            background_tasks: None,
86            sandbox: None,
87            printer: false,
88            storage: None,
89            context_manager: None,
90            context_archive: None,
91            latest_call_tools: CallToolsRecord::default(),
92            interventions: Arc::from(Vec::new()),
93        }
94    }
95
96    pub(crate) fn set_name(&mut self, name: Option<String>, description: Option<String>) {
97        self.name = name;
98        self.description = description;
99    }
100
101    /// Uses a session manager's id instead of the generated one.
102    pub(crate) fn set_session_id(&mut self, session_id: String) {
103        self.session_id = OnceLock::from(session_id);
104    }
105
106    pub(crate) fn set_model(&mut self, model: Arc<dyn Model>) {
107        self.model = model;
108    }
109
110    pub(crate) fn set_aux_model(&mut self, aux_model: Option<Arc<dyn Model>>) {
111        self.aux_model = aux_model;
112    }
113
114    pub(crate) fn set_agent_metadata(&mut self, agent_metadata: Option<AgentMetadata>) {
115        self.agent_metadata = agent_metadata;
116    }
117
118    pub(crate) fn set_storage(&mut self, storage: Option<Arc<dyn Storage>>) {
119        self.storage = storage;
120    }
121
122    /// Records the agent's intervention handlers, for the children the default subagent builder
123    /// makes.
124    pub(crate) fn set_interventions(&mut self, interventions: Arc<[Arc<dyn InterventionHandler>]>) {
125        self.interventions = interventions;
126    }
127
128    #[cfg(test)]
129    pub(crate) fn interventions(&self) -> &[Arc<dyn InterventionHandler>] {
130        &self.interventions
131    }
132
133    pub(crate) fn set_context_manager(&mut self, context_manager: Option<ContextManager>) {
134        self.context_manager = context_manager;
135    }
136
137    /// The resolved context manager, when a preset, configuration or instance was given.
138    pub(crate) fn context_manager(&self) -> Option<&ContextManager> {
139        self.context_manager.as_ref()
140    }
141
142    pub(crate) fn set_context_archive(&mut self, context_archive: Option<AgentArchive>) {
143        self.context_archive = context_archive;
144    }
145
146    /// The archive the context manager made for this agent, once it is attached.
147    pub(crate) fn context_archive(&self) -> Option<&AgentArchive> {
148        self.context_archive.as_ref()
149    }
150
151    /// Where the agent's model calls record the tools they send.
152    pub(crate) fn latest_call_tools_record(&self) -> &CallToolsRecord {
153        &self.latest_call_tools
154    }
155
156    /// The tools the agent's latest model call sent, before any stubs; `None` before its first
157    /// call (`latestCallTools`).
158    pub(crate) fn latest_call_tools(&self) -> Option<CallTools> {
159        self.latest_call_tools
160            .lock()
161            .unwrap_or_else(PoisonError::into_inner)
162            .clone()
163    }
164
165    pub(crate) fn set_cancel_handle(&mut self, cancel_handle: CancelHandle) {
166        self.cancel_signal = cancel_handle.signal();
167        self.cancel_handle = cancel_handle;
168    }
169
170    pub(crate) fn cancel_handle(&self) -> &CancelHandle {
171        &self.cancel_handle
172    }
173
174    /// Sets the signal of the current invocation: the agent's own, merged with the caller's.
175    pub(crate) fn set_cancel_signal(&mut self, cancel_signal: CancelSignal) {
176        self.cancel_signal = cancel_signal;
177    }
178
179    pub(crate) fn meter(&self) -> &Arc<Mutex<Meter>> {
180        &self.meter
181    }
182
183    pub(crate) fn tracer(&self) -> &Arc<Tracer> {
184        &self.tracer
185    }
186
187    pub(crate) fn set_tracer(&mut self, tracer: Tracer) {
188        self.tracer = Arc::new(tracer);
189    }
190
191    pub(crate) fn hooks(&self) -> &Arc<HookRegistry> {
192        &self.hooks
193    }
194
195    /// The agent's background tasks once it is initialized; snapshot loads check them.
196    pub(crate) fn set_background_tasks(&mut self, background_tasks: Option<Arc<BackgroundTasks>>) {
197        self.background_tasks = background_tasks;
198    }
199
200    pub(crate) fn background_tasks(&self) -> Option<&Arc<BackgroundTasks>> {
201        self.background_tasks.as_ref()
202    }
203
204    pub(crate) fn middleware(&self) -> &Arc<MiddlewareRegistry> {
205        &self.middleware
206    }
207
208    pub(crate) fn interrupt_state(&self) -> &InterruptState {
209        &self.interrupt_state
210    }
211
212    /// Records whether the agent prints, for the children the default subagent builder makes.
213    pub(crate) fn set_printer(&mut self, printer: bool) {
214        self.printer = printer;
215    }
216
217    pub(crate) fn set_sandbox(&mut self, sandbox: Option<Arc<dyn Sandbox>>) {
218        self.sandbox = sandbox;
219    }
220
221    /// The sandbox from the agent's configuration, without the default.
222    pub(crate) fn configured_sandbox(&self) -> Option<&Arc<dyn Sandbox>> {
223        self.sandbox.as_ref()
224    }
225
226    /// The view tools of the next batch get: shared state and models, and snapshots of the
227    /// messages and tools.
228    pub(crate) fn tool_agent(&self) -> ToolAgent {
229        ToolAgent::new(self.id.clone(), self.session_id(), self.model.clone())
230            .with_name(self.name.clone())
231            .with_state(self.app_state.clone(), self.model_state.clone())
232            .with_aux_model(self.aux_model.clone())
233            .with_cancel_handle(self.cancel_handle.clone())
234            .with_cancel_signal(self.cancel_signal.clone())
235            .with_messages(Arc::from(self.messages.clone()))
236            .with_tool_registry(Arc::new(self.tool_registry.clone()))
237            .with_interrupt_state(self.interrupt_state.clone())
238            .with_sandbox(self.sandbox().clone())
239            .with_printer(self.printer)
240            .with_inheritance(ChildInheritance {
241                context_manager: self.context_manager.clone(),
242                interventions: self.interventions.clone(),
243                tracer: Some(self.tracer.clone()),
244            })
245    }
246
247    /// The agent's unique id.
248    #[must_use]
249    pub fn id(&self) -> &str {
250        &self.id
251    }
252
253    /// The agent's name.
254    #[must_use]
255    pub fn name(&self) -> &str {
256        self.name.as_deref().unwrap_or(super::agent::DEFAULT_AGENT_NAME)
257    }
258
259    /// What the agent does.
260    #[must_use]
261    pub fn description(&self) -> Option<&str> {
262        self.description.as_deref()
263    }
264
265    /// A stable id for the current conversation session: the session manager's id
266    /// when one is attached, otherwise a random 8-character hex id generated once per agent.
267    #[must_use]
268    pub fn session_id(&self) -> &str {
269        self.session_id.get_or_init(|| format!("{:08x}", rand::random::<u32>()))
270    }
271
272    /// App state shared with tools and application code.
273    #[must_use]
274    pub fn app_state(&self) -> &StateStore {
275        &self.app_state
276    }
277
278    /// The model provider's runtime state, such as response ids of server-side conversations.
279    #[must_use]
280    pub fn model_state(&self) -> &StateStore {
281        &self.model_state
282    }
283
284    /// The conversation history.
285    #[must_use]
286    pub fn messages(&self) -> &[Message] {
287        &self.messages
288    }
289
290    /// The conversation history, to edit.
291    pub fn messages_mut(&mut self) -> &mut Vec<Message> {
292        &mut self.messages
293    }
294
295    /// The system prompt.
296    #[must_use]
297    pub fn system_prompt(&self) -> Option<&SystemPrompt> {
298        self.system_prompt.as_ref()
299    }
300
301    /// Replaces or clears the system prompt.
302    pub fn set_system_prompt(&mut self, system_prompt: Option<SystemPrompt>) {
303        self.system_prompt = system_prompt;
304    }
305
306    /// The model the agent calls.
307    #[must_use]
308    pub fn model(&self) -> &Arc<dyn Model> {
309        &self.model
310    }
311
312    /// The model for auxiliary side calls (summaries, classification); the agent's model unless
313    /// one was configured.
314    #[must_use]
315    pub fn aux_model(&self) -> &Arc<dyn Model> {
316        self.aux_model.as_ref().unwrap_or(&self.model)
317    }
318
319    /// The metadata the agent passes to its model.
320    #[must_use]
321    pub fn agent_metadata(&self) -> Option<&AgentMetadata> {
322        self.agent_metadata.as_ref()
323    }
324
325    /// Where the agent's tools run commands and touch files (`sandbox`): the configured sandbox,
326    /// or the shared [`NotASandboxLocalEnvironment`](crate::sandbox::NotASandboxLocalEnvironment)
327    /// when none is configured.
328    #[must_use]
329    pub fn sandbox(&self) -> &Arc<dyn Sandbox> {
330        self.sandbox.as_ref().unwrap_or(default_sandbox())
331    }
332
333    /// The default storage backend for agent subsystems (`storage`): subsystems without their own
334    /// storage, such as the session manager, resolve from it under their own namespace.
335    #[must_use]
336    pub fn storage(&self) -> Option<&Arc<dyn Storage>> {
337        self.storage.as_ref()
338    }
339
340    /// The agent's tools.
341    #[must_use]
342    pub fn tool_registry(&self) -> &ToolRegistry {
343        &self.tool_registry
344    }
345
346    /// The agent's tools, to add or remove some.
347    pub fn tool_registry_mut(&mut self) -> &mut ToolRegistry {
348        &mut self.tool_registry
349    }
350
351    /// The cancellation signal of the current invocation.
352    #[must_use]
353    pub fn cancel_signal(&self) -> CancelSignal {
354        self.cancel_signal.clone()
355    }
356
357    /// Cancels the current invocation (`cancel`); does nothing when the agent is idle.
358    pub fn cancel(&self, options: CancelOptions) {
359        self.cancel_handle.cancel(options);
360    }
361
362    /// Aggregated loop metrics of the agent: cycles, token usage and tool statistics.
363    #[must_use]
364    pub fn metrics(&self) -> AgentMetrics {
365        self.meter.lock().unwrap_or_else(PoisonError::into_inner).metrics()
366    }
367
368    /// Registers a hook closure; see [`HookRegistry::add_hook`].
369    pub fn add_hook<K: HookEvent>(&self, callback: impl IntoSyncHook<K>) -> HookCleanup {
370        self.hooks.add_hook(callback)
371    }
372
373    /// Registers a hook closure with options; see [`HookRegistry::add_hook_with`].
374    pub fn add_hook_with<K: HookEvent>(
375        &self,
376        callback: impl IntoSyncHook<K>,
377        options: HookCallbackOptions,
378    ) -> HookCleanup {
379        self.hooks.add_hook_with(callback, options)
380    }
381
382    /// Registers an async hook closure; see [`HookRegistry::add_async_hook`].
383    pub fn add_async_hook<K: HookEvent>(&self, callback: impl IntoAsyncHook<K>) -> HookCleanup {
384        self.hooks.add_async_hook::<K>(callback)
385    }
386
387    /// Registers an async hook closure with options; see [`HookRegistry::add_async_hook_with`].
388    pub fn add_async_hook_with<K: HookEvent>(
389        &self,
390        callback: impl IntoAsyncHook<K>,
391        options: HookCallbackOptions,
392    ) -> HookCleanup {
393        self.hooks.add_async_hook_with::<K>(callback, options)
394    }
395
396    /// Registers a [`Hook`](crate::hooks::Hook) implementation; see [`HookRegistry::add_hook_impl`].
397    pub fn add_hook_impl<K: HookEvent>(&self, hook: impl IntoHookImpl<K>) -> HookCleanup {
398        self.hooks.add_hook_impl(hook)
399    }
400
401    /// Registers a [`Hook`](crate::hooks::Hook) implementation with options.
402    pub fn add_hook_impl_with<K: HookEvent>(
403        &self,
404        hook: impl IntoHookImpl<K>,
405        options: HookCallbackOptions,
406    ) -> HookCleanup {
407        self.hooks.add_hook_impl_with(hook, options)
408    }
409
410    /// Registers a middleware handler for its stage and phase; see
411    /// [`middleware`](crate::middleware). Handlers registered while an invocation runs apply from
412    /// the next stage call.
413    pub fn add_middleware<S: MiddlewareStage>(&self, middleware: Middleware<S>) -> MiddlewareCleanup {
414        self.middleware.add(middleware)
415    }
416}
417
418impl fmt::Debug for LocalAgent {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        f.debug_struct("LocalAgent")
421            .field("id", &self.id)
422            .field("name", &self.name)
423            .field("messages", &self.messages.len())
424            .field("tool_registry", &self.tool_registry)
425            .finish_non_exhaustive()
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use serde_json::json;
432
433    use super::*;
434    use crate::test_support::MockTool;
435    use crate::testing::MockModel;
436
437    fn agent() -> LocalAgent {
438        LocalAgent::new("agent-1", Arc::new(MockModel::new()))
439    }
440
441    #[test]
442    fn session_id_is_generated_once_as_eight_hex_characters() {
443        let agent = agent();
444        let id = agent.session_id().to_owned();
445        assert_eq!(id.len(), 8);
446        assert!(id.bytes().all(|byte| byte.is_ascii_hexdigit()));
447        assert_eq!(agent.session_id(), id);
448        let mut agent = agent;
449        agent.set_session_id("session-1".into());
450        assert_eq!(agent.session_id(), "session-1");
451    }
452
453    #[test]
454    fn tool_agent_shares_state_and_snapshots_messages_and_tools() {
455        let mut agent = agent();
456        agent.messages_mut().push(Message::user("hi"));
457        agent.tool_registry_mut().add(MockTool::new("probe")).unwrap();
458        let view = agent.tool_agent();
459        agent.messages_mut().clear();
460        agent.tool_registry_mut().clear();
461        view.app_state().set("k", json!(1)).unwrap();
462
463        assert_eq!(view.messages().len(), 1);
464        assert!(view.tool_registry().get("probe").is_some());
465        assert_eq!(agent.app_state().get_value("k"), Some(json!(1)));
466        assert_eq!(view.session_id(), agent.session_id());
467        agent.cancel(CancelOptions::default());
468        assert!(view.cancel_signal().is_cancelled());
469    }
470
471    #[test]
472    fn system_prompt_and_aux_model_have_setters() {
473        let mut agent = agent();
474        agent.set_system_prompt(Some("Be brief.".into()));
475        assert_eq!(agent.system_prompt(), Some(&SystemPrompt::from("Be brief.")));
476        assert!(Arc::ptr_eq(agent.aux_model(), agent.model()));
477        let aux: Arc<dyn Model> = Arc::new(MockModel::new());
478        agent.set_aux_model(Some(aux.clone()));
479        assert!(Arc::ptr_eq(agent.aux_model(), &aux));
480    }
481}