Skip to main content

agentmux_srv/server/
jekt_start.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Start-then-deliver (`docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md` §D4, P2b): with
5//! `agents:always_available` on, a message that finds its agent stopped starts it instead of only
6//! waiting for someone to open it.
7//!
8//! - A held message (`HoldReason::NotRunning`): `hold_with_reason` has already kept the row, and only
9//!   a host-tier, full-key sender gets that far (`hold_applies`), so a LAN or WAN peer or an
10//!   unverified sender never starts an agent. The start runs in the background; the replay delivers
11//!   the row when the agent registers (`jekt_held`).
12//! - An operator Job or cron fire, which is never held: [`deliver_cron`] starts the agent first, waits
13//!   for it to register and then delivers.
14//!
15//! Admission, the spawn gate and the lease apply as for `agent.open`; a start that fails leaves the
16//! message held (or the fire missed) exactly as before.
17
18use std::collections::HashSet;
19use std::sync::{Mutex, OnceLock};
20use std::time::Duration;
21
22use crate::backend::agent_availability::Availability;
23use crate::backend::agent_status::{decide, AgentStatus, Decision, Intent, Pane, Reach, Wanted};
24use crate::backend::reactive::InjectionRequest;
25
26use super::AppState;
27
28/// How long a Job's fire waits for a started agent to register before it is missed.
29const REGISTER_WAIT: Duration = Duration::from_secs(60);
30const REGISTER_POLL: Duration = Duration::from_millis(500);
31
32/// Whether a stopped agent is started by a message (the `agents:always_available` setting).
33fn enabled(state: &AppState) -> bool {
34    crate::sagas::park_agents::enabled(state)
35}
36
37/// Whether a message to an agent with no process starts it: the shared decision (`Intent::Start`) for
38/// a stopped agent, `allowed` being the setting and the sender. Every caller has already found the agent
39/// absent (held as `NotRunning`, or not registered anywhere), so that is the status it is asked about.
40fn starts_the_agent(allowed: bool) -> bool {
41    let stopped = AgentStatus {
42        availability: Availability::NotRunning { exited_with_error: false },
43        pane: Pane::None,
44        wanted: Wanted::Unset,
45        api: Reach::NotTracked,
46        controller: false,
47    };
48    decide(&stopped, Intent::Start { allowed }, || false) == Decision::Start
49}
50
51/// Agents with a start in flight, so a burst of messages makes one start.
52fn starting() -> &'static Mutex<HashSet<String>> {
53    static SET: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
54    SET.get_or_init(Default::default)
55}
56
57/// Holds an agent's slot in [`starting`] until dropped.
58struct StartSlot(String);
59
60impl StartSlot {
61    /// `None` when a start of `uid` is already in flight.
62    fn claim(uid: &str) -> Option<Self> {
63        starting().lock().unwrap().insert(uid.to_string()).then(|| Self(uid.to_string()))
64    }
65}
66
67impl Drop for StartSlot {
68    fn drop(&mut self) {
69        starting().lock().unwrap().remove(&self.0);
70    }
71}
72
73/// Start the agent `uid` for `sender_key` unless it is registered or a start is in flight. A start that
74/// goes ahead counts against the sender's starts per minute (`start_rate`); a no-op does not.
75async fn start_once(state: &AppState, uid: &str, sender_key: &str) -> Result<(), String> {
76    if state.reactive_handler.has_uid_registration(uid) {
77        return Ok(());
78    }
79    let Some(_slot) = StartSlot::claim(uid) else {
80        return Ok(());
81    };
82    super::start_rate::allow(state, sender_key)?;
83    let block_id = super::app_api::agent_attach::start_agent(state, uid).await?;
84    make_addressable(state, uid, &block_id, 0);
85    Ok(())
86}
87
88/// A started agent that has never run (no session to resume) has a controller that spawns on its first
89/// turn and registers for delivery only then, and there is no pane to send that turn. Register it here, so
90/// the replay (or a Job's fire) reaches it and the delivery starts that turn.
91pub(super) fn make_addressable(state: &AppState, uid: &str, block_id: &str, nonce: u64) -> bool {
92    if state.reactive_handler.has_uid_registration(uid) {
93        return false;
94    }
95    let slug = state.mstore.agent_def_get(uid).ok().flatten().map(|d| d.slug).filter(|s| !s.is_empty()).unwrap_or_else(|| uid.to_string());
96    match state.reactive_handler.register_agent_full(&slug, block_id, None, nonce, Some(&slug), Some(uid), "registration.start") {
97        Ok(()) => true,
98        Err(e) => {
99            tracing::warn!(target_uid = %uid, "start: could not register the started agent for delivery: {e}");
100            false
101        }
102    }
103}
104
105/// Whether the sender may start an agent: not one whose signature failed (`sig_verified` is `Some(false)`
106/// only for a sender that has a key and did not prove it). The hold's own test (`hold_applies`) has
107/// already kept LAN and WAN callers out.
108fn may_start(req: &InjectionRequest) -> bool {
109    req.sig_verified != Some(false)
110}
111
112/// Whose starts per minute a message-started agent counts against: the sender's uid, which its token
113/// attributed (the same key `Agents start` uses, so one agent has one budget across both paths), else
114/// the name it sent as.
115fn sender_key(req: &InjectionRequest) -> String {
116    if !req.audit_source_uid.is_empty() {
117        return req.audit_source_uid.clone();
118    }
119    req.source_agent.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| "unknown".to_string())
120}
121
122/// What became of the start a held message asked for.
123pub(super) enum HeldStart {
124    /// A start was launched; the sender is told so, and does not send the message again.
125    Starting,
126    /// A limit would refuse the start (the reason, as `agent_lifecycle::start_blocked` gives it), so none
127    /// was launched; the sender is told why, not that it is starting.
128    Blocked(String),
129    /// The setting or the sender does not allow a start.
130    No,
131}
132
133impl HeldStart {
134    /// What the sender is told about the held message for the stopped agent `target`.
135    pub(super) fn not_running_text(&self, target: &str) -> String {
136        match self {
137            Self::Starting => format!("agent {target} is not running — starting it, the message is delivered as soon as it is up (held for up to 24 h if the start fails)"),
138            Self::Blocked(why) => format!("agent {target} is not running and was not started — held for up to 24 h, delivered when it starts. {why}"),
139            Self::No => format!("agent {target} is not running — held for delivery on this AgentMux instance for up to 24 h"),
140        }
141    }
142
143    /// Adds what the answer says about the start: `starting`, or `start_blocked` with the reason.
144    pub(super) fn annotate(&self, answer: &mut serde_json::Value) {
145        match self {
146            Self::Starting => answer["starting"] = serde_json::json!(true),
147            Self::Blocked(why) => answer["start_blocked"] = serde_json::json!(why),
148            Self::No => {}
149        }
150    }
151}
152
153/// A message was held for the stopped agent `target_uid`: start it in the background unless a limit would
154/// refuse it. The row stays held and the replay delivers it once the agent registers, so a failed start
155/// loses nothing.
156pub(super) fn start_for_held(state: &AppState, req: &InjectionRequest, target_uid: &str) -> HeldStart {
157    if !starts_the_agent(enabled(state) && may_start(req)) {
158        return HeldStart::No;
159    }
160    if let Some(why) = super::agent_lifecycle::start_blocked(state, target_uid) {
161        tracing::info!(target_uid = %target_uid, "message for a stopped agent: not starting it, the message stays held: {why}");
162        return HeldStart::Blocked(why);
163    }
164    let (state, uid) = (state.clone(), target_uid.to_string());
165    let sender = sender_key(req);
166    tokio::spawn(async move {
167        match start_once(&state, &uid, &sender).await {
168            Ok(()) => tracing::info!(target_uid = %uid, "message for a stopped agent: started it, the held message follows"),
169            Err(e) => tracing::warn!(target_uid = %uid, "message for a stopped agent: could not start it, the message stays held: {e}"),
170        }
171    });
172    HeldStart::Starting
173}
174
175/// Deliver a Job or cron fire. With the setting on, a target that is an agent of this instance and runs
176/// nowhere is started first and waited for, then the fire goes the normal way: before this, a signed-in
177/// instance would have queued the fire to the cloud as delivered while the local agent stayed stopped.
178pub(crate) async fn deliver_cron(state: &AppState, creator_uid: &str, mut req: InjectionRequest) -> serde_json::Value {
179    name_the_proof(state, &mut req);
180    if starts_the_agent(enabled(state)) {
181        let sender = if creator_uid.is_empty() { "job".to_string() } else { format!("job:{creator_uid}") };
182        start_stopped_local_target(state, &req.target_agent, &sender).await;
183    }
184    super::reactive::deliver(state, super::ReactiveAuthVia::FullAuthKey, creator_uid, req).await
185}
186
187/// Name who a scheduled fire runs for, from the agent's own record here: the marker shows that name, never one a
188/// request carried. An agent that no longer exists here names no one, so the fire goes unproven.
189fn name_the_proof(state: &AppState, req: &mut InjectionRequest) {
190    let Some(fire) = req.scheduler_fire.as_mut() else { return };
191    if !fire.runs_for.is_empty() {
192        return;
193    }
194    match state.mstore.agent_def_get(&fire.proof_uid) {
195        Ok(Some(def)) if !def.slug.trim().is_empty() => fire.runs_for = def.slug.clone(),
196        _ => req.scheduler_fire = None,
197    }
198    req.prove_scheduler_fire(); // before anything reads the verdict, a hold included (`types.rs`)
199}
200
201/// Start the agent `target` names when it is defined here and runs nowhere (not here, not in another
202/// channel on this computer, not by a lease held elsewhere), and wait for it to register.
203async fn start_stopped_local_target(state: &AppState, target: &str, sender_key: &str) {
204    let mstore = state.mstore.clone();
205    let name = target.to_string();
206    let Some((uid, slug)) = tokio::task::spawn_blocking(move || super::reactive::defined_here(&mstore, &name)).await.ok().flatten() else {
207        return;
208    };
209    let running_elsewhere = || {
210        crate::registry::resolve_shared_reactive_dir().is_some_and(|dir| {
211            crate::backend::jobs::registered_in_another_channel(&dir, &uid, &crate::backend::reactive::registry::local_channel_id())
212        }) || crate::muxbus::wan_lease::held_elsewhere(&slug).is_some()
213    };
214    if state.reactive_handler.has_uid_registration(&uid) || running_elsewhere() {
215        return;
216    }
217    if let Err(e) = start_once(state, &uid, sender_key).await {
218        tracing::warn!(target_uid = %uid, "cron: could not start the stopped agent: {e}");
219        return;
220    }
221    wait_registered(state, &uid).await;
222}
223
224async fn wait_registered(state: &AppState, uid: &str) -> bool {
225    let deadline = tokio::time::Instant::now() + REGISTER_WAIT;
226    while tokio::time::Instant::now() < deadline {
227        if state.reactive_handler.has_uid_registration(uid) {
228            return true;
229        }
230        tokio::time::sleep(REGISTER_POLL).await;
231    }
232    state.reactive_handler.has_uid_registration(uid)
233}
234
235#[cfg(test)]
236mod tests;