use std::collections::HashMap;
use std::future::Future;
use std::ops::ControlFlow;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use aither_core::LanguageModel;
use aither_core::llm::tool::CancelSignal;
use aither_core::llm::{AgentIdentity, CallIdentity, SubagentIdentity};
use crate::agent::{Agent, CancelHandle};
use crate::context::HandoffSchema;
use crate::event::{AgentEvent, AgentPath, RunOutcome, TimedEvent};
use crate::hook::Hooks;
pub trait ChildAgent: Send {
fn run(
&mut self,
prompt: &str,
events: &ChildEvents,
cancel: CancelSignal,
) -> impl Future<Output = RunOutcome> + Send;
}
impl<M, H, C, Schema> ChildAgent for Agent<M, H, C, Schema>
where
Schema: HandoffSchema,
M: LanguageModel + 'static,
C: LanguageModel + 'static,
H: Hooks,
{
async fn run(
&mut self,
prompt: &str,
events: &ChildEvents,
cancel: CancelSignal,
) -> RunOutcome {
let own = AgentPath::of(self.identity());
let driven = Self::run(self, prompt, std::iter::empty())
.drive(None, cancel.cancelled(), |ended, timed| {
let outcome = match (&timed.event, timed.agent == own) {
(AgentEvent::RunEnded { outcome, .. }, true) => Some(outcome.clone()),
_ => ended,
};
events.forward(timed);
std::future::ready(ControlFlow::<(), _>::Continue(outcome))
})
.await;
match driven {
Ok(ControlFlow::Continue(Some(outcome))) => outcome,
Ok(ControlFlow::Continue(None) | ControlFlow::Break(())) => RunOutcome::Cancelled,
Err(error) => RunOutcome::Failed { error },
}
}
}
#[derive(Debug, Clone)]
pub struct ChildEvents {
sender: async_channel::Sender<TimedEvent>,
}
impl ChildEvents {
pub fn forward(&self, event: TimedEvent) {
let _ = self.sender.try_send(event);
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SubagentRunInfo {
pub id: u64,
pub name: String,
pub prompt: String,
pub started: Instant,
}
#[derive(Debug)]
struct Slot {
info: SubagentRunInfo,
cancel: CancelHandle,
}
#[derive(Debug)]
struct Shared {
runs: Mutex<HashMap<u64, Slot>>,
next_id: AtomicU64,
events: async_channel::Sender<TimedEvent>,
incoming: async_channel::Receiver<TimedEvent>,
}
#[derive(Debug, Clone)]
pub struct SubagentRuns {
shared: Arc<Shared>,
}
impl Default for SubagentRuns {
fn default() -> Self {
let (events, incoming) = async_channel::unbounded();
Self {
shared: Arc::new(Shared {
runs: Mutex::default(),
next_id: AtomicU64::new(0),
events,
incoming,
}),
}
}
}
impl SubagentRuns {
pub fn start(&self, started_by: &CallIdentity, name: &str, prompt: &str) -> SubagentRun {
let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
let identity =
AgentIdentity::Subagent(SubagentIdentity::new(name, Some(started_by.clone())));
let parent = AgentPath::of(started_by.agent());
let path = AgentPath::of(&identity);
let cancel = CancelHandle::default();
self.shared
.runs
.lock()
.expect("subagent runs lock poisoned")
.insert(
id,
Slot {
info: SubagentRunInfo {
id,
name: name.to_string(),
prompt: prompt.to_string(),
started: Instant::now(),
},
cancel: cancel.clone(),
},
);
let run = SubagentRun {
id,
runs: self.clone(),
parent,
path,
identity,
cancel,
ended: false,
};
run.announce(AgentEvent::SubagentStarted {
child: run.path.clone(),
name: name.to_string(),
prompt: prompt.to_string(),
});
run
}
#[must_use]
pub fn list(&self) -> Vec<SubagentRunInfo> {
let mut infos: Vec<_> = self
.shared
.runs
.lock()
.expect("subagent runs lock poisoned")
.values()
.map(|slot| slot.info.clone())
.collect();
infos.sort_by_key(|info| info.id);
infos
}
#[must_use]
pub fn cancel(&self, id: u64) -> bool {
self.shared
.runs
.lock()
.expect("subagent runs lock poisoned")
.get(&id)
.map(|slot| slot.cancel.cancel())
.is_some()
}
#[must_use]
pub fn cancel_all(&self) -> usize {
let runs = self
.shared
.runs
.lock()
.expect("subagent runs lock poisoned");
for slot in runs.values() {
slot.cancel.cancel();
}
runs.len()
}
pub(crate) fn incoming(&self) -> &async_channel::Receiver<TimedEvent> {
&self.shared.incoming
}
}
#[derive(Debug)]
#[must_use = "a registered child ends when it is run, finished or dropped"]
pub struct SubagentRun {
id: u64,
runs: SubagentRuns,
parent: AgentPath,
path: AgentPath,
identity: AgentIdentity,
cancel: CancelHandle,
ended: bool,
}
impl SubagentRun {
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
#[must_use]
pub fn identity(&self) -> AgentIdentity {
self.identity.clone()
}
#[must_use]
pub const fn path(&self) -> &AgentPath {
&self.path
}
#[must_use]
pub fn cancel_signal(&self) -> CancelSignal {
self.cancel.signal()
}
#[must_use]
pub fn events(&self) -> ChildEvents {
ChildEvents {
sender: self.runs.shared.events.clone(),
}
}
pub async fn run<C: ChildAgent>(self, child: &mut C, prompt: &str) -> RunOutcome {
let outcome = child
.run(prompt, &self.events(), self.cancel_signal())
.await;
self.finish(outcome.clone());
outcome
}
pub fn finish(mut self, outcome: RunOutcome) {
self.close(outcome);
}
fn close(&mut self, outcome: RunOutcome) {
if std::mem::replace(&mut self.ended, true) {
return;
}
self.runs
.shared
.runs
.lock()
.expect("subagent runs lock poisoned")
.remove(&self.id);
self.announce(AgentEvent::SubagentEnded {
child: self.path.clone(),
outcome,
});
}
fn announce(&self, event: AgentEvent) {
let _ = self.runs.shared.events.try_send(TimedEvent {
at: jiff::Timestamp::now(),
agent: self.parent.clone(),
event,
});
}
}
impl Drop for SubagentRun {
fn drop(&mut self) {
self.close(RunOutcome::Cancelled);
}
}