Skip to main content

strands/memory/
memory_manager.rs

1//! The memory manager plugin.
2
3use std::collections::HashSet;
4use std::fmt;
5use std::sync::{Arc, Mutex, PoisonError};
6
7use async_trait::async_trait;
8use futures::future::join_all;
9use serde_json::json;
10use tracing::Instrument;
11
12use super::extraction::coordinator::{ExtractionBinding, ExtractionCoordinator};
13use super::extraction::resolve::resolve_extraction_config;
14use super::extraction::{ExtractionFire, ExtractionTriggerContext};
15use super::types::{
16    AggregateError, MemoryAddOptions, MemoryAddToolConfig, MemoryEntry, MemoryInjectionConfig, MemoryManagerConfig,
17    MemorySearchOptions, MemoryStore, MemoryToolConfig, SearchOptions,
18};
19use crate::agent::LocalAgent;
20use crate::error::{Error, Result};
21use crate::hooks::MessageAddedEvent;
22use crate::injection::xml::{escape_xml_attr, escape_xml_text};
23use crate::injection::{InjectionTrigger, injection_middleware, is_user_turn};
24use crate::plugins::Plugin;
25use crate::telemetry::{
26    EndMemoryAddSpanOptions, EndMemoryInjectSpanOptions, EndMemorySearchSpanOptions, StartMemoryAddSpanOptions,
27    StartMemoryInjectSpanOptions, StartMemorySearchSpanOptions, Tracer,
28};
29use crate::tools::{FunctionTool, SchemaValidator, ToolError, ToolSource};
30use crate::types::Toggle;
31use crate::types::{ContentBlock, JsonValue, Message, Role};
32
33const SEARCH_TOOL_DESCRIPTION: &str = "Search long-term memory for facts, preferences, or context from previous conversations. Use when you need background about the user or topic that may have been discussed before.";
34
35const ADD_TOOL_DESCRIPTION: &str = "Add facts, preferences, or decisions to long-term memory so they are remembered across conversations. Use when the user shares something worth recalling later.";
36
37/// Results per store when neither the caller nor the store sets a limit.
38pub(crate) const DEFAULT_MAX_SEARCH_RESULTS: usize = 3;
39
40/// Entries injected per model call by default: a store ranks by similarity, not usefulness, so a
41/// small candidate set beats betting on the top hit.
42const DEFAULT_MAX_ENTRIES: usize = 5;
43
44const MEMORY_MANAGER_NAME: &str = "strands:memory-manager";
45
46fn has_write_sink(store: &dyn MemoryStore) -> bool {
47    store.implements_add() || store.implements_add_messages()
48}
49
50/// Why an `add` failed: a bad target, or the store writes that failed.
51enum AddError {
52    Target(Error),
53    Writes(AggregateError),
54}
55
56impl From<AddError> for Error {
57    fn from(error: AddError) -> Self {
58        match error {
59            AddError::Target(error) => error,
60            AddError::Writes(error) => Error::other(error),
61        }
62    }
63}
64
65struct Inner {
66    stores: Vec<Arc<dyn MemoryStore>>,
67    /// Writable stores implementing `add`: the unscoped targets of [`MemoryManager::add`].
68    add_stores: Vec<Arc<dyn MemoryStore>>,
69    search_tool_config: Option<MemoryToolConfig>,
70    add_tool: Option<(MemoryAddToolConfig, Vec<Arc<dyn MemoryStore>>)>,
71    extraction: Vec<ExtractionBinding>,
72    injection: Option<MemoryInjectionConfig>,
73    coordinator: Mutex<Option<ExtractionCoordinator>>,
74    /// The memory spans' tracer, shared with the extraction coordinator. Each manager has its own;
75    /// spans still parent through the current span.
76    tracer: Arc<Tracer>,
77}
78
79/// Cross-session memory for agents (`MemoryManager`): manages one or more [`MemoryStore`]s and
80/// exposes the `search_memory` and `add_memory` tools, any tools the stores provide, memory
81/// injection before model calls and automatic extraction.
82///
83/// A `MemoryManager` is a handle: clones share the stores, the configuration and the pending
84/// extraction, so a clone kept before handing one to an agent can search or flush the same state.
85///
86/// ```
87/// use std::sync::Arc;
88/// use strands::memory::{MemoryManager, MemoryManagerConfig, MemoryStore};
89/// use strands::vended_memory_stores::test_memory_store::{TestMemoryStore, TestMemoryStoreConfig};
90///
91/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
92/// let store = TestMemoryStore::new(TestMemoryStoreConfig { persist: Some(false), ..TestMemoryStoreConfig::new("notes") })?;
93/// store.add("User prefers dark mode", None).await?;
94/// let manager = MemoryManager::new(MemoryManagerConfig {
95///     stores: vec![Arc::new(store)],
96///     ..Default::default()
97/// })?;
98/// let entries = manager.search("dark mode").await?;
99/// assert_eq!(entries[0].content, "User prefers dark mode");
100/// assert_eq!(entries[0].store_name.as_deref(), Some("notes"));
101/// # Ok::<(), strands::Error>(())
102/// # }).unwrap();
103/// ```
104#[derive(Clone)]
105pub struct MemoryManager {
106    inner: Arc<Inner>,
107}
108
109impl MemoryManager {
110    /// Whether two handles share one manager.
111    #[cfg(test)]
112    pub(crate) fn same_as(&self, other: &Self) -> bool {
113        Arc::ptr_eq(&self.inner, &other.inner)
114    }
115}
116
117impl fmt::Debug for MemoryManager {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.debug_struct("MemoryManager")
120            .field(
121                "stores",
122                &self.inner.stores.iter().map(|store| store.name()).collect::<Vec<_>>(),
123            )
124            .finish_non_exhaustive()
125    }
126}
127
128fn validate_store(store: &Arc<dyn MemoryStore>, seen: &mut HashSet<String>) -> Result<Option<ExtractionBinding>> {
129    let name = store.name();
130    if !seen.insert(name.to_owned()) {
131        return Err(Error::other(format!("MemoryManager: duplicate store name '{name}'")));
132    }
133    if store.writable() && !has_write_sink(store.as_ref()) {
134        return Err(Error::other(format!(
135            "MemoryManager: store '{name}' is writable but has no add or addMessages method"
136        )));
137    }
138    let Some(extraction) = store.extraction() else {
139        return Ok(None);
140    };
141    if !store.writable() {
142        return Err(Error::other(format!(
143            "MemoryManager: store '{name}' has extraction config but is not writable"
144        )));
145    }
146    let Some(config) = resolve_extraction_config(Some(extraction), store.as_ref()) else {
147        return Ok(None);
148    };
149    if config.triggers.is_empty() {
150        return Err(Error::other(format!(
151            "MemoryManager: store '{name}' has extraction config but no triggers"
152        )));
153    }
154    if config.extractor.is_some() && !store.implements_add() {
155        return Err(Error::other(format!(
156            "MemoryManager: store '{name}' has an extractor but no add method (extracted entries are written via add)"
157        )));
158    }
159    if config.extractor.is_none() && !store.implements_add_messages() {
160        return Err(Error::other(format!(
161            "MemoryManager: store '{name}' has extraction config without an extractor but no addMessages method"
162        )));
163    }
164    Ok(Some(ExtractionBinding {
165        store: store.clone(),
166        config,
167    }))
168}
169
170/// The stores' names, in order.
171fn names_of(stores: &[Arc<dyn MemoryStore>]) -> Vec<String> {
172    stores.iter().map(|store| store.name().to_owned()).collect()
173}
174
175/// Keeps the first of each name.
176fn dedupe(names: &[String]) -> Vec<&str> {
177    let mut seen = HashSet::new();
178    names
179        .iter()
180        .map(String::as_str)
181        .filter(|name| seen.insert(*name))
182        .collect()
183}
184
185impl MemoryManager {
186    /// Creates the manager.
187    ///
188    /// # Errors
189    ///
190    /// No stores, duplicate store names, a writable store with no write method, an extraction
191    /// config the store cannot serve (not writable, no triggers, or missing the write method its
192    /// route needs), or an `add_memory` tool with no store it may write to.
193    pub fn new(config: MemoryManagerConfig) -> Result<Self> {
194        if config.stores.is_empty() {
195            return Err(Error::other("MemoryManager: at least one store is required"));
196        }
197        let mut seen = HashSet::new();
198        let mut extraction = Vec::new();
199        for store in &config.stores {
200            extraction.extend(validate_store(store, &mut seen)?);
201        }
202        let add_stores: Vec<_> = config
203            .stores
204            .iter()
205            .filter(|store| store.writable() && store.implements_add())
206            .cloned()
207            .collect();
208        let search_tool_config = config
209            .search_tool_config
210            .unwrap_or(Toggle::On(MemoryToolConfig::default()))
211            .into_option();
212        let add_tool = match config.add_tool_config.and_then(Toggle::into_option) {
213            None => None,
214            Some(tool_config) => {
215                if add_stores.is_empty() {
216                    return Err(Error::other(
217                        "MemoryManager: addToolConfig is enabled but no writable stores implement add",
218                    ));
219                }
220                let stores = resolve_add_tool_stores(&config.stores, &add_stores, &tool_config)?;
221                Some((tool_config, stores))
222            }
223        };
224        let injection = config
225            .injection
226            .unwrap_or(Toggle::On(MemoryInjectionConfig::default()))
227            .into_option();
228        Ok(Self {
229            inner: Arc::new(Inner {
230                stores: config.stores,
231                add_stores,
232                search_tool_config,
233                add_tool,
234                extraction,
235                injection,
236                coordinator: Mutex::new(None),
237                tracer: Arc::new(Tracer::default()),
238            }),
239        })
240    }
241
242    /// Searches every store and concatenates their results in store order, each entry carrying
243    /// its store's name (`search` without options); [`search_with`](Self::search_with) narrows
244    /// the stores or the result count. Every store gets its own default count, else 3. A store
245    /// that fails is logged and skipped.
246    ///
247    /// # Errors
248    ///
249    /// None today: store failures are logged and skipped.
250    pub async fn search(&self, query: &str) -> Result<Vec<MemoryEntry>> {
251        self.search_with(query, MemorySearchOptions::default()).await
252    }
253
254    /// Searches the stores with options (`search`): every store gets the caller's
255    /// `max_search_results`, else its own default, else 3.
256    ///
257    /// # Errors
258    ///
259    /// `MemoryManager: store '<name>' not found` for a named store that is not configured.
260    pub async fn search_with(&self, query: &str, options: MemorySearchOptions) -> Result<Vec<MemoryEntry>> {
261        self.inner.search(query, options).await
262    }
263
264    /// Adds content to every writable store (`add` without options), waiting for every write;
265    /// [`add_with`](Self::add_with) names the stores or attaches metadata. Store failures are
266    /// logged and reported together.
267    ///
268    /// # Errors
269    ///
270    /// No writable store (`no writable store matched`), or an [`AggregateError`]
271    /// `MemoryManager: store writes failed: <names>` when any write fails.
272    pub async fn add(&self, content: &str) -> Result<()> {
273        self.add_with(content, MemoryAddOptions::default()).await
274    }
275
276    /// Adds content with options (`add`): to the named writable stores, with metadata.
277    ///
278    /// # Errors
279    ///
280    /// An unknown (`store '<name>' not found`) or read-only (`store '<name>' is read-only`)
281    /// named store, no target (`no writable store matched`), or an [`AggregateError`]
282    /// `MemoryManager: store writes failed: <names>` when any write fails.
283    pub async fn add_with(&self, content: &str, options: MemoryAddOptions) -> Result<()> {
284        Ok(self.inner.add(content, options, false).await?)
285    }
286
287    /// Saves every store's remaining messages and waits for the saves (`flush`); does nothing
288    /// without extraction. Extraction runs in the background, so the latest turn may not be saved
289    /// when the agent answers; [`Agent::shutdown`](crate::Agent::shutdown) calls this. Calling it
290    /// after every turn forces a save each time and defeats the triggers' schedule.
291    pub async fn flush(&self) {
292        let coordinator = self
293            .inner
294            .coordinator
295            .lock()
296            .unwrap_or_else(PoisonError::into_inner)
297            .clone();
298        if let Some(coordinator) = coordinator {
299            coordinator.flush().await;
300        }
301    }
302
303    #[cfg(test)]
304    pub(crate) fn coordinator(&self) -> Option<ExtractionCoordinator> {
305        self.inner
306            .coordinator
307            .lock()
308            .unwrap_or_else(PoisonError::into_inner)
309            .clone()
310    }
311
312    #[cfg(test)]
313    pub(crate) fn injection_config(&self) -> Option<&MemoryInjectionConfig> {
314        self.inner.injection.as_ref()
315    }
316
317    #[cfg(test)]
318    pub(crate) async fn provide_memory_context(&self, messages: &[Message]) -> Result<Option<String>> {
319        let config = self.inner.injection.clone().unwrap_or_default();
320        self.inner.provide_memory_context(messages, &config).await
321    }
322
323    fn init_extraction(&self, agent: &LocalAgent) {
324        if self.inner.extraction.is_empty() {
325            return;
326        }
327        let coordinator = ExtractionCoordinator::new(
328            self.inner.extraction.clone(),
329            agent.aux_model().clone(),
330            self.inner.tracer.clone(),
331        );
332        *self.inner.coordinator.lock().unwrap_or_else(PoisonError::into_inner) = Some(coordinator.clone());
333        let recorder = coordinator.clone();
334        agent.add_hook(move |event: &mut MessageAddedEvent<'_>| recorder.record(event.message().clone()));
335        for (index, binding) in self.inner.extraction.iter().enumerate() {
336            for trigger in &binding.config.triggers {
337                let coordinator = coordinator.clone();
338                let fire = ExtractionFire::new(move |invocation_context| {
339                    drop(coordinator.process(index, invocation_context));
340                });
341                trigger.attach(ExtractionTriggerContext { agent, fire });
342            }
343        }
344    }
345
346    fn init_injection(&self, agent: &LocalAgent) {
347        let Some(config) = self.inner.injection.clone() else {
348            return;
349        };
350        let inner = self.inner.clone();
351        let trigger = config.trigger.clone().unwrap_or(InjectionTrigger::UserTurn);
352        agent.add_middleware(injection_middleware(trigger, move |context| {
353            let inner = inner.clone();
354            let config = config.clone();
355            async move {
356                inner
357                    .provide_memory_context(&context.messages, &config)
358                    .await
359                    .unwrap_or_else(|error| {
360                        tracing::warn!("reason=<{error}> | injection renderContent threw; skipping injection");
361                        None
362                    })
363            }
364        }));
365    }
366}
367
368fn resolve_add_tool_stores(
369    stores: &[Arc<dyn MemoryStore>],
370    add_stores: &[Arc<dyn MemoryStore>],
371    config: &MemoryAddToolConfig,
372) -> Result<Vec<Arc<dyn MemoryStore>>> {
373    let Some(names) = &config.stores else {
374        return Ok(add_stores.to_vec());
375    };
376    dedupe(names)
377        .into_iter()
378        .map(|name| {
379            let Some(found) = stores.iter().find(|store| store.name() == name) else {
380                return Err(Error::other(format!(
381                    "MemoryManager: addToolConfig store '{name}' not found"
382                )));
383            };
384            if !found.writable() {
385                return Err(Error::other(format!(
386                    "MemoryManager: addToolConfig store '{name}' is not writable"
387                )));
388            }
389            if !found.implements_add() {
390                return Err(Error::other(format!(
391                    "MemoryManager: addToolConfig store '{name}' has no add method (only addMessages)"
392                )));
393            }
394            Ok(found.clone())
395        })
396        .collect()
397}
398
399/// The stores a tool call targets: all in scope when none are named;
400/// out-of-scope names are dropped with a warning, and an error when none is left.
401fn resolve_tool_targets(
402    scoped: &[String],
403    requested: Option<Vec<String>>,
404) -> std::result::Result<Vec<String>, ToolError> {
405    let Some(requested) = requested.filter(|requested| !requested.is_empty()) else {
406        return Ok(scoped.to_vec());
407    };
408    let (in_scope, out_of_scope): (Vec<String>, Vec<String>) =
409        requested.iter().cloned().partition(|name| scoped.contains(name));
410    if in_scope.is_empty() {
411        return Err(ToolError::msg(format!(
412            "MemoryManager: requested=<{}> | none of the requested memory stores are available; available stores: {}",
413            requested.join(", "),
414            scoped.join(", ")
415        )));
416    }
417    if !out_of_scope.is_empty() {
418        tracing::warn!(
419            "requested=<{}> | ignoring memory stores outside this tool's scope",
420            out_of_scope.join(", ")
421        );
422    }
423    Ok(in_scope)
424}
425
426fn store_descriptions(stores: &[Arc<dyn MemoryStore>]) -> Vec<String> {
427    stores
428        .iter()
429        .filter_map(|store| {
430            let description = store.description().filter(|description| !description.is_empty())?;
431            Some(format!("- {}: {description}", store.name()))
432        })
433        .collect()
434}
435
436fn string_list(input: &JsonValue, key: &str) -> Option<Vec<String>> {
437    input.get(key)?.as_array().map(|items| {
438        items
439            .iter()
440            .filter_map(|item| item.as_str().map(str::to_owned))
441            .collect()
442    })
443}
444
445fn validator(schema: &JsonValue) -> Option<Arc<SchemaValidator>> {
446    SchemaValidator::new(schema).ok().map(Arc::new)
447}
448
449fn validate(validator: Option<&SchemaValidator>, input: &JsonValue) -> std::result::Result<(), ToolError> {
450    match validator {
451        Some(validator) => validator.validate(input).map_err(ToolError::new),
452        None => Ok(()),
453    }
454}
455
456/// Collects the store errors behind failed `add` calls.
457fn flatten(failures: Vec<AddError>) -> Vec<Error> {
458    failures
459        .into_iter()
460        .flat_map(|failure| match failure {
461            AddError::Target(error) => vec![error],
462            AddError::Writes(aggregate) => aggregate.into_errors(),
463        })
464        .collect()
465}
466
467impl Inner {
468    fn find(&self, name: &str) -> Result<&Arc<dyn MemoryStore>> {
469        self.stores
470            .iter()
471            .find(|store| store.name() == name)
472            .ok_or_else(|| Error::other(format!("MemoryManager: store '{name}' not found")))
473    }
474
475    async fn search(&self, query: &str, options: MemorySearchOptions) -> Result<Vec<MemoryEntry>> {
476        tracing::debug!(
477            "query=<{query}>, max_search_results=<{:?}>, stores=<{:?}> | searching stores",
478            options.max_search_results,
479            options.stores
480        );
481        let store_names = options.stores.clone().unwrap_or_else(|| names_of(&self.stores));
482        let span = self.tracer.start_memory_search_span(StartMemorySearchSpanOptions {
483            query,
484            store_names: &store_names,
485            max_search_results: options.max_search_results,
486        });
487        let targets = match self.search_targets(options.stores.as_deref()) {
488            Ok(targets) => targets,
489            Err(error) => {
490                let message = error.to_string();
491                self.tracer.end_memory_search_span(
492                    span,
493                    EndMemorySearchSpanOptions {
494                        error: Some(&message),
495                        ..EndMemorySearchSpanOptions::default()
496                    },
497                );
498                return Err(error);
499            }
500        };
501        let searches = targets.iter().map(|store| {
502            let max_search_results = options
503                .max_search_results
504                .or_else(|| store.max_search_results())
505                .unwrap_or(DEFAULT_MAX_SEARCH_RESULTS);
506            store.search(
507                query,
508                SearchOptions {
509                    max_search_results: Some(max_search_results),
510                },
511            )
512        });
513        let mut results = Vec::new();
514        let mut store_failure_count = 0;
515        for (store, outcome) in targets.iter().zip(join_all(searches).await) {
516            let name = store.name();
517            match outcome {
518                Ok(entries) => results.extend(entries.into_iter().map(|entry| entry.with_store_name(name))),
519                Err(error) => {
520                    tracing::warn!("store=<{name}>, reason=<{error}> | store search failed");
521                    store_failure_count += 1;
522                }
523            }
524        }
525        self.tracer.end_memory_search_span(
526            span,
527            EndMemorySearchSpanOptions {
528                entries: &results,
529                store_failure_count,
530                error: None,
531            },
532        );
533        tracing::debug!("results=<{}> | search complete", results.len());
534        Ok(results)
535    }
536
537    fn search_targets(&self, stores: Option<&[String]>) -> Result<Vec<&Arc<dyn MemoryStore>>> {
538        match stores {
539            Some(names) => dedupe(names).into_iter().map(|name| self.find(name)).collect(),
540            None => Ok(self.stores.iter().collect()),
541        }
542    }
543
544    fn add_targets(&self, stores: Option<&[String]>) -> Result<Vec<Arc<dyn MemoryStore>>> {
545        let Some(names) = stores else {
546            return Ok(self.add_stores.clone());
547        };
548        dedupe(names)
549            .into_iter()
550            .map(|name| {
551                let found = self.find(name)?;
552                if !found.writable() {
553                    return Err(Error::other(format!("MemoryManager: store '{name}' is read-only")));
554                }
555                Ok(found.clone())
556            })
557            .collect()
558    }
559
560    /// Writes `content` (`add`); a `detached` write (the fire-and-forget tool path) starts its
561    /// span as a trace root rather than under a span that may have ended.
562    async fn add(&self, content: &str, options: MemoryAddOptions, detached: bool) -> std::result::Result<(), AddError> {
563        let store_names = options.stores.clone().unwrap_or_else(|| names_of(&self.add_stores));
564        let span = self.tracer.start_memory_add_span(StartMemoryAddSpanOptions {
565            content,
566            store_names: &store_names,
567            force_root: detached,
568        });
569        let outcome = self.write(content, options).await;
570        let (store_failure_count, message) = match &outcome {
571            Ok(()) => (0, None),
572            Err(AddError::Target(error)) => (0, Some(error.to_string())),
573            Err(AddError::Writes(error)) => (error.errors().len(), Some(error.to_string())),
574        };
575        self.tracer.end_memory_add_span(
576            span,
577            EndMemoryAddSpanOptions {
578                store_failure_count,
579                error: message.as_deref(),
580            },
581        );
582        outcome
583    }
584
585    async fn write(&self, content: &str, options: MemoryAddOptions) -> std::result::Result<(), AddError> {
586        let targets = self.add_targets(options.stores.as_deref()).map_err(AddError::Target)?;
587        if targets.is_empty() {
588            return Err(AddError::Target(Error::other(
589                "MemoryManager: no writable store matched",
590            )));
591        }
592        let writes = targets.iter().map(|store| store.add(content, options.metadata.clone()));
593        let mut failed = Vec::new();
594        let mut errors = Vec::new();
595        for (store, outcome) in targets.iter().zip(join_all(writes).await) {
596            let Err(error) = outcome else {
597                continue;
598            };
599            let name = store.name();
600            tracing::warn!("store=<{name}>, reason=<{error}> | store write failed");
601            failed.push(name.to_owned());
602            errors.push(error);
603        }
604        if errors.is_empty() {
605            return Ok(());
606        }
607        Err(AddError::Writes(AggregateError::new(
608            errors,
609            format!("MemoryManager: store writes failed: {}", failed.join(", ")),
610        )))
611    }
612
613    /// The text to inject for a call, or `None` to skip: derives the
614    /// query, searches and renders the top entries.
615    async fn provide_memory_context(
616        &self,
617        messages: &[Message],
618        config: &MemoryInjectionConfig,
619    ) -> Result<Option<String>> {
620        let max_entries = config.max_entries.unwrap_or(DEFAULT_MAX_ENTRIES);
621        let span = self.tracer.start_memory_inject_span(StartMemoryInjectSpanOptions {
622            max_entries: Some(max_entries),
623        });
624        let outcome = self
625            .render_memory_context(messages, config, max_entries)
626            .instrument(span.span())
627            .await;
628        let (rendered, end) = match outcome {
629            Ok(rendered) => rendered,
630            Err(error) => {
631                self.tracer
632                    .end_memory_inject_span(span, EndMemoryInjectSpanOptions::default());
633                return Err(error);
634            }
635        };
636        self.tracer.end_memory_inject_span(span, end);
637        Ok(rendered)
638    }
639
640    /// Derives the query, searches and renders the top entries, with how the inject span ends.
641    async fn render_memory_context(
642        &self,
643        messages: &[Message],
644        config: &MemoryInjectionConfig,
645        max_entries: usize,
646    ) -> Result<(Option<String>, EndMemoryInjectSpanOptions)> {
647        let skipped = EndMemoryInjectSpanOptions::default();
648        let Some(query) = resolve_injection_query(messages, config).filter(|query| !query.trim().is_empty()) else {
649            return Ok((None, skipped));
650        };
651        let options = MemorySearchOptions {
652            max_search_results: Some(max_entries),
653            stores: None,
654        };
655        let mut entries = self.search(&query, options).await?;
656        entries.truncate(max_entries);
657        if entries.is_empty() {
658            return Ok((None, skipped));
659        }
660        let injected = EndMemoryInjectSpanOptions {
661            injected: true,
662            entry_count: entries.len(),
663            format_error: false,
664        };
665        let Some(format) = &config.format else {
666            return Ok((Some(default_injection_format(&entries)), injected));
667        };
668        match (format.0)(&entries) {
669            Ok(rendered) => Ok((Some(rendered), injected)),
670            Err(error) => {
671                tracing::warn!("reason=<{error}> | injection format threw; skipping injection");
672                let format_error = EndMemoryInjectSpanOptions {
673                    format_error: true,
674                    ..skipped
675                };
676                Ok((None, format_error))
677            }
678        }
679    }
680}
681
682/// The injection search query: the configured callback, or the latest
683/// user text on a user turn and the most recent assistant text otherwise.
684fn resolve_injection_query(messages: &[Message], config: &MemoryInjectionConfig) -> Option<String> {
685    if let Some(query) = &config.query {
686        return (query.0)(messages).unwrap_or_else(|error| {
687            tracing::warn!("reason=<{error}> | injection query threw; skipping injection");
688            None
689        });
690    }
691    let role = if is_user_turn(messages) {
692        Role::User
693    } else {
694        Role::Assistant
695    };
696    let message = messages.iter().rev().find(|message| message.role == role)?;
697    let text = message
698        .content
699        .iter()
700        .filter_map(|block| match block {
701            ContentBlock::Text(text) => Some(text.text.as_str()),
702            _ => None,
703        })
704        .collect::<Vec<_>>()
705        .join("\n");
706    let text = text.trim();
707    (!text.is_empty()).then(|| text.to_owned())
708}
709
710/// The default injection format: a `<memory>` block with one
711/// escaped `<entry>` per result, attributed to its store when known.
712pub(crate) fn default_injection_format(entries: &[MemoryEntry]) -> String {
713    let items: Vec<String> = entries
714        .iter()
715        .map(
716            |entry| match entry.store_name.as_deref().filter(|name| !name.is_empty()) {
717                Some(store) => format!(
718                    "<entry source=\"{}\">{}</entry>",
719                    escape_xml_attr(store),
720                    escape_xml_text(&entry.content)
721                ),
722                None => format!("<entry>{}</entry>", escape_xml_text(&entry.content)),
723            },
724        )
725        .collect();
726    format!("<memory>\n{}\n</memory>", items.join("\n"))
727}
728
729fn search_tool(inner: &Arc<Inner>, config: &MemoryToolConfig) -> FunctionTool {
730    let mut description = config
731        .description
732        .clone()
733        .unwrap_or_else(|| SEARCH_TOOL_DESCRIPTION.to_owned());
734    let descriptions = store_descriptions(&inner.stores);
735    if !descriptions.is_empty() {
736        description.push_str(&format!("\n\nAvailable memory stores:\n{}", descriptions.join("\n")));
737        description.push_str("\n\nYou can target one or more memory stores by name if you know which domains are relevant, or omit the stores parameter to search all.");
738    }
739    let scoped: Arc<Vec<String>> = Arc::new(inner.stores.iter().map(|store| store.name().to_owned()).collect());
740    let schema = json!({
741        "type": "object",
742        "properties": {
743            "query": {"type": "string", "description": "What to search for"},
744            "maxSearchResults": {"description": "Maximum number of results per store", "type": "number"},
745            "stores": {
746                "description": "Filter to specific stores by name. Omit to search all available stores.",
747                "type": "array",
748                "items": {"type": "string"}
749            }
750        },
751        "required": ["query"],
752        "additionalProperties": false
753    });
754    let validator = validator(&schema);
755    let inner = inner.clone();
756    FunctionTool::builder(config.name.as_deref().unwrap_or("search_memory"), description)
757        .input_schema(schema)
758        .callback(move |input, _context| {
759            let inner = inner.clone();
760            let scoped = scoped.clone();
761            let validator = validator.clone();
762            async move {
763                validate(validator.as_deref(), &input)?;
764                let stores = resolve_tool_targets(&scoped, string_list(&input, "stores"))?;
765                let query = input.get("query").and_then(JsonValue::as_str).unwrap_or_default();
766                #[allow(
767                    clippy::cast_possible_truncation,
768                    clippy::cast_sign_loss,
769                    reason = "a JSON number of results, clamped at zero and floored to a count"
770                )]
771                let max_search_results = input
772                    .get("maxSearchResults")
773                    .and_then(JsonValue::as_f64)
774                    .map(|max| max.max(0.0) as usize);
775                let options = MemorySearchOptions {
776                    max_search_results,
777                    stores: Some(stores),
778                };
779                let results = inner.search(query, options).await?;
780                Ok(serde_json::to_value(results)?)
781            }
782        })
783}
784
785fn add_tool(inner: &Arc<Inner>, config: &MemoryAddToolConfig, stores: &[Arc<dyn MemoryStore>]) -> FunctionTool {
786    let mut description = config
787        .description
788        .clone()
789        .unwrap_or_else(|| ADD_TOOL_DESCRIPTION.to_owned());
790    let descriptions = store_descriptions(stores);
791    if !descriptions.is_empty() {
792        description.push_str(&format!("\n\nAvailable writable stores:\n{}", descriptions.join("\n")));
793        description.push_str("\n\nYou can target a specific store by name to route facts to the right place, or omit to add to all available writable stores.");
794    }
795    let scoped: Arc<Vec<String>> = Arc::new(stores.iter().map(|store| store.name().to_owned()).collect());
796    let wait_for_writes = config.wait_for_writes.unwrap_or(true);
797    let schema = json!({
798        "type": "object",
799        "properties": {
800            "entries": {
801                "minItems": 1,
802                "type": "array",
803                "items": {"type": "string"},
804                "description": "Data to add to long-term memory"
805            },
806            "stores": {
807                "description": "Target specific stores by name. Omit to add to all writable stores.",
808                "type": "array",
809                "items": {"type": "string"}
810            }
811        },
812        "required": ["entries"],
813        "additionalProperties": false
814    });
815    let validator = validator(&schema);
816    let inner = inner.clone();
817    FunctionTool::builder(config.name.as_deref().unwrap_or("add_memory"), description)
818        .input_schema(schema)
819        .callback(move |input, _context| {
820            let inner = inner.clone();
821            let scoped = scoped.clone();
822            let validator = validator.clone();
823            async move {
824                validate(validator.as_deref(), &input)?;
825                let stores = resolve_tool_targets(&scoped, string_list(&input, "stores"))?;
826                let entries = string_list(&input, "entries").unwrap_or_default();
827                if wait_for_writes {
828                    store_entries(&inner, entries, stores).await
829                } else {
830                    Ok(dispatch_entries(&inner, &entries, &stores))
831                }
832            }
833        })
834}
835
836/// Awaits every write and reports the store errors behind any failure.
837async fn store_entries(
838    inner: &Inner,
839    entries: Vec<String>,
840    stores: Vec<String>,
841) -> std::result::Result<JsonValue, ToolError> {
842    let writes = entries.iter().map(|content| {
843        let options = MemoryAddOptions {
844            metadata: None,
845            stores: Some(stores.clone()),
846        };
847        inner.add(content, options, false)
848    });
849    let failures: Vec<AddError> = join_all(writes)
850        .await
851        .into_iter()
852        .filter_map(|outcome| outcome.err())
853        .collect();
854    if failures.is_empty() {
855        return Ok(json!({"stored": entries.len()}));
856    }
857    let failed = failures.len();
858    let reasons = flatten(failures);
859    let message = format!(
860        "MemoryManager: failed to add {failed} of {} entries: {}",
861        entries.len(),
862        reasons.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
863    );
864    Err(ToolError::new(AggregateError::new(reasons, message)))
865}
866
867/// Dispatches the writes without waiting, so a slow backend never blocks the loop; `add` logs
868/// failures.
869fn dispatch_entries(inner: &Arc<Inner>, entries: &[String], stores: &[String]) -> JsonValue {
870    if let Ok(runtime) = tokio::runtime::Handle::try_current() {
871        for content in entries {
872            let inner = inner.clone();
873            let content = content.clone();
874            let options = MemoryAddOptions {
875                metadata: None,
876                stores: Some(stores.to_vec()),
877            };
878            runtime.spawn(async move {
879                let _ = inner.add(&content, options, true).await;
880            });
881        }
882    }
883    json!({"accepted": entries.len()})
884}
885
886#[async_trait]
887impl Plugin for MemoryManager {
888    fn name(&self) -> &str {
889        MEMORY_MANAGER_NAME
890    }
891
892    /// Initializes the stores, wires extraction for the stores that use it, and registers the
893    /// injection middleware when injection is on.
894    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
895        for store in &self.inner.stores {
896            store.initialize().await?;
897        }
898        self.init_extraction(agent);
899        self.init_injection(agent);
900        Ok(())
901    }
902
903    /// The `search_memory` and `add_memory` tools as configured, then each store's tools.
904    fn get_tools(&self) -> Vec<ToolSource> {
905        let mut tools: Vec<ToolSource> = Vec::new();
906        if let Some(config) = &self.inner.search_tool_config {
907            tools.push(search_tool(&self.inner, config).into());
908        }
909        if let Some((config, stores)) = &self.inner.add_tool {
910            tools.push(add_tool(&self.inner, config, stores).into());
911        }
912        tools.extend(self.inner.stores.iter().flat_map(|store| store.get_tools()));
913        tools
914    }
915}
916
917#[cfg(test)]
918#[cfg(feature = "otel")]
919mod tracing_tests;