agentmux_srv_core/backend/
quiet_remote.rs1use std::collections::HashMap;
12use std::sync::{LazyLock, Mutex};
13
14use serde::{Deserialize, Serialize};
15
16use crate::backend::reactive::sanitize::{neutralize_markers, quote_in_system_note};
17
18pub const PREFIX: &str = "QUIET-NOTE ";
20const MAX_TASKS: usize = 8;
22const MAX_LAST: usize = 120;
23const MAX_NAME: usize = agentmux_common::slug::AGENT_ID_MAX_LEN;
24const MAX_MINUTES: u64 = 100_000;
25pub const SHOWN_PER_HOUR: usize = 4;
27const HOUR_MS: u64 = 60 * 60 * 1000;
28const OUTBOX_MAX: usize = 32;
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct Note {
35 pub agent: String,
37 pub state: String,
39 pub minutes: u64,
40 pub tasks: Vec<i64>,
42 pub last: String,
44}
45
46fn clean_name(raw: &str) -> String {
50 let kept: String = agentmux_common::slug::agent_route_name(raw.trim()).chars().filter(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | ' ')).collect();
51 kept.trim().chars().take(MAX_NAME).collect()
52}
53
54fn clean_last(raw: &str) -> String {
55 quote_in_system_note(raw).chars().take(MAX_LAST).collect::<String>().trim().to_string()
56}
57
58impl Note {
59 pub fn new(agent: &str, running: bool, minutes: u64, tasks: &[i64], last: &str) -> Note {
61 let mut nums: Vec<i64> = tasks.iter().copied().filter(|n| *n > 0).collect();
62 nums.sort_unstable();
63 nums.dedup();
64 nums.truncate(MAX_TASKS);
65 Note { agent: clean_name(agent), state: if running { "running" } else { "idle" }.to_string(), minutes: minutes.min(MAX_MINUTES), tasks: nums, last: clean_last(last) }
66 }
67
68 pub fn wire(&self) -> String {
70 format!("{PREFIX}{}", serde_json::to_string(self).unwrap_or_default())
71 }
72}
73
74pub fn is_quiet_note(text: &str) -> bool {
76 text.starts_with(PREFIX)
77}
78
79pub fn parse(text: &str) -> Option<Note> {
82 let note: Note = serde_json::from_str(text.strip_prefix(PREFIX)?).ok()?;
83 if (note.state != "idle" && note.state != "running") || !note.agent.chars().any(char::is_alphanumeric) {
84 return None;
85 }
86 let clean = Note::new(¬e.agent, note.state == "running", note.minutes, ¬e.tasks, ¬e.last);
87 (!clean.agent.is_empty()).then_some(clean)
88}
89
90fn tasks_words(tasks: &[i64]) -> String {
91 match tasks {
92 [] => String::new(),
93 _ => format!(" on {}", tasks.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")),
94 }
95}
96
97pub fn render(sender: &str, machine: &str, ts_secs: i64, note: &Note) -> String {
101 let machine = clean_name(machine);
102 let state = if note.state == "running" { "Its turn is still running but has written nothing." } else { "It is idle." };
103 let last = if note.last.is_empty() { String::new() } else { format!(" Its last words: \"{}\"", note.last) };
104 let body = format!("Your agent {} (on {machine}) has been quiet for {} min{}. {state}{last}", note.agent, note.minutes, tasks_words(¬e.tasks));
105 block(sender, ts_secs, &body)
106}
107
108pub fn render_folded(sender: &str, machine: &str, ts_secs: i64, more: usize) -> String {
110 let what = if more == 1 { "1 more quiet note".to_string() } else { format!("{more} more quiet notes") };
111 block(sender, ts_secs, &format!("{what} from {} in the last hour, not shown here.", clean_name(machine)))
112}
113
114fn block(sender: &str, ts_secs: i64, body: &str) -> String {
115 let from: String = sender.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
116 format!("[BULLETIN:FROM={from} TRUST=lan-verified INSTANCE_STATUS=approved TS={ts_secs}]\n{}\n[/BULLETIN]", neutralize_markers(body))
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Admit {
122 Show,
124 Fold { more: usize },
126}
127
128#[derive(Default)]
130pub struct Limiter {
131 seen: HashMap<(String, String), Vec<u64>>,
132}
133
134impl Limiter {
135 pub fn admit(&mut self, lead: &str, machine: &str, now_ms: u64) -> Admit {
136 let times = self.seen.entry((lead.to_lowercase(), machine.to_lowercase())).or_default();
137 times.retain(|t| now_ms.saturating_sub(*t) < HOUR_MS);
138 times.push(now_ms);
139 let n = times.len();
140 if self.seen.len() > 256 {
141 self.seen.retain(|_, v| v.last().is_some_and(|t| now_ms.saturating_sub(*t) < HOUR_MS));
142 }
143 if n <= SHOWN_PER_HOUR {
144 Admit::Show
145 } else {
146 Admit::Fold { more: n - SHOWN_PER_HOUR }
147 }
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct Outgoing {
154 pub lead: String,
155 pub note: Note,
156}
157
158static OUTBOX: LazyLock<Mutex<Vec<Outgoing>>> = LazyLock::new(Default::default);
159
160pub fn queue(lead: &str, note: Note) {
162 let mut outbox = OUTBOX.lock().unwrap_or_else(|e| e.into_inner());
163 outbox.retain(|o| !(o.lead.eq_ignore_ascii_case(lead) && o.note.agent == note.agent));
164 if outbox.len() >= OUTBOX_MAX {
165 outbox.remove(0);
166 }
167 outbox.push(Outgoing { lead: lead.to_string(), note });
168}
169
170pub fn drain() -> Vec<Outgoing> {
172 std::mem::take(&mut *OUTBOX.lock().unwrap_or_else(|e| e.into_inner()))
173}
174
175pub fn lead_parts(lead: &str) -> Option<(&str, &str)> {
177 let (name, machine) = lead.split_once('@')?;
178 (!name.is_empty() && !machine.is_empty()).then_some((name, machine))
179}
180
181static DROPPED: LazyLock<Mutex<std::collections::HashSet<String>>> = LazyLock::new(Default::default);
182
183pub fn first_drop(key: &str) -> bool {
185 DROPPED.lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_lowercase())
186}
187
188#[cfg(test)]
189#[path = "quiet_remote_tests.rs"]
190mod tests;