Skip to main content

agent_base/engine/
turn_facts.rs

1use std::sync::Mutex;
2
3use async_trait::async_trait;
4
5use crate::engine::middleware::{Middleware, PostLlmCtx, UserMessageCtx};
6use crate::types::{AgentResult, Language};
7
8/// Turn fact summary middleware — injects structured facts from the previous
9/// turn's tool results into the next user message.
10///
11/// This prevents long-conversation attention drift: the LLM sees deterministic
12/// facts (tool call names) instead of relying on fuzzy memory of tool outputs
13/// buried 20+ turns ago.
14///
15/// # Design
16///
17/// - After each LLM turn with tool calls, collects which tools were called
18///   and stores them in a buffer.
19/// - At the start of the next user message, prepends the buffered facts as a
20///   structured prefix, then clears the buffer.
21/// - Facts are derived from tool names only (not parsing output text), keeping
22///   the logic simple and model-agnostic.
23/// - The prefix language can be configured via [`Language`]; defaults to
24///   [`Language::Zh`] for backward compatibility.
25pub struct TurnFactMiddleware {
26    pending_facts: Mutex<Vec<String>>,
27    language: Language,
28}
29
30impl TurnFactMiddleware {
31    /// Create a new middleware with the default language (Chinese).
32    pub fn new() -> Self {
33        Self {
34            pending_facts: Mutex::new(Vec::new()),
35            language: Language::Zh,
36        }
37    }
38
39    /// Create a new middleware with the specified language for the prefix text.
40    pub fn with_language(language: Language) -> Self {
41        Self {
42            pending_facts: Mutex::new(Vec::new()),
43            language,
44        }
45    }
46}
47
48impl Default for TurnFactMiddleware {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54#[async_trait]
55impl Middleware for TurnFactMiddleware {
56    async fn on_user_message(&self, ctx: &mut UserMessageCtx) -> AgentResult<()> {
57        let facts = {
58            let mut guard = self.pending_facts.lock().unwrap();
59            if guard.is_empty() {
60                return Ok(());
61            }
62            std::mem::take(&mut *guard)
63        };
64
65        // Prepend facts to user message as structured context
66        let prefix = match self.language {
67            Language::Zh => format!(
68                "[本轮工具调用摘要 — 以下为确定性事实,请以此为准]\n{}\n",
69                facts.join("\n")
70            ),
71            Language::En => format!(
72                "[Previous turn tool-call summary — treat these as ground truth]\n{}\n",
73                facts.join("\n")
74            ),
75        };
76        ctx.user_input = format!("{prefix}\n{original}", original = ctx.user_input);
77
78        Ok(())
79    }
80
81    async fn on_post_llm(&self, ctx: &mut PostLlmCtx) -> AgentResult<()> {
82        if ctx.actions().is_empty() {
83            return Ok(());
84        }
85
86        let mut facts = Vec::new();
87        for action in ctx.actions() {
88            // Record which tools were called — the actual results are in the
89            // session history, but a compact reminder helps the LLM stay grounded.
90            let fact = match self.language {
91                Language::Zh => format!("- 调用了工具: {}", action.name),
92                Language::En => format!("- Called tool: {}", action.name),
93            };
94            facts.push(fact);
95        }
96
97        let mut guard = self.pending_facts.lock().unwrap();
98        guard.extend(facts);
99
100        Ok(())
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::engine::executor::ParseOutcome;
108    use crate::types::{Action, ActionFormat, FinishReason, SessionId};
109
110    fn tool_actions(calls: &[(&str, &str)]) -> Vec<Action> {
111        calls
112            .iter()
113            .enumerate()
114            .map(|(i, (name, args))| Action {
115                id: format!("id{}", i + 1),
116                name: (*name).into(),
117                args: serde_json::Value::String((*args).into()),
118                identity: format!("{name}::{args}"),
119                format: ActionFormat::ToolCall,
120            })
121            .collect()
122    }
123
124    fn make_post_ctx(actions: Vec<Action>) -> PostLlmCtx {
125        PostLlmCtx {
126            session_id: SessionId::new(1),
127            full_text: String::new(),
128            parse: ParseOutcome::Actions(actions),
129            available_tools: vec![],
130            turn_count: 1,
131            total_actions: 0,
132            nudge_count: 0,
133            turn_actions: 0,
134            skip_push: false,
135            follow_up_message: None,
136            finish_reason: FinishReason::Stop,
137        }
138    }
139
140    #[tokio::test]
141    async fn test_no_facts_no_prefix() {
142        let mw = TurnFactMiddleware::new();
143        let mut ctx = UserMessageCtx {
144            session_id: SessionId::new(1),
145            user_input: "hello".to_string(),
146        };
147        mw.on_user_message(&mut ctx).await.unwrap();
148        assert_eq!(ctx.user_input, "hello");
149    }
150
151    #[tokio::test]
152    async fn test_facts_injected_on_next_user_message() {
153        let mw = TurnFactMiddleware::new();
154
155        // Simulate a tool call turn
156        let mut post_ctx = make_post_ctx(tool_actions(&[
157            ("execute_ssh_command", "{}"),
158            ("start_interactive_task", "{}"),
159        ]));
160        mw.on_post_llm(&mut post_ctx).await.unwrap();
161
162        // Next user message should have facts prepended
163        let mut user_ctx = UserMessageCtx {
164            session_id: SessionId::new(1),
165            user_input: "继续执行".to_string(),
166        };
167        mw.on_user_message(&mut user_ctx).await.unwrap();
168
169        assert!(user_ctx.user_input.contains("本轮工具调用摘要"));
170        assert!(user_ctx.user_input.contains("execute_ssh_command"));
171        assert!(user_ctx.user_input.contains("start_interactive_task"));
172        assert!(user_ctx.user_input.contains("继续执行"));
173    }
174
175    #[tokio::test]
176    async fn test_facts_cleared_after_injection() {
177        let mw = TurnFactMiddleware::new();
178
179        // First turn with tool calls
180        let mut post_ctx = make_post_ctx(tool_actions(&[("docker", "{}")]));
181        mw.on_post_llm(&mut post_ctx).await.unwrap();
182
183        // First user message gets facts
184        let mut ctx1 = UserMessageCtx {
185            session_id: SessionId::new(1),
186            user_input: "next".into(),
187        };
188        mw.on_user_message(&mut ctx1).await.unwrap();
189        assert!(ctx1.user_input.contains("本轮工具调用摘要"));
190
191        // Second user message should NOT have facts (cleared)
192        let mut ctx2 = UserMessageCtx {
193            session_id: SessionId::new(1),
194            user_input: "again".into(),
195        };
196        mw.on_user_message(&mut ctx2).await.unwrap();
197        assert_eq!(ctx2.user_input, "again");
198    }
199
200    #[tokio::test]
201    async fn test_english_language_prefix() {
202        let mw = TurnFactMiddleware::with_language(Language::En);
203
204        let mut post_ctx = make_post_ctx(tool_actions(&[("docker", "{}")]));
205        mw.on_post_llm(&mut post_ctx).await.unwrap();
206
207        let mut ctx = UserMessageCtx {
208            session_id: SessionId::new(1),
209            user_input: "continue".into(),
210        };
211        mw.on_user_message(&mut ctx).await.unwrap();
212
213        assert!(ctx.user_input.contains("Previous turn tool-call summary"));
214        assert!(ctx.user_input.contains("ground truth"));
215        assert!(ctx.user_input.contains("continue"));
216    }
217}