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]
208 pub const fn user_label(&self) -> &'static str {
209 match self {
210 ErrorCategory::Network => "Network error",
211 ErrorCategory::Timeout => "Request timed out",
212 ErrorCategory::RateLimit => "Rate limit exceeded",
213 ErrorCategory::ServiceUnavailable => "Service temporarily unavailable",
214 ErrorCategory::CircuitOpen => "Tool temporarily disabled",
215 ErrorCategory::Authentication => "Authentication failed",
216 ErrorCategory::InvalidParameters => "Invalid parameters",
217 ErrorCategory::ToolNotFound => "Tool not found",
218 ErrorCategory::ResourceNotFound => "Resource not found",
219 ErrorCategory::PermissionDenied => "Permission denied",
220 ErrorCategory::PolicyViolation => "Blocked by policy",
221 ErrorCategory::PlanningPolicyViolation => "Not allowed in planning workflow",
222 ErrorCategory::SandboxFailure => "Sandbox denied",
223 ErrorCategory::ResourceExhausted => "Resource limit reached",
224 ErrorCategory::Cancelled => "Operation cancelled",
225 ErrorCategory::ExecutionError => "Execution failed",
226 }
227 }
228
229 #[must_use]
243 pub fn auth_recovery_guidance(
244 &self,
245 provider_label: &str,
246 provider_key: &str,
247 is_managed_auth: bool,
248 has_credential: bool,
249 rejected_source: Option<RejectedCredentialSource>,
250 ) -> Vec<String> {
251 if !matches!(self, ErrorCategory::Authentication) {
252 return vec![];
253 }
254
255 if is_managed_auth {
256 return vec![format!(
257 "Authentication failed for {provider_label}. Run /login {provider_key} to re-authenticate."
258 )];
259 }
260 if !has_credential {
261 return vec![format!(
262 "Authentication failed for {provider_label}. Run /secret add {provider_key} to store your API key in secure storage (OS keyring or encrypted file)."
263 )];
264 }
265 match rejected_source {
266 Some(RejectedCredentialSource::Environment { env_var }) => vec![format!(
267 "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.",
268 env_var.map_or_else(|| "a custom variable".to_string(), |name| format!("`{name}`"))
269 )],
270 Some(RejectedCredentialSource::WorkspaceDotEnv { env_var }) => vec![format!(
271 "Authentication failed for {provider_label}. The rejected key came from {} — check the value there.",
272 env_var.map_or_else(
273 || "the workspace `.env` file".to_string(),
274 |name| format!("`{name}` in the workspace `.env` file")
275 )
276 )],
277 Some(RejectedCredentialSource::SecureStorage) => vec![format!(
278 "Authentication failed for {provider_label}. The stored API key was rejected — run /secret add {provider_key} to replace it with a valid key."
279 )],
280 None => vec![format!(
281 "Authentication failed for {provider_label}. The configured credential was rejected — verify the value, or run /secret add {provider_key} to store a fresh key."
282 )],
283 }
284 }
285}
286
287impl fmt::Display for ErrorCategory {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 f.write_str(self.user_label())
290 }
291}
292
293#[must_use]
312pub fn classify_anyhow_error(err: &anyhow::Error) -> ErrorCategory {
313 let outer = classify_error_message(&err.to_string());
316 if outer != ErrorCategory::ExecutionError {
317 return outer;
318 }
319
320 if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
324 return ErrorCategory::from(llm_error);
325 }
326
327 for cause in err.chain().skip(1) {
328 let category = classify_error_message(&cause.to_string());
329 if category != ErrorCategory::ExecutionError {
330 return category;
331 }
332 }
333
334 ErrorCategory::ExecutionError
335}
336
337#[must_use]
346pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
347 err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
348}
349
350#[must_use]
352pub fn is_context_capacity_message(message: &str) -> bool {
353 let message = message.to_ascii_lowercase();
354 contains_any(
355 &message,
356 &[
357 "context_length_exceeded",
358 "context length exceeded",
359 "maximum context length",
360 "maximum context window",
361 "context window exceeded",
362 "context window is too small",
363 "exceeds the model's maximum context",
364 "exceeds model context",
365 "exceeds the maximum context",
366 "prompt is too long",
367 "input is too long",
368 "input token count exceeds",
369 "exceeds the maximum number of tokens",
370 "maximum input tokens",
371 "too many tokens in the prompt",
372 "request exceeds the context",
373 "context limit exceeded",
378 "context size exceeded",
379 "exceeds context",
380 "input tokens exceed",
381 "prompt tokens exceed",
382 "prompt token count exceeds",
383 "token limit exceeded",
384 "input too large",
385 "prompt too large",
386 ],
387 )
388}
389
390#[inline]
395#[must_use]
396pub fn classify_error_message(msg: &str) -> ErrorCategory {
397 let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
398 Cow::Owned(msg.to_ascii_lowercase())
399 } else {
400 Cow::Borrowed(msg)
401 };
402
403 if contains_any(
405 &msg,
406 &[
407 "policy violation",
408 "denied by policy",
409 "tool permission denied",
410 "safety validation failed",
411 "not allowed in planning workflow",
412 "only available when planning workflow is active",
413 "workspace boundary",
414 "blocked by policy",
415 ],
416 ) {
417 return ErrorCategory::PolicyViolation;
418 }
419
420 if contains_any(
422 &msg,
423 &[
424 "planning workflow",
425 "read-only permissions",
426 concat!("read-only ", "mode"),
427 "planning_policy_violation",
428 ],
429 ) {
430 return ErrorCategory::PlanningPolicyViolation;
431 }
432
433 if contains_any(
435 &msg,
436 &[
437 "invalid api key",
438 "authentication failed",
439 "unauthorized",
440 "401",
441 "invalid credentials",
442 ],
443 ) {
444 return ErrorCategory::Authentication;
445 }
446
447 if contains_any(
449 &msg,
450 &[
451 "weekly usage limit",
452 "daily usage limit",
453 "monthly spending limit",
454 "insufficient credits",
455 "quota exceeded",
456 "billing",
457 "payment required",
458 ],
459 ) {
460 return ErrorCategory::ResourceExhausted;
461 }
462
463 if contains_any(
465 &msg,
466 &[
467 "invalid argument",
468 "invalid parameters",
469 "invalid type",
470 "malformed",
471 "failed to parse arguments",
472 "failed to parse argument",
473 "missing required",
474 "at least one item is required",
475 "is required for",
476 "schema validation",
477 "argument validation failed",
478 "unknown field",
479 "unknown variant",
480 "expected struct",
481 "expected enum",
482 "type mismatch",
483 "must be an absolute path",
484 "not parseable",
485 "parseable as",
486 "invalid patch format",
494 "invalid patch hunk",
495 "invalid patch operation",
496 "cannot parse empty patch",
497 "patch does not contain",
498 "semantic patch anchor",
499 ],
500 ) {
501 return ErrorCategory::InvalidParameters;
502 }
503
504 if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
506 return ErrorCategory::ToolNotFound;
507 }
508
509 if contains_any(
511 &msg,
512 &[
513 "no such file",
514 "no such directory",
515 "file not found",
516 "directory not found",
517 "resource not found",
518 "path not found",
519 "does not exist",
520 "enoent",
521 ],
522 ) {
523 return ErrorCategory::ResourceNotFound;
524 }
525
526 if contains_any(
528 &msg,
529 &[
530 "permission denied",
531 "access denied",
532 "operation not permitted",
533 "eacces",
534 "eperm",
535 "forbidden",
536 "403",
537 ],
538 ) {
539 return ErrorCategory::PermissionDenied;
540 }
541
542 if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
544 return ErrorCategory::Cancelled;
545 }
546
547 if contains_any(&msg, &["circuit breaker", "circuit open"]) {
549 return ErrorCategory::CircuitOpen;
550 }
551
552 if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
554 return ErrorCategory::SandboxFailure;
555 }
556
557 if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
559 return ErrorCategory::RateLimit;
560 }
561
562 if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
564 return ErrorCategory::Timeout;
565 }
566
567 if contains_any(
569 &msg,
570 &[
571 "invalid response format: missing choices",
572 "invalid response format: missing message",
573 "missing choices in response",
574 "missing message in choice",
575 "no choices in response",
576 "invalid response from ",
577 "empty response body",
578 "response did not contain",
579 "unexpected response format",
580 "failed to parse response",
581 "stream disconnected",
587 "stream closed unexpectedly",
588 "incomplete stream",
589 "unexpected end of stream",
590 "truncated response",
591 "failed to decode stream",
592 "stream terminated",
593 ],
594 ) {
595 return ErrorCategory::ServiceUnavailable;
596 }
597
598 if contains_any(&msg, &["without an event boundary"]) {
605 return ErrorCategory::ExecutionError;
606 }
607
608 if contains_any(
610 &msg,
611 &[
612 "service unavailable",
613 "temporarily unavailable",
614 "internal server error",
615 "bad gateway",
616 "gateway timeout",
617 "overloaded",
618 "500",
619 "502",
620 "503",
621 "504",
622 ],
623 ) {
624 return ErrorCategory::ServiceUnavailable;
625 }
626
627 if contains_any(
629 &msg,
630 &[
631 "network",
632 "connection reset",
633 "connection refused",
634 "broken pipe",
635 "dns",
636 "name resolution",
637 "try again",
638 "retry later",
639 "upstream connect error",
640 "tls handshake",
641 "socket hang up",
642 "econnreset",
643 "etimedout",
644 "error decoding response body",
648 "connection closed before",
653 "stream reset",
654 "stream error received",
655 ],
656 ) {
657 return ErrorCategory::Network;
658 }
659
660 if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
662 return ErrorCategory::ResourceExhausted;
663 }
664
665 ErrorCategory::ExecutionError
667}
668
669#[inline]
674#[must_use]
675pub fn is_retryable_llm_error_message(msg: &str) -> bool {
676 let category = classify_error_message(msg);
677 category.is_retryable()
678}
679
680#[inline]
681fn contains_any(message: &str, markers: &[&str]) -> bool {
682 markers.iter().any(|marker| message.contains(marker))
683}
684
685impl From<&crate::llm::LLMError> for ErrorCategory {
690 fn from(err: &crate::llm::LLMError) -> Self {
691 match err {
692 crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
693 crate::llm::LLMError::RateLimit { metadata } => {
694 classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
695 }
696 crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
697 crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
698 crate::llm::LLMError::Provider { message, metadata } => {
699 let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
700 if metadata_category != ErrorCategory::ExecutionError {
701 return metadata_category;
702 }
703
704 if let Some(meta) = metadata
706 && let Some(status) = meta.status
707 {
708 return match status {
709 401 => ErrorCategory::Authentication,
710 403 => ErrorCategory::PermissionDenied,
711 404 => ErrorCategory::ResourceNotFound,
712 429 => ErrorCategory::RateLimit,
713 400 => ErrorCategory::InvalidParameters,
714 500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
715 408 => ErrorCategory::Timeout,
716 _ => classify_error_message(message),
717 };
718 }
719 classify_error_message(message)
721 }
722 }
723 }
724}
725
726fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
727 let Some(metadata) = metadata else {
728 return fallback;
729 };
730
731 let mut hint = String::new();
732 if let Some(code) = &metadata.code {
733 hint.push_str(code);
734 hint.push(' ');
735 }
736 if let Some(message) = &metadata.message {
737 hint.push_str(message);
738 hint.push(' ');
739 }
740 if let Some(status) = metadata.status {
741 let _ = write!(&mut hint, "{status}");
742 }
743
744 let classified = classify_error_message(&hint);
745 if classified == ErrorCategory::ExecutionError {
746 fallback
747 } else {
748 classified
749 }
750}
751
752mod recovery;
753#[cfg(test)]
754mod tests;