Skip to main content

agentmux_srv/
config.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::path::PathBuf;
6
7use clap::{Parser, Subcommand};
8
9#[derive(Parser, Debug, Default)]
10#[command(name = "agentmux-srv", about = "AgentMux Rust backend server")]
11pub struct CliArgs {
12    /// Path to wave data directory (overrides AGENTMUX_DATA_HOME)
13    #[arg(long = "wavedata")]
14    pub wavedata: Option<PathBuf>,
15
16    /// Instance identifier (used for multi-version coexistence)
17    #[arg(long = "instance", default_value = "default")]
18    pub instance: String,
19
20    /// Run without a launcher or desktop host (container, server, CI).
21    /// Read early by `headless::prepare_env`; see
22    /// docs/specs/SPEC_SRV_HEADLESS_MODE_2026_09_26.md.
23    #[arg(long = "headless")]
24    pub headless: bool,
25
26    /// Headless: read the auth key from this file instead of generating one.
27    #[arg(long = "auth-key-file")]
28    pub auth_key_file: Option<PathBuf>,
29
30    /// Headless: fixed loopback port for the web listener (default: OS-chosen).
31    #[arg(long = "web-port")]
32    pub web_port: Option<u16>,
33
34    /// Headless: fixed loopback port for the websocket listener (default: OS-chosen).
35    #[arg(long = "ws-port")]
36    pub ws_port: Option<u16>,
37
38    /// Headless: serve the built frontend (a directory holding index.html)
39    /// at `/`; health stays at `/health`.
40    #[arg(long = "frontend-dir")]
41    pub frontend_dir: Option<PathBuf>,
42
43    /// Headless: also accept this browser origin (e.g. https://app.example.com)
44    /// for CORS and the /ws check, beside loopback. Repeatable. A launcher that
45    /// starts srv per run can give the one origin as `AGENTMUX_ALLOWED_ORIGIN`
46    /// instead (https, nothing else allowed); if both are given they must agree.
47    #[arg(long = "allowed-origin")]
48    pub allowed_origins: Vec<String>,
49
50    /// Headless: the key file of an external host whose attestations srv accepts (the person's window,
51    /// vouched for by a separate host process). Read once at boot; there is no way to register another
52    /// later. Without it srv accepts no external attestation.
53    #[arg(long = "external-host-key-file")]
54    pub external_host_key_file: Option<PathBuf>,
55
56    /// Headless, with `--frontend-dir`: the one origin a browser reaches the UI on when it is not
57    /// srv's own port, e.g. through `ssh -L 8080:127.0.0.1:7380`. Must be `http://127.0.0.1:<port>`.
58    #[arg(long = "public-origin")]
59    pub public_origin: Option<String>,
60
61    /// Headless: where srv keeps secrets (API keys, OAuth accounts, cloud
62    /// credentials). Default `file`: owner-only files under the shared dir,
63    /// for machines with no OS keychain.
64    #[arg(long = "secret-store", value_enum)]
65    pub secret_store: Option<SecretStoreKind>,
66
67    #[command(subcommand)]
68    pub command: Option<SrvCommand>,
69}
70
71/// `--secret-store`: see `identity::secret_store`.
72#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
73pub enum SecretStoreKind {
74    /// The OS keychain, as the desktop app uses.
75    Keychain,
76    /// Owner-only files, one per secret.
77    File,
78}
79
80#[derive(Subcommand, Debug)]
81pub enum SrvCommand {
82    /// Run pending data migrations and exit. Invoked by the launcher before
83    /// starting the daemon so the srv always starts with clean migrated state.
84    Migrate {
85        /// Print pending migrations without applying them.
86        #[arg(long)]
87        dry_run: bool,
88        /// List all migrations and their applied/pending status.
89        #[arg(long)]
90        list: bool,
91        /// Check every APPLIED migration post-condition (row counts, marker
92        /// files) instead of running anything. Exit 0 if every check holds or
93        /// is not verifiable, 3 if any is a mismatch or errored (2 is clap usage-error, so a typoed flag never reads as a data finding). This is the
94        /// doctor pass from SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03 Phase 1:
95        /// db_migrations only records that up() returned Ok, never that it
96        /// wrote what it was meant to.
97        #[arg(long)]
98        verify: bool,
99        /// Prepare this version's data for its first start, with srv stopped:
100        /// copy the previous version's data forward when this version has
101        /// none, back up, and run the pending migrations, each reported on
102        /// stderr for the splash. The upgrade step of
103        /// SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15 §10.
104        /// It writes, so it can't be combined with the read-only flags.
105        #[arg(long, conflicts_with_all = ["dry_run", "list", "verify"])]
106        prepare: bool,
107    },
108    /// Open a browser at a headless srv that serves its own UI (`--frontend-dir`): mint a one-time
109    /// code, open the browser at it, show the check phrase and ask whether it is the page you opened.
110    /// Run by the same user, in a terminal. SPEC_HEADLESS_SERVER_PACKAGE_AND_LOCAL_WEB_UI §3.
111    Open {
112        /// The server's web port (`--web-port`). By default `open` reads it from the file the server
113        /// writes beside its key file.
114        #[arg(long)]
115        port: Option<u16>,
116        /// The server's key file (default: `srv-auth-key` in its data folder).
117        #[arg(long, value_name = "FILE")]
118        key_file: Option<PathBuf>,
119        /// Print the one-time line for your own browser instead of opening one.
120        #[arg(long)]
121        print: bool,
122        /// The address the browser reaches the server on, when it is not `http://127.0.0.1:<port>`
123        /// (the other end of a tunnel; it must match the server's `--public-origin`).
124        #[arg(long)]
125        origin: Option<String>,
126    },
127    /// Disconnect every browser from a headless srv that serves its own UI. Proves the key to the
128    /// server the way `open` does, and sends nothing but that proof. Run by the same user.
129    Logout {
130        /// The server's web port (`--web-port`). By default read from the file the server writes
131        /// beside its key file.
132        #[arg(long)]
133        port: Option<u16>,
134        /// The server's key file (default: `srv-auth-key` in its data folder).
135        #[arg(long, value_name = "FILE")]
136        key_file: Option<PathBuf>,
137    },
138    /// Print how many browsers are open on a headless srv that serves its own UI: one number. Proves the
139    /// key to the server the way `open` does. Run by the same user; `agentmux status` shows it.
140    Sessions {
141        /// The server's web port (`--web-port`). By default read from the file the server writes
142        /// beside its key file.
143        #[arg(long)]
144        port: Option<u16>,
145        /// The server's key file (default: `srv-auth-key` in its data folder).
146        #[arg(long, value_name = "FILE")]
147        key_file: Option<PathBuf>,
148    },
149    /// Try the operating system's keychain the way the server would use it: store, read back and delete one test entry, waiting
150    /// a few seconds at most and showing no prompt. Prints one word (`works`, `absent`, `no-answer` or `failed`), then
151    /// optionally `: why`. Run by `agentmux setup` on Linux to choose between the keychain and owner-only files.
152    ProbeKeychain,
153    /// Ask a headless srv that serves its own UI to shut down, as a termination signal does (`agentmux stop` on
154    /// Windows, which has no such signal). Proves the key to the server the way `open` does. Run by the same user.
155    Shutdown {
156        /// The server's web port (`--web-port`). By default read from the file the server writes
157        /// beside its key file.
158        #[arg(long)]
159        port: Option<u16>,
160        /// The server's key file (default: `srv-auth-key` in its data folder).
161        #[arg(long, value_name = "FILE")]
162        key_file: Option<PathBuf>,
163    },
164    /// Give pre-fix forks the agent id `fork_slug` gives, keeping the old one
165    /// as a former slug (SPEC_FORK_SLUG_MIGRATION_2026_10_22.md §4 Phase 2).
166    /// With no flag, or `--plan`, prints what would change and changes nothing.
167    MigrateForkSlugs {
168        /// Print the plan (the default).
169        #[arg(long, conflicts_with_all = ["apply", "rollback", "restore"])]
170        plan: bool,
171        /// Migrate, or resume a run that stopped.
172        #[arg(long, conflicts_with_all = ["rollback", "restore"])]
173        apply: bool,
174        /// Undo a run from its journal.jsonl, step by step.
175        #[arg(long, value_name = "JOURNAL", conflicts_with = "restore")]
176        rollback: Option<String>,
177        /// Put a run's backup back, only while nothing has changed since.
178        #[arg(long, value_name = "JOURNAL")]
179        restore: Option<String>,
180    },
181}
182
183#[derive(Debug, Clone)]
184pub struct Config {
185    pub auth_key: String,
186    /// A separate, narrowly-scoped credential for LAN peer discovery
187    /// (mDNS TXT record + UDP broadcast responder) — NOT `auth_key`.
188    /// Minted fresh per-launch, internal to srv only (never needs to
189    /// leave this process except via the LAN broadcast itself, unlike
190    /// `auth_key` which the launcher/frontend also need — see
191    /// `LanDiscovery`'s doc comment). Broadcasting the full-access
192    /// `auth_key` to anything that can receive an mDNS multicast packet
193    /// or send a UDP probe used to mean a passive LAN listener got
194    /// standing access to the ENTIRE local `/agentmux/service` surface,
195    /// not just LAN-forwarding — this key is accepted only by the two
196    /// routes LAN peer forwarding actually needs
197    /// (`lan_or_full_auth_middleware` in `server/mod.rs`), so a captured
198    /// value's blast radius shrinks to "can forward jekts to this
199    /// instance and query which agents live here."
200    pub lan_key: String,
201    /// Shared secret proving a `host_ipc.Register` caller is really the
202    /// paired CEF host, not an agent process (agents share `auth_key` too
203    /// — see `host_ipc.rs::handle_register`'s doc comment). `None` when
204    /// nobody set `AGENTMUX_HOST_REG_SECRET` — `handle_register` then
205    /// refuses every registration rather than accepting one unauthenticated,
206    /// since there's nothing to check the caller against. Sourced from the
207    /// launcher (`agentmux-launcher::srv_spawner::SrvSpawnResult::host_reg_secret`,
208    /// minted once and reused across host-only crash-restarts, exactly
209    /// like `auth_key`) or, in host-owned-spawn/dev mode, from the host
210    /// itself (`crates/cef/src/sidecar.rs::spawn_backend`, which
211    /// generates it alongside its own `auth_key`).
212    pub host_reg_secret: Option<String>,
213    /// Empty when unset. Paths stay `PathBuf` (read with `var_os`) so a home
214    /// directory that isn't valid UTF-8 still reaches the stores intact
215    /// (Codex P2 on #3893).
216    pub data_home: PathBuf,
217    pub config_home: PathBuf,
218    pub app_path: String,
219    #[allow(dead_code)]
220    pub is_dev: bool,
221    pub version: &'static str,
222    pub build_time: &'static str,
223    pub instance_id: String,
224}
225
226impl Config {
227    /// Build config from env vars + CLI args.
228    /// Removes AGENTMUX_AUTH_KEY from the environment after reading (matching Go behavior).
229    pub fn from_env_and_args(args: &CliArgs) -> Result<Self, String> {
230        // `take` also wipes the value from the environment block that
231        // /proc/<pid>/environ (and `ps eww`) read, which remove_var alone does not.
232        let auth_key = agentmux_common::secret_env::take("AGENTMUX_AUTH_KEY")
233            .ok_or_else(|| "AGENTMUX_AUTH_KEY environment variable is required".to_string())?;
234
235        if auth_key.is_empty() {
236            return Err("AGENTMUX_AUTH_KEY must not be empty".to_string());
237        }
238
239        // CLI flag wins over env. The launcher sets the canonical
240        // `AGENTMUX_DATA_DIR` and `AGENTMUX_CONFIG_DIR` via
241        // `agentmux_common::DataPaths::to_env_vars`. Pre-unification
242        // names (`AGENTMUX_DATA_HOME`, `AGENTMUX_CONFIG_HOME`) are no
243        // longer set — no fallback (symmetry; partial-rollout isn't a
244        // supported scenario per spec §3.4 "no migration").
245        // An empty `--wavedata ""` counts as absent, as it does for the lock
246        // headless takes (`headless::effective_data_dir`) — otherwise the lock
247        // and the stores would pick different directories (Codex P2 on #3893).
248        let data_home = args
249            .wavedata
250            .clone()
251            .filter(|p| !p.as_os_str().is_empty())
252            .or_else(|| std::env::var_os("AGENTMUX_DATA_DIR").map(PathBuf::from))
253            .unwrap_or_default();
254
255        let config_home = std::env::var_os("AGENTMUX_CONFIG_DIR").map(PathBuf::from).unwrap_or_default();
256        let app_path = std::env::var("AGENTMUX_APP_PATH").unwrap_or_default();
257        // is_dev is now derived from AGENTMUX_RUNTIME_MODE (the
258        // canonical env var emitted by the unified DataPaths layer).
259        // Legacy AGENTMUX_DEV is no longer set by the launcher.
260        let is_dev = matches!(
261            agentmux_common::RuntimeMode::from_env(),
262            Some(agentmux_common::RuntimeMode::Dev { .. })
263        );
264
265        // Two v4 UUIDs concatenated for margin over a single UUID's 122 bits
266        // of randomness — same "avoid a rand/getrandom dependency just for
267        // this" reasoning as agent_jekt_keys.rs's random_key_bytes(), but
268        // kept as a plain string here (not raw bytes) since this only ever
269        // travels as a String — an mDNS TXT record value / UDP JSON field /
270        // HTTP header — never binary-serialized or HMAC-keyed.
271        let lan_key = format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4());
272
273        // Optional — only set by a launcher/host that knows about this
274        // credential. Scrub it from the env the same way AGENTMUX_AUTH_KEY
275        // is scrubbed above, so it can't be read back out of this
276        // process's own environment later (e.g. by a shell tool an agent
277        // asks this process to run — not applicable to srv itself, but
278        // matching the auth_key precedent costs nothing).
279        let host_reg_secret = agentmux_common::secret_env::take("AGENTMUX_HOST_REG_SECRET").filter(|s| !s.is_empty());
280
281        // The instance's keys are never written into a transcript.
282        for key in [Some(&auth_key), Some(&lan_key), host_reg_secret.as_ref()].into_iter().flatten() {
283            crate::backend::transcript::withhold::register(key);
284        }
285
286        Ok(Config {
287            auth_key,
288            lan_key,
289            host_reg_secret,
290            data_home,
291            config_home,
292            app_path,
293            is_dev,
294            version: env!("CARGO_PKG_VERSION"),
295            build_time: option_env!("BUILD_TIME").unwrap_or("dev"),
296            instance_id: args.instance.clone(),
297        })
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use std::sync::Mutex;
305
306    // Serialize config tests — they mutate process-global env vars
307    static ENV_LOCK: Mutex<()> = Mutex::new(());
308
309    /// Lock helper that recovers from poisoned mutex. A panic in any
310    /// test would otherwise propagate poison to all later tests via
311    /// `lock().unwrap()` and produce noise unrelated to the actual
312    /// failing test.
313    fn lock() -> std::sync::MutexGuard<'static, ()> {
314        ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
315    }
316
317    /// Clear every env var our config reads so each test starts from
318    /// a known state, regardless of leakage from prior tests.
319    fn clear_env() {
320        for k in [
321            "AGENTMUX_AUTH_KEY",
322            "AGENTMUX_DATA_DIR",
323            "AGENTMUX_DATA_HOME",
324            "AGENTMUX_CONFIG_DIR",
325            "AGENTMUX_CONFIG_HOME",
326            "AGENTMUX_APP_PATH",
327            "AGENTMUX_RUNTIME_MODE",
328            "AGENTMUX_DEV",
329            "AGENTMUX_HOST_REG_SECRET",
330        ] {
331            std::env::remove_var(k);
332        }
333    }
334
335    #[test]
336    fn missing_auth_key_errors() {
337        let _lock = lock();
338        clear_env();
339        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
340        let result = Config::from_env_and_args(&args);
341        assert!(result.is_err());
342        assert!(result.unwrap_err().contains("AGENTMUX_AUTH_KEY"));
343    }
344
345    #[test]
346    fn empty_auth_key_errors() {
347        let _lock = lock();
348        clear_env();
349        std::env::set_var("AGENTMUX_AUTH_KEY", "");
350        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
351        let result = Config::from_env_and_args(&args);
352        assert!(result.is_err());
353        clear_env();
354    }
355
356    #[test]
357    fn cli_wavedata_overrides_env() {
358        let _lock = lock();
359        clear_env();
360        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-12345");
361        std::env::set_var("AGENTMUX_DATA_DIR", "/from/env");
362        let args = CliArgs {
363            wavedata: Some("/from/cli".into()),
364            instance: "default".to_string(),
365            command: None,
366            ..Default::default()
367        };
368        let config = Config::from_env_and_args(&args).unwrap();
369        assert_eq!(config.data_home, PathBuf::from("/from/cli"));
370        assert!(std::env::var("AGENTMUX_AUTH_KEY").is_err());
371        clear_env();
372    }
373
374    #[test]
375    fn empty_cli_wavedata_counts_as_absent() {
376        let _lock = lock();
377        clear_env();
378        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-empty-wavedata");
379        std::env::set_var("AGENTMUX_DATA_DIR", "/from/env");
380        let args = CliArgs { wavedata: Some(PathBuf::new()), ..Default::default() };
381        let config = Config::from_env_and_args(&args).unwrap();
382        assert_eq!(config.data_home, PathBuf::from("/from/env"));
383        clear_env();
384    }
385
386    #[test]
387    fn env_var_parsing() {
388        let _lock = lock();
389        clear_env();
390        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-67890");
391        std::env::set_var("AGENTMUX_DATA_DIR", "/data");
392        std::env::set_var("AGENTMUX_CONFIG_DIR", "/config");
393        std::env::set_var("AGENTMUX_APP_PATH", "/app");
394        std::env::set_var("AGENTMUX_RUNTIME_MODE", "dev:main");
395        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
396        let config = Config::from_env_and_args(&args).unwrap();
397        assert_eq!(config.data_home, PathBuf::from("/data"));
398        assert_eq!(config.config_home, PathBuf::from("/config"));
399        assert_eq!(config.app_path, "/app");
400        assert!(config.is_dev);
401        clear_env();
402    }
403
404    /// A data or config dir that isn't valid UTF-8 (a Unix home with such a
405    /// name) is kept byte for byte, not dropped: `std::env::var` would call it
406    /// absent, and the stores would open under the default root instead.
407    #[cfg(unix)]
408    #[test]
409    fn non_utf8_dirs_are_kept() {
410        use std::ffi::OsStr;
411        use std::os::unix::ffi::OsStrExt;
412        let _lock = lock();
413        clear_env();
414        let data = OsStr::from_bytes(b"/home/caf\xe9/data");
415        let conf = OsStr::from_bytes(b"/home/caf\xe9/config");
416        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-non-utf8");
417        std::env::set_var("AGENTMUX_DATA_DIR", data);
418        std::env::set_var("AGENTMUX_CONFIG_DIR", conf);
419        let config = Config::from_env_and_args(&CliArgs::default()).unwrap();
420        assert_eq!(config.data_home.as_os_str(), data);
421        assert_eq!(config.config_home.as_os_str(), conf);
422        clear_env();
423    }
424
425    #[test]
426    fn host_reg_secret_defaults_to_none_when_unset() {
427        let _lock = lock();
428        clear_env();
429        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-host-reg-1");
430        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
431        let config = Config::from_env_and_args(&args).unwrap();
432        assert_eq!(config.host_reg_secret, None);
433        clear_env();
434    }
435
436    #[test]
437    fn host_reg_secret_is_read_and_scrubbed_from_env() {
438        let _lock = lock();
439        clear_env();
440        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-host-reg-2");
441        std::env::set_var("AGENTMUX_HOST_REG_SECRET", "the-shared-secret");
442        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
443        let config = Config::from_env_and_args(&args).unwrap();
444        assert_eq!(config.host_reg_secret, Some("the-shared-secret".to_string()));
445        assert!(std::env::var("AGENTMUX_HOST_REG_SECRET").is_err());
446        clear_env();
447    }
448
449    #[test]
450    fn lan_key_is_generated_nonempty_and_distinct_from_auth_key() {
451        let _lock = lock();
452        clear_env();
453        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-67890");
454        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
455        let config = Config::from_env_and_args(&args).unwrap();
456        assert!(!config.lan_key.is_empty());
457        assert_ne!(
458            config.lan_key, config.auth_key,
459            "the LAN-broadcast credential must never equal the full-access auth_key"
460        );
461        clear_env();
462    }
463
464    #[test]
465    fn lan_key_is_freshly_generated_per_call_not_a_fixed_constant() {
466        let _lock = lock();
467        clear_env();
468        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-67890");
469        let args = CliArgs { wavedata: None, instance: "default".to_string(), command: None, ..Default::default() };
470        let first = Config::from_env_and_args(&args).unwrap().lan_key;
471        std::env::set_var("AGENTMUX_AUTH_KEY", "test-key-67890");
472        let second = Config::from_env_and_args(&args).unwrap().lan_key;
473        assert_ne!(first, second, "each process launch must mint its own lan_key");
474        clear_env();
475    }
476
477    #[test]
478    fn migrate_prepare_refuses_the_read_only_flags() {
479        use clap::Parser;
480        for flag in ["--dry-run", "--list", "--verify"] {
481            let parsed = CliArgs::try_parse_from(["agentmux-srv", "migrate", "--prepare", flag]);
482            assert!(parsed.is_err(), "--prepare {flag} must be refused");
483        }
484        assert!(CliArgs::try_parse_from(["agentmux-srv", "migrate", "--prepare"]).is_ok());
485    }
486
487    #[test]
488    fn migrate_fork_slugs_takes_one_mode() {
489        use clap::Parser;
490        for ok in [vec![], vec!["--plan"], vec!["--apply"], vec!["--rollback", "j.jsonl"], vec!["--restore", "j.jsonl"]] {
491            let args = [vec!["agentmux-srv", "migrate-fork-slugs"], ok.clone()].concat();
492            assert!(CliArgs::try_parse_from(args).is_ok(), "{ok:?}");
493        }
494        for bad in [vec!["--apply", "--plan"], vec!["--apply", "--rollback", "j"], vec!["--rollback", "j", "--restore", "j"]] {
495            let args = [vec!["agentmux-srv", "migrate-fork-slugs"], bad.clone()].concat();
496            assert!(CliArgs::try_parse_from(args).is_err(), "{bad:?} is refused");
497        }
498    }
499}