Skip to main content

agent_base/engine/
recovery.rs

1use std::collections::HashMap;
2use std::sync::Mutex;
3
4use crate::types::{AgentError, AgentResult, SessionId};
5
6/// Action taken by the runtime after a tool execution failure
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum ToolErrorAction {
9    /// Stop the current run with a failed outcome
10    Stop,
11    /// Feed the error back to the LLM and continue reasoning
12    Retry,
13    /// Feed the full error history back to the LLM and let it evaluate.
14    ///
15    /// Emitted by [`ConsecutiveFailureRecovery`] when the same tool fails
16    /// `max_consecutive_failures` times in a row. Gives the LLM one grace
17    /// round to read the full error stack and either switch strategy or
18    /// explain the failure to the user.
19    RetryWithHistory {
20        /// Collected error messages from the consecutive failure streak.
21        errors: Vec<String>,
22    },
23}
24
25/// Recovery strategy after a tool execution failure
26///
27/// Defaults to [`StopOnError`], following the lightweight kernel design of
28/// conservative defaults and strategy injection.
29/// Upper-layer agents can inject custom strategies such as [`RetryOnError`].
30pub trait ToolErrorRecovery: Send + Sync {
31    fn on_error(
32        &self,
33        _session_id: &SessionId,
34        _tool_names: &[String],
35        _error: &AgentError,
36    ) -> AgentResult<ToolErrorAction>;
37
38    /// Called when a tool executes successfully.
39    ///
40    /// Default no-op. Strategies that track consecutive failures (e.g.
41    /// [`ConsecutiveFailureRecovery`]) override this to reset that tool's counter so
42    /// the "consecutive" semantics hold: a success breaks the failure streak.
43    fn on_success(&self, _session_id: &SessionId, _tool_name: &str) {}
44}
45
46/// Default strategy: stop on tool failure.
47///
48/// This is the most conservative strategy. The kernel only reports the fact
49/// without making business recovery decisions for the upper layer.
50pub struct StopOnError;
51
52impl ToolErrorRecovery for StopOnError {
53    fn on_error(
54        &self,
55        _session_id: &SessionId,
56        _tool_names: &[String],
57        _error: &AgentError,
58    ) -> AgentResult<ToolErrorAction> {
59        Ok(ToolErrorAction::Stop)
60    }
61}
62
63/// Continue on tool failure, feeding the error back to the model
64///
65/// Suitable for scenarios where model self-healing is desired (e.g. code-agent, browser-agent).
66pub struct RetryOnError;
67
68impl ToolErrorRecovery for RetryOnError {
69    fn on_error(
70        &self,
71        _session_id: &SessionId,
72        _tool_names: &[String],
73        _error: &AgentError,
74    ) -> AgentResult<ToolErrorAction> {
75        Ok(ToolErrorAction::Retry)
76    }
77}
78
79/// Recovery strategy that tracks consecutive failures per tool and stops after a limit.
80///
81/// This prevents runaway retry loops where the model keeps calling the same failing
82/// tool (e.g., `execute_ssh_command` failing due to auth, but the model retries
83/// indefinitely). After `max_consecutive_failures` for the same tool name, the
84/// strategy switches from `Retry` to `Stop` with a summary message.
85///
86/// Failure counters are tracked per session and reset when a different tool
87/// succeeds or a new session starts.
88pub struct ConsecutiveFailureRecovery {
89    max_consecutive_failures: usize,
90    /// session_id -> (tool_name -> consecutive_failures)
91    failure_counts: Mutex<HashMap<u64, HashMap<String, usize>>>,
92    /// session_id -> (tool_name -> collected error messages for the current streak)
93    error_messages: Mutex<HashMap<u64, HashMap<String, Vec<String>>>>,
94    /// session_id -> (tool_name -> whether RetryWithHistory grace was already used)
95    grace_used: Mutex<HashMap<u64, HashMap<String, bool>>>,
96}
97
98impl ConsecutiveFailureRecovery {
99    pub fn new(max_consecutive_failures: usize) -> Self {
100        Self {
101            max_consecutive_failures,
102            failure_counts: Mutex::new(HashMap::new()),
103            error_messages: Mutex::new(HashMap::new()),
104            grace_used: Mutex::new(HashMap::new()),
105        }
106    }
107
108    /// Reset failure count, error messages, and grace flag for a specific tool in a session.
109    /// Call this when a tool succeeds to avoid false positives.
110    pub fn reset_failures(&self, session_id: &SessionId, tool_name: &str) {
111        if let Ok(mut counts) = self.failure_counts.lock()
112            && let Some(session_counts) = counts.get_mut(&session_id.id)
113        {
114            session_counts.remove(tool_name);
115        }
116        if let Ok(mut msgs) = self.error_messages.lock()
117            && let Some(session_msgs) = msgs.get_mut(&session_id.id)
118        {
119            session_msgs.remove(tool_name);
120        }
121        if let Ok(mut grace) = self.grace_used.lock()
122            && let Some(session_grace) = grace.get_mut(&session_id.id)
123        {
124            session_grace.remove(tool_name);
125        }
126    }
127
128    /// Reset all failure counts, error messages, and grace flags for a session.
129    /// Call this when a new turn starts.
130    pub fn reset_session(&self, session_id: &SessionId) {
131        if let Ok(mut counts) = self.failure_counts.lock() {
132            counts.remove(&session_id.id);
133        }
134        if let Ok(mut msgs) = self.error_messages.lock() {
135            msgs.remove(&session_id.id);
136        }
137        if let Ok(mut grace) = self.grace_used.lock() {
138            grace.remove(&session_id.id);
139        }
140    }
141}
142
143impl ToolErrorRecovery for ConsecutiveFailureRecovery {
144    fn on_error(
145        &self,
146        session_id: &SessionId,
147        tool_names: &[String],
148        error: &AgentError,
149    ) -> AgentResult<ToolErrorAction> {
150        let mut counts = self
151            .failure_counts
152            .lock()
153            .map_err(|e| AgentError::internal(format!("Failed to lock failure counts: {}", e)))?;
154        let mut msgs = self
155            .error_messages
156            .lock()
157            .map_err(|e| AgentError::internal(format!("Failed to lock error messages: {}", e)))?;
158        let mut grace = self
159            .grace_used
160            .lock()
161            .map_err(|e| AgentError::internal(format!("Failed to lock grace_used: {}", e)))?;
162
163        let session_counts = counts.entry(session_id.id).or_insert_with(HashMap::new);
164        let session_msgs = msgs.entry(session_id.id).or_insert_with(HashMap::new);
165        let session_grace = grace.entry(session_id.id).or_insert_with(HashMap::new);
166
167        // Record error message and increment failure count for each failing tool
168        let error_text = error.to_string();
169        let mut max_failures = 0;
170        let mut threshold_tool: Option<String> = None;
171        for name in tool_names {
172            let count = session_counts.entry(name.clone()).or_insert(0);
173            *count += 1;
174            session_msgs
175                .entry(name.clone())
176                .or_insert_with(Vec::new)
177                .push(error_text.clone());
178            if *count > max_failures {
179                max_failures = *count;
180            }
181            if *count >= self.max_consecutive_failures {
182                threshold_tool = Some(name.clone());
183            }
184        }
185
186        if max_failures >= self.max_consecutive_failures {
187            let tool_name = threshold_tool.unwrap_or_else(|| tool_names[0].clone());
188
189            tracing::warn!(
190                session_id = session_id.id,
191                tool = %tool_name,
192                failures = max_failures,
193                max_consecutive_failures = self.max_consecutive_failures,
194                "ConsecutiveFailureRecovery: threshold reached"
195            );
196
197            // Check if grace was already used for this tool
198            let already_used = session_grace.get(&tool_name).copied().unwrap_or(false);
199
200            if already_used {
201                // Grace exhausted → hard stop. Clear all state for this session.
202                counts.remove(&session_id.id);
203                msgs.remove(&session_id.id);
204                grace.remove(&session_id.id);
205                return Ok(ToolErrorAction::Stop);
206            }
207
208            // First time at threshold → give LLM one grace round
209            session_grace.insert(tool_name.clone(), true);
210
211            let errors = session_msgs.get(&tool_name).cloned().unwrap_or_default();
212
213            // Clear messages but keep counts and grace flag so that the next
214            // failure for the same tool triggers Stop (not another RetryWithHistory).
215            msgs.remove(&session_id.id);
216
217            return Ok(ToolErrorAction::RetryWithHistory { errors });
218        }
219
220        Ok(ToolErrorAction::Retry)
221    }
222
223    fn on_success(&self, session_id: &SessionId, tool_name: &str) {
224        self.reset_failures(session_id, tool_name);
225    }
226}
227
228// ---------------------------------------------------------------------------
229// Invalid tool arguments (schema-level, pre-execution)
230// ---------------------------------------------------------------------------
231
232/// A tool call whose JSON arguments parse but omit fields the tool's schema
233/// declares as required.
234///
235/// Distinct from [`ToolErrorAction`]: this describes a **malformed call**, not
236/// a failed execution. The tool is never invoked, so `ToolErrorRecovery` is
237/// not involved and no side effect happens.
238#[derive(Debug, Clone)]
239pub struct InvalidArgsCtx<'a> {
240    /// Name of the tool the model tried to call.
241    pub tool_name: &'a str,
242    /// Required fields absent from the arguments object.
243    pub missing_fields: Vec<String>,
244    /// The raw arguments JSON produced by the model.
245    pub raw_args: &'a str,
246    /// The tool's input schema as declared to the model.
247    pub schema: Option<&'a serde_json::Value>,
248}
249
250/// What the runtime should do after it rejects an argument-invalid call.
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub enum InvalidArgsAction {
253    /// Feed the message back as the tool result and keep the run going so the
254    /// model can re-issue the call with complete arguments.
255    Reissue {
256        /// Guidance shown to the model in place of the tool result.
257        message: String,
258    },
259    /// Feed the message back as the tool result and end the run.
260    ///
261    /// For applications that prefer invalid calls to fail loudly instead of
262    /// silently retrying.
263    Stop {
264        /// Guidance shown to the model in place of the tool result.
265        message: String,
266    },
267}
268
269/// Strategy for calls that omit schema-required arguments.
270///
271/// Called before execution, once per rejected call, with the structured
272/// details. Implementations may perform side effects (load docs, trigger
273/// workflows) before returning an action.
274///
275/// The hook is `async` so applications can do I/O; the kernel only decides
276/// *when* to ask, not *how* to respond.
277#[async_trait::async_trait]
278pub trait InvalidArgsHandler: Send + Sync {
279    async fn on_invalid_args(&self, ctx: InvalidArgsCtx<'_>) -> AgentResult<InvalidArgsAction>;
280}
281
282/// Default handler: tell the model which required fields are missing and let it
283/// re-issue. Never surfaced to the user.
284pub struct ReissueMissingFields;
285
286#[async_trait::async_trait]
287impl InvalidArgsHandler for ReissueMissingFields {
288    async fn on_invalid_args(&self, ctx: InvalidArgsCtx<'_>) -> AgentResult<InvalidArgsAction> {
289        let missing = ctx.missing_fields.join("`, `");
290        Ok(InvalidArgsAction::Reissue {
291            message: format!(
292                "Tool call was not executed: it omitted required field(s) `{missing}`. \
293                 Re-issue the call with every required field filled in. If you need several \
294                 calls, emit each one with complete arguments."
295            ),
296        })
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn stop_on_error_always_stops() {
306        let recovery = StopOnError;
307        let session_id = SessionId::new(1);
308        let names = vec!["tool_a".to_string()];
309        let error = AgentError::internal("test error");
310        assert_eq!(
311            recovery.on_error(&session_id, &names, &error).unwrap(),
312            ToolErrorAction::Stop
313        );
314    }
315
316    #[test]
317    fn retry_on_error_always_retries() {
318        let recovery = RetryOnError;
319        let session_id = SessionId::new(1);
320        let names = vec!["tool_a".to_string()];
321        let error = AgentError::internal("test error");
322        assert_eq!(
323            recovery.on_error(&session_id, &names, &error).unwrap(),
324            ToolErrorAction::Retry
325        );
326    }
327
328    // ── ConsecutiveFailureRecovery: basic flow ───────────────────────
329
330    #[test]
331    fn consecutive_failure_retries_then_retry_with_history() {
332        let recovery = ConsecutiveFailureRecovery::new(3);
333        let session_id = SessionId::new(1);
334        let names = vec!["tool_a".to_string()];
335        let error = AgentError::internal("test error");
336
337        // First two failures: retry
338        assert_eq!(
339            recovery.on_error(&session_id, &names, &error).unwrap(),
340            ToolErrorAction::Retry
341        );
342        assert_eq!(
343            recovery.on_error(&session_id, &names, &error).unwrap(),
344            ToolErrorAction::Retry
345        );
346
347        // Third failure: RetryWithHistory (grace round)
348        let action = recovery.on_error(&session_id, &names, &error).unwrap();
349        assert!(matches!(action, ToolErrorAction::RetryWithHistory { .. }));
350    }
351
352    #[test]
353    fn consecutive_failure_stop_after_grace() {
354        let recovery = ConsecutiveFailureRecovery::new(3);
355        let session_id = SessionId::new(1);
356        let names = vec!["tool_a".to_string()];
357        let error = AgentError::internal("test error");
358
359        // 3 failures → RetryWithHistory (grace)
360        for _ in 0..2 {
361            recovery.on_error(&session_id, &names, &error).unwrap();
362        }
363        let action = recovery.on_error(&session_id, &names, &error).unwrap();
364        assert!(matches!(action, ToolErrorAction::RetryWithHistory { .. }));
365
366        // Counts NOT cleared — tool_a is still at count=3, grace_used=true.
367        // Next failure (count=4) hits threshold → grace already used → Stop.
368        let action = recovery.on_error(&session_id, &names, &error).unwrap();
369        assert!(
370            matches!(action, ToolErrorAction::Stop),
371            "should Stop after grace exhausted, got {:?}",
372            action
373        );
374    }
375
376    #[test]
377    fn consecutive_failure_retry_with_history_collects_errors() {
378        let recovery = ConsecutiveFailureRecovery::new(2);
379        let session_id = SessionId::new(1);
380        let names = vec!["tool_a".to_string()];
381
382        // Two failures with different error messages
383        let error1 = AgentError::internal("first error");
384        let error2 = AgentError::internal("second error");
385
386        recovery.on_error(&session_id, &names, &error1).unwrap();
387        let action = recovery.on_error(&session_id, &names, &error2).unwrap();
388
389        match action {
390            ToolErrorAction::RetryWithHistory { errors } => {
391                assert_eq!(errors.len(), 2);
392                assert!(errors[0].contains("first error"));
393                assert!(errors[1].contains("second error"));
394            }
395            _ => panic!("expected RetryWithHistory, got {:?}", action),
396        }
397    }
398
399    // ── ConsecutiveFailureRecovery: reset behavior ───────────────────
400
401    #[test]
402    fn consecutive_failure_resets_on_success() {
403        let recovery = ConsecutiveFailureRecovery::new(3);
404        let session_id = SessionId::new(1);
405        let names = vec!["tool_a".to_string()];
406        let error = AgentError::internal("test error");
407
408        // Two failures
409        recovery.on_error(&session_id, &names, &error).unwrap();
410        recovery.on_error(&session_id, &names, &error).unwrap();
411
412        // Reset on success
413        recovery.reset_failures(&session_id, "tool_a");
414
415        // Should retry again (counter reset)
416        assert_eq!(
417            recovery.on_error(&session_id, &names, &error).unwrap(),
418            ToolErrorAction::Retry
419        );
420    }
421
422    #[test]
423    fn consecutive_failure_on_success_resets_via_trait() {
424        let recovery = ConsecutiveFailureRecovery::new(2);
425        let session_id = SessionId::new(1);
426        let names = vec!["tool_a".to_string()];
427        let error = AgentError::internal("test error");
428
429        // One failure (below the threshold of 2)
430        assert_eq!(
431            recovery.on_error(&session_id, &names, &error).unwrap(),
432            ToolErrorAction::Retry
433        );
434
435        // A successful execution breaks the streak (this is what the react loop calls).
436        recovery.on_success(&session_id, "tool_a");
437
438        // The next failure starts a fresh streak: retry again, not stop.
439        assert_eq!(
440            recovery.on_error(&session_id, &names, &error).unwrap(),
441            ToolErrorAction::Retry
442        );
443    }
444
445    #[test]
446    fn consecutive_failure_on_success_resets_grace() {
447        let recovery = ConsecutiveFailureRecovery::new(2);
448        let session_id = SessionId::new(1);
449        let names = vec!["tool_a".to_string()];
450        let error = AgentError::internal("test error");
451
452        // 2 failures → RetryWithHistory
453        recovery.on_error(&session_id, &names, &error).unwrap();
454        let action = recovery.on_error(&session_id, &names, &error).unwrap();
455        assert!(matches!(action, ToolErrorAction::RetryWithHistory { .. }));
456
457        // Tool succeeds → reset
458        recovery.on_success(&session_id, "tool_a");
459
460        // Next 2 failures → should get RetryWithHistory again (grace reset)
461        recovery.on_error(&session_id, &names, &error).unwrap();
462        let action = recovery.on_error(&session_id, &names, &error).unwrap();
463        assert!(
464            matches!(action, ToolErrorAction::RetryWithHistory { .. }),
465            "grace should be reusable after success, got {:?}",
466            action
467        );
468    }
469
470    #[test]
471    fn consecutive_failure_resets_clears_error_messages() {
472        let recovery = ConsecutiveFailureRecovery::new(3);
473        let session_id = SessionId::new(1);
474        let names = vec!["tool_a".to_string()];
475        let error = AgentError::internal("test error");
476
477        // Two failures → error messages accumulated
478        recovery.on_error(&session_id, &names, &error).unwrap();
479        recovery.on_error(&session_id, &names, &error).unwrap();
480
481        // Reset
482        recovery.reset_failures(&session_id, "tool_a");
483
484        // Next failure → if we reach threshold, error messages should only
485        // contain the new ones (not the old ones before reset)
486        let error_new = AgentError::internal("new error");
487        recovery.on_error(&session_id, &names, &error_new).unwrap();
488        recovery.on_error(&session_id, &names, &error_new).unwrap();
489        let action = recovery.on_error(&session_id, &names, &error_new).unwrap();
490        match action {
491            ToolErrorAction::RetryWithHistory { errors } => {
492                assert_eq!(errors.len(), 3);
493                for e in &errors {
494                    assert!(e.contains("new error"), "old errors should be cleared");
495                }
496            }
497            _ => panic!("expected RetryWithHistory, got {:?}", action),
498        }
499    }
500
501    #[test]
502    fn consecutive_failure_resets_session_clears_everything() {
503        let recovery = ConsecutiveFailureRecovery::new(2);
504        let session_id = SessionId::new(1);
505        let names = vec!["tool_a".to_string()];
506        let error = AgentError::internal("test error");
507
508        // 2 failures → RetryWithHistory
509        recovery.on_error(&session_id, &names, &error).unwrap();
510        let action = recovery.on_error(&session_id, &names, &error).unwrap();
511        assert!(matches!(action, ToolErrorAction::RetryWithHistory { .. }));
512
513        // Reset session
514        recovery.reset_session(&session_id);
515
516        // Should retry again (fresh session)
517        assert_eq!(
518            recovery.on_error(&session_id, &names, &error).unwrap(),
519            ToolErrorAction::Retry
520        );
521    }
522
523    // ── ConsecutiveFailureRecovery: session isolation ─────────────────
524
525    #[test]
526    fn consecutive_failure_per_session_isolation() {
527        let recovery = ConsecutiveFailureRecovery::new(2);
528        let session1 = SessionId::new(1);
529        let session2 = SessionId::new(2);
530        let names = vec!["tool_a".to_string()];
531        let error = AgentError::internal("test error");
532
533        // Session 1: two failures → RetryWithHistory
534        recovery.on_error(&session1, &names, &error).unwrap();
535        let action = recovery.on_error(&session1, &names, &error).unwrap();
536        assert!(matches!(action, ToolErrorAction::RetryWithHistory { .. }));
537
538        // Session 1: one more failure → Stop (grace already used)
539        let action = recovery.on_error(&session1, &names, &error).unwrap();
540        assert!(
541            matches!(action, ToolErrorAction::Stop),
542            "session 1 should Stop after grace exhausted, got {:?}",
543            action
544        );
545
546        // Session 2: should still retry (isolated, no grace used)
547        assert_eq!(
548            recovery.on_error(&session2, &names, &error).unwrap(),
549            ToolErrorAction::Retry
550        );
551    }
552
553    // ── ConsecutiveFailureRecovery: different tools independent ───────
554
555    #[test]
556    fn consecutive_failure_different_tools_independent() {
557        let recovery = ConsecutiveFailureRecovery::new(2);
558        let session_id = SessionId::new(1);
559        let error = AgentError::internal("test error");
560
561        // tool_a: 1 failure
562        recovery
563            .on_error(&session_id, &["tool_a".to_string()], &error)
564            .unwrap();
565
566        // tool_b: 1 failure (independent counter)
567        assert_eq!(
568            recovery
569                .on_error(&session_id, &["tool_b".to_string()], &error,)
570                .unwrap(),
571            ToolErrorAction::Retry
572        );
573
574        // tool_a: 2nd failure → RetryWithHistory (not affected by tool_b)
575        let action = recovery
576            .on_error(&session_id, &["tool_a".to_string()], &error)
577            .unwrap();
578        assert!(
579            matches!(action, ToolErrorAction::RetryWithHistory { .. }),
580            "tool_a should trigger RetryWithHistory independently of tool_b"
581        );
582    }
583
584    // ── ConsecutiveFailureRecovery: ToolArgsInvalid error messages ────
585
586    #[test]
587    fn consecutive_failure_records_serde_error_details() {
588        let recovery = ConsecutiveFailureRecovery::new(2);
589        let session_id = SessionId::new(1);
590        let names = vec!["write_file".to_string()];
591
592        // Simulate the improved serde error message
593        let error = AgentError::ToolArgsInvalid {
594            name: "write_file".to_string(),
595            raw: "missing field `path` at line 1 column 2 (args: {})".to_string(),
596        };
597
598        recovery.on_error(&session_id, &names, &error).unwrap();
599        let action = recovery.on_error(&session_id, &names, &error).unwrap();
600
601        match action {
602            ToolErrorAction::RetryWithHistory { errors } => {
603                assert_eq!(errors.len(), 2);
604                assert!(
605                    errors[0].contains("missing field"),
606                    "should contain serde error details"
607                );
608            }
609            _ => panic!("expected RetryWithHistory, got {:?}", action),
610        }
611    }
612}