1#![expect(
2 clippy::let_underscore_must_use,
3 reason = "The category formatter intentionally ignores infallible formatting results."
4)]
5
6use std::borrow::Cow;
27use std::fmt;
28use std::fmt::Write;
29use std::time::Duration;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
34pub enum ErrorCategory {
35 Network,
38 Timeout,
40 RateLimit,
42 ServiceUnavailable,
44 CircuitOpen,
46
47 Authentication,
50 InvalidParameters,
52 ToolNotFound,
54 ResourceNotFound,
56 PermissionDenied,
58 PolicyViolation,
60 PlanningPolicyViolation,
62 SandboxFailure,
64 ResourceExhausted,
66 Cancelled,
68 ExecutionError,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum Retryability {
75 Retryable {
77 max_attempts: u32,
79 backoff: BackoffStrategy,
81 },
82 NonRetryable,
84 RequiresIntervention,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum BackoffStrategy {
91 Exponential { base: Duration, max: Duration },
93 Fixed(Duration),
95}
96
97impl ErrorCategory {
98 #[inline]
103 #[must_use]
104 pub const fn as_str(&self) -> &'static str {
105 self.user_label()
106 }
107
108 #[inline]
110 #[must_use]
111 pub const fn is_retryable(&self) -> bool {
112 matches!(
113 self,
114 ErrorCategory::Network
115 | ErrorCategory::Timeout
116 | ErrorCategory::RateLimit
117 | ErrorCategory::ServiceUnavailable
118 | ErrorCategory::CircuitOpen
119 )
120 }
121
122 #[inline]
124 #[must_use]
125 pub const fn should_trip_circuit_breaker(&self) -> bool {
126 matches!(
127 self,
128 ErrorCategory::Network
129 | ErrorCategory::Timeout
130 | ErrorCategory::RateLimit
131 | ErrorCategory::ServiceUnavailable
132 | ErrorCategory::ExecutionError
133 )
134 }
135
136 #[inline]
139 #[must_use]
140 const fn is_llm_mistake(&self) -> bool {
141 matches!(self, ErrorCategory::InvalidParameters)
142 }
143
144 #[inline]
146 #[must_use]
147 pub const fn is_permanent(&self) -> bool {
148 matches!(
149 self,
150 ErrorCategory::Authentication
151 | ErrorCategory::PolicyViolation
152 | ErrorCategory::PlanningPolicyViolation
153 | ErrorCategory::ResourceExhausted
154 )
155 }
156
157 #[must_use]
159 pub fn retryability(&self) -> Retryability {
160 match self {
161 ErrorCategory::Network | ErrorCategory::ServiceUnavailable => Retryability::Retryable {
162 max_attempts: 3,
163 backoff: BackoffStrategy::Exponential {
164 base: Duration::from_millis(500),
165 max: Duration::from_secs(10),
166 },
167 },
168 ErrorCategory::Timeout => Retryability::Retryable {
169 max_attempts: 2,
170 backoff: BackoffStrategy::Exponential {
171 base: Duration::from_millis(1000),
172 max: Duration::from_secs(15),
173 },
174 },
175 ErrorCategory::RateLimit => Retryability::Retryable {
176 max_attempts: 3,
177 backoff: BackoffStrategy::Exponential {
178 base: Duration::from_secs(1),
179 max: Duration::from_secs(30),
180 },
181 },
182 ErrorCategory::CircuitOpen => Retryability::Retryable {
183 max_attempts: 1,
184 backoff: BackoffStrategy::Fixed(Duration::from_secs(10)),
185 },
186 ErrorCategory::PermissionDenied => Retryability::RequiresIntervention,
187 _ => Retryability::NonRetryable,
188 }
189 }
190
191 #[must_use]
194 pub fn recovery_suggestions(&self) -> Vec<Cow<'static, str>> {
195 match self {
196 ErrorCategory::Network => vec![
197 Cow::Borrowed("Check network connectivity"),
198 Cow::Borrowed("Retry the operation after a brief delay"),
199 Cow::Borrowed("Verify external service availability"),
200 ],
201 ErrorCategory::Timeout => vec![
202 Cow::Borrowed("Increase timeout values if appropriate"),
203 Cow::Borrowed("Break large operations into smaller chunks"),
204 Cow::Borrowed("Check system resources and performance"),
205 ],
206 ErrorCategory::RateLimit => vec![
207 Cow::Borrowed("Wait before retrying the request"),
208 Cow::Borrowed("Reduce request frequency"),
209 Cow::Borrowed("Check provider rate limit documentation"),
210 ],
211 ErrorCategory::ServiceUnavailable => vec![
212 Cow::Borrowed("The service is temporarily unavailable"),
213 Cow::Borrowed("Retry after a brief delay"),
214 Cow::Borrowed("Check service status page if available"),
215 ],
216 ErrorCategory::CircuitOpen => vec![
217 Cow::Borrowed("This tool has been temporarily disabled due to repeated failures"),
218 Cow::Borrowed("Wait for the circuit breaker cooldown period"),
219 Cow::Borrowed("Try an alternative approach"),
220 ],
221 ErrorCategory::Authentication => vec![
222 Cow::Borrowed("Verify your API key or credentials"),
223 Cow::Borrowed("Check that your account is active and has sufficient permissions"),
224 Cow::Borrowed("Ensure environment variables for API keys are set correctly"),
225 ],
226 ErrorCategory::InvalidParameters => vec![
227 Cow::Borrowed("Check parameter names and types against the tool schema"),
228 Cow::Borrowed("Ensure required parameters are provided"),
229 Cow::Borrowed("Verify parameter values are within acceptable ranges"),
230 ],
231 ErrorCategory::ToolNotFound => vec![
232 Cow::Borrowed("Verify the tool name is spelled correctly"),
233 Cow::Borrowed("Check if the tool is available in the current context"),
234 ],
235 ErrorCategory::ResourceNotFound => vec![
236 Cow::Borrowed("Verify file paths and resource locations"),
237 Cow::Borrowed("Check if files exist and are accessible"),
238 Cow::Borrowed("Use list_dir to explore available resources"),
239 ],
240 ErrorCategory::PermissionDenied => vec![
241 Cow::Borrowed("Check file permissions and access rights"),
242 Cow::Borrowed("Ensure workspace boundaries are respected"),
243 ],
244 ErrorCategory::PolicyViolation => vec![
245 Cow::Borrowed("Review workspace policies and restrictions"),
246 Cow::Borrowed("Use alternative tools that comply with policies"),
247 ],
248 ErrorCategory::PlanningPolicyViolation => vec![
249 Cow::Borrowed("This operation is not allowed in the Planning workflow with read-only permissions"),
250 Cow::Borrowed("Exit the Planning workflow to perform mutating operations"),
251 ],
252 ErrorCategory::SandboxFailure => vec![
253 Cow::Borrowed("The sandbox denied this operation"),
254 Cow::Borrowed("Check sandbox configuration and permissions"),
255 ],
256 ErrorCategory::ResourceExhausted => vec![
257 Cow::Borrowed("Check your account usage limits and billing status"),
258 Cow::Borrowed("Review resource consumption and optimize if possible"),
259 ],
260 ErrorCategory::Cancelled => vec![Cow::Borrowed("The operation was cancelled")],
261 ErrorCategory::ExecutionError => vec![
262 Cow::Borrowed("Review error details for specific issues"),
263 Cow::Borrowed("Check tool documentation for known limitations"),
264 ],
265 }
266 }
267
268 #[must_use]
270 pub const fn user_label(&self) -> &'static str {
271 match self {
272 ErrorCategory::Network => "Network error",
273 ErrorCategory::Timeout => "Request timed out",
274 ErrorCategory::RateLimit => "Rate limit exceeded",
275 ErrorCategory::ServiceUnavailable => "Service temporarily unavailable",
276 ErrorCategory::CircuitOpen => "Tool temporarily disabled",
277 ErrorCategory::Authentication => "Authentication failed",
278 ErrorCategory::InvalidParameters => "Invalid parameters",
279 ErrorCategory::ToolNotFound => "Tool not found",
280 ErrorCategory::ResourceNotFound => "Resource not found",
281 ErrorCategory::PermissionDenied => "Permission denied",
282 ErrorCategory::PolicyViolation => "Blocked by policy",
283 ErrorCategory::PlanningPolicyViolation => "Not allowed in planning workflow",
284 ErrorCategory::SandboxFailure => "Sandbox denied",
285 ErrorCategory::ResourceExhausted => "Resource limit reached",
286 ErrorCategory::Cancelled => "Operation cancelled",
287 ErrorCategory::ExecutionError => "Execution failed",
288 }
289 }
290
291 #[must_use]
301 pub fn auth_recovery_guidance(
302 &self,
303 provider_label: &str,
304 provider_key: &str,
305 is_managed_auth: bool,
306 has_stored_credential: bool,
307 ) -> Vec<String> {
308 if !matches!(self, ErrorCategory::Authentication) {
309 return vec![];
310 }
311
312 if is_managed_auth {
313 vec![format!(
314 "Authentication failed for {provider_label}. Run /login {provider_key} to re-authenticate."
315 )]
316 } else if has_stored_credential {
317 vec![format!(
318 "Authentication failed for {provider_label}. The stored API key was rejected — run /secret add {provider_key} to replace it with a valid key."
319 )]
320 } else {
321 vec![format!(
322 "Authentication failed for {provider_label}. Run /secret add {provider_key} to store your API key in secure storage (OS keyring or encrypted file)."
323 )]
324 }
325 }
326}
327
328impl fmt::Display for ErrorCategory {
329 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330 f.write_str(self.user_label())
331 }
332}
333
334#[must_use]
353pub fn classify_anyhow_error(err: &anyhow::Error) -> ErrorCategory {
354 let outer = classify_error_message(&err.to_string());
357 if outer != ErrorCategory::ExecutionError {
358 return outer;
359 }
360
361 if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
365 return ErrorCategory::from(llm_error);
366 }
367
368 for cause in err.chain().skip(1) {
369 let category = classify_error_message(&cause.to_string());
370 if category != ErrorCategory::ExecutionError {
371 return category;
372 }
373 }
374
375 ErrorCategory::ExecutionError
376}
377
378#[must_use]
387pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
388 err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
389}
390
391#[must_use]
393pub fn is_context_capacity_message(message: &str) -> bool {
394 let message = message.to_ascii_lowercase();
395 contains_any(
396 &message,
397 &[
398 "context_length_exceeded",
399 "context length exceeded",
400 "maximum context length",
401 "maximum context window",
402 "context window exceeded",
403 "context window is too small",
404 "exceeds the model's maximum context",
405 "exceeds model context",
406 "exceeds the maximum context",
407 "prompt is too long",
408 "input is too long",
409 "input token count exceeds",
410 "exceeds the maximum number of tokens",
411 "maximum input tokens",
412 "too many tokens in the prompt",
413 "request exceeds the context",
414 "context limit exceeded",
419 "context size exceeded",
420 "exceeds context",
421 "input tokens exceed",
422 "prompt tokens exceed",
423 "prompt token count exceeds",
424 "token limit exceeded",
425 "input too large",
426 "prompt too large",
427 ],
428 )
429}
430
431#[inline]
436#[must_use]
437pub fn classify_error_message(msg: &str) -> ErrorCategory {
438 let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
439 Cow::Owned(msg.to_ascii_lowercase())
440 } else {
441 Cow::Borrowed(msg)
442 };
443
444 if contains_any(
446 &msg,
447 &[
448 "policy violation",
449 "denied by policy",
450 "tool permission denied",
451 "safety validation failed",
452 "not allowed in planning workflow",
453 "only available when planning workflow is active",
454 "workspace boundary",
455 "blocked by policy",
456 ],
457 ) {
458 return ErrorCategory::PolicyViolation;
459 }
460
461 if contains_any(
463 &msg,
464 &[
465 "planning workflow",
466 "read-only permissions",
467 concat!("read-only ", "mode"),
468 "planning_policy_violation",
469 ],
470 ) {
471 return ErrorCategory::PlanningPolicyViolation;
472 }
473
474 if contains_any(
476 &msg,
477 &[
478 "invalid api key",
479 "authentication failed",
480 "unauthorized",
481 "401",
482 "invalid credentials",
483 ],
484 ) {
485 return ErrorCategory::Authentication;
486 }
487
488 if contains_any(
490 &msg,
491 &[
492 "weekly usage limit",
493 "daily usage limit",
494 "monthly spending limit",
495 "insufficient credits",
496 "quota exceeded",
497 "billing",
498 "payment required",
499 ],
500 ) {
501 return ErrorCategory::ResourceExhausted;
502 }
503
504 if contains_any(
506 &msg,
507 &[
508 "invalid argument",
509 "invalid parameters",
510 "invalid type",
511 "malformed",
512 "failed to parse arguments",
513 "failed to parse argument",
514 "missing required",
515 "at least one item is required",
516 "is required for",
517 "schema validation",
518 "argument validation failed",
519 "unknown field",
520 "unknown variant",
521 "expected struct",
522 "expected enum",
523 "type mismatch",
524 "must be an absolute path",
525 "not parseable",
526 "parseable as",
527 "invalid patch format",
535 "invalid patch hunk",
536 "invalid patch operation",
537 "cannot parse empty patch",
538 "patch does not contain",
539 "semantic patch anchor",
540 ],
541 ) {
542 return ErrorCategory::InvalidParameters;
543 }
544
545 if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
547 return ErrorCategory::ToolNotFound;
548 }
549
550 if contains_any(
552 &msg,
553 &[
554 "no such file",
555 "no such directory",
556 "file not found",
557 "directory not found",
558 "resource not found",
559 "path not found",
560 "does not exist",
561 "enoent",
562 ],
563 ) {
564 return ErrorCategory::ResourceNotFound;
565 }
566
567 if contains_any(
569 &msg,
570 &[
571 "permission denied",
572 "access denied",
573 "operation not permitted",
574 "eacces",
575 "eperm",
576 "forbidden",
577 "403",
578 ],
579 ) {
580 return ErrorCategory::PermissionDenied;
581 }
582
583 if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
585 return ErrorCategory::Cancelled;
586 }
587
588 if contains_any(&msg, &["circuit breaker", "circuit open"]) {
590 return ErrorCategory::CircuitOpen;
591 }
592
593 if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
595 return ErrorCategory::SandboxFailure;
596 }
597
598 if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
600 return ErrorCategory::RateLimit;
601 }
602
603 if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
605 return ErrorCategory::Timeout;
606 }
607
608 if contains_any(
610 &msg,
611 &[
612 "invalid response format: missing choices",
613 "invalid response format: missing message",
614 "missing choices in response",
615 "missing message in choice",
616 "no choices in response",
617 "invalid response from ",
618 "empty response body",
619 "response did not contain",
620 "unexpected response format",
621 "failed to parse response",
622 "stream disconnected",
628 "stream closed unexpectedly",
629 "incomplete stream",
630 "unexpected end of stream",
631 "truncated response",
632 "failed to decode stream",
633 "stream terminated",
634 ],
635 ) {
636 return ErrorCategory::ServiceUnavailable;
637 }
638
639 if contains_any(
641 &msg,
642 &[
643 "service unavailable",
644 "temporarily unavailable",
645 "internal server error",
646 "bad gateway",
647 "gateway timeout",
648 "overloaded",
649 "500",
650 "502",
651 "503",
652 "504",
653 ],
654 ) {
655 return ErrorCategory::ServiceUnavailable;
656 }
657
658 if contains_any(
660 &msg,
661 &[
662 "network",
663 "connection reset",
664 "connection refused",
665 "broken pipe",
666 "dns",
667 "name resolution",
668 "try again",
669 "retry later",
670 "upstream connect error",
671 "tls handshake",
672 "socket hang up",
673 "econnreset",
674 "etimedout",
675 "error decoding response body",
679 "connection closed before",
684 "stream reset",
685 "stream error received",
686 ],
687 ) {
688 return ErrorCategory::Network;
689 }
690
691 if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
693 return ErrorCategory::ResourceExhausted;
694 }
695
696 ErrorCategory::ExecutionError
698}
699
700#[inline]
705#[must_use]
706pub fn is_retryable_llm_error_message(msg: &str) -> bool {
707 let category = classify_error_message(msg);
708 category.is_retryable()
709}
710
711#[inline]
712fn contains_any(message: &str, markers: &[&str]) -> bool {
713 markers.iter().any(|marker| message.contains(marker))
714}
715
716impl From<&crate::llm::LLMError> for ErrorCategory {
721 fn from(err: &crate::llm::LLMError) -> Self {
722 match err {
723 crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
724 crate::llm::LLMError::RateLimit { metadata } => {
725 classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
726 }
727 crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
728 crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
729 crate::llm::LLMError::Provider { message, metadata } => {
730 let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
731 if metadata_category != ErrorCategory::ExecutionError {
732 return metadata_category;
733 }
734
735 if let Some(meta) = metadata
737 && let Some(status) = meta.status
738 {
739 return match status {
740 401 => ErrorCategory::Authentication,
741 403 => ErrorCategory::PermissionDenied,
742 404 => ErrorCategory::ResourceNotFound,
743 429 => ErrorCategory::RateLimit,
744 400 => ErrorCategory::InvalidParameters,
745 500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
746 408 => ErrorCategory::Timeout,
747 _ => classify_error_message(message),
748 };
749 }
750 classify_error_message(message)
752 }
753 }
754 }
755}
756
757fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
758 let Some(metadata) = metadata else {
759 return fallback;
760 };
761
762 let mut hint = String::new();
763 if let Some(code) = &metadata.code {
764 hint.push_str(code);
765 hint.push(' ');
766 }
767 if let Some(message) = &metadata.message {
768 hint.push_str(message);
769 hint.push(' ');
770 }
771 if let Some(status) = metadata.status {
772 let _ = write!(&mut hint, "{status}");
773 }
774
775 let classified = classify_error_message(&hint);
776 if classified == ErrorCategory::ExecutionError {
777 fallback
778 } else {
779 classified
780 }
781}
782
783#[cfg(test)]
784mod tests;