agengo 0.4.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
use crate::{contract::string_or_empty, process::run};
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::{env, ffi::OsStr, path::Path, process::Command};

pub fn executable(agent: Option<&str>) -> Result<Option<String>> {
    let found =
        crate::process::resolve(OsStr::new(agent.unwrap_or("claude")), &env::current_dir()?);
    match (found, agent) {
        (Some(path), Some(_)) => Ok(Some(path.to_string_lossy().into())),
        (Some(_), None) => Ok(None),
        (None, Some(agent)) => bail!("agent executable not found: {agent}"),
        (None, None) => bail!("Claude Code is not on PATH; install it or pass --agent EXECUTABLE"),
    }
}

/// The program that runs Claude Code. On Windows `claude` is usually
/// `claude.cmd` (npm) or `claude.exe`, which `Command` does not find by name.
fn claude() -> std::ffi::OsString {
    env::current_dir()
        .ok()
        .and_then(|cwd| crate::process::resolve(OsStr::new("claude"), &cwd))
        .map_or_else(|| "claude".into(), |path| path.into_os_string())
}

#[derive(Debug)]
pub struct Action {
    pub message: String,
    pub recommendation: String,
    pub reason: String,
}
impl std::fmt::Display for Action {
    fn fmt(&self, display: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        display.write_str(&self.message)
    }
}
impl std::error::Error for Action {}

/// An agent reply together with the token and cost usage it reported.
pub struct Invocation {
    pub reply: Result<Value>,
    /// Normalized usage (see `crate::usage`); `None` when not reported or
    /// when the process never produced output, for example on a timeout.
    pub usage: Option<Value>,
}

/// How agent processes authenticate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Auth {
    /// Use the agent CLI's own login (a Claude or ChatGPT subscription):
    /// API key variables are removed from the agent's environment, because
    /// Claude Code and Codex prefer a key over the login when both exist.
    Subscription,
    /// Pass the environment through unchanged, API keys included.
    Api,
}

/// Variables that make agent CLIs bill an API key instead of the logged-in
/// subscription. `CLAUDE_CODE_OAUTH_TOKEN` is a subscription token and stays.
pub const API_KEY_VARIABLES: [&str; 6] = [
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_AUTH_TOKEN",
    "OPENAI_API_KEY",
    "CODEX_API_KEY",
    "GEMINI_API_KEY",
    "GOOGLE_API_KEY",
];

impl Auth {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Subscription => "subscription",
            Self::Api => "api",
        }
    }

    /// Runs recorded before this setting existed passed the environment
    /// through, so a missing value keeps that behavior on resume.
    pub fn from_stored(value: Option<&str>) -> Result<Self> {
        match value {
            Some("subscription") => Ok(Self::Subscription),
            Some("api") | None => Ok(Self::Api),
            Some(other) => bail!("unknown auth mode: {other}"),
        }
    }
}

pub fn invoke_measured(
    agent: Option<&str>,
    auth: Auth,
    request: &Value,
    cwd: &Path,
    timeout: u64,
    profile: &Value,
) -> Invocation {
    let mut usage = None;
    let reply = call(agent, auth, request, cwd, timeout, profile, &mut usage);
    Invocation { reply, usage }
}

/// Whether an agent's error text is an authentication failure, from Claude
/// Code, Codex or an API behind a custom adapter.
fn authentication_failure(text: &str) -> bool {
    let text = text.to_lowercase();
    [
        "not logged in",
        "please run /login",
        "invalid api key",
        "invalid_api_key",
        "incorrect api key",
        "authentication_error",
        "authentication failed",
        "401 unauthorized",
        "missing bearer",
        "oauth token has expired",
        "credit balance is too low",
        "codex login",
    ]
    .iter()
    .any(|pattern| text.contains(pattern))
}

fn authentication_action(agent: Option<&str>, auth: Auth, message: &str) -> Action {
    let name = agent
        .and_then(|path| Path::new(path).file_name())
        .map_or("claude".into(), |name| name.to_string_lossy().into_owned());
    let (recommendation, reason) = match auth {
        Auth::Subscription => (
            "Log in to the agent CLI on this machine with your subscription (for Claude Code: run claude, then /login; for Codex: codex login), then run agengo resume. To pay with an API key instead, start a new run with --auth api.".to_owned(),
            format!(
                "agengo removed API key variables ({}) from the {name} environment so the subscription login is used, and that login is missing or was refused.",
                API_KEY_VARIABLES.join(", ")
            ),
        ),
        Auth::Api => (
            "Check the API key the agent reads from the environment, or log in with a subscription and start a new run with --auth subscription.".to_owned(),
            format!("This run passes API keys through to {name}, and the key was refused."),
        ),
    };
    Action {
        message: message.into(),
        recommendation,
        reason,
    }
}

fn call(
    agent: Option<&str>,
    auth: Auth,
    request: &Value,
    cwd: &Path,
    timeout: u64,
    profile: &Value,
    usage: &mut Option<Value>,
) -> Result<Value> {
    let mut command = match agent {
        Some(agent) => Command::new(agent),
        None => Command::new(claude()),
    };
    command.current_dir(cwd);
    if auth == Auth::Subscription {
        for variable in API_KEY_VARIABLES {
            command.env_remove(variable);
        }
    }
    let mut payload = request.to_string();
    if agent.is_none() {
        let role = string_or_empty(&request["role"]);
        let config = &profile["roles"][role];
        // Print mode has nobody to approve prompts, so any tool that would ask
        // is refused. Pre-approve what each role's instructions require:
        // the builder edits files and runs tests, the reviewer runs checks.
        let (tools, mode, allowed) = match role {
            "plan" | "specify" => ("Read,Grep,Glob", "default", None),
            "build" => (
                "Read,Grep,Glob,Edit,Write,Bash",
                "acceptEdits",
                Some("Bash"),
            ),
            "review" | "verify" => ("Read,Grep,Glob,Bash", "default", Some("Bash")),
            _ => bail!("unknown role: {role}"),
        };
        // One line: Windows refuses line breaks in arguments to a batch file
        // such as claude.cmd.
        let schema = serde_json::from_str::<Value>(string_or_empty(&config["schema"]))
            .context("role schema is not valid JSON")?
            .to_string();
        command.args([
            "-p",
            "--output-format",
            "json",
            "--json-schema",
            &schema,
            "--tools",
            tools,
            "--permission-mode",
            mode,
            "--strict-mcp-config",
        ]);
        if let Some(allowed) = allowed {
            command.args(["--allowedTools", allowed]);
        }
        let mut prompt = string_or_empty(&config["instructions"]).to_owned();
        if role == "build" {
            prompt.push('\n');
            prompt.push_str(string_or_empty(
                &config["handoff_prompts"][request["builder_handoff"].as_str().unwrap_or("commit")],
            ));
        }
        if request["review_scope"] == "integrated" {
            prompt.push('\n');
            prompt.push_str(string_or_empty(&config["integrated_prompt"]));
        }
        payload = format!("{prompt}\n\n{payload}");
    }
    let output = run(&mut command, Some(payload.as_bytes()), Some(timeout))?;
    let mut result: Value = serde_json::from_slice(&output.stdout).unwrap_or(Value::Null);
    // Read usage before any error check: failed attempts are billed too.
    *usage = if agent.is_none() {
        crate::usage::from_claude(&result)
    } else {
        result
            .as_object_mut()
            .and_then(|object| object.remove("usage"))
            .and_then(|raw| crate::usage::from_adapter(&raw))
    };
    if agent.is_none() && result["is_error"] == true {
        let message = result["result"]
            .as_str()
            .unwrap_or("Claude Code reported an error");
        if authentication_failure(message) {
            return Err(authentication_action(agent, auth, message).into());
        }
        bail!("{message}");
    }
    if !output.status.success() {
        let error = String::from_utf8_lossy(if output.stderr.is_empty() && result.is_null() {
            &output.stdout
        } else {
            &output.stderr
        });
        let mut tail: Vec<_> = error.trim().chars().rev().take(2400).collect();
        tail.reverse();
        let message = format!(
            "{} exited with code {}\n{}",
            agent.unwrap_or("claude"),
            output.status.code().unwrap_or(-1),
            tail.into_iter().collect::<String>()
        );
        if authentication_failure(&message) {
            return Err(authentication_action(agent, auth, &message).into());
        }
        bail!("{message}");
    }
    if agent.is_none() {
        result = result["structured_output"].take();
    }
    if !result.is_object() {
        bail!("agent did not return a structured result");
    }
    Ok(result)
}

pub fn existing_source(path: &Path) -> Result<String> {
    std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// An adapter that reports which API key variables it can see, or fails
    /// the way Codex does without a login.
    fn adapter(directory: &Path, unix: &str, windows: &str) -> Result<String> {
        if cfg!(windows) {
            let path = directory.join("adapter.cmd");
            std::fs::write(&path, format!("@echo off\r\n{windows}\r\n"))?;
            return Ok(path.to_string_lossy().into_owned());
        }
        let path = directory.join("adapter");
        std::fs::write(&path, format!("#!/bin/sh\ncat >/dev/null\n{unix}\n"))?;
        #[cfg(unix)]
        std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        Ok(path.to_string_lossy().into_owned())
    }

    #[test]
    fn subscription_mode_hides_api_keys_from_the_agent() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let agent = adapter(
            directory.path(),
            r#"printf '{"anthropic":"%s","openai":"%s","oauth":"%s"}' "${ANTHROPIC_API_KEY:-}" "${OPENAI_API_KEY:-}" "${CLAUDE_CODE_OAUTH_TOKEN:-}""#,
            r#"echo {"anthropic":"%ANTHROPIC_API_KEY%","openai":"%OPENAI_API_KEY%","oauth":"%CLAUDE_CODE_OAUTH_TOKEN%"}"#,
        )?;
        // Only this test sets these variables.
        env::set_var("ANTHROPIC_API_KEY", "sk-ant-test");
        env::set_var("OPENAI_API_KEY", "sk-openai-test");
        env::set_var("CLAUDE_CODE_OAUTH_TOKEN", "oauth-test");
        let seen = |auth| {
            invoke_measured(
                Some(&agent),
                auth,
                &json!({}),
                directory.path(),
                30,
                &Value::Null,
            )
            .reply
        };
        let subscription = seen(Auth::Subscription)?;
        let api = seen(Auth::Api)?;
        env::remove_var("ANTHROPIC_API_KEY");
        env::remove_var("OPENAI_API_KEY");
        env::remove_var("CLAUDE_CODE_OAUTH_TOKEN");
        assert_eq!(
            subscription,
            json!({"anthropic":"","openai":"","oauth":"oauth-test"})
        );
        assert_eq!(
            api,
            json!({"anthropic":"sk-ant-test","openai":"sk-openai-test","oauth":"oauth-test"})
        );
        Ok(())
    }

    #[test]
    fn authentication_failures_ask_for_a_login() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let agent = adapter(
            directory.path(),
            "echo 'Error: 401 Unauthorized: Missing bearer authentication in header' >&2\nexit 1",
            "echo Error: 401 Unauthorized: Missing bearer authentication in header 1>&2\r\nexit /b 1",
        )?;
        let error = invoke_measured(
            Some(&agent),
            Auth::Subscription,
            &json!({}),
            directory.path(),
            30,
            &Value::Null,
        )
        .reply
        .unwrap_err();
        let action = error.downcast_ref::<Action>().expect("an action request");
        assert!(action.recommendation.contains("codex login"));
        assert!(action.reason.contains("OPENAI_API_KEY"));

        let crash = adapter(
            directory.path(),
            "echo 'segfault' >&2\nexit 1",
            "echo segfault 1>&2\r\nexit /b 1",
        )?;
        let error = invoke_measured(
            Some(&crash),
            Auth::Subscription,
            &json!({}),
            directory.path(),
            30,
            &Value::Null,
        )
        .reply
        .unwrap_err();
        assert!(error.downcast_ref::<Action>().is_none());
        Ok(())
    }

    #[test]
    fn runs_without_a_stored_mode_keep_passing_keys_through() -> Result<()> {
        assert_eq!(Auth::from_stored(None)?, Auth::Api);
        assert_eq!(Auth::from_stored(Some("subscription"))?, Auth::Subscription);
        assert!(Auth::from_stored(Some("other")).is_err());
        Ok(())
    }
}