Skip to main content

agent_base/engine/
middleware.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4use serde_json::Value;
5
6use crate::engine::executor::ParseOutcome;
7use crate::types::{Action, AgentResult, ChatMessage, FinishReason, SessionId, UserEvent};
8
9#[derive(Clone)]
10pub struct UserMessageCtx {
11    pub session_id: SessionId,
12    pub user_input: String,
13}
14
15pub struct PreLlmCtx {
16    pub session_id: SessionId,
17    pub messages: Vec<ChatMessage>,
18    pub tools: Vec<Value>,
19    /// Unified emit function: sends [`UserEvent`] to both the renderer (real-time)
20    /// and the event bus (persistence).  Set by the react loop; middleware calls
21    /// [`emit()`](Self::emit) which delegates to this closure.
22    ///
23    /// The closure captures the renderer callback and the event bus, so middleware
24    /// never needs to know about broadcast channels or drain mechanics.
25    pub emit_fn: Option<Box<dyn Fn(UserEvent) + Send + Sync>>,
26    /// Current turn count (1-indexed).
27    pub turn_count: u32,
28    /// Maximum turns allowed for this run.
29    pub max_turns: u32,
30}
31
32impl PreLlmCtx {
33    /// Emit a [`UserEvent`] to both the renderer and the event bus.
34    ///
35    /// This is the single entry point for middleware to send events.  The event
36    /// is delivered to the renderer callback (real-time display) and to the
37    /// event bus (persistence, event_log, checkpoint) in one call.
38    ///
39    /// Does nothing if the emit function was not set (e.g. in tests).
40    /// Panics inside the emit function are caught and logged as warnings.
41    pub fn emit(&self, event: UserEvent) {
42        if let Some(ref f) = self.emit_fn
43            && let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
44                f(event);
45            }))
46        {
47            tracing::warn!("emit failed: {:?}", e);
48        }
49    }
50}
51
52#[derive(Clone)]
53pub struct PostLlmCtx {
54    pub session_id: SessionId,
55    pub full_text: String,
56    /// The action backend's four-state verdict for this turn (M3 seam). The
57    /// turn's action list rides inside [`ParseOutcome::Actions`]; middleware
58    /// discards pending work with [`PostLlmCtx::demote_to_text`]. Tool calls
59    /// and CodeAct cells both surface here as [`Action`]s — no protocol shape.
60    pub parse: ParseOutcome,
61    pub available_tools: Vec<String>,
62    pub turn_count: u32,
63    pub total_actions: usize,
64    /// Number of tool-enforcement nudges issued in the current turn.
65    /// Read from session; middleware may increment this to track nudge attempts.
66    pub nudge_count: usize,
67    /// Number of tool calls already executed in the current turn.
68    /// Used by `TurnToolLimitMiddleware` to enforce per-turn tool call limits.
69    pub turn_actions: usize,
70    pub skip_push: bool,
71    pub follow_up_message: Option<String>,
72    /// Semantic finish reason from the LLM (Stop / ToolUse / Truncated / Other).
73    /// Middleware can inspect this to implement custom continuation logic
74    /// (e.g. auto-continue on truncation).
75    pub finish_reason: FinishReason,
76}
77
78impl PostLlmCtx {
79    /// The turn's pending actions (empty when the turn has none or was demoted).
80    pub fn actions(&self) -> &[Action] {
81        match &self.parse {
82            ParseOutcome::Actions(actions) => actions,
83            _ => &[],
84        }
85    }
86
87    /// Mutable access to the pending actions (e.g. to drop selected ones).
88    pub fn actions_mut(&mut self) -> Option<&mut Vec<Action>> {
89        match &mut self.parse {
90            ParseOutcome::Actions(actions) => Some(actions),
91            _ => None,
92        }
93    }
94
95    /// Discard the turn's pending actions and demote it to text-only. A
96    /// demoted turn dispatches exactly like [`ParseOutcome::Empty`] (nudge on
97    /// empty text, finish-anomaly handling on text).
98    pub fn demote_to_text(&mut self) {
99        self.parse = ParseOutcome::Empty;
100    }
101
102    /// Whether the backend saw action intent this turn — true for
103    /// [`ParseOutcome::Actions`] and [`ParseOutcome::Incomplete`] (a call the
104    /// truncation guard left with zero entries still counts as intent).
105    pub fn has_action_intent(&self) -> bool {
106        self.parse.has_action_intent()
107    }
108}
109
110#[async_trait]
111pub trait Middleware: Send + Sync {
112    async fn on_user_message(&self, _ctx: &mut UserMessageCtx) -> AgentResult<()> {
113        Ok(())
114    }
115
116    async fn on_pre_llm(&self, _ctx: &mut PreLlmCtx) -> AgentResult<()> {
117        Ok(())
118    }
119
120    async fn on_post_llm(&self, _ctx: &mut PostLlmCtx) -> AgentResult<()> {
121        Ok(())
122    }
123}
124
125pub(crate) type MiddlewareRef = Arc<dyn Middleware>;
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::types::SessionId;
131
132    #[test]
133    fn test_post_llm_ctx_new_fields_defaults() {
134        let ctx = PostLlmCtx {
135            session_id: SessionId {
136                id: 1,
137                external_id: None,
138            },
139            full_text: "test".to_string(),
140            parse: ParseOutcome::Empty,
141            available_tools: vec![],
142            turn_count: 0,
143            total_actions: 0,
144            nudge_count: 0,
145            turn_actions: 0,
146            skip_push: false,
147            follow_up_message: None,
148            finish_reason: FinishReason::Stop,
149        };
150        assert!(ctx.available_tools.is_empty());
151        assert_eq!(ctx.turn_count, 0);
152        assert_eq!(ctx.total_actions, 0);
153        assert!(!ctx.skip_push);
154        assert!(ctx.follow_up_message.is_none());
155        assert_eq!(ctx.finish_reason, FinishReason::Stop);
156    }
157
158    #[test]
159    fn test_post_llm_ctx_skip_push_follow_up_set() {
160        let ctx = PostLlmCtx {
161            session_id: SessionId {
162                id: 2,
163                external_id: None,
164            },
165            full_text: "I will execute...".to_string(),
166            parse: ParseOutcome::Empty,
167            available_tools: vec!["echo".to_string()],
168            turn_count: 1,
169            total_actions: 0,
170            nudge_count: 0,
171            turn_actions: 0,
172            skip_push: true,
173            follow_up_message: Some("Please call tools now.".to_string()),
174            finish_reason: FinishReason::Stop,
175        };
176        assert!(ctx.skip_push);
177        assert_eq!(
178            ctx.follow_up_message,
179            Some("Please call tools now.".to_string())
180        );
181        assert_eq!(ctx.available_tools, vec!["echo".to_string()]);
182        assert_eq!(ctx.total_actions, 0);
183    }
184
185    #[test]
186    fn test_post_llm_ctx_clone_preserves_new_fields() {
187        let ctx = PostLlmCtx {
188            session_id: SessionId {
189                id: 3,
190                external_id: None,
191            },
192            full_text: "hello".to_string(),
193            parse: ParseOutcome::Empty,
194            available_tools: vec!["add".to_string(), "subtract".to_string()],
195            turn_count: 5,
196            total_actions: 3,
197            nudge_count: 0,
198            turn_actions: 2,
199            skip_push: true,
200            follow_up_message: Some("nudge".to_string()),
201            finish_reason: FinishReason::Truncated {
202                reason: Some("max_tokens".into()),
203            },
204        };
205        let cloned = ctx.clone();
206        assert_eq!(cloned.available_tools, vec!["add", "subtract"]);
207        assert_eq!(cloned.turn_count, 5);
208        assert_eq!(cloned.total_actions, 3);
209        assert_eq!(cloned.turn_actions, 2);
210        assert!(cloned.skip_push);
211        assert_eq!(cloned.follow_up_message, Some("nudge".to_string()));
212        assert!(cloned.finish_reason.is_truncated());
213    }
214}