Skip to main content

strands/conversation_manager/
sliding_window_conversation_manager.rs

1//! The sliding window strategy.
2
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use async_trait::async_trait;
7use serde::Serialize;
8
9use super::compression::context_compression::{find_valid_trim_point, has_tool_result, has_tool_use};
10use super::compression::pin_message::{apply_pin_first, is_pinned};
11use super::{ConversationManager, ConversationManagerReduceOptions, ProactiveCompression};
12use crate::agent::LocalAgent;
13use crate::error::Result;
14use crate::hooks::AfterInvocationEvent;
15use crate::types::{
16    ContentBlock, DocumentBlock, DocumentSource, ImageBlock, ImageSource, Message, Role, TextBlock, ToolResultBlock,
17    ToolResultContent, VideoBlock, VideoSource,
18};
19
20const PRESERVE_CHARS: usize = 200;
21/// The longest plausible truncation marker, newlines included.
22const MIN_TRUNCATION_GAIN: usize = 50;
23/// Text at or below this length is not worth truncating, so truncated output (just above
24/// `2 * PRESERVE_CHARS`) is not truncated again.
25const TRUNCATION_THRESHOLD: usize = 2 * PRESERVE_CHARS + MIN_TRUNCATION_GAIN;
26const DEFAULT_WINDOW_SIZE: usize = 40;
27
28/// Configuration for [`SlidingWindowConversationManager`] (`SlidingWindowConversationManagerConfig`).
29#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
30pub struct SlidingWindowConversationManagerConfig {
31    /// The most messages kept in history. Defaults to 40.
32    pub window_size: Option<usize>,
33    /// Whether overflow recovery truncates large tool results before trimming messages.
34    /// Defaults to `true`.
35    pub should_truncate_results: Option<bool>,
36    /// Proactive compression before model calls. Defaults to disabled.
37    #[builder(into)]
38    pub proactive_compression: Option<ProactiveCompression>,
39    /// How many messages at the start of the conversation to pin permanently, so reduction never
40    /// removes them.
41    pub pin_first: Option<usize>,
42}
43
44struct Inner {
45    window_size: usize,
46    should_truncate_results: bool,
47    pin_first: Option<usize>,
48    pin_first_applied: AtomicBool,
49    compression_threshold: Option<f64>,
50}
51
52/// Keeps the most recent messages (`SlidingWindowConversationManager`): after every invocation
53/// it trims history to the window, and on a context-window overflow it truncates the oldest large
54/// tool result or trims the oldest messages. Trimming never starts history on a tool result or
55/// separates a tool use from its result.
56#[derive(Clone)]
57pub struct SlidingWindowConversationManager {
58    inner: Arc<Inner>,
59}
60
61impl Default for SlidingWindowConversationManager {
62    fn default() -> Self {
63        Self::with_inner(&SlidingWindowConversationManagerConfig::default(), None)
64    }
65}
66
67impl std::fmt::Debug for SlidingWindowConversationManager {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.debug_struct("SlidingWindowConversationManager")
70            .field("window_size", &self.inner.window_size)
71            .field("should_truncate_results", &self.inner.should_truncate_results)
72            .finish_non_exhaustive()
73    }
74}
75
76impl SlidingWindowConversationManager {
77    /// Creates the manager.
78    ///
79    /// # Errors
80    ///
81    /// A proactive compression threshold outside `(0, 1]`.
82    #[expect(
83        clippy::needless_pass_by_value,
84        reason = "configs are taken by value like every manager's, so fields that own data can join"
85    )]
86    pub fn new(config: SlidingWindowConversationManagerConfig) -> Result<Self> {
87        let threshold = config.proactive_compression.unwrap_or_default().threshold()?;
88        Ok(Self::with_inner(&config, threshold))
89    }
90
91    fn with_inner(config: &SlidingWindowConversationManagerConfig, compression_threshold: Option<f64>) -> Self {
92        Self {
93            inner: Arc::new(Inner {
94                window_size: config.window_size.unwrap_or(DEFAULT_WINDOW_SIZE),
95                should_truncate_results: config.should_truncate_results.unwrap_or(true),
96                pin_first: config.pin_first,
97                pin_first_applied: AtomicBool::new(false),
98                compression_threshold,
99            }),
100        }
101    }
102
103    /// The most messages kept in history.
104    #[must_use]
105    pub fn window_size(&self) -> usize {
106        self.inner.window_size
107    }
108
109    /// Whether overflow recovery truncates tool results first.
110    #[must_use]
111    pub fn should_truncate_results(&self) -> bool {
112        self.inner.should_truncate_results
113    }
114}
115
116#[async_trait]
117impl ConversationManager for SlidingWindowConversationManager {
118    fn name(&self) -> &str {
119        "strands:sliding-window-conversation-manager"
120    }
121
122    /// Truncates the oldest large tool result (overflow recovery only), otherwise trims the oldest
123    /// messages.
124    async fn reduce(&self, options: ConversationManagerReduceOptions<'_>) -> Result<bool> {
125        let overflow = options.error.is_some();
126        Ok(self.inner.reduce_context(options.agent.messages_mut(), overflow))
127    }
128
129    fn compression_threshold(&self) -> Option<f64> {
130        self.inner.compression_threshold
131    }
132
133    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
134        let inner = self.inner.clone();
135        agent.add_hook(move |event: &mut AfterInvocationEvent<'_>| {
136            inner.apply_management(event.agent_mut().messages_mut());
137        });
138        Ok(())
139    }
140}
141
142impl Inner {
143    /// Trims history to the window after an invocation.
144    fn apply_management(&self, messages: &mut Vec<Message>) {
145        if messages.len() <= self.window_size {
146            return;
147        }
148        self.reduce_context(messages, false);
149    }
150
151    fn reduce_context(&self, messages: &mut Vec<Message>, overflow: bool) -> bool {
152        if let Some(count) = self.pin_first.filter(|count| *count > 0)
153            && !self.pin_first_applied.swap(true, Ordering::Relaxed)
154        {
155            apply_pin_first(messages, count);
156        }
157
158        if overflow
159            && self.should_truncate_results
160            && let Some(index) = find_oldest_message_with_tool_results(messages)
161            && truncate_tool_results(messages, index)
162        {
163            return true;
164        }
165
166        let start_index = if messages.len() <= self.window_size {
167            2
168        } else {
169            messages.len() - self.window_size
170        };
171        let mut trim_index = find_valid_trim_point(messages, start_index);
172        let mut fallback_user_index = None;
173        if trim_index == messages.len()
174            && self.window_size > 0
175            && let Some(tool_pair_index) = find_tool_pair_trim_point(messages, start_index)
176        {
177            let Some(anchor) = find_tool_pair_user_anchor(messages, tool_pair_index) else {
178                tracing::debug!(
179                    "window_size=<{}>, trim_index=<{tool_pair_index}> | complete tool pair found but no valid user anchor, declining fallback",
180                    self.window_size
181                );
182                return false;
183            };
184            tracing::debug!(
185                "window_size=<{}>, trim_index=<{tool_pair_index}>, user_anchor_index=<{anchor}> | no plain user trim point, falling back to complete tool pair",
186                self.window_size
187            );
188            trim_index = tool_pair_index;
189            fallback_user_index = Some(anchor);
190        }
191
192        if trim_index > messages.len() || (trim_index == messages.len() && self.window_size > 0) {
193            tracing::warn!(
194                "window_size=<{}>, messages=<{}> | unable to trim conversation context, no valid trim point found",
195                self.window_size,
196                messages.len()
197            );
198            return false;
199        }
200
201        let to_remove: Vec<usize> = (0..trim_index)
202            .filter(|&index| Some(index) != fallback_user_index && !is_pinned(messages, index))
203            .collect();
204        if to_remove.is_empty() {
205            tracing::warn!(
206                "window_size=<{}>, messages=<{}> | all messages in trim range are protected, unable to reduce",
207                self.window_size,
208                messages.len()
209            );
210            return false;
211        }
212        for index in to_remove.into_iter().rev() {
213            messages.remove(index);
214        }
215        true
216    }
217}
218
219/// The oldest unpinned message holding tool results.
220pub(crate) fn find_oldest_message_with_tool_results(messages: &[Message]) -> Option<usize> {
221    (0..messages.len()).find(|&index| !is_pinned(messages, index) && has_tool_result(&messages[index]))
222}
223
224/// The first assistant tool use at or after `start_index` whose result follows.
225fn find_tool_pair_trim_point(messages: &[Message], start_index: usize) -> Option<usize> {
226    (start_index..messages.len()).find(|&index| {
227        let message = &messages[index];
228        message.role == Role::Assistant
229            && has_tool_use(message)
230            && messages
231                .get(index + 1)
232                .is_some_and(|next| next.role == Role::User && has_tool_result(next))
233    })
234}
235
236/// A user message that can stay right before a fallback tool pair:
237/// the last pinned message when the pinned prefix is a valid user-first alternation, otherwise the
238/// latest plain user message before the pair.
239fn find_tool_pair_user_anchor(messages: &[Message], tool_pair_index: usize) -> Option<usize> {
240    let pinned: Vec<usize> = (0..tool_pair_index)
241        .filter(|&index| is_pinned(messages, index))
242        .collect();
243    let Some(&last_pinned) = pinned.last() else {
244        return (0..tool_pair_index).rev().find(|&index| {
245            let message = &messages[index];
246            message.role == Role::User && !has_tool_use(message) && !has_tool_result(message)
247        });
248    };
249    let first = &messages[pinned[0]];
250    if first.role != Role::User || has_tool_result(first) {
251        return None;
252    }
253    if pinned
254        .windows(2)
255        .any(|pair| messages[pair[0]].role == messages[pair[1]].role)
256    {
257        return None;
258    }
259    let last = &messages[last_pinned];
260    (last.role == Role::User && !has_tool_use(last)).then_some(last_pinned)
261}
262
263/// Head and tail with a marker when `text` is over the threshold.
264fn truncate_long_text(text: &str) -> Option<String> {
265    let length = text.chars().count();
266    if length <= TRUNCATION_THRESHOLD {
267        return None;
268    }
269    let prefix: String = text.chars().take(PRESERVE_CHARS).collect();
270    let suffix: String = text.chars().skip(length - PRESERVE_CHARS).collect();
271    let removed = length - 2 * PRESERVE_CHARS;
272    Some(format!("{prefix}\n<truncated chars=\"{removed}\"/>\n{suffix}"))
273}
274
275fn wire<T: Serialize>(value: &T) -> String {
276    serde_json::to_value(value)
277        .ok()
278        .and_then(|value| value.as_str().map(str::to_owned))
279        .unwrap_or_default()
280}
281
282fn image_placeholder(image: &ImageBlock) -> String {
283    let format = wire(&image.format);
284    match &image.source {
285        ImageSource::Bytes(bytes) => format!("[image: {format}, source: bytes, {} bytes]", bytes.len()),
286        ImageSource::Url(_) => format!("[image: {format}, source: url]"),
287        _ => format!("[image: {format}, source: s3]"),
288    }
289}
290
291fn video_placeholder(video: &VideoBlock) -> String {
292    let format = wire(&video.format);
293    match &video.source {
294        VideoSource::Bytes(bytes) => format!("[video: {format}, source: bytes, {} bytes]", bytes.len()),
295        _ => format!("[video: {format}, source: s3]"),
296    }
297}
298
299fn document_placeholder(document: &DocumentBlock, bytes: Option<usize>) -> String {
300    let format = wire(&document.format);
301    match bytes {
302        Some(bytes) => format!("[document: {}, {format}, source: bytes, {bytes} bytes]", document.name),
303        None => format!("[document: {}, {format}, source: s3]", document.name),
304    }
305}
306
307/// The truncated form of a document, or `None` when it stays as it is.
308fn truncate_document(document: &DocumentBlock) -> Option<ToolResultContent> {
309    let source = match &document.source {
310        DocumentSource::Bytes(bytes) => {
311            return Some(ToolResultContent::text(document_placeholder(
312                document,
313                Some(bytes.len()),
314            )));
315        }
316        DocumentSource::Location(_) => return Some(ToolResultContent::text(document_placeholder(document, None))),
317        DocumentSource::Text(text) => DocumentSource::Text(truncate_long_text(text)?),
318        DocumentSource::Content(blocks) => {
319            let truncated: Vec<Option<String>> = blocks.iter().map(|block| truncate_long_text(&block.text)).collect();
320            if truncated.iter().all(Option::is_none) {
321                return None;
322            }
323            DocumentSource::Content(
324                blocks
325                    .iter()
326                    .zip(truncated)
327                    .map(|(block, truncated)| truncated.map_or_else(|| block.clone(), TextBlock::new))
328                    .collect(),
329            )
330        }
331    };
332    let mut document = document.clone();
333    document.source = source;
334    Some(ToolResultContent::Document(document))
335}
336
337/// The truncated form of one tool result item, or `None` when it stays as it is.
338fn truncate_item(item: &ToolResultContent) -> Option<ToolResultContent> {
339    match item {
340        ToolResultContent::Image(image) => Some(ToolResultContent::text(image_placeholder(image))),
341        ToolResultContent::Video(video) => Some(ToolResultContent::text(video_placeholder(video))),
342        ToolResultContent::Document(document) => truncate_document(document),
343        ToolResultContent::Json(json) => {
344            let length = serde_json::to_string(&json.json).ok()?.chars().count();
345            (length > TRUNCATION_THRESHOLD).then(|| ToolResultContent::text(format!("[json: {length} chars]")))
346        }
347        ToolResultContent::Text(text) => truncate_long_text(&text.text).map(ToolResultContent::text),
348        _ => None,
349    }
350}
351
352/// The truncated form of a tool result, keeping its status and error, or `None` when unchanged.
353fn truncate_result(result: &ToolResultBlock) -> Option<ToolResultBlock> {
354    let truncated: Vec<Option<ToolResultContent>> = result.content.iter().map(truncate_item).collect();
355    if truncated.iter().all(Option::is_none) {
356        return None;
357    }
358    let mut result = result.clone();
359    result.content = result
360        .content
361        .iter()
362        .zip(truncated)
363        .map(|(item, truncated)| truncated.unwrap_or_else(|| item.clone()))
364        .collect();
365    Some(result)
366}
367
368/// Truncates the tool results of the message at `index`, keeping its tracking id and dropping its
369/// metadata. Returns whether anything changed.
370pub(crate) fn truncate_tool_results(messages: &mut [Message], index: usize) -> bool {
371    let Some(message) = messages.get_mut(index) else {
372        return false;
373    };
374    let mut changed = false;
375    for block in &mut message.content {
376        let ContentBlock::ToolResult(result) = block else {
377            continue;
378        };
379        if let Some(truncated) = truncate_result(result) {
380            *result = truncated;
381            changed = true;
382        }
383    }
384    if changed {
385        message.metadata = None;
386    }
387    changed
388}
389
390#[cfg(test)]
391pub(crate) mod test_access {
392    use super::{Inner, SlidingWindowConversationManager};
393    use crate::types::Message;
394
395    impl SlidingWindowConversationManager {
396        pub(crate) fn reduce_messages(&self, messages: &mut Vec<Message>, overflow: bool) -> bool {
397            self.inner.reduce_context(messages, overflow)
398        }
399
400        pub(crate) fn apply_management(&self, messages: &mut Vec<Message>) {
401            Inner::apply_management(&self.inner, messages);
402        }
403    }
404
405    pub(crate) use super::{find_oldest_message_with_tool_results, truncate_tool_results};
406}