agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! How one kind of agent is started and how its output is read.
//!
//! `adapter::invoke_measured` does what every agent needs: it hides API keys
//! when asked, runs the process with a timeout, reads usage before looking
//! for errors, and turns login problems into an action request. A `Driver`
//! supplies only what differs between agents: the command and the text sent
//! to it, and where in its output the usage, an error it reports and the
//! reply are.

mod choose;
mod claude;
mod custom;
mod reply;
mod text;

#[cfg(all(test, unix))]
pub use text::Text;

pub use choose::{installed, program, selection, show, use_agent, Selection, Source, CLAUDE};
#[cfg(all(test, unix))]
pub use claude::guard_settings;
pub use claude::Claude;

use crate::config::Pick;
use anyhow::Result;
use serde_json::Value;
use std::process::Command;

/// A command ready to run, with the text to send on its standard input.
pub struct Prepared {
    pub command: Command,
    pub stdin: String,
}

pub trait Driver {
    /// Name used when the agent fails: `<name> exited with code N`.
    fn name(&self) -> String;

    /// What agengo can do about this agent's sandbox before starting it.
    fn sandbox_support(&self) -> crate::sandbox::Support {
        crate::sandbox::Support::Unavailable(
            "agengo has no way to sandbox it; run agengo in a container or VM".into(),
        )
    }

    /// The command for one request and what to write to its stdin.
    fn prepare(&self, request: &Value, profile: &Value, pick: &Pick) -> Result<Prepared>;

    /// Read the process's standard output as a JSON value, `Null` if it holds
    /// none. Agents that print a final message rather than JSON override it.
    fn parse(&self, stdout: &[u8]) -> Value {
        serde_json::from_slice(stdout).unwrap_or(Value::Null)
    }

    /// The command to run when the first reply held no JSON object: the same
    /// request, with a reminder of what to reply. `None` if asking again
    /// would not help.
    fn retry(&self, _request: &Value, _profile: &Value, _pick: &Pick) -> Option<Result<Prepared>> {
        None
    }

    /// Usage reported in the output. May take the usage out of `output` so
    /// it is not mistaken for part of the reply.
    fn usage(&self, output: &mut Value) -> Option<Value>;

    /// An error the agent reports in its output while still exiting normally.
    fn reported_error(&self, output: &Value) -> Option<String>;

    /// The reply to the request, taken from the agent's output.
    fn reply(&self, output: Value) -> Value;
}

/// The agents started by name (`--agent codex`), from `specs/agents.yaml`.
pub fn known_agents() -> Vec<String> {
    text::templates().keys().cloned().collect()
}

/// The program an agent known by name starts, `None` for other names.
pub fn known_program(name: &str) -> Option<String> {
    text::templates()
        .get(name)
        .map(|template| template.command[0].clone())
}

/// Whether `name` is experimental: its flags come from documentation only.
/// How the Builder hands over its work when `--builder-handoff` is not given:
/// the agent's own default from `specs/agents.yaml`, else `commit`.
pub fn default_handoff(agent: &str) -> &'static str {
    match text::templates()
        .get(agent)
        .and_then(|t| t.handoff.as_deref())
    {
        Some("worktree") => "worktree",
        _ => "commit",
    }
}

pub fn is_experimental(name: &str) -> bool {
    text::templates().get(name).is_some_and(|t| t.experimental)
}

/// The prompt for a role: its instructions, with the Builder's handoff
/// instructions and the whole-branch review's when the request asks for them.
pub fn role_prompt(request: &Value, profile: &Value) -> String {
    let config = &profile["roles"][crate::contract::string_or_empty(&request["role"])];
    let text = |value: &Value| crate::contract::string_or_empty(value).to_owned();
    let mut prompt = text(&config["instructions"]);
    if request["role"] == "build" {
        prompt.push('\n');
        prompt.push_str(&text(
            &config["handoff_prompts"][request["builder_handoff"].as_str().unwrap_or("commit")],
        ));
    }
    if request["review_scope"] == "integrated" {
        prompt.push('\n');
        prompt.push_str(&text(&config["integrated_prompt"]));
    }
    prompt
}

/// The driver for `--agent`: Claude Code when `None`, an agent known by name
/// (`codex`, `agy`), otherwise a custom adapter that follows the JSON
/// protocol.
pub fn for_agent(agent: Option<&str>) -> Box<dyn Driver> {
    match agent {
        None => Box::new(Claude { program: None }),
        Some(name) if text::templates().contains_key(name) => Box::new(text::Text::new(name)),
        Some(executable) => Box::new(custom::Custom {
            executable: executable.to_owned(),
        }),
    }
}