use crate::{config::Config, contract::string_or_empty, driver, process::run};
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::{env, ffi::OsStr, path::Path};
pub fn executable(agent: Option<&str>) -> Result<Option<String>> {
let cwd = env::current_dir()?;
let on_path = |program: &str| crate::process::resolve(OsStr::new(program), &cwd).is_some();
let Some(name) = agent.filter(|name| *name != driver::CLAUDE) else {
if on_path(driver::CLAUDE) {
return Ok(None);
}
bail!(
"Claude Code is not on PATH; install it, or pass --agent {}",
driver::known_agents().join(", --agent ")
);
};
if let Some(program) = driver::known_program(name) {
if !on_path(&program) {
bail!("{name} is not on PATH (agengo runs `{program}`); install it, or pick another --agent");
}
if driver::is_experimental(name) {
eprintln!("agengo: note: support for {name} is experimental; its flags come from its documentation and have not been tried against a signed-in {name}");
}
return Ok(Some(name.to_owned()));
}
match crate::process::resolve(OsStr::new(name), &cwd) {
Some(path) => Ok(Some(path.to_string_lossy().into())),
None => bail!(
"agent executable not found: {name} (agents known by name: claude, {})",
driver::known_agents().join(", ")
),
}
}
pub fn select(flag: Option<&str>, root: &Path) -> Result<Option<String>> {
match driver::selection(flag, root)? {
driver::Selection::Chosen { name, source } => {
let agent = executable(Some(&name))?;
if let Some(line) = crate::config::load(root)?.describe(&name) {
eprintln!("agengo: models · {line}");
}
if source == driver::Source::OnlyOneInstalled && name != driver::CLAUDE {
eprintln!("agengo: using {name}, the only agent installed (`agengo agent use NAME` or --agent chooses another)");
}
Ok(agent)
}
driver::Selection::Several(names) => {
let name = ask_which(&names, root)?;
let agent = executable(Some(&name))?;
if let Some(line) = crate::config::load(root)?.describe(&name) {
eprintln!("agengo: models · {line}");
}
Ok(agent)
}
driver::Selection::Nothing => bail!(
"no coding agent found on PATH; install Claude Code (claude), Codex (codex) or Antigravity (agy), or pass --agent EXECUTABLE"
),
}
}
fn ask_which(names: &[String], root: &Path) -> Result<String> {
use std::io::{BufRead, IsTerminal, Write};
let list = names.join(", ");
let command = format!("agengo agent use {}", names[0]);
if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal()) {
bail!(
"several agents are installed ({list}) and none is chosen, so agengo will not guess which login to use. Choose one for this repository, for example `{command}`, or pass --agent NAME"
);
}
eprintln!("agengo: several agents are installed and none is chosen. Which one should this repository use?");
for (number, name) in names.iter().enumerate() {
eprintln!(" {}) {name}", number + 1);
}
eprint!("Number or name: ");
std::io::stderr().flush().ok();
let mut answer = String::new();
std::io::stdin().lock().read_line(&mut answer)?;
let answer = answer.trim();
let chosen = answer
.parse::<usize>()
.ok()
.and_then(|number| number.checked_sub(1))
.and_then(|index| names.get(index))
.or_else(|| names.iter().find(|name| name.as_str() == answer));
match chosen {
Some(name) => {
crate::config::set_agent(root, Some(name))?;
eprintln!(
"agengo: this repository now uses {name} ({})",
crate::config::PATH
);
Ok(name.clone())
}
None => bail!("no agent chosen; choose one with `{command}` or pass --agent NAME"),
}
}
pub fn label(agent: Option<&str>, auth: Auth) -> String {
let name = agent.map_or_else(
|| "Claude Code".to_owned(),
|path| {
Path::new(path)
.file_name()
.map_or_else(|| path.to_owned(), |name| name.to_string_lossy().into())
},
);
let login = match auth {
Auth::Subscription => "subscription login",
Auth::Api => "API keys",
};
format!("agent {name} ({login})")
}
#[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,
config: &Config,
) -> Invocation {
let mut usage = None;
let reply = call(
agent, auth, request, cwd, timeout, profile, config, &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",
"please set an auth method",
"authentication required",
]
.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,
}
}
#[allow(clippy::too_many_arguments)]
fn call(
agent: Option<&str>,
auth: Auth,
request: &Value,
cwd: &Path,
timeout: u64,
profile: &Value,
config: &Config,
usage: &mut Option<Value>,
) -> Result<Value> {
drive(
&*driver::for_agent(agent),
agent,
auth,
request,
cwd,
timeout,
profile,
config,
usage,
)
}
#[allow(clippy::too_many_arguments)]
fn drive(
driver: &dyn driver::Driver,
agent: Option<&str>,
auth: Auth,
request: &Value,
cwd: &Path,
timeout: u64,
profile: &Value,
config: &Config,
usage: &mut Option<Value>,
) -> Result<Value> {
let pick = config.pick(
string_or_empty(&request["role"]),
agent.unwrap_or(driver::CLAUDE),
);
crate::sandbox::check(config.sandbox, &driver.name(), &driver.sandbox_support())?;
let mut prepared = driver.prepare(request, profile, &pick)?;
let mut asked_again = false;
loop {
prepared.command.current_dir(cwd);
if config.sandbox != crate::config::Sandbox::Off {
crate::sandbox::filter_env(&mut prepared.command, &config.sandbox_env);
}
if auth == Auth::Subscription {
for variable in API_KEY_VARIABLES {
prepared.command.env_remove(variable);
}
}
let output = run(
&mut prepared.command,
Some(prepared.stdin.as_bytes()),
Some(timeout),
)?;
let mut result = driver.parse(&output.stdout);
*usage = crate::usage::combine(usage.take(), driver.usage(&mut result));
if let Some(message) = driver.reported_error(&result) {
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{}",
driver.name(),
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}");
}
let reply = driver.reply(result);
if !reply.is_object() && !asked_again {
if let Some(next) = driver.retry(request, profile, &pick) {
prepared = next?;
asked_again = true;
continue;
}
}
if !reply.is_object() {
bail!(
"agent did not return a structured result{}",
what_it_printed(&output)
);
}
return Ok(reply);
}
}
fn what_it_printed(output: &std::process::Output) -> String {
let tail = |bytes: &[u8]| {
let text = String::from_utf8_lossy(bytes);
let mut chars: Vec<_> = text.trim().chars().rev().take(800).collect();
chars.reverse();
chars.into_iter().collect::<String>()
};
let (out, err) = (tail(&output.stdout), tail(&output.stderr));
let mut message = String::new();
if out.is_empty() {
message.push_str("\nthe agent printed nothing on stdout");
} else {
message.push_str(&format!("\nstdout (end): {out}"));
}
if !err.is_empty() {
message.push_str(&format!("\nstderr (end): {err}"));
}
message
}
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::*;
#[cfg(unix)]
use crate::config::Sandbox;
use serde_json::json;
#[test]
fn label_names_the_agent_and_how_it_logs_in() {
assert_eq!(
label(None, Auth::Subscription),
"agent Claude Code (subscription login)"
);
let path = Path::new("tools").join("codex-adapter.cmd");
assert_eq!(
label(path.to_str(), Auth::Api),
"agent codex-adapter.cmd (API keys)"
);
}
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())
}
fn call(agent: &str, auth: Auth, directory: &Path) -> Result<Value> {
for _ in 0..20 {
let reply = invoke_measured(
Some(agent),
auth,
&json!({}),
directory,
30,
&Value::Null,
&Config::default(),
)
.reply;
match &reply {
Err(error) if format!("{error:#}").contains("os error 26") => {
std::thread::sleep(std::time::Duration::from_millis(50));
}
_ => return reply,
}
}
invoke_measured(
Some(agent),
auth,
&json!({}),
directory,
30,
&Value::Null,
&Config::default(),
)
.reply
}
#[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| call(&agent, auth, directory.path());
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 = call(&agent, Auth::Subscription, directory.path()).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 = call(&crash, Auth::Subscription, directory.path()).unwrap_err();
assert!(error.downcast_ref::<Action>().is_none());
Ok(())
}
#[cfg(unix)]
#[test]
fn claude_is_started_with_the_documented_arguments_for_each_role() -> Result<()> {
let directory = tempfile::tempdir()?;
let record = directory.path().join("record");
std::fs::create_dir(&record)?;
let script = directory.path().join("claude");
std::fs::write(
&script,
format!(
"#!/bin/sh\nfor a in \"$@\"; do printf '%s\\n' \"$a\"; done > '{0}/args'\ncat > '{0}/stdin'\n\
printf '%s' '{{\"structured_output\":{{\"status\":\"pass\",\"summary\":\"ok\"}},\"usage\":{{\"input_tokens\":3,\"output_tokens\":4}},\"total_cost_usd\":0.5,\"modelUsage\":{{\"m\":{{}}}}}}'\n",
record.display()
),
)?;
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
let claude = driver::Claude {
program: Some(script.clone().into_os_string()),
};
let run = |request: &Value, profile: &Value| {
let mut usage = None;
let reply = drive(
&claude,
None,
Auth::Subscription,
request,
directory.path(),
30,
profile,
&Config {
sandbox: Sandbox::Off,
..Config::default()
},
&mut usage,
);
Invocation { reply, usage }
};
let profile = crate::contract::profile(None)?;
let cases = [
("plan", json!({}), "Read,Grep,Glob", "default", false),
("specify", json!({}), "Read,Grep,Glob", "default", false),
(
"build",
json!({"builder_handoff": "commit"}),
"Read,Grep,Glob,Edit,Write,Bash",
"acceptEdits",
true,
),
(
"build",
json!({"builder_handoff": "worktree"}),
"Read,Grep,Glob,Edit,Write,Bash",
"acceptEdits",
true,
),
("review", json!({}), "Read,Grep,Glob,Bash", "default", true),
(
"review",
json!({"review_scope": "integrated"}),
"Read,Grep,Glob,Bash",
"default",
true,
),
("verify", json!({}), "Read,Grep,Glob,Bash", "default", true),
];
let mut failures = Vec::new();
for (role, extra, tools, mode, bash) in cases {
let mut request = json!({"role": role});
for (key, value) in extra.as_object().unwrap() {
request[key] = value.clone();
}
let config = &profile["roles"][role];
let schema: Value = serde_json::from_str(config["schema"].as_str().unwrap())?;
let mut expected = vec![
"-p".to_owned(),
"--output-format".into(),
"json".into(),
"--json-schema".into(),
schema.to_string(),
"--tools".into(),
tools.into(),
"--permission-mode".into(),
mode.into(),
"--strict-mcp-config".into(),
];
if bash {
expected.extend([
"--allowedTools".to_owned(),
"Bash".into(),
"--settings".into(),
driver::guard_settings(),
]);
}
let mut prompt = config["instructions"].as_str().unwrap().to_owned();
if role == "build" {
prompt.push('\n');
prompt.push_str(
config["handoff_prompts"][request["builder_handoff"].as_str().unwrap()]
.as_str()
.unwrap(),
);
}
if request["review_scope"] == "integrated" {
prompt.push('\n');
prompt.push_str(config["integrated_prompt"].as_str().unwrap());
}
let invocation = run(&request, &profile);
let reply = invocation.reply?;
let args = std::fs::read_to_string(record.join("args"))?;
let stdin = std::fs::read_to_string(record.join("stdin"))?;
let label = format!("{role} {extra}");
if args.lines().collect::<Vec<_>>() != expected {
failures.push(format!("{label}: arguments differ: {args}"));
}
if stdin != format!("{prompt}\n\n{request}") {
failures.push(format!("{label}: prompt differs"));
}
assert_eq!(reply, json!({"status": "pass", "summary": "ok"}), "{label}");
assert_eq!(
invocation.usage,
Some(json!({"input_tokens": 3, "output_tokens": 4, "cost_usd": 0.5, "model": "m"})),
"{label}"
);
}
assert!(failures.is_empty(), "{failures:#?}");
let report = |body: &str| -> Result<()> {
std::fs::write(
&script,
format!("#!/bin/sh\ncat >/dev/null\nprintf '%s' '{body}'\n"),
)?;
Ok(())
};
let request = json!({"role": "review"});
report(
r#"{"is_error":true,"result":"Not logged in - Please run /login","usage":{"input_tokens":1}}"#,
)?;
let invocation = run(&request, &profile);
assert_eq!(invocation.usage, Some(json!({"input_tokens": 1})));
let error = invocation.reply.unwrap_err();
let action = error.downcast_ref::<Action>().expect("an action request");
assert!(action.recommendation.contains("run claude, then /login"));
report(r#"{"is_error":true,"result":"model overloaded"}"#)?;
let error = run(&request, &profile).reply.unwrap_err();
assert!(error.downcast_ref::<Action>().is_none());
assert_eq!(error.to_string(), "model overloaded");
report(r#"{"result":"no structured output"}"#)?;
let error = run(&request, &profile).reply.unwrap_err();
assert!(
error
.to_string()
.starts_with("agent did not return a structured result\n"),
"{error}"
);
Ok(())
}
#[cfg(unix)]
fn recording_agent(directory: &Path, output: &str) -> Result<std::path::PathBuf> {
let script = directory.join("agent");
std::fs::write(
&script,
format!(
"#!/bin/sh\nn=$(cat '{0}/count' 2>/dev/null || echo 0)\nn=$((n+1))\necho $n > '{0}/count'\n\
for a in \"$@\"; do printf '%s\\n' \"$a\"; done > \"{0}/args$n\"\ncat > \"{0}/stdin$n\"\n\
cat <<'AGENT_OUTPUT'\n{1}\nAGENT_OUTPUT\n",
directory.display(),
output
),
)?;
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
Ok(script)
}
#[cfg(unix)]
fn drive_text(name: &str, script: &Path, role: &str, directory: &Path) -> Result<Value> {
let agent = driver::Text::with_program(name, script.into());
let profile = crate::contract::profile(None)?;
drive(
&agent,
Some(name),
Auth::Subscription,
&json!({"role": role, "builder_handoff": "commit"}),
directory,
30,
&profile,
&Config {
sandbox: Sandbox::Off,
..Config::default()
},
&mut None,
)
}
#[cfg(unix)]
#[test]
fn sandbox_modes_limit_the_environment_and_strict_refuses_unchecked_agents() -> Result<()> {
let directory = tempfile::tempdir()?;
let script = directory.path().join("agent");
std::fs::write(
&script,
format!(
"#!/bin/sh\nenv > '{}/env'\ncat >/dev/null\necho '{{\"status\":\"pass\",\"summary\":\"ok\"}}'\n",
directory.path().display()
),
)?;
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
let agent = driver::Text::with_program("codex", script.into());
let profile = crate::contract::profile(None)?;
let request = json!({"role": "review", "builder_handoff": "commit"});
let run = |sandbox| {
let config = Config {
sandbox,
..Config::default()
};
drive(
&agent,
Some("codex"),
Auth::Subscription,
&request,
directory.path(),
30,
&profile,
&config,
&mut None,
)
};
run(crate::config::Sandbox::Off)?;
let env = std::fs::read_to_string(directory.path().join("env"))?;
assert!(env.contains("CARGO_MANIFEST_DIR="), "off passes everything");
run(crate::config::Sandbox::Auto)?;
let env = std::fs::read_to_string(directory.path().join("env"))?;
assert!(env.contains("PATH="));
assert!(!env.contains("CARGO_MANIFEST_DIR="), "auto filters {env}");
let unchecked = driver::Text::with_program("agy", directory.path().join("agent").into());
let error = drive(
&unchecked,
Some("agy"),
Auth::Subscription,
&request,
directory.path(),
30,
&profile,
&Config {
sandbox: crate::config::Sandbox::Strict,
..Config::default()
},
&mut None,
)
.unwrap_err()
.to_string();
assert!(error.contains("--sandbox strict"), "{error}");
Ok(())
}
#[cfg(unix)]
#[test]
fn codex_is_started_per_role_and_its_final_message_is_read() -> Result<()> {
let directory = tempfile::tempdir()?;
let script = recording_agent(
directory.path(),
"I looked at it.\n```json\n{\"status\":\"pass\",\"summary\":\"ok\"}\n```",
)?;
let reply = drive_text("codex", &script, "review", directory.path())?;
assert_eq!(reply, json!({"status": "pass", "summary": "ok"}));
let args = std::fs::read_to_string(directory.path().join("args1"))?;
assert_eq!(
args.lines().collect::<Vec<_>>(),
[
"exec",
"--sandbox",
"workspace-write",
"--skip-git-repo-check",
"-"
]
);
drive_text("codex", &script, "plan", directory.path())?;
let args = std::fs::read_to_string(directory.path().join("args2"))?;
assert!(
args.contains("read-only") && !args.contains("workspace-write"),
"{args}"
);
let stdin = std::fs::read_to_string(directory.path().join("stdin1"))?;
let profile = crate::contract::profile(None)?;
let instructions = profile["roles"]["review"]["instructions"].as_str().unwrap();
assert!(stdin.starts_with(instructions));
assert!(stdin.contains(r#"{"builder_handoff":"commit","role":"review"}"#));
assert!(stdin.contains("reply with exactly one JSON object"));
assert!(
stdin.contains("\"changes_requested\""),
"the schema is in the prompt"
);
drive_text("codex", &script, "build", directory.path())?;
let args = std::fs::read_to_string(directory.path().join("args3"))?;
assert!(
args.contains("workspace-write") && !args.contains("read-only"),
"{args}"
);
Ok(())
}
#[cfg(unix)]
#[test]
fn tiers_reach_each_agent_as_its_own_flags() -> Result<()> {
let directory = tempfile::tempdir()?;
let profile = crate::contract::profile(None)?;
let config: Config = serde_yaml_ng::from_str(
"sandbox: off\nthink: {model: big, effort: max, models: {codex: gpt-big}}\nbuild: {model: small, effort: low}\n",
)?;
let args_of = |name: &str, role: &str, count: &str| -> Result<Vec<String>> {
let script = recording_agent(
directory.path(),
r#"{"status":"pass","summary":"ok","response":"{\"status\":\"pass\",\"summary\":\"ok\"}"}"#,
)?;
let _ = std::fs::remove_file(directory.path().join("count"));
let agent = driver::Text::with_program(name, script.into());
drive(
&agent,
Some(name),
Auth::Subscription,
&json!({"role": role}),
directory.path(),
30,
&profile,
&config,
&mut None,
)?;
Ok(std::fs::read_to_string(directory.path().join(count))?
.lines()
.map(str::to_owned)
.collect())
};
let args = args_of("codex", "review", "args1")?;
assert_eq!(
args[..8],
[
"exec",
"--sandbox",
"workspace-write",
"--skip-git-repo-check",
"-m",
"gpt-big",
"-c",
"model_reasoning_effort=\"xhigh\""
]
);
assert_eq!(args[8], "-");
let args = args_of("codex", "build", "args1")?;
assert!(
args.windows(2).any(|pair| pair == ["-m", "small"]),
"{args:?}"
);
assert!(
args.contains(&"model_reasoning_effort=\"low\"".to_owned()),
"{args:?}"
);
let args = args_of("agy", "plan", "args1")?;
assert_eq!(
args[..6],
[
"--output-format",
"json",
"--model",
"big",
"--effort",
"max"
]
);
assert_eq!(args[6], "-p");
let script = directory.path().join("claude");
std::fs::write(
&script,
format!(
"#!/bin/sh\nfor a in \"$@\"; do printf '%s\\n' \"$a\"; done > '{0}/claude-args'\ncat >/dev/null\n\
printf '%s' '{{\"structured_output\":{{\"status\":\"pass\",\"summary\":\"ok\"}}}}'\n",
directory.path().display()
),
)?;
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
let claude = driver::Claude {
program: Some(script.into_os_string()),
};
let run = |role: &str, config: &Config| -> Result<String> {
drive(
&claude,
None,
Auth::Subscription,
&json!({"role": role}),
directory.path(),
30,
&profile,
config,
&mut None,
)?;
Ok(std::fs::read_to_string(
directory.path().join("claude-args"),
)?)
};
let args = run("review", &config)?;
assert!(args.contains("--model\nbig\n--effort\nmax\n"), "{args}");
let args = run("build", &config)?;
assert!(args.contains("--model\nsmall\n--effort\nlow\n"), "{args}");
let args = run("build", &Config::default())?;
assert!(
!args.contains("--model") && !args.contains("--effort"),
"{args}"
);
let adapter = recording_agent(directory.path(), r#"{"status":"pass","summary":"ok"}"#)?;
let _ = std::fs::remove_file(directory.path().join("count"));
let agent = adapter.to_str().unwrap();
invoke_measured(
Some(agent),
Auth::Subscription,
&json!({"role": "build"}),
directory.path(),
30,
&profile,
&config,
)
.reply?;
let sent: Value =
serde_json::from_str(&std::fs::read_to_string(directory.path().join("stdin1"))?)?;
assert_eq!(
(
sent["tier"].as_str(),
sent["model"].as_str(),
sent["effort"].as_str()
),
(Some("build"), Some("small"), Some("low"))
);
let _ = std::fs::remove_file(directory.path().join("count"));
invoke_measured(
Some(agent),
Auth::Subscription,
&json!({"role": "plan"}),
directory.path(),
30,
&profile,
&Config::default(),
)
.reply?;
let sent: Value =
serde_json::from_str(&std::fs::read_to_string(directory.path().join("stdin1"))?)?;
assert_eq!(sent["tier"], "think");
assert!(sent.get("model").is_none() && sent.get("effort").is_none());
Ok(())
}
#[cfg(unix)]
#[test]
fn a_reply_without_json_is_asked_for_once_more() -> Result<()> {
let directory = tempfile::tempdir()?;
let script = directory.path().join("agent");
std::fs::write(
&script,
format!(
"#!/bin/sh\ncat > '{0}/stdin'\nif [ -e '{0}/asked' ]; then echo '{{\"status\":\"pass\",\"summary\":\"ok\"}}'; \
else touch '{0}/asked'; echo 'All good, nothing to report.'; fi\n",
directory.path().display()
),
)?;
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
let reply = drive_text("codex", &script, "review", directory.path())?;
assert_eq!(reply, json!({"status": "pass", "summary": "ok"}));
let stdin = std::fs::read_to_string(directory.path().join("stdin"))?;
assert!(stdin.contains("did not contain the JSON object"), "{stdin}");
let silent = recording_agent(directory.path(), "no json at all")?;
let error = drive_text("codex", &silent, "review", directory.path()).unwrap_err();
assert!(
error
.to_string()
.starts_with("agent did not return a structured result\n"),
"{error}"
);
assert_eq!(
std::fs::read_to_string(directory.path().join("count"))?.trim(),
"2",
"it asks once, not forever"
);
Ok(())
}
#[cfg(unix)]
#[test]
fn antigravity_envelopes_are_read_by_status_and_structured_output() {
use driver::Driver;
let agent = driver::Text::new("agy");
let parse = |text: &str| agent.reported_error(&agent.parse(text.as_bytes()));
assert!(parse(r#"{"status":"WAITING","response":""}"#)
.unwrap()
.contains("status WAITING"));
assert_eq!(
agent.parse(
br#"{"status":"SUCCESS","response":"","structured_output":{"status":"pass"}}"#
),
json!({"status": "pass"})
);
assert_eq!(agent.parse(b""), serde_json::Value::Null);
}
#[cfg(unix)]
#[test]
fn antigravity_denied_tools_are_named() {
use driver::Driver;
let agent = driver::Text::new("agy");
let output = agent.parse(
br#"{"status":"SUCCESS","response":"","denied_actions":[{"action":"command","display_name":"Bash"}]}"#,
);
let error = agent.reported_error(&output).unwrap();
assert!(error.contains("not allowed to use command"), "{error}");
assert!(error.contains("\"command(*)\""), "{error}");
}
#[cfg(unix)]
#[test]
fn antigravity_is_asked_for_its_sandbox_only_when_the_mode_is_not_off() -> Result<()> {
let directory = tempfile::tempdir()?;
let envelope =
r#"{"status":"SUCCESS","response":"{\"status\":\"pass\",\"summary\":\"ok\"}"}"#;
let script = recording_agent(directory.path(), envelope)?;
let agent = driver::Text::with_program("agy", script.into());
let profile = crate::contract::profile(None)?;
let request = json!({"role": "review", "builder_handoff": "commit"});
let run = |sandbox, n: &str| -> Result<Vec<String>> {
let config = Config {
sandbox,
..Config::default()
};
drive(
&agent,
Some("agy"),
Auth::Subscription,
&request,
directory.path(),
30,
&profile,
&config,
&mut None,
)?;
Ok(std::fs::read_to_string(directory.path().join(n))?
.lines()
.map(str::to_owned)
.collect())
};
assert!(!run(crate::config::Sandbox::Off, "args1")?.contains(&"--sandbox".to_owned()));
assert!(run(crate::config::Sandbox::Auto, "args2")?.contains(&"--sandbox".to_owned()));
let error = drive(
&agent,
Some("agy"),
Auth::Subscription,
&request,
directory.path(),
30,
&profile,
&Config {
sandbox: crate::config::Sandbox::Strict,
..Config::default()
},
&mut None,
)
.unwrap_err()
.to_string();
assert!(
error.contains("cannot tell whether it is in force"),
"{error}"
);
Ok(())
}
#[test]
fn named_agents_choose_their_default_handoff() {
assert_eq!(driver::default_handoff("codex"), "worktree");
assert_eq!(driver::default_handoff("agy"), "commit");
assert_eq!(driver::default_handoff("./my-adapter"), "commit");
}
#[cfg(unix)]
#[test]
fn antigravity_gets_the_prompt_as_an_argument_and_returns_json_in_response() -> Result<()> {
let directory = tempfile::tempdir()?;
let envelope = r#"{"status":"SUCCESS","response":"Done: {\"status\":\"pass\",\"summary\":\"ok\"}","usage":{"input_tokens":5}}"#;
let script = recording_agent(directory.path(), envelope)?;
let reply = drive_text("agy", &script, "review", directory.path())?;
assert_eq!(reply, json!({"status": "pass", "summary": "ok"}));
let args = std::fs::read_to_string(directory.path().join("args1"))?;
let args: Vec<&str> = args.splitn(4, '\n').collect();
assert_eq!(&args[..3], ["--output-format", "json", "-p"]);
assert!(args[3].contains(r#"{"builder_handoff":"commit","role":"review"}"#));
assert_eq!(
std::fs::read_to_string(directory.path().join("stdin1"))?,
""
);
let failed = recording_agent(
directory.path(),
r#"{"status":"ERROR","error":"unknown model: nope"}"#,
)?;
let error = drive_text("agy", &failed, "review", directory.path()).unwrap_err();
assert_eq!(error.to_string(), "unknown model: nope");
let login = recording_agent(
directory.path(),
r#"{"status":"ERROR","error":"authentication required"}"#,
)?;
let error = drive_text("agy", &login, "review", directory.path()).unwrap_err();
assert!(error.downcast_ref::<Action>().is_some());
Ok(())
}
#[test]
fn agents_known_by_name_are_resolved_by_name() {
assert_eq!(driver::known_program("codex").as_deref(), Some("codex"));
assert_eq!(driver::known_program("agy").as_deref(), Some("agy"));
assert_eq!(driver::known_program("claude"), None);
assert_eq!(driver::known_program("./codex"), None);
assert!(label(Some("codex"), Auth::Subscription).contains("agent codex "));
}
#[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(())
}
}