Skip to main content

strands/context_manager/strategies/offload/
target.rs

1//! Offload targets: which blocks and messages a strategy acts on.
2
3use std::collections::{HashMap, HashSet};
4
5use crate::error::{Error, Result};
6use crate::types::{ContentBlock, Message, Role, ToolResultBlock, ToolResultContent, ToolResultStatus};
7
8/// What an offload strategy acts on (`OffloadTarget`).
9#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum OffloadTarget {
12    /// Whole messages (`'*'`).
13    All,
14    /// Successful tool results (`'toolResults'`).
15    ToolResults,
16    /// Failed tool results (`'toolResultErrors'`).
17    ToolResultErrors,
18    /// Text blocks of assistant messages (`'assistantText'`).
19    AssistantText,
20    /// Text blocks of user messages, tool results excluded (`'userText'`).
21    UserText,
22    /// Image, document, video and audio blocks outside tool results (`'media'`).
23    Media,
24    /// Results of the named tools (`bash` or `tool::bash`); a leading `!` excludes a tool instead.
25    /// A list of only exclusions acts on every other tool.
26    Tools(Vec<String>),
27}
28
29impl OffloadTarget {
30    /// The results of the named tools (`['tool::bash', '!tool::read']`).
31    pub fn tools(tools: impl IntoIterator<Item = impl Into<String>>) -> Self {
32        Self::Tools(tools.into_iter().map(Into::into).collect())
33    }
34}
35
36const TOOL_PREFIX: &str = "tool::";
37
38/// The media kind of a block, such as `image`, for markers, or `None` when it is not media
39/// (`mediaKind`).
40pub(crate) fn media_kind(block: &ContentBlock) -> Option<&'static str> {
41    match block {
42        ContentBlock::Image(_) => Some("image"),
43        ContentBlock::Document(_) => Some("document"),
44        ContentBlock::Video(_) => Some("video"),
45        ContentBlock::Audio(_) => Some("audio"),
46        _ => None,
47    }
48}
49
50/// A block's type name for logs, such as `textBlock` (`block.type`).
51pub(crate) fn block_type(block: &ContentBlock) -> &'static str {
52    match block {
53        ContentBlock::Text(_) => "textBlock",
54        ContentBlock::ToolUse(_) => "toolUseBlock",
55        ContentBlock::ToolResult(_) => "toolResultBlock",
56        ContentBlock::Reasoning(_) => "reasoningBlock",
57        ContentBlock::CachePoint(_) => "cachePointBlock",
58        ContentBlock::GuardContent(_) => "guardContentBlock",
59        ContentBlock::Audio(_) => "audioBlock",
60        ContentBlock::Image(_) => "imageBlock",
61        ContentBlock::Video(_) => "videoBlock",
62        ContentBlock::Document(_) => "documentBlock",
63        ContentBlock::Citations(_) => "citationsBlock",
64        ContentBlock::Injected(_) => "injectedBlock",
65        ContentBlock::Summary(_) => "summaryBlock",
66        _ => "unknownBlock",
67    }
68}
69
70/// The target as JSON, as a log names it: `"toolResults"`, or `["bash"]` for a tool list.
71pub(crate) fn target_json(target: &OffloadTarget) -> String {
72    let name = match target {
73        OffloadTarget::Tools(entries) => return serde_json::to_string(entries).unwrap_or_default(),
74        OffloadTarget::All => "*",
75        OffloadTarget::ToolResults => "toolResults",
76        OffloadTarget::ToolResultErrors => "toolResultErrors",
77        OffloadTarget::AssistantText => "assistantText",
78        OffloadTarget::UserText => "userText",
79        OffloadTarget::Media => "media",
80    };
81    format!("\"{name}\"")
82}
83
84/// Whether a block is an image, document, video or audio block (`isMediaBlock`).
85pub(crate) fn is_media_block(block: &ContentBlock) -> bool {
86    media_kind(block).is_some()
87}
88
89/// Whether tool result content is an image, document or video.
90pub(crate) fn is_media_content(content: &ToolResultContent) -> bool {
91    matches!(
92        content,
93        ToolResultContent::Image(_) | ToolResultContent::Document(_) | ToolResultContent::Video(_)
94    )
95}
96
97/// Whether a block is protocol rather than content: tool uses, cache points and reasoning are
98/// never stored or offloaded (`isProtocolBlock`).
99pub(crate) fn is_protocol_block(block: &ContentBlock) -> bool {
100    matches!(
101        block,
102        ContentBlock::ToolUse(_) | ContentBlock::CachePoint(_) | ContentBlock::Reasoning(_)
103    )
104}
105
106/// `toolUseId` to tool name, from every assistant tool use (`buildToolNameMap`).
107pub(crate) fn build_tool_name_map(messages: &[Message]) -> HashMap<String, String> {
108    messages
109        .iter()
110        .filter(|message| message.role == Role::Assistant)
111        .flat_map(|message| &message.content)
112        .filter_map(|block| match block {
113            ContentBlock::ToolUse(tool_use) => Some((tool_use.tool_use_id.clone(), tool_use.name.clone())),
114            _ => None,
115        })
116        .collect()
117}
118
119/// Matches blocks and messages against an [`OffloadTarget`]; a tool list's names are parsed once,
120/// here (`OffloadTargetMatcher`).
121#[derive(Debug, Clone)]
122pub(crate) struct OffloadTargetMatcher {
123    pub(crate) target: OffloadTarget,
124    include: Option<HashSet<String>>,
125    exclude: Option<HashSet<String>>,
126}
127
128impl OffloadTargetMatcher {
129    /// # Errors
130    ///
131    /// An empty tool list, or one that excludes every tool it includes.
132    pub(crate) fn new(target: OffloadTarget) -> Result<Self> {
133        let (include, exclude) = match &target {
134            OffloadTarget::Tools(entries) if entries.is_empty() => {
135                return Err(Error::other(
136                    "Empty array target matches nothing — provide at least one target",
137                ));
138            }
139            OffloadTarget::Tools(entries) => resolve_tool_filter(entries),
140            _ => (None, None),
141        };
142        if let (Some(include), OffloadTarget::Tools(entries)) = (&include, &target)
143            && include.is_empty()
144        {
145            return Err(Error::other(format!(
146                "Tool target {} excludes every tool it includes, so it matches nothing",
147                serde_json::to_string(entries).unwrap_or_default()
148            )));
149        }
150        Ok(Self {
151            target,
152            include,
153            exclude,
154        })
155    }
156
157    /// Whether every kind of block is in scope.
158    pub(crate) fn matches_all(&self) -> bool {
159        self.target == OffloadTarget::All
160    }
161
162    /// Whether a block in `message` is one this target covers. A placeholder matches like the text
163    /// block it is, so callers that must not re-offload one filter it out first.
164    pub(crate) fn matches_block(
165        &self,
166        block: &ContentBlock,
167        message: &Message,
168        tool_names: &HashMap<String, String>,
169    ) -> bool {
170        if self.matches_all() {
171            return true;
172        }
173        match block {
174            ContentBlock::Text(_) => self.matches_text(message),
175            ContentBlock::ToolResult(result) => self.matches_tool_result(result, tool_names),
176            other => self.target == OffloadTarget::Media && is_media_block(other),
177        }
178    }
179
180    /// Whether a message holds anything this target covers.
181    pub(crate) fn matches_message(&self, message: &Message, tool_names: &HashMap<String, String>) -> bool {
182        self.matches_all()
183            || message
184                .content
185                .iter()
186                .any(|block| self.matches_block(block, message, tool_names))
187    }
188
189    fn matches_text(&self, message: &Message) -> bool {
190        match self.target {
191            OffloadTarget::AssistantText => message.role == Role::Assistant,
192            OffloadTarget::UserText => message.role == Role::User,
193            _ => false,
194        }
195    }
196
197    fn matches_tool_result(&self, block: &ToolResultBlock, tool_names: &HashMap<String, String>) -> bool {
198        match self.target {
199            OffloadTarget::ToolResults => return block.status == ToolResultStatus::Success,
200            OffloadTarget::ToolResultErrors => return block.status == ToolResultStatus::Error,
201            OffloadTarget::Tools(_) => {}
202            _ => return false,
203        }
204        let Some(name) = tool_names.get(&block.tool_use_id).filter(|name| !name.is_empty()) else {
205            return false;
206        };
207        self.matches_tool(name)
208    }
209
210    /// Whether a tool list target covers the tool with this name; any other target covers none
211    /// (`matchesTool`).
212    pub(crate) fn matches_tool(&self, tool_name: &str) -> bool {
213        if let Some(include) = &self.include {
214            return include.contains(tool_name);
215        }
216        self.exclude
217            .as_ref()
218            .is_some_and(|exclude| !exclude.contains(tool_name))
219    }
220}
221
222/// A tool list's include and exclude sets. Entries may be prefixed with `tool::`; an extra leading
223/// `!` excludes. A list with includes keeps the includes minus the excludes.
224fn resolve_tool_filter(entries: &[String]) -> (Option<HashSet<String>>, Option<HashSet<String>>) {
225    let mut includes = Vec::new();
226    let mut excludes = HashSet::new();
227    for entry in entries {
228        let (excluded, name) = match entry.strip_prefix('!') {
229            Some(name) => (true, name),
230            None => (false, entry.as_str()),
231        };
232        let tool_name = name.strip_prefix(TOOL_PREFIX).unwrap_or(name).to_owned();
233        if excluded {
234            excludes.insert(tool_name);
235        } else {
236            includes.push(tool_name);
237        }
238    }
239    if !includes.is_empty() {
240        let include = includes.into_iter().filter(|name| !excludes.contains(name)).collect();
241        return (Some(include), None);
242    }
243    if !excludes.is_empty() {
244        return (None, Some(excludes));
245    }
246    (None, None)
247}