Skip to main content

agentmux_srv/server/app_api/agent_spawn/
import.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/agent/import`, the `Agents` tool's `import`: an agent archive (`.abf`, kind `agent`, written by
5//! `Agents export`) put in My Agents (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 4 and 7, step B of the build).
6//!
7//! The archive is read without trust: every part is checked against the manifest before anything is made, the definition
8//! comes through the allowlist (a field that widens what the agent may do is dropped and said), and an archive whose
9//! signature does not verify is refused. The agent arrives **stopped**: nothing in the archive starts it. It asks the user as
10//! `Agents create` does, unless the user's own turn asked for it. The agent is registered last, so a failure before that
11//! leaves nothing behind.
12//!
13//! Imported lines are never the person's: their marks are stripped (`agent_archive::place`). The conversation is placed as
14//! history, Personal Memory goes into the record, and a note the agent reads at its first start says where it came from.
15//! `dry_run` reads and checks and answers what would be made, asking no one.
16
17use std::path::PathBuf;
18
19use agentmux_common::api_types::ImportAgentRequest;
20
21use super::*;
22use crate::backend::agent_archive::definition::{ParsedDefinition, PortableDefinition};
23use crate::backend::agent_archive::manifest::Manifest;
24use crate::backend::agent_archive::place::{self, NoteFacts};
25use crate::backend::agent_archive::{ArchiveReader, Limits, SignatureState};
26
27pub(crate) mod moved;
28
29/// The audit entry's action.
30const AUDIT_ACTION: &str = "agent.import";
31/// The names of the notes the agent is given, in its Personal Memory.
32const NOTE_FILE: &str = "arrival-note.md";
33const CONVERSATION_FILE: &str = "imported-conversation.md";
34
35#[derive(Clone, Copy, PartialEq, Eq, Debug)]
36enum Mode {
37    Move,
38    Copy,
39}
40
41pub(crate) async fn handle_agent_import(
42    State(state): State<AppState>,
43    caller: Option<axum::Extension<crate::server::caller::Caller>>,
44    Json(req): Json<ImportAgentRequest>,
45) -> Response {
46    match import(&state, caller.as_deref(), req).await {
47        Ok(body) => Json(body).into_response(),
48        Err(e) => (e.status, Json(json!({ "error": e.message }))).into_response(),
49    }
50}
51
52/// What reading the archive found: no part is kept, only what a plan and an answer need.
53struct Loaded {
54    manifest: Manifest,
55    signature: SignatureState,
56    parsed: ParsedDefinition,
57}
58
59/// What an import would make here.
60struct Plan {
61    mode: Mode,
62    uid: String,
63    name: String,
64    definition: PortableDefinition,
65    blockers: Vec<String>,
66    warnings: Vec<String>,
67    memory: Vec<(String, u64)>,
68    sessions: Vec<(String, u64)>,
69    /// What the person's approval says about a paid model route the archive names, empty when it names none that works here.
70    route_line: String,
71}
72
73fn signature_line(s: &SignatureState) -> &'static str {
74    match s {
75        SignatureState::Unsigned => "not signed",
76        SignatureState::Valid { .. } => "signed by the computer that wrote it",
77        SignatureState::Invalid => "its signature does not verify",
78    }
79}
80
81async fn import(state: &AppState, caller: Option<&crate::server::caller::Caller>, req: ImportAgentRequest) -> Result<serde_json::Value, SpawnError> {
82    let leader = leader_of(state, caller, &req.auth)?;
83    let mode = match req.mode.as_deref().map(str::trim) {
84        None | Some("") | Some("move") => Mode::Move,
85        Some("copy") => Mode::Copy,
86        Some(other) => return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: mode {other:?}: move (the same agent arrives, keeping its id) or copy (a new agent with a new id)"))),
87    };
88    if leader.def.runtime() != crate::backend::runtime_adapter::RuntimeKind::Host {
89        return Err(refuse(
90            StatusCode::FORBIDDEN,
91            "a container agent has no folder on this computer to read the file from; importing from a container agent arrives with the container step of the move build. Ask an agent that runs natively, or the person in My Agents.",
92        ));
93    }
94    let base = PathBuf::from(crate::backend::project_instructions::effective_working_dir(&leader.def.working_directory, &leader.def.name));
95    let file = super::super::agent_export::resolve_input(&base, &req.file).map_err(|(status, message)| refuse(status, message))?;
96
97    let st = state.clone();
98    let path = file.clone();
99    let (loaded, plan) = tokio::task::spawn_blocking(move || -> Result<(Loaded, Plan), SpawnError> {
100        let loaded = load(&path)?;
101        let plan = make_plan(&st, &loaded, mode, req.name.as_deref())?;
102        Ok((loaded, plan))
103    })
104    .await
105    .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents import: {e}")))??;
106
107    if req.dry_run {
108        return Ok(report(&loaded, &plan, true, None));
109    }
110    if !plan.blockers.is_empty() {
111        audit(state, &leader, &plan.name, false, Some(&plan.blockers.join("; ")), "refused");
112        return Err(refuse(StatusCode::CONFLICT, format!("Agents import: {}", plan.blockers.join("; "))));
113    }
114
115    let size: u64 = plan.sessions.iter().chain(plan.memory.iter()).map(|(_, n)| n).sum();
116    let headline = format!("{} is importing an agent, {}", one_line(&leader.def.name, 60), one_line(&plan.name, 60));
117    let body = format!(
118        "From an archive written on {} ({}), {} signed. It adds {} memory files and {} conversations ({} MiB) to My Agents as {}, stopped: nothing starts until someone starts it. The history is carried as it is.",
119        one_line(&loaded.manifest.source.host_hint, 40),
120        one_line(&loaded.manifest.source.os, 12),
121        signature_line(&loaded.signature),
122        plan.memory.len(),
123        plan.sessions.len(),
124        (size >> 20).max(1),
125        one_line(&plan.name, 60),
126    ) + &plan.route_line;
127    // An archive that names a paid route is asked about every time: a waiver for the person's own turn does not cover who pays.
128    announce_start(state, &leader, &req.user_instruction, !plan.route_line.is_empty(), headline, body, "").await?;
129
130    let st = state.clone();
131    let path = file;
132    let name = plan.name.clone();
133    let outcome = tokio::task::spawn_blocking(move || apply(&st, &path, &loaded, plan))
134        .await
135        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents import: {e}")))?;
136    match outcome {
137        Ok((loaded, plan, extra)) => {
138            state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
139            audit(state, &leader, &plan.name, true, None, &format!("imported {} ({} memory files, {} conversations)", plan.uid, plan.memory.len(), plan.sessions.len()));
140            Ok(report(&loaded, &plan, false, Some(extra)))
141        }
142        Err(e) => {
143            audit(state, &leader, &name, false, Some(&e.message), "failed");
144            Err(e)
145        }
146    }
147}
148
149fn audit(state: &AppState, leader: &Leader, target: &str, ok: bool, error: Option<&str>, note: &str) {
150    let request_id = uuid::Uuid::new_v4().to_string();
151    let reason = format!("{} (uid {}): {note}", leader.def.slug, leader.def.id);
152    state.reactive_handler.log_fleet_action_audit(Some(&leader.def.slug), target, &leader.block_id, AUDIT_ACTION, ok, error, &request_id, Some(&reason));
153}
154
155/// Opens the archive, checks every part against its manifest and reads the definition through the allowlist.
156fn load(path: &std::path::Path) -> Result<Loaded, SpawnError> {
157    let bad = |e: String| refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {e}"));
158    let file = std::fs::File::open(path).map_err(|e| bad(format!("cannot open the file: {e}")))?;
159    let mut reader = ArchiveReader::open(std::io::BufReader::new(file), Limits::default()).map_err(|e| bad(e.to_string()))?;
160    // Every part before any is used: a changed archive is refused whole, not placed up to the part that was changed.
161    reader.verify_all().map_err(|e| bad(e.to_string()))?;
162    let json = reader.read_part_bytes("agent.json", 1 << 20).map_err(|e| bad(e.to_string()))?;
163    let parsed = PortableDefinition::parse(&json).map_err(|e| bad(e.to_string()))?;
164    Ok(Loaded { manifest: reader.manifest().clone(), signature: reader.signature().clone(), parsed })
165}
166
167fn make_plan(state: &AppState, loaded: &Loaded, mode: Mode, asked_name: Option<&str>) -> Result<Plan, SpawnError> {
168    let definition = loaded.parsed.definition.clone();
169    let mut blockers = Vec::new();
170    let mut warnings = Vec::new();
171    let mut route_line = String::new();
172
173    let uid = match mode {
174        Mode::Move => definition.uid.clone(),
175        Mode::Copy => uuid::Uuid::new_v4().to_string(),
176    };
177    let name = match asked_name.map(str::trim).filter(|n| !n.is_empty()) {
178        Some(n) => n.to_string(),
179        None if mode == Mode::Copy => format!("{} copy", definition.name),
180        None => definition.name.clone(),
181    };
182    if name.chars().count() > 64 || name.chars().any(char::is_control) {
183        blockers.push("the name is longer than 64 characters or not on one line".to_string());
184    } else if let Err(e) = crate::backend::reserved_names::check_all(&[name.as_str()]) {
185        blockers.push(e.to_string());
186    } else if !crate::server::agent_handlers::name_available(&state.mstore, &name) {
187        blockers.push(format!("an agent here already goes by {name:?}; give the agent another name with name"));
188    }
189    if mode == Mode::Move && state.mstore.agent_def_get(&uid).ok().flatten().is_some() {
190        blockers.push(format!("{uid} is already an agent here, so this one cannot arrive under its id; import it as a copy (mode copy) to make a new agent of it"));
191    }
192    if crate::backend::runtime_adapter::RuntimeKind::of_agent_type(&definition.agent_type) != crate::backend::runtime_adapter::RuntimeKind::Host {
193        blockers.push("this is a container agent; importing one arrives with the container step of the move build".to_string());
194    }
195    match &loaded.signature {
196        SignatureState::Invalid => blockers.push("the archive's signature does not verify: it was changed after it was written, or not written by the computer it names".to_string()),
197        SignatureState::Unsigned => warnings.push("the archive is not signed, so nothing says which computer wrote it".to_string()),
198        SignatureState::Valid { .. } => {}
199    }
200    if !loaded.parsed.dropped.is_empty() {
201        warnings.push(format!("settings in the archive that were not taken (they arrive at this computer's defaults): {}", loaded.parsed.dropped.join(", ")));
202    }
203    if let Some(role) = &loaded.parsed.seat_role_dropped {
204        warnings.push(format!("the seat role {role:?} is not carried: it is given here, by its own route"));
205    }
206    if let Some(r) = &definition.route {
207        match crate::backend::model_gateway::catalog::validate(&definition.harness, &r.route, &r.model) {
208            Ok((route, model)) => route_line = crate::backend::model_gateway::ask::consent_line(&crate::backend::model_gateway::ask::Picked { route, model }),
209            Err(e) => warnings.push(format!("its route {}/{} is not available here ({e}); it will use its harness's own sign-in until a route is chosen", r.route, r.model)),
210        }
211    }
212    if state.global_transcript_store.is_none() {
213        warnings.push("this computer has no history store, so the conversation is not placed".to_string());
214    }
215    if !gets_arrival_note(&definition.harness) {
216        warnings.push(format!(
217            "it runs on {}: only a Claude agent is given {NOTE_FILE} and {CONVERSATION_FILE} when it starts, so this agent will not read them itself; they are placed in its Personal Memory for a person or another agent to read, and its history is kept as it is",
218            definition.harness
219        ));
220    }
221    if !definition.parent_id.is_empty() {
222        warnings.push("it was a fork or a worker of another agent; that link is not carried".to_string());
223    }
224    if definition.seat.as_ref().and_then(|s| s.lead.as_ref()).is_some() {
225        warnings.push("its seat's lead is not carried: the lead is another agent, who may not be here".to_string());
226    }
227
228    let mut memory = Vec::new();
229    let mut sessions = Vec::new();
230    for part in &loaded.manifest.parts {
231        if let Some(name) = part.path.strip_prefix("memory/") {
232            memory.push((name.to_string(), part.size));
233        } else if let Some(zone) = place::session_zone(&uid, &part.path) {
234            // A conversation is never written into, over or between another: this computer keeps the history of an agent
235            // that was deleted here, so the same id may already have one.
236            let held = state.global_transcript_store.as_deref().and_then(|g| g.stat(&zone, crate::backend::agent_session::OUTPUT_FILE).ok().flatten()).is_some_and(|f| f.size > 0);
237            if held {
238                blockers.push(format!("this computer already holds a conversation for {uid} (the history of an agent that was deleted here is kept); import it as a copy (mode copy) to make a new agent of it"));
239                break;
240            }
241            sessions.push((part.path.clone(), part.size));
242        }
243    }
244    Ok(Plan { mode, uid, name, definition, blockers, warnings, memory, sessions, route_line })
245}
246
247/// What `apply` made beyond the plan.
248struct Extra {
249    memory_placed: Vec<String>,
250    memory_skipped: Vec<String>,
251    sessions_placed: usize,
252    route: Option<(String, String)>,
253    seat: bool,
254    slug: String,
255    warnings: Vec<String>,
256}
257
258type Applied = (Loaded, Plan, Extra);
259
260/// The plan was made before the consent wait: what it checked about the name and the id is checked again, now.
261fn recheck_after_consent(state: &AppState, plan: &Plan) -> Result<(), SpawnError> {
262    let fail = |m: String| refuse(StatusCode::CONFLICT, format!("Agents import: {m}"));
263    if !crate::server::agent_handlers::name_available(&state.mstore, &plan.name) {
264        return Err(fail(format!("an agent here took the name {:?} while this waited; nothing was made", plan.name)));
265    }
266    if state.mstore.agent_def_get(&plan.uid).ok().flatten().is_some() {
267        return Err(fail(format!("{} became an agent here while this waited; nothing was made", plan.uid)));
268    }
269    Ok(())
270}
271
272/// Makes the agent: its conversation, its memory, then the definition, last. A failure takes back what was put.
273fn apply(state: &AppState, path: &std::path::Path, loaded: &Loaded, plan: Plan) -> Result<Applied, SpawnError> {
274    let fail = |m: String| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents import: {m}"));
275    let file = std::fs::File::open(path).map_err(|e| fail(format!("cannot open the file again: {e}")))?;
276    let mut reader = ArchiveReader::open(std::io::BufReader::new(file), Limits::default()).map_err(|e| fail(e.to_string()))?;
277    if reader.manifest() != &loaded.manifest {
278        return Err(fail("the file changed while it was being imported; nothing was made".to_string()));
279    }
280    recheck_after_consent(state, &plan)?;
281    let mut extra = Extra { memory_placed: Vec::new(), memory_skipped: Vec::new(), sessions_placed: 0, route: None, seat: false, slug: String::new(), warnings: Vec::new() };
282
283    let mut zones: Vec<String> = Vec::new();
284    let undo = |zones: &[String], memory: &[String]| {
285        if let Some(gfs) = state.global_transcript_store.as_deref() {
286            zones.iter().for_each(|z| place::remove_session(gfs, z));
287        }
288        if let Some(gfs) = state.global_transcript_store.as_deref() {
289            place::remove_memory(gfs, &plan.uid, memory);
290        }
291    };
292
293    if let Some(gfs) = state.global_transcript_store.as_deref() {
294        for (part, _) in &plan.sessions {
295            let Some(zone) = place::session_zone(&plan.uid, part) else { continue };
296            let mut bytes = Vec::new();
297            if let Err(e) = reader.read_part(part, &mut bytes) {
298                undo(&zones, &[]);
299                return Err(fail(e.to_string()));
300            }
301            if let Err(e) = place::place_session(gfs, &zone, &place::strip_foreign_marks(&bytes)) {
302                undo(&zones, &[]);
303                return Err(fail(format!("{part}: {e}")));
304            }
305            zones.push(zone);
306        }
307        extra.sessions_placed = zones.len();
308    }
309
310    let mut files: Vec<(String, Vec<u8>)> = Vec::new();
311    for (name, size) in &plan.memory {
312        match reader.read_part_bytes(&format!("memory/{name}"), place::MAX_MEMORY_FILE_BYTES as u64) {
313            Ok(bytes) => files.push((name.clone(), bytes)),
314            Err(e) => extra.memory_skipped.push(format!("{name} ({size} bytes): {e}")),
315        }
316    }
317    let facts = NoteFacts {
318        name: plan.name.clone(),
319        host_hint: loaded.manifest.source.host_hint.clone(),
320        os: loaded.manifest.source.os.clone(),
321        app_version: loaded.manifest.source.app_version.clone(),
322        signature: signature_line(&loaded.signature).to_string(),
323        dropped: loaded.parsed.dropped.clone(),
324        memory_files: plan.memory.len(),
325        sessions: plan.sessions.len(),
326    };
327    let taken: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
328    let mut notes: Vec<(String, Vec<u8>)> = Vec::new();
329    if !taken.contains(&NOTE_FILE) {
330        notes.push((NOTE_FILE.to_string(), place::arrival_note(&facts).into_bytes()));
331    } else {
332        extra.warnings.push(format!("{NOTE_FILE} is a memory file of the archive's own, so no arrival note was written"));
333    }
334    if let Ok(md) = reader.read_part_bytes("history/transcript.md", 64 << 20) {
335        if !taken.contains(&CONVERSATION_FILE) {
336            notes.push((CONVERSATION_FILE.to_string(), place::conversation_note(&String::from_utf8_lossy(&md)).into_bytes()));
337        }
338    }
339    files.extend(notes);
340    if let Some(gfs) = state.global_transcript_store.as_deref() {
341        let done = place::place_memory(gfs, &plan.uid, &files);
342        extra.memory_skipped.extend(done.skipped);
343        extra.memory_placed = done.placed;
344    } else {
345        extra.memory_skipped.extend(files.iter().map(|(n, _)| format!("{n}: the memory record is not available")));
346    }
347
348    // The agent is made last: it is only then in My Agents.
349    let mut def = definition_of(&plan);
350    if let Err(e) = state.mstore.agent_def_insert(&mut def) {
351        undo(&zones, &extra.memory_placed);
352        return Err(fail(format!("the agent could not be made: {e}")));
353    }
354    extra.slug = def.slug.clone();
355    if let Some(r) = &plan.definition.route {
356        match crate::backend::model_gateway::launch::set_choice(&state.mstore, &plan.uid, &plan.definition.harness, &r.route, &r.model) {
357            Ok(c) => extra.route = Some((c.route, c.model)),
358            Err(e) => extra.warnings.push(format!("its route {}/{} was not set: {e}", r.route, r.model)),
359        }
360    }
361    extra.seat = set_seat(state, &plan, &mut extra.warnings);
362    Ok((Loaded { manifest: loaded.manifest.clone(), signature: loaded.signature.clone(), parsed: loaded.parsed.clone() }, plan, extra))
363}
364
365/// Gives the agent the seat the archive named, without its lead (a lead is another agent's uid, meaningless here) and
366/// only when the role is one this computer has. Whether it was set; a seat that was not set says why in `warnings`.
367fn set_seat(state: &AppState, plan: &Plan, warnings: &mut Vec<String>) -> bool {
368    let Some(seat) = &plan.definition.seat else { return false };
369    let mut seat = seat.clone();
370    seat.lead = None;
371    if !crate::backend::agent_seat::is_role(&seat.role) {
372        warnings.push(format!("its seat role {:?} is not a role here, so it has no seat", seat.role));
373        return false;
374    }
375    match state.mstore.agent_seat_set(&plan.uid, Some(&seat)) {
376        Ok(()) => true,
377        Err(e) => {
378            warnings.push(format!("its seat was not set: {e}"));
379            false
380        }
381    }
382}
383
384/// The definition this import makes: the archive's allowlisted fields, and nothing a computer decides (no working folder,
385/// accounts, shell, flags, environment, container image or ambient login).
386fn definition_of(plan: &Plan) -> AgentDefinition {
387    let d = &plan.definition;
388    let slug = match plan.mode {
389        Mode::Move => d.slug.clone(),
390        Mode::Copy => agentmux_common::slug::definition_slug(&plan.name),
391    };
392    let now = agentmux_common::time::now_ms();
393    serde_json::from_value(json!({
394        "id": plan.uid,
395        "slug": slug,
396        "name": plan.name,
397        "icon": d.icon,
398        "provider": d.harness,
399        "description": d.description,
400        "created_at": now,
401        "updated_at": now,
402        "auto_start": d.auto_start,
403        "restart_on_crash": d.restart_on_crash,
404        "idle_timeout_minutes": d.idle_timeout_minutes,
405        "agent_type": d.agent_type,
406        "branch_label": d.branch_label,
407        "conversation_visibility": d.conversation_visibility,
408        "is_seeded": 0,
409        "user_hidden": 0,
410    }))
411    .expect("a definition from allowlisted, checked fields")
412}
413
414/// Whether an agent of `harness` is given its arrival note and readable conversation when it starts: Personal Memory is read into
415/// a Claude agent's start only (a placement rule for each other harness is later work, spec section 7).
416fn gets_arrival_note(harness: &str) -> bool {
417    harness.eq_ignore_ascii_case("claude")
418}
419
420fn report(loaded: &Loaded, plan: &Plan, dry_run: bool, extra: Option<Extra>) -> serde_json::Value {
421    let sum = |v: &[(String, u64)]| v.iter().map(|(_, n)| n).sum::<u64>();
422    let mut warnings = plan.warnings.clone();
423    if let Some(e) = &extra {
424        warnings.extend(e.warnings.clone());
425        warnings.extend(e.memory_skipped.iter().map(|s| format!("memory file skipped: {s}")));
426    }
427    let mut out = json!({
428        "dry_run": dry_run,
429        "ok": plan.blockers.is_empty(),
430        "mode": if plan.mode == Mode::Move { "move" } else { "copy" },
431        "agent_id": plan.uid,
432        "name": plan.name,
433        "source": {
434            "computer": loaded.manifest.source.host_hint,
435            "os": loaded.manifest.source.os,
436            "app_version": loaded.manifest.source.app_version,
437            "written_at": loaded.manifest.created_at,
438            "signature": signature_line(&loaded.signature),
439        },
440        "carries": { "memory_files": plan.memory.len(), "memory_bytes": sum(&plan.memory), "conversations": plan.sessions.len(), "conversation_bytes": sum(&plan.sessions) },
441        "dropped_settings": loaded.parsed.dropped,
442        "blockers": plan.blockers,
443        "warnings": warnings,
444        "history_note": "The history is carried as it is: a secret that was pasted into a conversation and is not a value AgentMux holds is in it.",
445    });
446    if let Some(e) = extra {
447        out["started"] = json!(false);
448        out["slug"] = json!(e.slug);
449        out["memory_placed"] = json!(e.memory_placed);
450        out["conversations_placed"] = json!(e.sessions_placed);
451        out["route"] = json!(e.route.map(|(r, m)| format!("{r}/{m}")));
452        out["seat"] = json!(e.seat);
453        let told = gets_arrival_note(&plan.definition.harness);
454        out["arrival_note_given_to_agent"] = json!(told);
455        out["next"] = json!(if told {
456            "It is in My Agents, stopped. Start it with Agents open; its first message to itself is the arrival-note.md in its Personal Memory."
457        } else {
458            "It is in My Agents, stopped. Start it with Agents open. Its harness is not given the arrival note or the conversation at its first start, so tell it where it came from yourself; both are in its Personal Memory."
459        });
460    }
461    out
462}