use super::documents::{declare_document, DocTree, TagRule, Vocabulary};
use super::element::{attributes, elements, rust_name};
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
elements! {
harness: leaf;
agent: leaf;
}
attributes! {
pub trait AgentsAttrs {
kind; label; provider;
cli;
runs;
tasks;
realtime;
family; experimental; homepage; about;
harness;
parent;
name; model;
effort;
supervisor;
instructions; voice; voice_mode; tools; persona; color; icon; gender;
avatar;
sound;
skills;
kernel;
cognition;
routing;
fabric;
access;
confirm_spend;
}
}
pub(crate) const FAMILY: Family = Family { module: "agents", roots: &["harness", "agent"], declare };
pub const HARNESS_KINDS: &[&str] = &["cli", "api", "program"];
pub const HARNESS_RUNTIMES: &[&str] = &["host", "vm", "worker"];
pub const HARNESS_TASKS: &[&str] = &["classify", "decide", "extract", "summarize", "act"];
pub const REALTIME_IN: &[&str] = &["audio", "video", "text"];
pub const REALTIME_OUT: &[&str] = &["audio", "text", "tools"];
pub const AUDIO_FORMATS: &[&str] = &["g711-ulaw@8000", "pcm16@8000", "pcm16@16000", "pcm16@24000"];
pub const HARNESS_FIELDS: &[&str] = &["kind", "label", "provider", "cli", "runs", "tasks", "realtime", "family", "experimental", "homepage", "about"];
pub const AGENT_FIELDS: &[&str] = &[
"harness", "parent", "name", "model", "effort", "supervisor", "instructions", "voice", "voiceMode", "tools", "persona", "color", "icon", "gender",
"avatar", "sound", "skills", "kernel", "cognition", "routing", "fabric", "access", "confirmSpend",
];
pub const AGENT_OBJECT_FIELDS: &[&str] = &["persona", "kernel", "cognition", "routing", "fabric", "access"];
pub const VOICE_MODES: &[&str] = &["off", "push-to-talk", "open-mic"];
pub const REALTIME_FIELDS: &[&str] = &["in", "out", "audio", "fps", "hz", "minutes", "videoMinutes"];
const HARNESS: Vocabulary = Vocabulary {
format: "harness",
noun: "an agent harness",
root: "harness",
tags: &[TagRule::new("harness", &[]).required(&["kind", "label"]).attrs(HARNESS_FIELDS)],
from_tree: harness_of,
};
const AGENT: Vocabulary = Vocabulary { format: "agent", noun: "an agent", root: "agent", tags: &[TagRule::new("agent", &[]).attrs(AGENT_FIELDS)], from_tree: agent_of };
fn declare(root: El) -> Result<Declared, String> {
declare_document(&root, if root.tag == "harness" { &HARNESS } else { &AGENT })
}
fn quoted(values: &[&str]) -> String {
values.iter().map(|v| format!("\"{v}\"")).collect::<Vec<_>>().join(", ")
}
fn list_of(v: Option<&Json>, allowed: &[&str], empty: bool) -> bool {
let Some(Json::Arr(items)) = v else { return false };
let words: Vec<&str> = items.iter().filter_map(Json::as_str).collect();
(empty || !items.is_empty()) && words.len() == items.len() && words.iter().all(|w| allowed.contains(w)) && (1..words.len()).all(|i| !words[..i].contains(&words[i]))
}
fn positive(v: Option<&Json>) -> bool {
matches!(v, Some(Json::Num(n)) if n.is_finite() && *n > 0.0)
}
fn word(t: &DocTree, k: &str) -> Result<(), String> {
match t.attr_of(k) {
Some(Json::Str(s)) if !s.is_empty() => Ok(()),
None => Ok(()),
Some(v) => Err(format!("{}() {} is a word, not {}", t.tag, rust_name(k), v.text())),
}
}
fn one_of(t: &DocTree, k: &str, values: &[&str]) -> Result<(), String> {
match t.attr_of(k) {
None => Ok(()),
Some(Json::Str(s)) if values.contains(&s.as_str()) => Ok(()),
Some(v) => Err(format!("{}() {} is {}, not {}", t.tag, rust_name(k), quoted(values), v.text())),
}
}
fn check_realtime(v: &Json) -> Result<(), String> {
let no = |why: String| Err(format!("harness() realtime {why}"));
let Json::Obj(entries) = v else { return no(format!(r#"is an object ({{"in": ["audio"], "out": ["audio", "tools"], …}}), not {}"#, v.text())) };
for (k, _) in entries {
if !REALTIME_FIELDS.contains(&k.as_str()) {
return no(format!("has no field {k}; its fields are {}", REALTIME_FIELDS.join(", ")));
}
}
if !list_of(v.get("in"), REALTIME_IN, false) {
return no(format!("in is a list of {}", quoted(REALTIME_IN)));
}
if !list_of(v.get("out"), REALTIME_OUT, false) {
return no(format!("out is a list of {}", quoted(REALTIME_OUT)));
}
let says = |side: &str, what: &str| matches!(v.get(side), Some(Json::Arr(items)) if items.iter().any(|x| x.as_str() == Some(what)));
let audio = v.get("audio");
if says("in", "audio") || says("out", "audio") {
if !matches!(audio, Some(Json::Obj(_))) {
return no(r#"audio names the formats it takes and gives: {"in": ["pcm16@24000"], "out": ["pcm16@24000"]}"#.into());
}
for side in ["in", "out"] {
if says(side, "audio") && !list_of(audio.and_then(|a| a.get(side)), AUDIO_FORMATS, false) {
return no(format!("audio.{side} is a list of {}", quoted(AUDIO_FORMATS)));
}
}
} else if audio.is_some() {
return no("audio is for a harness that takes or gives audio".into());
}
if says("in", "video") && !positive(v.get("fps")) {
return no("fps is the most video frames a second it takes (a harness that takes video says it)".into());
}
if says("out", "tools") && !positive(v.get("hz")) {
return no("hz is the most tool calls a second it decides (a harness that calls tools says it)".into());
}
for k in ["fps", "hz", "minutes", "videoMinutes"] {
if let Some(x) = v.get(k) {
if !positive(Some(x)) {
return no(format!("{k} is a positive number, not {}", x.text()));
}
}
}
Ok(())
}
fn said(t: &DocTree, fields: &[&str]) -> Json {
let mut out = Json::obj();
for k in fields {
if let Some(v) = t.attr_of(k) {
out.set(k, v.clone());
}
}
out
}
fn harness_of(t: &DocTree) -> Result<Json, String> {
for k in ["label", "provider", "cli", "family", "homepage", "about"] {
word(t, k)?;
}
one_of(t, "kind", HARNESS_KINDS)?;
if let Some(v) = t.attr_of("experimental") {
if !matches!(v, Json::Bool(_)) {
return Err(format!("harness() experimental is true or false, not {}", v.text()));
}
}
if let Some(v) = t.attr_of("runs") {
if !list_of(Some(v), HARNESS_RUNTIMES, true) {
return Err(format!("harness() runs is a list of {}, not {}", quoted(HARNESS_RUNTIMES), v.text()));
}
}
if let Some(v) = t.attr_of("tasks") {
if !list_of(Some(v), HARNESS_TASKS, false) {
return Err(format!("harness() tasks is a list of {}, not {}", quoted(HARNESS_TASKS), v.text()));
}
}
let kind = t.attr_of("kind").and_then(Json::as_str);
if t.attr_of("tasks").is_some() && kind != Some("api") {
return Err(r#"harness() tasks is for kind("api") only: a model that does one task in a turn"#.into());
}
if kind == Some("cli") && t.attr_of("cli").is_none() {
return Err(r#"harness().kind("cli") names the program it starts: .cli("claude")"#.into());
}
if kind != Some("cli") && t.attr_of("cli").is_some() {
return Err(r#"harness() cli is for kind("cli") only"#.into());
}
if kind == Some("api") && t.attr_of("provider").is_none() {
return Err(r#"harness().kind("api") names its provider in the model catalog: .provider("anthropic")"#.into());
}
if let Some(r) = t.attr_of("realtime") {
if kind != Some("api") || t.attr_of("tasks").is_some() {
return Err(r#"harness() realtime is for kind("api") with no tasks: a model that converses live"#.into());
}
check_realtime(r)?;
}
Ok(said(t, HARNESS_FIELDS))
}
fn agent_of(t: &DocTree) -> Result<Json, String> {
for k in ["harness", "parent", "name", "model", "effort", "supervisor", "instructions", "voice", "color", "icon", "gender", "avatar", "sound"] {
word(t, k)?;
}
one_of(t, "voiceMode", VOICE_MODES)?;
if let Some(s) = t.attr_of("supervisor").and_then(|v| v.as_str()) {
let ok = s.split_once(':').is_some_and(|(k, id)| (k == "agent" || k == "person") && !id.is_empty() && !id.contains(char::is_whitespace));
if !ok {
return Err(format!("<agent> supervisor is an agent or a person (\"agent:lead\", \"person:me\"), not {:?}", s));
}
}
let (base, fork) = (t.attr_of("harness").is_some(), t.attr_of("parent").is_some());
if base == fork {
return Err(if base {
"agent() names a harness (a base instance) or a parent (a fork), not both: a fork keeps its parent's harness".into()
} else {
r#"agent() names its harness (a base instance: .harness("claude-code")) or its parent (a fork: .parent("cloud://home/user-commandagi/global/agents/claude-code"))"#.into()
});
}
if let Some(Json::Str(h)) = t.attr_of("harness") {
let id = h.len() <= 80 && h.bytes().enumerate().all(|(i, c)| c.is_ascii_lowercase() || c.is_ascii_digit() || (i > 0 && c == b'-'));
if !id {
return Err(format!(r#"agent() harness is a harness's id ("claude-code"), not {}"#, Json::Str(h.clone()).text()));
}
}
if let Some(v) = t.attr_of("tools") {
if !matches!(v, Json::Arr(items) if items.iter().all(|x| matches!(x, Json::Str(s) if !s.is_empty()))) {
return Err(format!("agent() tools is a list of tool names, not {}", v.text()));
}
}
if let Some(v) = t.attr_of("skills") {
if !matches!(v, Json::Arr(items) if items.iter().all(|x| matches!(x, Json::Str(s) if !s.is_empty()))) {
return Err(format!("agent() skills is a list of refs to SKILL.md files, not {}", v.text()));
}
}
for k in AGENT_OBJECT_FIELDS {
if let Some(v) = t.attr_of(k) {
if !matches!(v, Json::Obj(_)) {
let example = if *k == "persona" { r#"{"tone": "warm"}"# } else { "{ … }" };
return Err(format!("agent() {k} is an object ({example}), not {}", v.text()));
}
}
}
if let Some(v) = t.attr_of("confirmSpend") {
if !matches!(v, Json::Bool(_)) {
return Err(format!("agent() confirm_spend is true or false, not {}", v.text()));
}
}
if let Some(Json::Str(a)) = t.attr_of("avatar") {
if a.contains('/') || a.starts_with('.') {
return Err(format!(r#"agent() avatar is a file beside this one ("avatar.png"), not {}"#, Json::Str(a.clone()).text()));
}
}
Ok(said(t, AGENT_FIELDS))
}