use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use {
crate::agent::AgentDefinition,
crate::app::{
agent_executor::{AgentExecutor, AgentLaunchRequest, AgentRunHandle},
subagent_host_input::{SubagentHostInputBridge, SubagentHostInputRequest},
subagent_messaging::{SubagentNotice, SubagentNoticeBridge},
subagent_pool::{child_events, ChildObserver, StartedSubagent, SubagentPool},
},
crate::session::SessionPersistence,
crate::subagent::{self, RunStatus},
};
pub(crate) use super::subagent_messaging::ValidatedMessage;
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone, Debug)]
pub struct SubagentSnapshot {
pub id: String,
pub agent_id: String,
pub title: Option<String>,
pub elapsed: Duration,
pub status: RunStatus,
pub done: bool,
pub prior_notices: Vec<String>,
pub persistence: SessionPersistence,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct BackgroundChild {
pub(crate) run: String,
pub(crate) title: String,
pub(crate) session: Option<rho_sdk::SessionId>,
pub(crate) state: subagent::RunState,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct SubagentTaskIdentity {
pub run_id: String,
pub agent_id: String,
pub task: String,
}
struct AgentEntry {
agent_id: String,
task_fallback: Option<String>,
started: Instant,
handle: AgentRunHandle,
session_id: String,
persistence: SessionPersistence,
observed: bool,
explicitly_observed: bool,
}
impl AgentEntry {
fn display_title(&self, title: Option<String>) -> String {
title
.filter(|title| !title.trim().is_empty())
.or_else(|| self.task_fallback.clone())
.unwrap_or_else(|| "Delegated task".into())
}
fn snapshot(&self, id: &str) -> SubagentSnapshot {
let status = self.handle.status();
let elapsed = status
.elapsed_duration(subagent::unix_now_secs())
.unwrap_or_else(|| self.started.elapsed());
SubagentSnapshot {
id: id.to_string(),
agent_id: self.agent_id.clone(),
title: status.title.clone(),
elapsed,
done: self.handle.is_complete() && status.state.is_terminal(),
status,
prior_notices: Vec::new(),
persistence: self.persistence,
}
}
}
#[derive(Clone, Debug)]
pub struct SubagentNotification {
pub snapshot: SubagentSnapshot,
}
#[derive(Clone)]
pub struct SubagentManager {
inner: Arc<Mutex<HashMap<String, AgentEntry>>>,
executor: AgentExecutor,
ended: Arc<tokio::sync::Notify>,
started: Arc<tokio::sync::Notify>,
parent: Arc<Mutex<ParentBinding>>,
observer: Option<Arc<dyn ChildObserver>>,
}
#[derive(Clone)]
struct ParentBinding {
placement: subagent::RunPlacement,
workspace: Option<PathBuf>,
persistence: SessionPersistence,
}
impl SubagentManager {
pub(crate) fn new(
config: crate::config::Config,
config_path: PathBuf,
cwd: PathBuf,
pool: SubagentPool,
) -> Self {
let (concurrency, observer) = pool.into_parts(config.agent_concurrency);
Self {
inner: Arc::new(Mutex::new(HashMap::new())),
executor: AgentExecutor::new(
config,
config_path,
cwd,
concurrency,
SubagentHostInputBridge::new(),
SubagentNoticeBridge::new(),
),
ended: Arc::new(tokio::sync::Notify::new()),
started: Arc::new(tokio::sync::Notify::new()),
parent: Arc::new(Mutex::new(ParentBinding {
placement: subagent::RunPlacement::parentless(),
workspace: None,
persistence: SessionPersistence::Saved,
})),
observer,
}
}
pub(crate) fn with_environment(
mut self,
environment: crate::session_environment::SessionEnvironment,
) -> Self {
self.executor = self.executor.with_environment(environment);
self
}
pub(crate) fn bind_host_input(&self) -> tokio::sync::mpsc::Receiver<SubagentHostInputRequest> {
self.executor.host_input().bind_parent()
}
pub(crate) fn unbind_host_input(&self) {
self.executor.host_input().unbind_parent();
}
pub(crate) fn bind_host_input_to(
&self,
sender: tokio::sync::mpsc::Sender<SubagentHostInputRequest>,
) {
self.executor.host_input().bind_parent_to(sender);
}
pub(crate) fn rebind_notices(
&self,
old_receiver: Option<tokio::sync::mpsc::Receiver<SubagentNotice>>,
) -> crate::app::subagent_messaging::NoticeRebind {
self.executor.notices().rebind_parent(old_receiver)
}
pub(crate) fn unbind_notices(&self) {
self.executor.notices().unbind_parent();
}
pub(crate) fn bind_parent_session(
&self,
session_id: impl Into<String>,
storage: Option<&crate::session::Session>,
persistence: SessionPersistence,
) {
*self.parent.lock().expect("delegated session lock") = ParentBinding {
placement: subagent::RunPlacement::for_parent_session(
session_id,
storage.and_then(crate::session::Session::subagents_dir),
),
workspace: storage.map(|stored| stored.cwd().to_path_buf()),
persistence,
};
}
pub fn update_selection(
&self,
provider: &str,
model: &str,
reasoning: rho_sdk::ReasoningLevel,
auth: &str,
) {
self.executor
.update_selection(provider, model, reasoning, auth);
}
pub(crate) fn update_permission_mode(&self, mode: crate::permission::PermissionMode) {
self.executor.update_permission_mode(mode);
}
pub(crate) fn update_added_dirs(&self, added_dirs: crate::added_dirs::AddedDirs) {
self.executor.update_added_dirs(added_dirs);
}
pub(crate) async fn spawn(
&self,
definition: &AgentDefinition,
prompt: &str,
cwd: &Path,
model_override: Option<&str>,
) -> anyhow::Result<(String, PathBuf)> {
let ParentBinding {
placement,
workspace: parent_workspace,
persistence,
} = self.parent.lock().expect("delegated session lock").clone();
let Some(session_id) = placement.parent_session_id().map(str::to_owned) else {
anyhow::bail!("could not start subagent: no parent session is bound");
};
let parent_session_id = rho_sdk::SessionId::from_string(session_id.clone())
.map_err(|error| anyhow::anyhow!("could not start subagent: {error}"))?;
let run_cwd = cwd.to_path_buf();
let (id, directory) = tokio::task::spawn_blocking(move || {
subagent::reserve_run_directory(&placement, &run_cwd)
})
.await??;
let output_file = directory.join(subagent::RESULT_FILE_NAME);
let (events, followed) = child_events(self.observer.as_ref());
let launch = AgentLaunchRequest {
definition: Arc::new(definition.clone()),
model_override: model_override.map(str::to_owned),
prompt: prompt.to_string(),
run_id: id.clone(),
parent_session_id,
parent_workspace,
persistence,
output_file,
events,
};
let handle = match self.executor.spawn(launch) {
Ok(handle) => handle,
Err(error) => {
let cleanup_id = id.clone();
let cleanup_directory = directory.clone();
let cleanup = tokio::task::spawn_blocking(move || {
subagent::release_run_directory(&cleanup_id, &cleanup_directory)
})
.await?;
if let Err(cleanup_error) = cleanup {
return Err(anyhow::anyhow!(
"{error}; failed to clean up delegated run reservation: {cleanup_error}"
));
}
return Err(error);
}
};
if let Some(observer) = &self.observer {
observer.subagent_started(StartedSubagent::of(
id.clone(),
cwd.to_path_buf(),
&handle,
followed,
));
}
let mut ending = handle.clone();
self.inner.lock().expect("delegated registry lock").insert(
id.clone(),
AgentEntry {
agent_id: definition.id.to_string(),
task_fallback: prompt
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.map(str::to_owned),
started: Instant::now(),
handle,
session_id,
persistence,
observed: false,
explicitly_observed: false,
},
);
self.started.notify_waiters();
let ended = Arc::clone(&self.ended);
tokio::spawn(async move {
ending.wait().await;
ended.notify_waiters();
});
Ok((id, directory.join(subagent::LOG_FILE_NAME)))
}
#[cfg(test)]
pub(crate) fn insert_completed_for_test(
&self,
id: &str,
session_id: &str,
total_cost_usd: Option<f64>,
) {
self.insert_completed_status_for_test(
id,
session_id,
crate::subagent::RunStatus {
state: crate::subagent::RunState::Ok,
total_cost_usd,
..crate::subagent::RunStatus::default()
},
);
}
#[cfg(test)]
pub(crate) fn insert_completed_status_for_test(
&self,
id: &str,
session_id: &str,
status: crate::subagent::RunStatus,
) {
self.insert_handle_for_test(id, session_id, AgentRunHandle::completed_for_test(status));
}
#[cfg(test)]
pub(crate) fn post_notice_for_test(&self, notice: SubagentNotice) {
self.executor.notices().post(notice).unwrap();
}
#[cfg(test)]
pub(crate) fn insert_handle_for_test(
&self,
id: &str,
session_id: &str,
handle: AgentRunHandle,
) {
let _delivery = super::notification_delivery::lock();
self.inner.lock().expect("delegated registry lock").insert(
id.to_string(),
AgentEntry {
agent_id: "fixture".into(),
task_fallback: None,
started: Instant::now(),
handle,
session_id: session_id.into(),
persistence: SessionPersistence::Saved,
observed: false,
explicitly_observed: false,
},
);
}
pub(crate) fn status(&self, id: &str) -> Option<SubagentSnapshot> {
let id = crate::subagent::normalize_id(id).ok()?;
self.inner
.lock()
.expect("delegated registry lock")
.get(&id)
.map(|entry| entry.snapshot(&id))
}
pub fn list(&self) -> Vec<SubagentSnapshot> {
let entries = self.inner.lock().expect("delegated registry lock");
let mut snapshots = entries
.iter()
.map(|(id, entry)| entry.snapshot(id))
.collect::<Vec<_>>();
snapshots.sort_by_key(|snapshot| std::cmp::Reverse(snapshot.elapsed));
snapshots
}
pub(crate) fn task_identity(&self, id: &str) -> Option<SubagentTaskIdentity> {
let id = crate::subagent::normalize_id(id).ok()?;
let entries = self.inner.lock().expect("delegated registry lock");
let entry = entries.get(&id)?;
let task = entry.display_title(entry.handle.status().title);
Some(SubagentTaskIdentity {
run_id: id,
agent_id: entry.agent_id.clone(),
task,
})
}
#[cfg(test)]
pub fn has_running_for_session(&self, session_id: &str) -> bool {
self.inner
.lock()
.expect("delegated registry lock")
.values()
.any(|entry| entry.session_id == session_id && !entry.handle.is_complete())
}
pub(crate) fn has_running(&self, session_id: &str) -> bool {
self.inner
.lock()
.expect("delegated registry lock")
.iter()
.any(|(id, entry)| {
entry.session_id == session_id && !entry.observed && !entry.snapshot(id).done
})
}
pub fn has_active_or_pending_notification(&self, session_id: &str) -> bool {
self.inner
.lock()
.expect("delegated registry lock")
.values()
.any(|entry| entry.session_id == session_id && !entry.observed)
}
pub(crate) fn has_pending_notification(&self, session_id: &str) -> bool {
self.inner
.lock()
.expect("delegated registry lock")
.iter()
.any(|(id, entry)| {
entry.session_id == session_id && !entry.observed && entry.snapshot(id).done
})
}
pub(crate) fn undelivered_notices(&self, session_id: &str) -> Vec<SubagentNotice> {
self.executor.notices().undelivered(session_id)
}
pub(crate) fn parent_wake(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
let ended = Arc::clone(&self.ended).notified_owned();
let posted = self.executor.notices().posted();
async move {
tokio::select! {
() = ended => {}
() = posted => {}
}
}
}
pub(crate) fn changed(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
let started = Arc::clone(&self.started).notified_owned();
let ended = Arc::clone(&self.ended).notified_owned();
async move {
tokio::select! {
() = started => {}
() = ended => {}
}
}
}
pub(crate) fn background(&self, session_id: &str) -> Vec<BackgroundChild> {
let entries = self.inner.lock().expect("delegated registry lock");
let mut children: Vec<_> = entries
.iter()
.filter(|(_, entry)| entry.session_id == session_id && !entry.observed)
.map(|(id, entry)| {
let status = entry.handle.status();
let title = entry.display_title(status.title);
let state = if entry.handle.is_complete() {
status.state
} else {
subagent::RunState::Running
};
(
entry.started,
BackgroundChild {
run: id.clone(),
title,
session: entry.handle.session().cloned(),
state,
},
)
})
.collect();
children.sort_by(|(left, a), (right, b)| left.cmp(right).then_with(|| a.run.cmp(&b.run)));
children.into_iter().map(|(_, child)| child).collect()
}
pub(crate) fn cancel(&self, session_id: &str, id: &str) -> anyhow::Result<()> {
let entries = self.inner.lock().expect("delegated registry lock");
let entry = entries
.get(id)
.filter(|entry| entry.session_id == session_id)
.ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?;
if entry.handle.is_complete() {
anyhow::bail!("delegated run '{id}' already ended");
}
entry.handle.cancel();
Ok(())
}
pub(crate) async fn wait_for_notification(&self, session_id: &str) {
let handles = {
let entries = self.inner.lock().expect("delegated registry lock");
entries
.values()
.filter(|entry| entry.session_id == session_id && !entry.observed)
.map(|entry| entry.handle.clone())
.collect::<Vec<_>>()
};
let mut waits = handles
.into_iter()
.map(|mut handle| async move { handle.wait().await })
.collect::<futures_util::stream::FuturesUnordered<_>>();
if futures_util::StreamExt::next(&mut waits).await.is_none() {
std::future::pending::<()>().await;
}
}
pub fn take_notifications(&self, session_id: &str) -> Vec<SubagentNotification> {
let mut entries = self.inner.lock().expect("delegated registry lock");
let mut notifications = entries
.iter_mut()
.filter_map(|(id, entry)| {
if entry.observed || entry.session_id != session_id {
return None;
}
let snapshot = entry.snapshot(id);
snapshot.done.then(|| {
entry.observed = true;
(entry.started, SubagentNotification { snapshot })
})
})
.collect::<Vec<_>>();
notifications.sort_by(|(a_started, a), (b_started, b)| {
a_started
.cmp(b_started)
.then_with(|| a.snapshot.id.cmp(&b.snapshot.id))
});
notifications
.into_iter()
.map(|(_, notification)| notification)
.collect()
}
pub fn restore_notifications(&self, notifications: &[SubagentNotification]) {
if notifications.is_empty() {
return;
}
let mut entries = self.inner.lock().expect("delegated registry lock");
for notification in notifications {
let Some(entry) = entries.get_mut(¬ification.snapshot.id) else {
continue;
};
let snapshot = entry.snapshot(¬ification.snapshot.id);
if snapshot.done && entry.observed && !entry.explicitly_observed {
entry.observed = false;
}
}
}
pub fn observe(&self, id: &str) -> Option<SubagentSnapshot> {
let id = crate::subagent::normalize_id(id).ok()?;
let _delivery = super::notification_delivery::lock();
let mut entries = self.inner.lock().expect("delegated registry lock");
let entry = entries.get_mut(&id)?;
let mut snapshot = entry.snapshot(&id);
if snapshot.done {
snapshot.prior_notices = self
.executor
.notices()
.pending_for_run(&id)
.into_iter()
.map(|notice| {
notice.acknowledge();
notice.message
})
.collect();
entry.observed = true;
entry.explicitly_observed = true;
}
Some(snapshot)
}
#[cfg(test)]
pub async fn wait_done(&self, id: &str) -> Option<SubagentSnapshot> {
let id = crate::subagent::normalize_id(id).ok()?;
let mut handle = self
.inner
.lock()
.expect("delegated registry lock")
.get(&id)?
.handle
.clone();
handle.wait().await;
self.status(&id)
}
pub async fn stop(&self, id: &str) -> anyhow::Result<SubagentSnapshot> {
let id = crate::subagent::normalize_id(id)?;
let mut handle = self
.inner
.lock()
.expect("delegated registry lock")
.get(&id)
.ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?
.handle
.clone();
handle.cancel();
tokio::time::timeout(SHUTDOWN_TIMEOUT, handle.wait())
.await
.map_err(|_| anyhow::anyhow!("timed out stopping delegated run '{id}'"))?;
self.observe(&id)
.ok_or_else(|| anyhow::anyhow!("delegated run '{id}' disappeared"))
}
pub(crate) async fn message(&self, id: &str, message: &ValidatedMessage) -> anyhow::Result<()> {
let id = crate::subagent::normalize_id(id)?;
let handle = self
.inner
.lock()
.expect("delegated registry lock")
.get(&id)
.ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?
.handle
.clone();
handle.message_from_parent(message).await
}
pub async fn shutdown(&self) {
let handles = self
.inner
.lock()
.expect("delegated registry lock")
.values()
.map(|entry| entry.handle.clone())
.collect::<Vec<_>>();
for handle in &handles {
handle.cancel();
}
let waits = handles.into_iter().map(|mut handle| async move {
handle.wait().await;
});
let _ = tokio::time::timeout(SHUTDOWN_TIMEOUT, futures_util::future::join_all(waits)).await;
}
}
#[cfg(test)]
#[path = "subagent_manager_tests.rs"]
mod tests;