1use 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 crate::server::agent_runtime::{self, AgentRuntime, AgentRuntimeState};
29use crate::server::caller::Caller;
30use crate::server::state::AppState;
31
32#[derive(Debug, Deserialize)]
33pub(crate) struct LifecycleRequest {
34 pub(super) agent: String,
36}
37
38impl LifecycleRequest {
39 pub(super) fn of(agent: &str) -> Self {
41 Self { agent: agent.to_string() }
42 }
43}
44
45pub(super) struct Refusal {
46 pub(super) status: StatusCode,
47 pub(super) message: String,
48}
49
50pub(super) fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
51 Refusal { status, message: message.into() }
52}
53
54#[derive(Clone)]
56pub(super) struct Actor {
57 uid: String,
58 slug: String,
59 person: bool,
63}
64
65impl Actor {
66 pub(super) fn uid(&self) -> &str {
67 &self.uid
68 }
69
70 pub(super) fn slug(&self) -> &str {
71 &self.slug
72 }
73
74 pub(super) fn is_person(&self) -> bool {
76 self.person
77 }
78
79 pub(super) fn remote(who: &str) -> Self {
81 Self { uid: format!("remote:{who}"), slug: who.to_string(), person: false }
82 }
83}
84
85pub(super) fn actor_of(state: &AppState, caller: Option<&Caller>, action: &str) -> Result<Actor, Refusal> {
86 let Some(uid) = caller.and_then(Caller::uid) else {
87 return Err(refuse(
88 StatusCode::UNAUTHORIZED,
89 format!("no agent token: Agents {action} acts as the calling agent; the operator uses the Swarm or My Agents"),
90 ));
91 };
92 let def = state
93 .mstore
94 .agent_def_get(uid)
95 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents {action}: {e}")))?
96 .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
97 Ok(Actor { uid: uid.to_string(), slug: def.slug, person: false })
98}
99
100pub(super) fn acting(state: &AppState, caller: Option<&Caller>, action: &str, named: Option<&str>) -> Result<Actor, Refusal> {
104 if caller.and_then(Caller::uid).is_some() {
105 return actor_of(state, caller, action);
106 }
107 let named = named.map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: agent is empty; a person names the agent to {action}")))?;
108 let uid = crate::backend::agent_resolve::resolve_agent_named(&state.mstore, named)
109 .map_err(|e| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine: {e}")))?;
110 let lead = crate::backend::agent_seat::effective_seat_by_id(&state.mstore, &uid).and_then(|s| s.lead);
111 let through = lead.as_deref().and_then(|l| state.mstore.agent_def_get(l).ok().flatten()).or_else(|| state.mstore.agent_def_get(&uid).ok().flatten());
112 let def = through.ok_or_else(|| refuse(StatusCode::NOT_FOUND, "no such agent on this machine"))?;
113 Ok(Actor { uid: def.id, slug: def.slug, person: true })
114}
115
116pub(super) fn target_of(state: &AppState, named: &str) -> Result<AgentRuntime, Refusal> {
119 let named = named.trim();
120 if named.is_empty() {
121 return Err(refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: agent is empty; give an agent's id or slug (Agents list)"));
122 }
123 let uid = crate::backend::agent_resolve::resolve_agent_named(&state.mstore, named)
124 .map_err(|e| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine: {e}")))?;
125 agent_runtime::list(state, agentmux_common::time::now_ms_u64())
126 .into_iter()
127 .find(|r| r.agent_id == uid)
128 .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("TEMPLATE_NOT_OPENABLE: '{named}' is not an agent created on this machine")))
129}
130
131pub(super) fn is_running(row: &AgentRuntime) -> bool {
136 match row.state {
137 AgentRuntimeState::Stopped | AgentRuntimeState::Error => false,
138 AgentRuntimeState::Starting | AgentRuntimeState::Working | AgentRuntimeState::WaitingOnUser => true,
139 AgentRuntimeState::Idle | AgentRuntimeState::Limited | AgentRuntimeState::SignedOut => {
140 row.desired == agent_runtime::AgentDesiredState::Running
141 }
142 }
143}
144
145pub(super) fn may_have_process(row: &AgentRuntime) -> bool {
148 !matches!(row.state, AgentRuntimeState::Stopped | AgentRuntimeState::Error)
149}
150
151pub(super) fn audit(state: &AppState, actor: &Actor, action: &str, target: &str, block_id: &str, ok: bool, error: Option<&str>, note: &str) -> String {
152 let request_id = uuid::Uuid::new_v4().to_string();
153 let reason = format!("agent-initiated {action} by {} (uid {}): {note}", actor.slug, actor.uid);
154 tracing::info!(action, target, ok, "{reason}");
155 state.reactive_handler.log_fleet_action_audit(Some(&actor.slug), target, block_id, action, ok, error, &request_id, Some(&reason));
156 request_id
157}
158
159pub(super) fn row_json(state: &AppState, agent_id: &str) -> Value {
161 agent_runtime::list(state, agentmux_common::time::now_ms_u64())
162 .into_iter()
163 .find(|r| r.agent_id == agent_id)
164 .map(|r| json!({ "state": r.state, "desired": r.desired, "block_id": r.block_id }))
165 .unwrap_or(Value::Null)
166}
167
168async fn start(state: &AppState, actor: &Actor, req: &LifecycleRequest) -> Result<Value, Refusal> {
169 let blocking = state.clone();
170 let named = req.agent.clone();
171 let target = tokio::task::spawn_blocking(move || target_of(&blocking, &named))
172 .await
173 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents start: {e}")))??;
174 if is_running(&target) {
176 return Ok(json!({
177 "agent": target.name, "agent_id": target.agent_id, "started": false,
178 "note": "already running", "runtime": { "state": target.state, "desired": target.desired, "block_id": target.block_id },
179 }));
180 }
181 crate::server::start_rate::allow(state, &actor.uid).map_err(|e| refuse(StatusCode::TOO_MANY_REQUESTS, e))?;
182 let block_id = crate::server::app_api::agent_attach::start_agent(state, &target.agent_id)
183 .await
184 .map_err(|e| refuse(StatusCode::CONFLICT, format!("Agents start {}: {e}", target.name)))?;
185 Ok(json!({
186 "agent": target.name, "agent_id": target.agent_id, "started": true, "block_id": block_id,
187 "note": "running with no pane; Agents open shows it, Agents stop ends it",
188 "runtime": row_json(state, &target.agent_id),
189 }))
190}
191
192pub(crate) fn needs_window(mstore: &crate::backend::storage::store::Store, caller: &str, target: &str) -> bool {
195 target != caller && crate::server::app_api::agent_spawn::worker_of(mstore, target).as_deref() != Some(caller)
196}
197
198pub(super) async fn stop(state: &AppState, actor: &Actor, req: &LifecycleRequest) -> Result<Value, Refusal> {
199 let blocking = state.clone();
200 let named = req.agent.clone();
201 let target = tokio::task::spawn_blocking(move || target_of(&blocking, &named))
202 .await
203 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents stop: {e}")))??;
204 if !actor.person && target.agent_id == actor.uid {
205 return Err(refuse(
206 StatusCode::CONFLICT,
207 "SELF_STOP: that is you. Stop with action \"self\" ends your own agent, with the person's window to keep you",
208 ));
209 }
210 let Some(block_id) = target.block_id.clone() else {
211 return Ok(json!({ "agent": target.name, "agent_id": target.agent_id, "stopped": false, "note": "already stopped: it has no process" }));
212 };
213 if !may_have_process(&target) {
214 crate::server::app_api::agent_attach::set_desired(&state.mstore, &block_id, crate::server::app_api::agent_attach::DESIRED_STOPPED);
215 return Ok(json!({ "agent": target.name, "agent_id": target.agent_id, "stopped": false, "block_id": block_id, "note": "already stopped" }));
216 }
217 if !actor.person && needs_window(&state.mstore, &actor.uid, &target.agent_id) {
220 let (now, pending) =
221 crate::server::app_api::fleet::fleet_stop_keep_pane_with_override(state, &actor.slug, vec![block_id.clone()], None, None).await;
222 if let Some(v) = pending.into_iter().next() {
223 return Ok(json!({
224 "agent": target.name, "agent_id": target.agent_id, "stopped": false, "block_id": block_id, "pending": v,
225 "note": "its user has 30 seconds to keep it running; it stops after that unless they do",
226 "runtime": row_json(state, &target.agent_id),
227 }));
228 }
229 if let Some(failed) = now.failed.first() {
230 return Err(refuse(StatusCode::CONFLICT, format!("Agents stop {}: {}", target.name, failed.error)));
231 }
232 } else {
233 crate::sagas::agent_teardown::stop(state, &block_id, true, None)
234 .await
235 .map_err(|e| refuse(StatusCode::CONFLICT, format!("Agents stop {}: {e}", target.name)))?;
236 }
237 Ok(json!({
238 "agent": target.name, "agent_id": target.agent_id, "stopped": true, "block_id": block_id,
239 "note": "stopped by an agent and wanted stopped: a restart does not resume it; Agents start or a message starts it again",
240 "runtime": row_json(state, &target.agent_id),
241 }))
242}
243
244async fn detach(state: &AppState, req: &LifecycleRequest) -> Result<Value, Refusal> {
245 let blocking = state.clone();
246 let named = req.agent.clone();
247 let (target, found) = tokio::task::spawn_blocking(move || {
248 let target = target_of(&blocking, &named)?;
249 let found = crate::server::app_api::agent_block::find_agent_block_by_uid(&blocking.mstore, &target.agent_id)
250 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
251 Ok::<_, Refusal>((target, found))
252 })
253 .await
254 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents detach: {e}")))??;
255 let Some(found) = found else {
256 return Err(refuse(StatusCode::NOT_FOUND, format!("{} has no pane or parked block to detach: Agents start runs it with none", target.name)));
257 };
258 let block_id = found.block.oid.clone();
259 if found.tab_id.is_none() {
260 return Ok(json!({ "agent": target.name, "agent_id": target.agent_id, "detached": false, "block_id": block_id, "note": "already detached: no pane shows it" }));
261 }
262 if !crate::sagas::park_agents::is_parkable(state, &block_id) {
264 return Err(refuse(
265 StatusCode::CONFLICT,
266 format!("Agents detach {}: its block is not an agent pane that can be parked; it is left as it is", target.name),
267 ));
268 }
269 let opts = crate::sagas::close_pane::CloseOpts { frontend_waits: true, park_agents: true };
271 crate::sagas::close_pane::run_with(state, vec![block_id.clone()], opts)
272 .await
273 .map_err(|e| refuse(StatusCode::CONFLICT, format!("Agents detach {}: {e}", target.name)))?;
274 let parked = crate::server::app_api::agent_block::find_agent_block_by_uid(&state.mstore, &target.agent_id)
276 .ok()
277 .flatten()
278 .is_some_and(|b| b.tab_id.is_none());
279 if !parked {
280 return Err(refuse(StatusCode::CONFLICT, format!("Agents detach {}: its block is not parked", target.name)));
281 }
282 Ok(json!({
283 "agent": target.name, "agent_id": target.agent_id, "detached": true, "block_id": block_id,
284 "note": "the pane is gone and the agent keeps running; Agents open shows it again",
285 "runtime": row_json(state, &target.agent_id),
286 }))
287}
288
289async fn delete(state: &AppState, actor: &Actor, req: &LifecycleRequest) -> Result<Value, Refusal> {
293 let blocking = state.clone();
294 let named = req.agent.clone();
295 let (target, found) = tokio::task::spawn_blocking(move || {
296 let target = target_of(&blocking, &named)?;
297 let found = crate::server::app_api::agent_block::find_agent_block_by_uid(&blocking.mstore, &target.agent_id)
298 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
299 Ok::<_, Refusal>((target, found))
300 })
301 .await
302 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents delete: {e}")))??;
303 if target.agent_id == actor.uid {
304 return Err(refuse(StatusCode::CONFLICT, "SELF_DELETE: that is you; an agent cannot delete itself"));
305 }
306 if crate::server::app_api::agent_spawn::creator_of(&state.mstore, &target.agent_id).as_deref() != Some(actor.uid.as_str()) {
307 return Err(refuse(
308 StatusCode::FORBIDDEN,
309 format!("NOT_YOURS: {} was not made by you (Agents create, or a worker you spawned); only its maker, or the operator in My Agents, can delete it", target.name),
310 ));
311 }
312 if may_have_process(&target) {
313 return Err(refuse(StatusCode::CONFLICT, format!("RUNNING: {} is not stopped; Agents stop it first, then delete it", target.name)));
314 }
315 if found.as_ref().is_some_and(|f| f.tab_id.is_some()) {
316 return Err(refuse(StatusCode::CONFLICT, format!("PANE_OPEN: {} has a pane open; close it first (Agents detach), then delete it", target.name)));
317 }
318 let kept = state.mstore.agent_def_get(&target.agent_id).ok().flatten().as_ref().and_then(kept_workspace);
320 crate::server::agent_handlers::delete_agent_definition(state, &target.agent_id, "Agents delete")
321 .await
322 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
323 Ok(delete_answer(&target.name, &target.agent_id, kept))
324}
325
326fn kept_workspace(def: &crate::backend::storage::AgentDefinition) -> Option<std::path::PathBuf> {
330 let folder = crate::backend::base::expand_home_dir_safe(super::agent_open_steps::agent_work_dir(def).trim());
332 folder.is_dir().then_some(folder)
333}
334
335fn delete_answer(name: &str, agent_id: &str, kept: Option<std::path::PathBuf>) -> Value {
337 const GONE: &str = "the agent's definition, its parked block and its container storage are gone; this cannot be undone";
338 match kept {
339 Some(folder) => {
340 let folder = folder.to_string_lossy().replace('\\', "/");
341 json!({
342 "agent": name, "agent_id": agent_id, "deleted": true,
343 "workspace_kept": true, "workspace": folder,
344 "note": format!("{GONE}. Its workspace folder {folder} is kept, because it may hold work that was never pushed; remove it yourself when it does not. A new agent given the same name uses it again, clone included."),
345 })
346 }
347 None => json!({ "agent": name, "agent_id": agent_id, "deleted": true, "workspace_kept": false, "note": GONE }),
348 }
349}
350
351async fn run(state: &AppState, caller: Option<&Caller>, action: &str, req: LifecycleRequest) -> Result<Value, Refusal> {
352 let actor = actor_of(state, caller, action)?;
353 run_as(state, actor, action, req).await
354}
355
356pub(crate) async fn run_remote(state: &AppState, who: &str, action: &str, agent: &str) -> Result<Value, (StatusCode, String)> {
360 let actor = Actor { uid: format!("remote:{who}"), slug: who.to_string(), person: false };
361 run_as(state, actor, action, LifecycleRequest { agent: agent.to_string() }).await.map_err(|r| (r.status, r.message))
362}
363
364async fn run_as(state: &AppState, actor: Actor, action: &str, req: LifecycleRequest) -> Result<Value, Refusal> {
365 let outcome = match action {
366 "start" => start(state, &actor, &req).await,
367 "stop" => stop(state, &actor, &req).await,
368 "delete" => delete(state, &actor, &req).await,
369 _ => detach(state, &req).await,
370 };
371 let audit_action = format!("agent.{action}");
372 match outcome {
373 Ok(mut body) => {
374 let block_id = body["block_id"].as_str().unwrap_or_default().to_string();
375 let target = body["agent_id"].as_str().unwrap_or_default().to_string();
376 let note = body["note"].as_str().unwrap_or_default().to_string();
377 body["audit_id"] = json!(audit(state, &actor, &audit_action, &target, &block_id, true, None, ¬e));
378 Ok(body)
379 }
380 Err(refusal) => {
381 audit(state, &actor, &audit_action, req.agent.trim(), "", false, Some(&refusal.message), "refused");
382 Err(refusal)
383 }
384 }
385}
386
387async fn answer(state: AppState, caller: Option<Extension<Caller>>, action: &str, req: LifecycleRequest) -> Response {
388 let caller = caller.map(|Extension(c)| c);
389 match run(&state, caller.as_ref(), action, req).await {
390 Ok(body) => Json(body).into_response(),
391 Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
392 }
393}
394
395pub(crate) async fn handle_agent_start(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<LifecycleRequest>) -> Response {
396 answer(state, caller, "start", req).await
397}
398
399pub(crate) async fn handle_agent_stop(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<LifecycleRequest>) -> Response {
400 answer(state, caller, "stop", req).await
401}
402
403pub(crate) async fn handle_agent_detach(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<LifecycleRequest>) -> Response {
404 answer(state, caller, "detach", req).await
405}
406
407pub(crate) async fn handle_agent_delete(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<LifecycleRequest>) -> Response {
408 answer(state, caller, "delete", req).await
409}
410
411#[cfg(test)]
412#[path = "tests/agent_lifecycle_tests.rs"]
413mod tests;