1use std::collections::HashMap;
23use std::time::Duration;
24
25use crate::backend::agent_state::{agent_status_of_block, AgentState};
26use crate::backend::{blockcontroller, obj};
27
28use super::AppState;
29
30pub const SETTING_IDLE_STOP_MINUTES: &str = "agents:idle_stop_minutes";
31pub const SETTING_MAX_RUNNING: &str = "agents:max_running";
32pub const SETTING_COMMIT_LIMIT_PCT: &str = "agents:commit_limit_pct";
33pub const META_IDLE_STOP_MINUTES: &str = "agent:idle_stop_minutes";
35
36const DEFAULT_IDLE_STOP_MINUTES: f64 = 60.0;
37const DEFAULT_MAX_RUNNING: f64 = 24.0;
38const DEFAULT_COMMIT_LIMIT_PCT: f64 = 85.0;
39const SWEEP_EVERY: Duration = Duration::from_secs(60);
41
42#[derive(Debug, Clone, Copy, PartialEq)]
44pub(crate) struct Policy {
45 pub idle_stop_ms: Option<u64>,
46 pub max_running: Option<usize>,
47 pub commit_limit_pct: Option<f64>,
48}
49
50impl Policy {
51 pub(crate) fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
52 let num = |key: &str, default: f64| extra.get(key).and_then(|v| v.as_f64()).unwrap_or(default);
53 let on = |n: f64| (n > 0.0).then_some(n);
54 Self {
55 idle_stop_ms: on(num(SETTING_IDLE_STOP_MINUTES, DEFAULT_IDLE_STOP_MINUTES)).map(|m| (m * 60_000.0) as u64),
56 max_running: on(num(SETTING_MAX_RUNNING, DEFAULT_MAX_RUNNING)).map(|n| n as usize),
57 commit_limit_pct: on(num(SETTING_COMMIT_LIMIT_PCT, DEFAULT_COMMIT_LIMIT_PCT)),
58 }
59 }
60}
61
62fn policy(state: &AppState) -> Policy {
63 Policy::from_extra(&state.config_watcher.get_full_config().settings.extra)
64}
65
66#[derive(Debug, Clone)]
68pub(crate) struct Live {
69 pub block_id: String,
70 pub agent_id: String,
72 pub uid: String,
73 pub parked: bool,
75 pub state: Option<AgentState>,
76 pub since_ms: u64,
77 pub idle_override: Option<Option<u64>>,
79}
80
81impl Live {
82 pub(crate) fn evictable(&self) -> bool {
84 self.parked && self.state == Some(AgentState::Idle) && self.idle_override != Some(None)
85 }
86
87 pub(crate) fn idle_expired(&self, now_ms: u64, default_ms: Option<u64>) -> bool {
89 let window = self.idle_override.unwrap_or(default_ms);
90 self.evictable() && window.is_some_and(|w| now_ms.saturating_sub(self.since_ms) >= w)
91 }
92}
93
94fn view_lost_at() -> &'static std::sync::Mutex<HashMap<String, u64>> {
97 static LOST: std::sync::OnceLock<std::sync::Mutex<HashMap<String, u64>>> = std::sync::OnceLock::new();
98 LOST.get_or_init(Default::default)
99}
100
101fn idle_from_view_lost(lost: &mut HashMap<String, u64>, lives: &mut [Live], now: u64) {
104 lost.retain(|block_id, _| lives.iter().any(|l| l.parked && l.block_id == *block_id));
105 for l in lives.iter_mut().filter(|l| l.parked) {
106 let first_parked = *lost.entry(l.block_id.clone()).or_insert(now);
107 l.since_ms = l.since_ms.max(first_parked);
108 }
109}
110
111pub(crate) fn idle_override_of(block: &obj::Block) -> Option<Option<u64>> {
113 block.meta.get(META_IDLE_STOP_MINUTES).and_then(|v| v.as_f64()).map(|m| (m > 0.0).then(|| (m * 60_000.0) as u64))
114}
115
116pub(crate) fn idle_window_of(state: &AppState, block: &obj::Block) -> Option<u64> {
118 idle_override_of(block).unwrap_or(policy(state).idle_stop_ms)
119}
120
121pub(crate) fn live_agents(state: &AppState) -> Vec<Live> {
123 let mstore = &state.mstore;
124 let now = agentmux_common::time::now_ms_u64();
125 let Ok(blocks) = super::app_api::agent_block::blocks_in_tabs_or_parked(mstore) else {
126 return Vec::new();
127 };
128 let mut lives: Vec<Live> = blocks
129 .into_iter()
130 .filter_map(|(block, tab)| {
131 let controller = blockcontroller::get_controller(&block.oid)?;
132 if controller.get_runtime_status().shellprocstatus != blockcontroller::STATUS_RUNNING {
133 return None;
134 }
135 let agent = crate::sagas::park_agents::agent_of_block(state, &block.oid, &block)?;
136 let slug = mstore.agent_def_get(&agent.id).ok().flatten().map(|d| d.slug).filter(|s| !s.is_empty());
137 let status = agent_status_of_block(mstore, &block.oid);
138 let idle_override = idle_override_of(&block);
139 Some(Live {
140 block_id: block.oid.clone(),
141 agent_id: slug.unwrap_or_else(|| agent.id.clone()),
142 uid: agent.id,
143 parked: tab.is_none(),
144 state: status.map(|s| s.state),
145 since_ms: status.map_or(now, |s| s.since_ms),
146 idle_override,
147 })
148 })
149 .collect();
150 idle_from_view_lost(&mut view_lost_at().lock().unwrap_or_else(|e| e.into_inner()), &mut lives, now);
151 lives
152}
153
154pub(crate) fn running_agent_ids(state: &AppState) -> std::collections::HashSet<String> {
158 live_agents(state).into_iter().map(|l| l.uid).collect()
159}
160
161pub(crate) fn exempt(state: &AppState, live: &Live) -> Option<&'static str> {
164 exempt_agent(state, &live.agent_id, &live.uid)
165}
166
167pub(crate) fn exempt_agent(state: &AppState, agent_id: &str, uid: &str) -> Option<&'static str> {
170 match state.work_store.work_queue_claimed_by(agent_id, uid) {
172 Ok(claimed) if claimed.is_empty() => {}
173 Ok(_) => return Some("holds a claimed task"),
174 Err(_) => return Some("its claimed tasks could not be read"),
175 }
176 match state.mstore.jekt_held_targets() {
177 Ok(held) if !held.iter().any(|t| t == uid) => {}
178 Ok(_) => return Some("has a held message"),
179 Err(_) => return Some("its held messages could not be read"),
180 }
181 if build_slot_holder().is_some_and(|holder| holder.eq_ignore_ascii_case(agent_id)) {
182 return Some("holds the build slot");
183 }
184 None
185}
186
187fn build_slot_holder() -> Option<String> {
189 let owner = dirs::home_dir()?.join(".agentmux").join("shared").join("locks").join("build").join("slot").join("owner");
190 holder_in(&std::fs::read_to_string(owner).ok()?)
191}
192
193fn holder_in(owner_file: &str) -> Option<String> {
195 owner_file.lines().find_map(|l| l.strip_prefix("agent=")).map(|a| a.trim().to_string()).filter(|a| !a.is_empty())
196}
197
198async fn stop(state: &AppState, live: &Live, why: &str) -> bool {
200 match crate::sagas::agent_teardown::stop(state, &live.block_id, true, None).await {
201 Ok(_) => {
202 tracing::info!(agent = %live.agent_id, block_id = %live.block_id, "agent lifecycle: stopped it ({why})");
203 true
204 }
205 Err(e) => {
206 tracing::warn!(agent = %live.agent_id, block_id = %live.block_id, "agent lifecycle: could not stop it ({why}): {e}");
207 false
208 }
209 }
210}
211
212fn stop_note(victim: &str, started: &str, why: &str, goal: Option<&str>) -> String {
215 let mut note = format!("Your agent {victim} was stopped to make room for starting {started} ({why}).");
216 if let Some(goal) = goal.map(str::trim).filter(|g| !g.is_empty()) {
217 let short: String = goal.chars().take(160).collect();
218 note.push_str(&format!(" It was working on: {short}{}.", if short.len() < goal.len() { "…" } else { "" }));
219 }
220 note.push_str(" Start it again with Agents start once there is room.");
221 note
222}
223
224fn tell_leader_of_stop(state: &AppState, victim: &Live, started: &str, why: &str) {
227 let name_of = |id: &str| state.mstore.agent_def_get(id).ok().flatten().map(|d| d.name).unwrap_or_else(|| id.to_string());
228 let goal = state.mstore.get::<obj::Block>(&victim.block_id).ok().flatten().and_then(|b| crate::backend::work_facts::goal_of(&b.meta));
229 let note = stop_note(&name_of(&victim.uid), &name_of(started), why, goal.as_deref());
230 if !crate::backend::worker_notes::tell_leader(&state.mstore, &victim.uid, ¬e) {
231 tracing::info!(agent = %victim.agent_id, "agent lifecycle: no leader to tell that it was stopped to make room");
232 }
233}
234
235pub(crate) async fn sweep_once(state: &AppState) -> usize {
238 if !crate::sagas::park_agents::enabled(state) {
239 return 0;
240 }
241 let default_ms = policy(state).idle_stop_ms;
242 let now = agentmux_common::time::now_ms_u64();
243 let mut stopped = 0;
244 for live in live_agents(state) {
245 if live.idle_expired(now, default_ms) && exempt(state, &live).is_none() && stop(state, &live, "idle with no view").await {
246 stopped += 1;
247 }
248 }
249 stopped
250}
251
252pub(crate) fn install(state: &AppState) {
254 super::agent_wanted_running::install(state.broker.clone(), state.mstore.clone(), state.event_bus.clone());
256 let state = state.clone();
257 tokio::spawn(async move {
258 loop {
259 tokio::time::sleep(SWEEP_EVERY).await;
260 sweep_once(&state).await;
261 }
262 });
263}
264
265pub(crate) fn commit_used_pct() -> Option<f64> {
269 #[cfg(target_os = "windows")]
270 {
271 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
272 let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
273 mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
274 if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 && mem.ullTotalPageFile > 0 {
275 return Some((mem.ullTotalPageFile - mem.ullAvailPageFile) as f64 / mem.ullTotalPageFile as f64 * 100.0);
276 }
277 }
278 None
279}
280
281pub(crate) fn commit_total_gb() -> Option<f64> {
283 #[cfg(target_os = "windows")]
284 {
285 use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
286 let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
287 mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
288 if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 && mem.ullTotalPageFile > 0 {
289 return Some(mem.ullTotalPageFile as f64 / (1024.0 * 1024.0 * 1024.0));
290 }
291 }
292 None
293}
294
295const COMMIT_FREED_BY_ONE_STOP_GB: f64 = 1.0;
298
299fn one_stop_brings_commit_down(used_pct: f64, limit_pct: f64, total_gb: Option<f64>) -> Result<(), String> {
303 let Some(total) = total_gb else { return Ok(()) };
304 let short_gb = (used_pct - limit_pct) / 100.0 * total;
305 if short_gb <= COMMIT_FREED_BY_ONE_STOP_GB {
306 return Ok(());
307 }
308 Err(format!(
309 "capacity: memory commit is at {used_pct:.0}% (the limit is {limit_pct:.0}%): about {short_gb:.1} GB has to be freed and stopping one idle agent frees about {COMMIT_FREED_BY_ONE_STOP_GB:.0} GB, so no agent was stopped. Free memory (close programs or stop agents), then start it again"
310 ))
311}
312
313fn commit_over(policy: &Policy, used_pct: Option<f64>) -> Option<(f64, f64)> {
317 match (used_pct, policy.commit_limit_pct) {
318 (Some(used), Some(limit)) if used > limit => Some((used, limit)),
319 _ => None,
320 }
321}
322
323#[derive(Debug, PartialEq)]
325enum Over {
326 Cap(String),
327 Commit(String),
328}
329
330impl Over {
331 fn why(&self) -> &str {
332 match self {
333 Over::Cap(why) | Over::Commit(why) => why,
334 }
335 }
336}
337
338fn over_limit(policy: &Policy, running: usize, commit_pct: Option<f64>) -> Option<Over> {
340 if let Some(max) = policy.max_running.filter(|max| running >= *max) {
341 return Some(Over::Cap(format!("{running} agents are running (the limit is {max})")));
342 }
343 match (policy.commit_limit_pct, commit_pct) {
344 (Some(limit), Some(used)) if used > limit => Some(Over::Commit(format!("memory commit is at {used:.0}% (the limit is {limit:.0}%)"))),
345 _ => None,
346 }
347}
348
349const PENDING_FOR: Duration = Duration::from_secs(90);
351
352type Reservation = (std::sync::Weak<crate::backend::storage::store::Store>, std::time::Instant);
356
357fn pending() -> &'static std::sync::Mutex<HashMap<String, Reservation>> {
358 static PENDING: std::sync::OnceLock<std::sync::Mutex<HashMap<String, Reservation>>> = std::sync::OnceLock::new();
359 PENDING.get_or_init(Default::default)
360}
361
362fn batch_held() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {
366 static HELD: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();
367 HELD.get_or_init(Default::default)
368}
369
370fn pending_key(state: &AppState, agent_id: &str) -> String {
372 format!("{:p}:{agent_id}", std::sync::Arc::as_ptr(&state.mstore))
373}
374
375fn pending_not_running(state: &AppState, live: &[Live]) -> usize {
379 let prefix = pending_key(state, "");
380 let mut pending = pending().lock().unwrap_or_else(|e| e.into_inner());
381 pending.retain(|key, (store, at)| {
382 if at.elapsed() >= PENDING_FOR || store.strong_count() == 0 {
383 return false;
384 }
385 match key.strip_prefix(prefix.as_str()) {
386 Some(id) => !live.iter().any(|l| l.uid == id || l.agent_id == id),
387 None => true,
388 }
389 });
390 pending.keys().filter(|key| key.starts_with(prefix.as_str())).count()
391}
392
393fn is_reserved(state: &AppState, agent_id: &str) -> bool {
395 pending().lock().unwrap_or_else(|e| e.into_inner()).get(&pending_key(state, agent_id)).is_some_and(|(store, at)| at.elapsed() < PENDING_FOR && store.strong_count() > 0)
396}
397
398fn take_batch_claim(state: &AppState, agent_id: &str) -> bool {
401 let key = pending_key(state, agent_id);
402 is_reserved(state, agent_id) && batch_held().lock().unwrap_or_else(|e| e.into_inner()).remove(&key)
403}
404
405pub(crate) fn release_start(state: &AppState, agent_id: &str) {
408 let key = pending_key(state, agent_id);
409 batch_held().lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
410 pending().lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
411}
412
413pub(crate) fn rekey_reservation(state: &AppState, from: &str, to: &str) {
417 let mut pending = pending().lock().unwrap_or_else(|e| e.into_inner());
418 let (from_key, to_key) = (pending_key(state, from), pending_key(state, to));
419 if let Some(reservation) = pending.remove(&from_key) {
420 pending.insert(to_key.clone(), reservation);
421 let mut claims = batch_held().lock().unwrap_or_else(|e| e.into_inner());
422 if claims.remove(&from_key) {
423 claims.insert(to_key);
424 }
425 }
426}
427
428fn admission() -> &'static tokio::sync::Mutex<()> {
430 static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
431 &LOCK
432}
433
434pub(crate) async fn admit_start(state: &AppState, agent_id: &str) -> Result<(), String> {
437 admit(state, agent_id, commit_used_pct, commit_total_gb, true).await
438}
439
440pub(crate) async fn admit_start_with(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>) -> Result<(), String> {
441 admit(state, agent_id, commit_pct, || None, true).await
442}
443
444#[cfg(test)]
447pub(crate) async fn admit_start_with_total(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>, commit_total: impl Fn() -> Option<f64>) -> Result<(), String> {
448 admit(state, agent_id, commit_pct, commit_total, true).await
449}
450
451pub(crate) fn start_blocked(state: &AppState, agent_id: &str) -> Option<String> {
455 start_blocked_with(state, agent_id, commit_used_pct, commit_total_gb)
456}
457
458pub(crate) fn start_blocked_with(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>, commit_total: impl Fn() -> Option<f64>) -> Option<String> {
459 let live = live_agents(state);
460 if live.iter().any(|l| l.uid == agent_id || l.agent_id == agent_id) {
461 return None;
462 }
463 if let Some(why) = state.mstore.agent_def_get(agent_id).ok().flatten().and_then(|def| crate::backend::folder_overlap::waiting_reason(&state.mstore, &def)) {
465 return Some(why);
466 }
467 if !crate::sagas::park_agents::enabled(state) || is_reserved(state, agent_id) {
468 return None;
469 }
470 let policy = policy(state);
471 let used = commit_pct();
472 let over = over_limit(&policy, live.len() + pending_not_running(state, &live), used)?;
473 if let Some((used, limit)) = commit_over(&policy, used) {
474 if let Err(why) = one_stop_brings_commit_down(used, limit, commit_total()) {
475 return Some(why);
476 }
477 }
478 let can_stop_one = live.iter().any(|l| l.evictable() && exempt(state, l).is_none());
479 (!can_stop_one).then(|| format!("capacity: {}, and no agent with no view is idle enough to stop for it", over.why()))
480}
481
482pub(crate) async fn admit_start_without_eviction(state: &AppState, agent_id: &str) -> Result<(), String> {
486 admit(state, agent_id, commit_used_pct, commit_total_gb, false).await
487}
488
489async fn admit(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>, commit_total: impl Fn() -> Option<f64>, evict: bool) -> Result<(), String> {
490 if !crate::sagas::park_agents::enabled(state) {
491 return Ok(());
492 }
493 if take_batch_claim(state, agent_id) {
495 return Ok(());
496 }
497 let policy = policy(state);
498 if policy.max_running.is_none() && policy.commit_limit_pct.is_none() {
499 return Ok(());
500 }
501 let _one_at_a_time = admission().lock().await;
502 let mut live = live_agents(state);
503 if live.iter().any(|l| l.uid == agent_id || l.agent_id == agent_id) {
504 return Ok(());
505 }
506 let mut could_not_stop = std::collections::HashSet::new();
507 let mut stopped_for_commit = None;
508 loop {
509 let used = commit_pct();
510 let Some(over) = over_limit(&policy, live.len() + pending_not_running(state, &live), used) else {
511 let reservation = (std::sync::Arc::downgrade(&state.mstore), std::time::Instant::now());
512 pending().lock().unwrap_or_else(|e| e.into_inner()).insert(pending_key(state, agent_id), reservation);
513 return Ok(());
514 };
515 if !evict {
516 return Err(format!("capacity: {}, and this start does not stop other agents", over.why()));
517 }
518 let commit_over = commit_over(&policy, used);
521 if let (Some((used, limit)), Some(stopped)) = (commit_over, &stopped_for_commit) {
522 return Err(format!("capacity: memory commit is at {used:.0}% (the limit is {limit:.0}%), and stopping {stopped} did not bring it down"));
523 }
524 if let Some((used, limit)) = commit_over {
525 one_stop_brings_commit_down(used, limit, commit_total())?;
526 }
527 let victim = live
528 .iter()
529 .filter(|l| l.evictable() && !could_not_stop.contains(&l.block_id) && exempt(state, l).is_none())
530 .min_by_key(|l| l.since_ms)
531 .cloned();
532 let Some(victim) = victim else {
533 return Err(format!("capacity: {}, and no agent with no view is idle enough to stop for it", over.why()));
534 };
535 if stop(state, &victim, &format!("to make room: {}", over.why())).await {
536 tell_leader_of_stop(state, &victim, agent_id, over.why());
537 if commit_over.is_some() {
538 stopped_for_commit = Some(victim.agent_id.clone());
539 }
540 live.retain(|l| l.block_id != victim.block_id);
541 } else {
542 could_not_stop.insert(victim.block_id);
543 }
544 }
545}
546
547pub(crate) struct Wanted {
550 pub key: String,
551 pub label: String,
552}
553
554fn names_in_words(labels: &[&str]) -> String {
556 match labels {
557 [] => String::new(),
558 [only] => (*only).to_string(),
559 [init @ .., last] => format!("{} and {last}", init.join(", ")),
560 }
561}
562
563pub(crate) async fn admit_batch(state: &AppState, wanted: &[Wanted], reserve: bool) -> Result<(), String> {
569 admit_batch_with(state, wanted, reserve, commit_used_pct).await
570}
571
572pub(crate) async fn admit_batch_with(state: &AppState, wanted: &[Wanted], reserve: bool, commit_pct: impl Fn() -> Option<f64>) -> Result<(), String> {
573 if !crate::sagas::park_agents::enabled(state) {
574 return Ok(());
575 }
576 let policy = policy(state);
577 if policy.max_running.is_none() && policy.commit_limit_pct.is_none() {
578 return Ok(());
579 }
580 let _one_at_a_time = admission().lock().await;
581 let live = live_agents(state);
582 let to_start: Vec<&Wanted> = wanted.iter().filter(|w| !live.iter().any(|l| l.uid == w.key || l.agent_id == w.key) && !is_reserved(state, &w.key)).collect();
583 if to_start.is_empty() {
584 return Ok(());
585 }
586 let running = live.len() + pending_not_running(state, &live);
587 let asked = to_start.len();
588 let room = policy.max_running.map_or(usize::MAX, |max| max.saturating_sub(running));
589 let idle = live.iter().filter(|l| l.evictable() && exempt(state, l).is_none()).count();
590 let stop_some = if idle > 0 { format!("Stop some agents ({idle} {} idle with no view), or ask for fewer.", if idle == 1 { "is" } else { "are" }) } else { "Stop some agents, or ask for fewer.".to_string() };
591 if let (Some(limit), Some(used)) = (policy.commit_limit_pct, commit_pct()) {
592 if used > limit {
593 return Err(format!("capacity: memory commit is at {used:.0}% (the limit is {limit:.0}%), so none of the {asked} asked would start. {stop_some}"));
594 }
595 }
596 if asked > room {
597 let max = policy.max_running.unwrap_or(running);
598 let labels: Vec<&str> = to_start.iter().map(|w| w.label.as_str()).collect();
599 let fit = names_in_words(&labels[..room]);
600 let rest = names_in_words(&labels[room..]);
601 let outcome = if room == 0 { format!("none of the {asked} asked would fit: {rest}") } else { format!("room for {room} of the {asked} asked: {fit} would fit, {rest} would not") };
602 return Err(format!("capacity: {running} agents are running (the limit is {max}); {outcome}. {stop_some}"));
603 }
604 if reserve {
605 let mut held = pending().lock().unwrap_or_else(|e| e.into_inner());
606 let mut claims = batch_held().lock().unwrap_or_else(|e| e.into_inner());
607 for w in to_start {
608 let key = pending_key(state, &w.key);
609 claims.insert(key.clone());
610 held.insert(key, (std::sync::Arc::downgrade(&state.mstore), std::time::Instant::now()));
611 }
612 }
613 Ok(())
614}
615
616pub(crate) fn release_batch(state: &AppState, wanted: &[Wanted]) {
619 for w in wanted {
620 release_start(state, &w.key);
621 }
622}
623
624#[cfg(test)]
625mod tests;