Skip to main content

agentmux_srv/server/app_api/
agent_lifecycle.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents start`, `stop`, `detach` and `delete` (`POST /api/v1/agent/{start,stop,detach,delete}`): an agent runs, stops,
5//! leaves its pane or is deleted without the operator's window (a stop of another agent keeps its override window)
6//! (docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md ยง5.1). Each acts as the agent its token
7//! names; a request without one is refused, so a change is never attributed to the operator, and
8//! each one, and each refusal, is recorded in the audit log under the calling agent.
9//!
10//! - start: `agent_attach::start_agent`, the one start path (admission, the spawn gate and the lease
11//!   apply), after the per-sender start limit (`start_rate`). Running already is not a start.
12//! - stop: `agent_teardown::stop`, which also records the agent as wanted stopped. Not your own
13//!   agent: `Stop` `self` is the way to end yourself. Another agent's stop waits for the person's
14//!   30 s override window, like `Stop agents` (`fleet_stop_keep_pane_with_override`); a worker the
15//!   caller opened is stopped at once.
16//! - detach: the agent's pane closes and its block is parked, whatever `agents:always_available`
17//!   says (the setting decides what closing a pane does; this is the explicit action).
18//! - delete: only an agent the caller made (`Agents create`, or a worker it spawned), only when it is stopped
19//!   and has no open pane, never the caller itself; the same deletion the window's Delete does.
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 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    /// The agent's id, slug or name.
35    pub(super) agent: String,
36}
37
38impl LifecycleRequest {
39    /// A request naming the agent `agent` (an id, slug or name).
40    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/// The agent making the request.
55#[derive(Clone)]
56pub(super) struct Actor {
57    uid: String,
58    slug: String,
59    /// A person at this computer acting through the agent named here (the moved agent's leader, or the agent itself when
60    /// it has none): the agent whose key signs what is sent on, never the one who asked. A person is not the agent, so the
61    /// agent-only refusals ("not yourself", "only your leader") do not apply to them.
62    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    /// Whether a person at this computer asked, acting through this agent.
75    pub(super) fn is_person(&self) -> bool {
76        self.person
77    }
78
79    /// An agent on another machine (`slug@machine`), by the same name `run_remote` records.
80    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
100/// Who acts: the calling agent, or, for a request that carries no agent token (the person at the UI), that person acting through
101/// the agent named: its leader, or the agent itself when it has none (the agent whose key signs what is sent to another computer).
102/// A person must name the agent.
103pub(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
116/// The agent named, as its runtime row: an id, slug or name of an agent created on this machine.
117/// A template is not an agent.
118pub(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
131/// Whether a start has nothing to do. A turn in flight is a process, whatever was recorded. In the states
132/// that do not say (idle, and limited or signed out, which show over an ended process) the explicit
133/// stop settles it: a subprocess agent that was stopped reads `idle` because its process exits between
134/// turns, and a stop is not undone until a start or a message sets it running again.
135pub(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
145/// Whether a stop has anything to stop: any state with a process may be one, so the teardown decides,
146/// not the recorded intent (a message to a stopped agent can run it again without clearing that).
147pub(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
159/// What the answer says about the agent now: its state (re-read after the change).
160pub(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    // Running already is not a start: it costs nothing, so it does not use the sender's minute.
175    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
192/// Whether `caller` stopping `target` waits for the person's override window: always, except for
193/// itself and for a worker it opened (`agent_spawn::worker_of`).
194pub(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    // Another agent's stop waits for its user's override window; the agent's own worker is the
218    // leader's to end.
219    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    // Detach parks or it does nothing: a block that cannot be parked is left running, never closed.
263    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    // This agent's block alone: a pane that stacks other tabs keeps them.
270    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    // Parked means the agent's block exists, in no tab. Anything else is not a detach, whatever the saga said.
275    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
289/// `delete`: the agent definition goes, with its container storage. Only for the agent that made it, and only once it
290/// is stopped and shows no pane: a running agent is stopped first (`Agents stop`), which for another agent's
291/// agent is the person's call.
292async 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    // Read before the definition goes: the folder is named by it.
319    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
326/// The folder an agent worked in, when it is on this machine. A delete leaves it: it may hold work that
327/// was never pushed, and deleting an agent is not a reason to lose it. (A new agent made with the same name
328/// gets this folder again, clone and all, unless its owner removes it first.)
329fn kept_workspace(def: &crate::backend::storage::AgentDefinition) -> Option<std::path::PathBuf> {
330    // Where the agent was launched, by the launch path's own rule (a blank folder is named from the agent's name).
331    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
335/// `Agents delete`'s answer: what went, and that the workspace folder did not (with where it is).
336fn 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
356/// `start` or `stop` of `agent` for an agent on another machine (`remote_ops::agent_ops`): the same
357/// code a local call runs, with `who` (`slug@machine`) as the actor. Such a caller owns no worker here,
358/// so a stop of another agent always waits for the person's override window.
359pub(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, &note));
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;