1use std::collections::HashMap;
36use std::future::Future;
37use std::ops::ControlFlow;
38use std::sync::atomic::{AtomicU64, Ordering};
39use std::sync::{Arc, Mutex};
40use std::time::Instant;
41
42use aither_core::LanguageModel;
43use aither_core::llm::tool::CancelSignal;
44use aither_core::llm::{AgentIdentity, CallIdentity, SubagentIdentity};
45
46use crate::agent::{Agent, CancelHandle};
47use crate::context::HandoffSchema;
48use crate::event::{AgentEvent, AgentPath, RunOutcome, TimedEvent};
49use crate::hook::Hooks;
50
51pub trait ChildAgent: Send {
58 fn run(
60 &mut self,
61 prompt: &str,
62 events: &ChildEvents,
63 cancel: CancelSignal,
64 ) -> impl Future<Output = RunOutcome> + Send;
65}
66
67impl<M, H, C, Schema> ChildAgent for Agent<M, H, C, Schema>
68where
69 Schema: HandoffSchema,
70 M: LanguageModel + 'static,
71 C: LanguageModel + 'static,
72 H: Hooks,
73{
74 async fn run(
75 &mut self,
76 prompt: &str,
77 events: &ChildEvents,
78 cancel: CancelSignal,
79 ) -> RunOutcome {
80 let own = AgentPath::of(self.identity());
81 let driven = Self::run(self, prompt, std::iter::empty())
82 .drive(None, cancel.cancelled(), |ended, timed| {
83 let outcome = match (&timed.event, timed.agent == own) {
84 (AgentEvent::RunEnded { outcome, .. }, true) => Some(outcome.clone()),
85 _ => ended,
86 };
87 events.forward(timed);
88 std::future::ready(ControlFlow::<(), _>::Continue(outcome))
89 })
90 .await;
91 match driven {
92 Ok(ControlFlow::Continue(Some(outcome))) => outcome,
93 Ok(ControlFlow::Continue(None) | ControlFlow::Break(())) => RunOutcome::Cancelled,
94 Err(error) => RunOutcome::Failed { error },
95 }
96 }
97}
98
99#[derive(Debug, Clone)]
101pub struct ChildEvents {
102 sender: async_channel::Sender<TimedEvent>,
103}
104
105impl ChildEvents {
106 pub fn forward(&self, event: TimedEvent) {
109 let _ = self.sender.try_send(event);
110 }
111}
112
113#[derive(Debug, Clone)]
115#[non_exhaustive]
116pub struct SubagentRunInfo {
117 pub id: u64,
119 pub name: String,
121 pub prompt: String,
123 pub started: Instant,
125}
126
127#[derive(Debug)]
128struct Slot {
129 info: SubagentRunInfo,
130 cancel: CancelHandle,
131}
132
133#[derive(Debug)]
134struct Shared {
135 runs: Mutex<HashMap<u64, Slot>>,
136 next_id: AtomicU64,
137 events: async_channel::Sender<TimedEvent>,
138 incoming: async_channel::Receiver<TimedEvent>,
139}
140
141#[derive(Debug, Clone)]
149pub struct SubagentRuns {
150 shared: Arc<Shared>,
151}
152
153impl Default for SubagentRuns {
154 fn default() -> Self {
155 let (events, incoming) = async_channel::unbounded();
156 Self {
157 shared: Arc::new(Shared {
158 runs: Mutex::default(),
159 next_id: AtomicU64::new(0),
160 events,
161 incoming,
162 }),
163 }
164 }
165}
166
167impl SubagentRuns {
168 pub fn start(&self, started_by: &CallIdentity, name: &str, prompt: &str) -> SubagentRun {
175 let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
176 let identity =
177 AgentIdentity::Subagent(SubagentIdentity::new(name, Some(started_by.clone())));
178 let parent = AgentPath::of(started_by.agent());
179 let path = AgentPath::of(&identity);
180 let cancel = CancelHandle::default();
181 self.shared
182 .runs
183 .lock()
184 .expect("subagent runs lock poisoned")
185 .insert(
186 id,
187 Slot {
188 info: SubagentRunInfo {
189 id,
190 name: name.to_string(),
191 prompt: prompt.to_string(),
192 started: Instant::now(),
193 },
194 cancel: cancel.clone(),
195 },
196 );
197 let run = SubagentRun {
198 id,
199 runs: self.clone(),
200 parent,
201 path,
202 identity,
203 cancel,
204 ended: false,
205 };
206 run.announce(AgentEvent::SubagentStarted {
207 child: run.path.clone(),
208 name: name.to_string(),
209 prompt: prompt.to_string(),
210 });
211 run
212 }
213
214 #[must_use]
220 pub fn list(&self) -> Vec<SubagentRunInfo> {
221 let mut infos: Vec<_> = self
222 .shared
223 .runs
224 .lock()
225 .expect("subagent runs lock poisoned")
226 .values()
227 .map(|slot| slot.info.clone())
228 .collect();
229 infos.sort_by_key(|info| info.id);
230 infos
231 }
232
233 #[must_use]
242 pub fn cancel(&self, id: u64) -> bool {
243 self.shared
244 .runs
245 .lock()
246 .expect("subagent runs lock poisoned")
247 .get(&id)
248 .map(|slot| slot.cancel.cancel())
249 .is_some()
250 }
251
252 #[must_use]
258 pub fn cancel_all(&self) -> usize {
259 let runs = self
260 .shared
261 .runs
262 .lock()
263 .expect("subagent runs lock poisoned");
264 for slot in runs.values() {
265 slot.cancel.cancel();
266 }
267 runs.len()
268 }
269
270 pub(crate) fn incoming(&self) -> &async_channel::Receiver<TimedEvent> {
272 &self.shared.incoming
273 }
274}
275
276#[derive(Debug)]
282#[must_use = "a registered child ends when it is run, finished or dropped"]
283pub struct SubagentRun {
284 id: u64,
285 runs: SubagentRuns,
286 parent: AgentPath,
288 path: AgentPath,
289 identity: AgentIdentity,
290 cancel: CancelHandle,
291 ended: bool,
292}
293
294impl SubagentRun {
295 #[must_use]
297 pub const fn id(&self) -> u64 {
298 self.id
299 }
300
301 #[must_use]
304 pub fn identity(&self) -> AgentIdentity {
305 self.identity.clone()
306 }
307
308 #[must_use]
310 pub const fn path(&self) -> &AgentPath {
311 &self.path
312 }
313
314 #[must_use]
316 pub fn cancel_signal(&self) -> CancelSignal {
317 self.cancel.signal()
318 }
319
320 #[must_use]
322 pub fn events(&self) -> ChildEvents {
323 ChildEvents {
324 sender: self.runs.shared.events.clone(),
325 }
326 }
327
328 pub async fn run<C: ChildAgent>(self, child: &mut C, prompt: &str) -> RunOutcome {
331 let outcome = child
332 .run(prompt, &self.events(), self.cancel_signal())
333 .await;
334 self.finish(outcome.clone());
335 outcome
336 }
337
338 pub fn finish(mut self, outcome: RunOutcome) {
341 self.close(outcome);
342 }
343
344 fn close(&mut self, outcome: RunOutcome) {
345 if std::mem::replace(&mut self.ended, true) {
346 return;
347 }
348 self.runs
349 .shared
350 .runs
351 .lock()
352 .expect("subagent runs lock poisoned")
353 .remove(&self.id);
354 self.announce(AgentEvent::SubagentEnded {
355 child: self.path.clone(),
356 outcome,
357 });
358 }
359
360 fn announce(&self, event: AgentEvent) {
362 let _ = self.runs.shared.events.try_send(TimedEvent {
363 at: jiff::Timestamp::now(),
364 agent: self.parent.clone(),
365 event,
366 });
367 }
368}
369
370impl Drop for SubagentRun {
371 fn drop(&mut self) {
372 self.close(RunOutcome::Cancelled);
373 }
374}