agentmux_srv/server/
jekt_start.rs1use 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
28const REGISTER_WAIT: Duration = Duration::from_secs(60);
30const REGISTER_POLL: Duration = Duration::from_millis(500);
31
32fn enabled(state: &AppState) -> bool {
34 crate::sagas::park_agents::enabled(state)
35}
36
37fn 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
51fn starting() -> &'static Mutex<HashSet<String>> {
53 static SET: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
54 SET.get_or_init(Default::default)
55}
56
57struct StartSlot(String);
59
60impl StartSlot {
61 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
73async 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
88pub(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
105fn may_start(req: &InjectionRequest) -> bool {
109 req.sig_verified != Some(false)
110}
111
112fn 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
122pub(super) enum HeldStart {
124 Starting,
126 Blocked(String),
129 No,
131}
132
133impl HeldStart {
134 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 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
153pub(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
175pub(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
187fn 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(); }
200
201async 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;