Skip to main content

gadk_agent/
error.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//! Agent and tool errors, and the agent event stream type. The `Display` texts of the wrapping
17//! and limit errors match the ADK error messages.
18
19use futures::stream::BoxStream;
20use gadk_model::ModelError;
21use gadk_session::compaction::CompactionError;
22use gadk_session::{Event, SessionError};
23
24/// Every agent's event stream; dropping it cancels the work it drives.
25pub type EventStream = BoxStream<'static, Result<Event, AgentError>>;
26
27/// Errors produced while running agents, callbacks, plugins and tools.
28#[non_exhaustive]
29#[derive(Debug, thiserror::Error)]
30pub enum AgentError {
31    /// A model call failed.
32    #[error(transparent)]
33    Model(#[from] ModelError),
34    /// A session service or state operation failed.
35    #[error(transparent)]
36    Session(#[from] SessionError),
37    /// An artifact service operation failed.
38    #[error(transparent)]
39    Artifact(#[from] gadk_artifact::ArtifactError),
40    /// A memory service operation failed.
41    #[error(transparent)]
42    Memory(#[from] gadk_memory::MemoryError),
43    /// A tool failed: `error tool "<name>" <source>`.
44    #[error("error tool {} {source}", crate::go_fmt::go_quote(.tool))]
45    Tool {
46        /// The tool's name.
47        tool: String,
48        /// The tool's error.
49        #[source]
50        source: ToolError,
51    },
52    /// A workflow error (carries `gadk_engine::WorkflowError`).
53    #[error(transparent)]
54    Workflow(Box<dyn std::error::Error + Send + Sync>),
55    /// The LLM call limit was exceeded: `max number of llm calls exceeded: limit is <n>`.
56    #[error("max number of llm calls exceeded: limit is {limit}")]
57    LlmCallsLimitExceeded {
58        /// The configured limit.
59        limit: i32,
60    },
61    /// The context was cancelled.
62    #[error("context canceled")]
63    Cancelled,
64    /// The context's deadline passed.
65    #[error("context deadline exceeded")]
66    DeadlineExceeded,
67    /// Invalid configuration; the message is shown as is.
68    #[error("{0}")]
69    Config(String),
70    /// Context compaction failed; the
71    /// turn's own events are already persisted.
72    #[error(transparent)]
73    Compaction(CompactionError),
74    /// Any other error.
75    #[error("{0}")]
76    Other(Box<dyn std::error::Error + Send + Sync>),
77}
78
79impl AgentError {
80    /// An [`AgentError::Other`] carrying `msg`.
81    pub fn other(msg: impl Into<String>) -> Self {
82        AgentError::Other(msg.into().into())
83    }
84
85    /// Whether this error, or any error it wraps,
86    /// is a [`CompactionError`].
87    pub fn is_compaction(&self) -> bool {
88        chain_any(self, &|e| {
89            e.is::<CompactionError>()
90                || matches!(
91                    e.downcast_ref::<AgentError>(),
92                    Some(AgentError::Compaction(_))
93                )
94        })
95    }
96}
97
98/// Whether `pred` holds for `err` or any error it wraps. Besides
99/// `source()`, it steps into the errors [`AgentError::Other`], [`AgentError::Workflow`] and
100/// [`ToolError::Execution`] carry as a plain field (their `source()` skips them).
101pub(crate) fn chain_any(
102    err: &AgentError,
103    pred: &dyn Fn(&(dyn std::error::Error + 'static)) -> bool,
104) -> bool {
105    let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(err);
106    while let Some(e) = cur {
107        if pred(e) {
108            return true;
109        }
110        match e.downcast_ref::<AgentError>() {
111            Some(AgentError::Other(inner) | AgentError::Workflow(inner)) => {
112                cur = Some(&**inner);
113                continue;
114            }
115            Some(AgentError::Tool {
116                source: ToolError::Execution(inner),
117                ..
118            }) => {
119                cur = Some(&**inner);
120                continue;
121            }
122            _ => {}
123        }
124        if let Some(ToolError::Execution(inner)) = e.downcast_ref::<ToolError>() {
125            cur = Some(&**inner);
126            continue;
127        }
128        cur = e.source();
129    }
130    false
131}
132
133/// Errors produced by tools.
134#[non_exhaustive]
135#[derive(Debug, thiserror::Error)]
136pub enum ToolError {
137    /// A tool that requires confirmation was called without one.
138    #[error("requires confirmation, please approve or reject")]
139    ConfirmationRequired,
140    /// The user rejected the tool call.
141    #[error("call is rejected")]
142    ConfirmationRejected,
143    /// Invalid arguments or tool usage; the message is shown as is.
144    #[error("{0}")]
145    InvalidArgument(String),
146    /// A tool panicked; the text describes the panic.
147    #[error("{0}")]
148    Panic(String),
149    /// The tool's own execution failed.
150    #[error(transparent)]
151    Execution(Box<dyn std::error::Error + Send + Sync>),
152}
153
154/// A shared [`ToolError`] carried as an error value, for callbacks that hand the original tool
155/// error back unchanged (e.g. as `AgentError::Other(Box::new(SharedToolError(err)))`).
156/// Display-transparent: it writes the tool error's text, and
157/// `source()` is the tool error's own source. The `Arc` is kept, so callers can check identity
158/// with `Arc::ptr_eq` after a downcast.
159#[derive(Debug, Clone)]
160pub struct SharedToolError(pub std::sync::Arc<ToolError>);
161
162impl std::fmt::Display for SharedToolError {
163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164        std::fmt::Display::fmt(&*self.0, f)
165    }
166}
167
168impl std::error::Error for SharedToolError {
169    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
170        std::error::Error::source(&*self.0)
171    }
172}
173
174/// Prefixes an error: Display `"<msg>: <source>"`, `source()` = the wrapped error.
175#[derive(Debug)]
176pub(crate) struct Wrapped {
177    msg: String,
178    source: AgentError,
179}
180
181impl std::fmt::Display for Wrapped {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        write!(f, "{}: {}", self.msg, self.source)
184    }
185}
186
187impl std::error::Error for Wrapped {
188    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
189        Some(&self.source)
190    }
191}
192
193/// Wraps `source` with the prefix `msg`, as `"<msg>: <source>"`.
194pub(crate) fn wrap(msg: impl Into<String>, source: AgentError) -> AgentError {
195    AgentError::Other(Box::new(Wrapped {
196        msg: msg.into(),
197        source,
198    }))
199}
200
201#[cfg(test)]
202#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
203mod tests {
204    use gadk_session::compaction::CompactionError;
205
206    use super::*;
207
208    #[test]
209    fn compaction_error_displays_go_text_and_is_compaction() {
210        let e = AgentError::Compaction(CompactionError::new("post-invocation: boom"));
211        assert_eq!(
212            e.to_string(),
213            "context compaction failed: post-invocation: boom"
214        );
215        assert!(e.to_string().starts_with("context compaction failed: "));
216        assert!(e.is_compaction());
217    }
218
219    #[test]
220    fn shared_tool_error_is_display_transparent_and_keeps_the_arc() {
221        use std::error::Error as _;
222        use std::sync::Arc;
223
224        let plain = Arc::new(ToolError::InvalidArgument("bad args".into()));
225        let shared = SharedToolError(plain.clone());
226        assert_eq!(shared.to_string(), "bad args");
227        assert!(shared.source().is_none(), "InvalidArgument has no source");
228
229        // Execution is transparent, so the source is the boxed error's own source.
230        let inner = Wrapped {
231            msg: "outer".into(),
232            source: AgentError::other("root cause"),
233        };
234        let exec = Arc::new(ToolError::Execution(Box::new(inner)));
235        let shared_exec = SharedToolError(exec.clone());
236        assert_eq!(shared_exec.to_string(), "outer: root cause");
237        assert_eq!(
238            shared_exec.source().map(|s| s.to_string()).as_deref(),
239            Some("root cause")
240        );
241
242        // Boxed as an AgentError, the original Arc is recoverable for an identity check.
243        let agent_err = AgentError::Other(Box::new(SharedToolError(plain.clone())));
244        assert_eq!(agent_err.to_string(), "bad args");
245        let AgentError::Other(boxed) = &agent_err else {
246            panic!("not Other: {agent_err:?}")
247        };
248        let got = boxed.downcast_ref::<SharedToolError>().unwrap();
249        assert!(Arc::ptr_eq(&got.0, &plain));
250        assert!(!Arc::ptr_eq(&got.0, &exec));
251        let cloned = shared.clone();
252        assert!(Arc::ptr_eq(&cloned.0, &shared.0));
253    }
254
255    #[test]
256    fn is_compaction_walks_the_chain() {
257        // Wrapped by Go-style fmt.Errorf("…: %w") (Wrapped's source is the AgentError).
258        let wrapped = wrap("outer", AgentError::Compaction(CompactionError::new("x")));
259        assert!(wrapped.is_compaction());
260        // Boxed inside Other / Workflow.
261        assert!(AgentError::Other(Box::new(CompactionError::new("x"))).is_compaction());
262        assert!(AgentError::Workflow(Box::new(CompactionError::new("x"))).is_compaction());
263        // Not a compaction failure.
264        assert!(!AgentError::other("context compaction failed: lookalike").is_compaction());
265        assert!(!AgentError::Cancelled.is_compaction());
266        assert!(!wrap("outer", AgentError::Cancelled).is_compaction());
267    }
268}