#![expect(
clippy::let_underscore_must_use,
reason = "The category formatter intentionally ignores infallible formatting results."
)]
use std::borrow::Cow;
use std::fmt;
use std::fmt::Write;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RejectedCredentialSource {
Environment { env_var: Option<String> },
WorkspaceDotEnv { env_var: Option<String> },
SecureStorage,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ErrorCategory {
Network,
Timeout,
RateLimit,
ServiceUnavailable,
CircuitOpen,
Authentication,
InvalidParameters,
ToolNotFound,
ResourceNotFound,
PermissionDenied,
PolicyViolation,
PlanningPolicyViolation,
SandboxFailure,
ResourceExhausted,
Cancelled,
ExecutionError,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Retryability {
Retryable {
max_attempts: u32,
backoff: BackoffStrategy,
},
NonRetryable,
RequiresIntervention,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BackoffStrategy {
Exponential { base: Duration, max: Duration },
Fixed(Duration),
}
impl ErrorCategory {
#[inline]
#[must_use]
pub const fn as_str(&self) -> &'static str {
self.user_label()
}
#[inline]
#[must_use]
pub const fn is_retryable(&self) -> bool {
matches!(
self,
ErrorCategory::Network
| ErrorCategory::Timeout
| ErrorCategory::RateLimit
| ErrorCategory::ServiceUnavailable
| ErrorCategory::CircuitOpen
)
}
#[inline]
#[must_use]
pub const fn should_trip_circuit_breaker(&self) -> bool {
matches!(
self,
ErrorCategory::Network
| ErrorCategory::Timeout
| ErrorCategory::RateLimit
| ErrorCategory::ServiceUnavailable
| ErrorCategory::ExecutionError
)
}
#[inline]
#[must_use]
const fn is_llm_mistake(&self) -> bool {
matches!(self, ErrorCategory::InvalidParameters)
}
#[inline]
#[must_use]
pub const fn is_permanent(&self) -> bool {
matches!(
self,
ErrorCategory::Authentication
| ErrorCategory::PolicyViolation
| ErrorCategory::PlanningPolicyViolation
| ErrorCategory::ResourceExhausted
)
}
#[must_use]
pub fn retryability(&self) -> Retryability {
match self {
ErrorCategory::Network | ErrorCategory::ServiceUnavailable => Retryability::Retryable {
max_attempts: 3,
backoff: BackoffStrategy::Exponential {
base: Duration::from_millis(500),
max: Duration::from_secs(10),
},
},
ErrorCategory::Timeout => Retryability::Retryable {
max_attempts: 2,
backoff: BackoffStrategy::Exponential {
base: Duration::from_millis(1000),
max: Duration::from_secs(15),
},
},
ErrorCategory::RateLimit => Retryability::Retryable {
max_attempts: 3,
backoff: BackoffStrategy::Exponential {
base: Duration::from_secs(1),
max: Duration::from_secs(30),
},
},
ErrorCategory::CircuitOpen => Retryability::Retryable {
max_attempts: 1,
backoff: BackoffStrategy::Fixed(Duration::from_secs(10)),
},
ErrorCategory::PermissionDenied => Retryability::RequiresIntervention,
_ => Retryability::NonRetryable,
}
}
#[must_use]
pub const fn user_label(&self) -> &'static str {
match self {
ErrorCategory::Network => "Network error",
ErrorCategory::Timeout => "Request timed out",
ErrorCategory::RateLimit => "Rate limit exceeded",
ErrorCategory::ServiceUnavailable => "Service temporarily unavailable",
ErrorCategory::CircuitOpen => "Tool temporarily disabled",
ErrorCategory::Authentication => "Authentication failed",
ErrorCategory::InvalidParameters => "Invalid parameters",
ErrorCategory::ToolNotFound => "Tool not found",
ErrorCategory::ResourceNotFound => "Resource not found",
ErrorCategory::PermissionDenied => "Permission denied",
ErrorCategory::PolicyViolation => "Blocked by policy",
ErrorCategory::PlanningPolicyViolation => "Not allowed in planning workflow",
ErrorCategory::SandboxFailure => "Sandbox denied",
ErrorCategory::ResourceExhausted => "Resource limit reached",
ErrorCategory::Cancelled => "Operation cancelled",
ErrorCategory::ExecutionError => "Execution failed",
}
}
#[must_use]
pub fn auth_recovery_guidance(
&self,
provider_label: &str,
provider_key: &str,
is_managed_auth: bool,
has_credential: bool,
rejected_source: Option<RejectedCredentialSource>,
) -> Vec<String> {
if !matches!(self, ErrorCategory::Authentication) {
return vec![];
}
if is_managed_auth {
return vec![format!(
"Authentication failed for {provider_label}. Run /login {provider_key} to re-authenticate."
)];
}
if !has_credential {
return vec![format!(
"Authentication failed for {provider_label}. Run /secret add {provider_key} to store your API key in secure storage (OS keyring or encrypted file)."
)];
}
match rejected_source {
Some(RejectedCredentialSource::Environment { env_var }) => vec![format!(
"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.",
env_var.map_or_else(|| "a custom variable".to_string(), |name| format!("`{name}`"))
)],
Some(RejectedCredentialSource::WorkspaceDotEnv { env_var }) => vec![format!(
"Authentication failed for {provider_label}. The rejected key came from {} — check the value there.",
env_var.map_or_else(
|| "the workspace `.env` file".to_string(),
|name| format!("`{name}` in the workspace `.env` file")
)
)],
Some(RejectedCredentialSource::SecureStorage) => vec![format!(
"Authentication failed for {provider_label}. The stored API key was rejected — run /secret add {provider_key} to replace it with a valid key."
)],
None => vec![format!(
"Authentication failed for {provider_label}. The configured credential was rejected — verify the value, or run /secret add {provider_key} to store a fresh key."
)],
}
}
}
impl fmt::Display for ErrorCategory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.user_label())
}
}
#[must_use]
pub fn classify_anyhow_error(err: &anyhow::Error) -> ErrorCategory {
let outer = classify_error_message(&err.to_string());
if outer != ErrorCategory::ExecutionError {
return outer;
}
if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
return ErrorCategory::from(llm_error);
}
for cause in err.chain().skip(1) {
let category = classify_error_message(&cause.to_string());
if category != ErrorCategory::ExecutionError {
return category;
}
}
ErrorCategory::ExecutionError
}
#[must_use]
pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
}
#[must_use]
pub fn is_context_capacity_message(message: &str) -> bool {
let message = message.to_ascii_lowercase();
contains_any(
&message,
&[
"context_length_exceeded",
"context length exceeded",
"maximum context length",
"maximum context window",
"context window exceeded",
"context window is too small",
"exceeds the model's maximum context",
"exceeds model context",
"exceeds the maximum context",
"prompt is too long",
"input is too long",
"input token count exceeds",
"exceeds the maximum number of tokens",
"maximum input tokens",
"too many tokens in the prompt",
"request exceeds the context",
"context limit exceeded",
"context size exceeded",
"exceeds context",
"input tokens exceed",
"prompt tokens exceed",
"prompt token count exceeds",
"token limit exceeded",
"input too large",
"prompt too large",
],
)
}
#[inline]
#[must_use]
pub fn classify_error_message(msg: &str) -> ErrorCategory {
let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
Cow::Owned(msg.to_ascii_lowercase())
} else {
Cow::Borrowed(msg)
};
if contains_any(
&msg,
&[
"policy violation",
"denied by policy",
"tool permission denied",
"safety validation failed",
"not allowed in planning workflow",
"only available when planning workflow is active",
"workspace boundary",
"blocked by policy",
],
) {
return ErrorCategory::PolicyViolation;
}
if contains_any(
&msg,
&[
"planning workflow",
"read-only permissions",
concat!("read-only ", "mode"),
"planning_policy_violation",
],
) {
return ErrorCategory::PlanningPolicyViolation;
}
if contains_any(
&msg,
&[
"invalid api key",
"authentication failed",
"unauthorized",
"401",
"invalid credentials",
],
) {
return ErrorCategory::Authentication;
}
if contains_any(
&msg,
&[
"weekly usage limit",
"daily usage limit",
"monthly spending limit",
"insufficient credits",
"quota exceeded",
"billing",
"payment required",
],
) {
return ErrorCategory::ResourceExhausted;
}
if contains_any(
&msg,
&[
"invalid argument",
"invalid parameters",
"invalid type",
"malformed",
"failed to parse arguments",
"failed to parse argument",
"missing required",
"at least one item is required",
"is required for",
"schema validation",
"argument validation failed",
"unknown field",
"unknown variant",
"expected struct",
"expected enum",
"type mismatch",
"must be an absolute path",
"not parseable",
"parseable as",
"invalid patch format",
"invalid patch hunk",
"invalid patch operation",
"cannot parse empty patch",
"patch does not contain",
"semantic patch anchor",
],
) {
return ErrorCategory::InvalidParameters;
}
if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
return ErrorCategory::ToolNotFound;
}
if contains_any(
&msg,
&[
"no such file",
"no such directory",
"file not found",
"directory not found",
"resource not found",
"path not found",
"does not exist",
"enoent",
],
) {
return ErrorCategory::ResourceNotFound;
}
if contains_any(
&msg,
&[
"permission denied",
"access denied",
"operation not permitted",
"eacces",
"eperm",
"forbidden",
"403",
],
) {
return ErrorCategory::PermissionDenied;
}
if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
return ErrorCategory::Cancelled;
}
if contains_any(&msg, &["circuit breaker", "circuit open"]) {
return ErrorCategory::CircuitOpen;
}
if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
return ErrorCategory::SandboxFailure;
}
if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
return ErrorCategory::RateLimit;
}
if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
return ErrorCategory::Timeout;
}
if contains_any(
&msg,
&[
"invalid response format: missing choices",
"invalid response format: missing message",
"missing choices in response",
"missing message in choice",
"no choices in response",
"invalid response from ",
"empty response body",
"response did not contain",
"unexpected response format",
"failed to parse response",
"stream disconnected",
"stream closed unexpectedly",
"incomplete stream",
"unexpected end of stream",
"truncated response",
"failed to decode stream",
"stream terminated",
],
) {
return ErrorCategory::ServiceUnavailable;
}
if contains_any(&msg, &["without an event boundary"]) {
return ErrorCategory::ExecutionError;
}
if contains_any(
&msg,
&[
"service unavailable",
"temporarily unavailable",
"internal server error",
"bad gateway",
"gateway timeout",
"overloaded",
"500",
"502",
"503",
"504",
],
) {
return ErrorCategory::ServiceUnavailable;
}
if contains_any(
&msg,
&[
"network",
"connection reset",
"connection refused",
"broken pipe",
"dns",
"name resolution",
"try again",
"retry later",
"upstream connect error",
"tls handshake",
"socket hang up",
"econnreset",
"etimedout",
"error decoding response body",
"connection closed before",
"stream reset",
"stream error received",
],
) {
return ErrorCategory::Network;
}
if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
return ErrorCategory::ResourceExhausted;
}
ErrorCategory::ExecutionError
}
#[inline]
#[must_use]
pub fn is_retryable_llm_error_message(msg: &str) -> bool {
let category = classify_error_message(msg);
category.is_retryable()
}
#[inline]
fn contains_any(message: &str, markers: &[&str]) -> bool {
markers.iter().any(|marker| message.contains(marker))
}
impl From<&crate::llm::LLMError> for ErrorCategory {
fn from(err: &crate::llm::LLMError) -> Self {
match err {
crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
crate::llm::LLMError::RateLimit { metadata } => {
classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
}
crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
crate::llm::LLMError::Provider { message, metadata } => {
let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
if metadata_category != ErrorCategory::ExecutionError {
return metadata_category;
}
if let Some(meta) = metadata
&& let Some(status) = meta.status
{
return match status {
401 => ErrorCategory::Authentication,
403 => ErrorCategory::PermissionDenied,
404 => ErrorCategory::ResourceNotFound,
429 => ErrorCategory::RateLimit,
400 => ErrorCategory::InvalidParameters,
500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
408 => ErrorCategory::Timeout,
_ => classify_error_message(message),
};
}
classify_error_message(message)
}
}
}
}
fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
let Some(metadata) = metadata else {
return fallback;
};
let mut hint = String::new();
if let Some(code) = &metadata.code {
hint.push_str(code);
hint.push(' ');
}
if let Some(message) = &metadata.message {
hint.push_str(message);
hint.push(' ');
}
if let Some(status) = metadata.status {
let _ = write!(&mut hint, "{status}");
}
let classified = classify_error_message(&hint);
if classified == ErrorCategory::ExecutionError {
fallback
} else {
classified
}
}
mod recovery;
#[cfg(test)]
mod tests;