Skip to main content

agentmux_srv/server/app_api/
agent_migrate_ids.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents migrate_ids` (`POST /api/v1/agent/migrate-ids`): an agent runs the agent id update for
5//! the person, the same steps Settings › Agents › Outdated agent ids runs
6//! (`agents.migrateForkSlugs`, `agent_handlers/fork_slugs.rs`): `plan` reads and changes nothing,
7//! `stop` asks every pane running an affected agent to stop (each with its user's 30 s override,
8//! and the answer says how long to wait), `apply` migrates, `rollback` undoes a run from its
9//! journal (always the latest finished run: an agent names no journal file). The caller is the agent its token names; a request without one is refused, so a change
10//! is never attributed to the operator. Every step but `plan` is recorded in the audit log under
11//! the calling agent's slug.
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::json;
19
20use crate::backend::rpc_types::{CommandMigrateForkSlugsData, ForkSlugChoice, ForkSlugMigrationMode};
21use crate::server::agent_handlers::fork_slugs;
22use crate::server::caller::Caller;
23use crate::server::state::AppState;
24
25/// The audit entry's action for a step.
26pub(crate) const AUDIT_ACTION: &str = "agent.ids.update";
27
28#[derive(Debug, Deserialize)]
29pub(crate) struct MigrateIdsRequest {
30    /// `plan`, `stop`, `apply` or `rollback`.
31    step: String,
32    /// Not accepted: opening a journal repairs it in place and its undo steps rename and restore the paths it
33    /// names, so a path from an agent would reach any file. A rollback undoes the latest finished run.
34    #[serde(default)]
35    journal: Option<String>,
36    /// The id to give an agent whose computed id is taken: `[{uid, new_slug}]`.
37    #[serde(default)]
38    choices: Option<Vec<ForkSlugChoice>>,
39}
40
41/// What the migration does for `step`, if it is one an agent may ask for.
42pub(crate) fn mode_of(step: &str) -> Option<ForkSlugMigrationMode> {
43    match step {
44        "plan" => Some(ForkSlugMigrationMode::Plan),
45        "stop" => Some(ForkSlugMigrationMode::Stop),
46        "apply" => Some(ForkSlugMigrationMode::Apply),
47        "rollback" => Some(ForkSlugMigrationMode::Rollback),
48        _ => None,
49    }
50}
51
52fn refuse(status: StatusCode, message: impl Into<String>) -> Response {
53    (status, Json(json!({ "error": message.into() }))).into_response()
54}
55
56fn audit(state: &AppState, uid: &str, slug: &str, step: &str, error: Option<&str>) {
57    let block_id = state.reactive_handler.block_for_uid(uid).unwrap_or_default();
58    let reason = format!("{slug} (uid {uid}): agent id update, step {step}");
59    state.reactive_handler.log_fleet_action_audit(
60        Some(slug),
61        "all agents",
62        &block_id,
63        AUDIT_ACTION,
64        error.is_none(),
65        error,
66        &uuid::Uuid::new_v4().to_string(),
67        Some(&reason),
68    );
69}
70
71pub(crate) async fn handle_agent_migrate_ids(
72    State(state): State<AppState>,
73    caller: Option<Extension<Caller>>,
74    Json(req): Json<MigrateIdsRequest>,
75) -> Response {
76    let caller = caller.map(|Extension(c)| c);
77    let Some(uid) = caller.as_ref().and_then(Caller::uid) else {
78        return refuse(
79            StatusCode::UNAUTHORIZED,
80            "no agent token: Agents migrate_ids acts as the calling agent; the operator runs the update in Settings › Agents",
81        );
82    };
83    if req.journal.is_some() {
84        return refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: journal is not accepted from an agent: rollback undoes the latest finished run");
85    }
86    let step = req.step.trim().to_string();
87    let Some(mode) = mode_of(&step) else {
88        return refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: step is plan, stop, apply or rollback");
89    };
90    let def = match state.mstore.agent_def_get(uid) {
91        Ok(Some(def)) => def,
92        Ok(None) => return refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"),
93        Err(e) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent id update: {e}")),
94    };
95    let cmd = CommandMigrateForkSlugsData { mode, journal: None, quick: None, choices: req.choices };
96    let stopped_by = format!("{} (Agents migrate_ids)", def.slug);
97    let result = fork_slugs::run(&state, cmd, &stopped_by).await;
98    if mode != ForkSlugMigrationMode::Plan {
99        audit(&state, uid, &def.slug, &step, result.as_ref().err().map(String::as_str));
100    }
101    match result {
102        Ok(r) => Json(r).into_response(),
103        Err(e) => refuse(StatusCode::INTERNAL_SERVER_ERROR, e),
104    }
105}
106
107#[cfg(test)]
108#[path = "tests/agent_migrate_ids_tests.rs"]
109mod tests;