Skip to main content

agentmux_srv/server/
host_control.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! What a headless server's registered external host asks of srv besides
5//! vouching for a connection: whether the workspace is in use, a graceful shutdown, and the notice that it
6//! is going to stop.
7//!
8//! These are host routes, never RPCs: an RPC is a command an agent can call, and these must not be. Every
9//! agent on the machine holds the instance key, so the key does not open them. Each call is signed by the
10//! registered host (`external_host::Host::check_call`), for this workspace, over its operation and
11//! arguments, and answers 404 when no host is registered, so a desktop or a plain headless srv has none of
12//! these routes.
13//!
14//! - `POST /api/v1/host/activity`: `{ busy, agentsWorking, lastOutputAt, keepRunning }`; `keepRunning` is the last
15//!   thing an agent asked for (`app_api::workspace_stop`), for the host to honour or not. A turn counts only while its pane
16//!   has written output in the last ten minutes (`ACTIVE_WINDOW_MS`), so a hung turn cannot keep a workspace
17//!   up for ever; a pane process that wrote that recently counts as busy too.
18//! - `POST /api/v1/host/shutdown`: srv's own graceful teardown (the one SIGTERM runs: interrupt turns, save
19//!   final state) and the answer when it is done, within the deadline given.
20//! - `POST /api/v1/host/notice`: the stop time and why, as the fixed reason ids `person`, `timer`, `credit`
21//!   and `cap`, never text: srv builds the phrase the page and the agents are shown, so nothing a person or an
22//!   agent wrote can cross. `stopAt` and `reason` both null cancel it.
23
24use std::sync::Mutex;
25use std::time::Duration;
26
27use axum::extract::State;
28use axum::http::StatusCode;
29use axum::response::{IntoResponse, Response};
30use axum::Json;
31use serde::Deserialize;
32use serde_json::json;
33
34use super::external_host::{host, Refusal};
35use super::AppState;
36use crate::backend::blockcontroller::{get_all_controllers, shell::ShellController, STATUS_RUNNING};
37use crate::backend::shutdown_events::WorkspaceStopView;
38
39/// A turn or a pane process counts as working only if it wrote output this recently.
40pub(crate) const ACTIVE_WINDOW_MS: i64 = 10 * 60 * 1000;
41/// The longest graceful shutdown a caller may ask for.
42const MAX_DEADLINE_SECS: u64 = 120;
43/// The furthest ahead a stop may be set.
44const MAX_AHEAD_MS: u64 = 7 * 24 * 60 * 60 * 1000;
45/// How far in the past a stop time may be before it is refused (clock skew between host and srv).
46const SKEW_MS: u64 = 60 * 1000;
47/// The held-note key: a newer stop notice replaces an older one still waiting for an agent's next turn.
48const NOTE_KEY: &str = "workspace-stop";
49/// The last reminder to the agents, this long before the stop.
50const REMIND_BEFORE_MS: u64 = 60 * 1000;
51
52fn current_ms() -> u64 {
53    agentmux_common::time::now_ms_u64()
54}
55
56fn refused((status, error): Refusal) -> Response {
57    (status, Json(json!({ "ok": false, "error": error }))).into_response()
58}
59
60/// What one pane's controller says, for the activity answer.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub(crate) struct Seen {
63    pub turn_active: bool,
64    pub last_output_ms: Option<i64>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub(crate) struct Activity {
69    pub busy: bool,
70    pub agents_working: usize,
71    pub last_output_at: Option<i64>,
72}
73
74/// The workspace's activity from its running panes. A turn that has been silent for `ACTIVE_WINDOW_MS` is not
75/// working (the guard against a stuck turn); a pane that wrote output within it is busy even with no turn.
76pub(crate) fn summarize(running: &[Seen], now_ms: i64) -> Activity {
77    let recent = |s: &Seen| s.last_output_ms.is_some_and(|t| now_ms - t <= ACTIVE_WINDOW_MS);
78    let agents_working = running.iter().filter(|s| s.turn_active && recent(s)).count();
79    Activity {
80        busy: agents_working > 0 || running.iter().any(recent),
81        agents_working,
82        last_output_at: running.iter().filter_map(|s| s.last_output_ms).max(),
83    }
84}
85
86fn running_panes(now_ms: i64) -> Vec<Seen> {
87    get_all_controllers()
88        .values()
89        .filter_map(|ctrl| {
90            let status = ctrl.get_runtime_status();
91            if status.shellprocstatus != STATUS_RUNNING {
92                return None;
93            }
94            let last_output_ms = match ctrl.as_any().downcast_ref::<ShellController>() {
95                Some(shell) => shell.last_output_secs_ago().map(|secs| now_ms - secs as i64 * 1000),
96                None => ctrl.last_output_ms(),
97            };
98            Some(Seen { turn_active: status.turn_active, last_output_ms })
99        })
100        .collect()
101}
102
103#[derive(Debug, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub(crate) struct ActivityRequest {
106    v: u32,
107    workspace: String,
108    issued_at: u64,
109    sig: String,
110}
111
112/// `POST /api/v1/host/activity`.
113pub(crate) async fn handle_activity(Json(req): Json<ActivityRequest>) -> Response {
114    let Some(host) = host() else { return not_registered() };
115    if req.v != 1 {
116        return refused((StatusCode::BAD_REQUEST, "unsupported version"));
117    }
118    if let Err(r) = host.check_call("activity", &req.workspace, req.issued_at, "", &req.sig, agentmux_common::time::now_secs_u64()) {
119        return refused(r);
120    }
121    let now = current_ms() as i64;
122    let a = summarize(&running_panes(now), now);
123    let keep = current().1.map(|k| json!({ "minutes": k.minutes, "by": k.by, "atMs": k.at_ms }));
124    Json(json!({ "ok": true, "busy": a.busy, "agentsWorking": a.agents_working, "lastOutputAt": a.last_output_at, "keepRunning": keep })).into_response()
125}
126
127#[derive(Debug, Deserialize)]
128#[serde(rename_all = "camelCase")]
129pub(crate) struct ShutdownRequest {
130    v: u32,
131    workspace: String,
132    issued_at: u64,
133    deadline_seconds: u64,
134    sig: String,
135}
136
137/// `POST /api/v1/host/shutdown`: srv's graceful teardown, and the answer once it is done (`done: false` when the
138/// deadline came first, with the teardown still running). Calling it again is harmless: what is closed is gone.
139pub(crate) async fn handle_shutdown(State(state): State<AppState>, Json(req): Json<ShutdownRequest>) -> Response {
140    let Some(host) = host() else { return not_registered() };
141    if req.v != 1 || !(1..=MAX_DEADLINE_SECS).contains(&req.deadline_seconds) {
142        return refused((StatusCode::BAD_REQUEST, "a field is not valid"));
143    }
144    let args = req.deadline_seconds.to_string();
145    if let Err(r) = host.check_call("shutdown", &req.workspace, req.issued_at, &args, &req.sig, agentmux_common::time::now_secs_u64()) {
146        return refused(r);
147    }
148    tracing::info!(deadline_seconds = req.deadline_seconds, "the external host asked for a graceful shutdown");
149    // The teardown runs in a task of its own, so a deadline that passes first leaves it running (dropping the future
150    // would cancel it at its next await and lose the state it has yet to record): only the wait for it is cut short.
151    let mut teardown = tokio::spawn({
152        let state = state.clone();
153        async move { crate::sagas::agent_teardown::app_exit(&state).await }
154    });
155    match tokio::time::timeout(Duration::from_secs(req.deadline_seconds), &mut teardown).await {
156        Ok(Ok(closed)) => Json(json!({ "ok": true, "done": true, "closed": closed })).into_response(),
157        Ok(Err(e)) => {
158            tracing::warn!("the graceful shutdown task ended abnormally: {e}");
159            refused((StatusCode::INTERNAL_SERVER_ERROR, "the shutdown did not complete"))
160        }
161        Err(_) => Json(json!({ "ok": true, "done": false })).into_response(),
162    }
163}
164
165/// Why a workspace is going to stop: the only reasons srv will say, as ids.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub(crate) enum Reason {
168    Person,
169    Timer { idle_minutes: u32 },
170    Credit,
171    Cap,
172}
173
174impl Reason {
175    pub(crate) fn id(self) -> &'static str {
176        match self {
177            Reason::Person => "person",
178            Reason::Timer { .. } => "timer",
179            Reason::Credit => "credit",
180            Reason::Cap => "cap",
181        }
182    }
183
184    /// The reason as a person and an agent are told it.
185    pub(crate) fn phrase(self) -> String {
186        match self {
187            Reason::Person => "you asked".to_string(),
188            Reason::Timer { idle_minutes } => format!("nothing has happened for {idle_minutes} minutes"),
189            Reason::Credit => "your credit ran out".to_string(),
190            Reason::Cap => "a daily cap was reached".to_string(),
191        }
192    }
193}
194
195/// A notice as srv holds it: the stop time and why.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub(crate) struct Stop {
198    pub at_ms: u64,
199    pub reason: Reason,
200}
201
202/// What the host sent, checked: a stop, or its cancelling.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub(crate) enum Notice {
205    Set(Stop),
206    Clear,
207}
208
209/// The notice in a request, or why it is refused. A stop needs both a time and a reason id; neither cancels.
210/// `idleMinutes` goes with `timer` and with nothing else.
211pub(crate) fn parse_notice(stop_at: Option<u64>, reason: Option<&str>, idle_minutes: Option<u32>, now_ms: u64) -> Result<Notice, &'static str> {
212    let (Some(at_ms), Some(reason)) = (stop_at, reason) else {
213        return match (stop_at, reason, idle_minutes) {
214            (None, None, None) => Ok(Notice::Clear),
215            _ => Err("a stop needs both a time and a reason"),
216        };
217    };
218    if at_ms.saturating_add(SKEW_MS) < now_ms || at_ms > now_ms.saturating_add(MAX_AHEAD_MS) {
219        return Err("the stop time is not within a week ahead");
220    }
221    let reason = match (reason, idle_minutes) {
222        ("timer", Some(m)) if (1..=1440).contains(&m) => Reason::Timer { idle_minutes: m },
223        ("timer", _) => return Err("a timer stop needs idleMinutes between 1 and 1440"),
224        (_, Some(_)) => return Err("idleMinutes goes only with a timer stop"),
225        ("person", None) => Reason::Person,
226        ("credit", None) => Reason::Credit,
227        ("cap", None) => Reason::Cap,
228        _ => return Err("the reason is not one of person, timer, credit, cap"),
229    };
230    Ok(Notice::Set(Stop { at_ms, reason }))
231}
232
233/// What to do with a notice, given the one held.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub(crate) enum Plan {
236    /// The same as held (or nothing to cancel): nothing is said again.
237    Nothing,
238    Announce(Stop),
239    Cancel,
240}
241
242pub(crate) fn plan(held: Option<Stop>, notice: Notice) -> Plan {
243    match (held, notice) {
244        (Some(h), Notice::Set(s)) if h == s => Plan::Nothing,
245        (_, Notice::Set(s)) => Plan::Announce(s),
246        (Some(_), Notice::Clear) => Plan::Cancel,
247        (None, Notice::Clear) => Plan::Nothing,
248    }
249}
250
251/// `HH:MM UTC` of a unix-ms time.
252pub(crate) fn clock(at_ms: u64) -> String {
253    let secs = at_ms / 1000;
254    format!("{:02}:{:02} UTC", (secs / 3600) % 24, (secs / 60) % 60)
255}
256
257/// The note every agent is given when a stop is set.
258pub(crate) fn stop_note(stop: Stop) -> String {
259    format!("This workspace stops at {} because {}. Your conversation is saved.", clock(stop.at_ms), stop.reason.phrase())
260}
261
262/// The last reminder, sent a minute before.
263pub(crate) fn remind_note(stop: Stop) -> String {
264    format!("This workspace stops in about a minute, at {}, because {}. Your conversation is saved.", clock(stop.at_ms), stop.reason.phrase())
265}
266
267/// The note when a stop is cancelled.
268pub(crate) const CANCEL_NOTE: &str = "The workspace's stop was cancelled; it keeps running.";
269
270/// What an agent has asked for: the stop pushed back by `minutes`, recorded as the agent that asked.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub(crate) struct KeepRunning {
273    pub minutes: u32,
274    pub by: String,
275    pub at_ms: u64,
276}
277
278/// The most an agent may ask to push a stop back at a time.
279pub(crate) const MAX_KEEP_MINUTES: u32 = 240;
280
281/// Why a keep-running request was refused.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub(crate) enum KeepRefusal {
284    Minutes,
285    NoStop,
286}
287
288impl KeepRefusal {
289    pub(crate) fn message(self) -> &'static str {
290        match self {
291            KeepRefusal::Minutes => "minutes is a whole number from 1 to 240",
292            KeepRefusal::NoStop => "the workspace has no stop pending, so there is nothing to put back",
293        }
294    }
295}
296
297/// The notice srv holds, what an agent has asked for since, and a counter that tells a reminder task whether
298/// it is still the current one.
299#[derive(Debug, Default)]
300pub(crate) struct Held {
301    stop: Option<Stop>,
302    keep: Option<KeepRunning>,
303    generation: u64,
304}
305
306impl Held {
307    /// Take a notice in. `None` when there was nothing to do (the same stop again, or a cancel with none held). A
308    /// changed or cancelled stop ends what an agent asked of the one before: its answer is the timer's to give again.
309    fn take(&mut self, notice: Notice) -> Option<(Plan, u64)> {
310        let what = plan(self.stop, notice);
311        match what {
312            Plan::Nothing => return None,
313            Plan::Announce(s) => self.stop = Some(s),
314            Plan::Cancel => self.stop = None,
315        }
316        self.keep = None;
317        self.generation += 1;
318        Some((what, self.generation))
319    }
320
321    /// An agent asks for the stop to be pushed back: only while one is pending, and by 1 to 240 minutes. srv records
322    /// the request and tells the host with its next activity answer; whether to honour it is the host's.
323    pub(crate) fn ask_keep_running(&mut self, minutes: u32, by: &str, at_ms: u64) -> Result<KeepRunning, KeepRefusal> {
324        if !(1..=MAX_KEEP_MINUTES).contains(&minutes) {
325            return Err(KeepRefusal::Minutes);
326        }
327        if self.stop.is_none() {
328            return Err(KeepRefusal::NoStop);
329        }
330        let keep = KeepRunning { minutes, by: by.to_string(), at_ms };
331        self.keep = Some(keep.clone());
332        Ok(keep)
333    }
334}
335
336static HELD: Mutex<Held> = Mutex::new(Held { stop: None, keep: None, generation: 0 });
337
338fn held() -> std::sync::MutexGuard<'static, Held> {
339    HELD.lock().unwrap_or_else(|e| e.into_inner())
340}
341
342/// The stop srv holds now, and what an agent has asked for since.
343pub(crate) fn current() -> (Option<Stop>, Option<KeepRunning>) {
344    let h = held();
345    (h.stop, h.keep.clone())
346}
347
348/// An agent asks to push the stop back (`Held::ask_keep_running`).
349pub(crate) fn ask_keep_running(minutes: u32, by: &str) -> Result<KeepRunning, KeepRefusal> {
350    held().ask_keep_running(minutes, by, current_ms())
351}
352
353#[derive(Debug, Deserialize)]
354#[serde(rename_all = "camelCase")]
355pub(crate) struct NoticeRequest {
356    v: u32,
357    workspace: String,
358    issued_at: u64,
359    stop_at: Option<u64>,
360    reason: Option<String>,
361    idle_minutes: Option<u32>,
362    sig: String,
363}
364
365fn text_of(v: Option<impl ToString>) -> String {
366    v.map_or_else(|| "-".to_string(), |x| x.to_string())
367}
368
369fn tell_agents(state: &AppState, text: &str) {
370    for agent in crate::backend::reactive::get_global_handler().list_agents() {
371        if let Err(e) = state.reactive_handler.hold_system_note(&agent.agent_id, NOTE_KEY, text) {
372            tracing::debug!(agent = %agent.agent_id, "workspace stop note not held: {e}");
373        }
374    }
375}
376
377fn publish(state: &AppState, view: &WorkspaceStopView) {
378    state.broker.publish_event::<crate::backend::mps_events::WorkspaceStop>(view, vec![], 1);
379}
380
381/// `POST /api/v1/host/notice`.
382pub(crate) async fn handle_notice(State(state): State<AppState>, Json(req): Json<NoticeRequest>) -> Response {
383    let Some(host) = host() else { return not_registered() };
384    if req.v != 1 {
385        return refused((StatusCode::BAD_REQUEST, "unsupported version"));
386    }
387    // Signed as `<stopAt>,<reason>,<idleMinutes>`, `-` for a null (a cancel is `-,-,-`).
388    let args = format!("{},{},{}", text_of(req.stop_at), text_of(req.reason.as_deref()), text_of(req.idle_minutes));
389    if let Err(r) = host.check_call("notice", &req.workspace, req.issued_at, &args, &req.sig, agentmux_common::time::now_secs_u64()) {
390        return refused(r);
391    }
392    let notice = match parse_notice(req.stop_at, req.reason.as_deref(), req.idle_minutes, current_ms()) {
393        Ok(n) => n,
394        Err(why) => return refused((StatusCode::BAD_REQUEST, why)),
395    };
396    apply(&state, notice);
397    Json(json!({ "ok": true })).into_response()
398}
399
400/// Hold the notice, show it, tell the agents, and remind them a minute before; or take it back.
401fn apply(state: &AppState, notice: Notice) {
402    let Some((what, generation)) = held().take(notice) else { return };
403    match what {
404        Plan::Announce(stop) => {
405            tracing::info!(reason = stop.reason.id(), stop_at_ms = stop.at_ms, "the external host set a workspace stop");
406            publish(state, &WorkspaceStopView { status: "pending", stop_at_ms: stop.at_ms as i64, reason_id: stop.reason.id().to_string(), reason: stop.reason.phrase() });
407            tell_agents(state, &stop_note(stop));
408            remind_later(state.clone(), stop, generation);
409        }
410        Plan::Cancel => {
411            tracing::info!("the external host cancelled the workspace stop");
412            publish(state, &WorkspaceStopView { status: "cleared", stop_at_ms: 0, reason_id: String::new(), reason: String::new() });
413            tell_agents(state, CANCEL_NOTE);
414        }
415        Plan::Nothing => {}
416    }
417}
418
419/// A minute before the stop, if it is still the stop that is held, the agents are reminded.
420fn remind_later(state: AppState, stop: Stop, generation: u64) {
421    let wait = stop.at_ms.saturating_sub(REMIND_BEFORE_MS).saturating_sub(current_ms());
422    if wait == 0 {
423        return;
424    }
425    tokio::spawn(async move {
426        tokio::time::sleep(Duration::from_millis(wait)).await;
427        if held().generation == generation {
428            tell_agents(&state, &remind_note(stop));
429        }
430    });
431}
432
433fn not_registered() -> Response {
434    refused((StatusCode::NOT_FOUND, "no external host is registered"))
435}
436
437#[cfg(test)]
438#[path = "host_control_tests.rs"]
439mod tests;