use std::time::Instant;
use super::{AgentEntry, SubagentManager, ValidatedMessage};
use crate::{
app::{
agent_executor::{AgentRunHandle, ChildConversation, LaunchWorkspace},
subagent_pool::{child_events, RunSession, StartedSubagent},
},
session::SessionPersistence,
};
enum Delivery {
Live(AgentRunHandle),
FollowedUp(AgentRunHandle, StartedSubagent),
}
impl SubagentManager {
pub(crate) async fn message(&self, id: &str, message: &ValidatedMessage) -> anyhow::Result<()> {
let id = crate::subagent::normalize_id(id)?;
let delivery = {
let mut entries = self.inner.lock().expect("delegated registry lock");
let entry = entries
.get_mut(&id)
.ok_or_else(|| anyhow::anyhow!("unknown delegated run '{id}'"))?;
if entry.handle.is_complete() {
let (handle, started) = self.follow_up(&id, entry, message)?;
Delivery::FollowedUp(handle, started)
} else {
Delivery::Live(entry.handle.clone())
}
};
match delivery {
Delivery::Live(handle) => handle.message_from_parent(message).await,
Delivery::FollowedUp(handle, started) => {
if let Some(observer) = &self.observer {
observer.subagent_started(started);
}
self.registered(handle);
Ok(())
}
}
}
fn follow_up(
&self,
id: &str,
entry: &mut AgentEntry,
message: &ValidatedMessage,
) -> anyhow::Result<(AgentRunHandle, StartedSubagent)> {
let cannot = |why: &str| {
anyhow::anyhow!("delegated run '{id}' has finished and cannot be followed up: {why}")
};
let Some(RunSession::Rho(session)) = entry.handle.session().cloned() else {
return Err(cannot(
"only a Rho-runtime run keeps a session to continue; start a new run instead",
));
};
let launch = entry
.launch
.clone()
.ok_or_else(|| cannot("it was never launched"))?;
anyhow::ensure!(
launch.persistence == SessionPersistence::Saved,
cannot("its session was not saved; start a new run instead")
);
let cwd = match &launch.workspace {
LaunchWorkspace::Executor => self.executor.cwd(),
LaunchWorkspace::Worktree { cwd, .. } => cwd,
};
anyhow::ensure!(
cwd.is_dir(),
cannot(&format!(
"the directory it worked in, {}, is gone",
cwd.display()
))
);
anyhow::ensure!(
crate::session::Session::is_saved_in_workspace(cwd, session.as_str())?,
cannot("it ended before it saved its session; start a new run instead")
);
anyhow::ensure!(
!crate::session::is_held_alone(cwd, session.as_str())?,
cannot("a person has its session open; follow it up once the daemon unloads it")
);
anyhow::ensure!(
entry.observed,
cannot(
"its result has not reached you yet; read it with action=status, then follow up"
)
);
let works_in = launch.works_in.clone();
let conversation = ChildConversation::FollowUp {
session,
title: entry.handle.status().title,
};
let (events, followed) = child_events(self.observer.as_ref());
let request = launch.request(id, message.as_str(), events, conversation);
let handle = self.executor.spawn(request)?;
entry.handle = handle.clone();
entry.started = Instant::now();
entry.observed = false;
entry.explicitly_observed = false;
let started = StartedSubagent::of(
id.to_owned(),
works_in,
&handle,
followed,
entry.task_fallback.clone(),
);
Ok((handle, started))
}
}