1use 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#[derive(Clone, Default)]
37#[non_exhaustive]
38pub enum InjectionTrigger {
39 #[default]
42 UserTurn,
43 EveryTurn,
45 Predicate(TriggerFn),
48}
49
50impl InjectionTrigger {
51 pub fn predicate(predicate: impl Fn(&InjectionContext) -> Result<bool, BoxError> + Send + Sync + 'static) -> Self {
53 Self::Predicate(Arc::new(predicate))
54 }
55
56 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#[derive(Clone)]
82#[non_exhaustive]
83pub struct InjectionContext {
84 pub messages: Vec<Message>,
86 pub app_state: StateStore,
88 pub agent: ToolAgent,
90}
91
92impl InjectionContext {
93 #[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#[derive(Debug, Clone, Default, bon::Builder)]
124pub struct InjectionConfig {
125 pub trigger: Option<InjectionTrigger>,
127}
128
129#[derive(Clone)]
132pub struct RenderContent(RenderFn);
133
134impl RenderContent {
135 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 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
162pub(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
173pub(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 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
193pub(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 context.dynamic_trailing_blocks = Some(context.dynamic_trailing_blocks.unwrap_or(0) + appended);
218 context
219}
220
221pub(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}