Skip to main content

agentmux_srv/server/
quiet_remote.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! The quiet note between machines, the srv half (`docs/specs/SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md`
4//! section 19; the closed note itself is `backend::quiet_remote`).
5//!
6//! **Sending.** The watch queues a note for a lead whose seat names another machine (`Name@machine`). Every few seconds
7//! this sends what is queued as a jekt signed by this machine's own sender key, the one a Swarm broadcast uses, to the
8//! one LAN peer that lists the lead. A lead whose machine is not exactly one listed peer, or whose key this machine has
9//! not pinned, is not sent to; that is logged once. A peer that does not answer loses the note: it is about a moment.
10//!
11//! **Receiving.** A jekt from another machine's sender key whose text starts like a quiet note is never delivered as a
12//! jekt. It is accepted only if the signature verified, the install that vouches for the sender key is one this machine
13//! trusts, the sender is a LAN peer that lists the named worker, and the lead is a running agent here. What the lead then
14//! reads is written here from the closed fields (`quiet_remote::render`), held for its next turn like every other quiet
15//! note, and limited to four an hour per lead and sending machine.
16
17use std::sync::{LazyLock, Mutex};
18use std::time::Duration;
19
20use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
21use serde_json::{json, Value};
22
23use super::AppState;
24use crate::backend::lan::discovery::LanInstance;
25use crate::backend::lan::swarm_broadcast as lan;
26use crate::backend::quiet_remote::{self as note, Admit, Note};
27use crate::backend::swarm_remote::PeerRoute;
28
29const SEND_EVERY: Duration = Duration::from_secs(5);
30
31/// Starts the sender: what the watch queued is sent every few seconds.
32pub(crate) fn install(state: AppState) {
33    tokio::spawn(async move {
34        let mut tick = tokio::time::interval(SEND_EVERY);
35        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
36        loop {
37            tick.tick().await;
38            for out in note::drain() {
39                send_one(&state, &out).await;
40            }
41        }
42    });
43}
44
45/// The one LAN peer that is `machine` and lists `lead`, or why none: a machine that is not a peer, or lists no such
46/// agent, or is two peers of that name (the seat then has to say which).
47pub(crate) fn peer_for<'a>(peers: &'a [LanInstance], lead: &str, machine: &str) -> Result<&'a LanInstance, &'static str> {
48    let listed: Vec<&LanInstance> = peers
49        .iter()
50        .filter(|p| p.hostname.trim().eq_ignore_ascii_case(machine.trim()) && p.agents.iter().any(|a| a.eq_ignore_ascii_case(lead)))
51        .collect();
52    match listed.as_slice() {
53        [one] => Ok(one),
54        [] => Err("that machine is not a LAN peer here that lists the lead"),
55        _ => Err("that machine is more than one LAN peer that lists the lead"),
56    }
57}
58
59async fn send_one(state: &AppState, out: &note::Outgoing) {
60    let Some((lead, machine)) = note::lead_parts(&out.lead) else { return };
61    let drop_once = |why: &str| {
62        if note::first_drop(&format!("{}:{why}", out.lead)) {
63            tracing::info!(lead = %out.lead, why, "quiet note not sent to a lead on another machine");
64        }
65    };
66    let peers = state.lan_discovery.get_instances();
67    let peer = match peer_for(&peers, lead, machine) {
68        Ok(p) => p,
69        Err(why) => return drop_once(why),
70    };
71    if !matches!(state.mstore.lan_peer_pubkey_pin_since(lead), Ok(Some(_))) {
72        return drop_once("this machine has not pinned the lead's key");
73    }
74    let sender = lan::this_sender_id(&state.hostname);
75    let Ok(pair) = state.mstore.agent_lan_key_ensure(&sender) else { return drop_once("this machine's sender key is unreadable") };
76    let msg_id = uuid::Uuid::new_v4().to_string();
77    let Some(req) = lan::signed_request(&sender, &pair.private_key, lead, &out.note.wire(), &msg_id, agentmux_common::time::now_secs()) else {
78        return drop_once("this machine's sender key is unusable");
79    };
80    let route = PeerRoute { url: crate::backend::lan::discovery::peer_base_url(&peer.address, peer.port), auth_key: peer.auth_key.clone() };
81    if let Err(e) = lan::send(&state.http_client, &route, &req).await {
82        tracing::debug!(lead = %out.lead, error = %e, "quiet note not taken by the lead's machine");
83    }
84}
85
86/// What the receiving side decided about a text that claims to be a quiet note.
87#[derive(Debug, PartialEq, Eq)]
88pub(crate) enum Verdict {
89    /// Not from a machine's sender key, or not a quiet note: delivered as any jekt is.
90    Ordinary,
91    Refuse(&'static str),
92    Accept { note: Note, machine: String },
93}
94
95/// Whether `sender` is a machine's own sender name (`swarm-<host>-<hash>`).
96fn is_machine_sender(sender: &str) -> bool {
97    sender.starts_with("swarm-") && crate::backend::reactive::sanitize::validate_agent_id(sender)
98}
99
100/// The decision, from what was proven: `verified` is the signature check's outcome, `install_ok` whether the install that
101/// vouches for the sender key is one this machine trusts. Pure, so each refusal has a test.
102pub(crate) fn judge(text: &str, sender: &str, verified: Option<bool>, install_ok: bool, peers: &[LanInstance]) -> Verdict {
103    if !note::is_quiet_note(text) || !is_machine_sender(sender) {
104        return Verdict::Ordinary;
105    }
106    if verified != Some(true) {
107        return Verdict::Refuse("the sender is not proven");
108    }
109    if !install_ok {
110        return Verdict::Refuse("the install that vouches for the sender is not approved here");
111    }
112    let Some(n) = note::parse(text) else { return Verdict::Refuse("not a quiet note") };
113    let hosts: Vec<&LanInstance> = peers.iter().filter(|p| lan::instance_sender_id(p.hostname.trim(), &p.channel) == sender.to_lowercase()).collect();
114    let [peer] = hosts.as_slice() else { return Verdict::Refuse("the sender is not one LAN peer here") };
115    if !peer.agents.iter().any(|a| a.eq_ignore_ascii_case(&n.agent)) {
116        return Verdict::Refuse("the named agent is not on the sending machine");
117    }
118    Verdict::Accept { note: n, machine: peer.hostname.trim().to_string() }
119}
120
121static LIMITER: LazyLock<Mutex<note::Limiter>> = LazyLock::new(Default::default);
122
123/// Whether the install behind `sender`'s pinned key is one this machine trusts: its certificate verifies for exactly
124/// that key, and the install is approved (not new, not revoked).
125pub(crate) async fn install_approved(state: &AppState, sender: &str) -> bool {
126    let Ok(Some((pinned, _))) = state.mstore.lan_peer_pubkey_pin_since(sender) else { return false };
127    let Ok(key) = BASE64.decode(pinned) else { return false };
128    let Some(cert) = state.lan_discovery.cached_lan_cert(sender) else { return false };
129    if super::reactive::lan_continuity::check_cert(&cert, sender, &key, 0, agentmux_common::time::now_secs()).is_err() {
130        return false;
131    }
132    super::lan_watch::during("install trust check", super::reactive::lan_continuity::instance_trust(state, &cert.instance_id)).await.is_ok()
133}
134
135/// Settles the claim on the note's message id: a note that was taken is counted, so a copy of it is not proven again;
136/// one that was refused releases it, as any refused jekt does. Returns `answer` unchanged.
137fn finish(replay: &mut super::reactive::replay::Reservation, answer: Value) -> Value {
138    if answer["success"] == true {
139        replay.delivered();
140    }
141    answer
142}
143
144/// Puts the note, or the line that stands for the ones past the limit, where the lead reads it. A note joins a running turn
145/// or is held for the next, and never starts one. The folded line is only ever held, under one key: written into a running
146/// turn it could not be replaced by the next, and each note past the limit would be a message of its own.
147fn place(block_id: &str, sender: &str, machine: &str, ts: i64, n: &Note, admit: Admit) {
148    match admit {
149        Admit::Show => {
150            crate::backend::blockcontroller::system_note_into_turn_or_hold(block_id, &format!("lan-quiet:{sender}:{}", n.agent.to_lowercase()), &note::render(sender, machine, ts, n));
151        }
152        Admit::Fold { more } => crate::backend::reactive::held_notes::hold(block_id, &format!("lan-quiet-more:{sender}"), &note::render_folded(sender, machine, ts, more)),
153    }
154}
155
156fn answer(req_id: &str, ok: bool, error: &str) -> Value {
157    if ok {
158        json!({ "success": true, "request_id": req_id, "handled": "quiet-note" })
159    } else {
160        json!({ "success": false, "refused": true, "request_id": req_id, "error": error })
161    }
162}
163
164/// A jekt that claims to be a quiet note: answered here (`Some`), never delivered as a jekt. `None` for every other jekt.
165pub(crate) async fn intercept(state: &AppState, req: &crate::backend::reactive::types::InjectionRequest, replay: &mut super::reactive::replay::Reservation) -> Option<Value> {
166    intercept_among(state, req, replay, state.lan_discovery.get_instances()).await
167}
168
169/// [`intercept`] with the LAN peers named, so the whole path can be run with the peers a test lists.
170async fn intercept_among(state: &AppState, req: &crate::backend::reactive::types::InjectionRequest, replay: &mut super::reactive::replay::Reservation, peers: Vec<LanInstance>) -> Option<Value> {
171    let sender = req.source_agent.as_deref().unwrap_or_default();
172    if req.delivery_tier.as_deref() != Some("lan") || !note::is_quiet_note(&req.message) || !is_machine_sender(sender) {
173        return None;
174    }
175    let req_id = req.request_id.clone().unwrap_or_default();
176    let install_ok = req.lan_verified == Some(true) && install_approved(state, sender).await;
177    let (n, machine) = match judge(&req.message, sender, req.lan_verified, install_ok, &peers) {
178        Verdict::Ordinary => return None,
179        Verdict::Refuse(why) => {
180            tracing::info!(sender, why, "quiet note from another machine not accepted");
181            return Some(answer(&req_id, false, why));
182        }
183        Verdict::Accept { note, machine } => (note, machine),
184    };
185    let Some(lead) = state.reactive_handler.get_delivery_target(&req.target_agent) else {
186        return Some(answer(&req_id, false, "the lead is not a running agent here"));
187    };
188    let now_ms = agentmux_common::time::now_ms_u64();
189    let ts = (now_ms / 1000) as i64;
190    let admit = LIMITER.lock().unwrap_or_else(|e| e.into_inner()).admit(&lead.agent_id, &machine, now_ms);
191    place(&lead.block_id, sender, &machine, ts, &n, admit);
192    Some(finish(replay, answer(&req_id, true, "")))
193}
194
195#[cfg(test)]
196#[path = "quiet_remote_tests.rs"]
197mod tests;