Skip to main content

strands/context_manager/
context_manager.rs

1//! The context manager: strategy-driven context reduction, offloading to the archive and overflow
2//! recovery.
3
4use std::collections::HashSet;
5use std::fmt;
6use std::str::FromStr;
7use std::sync::atomic::{AtomicU32, Ordering};
8use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
9
10use async_trait::async_trait;
11
12use super::archive::Archive;
13use super::methods::truncate::TruncateConfig;
14use super::presets::resolve_strategies;
15use super::retrieval_tool::{RETRIEVAL_TOOL_NAME, create_retrieval_tool};
16use super::strategies::deferred_tool_loading::DeferStrategy;
17use super::strategies::offload::{
18    EmergencyTruncateStrategy, Offload, OffloadConditions, OffloadTarget, SummarizeConfig,
19};
20use super::types::{ArchiveConfig, ContextManagerConfig, ContextState, ContextStrategy};
21use crate::agent::{InvocationContext, LocalAgent};
22use crate::error::{Error, Result};
23use crate::hooks::{AfterModelCallEvent, BeforeModelCallEvent, MessageAddedEvent};
24use crate::models::Model;
25use crate::models::model_proxy::{CallTools, count_request_tokens};
26use crate::plugins::Plugin;
27use crate::storage::{InMemoryStorage, Storage};
28use crate::tools::{LOAD_TOOLS_TOOL_NAME, ToolRegistry, ToolSource};
29use crate::types::{ContentBlock, Message, Toggle, ToolSpec};
30
31const TRUNCATE_PREVIEW_TOKENS: f64 = 750.0;
32const MAX_OVERFLOW_RETRIES: u32 = 3;
33
34/// The plugin name (`name`).
35pub(crate) const CONTEXT_MANAGER_NAME: &str = "strands:context-manager";
36
37/// What `AgentConfig::context_manager` accepts (`ContextManagerStrategy`).
38#[derive(Debug, Clone)]
39#[non_exhaustive]
40pub enum ContextManagerStrategy {
41    /// Proactive truncation of tool results and summarization at 85% utilization (`'auto'`).
42    Auto,
43    /// Model-driven context management through the `summarize_context`, `truncate_context` and
44    /// `pin_context` tools, a higher truncation threshold and summarization only on overflow
45    /// (`'agentic'`, experimental).
46    Agentic,
47    /// A custom pipeline and archive.
48    Config(ContextManagerConfig),
49    /// An instance, used as is (a handle: clones share the manager).
50    Instance(ContextManager),
51    /// No context management: no compression, no offloading (`false`).
52    Disabled,
53}
54
55impl From<ContextManagerConfig> for ContextManagerStrategy {
56    fn from(config: ContextManagerConfig) -> Self {
57        Self::Config(config)
58    }
59}
60
61impl From<ContextManager> for ContextManagerStrategy {
62    fn from(manager: ContextManager) -> Self {
63        Self::Instance(manager)
64    }
65}
66
67impl From<Arc<ContextManager>> for ContextManagerStrategy {
68    fn from(manager: Arc<ContextManager>) -> Self {
69        Self::Instance((*manager).clone())
70    }
71}
72
73impl FromStr for ContextManagerStrategy {
74    type Err = Error;
75
76    /// Parses a preset name, `auto` or `agentic`.
77    fn from_str(preset: &str) -> Result<Self> {
78        match preset {
79            "auto" => Ok(Self::Auto),
80            "agentic" => Ok(Self::Agentic),
81            other => Err(Error::other(format!(
82                "Unknown contextManager preset: \"{other}\". Valid presets: \"auto\", \"agentic\""
83            ))),
84        }
85    }
86}
87
88#[derive(Clone)]
89enum ArchiveStorage {
90    Default,
91    Explicit(Arc<dyn Storage>),
92    Disabled,
93}
94
95/// Manages context reduction for an agent's conversation (`ContextManager`).
96///
97/// Before each model call it runs its strategy pipeline; on a context window overflow it runs
98/// the pipeline in recovery mode and retries the call, up to three times. An emergency truncation
99/// always runs last and fires only when the window still overflows after the configured strategies
100/// have run. Offloaded content is archived, and the `retrieve_context` tool lets the model read it
101/// back.
102///
103/// Configure it through `AgentConfig::context_manager`; with one present no separate
104/// conversation manager is needed. Cheap to clone: clones are handles to the same manager and
105/// compare equal; separately built managers never do.
106///
107/// ```
108/// use strands::Agent;
109/// use strands::context_manager::ContextManagerStrategy;
110/// use strands::testing::MockModel;
111///
112/// let agent = Agent::builder()
113///     .model(MockModel::new().with_turn("Hi"))
114///     .context_manager(ContextManagerStrategy::Auto)
115///     .printer(false)
116///     .build()?;
117/// # let _ = agent;
118/// # Ok::<(), strands::Error>(())
119/// ```
120#[derive(Clone)]
121pub struct ContextManager {
122    strategies: Arc<[Arc<dyn ContextStrategy>]>,
123    archive_storage: ArchiveStorage,
124    enable_retrieval_tool: bool,
125    last_archive: Arc<Mutex<Option<AgentArchive>>>,
126}
127
128/// The archive a context manager made for one agent, kept on that agent so its hooks, strategies,
129/// retrieval tool and session manager use it even when the manager serves several agents.
130#[derive(Clone, Debug)]
131pub(crate) struct AgentArchive {
132    pub(crate) archive: Archive,
133    pub(crate) durable: bool,
134}
135
136impl PartialEq for ContextManager {
137    fn eq(&self, other: &Self) -> bool {
138        Arc::ptr_eq(&self.last_archive, &other.last_archive)
139    }
140}
141
142impl Eq for ContextManager {}
143
144impl fmt::Debug for ContextManager {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        let strategies: Vec<&str> = self.strategies.iter().map(|strategy| strategy.name()).collect();
147        f.debug_struct("ContextManager")
148            .field("strategies", &strategies)
149            .field("archive", &self.archive())
150            .finish_non_exhaustive()
151    }
152}
153
154/// The retrieval tool calls answered by the message at `index`. Their results are copies of archived
155/// content, so the archive leaves them out. A tool result follows the message that called it.
156fn retrieval_calls_before(messages: &[Message], index: usize) -> HashSet<String> {
157    let Some(previous) = index.checked_sub(1).and_then(|previous| messages.get(previous)) else {
158        return HashSet::new();
159    };
160    previous
161        .content
162        .iter()
163        .filter_map(|block| match block {
164            ContentBlock::ToolUse(tool_use) if tool_use.name == RETRIEVAL_TOOL_NAME => {
165                Some(tool_use.tool_use_id.clone())
166            }
167            _ => None,
168        })
169        .collect()
170}
171
172/// The strategy pipeline of a preset: tool results over `truncate_threshold` tokens truncated to a
173/// 750-token preview, then summarization at `summarize_utilization`. `auto` is also the default
174/// for a config that names none.
175fn preset_strategies(truncate_threshold: u64, summarize_utilization: &str) -> Result<Vec<Arc<dyn ContextStrategy>>> {
176    let truncate = Offload::truncate(
177        OffloadTarget::ToolResults,
178        TruncateConfig {
179            preview_tokens: Some(TRUNCATE_PREVIEW_TOKENS),
180            ..TruncateConfig::default()
181        },
182    )?
183    .when(OffloadConditions {
184        block_threshold: Some(truncate_threshold.into()),
185        ..OffloadConditions::default()
186    })?;
187    let summarize = Offload::summarize(OffloadTarget::All, SummarizeConfig::default())?.when(OffloadConditions {
188        context_utilization: Some(summarize_utilization.into()),
189        preserve_recent: Some(4.into()),
190        ..OffloadConditions::default()
191    })?;
192    Ok(vec![Arc::new(truncate), Arc::new(summarize)])
193}
194
195fn auto_strategies() -> Result<Vec<Arc<dyn ContextStrategy>>> {
196    preset_strategies(1_500, "85%")
197}
198
199fn agentic_strategies() -> Result<Vec<Arc<dyn ContextStrategy>>> {
200    preset_strategies(8_000, "100%")
201}
202
203/// Runs the pipeline once; a failing strategy is logged and the next runs.
204async fn run_strategies(
205    strategies: &[Arc<dyn ContextStrategy>],
206    archive: Option<Archive>,
207    agent: &mut LocalAgent,
208    precomputed_input_tokens: Option<u64>,
209    overflow: bool,
210    invocation_context: Option<&InvocationContext>,
211) -> Result<bool> {
212    let model = agent.model().clone();
213    let input_tokens = match precomputed_input_tokens {
214        Some(tokens) => tokens,
215        None => count_request_tokens(agent, agent.messages()).await?,
216    };
217    let agent_id = agent.id().to_owned();
218    let mut state = ContextState::new(agent, model.estimate_utilization(input_tokens))
219        .with_overflow(overflow)
220        .with_archive(archive)
221        .with_invocation_context(InvocationContext::auxiliary(invocation_context));
222    let mut any_acted = false;
223    for strategy in strategies {
224        if any_acted && strategy.name() == "offload:emergency-truncate" {
225            state.overflow = false;
226        }
227        let applied = apply_strategy(strategy.as_ref(), &mut state, &model, &mut any_acted).await;
228        if let Err(error) = applied {
229            tracing::warn!(
230                "strategy=<{}>, agent_id=<{agent_id}>, error=<{error}> | strategy failed, continuing",
231                strategy.name()
232            );
233        }
234    }
235    Ok(any_acted)
236}
237
238/// Applies one strategy and, when it acted, recounts the utilization; a recount that fails counts
239/// as the strategy failing, after it acted.
240async fn apply_strategy(
241    strategy: &dyn ContextStrategy,
242    state: &mut ContextState<'_>,
243    model: &Arc<dyn Model>,
244    any_acted: &mut bool,
245) -> Result<()> {
246    if !strategy.apply(state).await? {
247        return Ok(());
248    }
249    *any_acted = true;
250    let tokens = count_request_tokens(state.agent, state.agent.messages()).await?;
251    state.utilization = model.estimate_utilization(tokens);
252    tracing::debug!(
253        "strategy=<{}>, agent_id=<{}> | strategy applied",
254        strategy.name(),
255        state.agent.id()
256    );
257    Ok(())
258}
259
260impl ContextManager {
261    /// Creates a context manager (`new ContextManager(config)`).
262    ///
263    /// # Errors
264    ///
265    /// A preset that does not resolve.
266    pub fn new(config: ContextManagerConfig) -> Result<Self> {
267        let mut strategies = match &config.strategies {
268            Some(entries) => resolve_strategies(entries)?,
269            None => auto_strategies()?,
270        };
271        check_one_tool_loading_strategy(&strategies)?;
272        strategies.push(Arc::new(EmergencyTruncateStrategy::new()));
273        let archive = config.archive.unwrap_or_else(|| Toggle::On(ArchiveConfig::default()));
274        let (archive_storage, enable_retrieval_tool) = match archive.into_option() {
275            None => (ArchiveStorage::Disabled, false),
276            Some(archive) => (
277                archive
278                    .storage
279                    .map_or(ArchiveStorage::Default, ArchiveStorage::Explicit),
280                archive.retrieval_tool != Some(false),
281            ),
282        };
283        Ok(Self {
284            strategies: strategies.into(),
285            archive_storage,
286            enable_retrieval_tool,
287            last_archive: Arc::default(),
288        })
289    }
290
291    /// The `agentic` preset's manager: tool results truncated over 8,000 tokens and
292    /// summarization only on overflow.
293    fn agentic() -> Result<Self> {
294        let mut manager = Self::new(ContextManagerConfig::default())?;
295        let mut strategies = agentic_strategies()?;
296        strategies.push(Arc::new(EmergencyTruncateStrategy::new()));
297        manager.strategies = strategies.into();
298        Ok(manager)
299    }
300
301    /// Resolves a strategy value to a manager (`ContextManager.from`): an instance as is, a new
302    /// manager for a preset or a configuration, and `None` for `Disabled` or no value.
303    ///
304    /// # Errors
305    ///
306    /// A configuration whose presets do not resolve.
307    pub fn from_strategy(strategy: Option<ContextManagerStrategy>) -> Result<Option<Self>> {
308        Ok(match strategy {
309            None | Some(ContextManagerStrategy::Disabled) => None,
310            Some(ContextManagerStrategy::Instance(manager)) => Some(manager),
311            Some(ContextManagerStrategy::Auto) => Some(Self::new(ContextManagerConfig::default())?),
312            Some(ContextManagerStrategy::Agentic) => Some(Self::agentic()?),
313            Some(ContextManagerStrategy::Config(config)) => Some(Self::new(config)?),
314        })
315    }
316
317    /// The tools an agent's model call with these tool specs on this model sends, so a count or a
318    /// summary replay of the request carries the same tools (`callTools`): the specs and the names
319    /// of the ones it defers, or every spec without an `Offload.defer` strategy.
320    pub(crate) fn call_tools(
321        &self,
322        _agent_id: &str,
323        registry: &ToolRegistry,
324        tool_specs: &[ToolSpec],
325        model: &Arc<dyn Model>,
326    ) -> CallTools {
327        match self.tool_loading_strategy() {
328            Some(strategy) => strategy.call_tools(registry, tool_specs, model),
329            None => CallTools {
330                tool_specs: tool_specs.to_vec(),
331                ..CallTools::default()
332            },
333        }
334    }
335
336    /// The `Offload.defer` strategy among the strategies, if there is one.
337    fn tool_loading_strategy(&self) -> Option<&DeferStrategy> {
338        self.strategies.iter().find_map(|strategy| strategy.as_defer_strategy())
339    }
340
341    /// A manager whose archive is `archive`, for session tests that stand in for an attached one.
342    #[cfg(test)]
343    pub(crate) fn with_test_archive(archive: Archive, durable: bool) -> Result<Self> {
344        let manager = Self::new(ContextManagerConfig::default())?;
345        *manager.lock_last_archive() = Some(AgentArchive { archive, durable });
346        Ok(manager)
347    }
348
349    /// The archive, once the manager is attached to an agent and the archive is enabled (`archive`).
350    ///
351    /// A manager shared by several agents gives each agent its own archive; this returns the one
352    /// made for the agent attached last.
353    #[must_use]
354    pub fn archive(&self) -> Option<Archive> {
355        self.lock_last_archive()
356            .as_ref()
357            .map(|agent_archive| agent_archive.archive.clone())
358    }
359
360    /// Whether the archive is on storage that outlives the process, so session snapshots need not
361    /// embed its data. For a shared manager, of the agent attached last.
362    #[must_use]
363    pub fn archive_is_durable(&self) -> bool {
364        self.lock_last_archive()
365            .as_ref()
366            .is_some_and(|agent_archive| agent_archive.durable)
367    }
368
369    fn lock_last_archive(&self) -> MutexGuard<'_, Option<AgentArchive>> {
370        self.last_archive.lock().unwrap_or_else(PoisonError::into_inner)
371    }
372
373    fn resolve_archive(&self, agent: &LocalAgent) -> Result<Option<AgentArchive>> {
374        let (storage, custom_namespace): (Arc<dyn Storage>, bool) = match &self.archive_storage {
375            ArchiveStorage::Disabled => return Ok(None),
376            ArchiveStorage::Explicit(storage) => (storage.clone(), true),
377            ArchiveStorage::Default => (
378                agent
379                    .storage()
380                    .cloned()
381                    .unwrap_or_else(|| Arc::new(InMemoryStorage::new())),
382                false,
383            ),
384        };
385        let durable = !storage.is_ephemeral();
386        let archive = Archive::with_namespace(storage, agent.session_id(), agent.id(), custom_namespace)?;
387        Ok(Some(AgentArchive { archive, durable }))
388    }
389}
390
391/// Overflow recovery: reruns the pipeline and retries the call, at most three times in a row.
392async fn on_overflow(
393    strategies: Arc<[Arc<dyn ContextStrategy>]>,
394    archive: Option<Archive>,
395    retries: Arc<AtomicU32>,
396    event: &mut AfterModelCallEvent<'_>,
397) -> Result<()> {
398    if !matches!(event.error(), Some(Error::ContextWindowOverflow(_))) {
399        retries.store(0, Ordering::Relaxed);
400        return Ok(());
401    }
402    let agent_id = event.agent().id().to_owned();
403    if retries.load(Ordering::Relaxed) >= MAX_OVERFLOW_RETRIES {
404        tracing::warn!("agent_id=<{agent_id}> | overflow retry limit reached, giving up");
405        retries.store(0, Ordering::Relaxed);
406        return Ok(());
407    }
408    let invocation_context = event.invocation_context().cloned();
409    let acted = run_strategies(
410        &strategies,
411        archive,
412        event.agent_mut(),
413        None,
414        true,
415        invocation_context.as_ref(),
416    )
417    .await?;
418    if !acted {
419        tracing::warn!("agent_id=<{agent_id}> | no strategy made progress, skipping retry");
420        return Ok(());
421    }
422    retries.fetch_add(1, Ordering::Relaxed);
423    event.set_retry(true);
424    Ok(())
425}
426
427#[async_trait]
428impl Plugin for ContextManager {
429    fn name(&self) -> &str {
430        CONTEXT_MANAGER_NAME
431    }
432
433    fn get_tools(&self) -> Vec<ToolSource> {
434        let retrieval = self
435            .archive()
436            .filter(|_| self.enable_retrieval_tool)
437            .map(|archive| ToolSource::from(create_retrieval_tool(archive)));
438        let loader = self
439            .tool_loading_strategy()
440            .map(|strategy| ToolSource::from(strategy.load_tools()));
441        retrieval.into_iter().chain(loader).collect()
442    }
443
444    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
445        if self.tool_loading_strategy().is_some() && agent.tool_registry().get(LOAD_TOOLS_TOOL_NAME).is_some() {
446            return Err(Error::other(format!(
447                "contextManager adds a tool named '{LOAD_TOOLS_TOOL_NAME}' for Offload.defer and the 'deferredToolLoading' preset, and the agent already has one; rename the agent's tool"
448            )));
449        }
450        let agent_archive = self.resolve_archive(agent)?;
451        agent.set_context_archive(agent_archive.clone());
452        *self.lock_last_archive() = agent_archive.clone();
453        let archive = agent_archive.map(|agent_archive| agent_archive.archive);
454        if let Some(archive) = archive.clone() {
455            let stored_keys: HashSet<String> = archive.list("").await?.into_iter().collect();
456            let messages = agent.messages().to_vec();
457            for (index, message) in messages.iter().enumerate() {
458                let skip = retrieval_calls_before(&messages, index);
459                archive.store_message(message, Some(&skip), Some(&stored_keys)).await;
460            }
461            agent.add_async_hook::<MessageAddedEvent<'_>>(move |event| {
462                let archive = archive.clone();
463                Box::pin(async move {
464                    let message = event.message().clone();
465                    let messages = event.agent().messages();
466                    let index = messages
467                        .iter()
468                        .rposition(|candidate| candidate.tracking_id() == message.tracking_id())
469                        .unwrap_or(messages.len());
470                    let skip = retrieval_calls_before(messages, index);
471                    archive.store_message(&message, Some(&skip), None).await;
472                })
473            });
474        }
475        for strategy in self.strategies.iter() {
476            strategy.init(agent, archive.as_ref())?;
477        }
478        let strategies = self.strategies.clone();
479        let before_archive = archive.clone();
480        agent.add_async_hook::<BeforeModelCallEvent<'_>>(move |event| {
481            let strategies = strategies.clone();
482            let archive = before_archive.clone();
483            Box::pin(async move {
484                let projected = event.projected_input_tokens();
485                let invocation_context = event.invocation_context().cloned();
486                run_strategies(
487                    &strategies,
488                    archive,
489                    event.agent_mut(),
490                    projected,
491                    false,
492                    invocation_context.as_ref(),
493                )
494                .await
495                .map(drop)
496            })
497        });
498        let strategies = self.strategies.clone();
499        let retries = Arc::new(AtomicU32::new(0));
500        agent.add_async_hook::<AfterModelCallEvent<'_>>(move |event| {
501            let strategies = strategies.clone();
502            let archive = archive.clone();
503            let retries = retries.clone();
504            Box::pin(async move { on_overflow(strategies, archive, retries, event).await })
505        });
506        Ok(())
507    }
508}
509
510/// Two `Offload.defer` strategies can't share an agent's tools list, which holds one `load_tools`.
511fn check_one_tool_loading_strategy(strategies: &[Arc<dyn ContextStrategy>]) -> Result<()> {
512    let count = strategies
513        .iter()
514        .filter(|strategy| strategy.as_defer_strategy().is_some())
515        .count();
516    if count < 2 {
517        return Ok(());
518    }
519    Err(Error::other(
520        "contextManager takes one Offload.defer strategy, and the 'deferredToolLoading' preset is one; to change what the preset defers or when, use Offload.defer(target).when(conditions) in its place",
521    ))
522}
523
524impl crate::Agent {
525    /// The resolved context manager, when `AgentConfig::context_manager` set a preset, a
526    /// configuration or an instance. Experimental, like the
527    /// [`context_manager`](crate::context_manager) module: it may change in a minor
528    /// release.
529    #[must_use]
530    pub fn context_manager(&self) -> Option<&ContextManager> {
531        self.local.context_manager()
532    }
533}
534
535#[cfg(test)]
536#[path = "context_manager/tests.rs"]
537mod tests;
538
539#[cfg(test)]
540#[path = "context_manager/agent_tests.rs"]
541mod agent_tests;