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 pub emit_fn: Option<Box<dyn Fn(UserEvent) + Send + Sync>>,
26 pub turn_count: u32,
28 pub max_turns: u32,
30}
31
32impl PreLlmCtx {
33 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 pub parse: ParseOutcome,
61 pub available_tools: Vec<String>,
62 pub turn_count: u32,
63 pub total_actions: usize,
64 pub nudge_count: usize,
67 pub turn_actions: usize,
70 pub skip_push: bool,
71 pub follow_up_message: Option<String>,
72 pub finish_reason: FinishReason,
76}
77
78impl PostLlmCtx {
79 pub fn actions(&self) -> &[Action] {
81 match &self.parse {
82 ParseOutcome::Actions(actions) => actions,
83 _ => &[],
84 }
85 }
86
87 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 pub fn demote_to_text(&mut self) {
99 self.parse = ParseOutcome::Empty;
100 }
101
102 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}