strands/context_manager/
presets.rs1use std::fmt;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use super::methods::truncate::TruncateConfig;
11use super::strategies::deferred_tool_loading::{DeferConditions, DeferTarget};
12use super::strategies::offload::{ConditionValue, Offload, OffloadConditions, OffloadTarget, SummarizeConfig};
13use super::types::ContextStrategy;
14use crate::error::{Error, Result};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum StrategyPresetName {
20 ProactiveSummarization,
23 LargeToolOffloading,
25 OverflowProtection,
27 StaleToolCleanup,
29 DeferredToolLoading,
37}
38
39pub(crate) const STRATEGY_PRESET_NAMES: [StrategyPresetName; 5] = [
41 StrategyPresetName::ProactiveSummarization,
42 StrategyPresetName::LargeToolOffloading,
43 StrategyPresetName::OverflowProtection,
44 StrategyPresetName::StaleToolCleanup,
45 StrategyPresetName::DeferredToolLoading,
46];
47
48impl StrategyPresetName {
49 #[must_use]
51 pub fn as_str(self) -> &'static str {
52 match self {
53 Self::ProactiveSummarization => "proactiveSummarization",
54 Self::LargeToolOffloading => "largeToolOffloading",
55 Self::OverflowProtection => "overflowProtection",
56 Self::StaleToolCleanup => "staleToolCleanup",
57 Self::DeferredToolLoading => "deferredToolLoading",
58 }
59 }
60}
61
62impl fmt::Display for StrategyPresetName {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.write_str(self.as_str())
65 }
66}
67
68impl FromStr for StrategyPresetName {
69 type Err = Error;
70
71 fn from_str(name: &str) -> Result<Self> {
72 STRATEGY_PRESET_NAMES
73 .into_iter()
74 .find(|preset| preset.as_str() == name)
75 .ok_or_else(|| {
76 let valid: Vec<&str> = STRATEGY_PRESET_NAMES.iter().map(|preset| preset.as_str()).collect();
77 Error::other(format!(
78 "Unknown strategy preset: \"{name}\". Valid presets: {}",
79 valid.join(", ")
80 ))
81 })
82 }
83}
84
85#[derive(Clone)]
87#[non_exhaustive]
88pub enum StrategyEntry {
89 Strategy(Arc<dyn ContextStrategy>),
91 Preset(StrategyPresetName),
93}
94
95impl fmt::Debug for StrategyEntry {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 match self {
98 Self::Strategy(strategy) => f.debug_tuple("Strategy").field(&strategy.name()).finish(),
99 Self::Preset(preset) => f.debug_tuple("Preset").field(preset).finish(),
100 }
101 }
102}
103
104impl From<StrategyPresetName> for StrategyEntry {
105 fn from(preset: StrategyPresetName) -> Self {
106 Self::Preset(preset)
107 }
108}
109
110impl From<Arc<dyn ContextStrategy>> for StrategyEntry {
111 fn from(strategy: Arc<dyn ContextStrategy>) -> Self {
112 Self::Strategy(strategy)
113 }
114}
115
116impl<S: ContextStrategy> From<S> for StrategyEntry {
117 fn from(strategy: S) -> Self {
118 Self::Strategy(Arc::new(strategy))
119 }
120}
121
122fn conditions(
123 context_utilization: Option<&str>,
124 block_threshold: Option<u64>,
125 preserve_recent: Option<ConditionValue>,
126) -> OffloadConditions {
127 OffloadConditions {
128 context_utilization: context_utilization.map(ConditionValue::from),
129 block_threshold: block_threshold.map(ConditionValue::from),
130 preserve_recent,
131 }
132}
133
134fn preview(tokens: f64) -> TruncateConfig {
135 TruncateConfig {
136 preview_tokens: Some(tokens),
137 ..TruncateConfig::default()
138 }
139}
140
141pub(crate) fn resolve_preset(name: StrategyPresetName) -> Result<Vec<Arc<dyn ContextStrategy>>> {
143 let strategy: Arc<dyn ContextStrategy> = match name {
144 StrategyPresetName::ProactiveSummarization => Arc::new(
145 Offload::summarize(OffloadTarget::All, SummarizeConfig::default())?.when(conditions(
146 Some("70%"),
147 None,
148 Some("70%".into()),
149 ))?,
150 ),
151 StrategyPresetName::LargeToolOffloading => Arc::new(
152 Offload::truncate(OffloadTarget::ToolResults, preview(1000.0))?.when(conditions(None, Some(2500), None))?,
153 ),
154 StrategyPresetName::OverflowProtection => {
155 Arc::new(Offload::drop(OffloadTarget::All)?.when(conditions(Some("100%"), None, Some(4.into())))?)
156 }
157 StrategyPresetName::StaleToolCleanup => {
158 Arc::new(Offload::drop(OffloadTarget::ToolResults)?.when(conditions(None, None, Some(5.into())))?)
159 }
160 StrategyPresetName::DeferredToolLoading => {
161 Arc::new(Offload::defer(DeferTarget::ToolSpecs)?.when(DeferConditions {
162 tool_count: Some(20.into()),
163 ..DeferConditions::default()
164 })?)
165 }
166 };
167 Ok(vec![strategy])
168}
169
170pub(crate) fn resolve_strategies(entries: &[StrategyEntry]) -> Result<Vec<Arc<dyn ContextStrategy>>> {
172 let mut strategies = Vec::new();
173 for entry in entries {
174 match entry {
175 StrategyEntry::Strategy(strategy) => strategies.push(strategy.clone()),
176 StrategyEntry::Preset(preset) => strategies.extend(resolve_preset(*preset)?),
177 }
178 }
179 Ok(strategies)
180}
181
182#[cfg(test)]
183#[path = "presets/tests.rs"]
184mod tests;