1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum AgentError {
5 #[error("LLM call failed: {0}")]
6 Llm(String),
7
8 #[error("LLM API error: {message}")]
9 LlmApi { message: String },
10
11 #[error("LLM rate limit exceeded")]
12 RateLimitExceeded,
13
14 #[error("LLM service unavailable: {0}")]
15 ServiceUnavailable(String),
16
17 #[error("SSE stream error: {0}")]
18 LlmStream(String),
19
20 #[error("JSON parse error: {0}")]
21 Json(String),
22
23 #[error("Tool '{name}' not registered")]
24 ToolNotFound { name: String },
25
26 #[error("Tool '{name}' argument parsing failed: {raw}")]
27 ToolArgsInvalid { name: String, raw: String },
28
29 #[error("Tool '{name}' execution failed: {source}")]
30 ToolExecution {
31 name: String,
32 #[source]
33 source: Box<AgentError>,
34 },
35
36 #[error("Tool timeout exceeded")]
37 ToolTimeout,
38
39 #[error("Tool '{name}' output exceeds the {max_chars}-char limit")]
40 ToolOutputTooLarge { name: String, max_chars: usize },
41
42 #[error("Tool call rejected by approval: {tool_name}")]
43 ApprovalDenied { tool_name: String },
44
45 #[error("Tool call blocked: {0}")]
46 ToolBlocked(String),
47
48 #[error("Session {0} not found")]
49 SessionNotFound(u64),
50
51 #[error("Max turns ({limit}) reached, stopping forcibly")]
52 MaxTurnsExceeded { limit: u32 },
53
54 #[error("Operation cancelled")]
55 Cancelled,
56
57 #[error("Resource unavailable: {0}")]
58 ResourceUnavailable(String),
59
60 #[error("Configuration error: {0}")]
61 ConfigError(String),
62
63 #[error("{0}")]
66 Checkpoint(String),
67
68 #[error("Internal error: {0}")]
69 Internal(String),
70}
71
72impl AgentError {
73 pub fn llm(message: impl Into<String>) -> Self {
74 Self::Llm(message.into())
75 }
76
77 pub fn json(message: impl Into<String>) -> Self {
78 Self::Json(message.into())
79 }
80
81 pub fn internal(message: impl Into<String>) -> Self {
82 Self::Internal(message.into())
83 }
84
85 pub fn tool_not_found(name: impl Into<String>) -> Self {
86 Self::ToolNotFound { name: name.into() }
87 }
88
89 pub fn session_not_found(id: u64) -> Self {
90 Self::SessionNotFound(id)
91 }
92
93 pub fn tool_timeout() -> Self {
94 Self::ToolTimeout
95 }
96
97 pub fn rate_limit_exceeded() -> Self {
98 Self::RateLimitExceeded
99 }
100
101 pub fn service_unavailable(message: impl Into<String>) -> Self {
102 Self::ServiceUnavailable(message.into())
103 }
104
105 pub fn resource_unavailable(message: impl Into<String>) -> Self {
106 Self::ResourceUnavailable(message.into())
107 }
108
109 pub fn config_error(message: impl Into<String>) -> Self {
110 Self::ConfigError(message.into())
111 }
112
113 pub fn is_cancelled(&self) -> bool {
114 matches!(self, Self::Cancelled)
115 }
116
117 pub fn is_retryable(&self) -> bool {
118 matches!(
119 self,
120 Self::Llm(_)
121 | Self::LlmApi { .. }
122 | Self::LlmStream(_)
123 | Self::ServiceUnavailable(_)
124 | Self::RateLimitExceeded
125 )
126 }
127
128 pub fn is_rate_limited(&self) -> bool {
129 matches!(self, Self::RateLimitExceeded)
130 }
131
132 pub fn is_resource_unavailable(&self) -> bool {
133 matches!(self, Self::ResourceUnavailable(_))
134 }
135
136 pub fn kind(&self) -> ErrorKind {
138 match self {
139 Self::ToolExecution { name, .. } => ErrorKind::ToolCallFailed {
140 tool_name: name.clone(),
141 },
142 Self::ToolNotFound { .. } => ErrorKind::ToolNotFound,
143 Self::ToolArgsInvalid { .. } => ErrorKind::ToolArgsInvalid,
144 Self::ToolTimeout => ErrorKind::ToolTimeout,
145 Self::ToolOutputTooLarge { name, .. } => ErrorKind::ToolCallFailed {
146 tool_name: name.clone(),
147 },
148 Self::ServiceUnavailable(_) => ErrorKind::ModelOverloaded,
149 Self::RateLimitExceeded => ErrorKind::RateLimited,
150 Self::Cancelled => ErrorKind::Cancelled,
151 Self::Llm(_) | Self::LlmApi { .. } | Self::LlmStream(_) => ErrorKind::ModelOverloaded,
153 _ => ErrorKind::Internal,
155 }
156 }
157}
158
159impl From<std::io::Error> for AgentError {
162 fn from(e: std::io::Error) -> Self {
163 AgentError::internal(e.to_string())
164 }
165}
166
167impl From<serde_json::Error> for AgentError {
168 fn from(e: serde_json::Error) -> Self {
169 AgentError::json(e.to_string())
170 }
171}
172
173impl From<llm_trait::LlmError> for AgentError {
174 fn from(e: llm_trait::LlmError) -> Self {
175 match e {
176 llm_trait::LlmError::Config(msg) => AgentError::ConfigError(msg),
177 llm_trait::LlmError::LlmApi { status, message } => {
178 if status == 429 {
179 AgentError::RateLimitExceeded
180 } else if status >= 500 {
181 AgentError::ServiceUnavailable(format!("HTTP {status}: {message}"))
182 } else {
183 AgentError::LlmApi {
184 message: format!("HTTP {status}: {message}"),
185 }
186 }
187 }
188 llm_trait::LlmError::Llm(msg) => AgentError::Llm(msg),
189 llm_trait::LlmError::Stream(msg) => AgentError::LlmStream(msg),
190 }
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
200pub enum ErrorKind {
201 ToolCallFailed { tool_name: String },
203 ToolNotFound,
205 ToolArgsInvalid,
207 ToolTimeout,
209 ModelOverloaded,
211 RateLimited,
213 Cancelled,
215 Internal,
217}
218
219impl std::fmt::Display for ErrorKind {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 match self {
222 Self::ToolCallFailed { tool_name } => write!(f, "tool call failed: {tool_name}"),
223 Self::ToolNotFound => write!(f, "tool not found"),
224 Self::ToolArgsInvalid => write!(f, "tool args invalid"),
225 Self::ToolTimeout => write!(f, "tool timeout"),
226 Self::ModelOverloaded => write!(f, "model overloaded"),
227 Self::RateLimited => write!(f, "rate limited"),
228 Self::Cancelled => write!(f, "cancelled"),
229 Self::Internal => write!(f, "internal error"),
230 }
231 }
232}
233
234pub type AgentResult<T> = Result<T, AgentError>;
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[test]
241 fn kind_tool_execution() {
242 let err = AgentError::ToolExecution {
243 name: "my_tool".to_string(),
244 source: Box::new(AgentError::internal("boom")),
245 };
246 assert_eq!(
247 err.kind(),
248 ErrorKind::ToolCallFailed {
249 tool_name: "my_tool".to_string()
250 }
251 );
252 }
253
254 #[test]
255 fn kind_tool_not_found() {
256 let err = AgentError::tool_not_found("missing");
257 assert_eq!(err.kind(), ErrorKind::ToolNotFound);
258 }
259
260 #[test]
261 fn kind_tool_args_invalid() {
262 let err = AgentError::ToolArgsInvalid {
263 name: "t".to_string(),
264 raw: "bad".to_string(),
265 };
266 assert_eq!(err.kind(), ErrorKind::ToolArgsInvalid);
267 }
268
269 #[test]
270 fn kind_tool_timeout() {
271 let err = AgentError::tool_timeout();
272 assert_eq!(err.kind(), ErrorKind::ToolTimeout);
273 }
274
275 #[test]
276 fn kind_service_unavailable() {
277 let err = AgentError::service_unavailable("overloaded");
278 assert_eq!(err.kind(), ErrorKind::ModelOverloaded);
279 }
280
281 #[test]
282 fn kind_rate_limit() {
283 let err = AgentError::rate_limit_exceeded();
284 assert_eq!(err.kind(), ErrorKind::RateLimited);
285 }
286
287 #[test]
288 fn kind_llm_maps_to_overloaded() {
289 let err = AgentError::llm("connection refused");
290 assert_eq!(err.kind(), ErrorKind::ModelOverloaded);
291 }
292
293 #[test]
294 fn kind_llm_api_maps_to_overloaded() {
295 let err = AgentError::LlmApi {
296 message: "529".to_string(),
297 };
298 assert_eq!(err.kind(), ErrorKind::ModelOverloaded);
299 }
300
301 #[test]
302 fn kind_llm_stream_maps_to_overloaded() {
303 let err = AgentError::LlmStream("stream broken".to_string());
304 assert_eq!(err.kind(), ErrorKind::ModelOverloaded);
305 }
306
307 #[test]
308 fn kind_cancelled() {
309 assert_eq!(AgentError::Cancelled.kind(), ErrorKind::Cancelled);
310 }
311
312 #[test]
313 fn kind_internal_fallback() {
314 let err = AgentError::internal("something");
315 assert_eq!(err.kind(), ErrorKind::Internal);
316
317 let err = AgentError::config_error("bad config");
318 assert_eq!(err.kind(), ErrorKind::Internal);
319 }
320
321 #[test]
322 fn error_kind_display() {
323 assert_eq!(
324 ErrorKind::ToolCallFailed {
325 tool_name: "t".to_string()
326 }
327 .to_string(),
328 "tool call failed: t"
329 );
330 assert_eq!(ErrorKind::ToolNotFound.to_string(), "tool not found");
331 assert_eq!(ErrorKind::ModelOverloaded.to_string(), "model overloaded");
332 assert_eq!(ErrorKind::RateLimited.to_string(), "rate limited");
333 }
334
335 #[test]
338 fn from_io_error_maps_to_internal() {
339 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
340 let agent_err: AgentError = io_err.into();
341 assert!(matches!(agent_err, AgentError::Internal(_)));
342 assert!(agent_err.to_string().contains("file missing"));
343 }
344
345 #[test]
346 fn from_serde_json_error_maps_to_json() {
347 let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
348 let agent_err: AgentError = json_err.into();
349 assert!(matches!(agent_err, AgentError::Json(_)));
350 }
351
352 #[test]
355 fn from_impls_work_with_try_operator() -> AgentResult<()> {
356 fn read_file() -> AgentResult<String> {
358 let _ = std::fs::read_to_string("/nonexistent/path")?;
359 unreachable!()
360 }
361 assert!(read_file().is_err());
362
363 fn parse_json() -> AgentResult<serde_json::Value> {
365 let v: serde_json::Value = serde_json::from_str("bad json")?;
366 Ok(v)
367 }
368 assert!(parse_json().is_err());
369
370 Ok(())
371 }
372}