use std::{
collections::HashMap,
sync::{Arc, Mutex, MutexGuard, PoisonError},
time::Duration,
};
use agent_client_protocol::{v1::schema as v1, v2::schema as v2};
use agent_client_protocol::{v2::ConnectionTo as V2ConnectionTo, Client, Error as AcpError};
use rho_protocol::{
methods::{JobList, SessionObserve},
BackgroundItem, BackgroundStatus, BackgroundWork, ClientError, DetachReason, ErrorCode,
JobKind, JobListParams, JobState, JobSummary, Replay, SessionAttachResponse, SessionEvent,
SessionId, SessionObserveParams, SessionOptions,
};
use tokio::{
sync::{mpsc, oneshot},
task::JoinHandle,
};
use super::{background::subagent_idle, bridge, port::V2Port, requests};
use crate::app::{
acp::{
host_features::{HostFeatures, Toggles},
prompt,
sessions::Attacher,
updates::{self, Delivery, Updates},
Foreground, TurnEnd,
},
daemon_client::{Daemon, DaemonError, Part, Routed, StreamPosition},
};
const OBSERVE_AGAIN: Duration = Duration::from_millis(250);
pub(super) fn child_id(run: &str, session: Option<&SessionId>) -> String {
session.map_or_else(|| run.to_owned(), |session| session.as_str().to_owned())
}
pub(super) struct Subagents {
daemon: Arc<Daemon>,
features: Mutex<HostFeatures>,
children: Mutex<HashMap<String, Child>>,
}
struct Child {
parent: String,
relay: Option<JoinHandle<()>>,
state: Arc<Mutex<ChildState>>,
}
#[derive(Default)]
struct ChildState {
told: Option<Told>,
ended: Option<BackgroundStatus>,
unrelayed: bool,
released: bool,
}
impl ChildState {
fn settled(&self) -> Option<v2::StateUpdate> {
match (self.told, self.unrelayed, self.ended) {
(Some(Told::Idle), _, _) => None,
(_, true, Some(status)) => Some(subagent_idle(status)),
(_, _, _) => None,
}
}
}
impl Drop for Child {
fn drop(&mut self) {
if let Some(relay) = self.relay.take() {
relay.abort();
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Resumed {
Replayed,
Current,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ChildReplay {
History,
Live,
}
impl Subagents {
pub(super) fn new(daemon: Arc<Daemon>) -> Self {
Self {
daemon,
features: Mutex::default(),
children: Mutex::default(),
}
}
pub(super) fn negotiated(&self, features: HostFeatures) {
*lock(&self.features) = features;
}
pub(super) fn announced(&self, parent: &v2::SessionId, child: &v2::SessionId) {
lock(&self.children)
.entry(child.0.to_string())
.or_insert_with(|| Child {
parent: parent.0.to_string(),
relay: None,
state: Arc::default(),
});
}
pub(super) fn is_child(&self, session: &str) -> bool {
lock(&self.children).contains_key(session)
}
pub(super) fn is_child_of(&self, parent: &str, child: &str) -> bool {
lock(&self.children)
.get(child)
.is_some_and(|known| known.parent == parent)
}
pub(super) fn follow(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
work: &[BackgroundWork],
) {
for (child, session) in sessions(work) {
self.relay(cx, parent, child, session, Show::Live);
}
}
pub(super) fn linked(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: String,
session: SessionId,
) {
let relayed = lock(&self.children)
.get(&child)
.is_some_and(|known| known.relay.is_some());
if !relayed {
self.relay(cx, parent, child, session, Show::Live);
}
}
pub(super) fn ended(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: &str,
status: BackgroundStatus,
) {
let Some(state) = lock(&self.children)
.get(child)
.map(|known| Arc::clone(&known.state))
else {
return;
};
let mut state = lock(&state);
state.ended = Some(status);
if let Some(idle) = state.settled() {
let child = v2::SessionId::new(child);
tell(cx, parent, &child, &mut state, Told::Idle, idle);
}
}
pub(super) fn release(&self, parent: &str) {
let released: Vec<Child> = {
let mut children = lock(&self.children);
let ids: Vec<String> = children
.iter()
.filter(|(_, child)| child.parent == parent)
.map(|(id, _)| id.clone())
.collect();
ids.iter().filter_map(|id| children.remove(id)).collect()
};
for child in &released {
lock(&child.state).released = true;
}
drop(released);
}
pub(super) async fn resume(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
work: &[BackgroundWork],
resumed: Resumed,
) {
let running: HashMap<String, SessionId> = sessions(work).collect();
let announced: Vec<String> = lock(&self.children)
.iter()
.filter(|(_, child)| child.parent == parent.0.as_ref())
.map(|(id, _)| id.clone())
.collect();
let mut caught_up = Vec::new();
for child in announced {
match (running.get(&child), resumed) {
(Some(session), Resumed::Replayed) => {
let (told, waited) = oneshot::channel();
let history = Show::History {
port: V2Port::child(cx.clone(), ChildReplay::History),
caught_up: told,
};
self.relay(cx, parent, child, session.clone(), history);
caught_up.push(waited);
}
(Some(session), Resumed::Current) => {
self.relay(cx, parent, child, session.clone(), Show::Skip);
}
(None, Resumed::Replayed) => {
send(cx, &v2::SessionId::new(child), replay_complete());
}
(None, Resumed::Current) => {}
}
}
for waited in caught_up {
let _ = waited.await;
}
}
fn relay(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: String,
session: SessionId,
show: Show,
) {
let mut children = lock(&self.children);
let Some(known) = children.get_mut(&child) else {
return;
};
let child = v2::SessionId::new(child);
let show = match &known.relay {
Some(relay) if !relay.is_finished() => {
show.over(cx, &child);
return;
}
Some(_) => match show {
Show::Live => Show::Skip,
show @ (Show::Skip | Show::History { .. }) => show,
},
None => show,
};
let state = Arc::clone(&known.state);
lock(&state).unrelayed = false;
let relay = Relay {
daemon: Arc::clone(&self.daemon),
state,
port: V2Port::child(cx.clone(), ChildReplay::Live),
show,
parent: parent.clone(),
child,
session,
updates: Updates::new(*lock(&self.features)),
position: None,
pending: None,
};
known.relay = Some(tokio::spawn(relay.run()));
}
}
fn sessions(work: &[BackgroundWork]) -> impl Iterator<Item = (String, SessionId)> + '_ {
work.iter()
.filter(|work| work.status.is_running())
.filter_map(|work| match &work.item {
BackgroundItem::Subagent {
run,
session: Some(session),
} => Some((child_id(run, Some(session)), session.clone())),
_ => None,
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Told {
Running,
RequiresAction,
Idle,
Unknown,
}
enum Show {
Live,
Skip,
History {
port: V2Port,
caught_up: oneshot::Sender<()>,
},
}
impl Show {
fn resumed(replay: Replay) -> Self {
match replay {
Replay::Tail => Self::Live,
Replay::Reset => Self::Skip,
}
}
fn over(self, cx: &V2ConnectionTo<Client>, child: &v2::SessionId) {
if let Self::History { caught_up, .. } = self {
send(cx, child, replay_complete());
let _ = caught_up.send(());
}
}
}
struct Relay {
daemon: Arc<Daemon>,
state: Arc<Mutex<ChildState>>,
port: V2Port,
show: Show,
parent: v2::SessionId,
child: v2::SessionId,
session: SessionId,
updates: Updates,
position: Option<StreamPosition>,
pending: Option<(SessionOptions, JobState)>,
}
enum Next {
Again,
Stop(Stopped),
}
#[derive(Clone, Copy)]
enum Stopped {
Ended,
Lost,
Released,
}
impl Relay {
async fn run(mut self) {
if let Err(error) = Attacher::detach(&*self.daemon, &self.session).await {
tracing::debug!(%error, "could not stop following a subagent's session");
}
loop {
let routed = self.daemon.route_channel(&self.session);
let params = SessionObserveParams {
session: self.session.clone(),
after: self
.position
.as_ref()
.and_then(StreamPosition::cursor)
.cloned(),
};
let next = match self.daemon.request::<SessionObserve>(¶ms).await {
Ok(response) => {
self.begin(&response);
self.read(routed).await
}
Err(DaemonError::Request(error))
if error.error_code() == Some(ErrorCode::SessionBusy) =>
{
self.daemon.unroute(&self.session);
self.history_over();
tokio::time::sleep(OBSERVE_AGAIN).await;
Next::Again
}
Err(
error @ (DaemonError::Unreachable(_)
| DaemonError::Request(ClientError::Closed | ClientError::Frame(_))),
) => {
tracing::debug!(%error, "could not observe a subagent's session");
Next::Stop(Stopped::Lost)
}
Err(DaemonError::Request(error)) => {
tracing::debug!(%error, "could not observe a subagent's session");
Next::Stop(Stopped::Ended)
}
};
match next {
Next::Again => {}
Next::Stop(Stopped::Released) => return,
Next::Stop(stopped) => {
self.daemon.unroute(&self.session);
self.history_over();
if matches!(stopped, Stopped::Ended) {
self.learn_how_it_ended().await;
}
self.stopped(stopped);
return;
}
}
}
}
async fn learn_how_it_ended(&self) {
{
let state = lock(&self.state);
if state.told == Some(Told::Idle) || state.ended.is_some() {
return;
}
}
let jobs = match self.daemon.request::<JobList>(&JobListParams {}).await {
Ok(response) => response.jobs,
Err(error) => {
tracing::debug!(%error, "could not ask how a subagent's run ended");
return;
}
};
if let Some(status) = run_ended(&jobs, &self.session) {
lock(&self.state).ended.get_or_insert(status);
}
}
fn stopped(&self, stopped: Stopped) {
let mut state = lock(&self.state);
state.unrelayed = true;
let (told, update) = match (state.settled(), stopped) {
(Some(idle), _) => (Told::Idle, idle),
(None, Stopped::Lost) if state.told != Some(Told::Idle) => (
Told::Unknown,
v2::StateUpdate::Unknown(v2::UnknownStateUpdate::new()),
),
(None, Stopped::Lost | Stopped::Ended | Stopped::Released) => return,
};
self.tell_locked(&mut state, told, update);
}
fn begin(&mut self, response: &SessionAttachResponse) {
match &mut self.position {
Some(position) => {
position.reattached(response);
self.history_over();
self.show = Show::resumed(response.replay);
}
None => self.position = Some(StreamPosition::attached(response)),
}
let directories: Vec<v2::AbsolutePath> = response
.options
.added_dirs
.iter()
.cloned()
.map(v2::AbsolutePath::new)
.collect();
let placed = v2::SubagentUpdate::new(self.child.clone())
.cwd(v2::AbsolutePath::new(response.workspace.clone()))
.additional_directories(directories);
send(
self.port.cx(),
&self.parent,
v2::SessionUpdate::SubagentUpdate(placed),
);
self.pending = Some((response.options.clone(), response.state));
if !matches!(self.show, Show::History { .. }) {
self.current();
}
}
fn current(&mut self) {
let Some((options, state)) = self.pending.take() else {
return;
};
self.options(&options);
self.busy(Foreground::of(state));
}
async fn read(&mut self, mut routed: mpsc::UnboundedReceiver<Routed>) -> Next {
if !self
.position
.as_ref()
.is_some_and(StreamPosition::replaying)
{
self.history_over();
}
while let Some(next) = routed.recv().await {
match next {
Routed::Event { seq, event } => {
if lock(&self.state).released {
return Next::Stop(Stopped::Released);
}
self.updates.observe(&event);
let Some(position) = self.position.as_mut() else {
return Next::Stop(Stopped::Ended);
};
match position.observe(seq) {
Part::Live => self.live(&event),
Part::Replayed { left, .. } => {
match &self.show {
Show::Live => self.live(&event),
Show::History { .. } => self.replayed(&event),
Show::Skip => {}
}
if left == 0 {
self.history_over();
}
}
}
}
Routed::Detached(DetachReason::Lagged) => return Next::Again,
Routed::Detached(DetachReason::DaemonStopping | DetachReason::Restarting)
| Routed::Lost => return Next::Stop(Stopped::Lost),
Routed::Detached(_) => return Next::Stop(Stopped::Ended),
}
}
Next::Stop(Stopped::Ended)
}
fn history_over(&mut self) {
let show = std::mem::replace(&mut self.show, Show::Live);
let Show::History { caught_up, .. } = show else {
self.show = show;
return;
};
send(self.port.cx(), &self.child, replay_complete());
self.current();
let _ = caught_up.send(());
}
fn live(&mut self, event: &SessionEvent) {
match event {
SessionEvent::UserMessage { .. } => {
let message = self.task(event);
send(self.port.cx(), &self.child, message);
}
SessionEvent::State { state, .. } => self.busy(Foreground::of(*state)),
SessionEvent::TurnEnded { outcome, .. } => {
self.mapped(event, Delivery::Live);
let end = TurnEnd::Ended(prompt::stop_reason(outcome.clone()));
let idle = v2::IdleStateUpdate::new().stop_reason(requests::stop_reason(&end));
self.tell_locked(
&mut lock(&self.state),
Told::Idle,
v2::StateUpdate::Idle(idle),
);
}
SessionEvent::OptionsChanged { options } => self.options(options),
SessionEvent::InputRequested { .. }
| SessionEvent::InputResolved { .. }
| SessionEvent::Background { .. } => {}
event => self.mapped(event, Delivery::Live),
}
}
fn replayed(&mut self, event: &SessionEvent) {
match event {
SessionEvent::UserMessage { .. } => {
let message = self.task(event);
if let Show::History { port, .. } = &self.show {
let replayed = v2::UpdateSessionNotification::new(self.child.clone(), message)
.meta(updates::replay_meta());
if let Err(error) = port.cx().send_notification(replayed) {
tracing::debug!(%error, "could not replay a subagent's task over ACP v2");
}
}
}
SessionEvent::State { .. }
| SessionEvent::OptionsChanged { .. }
| SessionEvent::InputRequested { .. }
| SessionEvent::InputResolved { .. }
| SessionEvent::Background { .. } => {}
event => self.mapped(event, Delivery::Replay),
}
}
fn mapped(&mut self, event: &SessionEvent, delivery: Delivery) {
let child = v1::SessionId::new(self.child.0.clone());
let mapped = self.updates.map(event);
let port = match (&self.show, delivery) {
(Show::History { port, .. }, Delivery::Replay) => port,
_ => &self.port,
};
for update in mapped {
port.forward(updates::notification(&child, update, delivery));
}
}
fn task(&mut self, event: &SessionEvent) -> v2::SessionUpdate {
let mut id = None;
let mut content = Vec::new();
for update in self.updates.map(event) {
if let v1::SessionUpdate::UserMessageChunk(chunk) = update {
id = id.or(chunk.message_id);
match bridge::<_, v2::ContentBlock>(&chunk.content) {
Ok(block) => content.push(block),
Err(error) => tracing::warn!(%error, "could not report a subagent's task"),
}
}
}
let id = id.map_or_else(|| format!("{}-task", self.child.0), |id| id.0.to_string());
v2::SessionUpdate::SessionMessage(
v2::SessionMessage::new(id)
.sender_session_id(self.parent.clone())
.recipient_session_id(self.child.clone())
.content(content),
)
}
fn options(&self, options: &SessionOptions) {
match child_options(options) {
Ok(update) => send(self.port.cx(), &self.child, update),
Err(error) => tracing::warn!(%error, "could not report a subagent's options"),
}
}
fn busy(&self, foreground: Foreground) {
let (told, state) = match foreground {
Foreground::Running => (
Told::Running,
v2::StateUpdate::Running(v2::RunningStateUpdate::new()),
),
Foreground::RequiresAction => (
Told::RequiresAction,
v2::StateUpdate::RequiresAction(v2::RequiresActionStateUpdate::new()),
),
Foreground::Idle => return,
};
self.tell_locked(&mut lock(&self.state), told, state);
}
fn tell_locked(&self, state: &mut ChildState, told: Told, update: v2::StateUpdate) {
tell(
self.port.cx(),
&self.parent,
&self.child,
state,
told,
update,
);
}
}
fn run_ended(jobs: &[JobSummary], session: &SessionId) -> Option<BackgroundStatus> {
let job = jobs
.iter()
.rev()
.find(|job| job.kind == JobKind::Subagent && job.session.as_ref() == Some(session))?;
match job.state {
JobState::Completed => Some(BackgroundStatus::Completed),
JobState::Failed | JobState::TimedOut => Some(BackgroundStatus::Failed),
JobState::Cancelled => Some(BackgroundStatus::Cancelled),
JobState::Interrupted | JobState::Unknown => Some(BackgroundStatus::Unknown),
JobState::Idle | JobState::Queued | JobState::Running | JobState::WaitingForInput => None,
_ => Some(BackgroundStatus::Unknown),
}
}
fn tell(
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: &v2::SessionId,
state: &mut ChildState,
told: Told,
update: v2::StateUpdate,
) {
if state.released || state.told == Some(told) {
return;
}
state.told = Some(told);
send(cx, child, v2::SessionUpdate::StateUpdate(update.clone()));
let mirror = v2::SubagentUpdate::new(child.clone()).state(update);
send(cx, parent, v2::SessionUpdate::SubagentUpdate(mirror));
}
fn child_options(options: &SessionOptions) -> Result<v2::SessionUpdate, AcpError> {
let options = requests::setup(options, Toggles::Select)?
.config_options
.into_iter()
.map(|mut option| {
if let v2::SessionConfigKind::Select(select) = &mut option.kind {
let current = select.current_value.clone();
let choices = match &select.options {
v2::SessionConfigSelectOptions::Grouped(groups) => {
groups.iter().flat_map(|group| &group.options).collect()
}
v2::SessionConfigSelectOptions::Ungrouped(choices) => choices.iter().collect(),
_ => Vec::new(),
};
let kept: Vec<_> = choices
.into_iter()
.filter(|choice| choice.value == current)
.cloned()
.collect();
if kept.is_empty() {
tracing::warn!(
option = %option.config_id.0,
"a subagent's option offers no choice for its current value"
);
} else {
select.options = kept.into();
}
}
option
})
.collect();
Ok(v2::SessionUpdate::ConfigOptionUpdate(
v2::ConfigOptionUpdate::new(options),
))
}
fn replay_complete() -> v2::SessionUpdate {
v2::SessionUpdate::ReplayComplete(v2::ReplayComplete::new())
}
fn send(cx: &V2ConnectionTo<Client>, session: &v2::SessionId, update: v2::SessionUpdate) {
let notification = v2::UpdateSessionNotification::new(session.clone(), update);
if let Err(error) = cx.send_notification(notification) {
tracing::debug!(%error, "could not send a subagent's update over ACP v2");
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[path = "subagents_tests.rs"]
mod tests;