Skip to main content

aither_agent/
subagent_file.rs

1//! File-based subagent definitions.
2//!
3//! Subagents can be defined in markdown files with YAML frontmatter:
4//!
5//! ```markdown
6//! ---
7//! name: subagent-id
8//! description: One sentence description of when to use this subagent.
9//! ---
10//!
11//! # Subagent Title
12//!
13//! System prompt content here...
14//! ```
15//!
16//! The `name` field is the subagent ID used for tool registration.
17//! The `description` field is shown in tool listings.
18//! Everything after the frontmatter is the system prompt.
19
20use 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/// A subagent definition loaded from a file.
42#[derive(Debug, Clone)]
43pub struct SubagentDefinition {
44    /// Unique identifier (e.g., "explore", "plan").
45    pub id: String,
46    /// One-sentence description for the tool listing.
47    pub description: String,
48    /// System prompt for the subagent.
49    pub system_prompt: String,
50    /// Maximum iterations (default: 20).
51    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    /// Parse a subagent definition from markdown content with YAML frontmatter.
98    ///
99    /// Format:
100    /// ```markdown
101    /// ---
102    /// name: subagent-id
103    /// description: Description of when to use this subagent.
104    /// ---
105    ///
106    /// System prompt content...
107    /// ```
108    ///
109    /// # Errors
110    ///
111    /// Returns an error when frontmatter is missing, invalid, or uses an unsupported version.
112    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    /// Load a subagent definition from a file asynchronously.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error when the file cannot be read or parsed.
128    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    /// Load all subagent definitions from a directory asynchronously.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error when the directory cannot be read or any definition cannot be parsed.
138    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/// Default subagent definitions embedded in the binary.
160///
161/// # Panics
162///
163/// Panics if an embedded subagent definition is invalid.
164#[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        // Check that explore is present
210        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        // Check that plan is present
217        let plan = defs.iter().find(|d| d.id == "plan");
218        assert!(plan.is_some(), "should have plan subagent");
219    }
220}