agent-commander 0.6.0

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
//! Tests for the HTTP status of failed API requests (issues #67, #68, #69):
//! Codex's status parsed from its failure text, `$schema`-declaring
//! structured-output schemas, and stopping Claude on a 401/403 retry.

use agent_commander::tools::{claude, codex, qwen};
use agent_commander::{
    auth_refusal_status, build_normalized_result_metadata, codex_api_error_status,
    http_status_from_error_text, json_schema_arg, last_api_retry_status, BuildMetadataOptions,
    LaunchOptions, ResultMetadata,
};
use serde_json::{json, Value};

fn lines(events: &[Value]) -> String {
    events
        .iter()
        .map(Value::to_string)
        .collect::<Vec<_>>()
        .join("\n")
}

fn codex_failure(message: &str) -> Vec<Value> {
    vec![
        json!({"type": "thread.started", "thread_id": "thread-1"}),
        json!({"type": "turn.started"}),
        json!({"type": "error", "message": format!("Reconnecting... 1/5 ({message})")}),
        json!({"type": "error", "message": message}),
        json!({"type": "turn.failed", "error": {"message": message}}),
    ]
}

fn metadata(tool: &str, exit_code: i32, events: &[Value]) -> ResultMetadata {
    build_normalized_result_metadata(BuildMetadataOptions {
        tool,
        exit_code,
        plain_output: &lines(events),
        ..Default::default()
    })
}

// Issue #67 ------------------------------------------------------------------

#[test]
fn http_status_from_error_text_reads_the_codex_unexpected_status_text() {
    assert_eq!(
        http_status_from_error_text(r#"unexpected status 401 Unauthorized: {"error":"bad token"}"#),
        Some(401)
    );
    assert_eq!(
        http_status_from_error_text("Reconnecting... 2/5 (unexpected status 503)"),
        Some(503)
    );
    assert_eq!(http_status_from_error_text("stream disconnected"), None);
}

#[test]
fn codex_api_error_status_comes_from_turn_failed() {
    for (text, status) in [
        (
            r#"unexpected status 401 Unauthorized: {"error":"bad token"}"#,
            401,
        ),
        ("unexpected status 403 Forbidden: denied", 403),
        ("unexpected status 429 Too Many Requests: slow down", 429),
        ("unexpected status 502 Bad Gateway: upstream", 502),
    ] {
        let metadata = metadata("codex", 1, &codex_failure(text));
        assert!(!metadata.success, "{text}");
        assert_eq!(metadata.api_error_status, Some(status), "{text}");
        assert!(
            metadata
                .error_message
                .as_deref()
                .is_some_and(|message| message.starts_with("unexpected status")),
            "{:?}",
            metadata.error_message
        );
    }
}

#[test]
fn codex_turn_failed_without_a_status_keeps_api_error_status_none() {
    let metadata = metadata(
        "codex",
        1,
        &[
            json!({"type": "turn.started"}),
            json!({"type": "turn.failed", "error": {"message": "stream disconnected"}}),
        ],
    );
    assert_eq!(metadata.api_error_status, None);
}

#[test]
fn codex_retry_that_recovered_does_not_set_api_error_status() {
    let metadata = metadata(
        "codex",
        0,
        &[
            json!({"type": "turn.started"}),
            json!({"type": "error", "message": "Reconnecting... 1/5 (unexpected status 503)"}),
            json!({"type": "item.completed", "item": {"type": "agent_message", "text": "Done"}}),
            json!({"type": "turn.completed", "usage": {"input_tokens": 1, "output_tokens": 1}}),
        ],
    );
    assert!(metadata.success, "{metadata:?}");
    assert_eq!(metadata.api_error_status, None);
}

#[test]
fn codex_run_stopped_while_reconnecting_reports_the_retried_status() {
    assert_eq!(
        codex_api_error_status(&[
            json!({"type": "turn.started"}),
            json!({"type": "error", "message": "Reconnecting... 3/5 (unexpected status 401)"}),
        ]),
        Some(401)
    );
}

// Issue #68 ------------------------------------------------------------------

const ZOD4_SCHEMA: &str = r#"{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "answer": { "type": "string" },
    "nested": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object" }
  },
  "required": ["answer"],
  "additionalProperties": false
}"#;

#[test]
fn json_schema_arg_drops_a_top_level_schema_dialect() {
    let arg: Value = serde_json::from_str(&json_schema_arg(ZOD4_SCHEMA)).unwrap();
    assert_eq!(
        arg,
        json!({
            "type": "object",
            "properties": {
                "answer": {"type": "string"},
                "nested": {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object"}
            },
            "required": ["answer"],
            "additionalProperties": false
        })
    );
}

#[test]
fn every_tool_receives_the_schema_without_its_dialect() {
    let launch = LaunchOptions {
        json_schema: Some(
            r#"{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object"}"#
                .to_string(),
        ),
        ..Default::default()
    };
    let claude_args = claude::build_args(&claude::ClaudeBuildOptions {
        prompt: Some("hi".to_string()),
        launch: launch.clone(),
        ..Default::default()
    });
    let qwen_args = qwen::build_args(&qwen::QwenBuildOptions {
        prompt: Some("hi".to_string()),
        launch: launch.clone(),
        ..Default::default()
    });
    for args in [claude_args, qwen_args] {
        let index = args.iter().position(|arg| arg == "--json-schema").unwrap();
        assert_eq!(args[index + 1], r#"{"type":"object"}"#, "{args:?}");
    }
    let command = codex::build_command(&codex::CodexBuildOptions {
        prompt: Some("hi".to_string()),
        launch,
        ..Default::default()
    });
    assert!(!command.contains("draft/2020-12"), "{command}");
    assert!(command.contains(r#"{\"type\":\"object\"}"#), "{command}");
}

// Issue #69 ------------------------------------------------------------------

fn init() -> Value {
    json!({"type": "system", "subtype": "init", "session_id": "sess-1"})
}

fn retry(status: i64, attempt: i64) -> Value {
    json!({
        "type": "system",
        "subtype": "api_retry",
        "error_status": status,
        "attempt": attempt,
        "max_retries": 10,
        "retry_delay_ms": 500,
        "error": "authentication_failed"
    })
}

#[test]
fn auth_refusal_status_accepts_only_401_and_403_api_retry_events() {
    assert_eq!(auth_refusal_status(&retry(401, 1)), Some(401));
    assert_eq!(auth_refusal_status(&retry(403, 1)), Some(403));
    assert_eq!(auth_refusal_status(&retry(429, 1)), None);
    assert_eq!(auth_refusal_status(&retry(529, 1)), None);
    let mut other = retry(401, 1);
    other["subtype"] = json!("x");
    assert_eq!(auth_refusal_status(&other), None);
    assert_eq!(auth_refusal_status(&Value::Null), None);
    assert_eq!(
        last_api_retry_status(&[retry(529, 1), retry(401, 2)]),
        Some(401)
    );
}

#[test]
fn claude_run_stopped_during_retries_records_the_retried_status() {
    let metadata = metadata("claude", 143, &[init(), retry(401, 1), retry(401, 2)]);
    assert!(!metadata.success);
    assert_eq!(metadata.api_retry_status, Some(401));
    assert_eq!(metadata.api_error_status, Some(401));
}

#[test]
fn claude_retry_that_recovered_keeps_api_error_status_none() {
    let metadata = metadata(
        "claude",
        0,
        &[
            init(),
            retry(529, 1),
            json!({"type": "result", "subtype": "success", "is_error": false, "result": "ok"}),
        ],
    );
    assert!(metadata.success, "{metadata:?}");
    assert_eq!(metadata.api_retry_status, Some(529));
    assert_eq!(metadata.api_error_status, None);
}

#[test]
fn an_auth_refusal_stop_is_reported_as_auth_refused() {
    let metadata = build_normalized_result_metadata(BuildMetadataOptions {
        tool: "claude",
        exit_code: 143,
        signal: Some("SIGTERM".into()),
        plain_output: &lines(&[init(), retry(403, 1)]),
        auth_refusal: Some(retry(403, 1)),
        ..Default::default()
    });
    assert!(!metadata.success);
    assert_eq!(metadata.error_type.as_deref(), Some("auth_refused"));
    assert_eq!(metadata.api_error_status, Some(403));
    assert_eq!(
        metadata.error_message.as_deref(),
        Some("API request refused with status 403 (authentication_failed); stopped at retry 1/10 by failFastOnAuthError")
    );
}

#[test]
fn api_retry_status_serializes_in_camel_case() {
    let metadata = metadata("claude", 143, &[init(), retry(401, 1)]);
    let value = serde_json::to_value(&metadata).unwrap();
    assert_eq!(value["apiRetryStatus"], 401);
    assert_eq!(value["apiErrorStatus"], 401);
}

#[cfg(unix)]
mod fail_fast {
    use super::{init, retry};
    use agent_commander::{
        agent, AgentCommandOptions, AgentOptions, AgentResult, AgentStartOptions, GatewayOptions,
        LaunchOptions, ToolOverrides,
    };
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    /// A fake claude that reports a refused retry and keeps retrying for 30 s.
    fn retrying_claude(status: i64, options: AgentOptions) -> AgentOptions {
        let command = format!(
            "printf '%s\\n' '{}' '{}'; sleep 30",
            init(),
            retry(status, 1)
        );
        AgentOptions {
            tool: "claude".into(),
            working_directory: std::env::temp_dir().display().to_string(),
            prompt: Some("hi".into()),
            json: true,
            isolation: "none".into(),
            tool_overrides: ToolOverrides {
                build_command: Some(Arc::new(move |_: &AgentCommandOptions| command.clone())),
                ..Default::default()
            },
            ..options
        }
    }

    async fn run(options: AgentOptions, wait: Duration) -> (Option<AgentResult>, Duration) {
        let mut controller = agent(options).unwrap();
        controller
            .start(AgentStartOptions {
                attached: false,
                ..Default::default()
            })
            .await
            .unwrap();
        let started = Instant::now();
        let result = tokio::time::timeout(wait, controller.stop(Default::default())).await;
        let elapsed = started.elapsed();
        if let Ok(result) = result {
            (Some(result.unwrap()), elapsed)
        } else {
            let cancelled = controller.cancel().await.unwrap();
            assert!(!cancelled.metadata.success);
            assert_ne!(
                cancelled.metadata.error_type.as_deref(),
                Some("auth_refused")
            );
            assert_eq!(cancelled.metadata.api_retry_status, Some(401));
            assert_eq!(cancelled.metadata.api_error_status, Some(401));
            (None, elapsed)
        }
    }

    #[tokio::test]
    async fn fail_fast_on_auth_error_stops_claude_on_the_first_401_retry() {
        let (result, elapsed) = run(
            retrying_claude(
                401,
                AgentOptions {
                    fail_fast_on_auth_error: Some(true),
                    ..Default::default()
                },
            ),
            Duration::from_secs(10),
        )
        .await;
        let result = result.expect("the run ended before the caller timeout");
        assert!(elapsed < Duration::from_secs(10), "{elapsed:?}");
        let metadata = result.metadata;
        assert!(!metadata.success);
        assert_eq!(metadata.error_type.as_deref(), Some("auth_refused"));
        assert_eq!(metadata.api_error_status, Some(401));
        assert_eq!(metadata.api_retry_status, Some(401));
    }

    #[tokio::test]
    async fn a_gateway_run_fails_fast_by_default() {
        let token = "AGENT_COMMANDER_TEST_GATEWAY_TOKEN";
        let (result, _) = run(
            retrying_claude(
                403,
                AgentOptions {
                    extra_env: vec![(token.into(), "expired".into())],
                    launch: LaunchOptions {
                        gateway: Some(GatewayOptions::with_base_url("http://127.0.0.1:9", token)),
                        ..Default::default()
                    },
                    ..Default::default()
                },
            ),
            Duration::from_secs(10),
        )
        .await;
        let metadata = result
            .expect("the run ended before the caller timeout")
            .metadata;
        assert_eq!(metadata.error_type.as_deref(), Some("auth_refused"));
        assert_eq!(metadata.api_error_status, Some(403));
    }

    #[tokio::test]
    async fn without_fail_fast_the_retry_status_explains_a_cancel() {
        let (result, _) = run(
            retrying_claude(401, AgentOptions::default()),
            Duration::from_millis(1500),
        )
        .await;
        assert!(result.is_none(), "claude keeps retrying");
    }
}