Skip to main content

gadk_engine/tool/
exit_loop.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//! The `exit_loop` tool.
17
18use std::any::Any;
19use std::collections::BTreeMap;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use gadk_agent::{Context, RunnableTool, Tool, ToolError};
24use schemars::JsonSchema;
25use serde::Deserialize;
26use serde_json::{Map, Value};
27
28use crate::tool::{FunctionTool, FunctionToolConfig};
29
30// Empty args struct. A plain comment: a doc comment would become the schema's `description`,
31// which this empty-struct schema does not have.
32#[derive(Deserialize, JsonSchema)]
33struct ExitLoopArgs {}
34
35/// A tool that sets `escalate` and `skip_summarization` on the
36/// calling tool context's actions, ending the enclosing loop.
37///
38/// Construction can fail only if schema inference fails for
39/// these fixed types, which it never does, so this signature is infallible and the impossible
40/// error is surfaced at call time instead of panicking.
41pub fn exit_loop() -> Arc<dyn Tool> {
42    let built = FunctionTool::new(
43        FunctionToolConfig::new(
44            "exit_loop",
45            "Exits the loop.\n\nCall this function only when you are instructed to do so.\n",
46        ),
47        |ctx: Context, _args: ExitLoopArgs| async move {
48            ctx.update_actions(|a| {
49                a.escalate = true;
50                a.skip_summarization = true;
51            });
52            // A Rust result map cannot be nil, so the empty map stands in for "nothing": the
53            // flow wraps a tool's empty result as {"result": null}.
54            Ok::<_, ToolError>(BTreeMap::<String, String>::new())
55        },
56    );
57    match built {
58        Ok(t) => t,
59        Err(e) => Arc::new(UnavailableExitLoop(format!(
60            "error creating exit loop tool: {e}"
61        ))),
62    }
63}
64
65/// Stand-in returned only if FunctionTool construction failed; every run reports the
66/// construction error.
67struct UnavailableExitLoop(String);
68
69impl Tool for UnavailableExitLoop {
70    fn name(&self) -> &str {
71        "exit_loop"
72    }
73
74    fn description(&self) -> &str {
75        &self.0
76    }
77
78    fn as_runnable(&self) -> Option<&dyn RunnableTool> {
79        Some(self)
80    }
81
82    fn as_any(&self) -> &dyn Any {
83        self
84    }
85}
86
87#[async_trait]
88impl RunnableTool for UnavailableExitLoop {
89    async fn run(&self, _ctx: Context, _args: Value) -> Result<Map<String, Value>, ToolError> {
90        Err(ToolError::Execution(self.0.clone().into()))
91    }
92}
93
94#[cfg(test)]
95#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
96mod tests {
97    use super::*;
98    use serde_json::json;
99
100    #[tokio::test]
101    async fn exit_loop_sets_escalate_and_skip_summarization() {
102        let t = exit_loop();
103        assert_eq!(t.name(), "exit_loop");
104        assert_eq!(
105            t.description(),
106            "Exits the loop.\n\nCall this function only when you are instructed to do so.\n"
107        );
108        // A tool context that owns its actions (Go NewToolContext: a function_call_id delta
109        // allocates them), so the escalate/skip_summarization writes are observable.
110        let ctx = Context::builder()
111            .build()
112            .with_delta(gadk_agent::ContextDelta {
113                function_call_id: Some("call".into()),
114                ..Default::default()
115            });
116        let out = t
117            .as_runnable()
118            .unwrap()
119            .run(ctx.clone(), json!({}))
120            .await
121            .unwrap();
122        assert!(out.is_empty());
123        let actions = ctx.actions();
124        assert!(actions.escalate && actions.skip_summarization);
125    }
126}