1use 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#[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 #[must_use]
36 pub const fn agent(&self) -> &AgentPath {
37 &self.agent
38 }
39
40 #[must_use]
42 pub fn task_id(&self) -> &str {
43 &self.task_id
44 }
45
46 #[must_use]
49 pub fn output_preview(&self) -> &str {
50 &self.output_preview
51 }
52
53 #[must_use]
55 pub const fn output_file(&self) -> &StoredFile {
56 &self.output_file
57 }
58}
59
60#[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 #[must_use]
76 pub const fn agent(&self) -> &AgentPath {
77 &self.agent
78 }
79
80 #[must_use]
84 pub const fn info(&self) -> &crate::JobInfo {
85 &self.info
86 }
87
88 #[must_use]
91 pub const fn result(&self) -> &Result<CompletedCommand, TerminalError> {
92 &self.result
93 }
94
95 #[must_use]
97 pub const fn timeout_kill(&self) -> Option<&TimeoutKill> {
98 self.timeout_kill.as_ref()
99 }
100
101 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#[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 #[must_use]
133 pub const fn agent(&self) -> &AgentPath {
134 &self.agent
135 }
136
137 #[must_use]
139 pub fn task_id(&self) -> &str {
140 &self.task_id
141 }
142
143 #[must_use]
145 pub fn script(&self) -> &str {
146 &self.script
147 }
148
149 #[must_use]
151 pub const fn after(&self) -> Duration {
152 self.after
153 }
154}
155
156#[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 #[must_use]
172 pub const fn agent(&self) -> &AgentPath {
173 &self.agent
174 }
175
176 #[must_use]
178 pub fn task_id(&self) -> &str {
179 &self.task_id
180 }
181
182 #[must_use]
184 pub fn script(&self) -> &str {
185 &self.script
186 }
187}
188
189#[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 #[must_use]
203 pub const fn agent(&self) -> &AgentPath {
204 &self.agent
205 }
206
207 #[must_use]
209 pub fn task_id(&self) -> &str {
210 &self.task_id
211 }
212
213 #[must_use]
215 pub fn script(&self) -> &str {
216 &self.script
217 }
218
219 #[must_use]
221 pub fn error(&self) -> &str {
222 &self.error
223 }
224}
225
226#[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 #[must_use]
242 pub const fn agent(&self) -> &AgentPath {
243 &self.agent
244 }
245
246 #[must_use]
248 pub fn task_id(&self) -> &str {
249 &self.task_id
250 }
251
252 #[must_use]
254 pub const fn call(&self) -> Option<&CallIdentity> {
255 self.call.as_ref()
256 }
257
258 #[must_use]
260 pub fn processes(&self) -> &[JobProcess] {
261 &self.processes
262 }
263}
264
265#[derive(Debug)]
267#[non_exhaustive]
268pub enum ShellEvent {
269 JobStarted(JobStarted),
271 JobEnded(Box<JobEnded>),
273 LongRunning(LongRunning),
275 StdinBlocked(StdinBlocked),
277 StdinWatchFailed(StdinWatchFailed),
279 DescendantsKilled(DescendantsKilled),
282 MonitorIncrement(MonitorIncrement),
284 MonitorStalled(MonitorStalled),
286 MonitorEnded(MonitorEnded),
288}
289
290impl ShellEvent {
291 #[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#[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 pub(crate) const fn agent(&self) -> &AgentPath {
327 &self.agent
328 }
329
330 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#[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#[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 #[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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 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}