Skip to main content

agentmux_srv/server/app_api/agent_spawn/import/
moved.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A move arriving over the LAN, as `Agents import` places a file (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 6.4,
5//! step D of the build). The archive was received as sealed chunks and opened into one file; before anything is made it is
6//! checked against what the source **signed** in its offer: the manifest must hash to the offered hash, be signed by the
7//! source's own install key, and name the agent the offer named. The agent is then placed as a move: it keeps its id and
8//! arrives stopped, with its memory and history.
9//!
10//! The person's decision was taken before the first chunk (`remote_ops::move_consent`), so this asks no one again.
11
12use std::path::Path;
13
14use super::{apply, load, make_plan, Mode};
15use crate::backend::agent_archive::SignatureState;
16use super::AppState;
17
18/// What the signed offer says the archive is.
19pub(crate) struct Expect<'a> {
20    pub manifest_hash: &'a str,
21    /// The source install's public key: the archive must be signed by it.
22    pub source_public: [u8; 32],
23    pub uid: &'a str,
24    pub name: &'a str,
25    /// The route the signed offer names, when it does.
26    pub route: Option<&'a crate::backend::agent_move::signed::RouteRef>,
27    /// What the person was shown about it when the offer was filed (`RouteCall::shown`): the route is kept only when it still
28    /// comes to the same, so a key added after the person decided does not start billing they were not told about.
29    pub route_shown: &'a str,
30}
31
32/// What a paid route the offer names comes to on this computer.
33#[derive(Debug, PartialEq, Eq)]
34pub(crate) enum RouteCall {
35    /// The offer names none.
36    None,
37    /// It is kept: the catalog has it and its key is in this computer's Vault. The sentence says who pays.
38    Keep(String),
39    /// It is not kept, and why: the agent uses its harness's own sign-in until a route is chosen here.
40    Drop(String),
41}
42
43impl RouteCall {
44    /// The words the person was shown, empty when there was nothing to show.
45    pub(crate) fn shown(&self) -> String {
46        match self {
47            RouteCall::None => String::new(),
48            RouteCall::Keep(text) | RouteCall::Drop(text) => text.clone(),
49        }
50    }
51}
52
53/// The Vault key a route the offer names needs and this computer does not have: its label, when the catalog has the route and
54/// only the key is missing (a route the catalog does not know has nothing to ask for).
55pub(crate) fn missing_key(state: &AppState, named: Option<&crate::backend::agent_move::signed::RouteRef>) -> Option<&'static str> {
56    let r = named?;
57    let (route, _) = crate::backend::model_gateway::catalog::validate(&r.harness, &r.route, &r.model).ok()?;
58    (!crate::backend::vault::route_key::present(&state.identity_store, route.key_label)).then_some(route.key_label)
59}
60
61/// Judges the route a signed offer names, for the person's decision and for the registration: the same answer in both.
62pub(crate) fn route_call(state: &AppState, named: Option<&crate::backend::agent_move::signed::RouteRef>) -> RouteCall {
63    use crate::backend::model_gateway::{ask, catalog};
64    let Some(r) = named else { return RouteCall::None };
65    match catalog::validate(&r.harness, &r.route, &r.model) {
66        Err(e) => RouteCall::Drop(format!("its route {}/{} is not available here ({e}): it uses its harness's own sign-in until a route is chosen", r.route, r.model)),
67        Ok((route, model)) => {
68            if !crate::backend::vault::route_key::present(&state.identity_store, route.key_label) {
69                return RouteCall::Drop(format!(
70                    "its route {} needs the \"{}\" key in the Vault, which this computer does not have: it uses its harness's own sign-in until the key is added and a route is chosen",
71                    route.label, route.key_label
72                ));
73            }
74            RouteCall::Keep(ask::consent_line(&ask::Picked { route, model }).trim().to_string())
75        }
76    }
77}
78
79/// Why an archive is not placed.
80#[derive(Debug, PartialEq, Eq)]
81pub(crate) enum Why {
82    /// The archive is not what was offered: the move is over.
83    NotWhatWasOffered(String),
84    /// It cannot be placed now (a name or an id here is taken): the move stays staged until it is decided.
85    Blocked(String),
86}
87
88/// The archive, read and planned, not yet placed.
89pub(crate) struct Verified {
90    loaded: super::Loaded,
91    plan: super::Plan,
92    /// The route the offer named whose key this computer does not have: kept so the agent takes it when the key lands, and the person
93    /// gets the Vault request for the key once the agent is here.
94    needs_key: Option<crate::backend::model_gateway::pending_route::Pending>,
95}
96
97/// What was made.
98pub(crate) struct Placed {
99    pub uid: String,
100    pub name: String,
101    pub slug: String,
102    pub warnings: Vec<String>,
103    /// The Vault key its route needs that is not here (see [`Verified`]): the label.
104    pub needs_key: Option<String>,
105}
106
107/// Reads the archive at `path` (every part against its manifest) and checks it against the signed offer.
108pub(crate) fn verify(state: &AppState, path: &Path, expect: &Expect<'_>) -> Result<Verified, Why> {
109    let bad = |m: String| Why::NotWhatWasOffered(m);
110    let loaded = load(path).map_err(|e| bad(e.message))?;
111    if crate::backend::memory::record::sha256_hex(&loaded.manifest.signed_bytes()) != expect.manifest_hash {
112        return Err(bad("the archive is not the one that was offered: its manifest does not hash to the offered hash".to_string()));
113    }
114    match &loaded.signature {
115        SignatureState::Valid { public_key } if *public_key == expect.source_public => {}
116        _ => return Err(bad("the archive is not signed by the computer that sent it".to_string())),
117    }
118    if loaded.manifest.agent.uid != expect.uid || loaded.manifest.agent.name != expect.name {
119        return Err(bad("the archive is of another agent than the one offered".to_string()));
120    }
121    let plan = make_plan(state, &loaded, Mode::Move, None).map_err(|e| bad(e.message))?;
122    if plan.uid != expect.uid || plan.name != expect.name {
123        return Err(bad("the definition in the archive is of another agent than the one offered".to_string()));
124    }
125    if !plan.blockers.is_empty() {
126        return Err(Why::Blocked(plan.blockers.join("; ")));
127    }
128    // A paid model route is kept only when the person was shown it (the signed offer names it, and the consent said who pays),
129    // the archive names exactly that route, and this computer has it and its key. Any other route is not installed: the agent
130    // arrives on its harness's own sign-in and a route is chosen here.
131    let mut plan = plan;
132    let mut needs_key = None;
133    if let Some(r) = plan.definition.route.take() {
134        let named_by_offer = expect.route.is_some_and(|n| n.harness == plan.definition.harness && n.route == r.route && n.model == r.model);
135        match (named_by_offer, route_call(state, expect.route)) {
136            (true, RouteCall::Keep(now)) if now == expect.route_shown => plan.definition.route = Some(r),
137            (true, RouteCall::Keep(_)) => {
138                plan.warnings.push(format!("its route {}/{} was not set: what it would bill was not what the person was shown when they decided, so the agent uses its harness's own sign-in until a route is chosen here", r.route, r.model));
139                plan.route_line.clear();
140            }
141            (true, RouteCall::Drop(why)) => {
142                needs_key = missing_key(state, expect.route).zip(expect.route).map(|(key_label, n)| crate::backend::model_gateway::pending_route::Pending {
143                    harness: n.harness.clone(),
144                    route: n.route.clone(),
145                    model: n.model.clone(),
146                    key_label: key_label.to_string(),
147                });
148                plan.warnings.push(why);
149                plan.route_line.clear();
150            }
151            _ => {
152                plan.warnings.push(format!("its route {}/{} was not set: the offer the person decided on did not name it, so the agent uses its harness's own sign-in until a route is chosen here", r.route, r.model));
153                plan.route_line.clear();
154            }
155        }
156    }
157    Ok(Verified { loaded, plan, needs_key })
158}
159
160/// Makes the agent from the verified archive: its conversation, its memory, then the definition, last.
161pub(crate) fn place(state: &AppState, path: &Path, verified: Verified) -> Result<Placed, String> {
162    let waiting = verified.needs_key;
163    let (_, plan, mut extra) = apply(state, path, &verified.loaded, verified.plan).map_err(|e| e.message)?;
164    // The route it came with waits for its key, and is taken when the key lands (`pending_route::settle`).
165    let mut needs_key = None;
166    if let Some(pending) = waiting {
167        match crate::backend::model_gateway::pending_route::set_pending(&state.mstore, &plan.uid, &pending) {
168            Ok(()) => needs_key = Some(pending.key_label),
169            Err(e) => extra.warnings.push(format!("its route could not be kept to take once its key is added: {e}")),
170        }
171    }
172    // What was left out is said, never reported as an unqualified success.
173    let mut warnings = plan.warnings.clone();
174    warnings.extend(extra.memory_skipped.drain(..).map(|m| format!("memory not placed: {m}")));
175    warnings.append(&mut extra.warnings);
176    Ok(Placed { uid: plan.uid, name: plan.name, slug: extra.slug, warnings, needs_key })
177}
178
179/// A commit that was interrupted after it placed a conversation and before the agent was made leaves conversations of this
180/// agent that the plan would refuse (it never places over a conversation). The archive's conversations are taken back so the
181/// placement can run again; none existed before the first check of this move, which refused otherwise.
182pub(crate) fn undo_partial(state: &AppState, path: &Path) {
183    let (Ok(loaded), Some(gfs)) = (load(path), state.global_transcript_store.as_deref()) else { return };
184    for part in &loaded.manifest.parts {
185        if let Some(zone) = crate::backend::agent_archive::place::session_zone(&loaded.manifest.agent.uid, &part.path) {
186            crate::backend::agent_archive::place::remove_session(gfs, &zone);
187        }
188    }
189}