1use std::collections::HashMap;
2use std::sync::Mutex;
3
4use crate::types::{AgentError, AgentResult, SessionId};
5
6#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum ToolErrorAction {
9 Stop,
11 Retry,
13 RetryWithHistory {
20 errors: Vec<String>,
22 },
23}
24
25pub 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 fn on_success(&self, _session_id: &SessionId, _tool_name: &str) {}
44}
45
46pub 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
63pub 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
79pub struct ConsecutiveFailureRecovery {
89 max_consecutive_failures: usize,
90 failure_counts: Mutex<HashMap<u64, HashMap<String, usize>>>,
92 error_messages: Mutex<HashMap<u64, HashMap<String, Vec<String>>>>,
94 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 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 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 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 let already_used = session_grace.get(&tool_name).copied().unwrap_or(false);
199
200 if already_used {
201 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 session_grace.insert(tool_name.clone(), true);
210
211 let errors = session_msgs.get(&tool_name).cloned().unwrap_or_default();
212
213 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#[derive(Debug, Clone)]
239pub struct InvalidArgsCtx<'a> {
240 pub tool_name: &'a str,
242 pub missing_fields: Vec<String>,
244 pub raw_args: &'a str,
246 pub schema: Option<&'a serde_json::Value>,
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
252pub enum InvalidArgsAction {
253 Reissue {
256 message: String,
258 },
259 Stop {
264 message: String,
266 },
267}
268
269#[async_trait::async_trait]
278pub trait InvalidArgsHandler: Send + Sync {
279 async fn on_invalid_args(&self, ctx: InvalidArgsCtx<'_>) -> AgentResult<InvalidArgsAction>;
280}
281
282pub 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 #[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 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 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 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 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 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 #[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 recovery.on_error(&session_id, &names, &error).unwrap();
410 recovery.on_error(&session_id, &names, &error).unwrap();
411
412 recovery.reset_failures(&session_id, "tool_a");
414
415 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 assert_eq!(
431 recovery.on_error(&session_id, &names, &error).unwrap(),
432 ToolErrorAction::Retry
433 );
434
435 recovery.on_success(&session_id, "tool_a");
437
438 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 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 recovery.on_success(&session_id, "tool_a");
459
460 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 recovery.on_error(&session_id, &names, &error).unwrap();
479 recovery.on_error(&session_id, &names, &error).unwrap();
480
481 recovery.reset_failures(&session_id, "tool_a");
483
484 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 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 recovery.reset_session(&session_id);
515
516 assert_eq!(
518 recovery.on_error(&session_id, &names, &error).unwrap(),
519 ToolErrorAction::Retry
520 );
521 }
522
523 #[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 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 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 assert_eq!(
548 recovery.on_error(&session2, &names, &error).unwrap(),
549 ToolErrorAction::Retry
550 );
551 }
552
553 #[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 recovery
563 .on_error(&session_id, &["tool_a".to_string()], &error)
564 .unwrap();
565
566 assert_eq!(
568 recovery
569 .on_error(&session_id, &["tool_b".to_string()], &error,)
570 .unwrap(),
571 ToolErrorAction::Retry
572 );
573
574 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 #[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 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}