agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Agents that print a final message instead of a JSON envelope (Codex,
//! Antigravity). They are started from a template in `specs/agents.yaml`;
//! the prompt tells them to end with one JSON object, and `reply::extract_object`
//! finds it.

use super::{reply::extract_object, role_prompt, Driver, Prepared};
use crate::config::Pick;
use crate::contract::string_or_empty;
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use serde_json::{json, Value};
use std::{collections::BTreeMap, process::Command, sync::OnceLock};

/// Longest prompt passed as an argument; operating systems refuse longer
/// ones (Windows at about 32 KB, Linux at 128 KB per argument).
const MAX_ARGUMENT_BYTES: usize = 30_000;

/// Key under which `parse` reports an error found in the agent's output.
const ERROR_KEY: &str = "__agengo_error";

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Template {
    pub command: Vec<String>,
    prompt: PromptWhere,
    #[serde(default)]
    prompt_marker: Option<String>,
    #[serde(default)]
    prompt_flag: Option<String>,
    #[serde(default)]
    read_only: Vec<String>,
    #[serde(default)]
    read_write: Vec<String>,
    #[serde(default)]
    extra: Vec<String>,
    /// Added when `--sandbox` is `auto` or `strict`.
    #[serde(default)]
    sandbox: Vec<String>,
    /// How the Builder hands over its work when the user does not say:
    /// `worktree` or `commit` (the default).
    #[serde(default)]
    pub handoff: Option<String>,
    /// Arguments that set the model, followed by its name.
    #[serde(default)]
    model_flag: Vec<String>,
    /// Arguments that set the effort; `{effort}` stands for the value.
    #[serde(default)]
    effort_flag: Vec<String>,
    /// Effort values this agent spells differently (`max: xhigh`).
    #[serde(default)]
    effort_map: BTreeMap<String, String>,
    reply: String,
    #[allow(dead_code)]
    login: String,
    #[serde(default)]
    pub experimental: bool,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "lowercase")]
enum PromptWhere {
    Stdin,
    Arg,
}

#[derive(Deserialize)]
struct Catalog {
    agents: BTreeMap<String, Template>,
}

pub fn templates() -> &'static BTreeMap<String, Template> {
    static TEMPLATES: OnceLock<BTreeMap<String, Template>> = OnceLock::new();
    TEMPLATES.get_or_init(|| {
        let catalog: Catalog = serde_yaml_ng::from_str(include_str!("../../specs/agents.yaml"))
            .expect("specs/agents.yaml is valid");
        catalog.agents
    })
}

pub struct Text {
    name: String,
    /// The program to run; `None` finds the template's command on PATH.
    /// Tests give a script.
    program: Option<std::ffi::OsString>,
}

impl Text {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            program: None,
        }
    }

    #[cfg(all(test, unix))]
    pub fn with_program(name: &str, program: std::ffi::OsString) -> Self {
        Self {
            name: name.into(),
            program: Some(program),
        }
    }

    fn template(&self) -> &'static Template {
        &templates()[&self.name]
    }

    fn build(
        &self,
        request: &Value,
        profile: &Value,
        pick: &Pick,
        note: Option<&str>,
    ) -> Result<Prepared> {
        let template = self.template();
        let role = string_or_empty(&request["role"]);
        if !matches!(role, "plan" | "specify" | "build" | "review" | "verify") {
            bail!("unknown role: {role}");
        }
        let schema =
            serde_json::from_str::<Value>(string_or_empty(&profile["roles"][role]["schema"]))
                .context("role schema is not valid JSON")?;
        let mut prompt = format!(
            "{}\n\n{request}\n\nWhen you are done, reply with exactly one JSON object and nothing \
             after it. It must match this JSON Schema:\n{schema}",
            role_prompt(request, profile)
        );
        if let Some(note) = note {
            prompt.push_str("\n\n");
            prompt.push_str(note);
        }
        let program = match &self.program {
            Some(program) => program.clone(),
            None => crate::process::resolve(
                std::ffi::OsStr::new(&template.command[0]),
                &std::env::current_dir()?,
            )
            .map_or_else(
                || template.command[0].clone().into(),
                std::path::PathBuf::into_os_string,
            ),
        };
        let mut command = Command::new(program);
        command.args(&template.command[1..]);
        command.args(if role == "build" {
            &template.read_write
        } else {
            &template.read_only
        });
        command.args(&template.extra);
        if pick.sandbox != crate::config::Sandbox::Off {
            command.args(&template.sandbox);
        }
        if let Some(model) = &pick.model {
            if template.model_flag.is_empty() {
                eprintln!("agengo: note: {} has no model setting here, so the model `{model}` is not passed", self.name);
            } else {
                command.args(&template.model_flag).arg(model);
            }
        }
        if let Some(effort) = pick.effort {
            if template.effort_flag.is_empty() {
                eprintln!(
                    "agengo: note: {} has no effort setting here, so effort `{}` is not passed",
                    self.name,
                    effort.as_str()
                );
            } else {
                let value = template
                    .effort_map
                    .get(effort.as_str())
                    .map_or(effort.as_str(), String::as_str);
                command.args(
                    template
                        .effort_flag
                        .iter()
                        .map(|part| part.replace("{effort}", value)),
                );
            }
        }
        let stdin = match template.prompt {
            PromptWhere::Stdin => {
                if let Some(marker) = &template.prompt_marker {
                    command.arg(marker);
                }
                prompt
            }
            PromptWhere::Arg => {
                if prompt.len() > MAX_ARGUMENT_BYTES {
                    bail!(
                        "the {role} prompt is {} bytes, too long to pass to {} as an argument (limit {MAX_ARGUMENT_BYTES})",
                        prompt.len(),
                        self.name
                    );
                }
                if let Some(flag) = &template.prompt_flag {
                    command.arg(flag);
                }
                command.arg(prompt);
                String::new()
            }
        };
        Ok(Prepared { command, stdin })
    }
}

impl Text {
    /// agy cannot ask for approval when it has no terminal: a tool it needs is
    /// denied, the run still ends with `SUCCESS` and an empty `response`.
    fn denied_actions(&self, stdout: &str) -> Option<String> {
        let envelope = serde_json::from_str::<Value>(stdout).ok()?;
        let denied = envelope["denied_actions"].as_array()?;
        // agy names a denied tool twice: `action` is the permission rule's
        // name (`command`, `write_file`), `display_name` the tool (Bash, Edit).
        let rule = |action: &Value| -> Option<String> {
            let name = action["action"]
                .as_str()
                .or(action["display_name"].as_str())?;
            Some(
                match name.to_ascii_lowercase().as_str() {
                    "bash" | "command" => "command",
                    "edit" | "write" | "write_file" | "write_to_file" => "write_file",
                    "read" | "read_file" | "view_file" => "read_file",
                    _ => return Some(name.to_owned()),
                }
                .to_owned(),
            )
        };
        let mut rules: Vec<String> = denied.iter().filter_map(rule).collect();
        rules.sort();
        rules.dedup();
        if rules.is_empty() {
            return None;
        }
        let allow = rules
            .iter()
            .map(|name| format!("\"{name}(*)\""))
            .collect::<Vec<_>>()
            .join(", ");
        Some(format!(
            "{} was not allowed to use {} and stopped without a result: it cannot ask for approval when it runs without a terminal. \
             Add {allow} under `permissions.allow` in ~/.gemini/antigravity-cli/settings.json (`agengo doctor` checks it), \
             or use another agent (`agengo agent use claude`)",
            self.name,
            rules.join(", ")
        ))
    }
}

impl Driver for Text {
    fn name(&self) -> String {
        self.name.clone()
    }

    fn sandbox_support(&self) -> crate::sandbox::Support {
        use crate::sandbox::{self, Support};
        let template = self.template();
        let cwd = std::env::current_dir().unwrap_or_default();
        if template.read_only.iter().any(|flag| flag == "--sandbox") {
            // agengo always passes `--sandbox`; what is left to say is
            // whether it can start here.
            sandbox::codex_support(&cwd)
        } else if !template.sandbox.is_empty() {
            Support::Unchecked(format!(
                "{} ignores {} without a message when its sandbox is not available, so agengo cannot tell whether it is in force",
                self.name,
                template.sandbox.join(" ")
            ))
        } else {
            Support::Unavailable(format!(
                "agengo has no sandbox option for {} yet; run agengo in a container or VM",
                self.name
            ))
        }
    }

    fn prepare(&self, request: &Value, profile: &Value, pick: &Pick) -> Result<Prepared> {
        self.build(request, profile, pick, None)
    }

    fn retry(&self, request: &Value, profile: &Value, pick: &Pick) -> Option<Result<Prepared>> {
        Some(self.build(
            request,
            profile,
            pick,
            Some(
                "Your previous reply did not contain the JSON object. Reply again with only \
                 the JSON object that matches the schema.",
            ),
        ))
    }

    fn parse(&self, stdout: &[u8]) -> Value {
        let text = String::from_utf8_lossy(stdout);
        let message = match self.template().reply.strip_prefix("json:") {
            None => text.clone().into_owned(),
            Some(field) => {
                let Ok(envelope) = serde_json::from_str::<Value>(&text) else {
                    return Value::Null;
                };
                if let Some(error) = envelope["error"]
                    .as_str()
                    .or_else(|| envelope["error"]["message"].as_str())
                {
                    return json!({ ERROR_KEY: error });
                }
                // agy reports a run it could not finish in `status`, with the
                // reason in `response` or on stderr.
                if let Some(status) = envelope["status"].as_str() {
                    if matches!(
                        status,
                        "ERROR" | "INVALID" | "CANCELED" | "INTERRUPTED" | "WAITING" | "RUNNING"
                    ) {
                        let detail = envelope[field].as_str().unwrap_or_default().trim();
                        return json!({ ERROR_KEY: if detail.is_empty() {
                            format!("{} finished with status {status}", self.name)
                        } else {
                            format!("{} finished with status {status}: {detail}", self.name)
                        } });
                    }
                }
                // With a schema the envelope also carries the parsed object.
                if envelope["structured_output"].is_object() {
                    return envelope["structured_output"].clone();
                }
                envelope[field].as_str().unwrap_or_default().to_owned()
            }
        };
        match extract_object(&message) {
            Some(reply) => reply,
            None => self
                .denied_actions(&text)
                .map_or(Value::Null, |error| json!({ ERROR_KEY: error })),
        }
    }

    fn usage(&self, _output: &mut Value) -> Option<Value> {
        None
    }

    fn reported_error(&self, output: &Value) -> Option<String> {
        output[ERROR_KEY].as_str().map(str::to_owned)
    }

    fn reply(&self, output: Value) -> Value {
        output
    }
}

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

    #[test]
    fn the_catalog_loads_and_names_a_program_for_every_agent() {
        assert!(!templates().is_empty());
        for (name, template) in templates() {
            assert!(!template.command.is_empty(), "{name}");
            let reply = &template.reply;
            assert!(
                reply == "text" || reply.starts_with("json:"),
                "{name}: {reply}"
            );
        }
    }
}