agent-commander 0.7.0

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
//! HTTP status of a failed API request, for every tool (issues #67, #69).
//!
//! - Claude reports it as `result.api_error_status`, and every retry as a
//!   `{"type":"system","subtype":"api_retry","error_status":401}` event.
//! - Codex has no structured field: the status is only in the text of its
//!   `turn.failed` / `error` events (`unexpected status 401 Unauthorized: ...`).

use regex::Regex;
use serde_json::Value;
use std::sync::LazyLock;

/// Statuses that refuse the credential: retrying cannot succeed.
pub const AUTH_REFUSAL_STATUSES: [i64; 2] = [401, 403];

// codex-rs `UnexpectedResponseError` Display: `unexpected status {status}: ...`
// (also wrapped in `Reconnecting... 1/5 (unexpected status 401 ...)`).
static CODEX_STATUS_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)\bunexpected status (\d{3})\b").expect("valid regex"));

fn http_status(value: &Value) -> Option<i64> {
    value
        .as_i64()
        .or_else(|| value.as_str().and_then(|text| text.trim().parse().ok()))
        .filter(|status| (100..=599).contains(status))
}

/// Parse the HTTP status from a Codex error text.
pub fn http_status_from_error_text(text: &str) -> Option<i64> {
    CODEX_STATUS_PATTERN
        .captures(text)
        .and_then(|captures| captures[1].parse().ok())
}

fn codex_error_text(event: &Value) -> Option<&str> {
    match event.get("type").and_then(Value::as_str) {
        Some("turn.failed") => event["error"]["message"]
            .as_str()
            .or_else(|| event["message"].as_str()),
        Some("error") => event["message"]
            .as_str()
            .or_else(|| event["error"]["message"].as_str()),
        _ => None,
    }
}

/// HTTP status of the Codex failure that ended the run: the last
/// `turn.failed` event, or the last `error` event of a turn that did not
/// complete.
pub fn codex_api_error_status(messages: &[Value]) -> Option<i64> {
    let failed = messages
        .iter()
        .rev()
        .find(|event| event["type"] == "turn.failed");
    if let Some(status) = failed
        .and_then(codex_error_text)
        .and_then(http_status_from_error_text)
    {
        return Some(status);
    }
    if messages
        .iter()
        .any(|event| event["type"] == "turn.completed")
    {
        return None;
    }
    messages
        .iter()
        .rev()
        .filter_map(codex_error_text)
        .find_map(http_status_from_error_text)
}

/// The HTTP status a Claude `system/api_retry` event reports.
pub fn api_retry_status(event: &Value) -> Option<i64> {
    if event["type"] != "system" || event["subtype"] != "api_retry" {
        return None;
    }
    http_status(&event["error_status"])
}

/// Status of the last `api_retry` event in the stream.
pub fn last_api_retry_status(messages: &[Value]) -> Option<i64> {
    messages.iter().rev().find_map(api_retry_status)
}

/// The 401/403 a retry event reports: the credential is refused and every
/// further retry fails the same way (issue #69).
pub fn auth_refusal_status(event: &Value) -> Option<i64> {
    api_retry_status(event).filter(|status| AUTH_REFUSAL_STATUSES.contains(status))
}

/// Message for a run stopped on an authentication refusal.
pub fn auth_refusal_message(event: &Value) -> String {
    let status = api_retry_status(event).unwrap_or_default();
    let retry = match (event["attempt"].as_i64(), event["max_retries"].as_i64()) {
        (Some(attempt), Some(max)) => format!(" at retry {attempt}/{max}"),
        (Some(attempt), None) => format!(" at retry {attempt}"),
        _ => String::new(),
    };
    let detail = event["error"]
        .as_str()
        .filter(|error| !error.is_empty())
        .map(|error| format!(" ({error})"))
        .unwrap_or_default();
    format!(
        "API request refused with status {status}{detail}; stopped{retry} by failFastOnAuthError"
    )
}

/// The run's API error status.
///
/// Claude's `result.api_error_status`, the status in Codex's failure text, or,
/// when no final result arrived (a run stopped during retries), the status of
/// the last `api_retry` event.
pub fn resolve_api_error_status(messages: &[Value]) -> Option<i64> {
    let result = messages
        .iter()
        .rev()
        .find(|event| event["type"] == "result");
    if let Some(status) = result.and_then(|result| http_status(&result["api_error_status"])) {
        return Some(status);
    }
    if let Some(status) = codex_api_error_status(messages) {
        return Some(status);
    }
    if result.is_some() {
        None
    } else {
        last_api_retry_status(messages)
    }
}