Skip to main content

agentmux_srv/
main.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4mod bootstrap;
5mod config;
6mod headless;
7#[cfg(all(target_os = "linux", target_env = "gnu"))]
8mod malloc_arenas;
9mod proc_name;
10mod sagas;
11mod server;
12#[cfg(target_os = "windows")]
13mod srv_ipc;
14mod system_drive;
15mod drone;
16mod messaging;
17mod open_cli;
18#[cfg(windows)]
19mod crash_monitor;
20
21/// The system allocator with counters in front of it, so the `srv memory` log line can say how much
22/// of what the process has committed is in use (`backend::mem_census::alloc`).
23#[global_allocator]
24static ALLOCATOR: agentmux_srv_core::backend::mem_census::alloc::CountingAlloc = agentmux_srv_core::backend::mem_census::alloc::CountingAlloc;
25
26use agentmux_srv_core::{adoption, agents, ambient, backend, boot_timing, broker, connectivity, event_log, http_client, identity, migrations, muxbus, persist, persist_subscriber, reducer, registry, srv_info, state, util};
27use server::build_routers;
28
29#[cfg(test)]
30use agentmux_srv_core::test_support;
31
32#[cfg(test)]
33mod data_env_tests;
34// `agentmux status`'s copy of the presence rule, compiled here to be held to the server's.
35#[cfg(test)]
36#[allow(dead_code)]
37#[path = "agentmux_cli/reach.rs"]
38mod reach_cli;
39#[cfg(test)]
40mod reach_rule_tests;
41#[cfg(test)]
42mod tls_test_init;
43
44fn main() {
45    // Before anything is spawned or any thread exists: the launcher's secrets leave
46    // the environment, so no child inherits them and /proc/<pid>/environ shows none.
47    agentmux_common::secret_env::stash_startup_secrets();
48    agentmux_common::tls_provider::install_ring_provider(); // reqwest 0.13 builds no client without it
49    // A bare environment has no SystemDrive, and the Windows shell then makes a
50    // folder named "%SystemDrive%" in the current directory (#2524).
51    system_drive::ensure();
52    // Linux (glibc): cap malloc arenas before any thread exists, so the runtime's
53    // workers below share them (malloc_arenas.rs).
54    #[cfg(all(target_os = "linux", target_env = "gnu"))]
55    malloc_arenas::apply();
56    // What a bare `#[tokio::main]` expands to (tokio-macros 2.7: the multi-thread
57    // flavor, `enable_all`, no worker count, thread name or other setting, and the
58    // same panic message), built by hand so the call above runs first: the runtime
59    // starts its worker threads when it is built. This is on EVERY platform. The one
60    // addition is a note of which threads are the workers (`thread_roles`), which
61    // changes nothing about the runtime.
62    let runtime = tokio::runtime::Builder::new_multi_thread()
63        .enable_all()
64        .on_thread_start(backend::thread_roles::thread_started)
65        .build()
66        .expect("Failed building the Runtime");
67    backend::thread_roles::settle(runtime.metrics().num_workers());
68    runtime.block_on(app_main());
69}
70
71/// Runs the document-reading or file-icon child srv was started as, and exits; returns when
72/// this is an ordinary start.
73fn exit_if_helper_child() {
74    // -2. Document reading child: srv re-runs itself to parse one attached
75    //     document (PDF, Word, Excel, PowerPoint, ODF, RTF) out of process,
76    //     since parsers can crash, recurse or run long on hostile input and
77    //     the parent kills the child at its deadline
78    //     (SPEC_AGENT_PANE_FILE_ATTACHMENTS_2026_09_26.md §6). Nothing else
79    //     may start in this mode.
80    {
81        let args: Vec<String> = std::env::args().collect();
82        if args.get(1).map(String::as_str) == Some(backend::attachments::extract::CHILD_ARG) {
83            proc_name::set(proc_name::DOC_CHILD);
84            std::process::exit(backend::attachments::extract::run_child(&args[2..]));
85        }
86    }
87    // -2b. File icon child: srv re-runs itself to ask the operating system for a file type's
88    //      icon, since the shell loads third-party code that can hang or crash; the parent
89    //      kills it at its deadline (SPEC_FILES_SYSTEM_FILE_ICONS_2026_10_27.md §4.2).
90    {
91        let args: Vec<String> = std::env::args().collect();
92        if args.get(1).map(String::as_str) == Some(backend::file_icons::CHILD_ARG) {
93            proc_name::set(proc_name::ICON_CHILD);
94            std::process::exit(backend::file_icons::child::run_child());
95        }
96    }
97}
98
99/// Prepares the process for headless or launcher-owned running; true when headless.
100fn prepare_process_mode() -> bool {
101    let headless = headless::requested();
102    backend::startup_mode::set_headless(headless);
103    agentmux_common::process_hardening::deny_memory_access(headless);
104    if headless {
105        match headless::prepare_env() {
106            Ok(Some(key_file)) => eprintln!("agentmux-srv --headless: auth key written to {}", key_file.display()),
107            Ok(None) => {}
108            Err(e) => {
109                eprintln!("agentmux-srv --headless: {e}");
110                std::process::exit(1);
111            }
112        }
113    } else {
114        bootstrap::install_process_watchers();
115        // An isolated test or dev instance never touches the person's keychain.
116        if let Err(e) = crate::identity::secret_store::isolate_for_home_override() {
117            eprintln!("agentmux-srv: {e}");
118            std::process::exit(1);
119        }
120    }
121    headless
122}
123
124async fn app_main() {
125    exit_if_helper_child();
126    // `agentmux-srv open` is a client of a running headless srv: it starts nothing of srv's own.
127    open_cli::exit_if_requested().await;
128    server::streamed_browser::exit_if_browser_host().await; // --streamed-browser-host: one person's browser, nothing else
129    // -1. Crash monitor branch — must be checked before any other initialization.
130    if bootstrap::maybe_run_crash_monitor() {
131        return;
132    }
133    // Linux: a stable name for ps/top instead of the versioned file name's
134    // first 15 bytes. This runs on the main thread (tokio's block_on).
135    proc_name::set(proc_name::MAIN);
136
137    // Before anything changes the environment (srv_info.rs).
138    srv_info::capture_home_dir();
139
140    // 0. Headless (no launcher/host): prepare the env the launcher would have
141    //    provided, and don't tie srv's life to a parent or stdin. Otherwise start
142    //    the parent process watcher BEFORE tokio runtime does real work
143    //    (Linux/macOS only). docs/specs/SPEC_SRV_HEADLESS_MODE_2026_09_26.md.
144    let headless = prepare_process_mode();
145
146    // 0b. Attach out-of-process crash dump handler (Windows only).
147    //     _crash_guard must stay alive — dropping it uninstalls the VEH handler.
148    #[cfg(windows)]
149    let _crash_guard = bootstrap::install_crash_guard();
150
151    // 0c. Anchor the uptime clock before anything else can take time. Must be
152    //     neither a wall-clock stamp (moves backwards on a clock step) nor an
153    //     `Instant` (stops while suspended) — see `suspend_aware_now_ms` in
154    //     `backend::sysinfo` for both bugs and the per-platform sources.
155    backend::sysinfo::mark_process_start();
156
157    // 1. Init tracing (stderr + rolling file)
158    let _log_guard = bootstrap::init_logging();
159    // The external host key registered by `prepare_process_mode`, if any: its fingerprint, now that there is a log to say it in.
160    server::external_host::log_registered();
161
162    // 1'. Count every panic from here on (`backend::panic_watch`): the log keeps its lines, and the status bar, `/health` and the
163    //     agents hear of a storm (2026-11-15: 30,000 panics in two hours, and nothing said so).
164    backend::panic_watch::install_hook();
165
166    // 1a'. What the machine's certificates allow: with none, https requests fail and the log says so here, once
167    //      (http_client.rs); the server starts and runs either way.
168    http_client::no_system_certs();
169
170    // 1a. Start the boot-path stopwatch. Logged as one summary line at
171    //     ESTART below — see `boot_timing`'s module doc for why these numbers
172    //     go to the log rather than the splash.
173    boot_timing::init();
174
175    // 1b. Direct-launch PATH fallback.
176    bootstrap::enrich_path();
177
178    // 2. Parse CLI args and build config (dispatches `migrate` subcommand internally).
179    let config = bootstrap::load_config();
180    let version = config.version.to_string();
181    let build_time = config.build_time.to_string();
182
183    let (stores, bg) = bootstrap::open_stores_and_background(&config, &version, &build_time);
184
185    // 5. Bind TCP listeners, bring up LAN discovery / LSP supervisor / process tracker.
186    let net = boot_timing::time_async(
187        "bind_listeners_and_network",
188        bootstrap::bind_listeners_and_network(&config, &bg.event_bus, &bg.broker, &version),
189    )
190    .await;
191
192    // Phase E.2 — srv reducer plumbing (state, event bus, event log, persist subscriber).
193    let reducer = bootstrap::spawn_reducer_plumbing(&stores.mstore, &bg.event_bus, &bg.subagent_watcher).await;
194
195    let state = bootstrap::build_app_state(&config, version.clone(), stores, bg, &net, &reducer);
196
197    bootstrap::install_state_hooks(&state);
198    bootstrap::start_job_ledger_and_cron(&state).await;
199    bootstrap::resume_unresolved_sagas(&state).await;
200    bootstrap::announce_ready(&state, &net, &reducer, &config, &version, &build_time);
201
202    let viewer_router = server::build_viewer_router(state.clone());
203    bootstrap::spawn_state_services(&state);
204    bootstrap::publish_instance_record(&state);
205    // A headless srv that serves its own UI signs a browser in on its web port.
206    server::local_session_routes::enable(net.web_addr.port(), &config.instance_id);
207    let routers = build_routers(state.clone());
208    backend::container::listener::set_router(routers.container);
209    let router = routers.full;
210
211    bootstrap::attach_listeners(&state, &net, routers.lan, viewer_router);
212
213    // 8 & 9. Spawn stdin watch thread + SIGINT/SIGTERM handler (graceful shutdown).
214    let stdin_token = bootstrap::install_shutdown_handlers(!headless);
215    // `agentmux stop` has no signal to send on Windows: it asks over the signed channel, which ends the server by this token.
216    server::local_session_routes::set_shutdown(stdin_token.clone());
217
218    bootstrap::spawn_serving_loops(&state, &stdin_token);
219
220    bootstrap::serve_until_shutdown(net.web_listener, net.ws_listener, router, &stdin_token).await;
221
222    bootstrap::shut_down(&state, &net.lan_discovery).await;
223}
224
225// This test binary must hold this checkout's code, not another clone's from
226// a shared target directory (`agentmux_common::checkout`).
227#[cfg(test)]
228agentmux_common::checkout_guard!(agentmux_remote::CHECKOUT_DIR, agentmux_procstats::CHECKOUT_DIR);