ralph_workflow/agents/
error.rs

1//! Error classification for agent failures.
2//!
3//! This module provides error classification logic to determine appropriate
4//! recovery strategies when agents fail. Different error types warrant
5//! different responses: retry, fallback to another agent, or abort.
6
7/// Check if an agent name or command string indicates a GLM-like agent.
8///
9/// GLM-like agents include GLM, `ZhipuAI`, ZAI, Qwen, and `DeepSeek`.
10/// These agents have known compatibility issues with review tasks and may
11/// require special handling or fallback logic.
12///
13/// # Arguments
14///
15/// * `s` - The agent name or command string to check
16///
17/// # Returns
18///
19/// `true` if the string indicates a GLM-like agent, `false` otherwise
20pub fn is_glm_like_agent(s: &str) -> bool {
21    let s_lower = s.to_lowercase();
22    s_lower.contains("glm")
23        || s_lower.contains("zhipuai")
24        || s_lower.contains("zai")
25        || s_lower.contains("qwen")
26        || s_lower.contains("deepseek")
27}
28
29/// Error classification for agent failures.
30///
31/// Used to determine appropriate recovery strategy when an agent fails:
32/// - `should_retry()` - Try same agent again after delay
33/// - `should_fallback()` - Switch to next agent in the chain
34/// - `is_unrecoverable()` - Abort the pipeline
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum AgentErrorKind {
37    /// API rate limit exceeded - retry after delay.
38    RateLimited,
39    /// Token/context limit exceeded - may need different agent.
40    TokenExhausted,
41    /// API temporarily unavailable (server-side issue) - retry.
42    ApiUnavailable,
43    /// Network connectivity issue (client-side) - retry.
44    NetworkError,
45    /// Authentication failure - switch agent.
46    AuthFailure,
47    /// Command not found - switch agent.
48    CommandNotFound,
49    /// Disk space exhausted - cannot continue.
50    DiskFull,
51    /// Process killed (OOM, signal) - may retry with smaller context.
52    ProcessKilled,
53    /// Invalid JSON response from agent - may retry.
54    InvalidResponse,
55    /// Request/response timeout - retry.
56    Timeout,
57    /// Tool execution failed - should fallback (e.g., file write issues).
58    ToolExecutionFailed,
59    /// Known agent-specific behavioral quirk - should fallback with specific advice.
60    AgentSpecificQuirk,
61    /// Agent-specific issue that may be transient - should retry before falling back.
62    RetryableAgentQuirk,
63    /// Other transient error - retry.
64    Transient,
65    /// Permanent failure - do not retry.
66    Permanent,
67}
68
69impl AgentErrorKind {
70    /// Determine if this error should trigger a retry.
71    pub const fn should_retry(self) -> bool {
72        matches!(
73            self,
74            Self::RateLimited
75                | Self::ApiUnavailable
76                | Self::NetworkError
77                | Self::Timeout
78                | Self::InvalidResponse
79                | Self::RetryableAgentQuirk
80                | Self::Transient
81        )
82    }
83
84    /// Determine if this error should trigger a fallback to another agent.
85    pub const fn should_fallback(self) -> bool {
86        matches!(
87            self,
88            Self::TokenExhausted
89                | Self::AuthFailure
90                | Self::CommandNotFound
91                | Self::ProcessKilled
92                | Self::ToolExecutionFailed
93                | Self::AgentSpecificQuirk
94        )
95    }
96
97    /// Determine if this error is unrecoverable (should abort).
98    pub const fn is_unrecoverable(self) -> bool {
99        matches!(self, Self::DiskFull | Self::Permanent)
100    }
101
102    /// Check if this is a command not found error.
103    pub const fn is_command_not_found(self) -> bool {
104        matches!(self, Self::CommandNotFound)
105    }
106
107    /// Check if this is a network-related error.
108    pub const fn is_network_error(self) -> bool {
109        matches!(self, Self::NetworkError | Self::Timeout)
110    }
111
112    /// Check if this error might be resolved by reducing context size.
113    pub const fn suggests_smaller_context(self) -> bool {
114        matches!(self, Self::TokenExhausted | Self::ProcessKilled)
115    }
116
117    /// Get suggested wait time in milliseconds before retry.
118    pub const fn suggested_wait_ms(self) -> u64 {
119        match self {
120            Self::RateLimited => 5000,    // Rate limit: wait 5 seconds
121            Self::ApiUnavailable => 3000, // Server issue: wait 3 seconds
122            Self::NetworkError => 2000,   // Network: wait 2 seconds
123            Self::Timeout | Self::Transient | Self::RetryableAgentQuirk => 1000, // Timeout/Transient: short wait
124            Self::InvalidResponse => 500, // Bad response: quick retry
125            _ => 0,                       // No wait for non-retryable errors
126        }
127    }
128
129    /// Get a user-friendly description of this error type.
130    pub const fn description(self) -> &'static str {
131        match self {
132            Self::RateLimited => "API rate limit exceeded",
133            Self::TokenExhausted => "Token/context limit exceeded",
134            Self::ApiUnavailable => "API service temporarily unavailable",
135            Self::NetworkError => "Network connectivity issue",
136            Self::AuthFailure => "Authentication failure",
137            Self::CommandNotFound => "Command not found",
138            Self::DiskFull => "Disk space exhausted",
139            Self::ProcessKilled => "Process terminated (possibly OOM)",
140            Self::InvalidResponse => "Invalid response from agent",
141            Self::Timeout => "Request timed out",
142            Self::ToolExecutionFailed => "Tool execution failed (e.g., file write)",
143            Self::AgentSpecificQuirk => "Known agent-specific issue",
144            Self::RetryableAgentQuirk => "Agent-specific issue (may be transient)",
145            Self::Transient => "Transient error",
146            Self::Permanent => "Permanent error",
147        }
148    }
149
150    /// Get recovery advice for this error type.
151    pub const fn recovery_advice(self) -> &'static str {
152        match self {
153            Self::RateLimited => {
154                "Will retry after delay. Tip: Consider reducing request frequency or using a different provider."
155            }
156            Self::TokenExhausted => {
157                "Switching to alternative agent. Tip: Try RALPH_DEVELOPER_CONTEXT=0 or RALPH_REVIEWER_CONTEXT=0"
158            }
159            Self::ApiUnavailable => {
160                "API server issue. Will retry automatically. Tip: Check status page or try different provider."
161            }
162            Self::NetworkError => {
163                "Check your internet connection. Will retry automatically. Tip: Check firewall/VPN settings."
164            }
165            Self::AuthFailure => {
166                "Check API key or run 'agent auth' to authenticate. Tip: Verify credentials for this provider."
167            }
168            Self::CommandNotFound => {
169                "Agent binary not installed. See installation guidance below. Tip: Run 'ralph --list-available-agents'"
170            }
171            Self::DiskFull => "Free up disk space and try again. Tip: Check .agent directory size.",
172            Self::ProcessKilled => {
173                "Process was killed (possible OOM). Trying with smaller context. Tip: Reduce context with RALPH_*_CONTEXT=0"
174            }
175            Self::InvalidResponse => {
176                "Received malformed response. Retrying... Tip: May indicate parser mismatch with this agent."
177            }
178            Self::Timeout => {
179                "Request timed out. Will retry with longer timeout. Tip: Try reducing prompt size or context."
180            }
181            Self::ToolExecutionFailed => {
182                "Tool execution failed (file write/permissions). Switching agent. Tip: Check directory write permissions."
183            }
184            Self::AgentSpecificQuirk => {
185                "Known agent-specific issue. Switching to alternative agent. Tip: See docs/agent-compatibility.md"
186            }
187            Self::RetryableAgentQuirk => {
188                "Agent-specific issue that may be transient. Retrying... Tip: See docs/agent-compatibility.md"
189            }
190            Self::Transient => "Temporary issue. Will retry automatically.",
191            Self::Permanent => {
192                "Unrecoverable error. Check agent logs (.agent/logs/) and see docs/agent-compatibility.md for help."
193            }
194        }
195    }
196
197    /// Classify an error from exit code, output, and agent name.
198    ///
199    /// This variant takes the agent name into account for better classification.
200    /// Some agents have known failure patterns that should trigger fallback
201    /// instead of retry, even when the stderr output is generic.
202    ///
203    /// # Arguments
204    ///
205    /// * `exit_code` - The process exit code
206    /// * `stderr` - The standard error output from the agent
207    /// * `agent_name` - Optional agent name for context-aware classification
208    pub fn classify_with_agent(
209        exit_code: i32,
210        stderr: &str,
211        agent_name: Option<&str>,
212        model_flag: Option<&str>,
213    ) -> Self {
214        let stderr_lower = stderr.to_lowercase();
215
216        // Check for specific error patterns FIRST, before applying agent-specific heuristics.
217        // This ensures that token exhaustion is detected even for GLM-like agents.
218        if let Some(err) = Self::check_api_errors(&stderr_lower) {
219            return err;
220        }
221
222        if let Some(err) = Self::check_network_errors(&stderr_lower) {
223            return err;
224        }
225
226        if let Some(err) = Self::check_resource_errors(exit_code, &stderr_lower) {
227            return err;
228        }
229
230        if let Some(err) = Self::check_tool_failures(&stderr_lower) {
231            return err;
232        }
233
234        // If we know this is a GLM-like agent and it failed with exit code 1
235        // (and we haven't matched a specific error pattern above),
236        // classify based on stderr content:
237        // - If stderr is empty or contains only generic messages, treat as RetryableAgentQuirk
238        // - If stderr contains specific error patterns, it will be caught by check_agent_specific_quirks below
239        let is_problematic_agent =
240            agent_name.is_some_and(is_glm_like_agent) || model_flag.is_some_and(is_glm_like_agent);
241
242        if is_problematic_agent && exit_code == 1 {
243            // Check if stderr has known problematic patterns that indicate unrecoverable issues
244            let has_known_problematic_pattern = stderr_lower.contains("permission")
245                || stderr_lower.contains("denied")
246                || stderr_lower.contains("unauthorized")
247                || stderr_lower.contains("auth")
248                || stderr_lower.contains("token")
249                || stderr_lower.contains("limit")
250                || stderr_lower.contains("quota")
251                || stderr_lower.contains("disk")
252                || stderr_lower.contains("space")
253                // Agent-specific known patterns (from check_agent_specific_quirks)
254                || (stderr_lower.contains("glm") && stderr_lower.contains("failed"))
255                || (stderr_lower.contains("ccs") && stderr_lower.contains("failed"));
256
257            if has_known_problematic_pattern {
258                // Known issue - should fallback
259                return Self::AgentSpecificQuirk;
260            }
261
262            // Unknown error - may be transient, should retry
263            return Self::RetryableAgentQuirk;
264        }
265
266        if let Some(err) = Self::check_agent_specific_quirks(&stderr_lower, exit_code) {
267            return err;
268        }
269
270        if let Some(err) = Self::check_command_not_found(exit_code, &stderr_lower) {
271            return err;
272        }
273
274        // Transient errors (exit codes that might succeed on retry)
275        // This is now a more specific catch-all for actual transient issues
276        if exit_code == 1 && stderr_lower.contains("error") {
277            // But only if it's not a known permanent issue pattern
278            // (permission, tool failures, GLM issues are already handled above)
279            return Self::Transient;
280        }
281
282        Self::Permanent
283    }
284
285    /// Check for API-level errors (rate limiting, auth, server issues).
286    fn check_api_errors(stderr_lower: &str) -> Option<Self> {
287        // Rate limiting indicators (API-side)
288        if stderr_lower.contains("rate limit")
289            || stderr_lower.contains("too many requests")
290            || stderr_lower.contains("429")
291            || stderr_lower.contains("quota exceeded")
292        {
293            return Some(Self::RateLimited);
294        }
295
296        // Token/context exhaustion (API-side)
297        // Check this BEFORE GLM agent-specific fallback to ensure TokenExhausted is detected
298        if stderr_lower.contains("token")
299            || stderr_lower.contains("context length")
300            || stderr_lower.contains("maximum context")
301            || stderr_lower.contains("too long")
302            || stderr_lower.contains("input too large")
303        {
304            return Some(Self::TokenExhausted);
305        }
306
307        // Auth failures
308        if stderr_lower.contains("unauthorized")
309            || stderr_lower.contains("authentication")
310            || stderr_lower.contains("401")
311            || stderr_lower.contains("api key")
312            || stderr_lower.contains("invalid token")
313            || stderr_lower.contains("forbidden")
314            || stderr_lower.contains("403")
315            || stderr_lower.contains("access denied")
316        {
317            return Some(Self::AuthFailure);
318        }
319
320        None
321    }
322
323    /// Check for network and server-side errors.
324    fn check_network_errors(stderr_lower: &str) -> Option<Self> {
325        // Network errors (client-side connectivity issues)
326        if stderr_lower.contains("connection refused")
327            || stderr_lower.contains("network unreachable")
328            || stderr_lower.contains("dns resolution")
329            || stderr_lower.contains("name resolution")
330            || stderr_lower.contains("no route to host")
331            || stderr_lower.contains("network is down")
332            || stderr_lower.contains("host unreachable")
333            || stderr_lower.contains("connection reset")
334            || stderr_lower.contains("broken pipe")
335            || stderr_lower.contains("econnrefused")
336            || stderr_lower.contains("enetunreach")
337        {
338            return Some(Self::NetworkError);
339        }
340
341        // API unavailable (server-side issues)
342        if stderr_lower.contains("service unavailable")
343            || stderr_lower.contains("503")
344            || stderr_lower.contains("502")
345            || stderr_lower.contains("504")
346            || stderr_lower.contains("500")
347            || stderr_lower.contains("internal server error")
348            || stderr_lower.contains("bad gateway")
349            || stderr_lower.contains("gateway timeout")
350            || stderr_lower.contains("overloaded")
351            || stderr_lower.contains("maintenance")
352        {
353            return Some(Self::ApiUnavailable);
354        }
355
356        // Request timeout
357        if stderr_lower.contains("timeout")
358            || stderr_lower.contains("timed out")
359            || stderr_lower.contains("request timeout")
360            || stderr_lower.contains("deadline exceeded")
361        {
362            return Some(Self::Timeout);
363        }
364
365        None
366    }
367
368    /// Check for resource exhaustion errors (disk, memory, process).
369    fn check_resource_errors(exit_code: i32, stderr_lower: &str) -> Option<Self> {
370        // Disk space exhaustion
371        if stderr_lower.contains("no space left")
372            || stderr_lower.contains("disk full")
373            || stderr_lower.contains("enospc")
374            || stderr_lower.contains("out of disk")
375            || stderr_lower.contains("insufficient storage")
376        {
377            return Some(Self::DiskFull);
378        }
379
380        // Process killed (OOM or signals)
381        // Exit code 137 = 128 + 9 (SIGKILL), 139 = 128 + 11 (SIGSEGV)
382        if exit_code == 137
383            || exit_code == 139
384            || exit_code == -9
385            || stderr_lower.contains("killed")
386            || stderr_lower.contains("oom")
387            || stderr_lower.contains("out of memory")
388            || stderr_lower.contains("memory exhausted")
389            || stderr_lower.contains("cannot allocate")
390            || stderr_lower.contains("segmentation fault")
391            || stderr_lower.contains("sigsegv")
392            || stderr_lower.contains("sigkill")
393        {
394            return Some(Self::ProcessKilled);
395        }
396
397        None
398    }
399
400    /// Check for tool and file operation failures.
401    fn check_tool_failures(stderr_lower: &str) -> Option<Self> {
402        // Invalid JSON response
403        if stderr_lower.contains("invalid json")
404            || stderr_lower.contains("json parse")
405            || stderr_lower.contains("unexpected token")
406            || stderr_lower.contains("malformed")
407            || stderr_lower.contains("truncated response")
408            || stderr_lower.contains("incomplete response")
409        {
410            return Some(Self::InvalidResponse);
411        }
412
413        // Tool execution failures (file writes, tool calls, etc.)
414        // These should trigger fallback, not retry
415        if stderr_lower.contains("write error")
416            || stderr_lower.contains("cannot write")
417            || stderr_lower.contains("failed to write")
418            || stderr_lower.contains("unable to create file")
419            || stderr_lower.contains("file creation failed")
420            || stderr_lower.contains("i/o error")
421            || stderr_lower.contains("io error")
422            || stderr_lower.contains("tool failed")
423            || stderr_lower.contains("tool execution failed")
424            || stderr_lower.contains("tool call failed")
425        {
426            return Some(Self::ToolExecutionFailed);
427        }
428
429        // Permission denied errors (specific patterns that should fallback)
430        // These need to be checked BEFORE the generic "error" catch-all
431        // Note: "access denied" is already caught by AuthFailure above (for HTTP 403)
432        // This catches file-system permission errors specifically
433        if stderr_lower.contains("permission denied")
434            || stderr_lower.contains("operation not permitted")
435            || stderr_lower.contains("insufficient permissions")
436            || stderr_lower.contains("eacces")
437            || stderr_lower.contains("eperm")
438        {
439            return Some(Self::ToolExecutionFailed);
440        }
441
442        None
443    }
444
445    /// Check for agent-specific quirks that should trigger fallback.
446    fn check_agent_specific_quirks(stderr_lower: &str, exit_code: i32) -> Option<Self> {
447        // GLM/CCS-specific known issues
448        // These are known quirks that should trigger fallback
449        // Check for CCS-specific error patterns
450        if stderr_lower.contains("ccs") || stderr_lower.contains("glm") {
451            // CCS/GLM with exit code 1 is likely a permission/tool issue
452            if exit_code == 1 {
453                return Some(Self::AgentSpecificQuirk);
454            }
455            // CCS-specific error patterns
456            if stderr_lower.contains("ccs") && stderr_lower.contains("failed") {
457                return Some(Self::AgentSpecificQuirk);
458            }
459            // GLM-specific permission errors
460            if stderr_lower.contains("glm")
461                && (stderr_lower.contains("permission")
462                    || stderr_lower.contains("denied")
463                    || stderr_lower.contains("unauthorized"))
464            {
465                return Some(Self::AgentSpecificQuirk);
466            }
467        }
468
469        // Fallback for GLM with any error and exit code 1
470        if stderr_lower.contains("glm") && exit_code == 1 {
471            return Some(Self::AgentSpecificQuirk);
472        }
473
474        None
475    }
476
477    /// Check for command not found errors.
478    fn check_command_not_found(exit_code: i32, stderr_lower: &str) -> Option<Self> {
479        // Command not found (keep this after permission checks since permission
480        // errors also contain "permission denied")
481        if exit_code == 127
482            || exit_code == 126
483            || stderr_lower.contains("command not found")
484            || stderr_lower.contains("not found")
485            || stderr_lower.contains("no such file")
486        {
487            return Some(Self::CommandNotFound);
488        }
489
490        None
491    }
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497
498    fn classify(exit_code: i32, stderr: &str) -> AgentErrorKind {
499        AgentErrorKind::classify_with_agent(exit_code, stderr, None, None)
500    }
501
502    #[test]
503    fn test_agent_error_kind_should_retry() {
504        assert!(AgentErrorKind::RateLimited.should_retry());
505        assert!(AgentErrorKind::ApiUnavailable.should_retry());
506        assert!(AgentErrorKind::NetworkError.should_retry());
507        assert!(AgentErrorKind::Timeout.should_retry());
508        assert!(AgentErrorKind::InvalidResponse.should_retry());
509        assert!(AgentErrorKind::Transient.should_retry());
510        assert!(AgentErrorKind::RetryableAgentQuirk.should_retry());
511
512        assert!(!AgentErrorKind::AuthFailure.should_retry());
513        assert!(!AgentErrorKind::CommandNotFound.should_retry());
514        assert!(!AgentErrorKind::Permanent.should_retry());
515    }
516
517    #[test]
518    fn test_agent_error_kind_should_fallback() {
519        assert!(AgentErrorKind::TokenExhausted.should_fallback());
520        assert!(AgentErrorKind::AuthFailure.should_fallback());
521        assert!(AgentErrorKind::CommandNotFound.should_fallback());
522        assert!(AgentErrorKind::ProcessKilled.should_fallback());
523        assert!(AgentErrorKind::ToolExecutionFailed.should_fallback());
524        assert!(AgentErrorKind::AgentSpecificQuirk.should_fallback());
525
526        assert!(!AgentErrorKind::RateLimited.should_fallback());
527        assert!(!AgentErrorKind::Permanent.should_fallback());
528    }
529
530    #[test]
531    fn test_agent_error_kind_is_unrecoverable() {
532        assert!(AgentErrorKind::DiskFull.is_unrecoverable());
533        assert!(AgentErrorKind::Permanent.is_unrecoverable());
534
535        assert!(!AgentErrorKind::RateLimited.is_unrecoverable());
536        assert!(!AgentErrorKind::AuthFailure.is_unrecoverable());
537    }
538
539    #[test]
540    fn test_agent_error_kind_classify() {
541        // Rate limiting
542        assert_eq!(
543            classify(1, "rate limit exceeded"),
544            AgentErrorKind::RateLimited
545        );
546        assert_eq!(classify(1, "error 429"), AgentErrorKind::RateLimited);
547
548        // Auth failure
549        assert_eq!(classify(1, "unauthorized"), AgentErrorKind::AuthFailure);
550        assert_eq!(classify(1, "error 401"), AgentErrorKind::AuthFailure);
551
552        // Command not found
553        assert_eq!(classify(127, ""), AgentErrorKind::CommandNotFound);
554        assert_eq!(
555            classify(1, "command not found"),
556            AgentErrorKind::CommandNotFound
557        );
558
559        // Process killed
560        assert_eq!(classify(137, ""), AgentErrorKind::ProcessKilled);
561        assert_eq!(classify(1, "out of memory"), AgentErrorKind::ProcessKilled);
562
563        // Tool execution failures (NEW)
564        assert_eq!(
565            classify(1, "write error"),
566            AgentErrorKind::ToolExecutionFailed
567        );
568        assert_eq!(
569            classify(1, "tool failed"),
570            AgentErrorKind::ToolExecutionFailed
571        );
572        assert_eq!(
573            classify(1, "failed to write"),
574            AgentErrorKind::ToolExecutionFailed
575        );
576
577        // Permission denied errors (should fallback, not retry)
578        assert_eq!(
579            classify(1, "permission denied"),
580            AgentErrorKind::ToolExecutionFailed
581        );
582        assert_eq!(
583            classify(1, "operation not permitted"),
584            AgentErrorKind::ToolExecutionFailed
585        );
586        assert_eq!(
587            classify(1, "insufficient permissions"),
588            AgentErrorKind::ToolExecutionFailed
589        );
590
591        // "access denied" is caught by AuthFailure earlier (HTTP 403)
592        assert_eq!(classify(1, "access denied"), AgentErrorKind::AuthFailure);
593
594        // GLM-specific known issues (NEW)
595        assert_eq!(classify(1, "glm error"), AgentErrorKind::AgentSpecificQuirk);
596        assert_eq!(
597            classify(1, "ccs glm failed"),
598            AgentErrorKind::AgentSpecificQuirk
599        );
600
601        // Generic exit code 1 with "error" is now more selective
602        // It should NOT match patterns that are handled above
603        assert_eq!(classify(1, "some random error"), AgentErrorKind::Transient);
604
605        // GLM with unknown error (no specific pattern) should be RetryableAgentQuirk
606        assert_eq!(
607            AgentErrorKind::classify_with_agent(1, "some random error", Some("ccs/glm"), None),
608            AgentErrorKind::RetryableAgentQuirk
609        );
610
611        // GLM with known problematic patterns - permission denied is caught by check_tool_failures first
612        assert_eq!(
613            AgentErrorKind::classify_with_agent(1, "permission denied", Some("ccs/glm"), None),
614            AgentErrorKind::ToolExecutionFailed // Caught by earlier check
615        );
616        assert_eq!(
617            AgentErrorKind::classify_with_agent(1, "token limit exceeded", Some("ccs/glm"), None),
618            AgentErrorKind::TokenExhausted // Caught by earlier check
619        );
620        assert_eq!(
621            AgentErrorKind::classify_with_agent(1, "disk full", Some("ccs/glm"), None),
622            AgentErrorKind::DiskFull // Caught by earlier check (disk pattern)
623        );
624        // GLM mentioned in stderr with "failed" - AgentSpecificQuirk
625        assert_eq!(
626            AgentErrorKind::classify_with_agent(1, "glm failed", Some("ccs/glm"), None),
627            AgentErrorKind::AgentSpecificQuirk
628        );
629    }
630
631    #[test]
632    fn test_agent_error_kind_description_and_advice() {
633        let error = AgentErrorKind::RateLimited;
634        assert!(!error.description().is_empty());
635        assert!(!error.recovery_advice().is_empty());
636    }
637
638    #[test]
639    fn test_agent_error_kind_suggested_wait_ms() {
640        assert_eq!(AgentErrorKind::RateLimited.suggested_wait_ms(), 5000);
641        assert_eq!(AgentErrorKind::Permanent.suggested_wait_ms(), 0);
642    }
643
644    #[test]
645    fn test_agent_error_kind_suggests_smaller_context() {
646        assert!(AgentErrorKind::TokenExhausted.suggests_smaller_context());
647        assert!(AgentErrorKind::ProcessKilled.suggests_smaller_context());
648        assert!(!AgentErrorKind::RateLimited.suggests_smaller_context());
649    }
650}