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"),
}
}
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 {}
pub struct Invocation {
pub reply: Result<Value>,
pub usage: Option<Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Auth {
Subscription,
Api,
}
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",
}
}
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 }
}
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];
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}"),
};
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);
*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;
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%"}"#,
)?;
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(())
}
}