Skip to main content

rbnx/
main.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Robonix CLI Main Entry
3//
4// Main entry point for robonix-cli command-line tool
5
6use anyhow::Result;
7use clap::Parser;
8use robonix_cli::{Config, build_info::BuildInfo};
9use robonix_scribe::warn;
10use std::path::{Path, PathBuf};
11use std::sync::LazyLock;
12
13mod cmd;
14mod pb;
15
16static VERSION: LazyLock<String> = LazyLock::new(|| BuildInfo::get().summary());
17
18#[derive(Parser)]
19#[command(name = "rbnx")]
20#[command(version = VERSION.as_str())]
21#[command(about = "Robonix helper CLI for package validation, build, and local orchestration", long_about = None)]
22struct Cli {
23    #[command(subcommand)]
24    command: cmd::Commands,
25}
26
27/// Ensure the loopback control plane is never tunneled through an HTTP proxy.
28///
29/// Robonix's atlas (gRPC), the executor↔package MCP calls (HTTP), and the CLI
30/// itself all talk over `127.0.0.1` / `localhost`. If the environment has
31/// `http_proxy` set without those hosts in `no_proxy`, every local call gets
32/// routed through the proxy and fails (gRPC "Socket closed", MCP "502 Bad
33/// Gateway"). Merge the loopback hosts into `no_proxy`/`NO_PROXY` (preserving
34/// any existing entries, case-insensitively) so this process and every child
35/// it spawns — atlas, executor, pilot, the Python packages — bypass the proxy
36/// for the local control plane.
37fn ensure_loopback_bypasses_proxy() {
38    const LOOPBACK: [&str; 3] = ["127.0.0.1", "localhost", "::1"];
39    for var in ["no_proxy", "NO_PROXY"] {
40        let mut entries: Vec<String> = std::env::var(var)
41            .unwrap_or_default()
42            .split(',')
43            .map(|s| s.trim().to_string())
44            .filter(|s| !s.is_empty())
45            .collect();
46        let have: std::collections::HashSet<String> =
47            entries.iter().map(|s| s.to_ascii_lowercase()).collect();
48        for host in LOOPBACK {
49            if !have.contains(host) {
50                entries.push(host.to_string());
51            }
52        }
53        // SAFETY: called once at the very top of main, before any worker
54        // thread or child process reads proxy configuration from the env.
55        unsafe { std::env::set_var(var, entries.join(",")) };
56    }
57}
58
59fn boot_log_dir(command: &cmd::Commands) -> Option<PathBuf> {
60    let cmd::Commands::Boot { file, log_dir, .. } = command else {
61        return None;
62    };
63    if let Some(log_dir) = log_dir {
64        return Some(log_dir.clone());
65    }
66    let manifest = if file.is_absolute() {
67        file.clone()
68    } else {
69        std::env::current_dir().ok()?.join(file)
70    };
71    Some(
72        manifest
73            .parent()
74            .unwrap_or_else(|| Path::new("."))
75            .join("rbnx-boot")
76            .join("logs"),
77    )
78}
79
80fn prepare_boot_log_dir(command: &cmd::Commands) -> Result<()> {
81    let Some(log_dir) = boot_log_dir(command) else {
82        return Ok(());
83    };
84    std::fs::create_dir_all(&log_dir)?;
85    for entry in std::fs::read_dir(&log_dir)?.flatten() {
86        let path = entry.path();
87        if path.extension().and_then(|s| s.to_str()) == Some("log") {
88            let _ = std::fs::remove_file(path);
89        }
90    }
91    // Safety: startup is still single-threaded and Scribe has not been used.
92    unsafe { std::env::set_var("SCRIBE_LOG_DIR", &log_dir) };
93    Ok(())
94}
95
96#[tokio::main]
97async fn main() -> Result<()> {
98    ensure_loopback_bypasses_proxy();
99
100    let cli = Cli::parse();
101    // The detached boot watchdog must not depend on user config, package DB
102    // sync, a terminal, or Scribe initialization. It only reads the persisted
103    // boot state and performs teardown if the exact parent process vanishes.
104    if let cmd::Commands::WatchBoot {
105        state,
106        boot_pid,
107        boot_start_time_ticks,
108        boot_id,
109    } = &cli.command
110    {
111        return cmd::boot_watchdog::execute(
112            state.clone(),
113            *boot_pid,
114            *boot_start_time_ticks,
115            boot_id.clone(),
116        )
117        .await;
118    }
119    let verbose_boot = matches!(&cli.command, cmd::Commands::Boot { verbose: true, .. });
120    prepare_boot_log_dir(&cli.command)?;
121
122    // Select the Scribe console threshold before its LazyLock is initialized.
123    // Normal boot keeps package logs in files; verbose boot streams the same
124    // Scribe records to the terminal without introducing a second log path.
125    // Safety: no other threads exist yet (tokio runtime not started).
126    unsafe {
127        std::env::set_var(
128            "SCRIBE_CONSOLE_LEVEL",
129            if verbose_boot { "info" } else { "error" },
130        );
131    }
132
133    robonix_scribe::init("rbnx");
134
135    let config = Config::load()?;
136    config.ensure_storage_dir()?;
137
138    // Enforce robonix_source_path migration: subcommands that build / start packages
139    // need the new ~/.robonix/config.yaml field. Exempt commands that bootstrap the
140    // config itself (Setup), read it (Config, Path), or operate purely on atlas (Nodes,
141    // Describe, Tools, Channels, Inspect, Chat, Graph, List, Info).
142    let needs_source = matches!(
143        &cli.command,
144        cmd::Commands::Build { .. }
145            | cmd::Commands::Start { .. }
146            | cmd::Commands::Validate { .. }
147            | cmd::Commands::Install { .. }
148            | cmd::Commands::Codegen { .. }
149    );
150    if needs_source {
151        let _ = config.require_source_path();
152    }
153
154    if let Err(e) = robonix_cli::PackageDatabase::sync(&config.package_storage_path) {
155        warn!("Package database sync failed: {}", e);
156    }
157
158    cmd::execute(cli.command, config).await?;
159
160    Ok(())
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use clap::CommandFactory;
167
168    #[test]
169    fn build_accepts_explicit_deploy_manifest() {
170        let cli = Cli::try_parse_from(["rbnx", "build", "-f", "robot/robonix_manifest.yaml"])
171            .expect("build -f should parse");
172        match cli.command {
173            cmd::Commands::Build {
174                file, path, global, ..
175            } => {
176                assert_eq!(file, Some("robot/robonix_manifest.yaml".into()));
177                assert!(path.is_none());
178                assert!(global.is_none());
179            }
180            _ => panic!("expected build command"),
181        }
182    }
183
184    #[test]
185    fn build_manifest_conflicts_with_single_package_selectors() {
186        assert!(Cli::try_parse_from(["rbnx", "build", "-f", "deploy.yaml", "-p", "."]).is_err());
187        assert!(Cli::try_parse_from(["rbnx", "build", "-f", "deploy.yaml", "-g", "pkg"]).is_err());
188    }
189
190    #[test]
191    fn build_accepts_no_update_check() {
192        let cli = Cli::try_parse_from([
193            "rbnx",
194            "build",
195            "-f",
196            "robot/robonix_manifest.yaml",
197            "--no-update-check",
198        ])
199        .expect("build --no-update-check should parse");
200        assert!(matches!(
201            cli.command,
202            cmd::Commands::Build {
203                no_update_check: true,
204                ..
205            }
206        ));
207    }
208
209    #[test]
210    fn update_accepts_yes_and_check_flags() {
211        let cli = Cli::try_parse_from(["rbnx", "update", "-y"]).expect("update -y should parse");
212        assert!(matches!(
213            cli.command,
214            cmd::Commands::Update { yes: true, .. }
215        ));
216        let cli = Cli::try_parse_from(["rbnx", "update", "--check", "--json"])
217            .expect("update --check --json should parse");
218        assert!(matches!(
219            cli.command,
220            cmd::Commands::Update {
221                check: true,
222                json: true,
223                ..
224            }
225        ));
226        assert!(Cli::try_parse_from(["rbnx", "update", "--json"]).is_err());
227        assert!(Cli::try_parse_from(["rbnx", "update", "--check", "-y"]).is_err());
228    }
229
230    #[test]
231    fn boot_accepts_verbose_mode() {
232        let cli = Cli::try_parse_from(["rbnx", "boot", "-v"]).expect("boot -v should parse");
233        assert!(matches!(
234            cli.command,
235            cmd::Commands::Boot { verbose: true, .. }
236        ));
237    }
238
239    /// Keep boot help aligned with the supported built-in system components.
240    #[test]
241    fn boot_help_lists_vitals() {
242        let mut command = Cli::command();
243        let help = command
244            .find_subcommand_mut("boot")
245            .expect("boot subcommand")
246            .render_long_help()
247            .to_string();
248        assert!(help.contains("vitals"));
249    }
250
251    #[test]
252    fn boot_uses_manifest_local_scribe_directory() {
253        let cli = Cli::try_parse_from(["rbnx", "boot", "-f", "robot/robonix_manifest.yaml"])
254            .expect("boot manifest should parse");
255        assert_eq!(
256            boot_log_dir(&cli.command),
257            std::env::current_dir()
258                .ok()
259                .map(|cwd| cwd.join("robot/rbnx-boot/logs"))
260        );
261    }
262}
浙ICP备2023005800号-2 浙公网安备33010902005384号