Skip to main content

agentmux_srv_core/backend/lan/
swarm_broadcast.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Swarm broadcast to agents on a LAN peer
5//! (`docs/specs/SPEC_SWARM_REFINEMENTS_2026_10_17.md` §4.2).
6//!
7//! On this machine a broadcast is the user's own turn. On another machine it
8//! can't be: the LAN key that delivers it is readable by anything on the
9//! network and names an instance, not a person
10//! (`SPEC_SWARM_REMOTE_AGENTS_PLATFORM_TAG_AND_SELECTION_2026_10_03.md` §6). So
11//! it goes as a jekt from this instance, signed with this instance's own LAN key
12//! under a reserved sender name ([`instance_sender_id`]). The receiving instance
13//! checks it as it checks any agent's LAN jekt
14//! (`SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md`): it asks the LAN peers for the
15//! sender's public key, which this instance's `/agentmux/reactive/agent?id=`
16//! answers, pins it once a trusted install vouches for it, and marks the message `TRUST=lan-verified`.
17//! It claims no user authority: normal tier, from this instance, in its own
18//! words.
19
20use crate::backend::reactive::types::InjectionRequest;
21use crate::backend::swarm_remote::{PeerRoute, RemoteHost};
22
23/// The prefix of a Swarm selection key for an agent on another machine
24/// (the frontend's `remoteAgentKey`).
25pub const REMOTE_KEY_PREFIX: &str = "remote:";
26
27/// How long a peer gets to take the message.
28const SEND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
29
30/// This instance's sender name on the LAN: `swarm-<host>-<hash>`, a valid agent
31/// id (letters, digits, `-`, at most 39 characters). The hash of the hostname and
32/// channel keeps two instances apart, including two machines with one name, and
33/// stays the same across restarts, so a peer's first-use pin of its key holds.
34pub fn instance_sender_id(hostname: &str, channel: &str) -> String {
35    let host: String = hostname
36        .chars()
37        .filter(|c| c.is_ascii_alphanumeric() || *c == '-')
38        .take(24)
39        .collect::<String>()
40        .to_lowercase();
41    let host = if host.is_empty() { "host".to_string() } else { host };
42    let hash = crate::backend::swarm_remote::fnv1a32(&format!("{hostname}\n{channel}"));
43    format!("swarm-{host}-{hash:08x}")
44}
45
46/// This instance's own sender name.
47pub fn this_sender_id(hostname: &str) -> String {
48    instance_sender_id(hostname, &crate::backend::reactive::registry::local_channel_id())
49}
50
51/// `/agentmux/reactive/agent?id=`'s answer when `id` is this instance's own
52/// sender: its name and public key, so a peer can verify a Swarm broadcast from
53/// here. `None` for any other id, and before the first LAN broadcast minted the
54/// key, when there is nothing to verify.
55pub fn sender_lookup(store: &crate::backend::storage::store::Store, hostname: &str, id: &str) -> Option<serde_json::Value> {
56    let sender = this_sender_id(hostname);
57    if !id.eq_ignore_ascii_case(&sender) {
58        return None;
59    }
60    let pubkey = store.agent_lan_public_key_load(&sender).ok()??;
61    Some(serde_json::json!({ "agent_id": sender, "lan_public_key": pubkey }))
62}
63
64/// `remote:<host id>/<channel>/<name>` as `(section key, agent name)`, the
65/// section key being `<host id>/<channel>`. `None` for any other key.
66pub fn parse_remote_key(key: &str) -> Option<(&str, &str)> {
67    let (section, name) = key.strip_prefix(REMOTE_KEY_PREFIX)?.rsplit_once('/')?;
68    (!section.is_empty() && !name.is_empty()).then_some((section, name))
69}
70
71/// The route to the LAN instance a section key names, from the hosts the Swarm
72/// lists. `None` when it isn't a LAN instance, isn't listed, or has gone stale.
73pub fn route_for(hosts: &[RemoteHost], section_key: &str) -> Option<PeerRoute> {
74    hosts
75        .iter()
76        .filter(|h| h.tier == "lan")
77        .flat_map(|h| h.channels.iter().map(move |c| (h, c)))
78        .find(|(h, c)| !c.stale && format!("{}/{}", h.host_id, c.channel) == section_key)
79        .and_then(|(_, c)| c.route.clone())
80}
81
82/// What the receiving agent reads: where it came from and that it went to every
83/// agent selected, then the message.
84pub fn broadcast_text(hostname: &str, recipients: usize, message: &str) -> String {
85    let to = if recipients == 1 { "1 agent".to_string() } else { format!("{recipients} agents") };
86    format!("Swarm broadcast from {hostname}, sent by its operator to {to}:\n\n{message}")
87}
88
89/// The signed request for one agent. `None` when the private key is unusable.
90pub fn signed_request(sender_id: &str, private_key_b64: &str, target: &str, text: &str, msg_id: &str, ts_secs: i64) -> Option<InjectionRequest> {
91    let key = agentmux_common::jekt_sign::decode_key(private_key_b64)?;
92    let sig = agentmux_common::jekt_sign::sign_lan_jekt(&key, msg_id, sender_id, target, ts_secs, text)?;
93    Some(InjectionRequest {
94        target_agent: target.to_string(),
95        message: text.to_string(),
96        source_agent: Some(sender_id.to_string()),
97        request_id: Some(msg_id.to_string()),
98        ts_secs: Some(ts_secs),
99        lan_sig: Some(sig),
100        ..Default::default()
101    })
102}
103
104/// Sends one signed request to the peer and says whether it delivered, with the
105/// peer's reason when it didn't.
106pub async fn send(http: &reqwest::Client, route: &PeerRoute, req: &InjectionRequest) -> Result<(), String> {
107    let resp = http
108        .post(format!("{}/agentmux/reactive/inject", route.url))
109        .header(agentmux_common::AUTH_KEY_HEADER, &route.auth_key)
110        .timeout(SEND_TIMEOUT)
111        .json(req)
112        .send()
113        .await
114        .map_err(|e| format!("couldn't reach that machine: {e}"))?;
115    let status = resp.status();
116    let body: serde_json::Value = resp.json().await.unwrap_or_default();
117    if status.is_success() && body.get("success").and_then(|v| v.as_bool()) == Some(true) {
118        return Ok(());
119    }
120    Err(refusal_words(status.as_u16(), body.get("error").and_then(|v| v.as_str())))
121}
122
123/// What a peer's refusal of a send says: its own reason when it gave one. A machine too old to have the route says
124/// nothing (a bare 404 or 405): then which version to update it to.
125fn refusal_words(status: u16, reason: Option<&str>) -> String {
126    match reason {
127        Some(reason) => reason.to_string(),
128        None if matches!(status, 404 | 405) => {
129            format!("that machine's AgentMux is too old to take this: update it to AgentMux {} or newer", crate::backend::remote_panes::host::own_version())
130        }
131        None => format!("that machine answered {status}"),
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::backend::swarm_remote::RemoteChannel;
139
140    #[test]
141    fn a_machine_too_old_for_the_route_is_told_which_version_to_update_to() {
142        let own = crate::backend::remote_panes::host::own_version();
143        for status in [404, 405] {
144            assert_eq!(refusal_words(status, None), format!("that machine's AgentMux is too old to take this: update it to AgentMux {own} or newer"));
145        }
146        assert_eq!(refusal_words(404, Some("no such agent")), "no such agent", "a reason the machine gave is kept");
147        assert_eq!(refusal_words(502, None), "that machine answered 502");
148    }
149
150    #[test]
151    fn the_sender_id_is_a_valid_agent_id_and_stable() {
152        let id = instance_sender_id("Area54 (office)!", "local-main-b28b7a-1713be7f");
153        assert!(crate::backend::reactive::sanitize::validate_agent_id(&id), "{id}");
154        assert!(id.starts_with("swarm-area54office-"), "{id}");
155        assert_eq!(id, instance_sender_id("Area54 (office)!", "local-main-b28b7a-1713be7f"));
156        // Another channel, or another machine of the same name, is another sender.
157        assert_ne!(id, instance_sender_id("Area54 (office)!", "stable"));
158        let long = instance_sender_id(&"x".repeat(200), "stable");
159        assert!(long.len() <= 64 && crate::backend::reactive::sanitize::validate_agent_id(&long), "{long}");
160        assert!(instance_sender_id("", "stable").starts_with("swarm-host-"));
161    }
162
163    #[test]
164    fn a_remote_key_splits_into_its_section_and_name() {
165        assert_eq!(parse_remote_key("remote:lan:area54#1a2b3c4d/stable/Manoz"), Some(("lan:area54#1a2b3c4d/stable", "Manoz")));
166        assert_eq!(parse_remote_key("blk-123"), None);
167        assert_eq!(parse_remote_key("remote:nosep"), None);
168        assert_eq!(parse_remote_key("remote:lan:x/stable/"), None);
169    }
170
171    fn host(tier: &'static str, channel: &str, stale: bool) -> RemoteHost {
172        RemoteHost {
173            host_id: "lan:area54#1".into(),
174            display_name: "Area54".into(),
175            tier,
176            channels: vec![RemoteChannel {
177                channel: channel.into(),
178                seen_at_ms: 1,
179                stale,
180                os: String::new(),
181                agents: vec![],
182                route: Some(PeerRoute { url: "http://192.0.2.7:29700".into(), auth_key: "k".into() }),
183                paired_computer: None,
184            }],
185        }
186    }
187
188    #[test]
189    fn a_route_is_found_only_for_a_listed_fresh_lan_instance() {
190        let hosts = [host("lan", "stable", false)];
191        assert_eq!(route_for(&hosts, "lan:area54#1/stable").map(|r| r.url), Some("http://192.0.2.7:29700".to_string()));
192        assert!(route_for(&hosts, "lan:area54#1/dev").is_none());
193        assert!(route_for(&[host("lan", "stable", true)], "lan:area54#1/stable").is_none(), "stale");
194        assert!(route_for(&[host("host", "stable", false)], "lan:area54#1/stable").is_none(), "not LAN");
195    }
196
197    #[test]
198    fn the_lookup_answers_for_this_sender_only_once_its_key_exists() {
199        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
200        let sender = this_sender_id("Area54");
201        assert!(sender_lookup(&store, "Area54", &sender).is_none(), "no key minted yet");
202        let key = store.agent_lan_key_ensure(&sender).unwrap();
203        let answer = sender_lookup(&store, "Area54", &sender.to_uppercase()).expect("answers, case-insensitively");
204        assert_eq!(answer["agent_id"], sender);
205        assert_eq!(answer["lan_public_key"], key.public_key);
206        assert!(answer.get("private_key").is_none() && !answer.to_string().contains(&key.private_key));
207        assert!(sender_lookup(&store, "Area54", "Manoz").is_none());
208    }
209
210    #[test]
211    fn the_route_never_prints_its_key() {
212        let route = PeerRoute { url: "http://192.0.2.7:29700".into(), auth_key: "lan-secret".into() };
213        assert!(!format!("{route:?}").contains("lan-secret"));
214    }
215
216    #[test]
217    fn the_request_is_signed_so_the_receiver_can_verify_it() {
218        let (public, seed) = agentmux_common::jekt_sign::generate_lan_keypair([7u8; 32]);
219        use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
220        let text = broadcast_text("Area54", 2, "merge on approval");
221        let req = signed_request("swarm-area54-0000abcd", &BASE64.encode(seed), "Manoz", &text, "msg-1", 1_000).unwrap();
222        assert_eq!(req.source_agent.as_deref(), Some("swarm-area54-0000abcd"));
223        assert!(req.delivery_tier.is_none(), "the receiver sets the tier from how the request authenticated");
224        assert!(agentmux_common::jekt_sign::verify_lan_jekt(
225            &public,
226            "msg-1",
227            "swarm-area54-0000abcd",
228            "Manoz",
229            1_000,
230            &text,
231            req.lan_sig.as_deref().unwrap(),
232        ));
233        assert!(signed_request("s", "not base64!", "Manoz", &text, "m", 1).is_none());
234    }
235
236    type Seen = std::sync::Arc<std::sync::Mutex<Vec<(Option<String>, serde_json::Value)>>>;
237
238    /// A fake LAN peer's inject route: records each request's `X-AuthKey` and
239    /// body, and answers with `reply`.
240    async fn peer(reply: serde_json::Value) -> (PeerRoute, Seen) {
241        let seen: Seen = Default::default();
242        let s = seen.clone();
243        let app = axum::Router::new().route(
244            "/agentmux/reactive/inject",
245            axum::routing::post(move |headers: axum::http::HeaderMap, axum::Json(body): axum::Json<serde_json::Value>| {
246                let (s, reply) = (s.clone(), reply.clone());
247                async move {
248                    let key = headers.get("X-AuthKey").and_then(|v| v.to_str().ok()).map(str::to_string);
249                    s.lock().unwrap().push((key, body));
250                    axum::Json(reply)
251                }
252            }),
253        );
254        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
255        let url = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
256        tokio::spawn(async move {
257            let _ = axum::serve(listener, app).await;
258        });
259        (PeerRoute { url, auth_key: "peer-lan-key".into() }, seen)
260    }
261
262    fn request() -> (InjectionRequest, [u8; 32]) {
263        use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
264        let (public, seed) = agentmux_common::jekt_sign::generate_lan_keypair([9u8; 32]);
265        let text = broadcast_text("Area54", 1, "hi");
266        (signed_request("swarm-area54-0000abcd", &BASE64.encode(seed), "Manoz", &text, "m-1", 1_000).unwrap(), public)
267    }
268
269    #[tokio::test]
270    async fn a_delivery_goes_with_the_peers_key_and_a_signature_it_can_check() {
271        let (route, seen) = peer(serde_json::json!({ "success": true })).await;
272        let (req, public) = request();
273        assert_eq!(send(&reqwest::Client::new(), &route, &req).await, Ok(()));
274        let seen = seen.lock().unwrap();
275        assert_eq!(seen[0].0.as_deref(), Some("peer-lan-key"));
276        let body = &seen[0].1;
277        assert_eq!(body["source_agent"], "swarm-area54-0000abcd");
278        assert_eq!(body["target_agent"], "Manoz");
279        assert!(agentmux_common::jekt_sign::verify_lan_jekt(
280            &public,
281            body["request_id"].as_str().unwrap(),
282            body["source_agent"].as_str().unwrap(),
283            body["target_agent"].as_str().unwrap(),
284            body["ts_secs"].as_i64().unwrap(),
285            body["message"].as_str().unwrap(),
286            body["lan_sig"].as_str().unwrap(),
287        ));
288    }
289
290    #[tokio::test]
291    async fn a_refusal_carries_the_peers_reason() {
292        let (route, _) = peer(serde_json::json!({ "success": false, "error": "agent not found" })).await;
293        assert_eq!(send(&reqwest::Client::new(), &route, &request().0).await, Err("agent not found".to_string()));
294    }
295
296    #[tokio::test]
297    async fn an_unreachable_peer_says_so() {
298        let route = PeerRoute { url: "http://127.0.0.1:9".into(), auth_key: "k".into() };
299        let Err(e) = send(&reqwest::Client::new(), &route, &request().0).await else { panic!("must fail") };
300        assert!(e.starts_with("couldn't reach that machine"), "{e}");
301    }
302
303    #[test]
304    fn the_text_says_where_it_came_from_and_how_many_got_it() {
305        assert_eq!(
306            broadcast_text("Area54", 3, "stop and commit"),
307            "Swarm broadcast from Area54, sent by its operator to 3 agents:\n\nstop and commit"
308        );
309        assert!(broadcast_text("Area54", 1, "x").contains("to 1 agent:"));
310    }
311}