Skip to main content

aither_agent/
subagent.rs

1//! Subagents as a mechanism: a child agent run on behalf of a parent's tool.
2//!
3//! aither defines no `subagent` command, no subagent types and no definition
4//! files; the embedder writes the tool and decides what a child is. What
5//! aither provides is the part every embedder needs and cannot write against
6//! the loop's internals:
7//!
8//! - [`SubagentRuns`] records the children in flight, lists them and cancels
9//!   one or all, without aborting the parent's turn;
10//! - [`SubagentRun`] is one registered child: the identity its agent is
11//!   built with, the signal that cancels it, and the sink its events go to;
12//! - [`ChildAgent`] is anything that can be run as a child: an in-process
13//!   [`Agent`](crate::Agent), or an external agent behind a protocol.
14//!
15//! The parent reports a child on its own stream: [`SubagentStarted`] and
16//! [`SubagentEnded`] bracket the run, and every event of the child follows
17//! with the child's [`AgentPath`], so one consumer sees the whole tree.
18//!
19//! [`SubagentStarted`]: crate::AgentEvent::SubagentStarted
20//! [`SubagentEnded`]: crate::AgentEvent::SubagentEnded
21//!
22//! # Example
23//!
24//! ```rust,ignore
25//! let runs = SubagentRuns::default();
26//! let agent = Agent::builder(model).subagents(runs.clone()).tool(SubagentTool::new(runs)).build();
27//!
28//! // Inside the tool's `call`:
29//! let started_by = cx.identity().expect("the agent loop identifies its calls");
30//! let run = runs.start(started_by, "researcher", &prompt);
31//! let mut child = Agent::builder(model).identity(run.identity()).build();
32//! let outcome = run.run(&mut child, &prompt).await;
33//! ```
34
35use 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
51/// An agent that can run as a child of another.
52///
53/// Implemented for [`Agent`]; an embedder implements it for an agent that
54/// lives elsewhere, such as an external session behind a protocol. The child
55/// reports its events to `events`, each stamped with its own path, and stops
56/// when `cancel` fires.
57pub trait ChildAgent: Send {
58    /// Runs the child on `prompt` until it ends, and says how it ended.
59    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/// Where a child's events go: the parent's stream.
100#[derive(Debug, Clone)]
101pub struct ChildEvents {
102    sender: async_channel::Sender<TimedEvent>,
103}
104
105impl ChildEvents {
106    /// Hands an event of the child to the parent's stream as it is: the
107    /// event already names the child that emitted it.
108    pub fn forward(&self, event: TimedEvent) {
109        let _ = self.sender.try_send(event);
110    }
111}
112
113/// Snapshot of one child in flight.
114#[derive(Debug, Clone)]
115#[non_exhaustive]
116pub struct SubagentRunInfo {
117    /// Unique run id within the owning [`SubagentRuns`].
118    pub id: u64,
119    /// The name the child was started under.
120    pub name: String,
121    /// The task prompt the child was given.
122    pub prompt: String,
123    /// When the child started.
124    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/// The registry of children in flight.
142///
143/// Create one, give a clone to the agent with
144/// [`AgentBuilder::subagents`](crate::AgentBuilder::subagents) and one to the
145/// tool that starts children. The agent forwards the events the registry
146/// receives onto its own stream; a host lists and cancels children through
147/// any clone.
148#[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    /// Registers a child named `name` that the call `started_by` starts
169    /// with `prompt`, and announces it on the parent's stream.
170    ///
171    /// # Panics
172    ///
173    /// Panics if the registry lock is poisoned.
174    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    /// Every child in flight, ordered by id.
215    ///
216    /// # Panics
217    ///
218    /// Panics if the registry lock is poisoned.
219    #[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    /// Cancels one child; the parent's turn goes on.
234    ///
235    /// Returns `false` only when `id` is unknown. A cancelled child keeps
236    /// appearing in [`list`](Self::list) until it unwinds.
237    ///
238    /// # Panics
239    ///
240    /// Panics if the registry lock is poisoned.
241    #[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    /// Cancels every child in flight; returns how many were signalled.
253    ///
254    /// # Panics
255    ///
256    /// Panics if the registry lock is poisoned.
257    #[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    /// The events children have reported and the parent has not taken yet.
271    pub(crate) fn incoming(&self) -> &async_channel::Receiver<TimedEvent> {
272        &self.shared.incoming
273    }
274}
275
276/// One registered child.
277///
278/// Ends with [`run`](Self::run) or [`finish`](Self::finish); dropped before
279/// that, it ends as cancelled, so the parent's stream always closes what it
280/// opened.
281#[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    /// The path of the agent whose call started the child.
287    parent: AgentPath,
288    path: AgentPath,
289    identity: AgentIdentity,
290    cancel: CancelHandle,
291    ended: bool,
292}
293
294impl SubagentRun {
295    /// The id [`SubagentRuns::cancel`] takes.
296    #[must_use]
297    pub const fn id(&self) -> u64 {
298        self.id
299    }
300
301    /// The identity to build the child agent with, so its events and tool
302    /// calls name it and the call that started it.
303    #[must_use]
304    pub fn identity(&self) -> AgentIdentity {
305        self.identity.clone()
306    }
307
308    /// The child's path.
309    #[must_use]
310    pub const fn path(&self) -> &AgentPath {
311        &self.path
312    }
313
314    /// The signal that fires when the child is cancelled.
315    #[must_use]
316    pub fn cancel_signal(&self) -> CancelSignal {
317        self.cancel.signal()
318    }
319
320    /// Where the child reports its events.
321    #[must_use]
322    pub fn events(&self) -> ChildEvents {
323        ChildEvents {
324            sender: self.runs.shared.events.clone(),
325        }
326    }
327
328    /// Runs `child` on `prompt` to its end and closes the registration with
329    /// the outcome.
330    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    /// Closes the registration with `outcome`, for a child that ran outside
339    /// [`run`](Self::run).
340    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    /// Reports `event` on the parent's stream.
361    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}