Skip to main content

agent_commander/
api_status.rs

1//! HTTP status of a failed API request, for every tool (issues #67, #69).
2//!
3//! - Claude reports it as `result.api_error_status`, and every retry as a
4//!   `{"type":"system","subtype":"api_retry","error_status":401}` event.
5//! - Codex has no structured field: the status is only in the text of its
6//!   `turn.failed` / `error` events (`unexpected status 401 Unauthorized: ...`).
7
8use regex::Regex;
9use serde_json::Value;
10use std::sync::LazyLock;
11
12/// Statuses that refuse the credential: retrying cannot succeed.
13pub const AUTH_REFUSAL_STATUSES: [i64; 2] = [401, 403];
14
15// codex-rs `UnexpectedResponseError` Display: `unexpected status {status}: ...`
16// (also wrapped in `Reconnecting... 1/5 (unexpected status 401 ...)`).
17static CODEX_STATUS_PATTERN: LazyLock<Regex> =
18    LazyLock::new(|| Regex::new(r"(?i)\bunexpected status (\d{3})\b").expect("valid regex"));
19
20fn http_status(value: &Value) -> Option<i64> {
21    value
22        .as_i64()
23        .or_else(|| value.as_str().and_then(|text| text.trim().parse().ok()))
24        .filter(|status| (100..=599).contains(status))
25}
26
27/// Parse the HTTP status from a Codex error text.
28pub fn http_status_from_error_text(text: &str) -> Option<i64> {
29    CODEX_STATUS_PATTERN
30        .captures(text)
31        .and_then(|captures| captures[1].parse().ok())
32}
33
34fn codex_error_text(event: &Value) -> Option<&str> {
35    match event.get("type").and_then(Value::as_str) {
36        Some("turn.failed") => event["error"]["message"]
37            .as_str()
38            .or_else(|| event["message"].as_str()),
39        Some("error") => event["message"]
40            .as_str()
41            .or_else(|| event["error"]["message"].as_str()),
42        _ => None,
43    }
44}
45
46/// HTTP status of the Codex failure that ended the run: the last
47/// `turn.failed` event, or the last `error` event of a turn that did not
48/// complete.
49pub fn codex_api_error_status(messages: &[Value]) -> Option<i64> {
50    let failed = messages
51        .iter()
52        .rev()
53        .find(|event| event["type"] == "turn.failed");
54    if let Some(status) = failed
55        .and_then(codex_error_text)
56        .and_then(http_status_from_error_text)
57    {
58        return Some(status);
59    }
60    if messages
61        .iter()
62        .any(|event| event["type"] == "turn.completed")
63    {
64        return None;
65    }
66    messages
67        .iter()
68        .rev()
69        .filter_map(codex_error_text)
70        .find_map(http_status_from_error_text)
71}
72
73/// The HTTP status a Claude `system/api_retry` event reports.
74pub fn api_retry_status(event: &Value) -> Option<i64> {
75    if event["type"] != "system" || event["subtype"] != "api_retry" {
76        return None;
77    }
78    http_status(&event["error_status"])
79}
80
81/// Status of the last `api_retry` event in the stream.
82pub fn last_api_retry_status(messages: &[Value]) -> Option<i64> {
83    messages.iter().rev().find_map(api_retry_status)
84}
85
86/// The 401/403 a retry event reports: the credential is refused and every
87/// further retry fails the same way (issue #69).
88pub fn auth_refusal_status(event: &Value) -> Option<i64> {
89    api_retry_status(event).filter(|status| AUTH_REFUSAL_STATUSES.contains(status))
90}
91
92/// Message for a run stopped on an authentication refusal.
93pub fn auth_refusal_message(event: &Value) -> String {
94    let status = api_retry_status(event).unwrap_or_default();
95    let retry = match (event["attempt"].as_i64(), event["max_retries"].as_i64()) {
96        (Some(attempt), Some(max)) => format!(" at retry {attempt}/{max}"),
97        (Some(attempt), None) => format!(" at retry {attempt}"),
98        _ => String::new(),
99    };
100    let detail = event["error"]
101        .as_str()
102        .filter(|error| !error.is_empty())
103        .map(|error| format!(" ({error})"))
104        .unwrap_or_default();
105    format!(
106        "API request refused with status {status}{detail}; stopped{retry} by failFastOnAuthError"
107    )
108}
109
110/// The run's API error status.
111///
112/// Claude's `result.api_error_status`, the status in Codex's failure text, or,
113/// when no final result arrived (a run stopped during retries), the status of
114/// the last `api_retry` event.
115pub fn resolve_api_error_status(messages: &[Value]) -> Option<i64> {
116    let result = messages
117        .iter()
118        .rev()
119        .find(|event| event["type"] == "result");
120    if let Some(status) = result.and_then(|result| http_status(&result["api_error_status"])) {
121        return Some(status);
122    }
123    if let Some(status) = codex_api_error_status(messages) {
124        return Some(status);
125    }
126    if result.is_some() {
127        None
128    } else {
129        last_api_retry_status(messages)
130    }
131}