use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use aither_core::{
LanguageModel,
llm::{Tool, ToolResult},
};
use aither_sandbox::TerminalToolFactory;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::AgentBuilder;
use crate::fs_util::path_exists;
use crate::subagent_file::SubagentDefinition;
async fn checked_path_exists(path: &Path) -> anyhow::Result<bool> {
path_exists(path)
.await
.map_err(|error| anyhow::anyhow!("failed to inspect path '{}': {error}", path.display()))
}
pub type SubagentBuilder<LLM> = Arc<dyn Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync>;
pub struct SubagentType<LLM> {
pub description: String,
builder: SubagentBuilder<LLM>,
}
#[derive(Clone, Debug)]
pub struct SubagentFileMount {
pub virtual_prefix: PathBuf,
pub host_root: PathBuf,
}
impl SubagentFileMount {
#[must_use]
pub fn new(virtual_prefix: impl Into<PathBuf>, host_root: impl Into<PathBuf>) -> Self {
Self {
virtual_prefix: virtual_prefix.into(),
host_root: host_root.into(),
}
}
}
impl<LLM> std::fmt::Debug for SubagentType<LLM> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubagentType")
.field("description", &self.description)
.finish_non_exhaustive()
}
}
impl<LLM: Clone> SubagentType<LLM> {
pub fn new<F>(description: impl Into<String>, builder: F) -> Self
where
F: Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync + 'static,
{
Self {
description: description.into(),
builder: Arc::new(builder),
}
}
pub fn builder(&self, llm: LLM) -> AgentBuilder<LLM, LLM, LLM, ()> {
(self.builder)(llm)
}
}
#[derive(Debug, Clone, JsonSchema, Deserialize)]
pub struct SubagentArgs {
pub subagent: String,
pub prompt: String,
}
#[derive(Debug, Clone, Serialize)]
struct SubagentResult {
subagent: String,
status: &'static str,
result: String,
}
pub struct SubagentTool<LLM> {
llm: LLM,
types: HashMap<String, SubagentType<LLM>>,
base_dir: Option<PathBuf>,
mounts: Vec<SubagentFileMount>,
terminal_tool_factory: Option<TerminalToolFactory>,
}
impl<LLM> std::fmt::Debug for SubagentTool<LLM> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let type_names: Vec<_> = self.types.keys().cloned().collect();
f.debug_struct("SubagentTool")
.field("type_names", &type_names)
.field("base_dir", &self.base_dir)
.finish_non_exhaustive()
}
}
impl<LLM: Clone + Sync> SubagentTool<LLM> {
pub fn new(llm: LLM) -> Self {
Self {
llm,
types: HashMap::new(),
base_dir: None,
mounts: Vec::new(),
terminal_tool_factory: None,
}
}
#[must_use]
pub fn with_base_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
self.base_dir = Some(dir.into());
self
}
#[must_use]
pub fn with_file_mounts<I>(mut self, mounts: I) -> Self
where
I: IntoIterator<Item = SubagentFileMount>,
{
self.mounts = mounts.into_iter().collect();
self
}
#[must_use]
pub fn with_terminal_tool_factory(mut self, factory: TerminalToolFactory) -> Self {
self.terminal_tool_factory = Some(factory);
self
}
pub fn register(&mut self, name: impl Into<String>, subagent: SubagentType<LLM>) {
let name = name.into();
self.types.insert(name, subagent);
}
#[must_use]
pub fn with_type(mut self, name: impl Into<String>, subagent: SubagentType<LLM>) -> Self {
self.register(name, subagent);
self
}
pub fn type_descriptions(&self) -> Vec<(&str, &str)> {
self.types
.iter()
.map(|(name, t)| (name.as_str(), t.description.as_str()))
.collect()
}
fn effective_mounts(&self) -> Vec<SubagentFileMount> {
if !self.mounts.is_empty() {
return self.mounts.clone();
}
let base = self
.base_dir
.clone()
.unwrap_or_else(|| PathBuf::from(Path::new(".")));
vec![
SubagentFileMount::new(PathBuf::from("."), base.clone()),
SubagentFileMount::new(PathBuf::from("subagents"), base.join("subagents")),
SubagentFileMount::new(PathBuf::from("skills"), base.join("skills")),
]
}
fn strip_leading_curdir(path: &Path) -> PathBuf {
let mut stripped = PathBuf::new();
for component in path.components() {
if matches!(component, Component::CurDir) {
continue;
}
stripped.push(component.as_os_str());
}
stripped
}
fn to_mount_relative(path: &Path, virtual_prefix: &Path) -> Option<PathBuf> {
let normalized_path = Self::strip_leading_curdir(path);
if normalized_path.as_os_str().is_empty() {
return None;
}
if normalized_path.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return None;
}
let normalized_prefix = Self::strip_leading_curdir(virtual_prefix);
if normalized_prefix.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return None;
}
if normalized_prefix.as_os_str().is_empty() {
return Some(normalized_path);
}
if normalized_path.starts_with(&normalized_prefix) {
let Ok(stripped) = normalized_path.strip_prefix(&normalized_prefix) else {
return None;
};
let relative = Self::strip_leading_curdir(stripped);
if relative.as_os_str().is_empty() {
None
} else {
Some(relative)
}
} else {
None
}
}
fn mount_specificity(prefix: &Path) -> usize {
Self::strip_leading_curdir(prefix).components().count()
}
fn matching_mounts<'a>(
mounts: &'a [SubagentFileMount],
file_path: &Path,
) -> Vec<(usize, &'a SubagentFileMount, PathBuf)> {
let mut matched = mounts
.iter()
.enumerate()
.filter_map(|(index, mount)| {
Self::to_mount_relative(file_path, &mount.virtual_prefix)
.map(|relative| (index, mount, relative))
})
.collect::<Vec<_>>();
matched.sort_by(|(index_a, mount_a, _), (index_b, mount_b, _)| {
Self::mount_specificity(&mount_b.virtual_prefix)
.cmp(&Self::mount_specificity(&mount_a.virtual_prefix))
.then(index_a.cmp(index_b))
});
matched
}
async fn resolve_relative_path_through_mounts(
requested_display: &Path,
file_path: &Path,
mounts: &[SubagentFileMount],
) -> anyhow::Result<PathBuf> {
let mut attempted = Vec::new();
let matched = Self::matching_mounts(mounts, file_path);
for (_, mount, relative) in matched {
let candidate = mount.host_root.join(relative);
let display_prefix = Self::strip_leading_curdir(&mount.virtual_prefix);
let display_path = if display_prefix.as_os_str().is_empty() {
candidate
.strip_prefix(&mount.host_root)
.map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf)
} else {
display_prefix.join(
candidate
.strip_prefix(&mount.host_root)
.map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf),
)
};
attempted.push(display_path.display().to_string());
if checked_path_exists(&candidate).await? {
return Ok(candidate);
}
}
if attempted.is_empty() {
return Err(anyhow::anyhow!(
"Subagent file '{}' is outside mounted paths or uses forbidden path components",
requested_display.display()
));
}
Err(anyhow::anyhow!(
"Subagent file '{}' not found. Attempted: {}",
requested_display.display(),
attempted.join(", ")
))
}
async fn resolve_subagent_path(
mounts: &[SubagentFileMount],
base_dir: Option<&Path>,
file_path: &Path,
) -> anyhow::Result<PathBuf> {
if file_path.is_absolute() {
if let Some(base_dir) = base_dir
&& let Ok(stripped) = file_path.strip_prefix(base_dir)
{
let relative = Self::strip_leading_curdir(stripped);
if !relative.as_os_str().is_empty() {
return Self::resolve_relative_path_through_mounts(
&relative, &relative, mounts,
)
.await;
}
}
if checked_path_exists(file_path).await? {
return Ok(file_path.to_path_buf());
}
return Err(anyhow::anyhow!(
"Subagent file '{}' not found",
file_path.display()
));
}
Self::resolve_relative_path_through_mounts(file_path, file_path, mounts).await
}
}
impl<LLM: LanguageModel + Clone + Sync> SubagentTool<LLM> {
#[must_use]
pub fn with_definition(self, def: SubagentDefinition) -> Self {
let subagent = SubagentType::new(def.description.clone(), move |llm| {
crate::AgentBuilder::new(llm)
.agent_kind(crate::AgentKind::Chatbot)
.system_prompt(&def.system_prompt)
.max_iterations(def.max_iterations)
});
self.with_type(def.id, subagent)
}
#[must_use]
pub fn with_builtins(mut self) -> Self {
for def in crate::builtin_subagents() {
self = self.with_definition(def);
}
self
}
}
impl<LLM> Tool for SubagentTool<LLM>
where
LLM: LanguageModel + Clone + Sync + 'static,
{
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("subagent")
}
type Arguments = SubagentArgs;
type Res = ToolResult;
async fn call(&self, args: Self::Arguments) -> aither_core::Result<Self::Res> {
let is_file_path = args.subagent.contains('/')
|| Path::new(&args.subagent)
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("md"));
let (subagent_id, agent_builder) = if is_file_path {
let file_path = PathBuf::from(&args.subagent);
let resolved_path = Self::resolve_subagent_path(
&self.effective_mounts(),
self.base_dir.as_deref(),
&file_path,
)
.await?;
let def = SubagentDefinition::from_file_async(&resolved_path)
.await
.map_err(|e| {
anyhow::anyhow!(
"Failed to read subagent file '{}': {e}",
resolved_path.display()
)
})?;
let builder = crate::AgentBuilder::new(self.llm.clone())
.agent_kind(crate::AgentKind::Chatbot)
.system_prompt(&def.system_prompt)
.max_iterations(def.max_iterations);
(def.id, builder)
} else {
let type_name = &args.subagent;
let subagent_type = self.types.get(type_name).ok_or_else(|| {
let available: Vec<&str> =
self.types.keys().map(std::string::String::as_str).collect();
anyhow::anyhow!(
"Unknown subagent type '{}'. Available: {}",
type_name,
available.join(", ")
)
})?;
(type_name.clone(), subagent_type.builder(self.llm.clone()))
};
tracing::info!(subagent = %subagent_id, "Starting subagent");
let (agent_builder, child_job_registry) = if let Some(factory) = &self.terminal_tool_factory
{
let dyn_terminal = factory
.create()
.await
.map_err(|e| anyhow::anyhow!("failed to create subagent terminal tool: {e}"))?;
let job_registry = dyn_terminal.job_registry();
(agent_builder.dyn_terminal(dyn_terminal), Some(job_registry))
} else {
(agent_builder, None)
};
let mut agent = agent_builder.build();
let query_result = agent.query(&args.prompt).await;
if let Some(job_registry) = child_job_registry {
let killed = job_registry.kill_running().await;
if killed > 0 {
tracing::info!(
subagent = %subagent_id,
killed,
"Stopped background terminal jobs left by completed subagent"
);
}
}
let result = match query_result {
Ok(result) => result,
Err(error) => {
let history = agent.history();
let recent = history
.into_iter()
.rev()
.take(12)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect::<Vec<_>>();
let recent_json = serde_json::to_string(&recent)
.unwrap_or_else(|serialize_error| serialize_error.to_string());
return Err(anyhow::anyhow!(
"Subagent '{subagent_id}' error: {error}\nRecent subagent history: {recent_json}"
));
}
};
tracing::info!(subagent = %subagent_id, "Subagent completed");
ToolResult::json(&SubagentResult {
subagent: subagent_id,
status: "completed",
result,
})
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
#[test]
fn subagent_args_schema() {
let schema = schemars::schema_for!(SubagentArgs);
let value = schema.to_value();
let props = value.get("properties").expect("should have properties");
assert!(props.get("subagent").is_some());
assert!(props.get("prompt").is_some());
let required = value.get("required").expect("should have required");
assert!(required.is_array());
}
#[test]
fn subagent_result_serializes_as_structured_json() {
let value = serde_json::to_value(SubagentResult {
subagent: "research".to_string(),
status: "completed",
result: "done".to_string(),
})
.expect("subagent result should serialize");
assert_eq!(
value,
serde_json::json!({
"subagent": "research",
"status": "completed",
"result": "done",
})
);
}
fn unique_temp_dir(tag: &str) -> PathBuf {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let dir = std::env::temp_dir().join(format!(
"aither-subagent-{tag}-{}-{nanos}",
std::process::id()
));
std::fs::create_dir_all(&dir).expect("create test temp dir");
dir
}
#[tokio::test]
async fn resolves_file_through_mount_prefix() {
let root = unique_temp_dir("mount-resolve");
let skills_root = root.join("skills");
let skill_file = skills_root.join("slide").join("SKILL.md");
std::fs::create_dir_all(skill_file.parent().expect("skill parent"))
.expect("create skill parent");
std::fs::write(&skill_file, "# slide").expect("write skill file");
let tool = SubagentTool::new(()).with_file_mounts([
SubagentFileMount::new(".", root.join("workspace")),
SubagentFileMount::new(".skills", skills_root.clone()),
]);
let resolved = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(),
tool.base_dir.as_deref(),
Path::new(".skills/slide/SKILL.md"),
)
.await
.expect("resolve mounted skill path");
assert_eq!(resolved, skill_file);
let _ = std::fs::remove_dir_all(root);
}
#[tokio::test]
async fn rejects_parent_traversal_paths() {
let root = unique_temp_dir("mount-traversal");
let tool = SubagentTool::new(())
.with_file_mounts([SubagentFileMount::new("skills", root.join("skills"))]);
let error = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(),
tool.base_dir.as_deref(),
Path::new("../outside.md"),
)
.await
.expect_err("parent traversal should fail");
assert!(
error
.to_string()
.contains("outside mounted paths or uses forbidden path components"),
"unexpected error: {error}"
);
let _ = std::fs::remove_dir_all(root);
}
#[tokio::test]
async fn missing_file_error_does_not_leak_host_mount_path() {
let root = unique_temp_dir("mount-errors");
let skills_root = root.join("skills");
std::fs::create_dir_all(&skills_root).expect("create skills root");
let tool = SubagentTool::new(())
.with_file_mounts([SubagentFileMount::new("skills", skills_root.clone())]);
let error = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(),
tool.base_dir.as_deref(),
Path::new(".skills/missing.md"),
)
.await
.expect_err("missing file should fail");
let message = error.to_string();
assert!(
message.contains("skills/missing.md"),
"missing virtual path in error: {message}"
);
assert!(
!message.contains(skills_root.to_string_lossy().as_ref()),
"host path leaked in error: {message}"
);
let _ = std::fs::remove_dir_all(root);
}
#[tokio::test]
async fn absolute_workspace_skills_path_resolves_to_skills_mount() {
let root = unique_temp_dir("absolute-workspace-skills");
let workspace_root = root.join("workspace");
let skills_root = root.join("skills");
let session_skills_file = workspace_root.join("skills/slide/subagents/art_direction.md");
let mounted_skill_file = skills_root.join("slide/subagents/art_direction.md");
std::fs::create_dir_all(session_skills_file.parent().expect("session skill parent"))
.expect("create session skill parent");
std::fs::create_dir_all(mounted_skill_file.parent().expect("mounted skill parent"))
.expect("create mounted skill parent");
std::fs::write(&mounted_skill_file, "# art direction").expect("write mounted skill file");
let tool = SubagentTool::new(())
.with_base_dir(workspace_root.clone())
.with_file_mounts([
SubagentFileMount::new(".", workspace_root.clone()),
SubagentFileMount::new("skills", skills_root.clone()),
]);
let resolved = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(),
tool.base_dir.as_deref(),
&session_skills_file,
)
.await
.expect("resolve absolute workspace .skills path");
assert_eq!(resolved, mounted_skill_file);
let _ = std::fs::remove_dir_all(root);
}
}