Skip to main content

agentmux_launcher/supervisor/
mod.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Platform host-supervision loops. The Windows and Unix supervisors are
5//! fully `#[cfg]`-gated in separate files; only the flow spine
6//! (`launcher_main`) lives at the crate root.
7
8/// Phase 1 host supervision (spec
9/// `docs/specs/SPEC_SERVICE_SUPERVISION_AND_RECOVERY_2026_05_20.md`): on an
10/// abnormal host exit the launcher relaunches the host, but at most
11/// `HOST_RESTART_BUDGET` times within `HOST_RESTART_WINDOW` — a crash budget
12/// so a deterministic crash cannot spin forever (spec §10-A). Shared by
13/// the Windows (`run_windows`) and Unix (`run_unix`) supervisors.
14pub(crate) const HOST_RESTART_BUDGET: usize = 3;
15pub(crate) const HOST_RESTART_WINDOW: std::time::Duration = std::time::Duration::from_secs(60);
16
17/// SPEC_SRV_SUPERVISION_RECYCLE_2026_07_11 (#942 Phase 2) — srv gets its
18/// own crash budget: an unexpected srv exit respawns srv and recycles the
19/// host through the existing supervised-restart path (crash-reproject
20/// restores the session), at most this many times per window. A wider
21/// window than the host's: each srv recycle also costs a host restart, so
22/// a crash-looping srv burns both budgets and gives up loudly either way.
23pub(crate) const SRV_RESTART_BUDGET: usize = 3;
24pub(crate) const SRV_RESTART_WINDOW: std::time::Duration = std::time::Duration::from_secs(120);
25
26/// Whether this abnormal host exit repeats the previous one closely enough to
27/// be the same fault twice in a row — what the retry ladder answers with
28/// `--disable-gpu` (issue #3666).
29///
30/// A manual kill of a hung host also exits with code 1 (`TerminateProcess`,
31/// `taskkill /F`), so the code alone pairs two unrelated kills and the degraded
32/// relaunch sticks for the rest of the launcher's life. Two things pair an exit
33/// instead:
34///   - a Windows fault code (an NTSTATUS exception, negative as `i32`): a real
35///     crash that repeats is deterministic however long the host ran between;
36///   - the same code as an exit within [`HOST_RESTART_WINDOW`] of the previous
37///     one: a crash soon after a relaunch, which is the case software rendering
38///     actually helps. A host that ran for minutes and was then killed is
39///     neither, so it degrades nothing.
40pub(crate) fn repeats_crash(last: Option<(i32, std::time::Instant)>, code: i32, now: std::time::Instant) -> bool {
41    match last {
42        Some((last_code, at)) => last_code == code && (is_fault_code(code) || now.saturating_duration_since(at) < HOST_RESTART_WINDOW),
43        None => false,
44    }
45}
46
47/// Whether a host exit is the one that says "the browser sandbox is blocked by system policy and nobody can answer
48/// the dialog" (`agentmux_common::process::HOST_EXIT_SANDBOX_UNAVAILABLE`, set by `agentmux-cef` for a start made
49/// from an agent's environment). The same stop would come again at every relaunch, so the supervisor ends with
50/// that code at once instead of spending its crash budget on it.
51#[cfg_attr(not(unix), allow(dead_code))]
52pub(crate) fn is_sandbox_unavailable_exit(code: i32) -> bool {
53    code == agentmux_common::process::HOST_EXIT_SANDBOX_UNAVAILABLE
54}
55
56/// The log line for a host exit that ends the launcher without a relaunch: a clean exit, or the stop for a blocked
57/// sandbox (#610), which says why where the person or agent reading this log looks.
58#[cfg_attr(not(unix), allow(dead_code))]
59pub(crate) fn final_host_exit_line(code: i32) -> String {
60    if is_sandbox_unavailable_exit(code) {
61        format!(
62            "CEF host stopped at start-up (code {code}): the browser sandbox is blocked by system policy and this start came \
63             from an agent's environment, so nobody can answer the dialog. Not relaunching. The host's stderr says why; \
64             AGENTMUX_UNSAFE_NOSANDBOX=1 is the explicit opt-out (docs/linux.md)."
65        )
66    } else {
67        format!("CEF host exited cleanly (code {code}) — shutting down")
68    }
69}
70
71/// `STATUS_CONTROL_C_EXIT`: the console interrupted the process (Ctrl+C or a
72/// close) — a shutdown, not a fault, whatever its NTSTATUS-looking value.
73const STATUS_CONTROL_C_EXIT: i32 = 0xC000_013A_u32 as i32;
74
75/// Whether an exit code is cast as a Windows fault: an NTSTATUS exception
76/// (negative as `i32`), except the console's own control-C exit.
77fn is_fault_code(code: i32) -> bool {
78    code < 0 && code != STATUS_CONTROL_C_EXIT
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use std::time::{Duration, Instant};
85
86    #[test]
87    fn the_final_exit_line_says_which_stop_it_is() {
88        assert_eq!(final_host_exit_line(0), "CEF host exited cleanly (code 0) — shutting down");
89        let l = final_host_exit_line(agentmux_common::process::HOST_EXIT_SANDBOX_UNAVAILABLE);
90        assert!(l.contains("code 78") && l.contains("Not relaunching") && l.contains("AGENTMUX_UNSAFE_NOSANDBOX=1"), "{l}");
91    }
92
93    #[test]
94    fn only_the_sandbox_unavailable_code_ends_the_launcher_without_a_relaunch() {
95        assert!(is_sandbox_unavailable_exit(agentmux_common::process::HOST_EXIT_SANDBOX_UNAVAILABLE));
96        for ordinary in [0, 1, 2, -1, 101] {
97            assert!(!is_sandbox_unavailable_exit(ordinary), "{ordinary} keeps the crash-budget relaunch");
98        }
99    }
100
101    #[test]
102    fn a_manual_kill_after_a_long_run_is_not_a_repeat_crash() {
103        let t0 = Instant::now();
104        assert!(!repeats_crash(Some((1, t0)), 1, t0 + Duration::from_secs(8 * 60)));
105    }
106
107    #[test]
108    fn two_startup_crashes_with_the_same_code_are_a_repeat_crash() {
109        let t0 = Instant::now();
110        assert!(repeats_crash(Some((1, t0)), 1, t0 + Duration::from_secs(5)));
111        assert!(!repeats_crash(Some((1, t0)), 2, t0 + Duration::from_secs(5)), "a different code is a different fault");
112        assert!(!repeats_crash(None, 1, t0), "the first crash has nothing to repeat");
113    }
114
115    #[test]
116    fn the_window_is_the_host_restart_window_and_it_is_exclusive() {
117        let t0 = Instant::now();
118        assert!(repeats_crash(Some((1, t0)), 1, t0 + HOST_RESTART_WINDOW - Duration::from_millis(1)));
119        assert!(!repeats_crash(Some((1, t0)), 1, t0 + HOST_RESTART_WINDOW), "exactly a window later is not a repeat");
120    }
121
122    #[test]
123    fn a_repeated_windows_fault_code_is_deterministic_however_long_between() {
124        // An NTSTATUS exception (0xC0000005 as i32) is a real crash, not a
125        // TerminateProcess(1) kill: it still steps the ladder down after a
126        // long run, as before.
127        let access_violation = 0xC0000005u32 as i32;
128        let t0 = Instant::now();
129        assert!(access_violation < 0, "precondition: the exception code is negative as i32");
130        assert!(repeats_crash(Some((access_violation, t0)), access_violation, t0 + Duration::from_secs(8 * 60)));
131        // A console interrupt is a shutdown, not a fault, even though its
132        // NTSTATUS value looks like one.
133        assert!(!repeats_crash(Some((STATUS_CONTROL_C_EXIT, t0)), STATUS_CONTROL_C_EXIT, t0 + Duration::from_secs(8 * 60)));
134    }
135}
136
137#[cfg(target_os = "windows")]
138mod windows;
139#[cfg(target_os = "windows")]
140pub(crate) use windows::run_windows;
141
142#[cfg(not(target_os = "windows"))]
143mod srv_exit;
144#[cfg(not(target_os = "windows"))]
145mod unix;
146#[cfg(not(target_os = "windows"))]
147pub(crate) use unix::run_unix;