1use std::borrow::Cow;
9use std::collections::HashMap;
10use std::path::Component;
11use std::path::Path;
12use std::path::PathBuf;
13use std::sync::Arc;
14
15use aither_core::llm::ToolContext;
16use aither_core::{
17 LanguageModel,
18 llm::{Tool, ToolResult},
19};
20use aither_sandbox::TerminalToolFactory;
21use schemars::JsonSchema;
22use serde::{Deserialize, Serialize};
23
24use crate::AgentBuilder;
25use crate::fs_util::path_exists;
26use crate::subagent_file::SubagentDefinition;
27
28async fn checked_path_exists(path: &Path) -> anyhow::Result<bool> {
29 path_exists(path)
30 .await
31 .map_err(|error| anyhow::anyhow!("failed to inspect path '{}': {error}", path.display()))
32}
33
34pub type SubagentBuilder<LLM> = Arc<dyn Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync>;
38
39pub struct SubagentType<LLM> {
41 pub description: String,
43 builder: SubagentBuilder<LLM>,
45}
46
47#[derive(Clone, Debug)]
52pub struct SubagentFileMount {
53 pub virtual_prefix: PathBuf,
55 pub host_root: PathBuf,
57}
58
59impl SubagentFileMount {
60 #[must_use]
62 pub fn new(virtual_prefix: impl Into<PathBuf>, host_root: impl Into<PathBuf>) -> Self {
63 Self {
64 virtual_prefix: virtual_prefix.into(),
65 host_root: host_root.into(),
66 }
67 }
68}
69
70impl<LLM> std::fmt::Debug for SubagentType<LLM> {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 f.debug_struct("SubagentType")
73 .field("description", &self.description)
74 .finish_non_exhaustive()
75 }
76}
77
78impl<LLM: Clone> SubagentType<LLM> {
79 pub fn new<F>(description: impl Into<String>, builder: F) -> Self
84 where
85 F: Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync + 'static,
86 {
87 Self {
88 description: description.into(),
89 builder: Arc::new(builder),
90 }
91 }
92
93 pub fn builder(&self, llm: LLM) -> AgentBuilder<LLM, LLM, LLM, ()> {
95 (self.builder)(llm)
96 }
97}
98
99#[derive(Debug, Clone, JsonSchema, Deserialize)]
115pub struct SubagentArgs {
116 pub subagent: String,
119 pub prompt: String,
121}
122
123#[derive(Debug, Clone, Serialize)]
124struct SubagentResult {
125 subagent: String,
126 status: &'static str,
127 result: String,
128}
129
130pub struct SubagentTool<LLM> {
158 llm: LLM,
159 types: HashMap<String, SubagentType<LLM>>,
160 base_dir: Option<PathBuf>,
162 mounts: Vec<SubagentFileMount>,
164 terminal_tool_factory: Option<TerminalToolFactory>,
166}
167
168impl<LLM> std::fmt::Debug for SubagentTool<LLM> {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 let type_names: Vec<_> = self.types.keys().cloned().collect();
171 f.debug_struct("SubagentTool")
172 .field("type_names", &type_names)
173 .field("base_dir", &self.base_dir)
174 .finish_non_exhaustive()
175 }
176}
177
178impl<LLM: Clone + Sync> SubagentTool<LLM> {
179 pub fn new(llm: LLM) -> Self {
181 Self {
182 llm,
183 types: HashMap::new(),
184 base_dir: None,
185 mounts: Vec::new(),
186 terminal_tool_factory: None,
187 }
188 }
189
190 #[must_use]
195 pub fn with_base_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
196 self.base_dir = Some(dir.into());
197 self
198 }
199
200 #[must_use]
204 pub fn with_file_mounts<I>(mut self, mounts: I) -> Self
205 where
206 I: IntoIterator<Item = SubagentFileMount>,
207 {
208 self.mounts = mounts.into_iter().collect();
209 self
210 }
211
212 #[must_use]
214 pub fn with_terminal_tool_factory(mut self, factory: TerminalToolFactory) -> Self {
215 self.terminal_tool_factory = Some(factory);
216 self
217 }
218
219 pub fn register(&mut self, name: impl Into<String>, subagent: SubagentType<LLM>) {
221 let name = name.into();
222 self.types.insert(name, subagent);
223 }
224
225 #[must_use]
227 pub fn with_type(mut self, name: impl Into<String>, subagent: SubagentType<LLM>) -> Self {
228 self.register(name, subagent);
229 self
230 }
231
232 pub fn type_descriptions(&self) -> Vec<(&str, &str)> {
237 self.types
238 .iter()
239 .map(|(name, t)| (name.as_str(), t.description.as_str()))
240 .collect()
241 }
242
243 fn effective_mounts(&self) -> Vec<SubagentFileMount> {
244 if !self.mounts.is_empty() {
245 return self.mounts.clone();
246 }
247
248 let base = self
249 .base_dir
250 .clone()
251 .unwrap_or_else(|| PathBuf::from(Path::new(".")));
252 vec![
253 SubagentFileMount::new(PathBuf::from("."), base.clone()),
254 SubagentFileMount::new(PathBuf::from("subagents"), base.join("subagents")),
255 SubagentFileMount::new(PathBuf::from("skills"), base.join("skills")),
256 ]
257 }
258
259 fn strip_leading_curdir(path: &Path) -> PathBuf {
260 let mut stripped = PathBuf::new();
261 for component in path.components() {
262 if matches!(component, Component::CurDir) {
263 continue;
264 }
265 stripped.push(component.as_os_str());
266 }
267 stripped
268 }
269
270 fn to_mount_relative(path: &Path, virtual_prefix: &Path) -> Option<PathBuf> {
271 let normalized_path = Self::strip_leading_curdir(path);
272 if normalized_path.as_os_str().is_empty() {
273 return None;
274 }
275 if normalized_path.components().any(|component| {
276 matches!(
277 component,
278 Component::ParentDir | Component::RootDir | Component::Prefix(_)
279 )
280 }) {
281 return None;
282 }
283
284 let normalized_prefix = Self::strip_leading_curdir(virtual_prefix);
285 if normalized_prefix.components().any(|component| {
286 matches!(
287 component,
288 Component::ParentDir | Component::RootDir | Component::Prefix(_)
289 )
290 }) {
291 return None;
292 }
293 if normalized_prefix.as_os_str().is_empty() {
294 return Some(normalized_path);
295 }
296
297 if normalized_path.starts_with(&normalized_prefix) {
298 let Ok(stripped) = normalized_path.strip_prefix(&normalized_prefix) else {
299 return None;
300 };
301 let relative = Self::strip_leading_curdir(stripped);
302 if relative.as_os_str().is_empty() {
303 None
304 } else {
305 Some(relative)
306 }
307 } else {
308 None
309 }
310 }
311
312 fn mount_specificity(prefix: &Path) -> usize {
313 Self::strip_leading_curdir(prefix).components().count()
314 }
315
316 fn matching_mounts<'a>(
317 mounts: &'a [SubagentFileMount],
318 file_path: &Path,
319 ) -> Vec<(usize, &'a SubagentFileMount, PathBuf)> {
320 let mut matched = mounts
321 .iter()
322 .enumerate()
323 .filter_map(|(index, mount)| {
324 Self::to_mount_relative(file_path, &mount.virtual_prefix)
325 .map(|relative| (index, mount, relative))
326 })
327 .collect::<Vec<_>>();
328 matched.sort_by(|(index_a, mount_a, _), (index_b, mount_b, _)| {
329 Self::mount_specificity(&mount_b.virtual_prefix)
330 .cmp(&Self::mount_specificity(&mount_a.virtual_prefix))
331 .then(index_a.cmp(index_b))
332 });
333 matched
334 }
335
336 async fn resolve_relative_path_through_mounts(
337 requested_display: &Path,
338 file_path: &Path,
339 mounts: &[SubagentFileMount],
340 ) -> anyhow::Result<PathBuf> {
341 let mut attempted = Vec::new();
342 let matched = Self::matching_mounts(mounts, file_path);
343
344 for (_, mount, relative) in matched {
345 let candidate = mount.host_root.join(relative);
346 let display_prefix = Self::strip_leading_curdir(&mount.virtual_prefix);
347 let display_path = if display_prefix.as_os_str().is_empty() {
348 candidate
349 .strip_prefix(&mount.host_root)
350 .map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf)
351 } else {
352 display_prefix.join(
353 candidate
354 .strip_prefix(&mount.host_root)
355 .map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf),
356 )
357 };
358 attempted.push(display_path.display().to_string());
359 if checked_path_exists(&candidate).await? {
360 return Ok(candidate);
361 }
362 }
363
364 if attempted.is_empty() {
365 return Err(anyhow::anyhow!(
366 "Subagent file '{}' is outside mounted paths or uses forbidden path components",
367 requested_display.display()
368 ));
369 }
370
371 Err(anyhow::anyhow!(
372 "Subagent file '{}' not found. Attempted: {}",
373 requested_display.display(),
374 attempted.join(", ")
375 ))
376 }
377
378 async fn resolve_subagent_path(
383 mounts: &[SubagentFileMount],
384 base_dir: Option<&Path>,
385 file_path: &Path,
386 ) -> anyhow::Result<PathBuf> {
387 if file_path.is_absolute() {
388 if let Some(base_dir) = base_dir
389 && let Ok(stripped) = file_path.strip_prefix(base_dir)
390 {
391 let relative = Self::strip_leading_curdir(stripped);
392 if !relative.as_os_str().is_empty() {
393 return Self::resolve_relative_path_through_mounts(
394 &relative, &relative, mounts,
395 )
396 .await;
397 }
398 }
399
400 if checked_path_exists(file_path).await? {
401 return Ok(file_path.to_path_buf());
402 }
403 return Err(anyhow::anyhow!(
404 "Subagent file '{}' not found",
405 file_path.display()
406 ));
407 }
408
409 Self::resolve_relative_path_through_mounts(file_path, file_path, mounts).await
410 }
411}
412
413impl<LLM: LanguageModel + Clone + Sync> SubagentTool<LLM> {
414 #[must_use]
419 pub fn with_definition(self, def: SubagentDefinition) -> Self {
420 let subagent = SubagentType::new(def.description.clone(), move |llm| {
421 crate::AgentBuilder::new(llm)
422 .agent_kind(crate::AgentKind::Chatbot)
423 .system_prompt(&def.system_prompt)
424 .max_iterations(def.max_iterations)
425 });
426 self.with_type(def.id, subagent)
427 }
428
429 #[must_use]
433 pub fn with_builtins(mut self) -> Self {
434 for def in crate::builtin_subagents() {
435 self = self.with_definition(def);
436 }
437 self
438 }
439}
440
441impl<LLM> Tool for SubagentTool<LLM>
442where
443 LLM: LanguageModel + Clone + Sync + 'static,
444{
445 fn name(&self) -> Cow<'static, str> {
446 Cow::Borrowed("subagent")
447 }
448
449 type Arguments = SubagentArgs;
450 type Res = ToolResult;
451
452 async fn call(
453 &self,
454 args: Self::Arguments,
455 _cx: ToolContext,
456 ) -> aither_core::Result<Self::Res> {
457 let is_file_path = args.subagent.contains('/')
460 || Path::new(&args.subagent)
461 .extension()
462 .is_some_and(|extension| extension.eq_ignore_ascii_case("md"));
463
464 let (subagent_id, agent_builder) = if is_file_path {
465 let file_path = PathBuf::from(&args.subagent);
468 let resolved_path = Self::resolve_subagent_path(
469 &self.effective_mounts(),
470 self.base_dir.as_deref(),
471 &file_path,
472 )
473 .await?;
474
475 let def = SubagentDefinition::from_file_async(&resolved_path)
476 .await
477 .map_err(|e| {
478 anyhow::anyhow!(
479 "Failed to read subagent file '{}': {e}",
480 resolved_path.display()
481 )
482 })?;
483
484 let builder = crate::AgentBuilder::new(self.llm.clone())
485 .agent_kind(crate::AgentKind::Chatbot)
486 .system_prompt(&def.system_prompt)
487 .max_iterations(def.max_iterations);
488
489 (def.id, builder)
490 } else {
491 let type_name = &args.subagent;
493 let subagent_type = self.types.get(type_name).ok_or_else(|| {
494 let available: Vec<&str> =
495 self.types.keys().map(std::string::String::as_str).collect();
496 anyhow::anyhow!(
497 "Unknown subagent type '{}'. Available: {}",
498 type_name,
499 available.join(", ")
500 )
501 })?;
502 (type_name.clone(), subagent_type.builder(self.llm.clone()))
503 };
504
505 tracing::info!(subagent = %subagent_id, "Starting subagent");
506
507 let (agent_builder, child_job_registry) = if let Some(factory) = &self.terminal_tool_factory
509 {
510 let dyn_terminal = factory
511 .create()
512 .await
513 .map_err(|e| anyhow::anyhow!("failed to create subagent terminal tool: {e}"))?;
514 let job_registry = dyn_terminal.job_registry();
515 (agent_builder.dyn_terminal(dyn_terminal), Some(job_registry))
516 } else {
517 (agent_builder, None)
518 };
519
520 let mut agent = agent_builder.build();
521
522 let query_result = agent.query(&args.prompt).await;
524 if let Some(job_registry) = child_job_registry {
525 let killed = job_registry.kill_running().await;
526 if killed > 0 {
527 tracing::info!(
528 subagent = %subagent_id,
529 killed,
530 "Stopped background terminal jobs left by completed subagent"
531 );
532 }
533 }
534 let result = match query_result {
535 Ok(result) => result,
536 Err(error) => {
537 let history = agent.history();
538 let recent = history
539 .into_iter()
540 .rev()
541 .take(12)
542 .collect::<Vec<_>>()
543 .into_iter()
544 .rev()
545 .collect::<Vec<_>>();
546 let recent_json = serde_json::to_string(&recent)
547 .unwrap_or_else(|serialize_error| serialize_error.to_string());
548 return Err(anyhow::anyhow!(
549 "Subagent '{subagent_id}' error: {error}\nRecent subagent history: {recent_json}"
550 ));
551 }
552 };
553
554 tracing::info!(subagent = %subagent_id, "Subagent completed");
555
556 ToolResult::json(&SubagentResult {
557 subagent: subagent_id,
558 status: "completed",
559 result,
560 })
561 }
562}
563
564#[cfg(test)]
565mod tests {
566 use std::path::PathBuf;
567
568 use super::*;
569
570 #[test]
571 fn subagent_args_schema() {
572 let schema = schemars::schema_for!(SubagentArgs);
573 let value = schema.to_value();
574 let props = value.get("properties").expect("should have properties");
575 assert!(props.get("subagent").is_some());
576 assert!(props.get("prompt").is_some());
577
578 let required = value.get("required").expect("should have required");
580 assert!(required.is_array());
581 }
582
583 #[test]
584 fn subagent_result_serializes_as_structured_json() {
585 let value = serde_json::to_value(SubagentResult {
586 subagent: "research".to_string(),
587 status: "completed",
588 result: "done".to_string(),
589 })
590 .expect("subagent result should serialize");
591 assert_eq!(
592 value,
593 serde_json::json!({
594 "subagent": "research",
595 "status": "completed",
596 "result": "done",
597 })
598 );
599 }
600
601 fn unique_temp_dir(tag: &str) -> PathBuf {
602 let nanos = std::time::SystemTime::now()
603 .duration_since(std::time::UNIX_EPOCH)
604 .expect("system clock before unix epoch")
605 .as_nanos();
606 let dir = std::env::temp_dir().join(format!(
607 "aither-subagent-{tag}-{}-{nanos}",
608 std::process::id()
609 ));
610 std::fs::create_dir_all(&dir).expect("create test temp dir");
611 dir
612 }
613
614 #[tokio::test]
615 async fn resolves_file_through_mount_prefix() {
616 let root = unique_temp_dir("mount-resolve");
617 let skills_root = root.join("skills");
618 let skill_file = skills_root.join("slide").join("SKILL.md");
619 std::fs::create_dir_all(skill_file.parent().expect("skill parent"))
620 .expect("create skill parent");
621 std::fs::write(&skill_file, "# slide").expect("write skill file");
622
623 let tool = SubagentTool::new(()).with_file_mounts([
624 SubagentFileMount::new(".", root.join("workspace")),
625 SubagentFileMount::new(".skills", skills_root.clone()),
626 ]);
627 let resolved = SubagentTool::<()>::resolve_subagent_path(
628 &tool.effective_mounts(),
629 tool.base_dir.as_deref(),
630 Path::new(".skills/slide/SKILL.md"),
631 )
632 .await
633 .expect("resolve mounted skill path");
634 assert_eq!(resolved, skill_file);
635
636 let _ = std::fs::remove_dir_all(root);
637 }
638
639 #[tokio::test]
640 async fn rejects_parent_traversal_paths() {
641 let root = unique_temp_dir("mount-traversal");
642 let tool = SubagentTool::new(())
643 .with_file_mounts([SubagentFileMount::new("skills", root.join("skills"))]);
644
645 let error = SubagentTool::<()>::resolve_subagent_path(
646 &tool.effective_mounts(),
647 tool.base_dir.as_deref(),
648 Path::new("../outside.md"),
649 )
650 .await
651 .expect_err("parent traversal should fail");
652 assert!(
653 error
654 .to_string()
655 .contains("outside mounted paths or uses forbidden path components"),
656 "unexpected error: {error}"
657 );
658
659 let _ = std::fs::remove_dir_all(root);
660 }
661
662 #[tokio::test]
663 async fn missing_file_error_does_not_leak_host_mount_path() {
664 let root = unique_temp_dir("mount-errors");
665 let skills_root = root.join("skills");
666 std::fs::create_dir_all(&skills_root).expect("create skills root");
667 let tool = SubagentTool::new(())
668 .with_file_mounts([SubagentFileMount::new("skills", skills_root.clone())]);
669
670 let error = SubagentTool::<()>::resolve_subagent_path(
671 &tool.effective_mounts(),
672 tool.base_dir.as_deref(),
673 Path::new(".skills/missing.md"),
674 )
675 .await
676 .expect_err("missing file should fail");
677 let message = error.to_string();
678 assert!(
679 message.contains("skills/missing.md"),
680 "missing virtual path in error: {message}"
681 );
682 assert!(
683 !message.contains(skills_root.to_string_lossy().as_ref()),
684 "host path leaked in error: {message}"
685 );
686
687 let _ = std::fs::remove_dir_all(root);
688 }
689
690 #[tokio::test]
691 async fn absolute_workspace_skills_path_resolves_to_skills_mount() {
692 let root = unique_temp_dir("absolute-workspace-skills");
693 let workspace_root = root.join("workspace");
694 let skills_root = root.join("skills");
695 let session_skills_file = workspace_root.join("skills/slide/subagents/art_direction.md");
696 let mounted_skill_file = skills_root.join("slide/subagents/art_direction.md");
697 std::fs::create_dir_all(session_skills_file.parent().expect("session skill parent"))
698 .expect("create session skill parent");
699 std::fs::create_dir_all(mounted_skill_file.parent().expect("mounted skill parent"))
700 .expect("create mounted skill parent");
701 std::fs::write(&mounted_skill_file, "# art direction").expect("write mounted skill file");
702
703 let tool = SubagentTool::new(())
704 .with_base_dir(workspace_root.clone())
705 .with_file_mounts([
706 SubagentFileMount::new(".", workspace_root.clone()),
707 SubagentFileMount::new("skills", skills_root.clone()),
708 ]);
709
710 let resolved = SubagentTool::<()>::resolve_subagent_path(
711 &tool.effective_mounts(),
712 tool.base_dir.as_deref(),
713 &session_skills_file,
714 )
715 .await
716 .expect("resolve absolute workspace .skills path");
717 assert_eq!(resolved, mounted_skill_file);
718
719 let _ = std::fs::remove_dir_all(root);
720 }
721}