1use core::fmt;
4use std::borrow::Cow;
5
6use aither_core::llm::{Classify, Failure};
7
8#[derive(Debug, Clone)]
10#[non_exhaustive]
11pub enum AgentError {
12 Llm {
14 message: String,
16 failure: Failure,
20 },
21
22 ToolExecution {
24 name: String,
26 error: String,
28 },
29
30 MaxIterations {
32 limit: usize,
34 },
35
36 HookRejected {
38 hook: Cow<'static, str>,
40 reason: String,
42 },
43
44 ToolNotFound {
46 name: String,
48 },
49
50 Config(String),
52
53 Approval(std::sync::Arc<aither_core::llm::tool::ApprovalError>),
57
58 Cancelled,
65
66 Paused(crate::RunPause),
71}
72
73impl fmt::Display for AgentError {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 Self::Llm { message, .. } => write!(f, "LLM error: {message}"),
77 Self::ToolExecution { name, error } => {
78 write!(f, "tool '{name}' failed: {error}")
79 }
80 Self::MaxIterations { limit } => {
81 write!(f, "exceeded maximum iterations ({limit})")
82 }
83 Self::HookRejected { hook, reason } => {
84 write!(f, "hook '{hook}' rejected: {reason}")
85 }
86 Self::ToolNotFound { name } => {
87 write!(f, "tool '{name}' not found")
88 }
89 Self::Config(msg) => write!(f, "configuration error: {msg}"),
90 Self::Approval(error) => write!(f, "{error}"),
91 Self::Cancelled => f.write_str("the run was cancelled"),
92 Self::Paused(pause) => write!(f, "the run paused: {pause:?}"),
93 }
94 }
95}
96
97impl std::error::Error for AgentError {}
98
99impl AgentError {
100 pub fn from_model_error<E: std::error::Error + Classify>(error: &E) -> Self {
102 Self::Llm {
103 message: error.to_string(),
104 failure: error.failure(),
105 }
106 }
107
108 pub fn llm_local(message: impl Into<String>) -> Self {
111 Self::Llm {
112 message: message.into(),
113 failure: Failure::permanent(),
114 }
115 }
116
117 #[must_use]
123 pub const fn failure(&self) -> Option<&Failure> {
124 match self {
125 Self::Llm { failure, .. } => Some(failure),
126 _ => None,
127 }
128 }
129}
130
131impl From<anyhow::Error> for AgentError {
132 fn from(error: anyhow::Error) -> Self {
133 Self::llm_local(error.to_string())
134 }
135}
136
137impl From<String> for AgentError {
138 fn from(error: String) -> Self {
139 Self::llm_local(error)
140 }
141}
142
143impl From<crate::context::CompactionError> for AgentError {
144 fn from(error: crate::context::CompactionError) -> Self {
145 use crate::context::CompactionError;
146 let failure = match &error {
147 CompactionError::Provider { failure, .. } => *failure,
148 CompactionError::Invalid { .. } | CompactionError::Empty => Failure::permanent(),
149 };
150 Self::Llm {
151 message: error.to_string(),
152 failure,
153 }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use std::time::Duration;
160
161 use aither_core::llm::{Classify, Failure, FailureKind};
162
163 use super::AgentError;
164
165 #[derive(Debug)]
166 struct Overloaded;
167
168 impl std::fmt::Display for Overloaded {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 f.write_str("overloaded")
171 }
172 }
173
174 impl std::error::Error for Overloaded {}
175
176 impl Classify for Overloaded {
177 fn failure(&self) -> Failure {
178 Failure::transient().with_retry_after(Some(Duration::from_secs(5)))
179 }
180 }
181
182 #[test]
183 fn provider_failure_is_carried() {
184 let error = AgentError::from_model_error(&Overloaded);
185 assert_eq!(error.to_string(), "LLM error: overloaded");
186 let failure = error.failure().expect("an LLM error carries a failure");
187 assert_eq!(failure.kind, FailureKind::Transient);
188 assert_eq!(failure.retry_after, Some(Duration::from_secs(5)));
189 }
190
191 #[test]
192 fn non_llm_errors_have_no_failure() {
193 assert!(AgentError::Config("x".into()).failure().is_none());
194 assert_eq!(
195 AgentError::llm_local("x").failure().map(|f| f.kind),
196 Some(FailureKind::Permanent)
197 );
198 }
199}
200
201#[cfg(feature = "serde")]
206#[derive(serde::Serialize, serde::Deserialize)]
207enum AgentErrorRepr {
208 Llm {
209 message: String,
210 failure: Failure,
211 },
212 ToolExecution {
213 name: String,
214 error: String,
215 },
216 MaxIterations {
217 limit: usize,
218 },
219 HookRejected {
220 hook: String,
221 reason: String,
222 },
223 ToolNotFound {
224 name: String,
225 },
226 Config(String),
227 ApprovalNoApprover {
228 kind: aither_core::llm::tool::ApprovalKind,
229 },
230 ApprovalFailed {
231 kind: aither_core::llm::tool::ApprovalKind,
232 message: String,
233 },
234 ApprovalCancelled,
235 Cancelled,
236 Paused(crate::RunPause),
237}
238
239#[cfg(feature = "serde")]
240impl From<&AgentError> for AgentErrorRepr {
241 fn from(error: &AgentError) -> Self {
242 use aither_core::llm::tool::ApprovalError;
243 match error {
244 AgentError::Llm { message, failure } => Self::Llm {
245 message: message.clone(),
246 failure: *failure,
247 },
248 AgentError::ToolExecution { name, error } => Self::ToolExecution {
249 name: name.clone(),
250 error: error.clone(),
251 },
252 AgentError::MaxIterations { limit } => Self::MaxIterations { limit: *limit },
253 AgentError::HookRejected { hook, reason } => Self::HookRejected {
254 hook: hook.to_string(),
255 reason: reason.clone(),
256 },
257 AgentError::ToolNotFound { name } => Self::ToolNotFound { name: name.clone() },
258 AgentError::Config(message) => Self::Config(message.clone()),
259 AgentError::Approval(approval) => match &**approval {
260 ApprovalError::NoApprover { kind } => {
261 Self::ApprovalNoApprover { kind: kind.clone() }
262 }
263 ApprovalError::Failed { kind, failure } => Self::ApprovalFailed {
264 kind: kind.clone(),
265 message: std::error::Error::source(failure)
266 .map_or_else(|| failure.to_string(), ToString::to_string),
267 },
268 ApprovalError::Cancelled => Self::ApprovalCancelled,
269 },
270 AgentError::Cancelled => Self::Cancelled,
271 AgentError::Paused(pause) => Self::Paused(*pause),
272 }
273 }
274}
275
276#[cfg(feature = "serde")]
277impl From<AgentErrorRepr> for AgentError {
278 fn from(repr: AgentErrorRepr) -> Self {
279 use aither_core::llm::tool::{ApprovalError, ApproverFailure};
280 let approval = |error| Self::Approval(std::sync::Arc::new(error));
281 match repr {
282 AgentErrorRepr::Llm { message, failure } => Self::Llm { message, failure },
283 AgentErrorRepr::ToolExecution { name, error } => Self::ToolExecution { name, error },
284 AgentErrorRepr::MaxIterations { limit } => Self::MaxIterations { limit },
285 AgentErrorRepr::HookRejected { hook, reason } => Self::HookRejected {
286 hook: hook.into(),
287 reason,
288 },
289 AgentErrorRepr::ToolNotFound { name } => Self::ToolNotFound { name },
290 AgentErrorRepr::Config(message) => Self::Config(message),
291 AgentErrorRepr::ApprovalNoApprover { kind } => {
292 approval(ApprovalError::NoApprover { kind })
293 }
294 AgentErrorRepr::ApprovalFailed { kind, message } => approval(ApprovalError::Failed {
295 kind,
296 failure: ApproverFailure::new(std::io::Error::other(message)),
297 }),
298 AgentErrorRepr::ApprovalCancelled => approval(ApprovalError::Cancelled),
299 AgentErrorRepr::Cancelled => Self::Cancelled,
300 AgentErrorRepr::Paused(pause) => Self::Paused(pause),
301 }
302 }
303}
304
305#[cfg(feature = "serde")]
306impl serde::Serialize for AgentError {
307 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
308 AgentErrorRepr::from(self).serialize(serializer)
309 }
310}
311
312#[cfg(feature = "serde")]
313impl<'de> serde::Deserialize<'de> for AgentError {
314 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
315 AgentErrorRepr::deserialize(deserializer).map(Self::from)
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
325#[error("tool '{name}' panicked: {message}")]
326pub struct ToolPanic {
327 pub name: String,
329 pub message: String,
331}
332
333impl ToolPanic {
334 pub(crate) fn caught(name: &str, payload: &(dyn std::any::Any + Send)) -> Self {
336 let message = payload
337 .downcast_ref::<&str>()
338 .map(|message| (*message).to_owned())
339 .or_else(|| payload.downcast_ref::<String>().cloned())
340 .unwrap_or_else(|| "the panic payload is not a string".to_owned());
341 Self {
342 name: name.to_owned(),
343 message,
344 }
345 }
346}