Skip to main content

agentmux_srv/server/app_api/
agent_move.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents move` (`POST /api/v1/agent/move`): one agent moved to another computer on the LAN, in one step
5//! (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER sections 5 and 6, step D of the build). This is the source's side; the
6//! destination's operations are `remote_ops::move_ops`.
7//!
8//! In order: **preflight** (the destination answers, signed by its install key for this asker and this nonce, with the box
9//! key the move's content key is sealed to); **hand over** (the agent is stopped and marked, and its archive written, by
10//! the same export `Agents export` makes); **offer** (signed by this install: the person at the destination decides, and
11//! `dry_run` stops before any of this); **transfer** (256 KiB sealed chunks, the destination's bitmap says which are
12//! missing); **commit** (the destination registers the agent last and answers `registered`). Only after that answer is the
13//! agent marked `moved` here. A move that stops anywhere before it leaves the agent `handed_over`: `resume` continues it as a
14//! new attempt, `bring_back` returns it. Who may ask is who may export with a hand-over: the agent's leader, never the agent
15//! itself.
16
17use 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";
41/// How long the person at the destination has to decide (the countdown is 30 s, doubled with no super agent there).
42const CONSENT_WAIT: Duration = Duration::from_secs(5 * 60);
43const POLL: Duration = Duration::from_secs(2);
44/// Tries for one chunk before the move stops (and can be resumed).
45const CHUNK_TRIES: u32 = 3;
46/// Questions in a row that may fail while waiting for the person's decision.
47const 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    /// The agent's id, slug or name (default: the caller's own, which is refused: an agent does not move itself).
53    #[serde(default)]
54    agent: Option<String>,
55    /// The computer, as `Agents list` shows it (`name` or `name/channel`).
56    host: String,
57    /// Ask the destination and say what would be sent; stop there.
58    #[serde(default)]
59    dry_run: bool,
60    /// Continue a move that stopped after the agent was handed over, as a new attempt.
61    #[serde(default)]
62    resume: bool,
63}
64
65/// What a move that stopped keeps, so `resume` continues it: the archive that was written and the move's name.
66#[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    /// The install the move was offered to: a resume goes to that one, whatever else answers to the host's name now.
74    #[serde(default)]
75    dest_install: String,
76    contents: Vec<String>,
77}
78
79/// The agents being moved from here now. One move of an agent at a time, from its hand-over to its answer: a second `move` or
80/// `resume`, or a `bring_back`, of an agent in this set is refused, so the agent never has two lives and two attempts never race.
81fn 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
86/// Whether a move of `uid` is running here now.
87pub(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
152/// Before `bring_back` clears the mark of an agent whose move stopped: the destination is asked to end that move, because it may
153/// have registered the agent with only its answer lost, and the agent would then live in both places. The agent comes back
154/// only when the destination says the move is ended (it holds nothing of it any more) or when `force` says it is not there; a
155/// destination that cannot be reached, or that already placed the agent, keeps it handed over. The kept archive is removed.
156pub(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    // The archive holds the agent's memory and history: it does not stay in the folder it was written to.
177    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
190/// The answer of an operation that was done, or why it was not.
191fn 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
209/// This install's keys.
210fn 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
215/// The destination install's public key, proved by a certificate one of its agents holds: the chain must verify and the
216/// install id the certificate names must be the one the peer advertises (an id is derived from its key).
217async 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
233/// What the destination said about itself, checked.
234struct 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
258/// The consent the person at the destination gives, or why not. Polled: the destination answers at once and the
259/// countdown runs there.
260async 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            // One poll that did not get through is not an answer: the destination still holds the offer. Several in a row
281            // stop the move, resumable.
282            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
299/// Why the wait for the person's decision ended without it: they (or the clock) said no, so the agent is returned; or the
300/// destination could not be reached, so the move is kept to be resumed.
301enum Wait {
302    Declined(Refusal),
303    Failed(Refusal),
304}
305
306/// Sends every chunk the destination is missing, one at a time, each tried a few times.
307async 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    // A count only: how many of the parts there were had to be sent this time (a resumed move sends what the destination lacks).
329    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
350/// What starting a move comes to: the agent was already placed there and the move is finished, or the move goes on with this journal
351/// (and whether it is a resumed one).
352enum Begun {
353    Finished(Value),
354    Go(Journal, bool),
355}
356
357/// The agent is handed over (stopped, marked, written to a file) for a first move, or the kept move is taken up again for a resume.
358async 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    // The agent is handed over: stopped, marked, and written to a file. A resume reuses the file that was written.
361    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        // The same computer, not whichever one answers to its name now: the first may hold the agent already.
368        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        // The destination may have registered it already, with only the answer lost.
372        let there = send::call(state, operator, host, "agent.move.status", json!({ "move_id": j.move_id }), "has the agent arrived").await;
373        // Where the destination holds the move as committing or committed, a new attempt would be refused there and the agent may
374        // be placed there already: the same attempt is asked to commit again, which recovers a commit that was cut short and
375        // answers the same again for one that was done.
376        // No answer is not "not there": the attempt stays as it was, so a later resume asks the destination again with it.
377        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        // A first move starts from an agent that is not handed over. One that is (an earlier move stopped, or an export kept
394        // it) may already be registered at the destination, so a new move would be refused there and clear the mark: it is
395        // continued with `resume`, or returned with `bring_back`, never started again.
396        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        // A journal left behind by a move that was brought back: its archive holds the agent's memory and history and is removed
400        // rather than orphaned by the new journal.
401        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    // A dry run stops and sends nothing; a move holds the agent from its hand-over to its answer.
427    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        // Who asked, as the destination's person reads it: a person here, or the agent that asked.
461        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    // The destination refusing the offer (a name taken, busy) returns the agent; not reaching it keeps the move to resume.
475    let offered = offer_to(state, &operator, &host, &target.name, &summary, &offer).await;
476    // A first offer the destination refuses (a name taken, busy) returns the agent. A resumed move is kept: the destination may
477    // hold the agent from an earlier attempt, so nothing is cleared here on a refusal.
478    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
498/// A step of the move stopped it (the destination could not be reached, or an answer was not the one a step needs): the move's trail
499/// ends with a `stopped` row saying why, under the move id, and the agent stays handed over so the move can be resumed.
500fn 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
505/// Sends the offer, after the source's row for it: who asked, what is offered, to which computer. A row says sizes and counts, never content.
506/// An offer the destination refuses is a `refused` row too, with its reason, so the trail does not end at `offered`.
507async 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, &note);
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
522/// The `refused` row of an offer the destination did not take, with its reason; nothing for any other answer.
523fn 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
531/// The destination refused, or nobody decided: the agent that was handed over for it is returned.
532fn 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    // The archive holds the agent's memory and history: it does not stay in the folder it was written to.
536    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
541/// The destination registered the agent: it is marked moved here, and the file and the journal are removed.
542async fn finish(state: &AppState, target: &crate::backend::storage::AgentDefinition, host: &str, journal: &Journal, registered: &Value, tell: &Tell<'_>) -> Result<Value, Refusal> {
543    // The mark is written whatever it was: the agent is registered there, so it must not start here. If someone had cleared
544    // the hand-over meanwhile it may be running here now, and that is said.
545    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    // Only now, after the destination answered `registered` and the mark is written, are the other computers told.
551    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
566/// What telling the peers needs.
567struct Tell<'a> {
568    operator: &'a str,
569    me: &'a crate::backend::storage::wan_identity::WanInstance,
570    dest_install: &'a str,
571}
572
573/// The statement that the name moved, signed by this install and sent to every other computer on the LAN: the ones that
574/// pinned the name under this install move their pin when the new key shows up, and the others refuse it as they do not hold
575/// the name. Best effort: a computer not reached falls back to accepting the key by hand. How many accepted it.
576async 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    // The key is under the name the agent has there: a name that changed is a new name to peers, not a moved one.
579    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        // Named so that exactly this install is found: two installs of one channel on a computer differ only by how they are installed.
600        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;