Skip to main content

agentmux_srv/drone/executor/scheduler/
wait.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Wait block: the run stops for a time or for an event
5//! (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md ยง3.3, "Waiting").
6//!
7//! Before it waits the run keeps a checkpoint that says what it waits for: the
8//! time (`deadlines`) or the key of the event (`resume_on`), with the block in
9//! `frontier.waiting`. A restart finds that checkpoint, runs the block again, and
10//! the block takes the deadline or the key it finds there, so the wait goes on
11//! where it was. A deadline that passed while AgentMux was stopped ends the wait
12//! at once, saying it was `late`. A wait on an event does not remember events
13//! that came while AgentMux was stopped: their source sends them again.
14
15use serde_json::{json, Value};
16
17use super::Scheduler;
18use crate::drone::executor::schedule;
19use crate::backend::drone_wait;
20use crate::drone::executor::blocks::approval::{self, Card};
21use crate::drone::executor::blocks::wait::{self as config, Wait};
22use crate::drone::executor::engine::RunEvent;
23use crate::drone::types::FlowNode;
24use agentmux_common::time::now_ms;
25
26/// Closes the wait on its key when the block ends however it ends, including
27/// when the run is stopped and the block is dropped.
28struct OpenKey(String, Option<(String, String)>);
29
30impl Drop for OpenKey {
31    fn drop(&mut self) {
32        drone_wait::close(&self.0);
33        if let Some((run, block)) = &self.1 {
34            crate::backend::drone_approval::forget(run, block);
35        }
36    }
37}
38
39impl<'a> Scheduler<'a> {
40    /// Wait as `node` says, keeping the checkpoint first, and give what the wait
41    /// came to: when it ended and whether it was late, or the event's payload.
42    pub(super) async fn run_wait(&mut self, node: &'a FlowNode) -> Result<Value, String> {
43        let wait = config::parse(node, &|t| self.scope.resolve(t), now_ms())?;
44        self.wait_for(node, wait, None).await
45    }
46
47    /// An Approval block: wait for the person's answer on a key that stays inside AgentMux, showing `card`.
48    /// A yes is the block's output; a no and silence fail it.
49    pub(super) async fn run_approval(&mut self, node: &'a FlowNode) -> Result<Value, String> {
50        let card = approval::card(node, &self.scope)?;
51        let limit = schedule::timeout_seconds(node)?.unwrap_or(approval::DEFAULT_TIMEOUT_S);
52        match self.wait_for(node, Wait::On("approval".to_string()), Some((card, limit))).await {
53            Ok(done) => approval::decide(done.get("payload").unwrap_or(&Value::Null)),
54            Err(e) if e.starts_with("timed out") => Err(format!("approval_timeout: nobody answered ({e})")),
55            Err(e) => Err(e),
56        }
57    }
58
59    async fn wait_for(&mut self, node: &'a FlowNode, wait: Wait, approval: Option<(Card, u64)>) -> Result<Value, String> {
60        let id = node.id.as_str();
61        let now = now_ms();
62        let restored_at = self.deadlines.get(id).copied();
63        let restored_key = self.resume_on.get(id).cloned();
64        let restored = restored_at.is_some() || restored_key.is_some();
65        // The block's own limit, kept so a restart finds how much of it is left.
66        let limit_s = match &approval {
67            Some((_, limit)) => Some(*limit),
68            None => schedule::timeout_seconds(node)?,
69        };
70        let timeout_at = self.wait_timeouts.get(id).copied().or_else(|| limit_s.map(|s| now.saturating_add(i64::try_from(s).unwrap_or(i64::MAX) * 1000)));
71        let timed_out = || Err(format!("timed out after {}", super::plain_duration(std::time::Duration::from_secs(limit_s.unwrap_or(0)))));
72
73        // What it waits for, and the way to be told.
74        let (at, event) = match &wait {
75            Wait::For(ms) => (Some(restored_at.unwrap_or(now.saturating_add(*ms))), None),
76            Wait::Until(at) => (Some(*at), None),
77            // The limit passed while AgentMux was stopped: the key is not opened again, so an event that
78            // is sent again now cannot end a wait that is already over.
79            Wait::On(_) if timeout_at.is_some_and(|t| t <= now) => return timed_out(),
80            Wait::On(label) => {
81                let key = restored_key.unwrap_or_else(drone_wait::new_key);
82                let rx = drone_wait::open(&key);
83                (None, Some((label.clone(), key, rx)))
84            }
85        };
86        // A timed wait whose limit came first and is already past fails the same way, before it says it waits.
87        if let (Some(at), Some(t)) = (at, timeout_at) {
88            if t < at && t <= now {
89                return timed_out();
90            }
91        }
92        let _open = event.as_ref().map(|(_, key, _)| OpenKey(key.clone(), approval.as_ref().map(|_| (self.run_id.to_string(), id.to_string()))));
93        if let (Some((card, _)), Some((_, key, _)), Some(deadline)) = (&approval, &event, timeout_at) {
94            crate::backend::drone_approval::register(
95                crate::backend::drone_approval::DroneApproval {
96                    run_id: self.run_id.to_string(),
97                    block_id: id.to_string(),
98                    drone_id: self.scope.drone_id.clone(),
99                    title: card.title.clone(),
100                    items: card.items.clone(),
101                    deadline_ms: deadline,
102                },
103                key,
104            );
105        }
106        if let Some(at) = at {
107            self.deadlines.insert(id.to_string(), at);
108        }
109        if let Some((_, key, _)) = &event {
110            self.resume_on.insert(id.to_string(), key.clone());
111        }
112        if let Some(t) = timeout_at {
113            self.wait_timeouts.insert(id.to_string(), t);
114        }
115        if !restored {
116            // The run cannot be taken up again where it waits unless this is kept.
117            self.checkpoint_required(id)?;
118        }
119        let _ = self.tx.send(RunEvent::Waiting {
120            run_id: self.run_id.to_string(),
121            block_id: id.to_string(),
122            resume_at: at,
123            on: event.as_ref().map(|(label, _, _)| label.clone()),
124            // An approval's key stays inside AgentMux: whoever reads the run's events cannot answer with it.
125            key: event.as_ref().filter(|_| approval.is_none()).map(|(_, key, _)| key.clone()),
126        });
127
128        // How long until the block's limit, if it has one: it may already be past.
129        let until_timeout = || timeout_at.map(|t| u64::try_from(t - now_ms()).unwrap_or(0));
130        if let Some(at) = at {
131            // The limit comes first when it is earlier than the time: even after a restart that found both past.
132            if let Some(t) = timeout_at.filter(|t| *t < at) {
133                tokio::time::sleep(std::time::Duration::from_millis(u64::try_from(t - now_ms()).unwrap_or(0))).await;
134                return timed_out();
135            }
136            let left = at - now_ms();
137            if left > 0 {
138                tokio::time::sleep(std::time::Duration::from_millis(u64::try_from(left).unwrap_or(0))).await;
139            }
140            // Late is what a restart makes of a wait: it was taken up past its time.
141            let late_ms = if restored_at.is_some() { (now - at).max(0) } else { 0 };
142            return Ok(json!({ "resume_at": at, "late": late_ms > 0, "late_ms": late_ms }));
143        }
144        let Some((label, _, rx)) = event else { return Err("the wait has nothing to wait for".to_string()) };
145        let payload = match until_timeout() {
146            Some(t) => tokio::select! {
147                biased;
148                () = tokio::time::sleep(std::time::Duration::from_millis(t)) => return timed_out(),
149                payload = rx => payload,
150            },
151            None => rx.await,
152        }
153        .map_err(|_| "the run stopped waiting for its event".to_string())?;
154        Ok(json!({ "on": label, "payload": payload, "late": false, "late_ms": 0 }))
155    }
156
157    /// The wait is over, however it ended: the run is no longer waiting.
158    pub(super) fn end_wait(&mut self, id: &str, late: bool) {
159        self.waiting = None;
160        self.deadlines.remove(id);
161        self.resume_on.remove(id);
162        self.wait_timeouts.remove(id);
163        let _ = self.tx.send(RunEvent::WaitEnded { run_id: self.run_id.to_string(), block_id: id.to_string(), late });
164    }
165}