Skip to main content

strands/injection/
mod.rs

1//! Context injection: the configuration shared by the
2//! [`ContextInjector`](crate::vended_plugins::context_injector::ContextInjector) plugin and the
3//! `MemoryManager`'s injection, and the crate-internal engine that folds text into the latest
4//! user message before a model call.
5
6use std::fmt;
7use std::future::Future;
8use std::sync::Arc;
9
10use futures::future::BoxFuture;
11
12use crate::agent::ToolAgent;
13use crate::error::BoxError;
14use crate::middleware::{InvokeModelContext, InvokeModelStage, Middleware};
15use crate::state_store::StateStore;
16use crate::types::{ContentBlock, Message, Role};
17
18pub(crate) mod xml;
19
20#[cfg(test)]
21pub(crate) mod tests;
22
23type TriggerFn = Arc<dyn Fn(&InjectionContext) -> Result<bool, BoxError> + Send + Sync>;
24type RenderFn = Arc<dyn Fn(InjectionContext) -> BoxFuture<'static, Result<Option<String>, BoxError>> + Send + Sync>;
25
26/// When injection runs before a model call (`InjectionTrigger`, plus the predicate form of
27/// `InjectionConfig.trigger`).
28///
29/// ```
30/// use strands::injection::InjectionTrigger;
31///
32/// let every_other = InjectionTrigger::predicate(|context| Ok(context.messages.len() % 2 == 1));
33/// assert!(matches!(InjectionTrigger::default(), InjectionTrigger::UserTurn));
34/// # let _ = every_other;
35/// ```
36#[derive(Clone, Default)]
37#[non_exhaustive]
38pub enum InjectionTrigger {
39    /// Only when the latest message is a fresh user ask: a user message with no tool result
40    /// (`'userTurn'`, the default).
41    #[default]
42    UserTurn,
43    /// Before every model call, including tool-result turns (`'everyTurn'`).
44    EveryTurn,
45    /// A predicate over the [`InjectionContext`]. One that returns an error fails open: injection
46    /// is skipped and the model call proceeds.
47    Predicate(TriggerFn),
48}
49
50impl InjectionTrigger {
51    /// A predicate trigger.
52    pub fn predicate(predicate: impl Fn(&InjectionContext) -> Result<bool, BoxError> + Send + Sync + 'static) -> Self {
53        Self::Predicate(Arc::new(predicate))
54    }
55
56    /// Whether to inject for this context; a failing predicate logs and skips.
57    pub(crate) fn fires(&self, context: &InjectionContext) -> bool {
58        match self {
59            Self::UserTurn => is_user_turn(&context.messages),
60            Self::EveryTurn => true,
61            Self::Predicate(predicate) => predicate(context).unwrap_or_else(|error| {
62                tracing::warn!("reason=<{error}> | injection trigger threw; skipping injection");
63                false
64            }),
65        }
66    }
67}
68
69impl fmt::Debug for InjectionTrigger {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            Self::UserTurn => f.write_str("UserTurn"),
73            Self::EveryTurn => f.write_str("EveryTurn"),
74            Self::Predicate(_) => f.write_str("Predicate(..)"),
75        }
76    }
77}
78
79/// What an injection consumer receives on each model call (`InjectionContext`): passed to the
80/// render callback and to a predicate trigger.
81#[derive(Clone)]
82#[non_exhaustive]
83pub struct InjectionContext {
84    /// The conversation this model call sends.
85    pub messages: Vec<Message>,
86    /// The agent's app state, shared with hooks and tools.
87    pub app_state: StateStore,
88    /// The agent the injection is attached to.
89    pub agent: ToolAgent,
90}
91
92impl InjectionContext {
93    /// The context for a model call that sends `messages` on `agent`, with the agent's app state.
94    /// [`testing::injection_context`](crate::testing::injection_context) builds one on a mock
95    /// agent, to test a render callback or a predicate on its own.
96    #[must_use]
97    pub fn new(messages: Vec<Message>, agent: ToolAgent) -> Self {
98        Self {
99            messages,
100            app_state: agent.app_state().clone(),
101            agent,
102        }
103    }
104
105    pub(crate) fn from_model_context(context: &InvokeModelContext) -> Self {
106        Self {
107            messages: context.messages.clone(),
108            app_state: context.agent.app_state().clone(),
109            agent: context.agent.clone(),
110        }
111    }
112}
113
114impl fmt::Debug for InjectionContext {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.debug_struct("InjectionContext")
117            .field("messages", &self.messages.len())
118            .finish_non_exhaustive()
119    }
120}
121
122/// Configuration common to every injection consumer: when to inject (`InjectionConfig`).
123#[derive(Debug, Clone, Default, bon::Builder)]
124pub struct InjectionConfig {
125    /// When injection runs. Defaults to [`InjectionTrigger::UserTurn`].
126    pub trigger: Option<InjectionTrigger>,
127}
128
129/// The callback that renders the text to inject (`renderContent`): `Ok(None)` or blank text skips
130/// the call, and an error fails open (logged, injection skipped).
131#[derive(Clone)]
132pub struct RenderContent(RenderFn);
133
134impl RenderContent {
135    /// Wraps an async render callback.
136    pub fn new<F, Fut>(render: F) -> Self
137    where
138        F: Fn(InjectionContext) -> Fut + Send + Sync + 'static,
139        Fut: Future<Output = Result<Option<String>, BoxError>> + Send + 'static,
140    {
141        Self(Arc::new(move |context| Box::pin(render(context))))
142    }
143
144    /// Renders the text for a context; an error is logged and skips the injection.
145    pub(crate) async fn render(&self, context: InjectionContext) -> Option<String> {
146        match (self.0)(context).await {
147            Ok(text) => text,
148            Err(error) => {
149                tracing::warn!("reason=<{error}> | injection renderContent threw; skipping injection");
150                None
151            }
152        }
153    }
154}
155
156impl fmt::Debug for RenderContent {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        f.write_str("RenderContent(..)")
159    }
160}
161
162/// Whether the latest message is a fresh user ask: a user message with no tool result.
163pub(crate) fn is_user_turn(messages: &[Message]) -> bool {
164    messages.last().is_some_and(|last| {
165        last.role == Role::User
166            && !last
167                .content
168                .iter()
169                .any(|block| matches!(block, ContentBlock::ToolResult(_)))
170    })
171}
172
173/// Appends `text` to the most recent user message as a text block,
174/// keeping its tracking id and metadata. Returns the messages and how many trailing blocks of the
175/// last message are per-call content: 1 when the fold landed on the last message, otherwise 0
176/// (also when there is no user message, in which case the messages are returned unchanged).
177pub(crate) fn fold_into_last_user_message(mut messages: Vec<Message>, text: &str) -> (Vec<Message>, usize) {
178    let Some(index) = messages.iter().rposition(|message| message.role == Role::User) else {
179        return (messages, 0);
180    };
181    let target = &mut messages[index];
182    // Some providers concatenate adjacent text blocks, which would run this onto the user's words.
183    let separator = if !target.content.is_empty() && !text.starts_with('\n') {
184        "\n\n"
185    } else {
186        ""
187    };
188    target.content.push(ContentBlock::text(format!("{separator}{text}")));
189    let appended = usize::from(index == messages.len() - 1);
190    (messages, appended)
191}
192
193/// Folds the rendered text into the latest user message of this call only (the input phase of
194/// `injection_middleware`). Anything that skips returns the context unchanged.
195pub(crate) async fn inject<F, Fut>(
196    mut context: InvokeModelContext,
197    trigger: &InjectionTrigger,
198    render: F,
199) -> InvokeModelContext
200where
201    F: FnOnce(InjectionContext) -> Fut,
202    Fut: Future<Output = Option<String>>,
203{
204    let injection_context = InjectionContext::from_model_context(&context);
205    if !trigger.fires(&injection_context) {
206        return context;
207    }
208    let Some(text) = render(injection_context).await else {
209        return context;
210    };
211    if text.trim().is_empty() {
212        return context;
213    }
214    let (messages, appended) = fold_into_last_user_message(std::mem::take(&mut context.messages), &text);
215    context.messages = messages;
216    // Several producers may append on one call; the cache point precedes all of it.
217    context.dynamic_trailing_blocks = Some(context.dynamic_trailing_blocks.unwrap_or(0) + appended);
218    context
219}
220
221/// The `InvokeModelStage` input handler that folds rendered text into the model input, ephemerally.
222pub(crate) fn injection_middleware<F, Fut>(trigger: InjectionTrigger, render: F) -> Middleware<InvokeModelStage>
223where
224    F: Fn(InjectionContext) -> Fut + Send + Sync + 'static,
225    Fut: Future<Output = Option<String>> + Send + 'static,
226{
227    let render = Arc::new(render);
228    let trigger = Arc::new(trigger);
229    InvokeModelStage::input(move |context| {
230        let render = render.clone();
231        let trigger = trigger.clone();
232        async move { Ok(inject(context, &trigger, |injection| render(injection)).await) }
233    })
234}