use crate::{contract::string_or_empty, process::run};
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::{env, os::unix::fs::PermissionsExt, path::Path, process::Command};
pub fn executable(agent: Option<&str>) -> Result<Option<String>> {
let program = Path::new(agent.unwrap_or("claude"));
let candidates: Vec<_> = if program.components().count() > 1 || program.is_absolute() {
vec![program.to_owned()]
} else {
env::split_paths(&env::var_os("PATH").unwrap_or_default())
.map(|dir| dir.join(program))
.collect()
};
for path in candidates {
if path
.metadata()
.is_ok_and(|info| info.is_file() && info.permissions().mode() & 0o111 != 0)
{
let absolute = if path.is_absolute() {
path
} else {
env::current_dir()?.join(path)
};
return Ok(agent.map(|_| absolute.to_string_lossy().into()));
}
}
if let Some(agent) = agent {
bail!("agent executable not found: {agent}");
}
bail!("Claude Code is not on PATH; install it or pass --agent EXECUTABLE")
}
#[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>,
}
pub fn invoke_measured(
agent: Option<&str>,
request: &Value,
cwd: &Path,
timeout: u64,
profile: &Value,
) -> Invocation {
let mut usage = None;
let reply = call(agent, request, cwd, timeout, profile, &mut usage);
Invocation { reply, usage }
}
fn call(
agent: Option<&str>,
request: &Value,
cwd: &Path,
timeout: u64,
profile: &Value,
usage: &mut Option<Value>,
) -> Result<Value> {
let mut command = Command::new(agent.unwrap_or("claude"));
command.current_dir(cwd);
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" => ("Read,Grep,Glob", "default", None),
"build" => (
"Read,Grep,Glob,Edit,Write,Bash",
"acceptEdits",
Some("Bash"),
),
"review" => ("Read,Grep,Glob,Bash", "default", Some("Bash")),
_ => bail!("unknown role: {role}"),
};
command.args([
"-p",
"--output-format",
"json",
"--json-schema",
string_or_empty(&config["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 message.to_lowercase().contains("not logged in") {
return Err(Action {
message: message.into(),
recommendation: "Log in to Claude Code on this machine.".into(),
reason: "Agent attempts need an authenticated account.".into(),
}
.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();
bail!(
"{} exited with code {}\n{}",
agent.unwrap_or("claude"),
output.status.code().unwrap_or(-1),
tail.into_iter().collect::<String>()
);
}
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()))
}