1use std::io::Read;
18use std::path::{Path, PathBuf};
19use std::time::Duration;
20
21use axum::extract::State;
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Response};
24use axum::{Extension, Json};
25use base64::Engine;
26use serde::{Deserialize, Serialize};
27use serde_json::{json, Value};
28
29use super::agent_lifecycle::{acting, refuse, Actor, Refusal};
30use crate::backend::agent_archive::manifest::CHUNK_BYTES;
31use crate::backend::agent_move::seal::{self, ContentKey, MoveBinding, Sealer};
32use crate::backend::agent_move::signed::{OfferSummary, PreflightAnswer, SignedOffer};
33use crate::registry::Handover;
34use crate::server::caller::Caller;
35use crate::server::remote_ops::move_audit;
36use crate::server::remote_ops::op::{OpStatus, RemoteOpResult};
37use crate::server::remote_ops::send;
38use crate::server::state::AppState;
39
40const AUDIT_ACTION: &str = "agent.move";
41const CONSENT_WAIT: Duration = Duration::from_secs(5 * 60);
43const POLL: Duration = Duration::from_secs(2);
44const CHUNK_TRIES: u32 = 3;
46const POLL_TRIES: u32 = 3;
48const STD: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
49
50#[derive(Debug, Clone, Deserialize)]
51pub(crate) struct MoveRequest {
52 #[serde(default)]
54 agent: Option<String>,
55 host: String,
57 #[serde(default)]
59 dry_run: bool,
60 #[serde(default)]
62 resume: bool,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67struct Journal {
68 move_id: String,
69 attempt: u32,
70 host: String,
71 file: PathBuf,
72 manifest_hash: String,
73 #[serde(default)]
75 dest_install: String,
76 contents: Vec<String>,
77}
78
79fn moving() -> std::sync::MutexGuard<'static, std::collections::HashSet<String>> {
82 static ACTIVE: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();
83 ACTIVE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
84}
85
86pub(crate) fn move_in_flight(uid: &str) -> bool {
88 moving().contains(uid)
89}
90
91struct MoveClaim(String);
92
93impl MoveClaim {
94 fn take(uid: &str) -> Result<Self, Refusal> {
95 if moving().insert(uid.to_string()) {
96 Ok(Self(uid.to_string()))
97 } else {
98 Err(refuse(StatusCode::CONFLICT, "this agent is being moved right now: ask again when that has finished (Agents move_status says where it stands)"))
99 }
100 }
101}
102
103impl Drop for MoveClaim {
104 fn drop(&mut self) {
105 moving().remove(&self.0);
106 }
107}
108
109fn journal_path(uid: &str) -> PathBuf {
110 crate::backend::base::get_mux_data_dir().join("move-journals").join(format!("{uid}.json"))
111}
112
113fn read_journal(uid: &str) -> Option<Journal> {
114 serde_json::from_slice(&std::fs::read(journal_path(uid)).ok()?).ok()
115}
116
117fn write_journal(uid: &str, j: &Journal) -> Result<(), String> {
118 let path = journal_path(uid);
119 std::fs::create_dir_all(path.parent().unwrap_or(Path::new("."))).map_err(|e| e.to_string())?;
120 std::fs::write(path, serde_json::to_vec(j).map_err(|e| e.to_string())?).map_err(|e| e.to_string())
121}
122
123pub(crate) async fn handle_agent_move(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<MoveRequest>) -> Response {
124 match run(&state, caller.map(|Extension(c)| c).as_ref(), req).await {
125 Ok(body) => Json(body).into_response(),
126 Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
127 }
128}
129
130fn audit(state: &AppState, actor: &Actor, target: &str, ok: bool, error: Option<&str>, note: &str) {
131 let request_id = uuid::Uuid::new_v4().to_string();
132 let block_id = state.reactive_handler.block_for_uid(actor.uid()).unwrap_or_default();
133 let reason = format!("{} (uid {}): {note}", actor.slug(), actor.uid());
134 state.reactive_handler.log_fleet_action_audit(Some(actor.slug()), target, &block_id, AUDIT_ACTION, ok, error, &request_id, Some(&reason));
135}
136
137async fn run(state: &AppState, caller: Option<&Caller>, req: MoveRequest) -> Result<Value, Refusal> {
138 let actor = acting(state, caller, "move", req.agent.as_deref())?;
139 let named = req.agent.clone().unwrap_or_else(|| actor.uid().to_string());
140 match move_agent(state, &actor, &req).await {
141 Ok(body) => {
142 audit(state, &actor, &named, true, None, &format!("to {}: {}", req.host.trim(), body["status"].as_str().unwrap_or("")));
143 Ok(body)
144 }
145 Err(r) => {
146 audit(state, &actor, &named, false, Some(&r.message), "stopped");
147 Err(r)
148 }
149 }
150}
151
152pub(super) async fn release_kept_move(state: &AppState, actor: &Actor, req: &super::agent_handover::HandoverRequest) -> Result<(), Refusal> {
157 let target = super::agent_handover::target_for(state, actor, req.agent.as_deref(), "bring_back")?;
158 if move_in_flight(&target.id) {
159 return Err(refuse(StatusCode::CONFLICT, format!("{} is being handed over right now: try again when that has finished.", target.name)));
160 }
161 let Some(journal) = read_journal(&target.id) else { return Ok(()) };
162 let handed_over = super::agent_handover::current_mark(state, &target)?.is_some_and(|m| m.state == Handover::HANDED_OVER);
163 if handed_over && !req.force {
164 let operator = actor.slug().to_string();
165 let ended = send::call(state, &operator, &journal.host, "agent.move.abort", json!({ "move_id": journal.move_id }), "the move was stopped and the agent is brought back").await;
166 if ended.status != OpStatus::Done {
167 return Err(refuse(
168 StatusCode::CONFLICT,
169 format!(
170 "{} was being moved to {} and that computer did not confirm the move ended (it may have placed the agent already, or could not be reached): Agents move with resume asks again; bring_back with force: true only if it is not there.",
171 target.name, journal.host
172 ),
173 ));
174 }
175 }
176 let _ = std::fs::remove_file(&journal.file);
178 let _ = std::fs::remove_file(journal_path(&target.id));
179 Ok(())
180}
181
182fn internal(e: impl std::fmt::Display) -> Refusal {
183 refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents move: {e}"))
184}
185
186fn unreachable(host: &str, what: &str, e: impl std::fmt::Display) -> Refusal {
187 refuse(StatusCode::BAD_GATEWAY, format!("Agents move: {what} on {host} did not work: {e}"))
188}
189
190fn done(host: &str, what: &str, result: RemoteOpResult) -> Result<Value, Refusal> {
192 match result.status {
193 OpStatus::Done | OpStatus::Queued => Ok(result.result),
194 OpStatus::PendingVeto => Ok(result.result),
195 OpStatus::Refused | OpStatus::Failed => {
196 let why = result
197 .result
198 .get("message")
199 .or_else(|| result.result.get("error"))
200 .and_then(Value::as_str)
201 .map(str::to_string)
202 .or(result.refused_reason)
203 .unwrap_or_else(|| "refused".to_string());
204 Err(unreachable(host, what, why))
205 }
206 }
207}
208
209fn my_install(state: &AppState) -> Result<crate::backend::storage::wan_identity::WanInstance, Refusal> {
211 let wan = state.mstore.wan_identity().or_else(crate::backend::storage::wan_identity::global).ok_or_else(|| internal("this install has no identity yet"))?;
212 wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).map_err(internal)
213}
214
215async fn destination_key(state: &AppState, peer: &crate::backend::lan::discovery::LanInstance) -> Result<[u8; 32], Refusal> {
218 if peer.install_id.is_empty() {
219 return Err(refuse(StatusCode::BAD_GATEWAY, "that computer does not say which install it is, so its key cannot be checked; it needs a newer AgentMux"));
220 }
221 for name in peer.agents.iter().take(8) {
222 state.lan_discovery.find_agent_lan_pubkey_asking_again(name, &state.http_client).await;
223 let Some(cert) = state.lan_discovery.cached_lan_cert(name) else { continue };
224 if cert.instance_id == peer.install_id && cert.check_chain().is_some() {
225 if let Some(key) = agentmux_common::jekt_sign::decode_public_key_b64(&cert.instance_pubkey) {
226 return Ok(key);
227 }
228 }
229 }
230 Err(refuse(StatusCode::BAD_GATEWAY, "no agent on that computer showed a certificate that proves its install key, so nothing can be sealed to it"))
231}
232
233struct Destination {
235 install_id: String,
236 public: [u8; 32],
237 box_key: [u8; 32],
238 facts: Value,
239}
240
241async fn preflight(state: &AppState, operator: &str, host: &str, peer: &crate::backend::lan::discovery::LanInstance, me: &str) -> Result<Destination, Refusal> {
242 let public = destination_key(state, peer).await?;
243 let nonce = uuid::Uuid::new_v4().simple().to_string();
244 let answer = done(host, "the preflight", send::call(state, operator, host, "agent.move.preflight", json!({ "nonce": nonce }), "move an agent here").await)?;
245 let answer: PreflightAnswer = serde_json::from_value(answer).map_err(|e| unreachable(host, "the preflight answer", e))?;
246 if answer.dest_install != peer.install_id {
247 return Err(unreachable(host, "the preflight", "it answered for another install than the one it advertises"));
248 }
249 let box_key = answer.verify(&public, me, &nonce).map_err(|e| unreachable(host, "the preflight answer", e))?;
250 let facts = serde_json::from_str(&answer.facts).unwrap_or(Value::Null);
251 Ok(Destination { install_id: answer.dest_install, public, box_key, facts })
252}
253
254fn chunk_count(bytes: u64) -> u64 {
255 bytes.div_ceil(CHUNK_BYTES).max(1)
256}
257
258async fn await_consent(state: &AppState, operator: &str, host: &str, agent: &str, move_id: &str) -> Result<(), Wait> {
261 let deadline = tokio::time::Instant::now() + CONSENT_WAIT;
262 let mut failed_polls = 0;
263 loop {
264 match done(host, "the question where the move stands", send::call(state, operator, host, "agent.move.status", json!({ "move_id": move_id }), "move an agent here").await) {
265 Ok(st) => {
266 failed_polls = 0;
267 match (st["consent"].as_str(), st["state"].as_str()) {
268 (Some("granted"), _) => {
269 move_audit::row(state, "accepted", operator, agent, move_id, None, &format!("the person at {host} allowed it"));
270 return Ok(());
271 }
272 (Some("refused"), _) | (_, Some("aborted")) => {
273 let why = format!("the person at {host} did not allow the move");
274 move_audit::row(state, "refused", operator, agent, move_id, Some(&why), host);
275 return Err(Wait::Declined(refuse(StatusCode::CONFLICT, why)));
276 }
277 _ => {}
278 }
279 }
280 Err(e) => {
283 failed_polls += 1;
284 if failed_polls >= POLL_TRIES {
285 return Err(Wait::Failed(e));
286 }
287 }
288 }
289 if tokio::time::Instant::now() >= deadline {
290 let _ = send::call(state, operator, host, "agent.move.abort", json!({ "move_id": move_id }), "the move was not decided in time").await;
291 let why = format!("nobody at {host} decided on the move in time; it was withdrawn");
292 move_audit::row(state, "refused", operator, agent, move_id, Some(&why), host);
293 return Err(Wait::Declined(refuse(StatusCode::REQUEST_TIMEOUT, why)));
294 }
295 tokio::time::sleep(POLL).await;
296 }
297}
298
299enum Wait {
302 Declined(Refusal),
303 Failed(Refusal),
304}
305
306async fn transfer(state: &AppState, operator: &str, host: &str, agent: &str, journal: &Journal, sealer: &mut Sealer, missing: Vec<u64>) -> Result<(), Refusal> {
308 let mut file = std::fs::File::open(&journal.file).map_err(|e| internal(format!("the archive file cannot be read: {e}")))?;
309 let total = chunk_count(file.metadata().map_err(internal)?.len());
310 let mut buf = vec![0u8; CHUNK_BYTES as usize];
311 for index in 0..total {
312 let filled = read_full(&mut file, &mut buf).map_err(|e| internal(format!("the archive file cannot be read: {e}")))?;
313 if !missing.contains(&index) {
314 continue;
315 }
316 let sealed = sealer.seal(index, &buf[..filled]).map_err(|e| internal(format!("a chunk could not be sealed: {e}")))?;
317 let params = json!({ "move_id": journal.move_id, "attempt": journal.attempt, "index": index, "bytes": STD.encode(sealed) });
318 let mut tried = 0;
319 loop {
320 tried += 1;
321 match done(host, "a chunk", send::call(state, operator, host, "agent.move.chunk", params.clone(), "move an agent here").await) {
322 Ok(_) => break,
323 Err(e) if tried >= CHUNK_TRIES => return Err(e),
324 Err(_) => tokio::time::sleep(POLL).await,
325 }
326 }
327 }
328 move_audit::row(state, "transferred", operator, agent, &journal.move_id, None, &format!("to {host}: {} of {total} parts sent", missing.len()));
330 Ok(())
331}
332
333fn read_full(file: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result<usize> {
334 let mut at = 0;
335 while at < buf.len() {
336 match file.read(&mut buf[at..])? {
337 0 => break,
338 n => at += n,
339 }
340 }
341 Ok(at)
342}
343
344fn contents_of(body: &Value) -> Vec<String> {
345 let files = body["memory_files"].as_u64().unwrap_or(0);
346 let sessions = body["sessions"].as_u64().unwrap_or(0);
347 vec![format!("memory: {files} files"), format!("history: {sessions} conversations, carried as it is")]
348}
349
350enum Begun {
353 Finished(Value),
354 Go(Journal, bool),
355}
356
357async fn begin(state: &AppState, actor: &Actor, req: &MoveRequest, target: &crate::backend::storage::AgentDefinition, host: &str, tell: &Tell<'_>) -> Result<Begun, Refusal> {
359 let operator = tell.operator;
360 if req.resume {
362 let mark = super::agent_handover::current_mark(state, target)?;
363 let mut j = read_journal(&target.id).ok_or_else(|| refuse(StatusCode::CONFLICT, "there is no move of this agent to resume (Agents move_status says where it stands)"))?;
364 if !mark.as_ref().is_some_and(|m| m.state == Handover::HANDED_OVER && m.manifest_hash == j.manifest_hash) || !j.host.eq_ignore_ascii_case(host) || !j.file.is_file() {
365 return Err(refuse(StatusCode::CONFLICT, "the move that was kept is not this agent's hand-over to that computer any more; bring it back, or move it again"));
366 }
367 if j.dest_install != tell.dest_install {
369 return Err(refuse(StatusCode::CONFLICT, format!("{host} is not the computer this move was offered to (another computer answers to that name now): nothing was changed. Resume once the first one is back, or bring_back asks it to end the move.")));
370 }
371 let there = send::call(state, operator, host, "agent.move.status", json!({ "move_id": j.move_id }), "has the agent arrived").await;
373 if matches!(there.status, OpStatus::Failed | OpStatus::Queued | OpStatus::PendingVeto) {
378 return Err(refuse(StatusCode::BAD_GATEWAY, format!("{host} did not answer where the move stands; nothing was changed: Agents move with resume asks again when it can be reached")));
379 }
380 let state_there = if there.status == OpStatus::Done { there.result["state"].as_str().map(str::to_string) } else { None };
381 if matches!(state_there.as_deref(), Some("committed" | "committing")) {
382 let again = done(host, "the commit", send::call(state, operator, host, "agent.move.commit", json!({ "move_id": j.move_id, "attempt": j.attempt }), "has the agent arrived").await).map_err(|e| {
383 refuse(e.status, format!("{} The agent stays handed over and stopped here: Agents move with resume asks again, and bring_back is refused while it may be live there.", e.message))
384 })?;
385 if again["status"].as_str() != Some("registered") {
386 return Err(refuse(StatusCode::BAD_GATEWAY, "the destination did not answer that the agent is registered; the agent stays handed over here: Agents move with resume asks again"));
387 }
388 return Ok(Begun::Finished(finish(state, target, host, &j, &again, tell).await?));
389 }
390 j.attempt += 1;
391 Ok(Begun::Go(j, true))
392 } else {
393 if super::agent_handover::current_mark(state, target)?.is_some_and(|m| m.state == Handover::HANDED_OVER) {
397 return Err(refuse(StatusCode::CONFLICT, "this agent is already handed over (an earlier move stopped, or it was exported with a hand-over): Agents move with resume continues that move, Agents bring_back returns the agent here"));
398 }
399 if let Some(old) = read_journal(&target.id) {
402 let _ = std::fs::remove_file(&old.file);
403 let _ = std::fs::remove_file(journal_path(&target.id));
404 }
405 let exported = super::agent_export::run_as(state, actor, super::agent_export::ExportRequest::for_move(&target.id, host)).await?;
406 let file = PathBuf::from(exported["path"].as_str().unwrap_or_default());
407 let journal = Journal {
408 move_id: uuid::Uuid::new_v4().simple().to_string(),
409 attempt: 1,
410 host: host.to_string(),
411 file,
412 manifest_hash: exported["manifest_hash"].as_str().unwrap_or_default().to_string(),
413 dest_install: tell.dest_install.to_string(),
414 contents: contents_of(&exported),
415 };
416 Ok(Begun::Go(journal, false))
417 }
418}
419
420async fn move_agent(state: &AppState, actor: &Actor, req: &MoveRequest) -> Result<Value, Refusal> {
421 let target = super::agent_handover::target_for(state, actor, req.agent.as_deref(), "move")?;
422 if !actor.is_person() && target.id == actor.uid() {
423 return Err(refuse(StatusCode::CONFLICT, "an agent cannot move itself: it keeps running until it is stopped. Ask the agent that leads it, or the person in My Agents."));
424 }
425 let host = req.host.trim().to_string();
426 let _claim = if req.dry_run { None } else { Some(MoveClaim::take(&target.id)?) };
428 let peer = send::resolve_peer(&state.lan_discovery.get_instances(), &host).map_err(|e| refuse(StatusCode::BAD_REQUEST, e))?;
429 let me = my_install(state)?;
430 let operator = actor.slug().to_string();
431 let dest = preflight(state, &operator, &host, &peer, &me.instance_id).await?;
432 if req.dry_run {
433 return Ok(json!({
434 "dry_run": true, "agent": target.name, "to": host,
435 "destination": dest.facts,
436 "note": "Nothing was stopped or sent. The agent's history is carried as it is: a secret someone pasted into a conversation is in it. The person at the destination decides before anything is taken.",
437 }));
438 }
439
440 let (journal, resumed) = match begin(state, actor, req, &target, &host, &Tell { operator: &operator, me: &me, dest_install: &dest.install_id }).await? {
441 Begun::Finished(done) => return Ok(done),
442 Begun::Go(journal, resumed) => (journal, resumed),
443 };
444 write_journal(&target.id, &journal).map_err(internal)?;
445
446 let stopped = |r: Refusal| stopped_row(state, &operator, &target.name, &journal.move_id, r);
447 let size = std::fs::metadata(&journal.file).map_err(|e| internal(format!("the archive file cannot be read: {e}")))?.len();
448 let binding = MoveBinding::new(&journal.move_id, journal.attempt, &journal.manifest_hash, &me.instance_id, &dest.install_id, chunk_count(size)).map_err(internal)?;
449 let key = ContentKey::generate().map_err(internal)?;
450 let sealed_key = key.seal_to(&binding, &seal::recipient(&dest.public, dest.box_key)).map_err(internal)?;
451 let summary = OfferSummary {
452 move_id: journal.move_id.clone(),
453 attempt: journal.attempt,
454 manifest_hash: journal.manifest_hash.clone(),
455 total_bytes: size,
456 total_chunks: chunk_count(size),
457 agent_uid: target.id.clone(),
458 agent_name: target.name.clone(),
459 runtime: "native".to_string(),
460 requester: if actor.is_person() { "a person at the source computer".to_string() } else { actor.slug().to_string() },
462 asker_kind: if actor.is_person() { "person" } else { "agent" }.to_string(),
463 operator: operator.clone(),
464 contents: journal.contents.clone(),
465 source_install: me.instance_id.clone(),
466 dest_install: dest.install_id.clone(),
467 issued_at_ms: agentmux_common::time::now_ms(),
468 sealed_key,
469 route: crate::backend::model_gateway::launch::choice_of(&state.mstore, &target.id)
470 .map(|c| crate::backend::agent_move::signed::RouteRef { harness: target.provider.clone(), route: c.route, model: c.model }),
471 harness: target.provider.clone(),
472 };
473 let offer = SignedOffer::sign(&me.private_key, &summary).map_err(internal)?;
474 let offered = offer_to(state, &operator, &host, &target.name, &summary, &offer).await;
476 let refused = offered.status == OpStatus::Refused && !resumed;
479 done(&host, "the offer", offered).map_err(|e| if refused { declined(state, &target, &journal, e) } else { stopped(e) })?;
480 await_consent(state, &operator, &host, &target.name, &journal.move_id).await.map_err(|w| match w {
481 Wait::Declined(e) => declined(state, &target, &journal, e),
482 Wait::Failed(e) => stopped(e),
483 })?;
484 let status = done(&host, "the question where the move stands", send::call(state, &operator, &host, "agent.move.status", json!({ "move_id": journal.move_id }), "move an agent here").await).map_err(stopped)?;
485 let missing: Vec<u64> = status["missing"].as_array().map(|a| a.iter().filter_map(Value::as_u64).collect()).unwrap_or_default();
486 let mut sealer = Sealer::new(key, binding);
487 transfer(state, &operator, &host, &target.name, &journal, &mut sealer, missing).await.map_err(stopped)?;
488 let committed = done(&host, "the commit", send::call(state, &operator, &host, "agent.move.commit", json!({ "move_id": journal.move_id, "attempt": journal.attempt }), "move an agent here").await).map_err(stopped)?;
489 if committed["status"].as_str() != Some("registered") {
490 return Err(stopped(unreachable(&host, "the commit", "it did not answer that the agent is registered")));
491 }
492 let mut body = finish(state, &target, &host, &journal, &committed, &Tell { operator: &operator, me: &me, dest_install: &dest.install_id }).await?;
493 body["resumed"] = json!(resumed);
494 body["warnings"] = committed["warnings"].clone();
495 Ok(body)
496}
497
498fn stopped_row(state: &AppState, operator: &str, agent: &str, move_id: &str, r: Refusal) -> Refusal {
501 move_audit::row(state, "stopped", operator, agent, move_id, Some(&r.message), "the move can be resumed");
502 refuse(r.status, format!("{} The agent is handed over and stays stopped here: Agents move with resume continues, Agents bring_back returns it.", r.message))
503}
504
505async fn offer_to(state: &AppState, operator: &str, host: &str, agent: &str, summary: &OfferSummary, offer: &SignedOffer) -> RemoteOpResult {
508 let note = format!(
509 "to {host}: {} in {} parts, asked by {}, manifest {}, attempt {}",
510 move_audit::size_text(summary.total_bytes),
511 summary.total_chunks,
512 summary.requester,
513 move_audit::short(&summary.manifest_hash),
514 summary.attempt
515 );
516 move_audit::row(state, "offered", operator, agent, &summary.move_id, None, ¬e);
517 let sent = send::call(state, operator, host, "agent.move.offer", json!({ "offer": offer }), "move an agent here").await;
518 refused_row(state, operator, agent, &summary.move_id, host, &sent);
519 sent
520}
521
522fn refused_row(state: &AppState, operator: &str, agent: &str, move_id: &str, host: &str, sent: &RemoteOpResult) {
524 if sent.status != OpStatus::Refused {
525 return;
526 }
527 let why = sent.result.get("message").or_else(|| sent.result.get("error")).and_then(Value::as_str).or(sent.refused_reason.as_deref()).unwrap_or("refused");
528 move_audit::row(state, "refused", operator, agent, move_id, Some(why), &format!("{host} did not take the offer"));
529}
530
531fn declined(state: &AppState, target: &crate::backend::storage::AgentDefinition, journal: &Journal, e: Refusal) -> Refusal {
533 let _ = state.mstore.agent_handover_set(&target.id, None);
534 state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
535 let _ = std::fs::remove_file(&journal.file);
537 let _ = std::fs::remove_file(journal_path(&target.id));
538 refuse(e.status, format!("{} The agent was not moved and is back here: it starts when someone starts it.", e.message))
539}
540
541async fn finish(state: &AppState, target: &crate::backend::storage::AgentDefinition, host: &str, journal: &Journal, registered: &Value, tell: &Tell<'_>) -> Result<Value, Refusal> {
543 let brought_back = !super::agent_handover::current_mark(state, target)?.is_some_and(|m| m.state == Handover::HANDED_OVER && m.manifest_hash == journal.manifest_hash);
546 super::agent_handover::mark_moved(state, target, host, &journal.manifest_hash).map_err(|e| internal(format!("the agent is registered at {host}, but the mark could not be written here: {e}")))?;
547 let _ = std::fs::remove_file(&journal.file);
548 let _ = std::fs::remove_file(journal_path(&target.id));
549 move_audit::row(state, "completed", tell.operator, &target.name, &journal.move_id, None, &format!("registered at {host}, marked moved here, manifest {}", move_audit::short(&journal.manifest_hash)));
550 let told = tell_peers(state, target, journal, registered, tell).await;
552 Ok(json!({
553 "status": "moved",
554 "peers_told": told,
555 "agent": target.name,
556 "agent_id": target.id,
557 "to": host,
558 "note": if brought_back {
559 "The agent is registered at the destination, but its hand-over was cleared here while the move ran, so it may be running here now: stop it here. It is marked moved and starts nowhere here from now on."
560 } else {
561 "The agent is registered at the destination, stopped, with its memory and history; start it there. It starts nowhere here. Its history was carried as it is."
562 },
563 }))
564}
565
566struct Tell<'a> {
568 operator: &'a str,
569 me: &'a crate::backend::storage::wan_identity::WanInstance,
570 dest_install: &'a str,
571}
572
573async fn tell_peers(state: &AppState, target: &crate::backend::storage::AgentDefinition, journal: &Journal, registered: &Value, tell: &Tell<'_>) -> usize {
577 let new_key = registered["lan_key"].as_str().unwrap_or_default();
578 if new_key.is_empty() || !registered["agent"]["slug"].as_str().is_some_and(|s| s.eq_ignore_ascii_case(&target.slug)) {
580 return 0;
581 }
582 let Ok(old) = state.mstore.agent_lan_key_ensure(&target.slug) else { return 0 };
583 let old_fp = crate::server::reactive::lan_continuity::fingerprint(&old.public_key);
584 let Ok(cert) = crate::backend::agent_move::handover::HandoverCertificate::sign(
585 &tell.me.private_key,
586 &target.slug,
587 &target.id,
588 &old_fp,
589 new_key,
590 (&tell.me.instance_id, tell.dest_install),
591 &journal.move_id,
592 agentmux_common::time::now_secs(),
593 ) else {
594 return 0;
595 };
596 let peers = crate::backend::lan::discovery::one_per_instance(state.lan_discovery.get_instances());
597 let mut accepted = 0;
598 for peer in peers.iter().filter(|p| p.install_id != tell.dest_install && p.install_id != tell.me.instance_id).take(16) {
599 let host = send::host_for(peer, &peers);
601 let answer = send::call(state, tell.operator, &host, "agent.moved", json!({ "certificate": cert }), "an agent moved to another computer").await;
602 if answer.status == OpStatus::Done {
603 accepted += 1;
604 }
605 }
606 accepted
607}
608
609#[cfg(test)]
610#[path = "agent_move_tests.rs"]
611mod tests;