Skip to main content

agentmux_srv/server/remote_ops/
send.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sending half (spec §4.1, §4.8): an agent asks this machine's srv to run an operation on
5//! another machine. srv builds the envelope, signs it with the agent's own LAN key (the agent's
6//! process never holds the signing step, as for a jekt from an agent that signed nothing), sends
7//! it to the peer and returns the peer's answer. It writes `remote.request` to this machine's
8//! audit trail, by `agent@machine`.
9//!
10//! `host` is a machine's name as `Agents list` shows it, or `name/channel` when a machine runs
11//! several instances. It must be named on every call; a name that fits more than one instance
12//! is an error, never a guess.
13
14use std::time::Duration;
15
16use axum::extract::{Extension, State};
17use axum::response::{IntoResponse, Response};
18use axum::Json;
19use serde_json::{json, Value};
20
21use crate::server::remote_ops::op::{lan_audience, RemoteOp, RemoteOpResult, Requester, SignedRemoteOp, REMOTE_OP_VERSION};
22
23use super::enabled;
24use crate::backend::lan::discovery::{one_per_instance, LanInstance};
25use crate::backend::lan::peer_words::{describe_peer, install_words};
26use crate::server::actor::{self, ActorSite};
27use crate::server::{app_api_response, caller, AppState};
28
29/// How long a peer gets to answer. An operation may wait on the peer's own countdown only by
30/// answering `pending_veto` first, so this is a request's round trip, not a human's time.
31const PEER_TIMEOUT: Duration = Duration::from_secs(30);
32
33#[derive(serde::Deserialize)]
34pub(crate) struct RemoteOpRequest {
35    /// The calling agent (must be one only the token's own agent answers to).
36    pub agent_id: String,
37    pub host: String,
38    pub op: String,
39    #[serde(default)]
40    pub params: Value,
41    #[serde(default)]
42    pub reason: String,
43}
44
45/// A refusal because the agent isn't on that machine, with the machine said in words: the Store copy
46/// of a host that runs no agents answers like a host that has none of this one.
47pub(super) fn explain_not_found(result: &mut RemoteOpResult, peer: &LanInstance) {
48    if result.refused_reason.as_deref() != Some("not_found") {
49        return;
50    }
51    let said = format!("That was {}.", describe_peer(peer));
52    match result.result.get("message").and_then(Value::as_str).map(str::to_string) {
53        Some(message) => result.result["message"] = Value::String(format!("{message} {said}")),
54        None => result.result = json!({ "message": said }),
55    }
56}
57
58/// A refusal because the machine's AgentMux has no remote operations, or doesn't know this one, with the version it runs
59/// (what it advertised, when that reads as a version) and the version of this machine to update it to. In this machine's
60/// words: nothing of the peer's text goes into the sentence.
61pub(super) fn explain_too_old(result: &mut RemoteOpResult, peer: &LanInstance) {
62    let what = match result.refused_reason.as_deref() {
63        Some("peer_cannot_do_remote_ops") => "do remote operations",
64        Some("unknown_op") => "do this operation",
65        _ => return,
66    };
67    let said = crate::backend::remote_panes::host::outdated_text(peer.hostname.trim(), &crate::backend::remote_panes::host::clean_version(&peer.version), what);
68    result.result = json!({ "message": said });
69}
70
71/// The one LAN instance `host` names, or why not. `machine`, `machine/channel` or
72/// `machine/channel/install` (`windows-store`, or "Microsoft Store"): two installs of one channel on a
73/// host differ only by how they are installed.
74pub(crate) fn resolve_peer(peers: &[LanInstance], host: &str) -> Result<LanInstance, String> {
75    let wanted = host.trim();
76    if wanted.is_empty() {
77        return Err("name the machine (host): remote operations never default to a machine".into());
78    }
79    let mut parts = wanted.splitn(3, '/').map(str::trim);
80    let name = parts.next().unwrap_or(wanted);
81    let channel = parts.next();
82    let install = parts.next();
83    // One machine found at two addresses is one instance, not two to choose between.
84    let peers = one_per_instance(peers.to_vec());
85    let found: Vec<&LanInstance> = peers
86        .iter()
87        .filter(|p| {
88            p.hostname.trim().eq_ignore_ascii_case(name)
89                && channel.is_none_or(|c| p.channel.eq_ignore_ascii_case(c))
90                && install.is_none_or(|i| p.install.eq_ignore_ascii_case(i) || install_words(&p.install).eq_ignore_ascii_case(i))
91        })
92        .collect();
93    match found.as_slice() {
94        [one] => Ok((*one).clone()),
95        [] => {
96            let known: Vec<String> = peers.iter().map(describe_peer).collect();
97            Err(format!("no machine {wanted:?} among the LAN peers; they are: {}", known.join(", ")))
98        }
99        many => {
100            // Said so that a name can be copied: the install part tells two of one channel apart.
101            let names: Vec<String> = many
102                .iter()
103                .map(|p| {
104                    let base = format!("{}/{}", p.hostname.trim(), p.channel);
105                    if p.install.is_empty() { base } else { format!("{base}/{}", p.install) }
106                })
107                .collect();
108            Err(format!("{wanted:?} fits more than one instance: name one of {}", names.join(", ")))
109        }
110    }
111}
112
113/// The host name that [`resolve_peer`] takes to find `peer` among `all` and no other: `name/channel` (just `name` for a peer that does
114/// not advertise a channel), with `/install` added when another instance of the same name runs the same channel, which is all that
115/// tells two installs of one channel apart.
116pub(crate) fn host_for(peer: &LanInstance, all: &[LanInstance]) -> String {
117    let name = peer.hostname.trim();
118    if peer.channel.is_empty() {
119        return name.to_string();
120    }
121    let twin = all.iter().any(|q| (q.address != peer.address || q.port != peer.port) && q.hostname.trim().eq_ignore_ascii_case(name) && q.channel.eq_ignore_ascii_case(&peer.channel));
122    if twin && !peer.install.is_empty() {
123        format!("{name}/{}/{}", peer.channel, peer.install)
124    } else {
125        format!("{name}/{}", peer.channel)
126    }
127}
128
129fn fresh_nonce() -> String {
130    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
131    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
132    format!("{}-{}-{n}-{}", agentmux_common::time::now_ms_u64(), std::process::id(), &uuid::Uuid::new_v4().simple().to_string()[..8])
133}
134
135/// Run `op` on `host` as the agent `slug` and return the machine's answer. A failure to reach or
136/// sign is a `failed` result, so every caller gets one shape back. The srv-side door for
137/// operations that other features make: the fleet Global Memory sync (`fleet_sync`) is the first.
138pub(crate) async fn call(state: &AppState, slug: &str, host: &str, op: &str, params: Value, reason: &str) -> RemoteOpResult {
139    let uid = match crate::backend::agent_resolve::resolve_agent_id(&state.mstore, slug) {
140        Ok(uid) => uid,
141        Err(e) => return RemoteOpResult::failed(&format!("no agent {slug:?} here: {e}")),
142    };
143    call_as(state, slug, &uid, host, op, params, reason).await
144}
145
146async fn call_as(state: &AppState, slug: &str, uid: &str, host: &str, op: &str, params: Value, reason: &str) -> RemoteOpResult {
147    if !enabled(state) {
148        return RemoteOpResult::refused("remote_ops_off");
149    }
150    let peer = match resolve_peer(&state.lan_discovery.get_instances(), host) {
151        Ok(p) => p,
152        Err(e) => return RemoteOpResult::failed(&e),
153    };
154    let Some(key) = state.mstore.agent_lan_key_ensure(slug).ok().and_then(|k| agentmux_common::jekt_sign::decode_key(&k.private_key)) else {
155        return RemoteOpResult::failed("this agent has no LAN key to sign with");
156    };
157    let instance_id = state
158        .mstore
159        .wan_identity()
160        .or_else(crate::backend::storage::wan_identity::global)
161        .and_then(|wan| wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).ok())
162        .map(|i| i.instance_id)
163        .unwrap_or_default();
164    let envelope = RemoteOp {
165        v: REMOTE_OP_VERSION,
166        op: op.to_string(),
167        params,
168        requester: Requester { agent_uid: uid.to_string(), slug: slug.to_string(), instance_id },
169        audience: lan_audience(&peer.auth_key),
170        ts: agentmux_common::time::now_secs(),
171        nonce: fresh_nonce(),
172        reason: crate::server::remote_ops::op::clip_reason(reason),
173    };
174    let nonce = envelope.nonce.clone();
175    let target = envelope.params.get("target_agent").and_then(Value::as_str).unwrap_or_default().to_string();
176    let envelope_params = if op == "app.upgrade" { envelope.params.clone() } else { Value::Null };
177    let Some(signed) = envelope.sign_with(&key, super::max_params_of(op)) else {
178        return RemoteOpResult::failed("the request could not be signed (too long, or a malformed field)");
179    };
180    let mut result = post(state, &peer, &signed).await;
181    explain_not_found(&mut result, &peer);
182    explain_too_old(&mut result, &peer);
183    if op == "tasks.enqueue" {
184        crate::server::task_flow_notes::note_remote_filed(slug, &peer.hostname, &target, &result.result);
185    }
186    if op == "app.upgrade" {
187        super::upgrade_watch::note_asked(state, slug, uid, host, &envelope_params, &result);
188    }
189    let ok = matches!(result.status, crate::server::remote_ops::op::OpStatus::Done | crate::server::remote_ops::op::OpStatus::Queued | crate::server::remote_ops::op::OpStatus::PendingVeto);
190    let note = result.refused_reason.clone().or_else(|| result.result.get("error").and_then(Value::as_str).map(str::to_string));
191    // A read of the Audit is no row in it, whatever the answer: the Audit asks again every few seconds while it is
192    // shown, and a row (a refusal from a computer that does not share, say) would make it ask again at once.
193    if op == crate::backend::audit_query::peers::QUERY_OP {
194        return result;
195    }
196    state.reactive_handler.log_fleet_action_audit(
197        Some(&format!("{slug}@{}", state.hostname)),
198        peer.hostname.trim(),
199        "",
200        &format!("remote.request {op}"),
201        ok,
202        note.as_deref(),
203        &nonce,
204        (!reason.is_empty()).then_some(reason),
205    );
206    result
207}
208
209async fn post(state: &AppState, peer: &LanInstance, signed: &SignedRemoteOp) -> RemoteOpResult {
210    let url = format!("{}/agentmux/remote/op", crate::backend::lan::discovery::peer_base_url(&peer.address, peer.port));
211    let response = state
212        .http_client
213        .post(url)
214        .header(agentmux_common::AUTH_KEY_HEADER, &peer.auth_key)
215        .timeout(PEER_TIMEOUT)
216        .json(signed)
217        .send()
218        .await;
219    match response {
220        Ok(resp) if resp.status().is_success() => resp.json::<RemoteOpResult>().await.unwrap_or_else(|e| RemoteOpResult::failed(&format!("that machine's answer was not understood: {e}"))),
221        // A machine too old to have the route answers 404, or 405 when something else owns the path.
222        Ok(resp) if matches!(resp.status(), reqwest::StatusCode::NOT_FOUND | reqwest::StatusCode::METHOD_NOT_ALLOWED) => RemoteOpResult::refused("peer_cannot_do_remote_ops"),
223        Ok(resp) => RemoteOpResult::failed(&format!("that machine answered {}", resp.status())),
224        Err(e) => RemoteOpResult::failed(&format!("couldn't reach that machine: {e}")),
225    }
226}
227
228/// `POST /api/v1/agent/remote/op`: backs the `host` argument of the MuxAPI tools. The agent is
229/// the one its token proves; the body's word is only checked against it.
230pub(crate) async fn handle_agent_remote_op(
231    State(state): State<AppState>,
232    who: Option<Extension<caller::Caller>>,
233    Json(req): Json<RemoteOpRequest>,
234) -> Response {
235    let (slug, uid) = match actor::require_token_actor(&state, who.as_deref(), ActorSite::RemoteOp, &req.agent_id).await {
236        Ok(found) => found,
237        Err(e) => return app_api_response::<()>(Err(e)).into_response(),
238    };
239    let result = call_as(&state, &slug, &uid, &req.host, &req.op, req.params, &req.reason).await;
240    Json(json!(result)).into_response()
241}