Skip to main content

aither_sandbox/
events.rs

1//! The facts a shell raises about its jobs.
2//!
3//! A [`ShellEvent`] carries no text: the embedder turns each fact into the
4//! alert, reminder or wake its agent reads. Every event reaches exactly one
5//! reader of the [`ShellEvents`] it was raised on: clones share their queues,
6//! so an embedder that aggregates the jobs of several shells hands each the
7//! same [`ShellEvents`] and reads them all from one place.
8
9use std::time::Duration;
10
11use aither_core::llm::{AgentPath, CallIdentity, StoredFile};
12use async_channel::{Receiver, Sender};
13use futures_lite::future::or;
14
15use crate::job_registry::PendingCompletion;
16use crate::monitor::{MonitorEnded, MonitorIncrement, MonitorStalled};
17use crate::process_tree::JobProcess;
18use crate::terminal::{CompletedCommand, TerminalError, TimeoutKill};
19
20/// A job the shell has just detached: started with `background`, or promoted
21/// past [`ShellLimits::foreground_wait`](crate::ShellLimits).
22///
23/// A job raises exactly one.
24#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub struct JobStarted {
27    pub(crate) agent: AgentPath,
28    pub(crate) task_id: String,
29    pub(crate) output_preview: String,
30    pub(crate) output_file: StoredFile,
31}
32
33impl JobStarted {
34    /// The agent whose shell raised the event.
35    #[must_use]
36    pub const fn agent(&self) -> &AgentPath {
37        &self.agent
38    }
39
40    /// Task ID of the job, a word leased from the shell's id allocator.
41    #[must_use]
42    pub fn task_id(&self) -> &str {
43        &self.task_id
44    }
45
46    /// First lines of the redirected output; empty when nothing was written
47    /// yet.
48    #[must_use]
49    pub fn output_preview(&self) -> &str {
50        &self.output_preview
51    }
52
53    /// File receiving the full redirected output.
54    #[must_use]
55    pub const fn output_file(&self) -> &StoredFile {
56        &self.output_file
57    }
58}
59
60/// A job that ran to its end: one promoted past the foreground window or
61/// started in the background. A script whose call returned its result, and
62/// every [`Shell::run`](crate::Shell::run), raises none.
63#[derive(Debug)]
64#[non_exhaustive]
65pub struct JobEnded {
66    pub(crate) agent: AgentPath,
67    pub(crate) info: crate::JobInfo,
68    pub(crate) result: Result<CompletedCommand, TerminalError>,
69    pub(crate) timeout_kill: Option<TimeoutKill>,
70    pub(crate) pending: Option<PendingCompletion>,
71}
72
73impl JobEnded {
74    /// The agent whose shell raised the event.
75    #[must_use]
76    pub const fn agent(&self) -> &AgentPath {
77        &self.agent
78    }
79
80    /// The job as it ended: its task id (a word leased from the shell's id
81    /// allocator), script, status with the cause of a kill, and the path of
82    /// its stored output.
83    #[must_use]
84    pub const fn info(&self) -> &crate::JobInfo {
85        &self.info
86    }
87
88    /// The result of the execution: the output as the model reads it and
89    /// the outages the job ran through.
90    #[must_use]
91    pub const fn result(&self) -> &Result<CompletedCommand, TerminalError> {
92        &self.result
93    }
94
95    /// Set when the kill was the job's `timeout` bound passing.
96    #[must_use]
97    pub const fn timeout_kill(&self) -> Option<&TimeoutKill> {
98        self.timeout_kill.as_ref()
99    }
100
101    /// The job, split into what it ended as, its result, the bound that
102    /// killed it and the hold that keeps it in its [`Jobs`](crate::Jobs).
103    ///
104    /// The hold keeps the job listed, and its task id leased, until the
105    /// consumer takes the completion by dropping it; it is `None` when a
106    /// waiter ([`Job::wait`](crate::Job::wait)) took the completion first, so
107    /// nothing is owed to the agent.
108    pub fn into_parts(
109        self,
110    ) -> (
111        crate::JobInfo,
112        Result<CompletedCommand, TerminalError>,
113        Option<TimeoutKill>,
114        Option<PendingCompletion>,
115    ) {
116        (self.info, self.result, self.timeout_kill, self.pending)
117    }
118}
119
120/// A job that crossed the long-running threshold; raised once per job.
121#[derive(Debug, Clone)]
122#[non_exhaustive]
123pub struct LongRunning {
124    pub(crate) agent: AgentPath,
125    pub(crate) task_id: String,
126    pub(crate) script: String,
127    pub(crate) after: Duration,
128}
129
130impl LongRunning {
131    /// The agent whose shell raised the event.
132    #[must_use]
133    pub const fn agent(&self) -> &AgentPath {
134        &self.agent
135    }
136
137    /// Task ID of the job.
138    #[must_use]
139    pub fn task_id(&self) -> &str {
140        &self.task_id
141    }
142
143    /// The script the job runs.
144    #[must_use]
145    pub fn script(&self) -> &str {
146        &self.script
147    }
148
149    /// How long the job had been running.
150    #[must_use]
151    pub const fn after(&self) -> Duration {
152        self.after
153    }
154}
155
156/// A job whose stdin pipe has a reader waiting for input; raised once per
157/// blocking episode, so again only after the job was fed and blocks anew.
158///
159/// Only a job started in the background has a stdin pipe: a foreground
160/// command reads the null device, and keeps it when it is promoted.
161#[derive(Debug, Clone)]
162#[non_exhaustive]
163pub struct StdinBlocked {
164    pub(crate) agent: AgentPath,
165    pub(crate) task_id: String,
166    pub(crate) script: String,
167}
168
169impl StdinBlocked {
170    /// The agent whose shell raised the event.
171    #[must_use]
172    pub const fn agent(&self) -> &AgentPath {
173        &self.agent
174    }
175
176    /// Task ID of the job.
177    #[must_use]
178    pub fn task_id(&self) -> &str {
179        &self.task_id
180    }
181
182    /// The script the job runs.
183    #[must_use]
184    pub fn script(&self) -> &str {
185        &self.script
186    }
187}
188
189/// A job whose stdin watch failed; raised once, after which the job can no
190/// longer report being blocked on stdin.
191#[derive(Debug, Clone)]
192#[non_exhaustive]
193pub struct StdinWatchFailed {
194    pub(crate) agent: AgentPath,
195    pub(crate) task_id: String,
196    pub(crate) script: String,
197    pub(crate) error: String,
198}
199
200impl StdinWatchFailed {
201    /// The agent whose shell raised the event.
202    #[must_use]
203    pub const fn agent(&self) -> &AgentPath {
204        &self.agent
205    }
206
207    /// Task ID of the job.
208    #[must_use]
209    pub fn task_id(&self) -> &str {
210        &self.task_id
211    }
212
213    /// The script the job runs.
214    #[must_use]
215    pub fn script(&self) -> &str {
216        &self.script
217    }
218
219    /// Why the watch failed.
220    #[must_use]
221    pub fn error(&self) -> &str {
222        &self.error
223    }
224}
225
226/// Processes a foreground command left running when its shell exited, killed
227/// with it.
228///
229/// Raised once per command, at the moment they were killed.
230#[derive(Debug, Clone)]
231#[non_exhaustive]
232pub struct DescendantsKilled {
233    pub(crate) agent: AgentPath,
234    pub(crate) task_id: String,
235    pub(crate) call: Option<CallIdentity>,
236    pub(crate) processes: Vec<JobProcess>,
237}
238
239impl DescendantsKilled {
240    /// The agent whose shell raised the event.
241    #[must_use]
242    pub const fn agent(&self) -> &AgentPath {
243        &self.agent
244    }
245
246    /// Task ID of the command.
247    #[must_use]
248    pub fn task_id(&self) -> &str {
249        &self.task_id
250    }
251
252    /// The tool call that ran the command, when it came from one.
253    #[must_use]
254    pub const fn call(&self) -> Option<&CallIdentity> {
255        self.call.as_ref()
256    }
257
258    /// Every process killed.
259    #[must_use]
260    pub fn processes(&self) -> &[JobProcess] {
261        &self.processes
262    }
263}
264
265/// A fact about a job of a shell.
266#[derive(Debug)]
267#[non_exhaustive]
268pub enum ShellEvent {
269    /// A job was detached as a background task.
270    JobStarted(JobStarted),
271    /// A job ended; boxed to keep the enum small.
272    JobEnded(Box<JobEnded>),
273    /// A job crossed the long-running threshold.
274    LongRunning(LongRunning),
275    /// A job is waiting for input on its stdin.
276    StdinBlocked(StdinBlocked),
277    /// Watching a job's stdin failed.
278    StdinWatchFailed(StdinWatchFailed),
279    /// A foreground command's shell exited while descendants were still
280    /// running, and they were killed.
281    DescendantsKilled(DescendantsKilled),
282    /// A monitor collected new output lines from its watched job.
283    MonitorIncrement(MonitorIncrement),
284    /// A monitor saw no new output for its stall window.
285    MonitorStalled(MonitorStalled),
286    /// A monitor ended, reporting why.
287    MonitorEnded(MonitorEnded),
288}
289
290impl ShellEvent {
291    /// The agent whose shell raised the event: the root path for the main
292    /// shell, the subagent's path for a subagent's shell.
293    #[must_use]
294    pub const fn agent(&self) -> &AgentPath {
295        match self {
296            Self::JobStarted(event) => event.agent(),
297            Self::JobEnded(event) => event.agent(),
298            Self::LongRunning(event) => event.agent(),
299            Self::StdinBlocked(event) => event.agent(),
300            Self::StdinWatchFailed(event) => event.agent(),
301            Self::DescendantsKilled(event) => event.agent(),
302            Self::MonitorIncrement(event) => event.agent(),
303            Self::MonitorStalled(event) => event.agent(),
304            Self::MonitorEnded(event) => event.agent(),
305        }
306    }
307}
308
309/// The raising half of a shell's events, cloned into every task that reports
310/// a fact.
311///
312/// Events of different kinds queue apart, so a reader of one kind never waits
313/// behind another; [`ShellEvents`] reads them back in the order a job lives
314/// them: started, then the facts about it, then its end. It knows the agent
315/// whose shell raises through it, which every event it builds names.
316#[derive(Clone, Debug)]
317pub struct EventSender {
318    agent: AgentPath,
319    started: Sender<ShellEvent>,
320    facts: Sender<ShellEvent>,
321    ended: Sender<ShellEvent>,
322}
323
324impl EventSender {
325    /// The agent whose shell this raises for.
326    pub(crate) const fn agent(&self) -> &AgentPath {
327        &self.agent
328    }
329
330    /// Raises `event`.
331    ///
332    /// # Errors
333    ///
334    /// Returns the event when every [`ShellEvents`] of its queue is gone.
335    pub(crate) async fn send(
336        &self,
337        event: ShellEvent,
338    ) -> Result<(), Box<async_channel::SendError<ShellEvent>>> {
339        match event {
340            ShellEvent::JobStarted(_) => self.started.send(event).await,
341            ShellEvent::JobEnded(_) => self.ended.send(event).await,
342            ShellEvent::LongRunning(_)
343            | ShellEvent::StdinBlocked(_)
344            | ShellEvent::StdinWatchFailed(_)
345            | ShellEvent::DescendantsKilled(_)
346            | ShellEvent::MonitorIncrement(_)
347            | ShellEvent::MonitorStalled(_)
348            | ShellEvent::MonitorEnded(_) => self.facts.send(event).await,
349        }
350        .map_err(Box::new)
351    }
352}
353
354/// One queue of events: both halves, so it never closes while a
355/// [`ShellEvents`] holds it.
356#[derive(Clone, Debug)]
357struct Queue {
358    tx: Sender<ShellEvent>,
359    rx: Receiver<ShellEvent>,
360}
361
362impl Queue {
363    fn new() -> Self {
364        let (tx, rx) = async_channel::unbounded();
365        Self { tx, rx }
366    }
367}
368
369/// The events of one or several shells, and where they are read.
370///
371/// Cloning shares the queues: an event goes to one of the clones that read. A
372/// handle owns both halves of its queues, so they never close: [`recv`]
373/// waits for as long as the embedder keeps the handle.
374///
375/// A shell built [with a handle](crate::ShellBuilder::events) raises its
376/// events on it, and so does every subagent shell it launches.
377///
378/// [`recv`]: Self::recv
379#[derive(Clone, Debug)]
380pub struct ShellEvents {
381    started: Queue,
382    facts: Queue,
383    ended: Queue,
384}
385
386impl Default for ShellEvents {
387    fn default() -> Self {
388        Self::new()
389    }
390}
391
392impl ShellEvents {
393    /// A handle with no events raised on it yet.
394    #[must_use]
395    pub fn new() -> Self {
396        Self {
397            started: Queue::new(),
398            facts: Queue::new(),
399            ended: Queue::new(),
400        }
401    }
402
403    /// A raising half of these queues, for the shell of `agent`.
404    pub(crate) fn sender(&self, agent: AgentPath) -> EventSender {
405        EventSender {
406            agent,
407            started: self.started.tx.clone(),
408            facts: self.facts.tx.clone(),
409            ended: self.ended.tx.clone(),
410        }
411    }
412
413    /// The next event already raised, without waiting.
414    #[must_use]
415    pub fn try_recv(&self) -> Option<ShellEvent> {
416        self.started
417            .rx
418            .try_recv()
419            .or_else(|_| self.facts.rx.try_recv())
420            .or_else(|_| self.ended.rx.try_recv())
421            .ok()
422    }
423
424    /// Waits for the next event.
425    ///
426    /// Cancel-safe: an event is taken only when this future completes, so a
427    /// caller racing it against other work loses nothing.
428    ///
429    /// # Panics
430    /// Never in practice: the handle holds the senders of its own queues, so
431    /// they cannot close.
432    pub async fn recv(&self) -> ShellEvent {
433        or(
434            self.started.rx.recv(),
435            or(self.facts.rx.recv(), self.ended.rx.recv()),
436        )
437        .await
438        .expect("a handle holds the senders of its own queues")
439    }
440
441    /// Waits for the next event, for at most `duration`.
442    pub async fn recv_timeout(&self, duration: Duration) -> Option<ShellEvent> {
443        or(async { Some(self.recv().await) }, async {
444            async_io::Timer::after(duration).await;
445            None
446        })
447        .await
448    }
449
450    /// Whether no event is waiting.
451    #[must_use]
452    pub fn is_empty(&self) -> bool {
453        self.started.rx.is_empty() && self.facts.rx.is_empty() && self.ended.rx.is_empty()
454    }
455
456    /// The events of one kind, for tests that assert on a single stream of
457    /// facts.
458    #[cfg(test)]
459    pub(crate) fn take_started(&self) -> Vec<JobStarted> {
460        std::iter::from_fn(|| self.started.rx.try_recv().ok())
461            .filter_map(|event| match event {
462                ShellEvent::JobStarted(started) => Some(started),
463                _ => None,
464            })
465            .collect()
466    }
467
468    /// Waits for the next job to end, leaving every other event queued.
469    #[cfg(test)]
470    pub(crate) async fn recv_completed(&self) -> JobEnded {
471        match self
472            .ended
473            .rx
474            .recv()
475            .await
476            .expect("a handle holds the senders of its own queues")
477        {
478            ShellEvent::JobEnded(ended) => *ended,
479            _ => unreachable!("the ended queue holds ended jobs"),
480        }
481    }
482
483    /// The jobs that ended and were not yet read.
484    #[cfg(test)]
485    pub(crate) fn take_completed(&self) -> Vec<JobEnded> {
486        std::iter::from_fn(|| self.ended.rx.try_recv().ok())
487            .filter_map(|event| match event {
488                ShellEvent::JobEnded(ended) => Some(*ended),
489                _ => None,
490            })
491            .collect()
492    }
493
494    /// The facts raised and not yet read.
495    #[cfg(test)]
496    pub(crate) fn take_job_alerts(&self) -> Vec<ShellEvent> {
497        std::iter::from_fn(|| self.facts.rx.try_recv().ok()).collect()
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504    use crate::monitor::MonitorStalled;
505
506    fn stalled(task_id: &str) -> ShellEvent {
507        ShellEvent::MonitorStalled(MonitorStalled {
508            agent: AgentPath::main(),
509            task_id: task_id.to_string(),
510            stall_secs: 1,
511        })
512    }
513
514    #[tokio::test]
515    async fn a_handle_waits_for_events_it_never_loses_the_queues_of() {
516        let events = ShellEvents::new();
517        let reader = events.clone();
518        // Nothing is raised: the read waits, it neither ends nor spins.
519        assert!(
520            reader
521                .recv_timeout(Duration::from_millis(50))
522                .await
523                .is_none()
524        );
525        events
526            .sender(AgentPath::main())
527            .send(stalled("late"))
528            .await
529            .unwrap();
530        let ShellEvent::MonitorStalled(event) = reader.recv().await else {
531            panic!("the raised event is the one read");
532        };
533        assert_eq!(event.task_id(), "late");
534    }
535
536    #[tokio::test]
537    async fn senders_of_one_handle_reach_every_reader_of_it_once() {
538        let events = ShellEvents::new();
539        let (first, second) = (
540            events.sender(AgentPath::main()),
541            events.sender(AgentPath::main()),
542        );
543        first.send(stalled("one")).await.unwrap();
544        second.send(stalled("two")).await.unwrap();
545        let reader = events.clone();
546        assert!(
547            matches!(events.try_recv(), Some(ShellEvent::MonitorStalled(e)) if e.task_id() == "one")
548        );
549        assert!(
550            matches!(reader.try_recv(), Some(ShellEvent::MonitorStalled(e)) if e.task_id() == "two")
551        );
552        assert!(events.is_empty());
553    }
554}