Skip to main content

agentmux_srv/server/remote_ops/
move_ops.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The destination's operations for a move of an agent to this computer (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 6.2,
5//! step D of the build): `agent.move.preflight`, `.offer`, `.chunk`, `.status` and `.abort`. Each is a write operation, so
6//! the transport has already required a LAN-verified caller whose install this computer trusts.
7//!
8//! - **Preflight** answers with this install's box key and what the asker needs to know, signed by this install's key for
9//!   this asker and this nonce: LAN answers carry no signature of their own, and the asker seals the move's key only to a
10//!   key that verifies.
11//! - **Offer** carries the source's signed summary. It is verified against the install key the caller's certificate names,
12//!   the sealed content key is checked to open here, the uid and name are checked against the agents here and on the other
13//!   computers, and the move is filed in the staging area **awaiting the person's decision**: no chunk is taken before it
14//!   is allowed.
15//! - **Chunk, status, abort** are accepted only from the source and requester that made the offer. Only `chunk` takes a
16//!   large body.
17//!
18//! - **Commit** opens the staged chunks into the archive, checks it against what the source signed (`import::moved`), and
19//!   registers the agent here, stopped, with its memory and history. It answers `registered`, and answers the same again
20//!   when asked again, so a source that lost the answer can ask.
21//!
22//! The person's decision is `move_consent`.
23
24use base64::Engine;
25use serde::Deserialize;
26use serde_json::{json, Value};
27
28use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
29use crate::backend::agent_move::seal::{ContentKey, MoveBinding, Opener};
30use crate::backend::agent_move::signed::{OfferSummary, PreflightAnswer, SignedOffer};
31use crate::backend::agent_move::staging::{Consent, Counterpart, MoveState, Offer, StageError, Staging, Status};
32use crate::server::app_api::agent_spawn::import::moved::{self, Expect, Why};
33
34/// The largest `agent.move.chunk` body: one 256 KiB sealed chunk as base64, with the envelope around it.
35pub(super) const MAX_CHUNK_PARAMS: usize = 400 * 1024;
36/// How old an offer may be when it arrives.
37const OFFER_MAX_AGE_MS: i64 = 10 * 60 * 1000;
38const STD: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
39
40fn parse<T: serde::de::DeserializeOwned>(op: &str, params: Value) -> Result<T, RemoteRefusal> {
41    serde_json::from_value(params).map_err(|e| RemoteRefusal::new("bad_params", format!("{op}: {e}")))
42}
43
44fn staging(state: &AppState) -> Result<&Staging, RemoteRefusal> {
45    state.move_staging.as_deref().ok_or_else(|| RemoteRefusal::new("not_available", "this AgentMux has no staging area for incoming agents"))
46}
47
48/// The caller as the staging area knows it: the install its certificate names and the agent whose key signed the request.
49fn counterpart(caller: &RemoteCaller) -> Result<Counterpart, RemoteRefusal> {
50    if caller.instance_id.is_empty() || !caller.install_trusted {
51        return Err(RemoteRefusal::new("needs_certificate", "an agent move is taken only from a trusted install that showed a certificate"));
52    }
53    Ok(Counterpart { source_install: caller.instance_id.clone(), requester: caller.slug.clone() })
54}
55
56fn refuse(e: StageError) -> RemoteRefusal {
57    let code = match e {
58        StageError::Busy(_) => "busy",
59        StageError::NotYours | StageError::Unknown => "unknown_move",
60        StageError::NotAllowed(_) => "not_allowed",
61        StageError::WrongState(_) | StageError::WrongAttempt { .. } | StageError::Incomplete { .. } => "wrong_state",
62        StageError::Expired => "expired",
63        StageError::BadOffer(_) | StageError::BadChunk(_) | StageError::ChunkConflict(_) => "bad_params",
64        StageError::Io(_) => "failed",
65    };
66    RemoteRefusal::new(code, e.to_string())
67}
68
69/// This install: its id, its keys.
70fn me(state: &AppState) -> Result<crate::backend::storage::wan_identity::WanInstance, RemoteRefusal> {
71    let wan = state.mstore.wan_identity().or_else(crate::backend::storage::wan_identity::global).ok_or_else(|| RemoteRefusal::failed("this install has no identity yet"))?;
72    wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).map_err(|e| RemoteRefusal::failed(e.to_string()))
73}
74
75/// The public key of the install the caller's certificate names. The certificate must be one this computer holds for the
76/// caller's agent, name the same install the request was admitted under, and verify down to its own key.
77pub(super) fn source_key(state: &AppState, caller: &RemoteCaller) -> Result<[u8; 32], RemoteRefusal> {
78    let bad = || RemoteRefusal::new("needs_certificate", "the caller's install key could not be established");
79    let cert = state.lan_discovery.cached_lan_cert(&caller.slug).ok_or_else(bad)?;
80    if cert.instance_id != caller.instance_id || cert.check_chain().is_none() {
81        return Err(bad());
82    }
83    agentmux_common::jekt_sign::decode_public_key_b64(&cert.instance_pubkey).ok_or_else(bad)
84}
85
86fn status_json(status: &Status) -> Value {
87    json!({
88        "state": status.state,
89        "consent": status.consent,
90        "attempt": status.attempt,
91        "total_chunks": status.total_chunks,
92        "received": status.received,
93        "missing": status.missing,
94    })
95}
96
97#[derive(Deserialize)]
98struct PreflightReq {
99    nonce: String,
100}
101
102pub(super) async fn preflight(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
103    let req: PreflightReq = parse("agent.move.preflight", params)?;
104    let who = counterpart(caller)?;
105    staging(state)?;
106    let me = me(state)?;
107    let box_key = crate::backend::jekt_seal::box_public(&me.private_key).ok_or_else(|| RemoteRefusal::failed("this install's box key could not be made"))?;
108    // What the asker may know of this computer: its version, and that a person here decides (no standing setting yet).
109    let facts = json!({ "version": state.version, "accepts_without_asking": false, "capacity": super::move_capacity::measure(state).facts() }).to_string();
110    let answer = PreflightAnswer::sign(&me.private_key, &me.instance_id, &who.source_install, &req.nonce, &box_key, &facts).map_err(|e| RemoteRefusal::new("bad_params", e.to_string()))?;
111    serde_json::to_value(answer).map_err(|e| RemoteRefusal::failed(e.to_string()))
112}
113
114#[derive(Deserialize)]
115struct OfferReq {
116    offer: SignedOffer,
117}
118
119/// Why an offer for this uid and name is refused here: an agent with this id lives here, the name is taken, or another
120/// computer on the network hosts an agent of that name.
121fn clash(state: &AppState, summary: &OfferSummary, source_install: &str) -> Option<String> {
122    if state.mstore.agent_def_get(&summary.agent_uid).ok().flatten().is_some() {
123        return Some(format!("an agent with this id already lives here; {} is not moved over it", summary.agent_name));
124    }
125    if !crate::server::agent_handlers::name_available(&state.mstore, &summary.agent_name) {
126        return Some(format!("the name {} is already taken here", summary.agent_name));
127    }
128    let name = summary.agent_name.to_lowercase();
129    let elsewhere = state.lan_discovery.get_instances().into_iter().any(|i| i.install_id != source_install && i.agents.iter().any(|a| a.to_lowercase() == name));
130    elsewhere.then(|| format!("another computer on the network already hosts an agent named {}", summary.agent_name))
131}
132
133/// An offer that is refused is a row too: who sent it and why it was not taken. A refusal after the offer verified is under the
134/// move id and names the agent, so it reads next to the source rows; one before it has no move to name, so its id is its own.
135pub(super) async fn offer(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
136    let mut verified = None;
137    let answer = receive(state, caller, params, &mut verified).await;
138    if let Err(refusal) = &answer {
139        let (id, agent) = verified.unwrap_or_else(|| (uuid::Uuid::new_v4().to_string(), "(an agent on its way)".to_string()));
140        super::move_audit::row(state, "refused", &caller.actor(), &agent, &id, Some(&refusal.message), &format!("an offer from {}", caller.machine));
141    }
142    answer
143}
144
145/// `verified` is set to the move id and the agent name once the offer has verified, for the row of a refusal after that.
146async fn receive(state: &AppState, caller: &RemoteCaller, params: Value, verified: &mut Option<(String, String)>) -> RemoteResult {
147    let req: OfferReq = parse("agent.move.offer", params)?;
148    let who = counterpart(caller)?;
149    let staging = staging(state)?;
150    let me = me(state)?;
151    let now = agentmux_common::time::now_ms();
152    let summary = req.offer.verify(&source_key(state, caller)?, &me.instance_id, now, OFFER_MAX_AGE_MS).map_err(|e| RemoteRefusal::new("bad_offer", e.to_string()))?;
153    if summary.source_install != who.source_install {
154        return Err(RemoteRefusal::new("bad_offer", "the offer is signed for another source than the one asking"));
155    }
156    *verified = Some((summary.move_id.clone(), summary.agent_name.clone()));
157    // The move belongs to the agent that signs its operations. An offer an agent of the same install picked up cannot be
158    // filed as that agent's own: the source named who sends it.
159    if !summary.operator.eq_ignore_ascii_case(&who.requester) {
160        return Err(RemoteRefusal::new("bad_offer", "the offer names another agent to send this move"));
161    }
162    // The content key must open here, for this move and attempt: an offer that cannot be received is refused now.
163    let binding = MoveBinding::new(&summary.move_id, summary.attempt, &summary.manifest_hash, &summary.source_install, &summary.dest_install, summary.total_chunks)
164        .map_err(|e| RemoteRefusal::new("bad_offer", e.to_string()))?;
165    ContentKey::open_sealed(&summary.sealed_key, &binding, &me.public_key, &me.private_key).map_err(|_| RemoteRefusal::new("bad_offer", "the content key is not sealed to this computer"))?;
166    if let Some(why) = clash(state, &summary, &who.source_install) {
167        return Err(RemoteRefusal::new("name_clash", why));
168    }
169    // What this computer has to hold it: refused now, with the numbers, before anything is sent.
170    if let Some(why) = super::move_capacity::shortfall(&super::move_capacity::measure(state), summary.total_bytes) {
171        return Err(RemoteRefusal::new("no_capacity", why));
172    }
173    // What a paid route the offer names comes to here, judged once: it is what the person is shown, and the commit keeps the route
174    // only if it still comes to exactly this.
175    // The agent's harness must be, or be installable, here: said to the person deciding, or the offer is refused before they are asked.
176    let harness = match super::move_harness::harness_call(&summary.harness).await {
177        super::move_harness::HarnessCall::Unavailable(why) => return Err(RemoteRefusal::new("no_harness", format!("{} cannot run here: {why}", summary.agent_name))),
178        other => other,
179    };
180    let route = moved::route_call(state, summary.route.as_ref());
181    let filed = Offer {
182        move_id: summary.move_id.clone(),
183        attempt: summary.attempt,
184        counterpart: who.clone(),
185        manifest_hash: summary.manifest_hash.clone(),
186        total_chunks: summary.total_chunks,
187        total_bytes: summary.total_bytes,
188        summary: req.offer.summary.clone(),
189        route_shown: route.shown(),
190    };
191    staging.offer(&filed, now).map_err(refuse)?;
192    // The person decides: nothing is taken until the countdown of this request ends unvetoed. An offer sent again for a
193    // move that was already allowed is not asked about twice, and a failure to ask never touches such a move; a move
194    // still waiting with no request to wait for is ended.
195    if staging.status(&summary.move_id, &who).map_err(refuse)?.consent == Consent::Pending {
196        if let Err(refusal) = super::move_consent::ask(state, caller, &who, &summary, &route, &harness).await {
197            let _ = staging.abort(&summary.move_id, &who);
198            return Err(refusal);
199        }
200    }
201    let st = staging.status(&summary.move_id, &who).map_err(refuse)?;
202    super::move_audit::row(state, "received", &who.requester, &summary.agent_name, &summary.move_id, None, &format!("from {}: {}, asked by {} ({}), waits for the person here", caller.machine, super::move_audit::size_text(summary.total_bytes), summary.requester, summary.asker_kind));
203    Ok(json!({ "move_id": summary.move_id, "status": "pending", "move": status_json(&st) }))
204}
205
206#[derive(Deserialize)]
207struct ChunkReq {
208    move_id: String,
209    attempt: u32,
210    index: u64,
211    bytes: String,
212}
213
214pub(super) async fn chunk(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
215    let req: ChunkReq = parse("agent.move.chunk", params)?;
216    let who = counterpart(caller)?;
217    let sealed = STD.decode(&req.bytes).map_err(|_| RemoteRefusal::new("bad_params", "the chunk is not base64"))?;
218    let staging = staging(state)?;
219    super::move_consent::reconcile(staging, &req.move_id, &who);
220    let st = staging.put_chunk(&req.move_id, &who, req.attempt, req.index, &sealed, agentmux_common::time::now_ms()).map_err(refuse)?;
221    Ok(status_json(&st))
222}
223
224#[derive(Deserialize)]
225struct MoveReq {
226    move_id: String,
227}
228
229pub(super) async fn status(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
230    let req: MoveReq = parse("agent.move.status", params)?;
231    let who = counterpart(caller)?;
232    let staging = staging(state)?;
233    super::move_consent::reconcile(staging, &req.move_id, &who);
234    let st = staging.status(&req.move_id, &who).map_err(refuse)?;
235    Ok(status_json(&st))
236}
237
238pub(super) async fn abort(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
239    let req: MoveReq = parse("agent.move.abort", params)?;
240    let who = counterpart(caller)?;
241    staging(state)?.abort(&req.move_id, &who).map_err(refuse)?;
242    super::move_audit::row(state, "aborted", &caller.actor(), "(an agent on its way)", &req.move_id, None, &format!("the move was ended by {}", caller.machine));
243    Ok(json!({ "move_id": req.move_id, "aborted": true }))
244}
245
246#[derive(Deserialize)]
247struct CommitReq {
248    move_id: String,
249    attempt: u32,
250}
251
252/// The agent's LAN key here (made when there is none): the key peers will see it sign with from now on, which the source
253/// names in its statement that the name moved.
254fn lan_key_of(state: &AppState, slug: &str) -> String {
255    state.mstore.agent_lan_key_ensure(slug).map(|k| k.public_key).unwrap_or_default()
256}
257
258fn registered(state: &AppState, def: &crate::backend::storage::AgentDefinition, warnings: &[String]) -> Value {
259    json!({ "status": "registered", "agent": { "uid": def.id, "name": def.name, "slug": def.slug }, "lan_key": lan_key_of(state, &def.slug), "warnings": warnings })
260}
261
262/// The chunks, opened and put together as one file at `path`: the archive the source wrote. Anything that does not open
263/// under the move's key, or does not add up to the offered size, is not an archive of this move.
264fn assemble(staging: &Staging, who: &Counterpart, summary: &OfferSummary, opener: &Opener, path: &std::path::Path) -> Result<(), Assembly> {
265    use std::io::Write;
266    let local = |e: &dyn std::fmt::Display| Assembly::Local(e.to_string());
267    let mut out = std::io::BufWriter::new(std::fs::File::create(path).map_err(|e| local(&e))?);
268    let mut total = 0u64;
269    for index in 0..summary.total_chunks {
270        let sealed = staging.read_chunk(&summary.move_id, who, index).map_err(|e| local(&e))?;
271        let plain = opener.open(index, &sealed).map_err(|e| Assembly::NotThisMove(format!("chunk {index} does not open: {e}")))?;
272        total += plain.len() as u64;
273        out.write_all(&plain).map_err(|e| local(&e))?;
274    }
275    out.flush().map_err(|e| local(&e))?;
276    if total != summary.total_bytes {
277        return Err(Assembly::NotThisMove(format!("the chunks add up to {total} bytes, not the {} that were offered", summary.total_bytes)));
278    }
279    Ok(())
280}
281
282/// Why the chunks did not become the archive: they are not this move's (the move is over), or this computer could not
283/// read or write a file (the move stays staged to be tried again).
284enum Assembly {
285    NotThisMove(String),
286    Local(String),
287}
288
289/// The moves being committed here now: a second commit of a move that is being committed is refused, so two calls never
290/// share the opened archive or place the agent twice.
291fn committing() -> std::sync::MutexGuard<'static, std::collections::HashSet<String>> {
292    static ACTIVE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();
293    ACTIVE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
294}
295
296struct CommitClaim(String);
297
298impl CommitClaim {
299    fn take(move_id: &str) -> Result<Self, RemoteRefusal> {
300        if committing().insert(move_id.to_string()) {
301            Ok(Self(move_id.to_string()))
302        } else {
303            Err(RemoteRefusal::new("busy", "this move is being committed already; ask again for its answer in a moment"))
304        }
305    }
306}
307
308impl Drop for CommitClaim {
309    fn drop(&mut self) {
310        committing().remove(&self.0);
311    }
312}
313
314/// The opened archive never outlives the commit, whatever the outcome.
315struct Scratch<'a>(&'a std::path::Path);
316
317impl Drop for Scratch<'_> {
318    fn drop(&mut self) {
319        let _ = std::fs::remove_file(self.0);
320    }
321}
322
323/// The commit, on a blocking thread: it reads and writes files.
324fn commit_blocking(state: &AppState, who: &Counterpart, req: &CommitReq, was: MoveState, summary: &OfferSummary, keys: ([u8; 32], [u8; 32], [u8; 32])) -> Result<Value, RemoteRefusal> {
325    let (source_public, my_public, my_private) = keys;
326    let staging = staging(state)?;
327    let binding = MoveBinding::new(&summary.move_id, summary.attempt, &summary.manifest_hash, &summary.source_install, &summary.dest_install, summary.total_chunks)
328        .map_err(|e| RemoteRefusal::new("bad_offer", e.to_string()))?;
329    let key = ContentKey::open_sealed(&summary.sealed_key, &binding, &my_public, &my_private).map_err(|_| RemoteRefusal::new("bad_offer", "the content key does not open here"))?;
330    let scratch = staging.scratch_file(&req.move_id, who).map_err(refuse)?;
331    let _scratch = Scratch(&scratch);
332    let over = |why: String| {
333        let _ = staging.abort(&req.move_id, who);
334        RemoteRefusal::new("bad_archive", format!("the archive is not the one that was offered, so the move is over: {why}"))
335    };
336    match assemble(staging, who, summary, &Opener::new(key, binding), &scratch) {
337        Ok(()) => {}
338        Err(Assembly::NotThisMove(why)) => return Err(over(why)),
339        Err(Assembly::Local(why)) => return Err(RemoteRefusal::failed(format!("this computer could not open the archive: {why}"))),
340    }
341    if was == MoveState::Committing {
342        // The commit was begun and not finished (a restart in between), and the agent is not here: what it placed is taken back.
343        moved::undo_partial(state, &scratch);
344    }
345    let shown = staging.route_shown_of(&req.move_id, who).map_err(refuse)?;
346    let expect = Expect { manifest_hash: &summary.manifest_hash, source_public, uid: &summary.agent_uid, name: &summary.agent_name, route: summary.route.as_ref(), route_shown: &shown };
347    let verified = match moved::verify(state, &scratch, &expect) {
348        Ok(v) => v,
349        Err(Why::NotWhatWasOffered(why)) => return Err(over(why)),
350        Err(Why::Blocked(why)) => {
351            // A commit that was begun before a restart is not left reserved: the move is staged again, to be tried or ended.
352            if was == MoveState::Committing {
353                let _ = staging.end_commit_failed(&req.move_id, who);
354            }
355            return Err(RemoteRefusal::new("blocked", format!("the agent cannot be placed here now: {why}")));
356        }
357    };
358    if was == MoveState::Receiving {
359        staging.mark_staged(&req.move_id, who, req.attempt).map_err(refuse)?;
360    }
361    staging.begin_commit(&req.move_id, who, req.attempt).map_err(refuse)?;
362    match moved::place(state, &scratch, verified) {
363        Ok(placed) => {
364            staging.mark_committed(&req.move_id, who).map_err(refuse)?;
365            tracing::info!(uid = %placed.uid, "agent move: registered here");
366            super::move_audit::row(state, "registered", &who.requester, &placed.name, &req.move_id, None, &format!("from {}: {}, manifest {}", summary.source_install, super::move_audit::size_text(summary.total_bytes), super::move_audit::short(&summary.manifest_hash)));
367            // A route whose key is not in this computer's Vault: the person gets the request for it, never a value from the source.
368            if let Some(key) = &placed.needs_key {
369                super::move_key_request::ask(&state.broker, &placed.uid, &placed.name, key);
370            }
371            Ok(json!({ "status": "registered", "agent": { "uid": placed.uid, "name": placed.name, "slug": placed.slug }, "lan_key": lan_key_of(state, &placed.slug), "warnings": placed.warnings }))
372        }
373        Err(why) => {
374            let _ = staging.end_commit_failed(&req.move_id, who);
375            Err(RemoteRefusal::failed(format!("the agent could not be registered: {why}")))
376        }
377    }
378}
379
380pub(super) async fn commit(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
381    let req: CommitReq = parse("agent.move.commit", params)?;
382    let who = counterpart(caller)?;
383    // One commit of a move at a time, from before the state is read.
384    let claim = CommitClaim::take(&req.move_id)?;
385    let staging = staging(state)?;
386    let st = staging.status(&req.move_id, &who).map_err(refuse)?;
387    let summary: OfferSummary = serde_json::from_str(&staging.summary_of(&req.move_id, &who).map_err(refuse)?).map_err(|_| RemoteRefusal::failed("the offer on file does not read"))?;
388    if st.attempt != req.attempt {
389        return Err(refuse(StageError::WrongAttempt { staged: st.attempt }));
390    }
391    // Asked again after the agent was registered (the answer was lost, or a restart came between): the same answer.
392    let def_here = state.mstore.agent_def_get(&summary.agent_uid).ok().flatten();
393    match (st.state, def_here) {
394        (MoveState::Committed, Some(def)) => return Ok(registered(state, &def, &[])),
395        (MoveState::Committing, Some(def)) => {
396            staging.mark_committed(&req.move_id, &who).map_err(refuse)?;
397            return Ok(registered(state, &def, &[]));
398        }
399        _ => {}
400    }
401    // Only a move that is allowed, has every chunk and is not over is committed.
402    if !matches!(st.state, MoveState::Receiving | MoveState::Staged | MoveState::Committing) {
403        return Err(refuse(StageError::WrongState(st.state)));
404    }
405    if st.consent != Consent::Granted {
406        return Err(refuse(StageError::NotAllowed(st.consent)));
407    }
408    if !st.missing.is_empty() {
409        return Err(refuse(StageError::Incomplete { missing: st.missing.len() as u64 }));
410    }
411    let me = me(state)?;
412    let source_public = source_key(state, caller)?;
413    let (st2, who2, req2) = (state.clone(), who.clone(), CommitReq { move_id: req.move_id.clone(), attempt: req.attempt });
414    let keys = (source_public, me.public_key, me.private_key);
415    let done = tokio::task::spawn_blocking(move || {
416        let _claim = claim;
417        commit_blocking(&st2, &who2, &req2, st.state, &summary, keys)
418    })
419    .await.map_err(|e| RemoteRefusal::failed(e.to_string()))??;
420    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
421    Ok(done)
422}
423
424#[cfg(test)]
425#[path = "move_ops_tests.rs"]
426mod tests;