返回 CodeWhale
lib.rs
1 //! Shared error taxonomy across client, tools, runtime, and UI.
2 use std::fmt;
3
4 use codewhale_tools::ToolError;
5
6 /// Broad category for typed error handling and policy decisions.
7 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
8 #[serde(rename_all = "snake_case")]
9 pub enum ErrorCategory {
10 Network,
11 Authentication,
12 Authorization,
13 RateLimit,
14 Timeout,
15 Budget,
16 InvalidInput,
17 Parse,
18 Tool,
19 State,
20 Internal,
21 }
22
23 /// Severity hint for UI and logs.
24 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
25 #[serde(rename_all = "snake_case")]
26 pub enum ErrorSeverity {
27 Info,
28 Warning,
29 Error,
30 Critical,
31 }
32
33 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
34 #[serde(rename_all = "snake_case")]
35 pub enum RequestTransmission {
36 NotDispatched,
37 Rejected,
38 OutcomeUnknown,
39 }
40
41 /// Error code for a provider credential rejection (401-class) that arrived
42 /// before any model output, after the engine took the turn's question back
43 /// out of the session (#6566). Hosts that see it return the text to the
44 /// person to send again; nothing else about the authentication error changes.
45 pub const CREDENTIAL_REJECTED_UNSENT_CODE: &str = "llm_auth_rejected_unsent";
46
47 /// Unified envelope used when crossing subsystem boundaries.
48 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
49 pub struct ErrorEnvelope {
50 pub category: ErrorCategory,
51 pub severity: ErrorSeverity,
52 pub recoverable: bool,
53 pub code: String,
54 pub message: String,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub request_transmission: Option<RequestTransmission>,
57 }
58
59 impl fmt::Display for ErrorCategory {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 let label = match self {
62 Self::Network => "network",
63 Self::Authentication => "authentication",
64 Self::Authorization => "authorization",
65 Self::RateLimit => "rate_limit",
66 Self::Timeout => "timeout",
67 Self::Budget => "budget",
68 Self::InvalidInput => "invalid_input",
69 Self::Parse => "parse",
70 Self::Tool => "tool",
71 Self::State => "state",
72 Self::Internal => "internal",
73 };
74 f.write_str(label)
75 }
76 }
77
78 impl fmt::Display for ErrorSeverity {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 let label = match self {
81 Self::Info => "info",
82 Self::Warning => "warning",
83 Self::Error => "error",
84 Self::Critical => "critical",
85 };
86 f.write_str(label)
87 }
88 }
89
90 impl fmt::Display for RequestTransmission {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 let label = match self {
93 Self::NotDispatched => "not_dispatched",
94 Self::Rejected => "rejected",
95 Self::OutcomeUnknown => "outcome_unknown",
96 };
97 f.write_str(label)
98 }
99 }
100
101 impl fmt::Display for ErrorEnvelope {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 write!(f, "[{}] {}: {}", self.severity, self.code, self.message)
104 }
105 }
106
107 impl std::error::Error for ErrorEnvelope {}
108
109 impl ErrorEnvelope {
110 #[must_use]
111 pub fn new(
112 category: ErrorCategory,
113 severity: ErrorSeverity,
114 recoverable: bool,
115 code: impl Into<String>,
116 message: impl Into<String>,
117 ) -> Self {
118 Self {
119 category,
120 severity,
121 recoverable,
122 code: code.into(),
123 message: message.into(),
124 request_transmission: None,
125 }
126 }
127
128 /// Recoverable internal error — stream stalls, transient retries, generic
129 /// engine errors that the user can resolve by retrying. Severity is
130 /// `Warning` so the UI surfaces it in amber rather than red.
131 #[must_use]
132 pub fn transient(message: impl Into<String>) -> Self {
133 Self::new(
134 ErrorCategory::Internal,
135 ErrorSeverity::Warning,
136 true,
137 "transient",
138 message,
139 )
140 }
141
142 /// Non-recoverable internal error — missing client, spawn failure, etc.
143 /// Flips the session into offline mode.
144 #[must_use]
145 #[cfg(any(test, feature = "test-support"))]
146 pub fn fatal(message: impl Into<String>) -> Self {
147 Self::new(
148 ErrorCategory::Internal,
149 ErrorSeverity::Error,
150 false,
151 "fatal",
152 message,
153 )
154 }
155
156 /// Authentication failure — fatal for the attempted operation.
157 #[must_use]
158 pub fn fatal_auth(message: impl Into<String>) -> Self {
159 Self::new(
160 ErrorCategory::Authentication,
161 ErrorSeverity::Critical,
162 false,
163 "auth_fatal",
164 message,
165 )
166 }
167
168 /// Context length / overflow — invalid input, recoverable via /compact.
169 #[must_use]
170 pub fn context_overflow(message: impl Into<String>) -> Self {
171 Self::new(
172 ErrorCategory::InvalidInput,
173 ErrorSeverity::Error,
174 true,
175 "context_overflow",
176 message,
177 )
178 }
179
180 #[must_use]
181 pub fn image_count_exceeded(message: impl Into<String>) -> Self {
182 Self::new(
183 ErrorCategory::InvalidInput,
184 ErrorSeverity::Error,
185 true,
186 "image_count_exceeded",
187 message,
188 )
189 }
190
191 /// A stop Codewhale applied to itself (step ceiling, per-turn wall clock).
192 /// The turn failed, so the card is an error, but the session stays usable:
193 /// sending another message continues, so it is `recoverable` and does not
194 /// flip the session offline (#6843).
195 #[must_use]
196 pub fn budget_stop(message: impl Into<String>) -> Self {
197 Self::new(
198 ErrorCategory::Budget,
199 ErrorSeverity::Error,
200 true,
201 "turn_budget_stop",
202 message,
203 )
204 }
205
206 /// Recoverable network / transport hiccup.
207 #[must_use]
208 #[cfg(any(test, feature = "test-support"))]
209 pub fn network(message: impl Into<String>) -> Self {
210 Self::new(
211 ErrorCategory::Network,
212 ErrorSeverity::Warning,
213 true,
214 "network_transient",
215 message,
216 )
217 }
218
219 /// Build an envelope by classifying a raw error message string. Used at
220 /// boundaries where the underlying error type was already stringified.
221 #[must_use]
222 pub fn classify(message: impl Into<String>, recoverable: bool) -> Self {
223 let message = message.into();
224 let category = classify_error_message(&message);
225 let severity = match category {
226 ErrorCategory::Authentication => ErrorSeverity::Critical,
227 // A transient class stays amber only while the caller still
228 // expects the work to continue; `recoverable = false` means it
229 // ended (an error frame that failed the turn, a spent balance),
230 // and an ended turn is never rendered as a warning (#6795).
231 ErrorCategory::RateLimit
232 | ErrorCategory::Timeout
233 | ErrorCategory::Network
234 | ErrorCategory::Budget => {
235 if recoverable {
236 ErrorSeverity::Warning
237 } else {
238 ErrorSeverity::Error
239 }
240 }
241 ErrorCategory::InvalidInput | ErrorCategory::Authorization | ErrorCategory::Parse => {
242 ErrorSeverity::Error
243 }
244 ErrorCategory::Tool | ErrorCategory::State | ErrorCategory::Internal => {
245 if recoverable {
246 ErrorSeverity::Warning
247 } else {
248 ErrorSeverity::Error
249 }
250 }
251 };
252 Self::new(
253 category,
254 severity,
255 recoverable,
256 category.to_string(),
257 message,
258 )
259 }
260 }
261
262 /// Classify an error message string into an ErrorCategory.
263 ///
264 /// Uses heuristic keyword matching on the lowercased message.
265 /// This is a replacement for ad-hoc string matching in callers.
266 #[must_use]
267 pub fn classify_error_message(message: &str) -> ErrorCategory {
268 let lower = message.to_lowercase();
269
270 // A bare placeholder ("ERROR") carries no cause to classify. Say so
271 // instead of letting it fall to `Internal` (#6843).
272 if is_unreadable_error_text(&lower) || lower.contains("unreadable error") {
273 return ErrorCategory::Parse;
274 }
275 // Codewhale's own ceilings (step count, per-turn wall clock) and any
276 // provider text that names an exhausted budget.
277 if lower.contains("maximum model steps")
278 || lower.contains("step budget exhausted")
279 || lower.contains("wall-clock budget")
280 || lower.contains("wall clock budget")
281 || lower.contains("budget exhausted")
282 {
283 return ErrorCategory::Budget;
284 }
285 if lower.contains("model output truncated")
286 || lower.contains("model response incomplete")
287 || lower.contains("maximum context length")
288 || lower.contains("context length")
289 || lower.contains("context_length")
290 || lower.contains("prompt is too long")
291 || (lower.contains("requested") && lower.contains("tokens") && lower.contains("maximum"))
292 || lower.contains("context window")
293 // Codewhale's own overflow stop: the request no longer fits the
294 // route's context budget and automatic recovery gave up.
295 || lower.contains("context budget")
296 // A turn that ended on a terminal stop reason with nothing usable is
297 // an incomplete model response, like the two arms above, not a tool
298 // fault that merely mentions "tool call".
299 || lower.contains("no answer or tool call")
300 || lower.contains("model not exist")
301 || lower.contains("model not found")
302 || lower.contains("no such model")
303 || lower.contains("unknown model")
304 || lower.contains("invalid model")
305 || lower.contains("model does not exist")
306 || lower.starts_with("model error:")
307 {
308 return ErrorCategory::InvalidInput;
309 }
310 if lower.contains("rate limit")
311 || lower.contains("too many requests")
312 || lower.contains("request rate increased too quickly")
313 // Status codes are standalone tokens, not digits inside a URL or ID.
314 || lower.split_whitespace().any(|part| {
315 part.trim_matches(['(', ')', '[', ']', '{', '}', ':', ';', ',', '.', '\'', '"'])
316 == "429"
317 })
318 || is_spent_balance_text(&lower)
319 {
320 return ErrorCategory::RateLimit;
321 }
322 if lower.contains("timeout") || lower.contains("timed out") {
323 return ErrorCategory::Timeout;
324 }
325 if lower.contains("authentication")
326 || lower.contains("auth failed")
327 || lower.contains("auth error")
328 || lower.contains("unauthorized")
329 || lower.contains("api key")
330 || lower.contains("invalid key")
331 || lower.contains("invalid token")
332 || lower.contains("bearer token")
333 {
334 return ErrorCategory::Authentication;
335 }
336 if lower.contains("authorization")
337 || lower.contains("permission")
338 || lower.contains("forbidden")
339 || lower.contains("denied")
340 {
341 return ErrorCategory::Authorization;
342 }
343 // A rejected request is determinate: the same input fails again, so it is
344 // an input fault, not an internal one (#6843). Placed after the
345 // credential, quota and timeout vocabulary so an explicit billing or auth
346 // reason inside a 400 body still wins.
347 if lower.contains("invalid request")
348 || lower.contains("invalid_request_error")
349 || lower.contains("bad request")
350 || lower.contains("unprocessable")
351 || lower.contains("payload too large")
352 || lower.contains("request entity too large")
353 || mentions_http_status(&lower, &[400, 405, 409, 410, 413, 415, 422])
354 {
355 return ErrorCategory::InvalidInput;
356 }
357 if lower.contains("network")
358 || lower.contains("connection")
359 || lower.contains("dns")
360 || lower.contains("stream read error")
361 || lower.contains("error decoding response body")
362 || lower.contains("chunk decode error")
363 || lower.contains("body decode")
364 || lower.contains("temporarily unavailable")
365 // Gateways report a failed or empty upstream inside a 200 with this
366 // wording (OpenRouter); it is the upstream being unreachable.
367 || lower.contains("provider returned error")
368 || lower.contains("provider returned an empty response")
369 || lower.contains("malformed_response")
370 || lower.contains("upstream sse stream failed")
371 // Upstream 5xx wording, as a status or as the reason phrase.
372 || lower.contains("bad gateway")
373 || lower.contains("service unavailable")
374 || lower.contains("internal server error")
375 || lower.contains("overloaded")
376 || mentions_http_status(&lower, &[500, 502, 503, 504, 525, 529])
377 || lower.contains(" 502 ")
378 || lower.contains(" 503 ")
379 || lower.contains(" 504 ")
380 || lower.starts_with("502 ")
381 || lower.starts_with("503 ")
382 || lower.starts_with("504 ")
383 || lower.ends_with(" 502")
384 || lower.ends_with(" 503")
385 || lower.ends_with(" 504")
386 || lower == "502"
387 || lower == "503"
388 || lower == "504"
389 {
390 return ErrorCategory::Network;
391 }
392 if lower.contains("parse") || lower.contains("syntax") || lower.contains("malformed") {
393 return ErrorCategory::Parse;
394 }
395 if lower.contains("not found")
396 || lower.contains("unavailable")
397 || lower.contains("not available")
398 {
399 return ErrorCategory::State;
400 }
401 if lower.contains("tool") {
402 return ErrorCategory::Tool;
403 }
404
405 ErrorCategory::Internal
406 }
407
408 /// True when `message` reports an exhausted balance rather than a
409 /// short-lived limit: quota, usage limit, or a prepaid gateway's HTTP 402
410 /// ("Insufficient funds"). The operator resolves it by topping up or switching
411 /// route, so resending the same request cannot help.
412 pub fn is_spent_balance_message(message: &str) -> bool {
413 is_spent_balance_text(&message.to_lowercase())
414 }
415
416 /// True when `lower` (already lowercased) reports an exhausted balance rather
417 /// than a short-lived limit: quota, usage limit, or a prepaid gateway's HTTP
418 /// 402 ("Insufficient funds"). The operator resolves it by topping up or
419 /// switching route, so resending the same request cannot help.
420 fn is_spent_balance_text(lower: &str) -> bool {
421 lower.contains("quota")
422 || lower.contains("usage limit")
423 || lower.contains("insufficient credits")
424 || lower.contains("insufficient funds")
425 || lower.contains("payment required")
426 || lower.contains("http 402")
427 }
428
429 /// True when a provider "error" is only a placeholder word such as `ERROR`.
430 /// `lower` is lowercased. An empty string is not a placeholder here: callers
431 /// that hold an empty diagnostic mean "nothing recorded", not "unreadable".
432 fn is_unreadable_error_text(lower: &str) -> bool {
433 let token = lower.trim().trim_matches(|c: char| !c.is_alphanumeric());
434 matches!(token, "error" | "err" | "unknown error")
435 }
436
437 /// What the transcript says instead of a bare placeholder error text, or
438 /// `None` when the text is readable. The wording classifies as
439 /// [`ErrorCategory::Parse`], the "unreadable" label (#6843).
440 #[must_use]
441 pub fn unreadable_error_notice(message: &str) -> Option<String> {
442 let trimmed = message.trim();
443 if !trimmed.is_empty() && !is_unreadable_error_text(&message.to_lowercase()) {
444 return None;
445 }
446 Some(if trimmed.is_empty() {
447 "The provider reported an unreadable error: it sent no error text.".to_string()
448 } else {
449 format!(
450 "The provider reported an unreadable error: it sent only \"{trimmed}\" with no detail."
451 )
452 })
453 }
454
455 /// True when `lower` names one of `codes` as an HTTP status ("HTTP 422",
456 /// "status 413", "status code: 500"). A bare number is never a status: digits
457 /// inside a URL, an ID or a count must not classify a failure.
458 fn mentions_http_status(lower: &str, codes: &[u16]) -> bool {
459 [
460 "http ",
461 "status ",
462 "status: ",
463 "status code ",
464 "status code: ",
465 ]
466 .iter()
467 .any(|prefix| {
468 lower.match_indices(prefix).any(|(at, _)| {
469 let rest = &lower[at + prefix.len()..];
470 let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
471 digits.len() == 3
472 && digits
473 .parse::<u16>()
474 .is_ok_and(|code| codes.contains(&code))
475 })
476 })
477 }
478
479 impl From<ToolError> for ErrorEnvelope {
480 fn from(value: ToolError) -> Self {
481 match value {
482 ToolError::InvalidInput { message } => Self::new(
483 ErrorCategory::InvalidInput,
484 ErrorSeverity::Error,
485 false,
486 "tool_invalid_input",
487 message,
488 ),
489 ToolError::MissingField { field } => Self::new(
490 ErrorCategory::InvalidInput,
491 ErrorSeverity::Error,
492 false,
493 "tool_missing_field",
494 format!("Missing required field: {field}"),
495 ),
496 ToolError::PathEscape { path } => Self::new(
497 ErrorCategory::Authorization,
498 ErrorSeverity::Error,
499 false,
500 "tool_path_escape",
501 format!("Path escapes workspace: {}", path.display()),
502 ),
503 ToolError::ExecutionFailed { message, .. } => Self::new(
504 ErrorCategory::Tool,
505 ErrorSeverity::Error,
506 true,
507 "tool_execution_failed",
508 message,
509 ),
510 ToolError::Timeout { seconds } => Self::new(
511 ErrorCategory::Timeout,
512 ErrorSeverity::Warning,
513 true,
514 "tool_timeout",
515 format!("Tool timed out after {seconds}s"),
516 ),
517 ToolError::Cancelled { message } => Self::new(
518 ErrorCategory::Tool,
519 ErrorSeverity::Info,
520 false,
521 "tool_cancelled",
522 message,
523 ),
524 ToolError::NotAvailable { message } => Self::new(
525 ErrorCategory::State,
526 ErrorSeverity::Error,
527 false,
528 "tool_not_available",
529 message,
530 ),
531 ToolError::PermissionDenied { message } => Self::new(
532 ErrorCategory::Authorization,
533 ErrorSeverity::Error,
534 false,
535 "tool_permission_denied",
536 message,
537 ),
538 }
539 }
540 }
541
542 /// Stream‑level error discriminated by origin.
543 ///
544 /// Each variant maps to an `ErrorCategory` so the UI can render
545 /// stream‑specific icons or formatting. Wired into engine.rs at the three
546 /// stream guard sites (chunk timeout, max-bytes overflow, max-duration).
547 #[derive(Debug, Clone)]
548 pub enum StreamError {
549 /// Stream stalled — no chunk received within the idle timeout.
550 Stall { timeout_secs: u64 },
551 /// Stream exceeded content size limit.
552 Overflow { limit_bytes: usize },
553 /// Stream exceeded wall‑clock duration limit.
554 DurationLimit { limit_secs: u64 },
555 }
556
557 impl StreamError {
558 /// Convert directly into an `ErrorEnvelope` for emission on the engine
559 /// event channel. Stalls are warning-severity and recoverable; size and
560 /// duration limits are errors (the user must restart the turn).
561 #[must_use]
562 pub fn into_envelope(self) -> ErrorEnvelope {
563 match self {
564 Self::Stall { timeout_secs } => ErrorEnvelope::new(
565 ErrorCategory::Timeout,
566 ErrorSeverity::Warning,
567 true,
568 "stream_stall",
569 format!("Stream stalled: no data received for {timeout_secs}s, closing stream"),
570 ),
571 Self::Overflow { limit_bytes } => ErrorEnvelope::new(
572 ErrorCategory::Internal,
573 ErrorSeverity::Error,
574 true,
575 "stream_overflow",
576 format!("Stream exceeded maximum content size of {limit_bytes} bytes, closing"),
577 ),
578 Self::DurationLimit { limit_secs } => ErrorEnvelope::new(
579 ErrorCategory::Timeout,
580 ErrorSeverity::Error,
581 true,
582 "stream_duration_limit",
583 format!("Stream exceeded maximum duration of {limit_secs}s, closing"),
584 ),
585 }
586 }
587 }
588
589 impl fmt::Display for StreamError {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 match self {
592 Self::Stall { timeout_secs } => {
593 write!(f, "Stream stalled after {timeout_secs}s idle")
594 }
595 Self::Overflow { limit_bytes } => {
596 write!(f, "Stream exceeded {limit_bytes} bytes limit")
597 }
598 Self::DurationLimit { limit_secs } => {
599 write!(f, "Stream exceeded {limit_secs}s duration limit")
600 }
601 }
602 }
603 }
604
605 impl std::error::Error for StreamError {}
606
607 #[cfg(test)]
608 #[path = "tests.rs"]
609 mod quota_tests;
610
611 #[cfg(test)]
612 mod tests {
613 use super::*;
614
615 fn classify(msg: &str) -> ErrorCategory {
616 classify_error_message(msg)
617 }
618
619 #[test]
620 fn invalid_input_catches_context_overflow_phrasings() {
621 // Provider phrasing varies: DeepSeek/OpenAI/Anthropic/etc each
622 // surface context-overflow as a slightly different string.
623 // The classifier needs all of them on the same branch.
624 for msg in [
625 "This model's maximum context length is 1000000 tokens",
626 "Error: context_length_exceeded",
627 "Your prompt is too long for the current model",
628 "You requested 100000 tokens but the maximum is 65536",
629 "request exceeds context window",
630 ] {
631 assert_eq!(
632 classify(msg),
633 ErrorCategory::InvalidInput,
634 "expected InvalidInput for `{msg}`",
635 );
636 }
637 }
638
639 /// A prepaid gateway's exhausted balance (HTTP 402) is a quota condition:
640 /// the request was well-formed and the key was valid.
641 #[test]
642 fn insufficient_credits_classifies_as_rate_limit_not_auth() {
643 for msg in [
644 "Responses API error (HTTP 402 Payment Required): {\"error\":\"Insufficient funds\",\"message\":\"Your account has insufficient credits. Please add credits to continue.\"}",
645 "insufficient credits",
646 ] {
647 assert_eq!(
648 classify(msg),
649 ErrorCategory::RateLimit,
650 "expected RateLimit for `{msg}`"
651 );
652 }
653 // The documented 401 body still classifies as authentication.
654 assert_eq!(
655 classify(
656 "Responses API error (HTTP 401 Unauthorized): {\"error\":\"Unauthorized\",\"message\":\"Invalid API key\"}"
657 ),
658 ErrorCategory::Authentication
659 );
660 }
661
662 #[test]
663 fn standalone_rate_limit_status_beats_authentication() {
664 for msg in [
665 "429",
666 "HTTP 429: rejected",
667 "upstream response (429)",
668 "[429]: rejected",
669 "HTTP 429: Invalid API key",
670 "Server error (503): The request rate increased too quickly",
671 ] {
672 assert_eq!(classify(msg), ErrorCategory::RateLimit, "{msg}");
673 }
674 }
675
676 #[test]
677 fn numbers_in_urls_and_identifiers_are_not_rate_limit_statuses() {
678 for location in [
679 "http://127.0.0.1:42981/v1/responses",
680 "http://127.0.0.1:14290/v1/responses",
681 "http://127.0.0.1:429/v1/responses",
682 "https://example.test/429",
683 "https://example.test/?request_id=429",
684 "/429",
685 "request_429",
686 "request-429",
687 "14290",
688 ] {
689 let msg = format!(
690 "Responses API error (HTTP 401 Unauthorized) at {location}: Invalid API key"
691 );
692 assert_eq!(classify(&msg), ErrorCategory::Authentication, "{msg}");
693 }
694 assert_eq!(
695 classify("Network request failed for https://example.test/429"),
696 ErrorCategory::Network
697 );
698 assert_eq!(classify("request_429 failed"), ErrorCategory::Internal);
699 }
700
701 #[test]
702 fn timeout_catches_both_spellings() {
703 assert_eq!(classify("connection timeout"), ErrorCategory::Timeout);
704 assert_eq!(
705 classify("request timed out after 30s"),
706 ErrorCategory::Timeout
707 );
708 }
709
710 #[test]
711 fn network_catches_stream_body_decode_failures() {
712 for msg in [
713 "Warn Stream read error: error decoding response body",
714 "Stream read error: error decoding response body",
715 "chunk decode error",
716 "provider body decode failed mid-stream",
717 ] {
718 assert_eq!(
719 classify(msg),
720 ErrorCategory::Network,
721 "expected Network for `{msg}`",
722 );
723 }
724 }
725
726 #[test]
727 fn authentication_beats_authorization_when_api_key_phrasing_is_used() {
728 // "api key" landing on Authentication (not Authorization) keeps
729 // the operator-facing message correct: the user needs to fix
730 // their key, not their permissions.
731 for msg in [
732 "Invalid API key provided",
733 "Authentication failed",
734 "401 Unauthorized",
735 ] {
736 assert_eq!(
737 classify(msg),
738 ErrorCategory::Authentication,
739 "expected Authentication for `{msg}`",
740 );
741 }
742 }
743
744 #[test]
745 fn authorization_catches_forbidden_and_denied() {
746 for msg in [
747 "403 Forbidden",
748 "Authorization failed: Arcee AI API returned Cloudflare Access Denied",
749 "Permission denied for resource",
750 "Tool 'edit_file' denied by user",
751 ] {
752 assert_eq!(
753 classify(msg),
754 ErrorCategory::Authorization,
755 "expected Authorization for `{msg}`",
756 );
757 }
758 }
759
760 #[test]
761 fn network_catches_dns_connection_5xx() {
762 for msg in [
763 "Network is unreachable",
764 "Connection reset by peer",
765 "DNS resolution failed for api.deepseek.com",
766 "503 Service Unavailable",
767 "Upstream returned 502 Bad Gateway",
768 "Service temporarily unavailable",
769 "Gemini finished with MALFORMED_RESPONSE",
770 "OpenRouter: upstream SSE stream failed",
771 "HTTP 525 from gateway",
772 ] {
773 assert_eq!(
774 classify(msg),
775 ErrorCategory::Network,
776 "expected Network for `{msg}`",
777 );
778 }
779 // Edge-case precedence: "504 Gateway Timeout" mentions both
780 // a 504 status code AND the word "timeout". The classifier
781 // picks Timeout, which is correct — the operator-actionable
782 // category for a 504 is "wait and retry" (Timeout semantics)
783 // rather than "DNS / connection broken" (Network semantics).
784 assert_eq!(
785 classify("504 Gateway Timeout"),
786 ErrorCategory::Timeout,
787 "504 with the literal word `timeout` resolves as Timeout, not Network"
788 );
789 }
790
791 #[test]
792 fn parse_catches_syntax_and_malformed_json() {
793 for msg in [
794 "Failed to parse response JSON",
795 "Syntax error in tool arguments",
796 "Malformed event from stream",
797 ] {
798 assert_eq!(
799 classify(msg),
800 ErrorCategory::Parse,
801 "expected Parse for `{msg}`",
802 );
803 }
804 }
805
806 #[test]
807 fn state_catches_not_found_and_unavailable() {
808 for msg in [
809 "Session not found",
810 "Model is unavailable for this provider",
811 "Endpoint not available in this region",
812 ] {
813 assert_eq!(
814 classify(msg),
815 ErrorCategory::State,
816 "expected State for `{msg}`",
817 );
818 }
819 }
820
821 #[test]
822 fn tool_is_a_low_priority_catchall_for_tool_keyword() {
823 // The Tool branch is the last keyword check before falling
824 // through to Internal. Anything mentioning "tool" that didn't
825 // match an earlier category should land here.
826 assert_eq!(
827 classify("Tool returned non-zero exit status"),
828 ErrorCategory::Tool,
829 );
830 }
831
832 #[test]
833 fn unknown_messages_fall_through_to_internal() {
834 for msg in [
835 "Something exploded",
836 "panic at the disco",
837 "u-200 something happened",
838 "",
839 ] {
840 assert_eq!(
841 classify(msg),
842 ErrorCategory::Internal,
843 "expected Internal for `{msg}`",
844 );
845 }
846 }
847
848 #[test]
849 fn classifier_is_case_insensitive() {
850 // The function lowercases internally — every category must
851 // match regardless of input casing.
852 assert_eq!(classify("RATE LIMIT EXCEEDED"), ErrorCategory::RateLimit);
853 assert_eq!(classify("TimeOut"), ErrorCategory::Timeout);
854 assert_eq!(classify("UNAUTHORIZED"), ErrorCategory::Authentication);
855 }
856
857 #[test]
858 fn precedence_invalid_input_beats_tool() {
859 // A "context length" tool error should classify as
860 // InvalidInput, not Tool — InvalidInput is the more actionable
861 // category (the user needs to shorten their prompt; "tool
862 // failure" wouldn't tell them that).
863 assert_eq!(
864 classify("tool returned: maximum context length is 1000000"),
865 ErrorCategory::InvalidInput,
866 );
867 }
868
869 #[test]
870 fn precedence_timeout_beats_network() {
871 // A timeout that mentions a network call should still classify
872 // as Timeout — the retry policy for timeouts is gentler than
873 // for outright network failures.
874 assert_eq!(
875 classify("network call timed out after 30s"),
876 ErrorCategory::Timeout,
877 );
878 }
879
880 #[test]
881 fn precedence_rate_limit_beats_authentication() {
882 // 429 messages sometimes mention "api" or "auth" tokens, but
883 // RateLimit's retry semantics (back off + retry) are what the
884 // operator actually wants.
885 assert_eq!(
886 classify("Rate limit on your API quota exceeded"),
887 ErrorCategory::RateLimit,
888 );
889 }
890
891 #[test]
892 fn classifier_handles_unicode_safely() {
893 // Unicode shouldn't trip the lowercase step or the keyword
894 // scan — Chinese/Japanese error messages from
895 // OpenAI-compatible providers go through the same path.
896 assert_eq!(
897 classify("\u{8d85}\u{51fa}\u{6700}\u{5927}\u{4e0a}\u{4e0b}\u{6587} context length"),
898 ErrorCategory::InvalidInput,
899 );
900 // Pure-Chinese messages with no keyword match land on Internal.
901 assert_eq!(
902 classify("\u{4e0d}\u{77e5}\u{9053}\u{600e}\u{4e48}\u{56de}\u{4e8b}"),
903 ErrorCategory::Internal,
904 );
905 }
906
907 #[test]
908 fn error_envelope_display_includes_severity_code_message() {
909 let env = ErrorEnvelope::new(
910 ErrorCategory::Network,
911 ErrorSeverity::Warning,
912 true,
913 "net_transient",
914 "DNS resolution failed",
915 );
916 assert_eq!(
917 format!("{env}"),
918 "[warning] net_transient: DNS resolution failed"
919 );
920 }
921
922 #[test]
923 fn request_transmission_display_uses_snake_case() {
924 assert_eq!(
925 RequestTransmission::NotDispatched.to_string(),
926 "not_dispatched"
927 );
928 assert_eq!(RequestTransmission::Rejected.to_string(), "rejected");
929 assert_eq!(
930 RequestTransmission::OutcomeUnknown.to_string(),
931 "outcome_unknown"
932 );
933 }
934
935 #[test]
936 fn error_category_display_round_trips_via_snake_case() {
937 // The snake_case labels are what crosses the wire / hits logs;
938 // pin them so a future rename doesn't silently shift consumer
939 // contracts.
940 assert_eq!(format!("{}", ErrorCategory::Network), "network");
941 assert_eq!(format!("{}", ErrorCategory::RateLimit), "rate_limit");
942 assert_eq!(format!("{}", ErrorCategory::InvalidInput), "invalid_input");
943 assert_eq!(format!("{}", ErrorSeverity::Critical), "critical");
944 }
945 }
946
946 lines RUST