1use 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
34pub(super) const MAX_CHUNK_PARAMS: usize = 400 * 1024;
36const 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
48fn 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
69fn 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
75pub(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 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
119fn 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
133pub(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
145async 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 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 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 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 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 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
252fn 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
262fn 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
282enum Assembly {
285 NotThisMove(String),
286 Local(String),
287}
288
289fn 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
314struct 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
323fn 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 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 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 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 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 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 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;