agentmux_mcp/
heartbeat.rs1use std::sync::Arc;
15use std::time::Duration;
16
17use serde_json::json;
18
19use crate::serve::Health;
20
21const EVERY: Duration = Duration::from_secs(15);
22const FIRST: Duration = Duration::from_secs(5);
23const LATE_AFTER: Duration = Duration::from_secs(45);
27
28fn is_late(monotonic: Duration, wall: Duration) -> bool {
31 monotonic.max(wall) > LATE_AFTER
32}
33
34pub(crate) fn beat_body(health: &Health, slug: &str, late: bool) -> serde_json::Value {
38 let oldest = if late {
39 None
40 } else {
41 health.oldest_unanswered()
42 };
43 json!({
44 "agent": slug,
45 "pid": std::process::id(),
46 "inflight": health.inflight(),
47 "oldest_tool": oldest.as_ref().map(|(t, _)| t.clone()),
48 "oldest_s": oldest.map(|(_, s)| s),
49 "runtime_lag_ms": if late { 0 } else { health.runtime_lag_ms() },
50 "call_threads": health.call_threads(),
51 })
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57
58 #[test]
59 fn a_beat_is_late_by_either_clock() {
60 let ok = Duration::from_secs(15);
61 assert!(!is_late(ok, ok));
62 assert!(is_late(Duration::from_secs(60), ok));
63 assert!(
64 is_late(ok, Duration::from_secs(3600)),
65 "a suspend the monotonic clock didn't count"
66 );
67 }
68
69 #[test]
70 fn a_beat_after_a_sleep_reports_no_lag_and_no_call_age() {
71 let h = Health::new();
72 h.begin("1".into(), "UI".into());
73 std::thread::sleep(Duration::from_millis(1100));
74 let ordinary = beat_body(&h, "a", false);
75 assert!(ordinary["runtime_lag_ms"].as_u64().unwrap() >= 1000);
76 assert_eq!(ordinary["oldest_tool"], "UI");
77 let late = beat_body(&h, "a", true);
78 assert_eq!(late["runtime_lag_ms"], 0);
79 assert!(late["oldest_tool"].is_null() && late["oldest_s"].is_null());
80 assert_eq!(late["inflight"], 1);
81 }
82}
83
84pub(crate) fn start(health: Arc<Health>, local_url: String, auth_key: String) {
87 let var = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
88 let (Some(token), Some(slug)) = (var("AGENTMUX_AGENT_TOKEN"), var("AGENTMUX_AGENT_SLUG"))
89 else {
90 return;
91 };
92 if crate::self_keys::in_container() {
95 return;
96 }
97 if local_url.is_empty() || auth_key.is_empty() {
98 return;
99 }
100 let spawned = std::thread::Builder::new()
101 .name("mcp-heartbeat".into())
102 .spawn(move || {
103 let Ok(rt) = tokio::runtime::Builder::new_current_thread()
104 .enable_all()
105 .build()
106 else {
107 return;
108 };
109 rt.block_on(async move {
111 let Ok(client) = agentmux_common::local_http::builder()
112 .timeout(Duration::from_secs(10))
113 .build()
114 else {
115 return;
116 };
117 let url = format!(
118 "{}/api/v1/agent/self/mcp-beat",
119 local_url.trim_end_matches('/')
120 );
121 tokio::time::sleep(FIRST).await;
122 let mut last = std::time::Instant::now();
123 let mut last_wall = std::time::SystemTime::now();
124 loop {
125 let late = is_late(last.elapsed(), last_wall.elapsed().unwrap_or_default());
126 last = std::time::Instant::now();
127 last_wall = std::time::SystemTime::now();
128 let body = beat_body(&health, &slug, late);
129 let _ = client
131 .post(&url)
132 .header(agentmux_common::AUTH_KEY_HEADER, &auth_key)
133 .header("X-Agent-Token", token.trim())
134 .json(&body)
135 .send()
136 .await;
137 tokio::time::sleep(EVERY).await;
138 }
139 });
140 });
141 if let Err(e) = spawned {
142 eprintln!("agentmux-mcp: couldn't start the heartbeat thread: {e}");
143 }
144}