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, PartialEq, Eq)]
35pub enum RejectedCredentialSource {
36 Environment { env_var: Option<String> },
40 WorkspaceDotEnv { env_var: Option<String> },
42 SecureStorage,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
49pub enum ErrorCategory {
50 Network,
53 Timeout,
55 RateLimit,
57 ServiceUnavailable,
59 CircuitOpen,
61
62 Authentication,
65 InvalidParameters,
67 ToolNotFound,
69 ResourceNotFound,
71 PermissionDenied,
73 PolicyViolation,
75 PlanningPolicyViolation,
77 SandboxFailure,
79 ResourceExhausted,
81 Cancelled,
83 ExecutionError,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum Retryability {
90 Retryable {
92 max_attempts: u32,
94 backoff: BackoffStrategy,
96 },
97 NonRetryable,
99 RequiresIntervention,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum BackoffStrategy {
106 Exponential { base: Duration, max: Duration },
108 Fixed(Duration),
110}
111
112impl ErrorCategory {
113 #[inline]
118 #[must_use]
119 pub const fn as_str(&self) -> &'static str {
120 self.user_label()
121 }
122
123 #[inline]
125 #[must_use]
126 pub const fn is_retryable(&self) -> bool {
127 matches!(
128 self,
129 ErrorCategory::Network
130 | ErrorCategory::Timeout
131 | ErrorCategory::RateLimit
132 | ErrorCategory::ServiceUnavailable
133 | ErrorCategory::CircuitOpen
134 )
135 }
136
137 #[inline]
139 #[must_use]
140 pub const fn should_trip_circuit_breaker(&self) -> bool {
141 matches!(
142 self,
143 ErrorCategory::Network
144 | ErrorCategory::Timeout
145 | ErrorCategory::RateLimit
146 | ErrorCategory::ServiceUnavailable
147 | ErrorCategory::ExecutionError
148 )
149 }
150
151 #[inline]
154 #[must_use]
155 const fn is_llm_mistake(&self) -> bool {
156 matches!(self, ErrorCategory::InvalidParameters)
157 }
158
159 #[inline]
161 #[must_use]
162 pub const fn is_permanent(&self) -> bool {
163 matches!(
164 self,
165 ErrorCategory::Authentication
166 | ErrorCategory::PolicyViolation
167 | ErrorCategory::PlanningPolicyViolation
168 | ErrorCategory::ResourceExhausted
169 )
170 }
171
172 #[must_use]
174 pub fn retryability(&self) -> Retryability {
175 match self {
176 ErrorCategory::Network | ErrorCategory::ServiceUnavailable => Retryability::Retryable {
177 max_attempts: 3,
178 backoff: BackoffStrategy::Exponential {
179 base: Duration::from_millis(500),
180 max: Duration::from_secs(10),
181 },
182 },
183 ErrorCategory::Timeout => Retryability::Retryable {
184 max_attempts: 2,
185 backoff: BackoffStrategy::Exponential {
186 base: Duration::from_millis(1000),
187 max: Duration::from_secs(15),
188 },
189 },
190 ErrorCategory::RateLimit => Retryability::Retryable {
191 max_attempts: 3,
192 backoff: BackoffStrategy::Exponential {
193 base: Duration::from_secs(1),
194 max: Duration::from_secs(30),
195 },
196 },
197 ErrorCategory::CircuitOpen => Retryability::Retryable {
198 max_attempts: 1,
199 backoff: BackoffStrategy::Fixed(Duration::from_secs(10)),
200 },
201 ErrorCategory::PermissionDenied => Retryability::RequiresIntervention,
202 _ => Retryability::NonRetryable,
203 }
204 }
205
206 #[must_use]
209 pub fn recovery_suggestions(&self) -> Vec<Cow<'static, str>> {
210 match self {
211 ErrorCategory::Network => vec![
212 Cow::Borrowed("Check network connectivity"),
213 Cow::Borrowed("Retry the operation after a brief delay"),
214 Cow::Borrowed("Verify external service availability"),
215 ],
216 ErrorCategory::Timeout => vec![
217 Cow::Borrowed("Increase timeout values if appropriate"),
218 Cow::Borrowed("Break large operations into smaller chunks"),
219 Cow::Borrowed("Check system resources and performance"),
220 ],
221 ErrorCategory::RateLimit => vec![
222 Cow::Borrowed("Wait before retrying the request"),
223 Cow::Borrowed("Reduce request frequency"),
224 Cow::Borrowed("Check provider rate limit documentation"),
225 ],
226 ErrorCategory::ServiceUnavailable => vec![
227 Cow::Borrowed("The service is temporarily unavailable"),
228 Cow::Borrowed("Retry after a brief delay"),
229 Cow::Borrowed("Check service status page if available"),
230 ],
231 ErrorCategory::CircuitOpen => vec![
232 Cow::Borrowed("This tool has been temporarily disabled due to repeated failures"),
233 Cow::Borrowed("Wait for the circuit breaker cooldown period"),
234 Cow::Borrowed("Try an alternative approach"),
235 ],
236 ErrorCategory::Authentication => vec![
237 Cow::Borrowed("Verify your API key or credentials"),
238 Cow::Borrowed("Check that your account is active and has sufficient permissions"),
239 Cow::Borrowed("Ensure environment variables for API keys are set correctly"),
240 ],
241 ErrorCategory::InvalidParameters => vec![
242 Cow::Borrowed("Check parameter names and types against the tool schema"),
243 Cow::Borrowed("Ensure required parameters are provided"),
244 Cow::Borrowed("Verify parameter values are within acceptable ranges"),
245 ],
246 ErrorCategory::ToolNotFound => vec![
247 Cow::Borrowed("Verify the tool name is spelled correctly"),
248 Cow::Borrowed("Check if the tool is available in the current context"),
249 ],
250 ErrorCategory::ResourceNotFound => vec![
251 Cow::Borrowed("Verify file paths and resource locations"),
252 Cow::Borrowed("Check if files exist and are accessible"),
253 Cow::Borrowed("Use list_dir to explore available resources"),
254 ],
255 ErrorCategory::PermissionDenied => vec![
256 Cow::Borrowed("Check file permissions and access rights"),
257 Cow::Borrowed("Ensure workspace boundaries are respected"),
258 ],
259 ErrorCategory::PolicyViolation => vec![
260 Cow::Borrowed("Review workspace policies and restrictions"),
261 Cow::Borrowed("Use alternative tools that comply with policies"),
262 ],
263 ErrorCategory::PlanningPolicyViolation => vec![
264 Cow::Borrowed("This operation is not allowed in the Planning workflow with read-only permissions"),
265 Cow::Borrowed("Exit the Planning workflow to perform mutating operations"),
266 ],
267 ErrorCategory::SandboxFailure => vec![
268 Cow::Borrowed("The sandbox denied this operation"),
269 Cow::Borrowed("Check sandbox configuration and permissions"),
270 ],
271 ErrorCategory::ResourceExhausted => vec![
272 Cow::Borrowed("Check your account usage limits and billing status"),
273 Cow::Borrowed("Review resource consumption and optimize if possible"),
274 ],
275 ErrorCategory::Cancelled => vec![Cow::Borrowed("The operation was cancelled")],
276 ErrorCategory::ExecutionError => vec![
277 Cow::Borrowed("Review error details for specific issues"),
278 Cow::Borrowed("Check tool documentation for known limitations"),
279 ],
280 }
281 }
282
283 #[must_use]
285 pub const fn user_label(&self) -> &'static str {
286 match self {
287 ErrorCategory::Network => "Network error",
288 ErrorCategory::Timeout => "Request timed out",
289 ErrorCategory::RateLimit => "Rate limit exceeded",
290 ErrorCategory::ServiceUnavailable => "Service temporarily unavailable",
291 ErrorCategory::CircuitOpen => "Tool temporarily disabled",
292 ErrorCategory::Authentication => "Authentication failed",
293 ErrorCategory::InvalidParameters => "Invalid parameters",
294 ErrorCategory::ToolNotFound => "Tool not found",
295 ErrorCategory::ResourceNotFound => "Resource not found",
296 ErrorCategory::PermissionDenied => "Permission denied",
297 ErrorCategory::PolicyViolation => "Blocked by policy",
298 ErrorCategory::PlanningPolicyViolation => "Not allowed in planning workflow",
299 ErrorCategory::SandboxFailure => "Sandbox denied",
300 ErrorCategory::ResourceExhausted => "Resource limit reached",
301 ErrorCategory::Cancelled => "Operation cancelled",
302 ErrorCategory::ExecutionError => "Execution failed",
303 }
304 }
305
306 #[must_use]
320 pub fn auth_recovery_guidance(
321 &self,
322 provider_label: &str,
323 provider_key: &str,
324 is_managed_auth: bool,
325 has_credential: bool,
326 rejected_source: Option<RejectedCredentialSource>,
327 ) -> Vec<String> {
328 if !matches!(self, ErrorCategory::Authentication) {
329 return vec![];
330 }
331
332 if is_managed_auth {
333 return vec![format!(
334 "Authentication failed for {provider_label}. Run /login {provider_key} to re-authenticate."
335 )];
336 }
337 if !has_credential {
338 return vec![format!(
339 "Authentication failed for {provider_label}. Run /secret add {provider_key} to store your API key in secure storage (OS keyring or encrypted file)."
340 )];
341 }
342 match rejected_source {
343 Some(RejectedCredentialSource::Environment { env_var }) => vec![format!(
344 "Authentication failed for {provider_label}. The rejected key came from {} in the process environment, which shadows the workspace `.env` file and secure storage — check the export, or unset it so the next source applies.",
345 env_var.map_or_else(|| "a custom variable".to_string(), |name| format!("`{name}`"))
346 )],
347 Some(RejectedCredentialSource::WorkspaceDotEnv { env_var }) => vec![format!(
348 "Authentication failed for {provider_label}. The rejected key came from {} — check the value there.",
349 env_var.map_or_else(
350 || "the workspace `.env` file".to_string(),
351 |name| format!("`{name}` in the workspace `.env` file")
352 )
353 )],
354 Some(RejectedCredentialSource::SecureStorage) => vec![format!(
355 "Authentication failed for {provider_label}. The stored API key was rejected — run /secret add {provider_key} to replace it with a valid key."
356 )],
357 None => vec![format!(
358 "Authentication failed for {provider_label}. The configured credential was rejected — verify the value, or run /secret add {provider_key} to store a fresh key."
359 )],
360 }
361 }
362}
363
364impl fmt::Display for ErrorCategory {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 f.write_str(self.user_label())
367 }
368}
369
370#[must_use]
389pub fn classify_anyhow_error(err: &anyhow::Error) -> ErrorCategory {
390 let outer = classify_error_message(&err.to_string());
393 if outer != ErrorCategory::ExecutionError {
394 return outer;
395 }
396
397 if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
401 return ErrorCategory::from(llm_error);
402 }
403
404 for cause in err.chain().skip(1) {
405 let category = classify_error_message(&cause.to_string());
406 if category != ErrorCategory::ExecutionError {
407 return category;
408 }
409 }
410
411 ErrorCategory::ExecutionError
412}
413
414#[must_use]
423pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
424 err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
425}
426
427#[must_use]
429pub fn is_context_capacity_message(message: &str) -> bool {
430 let message = message.to_ascii_lowercase();
431 contains_any(
432 &message,
433 &[
434 "context_length_exceeded",
435 "context length exceeded",
436 "maximum context length",
437 "maximum context window",
438 "context window exceeded",
439 "context window is too small",
440 "exceeds the model's maximum context",
441 "exceeds model context",
442 "exceeds the maximum context",
443 "prompt is too long",
444 "input is too long",
445 "input token count exceeds",
446 "exceeds the maximum number of tokens",
447 "maximum input tokens",
448 "too many tokens in the prompt",
449 "request exceeds the context",
450 "context limit exceeded",
455 "context size exceeded",
456 "exceeds context",
457 "input tokens exceed",
458 "prompt tokens exceed",
459 "prompt token count exceeds",
460 "token limit exceeded",
461 "input too large",
462 "prompt too large",
463 ],
464 )
465}
466
467#[inline]
472#[must_use]
473pub fn classify_error_message(msg: &str) -> ErrorCategory {
474 let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
475 Cow::Owned(msg.to_ascii_lowercase())
476 } else {
477 Cow::Borrowed(msg)
478 };
479
480 if contains_any(
482 &msg,
483 &[
484 "policy violation",
485 "denied by policy",
486 "tool permission denied",
487 "safety validation failed",
488 "not allowed in planning workflow",
489 "only available when planning workflow is active",
490 "workspace boundary",
491 "blocked by policy",
492 ],
493 ) {
494 return ErrorCategory::PolicyViolation;
495 }
496
497 if contains_any(
499 &msg,
500 &[
501 "planning workflow",
502 "read-only permissions",
503 concat!("read-only ", "mode"),
504 "planning_policy_violation",
505 ],
506 ) {
507 return ErrorCategory::PlanningPolicyViolation;
508 }
509
510 if contains_any(
512 &msg,
513 &[
514 "invalid api key",
515 "authentication failed",
516 "unauthorized",
517 "401",
518 "invalid credentials",
519 ],
520 ) {
521 return ErrorCategory::Authentication;
522 }
523
524 if contains_any(
526 &msg,
527 &[
528 "weekly usage limit",
529 "daily usage limit",
530 "monthly spending limit",
531 "insufficient credits",
532 "quota exceeded",
533 "billing",
534 "payment required",
535 ],
536 ) {
537 return ErrorCategory::ResourceExhausted;
538 }
539
540 if contains_any(
542 &msg,
543 &[
544 "invalid argument",
545 "invalid parameters",
546 "invalid type",
547 "malformed",
548 "failed to parse arguments",
549 "failed to parse argument",
550 "missing required",
551 "at least one item is required",
552 "is required for",
553 "schema validation",
554 "argument validation failed",
555 "unknown field",
556 "unknown variant",
557 "expected struct",
558 "expected enum",
559 "type mismatch",
560 "must be an absolute path",
561 "not parseable",
562 "parseable as",
563 "invalid patch format",
571 "invalid patch hunk",
572 "invalid patch operation",
573 "cannot parse empty patch",
574 "patch does not contain",
575 "semantic patch anchor",
576 ],
577 ) {
578 return ErrorCategory::InvalidParameters;
579 }
580
581 if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
583 return ErrorCategory::ToolNotFound;
584 }
585
586 if contains_any(
588 &msg,
589 &[
590 "no such file",
591 "no such directory",
592 "file not found",
593 "directory not found",
594 "resource not found",
595 "path not found",
596 "does not exist",
597 "enoent",
598 ],
599 ) {
600 return ErrorCategory::ResourceNotFound;
601 }
602
603 if contains_any(
605 &msg,
606 &[
607 "permission denied",
608 "access denied",
609 "operation not permitted",
610 "eacces",
611 "eperm",
612 "forbidden",
613 "403",
614 ],
615 ) {
616 return ErrorCategory::PermissionDenied;
617 }
618
619 if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
621 return ErrorCategory::Cancelled;
622 }
623
624 if contains_any(&msg, &["circuit breaker", "circuit open"]) {
626 return ErrorCategory::CircuitOpen;
627 }
628
629 if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
631 return ErrorCategory::SandboxFailure;
632 }
633
634 if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
636 return ErrorCategory::RateLimit;
637 }
638
639 if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
641 return ErrorCategory::Timeout;
642 }
643
644 if contains_any(
646 &msg,
647 &[
648 "invalid response format: missing choices",
649 "invalid response format: missing message",
650 "missing choices in response",
651 "missing message in choice",
652 "no choices in response",
653 "invalid response from ",
654 "empty response body",
655 "response did not contain",
656 "unexpected response format",
657 "failed to parse response",
658 "stream disconnected",
664 "stream closed unexpectedly",
665 "incomplete stream",
666 "unexpected end of stream",
667 "truncated response",
668 "failed to decode stream",
669 "stream terminated",
670 ],
671 ) {
672 return ErrorCategory::ServiceUnavailable;
673 }
674
675 if contains_any(&msg, &["without an event boundary"]) {
682 return ErrorCategory::ExecutionError;
683 }
684
685 if contains_any(
687 &msg,
688 &[
689 "service unavailable",
690 "temporarily unavailable",
691 "internal server error",
692 "bad gateway",
693 "gateway timeout",
694 "overloaded",
695 "500",
696 "502",
697 "503",
698 "504",
699 ],
700 ) {
701 return ErrorCategory::ServiceUnavailable;
702 }
703
704 if contains_any(
706 &msg,
707 &[
708 "network",
709 "connection reset",
710 "connection refused",
711 "broken pipe",
712 "dns",
713 "name resolution",
714 "try again",
715 "retry later",
716 "upstream connect error",
717 "tls handshake",
718 "socket hang up",
719 "econnreset",
720 "etimedout",
721 "error decoding response body",
725 "connection closed before",
730 "stream reset",
731 "stream error received",
732 ],
733 ) {
734 return ErrorCategory::Network;
735 }
736
737 if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
739 return ErrorCategory::ResourceExhausted;
740 }
741
742 ErrorCategory::ExecutionError
744}
745
746#[inline]
751#[must_use]
752pub fn is_retryable_llm_error_message(msg: &str) -> bool {
753 let category = classify_error_message(msg);
754 category.is_retryable()
755}
756
757#[inline]
758fn contains_any(message: &str, markers: &[&str]) -> bool {
759 markers.iter().any(|marker| message.contains(marker))
760}
761
762impl From<&crate::llm::LLMError> for ErrorCategory {
767 fn from(err: &crate::llm::LLMError) -> Self {
768 match err {
769 crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
770 crate::llm::LLMError::RateLimit { metadata } => {
771 classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
772 }
773 crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
774 crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
775 crate::llm::LLMError::Provider { message, metadata } => {
776 let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
777 if metadata_category != ErrorCategory::ExecutionError {
778 return metadata_category;
779 }
780
781 if let Some(meta) = metadata
783 && let Some(status) = meta.status
784 {
785 return match status {
786 401 => ErrorCategory::Authentication,
787 403 => ErrorCategory::PermissionDenied,
788 404 => ErrorCategory::ResourceNotFound,
789 429 => ErrorCategory::RateLimit,
790 400 => ErrorCategory::InvalidParameters,
791 500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
792 408 => ErrorCategory::Timeout,
793 _ => classify_error_message(message),
794 };
795 }
796 classify_error_message(message)
798 }
799 }
800 }
801}
802
803fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
804 let Some(metadata) = metadata else {
805 return fallback;
806 };
807
808 let mut hint = String::new();
809 if let Some(code) = &metadata.code {
810 hint.push_str(code);
811 hint.push(' ');
812 }
813 if let Some(message) = &metadata.message {
814 hint.push_str(message);
815 hint.push(' ');
816 }
817 if let Some(status) = metadata.status {
818 let _ = write!(&mut hint, "{status}");
819 }
820
821 let classified = classify_error_message(&hint);
822 if classified == ErrorCategory::ExecutionError {
823 fallback
824 } else {
825 classified
826 }
827}
828
829#[cfg(test)]
830mod tests;