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};
const MAX_ARGUMENT_BYTES: usize = 30_000;
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>,
#[serde(default)]
sandbox: Vec<String>,
#[serde(default)]
pub handoff: Option<String>,
#[serde(default)]
model_flag: Vec<String>,
#[serde(default)]
effort_flag: Vec<String>,
#[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,
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 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") {
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.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 });
}
envelope[field].as_str().unwrap_or_default().to_owned()
}
};
extract_object(&message).unwrap_or(Value::Null)
}
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}"
);
}
}
}