1use futures::stream::BoxStream;
20use gadk_model::ModelError;
21use gadk_session::compaction::CompactionError;
22use gadk_session::{Event, SessionError};
23
24pub type EventStream = BoxStream<'static, Result<Event, AgentError>>;
26
27#[non_exhaustive]
29#[derive(Debug, thiserror::Error)]
30pub enum AgentError {
31 #[error(transparent)]
33 Model(#[from] ModelError),
34 #[error(transparent)]
36 Session(#[from] SessionError),
37 #[error(transparent)]
39 Artifact(#[from] gadk_artifact::ArtifactError),
40 #[error(transparent)]
42 Memory(#[from] gadk_memory::MemoryError),
43 #[error("error tool {} {source}", crate::go_fmt::go_quote(.tool))]
45 Tool {
46 tool: String,
48 #[source]
50 source: ToolError,
51 },
52 #[error(transparent)]
54 Workflow(Box<dyn std::error::Error + Send + Sync>),
55 #[error("max number of llm calls exceeded: limit is {limit}")]
57 LlmCallsLimitExceeded {
58 limit: i32,
60 },
61 #[error("context canceled")]
63 Cancelled,
64 #[error("context deadline exceeded")]
66 DeadlineExceeded,
67 #[error("{0}")]
69 Config(String),
70 #[error(transparent)]
73 Compaction(CompactionError),
74 #[error("{0}")]
76 Other(Box<dyn std::error::Error + Send + Sync>),
77}
78
79impl AgentError {
80 pub fn other(msg: impl Into<String>) -> Self {
82 AgentError::Other(msg.into().into())
83 }
84
85 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
98pub(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#[non_exhaustive]
135#[derive(Debug, thiserror::Error)]
136pub enum ToolError {
137 #[error("requires confirmation, please approve or reject")]
139 ConfirmationRequired,
140 #[error("call is rejected")]
142 ConfirmationRejected,
143 #[error("{0}")]
145 InvalidArgument(String),
146 #[error("{0}")]
148 Panic(String),
149 #[error(transparent)]
151 Execution(Box<dyn std::error::Error + Send + Sync>),
152}
153
154#[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#[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
193pub(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 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 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 let wrapped = wrap("outer", AgentError::Compaction(CompactionError::new("x")));
259 assert!(wrapped.is_compaction());
260 assert!(AgentError::Other(Box::new(CompactionError::new("x"))).is_compaction());
262 assert!(AgentError::Workflow(Box::new(CompactionError::new("x"))).is_compaction());
263 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}