Skip to main content

agentmux_srv/server/app_api/
agent_rotate_token.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents rotate_token` (`POST /api/v1/agent/rotate-token`): an agent replaces the token of an agent on this
5//! machine. The token is part of the agent's spawn environment, so the new one reaches the agent only through a
6//! restart; the old value stops working the moment the stored row is replaced (`Store::agent_token_rotate`).
7//!
8//! The caller is the agent its token names; a request without one is refused, so a change is never attributed
9//! to the operator. Each rotation, each wait for the person's window and each refusal is recorded in the audit
10//! log under the calling agent. The answer, the note a caller is sent and the audit never carry a token value.
11//!
12//! - Not your own agent: a restart of yourself is not yours to run; another agent rotates yours.
13//! - A stopped agent: the row is replaced and nothing restarts; it takes the new token when it next starts.
14//! - A running agent: it is stopped as `Agents stop` stops it (the person's 30 s window to keep it running,
15//!   except for a worker the caller opened, which is stopped at once), its row is replaced once it has stopped,
16//!   and it starts again in the pane and conversation it had. If its user keeps it running, nothing changes and
17//!   the caller is told.
18
19use std::time::{Duration, Instant};
20
21use axum::extract::State;
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Response};
24use axum::{Extension, Json};
25use serde::Deserialize;
26use serde_json::{json, Value};
27
28use super::agent_lifecycle::{actor_of, audit, may_have_process, refuse, row_json, stop, target_of, Actor, LifecycleRequest, Refusal};
29use crate::server::caller::Caller;
30use crate::server::state::AppState;
31
32/// The audit entry's action for a rotation.
33pub(crate) const AUDIT_ACTION: &str = "agent.rotate_token";
34
35#[derive(Debug, Deserialize)]
36pub(crate) struct RotateRequest {
37    /// The agent's id, slug or name.
38    agent: String,
39}
40
41/// Replace the stored token (and its index entry): off the async workers, as it takes the store's lock.
42async fn replace_row(state: &AppState, agent_id: &str) -> Result<(), String> {
43    let store = state.mstore.clone();
44    let uid = agent_id.to_string();
45    tokio::task::spawn_blocking(move || store.agent_token_rotate(&uid))
46        .await
47        .map_err(|e| format!("Agents rotate_token: {e}"))?
48        .map_err(|e| format!("Agents rotate_token: {e}"))
49}
50
51/// How a restart in the agent's own pane went.
52enum Restart {
53    Done,
54    /// The agent has no block any more (its tab was closed meanwhile): it is left stopped.
55    NoBlock,
56    Failed(String),
57}
58
59/// Start the agent again, in the block (pane) it has, with its session resumed: its spawn environment is built
60/// afresh and carries the replaced token.
61async fn restart_in_place(state: &AppState, agent_id: &str) -> Restart {
62    match super::agent_block::find_agent_block_by_uid(&state.mstore, agent_id) {
63        Ok(Some(_)) => match super::agent_attach::start_agent(state, agent_id).await {
64            Ok(_) => Restart::Done,
65            Err(e) => Restart::Failed(e),
66        },
67        Ok(None) => Restart::NoBlock,
68        Err(e) => Restart::Failed(e),
69    }
70}
71
72fn after_restart_note(name: &str, restart: &Restart) -> String {
73    match restart {
74        Restart::Done => format!("{name}'s token is replaced and it restarted in its pane with its conversation."),
75        Restart::NoBlock => format!("{name}'s token is replaced; it has no pane or block now, so it is stopped and takes the new token when it is next started (Agents start)."),
76        Restart::Failed(e) => format!("{name}'s token is replaced but it did not restart ({e}): it is stopped, and Agents start runs it with the new token."),
77    }
78}
79
80async fn rotate(state: &AppState, actor: &Actor, req: &RotateRequest) -> Result<Value, Refusal> {
81    let blocking = state.clone();
82    let named = req.agent.clone();
83    let target = tokio::task::spawn_blocking(move || target_of(&blocking, &named))
84        .await
85        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents rotate_token: {e}")))??;
86    if target.agent_id == actor.uid() {
87        return Err(refuse(
88            StatusCode::CONFLICT,
89            "SELF_ROTATE: that is you. A new token reaches an agent only through a restart, which you cannot run on yourself: ask another agent on this machine (your leader or a peer) to run Agents rotate_token with your id, and you restart in your pane",
90        ));
91    }
92    let running = may_have_process(&target);
93    // A restart is a start: the sender's per-minute limit counts it, and it is checked before the person's window opens.
94    if running {
95        crate::server::start_rate::allow(state, actor.uid()).map_err(|e| refuse(StatusCode::TOO_MANY_REQUESTS, e))?;
96    }
97    let stopped = stop(state, actor, &LifecycleRequest { agent: req.agent.clone() }).await?;
98    let (name, agent_id) = (target.name.clone(), target.agent_id.clone());
99
100    // The person has their window to keep it running: replace the token and restart only if it goes on to stop.
101    if let Some(pending) = stopped.get("pending").filter(|p| !p.is_null()) {
102        let Some(request_id) = pending["request_id"].as_str().map(str::to_string) else {
103            return Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, "Agents rotate_token: the stop request has no id"));
104        };
105        tokio::spawn(finish_after_window(state.clone(), actor.clone(), agent_id.clone(), name.clone(), request_id));
106        return Ok(json!({
107            "agent": name, "agent_id": agent_id, "rotated": false, "restarted": false, "pending": pending,
108            "note": "its user has 30 seconds to keep it running; if it stops, its token is replaced and it restarts in its pane, and you are told by a note either way",
109            "runtime": row_json(state, &agent_id),
110        }));
111    }
112
113    replace_row(state, &agent_id).await.map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
114    if stopped["stopped"] != true {
115        return Ok(json!({
116            "agent": name, "agent_id": agent_id, "rotated": true, "restarted": false,
117            "note": "it was not running: its token is replaced and it takes the new one when it is next started",
118            "runtime": row_json(state, &agent_id),
119        }));
120    }
121    let restart = restart_in_place(state, &agent_id).await;
122    Ok(json!({
123        "agent": name, "agent_id": agent_id, "rotated": true, "restarted": matches!(restart, Restart::Done),
124        "block_id": stopped["block_id"], "note": after_restart_note(&name, &restart),
125        "runtime": row_json(state, &agent_id),
126    }))
127}
128
129/// Wait for the stop request to end: `Ok` once the agent has stopped (or already had), else why it did not.
130async fn wait_for_stop(request_id: &str) -> Result<(), String> {
131    let give_up = Instant::now() + crate::sagas::pending_shutdown::OVERRIDE_WINDOW + Duration::from_secs(60);
132    loop {
133        match crate::sagas::pending_shutdown::status(request_id) {
134            None => return Err("the stop request was lost".to_string()),
135            Some(v) => match v.status {
136                "pending" | "proceeding" => {}
137                "shut_down" | "superseded" => return Ok(()),
138                "kept_by_user" => return Err("its user chose to keep it running".to_string()),
139                _ => return Err(v.error.unwrap_or_else(|| format!("the stop ended as {}", v.status))),
140            },
141        }
142        if Instant::now() >= give_up {
143            return Err("the stop did not finish in time".to_string());
144        }
145        tokio::time::sleep(Duration::from_millis(300)).await;
146    }
147}
148
149/// After the person's window: if the agent stopped, replace its token and start it again; tell the caller how it
150/// ended, by a held `[AgentMux]` note that does not wake it, and record it under the caller.
151async fn finish_after_window(state: AppState, actor: Actor, agent_id: String, name: String, request_id: String) {
152    let stopped = wait_for_stop(&request_id).await;
153    settle(&state, &actor, &agent_id, &name, &request_id, stopped).await;
154}
155
156async fn settle(state: &AppState, actor: &Actor, agent_id: &str, name: &str, request_id: &str, stopped: Result<(), String>) {
157    let (ok, text) = match stopped {
158        Err(why) => (false, format!("[AgentMux] Agents rotate_token for {name} was not done: {why}. Its token is unchanged; run it again when the agent can be stopped.")),
159        Ok(()) => match replace_row(state, agent_id).await {
160            Err(e) => (false, format!("[AgentMux] Agents rotate_token for {name} failed after it stopped: {e}. Its token is unchanged and it is stopped; Agents start runs it again.")),
161            Ok(()) => {
162                let restart = restart_in_place(state, agent_id).await;
163                (true, format!("[AgentMux] Agents rotate_token: {}", after_restart_note(name, &restart)))
164            }
165        },
166    };
167    audit(state, actor, AUDIT_ACTION, agent_id, "", ok, (!ok).then_some(text.as_str()), "after the user's window");
168    if let Err(e) = state.reactive_handler.hold_system_note(actor.slug(), &format!("rotate-token:{request_id}"), &text) {
169        tracing::debug!(by = actor.slug(), "rotate_token note not held: {e}");
170    }
171}
172
173async fn run(state: &AppState, caller: Option<&Caller>, req: RotateRequest) -> Result<Value, Refusal> {
174    let actor = actor_of(state, caller, "rotate_token")?;
175    match rotate(state, &actor, &req).await {
176        Ok(mut body) => {
177            let block_id = body["block_id"].as_str().unwrap_or_default().to_string();
178            let target = body["agent_id"].as_str().unwrap_or_default().to_string();
179            let note = body["note"].as_str().unwrap_or_default().to_string();
180            body["audit_id"] = json!(audit(state, &actor, AUDIT_ACTION, &target, &block_id, true, None, &note));
181            Ok(body)
182        }
183        Err(refusal) => {
184            audit(state, &actor, AUDIT_ACTION, req.agent.trim(), "", false, Some(&refusal.message), "refused");
185            Err(refusal)
186        }
187    }
188}
189
190pub(crate) async fn handle_agent_rotate_token(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<RotateRequest>) -> Response {
191    let caller = caller.map(|Extension(c)| c);
192    match run(&state, caller.as_ref(), req).await {
193        Ok(body) => Json(body).into_response(),
194        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
195    }
196}
197
198#[cfg(test)]
199#[path = "tests/agent_rotate_token_tests.rs"]
200mod tests;