Skip to main content

agentmux_srv_core/backend/
quiet_remote.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! A quiet agent whose lead is on another machine: the note that machine's AgentMux sends over the LAN, and what the
4//! lead's machine accepts of it (`docs/specs/SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md` section 19).
5//!
6//! The sending side builds a [`Note`] of closed fields and queues it ([`queue`]); `srv` sends it as a jekt signed by the
7//! machine's own sender key. The receiving side checks who sent it (in `srv`), parses it strictly ([`parse`]), limits
8//! how many it shows ([`Limiter`]) and writes the lead's copy itself ([`render`]): nothing the sender wrote reaches the
9//! lead except the closed fields, cleaned again here.
10
11use 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
18/// What a quiet note's text starts with. The text after it is one JSON object of exactly the fields of [`Note`].
19pub const PREFIX: &str = "QUIET-NOTE ";
20/// The most task numbers, characters of the last line and characters of a name that are kept.
21const 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;
25/// A lead is shown this many quiet notes an hour from one machine; the rest are folded into one line.
26pub const SHOWN_PER_HOUR: usize = 4;
27const HOUR_MS: u64 = 60 * 60 * 1000;
28/// Notes waiting to be sent, at most (the oldest is dropped: a note is about a moment).
29const OUTBOX_MAX: usize = 32;
30
31/// The whole of a quiet note. A field that is not here is not sent, and a text with any other field is not a note.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct Note {
35    /// The quiet agent's name.
36    pub agent: String,
37    /// `idle` (its turn ended) or `running` (its turn runs and has written nothing).
38    pub state: String,
39    pub minutes: u64,
40    /// The numbers of the tasks it owes.
41    pub tasks: Vec<i64>,
42    /// The end of its last line, one line, at most 120 characters, with marker text quoted. May be empty.
43    pub last: String,
44}
45
46/// The agent's name as the LAN lists it (its route name, `Loap #3` is `Loap-3`), kept to the characters a name may hold.
47/// The receiving machine compares it with the agents the sending machine lists, so it must be that name and not the
48/// definition's display text.
49fn 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    /// The note for `agent`, every field cleaned to what it may hold.
60    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    /// The text that is sent: the prefix and the note as JSON.
69    pub fn wire(&self) -> String {
70        format!("{PREFIX}{}", serde_json::to_string(self).unwrap_or_default())
71    }
72}
73
74/// Whether `text` claims to be a quiet note.
75pub fn is_quiet_note(text: &str) -> bool {
76    text.starts_with(PREFIX)
77}
78
79/// The note in `text`, or `None` when it is not exactly one: another field, a state that is not `idle` or `running`, no
80/// agent name. The fields are cleaned again, whatever the sender did.
81pub 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(&note.agent, note.state == "running", note.minutes, &note.tasks, &note.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
97/// What the lead reads for `note`, from `sender` (the machine's sender name, as proven here) at `ts_secs`: a block with
98/// its own marker, the trust line this machine computed and the words this machine wrote. It is not an `[AgentMux]`
99/// note: those are this machine's own.
100pub 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(&note.tasks));
105    block(sender, ts_secs, &body)
106}
107
108/// The one line that stands for the notes past the limit.
109pub 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/// What the limiter says of one more note.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Admit {
122    /// Show it.
123    Show,
124    /// Past the limit: show `more` notes' worth as one line instead (all the notes beyond the shown ones in the hour).
125    Fold { more: usize },
126}
127
128/// How many quiet notes each lead has had from each sending machine in the last hour.
129#[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/// A note waiting to be sent to the lead `lead` (`Name@machine`).
152#[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
160/// Queue `note` for the lead `lead`. A later note about the same agent for the same lead replaces the one waiting.
161pub 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
170/// Everything waiting, oldest first.
171pub fn drain() -> Vec<Outgoing> {
172    std::mem::take(&mut *OUTBOX.lock().unwrap_or_else(|e| e.into_inner()))
173}
174
175/// `Name@machine` as `(Name, machine)`.
176pub 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
183/// True the first time it is asked for `key`: a drop is logged once, not at every quiet.
184pub 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;