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 if let Some(denial) = err.downcast_ref::<SafeguardDenial>() {
316 return denial.kind().category();
317 }
318 let outer = classify_error_message(&err.to_string());
321 if outer != ErrorCategory::ExecutionError {
322 return outer;
323 }
324
325 if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
329 return ErrorCategory::from(llm_error);
330 }
331
332 for cause in err.chain().skip(1) {
333 let category = classify_error_message(&cause.to_string());
334 if category != ErrorCategory::ExecutionError {
335 return category;
336 }
337 }
338
339 ErrorCategory::ExecutionError
340}
341
342#[must_use]
351pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
352 err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
353}
354
355#[must_use]
357pub fn is_context_capacity_message(message: &str) -> bool {
358 let message = message.to_ascii_lowercase();
359 contains_any(
360 &message,
361 &[
362 "context_length_exceeded",
363 "context length exceeded",
364 "maximum context length",
365 "maximum context window",
366 "context window exceeded",
367 "context window is too small",
368 "exceeds the model's maximum context",
369 "exceeds model context",
370 "exceeds the maximum context",
371 "prompt is too long",
372 "input is too long",
373 "input token count exceeds",
374 "exceeds the maximum number of tokens",
375 "maximum input tokens",
376 "too many tokens in the prompt",
377 "request exceeds the context",
378 "context limit exceeded",
383 "context size exceeded",
384 "exceeds context",
385 "input tokens exceed",
386 "prompt tokens exceed",
387 "prompt token count exceeds",
388 "token limit exceeded",
389 "input too large",
390 "prompt too large",
391 ],
392 )
393}
394
395#[inline]
400#[must_use]
401pub fn classify_error_message(msg: &str) -> ErrorCategory {
402 let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
403 Cow::Owned(msg.to_ascii_lowercase())
404 } else {
405 Cow::Borrowed(msg)
406 };
407
408 if contains_any(
410 &msg,
411 &[
412 "policy violation",
413 "denied by policy",
414 "tool permission denied",
415 "safety validation failed",
416 "not allowed in planning workflow",
417 "only available when planning workflow is active",
418 "workspace boundary",
419 "blocked by policy",
420 ],
421 ) {
422 return ErrorCategory::PolicyViolation;
423 }
424
425 if contains_any(
427 &msg,
428 &[
429 "planning workflow",
430 "read-only permissions",
431 concat!("read-only ", "mode"),
432 "planning_policy_violation",
433 ],
434 ) {
435 return ErrorCategory::PlanningPolicyViolation;
436 }
437
438 if contains_any(
440 &msg,
441 &[
442 "invalid api key",
443 "authentication failed",
444 "unauthorized",
445 "401",
446 "invalid credentials",
447 ],
448 ) {
449 return ErrorCategory::Authentication;
450 }
451
452 if contains_any(
454 &msg,
455 &[
456 "weekly usage limit",
457 "daily usage limit",
458 "monthly spending limit",
459 "insufficient credits",
460 "quota exceeded",
461 "billing",
462 "payment required",
463 ],
464 ) {
465 return ErrorCategory::ResourceExhausted;
466 }
467
468 if contains_any(
470 &msg,
471 &[
472 "invalid argument",
473 "invalid parameters",
474 "invalid type",
475 "malformed",
476 "failed to parse arguments",
477 "failed to parse argument",
478 "missing required",
479 "at least one item is required",
480 "is required for",
481 "schema validation",
482 "argument validation failed",
483 "unknown field",
484 "unknown variant",
485 "expected struct",
486 "expected enum",
487 "type mismatch",
488 "must be an absolute path",
489 "not parseable",
490 "parseable as",
491 "invalid patch format",
499 "invalid patch hunk",
500 "invalid patch operation",
501 "cannot parse empty patch",
502 "patch does not contain",
503 "semantic patch anchor",
504 ],
505 ) {
506 return ErrorCategory::InvalidParameters;
507 }
508
509 if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
511 return ErrorCategory::ToolNotFound;
512 }
513
514 if contains_any(
516 &msg,
517 &[
518 "no such file",
519 "no such directory",
520 "file not found",
521 "directory not found",
522 "resource not found",
523 "path not found",
524 "does not exist",
525 "enoent",
526 ],
527 ) {
528 return ErrorCategory::ResourceNotFound;
529 }
530
531 if contains_any(
533 &msg,
534 &[
535 "permission denied",
536 "access denied",
537 "operation not permitted",
538 "eacces",
539 "eperm",
540 "forbidden",
541 "403",
542 ],
543 ) {
544 return ErrorCategory::PermissionDenied;
545 }
546
547 if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
549 return ErrorCategory::Cancelled;
550 }
551
552 if contains_any(&msg, &["circuit breaker", "circuit open"]) {
554 return ErrorCategory::CircuitOpen;
555 }
556
557 if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
559 return ErrorCategory::SandboxFailure;
560 }
561
562 if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
564 return ErrorCategory::RateLimit;
565 }
566
567 if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
569 return ErrorCategory::Timeout;
570 }
571
572 if contains_any(
574 &msg,
575 &[
576 "invalid response format: missing choices",
577 "invalid response format: missing message",
578 "missing choices in response",
579 "missing message in choice",
580 "no choices in response",
581 "invalid response from ",
582 "empty response body",
583 "response did not contain",
584 "unexpected response format",
585 "failed to parse response",
586 "stream disconnected",
592 "stream closed unexpectedly",
593 "incomplete stream",
594 "unexpected end of stream",
595 "truncated response",
596 "failed to decode stream",
597 "stream terminated",
598 ],
599 ) {
600 return ErrorCategory::ServiceUnavailable;
601 }
602
603 if contains_any(&msg, &["without an event boundary"]) {
610 return ErrorCategory::ExecutionError;
611 }
612
613 if contains_any(
615 &msg,
616 &[
617 "service unavailable",
618 "temporarily unavailable",
619 "internal server error",
620 "bad gateway",
621 "gateway timeout",
622 "overloaded",
623 "500",
624 "502",
625 "503",
626 "504",
627 ],
628 ) {
629 return ErrorCategory::ServiceUnavailable;
630 }
631
632 if contains_any(
634 &msg,
635 &[
636 "network",
637 "connection reset",
638 "connection refused",
639 "broken pipe",
640 "dns",
641 "name resolution",
642 "try again",
643 "retry later",
644 "upstream connect error",
645 "tls handshake",
646 "socket hang up",
647 "econnreset",
648 "etimedout",
649 "error decoding response body",
653 "connection closed before",
658 "stream reset",
659 "stream error received",
660 ],
661 ) {
662 return ErrorCategory::Network;
663 }
664
665 if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
667 return ErrorCategory::ResourceExhausted;
668 }
669
670 ErrorCategory::ExecutionError
672}
673
674#[inline]
679#[must_use]
680pub fn is_retryable_llm_error_message(msg: &str) -> bool {
681 let category = classify_error_message(msg);
682 category.is_retryable()
683}
684
685#[inline]
686fn contains_any(message: &str, markers: &[&str]) -> bool {
687 markers.iter().any(|marker| message.contains(marker))
688}
689
690impl From<&crate::llm::LLMError> for ErrorCategory {
695 fn from(err: &crate::llm::LLMError) -> Self {
696 match err {
697 crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
698 crate::llm::LLMError::RateLimit { metadata } => {
699 classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
700 }
701 crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
702 crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
703 crate::llm::LLMError::Provider { message, metadata } => {
704 let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
705 if metadata_category != ErrorCategory::ExecutionError {
706 return metadata_category;
707 }
708
709 if let Some(meta) = metadata
711 && let Some(status) = meta.status
712 {
713 return match status {
714 401 => ErrorCategory::Authentication,
715 403 => ErrorCategory::PermissionDenied,
716 404 => ErrorCategory::ResourceNotFound,
717 429 => ErrorCategory::RateLimit,
718 400 => ErrorCategory::InvalidParameters,
719 500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
720 408 => ErrorCategory::Timeout,
721 _ => classify_error_message(message),
722 };
723 }
724 classify_error_message(message)
726 }
727 }
728 }
729}
730
731fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
732 let Some(metadata) = metadata else {
733 return fallback;
734 };
735
736 let mut hint = String::new();
737 if let Some(code) = &metadata.code {
738 hint.push_str(code);
739 hint.push(' ');
740 }
741 if let Some(message) = &metadata.message {
742 hint.push_str(message);
743 hint.push(' ');
744 }
745 if let Some(status) = metadata.status {
746 let _ = write!(&mut hint, "{status}");
747 }
748
749 let classified = classify_error_message(&hint);
750 if classified == ErrorCategory::ExecutionError {
751 fallback
752 } else {
753 classified
754 }
755}
756
757mod recovery;
758mod safeguard;
759pub use safeguard::{SafeguardDenial, SafeguardKind};
760#[cfg(test)]
761mod tests;