aither_agent/
subagent_file.rs1use std::path::Path;
21
22use async_fs as fs;
23use futures_lite::stream::StreamExt;
24use serde::Deserialize;
25
26const CURRENT_SUBAGENT_VERSION: u32 = 1;
27
28#[derive(Debug, Deserialize)]
29struct SubagentFrontmatter {
30 version: u32,
31 name: String,
32 description: String,
33 #[serde(default = "default_max_iterations")]
34 max_iterations: usize,
35}
36
37const fn default_max_iterations() -> usize {
38 20
39}
40
41#[derive(Debug, Clone)]
43pub struct SubagentDefinition {
44 pub id: String,
46 pub description: String,
48 pub system_prompt: String,
50 pub max_iterations: usize,
52}
53
54impl SubagentDefinition {
55 fn split_frontmatter(content: &str) -> Result<(&str, &str), String> {
56 let content = content.trim();
57 let Some(after_open) = content.strip_prefix("---") else {
58 return Err("subagent definition must start with YAML frontmatter".to_string());
59 };
60 let after_open = after_open.trim_start_matches(['\r', '\n']);
61 let Some(close_idx) = after_open.find("\n---") else {
62 return Err("subagent definition frontmatter is not terminated".to_string());
63 };
64 let frontmatter = &after_open[..close_idx];
65 let system_prompt = after_open[close_idx + 4..].trim();
66 if system_prompt.is_empty() {
67 return Err("subagent definition system prompt must not be empty".to_string());
68 }
69 Ok((frontmatter, system_prompt))
70 }
71
72 fn parse_frontmatter(frontmatter: &str) -> Result<SubagentFrontmatter, String> {
73 let parsed: SubagentFrontmatter =
74 serde_yaml::from_str(frontmatter).map_err(|error| error.to_string())?;
75 if parsed.version != CURRENT_SUBAGENT_VERSION {
76 let mut message = String::new();
77 message.push_str("unsupported subagent definition version: ");
78 message.push_str(parsed.version.to_string().as_str());
79 return Err(message);
80 }
81 if parsed.name.trim().is_empty() {
82 return Err("subagent definition name must not be empty".to_string());
83 }
84 if parsed.description.trim().is_empty() {
85 return Err("subagent definition description must not be empty".to_string());
86 }
87 if parsed.max_iterations == 0 {
88 return Err("subagent definition max_iterations must be > 0".to_string());
89 }
90 Ok(parsed)
91 }
92
93 fn invalid_data_error(message: String) -> std::io::Error {
94 std::io::Error::new(std::io::ErrorKind::InvalidData, message)
95 }
96
97 pub fn parse(content: &str) -> Result<Self, String> {
113 let (frontmatter, system_prompt) = Self::split_frontmatter(content)?;
114 let parsed = Self::parse_frontmatter(frontmatter)?;
115 Ok(Self {
116 id: parsed.name,
117 description: parsed.description,
118 system_prompt: system_prompt.to_string(),
119 max_iterations: parsed.max_iterations,
120 })
121 }
122
123 pub async fn from_file_async(path: impl AsRef<Path>) -> std::io::Result<Self> {
129 let content = fs::read_to_string(path).await?;
130 Self::parse(&content).map_err(Self::invalid_data_error)
131 }
132
133 pub async fn load_from_dir_async(dir: impl AsRef<Path>) -> std::io::Result<Vec<Self>> {
139 let mut definitions = Vec::new();
140 let dir = dir.as_ref();
141
142 let mut entries = match fs::read_dir(dir).await {
143 Ok(entries) => entries,
144 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
145 Err(e) => return Err(e),
146 };
147
148 while let Some(entry) = entries.try_next().await? {
149 let path = entry.path();
150 if path.extension().is_some_and(|e| e == "md") {
151 definitions.push(Self::from_file_async(&path).await?);
152 }
153 }
154
155 Ok(definitions)
156 }
157}
158
159#[must_use]
165pub fn builtin_subagents() -> Vec<SubagentDefinition> {
166 vec![
167 SubagentDefinition::parse(include_str!("prompts/subagents/explore.md"))
168 .expect("builtin explore subagent must parse"),
169 SubagentDefinition::parse(include_str!("prompts/subagents/plan.md"))
170 .expect("builtin plan subagent must parse"),
171 SubagentDefinition::parse(include_str!("prompts/subagents/research.md"))
172 .expect("builtin research subagent must parse"),
173 ]
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn parse_subagent_definition() {
182 let content = r"---
183version: 1
184name: test-agent
185description: This is a test agent for exploring and testing.
186max_iterations: 42
187---
188
189# Test Agent
190
191You are a test agent. Do test things.
192";
193
194 let def = SubagentDefinition::parse(content).unwrap();
195 assert_eq!(def.id, "test-agent");
196 assert_eq!(
197 def.description,
198 "This is a test agent for exploring and testing."
199 );
200 assert_eq!(def.max_iterations, 42);
201 assert!(def.system_prompt.contains("You are a test agent"));
202 }
203
204 #[test]
205 fn builtin_subagents_load() {
206 let defs = builtin_subagents();
207 assert!(!defs.is_empty(), "should have builtin subagents");
208
209 let explore = defs.iter().find(|d| d.id == "explore");
211 assert!(explore.is_some(), "should have explore subagent");
212 let explore = explore.unwrap();
213 assert_ne!(explore.description, "");
214 assert_ne!(explore.system_prompt, "");
215
216 let plan = defs.iter().find(|d| d.id == "plan");
218 assert!(plan.is_some(), "should have plan subagent");
219 }
220}