Skip to main content

agentmux_srv/server/app_api/
agent_rename.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents rename` (`POST /api/v1/agent/rename`): an agent gives an agent on this machine a new displayed
5//! name, by the same path the window's rename takes (`agent_handlers::rename`), so the pane, My Agents, the
6//! Swarm, message addressing, seats and the Kanban all follow. The agent's id, slug, signing keys and
7//! workspace folder do not change: they are fixed when it launches. The old name keeps reaching it as a former
8//! name, and no other agent may take it.
9//!
10//! The caller is the agent its token names; a request without one is refused, so a change is never attributed
11//! to the operator. A name another agent has now is refused. Each rename, and each refusal, is recorded in the
12//! audit log under the calling agent.
13
14use axum::extract::State;
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::{Extension, Json};
18use serde::Deserialize;
19use serde_json::{json, Value};
20
21use super::agent_lifecycle::{refuse, target_of, Refusal};
22use crate::server::agent_handlers::rename::RenameError;
23use crate::server::caller::Caller;
24use crate::server::state::AppState;
25
26/// The audit entry's action for a rename.
27pub(crate) const AUDIT_ACTION: &str = "agent.rename";
28/// The longest name: what a pane tab and a Swarm row can show.
29const MAX_NAME_CHARS: usize = 64;
30
31#[derive(Debug, Clone, Deserialize)]
32pub(crate) struct RenameRequest {
33    /// The agent's id or slug.
34    agent: String,
35    /// Its new displayed name.
36    name: String,
37}
38
39/// The agent making the request.
40struct Actor {
41    uid: String,
42    slug: String,
43}
44
45fn actor_of(state: &AppState, caller: Option<&Caller>) -> Result<Actor, Refusal> {
46    let Some(uid) = caller.and_then(Caller::uid) else {
47        return Err(refuse(
48            StatusCode::UNAUTHORIZED,
49            "no agent token: Agents rename acts as the calling agent; the operator renames in My Agents",
50        ));
51    };
52    let def = state
53        .mstore
54        .agent_def_get(uid)
55        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents rename: {e}")))?
56        .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
57    Ok(Actor { uid: uid.to_string(), slug: def.slug })
58}
59
60fn audit(state: &AppState, actor: &Actor, target: &str, ok: bool, error: Option<&str>, note: &str) -> String {
61    let request_id = uuid::Uuid::new_v4().to_string();
62    let block_id = state.reactive_handler.block_for_uid(&actor.uid).unwrap_or_default();
63    let reason = format!("{} (uid {}): {note}", actor.slug, actor.uid);
64    state.reactive_handler.log_fleet_action_audit(Some(&actor.slug), target, &block_id, AUDIT_ACTION, ok, error, &request_id, Some(&reason));
65    request_id
66}
67
68async fn run_as(state: &AppState, actor: &Actor, req: RenameRequest) -> Result<Value, Refusal> {
69    let name = req.name.trim().to_string();
70    if name.is_empty() {
71        return Err(refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: name is empty; give the agent's new name"));
72    }
73    if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
74        return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: a name is at most {MAX_NAME_CHARS} characters on one line")));
75    }
76    let blocking = state.clone();
77    let named = req.agent.clone();
78    let target = tokio::task::spawn_blocking(move || target_of(&blocking, &named))
79        .await
80        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents rename: {e}")))??;
81    let (updated, old_name) = crate::server::agent_handlers::rename::rename_title(state, &target.agent_id, &name, true)
82        .await
83        .map_err(|e| {
84            let status = match &e {
85                RenameError::NotFound(_) => StatusCode::NOT_FOUND,
86                RenameError::Invalid(_) => StatusCode::BAD_REQUEST,
87                RenameError::Taken(_) => StatusCode::CONFLICT,
88                RenameError::Failed(_) => StatusCode::INTERNAL_SERVER_ERROR,
89            };
90            refuse(status, format!("Agents rename: {e}"))
91        })?;
92    let audit_id = audit(state, actor, &updated.slug, true, None, &format!("renamed {old_name} ({}) to {name}", target.agent_id));
93    Ok(json!({
94        "agent_id": target.agent_id,
95        "slug": updated.slug,
96        "name": name,
97        "was": old_name,
98        "audit_id": audit_id,
99        "note": "its id, slug and workspace folder are unchanged; the old name still reaches it; if it is running it has been told",
100    }))
101}
102
103async fn run(state: &AppState, caller: Option<&Caller>, req: RenameRequest) -> Result<Value, Refusal> {
104    let actor = actor_of(state, caller)?;
105    let named = req.agent.clone();
106    match run_as(state, &actor, req).await {
107        Ok(body) => Ok(body),
108        Err(refusal) => {
109            audit(state, &actor, named.trim(), false, Some(&refusal.message), "refused");
110            Err(refusal)
111        }
112    }
113}
114
115/// `rename` for an agent on another machine (`remote_ops::agent_ops`): the same checks and change a local call
116/// has, recorded under `who` (`slug@machine`).
117pub(crate) async fn run_remote(state: &AppState, who: &str, req: RenameRequest) -> Result<Value, (StatusCode, String)> {
118    let actor = Actor { uid: format!("remote:{who}"), slug: who.to_string() };
119    let named = req.agent.clone();
120    match run_as(state, &actor, req).await {
121        Ok(body) => Ok(body),
122        Err(r) => {
123            audit(state, &actor, named.trim(), false, Some(&r.message), "refused");
124            Err((r.status, r.message))
125        }
126    }
127}
128
129pub(crate) async fn handle_agent_rename(
130    State(state): State<AppState>,
131    caller: Option<Extension<Caller>>,
132    Json(req): Json<RenameRequest>,
133) -> Response {
134    let caller = caller.map(|Extension(c)| c);
135    match run(&state, caller.as_ref(), req).await {
136        Ok(body) => Json(body).into_response(),
137        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
138    }
139}
140
141#[cfg(test)]
142#[path = "tests/agent_rename_tests.rs"]
143mod tests;