use std::{
collections::{HashMap, HashSet},
path::Path,
sync::Arc,
};
use agent_client_protocol::{
schema::MaybeUndefined,
v1::schema::{self as v1, ToolCallId},
v2::schema as v2,
};
use tokio::task::JoinHandle;
use super::{
tool_calls::ToolCalls,
updates::{self, TurnEnd},
};
use crate::{
acp_runtime::{
connection,
deciders::mark_rejected,
driver::{render, DriverOutcome},
runtime_children::{ChildRecord, RuntimeChild, RuntimeChildren},
session::{run_ended, settle},
turn::TurnClassification,
},
cli_runtime::{
agent_event::{render::EventRenderer, AgentEvent},
status_sink::{RuntimeLabel, StatusSink},
CliPrompt,
},
};
pub(super) const OUTLIVED: &str = "acp: the run ended before this subagent did";
pub(super) struct Children<'a> {
hosts: HashMap<String, Arc<dyn RuntimeChildren>>,
cwd: &'a Path,
label: RuntimeLabel,
known: HashMap<String, Child>,
ending: Vec<JoinHandle<()>>,
}
#[derive(Default)]
struct Child {
announced_on: String,
title: Option<String>,
description: Option<String>,
working: bool,
run: Option<ChildRun>,
}
struct ChildRun {
sink: StatusSink,
renderer: EventRenderer,
tool_calls: ToolCalls,
}
impl<'a> Children<'a> {
pub(super) fn new(
root: &str,
host: Option<Arc<dyn RuntimeChildren>>,
cwd: &'a Path,
label: RuntimeLabel,
) -> Self {
Self {
hosts: host
.map(|host| (root.to_owned(), host))
.into_iter()
.collect(),
cwd,
label,
known: HashMap::new(),
ending: Vec::new(),
}
}
pub(super) fn announced(&mut self, update: v2::SubagentUpdate, on: &str) {
let id = update.session_id.to_string();
let child = self.known.entry(id.clone()).or_insert_with(|| Child {
announced_on: on.to_owned(),
..Child::default()
});
patch(&mut child.title, update.title);
patch(&mut child.description, update.description);
if let MaybeUndefined::Value(state) = &update.state {
self.state(&id, state);
}
}
pub(super) async fn messaged(
&mut self,
message: &v2::SessionMessage,
on: &str,
) -> Result<(), String> {
let (MaybeUndefined::Value(sender), MaybeUndefined::Value(recipient)) =
(&message.sender_session_id, &message.recipient_session_id)
else {
return Ok(());
};
if sender.to_string() != on {
return Ok(());
}
let Some(host) = self.hosts.get(on).cloned() else {
return Ok(());
};
let id = recipient.to_string();
let Some(child) = self
.known
.get_mut(&id)
.filter(|child| child.announced_on == on && child.run.is_none())
else {
return Ok(());
};
let task = match &message.content {
MaybeUndefined::Value(content) => connection::v2_prompt(content),
MaybeUndefined::Undefined | MaybeUndefined::Null => CliPrompt::text(""),
};
let started = RuntimeChild {
id: id.clone(),
title: child.title.clone(),
description: child.description.clone(),
task: task.clone(),
};
let record = host
.started(started)
.await
.map_err(|error| format!("acp: could not record a subagent's run: {error}"))?;
let ChildRecord {
output_file,
works_for,
identity,
status_tx,
observer,
children,
} = record;
let mut sink = StatusSink::new(
output_file,
&identity,
&task,
status_tx,
None,
self.label,
)
.map_err(|error| format!("acp: could not record a subagent's run: {error:#}"))?;
if let Some(observer) = observer {
sink.observed_by(observer);
}
sink.works_for(works_for);
sink.mark_running();
if let Some(children) = children {
self.hosts.insert(id, children);
}
child.run = Some(ChildRun {
sink,
renderer: EventRenderer::new(self.cwd.to_path_buf()),
tool_calls: ToolCalls::default(),
});
Ok(())
}
pub(super) async fn updated(
&mut self,
notification: v2::UpdateSessionNotification,
rejected: &HashSet<ToolCallId>,
) -> Result<(), String> {
let id = notification.session_id.to_string();
if !self.known.contains_key(&id) {
return Ok(());
}
match notification.update {
v2::SessionUpdate::StateUpdate(state) => {
self.state(&id, &state);
return Ok(());
}
v2::SessionUpdate::SubagentUpdate(update) => {
self.announced(update, &id);
return Ok(());
}
v2::SessionUpdate::SessionMessage(message) => {
return self.messaged(&message, &id).await;
}
_ => {}
}
let Some(run) = self.known.get_mut(&id).and_then(|child| child.run.as_mut()) else {
return Ok(());
};
let event = match updates::rendered(¬ification.update, &mut run.tool_calls) {
None => return Ok(()),
Some(Ok(mut update)) => {
mark_rejected(&mut update, rejected);
if let v1::SessionUpdate::UsageUpdate(usage) = &mut update {
usage.cost = None;
}
update.into()
}
Some(Err(source)) => AgentEvent::Notice(source.to_string()),
};
render(&mut run.renderer, &mut run.sink, event);
Ok(())
}
pub(super) async fn end(self) {
for child in self.known.into_values() {
if let Some(mut run) = child.run {
render(
&mut run.renderer,
&mut run.sink,
AgentEvent::Notice(OUTLIVED.into()),
);
run_ended(&mut run.renderer, &mut run.sink);
let outcome = DriverOutcome::of_child(TurnClassification::Stopped, &run.renderer);
settle(run.sink, Ok(outcome)).await;
}
}
for ending in self.ending {
let _ = ending.await;
}
}
fn state(&mut self, id: &str, state: &v2::StateUpdate) {
let Some(child) = self.known.get_mut(id) else {
return;
};
let stop = match state {
v2::StateUpdate::Running(_) | v2::StateUpdate::RequiresAction(_) => {
child.working = true;
return;
}
v2::StateUpdate::Idle(idle) if child.working => idle.stop_reason.as_ref(),
_ => return,
};
child.working = false;
let Some(mut run) = child.run.take() else {
return;
};
self.hosts.remove(id);
let end = TurnEnd::of_child(stop);
render(
&mut run.renderer,
&mut run.sink,
AgentEvent::TurnEnded(end.reason),
);
run_ended(&mut run.renderer, &mut run.sink);
let outcome = DriverOutcome::of_child(end.classification, &run.renderer);
self.ending
.push(tokio::spawn(settle(run.sink, Ok(outcome))));
}
}
fn patch(field: &mut Option<String>, value: MaybeUndefined<String>) {
match value {
MaybeUndefined::Undefined => {}
MaybeUndefined::Null => *field = None,
MaybeUndefined::Value(value) => *field = Some(value),
}
}
#[cfg(test)]
#[path = "children_tests.rs"]
mod tests;