include!(concat!(env!("OUT_DIR"), "/bundled_agents.rs"));
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentAction {
Install,
Update { from: String },
UpToDate,
}
impl AgentAction {
pub fn is_change(&self) -> bool {
!matches!(self, Self::UpToDate)
}
pub fn label(&self, to: &str) -> String {
match self {
Self::Install => format!("install {to}"),
Self::Update { from } => format!("update {from} → {to}"),
Self::UpToDate => "up to date".to_string(),
}
}
}
pub fn installed_version(agents_dir: &Path, name: &str) -> Option<String> {
let manifest = std::fs::read_to_string(agents_dir.join(name).join("agent.leviath")).ok()?;
leviath_core::manifest::parse_manifest(&manifest)
.ok()
.map(|bp| bp.version)
}
pub fn plan_agent_actions(agents_dir: &Path) -> Vec<(&'static BundledAgent, AgentAction)> {
BUNDLED_AGENTS
.iter()
.map(|agent| {
let action = match installed_version(agents_dir, agent.name) {
None => AgentAction::Install,
Some(v) if v == agent.version => AgentAction::UpToDate,
Some(from) => AgentAction::Update { from },
};
(agent, action)
})
.collect()
}
pub fn install_bundled(agent: &BundledAgent, agents_dir: &Path) -> anyhow::Result<()> {
let dest = agents_dir.join(agent.name);
if dest.exists() {
std::fs::remove_dir_all(&dest)?;
}
for (rel, contents) in agent.files {
let parent = match rel.rsplit_once('/') {
Some((dir, _)) => dest.join(dir),
None => dest.clone(),
};
std::fs::create_dir_all(&parent)?;
std::fs::write(dest.join(rel), contents)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_bundled_agent_has_a_name_version_and_manifest() {
assert!(
!BUNDLED_AGENTS.is_empty(),
"the binary shipped with no blueprints -- build.rs found no agents/ directory"
);
for agent in BUNDLED_AGENTS {
assert!(!agent.name.is_empty(), "a bundled agent has an empty name");
assert!(
!agent.version.is_empty(),
"bundled agent {} has an empty version",
agent.name
);
assert!(
agent.files.iter().any(|(rel, _)| *rel == "agent.leviath"),
"bundled agent {} has no agent.leviath",
agent.name
);
for (rel, contents) in agent.files {
assert!(
!rel.is_empty(),
"bundled agent {} has an empty path",
agent.name
);
assert!(
!contents.is_empty(),
"bundled agent {} has an empty file {rel}",
agent.name
);
}
}
}
#[test]
fn a_tool_script_shared_by_several_agents_is_identical_in_all_of_them() {
use std::collections::HashMap;
let mut first_seen: HashMap<&str, (&str, &str)> = HashMap::new();
for agent in BUNDLED_AGENTS {
for (rel, contents) in agent.files {
let Some(filename) = rel.strip_prefix("tools/") else {
continue;
};
match first_seen.get(filename) {
Some((other, expected)) => assert!(
expected == contents,
"tools/{filename} differs between bundled agents {other} and {} - \
a change to one copy was not applied to the others",
agent.name
),
None => {
first_seen.insert(filename, (agent.name, contents));
}
}
}
}
assert!(
!first_seen.is_empty(),
"no bundled agent ships a tools/ script - this invariant is not being tested"
);
}
#[test]
fn every_bundled_manifest_parses_and_agrees_with_its_recorded_version() {
for agent in BUNDLED_AGENTS {
let manifest = agent
.files
.iter()
.find(|(rel, _)| *rel == "agent.leviath")
.map(|(_, c)| *c)
.expect("checked above");
let parsed = leviath_core::manifest::parse_manifest(manifest);
assert!(
parsed.is_ok(),
"bundled agent {} does not parse",
agent.name
);
let blueprint = parsed.expect("asserted Ok just above");
assert_eq!(blueprint.version, agent.version);
assert_eq!(blueprint.name, agent.name);
}
}
#[test]
fn every_stage_tool_name_resolves_and_every_permission_names_a_granted_tool() {
const SUBAGENT: &[&str] = &[
"spawn_agent",
"check_agent",
"wait_for_agent",
"send_to_agent",
"kill_agent",
];
let builtin = leviath_tools::BuiltinTools::new(leviath_tools::ToolContext::new(
std::path::PathBuf::from("."),
))
.names();
for agent in BUNDLED_AGENTS {
let scripts: Vec<&str> = agent
.files
.iter()
.filter_map(|(rel, _)| rel.strip_prefix("tools/"))
.filter_map(|f| f.strip_suffix(".rhai"))
.collect();
let manifest = agent
.files
.iter()
.find(|(rel, _)| *rel == "agent.leviath")
.map(|(_, c)| *c)
.expect("every bundled agent has a manifest");
let parsed = leviath_core::manifest::parse_manifest(manifest);
assert!(
parsed.is_ok(),
"bundled agent {} does not parse",
agent.name
);
let blueprint = parsed.expect("asserted Ok just above");
for stage in &blueprint.stages {
for tool in &stage.available_tools {
let known = tool.contains("__")
|| builtin.iter().any(|b| b == tool)
|| SUBAGENT.contains(&tool.as_str())
|| scripts.contains(&tool.as_str());
assert!(
known,
"{}: stage '{}' grants '{}', which is not a built-in, a sub-agent tool, or one of this agent's own tools/*.rhai",
agent.name, stage.name, tool
);
}
for granted in stage.tool_permissions.keys() {
assert!(
stage.available_tools.contains(granted),
"{}: stage '{}' sets a permission for '{}', which it does not grant in available_tools",
agent.name,
stage.name,
granted
);
}
}
}
}
#[test]
fn the_stage_tool_invariant_rejects_a_typo_and_an_orphan_permission() {
let builtin = leviath_tools::BuiltinTools::new(leviath_tools::ToolContext::new(
std::path::PathBuf::from("."),
))
.names();
assert!(
!builtin.iter().any(|b| b == "raed_file"),
"a misspelled tool must not resolve"
);
let manifest = r#"
[agent]
name = "x"
version = "0.1.0"
description = "x"
[stages.only]
model = { provider = "anthropic", model = "m" }
available_tools = ["read_file"]
[stages.only.tool_permissions]
write_file = "allow"
"#;
let bp = leviath_core::manifest::parse_manifest(manifest)
.expect("the fixture parses; it is the invariant that should object");
let stage = &bp.stages[0];
assert!(
!stage.available_tools.contains(&"write_file".to_string()),
"the orphan-permission arm has something to catch"
);
}
#[test]
fn bundled_agent_names_are_unique() {
let mut names: Vec<&str> = BUNDLED_AGENTS.iter().map(|a| a.name).collect();
names.sort_unstable();
let count = names.len();
names.dedup();
assert_eq!(count, names.len(), "duplicate bundled agent names");
}
#[test]
fn installed_version_reads_a_manifest() {
let dir = tempfile::tempdir().unwrap();
let agent = &BUNDLED_AGENTS[0];
install_bundled(agent, dir.path()).unwrap();
assert_eq!(
installed_version(dir.path(), agent.name).as_deref(),
Some(agent.version)
);
}
#[test]
fn installed_version_is_none_when_nothing_is_installed() {
let dir = tempfile::tempdir().unwrap();
assert!(installed_version(dir.path(), "not-installed").is_none());
}
#[test]
fn installed_version_is_none_for_an_unparseable_manifest() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("broken")).unwrap();
std::fs::write(
dir.path().join("broken/agent.leviath"),
"not valid toml {{{",
)
.unwrap();
assert!(installed_version(dir.path(), "broken").is_none());
}
#[test]
fn plan_offers_to_install_everything_into_an_empty_dir() {
let dir = tempfile::tempdir().unwrap();
let plan = plan_agent_actions(dir.path());
assert_eq!(plan.len(), BUNDLED_AGENTS.len());
for (agent, action) in &plan {
assert_eq!(*action, AgentAction::Install);
assert!(action.is_change());
assert_eq!(
action.label(agent.version),
format!("install {}", agent.version)
);
}
}
#[test]
fn plan_reports_up_to_date_after_installing() {
let dir = tempfile::tempdir().unwrap();
for agent in BUNDLED_AGENTS {
install_bundled(agent, dir.path()).unwrap();
}
let plan = plan_agent_actions(dir.path());
for (agent, action) in &plan {
assert_eq!(*action, AgentAction::UpToDate, "{}", agent.name);
assert!(!action.is_change());
assert_eq!(action.label(agent.version), "up to date");
}
}
#[test]
fn plan_reports_an_update_when_the_installed_version_differs() {
let dir = tempfile::tempdir().unwrap();
let agent = &BUNDLED_AGENTS[0];
install_bundled(agent, dir.path()).unwrap();
let manifest_path = dir.path().join(agent.name).join("agent.leviath");
let manifest = std::fs::read_to_string(&manifest_path).unwrap();
let bumped = manifest.replacen(
&format!("version = \"{}\"", agent.version),
"version = \"9.9.9\"",
1,
);
std::fs::write(&manifest_path, bumped).unwrap();
let plan = plan_agent_actions(dir.path());
let (_, action) = plan
.iter()
.find(|(a, _)| a.name == agent.name)
.expect("the bundled agent is in the plan");
assert_eq!(
*action,
AgentAction::Update {
from: "9.9.9".to_string()
}
);
assert!(action.is_change());
assert_eq!(
action.label(agent.version),
format!("update 9.9.9 → {}", agent.version)
);
}
#[test]
fn install_writes_every_file_including_nested_ones() {
let dir = tempfile::tempdir().unwrap();
for agent in BUNDLED_AGENTS {
install_bundled(agent, dir.path()).unwrap();
for (rel, contents) in agent.files {
let written = std::fs::read_to_string(dir.path().join(agent.name).join(rel));
assert!(written.is_ok(), "{}/{rel} was not written", agent.name);
assert_eq!(written.expect("asserted Ok just above"), *contents);
}
}
assert!(
BUNDLED_AGENTS
.iter()
.any(|a| a.files.iter().any(|(rel, _)| rel.contains('/'))),
"no bundled blueprint has a nested file, so install's mkdir path is untested"
);
}
#[test]
fn install_replaces_an_existing_tree_and_drops_stale_files() {
let dir = tempfile::tempdir().unwrap();
let agent = &BUNDLED_AGENTS[0];
install_bundled(agent, dir.path()).unwrap();
let stale = dir
.path()
.join(agent.name)
.join("stale-from-an-older-version");
std::fs::write(&stale, "leftover").unwrap();
install_bundled(agent, dir.path()).unwrap();
assert!(
!stale.exists(),
"a reinstall must not leave files from the previous version behind"
);
assert!(dir.path().join(agent.name).join("agent.leviath").exists());
}
#[test]
fn install_surfaces_a_directory_creation_failure() {
let dir = tempfile::tempdir().unwrap();
let blocked = dir.path().join("not-a-dir");
std::fs::write(&blocked, "").unwrap();
let result = install_bundled(&BUNDLED_AGENTS[0], &blocked);
assert!(result.is_err());
}
#[test]
fn install_surfaces_a_file_write_failure() {
let agent = BundledAgent {
name: "collides-with-its-own-directory",
version: "0.0.1",
files: &[("tools/a.rhai", "nested first"), ("tools", "then the dir")],
};
let dir = tempfile::tempdir().unwrap();
let result = install_bundled(&agent, dir.path());
assert!(result.is_err());
}
#[test]
fn install_surfaces_a_remove_failure() {
let dir = tempfile::tempdir().unwrap();
let agent = &BUNDLED_AGENTS[0];
std::fs::write(dir.path().join(agent.name), "").unwrap();
let result = install_bundled(agent, dir.path());
assert!(result.is_err());
}
}