Skip to main content

gadk_engine/plugin/
retry_and_reflect.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! A plugin that turns tool failures into reflection guidance for the model. It counts
17//! consecutive failures per tool within a scope (one invocation, or global), and after
18//! `max_retries` failures tells the model to stop using the tool, or returns the original error.
19
20use std::collections::HashMap;
21use std::sync::Arc;
22
23use futures::future::{BoxFuture, ready};
24use gadk_agent::{
25    AfterRunCallback, AfterToolCallback, AgentError, Context, InvocationContext,
26    OnToolErrorCallback, Plugin, PluginConfig, SharedToolError, Tool, ToolError,
27};
28use gadk_session::Session;
29use parking_lot::Mutex;
30use serde_json::{Map, Value, json};
31
32use crate::llm::processors::{as_go_floats, go_json_marshal};
33use crate::tool::utils::model_error_text;
34
35/// The reflection guidance template (`reflection.md`), embedded verbatim.
36const REFLECTION_TEMPLATE: &str = include_str!("retry_and_reflect/reflection.md");
37/// The retry-exceeded template (`exceeded.md`), embedded verbatim.
38const EXCEEDED_TEMPLATE: &str = include_str!("retry_and_reflect/exceeded.md");
39
40/// The `response_type` of every result this plugin produces.
41pub(crate) const REFLECT_AND_RETRY_RESPONSE_TYPE: &str =
42    "ERROR_HANDLED_BY_REFLECT_AND_RETRY_PLUGIN";
43/// The counter scope used with [`TrackingScope::Global`].
44pub(crate) const GLOBAL_SCOPE_KEY: &str = "__global_reflect_and_retry_scope__";
45
46const NAME: &str = "RetryAndReflectPlugin";
47
48type MapResult = BoxFuture<'static, Result<Option<Map<String, Value>>, AgentError>>;
49
50/// The lifetime of the tool-failure counters.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum TrackingScope {
53    /// Failures are counted per invocation.
54    #[default]
55    Invocation,
56    /// Failures are counted across all invocations, turns and users.
57    Global,
58}
59
60/// The options of the retry-and-reflect plugin.
61#[derive(Debug, Clone)]
62pub struct RetryAndReflectConfig {
63    /// Consecutive failures of one tool that still get reflection guidance; must be `>= 0`.
64    pub max_retries: i32,
65    /// Past the limit, return the original tool error instead of the "retry exceeded" result.
66    pub error_if_retry_exceeded: bool,
67    /// The scope the failures are counted in.
68    pub tracking_scope: TrackingScope,
69}
70
71impl Default for RetryAndReflectConfig {
72    /// The defaults: 3 retries, no error past the limit, invocation scope.
73    fn default() -> Self {
74        Self {
75            max_retries: 3,
76            error_if_retry_exceeded: false,
77            tracking_scope: TrackingScope::Invocation,
78        }
79    }
80}
81
82/// Builds a plugin named `RetryAndReflectPlugin` that registers only the after-tool,
83/// on-tool-error and after-run callbacks. A negative `max_retries` is rejected with
84/// `maxRetries must be a non-negative integer`.
85pub fn new_retry_and_reflect_plugin(cfg: RetryAndReflectConfig) -> Result<Plugin, AgentError> {
86    if cfg.max_retries < 0 {
87        return Err(AgentError::Config(
88            "maxRetries must be a non-negative integer".into(),
89        ));
90    }
91    Ok(plugin_for(Arc::new(RetryAndReflect::new(&cfg))))
92}
93
94/// The plugin whose three callbacks share `r`.
95fn plugin_for(r: Arc<RetryAndReflect>) -> Plugin {
96    let after_run: AfterRunCallback = {
97        let r = r.clone();
98        Arc::new(move |ictx: InvocationContext| -> BoxFuture<'static, ()> {
99            r.after_run(&ictx);
100            Box::pin(ready(()))
101        })
102    };
103    let after_tool: AfterToolCallback = {
104        let r = r.clone();
105        Arc::new(
106            move |ctx: Context,
107                  tool: Arc<dyn Tool>,
108                  args: Map<String, Value>,
109                  result: Map<String, Value>,
110                  err: Option<Arc<ToolError>>|
111                  -> MapResult {
112                Box::pin(ready(r.after_tool(
113                    &ctx,
114                    &*tool,
115                    &args,
116                    &result,
117                    err.as_deref(),
118                )))
119            },
120        )
121    };
122    let on_tool_error: OnToolErrorCallback = {
123        let r = r.clone();
124        Arc::new(
125            move |ctx: Context,
126                  tool: Arc<dyn Tool>,
127                  args: Map<String, Value>,
128                  err: Arc<ToolError>|
129                  -> MapResult {
130                Box::pin(ready(r.on_tool_error(&ctx, &*tool, &args, &err)))
131            },
132        )
133    };
134    Plugin::new(PluginConfig {
135        name: NAME.into(),
136        after_tool_callback: Some(after_tool),
137        on_tool_error_callback: Some(on_tool_error),
138        after_run_callback: Some(after_run),
139        ..Default::default()
140    })
141}
142
143/// The plugin's settings and its failure counters, shared by its callbacks.
144pub(crate) struct RetryAndReflect {
145    pub(crate) max_retries: i32,
146    pub(crate) error_if_retry_exceeded: bool,
147    pub(crate) scope: TrackingScope,
148    /// Consecutive failures: scope key → tool name → count.
149    pub(crate) scoped_failure_counters: Mutex<HashMap<String, HashMap<String, i32>>>,
150}
151
152impl RetryAndReflect {
153    pub(crate) fn new(cfg: &RetryAndReflectConfig) -> Self {
154        Self {
155            max_retries: cfg.max_retries,
156            error_if_retry_exceeded: cfg.error_if_retry_exceeded,
157            scope: cfg.tracking_scope,
158            scoped_failure_counters: Mutex::new(HashMap::new()),
159        }
160    }
161
162    /// The after-tool callback. A success whose result is not this plugin's own reflection result
163    /// resets the tool's count in its scope. The result is never changed.
164    pub(crate) fn after_tool(
165        &self,
166        ctx: &Context,
167        tool: &dyn Tool,
168        _args: &Map<String, Value>,
169        result: &Map<String, Value>,
170        err: Option<&ToolError>,
171    ) -> Result<Option<Map<String, Value>>, AgentError> {
172        if err.is_none() {
173            let is_reflect_response = result.get("response_type").and_then(Value::as_str)
174                == Some(REFLECT_AND_RETRY_RESPONSE_TYPE);
175            if !is_reflect_response {
176                self.reset_failures_for_tool(ctx, tool.name());
177            }
178        }
179        Ok(None)
180    }
181
182    /// The on-tool-error callback: counts the failure and returns reflection guidance while the
183    /// count is within `max_retries`; past it, the original error or the "retry exceeded" result.
184    /// Confirmation requests and rejections are not failures and pass through.
185    pub(crate) fn on_tool_error(
186        &self,
187        ctx: &Context,
188        tool: &dyn Tool,
189        args: &Map<String, Value>,
190        err: &Arc<ToolError>,
191    ) -> Result<Option<Map<String, Value>>, AgentError> {
192        // A confirmation request or rejection is not a failure.
193        if is_confirmation_error(err) {
194            return Ok(None);
195        }
196
197        if self.max_retries == 0 {
198            if self.error_if_retry_exceeded {
199                return Err(original_error(err));
200            }
201            return Ok(Some(self.retry_exceeded_msg(tool, args, err)));
202        }
203
204        let scope_key = self.scope_key(ctx);
205        let current_retries = {
206            let mut counters = self.scoped_failure_counters.lock();
207            let n = counters
208                .entry(scope_key)
209                .or_default()
210                .entry(tool.name().to_string())
211                .or_insert(0);
212            *n = n.saturating_add(1);
213            *n
214        };
215
216        if current_retries <= self.max_retries {
217            return Ok(Some(self.reflection_response(
218                tool,
219                args,
220                err,
221                current_retries,
222            )));
223        }
224
225        // Max retry exceeded.
226        if self.error_if_retry_exceeded {
227            return Err(original_error(err));
228        }
229        Ok(Some(self.retry_exceeded_msg(tool, args, err)))
230    }
231
232    /// The after-run callback: drops the failure counts of an invocation once its run has ended,
233    /// since nothing reads them afterwards. Every scope but `Global` keys its
234    /// counts by invocation ID. The counts of a run that paused on an unanswered long-running
235    /// call are kept: the run that answers the call reuses the invocation ID and continues the
236    /// same retry budget, as in adk-python.
237    pub(crate) fn after_run(&self, ictx: &InvocationContext) {
238        if self.scope == TrackingScope::Global {
239            return;
240        }
241        let invocation_id = ictx.invocation_id();
242        let tracked = self
243            .scoped_failure_counters
244            .lock()
245            .contains_key(invocation_id);
246        // Most runs record no failure; skip the scan of the session events for them.
247        if !tracked || has_open_long_running_call(&*ictx.session(), invocation_id) {
248            return;
249        }
250        self.scoped_failure_counters.lock().remove(invocation_id);
251    }
252
253    /// The counter scope key for the context.
254    fn scope_key(&self, ctx: &Context) -> String {
255        match self.scope {
256            TrackingScope::Global => GLOBAL_SCOPE_KEY.to_string(),
257            TrackingScope::Invocation => ctx.invocation_id().to_string(),
258        }
259    }
260
261    /// Drops the tool's count, and the scope once it is empty.
262    fn reset_failures_for_tool(&self, ctx: &Context, tool_name: &str) {
263        let scope_key = self.scope_key(ctx);
264        let mut counters = self.scoped_failure_counters.lock();
265        if let Some(scope) = counters.get_mut(&scope_key) {
266            scope.remove(tool_name);
267            if scope.is_empty() {
268                counters.remove(&scope_key);
269            }
270        }
271    }
272
273    /// The result for a failure within the retry limit: reflection guidance and the retry count.
274    fn reflection_response(
275        &self,
276        tool: &dyn Tool,
277        args: &Map<String, Value>,
278        err: &ToolError,
279        retry_count: i32,
280    ) -> Map<String, Value> {
281        let rendered = render(
282            REFLECTION_TEMPLATE,
283            &TemplateData {
284                tool_name: tool.name(),
285                error_details: &format_error_details(tool, err),
286                args_summary: &format_tool_args(args),
287                retry_count,
288                max_retries: self.max_retries,
289            },
290        );
291        response_map(tool, err, retry_count, &rendered)
292    }
293
294    /// The result for a failure past the retry limit: the template's `RetryCount` and
295    /// `MaxRetries` are both `max_retries`, as is the map's `retry_count`.
296    fn retry_exceeded_msg(
297        &self,
298        tool: &dyn Tool,
299        args: &Map<String, Value>,
300        err: &ToolError,
301    ) -> Map<String, Value> {
302        let rendered = render(
303            EXCEEDED_TEMPLATE,
304            &TemplateData {
305                tool_name: tool.name(),
306                error_details: &format_error_details(tool, err),
307                args_summary: &format_tool_args(args),
308                retry_count: self.max_retries,
309                max_retries: self.max_retries,
310            },
311        );
312        response_map(tool, err, self.max_retries, &rendered)
313    }
314}
315
316/// Whether `err` is, or wraps, `ToolError::ConfirmationRequired` or
317/// `ToolError::ConfirmationRejected`.
318/// The flow hands confirmation sentinels over wrapped (`ToolError::Execution` around a named
319/// wrapper whose `source()` is the sentinel), so this walks the chain. Transparent
320/// layers (`ToolError::Execution`, `SharedToolError`, `AgentError::Other`) forward `source()` to
321/// their inner error's source, skipping the inner error itself, so the walk descends into them
322/// directly; any other error is followed through `source()`.
323fn is_confirmation_error(err: &ToolError) -> bool {
324    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
325    while let Some(e) = cur {
326        cur = if let Some(te) = e.downcast_ref::<ToolError>() {
327            match te {
328                ToolError::ConfirmationRequired | ToolError::ConfirmationRejected => return true,
329                ToolError::Execution(inner) => Some(&**inner),
330                _ => std::error::Error::source(te),
331            }
332        } else if let Some(shared) = e.downcast_ref::<SharedToolError>() {
333            Some(&*shared.0)
334        } else if let Some(AgentError::Other(inner)) = e.downcast_ref::<AgentError>() {
335            Some(&**inner)
336        } else {
337            e.source()
338        };
339    }
340    false
341}
342
343/// The original tool error, keeping the caller's `Arc` so the very same error value is returned.
344fn original_error(err: &Arc<ToolError>) -> AgentError {
345    AgentError::Other(Box::new(SharedToolError(Arc::clone(err))))
346}
347
348/// Whether the invocation has a long-running call that no user
349/// function response has answered yet. A failure response from this plugin also settles the
350/// call, since no answer will follow.
351fn has_open_long_running_call(sess: &dyn Session, invocation_id: &str) -> bool {
352    let mut open: std::collections::HashSet<String> = std::collections::HashSet::new();
353    for ev in sess.events() {
354        if ev.invocation_id != invocation_id {
355            continue;
356        }
357        open.extend(ev.long_running_tool_ids.iter().cloned());
358        let Some(content) = &ev.response.content else {
359            continue;
360        };
361        for fr in content
362            .parts
363            .iter()
364            .filter_map(|p| p.function_response.as_ref())
365        {
366            if fr.id.is_empty() {
367                continue;
368            }
369            if ev.author == "user"
370                || fr.response.get("response_type").and_then(Value::as_str)
371                    == Some(REFLECT_AND_RETRY_RESPONSE_TYPE)
372            {
373                open.remove(&fr.id);
374            }
375        }
376    }
377    !open.is_empty()
378}
379
380/// The `error_type` of a recovered tool panic.
381const PANIC_ERROR_TYPE: &str = "panic";
382
383/// The type and text of a failed call that the plugin may put in its response, which the model,
384/// the session and REST clients all see. A tool panic, at any wrapping depth, becomes the type
385/// `panic` and a generic message, because the panic's own text carries the panic value.
386fn model_error(tool: &dyn Tool, err: &ToolError) -> (String, String) {
387    match model_error_text(tool.name(), err) {
388        (text, true) => (PANIC_ERROR_TYPE.to_string(), text),
389        (text, false) => (error_type(err).to_string(), text),
390    }
391}
392
393/// The result map shared by the reflection and exceeded outcomes. `reflection_guidance` is the
394/// rendered template with surrounding whitespace trimmed.
395fn response_map(
396    tool: &dyn Tool,
397    err: &ToolError,
398    retry_count: i32,
399    rendered: &str,
400) -> Map<String, Value> {
401    let (err_type, err_details) = model_error(tool, err);
402    let mut m = Map::new();
403    m.insert(
404        "response_type".into(),
405        json!(REFLECT_AND_RETRY_RESPONSE_TYPE),
406    );
407    m.insert("error_type".into(), json!(err_type));
408    m.insert("error_details".into(), json!(err_details));
409    m.insert("retry_count".into(), json!(retry_count));
410    m.insert("reflection_guidance".into(), json!(rendered.trim()));
411    m
412}
413
414/// The error's type name for the result's `error_type`: the `ToolError` variant path, such as
415/// `ToolError::Execution`.
416fn error_type(err: &ToolError) -> &'static str {
417    match err {
418        ToolError::ConfirmationRequired => "ToolError::ConfirmationRequired",
419        ToolError::ConfirmationRejected => "ToolError::ConfirmationRejected",
420        ToolError::InvalidArgument(_) => "ToolError::InvalidArgument",
421        ToolError::Panic(_) => "ToolError::Panic",
422        ToolError::Execution(_) => "ToolError::Execution",
423        _ => "ToolError",
424    }
425}
426
427/// The template's `ErrorDetails`: `<type>: <details>` of [`model_error`].
428fn format_error_details(tool: &dyn Tool, err: &ToolError) -> String {
429    let (err_type, err_details) = model_error(tool, err);
430    format!("{err_type}: {err_details}")
431}
432
433/// The tool arguments as JSON (compact form as `go_json_marshal` writes it: keys sorted, `<`,
434/// `>` and `&` written as Unicode escapes) indented by two spaces (see [`go_indent`]); an empty map
435/// gives `null`. Numbers are decoded as `f64`, as tool arguments are, hence [`as_go_floats`].
436fn format_tool_args(args: &Map<String, Value>) -> String {
437    if args.is_empty() {
438        return "null".to_string();
439    }
440    go_indent(&go_json_marshal(&as_go_floats(&Value::Object(
441        args.clone(),
442    ))))
443}
444
445/// Indents compact, valid JSON by two spaces per level. `{`/`[` defer their newline until the
446/// next element, so empty objects and arrays stay `{}`/`[]`; `:` gains one space; strings are
447/// copied untouched.
448fn go_indent(compact: &str) -> String {
449    fn newline(out: &mut String, depth: usize) {
450        out.push('\n');
451        for _ in 0..depth {
452            out.push_str("  ");
453        }
454    }
455    let mut out = String::with_capacity(compact.len() * 2);
456    let mut depth = 0usize;
457    let mut need_indent = false;
458    let mut in_string = false;
459    let mut escaped = false;
460    for c in compact.chars() {
461        if in_string {
462            out.push(c);
463            if escaped {
464                escaped = false;
465            } else if c == '\\' {
466                escaped = true;
467            } else if c == '"' {
468                in_string = false;
469            }
470            continue;
471        }
472        if need_indent && c != '}' && c != ']' {
473            need_indent = false;
474            depth += 1;
475            newline(&mut out, depth);
476        }
477        match c {
478            '"' => {
479                in_string = true;
480                out.push(c);
481            }
482            '{' | '[' => {
483                need_indent = true;
484                out.push(c);
485            }
486            ',' => {
487                out.push(c);
488                newline(&mut out, depth);
489            }
490            ':' => {
491                out.push(c);
492                out.push(' ');
493            }
494            '}' | ']' => {
495                if need_indent {
496                    // Empty object or array: no indent.
497                    need_indent = false;
498                } else {
499                    depth = depth.saturating_sub(1);
500                    newline(&mut out, depth);
501                }
502                out.push(c);
503            }
504            _ => out.push(c),
505        }
506    }
507    out
508}
509
510/// The values substituted into the reflection and exceeded templates.
511struct TemplateData<'a> {
512    tool_name: &'a str,
513    error_details: &'a str,
514    args_summary: &'a str,
515    retry_count: i32,
516    max_retries: i32,
517}
518
519/// Renders `reflection.md` / `exceeded.md`. Both templates use only the five `{{.Field}}`
520/// actions, so one left-to-right substitution pass renders them exactly. Substituted values are
521/// never re-scanned. An unknown action, which neither template has, is
522/// copied through unchanged.
523fn render(template: &str, d: &TemplateData<'_>) -> String {
524    let mut out = String::with_capacity(template.len() + d.args_summary.len() + 64);
525    let mut rest = template;
526    while let Some(start) = rest.find("{{.") {
527        out.push_str(&rest[..start]);
528        let after = &rest[start + 3..];
529        let Some(end) = after.find("}}") else {
530            out.push_str(&rest[start..]);
531            rest = "";
532            break;
533        };
534        match &after[..end] {
535            "ToolName" => out.push_str(d.tool_name),
536            "ErrorDetails" => out.push_str(d.error_details),
537            "ArgsSummary" => out.push_str(d.args_summary),
538            "RetryCount" => out.push_str(&d.retry_count.to_string()),
539            "MaxRetries" => out.push_str(&d.max_retries.to_string()),
540            other => {
541                out.push_str("{{.");
542                out.push_str(other);
543                out.push_str("}}");
544            }
545        }
546        rest = &after[end + 2..];
547    }
548    out.push_str(rest);
549    out
550}
551
552#[cfg(test)]
553#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
554mod tests {
555    use std::any::Any;
556
557    use super::*;
558
559    struct NamedTool(&'static str);
560
561    impl Tool for NamedTool {
562        fn name(&self) -> &str {
563            self.0
564        }
565
566        fn description(&self) -> &str {
567            ""
568        }
569
570        fn as_any(&self) -> &dyn Any {
571            self
572        }
573    }
574
575    const WANT_REFLECTION: &str = r#"The call to tool `test-tool` failed.
576
577**Error Details:**
578```
579ToolError::Execution: fail
580```
581
582**Tool Arguments Used:**
583```json
584{
585  "arg1": "val1"
586}
587```
588
589**Reflection Guidance:**
590This is retry attempt **1 of 2**. Analyze the error and the arguments you provided. Do not repeat the exact same call. Consider the following before your next attempt:
591
5921.  **Invalid Parameters**: Does the error suggest that one or more arguments are incorrect, badly formatted, or missing? Review the tool's schema and your arguments.
5932.  **State or Preconditions**: Did a previous step fail or not produce the necessary state/resource for this tool to succeed?
5943.  **Alternative Approach**: Is this the right tool for the job? Could another tool or a different sequence of steps achieve the goal?
5954.  **Simplify the Task**: Can you break the problem down into smaller, simpler steps?
5965.  **Wrong Function Name**: Does the error indicates the tool is not found? Please check again and only use available tools.
597
598Formulate a new plan based on your analysis and try a corrected or different approach."#;
599
600    const WANT_EXCEEDED: &str = r#"The tool `test-tool` has failed consecutively 0 times and the retry limit has been exceeded.
601
602**Last Error:**
603```
604ToolError::Execution: fail
605```
606
607**Last Arguments Used:**
608```json
609null
610```
611
612**Final Instruction:**
613**Do not attempt to use the `test-tool` tool again for this task.** You must now try a different approach. Acknowledge the failure and devise a new strategy, potentially using other available tools or informing the user that the task cannot be completed."#;
614
615    fn fail() -> Arc<ToolError> {
616        Arc::new(ToolError::Execution("fail".into()))
617    }
618
619    #[test]
620    fn templates_are_go_bytes() {
621        assert!(REFLECTION_TEMPLATE.starts_with("\nThe call to tool `{{.ToolName}}` failed.\n"));
622        assert!(REFLECTION_TEMPLATE.ends_with("try a corrected or different approach.\n"));
623        assert!(EXCEEDED_TEMPLATE.starts_with(
624            "\nThe tool `{{.ToolName}}` has failed consecutively {{.MaxRetries}} times"
625        ));
626        assert!(EXCEEDED_TEMPLATE.ends_with("the task cannot be completed.\n"));
627    }
628
629    #[test]
630    fn reflection_result_renders_go_template() {
631        let r = RetryAndReflect::new(&RetryAndReflectConfig {
632            max_retries: 2,
633            ..Default::default()
634        });
635        let args = json!({"arg1": "val1"}).as_object().cloned().unwrap();
636        let res = r
637            .on_tool_error(
638                &Context::builder().build(),
639                &NamedTool("test-tool"),
640                &args,
641                &fail(),
642            )
643            .unwrap()
644            .unwrap();
645        let want = json!({
646            "response_type": "ERROR_HANDLED_BY_REFLECT_AND_RETRY_PLUGIN",
647            "error_type": "ToolError::Execution",
648            "error_details": "fail",
649            "retry_count": 1,
650            "reflection_guidance": WANT_REFLECTION,
651        });
652        assert_eq!(Value::Object(res), want);
653    }
654
655    // With max_retries 0 the guidance says "failed consecutively 0 times".
656    #[test]
657    fn exceeded_result_renders_go_template_with_zero_times() {
658        let r = RetryAndReflect::new(&RetryAndReflectConfig {
659            max_retries: 0,
660            ..Default::default()
661        });
662        let res = r
663            .on_tool_error(
664                &Context::builder().build(),
665                &NamedTool("test-tool"),
666                &Map::new(),
667                &fail(),
668            )
669            .unwrap()
670            .unwrap();
671        let want = json!({
672            "response_type": "ERROR_HANDLED_BY_REFLECT_AND_RETRY_PLUGIN",
673            "error_type": "ToolError::Execution",
674            "error_details": "fail",
675            "retry_count": 0,
676            "reflection_guidance": WANT_EXCEEDED,
677        });
678        assert_eq!(Value::Object(res), want);
679        // max_retries == 0 counts nothing.
680        assert!(r.scoped_failure_counters.lock().is_empty());
681    }
682
683    #[test]
684    fn exceeded_after_the_limit_reports_max_retries_times() {
685        let r = RetryAndReflect::new(&RetryAndReflectConfig {
686            max_retries: 1,
687            ..Default::default()
688        });
689        let ctx = Context::builder().build();
690        let tool = NamedTool("test-tool");
691        let _ = r.on_tool_error(&ctx, &tool, &Map::new(), &fail());
692        let res = r
693            .on_tool_error(&ctx, &tool, &Map::new(), &fail())
694            .unwrap()
695            .unwrap();
696        assert_eq!(res["retry_count"], json!(1));
697        // Go 4417f2d4: the template's RetryCount and MaxRetries are max_retries.
698        assert_eq!(
699            res["reflection_guidance"],
700            json!(WANT_EXCEEDED.replace("consecutively 0 times", "consecutively 1 times"))
701        );
702    }
703
704    #[test]
705    fn max_retries_zero_with_error_returns_the_original_error() {
706        let r = RetryAndReflect::new(&RetryAndReflectConfig {
707            max_retries: 0,
708            error_if_retry_exceeded: true,
709            ..Default::default()
710        });
711        let err = fail();
712        let got = r
713            .on_tool_error(
714                &Context::builder().build(),
715                &NamedTool("t"),
716                &Map::new(),
717                &err,
718            )
719            .unwrap_err();
720        let AgentError::Other(inner) = &got else {
721            panic!("want AgentError::Other, got {got:?}");
722        };
723        let shared = inner.downcast_ref::<SharedToolError>().unwrap();
724        assert!(Arc::ptr_eq(&shared.0, &err));
725        assert!(r.scoped_failure_counters.lock().is_empty());
726    }
727
728    #[test]
729    fn confirmation_errors_pass_through_uncounted() {
730        let r = RetryAndReflect::new(&RetryAndReflectConfig::default());
731        let ctx = Context::builder().build();
732        for e in [
733            ToolError::ConfirmationRequired,
734            ToolError::ConfirmationRejected,
735        ] {
736            let res = r.on_tool_error(&ctx, &NamedTool("t"), &Map::new(), &Arc::new(e));
737            assert!(matches!(res, Ok(None)), "{res:?}");
738        }
739        assert!(r.scoped_failure_counters.lock().is_empty());
740    }
741
742    /// Stands in for the flow's private `llm::functions::NamedToolError` (Go `fmt.Errorf("error
743    /// tool %q %w", name, sentinel)`): its `source()` is the sentinel.
744    #[derive(Debug)]
745    struct Wrapped(ToolError);
746
747    impl std::fmt::Display for Wrapped {
748        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
749            write!(f, "error tool \"t\" {}", self.0)
750        }
751    }
752
753    impl std::error::Error for Wrapped {
754        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
755            Some(&self.0)
756        }
757    }
758
759    /// The confirmation sentinels as the flow hands them over (`wrap_confirmation_error`), plus
760    /// further layers (`SharedToolError`, `AgentError::Other`) a wrapping tool might add.
761    fn wrapped_sentinels() -> Vec<ToolError> {
762        let mut v = Vec::new();
763        for s in [
764            || ToolError::ConfirmationRequired,
765            || ToolError::ConfirmationRejected,
766        ] {
767            v.push(ToolError::Execution(Box::new(Wrapped(s()))));
768            v.push(ToolError::Execution(Box::new(SharedToolError(Arc::new(
769                ToolError::Execution(Box::new(Wrapped(s()))),
770            )))));
771            v.push(ToolError::Execution(Box::new(AgentError::Other(Box::new(
772                SharedToolError(Arc::new(s())),
773            )))));
774        }
775        v
776    }
777
778    // Go errors.Is unwraps %w, so the flow-wrapped sentinels pass through uncounted too.
779    #[test]
780    fn wrapped_confirmation_errors_pass_through_uncounted() {
781        let r = RetryAndReflect::new(&RetryAndReflectConfig {
782            max_retries: 0,
783            error_if_retry_exceeded: true,
784            ..Default::default()
785        });
786        let ctx = Context::builder().build();
787        for e in wrapped_sentinels() {
788            let shown = e.to_string();
789            let res = r.on_tool_error(&ctx, &NamedTool("t"), &Map::new(), &Arc::new(e));
790            assert!(matches!(res, Ok(None)), "{shown}: {res:?}");
791        }
792        let r = RetryAndReflect::new(&RetryAndReflectConfig::default());
793        for e in wrapped_sentinels() {
794            let res = r.on_tool_error(&ctx, &NamedTool("t"), &Map::new(), &Arc::new(e));
795            assert!(matches!(res, Ok(None)), "{res:?}");
796        }
797        assert!(r.scoped_failure_counters.lock().is_empty());
798    }
799
800    #[test]
801    fn non_confirmation_wrapped_error_is_counted() {
802        let r = RetryAndReflect::new(&RetryAndReflectConfig::default());
803        let err = Arc::new(ToolError::Execution(Box::new(Wrapped(
804            ToolError::InvalidArgument("bad".into()),
805        ))));
806        let res = r
807            .on_tool_error(
808                &Context::builder().build(),
809                &NamedTool("t"),
810                &Map::new(),
811                &err,
812            )
813            .unwrap()
814            .unwrap();
815        assert_eq!(res["retry_count"], json!(1));
816    }
817
818    // Covers the plugin's closures: they share one state and pass the original error through.
819    #[tokio::test]
820    async fn plugin_callbacks_share_state_and_skip_confirmation() {
821        let p = new_retry_and_reflect_plugin(RetryAndReflectConfig {
822            max_retries: 1,
823            error_if_retry_exceeded: true,
824            ..Default::default()
825        })
826        .unwrap();
827        let on_err = p.on_tool_error_callback().unwrap();
828        let after = p.after_tool_callback().unwrap();
829        let ctx = Context::builder().invocation_id("inv").build();
830        let tool: Arc<dyn Tool> = Arc::new(NamedTool("t"));
831
832        let confirm = Arc::new(ToolError::Execution(Box::new(Wrapped(
833            ToolError::ConfirmationRequired,
834        ))));
835        let res = on_err(ctx.clone(), tool.clone(), Map::new(), confirm).await;
836        assert!(matches!(res, Ok(None)), "{res:?}");
837
838        let err = fail();
839        let res = on_err(ctx.clone(), tool.clone(), Map::new(), err.clone())
840            .await
841            .unwrap()
842            .unwrap();
843        assert_eq!(res["retry_count"], json!(1));
844        // The reflection result does not reset; a real success does.
845        let res = after(ctx.clone(), tool.clone(), Map::new(), res, None).await;
846        assert!(matches!(res, Ok(None)), "{res:?}");
847        let res = after(ctx.clone(), tool.clone(), Map::new(), Map::new(), None).await;
848        assert!(matches!(res, Ok(None)), "{res:?}");
849        let res = on_err(ctx.clone(), tool.clone(), Map::new(), err.clone())
850            .await
851            .unwrap()
852            .unwrap();
853        assert_eq!(res["retry_count"], json!(1), "success reset the count");
854
855        let got = on_err(ctx, tool, Map::new(), err.clone())
856            .await
857            .unwrap_err();
858        let AgentError::Other(inner) = &got else {
859            panic!("want AgentError::Other, got {got:?}");
860        };
861        let shared = inner.downcast_ref::<SharedToolError>().unwrap();
862        assert!(Arc::ptr_eq(&shared.0, &err));
863    }
864
865    #[test]
866    fn config_defaults_match_go() {
867        let d = RetryAndReflectConfig::default();
868        assert_eq!(
869            (d.max_retries, d.error_if_retry_exceeded, d.tracking_scope),
870            (3, false, TrackingScope::Invocation)
871        );
872    }
873
874    // Expected value printed by Go: json.MarshalIndent of the same JSON decoded into map[string]any.
875    #[test]
876    fn args_summary_matches_go_marshal_indent() {
877        let args = json!({
878            "b": [1, {}],
879            "a": "<x>&",
880            "c": [],
881            "d": {"z": 1.5, "y": null},
882            "e": 1e21,
883            "f": {"g": [true, "\u{2028}"]}
884        });
885        assert_eq!(
886            format_tool_args(args.as_object().unwrap()),
887            "{\n  \"a\": \"\\u003cx\\u003e\\u0026\",\n  \"b\": [\n    1,\n    {}\n  ],\n  \"c\": [],\n  \"d\": {\n    \"y\": null,\n    \"z\": 1.5\n  },\n  \"e\": 1e+21,\n  \"f\": {\n    \"g\": [\n      true,\n      \"\\u2028\"\n    ]\n  }\n}"
888        );
889        assert_eq!(format_tool_args(&Map::new()), "null");
890    }
891
892    #[test]
893    fn render_does_not_rescan_substituted_values() {
894        let d = TemplateData {
895            tool_name: "{{.ArgsSummary}}",
896            error_details: "",
897            args_summary: "ARGS",
898            retry_count: 0,
899            max_retries: 0,
900        };
901        assert_eq!(
902            render("{{.ToolName}}/{{.ArgsSummary}}", &d),
903            "{{.ArgsSummary}}/ARGS"
904        );
905    }
906
907    #[derive(serde::Deserialize, schemars::JsonSchema)]
908    struct NoArgs {}
909
910    /// Runner-level: a confirmation-requiring FunctionTool's error, as the flow really wraps it
911    /// (`error tool "<name>" requires confirmation, ...`), passes the guard. The model's
912    /// function response is Go's confirmation error, not reflection guidance, and no failure
913    /// is counted.
914    #[tokio::test]
915    async fn runner_confirmation_error_passes_through_uncounted() {
916        use gadk_genai::{Content, FunctionCall};
917        use gadk_model::LlmResponse;
918
919        use crate::llm::{LlmAgentConfig, agent as llm_agent};
920        use crate::testutil::{MockModel, TestAgentRunner, collect_events};
921        use crate::tool::{FunctionTool, FunctionToolConfig};
922
923        let secure = FunctionTool::new(
924            FunctionToolConfig {
925                require_confirmation: true,
926                ..FunctionToolConfig::new("secure_action", "needs approval")
927            },
928            |_ctx: Context, _: NoArgs| async move { Ok::<_, ToolError>(json!({"done": true})) },
929        )
930        .unwrap();
931        let call = Content::from_function_call(
932            FunctionCall {
933                id: "fc1".into(),
934                name: "secure_action".into(),
935                ..Default::default()
936            },
937            "model",
938        );
939        let model = MockModel::new(vec![
940            Ok(LlmResponse {
941                content: Some(call),
942                ..Default::default()
943            }),
944            Ok(LlmResponse {
945                content: Some(Content::from_text("done", "model")),
946                ..Default::default()
947            }),
948        ]);
949        let agent = llm_agent::new(LlmAgentConfig {
950            name: "a".into(),
951            model: Some(model.clone()),
952            tools: vec![secure],
953            ..Default::default()
954        })
955        .unwrap();
956        let state = Arc::new(RetryAndReflect::new(&RetryAndReflectConfig::default()));
957        let runner = TestAgentRunner::with_plugins(
958            agent,
959            crate::runner::PluginConfig {
960                plugins: vec![plugin_for(state.clone())],
961                close_timeout: std::time::Duration::from_secs(1),
962            },
963        )
964        .await;
965        let events = collect_events(runner.run("go")).await.unwrap();
966
967        let want = json!({
968            "error": "error tool \"secure_action\" requires confirmation, please approve or reject"
969        });
970        let responses: Vec<Value> = events
971            .iter()
972            .filter_map(|e| e.response.content.as_ref())
973            .flat_map(|c| c.parts.iter())
974            .filter_map(|p| p.function_response.as_ref())
975            .filter(|fr| fr.name == "secure_action")
976            .map(|fr| Value::Object(fr.response.clone()))
977            .collect();
978        assert_eq!(responses, vec![want.clone()]);
979        // The run pauses for the confirmation (as in Go); the model sees the response on the
980        // next turn.
981        assert_eq!(model.requests().len(), 1);
982        collect_events(runner.run("next")).await.unwrap();
983        let requests = model.requests();
984        assert_eq!(requests.len(), 2);
985        let sent: Vec<Value> = requests[1]
986            .contents
987            .iter()
988            .flat_map(|c| c.parts.iter())
989            .filter_map(|p| p.function_response.as_ref())
990            .filter(|fr| fr.name == "secure_action")
991            .map(|fr| Value::Object(fr.response.clone()))
992            .collect();
993        assert_eq!(sent, vec![want]);
994        let counters = state.scoped_failure_counters.lock();
995        assert!(
996            counters.values().all(|m| m.values().all(|&n| n == 0)),
997            "{counters:?}"
998        );
999    }
1000}