Skip to main content

strands/vended_plugins/context_injector/
mod.rs

1//! The context-injection plugin: [`ContextInjector`] writes just-in-time text into the latest
2//! user message before each model call, as an [`InjectedBlock`] that stays in the conversation.
3//!
4//! ```
5//! use strands::Agent;
6//! use strands::testing::MockModel;
7//! use strands::vended_plugins::context_injector::{ContextInjector, ContextInjectorConfig};
8//!
9//! # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
10//! let injector = ContextInjector::new(ContextInjectorConfig::new(|_context| async {
11//!     Ok(Some("<now>2026-11-11</now>".to_owned()))
12//! }));
13//! let mut agent = Agent::builder()
14//!     .model(MockModel::new().with_turn("ok"))
15//!     .plugins([injector])
16//!     .printer(false)
17//!     .build()?;
18//! agent.invoke("What day is it?").await?;
19//! assert_eq!(agent.messages()[0].content.len(), 2);
20//! # Ok::<(), strands::Error>(())
21//! # }).unwrap();
22//! ```
23
24use std::fmt;
25use std::future::Future;
26use std::sync::{Arc, Mutex, PoisonError};
27
28use async_trait::async_trait;
29
30use crate::agent::LocalAgent;
31use crate::error::{BoxError, Result};
32use crate::hooks::{
33    AfterInvocationEvent, AfterModelCallEvent, BeforeModelCallEvent, HookCallbackOptions, HookOrder, ModelMessageEvent,
34};
35use crate::injection::RenderContent;
36pub use crate::injection::{InjectionContext, InjectionTrigger};
37use crate::middleware::{InvokeModelContext, InvokeModelStage};
38use crate::plugins::Plugin;
39use crate::types::{ContentBlock, InjectedBlock, Message, Role};
40
41#[cfg(test)]
42mod tests;
43
44const DEFAULT_NAME: &str = "strands:context-injector";
45
46/// Configuration for the [`ContextInjector`] plugin (`ContextInjectorConfig`).
47///
48/// The render callback is required, so the config has no `Default`; start from
49/// [`ContextInjectorConfig::new`].
50#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct ContextInjectorConfig {
53    /// Plugin name, for logging and duplicate detection. Defaults to `strands:context-injector`.
54    /// It is stored with every block the injector writes and keeps a retried call from writing
55    /// again, also after a session restore, so keep it stable and give each injector its own.
56    pub name: Option<String>,
57    /// When to inject. Defaults to [`InjectionTrigger::UserTurn`].
58    pub trigger: Option<InjectionTrigger>,
59    /// Renders the text to write into the latest user message; `Ok(None)` or blank text skips.
60    /// The text reaches the model verbatim, so escape any attacker-influenced fields yourself.
61    /// Called at most once per user message: a retry, a forced structured output call or a resume
62    /// sends the text it returned the first time. An error fails open (logged, injection skipped).
63    pub render_content: RenderContent,
64}
65
66impl ContextInjectorConfig {
67    /// A config with the render callback and the default name and trigger.
68    pub fn new<F, Fut>(render_content: F) -> Self
69    where
70        F: Fn(InjectionContext) -> Fut + Send + Sync + 'static,
71        Fut: Future<Output = std::result::Result<Option<String>, BoxError>> + Send + 'static,
72    {
73        Self {
74            name: None,
75            trigger: None,
76            render_content: RenderContent::new(render_content),
77        }
78    }
79
80    /// Sets the plugin name.
81    #[must_use]
82    pub fn with_name(mut self, name: impl Into<String>) -> Self {
83        self.name = Some(name.into());
84        self
85    }
86
87    /// Sets the trigger.
88    #[must_use]
89    pub fn with_trigger(mut self, trigger: InjectionTrigger) -> Self {
90        self.trigger = Some(trigger);
91        self
92    }
93}
94
95/// A block written into this call's input that the conversation does not hold yet.
96struct PendingWrite {
97    tracking_id: String,
98    position: usize,
99    /// Blocks other injectors wrote ahead of this one at `position`, so the conversation keeps
100    /// the order the model input had.
101    rank: usize,
102    block: InjectedBlock,
103}
104
105/// The number of injected blocks that directly follow `start`.
106fn injected_run(content: &[ContentBlock], start: usize) -> usize {
107    content[start..]
108        .iter()
109        .take_while(|block| matches!(block, ContentBlock::Injected(_)))
110        .count()
111}
112
113struct Inner {
114    name: String,
115    trigger: InjectionTrigger,
116    render_content: RenderContent,
117    pending: Mutex<Vec<PendingWrite>>,
118}
119
120impl Inner {
121    fn wrote(&self, block: &ContentBlock) -> bool {
122        matches!(block, ContentBlock::Injected(injected) if injected.source == self.name)
123    }
124
125    fn has_pending(&self, tracking_id: &str) -> bool {
126        self.pending
127            .lock()
128            .unwrap_or_else(PoisonError::into_inner)
129            .iter()
130            .any(|write| write.tracking_id == tracking_id)
131    }
132
133    /// Writes the blocks of earlier model inputs into the conversation, each into the message it
134    /// was written for, at the position it had in that input.
135    fn apply(&self, messages: &mut [Message]) {
136        let writes = std::mem::take(&mut *self.pending.lock().unwrap_or_else(PoisonError::into_inner));
137        for write in writes {
138            let Some(message) = messages
139                .iter_mut()
140                .find(|message| message.tracking_id() == write.tracking_id)
141            else {
142                continue;
143            };
144            if message.content.iter().any(|block| self.wrote(block)) {
145                continue;
146            }
147            let start = write.position.min(message.content.len());
148            let at = start + write.rank.min(injected_run(&message.content, start));
149            message.content.insert(at, ContentBlock::Injected(write.block));
150        }
151    }
152
153    /// Writes the rendered text into the latest user message of this call (`_inject`). A message
154    /// gets at most one block from this injector; anything that skips leaves the input unchanged.
155    async fn inject(&self, mut context: InvokeModelContext) -> InvokeModelContext {
156        let Some(latest) = context.agent.messages().last() else {
157            return context;
158        };
159        if latest.role != Role::User || latest.content.iter().any(|block| self.wrote(block)) {
160            return context;
161        }
162        let tracking_id = latest.tracking_id().to_owned();
163        let position = latest.content.len();
164        if self.has_pending(&tracking_id) {
165            return context;
166        }
167        // Another middleware may have replaced this call's messages.
168        let Some(index) = context
169            .messages
170            .iter()
171            .position(|message| message.tracking_id() == tracking_id)
172        else {
173            return context;
174        };
175        let injection_context = InjectionContext::from_model_context(&context);
176        if !self.trigger.fires(&injection_context) {
177            return context;
178        }
179        let Some(text) = self.render_content.render(injection_context).await else {
180            return context;
181        };
182        if text.trim().is_empty() {
183            return context;
184        }
185        let block = InjectedBlock::new(text, self.name.clone());
186        let target = &mut context.messages[index];
187        // After the stored content, so text other middleware adds for this call only stays last.
188        let start = position.min(target.content.len());
189        let rank = injected_run(&target.content, start);
190        target
191            .content
192            .insert(start + rank, ContentBlock::Injected(block.clone()));
193        self.pending
194            .lock()
195            .unwrap_or_else(PoisonError::into_inner)
196            .push(PendingWrite {
197                tracking_id,
198                position,
199                rank,
200                block,
201            });
202        context
203    }
204}
205
206/// Injects just-in-time context into the latest user message before each model call
207/// (`ContextInjector`).
208///
209/// Before each model call the plugin asks its render callback for text, gated by the trigger, and
210/// writes it into the latest user message as an [`InjectedBlock`] named after the plugin. The
211/// block stays in the conversation and the session. A model that takes temporary messages
212/// receives each block as a system message it reads until the next user message, so the stored
213/// history is sent unchanged on every call; every other model receives only the latest user
214/// message's blocks, as text.
215///
216/// The block reaches the model input at once and the conversation when the model call ends
217/// (before `ModelMessageEvent` hooks run); one injector serves one agent. Several injectors may
218/// be registered; each contributes its text in plugin registration order.
219pub struct ContextInjector {
220    inner: Arc<Inner>,
221}
222
223impl ContextInjector {
224    /// Creates the plugin.
225    #[must_use]
226    pub fn new(config: ContextInjectorConfig) -> Self {
227        Self {
228            inner: Arc::new(Inner {
229                name: config.name.unwrap_or_else(|| DEFAULT_NAME.to_owned()),
230                trigger: config.trigger.unwrap_or_default(),
231                render_content: config.render_content,
232                pending: Mutex::new(Vec::new()),
233            }),
234        }
235    }
236}
237
238impl fmt::Debug for ContextInjector {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        f.debug_struct("ContextInjector")
241            .field("name", &self.inner.name)
242            .field("trigger", &self.inner.trigger)
243            .finish_non_exhaustive()
244    }
245}
246
247#[async_trait]
248impl Plugin for ContextInjector {
249    fn name(&self) -> &str {
250        &self.inner.name
251    }
252
253    async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
254        let inner = self.inner.clone();
255        agent.add_middleware(InvokeModelStage::input(move |context| {
256            let inner = inner.clone();
257            async move { Ok(inner.inject(context).await) }
258        }));
259        let first = HookCallbackOptions {
260            order: HookOrder::SDK_FIRST,
261        };
262        let inner = self.inner.clone();
263        agent.add_hook_with(
264            move |event: &mut BeforeModelCallEvent<'_>| inner.apply(event.agent_mut().messages_mut()),
265            first,
266        );
267        let inner = self.inner.clone();
268        agent.add_hook_with(
269            move |event: &mut ModelMessageEvent<'_>| inner.apply(event.agent_mut().messages_mut()),
270            first,
271        );
272        let inner = self.inner.clone();
273        agent.add_hook_with(
274            move |event: &mut AfterModelCallEvent<'_>| inner.apply(event.agent_mut().messages_mut()),
275            first,
276        );
277        let inner = self.inner.clone();
278        agent.add_hook_with(
279            move |event: &mut AfterInvocationEvent<'_>| inner.apply(event.agent_mut().messages_mut()),
280            first,
281        );
282        Ok(())
283    }
284}