1use 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
32pub(crate) const AUDIT_ACTION: &str = "agent.rotate_token";
34
35#[derive(Debug, Deserialize)]
36pub(crate) struct RotateRequest {
37 agent: String,
39}
40
41async 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
51enum Restart {
53 Done,
54 NoBlock,
56 Failed(String),
57}
58
59async 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 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 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
129async 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
149async 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, ¬e));
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;