Skip to main content

aither_agent/specialized/
task.rs

1//! Subagent tool for spawning specialized subagents.
2//!
3//! Allows the main agent to delegate complex tasks to specialized subagents
4//! that run autonomously and return results.
5//!
6//! Subagents can be defined in files or registered programmatically.
7
8use 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::{
16    LanguageModel,
17    llm::{Tool, ToolResult},
18};
19use aither_sandbox::TerminalToolFactory;
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22
23use crate::AgentBuilder;
24use crate::fs_util::path_exists;
25use crate::subagent_file::SubagentDefinition;
26
27async fn checked_path_exists(path: &Path) -> anyhow::Result<bool> {
28    path_exists(path)
29        .await
30        .map_err(|error| anyhow::anyhow!("failed to inspect path '{}': {error}", path.display()))
31}
32
33/// Builder function type for configuring a subagent.
34/// Returns an `AgentBuilder` so we can add hooks before building.
35/// The builder returns a single-model agent (all tiers use the same LLM).
36pub type SubagentBuilder<LLM> = Arc<dyn Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync>;
37
38/// Configuration for a subagent type.
39pub struct SubagentType<LLM> {
40    /// Description shown to the main agent.
41    pub description: String,
42    /// Builder function that creates the configured agent builder.
43    builder: SubagentBuilder<LLM>,
44}
45
46/// Maps a path the subagent sees onto the host directory it really refers to.
47///
48/// A subagent works inside a sandbox, so the paths in its prompts are virtual;
49/// this records how to resolve them without letting one escape its root.
50#[derive(Clone, Debug)]
51pub struct SubagentFileMount {
52    /// Path prefix as the subagent sees it.
53    pub virtual_prefix: PathBuf,
54    /// Directory on the host that prefix resolves to.
55    pub host_root: PathBuf,
56}
57
58impl SubagentFileMount {
59    /// Maps `virtual_prefix` onto `host_root`.
60    #[must_use]
61    pub fn new(virtual_prefix: impl Into<PathBuf>, host_root: impl Into<PathBuf>) -> Self {
62        Self {
63            virtual_prefix: virtual_prefix.into(),
64            host_root: host_root.into(),
65        }
66    }
67}
68
69impl<LLM> std::fmt::Debug for SubagentType<LLM> {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.debug_struct("SubagentType")
72            .field("description", &self.description)
73            .finish_non_exhaustive()
74    }
75}
76
77impl<LLM: Clone> SubagentType<LLM> {
78    /// Create a new subagent type with a builder function.
79    ///
80    /// The builder function should return an `AgentBuilder` (not a built `Agent`)
81    /// so that hooks can be added before building.
82    pub fn new<F>(description: impl Into<String>, builder: F) -> Self
83    where
84        F: Fn(LLM) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync + 'static,
85    {
86        Self {
87            description: description.into(),
88            builder: Arc::new(builder),
89        }
90    }
91
92    /// Get the agent builder for this subagent type.
93    pub fn builder(&self, llm: LLM) -> AgentBuilder<LLM, LLM, LLM, ()> {
94        (self.builder)(llm)
95    }
96}
97
98/// Launch a specialized subagent for complex tasks.
99///
100/// Subagents are autonomous agents that run in their own context window.
101/// Their work does not consume your context, and they return only their
102/// final results. This enables:
103///
104/// - Context isolation for research-heavy tasks
105/// - Parallel execution of independent investigations
106/// - Specialized capabilities per subagent type
107///
108/// Each subagent type has focused tools and prompts optimized for its purpose.
109/// Choose the subagent type that best matches the task requirements.
110///
111/// You can also load custom subagents from `.md` files by specifying a path
112/// (e.g., `./custom-agent.md` or `subagents/researcher.md`).
113#[derive(Debug, Clone, JsonSchema, Deserialize)]
114pub struct SubagentArgs {
115    /// Subagent type name (e.g., "explore", "plan") or path to a subagent file.
116    /// If the value contains '/' or ends with '.md', it's treated as a file path.
117    pub subagent: String,
118    /// The detailed task prompt for the subagent.
119    pub prompt: String,
120}
121
122#[derive(Debug, Clone, Serialize)]
123struct SubagentResult {
124    subagent: String,
125    status: &'static str,
126    result: String,
127}
128
129/// A tool that spawns specialized subagents to handle complex tasks.
130///
131/// Allows the main agent to delegate work to specialized subagents
132/// that have different capabilities and run in isolated context windows.
133///
134/// # Example
135///
136/// ```rust,ignore
137/// use aither_agent::specialized::task::{SubagentTool, SubagentType};
138///
139/// // Create subagent tool
140/// let mut subagent_tool = SubagentTool::new(llm.clone());
141///
142/// // Register an "explore" subagent type
143/// subagent_tool.register("explore", SubagentType::new(
144///     "Codebase explorer for finding files and searching code",
145///     |llm| Agent::builder(llm)
146///         .system_prompt("You are a codebase explorer...")
147///         .tool(FsTool::new())
148///         .max_iterations(15)
149///         .build()
150/// ));
151///
152/// let agent = Agent::builder(llm)
153///     .tool(subagent_tool)
154///     .build();
155/// ```
156pub struct SubagentTool<LLM> {
157    llm: LLM,
158    types: HashMap<String, SubagentType<LLM>>,
159    /// Base directory for resolving relative paths (e.g., sandbox directory).
160    base_dir: Option<PathBuf>,
161    /// Ordered mount map used to resolve virtual sandbox paths into host paths.
162    mounts: Vec<SubagentFileMount>,
163    /// Factory for creating child terminal tools for subagents.
164    terminal_tool_factory: Option<TerminalToolFactory>,
165}
166
167impl<LLM> std::fmt::Debug for SubagentTool<LLM> {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        let type_names: Vec<_> = self.types.keys().cloned().collect();
170        f.debug_struct("SubagentTool")
171            .field("type_names", &type_names)
172            .field("base_dir", &self.base_dir)
173            .finish_non_exhaustive()
174    }
175}
176
177impl<LLM: Clone + Sync> SubagentTool<LLM> {
178    /// Creates a new `TaskTool` with the given LLM.
179    pub fn new(llm: LLM) -> Self {
180        Self {
181            llm,
182            types: HashMap::new(),
183            base_dir: None,
184            mounts: Vec::new(),
185            terminal_tool_factory: None,
186        }
187    }
188
189    /// Sets the base directory for resolving relative paths.
190    ///
191    /// Paths like `subagents/...` and `skills/...` will be resolved
192    /// relative to this directory.
193    #[must_use]
194    pub fn with_base_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
195        self.base_dir = Some(dir.into());
196        self
197    }
198
199    /// Sets explicit mount mappings for resolving subagent file paths.
200    ///
201    /// Mappings are checked in order and matched by virtual path prefix.
202    #[must_use]
203    pub fn with_file_mounts<I>(mut self, mounts: I) -> Self
204    where
205        I: IntoIterator<Item = SubagentFileMount>,
206    {
207        self.mounts = mounts.into_iter().collect();
208        self
209    }
210
211    /// Sets the terminal tool factory used for subagents.
212    #[must_use]
213    pub fn with_terminal_tool_factory(mut self, factory: TerminalToolFactory) -> Self {
214        self.terminal_tool_factory = Some(factory);
215        self
216    }
217
218    /// Register a subagent type.
219    pub fn register(&mut self, name: impl Into<String>, subagent: SubagentType<LLM>) {
220        let name = name.into();
221        self.types.insert(name, subagent);
222    }
223
224    /// Register a subagent type (builder pattern).
225    #[must_use]
226    pub fn with_type(mut self, name: impl Into<String>, subagent: SubagentType<LLM>) -> Self {
227        self.register(name, subagent);
228        self
229    }
230
231    /// Returns a list of registered subagent types with their descriptions.
232    ///
233    /// Useful for injecting into system prompts so the main agent knows
234    /// what subagents are available.
235    pub fn type_descriptions(&self) -> Vec<(&str, &str)> {
236        self.types
237            .iter()
238            .map(|(name, t)| (name.as_str(), t.description.as_str()))
239            .collect()
240    }
241
242    fn effective_mounts(&self) -> Vec<SubagentFileMount> {
243        if !self.mounts.is_empty() {
244            return self.mounts.clone();
245        }
246
247        let base = self
248            .base_dir
249            .clone()
250            .unwrap_or_else(|| PathBuf::from(Path::new(".")));
251        vec![
252            SubagentFileMount::new(PathBuf::from("."), base.clone()),
253            SubagentFileMount::new(PathBuf::from("subagents"), base.join("subagents")),
254            SubagentFileMount::new(PathBuf::from("skills"), base.join("skills")),
255        ]
256    }
257
258    fn strip_leading_curdir(path: &Path) -> PathBuf {
259        let mut stripped = PathBuf::new();
260        for component in path.components() {
261            if matches!(component, Component::CurDir) {
262                continue;
263            }
264            stripped.push(component.as_os_str());
265        }
266        stripped
267    }
268
269    fn to_mount_relative(path: &Path, virtual_prefix: &Path) -> Option<PathBuf> {
270        let normalized_path = Self::strip_leading_curdir(path);
271        if normalized_path.as_os_str().is_empty() {
272            return None;
273        }
274        if normalized_path.components().any(|component| {
275            matches!(
276                component,
277                Component::ParentDir | Component::RootDir | Component::Prefix(_)
278            )
279        }) {
280            return None;
281        }
282
283        let normalized_prefix = Self::strip_leading_curdir(virtual_prefix);
284        if normalized_prefix.components().any(|component| {
285            matches!(
286                component,
287                Component::ParentDir | Component::RootDir | Component::Prefix(_)
288            )
289        }) {
290            return None;
291        }
292        if normalized_prefix.as_os_str().is_empty() {
293            return Some(normalized_path);
294        }
295
296        if normalized_path.starts_with(&normalized_prefix) {
297            let Ok(stripped) = normalized_path.strip_prefix(&normalized_prefix) else {
298                return None;
299            };
300            let relative = Self::strip_leading_curdir(stripped);
301            if relative.as_os_str().is_empty() {
302                None
303            } else {
304                Some(relative)
305            }
306        } else {
307            None
308        }
309    }
310
311    fn mount_specificity(prefix: &Path) -> usize {
312        Self::strip_leading_curdir(prefix).components().count()
313    }
314
315    fn matching_mounts<'a>(
316        mounts: &'a [SubagentFileMount],
317        file_path: &Path,
318    ) -> Vec<(usize, &'a SubagentFileMount, PathBuf)> {
319        let mut matched = mounts
320            .iter()
321            .enumerate()
322            .filter_map(|(index, mount)| {
323                Self::to_mount_relative(file_path, &mount.virtual_prefix)
324                    .map(|relative| (index, mount, relative))
325            })
326            .collect::<Vec<_>>();
327        matched.sort_by(|(index_a, mount_a, _), (index_b, mount_b, _)| {
328            Self::mount_specificity(&mount_b.virtual_prefix)
329                .cmp(&Self::mount_specificity(&mount_a.virtual_prefix))
330                .then(index_a.cmp(index_b))
331        });
332        matched
333    }
334
335    async fn resolve_relative_path_through_mounts(
336        requested_display: &Path,
337        file_path: &Path,
338        mounts: &[SubagentFileMount],
339    ) -> anyhow::Result<PathBuf> {
340        let mut attempted = Vec::new();
341        let matched = Self::matching_mounts(mounts, file_path);
342
343        for (_, mount, relative) in matched {
344            let candidate = mount.host_root.join(relative);
345            let display_prefix = Self::strip_leading_curdir(&mount.virtual_prefix);
346            let display_path = if display_prefix.as_os_str().is_empty() {
347                candidate
348                    .strip_prefix(&mount.host_root)
349                    .map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf)
350            } else {
351                display_prefix.join(
352                    candidate
353                        .strip_prefix(&mount.host_root)
354                        .map_or_else(|_| requested_display.to_path_buf(), Path::to_path_buf),
355                )
356            };
357            attempted.push(display_path.display().to_string());
358            if checked_path_exists(&candidate).await? {
359                return Ok(candidate);
360            }
361        }
362
363        if attempted.is_empty() {
364            return Err(anyhow::anyhow!(
365                "Subagent file '{}' is outside mounted paths or uses forbidden path components",
366                requested_display.display()
367            ));
368        }
369
370        Err(anyhow::anyhow!(
371            "Subagent file '{}' not found. Attempted: {}",
372            requested_display.display(),
373            attempted.join(", ")
374        ))
375    }
376
377    /// Resolves a path the subagent asked for against its mounts.
378    ///
379    /// Takes the mounts and base directory rather than `&self` so the returned
380    /// future does not borrow the tool, and so stays `Send`.
381    async fn resolve_subagent_path(
382        mounts: &[SubagentFileMount],
383        base_dir: Option<&Path>,
384        file_path: &Path,
385    ) -> anyhow::Result<PathBuf> {
386        if file_path.is_absolute() {
387            if let Some(base_dir) = base_dir
388                && let Ok(stripped) = file_path.strip_prefix(base_dir)
389            {
390                let relative = Self::strip_leading_curdir(stripped);
391                if !relative.as_os_str().is_empty() {
392                    return Self::resolve_relative_path_through_mounts(
393                        &relative, &relative, mounts,
394                    )
395                    .await;
396                }
397            }
398
399            if checked_path_exists(file_path).await? {
400                return Ok(file_path.to_path_buf());
401            }
402            return Err(anyhow::anyhow!(
403                "Subagent file '{}' not found",
404                file_path.display()
405            ));
406        }
407
408        Self::resolve_relative_path_through_mounts(file_path, file_path, mounts).await
409    }
410}
411
412impl<LLM: LanguageModel + Clone + Sync> SubagentTool<LLM> {
413    /// Register a subagent from a definition (builder pattern).
414    ///
415    /// Creates a subagent type from a `SubagentDefinition` loaded from a file.
416    /// The subagent will use the definition's system prompt and max iterations.
417    #[must_use]
418    pub fn with_definition(self, def: SubagentDefinition) -> Self {
419        let subagent = SubagentType::new(def.description.clone(), move |llm| {
420            crate::AgentBuilder::new(llm)
421                .agent_kind(crate::AgentKind::Chatbot)
422                .system_prompt(&def.system_prompt)
423                .max_iterations(def.max_iterations)
424        });
425        self.with_type(def.id, subagent)
426    }
427
428    /// Register all builtin subagents.
429    ///
430    /// Loads subagents from embedded definition files (explore, plan, etc.).
431    #[must_use]
432    pub fn with_builtins(mut self) -> Self {
433        for def in crate::builtin_subagents() {
434            self = self.with_definition(def);
435        }
436        self
437    }
438}
439
440impl<LLM> Tool for SubagentTool<LLM>
441where
442    LLM: LanguageModel + Clone + Sync + 'static,
443{
444    fn name(&self) -> Cow<'static, str> {
445        Cow::Borrowed("subagent")
446    }
447
448    type Arguments = SubagentArgs;
449    type Res = ToolResult;
450
451    async fn call(&self, args: Self::Arguments) -> aither_core::Result<Self::Res> {
452        // Determine if subagent is a file path or a registered type name
453        // File paths contain '/' or end with '.md'
454        let is_file_path = args.subagent.contains('/')
455            || Path::new(&args.subagent)
456                .extension()
457                .is_some_and(|extension| extension.eq_ignore_ascii_case("md"));
458
459        let (subagent_id, agent_builder) = if is_file_path {
460            // Load subagent from file
461            // Resolve paths using explicit search roots.
462            let file_path = PathBuf::from(&args.subagent);
463            let resolved_path = Self::resolve_subagent_path(
464                &self.effective_mounts(),
465                self.base_dir.as_deref(),
466                &file_path,
467            )
468            .await?;
469
470            let def = SubagentDefinition::from_file_async(&resolved_path)
471                .await
472                .map_err(|e| {
473                    anyhow::anyhow!(
474                        "Failed to read subagent file '{}': {e}",
475                        resolved_path.display()
476                    )
477                })?;
478
479            let builder = crate::AgentBuilder::new(self.llm.clone())
480                .agent_kind(crate::AgentKind::Chatbot)
481                .system_prompt(&def.system_prompt)
482                .max_iterations(def.max_iterations);
483
484            (def.id, builder)
485        } else {
486            // Use registered subagent type
487            let type_name = &args.subagent;
488            let subagent_type = self.types.get(type_name).ok_or_else(|| {
489                let available: Vec<&str> =
490                    self.types.keys().map(std::string::String::as_str).collect();
491                anyhow::anyhow!(
492                    "Unknown subagent type '{}'. Available: {}",
493                    type_name,
494                    available.join(", ")
495                )
496            })?;
497            (type_name.clone(), subagent_type.builder(self.llm.clone()))
498        };
499
500        tracing::info!(subagent = %subagent_id, "Starting subagent");
501
502        // Add child terminal tool if factory is configured
503        let (agent_builder, child_job_registry) = if let Some(factory) = &self.terminal_tool_factory
504        {
505            let dyn_terminal = factory
506                .create()
507                .await
508                .map_err(|e| anyhow::anyhow!("failed to create subagent terminal tool: {e}"))?;
509            let job_registry = dyn_terminal.job_registry();
510            (agent_builder.dyn_terminal(dyn_terminal), Some(job_registry))
511        } else {
512            (agent_builder, None)
513        };
514
515        let mut agent = agent_builder.build();
516
517        // Run the subagent with the prompt
518        let query_result = agent.query(&args.prompt).await;
519        if let Some(job_registry) = child_job_registry {
520            let killed = job_registry.kill_running().await;
521            if killed > 0 {
522                tracing::info!(
523                    subagent = %subagent_id,
524                    killed,
525                    "Stopped background terminal jobs left by completed subagent"
526                );
527            }
528        }
529        let result = match query_result {
530            Ok(result) => result,
531            Err(error) => {
532                let history = agent.history();
533                let recent = history
534                    .into_iter()
535                    .rev()
536                    .take(12)
537                    .collect::<Vec<_>>()
538                    .into_iter()
539                    .rev()
540                    .collect::<Vec<_>>();
541                let recent_json = serde_json::to_string(&recent)
542                    .unwrap_or_else(|serialize_error| serialize_error.to_string());
543                return Err(anyhow::anyhow!(
544                    "Subagent '{subagent_id}' error: {error}\nRecent subagent history: {recent_json}"
545                ));
546            }
547        };
548
549        tracing::info!(subagent = %subagent_id, "Subagent completed");
550
551        ToolResult::json(&SubagentResult {
552            subagent: subagent_id,
553            status: "completed",
554            result,
555        })
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use std::path::PathBuf;
562
563    use super::*;
564
565    #[test]
566    fn subagent_args_schema() {
567        let schema = schemars::schema_for!(SubagentArgs);
568        let value = schema.to_value();
569        let props = value.get("properties").expect("should have properties");
570        assert!(props.get("subagent").is_some());
571        assert!(props.get("prompt").is_some());
572
573        // Check required order
574        let required = value.get("required").expect("should have required");
575        assert!(required.is_array());
576    }
577
578    #[test]
579    fn subagent_result_serializes_as_structured_json() {
580        let value = serde_json::to_value(SubagentResult {
581            subagent: "research".to_string(),
582            status: "completed",
583            result: "done".to_string(),
584        })
585        .expect("subagent result should serialize");
586        assert_eq!(
587            value,
588            serde_json::json!({
589                "subagent": "research",
590                "status": "completed",
591                "result": "done",
592            })
593        );
594    }
595
596    fn unique_temp_dir(tag: &str) -> PathBuf {
597        let nanos = std::time::SystemTime::now()
598            .duration_since(std::time::UNIX_EPOCH)
599            .expect("system clock before unix epoch")
600            .as_nanos();
601        let dir = std::env::temp_dir().join(format!(
602            "aither-subagent-{tag}-{}-{nanos}",
603            std::process::id()
604        ));
605        std::fs::create_dir_all(&dir).expect("create test temp dir");
606        dir
607    }
608
609    #[tokio::test]
610    async fn resolves_file_through_mount_prefix() {
611        let root = unique_temp_dir("mount-resolve");
612        let skills_root = root.join("skills");
613        let skill_file = skills_root.join("slide").join("SKILL.md");
614        std::fs::create_dir_all(skill_file.parent().expect("skill parent"))
615            .expect("create skill parent");
616        std::fs::write(&skill_file, "# slide").expect("write skill file");
617
618        let tool = SubagentTool::new(()).with_file_mounts([
619            SubagentFileMount::new(".", root.join("workspace")),
620            SubagentFileMount::new(".skills", skills_root.clone()),
621        ]);
622        let resolved = SubagentTool::<()>::resolve_subagent_path(
623            &tool.effective_mounts(),
624            tool.base_dir.as_deref(),
625            Path::new(".skills/slide/SKILL.md"),
626        )
627        .await
628        .expect("resolve mounted skill path");
629        assert_eq!(resolved, skill_file);
630
631        let _ = std::fs::remove_dir_all(root);
632    }
633
634    #[tokio::test]
635    async fn rejects_parent_traversal_paths() {
636        let root = unique_temp_dir("mount-traversal");
637        let tool = SubagentTool::new(())
638            .with_file_mounts([SubagentFileMount::new("skills", root.join("skills"))]);
639
640        let error = SubagentTool::<()>::resolve_subagent_path(
641            &tool.effective_mounts(),
642            tool.base_dir.as_deref(),
643            Path::new("../outside.md"),
644        )
645        .await
646        .expect_err("parent traversal should fail");
647        assert!(
648            error
649                .to_string()
650                .contains("outside mounted paths or uses forbidden path components"),
651            "unexpected error: {error}"
652        );
653
654        let _ = std::fs::remove_dir_all(root);
655    }
656
657    #[tokio::test]
658    async fn missing_file_error_does_not_leak_host_mount_path() {
659        let root = unique_temp_dir("mount-errors");
660        let skills_root = root.join("skills");
661        std::fs::create_dir_all(&skills_root).expect("create skills root");
662        let tool = SubagentTool::new(())
663            .with_file_mounts([SubagentFileMount::new("skills", skills_root.clone())]);
664
665        let error = SubagentTool::<()>::resolve_subagent_path(
666            &tool.effective_mounts(),
667            tool.base_dir.as_deref(),
668            Path::new(".skills/missing.md"),
669        )
670        .await
671        .expect_err("missing file should fail");
672        let message = error.to_string();
673        assert!(
674            message.contains("skills/missing.md"),
675            "missing virtual path in error: {message}"
676        );
677        assert!(
678            !message.contains(skills_root.to_string_lossy().as_ref()),
679            "host path leaked in error: {message}"
680        );
681
682        let _ = std::fs::remove_dir_all(root);
683    }
684
685    #[tokio::test]
686    async fn absolute_workspace_skills_path_resolves_to_skills_mount() {
687        let root = unique_temp_dir("absolute-workspace-skills");
688        let workspace_root = root.join("workspace");
689        let skills_root = root.join("skills");
690        let session_skills_file = workspace_root.join("skills/slide/subagents/art_direction.md");
691        let mounted_skill_file = skills_root.join("slide/subagents/art_direction.md");
692        std::fs::create_dir_all(session_skills_file.parent().expect("session skill parent"))
693            .expect("create session skill parent");
694        std::fs::create_dir_all(mounted_skill_file.parent().expect("mounted skill parent"))
695            .expect("create mounted skill parent");
696        std::fs::write(&mounted_skill_file, "# art direction").expect("write mounted skill file");
697
698        let tool = SubagentTool::new(())
699            .with_base_dir(workspace_root.clone())
700            .with_file_mounts([
701                SubagentFileMount::new(".", workspace_root.clone()),
702                SubagentFileMount::new("skills", skills_root.clone()),
703            ]);
704
705        let resolved = SubagentTool::<()>::resolve_subagent_path(
706            &tool.effective_mounts(),
707            tool.base_dir.as_deref(),
708            &session_skills_file,
709        )
710        .await
711        .expect("resolve absolute workspace .skills path");
712        assert_eq!(resolved, mounted_skill_file);
713
714        let _ = std::fs::remove_dir_all(root);
715    }
716}