use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use aither_core::llm::{AgentIdentity, CallIdentity, SubagentIdentity, ToolContext};
use aither_core::{
LanguageModel,
llm::{Tool, ToolResult, oneshot},
};
use aither_sandbox::{
CommandRole, CommandUsage, CommitLedger, CommitLedgerError, CommitMark, DynTerminalTool,
SubagentCommit, SubagentGrant, TerminalBinding,
};
use askama::Template;
use schemars::JsonSchema;
use serde::Deserialize;
use super::external::{AnyExternalSession, AnyExternalSubagent, ExternalStart, ExternalSubagent};
use crate::AgentBuilder;
use crate::context::CacheLifetime;
use crate::external_hook::{self, ExternalHooks};
use crate::fork::{ForkSnapshot, ForkSource};
use crate::fs_util::path_exists;
use crate::model_group::ModelTier;
use crate::subagent_file::{Listed, SubagentAccess, SubagentDefinition, SubagentLookup};
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 SubagentHooks = crate::HCons<ExternalHooks, ()>;
pub type SubagentSetup<LLM> =
Arc<dyn Fn(AgentBuilder<LLM, LLM, LLM, ()>) -> AgentBuilder<LLM, LLM, LLM, ()> + Send + Sync>;
pub const FORK_DESCRIPTION: &str = "Continues your own context on your model; use it for work that depends on what you have read and decided";
#[derive(Clone)]
struct External {
description: String,
backend: Arc<AnyExternalSubagent>,
}
#[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(),
}
}
}
#[derive(Debug, Clone, JsonSchema, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SubagentArgs {
pub name: String,
pub prompt_file: String,
#[serde(default)]
pub id: Option<u64>,
#[serde(default)]
pub agent: Option<String>,
#[serde(default)]
pub worktrees: Vec<String>,
#[serde(default)]
pub commit_worktrees: Vec<String>,
}
enum Call<'a> {
Named { name: &'a str, grant: Requested<'a> },
Fork { grant: Requested<'a> },
External {
agent: &'a str,
grant: Requested<'a>,
},
Resume { id: u64 },
}
#[derive(Clone, Copy)]
struct Requested<'a> {
worktrees: &'a [String],
commit_worktrees: &'a [String],
}
impl Requested<'_> {
const fn is_empty(&self) -> bool {
self.worktrees.is_empty() && self.commit_worktrees.is_empty()
}
fn paths(&self, working_dir: Option<&Path>) -> (Vec<PathBuf>, Vec<PathBuf>) {
let resolve = |path: &String| {
let path = Path::new(path);
match working_dir {
Some(base) if path.is_relative() => base.join(path),
_ => path.to_path_buf(),
}
};
(
self.worktrees.iter().map(resolve).collect(),
self.commit_worktrees.iter().map(resolve).collect(),
)
}
fn grant(&self, working_dir: Option<&Path>) -> SubagentGrant {
let (worktrees, commit_worktrees) = self.paths(working_dir);
let grant = worktrees
.into_iter()
.fold(SubagentGrant::new(), SubagentGrant::with_worktree);
commit_worktrees
.into_iter()
.fold(grant, SubagentGrant::with_committing_worktree)
}
}
impl SubagentArgs {
#[must_use]
pub fn subagent(&self) -> Option<&str> {
match self.name.as_str() {
"resume" => None,
"external" => self.agent.as_deref(),
name => Some(name),
}
}
#[must_use]
pub fn prompt_file(&self) -> &str {
&self.prompt_file
}
fn call(&self) -> anyhow::Result<Call<'_>> {
let grant = Requested {
worktrees: &self.worktrees,
commit_worktrees: &self.commit_worktrees,
};
let name = self.name.as_str();
if name != "resume" && self.id.is_some() {
anyhow::bail!("`--id` continues a finished subagent: use it with `subagent resume`");
}
if name != "external" && self.agent.is_some() {
anyhow::bail!("`--agent` names a connected agent: use it with `subagent external`");
}
Ok(match name {
"resume" => {
let Some(id) = self.id else {
anyhow::bail!(
"`subagent resume` takes the `--id` of the finished subagent to continue"
);
};
if !grant.is_empty() {
anyhow::bail!(
"a continued subagent keeps what it was granted: `subagent resume` takes no `--worktrees` or `--commit-worktrees`"
);
}
Call::Resume { id }
}
"fork" => Call::Fork { grant },
"external" => {
let Some(agent) = self.agent.as_deref() else {
anyhow::bail!("`subagent external` takes the `--agent` to run");
};
Call::External { agent, grant }
}
name => Call::Named { name, grant },
})
}
}
#[derive(Template)]
#[template(path = "subagent_result.txt", escape = "none")]
struct SubagentResultTemplate<'a> {
subagent: &'a str,
outcome: SubagentReport<'a>,
commits: Option<&'a CommitListing>,
}
struct CommitListing {
listed: Result<Vec<SubagentCommit>, CommitLedgerError>,
setbacks: Vec<String>,
}
async fn list_commits(
ledger: Option<&CommitLedger>,
mark: Option<&CommitMark>,
) -> Option<CommitListing> {
match (ledger, mark) {
(Some(ledger), Some(mark)) => Some(CommitListing {
listed: ledger.since(mark).await,
setbacks: mark.setbacks().iter().map(ToString::to_string).collect(),
}),
_ => None,
}
}
enum SubagentReport<'a> {
Cancelled,
Completed {
tier: Option<&'static str>,
model: Option<&'a str>,
result: &'a str,
id: u64,
cache_bound: bool,
alert: Option<&'a str>,
},
}
struct HistoryEntry {
role: aither_core::llm::Role,
content: String,
tool_names: Vec<String>,
}
#[derive(Template)]
#[template(path = "subagent_error.txt", escape = "none")]
struct SubagentErrorTemplate<'a> {
subagent: &'a str,
error: &'a str,
commits: Option<&'a CommitListing>,
history: &'a [HistoryEntry],
}
#[derive(Template)]
#[template(path = "fork_refused.txt", escape = "none")]
struct ForkRefusedTemplate<'a> {
reason: &'a ForkRefusal,
}
enum ForkRefusal {
NoTerminal,
NothingSent,
OtherModel {
main: String,
fork: String,
},
NearCompaction {
usage: f32,
compaction: f32,
},
}
impl ForkRefusal {
fn into_error(self) -> anyhow::Error {
anyhow::anyhow!(
ForkRefusedTemplate { reason: &self }
.render()
.expect("fork refusal template must render")
)
}
}
#[derive(Debug, JsonSchema, Deserialize)]
struct SubagentRouting {
model: ModelTier,
}
struct RouterModel<'a> {
tier: &'static str,
name: &'a str,
description: &'a str,
}
#[derive(Template)]
#[template(path = "subagent_router.txt", escape = "none")]
struct SubagentRouter<'a> {
models: [RouterModel<'a>; 3],
}
const fn tier_label(tier: ModelTier) -> &'static str {
match tier {
ModelTier::Advanced => "advanced",
ModelTier::Balanced => "balanced",
ModelTier::Fast => "fast",
}
}
enum Source<'a, LLM> {
Definition {
definition: SubagentDefinition,
setup: Option<&'a SubagentSetup<LLM>>,
},
Fork,
}
struct Resolved<'a, LLM> {
name: String,
tier: Option<ModelTier>,
source: Source<'a, LLM>,
}
#[derive(Debug, Clone)]
pub struct SubagentRunInfo {
pub id: u64,
pub subagent: String,
pub prompt: String,
pub started: Instant,
}
type RunSlot = (SubagentRunInfo, async_channel::Sender<()>);
#[derive(Clone, Debug, Default)]
pub struct SubagentRuns {
runs: Arc<Mutex<HashMap<u64, RunSlot>>>,
next_id: Arc<AtomicU64>,
}
impl SubagentRuns {
#[must_use]
pub fn list(&self) -> Vec<SubagentRunInfo> {
let mut infos: Vec<_> = self
.runs
.lock()
.expect("subagent runs lock poisoned")
.values()
.map(|(info, _)| info.clone())
.collect();
infos.sort_by_key(|info| info.id);
infos
}
#[must_use]
pub fn cancel(&self, id: u64) -> bool {
self.runs
.lock()
.expect("subagent runs lock poisoned")
.get(&id)
.is_some_and(|(_, cancel)| cancel.try_send(()).is_ok() || cancel.is_full())
}
#[must_use]
pub fn cancel_all(&self) -> usize {
self.runs
.lock()
.expect("subagent runs lock poisoned")
.values()
.filter(|(_, cancel)| cancel.try_send(()).is_ok() || cancel.is_full())
.count()
}
fn begin(&self, subagent: &str, prompt: &str) -> (u64, async_channel::Receiver<()>) {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let (cancel_tx, cancel_rx) = async_channel::bounded(1);
let info = SubagentRunInfo {
id,
subagent: subagent.to_string(),
prompt: prompt.to_string(),
started: Instant::now(),
};
self.runs
.lock()
.expect("subagent runs lock poisoned")
.insert(id, (info, cancel_tx));
(id, cancel_rx)
}
fn finish(&self, id: u64) {
self.runs
.lock()
.expect("subagent runs lock poisoned")
.remove(&id);
}
}
enum SubagentOutcome<E> {
Finished(Result<String, E>),
Cancelled,
}
async fn await_subagent_run<F, E>(
query: F,
cancel_rx: async_channel::Receiver<()>,
) -> SubagentOutcome<E>
where
F: std::future::Future<Output = Result<String, E>>,
{
futures_lite::future::or(async { SubagentOutcome::Finished(query.await) }, async {
let _ = cancel_rx.recv().await;
SubagentOutcome::Cancelled
})
.await
}
struct FinishedSubagent<LLM> {
subagent: String,
tier: Option<ModelTier>,
model: Option<String>,
commit_ledger: Option<CommitLedger>,
body: SubagentBody<LLM>,
}
enum SubagentBody<LLM> {
Agent {
agent: Box<crate::Agent<LLM, LLM, LLM, SubagentHooks>>,
child_job_registry: Option<aither_sandbox::JobRegistry>,
lifetime: CacheLifetime,
},
External {
session: AnyExternalSession,
_terminal: Option<Box<DynTerminalTool>>,
},
}
impl<LLM: LanguageModel + 'static> FinishedSubagent<LLM> {
fn expired(&self) -> Option<CacheLifetime> {
let SubagentBody::Agent {
agent, lifetime, ..
} = &self.body
else {
return None;
};
(!agent.cache_warmth().is_warm()).then_some(*lifetime)
}
}
enum FinishedSlot<LLM> {
Idle(Box<FinishedSubagent<LLM>>),
Running,
Expired(CacheLifetime),
}
struct FinishedInner<LLM> {
next_id: u64,
slots: HashMap<u64, FinishedSlot<LLM>>,
}
struct FinishedSubagents<LLM> {
inner: Mutex<FinishedInner<LLM>>,
}
impl<LLM> FinishedSubagents<LLM> {
fn new() -> Self {
Self {
inner: Mutex::new(FinishedInner {
next_id: 1,
slots: HashMap::new(),
}),
}
}
}
impl<LLM: LanguageModel + 'static> FinishedSubagents<LLM> {
fn expire(inner: &mut FinishedInner<LLM>) {
for slot in inner.slots.values_mut() {
if let FinishedSlot::Idle(finished) = slot
&& let Some(lifetime) = finished.expired()
{
*slot = FinishedSlot::Expired(lifetime);
}
}
}
fn checkout(&self, id: u64) -> anyhow::Result<Box<FinishedSubagent<LLM>>> {
let mut inner = self.inner.lock().expect("finished subagents lock poisoned");
Self::expire(&mut inner);
match inner.slots.get_mut(&id) {
None => anyhow::bail!("unknown subagent id {id}"),
Some(FinishedSlot::Expired(lifetime)) => {
let CacheLifetime::Limited(lifetime) = lifetime else {
unreachable!("a permanent cache lifetime never expires");
};
anyhow::bail!(
"subagent {id} expired: its prompt-cache entry lived {lifetime:?} and its context was released"
);
}
Some(FinishedSlot::Running) => {
anyhow::bail!("subagent {id} is still running a continuation")
}
Some(slot @ FinishedSlot::Idle(_)) => {
let FinishedSlot::Idle(finished) = std::mem::replace(slot, FinishedSlot::Running)
else {
unreachable!("slot matched as idle");
};
Ok(finished)
}
}
}
fn store(&self, id: Option<u64>, finished: FinishedSubagent<LLM>) -> u64 {
let mut inner = self.inner.lock().expect("finished subagents lock poisoned");
Self::expire(&mut inner);
let id = id.unwrap_or_else(|| {
let id = inner.next_id;
inner.next_id += 1;
id
});
inner
.slots
.insert(id, FinishedSlot::Idle(Box::new(finished)));
id
}
fn release(&self, id: u64) {
self.inner
.lock()
.expect("finished subagents lock poisoned")
.slots
.remove(&id);
}
}
pub struct SubagentTool<LLM> {
advanced: LLM,
balanced: LLM,
fast: LLM,
global_dir: PathBuf,
setups: HashMap<String, SubagentSetup<LLM>>,
externals: BTreeMap<String, External>,
base_dir: Option<PathBuf>,
mounts: Vec<SubagentFileMount>,
binding: Option<TerminalBinding>,
runs: SubagentRuns,
cache_keep_alive: Option<crate::config::CacheKeepAlive>,
finished: FinishedSubagents<LLM>,
fork_source: ForkSource,
hooks: Option<ExternalHooks>,
#[cfg(feature = "languages")]
languages: Option<crate::LanguageGuard>,
}
impl<LLM> std::fmt::Debug for SubagentTool<LLM> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let setups: Vec<_> = self.setups.keys().collect();
let externals: Vec<_> = self.externals.keys().collect();
f.debug_struct("SubagentTool")
.field("global_dir", &self.global_dir)
.field("setups", &setups)
.field("externals", &externals)
.field("base_dir", &self.base_dir)
.finish_non_exhaustive()
}
}
impl<LLM: Clone + Sync> SubagentTool<LLM> {
pub fn new(llm: LLM, global_dir: impl Into<PathBuf>) -> Self {
Self {
advanced: llm.clone(),
balanced: llm.clone(),
fast: llm,
global_dir: global_dir.into(),
setups: HashMap::new(),
externals: BTreeMap::new(),
base_dir: None,
mounts: Vec::new(),
binding: None,
runs: SubagentRuns::default(),
cache_keep_alive: None,
finished: FinishedSubagents::new(),
fork_source: ForkSource::default(),
hooks: None,
#[cfg(feature = "languages")]
languages: 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_balanced_model(mut self, model: LLM) -> Self {
self.balanced = model;
self
}
#[must_use]
pub fn with_fast_model(mut self, model: LLM) -> Self {
self.fast = model;
self
}
#[must_use]
pub fn for_terminal(&self, binding: &TerminalBinding) -> Self {
assert_eq!(
binding.role(),
CommandRole::Main,
"a subagent's terminal has no `subagent` command: register it with `main_exclusive`"
);
Self {
advanced: self.advanced.clone(),
balanced: self.balanced.clone(),
fast: self.fast.clone(),
global_dir: self.global_dir.clone(),
setups: self.setups.clone(),
externals: self.externals.clone(),
base_dir: self.base_dir.clone(),
mounts: self.mounts.clone(),
binding: Some(binding.clone()),
runs: self.runs.clone(),
cache_keep_alive: self.cache_keep_alive.clone(),
finished: FinishedSubagents::new(),
fork_source: self.fork_source.clone(),
hooks: ExternalHooks::of_observer(binding.observer()).or_else(|| self.hooks.clone()),
#[cfg(feature = "languages")]
languages: self.languages.clone(),
}
}
#[cfg(feature = "languages")]
#[must_use]
pub fn with_languages(mut self, guard: crate::LanguageGuard) -> Self {
self.languages = Some(guard);
self
}
#[must_use]
pub fn with_hooks(mut self, hooks: ExternalHooks) -> Self {
self.hooks = Some(hooks);
self
}
#[must_use]
pub fn fork_source(&self) -> ForkSource {
self.fork_source.clone()
}
#[must_use]
pub fn with_runs(mut self, runs: SubagentRuns) -> Self {
self.runs = runs;
self
}
#[must_use]
pub const fn with_cache_keep_alive(
mut self,
keep_alive: crate::config::CacheKeepAlive,
) -> Self {
self.cache_keep_alive = Some(keep_alive);
self
}
#[must_use]
pub fn with_frequent_idle_threshold(mut self, threshold: usize) -> Self {
self.cache_keep_alive
.get_or_insert_with(crate::config::CacheKeepAlive::default)
.frequent_idle_threshold = threshold;
self
}
#[must_use]
pub fn runs(&self) -> SubagentRuns {
self.runs.clone()
}
#[must_use]
pub fn with_agent_setup<F>(mut self, name: impl Into<String>, setup: F) -> Self
where
F: Fn(AgentBuilder<LLM, LLM, LLM, ()>) -> AgentBuilder<LLM, LLM, LLM, ()>
+ Send
+ Sync
+ 'static,
{
self.setups.insert(name.into(), Arc::new(setup));
self
}
#[must_use]
pub fn with_external(
mut self,
name: impl Into<String>,
description: impl Into<String>,
backend: impl ExternalSubagent,
) -> Self {
self.externals.insert(
name.into(),
External {
description: description.into(),
backend: Arc::new(AnyExternalSubagent::new(backend)),
},
);
self
}
fn caller_dir<'a>(&'a self, requested: Option<&'a Path>) -> Option<&'a Path> {
requested
.or_else(|| self.binding.as_ref().map(TerminalBinding::working_dir))
.or(self.base_dir.as_deref())
}
fn lookup<'a>(&'a self, requested: Option<&'a Path>) -> anyhow::Result<SubagentLookup<'a>> {
let working_dir = self.caller_dir(requested).ok_or_else(|| {
anyhow::anyhow!(
"the subagent tool is bound to no terminal and has no base directory, so it has no `{}/` to look subagents up in",
crate::LOCAL_SUBAGENTS_DIR
)
})?;
Ok(SubagentLookup {
global: &self.global_dir,
working_dir,
})
}
async fn usage_text(&self) -> String {
let lookup = match self.lookup(None) {
Ok(lookup) => lookup,
Err(error) => return error.to_string(),
};
let subagents = lookup.resolvable().await;
SubagentUsageTemplate {
subagents: &subagents,
fork: FORK_DESCRIPTION,
externals: self
.externals
.iter()
.map(|(name, external)| (name.as_str(), external.description.as_str()))
.collect(),
}
.render()
.expect("subagent usage template must render")
}
fn effective_mounts(&self, requested: Option<&Path>) -> Vec<SubagentFileMount> {
let caller = requested
.or_else(|| self.binding.as_ref().map(TerminalBinding::working_dir))
.filter(|working_dir| self.base_dir.as_deref() != Some(*working_dir))
.map(|working_dir| SubagentFileMount::new(PathBuf::from("."), working_dir));
if !self.mounts.is_empty() {
return caller.into_iter().chain(self.mounts.clone()).collect();
}
let base = self
.base_dir
.clone()
.unwrap_or_else(|| PathBuf::from(Path::new(".")));
caller
.into_iter()
.chain([SubagentFileMount::new(PathBuf::from("."), base)])
.collect()
}
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
}
const fn model_for(&self, tier: ModelTier) -> &LLM {
match tier {
ModelTier::Advanced => &self.advanced,
ModelTier::Balanced => &self.balanced,
ModelTier::Fast => &self.fast,
}
}
async fn read_prompt(
&self,
prompt_file: &str,
requested: Option<&Path>,
) -> anyhow::Result<String> {
let resolved = Self::resolve_subagent_path(
&self.effective_mounts(requested),
self.base_dir.as_deref(),
Path::new(prompt_file),
)
.await
.map_err(|error| {
anyhow::anyhow!("subagent prompt must be a path to a prompt file: {error}")
})?;
let content = async_fs::read_to_string(&resolved).await.map_err(|error| {
anyhow::anyhow!(
"failed to read subagent prompt file '{}': {error}",
resolved.display()
)
})?;
let prompt = content.trim();
if prompt.is_empty() {
anyhow::bail!("subagent prompt file '{}' is empty", resolved.display());
}
#[cfg(feature = "languages")]
if let Some(guard) = &self.languages {
guard.check_working(prompt, crate::WorkingText::Internal)?;
}
Ok(prompt.to_string())
}
async fn named_source(
&self,
name: &str,
grant: Requested<'_>,
requested: Option<&Path>,
) -> anyhow::Result<Resolved<'_, LLM>> {
let definition = self.lookup(requested)?.resolve(name).await?;
if definition.access == SubagentAccess::ReadOnly && !grant.is_empty() {
anyhow::bail!(
"subagent '{name}' is read-only: it writes only its own working directory and takes no `--worktrees` or `--commit-worktrees`"
);
}
Ok(Resolved {
name: definition.name.clone(),
tier: definition.tier,
source: Source::Definition {
definition,
setup: self.setups.get(name),
},
})
}
}
impl<LLM: LanguageModel + Clone + Sync + 'static> SubagentTool<LLM> {
fn fork_snapshot(&self) -> anyhow::Result<Arc<ForkSnapshot>> {
if self.binding.is_none() {
return Err(ForkRefusal::NoTerminal.into_error());
}
let snapshot = self
.fork_source
.latest()
.ok_or_else(|| ForkRefusal::NothingSent.into_error())?;
if !snapshot.allows_fork() {
return Err(ForkRefusal::NearCompaction {
usage: snapshot.usage() * 100.0,
compaction: snapshot.compaction_usage() * 100.0,
}
.into_error());
}
Ok(snapshot)
}
async fn launch_terminal(
&self,
grant: SubagentGrant,
observer: Option<aither_sandbox::AnyCommandObserver>,
gate: Option<aither_sandbox::AnyCommandGate>,
) -> anyhow::Result<Option<DynTerminalTool>> {
if let Some(binding) = &self.binding {
let terminal = binding
.launcher()
.create(grant, observer, gate)
.await
.map_err(|e| anyhow::anyhow!("failed to create subagent terminal tool: {e}"))?;
Ok(Some(terminal))
} else if grant == SubagentGrant::new() {
Ok(None)
} else {
anyhow::bail!("worktrees can only be granted to a subagent launched from a terminal");
}
}
async fn start_external(
&self,
subagent_id: &str,
requested: Requested<'_>,
caller: Option<&Path>,
) -> anyhow::Result<FinishedSubagent<LLM>> {
let backend = &self
.externals
.get(subagent_id)
.ok_or_else(|| {
let connected: Vec<&str> = self.externals.keys().map(String::as_str).collect();
if connected.is_empty() {
anyhow::anyhow!("no external agent is connected, so '{subagent_id}' cannot run")
} else {
anyhow::anyhow!(
"no external agent '{subagent_id}' is connected; connected: {}",
connected.join(", ")
)
}
})?
.backend;
let working_dir = self.caller_dir(caller).ok_or_else(|| {
anyhow::anyhow!(
"external agent '{subagent_id}' needs a working directory: the tool is bound to no terminal and has no base directory"
)
})?;
let grant = requested.grant(Some(working_dir));
let (worktrees, commit_worktrees) = requested.paths(Some(working_dir));
let terminal = self.launch_terminal(grant, None, None).await?.map(Box::new);
let commit_ledger = terminal
.as_ref()
.and_then(|terminal| terminal.commit_ledger().cloned());
let session = backend
.open(ExternalStart {
working_dir,
worktrees: &worktrees,
commit_worktrees: &commit_worktrees,
})
.await
.map_err(|error| {
anyhow::anyhow!("failed to open a '{subagent_id}' session: {error}")
})?;
tracing::info!(subagent = %subagent_id, "Starting external subagent");
Ok(FinishedSubagent {
subagent: subagent_id.to_string(),
tier: None,
model: session.model(),
commit_ledger,
body: SubagentBody::External {
session,
_terminal: terminal,
},
})
}
async fn start_agent(
&self,
Resolved {
name: subagent_id,
tier: declared,
source,
}: Resolved<'_, LLM>,
grant: SubagentGrant,
prompt: &str,
started_by: Option<&CallIdentity>,
) -> anyhow::Result<FinishedSubagent<LLM>> {
let fork = match &source {
Source::Fork => Some(self.fork_snapshot()?),
Source::Definition { .. } => None,
};
let (tier, model) = match &fork {
Some(fork) => {
let resolved = self.select_model(prompt, Some(fork.tier())).await?;
if resolved.1 != fork.model() {
return Err(ForkRefusal::OtherModel {
main: fork.model().to_string(),
fork: resolved.1,
}
.into_error());
}
resolved
}
None => self.select_model(prompt, declared).await?,
};
let selected = self.model_for(tier).clone();
let agent_builder = match source {
Source::Definition { definition, setup } => {
let builder = crate::AgentBuilder::new(selected)
.agent_kind(crate::AgentKind::Chatbot)
.system_prompt(&definition.prompt);
match setup {
Some(setup) => setup(builder),
None => builder,
}
}
Source::Fork => crate::AgentBuilder::new(selected),
};
tracing::info!(subagent = %subagent_id, model = %model, "Starting subagent");
let child_hooks = self
.hooks
.as_ref()
.map_or_else(ExternalHooks::none, ExternalHooks::for_subagent);
let command_observer = self.hooks.is_some().then(|| child_hooks.command_observer());
let command_gate = self.hooks.is_some().then(|| child_hooks.command_gate());
let (agent_builder, child_job_registry, commit_ledger) = match self
.launch_terminal(grant, command_observer, command_gate)
.await?
{
Some(dyn_terminal) => {
let job_registry = dyn_terminal.job_registry();
let commit_ledger = dyn_terminal.commit_ledger().cloned();
let agent_builder = match &fork {
Some(fork) => agent_builder.forked_from(fork, dyn_terminal),
None => agent_builder.dyn_terminal(dyn_terminal),
};
(agent_builder, Some(job_registry), commit_ledger)
}
None => (agent_builder, None, None),
};
let identity = AgentIdentity::Subagent(SubagentIdentity::new(
subagent_id.clone(),
started_by.cloned(),
));
let agent = self
.subagent_harness(agent_builder)
.identity(identity)
.hook(child_hooks)
.build();
let lifetime = agent.cache_lifetime();
Ok(FinishedSubagent {
subagent: subagent_id,
tier: Some(tier),
model: Some(model),
commit_ledger,
body: SubagentBody::Agent {
agent: Box::new(agent),
child_job_registry,
lifetime,
},
})
}
fn subagent_harness(
&self,
agent_builder: AgentBuilder<LLM, LLM, LLM, ()>,
) -> AgentBuilder<LLM, LLM, LLM, ()> {
match &self.cache_keep_alive {
Some(keep_alive) => agent_builder
.cache_keep_alive(keep_alive.clone())
.claude_cache_ttl(aither_core::llm::model::ClaudePromptCacheTtl::FiveMinutes),
None => agent_builder,
}
}
async fn acquire(
&self,
call: Call<'_>,
prompt: &str,
started_by: Option<&CallIdentity>,
caller: Option<&Path>,
) -> anyhow::Result<(FinishedSubagent<LLM>, Option<u64>)> {
let (resolved, grant) = match call {
Call::Resume { id } => {
let finished = self.finished.checkout(id)?;
tracing::info!(subagent = %finished.subagent, id, "Continuing subagent");
return Ok((*finished, Some(id)));
}
Call::External { agent, grant } => {
return Ok((self.start_external(agent, grant, caller).await?, None));
}
Call::Fork { grant } => (
Resolved {
name: "fork".to_string(),
tier: None,
source: Source::Fork,
},
grant,
),
Call::Named { name, grant } => (self.named_source(name, grant, caller).await?, grant),
};
let grant = grant.grant(self.caller_dir(caller));
Ok((
self.start_agent(resolved, grant, prompt, started_by)
.await?,
None,
))
}
async fn select_model(
&self,
prompt: &str,
chosen: Option<ModelTier>,
) -> anyhow::Result<(ModelTier, String)> {
if let Some(tier) = chosen {
let profile = self.model_for(tier).profile().await.map_err(|error| {
anyhow::anyhow!(
"failed to fetch the {} model profile: {error}",
tier_label(tier)
)
})?;
return Ok((tier, profile.name));
}
self.route_model(prompt).await
}
async fn route_model(&self, prompt: &str) -> anyhow::Result<(ModelTier, String)> {
let (advanced, balanced, fast) = futures::join!(
self.advanced.profile(),
self.balanced.profile(),
self.fast.profile(),
);
let profiles = [
(ModelTier::Advanced, advanced),
(ModelTier::Balanced, balanced),
(ModelTier::Fast, fast),
]
.map(|(tier, profile)| {
profile.map_err(|error| {
anyhow::anyhow!(
"failed to fetch the {} model profile for subagent routing: {error}",
tier_label(tier)
)
})
});
let [advanced, balanced, fast] = profiles;
let (advanced, balanced, fast) = (advanced?, balanced?, fast?);
let system = SubagentRouter {
models: [
RouterModel {
tier: tier_label(ModelTier::Advanced),
name: &advanced.name,
description: &advanced.description,
},
RouterModel {
tier: tier_label(ModelTier::Balanced),
name: &balanced.name,
description: &balanced.description,
},
RouterModel {
tier: tier_label(ModelTier::Fast),
name: &fast.name,
description: &fast.description,
},
],
}
.render()
.map_err(|error| anyhow::anyhow!("failed to render the subagent router prompt: {error}"))?;
let routing: SubagentRouting = self
.fast
.generate(oneshot(system, prompt.to_string()))
.await
.map_err(|error| {
anyhow::anyhow!("the fast model failed to route the subagent prompt: {error}")
})?;
let name = match routing.model {
ModelTier::Advanced => advanced.name,
ModelTier::Balanced => balanced.name,
ModelTier::Fast => fast.name,
};
Ok((routing.model, name))
}
}
impl<LLM: LanguageModel + Clone + Sync + 'static> SubagentTool<LLM> {
async fn mark_commits(
&self,
finished: FinishedSubagent<LLM>,
resumed: Option<u64>,
) -> anyhow::Result<(FinishedSubagent<LLM>, Option<CommitMark>)> {
let Some(ledger) = &finished.commit_ledger else {
return Ok((finished, None));
};
match ledger.mark().await {
Ok(mark) => Ok((finished, Some(mark))),
Err(error) => {
if let Some(id) = resumed {
self.finished.store(Some(id), finished);
}
Err(anyhow::anyhow!(
"cannot record where the subagent's worktrees stand before its run: {error}"
))
}
}
}
}
fn subagent_stop_input<E: std::fmt::Display>(
subagent: &str,
outcome: &SubagentOutcome<E>,
) -> external_hook::SubagentStop {
let (end, result) = match outcome {
SubagentOutcome::Cancelled => (external_hook::SubagentEnd::Cancelled, String::new()),
SubagentOutcome::Finished(Ok(result)) => {
(external_hook::SubagentEnd::Completed, result.clone())
}
SubagentOutcome::Finished(Err(error)) => {
(external_hook::SubagentEnd::Failed, error.to_string())
}
};
external_hook::SubagentStop {
subagent: subagent.to_string(),
end,
result,
}
}
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, cx: ToolContext) -> aither_core::Result<Self::Res> {
let call = args.call()?;
let caller = cx.working_dir().map(Path::new);
let prompt = self.read_prompt(args.prompt_file(), caller).await?;
let (finished, resumed) = self.acquire(call, &prompt, cx.identity(), caller).await?;
let (
FinishedSubagent {
subagent: subagent_id,
tier,
model,
commit_ledger,
mut body,
},
commit_mark,
) = self.mark_commits(finished, resumed).await?;
if let Some(hooks) = &self.hooks {
hooks
.fire(&external_hook::SubagentStart {
subagent: subagent_id.clone(),
prompt: prompt.clone(),
})
.await;
}
let (run_id, cancel_rx) = self.runs.begin(&subagent_id, &prompt);
let outcome = body.run(&prompt, cancel_rx).await;
self.runs.finish(run_id);
if let Some(hooks) = &self.hooks {
hooks
.fire(&subagent_stop_input(&subagent_id, &outcome))
.await;
}
if let Some(job_registry) = body.job_registry() {
let killed = job_registry.kill_running().await;
if killed > 0 {
tracing::info!(
subagent = %subagent_id,
killed,
"Stopped background terminal jobs left by subagent"
);
}
}
let commits = list_commits(commit_ledger.as_ref(), commit_mark.as_ref()).await;
let result = match outcome {
SubagentOutcome::Cancelled => {
if let Some(id) = resumed {
self.finished.release(id);
}
body.end(true).await;
tracing::info!(subagent = %subagent_id, "Subagent cancelled");
return Ok(ToolResult::text(
SubagentResultTemplate {
subagent: &subagent_id,
outcome: SubagentReport::Cancelled,
commits: commits.as_ref(),
}
.render()
.expect("subagent result template must render"),
));
}
SubagentOutcome::Finished(Ok(result)) => result,
SubagentOutcome::Finished(Err(error)) => {
if let Some(id) = resumed {
self.finished.release(id);
}
let history = body.recent_history();
let error_text = failure_text(&subagent_id, &error, commits.as_ref(), &history);
body.end(false).await;
return Err(anyhow::anyhow!(error_text));
}
};
tracing::info!(subagent = %subagent_id, "Subagent completed");
let alert = body.idle_alert(&subagent_id);
let cache_bound = matches!(body, SubagentBody::Agent { .. });
let id = self.finished.store(
resumed,
FinishedSubagent {
subagent: subagent_id.clone(),
tier,
model: model.clone(),
commit_ledger,
body,
},
);
Ok(ToolResult::text(
SubagentResultTemplate {
subagent: &subagent_id,
outcome: SubagentReport::Completed {
tier: tier.map(tier_label),
model: model.as_deref(),
result: &result,
id,
cache_bound,
alert: alert.as_deref(),
},
commits: commits.as_ref(),
}
.render()
.expect("subagent result template must render"),
))
}
}
impl<LLM> CommandUsage for SubagentTool<LLM>
where
LLM: LanguageModel + Clone + Sync + 'static,
{
fn usage(&self) -> impl std::future::Future<Output = String> + Send {
self.usage_text()
}
}
#[derive(Template)]
#[template(path = "subagent_usage.txt", escape = "none")]
struct SubagentUsageTemplate<'a> {
subagents: &'a [Listed],
fork: &'a str,
externals: Vec<(&'a str, &'a str)>,
}
fn failure_text(
subagent: &str,
error: &str,
commits: Option<&CommitListing>,
history: &[HistoryEntry],
) -> String {
SubagentErrorTemplate {
subagent,
error,
commits,
history,
}
.render()
.expect("subagent error template must render")
}
impl<LLM: LanguageModel + 'static> SubagentBody<LLM> {
async fn run(
&mut self,
prompt: &str,
cancel_rx: async_channel::Receiver<()>,
) -> SubagentOutcome<String> {
match self {
Self::Agent { agent, .. } => {
await_subagent_run(
async { agent.query(prompt).await.map_err(|error| error.to_string()) },
cancel_rx,
)
.await
}
Self::External { session, .. } => {
await_subagent_run(
async {
session
.prompt(prompt)
.await
.map_err(|error| error.to_string())
},
cancel_rx,
)
.await
}
}
}
fn job_registry(&self) -> Option<aither_sandbox::JobRegistry> {
match self {
Self::Agent {
child_job_registry, ..
} => child_job_registry.clone(),
Self::External { .. } => None,
}
}
async fn end(self, cancelled: bool) {
if let Self::External { mut session, .. } = self {
if cancelled {
session.cancel().await;
}
session.close().await;
}
}
fn idle_alert(&self, subagent: &str) -> Option<String> {
let Self::Agent { agent, .. } = self else {
return None;
};
idle_alert(subagent, agent.cache_keep_alive_state())
}
fn recent_history(&self) -> Vec<HistoryEntry> {
let Self::Agent { agent, .. } = self else {
return Vec::new();
};
let history = agent.history();
let skipped = history.len().saturating_sub(12);
history
.iter()
.skip(skipped)
.map(|message| HistoryEntry {
role: message.role(),
content: message.content().to_string(),
tool_names: message
.tool_calls()
.iter()
.map(|call| call.name.clone())
.collect(),
})
.collect()
}
}
fn idle_alert(subagent: &str, keep_alive: &crate::agent::CacheKeepAliveState) -> Option<String> {
keep_alive.alerted.then(|| {
let reason = keep_alive
.last_reason
.clone()
.unwrap_or_else(|| "idle without a running background job".to_string());
format!(
"Subagent '{subagent}' needed {} prompt-cache keep-alives during its run — subagents should not idle frequently. Reason for its most recent idle: {reason}.",
keep_alive.sent
)
})
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use aither_core::llm::{Event, LLMRequest, model::Profile as ModelProfile};
use futures_core::Stream;
use super::*;
fn args_schema() -> serde_json::Value {
serde_json::to_value(schemars::schema_for!(SubagentArgs)).expect("schema serializes")
}
fn parse_cli(words: &[&str]) -> anyhow::Result<SubagentArgs> {
let words: Vec<String> = words.iter().map(ToString::to_string).collect();
let json = aither_sandbox::cli_to_json(&args_schema(), &words)?;
Ok(serde_json::from_value(json)?)
}
#[test]
fn the_name_and_the_brief_are_the_positional_arguments() {
let args = parse_cli(&["explore", "p.md"]).expect("a name and a brief parse");
assert_eq!(args.subagent(), Some("explore"));
assert_eq!(args.prompt_file(), "p.md");
assert!(matches!(
args.call().unwrap(),
Call::Named {
name: "explore",
..
}
));
let error = parse_cli(&[]).expect_err("a bare `subagent` names no subagent");
assert_eq!(error.to_string(), "missing required argument: name");
let schema = args_schema();
assert_eq!(
schema["required"],
serde_json::json!(["name", "prompt_file"]),
"only the name and the brief are positional"
);
assert!(
!schema["properties"]
.as_object()
.unwrap()
.contains_key("model"),
"no call takes a model"
);
}
#[test]
fn fork_resume_and_external_are_reserved_names_with_their_own_options() {
let fork = parse_cli(&["fork", "p.md", "--worktrees", "wt"]).expect("fork parses");
assert_eq!(fork.subagent(), Some("fork"));
let Call::Fork { grant } = fork.call().unwrap() else {
panic!("`fork` forks");
};
assert_eq!(
grant.paths(Some(Path::new("/base"))),
(vec![PathBuf::from("/base/wt")], vec![]),
"a fork keeps its worktree grants"
);
let resume =
parse_cli(&["resume", "--id", "3", "--prompt-file", "p.md"]).expect("resume parses");
assert_eq!(resume.subagent(), None);
assert!(matches!(resume.call().unwrap(), Call::Resume { id: 3 }));
let external = parse_cli(&["external", "p.md", "--agent", "codex"]).expect("parses");
assert_eq!(external.subagent(), Some("codex"));
assert!(matches!(
external.call().unwrap(),
Call::External { agent: "codex", .. }
));
for (words, refused) in [
(&["resume", "p.md"][..], "takes the `--id`"),
(
&["resume", "p.md", "--id", "3", "--worktrees", "wt"],
"keeps what it was granted",
),
(
&["explore", "p.md", "--id", "3"],
"use it with `subagent resume`",
),
(
&["fork", "p.md", "--agent", "codex"],
"use it with `subagent external`",
),
(&["external", "p.md"], "takes the `--agent`"),
] {
let error = parse_cli(words).unwrap().call().map(|_| ()).unwrap_err();
assert!(error.to_string().contains(refused), "{words:?}: {error}");
}
}
#[test]
fn subagent_error_history_names_tool_calls() {
let history = [
HistoryEntry {
role: aither_core::llm::Role::User,
content: "go".to_string(),
tool_names: Vec::new(),
},
HistoryEntry {
role: aither_core::llm::Role::Assistant,
content: String::new(),
tool_names: vec!["terminal".to_string(), "terminal_read".to_string()],
},
];
let rendered = SubagentErrorTemplate {
subagent: "research",
error: "boom",
commits: None,
history: &history,
}
.render()
.expect("subagent error should render");
assert_eq!(
rendered,
"Subagent 'research' error: boom\n\nRecent subagent history:\n- User: go\n- Assistant: [called terminal, terminal_read]\n"
);
}
#[test]
fn subagent_result_renders_as_prose() {
let completed = SubagentResultTemplate {
subagent: "research",
outcome: SubagentReport::Completed {
tier: Some("fast"),
model: Some("test-model"),
result: "done",
id: 7,
cache_bound: true,
alert: None,
},
commits: None,
}
.render()
.expect("subagent result should render");
assert_eq!(
completed,
"Subagent 'research' completed (fast tier, model: test-model).\n\ndone\n\nContinue this subagent with `subagent resume --id 7` while its prompt cache is still warm."
);
let external = SubagentResultTemplate {
subagent: "codex",
outcome: SubagentReport::Completed {
tier: None,
model: Some("its-model"),
result: "done",
id: 7,
cache_bound: false,
alert: None,
},
commits: None,
}
.render()
.expect("subagent result should render");
assert_eq!(
external,
"Subagent 'codex' completed (model: its-model).\n\ndone\n\nContinue this subagent with `subagent resume --id 7`."
);
let without_model = SubagentResultTemplate {
subagent: "research",
outcome: SubagentReport::Completed {
tier: None,
model: None,
result: "done",
id: 7,
cache_bound: true,
alert: Some("It idled too often."),
},
commits: None,
}
.render()
.expect("subagent result should render");
assert_eq!(
without_model,
"Subagent 'research' completed.\n\ndone\n\nContinue this subagent with `subagent resume --id 7` while its prompt cache is still warm.\n\nIt idled too often."
);
let cancelled = SubagentResultTemplate {
subagent: "explore",
outcome: SubagentReport::Cancelled,
commits: None,
}
.render()
.expect("cancelled result should render");
assert_eq!(cancelled, "Subagent 'explore' was cancelled by the user.");
}
#[test]
fn commit_listings_render_as_prose() {
let listed = CommitListing {
listed: Ok(vec![SubagentCommit {
worktree: PathBuf::from("/work/tree"),
commit: "abc123".to_string(),
subject: "fix the parser".to_string(),
}]),
setbacks: Vec::new(),
};
let completed = SubagentResultTemplate {
subagent: "worker",
outcome: SubagentReport::Completed {
tier: None,
model: None,
result: "done",
id: 3,
cache_bound: true,
alert: Some("It idled too often."),
},
commits: Some(&listed),
}
.render()
.expect("subagent result should render");
assert_eq!(
completed,
"Subagent 'worker' completed.\n\ndone\n\nContinue this subagent with `subagent resume --id 3` while its prompt cache is still warm.\n\nIt idled too often.\n\nCommits made in the granted worktrees:\n- abc123 fix the parser (in /work/tree)"
);
let none = CommitListing {
listed: Ok(Vec::new()),
setbacks: Vec::new(),
};
let cancelled = SubagentResultTemplate {
subagent: "worker",
outcome: SubagentReport::Cancelled,
commits: Some(&none),
}
.render()
.expect("cancelled result should render");
assert_eq!(
cancelled,
"Subagent 'worker' was cancelled by the user.\n\nNo commits were made in the granted worktrees."
);
let failed = CommitListing {
listed: Err(CommitLedgerError::Git {
repository: PathBuf::from("/repo"),
stderr: "boom".to_string(),
}),
setbacks: vec!["the repository at /repo is stuck".to_string()],
};
let rendered = SubagentErrorTemplate {
subagent: "worker",
error: "model failed",
commits: Some(&failed),
history: &[],
}
.render()
.expect("subagent error should render");
assert_eq!(
rendered,
"Subagent 'worker' error: model failed\n\nThe commits made in the granted worktrees could not be listed: git failed on /repo: boom\n\nBefore the run started: the repository at /repo is stuck\n\nRecent subagent history:\n"
);
}
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
}
struct Bundled {
root: tempfile::TempDir,
}
impl Bundled {
async fn new() -> Self {
let root = tempfile::tempdir().unwrap();
crate::install_bundled_subagents(&root.path().join("global"))
.await
.unwrap();
std::fs::create_dir_all(root.path().join("work")).unwrap();
Self { root }
}
fn global(&self) -> PathBuf {
self.root.path().join("global")
}
fn work(&self) -> PathBuf {
self.root.path().join("work")
}
fn tool<LLM: Clone + Sync>(&self, llm: LLM) -> SubagentTool<LLM> {
SubagentTool::new(llm, self.global()).with_base_dir(self.work())
}
}
fn write_definition(dir: &Path, name: &str, tier: Option<&str>, access: &str, prompt: &str) {
std::fs::create_dir_all(dir).unwrap();
let tier = tier.map_or_else(String::new, |tier| format!("tier = \"{tier}\"\n"));
std::fs::write(
dir.join(format!("{name}.toml")),
format!(
"name = \"{name}\"\ndescription = \"the {name} subagent\"\n{tier}access = \"{access}\"\nprompt = '''\n{prompt}\n'''\n"
),
)
.unwrap();
}
#[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((), root.join("global")).with_file_mounts([
SubagentFileMount::new(".", root.join("workspace")),
SubagentFileMount::new(".skills", skills_root.clone()),
]);
let resolved = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(None),
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((), root.join("global"))
.with_file_mounts([SubagentFileMount::new("skills", root.join("skills"))]);
let error = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(None),
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((), root.join("global"))
.with_file_mounts([SubagentFileMount::new("skills", skills_root.clone())]);
let error = SubagentTool::<()>::resolve_subagent_path(
&tool.effective_mounts(None),
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);
}
#[derive(Debug)]
struct NeverError;
impl std::fmt::Display for NeverError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("never resolves")
}
}
impl std::error::Error for NeverError {}
impl aither_core::llm::Classify for NeverError {
fn failure(&self) -> aither_core::llm::Failure {
aither_core::llm::Failure::permanent()
}
}
const ROUTE_FAST: &str = r#"{"model":"fast"}"#;
#[derive(Clone)]
struct PendingLlm;
impl LanguageModel for PendingLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
if request.parameters().structured_outputs {
futures::future::Either::Left(futures_lite::stream::iter([Ok(Event::Text(
ROUTE_FAST.to_string(),
))]))
} else {
futures::future::Either::Right(futures_lite::stream::pending())
}
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
"mock",
"test",
"pending-model",
"pending model",
128_000,
)))
}
}
#[derive(Clone)]
struct TextLlm {
name: &'static str,
structured: &'static str,
}
impl TextLlm {
const fn new(name: &'static str) -> Self {
Self {
name,
structured: "{}",
}
}
const fn routing(name: &'static str, decision: &'static str) -> Self {
Self {
name,
structured: decision,
}
}
}
impl LanguageModel for TextLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
let text = if request.parameters().structured_outputs {
self.structured
} else {
self.name
};
futures_lite::stream::iter([Ok(Event::Text(text.to_string()))])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
self.name,
"test",
self.name,
"text mock",
128_000,
)))
}
}
fn write_prompt_file(tag: &str, content: &str) -> (PathBuf, PathBuf) {
let dir = unique_temp_dir(tag);
let prompt_file = dir.join("prompt.txt");
std::fs::write(&prompt_file, content).expect("write prompt file");
(dir, prompt_file)
}
fn named(name: &str, prompt_file: &Path) -> SubagentArgs {
SubagentArgs {
name: name.to_string(),
prompt_file: prompt_file.to_string_lossy().into_owned(),
id: None,
agent: None,
worktrees: Vec::new(),
commit_worktrees: Vec::new(),
}
}
fn explore(prompt_file: &Path) -> SubagentArgs {
named("explore", prompt_file)
}
#[tokio::test]
async fn cancelled_run_returns_cancelled_result() {
let runs = SubagentRuns::default();
let bundled = Bundled::new().await;
let tool = bundled.tool(PendingLlm).with_runs(runs.clone());
let (dir, prompt_file) = write_prompt_file("cancelled-run", "survey the codebase");
let call = tokio::spawn(async move {
Tool::call(&tool, explore(&prompt_file), ToolContext::new()).await
});
let run = loop {
match runs.list().as_slice() {
[run] => break run.clone(),
[] => tokio::task::yield_now().await,
other => panic!("expected one registered run, got {}", other.len()),
}
};
assert_eq!(run.subagent, "explore");
assert_eq!(run.prompt, "survey the codebase");
assert!(runs.cancel(run.id));
assert!(runs.cancel(run.id), "re-cancel should still report true");
let result = call
.await
.expect("call task panicked")
.expect("subagent call failed");
let ToolResult::Text { text } = result else {
panic!("expected text result, got {result:?}");
};
assert_eq!(text, "Subagent 'explore' was cancelled by the user.");
assert!(runs.list().is_empty(), "finished run must unregister");
assert!(!runs.cancel(run.id), "finished run cannot be cancelled");
let _ = std::fs::remove_dir_all(dir);
}
fn git(dir: &Path, args: &[&str]) -> String {
let output = std::process::Command::new("git")
.args(["-c", "user.name=test", "-c", "user.email=test@example.com"])
.args(["-c", "commit.gpgSign=false"])
.args(args)
.current_dir(dir)
.output()
.expect("git runs");
assert!(
output.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
struct CommitFixture {
_dirs: [tempfile::TempDir; 2],
_cache: crate::test_support::TempDir,
bundled: Bundled,
terminal: aither_sandbox::TerminalTool<
aither_sandbox::permission::NoopPermissionHandler,
executor_core::tokio::TokioGlobal,
aither_sandbox::Configured,
>,
repository: PathBuf,
worktree: PathBuf,
}
impl CommitFixture {
async fn new() -> Self {
use aither_sandbox::permission::NoopPermissionHandler;
use aither_sandbox::{TerminalTool, ToolRegistryBuilder};
use executor_core::tokio::TokioGlobal;
let work = tempfile::tempdir().unwrap();
let source = tempfile::tempdir().unwrap();
let cache = crate::test_support::TempDir::new();
let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
let distribution = crate::test_support::fixture_distribution(&binary, "1.0.0").await;
let session = work.path().join("session");
let repository = session.join("repository");
std::fs::create_dir_all(&repository).unwrap();
git(&repository, &["init", "--initial-branch=main"]);
git(&repository, &["commit", "--allow-empty", "-m", "initial"]);
let worktree = session.join("worktree");
git(
&repository,
&[
"worktree",
"add",
"-b",
"subagent/work/main",
worktree.to_str().unwrap(),
],
);
let terminal = TerminalTool::new_exact(&session, NoopPermissionHandler, TokioGlobal)
.await
.expect("terminal tool should initialize")
.initialize_tools(&distribution, cache.path())
.await
.expect("tools should prepare");
let registry = Arc::new(ToolRegistryBuilder::new().build(terminal.outputs_dir()));
let terminal = terminal.with_registry(registry);
Self {
_dirs: [work, source],
_cache: cache,
bundled: Bundled::new().await,
terminal,
repository,
worktree,
}
}
fn tool<LLM: LanguageModel + Clone + Sync + 'static>(
&self,
llm: LLM,
runs: &SubagentRuns,
) -> SubagentTool<LLM> {
SubagentTool::new(llm, self.bundled.global())
.with_runs(runs.clone())
.with_agent_setup("general", |builder| builder.max_iterations(5))
.for_terminal(self.terminal.binding())
}
fn start(&self, tag: &str) -> (PathBuf, SubagentArgs) {
let (dir, prompt_file) = write_prompt_file(tag, "work in the worktree");
(
dir,
SubagentArgs {
commit_worktrees: vec![self.worktree.to_string_lossy().into_owned()],
..named("general", &prompt_file)
},
)
}
}
#[derive(Clone, Copy)]
enum CommitStep {
Commit,
CommitAndFail,
BreakRepository,
}
#[derive(Clone)]
struct CommittingLlm {
repository: PathBuf,
worktree: PathBuf,
step: CommitStep,
}
impl LanguageModel for CommittingLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
if request.parameters().structured_outputs {
return futures_lite::stream::iter([Ok(Event::Text(ROUTE_FAST.to_string()))]);
}
let answer = match self.step {
CommitStep::Commit => {
git(
&self.worktree,
&["commit", "--allow-empty", "-m", "made by the subagent"],
);
Ok(Event::Text("done".to_string()))
}
CommitStep::CommitAndFail => {
git(
&self.worktree,
&["commit", "--allow-empty", "-m", "made before failing"],
);
Err(NeverError)
}
CommitStep::BreakRepository => {
let git_dir = self.repository.join(".git");
std::fs::rename(git_dir.join("objects"), git_dir.join("objects-gone")).unwrap();
Ok(Event::Text("done".to_string()))
}
};
futures_lite::stream::iter([answer])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
"mock",
"test",
"committing-model",
"commits in a worktree",
128_000,
)))
}
}
impl CommitFixture {
fn llm(&self, step: CommitStep) -> CommittingLlm {
CommittingLlm {
repository: self.repository.clone(),
worktree: self.worktree.clone(),
step,
}
}
}
fn listed_subjects(text: &str) -> Vec<&str> {
let (_, listing) = text
.split_once("Commits made in the granted worktrees:\n")
.unwrap_or_else(|| panic!("the text lists commits: {text}"));
listing
.lines()
.map_while(|line| line.strip_prefix("- "))
.map(|line| {
let (_, rest) = line.split_once(' ').expect("a commit line names its id");
let (subject, _) = rest
.rsplit_once(" (in ")
.expect("a commit line names its worktree");
subject
})
.collect()
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_completed_run_lists_the_commits_made_in_its_granted_worktree() {
let fixture = CommitFixture::new().await;
let runs = SubagentRuns::default();
let tool = fixture.tool(fixture.llm(CommitStep::Commit), &runs);
let (dir, args) = fixture.start("completed-commits");
let result = Tool::call(&tool, args, ToolContext::new())
.await
.expect("the run completes");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'general' completed"), "{text}");
assert_eq!(listed_subjects(&text), ["made by the subagent"], "{text}");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_run_lists_the_commits_made_in_its_granted_worktree() {
let fixture = CommitFixture::new().await;
let runs = SubagentRuns::default();
let tool = fixture.tool(fixture.llm(CommitStep::CommitAndFail), &runs);
let (dir, args) = fixture.start("failed-commits");
let error = Tool::call(&tool, args, ToolContext::new())
.await
.expect_err("the run fails");
let failure = error.to_string();
assert!(
failure.starts_with("Subagent 'general' error: "),
"{failure}"
);
assert!(failure.contains("never resolves"), "{failure}");
assert_eq!(
listed_subjects(&failure),
["made before failing"],
"{failure}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_listing_failure_keeps_the_runs_outcome() {
let fixture = CommitFixture::new().await;
let runs = SubagentRuns::default();
let tool = fixture.tool(fixture.llm(CommitStep::BreakRepository), &runs);
let (dir, args) = fixture.start("broken-listing");
let result = Tool::call(&tool, args, ToolContext::new())
.await
.expect("the run's outcome survives the listing failure");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'general' completed"), "{text}");
assert!(text.contains("\n\ndone\n\n"), "{text}");
assert_eq!(
continuation_id(&text),
1,
"the subagent stays continuable: {text}"
);
assert!(
text.contains("The commits made in the granted worktrees could not be listed: "),
"the listing failure is reported in place of the commits: {text}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn cancelled_run_lists_the_commits_made_in_its_granted_worktree() {
let fixture = CommitFixture::new().await;
let runs = SubagentRuns::default();
let tool = fixture.tool(PendingLlm, &runs);
let (dir, args) = fixture.start("cancelled-commits");
let call = tokio::spawn(async move { Tool::call(&tool, args, ToolContext::new()).await });
let run = loop {
match runs.list().as_slice() {
[run] => break run.clone(),
[] => tokio::task::yield_now().await,
other => panic!("expected one registered run, got {}", other.len()),
}
};
git(
&fixture.worktree,
&["commit", "--allow-empty", "-m", "made during the run"],
);
assert!(runs.cancel(run.id));
let result = call
.await
.expect("call task panicked")
.expect("subagent call failed");
let text = result.render_for_model();
assert!(
text.starts_with("Subagent 'general' was cancelled by the user."),
"{text}"
);
assert_eq!(listed_subjects(&text), ["made during the run"], "{text}");
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_grant_without_a_terminal_is_refused() {
let bundled = Bundled::new().await;
let tool = bundled.tool(TextLlm::routing("only-model", ROUTE_FAST));
let (dir, prompt_file) = write_prompt_file("grant-without-terminal", "do it");
let error = Tool::call(
&tool,
SubagentArgs {
worktrees: vec!["somewhere".to_string()],
..named("general", &prompt_file)
},
ToolContext::new(),
)
.await
.expect_err("a grant cannot be given without a terminal");
assert!(
error.to_string().contains("launched from a terminal"),
"{error}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn inline_prompt_text_is_rejected() {
let bundled = Bundled::new().await;
let tool = bundled.tool(TextLlm::new("only-model"));
let error = Tool::call(
&tool,
explore(Path::new("summarize the repository layout")),
ToolContext::new(),
)
.await
.expect_err("inline prompt text must be rejected");
assert!(
error.to_string().contains("prompt file"),
"error should name the file requirement: {error}"
);
}
#[tokio::test]
async fn empty_prompt_file_is_rejected() {
let bundled = Bundled::new().await;
let tool = bundled.tool(TextLlm::new("only-model"));
let (dir, prompt_file) = write_prompt_file("empty-prompt", " \n");
let error = Tool::call(&tool, explore(&prompt_file), ToolContext::new())
.await
.expect_err("empty prompt file must be rejected");
assert!(
error.to_string().contains("is empty"),
"error should report the empty file: {error}"
);
let _ = std::fs::remove_dir_all(dir);
}
fn tiered_tool(bundled: &Bundled, routed: &'static str) -> SubagentTool<TextLlm> {
bundled
.tool(TextLlm::new("advanced-model"))
.with_balanced_model(TextLlm::new("balanced-model"))
.with_fast_model(TextLlm::routing("fast-model", routed))
}
async fn completed_text<LLM: LanguageModel + Clone + Sync + 'static>(
tool: &SubagentTool<LLM>,
args: SubagentArgs,
) -> String {
let result = Tool::call(tool, args, ToolContext::new())
.await
.expect("subagent call failed");
let ToolResult::Text { text } = result else {
panic!("expected text result, got {result:?}");
};
text
}
#[tokio::test]
async fn each_bundled_subagent_runs_on_its_stated_tier() {
let bundled = Bundled::new().await;
let tool = tiered_tool(&bundled, r#"{"model":"balanced"}"#);
let (dir, prompt_file) = write_prompt_file("stated-tier", "do the task");
let calls = [
("explore", "fast"),
("research", "fast"),
("audit", "advanced"),
("review", "advanced"),
("plan", "advanced"),
];
for (id, (subagent, tier)) in (1..).zip(calls) {
assert_eq!(
completed_text(&tool, named(subagent, &prompt_file)).await,
format!(
"Subagent '{subagent}' completed ({tier} tier, model: {tier}-model).\n\n{tier}-model\n\nContinue this subagent with `subagent resume --id {id}` while its prompt cache is still warm."
)
);
}
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn subagent_after_cd_resolves_agents_and_brief_in_the_callers_directory() {
let bundled = Bundled::new().await;
let skill = bundled.root.path().join("work/skills/slide");
write_definition(
&skill.join("agents"),
"art_direction",
Some("fast"),
"read_only",
"direct the art",
);
std::fs::write(skill.join("brief.md"), "design the deck").unwrap();
let tool = tiered_tool(&bundled, r#"{"model":"fast"}"#);
let args = |name: &str| named(name, Path::new("brief.md"));
let in_skill = || ToolContext::new().with_working_dir(skill.to_string_lossy());
let result = Tool::call(&tool, args("art_direction"), in_skill())
.await
.expect("agents/ and the brief resolve in the caller's directory");
let ToolResult::Text { text } = result else {
panic!("expected text result, got {result:?}");
};
assert!(
text.starts_with("Subagent 'art_direction' completed"),
"{text}"
);
let error = Tool::call(&tool, args("art_direction"), ToolContext::new())
.await
.expect_err("the starting directory holds neither the brief nor agents/");
assert!(error.to_string().contains("brief.md"), "{error}");
}
#[tokio::test]
async fn general_runs_on_and_reports_the_tier_routing_picked() {
let bundled = Bundled::new().await;
let (dir, prompt_file) = write_prompt_file("routed-tier", "do the task");
for (routed, tier) in [
(r#"{"model":"balanced"}"#, "balanced"),
(r#"{"model":"advanced"}"#, "advanced"),
] {
let text = completed_text(
&tiered_tool(&bundled, routed),
named("general", &prompt_file),
)
.await;
assert_eq!(
text,
format!(
"Subagent 'general' completed ({tier} tier, model: {tier}-model).\n\n{tier}-model\n\nContinue this subagent with `subagent resume --id 1` while its prompt cache is still warm."
)
);
}
let _ = std::fs::remove_dir_all(dir);
}
#[derive(Clone)]
struct RoleLlm {
name: &'static str,
structured: &'static str,
}
const ROLE_MARKERS: [&str; 3] = ["GLOBAL-ROLE", "LOCAL-ROLE", "ONLY-LOCAL-ROLE"];
impl LanguageModel for RoleLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
let text = if request.parameters().structured_outputs {
self.structured.to_string()
} else {
let sent = serde_json::to_string(request.messages()).unwrap();
let role = ROLE_MARKERS
.iter()
.rev()
.find(|marker| sent.contains(*marker))
.unwrap_or(&"no role");
format!("{} ran {role}", self.name)
};
futures_lite::stream::iter([Ok(Event::Text(text))])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
self.name,
"test",
self.name,
"role mock",
128_000,
)))
}
}
#[tokio::test]
async fn global_and_local_definitions_run_as_declared_and_a_global_name_wins() {
let bundled = Bundled::new().await;
let local = bundled.work().join(crate::LOCAL_SUBAGENTS_DIR);
write_definition(
&bundled.global(),
"shared",
Some("fast"),
"read_only",
"GLOBAL-ROLE",
);
write_definition(
&local,
"shared",
Some("advanced"),
"worktrees",
"LOCAL-ROLE",
);
write_definition(&local, "only_local", None, "worktrees", "ONLY-LOCAL-ROLE");
let role = |name| RoleLlm {
name,
structured: r#"{"model":"balanced"}"#,
};
let tool = bundled
.tool(role("advanced-model"))
.with_balanced_model(role("balanced-model"))
.with_fast_model(role("fast-model"));
let (dir, prompt_file) = write_prompt_file("definitions", "do the task");
let shared = completed_text(&tool, named("shared", &prompt_file)).await;
assert!(
shared.starts_with(
"Subagent 'shared' completed (fast tier, model: fast-model).\n\nfast-model ran GLOBAL-ROLE\n"
),
"the global definition shadows the local one: {shared}"
);
let only_local = completed_text(&tool, named("only_local", &prompt_file)).await;
assert!(
only_local.starts_with(
"Subagent 'only_local' completed (balanced tier, model: balanced-model).\n\nbalanced-model ran ONLY-LOCAL-ROLE\n"
),
"a local definition without a tier is routed: {only_local}"
);
let error = Tool::call(
&tool,
SubagentArgs {
worktrees: vec!["wt".to_string()],
..named("shared", &prompt_file)
},
ToolContext::new(),
)
.await
.expect_err("a read-only subagent takes no grant");
assert!(
error.to_string().contains("subagent 'shared' is read-only"),
"{error}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn an_unknown_name_names_both_places_it_was_looked_for() {
let bundled = Bundled::new().await;
let tool = bundled.tool(TextLlm::new("only-model"));
let (dir, prompt_file) = write_prompt_file("unknown-name", "do the task");
let error = Tool::call(&tool, named("nowhere", &prompt_file), ToolContext::new())
.await
.expect_err("an unknown name is refused");
assert_eq!(
error.to_string(),
format!(
"no subagent 'nowhere': neither the global subagents directory {} nor {} holds nowhere.toml",
bundled.global().display(),
bundled.work().join("agents").display()
)
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn the_usage_lists_every_name_that_resolves() {
let bundled = Bundled::new().await;
let local = bundled.work().join(crate::LOCAL_SUBAGENTS_DIR);
write_definition(&local, "only_local", None, "read_only", "ONLY-LOCAL-ROLE");
write_definition(&local, "explore", None, "read_only", "LOCAL-ROLE");
std::fs::write(local.join("broken.toml"), "name = ").unwrap();
let tool = bundled.tool(PendingLlm).with_external(
"outside",
"runs outside aither",
TestBackend {
log: EventLog::default(),
opened: Arc::default(),
},
);
let usage = tool.usage().await;
let listed: Vec<&str> = usage
.lines()
.filter_map(|line| line.strip_prefix("- "))
.filter_map(|line| line.split_once(':').map(|(name, _)| name))
.collect();
assert_eq!(
listed,
[
"audit",
"broken",
"explore",
"general",
"only_local",
"plan",
"research",
"review",
"fork",
"outside"
],
"{usage}"
);
assert!(
usage.contains(&format!(
"- explore: {}\n",
crate::BUNDLED_SUBAGENTS[0].definition().description
)),
"the global explore shadows the local one: {usage}"
);
assert!(
usage.contains("- broken: the subagent definition "),
"an invalid definition is listed with why: {usage}"
);
assert!(usage.contains("`subagent resume --id <id>"), "{usage}");
assert!(
usage.contains("`subagent external --agent <agent>"),
"{usage}"
);
}
#[derive(Clone)]
struct KeepAliveMockLlm {
author: &'static str,
requests: async_channel::Sender<LLMRequest>,
turns: Arc<std::sync::atomic::AtomicUsize>,
}
impl LanguageModel for KeepAliveMockLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
self.requests
.try_send(request.clone())
.expect("record model request");
if request.parameters().max_tokens == Some(0) {
return futures_lite::stream::iter([Ok(Event::Usage(aither_core::llm::Usage {
prompt_tokens: Some(10),
completion_tokens: Some(0),
total_tokens: Some(10),
reasoning_tokens: None,
cache_read_tokens: Some(10),
cache_write_tokens: None,
cost_usd: None,
stop_reason: Some("max_tokens".to_string()),
}))]);
}
let turn = self.turns.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let event = match turn {
0 => Event::ToolCall(aither_core::llm::ToolCall::new(
"bg-1",
"terminal",
serde_json::json!({
"description": "hold the cache window",
"script": "sleep 2",
"timeout": 60,
"background": true
}),
)),
_ => Event::Text("done".to_string()),
};
futures_lite::stream::iter([Ok(event)])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
let author = self.author;
std::future::ready(Ok(ModelProfile::new(
"mock",
author,
"mock-model",
"mock model",
100_000,
)))
}
}
fn keep_alive_tool(
bundled: &Bundled,
author: &'static str,
requests: async_channel::Sender<LLMRequest>,
keep_alive: Option<crate::config::CacheKeepAlive>,
) -> (
SubagentTool<KeepAliveMockLlm>,
aither_sandbox::BackgroundTaskSender,
aither_sandbox::JobRegistry,
aither_sandbox::JobRegistryService,
) {
let (sender, receiver) = aither_sandbox::background_task_channel();
let (job_registry, job_service) = aither_sandbox::job_registry_channel();
let child_jobs = job_registry.clone();
let tool = bundled.tool(KeepAliveMockLlm {
author,
requests,
turns: Arc::default(),
});
let tool = match keep_alive {
Some(keep_alive) => tool.with_cache_keep_alive(keep_alive),
None => tool,
}
.with_agent_setup("explore", move |builder| {
builder
.max_iterations(4)
.background_channels(receiver.clone(), child_jobs.clone())
});
(tool, sender, job_registry, job_service)
}
async fn register_running_job(
job_registry: &aither_sandbox::JobRegistry,
pid: u32,
script: &str,
) {
job_registry
.register(
pid,
"amber-test-task",
"exec-key",
script,
aither_sandbox::TerminalMode::Sandboxed,
None,
)
.await;
}
fn keep_alive_requests(requests: &async_channel::Receiver<LLMRequest>) -> Vec<LLMRequest> {
let mut drained = Vec::new();
while let Ok(request) = requests.try_recv() {
drained.push(request);
}
drained
.into_iter()
.filter(|request| request.parameters().max_tokens == Some(0))
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn anthropic_subagent_waiting_on_background_command_gets_keep_alives() {
let (dir, prompt_file) = write_prompt_file("keep-alive-warm-prompt", "hold a job");
let (request_tx, request_rx) = async_channel::unbounded();
let bundled = Bundled::new().await;
let (tool, sender, job_registry, job_service) = keep_alive_tool(
&bundled,
"Anthropic",
request_tx,
Some(crate::config::CacheKeepAlive {
send_before_expiry: std::time::Duration::from_millis(299_750),
frequent_idle_threshold: 2,
}),
);
tokio::spawn(job_service.serve());
register_running_job(&job_registry, 4242, "sleep 2").await;
sender.task_started();
let call = tokio::spawn(async move {
Tool::call(&tool, explore(&prompt_file), ToolContext::new()).await
});
let mut keep_alives = Vec::new();
tokio::time::timeout(std::time::Duration::from_secs(30), async {
while keep_alives.len() < 2 {
let request = request_rx.recv().await.expect("request channel closed");
if request.parameters().max_tokens == Some(0) {
keep_alives.push(request);
}
}
})
.await
.expect("two keep-alives while the job ran");
sender.task_finished();
sender
.send_completed(aither_sandbox::CompletedTask {
task_id: "amber-test-task".to_string(),
script: "sleep 2".to_string(),
killed: false,
timeout_kill: None,
result: Ok(aither_sandbox::CompletedCommand {
stdout: aither_core::llm::CommandStream::Inline {
text: String::new(),
},
stderr: None,
exit_code: 0,
interruptions: Vec::new(),
}),
})
.await;
let result = call
.await
.expect("call task panicked")
.expect("subagent call failed");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'explore' completed"), "{text}");
keep_alives.extend(keep_alive_requests(&request_rx));
for request in &keep_alives {
let params = request.parameters();
assert_eq!(params.max_tokens, Some(0));
assert_eq!(
params.stream,
Some(false),
"keep-alive must be non-streaming"
);
assert_eq!(
params.reasoning_effort, None,
"keep-alive must preserve the last request's effort"
);
assert!(
!params.include_reasoning,
"keep-alive must preserve the last request's thinking"
);
}
assert!(
text.contains("Subagent 'explore' needed"),
"alert names the subagent: {text}"
);
assert!(
text.contains("sleep 2"),
"alert gives the idle reason: {text}"
);
assert!(text.contains("should not idle frequently"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn subagent_without_keep_alive_config_gets_no_keep_alives() {
let (dir, prompt_file) = write_prompt_file("keep-alive-other-prompt", "hold a job");
let (request_tx, request_rx) = async_channel::unbounded();
let bundled = Bundled::new().await;
let (tool, sender, job_registry, job_service) =
keep_alive_tool(&bundled, "Anthropic", request_tx, None);
tokio::spawn(job_service.serve());
register_running_job(&job_registry, 4243, "sleep 2").await;
sender.task_started();
let call = tokio::spawn(async move {
Tool::call(&tool, explore(&prompt_file), ToolContext::new()).await
});
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
sender.task_finished();
sender
.send_completed(aither_sandbox::CompletedTask {
task_id: "amber-test-task".to_string(),
script: "sleep 2".to_string(),
killed: false,
timeout_kill: None,
result: Ok(aither_sandbox::CompletedCommand {
stdout: aither_core::llm::CommandStream::Inline {
text: String::new(),
},
stderr: None,
exit_code: 0,
interruptions: Vec::new(),
}),
})
.await;
let result = call
.await
.expect("call task panicked")
.expect("subagent call failed");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'explore' completed"), "{text}");
assert!(
keep_alive_requests(&request_rx).is_empty(),
"no keep-alive config means no keep-alives"
);
assert!(
!text.contains("keep-alives during its run"),
"no alert without keep-alives: {text}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn finished_subagent_gets_no_keep_alives() {
let (request_tx, request_rx) = async_channel::unbounded();
let llm = KeepAliveMockLlm {
author: "Anthropic",
requests: request_tx,
turns: Arc::new(std::sync::atomic::AtomicUsize::new(1)),
};
let bundled = Bundled::new().await;
let tool = bundled
.tool(llm)
.with_agent_setup("explore", |builder| builder.max_iterations(2));
let (dir, prompt_file) = write_prompt_file("keep-alive-idle", "answer directly");
let result = Tool::call(&tool, explore(&prompt_file), ToolContext::new())
.await
.expect("subagent call failed");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'explore' completed"), "{text}");
assert!(
keep_alive_requests(&request_rx).is_empty(),
"a run that never waits on a background job gets no keep-alive"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[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/references/layouts.md");
let mounted_skill_file = skills_root.join("slide/references/layouts.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, "# layouts").expect("write mounted skill file");
let tool = SubagentTool::new((), root.join("global"))
.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(None),
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);
}
#[derive(Clone)]
struct EchoLlm {
requests: async_channel::Sender<LLMRequest>,
replies: Arc<std::sync::atomic::AtomicUsize>,
}
impl LanguageModel for EchoLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
self.requests
.try_send(request)
.expect("record model request");
let n = self
.replies
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
futures_lite::stream::iter([Ok(Event::Text(format!("reply-{n}")))])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
"mock",
"Anthropic",
"mock-model",
"mock model",
100_000,
)))
}
}
async fn resume_tool(
lifetime: Option<CacheLifetime>,
keep_alive: Option<crate::config::CacheKeepAlive>,
) -> (
SubagentTool<EchoLlm>,
async_channel::Receiver<LLMRequest>,
Bundled,
) {
let (request_tx, request_rx) = async_channel::unbounded();
let bundled = Bundled::new().await;
let tool = bundled.tool(EchoLlm {
requests: request_tx,
replies: Arc::default(),
});
let tool = match keep_alive {
Some(keep_alive) => tool.with_cache_keep_alive(keep_alive),
None => tool,
}
.with_agent_setup("explore", move |builder| {
let builder = builder.max_iterations(2);
match lifetime {
Some(lifetime) => builder.prompt_cache(
crate::context::PromptCache::new("resume-test").with_lifetime(lifetime),
),
None => builder,
}
});
(tool, request_rx, bundled)
}
fn resume_args(prompt_file: &Path, resume: u64) -> SubagentArgs {
SubagentArgs {
id: Some(resume),
..named("resume", prompt_file)
}
}
fn continuation_id(text: &str) -> u64 {
let tail = text
.split("subagent resume --id ")
.nth(1)
.unwrap_or_else(|| panic!("result names a continuation id: {text}"));
tail.chars()
.take_while(char::is_ascii_digit)
.collect::<String>()
.parse()
.expect("continuation id is a number")
}
async fn first_run(tool: &SubagentTool<EchoLlm>, prompt_file: &Path) -> (String, u64) {
let result = Tool::call(tool, explore(prompt_file), ToolContext::new())
.await
.expect("subagent call failed");
let text = result.render_for_model();
let id = continuation_id(&text);
(text, id)
}
#[tokio::test]
async fn finished_subagent_continues_with_its_earlier_conversation() {
let (tool, requests, _bundled) = resume_tool(
None,
Some(crate::config::CacheKeepAlive {
send_before_expiry: std::time::Duration::ZERO,
frequent_idle_threshold: 3,
}),
)
.await;
let (dir, first_prompt) = write_prompt_file("resume-first", "first question marker");
let (first, id) = first_run(&tool, &first_prompt).await;
assert!(first.starts_with("Subagent 'explore' completed"), "{first}");
assert!(first.contains("\n\nreply-0\n\n"), "{first}");
while requests.try_recv().is_ok() {}
let follow_up = dir.join("follow-up.txt");
std::fs::write(&follow_up, "second question marker").expect("write follow-up");
let result = Tool::call(&tool, resume_args(&follow_up, id), ToolContext::new())
.await
.expect("continuing failed");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'explore' completed"), "{text}");
assert!(text.contains("\n\nreply-1\n\n"), "{text}");
assert_eq!(
continuation_id(&text),
id,
"a continued subagent keeps its id"
);
let request = requests.try_recv().expect("continuation sent a request");
let sent = serde_json::to_string(request.messages()).expect("serialize messages");
assert!(sent.contains("first question marker"), "{sent}");
assert!(sent.contains("reply-0"), "{sent}");
assert!(sent.contains("second question marker"), "{sent}");
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn continuing_an_unknown_id_is_an_error() {
let (tool, _requests, _bundled) = resume_tool(None, None).await;
let (dir, prompt_file) = write_prompt_file("resume-unknown", "follow-up");
let error = Tool::call(&tool, resume_args(&prompt_file, 99), ToolContext::new())
.await
.expect_err("unknown id must fail");
assert!(
error.to_string().contains("unknown subagent id 99"),
"{error}"
);
let _ = std::fs::remove_dir_all(dir);
}
fn age_finished_subagent(tool: &SubagentTool<EchoLlm>, id: u64, age: std::time::Duration) {
let mut inner = tool
.finished
.inner
.lock()
.expect("finished subagents lock poisoned");
let Some(FinishedSlot::Idle(finished)) = inner.slots.get_mut(&id) else {
panic!("subagent {id} is not idle");
};
let SubagentBody::Agent { agent, .. } = &mut finished.body else {
panic!("subagent {id} is not an aither agent");
};
agent.backdate_cache_entry(age);
drop(inner);
}
#[tokio::test]
async fn claude_subagent_expires_after_its_five_minute_lifetime() {
let (tool, _requests, _bundled) =
resume_tool(None, Some(crate::config::CacheKeepAlive::default())).await;
let (dir, prompt_file) = write_prompt_file("resume-expired", "first");
let (_, id) = first_run(&tool, &prompt_file).await;
age_finished_subagent(&tool, id, std::time::Duration::from_secs(301));
let error = Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
.await
.expect_err("expired subagent must fail");
let message = error.to_string();
assert!(message.contains("expired"), "{message}");
assert!(
message.contains("300s"),
"the error names the lifetime the id expired after: {message}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn claude_subagent_continues_just_inside_its_five_minute_lifetime() {
let (tool, _requests, _bundled) =
resume_tool(None, Some(crate::config::CacheKeepAlive::default())).await;
let (dir, prompt_file) = write_prompt_file("resume-inside", "first");
let (_, id) = first_run(&tool, &prompt_file).await;
age_finished_subagent(&tool, id, std::time::Duration::from_secs(290));
Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
.await
.expect("a subagent inside its lifetime continues");
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn non_claude_subagent_keeps_the_default_lifetime() {
let (tool, _requests, _bundled) = resume_tool(None, None).await;
let (dir, prompt_file) = write_prompt_file("resume-default-lifetime", "first");
let (_, id) = first_run(&tool, &prompt_file).await;
age_finished_subagent(&tool, id, std::time::Duration::from_secs(301));
Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
.await
.expect("past five minutes a non-Claude subagent still continues");
age_finished_subagent(&tool, id, std::time::Duration::from_secs(3601));
let error = Tool::call(&tool, resume_args(&prompt_file, id), ToolContext::new())
.await
.expect_err("expired subagent must fail");
assert!(error.to_string().contains("3600s"), "{error}");
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn claude_subagent_requests_five_minute_cache_and_main_agent_one_hour() {
use aither_core::llm::model::ClaudePromptCacheTtl;
let claude_ttl = |request: &LLMRequest| {
request
.parameters()
.cache
.claude
.as_ref()
.expect("request carries Claude cache control")
.ttl
};
let (tool, subagent_requests, _bundled) =
resume_tool(None, Some(crate::config::CacheKeepAlive::default())).await;
let (dir, prompt_file) = write_prompt_file("cache-ttl-claude", "first");
first_run(&tool, &prompt_file).await;
let subagent_request = subagent_requests.try_recv().expect("subagent request");
assert_eq!(
claude_ttl(&subagent_request),
ClaudePromptCacheTtl::FiveMinutes
);
let (other, other_requests, _other_bundled) = resume_tool(None, None).await;
first_run(&other, &prompt_file).await;
let other_request = other_requests.try_recv().expect("other subagent request");
assert_eq!(claude_ttl(&other_request), ClaudePromptCacheTtl::OneHour);
let (main_tx, main_requests) = async_channel::unbounded();
let mut main_agent = crate::AgentBuilder::new(EchoLlm {
requests: main_tx,
replies: Arc::default(),
})
.agent_kind(crate::AgentKind::Chatbot)
.build();
main_agent.query("hello").await.expect("main agent query");
let main_request = main_requests.try_recv().expect("main agent request");
assert_eq!(claude_ttl(&main_request), ClaudePromptCacheTtl::OneHour);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn no_call_carries_a_model_or_another_subagent_selector() {
for extra in ["model", "subagent", "command"] {
let error = serde_json::from_value::<SubagentArgs>(serde_json::json!({
"name": "resume",
"id": 7,
"prompt_file": "prompt.txt",
extra: "fast",
}))
.expect_err("a call cannot name a model or another selector");
assert!(
error.to_string().contains("unknown field"),
"{extra} must be rejected as unknown: {error}"
);
}
}
#[tokio::test]
async fn finished_subagent_without_keep_alive_still_continues() {
let (tool, requests, _bundled) = resume_tool(None, None).await;
let (dir, first_prompt) = write_prompt_file("resume-no-keepalive", "first marker");
let (first, id) = first_run(&tool, &first_prompt).await;
assert!(first.starts_with("Subagent 'explore' completed"), "{first}");
while requests.try_recv().is_ok() {}
let follow_up = dir.join("follow-up.txt");
std::fs::write(&follow_up, "second marker").expect("write follow-up");
let result = Tool::call(&tool, resume_args(&follow_up, id), ToolContext::new())
.await
.expect("continuing failed");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'explore' completed"), "{text}");
assert!(text.contains("\n\nreply-1\n\n"), "{text}");
assert_eq!(continuation_id(&text), id);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn permanent_cache_lifetime_never_expires() {
let (tool, _requests, _bundled) = resume_tool(Some(CacheLifetime::Permanent), None).await;
let (dir, first_prompt) = write_prompt_file("resume-permanent", "first");
let (_, id) = first_run(&tool, &first_prompt).await;
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
let follow_up = dir.join("follow-up.txt");
std::fs::write(&follow_up, "second").expect("write follow-up");
let result = Tool::call(&tool, resume_args(&follow_up, id), ToolContext::new())
.await
.expect("a permanent lifetime never expires");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'explore' completed"), "{text}");
assert_eq!(continuation_id(&text), id);
let _ = std::fs::remove_dir_all(dir);
}
const FORK_HANDOFF_JSON: &str = r#"{"current_task":"keep going","key_decisions":[],"context_files":[],"errors_fixes":[],"pending_work":["continue"],"recovery_hints":[],"skills":[]}"#;
#[derive(Clone)]
struct ScriptedLlm {
name: &'static str,
seen: async_channel::Sender<(&'static str, LLMRequest)>,
turns: Arc<Mutex<std::collections::VecDeque<Turn>>>,
}
type Turn = Box<dyn FnOnce(&LLMRequest) -> Vec<Event> + Send>;
impl ScriptedLlm {
fn new(
name: &'static str,
seen: &async_channel::Sender<(&'static str, LLMRequest)>,
) -> Self {
Self {
name,
seen: seen.clone(),
turns: Arc::default(),
}
}
fn then(&self, turns: impl IntoIterator<Item = Vec<Event>>) {
self.turns.lock().unwrap().extend(
turns
.into_iter()
.map(|events| Box::new(move |_: &LLMRequest| events) as Turn),
);
}
fn then_with(&self, turn: impl FnOnce(&LLMRequest) -> Vec<Event> + Send + 'static) {
self.turns.lock().unwrap().push_back(Box::new(turn));
}
}
impl LanguageModel for ScriptedLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
let compaction = request.parameters().structured_outputs;
let events = if compaction {
vec![Event::Text(FORK_HANDOFF_JSON.to_string())]
} else {
let turn = self.turns.lock().unwrap().pop_front();
turn.map_or_else(
|| vec![Event::Text("done".to_string())],
|turn| turn(&request),
)
};
self.seen
.try_send((self.name, request))
.expect("record model request");
futures_lite::stream::iter(events.into_iter().map(Ok))
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
self.name,
"test",
self.name,
"scripted model",
1_000_000,
)))
}
}
#[derive(Clone, Default)]
struct RecordingPermission {
asked: Arc<Mutex<Vec<(aither_sandbox::TerminalMode, String)>>>,
}
impl aither_sandbox::permission::PermissionHandler for RecordingPermission {
fn check(
&self,
mode: aither_sandbox::TerminalMode,
script: &str,
) -> impl std::future::Future<
Output = Result<bool, aither_sandbox::permission::PermissionError>,
> + Send {
self.asked.lock().unwrap().push((mode, script.to_string()));
std::future::ready(Ok(false))
}
}
struct ForkFixture {
_hook_tools: crate::test_support::PreparedFixture,
_dirs: [tempfile::TempDir; 2],
_cache: crate::test_support::TempDir,
bundled: Bundled,
terminal: aither_sandbox::TerminalTool<
crate::ReviewedPermission<RecordingPermission>,
executor_core::tokio::TokioGlobal,
aither_sandbox::Configured,
>,
asked: Arc<Mutex<Vec<(aither_sandbox::TerminalMode, String)>>>,
}
impl ForkFixture {
async fn new() -> Self {
Self::reviewed(Vec::new()).await
}
async fn reviewed(reviewers: Vec<crate::external_hook::ReviewerConfig>) -> Self {
Self::build(reviewers, Bundled::new().await, |_| {}).await
}
async fn build(
reviewers: Vec<crate::external_hook::ReviewerConfig>,
bundled: Bundled,
commands: impl FnOnce(&mut aither_sandbox::ToolRegistryBuilder),
) -> Self {
use aither_sandbox::{TerminalTool, ToolRegistryBuilder};
use executor_core::tokio::TokioGlobal;
let session = tempfile::tempdir().unwrap();
let source = tempfile::tempdir().unwrap();
let cache = crate::test_support::TempDir::new();
let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
let distribution = crate::test_support::fixture_distribution(&binary, "1.0.0").await;
let permission = RecordingPermission::default();
let asked = permission.asked.clone();
let hook_tools = crate::test_support::prepared_fixture().await;
let permission = crate::ReviewedPermission::new(
permission,
crate::external_hook::ExternalHooks::new(
&crate::external_hook::LiveHooks::start(
crate::external_hook::HooksConfig {
reviewers,
..crate::external_hook::HooksConfig::default()
},
&hook_tools.tools,
executor_core::AnyExecutor::new(TokioGlobal),
)
.await
.expect("the hooks start"),
),
);
let terminal = TerminalTool::new_exact(session.path(), permission, TokioGlobal)
.await
.expect("terminal tool should initialize")
.initialize_tools(&distribution, cache.path())
.await
.expect("tools should prepare");
let mut registry = ToolRegistryBuilder::new();
commands(&mut registry);
let registry = Arc::new(registry.build(terminal.outputs_dir()));
Self {
_dirs: [session, source],
_cache: cache,
_hook_tools: hook_tools,
bundled,
terminal: terminal.with_registry(registry),
asked,
}
}
fn tool(
&self,
main: &ScriptedLlm,
seen: &async_channel::Sender<(&'static str, LLMRequest)>,
) -> SubagentTool<ScriptedLlm> {
SubagentTool::new(main.clone(), self.bundled.global())
.with_balanced_model(ScriptedLlm::new("balanced", seen))
.with_fast_model(ScriptedLlm::new("fast", seen))
.for_terminal(self.terminal.binding())
}
fn main_agent<LLM: LanguageModel + Clone + 'static>(
&self,
llm: LLM,
source: ForkSource,
policy: crate::ContextPolicy,
) -> crate::Agent<LLM, LLM, LLM, ()> {
let jobs = self.terminal.job_registry();
crate::AgentBuilder::new(llm)
.config(
crate::AgentConfig::new()
.with_system_prompt("You are the main agent.")
.with_context_policy(policy),
)
.agent_kind(crate::AgentKind::Chatbot)
.dyn_terminal(self.terminal.clone().to_dyn())
.compact_tool()
.tool(aither_sandbox::builtin::KillTerminalTool::new(jobs.clone()))
.tool(aither_sandbox::builtin::InputTerminalTool::new(
jobs.clone(),
))
.tool(aither_sandbox::builtin::ReadTerminalDeltaTool::new(jobs))
.fork_source(source)
.build()
}
}
fn start_fork(tag: &str) -> (PathBuf, SubagentArgs) {
let (dir, prompt_file) = write_prompt_file(tag, "carry on from here");
(dir, named("fork", &prompt_file))
}
fn start_audit(tag: &str) -> (PathBuf, SubagentArgs) {
let (dir, prompt_file) = write_prompt_file(tag, "carry on from here");
(dir, named("audit", &prompt_file))
}
fn unsafe_terminal_call(id: &str) -> Event {
Event::ToolCall(aither_core::llm::ToolCall::new(
id,
"terminal",
serde_json::json!({
"description": "probe the permission path",
"script": "echo forked",
"mode": "unsafe",
"timeout": 30,
}),
))
}
fn drain(
seen: &async_channel::Receiver<(&'static str, LLMRequest)>,
) -> Vec<(&'static str, LLMRequest)> {
std::iter::from_fn(|| seen.try_recv().ok()).collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn a_forks_first_request_is_the_main_agents_request_then_the_fork_prompt() {
let fixture = ForkFixture::new().await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
main.then([
vec![
Event::ReasoningState(aither_core::llm::ReasoningState::new("test", "opaque")),
unsafe_terminal_call("call-1"),
],
vec![Event::Text("main answer".to_string())],
vec![Event::Text("fork answer".to_string())],
]);
let tool = fixture.tool(&main, &seen_tx);
let mut agent = fixture.main_agent(
main.clone(),
tool.fork_source(),
crate::ContextPolicy::default(),
);
agent.query("look into it").await.expect("main run");
let main_requests = drain(&seen_rx);
let (_, last_main) = main_requests.last().expect("the main agent sent requests");
assert_eq!(main_requests.len(), 2, "one tool round, then the answer");
let (dir, args) = start_fork("fork-first-request");
let result = Tool::call(&tool, args, ToolContext::new())
.await
.expect("fork call");
let text = result.render_for_model();
assert!(text.starts_with("Subagent 'fork' completed"), "{text}");
assert!(text.contains("fork answer"), "{text}");
let forked = drain(&seen_rx);
let [(model, first)] = forked.as_slice() else {
panic!("the fork sent one request, got {}", forked.len());
};
assert_eq!(*model, "main", "a fork runs on the main agent's model");
let shared = last_main.messages();
assert!(
shared.iter().any(|message| !message.reasoning().is_empty()),
"the inherited history carries the main agent's thinking"
);
assert_eq!(
&first.messages()[..shared.len()],
shared,
"the fork's request starts with the main agent's, unchanged"
);
let tail = &first.messages()[shared.len()..];
assert_eq!(tail.len(), 1, "and continues with the fork prompt alone");
assert!(
tail[0]
.content()
.starts_with("carry on from here\n\nSent at "),
"the fork prompt carries its time: {}",
tail[0].content()
);
assert_eq!(first.tool_definitions(), last_main.tool_definitions());
assert_eq!(
first.parameters().cache.openai,
last_main.parameters().cache.openai,
"the fork reads the main agent's cache"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fork_calling_compact_compacts_itself_and_leaves_the_main_agent_alone() {
use crate::compact_tool::CompactRequest;
let fixture = ForkFixture::new().await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
main.then([vec![Event::Text("main answer".to_string())]]);
let tool = fixture.tool(&main, &seen_tx);
let mut agent = fixture.main_agent(
main.clone(),
tool.fork_source(),
crate::ContextPolicy {
compaction_floor: 0,
..crate::ContextPolicy::default()
},
);
agent.query("look into it").await.expect("main run");
drain(&seen_rx);
main.then([
vec![Event::ToolCall(aither_core::llm::ToolCall::new(
"call-1",
"compact",
serde_json::json!({}),
))],
vec![Event::ToolCall(aither_core::llm::ToolCall::new(
"call-2",
"compact",
serde_json::json!({}),
))],
vec![Event::Text("fork answer".to_string())],
]);
let (dir, args) = start_fork("fork-compact");
Tool::call(&tool, args, ToolContext::new())
.await
.expect("fork call");
let requests = drain(&seen_rx);
let turns: Vec<_> = requests
.iter()
.filter(|(_, request)| !request.parameters().structured_outputs)
.collect();
let [_, (_, after_first), (_, after_second)] = turns.as_slice() else {
panic!("the fork sent three turns, got {}", turns.len());
};
let results = |request: &LLMRequest| {
request
.messages()
.iter()
.map(|message| message.content().to_string())
.collect::<Vec<_>>()
.join("\n")
};
assert!(
results(after_first).contains("Compaction started"),
"the first call started a compaction, not refused: {}",
results(after_first)
);
assert!(
results(after_second).contains("Nothing was started")
|| results(after_second).contains("nothing was started"),
"the second call found the fork's own compaction: {}",
results(after_second)
);
let signal = agent.compact_signal.as_ref().expect("main has the tool");
assert_eq!(
signal.request(),
CompactRequest::Started,
"the main agent's compaction state is untouched"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_forks_permission_request_reaches_the_main_agent_like_a_subagents() {
let fixture = ForkFixture::new().await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
main.then([vec![Event::Text("main answer".to_string())]]);
let tool = fixture.tool(&main, &seen_tx);
let mut agent = fixture.main_agent(
main.clone(),
tool.fork_source(),
crate::ContextPolicy::default(),
);
agent.query("look into it").await.expect("main run");
assert!(fixture.asked.lock().unwrap().is_empty());
let probe = || {
[
vec![unsafe_terminal_call("call-1")],
vec![Event::Text("finished".to_string())],
]
};
main.then(probe());
let (fork_dir, fork) = start_fork("fork-permission");
Tool::call(&tool, fork, ToolContext::new())
.await
.expect("fork call");
let asked_by_fork = std::mem::take(&mut *fixture.asked.lock().unwrap());
main.then(probe());
let (worker_dir, worker) = start_audit("worker-permission");
Tool::call(&tool, worker, ToolContext::new())
.await
.expect("worker call");
let asked_by_worker = std::mem::take(&mut *fixture.asked.lock().unwrap());
assert_eq!(
asked_by_fork,
[(
aither_sandbox::TerminalMode::Unsafe,
"echo forked".to_string()
)],
"the main agent's permission handler was asked"
);
assert_eq!(asked_by_fork, asked_by_worker);
drain(&seen_rx);
let _ = std::fs::remove_dir_all(fork_dir);
let _ = std::fs::remove_dir_all(worker_dir);
}
#[cfg(unix)]
async fn subagent_request_behind_reviewer(answer: &str) -> (usize, String, String) {
use crate::external_hook::tests::{logged, reviewers::reviewer};
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let fixture =
ForkFixture::reviewed(vec![reviewer(dir.path(), "guard", &log, answer)]).await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
let tool = fixture.tool(&main, &seen_tx);
main.then([
vec![unsafe_terminal_call("call-1")],
vec![Event::Text("finished".to_string())],
]);
let (worker_dir, worker) = start_audit("worker-reviewed");
Tool::call(&tool, worker, ToolContext::new())
.await
.expect("worker call");
let requests = drain(&seen_rx);
let (_, after_command) = requests.last().expect("the worker sent requests");
let seen_by_model = after_command
.messages()
.iter()
.map(|message| message.content().to_string())
.collect::<Vec<_>>()
.join("\n");
let reviewed = logged(&log);
assert_eq!(reviewed.len(), 1, "the reviewer saw the request once");
assert_eq!(reviewed[0]["role"], "subagent");
assert_eq!(reviewed[0]["script"], "echo forked");
let asked = fixture.asked.lock().unwrap().len();
let _ = std::fs::remove_dir_all(worker_dir);
(asked, reviewed[0].to_string(), seen_by_model)
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagents_request_every_reviewer_passes_reaches_the_main_agent() {
let (asked, _, _) = subagent_request_behind_reviewer(r#"{"decision":"pass"}"#).await;
assert_eq!(asked, 1, "the main agent's permission handler was asked");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_reviewer_approving_a_subagents_request_grants_it_without_asking() {
let (asked, _, seen) = subagent_request_behind_reviewer(r#"{"decision":"approve"}"#).await;
assert_eq!(asked, 0, "the main agent was not asked");
assert!(seen.contains("forked"), "the command ran: {seen}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_reviewer_denying_a_subagents_request_tells_its_model_why() {
let (asked, _, seen) =
subagent_request_behind_reviewer(r#"{"decision":"deny","reason":"no escalation"}"#)
.await;
assert_eq!(asked, 0, "the main agent was not asked");
assert!(
seen.contains("The permission reviewer guard denied this request: no escalation"),
"{seen}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fork_near_the_compaction_point_is_refused_until_the_main_agent_compacts() {
let fixture = ForkFixture::new().await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let big = "word ".repeat(40_000);
let probe = ScriptedLlm::new("main", &seen_tx);
let probe_tool = fixture.tool(&probe, &seen_tx);
fixture
.main_agent(
probe.clone(),
probe_tool.fork_source(),
crate::ContextPolicy::default(),
)
.query(&big)
.await
.expect("measuring run");
let usage = probe_tool
.fork_source()
.latest()
.expect("the measuring run published its request")
.usage();
let compact_at = usage / 0.95;
let policy = crate::ContextPolicy {
compact_at,
compact_ceiling: usize::MAX,
start_distance: 0,
safe_buffer: 0,
restore_budget: compact_at / 4.0,
..crate::ContextPolicy::default()
};
drain(&seen_rx);
let main = ScriptedLlm::new("main", &seen_tx);
main.then([
vec![Event::Text("main answer".to_string())],
vec![Event::Text("main answer again".to_string())],
vec![Event::Text("fork answer".to_string())],
]);
let tool = fixture.tool(&main, &seen_tx);
let mut agent = fixture.main_agent(main.clone(), tool.fork_source(), policy);
agent.query(&big).await.expect("main run");
drain(&seen_rx);
let spaces = || {
std::fs::read_dir(fixture.terminal.working_dir())
.unwrap()
.count()
};
let before = spaces();
let (dir, args) = start_fork("fork-refused");
let error = Tool::call(&tool, args.clone(), ToolContext::new())
.await
.expect_err("a fork this close to compaction is refused");
let text = error.to_string();
assert!(text.contains("Run `compact` first, then fork"), "{text}");
assert!(drain(&seen_rx).is_empty(), "nothing was sent to a model");
assert_eq!(spaces(), before, "no subagent terminal was launched");
assert!(tool.runs().list().is_empty());
agent.compact(None).await.expect("compaction");
agent
.query("continue")
.await
.expect("main run after compaction");
drain(&seen_rx);
let result = Tool::call(&tool, args, ToolContext::new())
.await
.expect("a fork after the compaction starts");
assert!(
result
.render_for_model()
.starts_with("Subagent 'fork' completed")
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn a_fork_is_refused_where_there_is_no_main_request_to_continue() {
let (seen_tx, _seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
let bundled = Bundled::new().await;
let tool = bundled.tool(main);
let (dir, args) = start_fork("fork-unbound");
let error = Tool::call(&tool, args, ToolContext::new())
.await
.expect_err("a tool bound to no terminal cannot fork");
assert!(error.to_string().contains("needs the terminal"), "{error}");
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fork_on_another_model_than_the_main_agents_is_refused() {
let fixture = ForkFixture::new().await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
main.then([vec![Event::Text("main answer".to_string())]]);
let other = ScriptedLlm::new("other", &seen_tx);
let tool = fixture.tool(&other, &seen_tx);
let mut agent = fixture.main_agent(
main.clone(),
tool.fork_source(),
crate::ContextPolicy::default(),
);
agent.query("look into it").await.expect("main run");
drain(&seen_rx);
let spaces = || {
std::fs::read_dir(fixture.terminal.working_dir())
.unwrap()
.count()
};
let before = spaces();
let (dir, args) = start_fork("fork-other-model");
let error = Tool::call(&tool, args, ToolContext::new())
.await
.expect_err("a fork on another model is refused");
let text = error.to_string();
assert!(
text.contains("'main'") && text.contains("'other'"),
"{text}"
);
assert!(drain(&seen_rx).is_empty(), "nothing was sent to a model");
assert_eq!(spaces(), before, "no subagent terminal was launched");
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
fn reported_task_id(request: &LLMRequest) -> String {
request
.messages()
.iter()
.rev()
.find_map(|message| {
let (_, rest) = message.content().split_once("task_id=")?;
Some(rest.split(')').next()?.to_string())
})
.unwrap_or_else(|| {
let contents: Vec<&str> = request
.messages()
.iter()
.map(aither_core::llm::Message::content)
.collect();
panic!("no terminal result reported a task id; messages: {contents:#?}")
})
}
#[cfg(unix)]
fn control_call(id: &str, name: &str, task_id: &str) -> Event {
Event::ToolCall(aither_core::llm::ToolCall::new(
id,
name,
serde_json::json!({ "task_id": task_id }),
))
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_forks_terminal_controls_reach_its_own_jobs_and_not_the_main_agents() {
let fixture = ForkFixture::new().await;
let (seen_tx, seen_rx) = async_channel::unbounded();
let main = ScriptedLlm::new("main", &seen_tx);
main.then([vec![Event::Text("main answer".to_string())]]);
let tool = fixture.tool(&main, &seen_tx);
let mut agent = fixture.main_agent(
main.clone(),
tool.fork_source(),
crate::ContextPolicy::default(),
);
agent.query("look into it").await.expect("main run");
let main_jobs = fixture.terminal.job_registry();
main_jobs
.register(
4242,
"main-job",
"exec-key",
"long running main job",
aither_sandbox::TerminalMode::Sandboxed,
None,
)
.await;
main.then([vec![Event::ToolCall(aither_core::llm::ToolCall::new(
"bg-1",
"terminal",
serde_json::json!({
"description": "start a job",
"script": "sleep 30",
"timeout": 60,
"background": true,
}),
))]]);
main.then_with(|request| {
vec![control_call(
"read-1",
"terminal_read",
&reported_task_id(request),
)]
});
main.then_with(|request| {
vec![control_call(
"kill-1",
"terminal_kill",
&reported_task_id(request),
)]
});
main.then([vec![control_call("kill-2", "terminal_kill", "main-job")]]);
main.then([vec![Event::Text("finished".to_string())]]);
let (dir, args) = start_fork("fork-controls");
Tool::call(&tool, args, ToolContext::new())
.await
.expect("fork call");
let requests = drain(&seen_rx);
let (_, last) = requests.last().expect("the fork sent requests");
let results: Vec<&str> = last
.messages()
.iter()
.filter_map(|message| match message {
aither_core::llm::Message::Tool { content, .. } => Some(content.as_str()),
_ => None,
})
.collect();
assert!(
results.iter().any(|text| text.contains("next cursor")),
"terminal_read read the fork's job: {results:?}"
);
assert!(
results.iter().any(|text| text.contains("terminated")),
"terminal_kill stopped the fork's job: {results:?}"
);
assert!(
results
.iter()
.any(|text| text.contains("No running background task 'main-job'")),
"the main agent's job is out of reach: {results:?}"
);
assert!(
main_jobs
.list()
.await
.iter()
.any(|job| job.task_id == "main-job"
&& job.status == aither_sandbox::JobStatus::Running),
"the main agent's job still runs"
);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(unix)]
#[tokio::test]
async fn a_subagents_actions_reach_hooks_with_the_subagent_role() {
use crate::external_hook::LifecycleKind;
use crate::external_hook::tests::{logged, recorder};
let hooks_dir = unique_temp_dir("subagent-hooks");
let tools = crate::test_support::prepared_fixture().await;
let log = hooks_dir.join("log");
let main = crate::external_hook::tests::lifecycle_hooks(
vec![recorder(
&hooks_dir,
&log,
&[
LifecycleKind::SessionStart,
LifecycleKind::UserMessage,
LifecycleKind::Stop,
LifecycleKind::SubagentStart,
LifecycleKind::SubagentStop,
],
)],
&tools,
)
.await;
let bundled = Bundled::new().await;
let tool = bundled
.tool(TextLlm::new("only-model"))
.with_hooks(main.clone());
let (dir, prompt_file) = write_prompt_file("subagent-hooks", "do it");
tokio::time::timeout(
std::time::Duration::from_secs(60),
Tool::call(&tool, explore(&prompt_file), ToolContext::new()),
)
.await
.expect("the subagent finishes within its bound")
.expect("the subagent completes");
let seen: Vec<(String, String)> = logged(&log)
.iter()
.map(|input| {
(
input["event"].as_str().unwrap().to_string(),
input["role"].as_str().unwrap().to_string(),
)
})
.collect();
let expected = [
("subagent_start", "main"),
("session_start", "subagent"),
("user_message", "subagent"),
("stop", "subagent"),
("subagent_stop", "main"),
]
.map(|(event, role)| (event.to_string(), role.to_string()));
assert_eq!(seen, expected);
let inputs = logged(&log);
assert_eq!(inputs[0]["subagent"], "explore");
assert_eq!(inputs[0]["prompt"], "do it");
assert_eq!(inputs[4]["end"], "completed");
assert_eq!(inputs[4]["result"], "only-model");
let injected = crate::Hook::take_injected_context(&main);
assert_eq!(injected.len(), 2);
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(hooks_dir);
}
type EventLog = Arc<Mutex<Vec<String>>>;
#[derive(Debug, thiserror::Error)]
#[error("backend refused: {0}")]
struct BackendError(String);
struct TestBackend {
log: EventLog,
opened: Arc<AtomicU64>,
}
struct TestSession {
number: u64,
turns: u64,
log: EventLog,
}
impl TestSession {
fn record(&self, event: String) {
self.log.lock().expect("log lock").push(event);
}
}
impl ExternalSubagent for TestBackend {
type Session = TestSession;
type Error = BackendError;
fn open(
&self,
start: ExternalStart<'_>,
) -> impl Future<Output = Result<TestSession, BackendError>> + Send {
let number = self.opened.fetch_add(1, Ordering::Relaxed);
self.log
.lock()
.expect("log lock")
.push(format!("open {number} in {}", start.working_dir.display()));
std::future::ready(Ok(TestSession {
number,
turns: 0,
log: self.log.clone(),
}))
}
}
impl crate::specialized::ExternalSession for TestSession {
type Error = BackendError;
async fn prompt(&mut self, prompt: &str) -> Result<String, BackendError> {
self.turns += 1;
self.record(format!("prompt {} {prompt}", self.number));
match prompt {
"hang" => std::future::pending().await,
"fail" => Err(BackendError("fail".to_string())),
_ => Ok(format!(
"turn {} of session {}: {prompt}",
self.turns, self.number
)),
}
}
async fn cancel(&mut self) {
self.record(format!("cancel {}", self.number));
}
async fn close(self) {
self.record(format!("close {}", self.number));
}
fn model(&self) -> Option<String> {
Some("external-model".to_string())
}
}
fn external_tool(dir: &Path) -> (SubagentTool<PendingLlm>, SubagentRuns, EventLog) {
let log = EventLog::default();
let runs = SubagentRuns::default();
let tool = SubagentTool::new(PendingLlm, dir.join("global"))
.with_base_dir(dir)
.with_runs(runs.clone())
.with_external(
"outside",
"runs outside aither",
TestBackend {
log: log.clone(),
opened: Arc::default(),
},
);
(tool, runs, log)
}
fn external_start(agent: &str, prompt_file: &Path) -> SubagentArgs {
SubagentArgs {
agent: Some(agent.to_string()),
..named("external", prompt_file)
}
}
fn events(log: &EventLog) -> Vec<String> {
log.lock().expect("log lock").clone()
}
async fn call_text(
tool: &SubagentTool<PendingLlm>,
args: SubagentArgs,
) -> aither_core::Result<String> {
match Tool::call(tool, args, ToolContext::new()).await? {
ToolResult::Text { text } => Ok(text),
other => panic!("expected a text result, got {other:?}"),
}
}
#[cfg(feature = "languages")]
#[tokio::test]
async fn a_prompt_not_in_the_working_language_is_refused() {
let (dir, chinese) =
write_prompt_file("language-refused", "请检查数据库迁移脚本是否正确。");
let english = dir.join("english.txt");
std::fs::write(
&english,
"Check that the database migration script is correct.",
)
.expect("write prompt file");
let (tool, _runs, _log) = external_tool(&dir);
let tool = tool.with_languages(crate::LanguageGuard::new(crate::Languages::new(
"Chinese".parse().unwrap(),
)));
let error = call_text(&tool, external_start("outside", &chinese))
.await
.expect_err("a Chinese prompt is refused");
assert!(error.to_string().contains("English"), "{error}");
call_text(&tool, external_start("outside", &english))
.await
.expect("an English prompt starts");
}
#[tokio::test]
async fn external_subagent_starts_and_resumes_the_same_session() {
let (dir, first) = write_prompt_file("external-resume", "first");
let second = dir.join("second.txt");
std::fs::write(&second, "second").expect("write prompt file");
let (tool, runs, log) = external_tool(&dir);
let text = call_text(&tool, external_start("outside", &first))
.await
.expect("start succeeds");
assert!(text.contains("turn 1 of session 0: first"), "{text}");
assert!(text.contains("(model: external-model)"), "{text}");
assert!(!text.contains("keep-alives"), "{text}");
assert!(!text.contains("prompt cache"), "{text}");
assert!(runs.list().is_empty());
let id = continuation_id(&text);
let text = call_text(&tool, resume_args(&second, id))
.await
.expect("resume succeeds");
assert!(text.contains("turn 2 of session 0: second"), "{text}");
assert_eq!(continuation_id(&text), id);
assert_eq!(
events(&log),
[
format!("open 0 in {}", dir.display()),
"prompt 0 first".to_string(),
"prompt 0 second".to_string(),
]
);
assert!(
tool.usage()
.await
.ends_with("--prompt-file <path>`:\n- outside: runs outside aither"),
"the usage lists the connected agent"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn an_agent_that_is_not_connected_is_refused_with_the_connected_ones() {
let (dir, prompt_file) = write_prompt_file("external-unknown", "first");
let (tool, _runs, log) = external_tool(&dir);
let error = call_text(&tool, external_start("elsewhere", &prompt_file))
.await
.expect_err("an unknown agent is refused");
assert_eq!(
error.to_string(),
"no external agent 'elsewhere' is connected; connected: outside"
);
assert!(events(&log).is_empty(), "no session was opened");
let error = call_text(
&SubagentTool::new(PendingLlm, dir.join("global")).with_base_dir(&dir),
external_start("outside", &prompt_file),
)
.await
.expect_err("no agent is connected");
assert!(
error
.to_string()
.starts_with("no external agent is connected"),
"{error}"
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn external_subagent_run_can_be_cancelled() {
let (dir, prompt_file) = write_prompt_file("external-cancel", "hang");
let (tool, runs, log) = external_tool(&dir);
let call =
tokio::spawn(
async move { call_text(&tool, external_start("outside", &prompt_file)).await },
);
let run = loop {
match runs.list().as_slice() {
[run] => break run.clone(),
[] => tokio::task::yield_now().await,
other => panic!("expected one registered run, got {}", other.len()),
}
};
assert_eq!(run.subagent, "outside");
assert!(runs.cancel(run.id));
let text = call
.await
.expect("call task panicked")
.expect("a cancelled run is a result");
assert!(text.contains("was cancelled"), "{text}");
assert!(runs.list().is_empty());
assert_eq!(
events(&log),
[
format!("open 0 in {}", dir.display()),
"prompt 0 hang".to_string(),
"cancel 0".to_string(),
"close 0".to_string(),
]
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn external_subagent_prompt_error_closes_the_session() {
let (dir, prompt_file) = write_prompt_file("external-error", "fail");
let (tool, runs, log) = external_tool(&dir);
let error = call_text(&tool, external_start("outside", &prompt_file))
.await
.expect_err("a failed turn is an error");
assert!(
error.to_string().contains("backend refused: fail"),
"{error}"
);
assert!(runs.list().is_empty());
assert_eq!(
events(&log),
[
format!("open 0 in {}", dir.display()),
"prompt 0 fail".to_string(),
"close 0".to_string(),
]
);
let _ = std::fs::remove_dir_all(dir);
}
#[tokio::test]
async fn external_subagent_needs_a_working_directory() {
let (dir, prompt_file) = write_prompt_file("external-no-dir", "first");
let tool = SubagentTool::new(PendingLlm, dir.join("global")).with_external(
"outside",
"runs outside aither",
TestBackend {
log: EventLog::default(),
opened: Arc::default(),
},
);
let error = call_text(&tool, external_start("outside", &prompt_file))
.await
.expect_err("no working directory is an error");
assert!(error.to_string().contains("working directory"), "{error}");
let _ = std::fs::remove_dir_all(dir);
}
const WRITE_PROBE: &str = "write probe";
#[derive(Clone)]
struct WritingLlm {
workspace: PathBuf,
}
impl WritingLlm {
fn script(&self) -> String {
[
"touch scratch.txt && echo scratch-written".to_string(),
format!(
"touch '{}' || echo workspace-refused",
self.workspace.join("probe.txt").display()
),
format!(
"touch '{}' || echo granted-refused",
self.workspace.join("granted").join("probe.txt").display()
),
]
.join("; ")
}
}
impl LanguageModel for WritingLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
let event = if request.parameters().structured_outputs {
Event::Text(ROUTE_FAST.to_string())
} else {
match request.messages().last() {
Some(aither_core::llm::Message::Tool { content, .. }) => {
Event::Text(content.clone())
}
Some(message) if message.content().contains(WRITE_PROBE) => {
Event::ToolCall(aither_core::llm::ToolCall::new(
"write-1",
"terminal",
serde_json::json!({
"description": "write probe",
"script": self.script(),
"timeout": 30,
}),
))
}
_ => Event::Text("ok".to_string()),
}
};
futures_lite::stream::iter([Ok(event)])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
"writing",
"test",
"writing-model",
"writes the workspace",
1_000_000,
)))
}
}
fn spaces_written(workspace: &Path) -> usize {
std::fs::read_dir(workspace.join("subagent-spaces"))
.expect("a subagent ran, so the spaces directory exists")
.map(|entry| entry.expect("a space entry reads").path())
.filter(|space| space.join("scratch.txt").is_file())
.count()
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn read_only_subagents_write_only_their_scratch_directory_and_writers_their_grants() {
let fixture = ForkFixture::new().await;
let workspace = std::fs::canonicalize(fixture.terminal.working_dir()).unwrap();
let granted = workspace.join("granted");
std::fs::create_dir_all(&granted).unwrap();
let local = workspace.join(crate::LOCAL_SUBAGENTS_DIR);
write_definition(&local, "helper", Some("fast"), "read_only", "You help.");
write_definition(&local, "writer", Some("fast"), "worktrees", "You write.");
let llm = WritingLlm {
workspace: workspace.clone(),
};
let tool = SubagentTool::new(llm.clone(), fixture.bundled.global())
.for_terminal(fixture.terminal.binding());
let mut main = fixture.main_agent(llm, tool.fork_source(), crate::ContextPolicy::default());
main.query("look around").await.expect("main run");
let (dir, prompt_file) = write_prompt_file("read-only-writes", WRITE_PROBE);
let read_only = [
"explore", "research", "audit", "review", "plan", "helper", "fork",
];
let mut runs = 0;
for subagent in read_only {
runs += 1;
let text = completed_text(&tool, named(subagent, &prompt_file)).await;
assert!(text.contains("scratch-written"), "{subagent}: {text}");
assert!(text.contains("workspace-refused"), "{subagent}: {text}");
assert!(text.contains("granted-refused"), "{subagent}: {text}");
assert!(
!workspace.join("probe.txt").exists(),
"{subagent} wrote the workspace"
);
assert!(
!granted.join("probe.txt").exists(),
"{subagent} wrote the workspace"
);
assert_eq!(
spaces_written(&workspace),
runs,
"{subagent} wrote its scratch directory"
);
}
for subagent in ["general", "writer", "fork"] {
runs += 1;
let text = completed_text(
&tool,
SubagentArgs {
worktrees: vec![granted.to_string_lossy().into_owned()],
..named(subagent, &prompt_file)
},
)
.await;
assert!(text.contains("workspace-refused"), "{subagent}: {text}");
assert!(!text.contains("granted-refused"), "{subagent}: {text}");
assert!(
!workspace.join("probe.txt").exists(),
"{subagent} wrote ungranted workspace"
);
assert!(
granted.join("probe.txt").exists(),
"{subagent} writes its grant"
);
std::fs::remove_file(granted.join("probe.txt")).unwrap();
assert_eq!(spaces_written(&workspace), runs);
}
assert!(
fixture.asked.lock().unwrap().is_empty(),
"nothing asked to escalate"
);
let _ = std::fs::remove_dir_all(dir);
}
const PROBE: &str = "run the probe";
#[derive(Clone)]
struct ProbingLlm {
script: &'static str,
seen: async_channel::Sender<String>,
}
impl LanguageModel for ProbingLlm {
type Error = NeverError;
fn respond(
&self,
request: LLMRequest,
) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
let event = if request.parameters().structured_outputs {
Event::Text(ROUTE_FAST.to_string())
} else {
self.seen
.try_send(serde_json::to_string(request.messages()).unwrap())
.unwrap();
let probe_result = request
.messages()
.iter()
.rev()
.take_while(|message| {
!matches!(message, aither_core::llm::Message::User { .. })
})
.find_map(|message| match message {
aither_core::llm::Message::Tool { content, .. } => Some(content.clone()),
_ => None,
});
match (probe_result, request.messages().last()) {
(Some(content), _) => Event::Text(content),
(None, Some(message)) if message.content().contains(PROBE) => {
Event::ToolCall(aither_core::llm::ToolCall::new(
"probe-1",
"terminal",
serde_json::json!({
"description": "probe",
"script": self.script,
"timeout": 30,
}),
))
}
_ => Event::Text("ok".to_string()),
}
};
futures_lite::stream::iter([Ok(event)])
}
fn profile(
&self,
) -> impl std::future::Future<Output = Result<ModelProfile, Self::Error>> + Send {
std::future::ready(Ok(ModelProfile::new(
"probing",
"test",
"probing-model",
"runs a probe",
1_000_000,
)))
}
}
const COMMAND_PROBE: &str = "if command -v subagent >/dev/null 2>&1; then echo has-subagent; else echo no-subagent; fi; subagent 2>&1; true";
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagent_has_no_subagent_command_and_a_bare_call_lists_the_names() {
let (seen_tx, _seen_rx) = async_channel::unbounded();
let llm = ProbingLlm {
script: COMMAND_PROBE,
seen: seen_tx,
};
let bundled = Bundled::new().await;
let shared = Arc::new(SubagentTool::new(llm.clone(), bundled.global()));
let bound = shared.clone();
let fixture = ForkFixture::build(Vec::new(), bundled, move |registry| {
registry.main_exclusive(|main| {
main.configure_terminal_bound_usage_tool("subagent", move |binding| {
bound.for_terminal(binding)
});
});
})
.await;
let tool = shared.for_terminal(fixture.terminal.binding());
let mut main = fixture.main_agent(llm, tool.fork_source(), crate::ContextPolicy::default());
let answer = main.query(PROBE).await.expect("main run");
assert!(
answer.contains("has-subagent"),
"the main agent has the command: {answer}"
);
assert!(
answer.contains("missing required argument: name\n\nName the subagent to run"),
"a bare `subagent` lists the names: {answer}"
);
for name in ["explore", "general", "fork"] {
assert!(answer.contains(&format!("\n- {name}: ")), "{answer}");
}
let (dir, prompt_file) = write_prompt_file("nesting", PROBE);
for subagent in ["explore", "fork"] {
let text = completed_text(&tool, named(subagent, &prompt_file)).await;
assert!(
text.contains("no-subagent"),
"{subagent} has no `subagent` command: {text}"
);
assert!(
!text.contains("Name the subagent to run"),
"{subagent} reached no `subagent` command: {text}"
);
}
let _ = std::fs::remove_dir_all(dir);
}
const TASKS_PROBE: &str = "printf '%s\\n' '- [x] SUBAGENT-TASK' > tasks.md && echo written";
fn subagent_tasks(workspace: &Path) -> Vec<String> {
std::fs::read_dir(workspace.join("subagent-spaces"))
.unwrap()
.filter_map(|entry| {
std::fs::read_to_string(entry.unwrap().path().join("tasks.md")).ok()
})
.collect()
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn a_subagent_keeps_its_own_tasks_md_and_never_touches_its_parents() {
let fixture = ForkFixture::new().await;
let workspace = std::fs::canonicalize(fixture.terminal.working_dir()).unwrap();
let parent_tasks = workspace.join("tasks.md");
std::fs::write(&parent_tasks, "- [x] PARENT-TASK\n").unwrap();
let (seen_tx, seen_rx) = async_channel::unbounded();
let llm = ProbingLlm {
script: TASKS_PROBE,
seen: seen_tx,
};
let tool = SubagentTool::new(llm.clone(), fixture.bundled.global())
.for_terminal(fixture.terminal.binding());
let mut main = fixture.main_agent(llm, tool.fork_source(), crate::ContextPolicy::default());
main.query("look around").await.expect("main run");
let main_requests: Vec<String> = std::iter::from_fn(|| seen_rx.try_recv().ok()).collect();
let parent_marks = main_requests
.last()
.expect("the main agent sent a request")
.matches("PARENT-TASK")
.count();
assert!(parent_marks > 0, "the main agent sees its own tasks.md");
let (dir, prompt_file) = write_prompt_file("subagent-tasks", PROBE);
for (run, subagent) in (1..).zip(["explore", "fork"]) {
let text = completed_text(&tool, named(subagent, &prompt_file)).await;
assert!(text.contains("written"), "{subagent}: {text}");
let requests: Vec<String> = std::iter::from_fn(|| seen_rx.try_recv().ok()).collect();
let [first, after_write] = requests.as_slice() else {
panic!("{subagent} sent two requests, got {}", requests.len());
};
let inherited = if subagent == "fork" { parent_marks } else { 0 };
assert_eq!(
first.matches("PARENT-TASK").count(),
inherited,
"{subagent} does not read its parent's tasks.md"
);
assert!(
after_write.contains("SUBAGENT-TASK"),
"{subagent}'s own tasks.md reaches its context: {after_write}"
);
assert_eq!(
std::fs::read_to_string(&parent_tasks).unwrap(),
"- [x] PARENT-TASK\n",
"{subagent} left its parent's tasks.md alone"
);
assert_eq!(
subagent_tasks(&workspace),
vec!["- [x] SUBAGENT-TASK\n".to_string(); run],
"{subagent} wrote tasks.md in its own space"
);
}
let _ = std::fs::remove_dir_all(dir);
}
}