rbnx/cmd/mod.rs
1// SPDX-License-Identifier: MulanPSL-2.0
2// Command Module
3//
4// Command definitions and execution for robonix-cli
5
6use anyhow::Result;
7use clap::Subcommand;
8use std::path::PathBuf;
9
10use robonix_cli::Config;
11
12mod ask;
13pub(crate) mod boot_watchdog;
14mod build;
15mod chat;
16mod check_remotes;
17mod clean;
18mod codegen;
19mod config;
20mod deploy;
21mod docs;
22mod info;
23mod init;
24mod inspect;
25mod install;
26mod list;
27mod llm_usage;
28mod logs;
29mod package_new;
30mod path;
31mod run_package;
32mod setup;
33mod shutdown;
34mod teardown;
35mod update;
36mod validate;
37mod version;
38
39const DEFAULT_ENDPOINT: &str = "localhost:50051";
40
41#[derive(Subcommand)]
42pub enum Commands {
43 /// Build a package (local path or system-installed)
44 Build {
45 /// Deployment manifest to build (builds every declared package)
46 #[arg(short = 'f', long, value_name = "FILE", conflicts_with_all = ["path", "global"])]
47 file: Option<PathBuf>,
48 /// Local package path (relative to $RBNX_INVOCATION_CWD, else process cwd)
49 #[arg(short = 'p', long)]
50 path: Option<PathBuf>,
51 /// Build by system-installed package name
52 #[arg(short = 'g', long)]
53 global: Option<String>,
54 /// Clean build (remove rbnx-build before building). Default: incremental.
55 #[arg(long)]
56 clean: bool,
57 /// Skip the remote-provider freshness check before building cached packages.
58 /// Useful when offline or when the deployment cache is intentionally pinned.
59 #[arg(long)]
60 no_update_check: bool,
61 },
62 /// Start one package (runs its `start` block; blocks until it exits)
63 ///
64 /// Defaults to the package containing the current directory when `-p`
65 /// is omitted. The pre-dev-packaging `-n / --node` flag is gone — one
66 /// package = one start body now.
67 Start {
68 /// Package path or installed name; relative paths use $RBNX_INVOCATION_CWD, else process cwd.
69 /// If omitted, rbnx walks up from the current directory to find a package manifest.
70 #[arg(short = 'p', long)]
71 package: Option<String>,
72 /// Registry endpoint (default: 127.0.0.1:50051)
73 #[arg(long)]
74 endpoint: Option<String>,
75 /// Per-instance config file (JSON or YAML). Decoded and delivered to
76 /// the provider through Driver(CMD_INIT). It has the same shape as a
77 /// package's nested `config:` block in `robonix_manifest.yaml`.
78 #[arg(short = 'c', long)]
79 config: Option<PathBuf>,
80 /// Inline config overrides. Repeatable, dotted-path keys, e.g.
81 /// `--set sensors.lidar2d=true --set algo=rtabmap`. Layered on
82 /// top of `--config` (sets win). Values are JSON-parsed when
83 /// possible (so `--set max_speed=0.5` is a number, `--set on=true`
84 /// is a bool); fall back to a string when JSON parsing fails.
85 #[arg(short = 's', long = "set", value_name = "KEY=VALUE")]
86 set: Vec<String>,
87 /// Package manifest filename to use instead of the default
88 /// `package_manifest.yaml`. Lets a package ship per-deployment-target
89 /// variants (e.g. `package_manifest.jetson-native.yaml`). `rbnx boot`
90 /// passes this through from a deploy entry's `manifest:` field.
91 #[arg(short = 'm', long)]
92 manifest: Option<String>,
93 },
94 /// Boot the whole stack from a `robonix_manifest.yaml` (until Ctrl-C)
95 ///
96 /// Brings up declared built-in system components
97 /// (atlas/chronos/executor/soma/pilot/vitals/liaison), other system packages, and
98 /// every package declared under `primitive`/`service`/`skill`.
99 /// `rbnx deploy` is kept as an alias for back-compat.
100 #[command(alias = "deploy")]
101 Boot {
102 /// Path to the deployment manifest (default: `./robonix_manifest.yaml`).
103 #[arg(short = 'f', long, default_value = "robonix_manifest.yaml")]
104 file: PathBuf,
105 /// Directory for per-component logs (default: `<manifest-dir>/rbnx-boot/logs`).
106 #[arg(long)]
107 log_dir: Option<PathBuf>,
108 /// Skip starting the `system:` block (atlas/pilot/etc). Useful when
109 /// those are already running externally.
110 #[arg(long)]
111 skip_system: bool,
112 /// Skip the remote-provider freshness check (the per-package
113 /// `git fetch` pass that runs before boot). Use when offline or in a
114 /// hurry.
115 #[arg(long)]
116 no_update_check: bool,
117 /// Stream append-only, Scribe-backed component logs during boot.
118 /// Disables animated cursor updates so output can be read or piped
119 /// like a Linux/FreeBSD kernel boot log or Android logcat.
120 #[arg(short, long)]
121 verbose: bool,
122 },
123 /// Internal detached cleanup process for one `rbnx boot` invocation.
124 #[command(name = "__watch-boot", hide = true)]
125 WatchBoot {
126 #[arg(long)]
127 state: PathBuf,
128 #[arg(long)]
129 boot_pid: u32,
130 #[arg(long)]
131 boot_start_time_ticks: Option<u64>,
132 #[arg(long)]
133 boot_id: String,
134 },
135 /// Update remote (`url:`) providers to their latest upstream commit
136 ///
137 /// In a deploy dir (or with `-f <manifest>`) updates ALL cloned remote
138 /// providers; with `-p <dir>` (or inside a package checkout) updates just
139 /// that one. Shows an overview and asks for confirmation before pulling;
140 /// when stdin is not a terminal it refuses unless `--yes` is given.
141 Update {
142 /// Update a single package checkout at this path.
143 #[arg(short = 'p', long)]
144 path: Option<PathBuf>,
145 /// Deploy manifest whose remote providers to update
146 /// (default: `./robonix_manifest.yaml`).
147 #[arg(short = 'f', long)]
148 file: Option<PathBuf>,
149 /// Pull without asking for confirmation.
150 #[arg(short = 'y', long, conflicts_with = "check")]
151 yes: bool,
152 /// Report which providers of the deploy have updates; pull nothing.
153 #[arg(long, conflicts_with = "path")]
154 check: bool,
155 /// With --check, print the report as one JSON object.
156 #[arg(long, requires = "check")]
157 json: bool,
158 },
159 /// Tear down a stack previously brought up by `rbnx boot`
160 ///
161 /// Reads the per-manifest state file boot writes
162 /// (`<manifest-dir>/rbnx-boot/state.json`) to kill the right process
163 /// groups + docker containers, so the host doesn't accumulate orphaned
164 /// drivers when boot dies on an error path or its shell window is closed.
165 Shutdown {
166 /// Path to the deployment manifest (default: `./robonix_manifest.yaml`).
167 #[arg(short = 'f', long, default_value = "robonix_manifest.yaml")]
168 file: PathBuf,
169 },
170 /// Drop build artifacts (`rbnx-build/`), per-package or per-deploy
171 ///
172 /// `rbnx clean -p <pkg>` removes `<pkg>/rbnx-build/`. `rbnx clean -f
173 /// <manifest>` recurses over every package the manifest references
174 /// (path: + url: + system/*), wipes each one's `rbnx-build/`, and clears
175 /// the deploy's `rbnx-boot/{logs,state.json}`. `--cache` also wipes
176 /// `rbnx-boot/cache/` (forces re-clone of url: packages). Defaults to the
177 /// package containing cwd when neither `-p` nor `-f` is given.
178 Clean {
179 /// Package path (defaults to walking up from cwd).
180 #[arg(short = 'p', long)]
181 package: Option<PathBuf>,
182 /// Deploy manifest path. When set, recurses over the manifest.
183 #[arg(short = 'f', long)]
184 file: Option<PathBuf>,
185 /// With `-f`, also wipe `rbnx-boot/cache/` (force re-clone).
186 #[arg(long)]
187 cache: bool,
188 /// With `-f`, also wipe `rbnx-boot/sessions/` (Pilot session
189 /// transcripts, which restore sessions after a restart).
190 #[arg(long)]
191 sessions: bool,
192 /// With `-f`, also wipe `rbnx-boot/llm-metrics/` (per-request model
193 /// usage records, which `rbnx llm-usage` sums).
194 #[arg(long)]
195 llm_metrics: bool,
196 },
197 /// Install a package from GitHub or local path
198 ///
199 /// Legacy system-installed-package tooling; superseded by deploy
200 /// manifests (`rbnx boot`/`build`). Hidden from the command list but
201 /// still functional.
202 #[command(hide = true)]
203 Install {
204 /// Install from GitHub (e.g. user/repo or <https://github.com/user/repo>)
205 #[arg(long)]
206 github: Option<String>,
207 /// Install from local path
208 #[arg(long)]
209 path: Option<PathBuf>,
210 },
211 /// List system-installed packages (legacy; hidden)
212 #[command(hide = true)]
213 List,
214 /// Show details of a system-installed package (legacy; hidden)
215 #[command(hide = true)]
216 Info {
217 /// Package name
218 name: String,
219 },
220 /// Validate a package manifest without building
221 ///
222 /// If no path is given, rbnx walks up from the current directory to find
223 /// a package manifest.
224 Validate {
225 /// Package directory (relative paths use $RBNX_INVOCATION_CWD, else process cwd)
226 path: Option<PathBuf>,
227 },
228 /// Configure robonix-cli
229 Config {
230 /// Set package storage path
231 #[arg(short = 'p', long)]
232 set_storage_path: Option<PathBuf>,
233 /// Show current configuration
234 #[arg(short, long)]
235 show: bool,
236 },
237 /// Run codegen for a package (proto + gRPC stubs + MCP types)
238 ///
239 /// Wraps robonix-codegen + Python grpcio-tools: stages system protos under
240 /// `<pkg>/rbnx-build/proto-staging/`, then emits generated artifacts under
241 /// `<pkg>/rbnx-build/codegen/`. If `-p` is omitted, rbnx walks up from the
242 /// current directory to find a package manifest.
243 Codegen {
244 /// Package path (relative to $RBNX_INVOCATION_CWD, else process cwd)
245 #[arg(short = 'p', long)]
246 package: Option<PathBuf>,
247 /// Also generate robonix_mcp_types/ (for MCP-based packages)
248 #[arg(long)]
249 mcp: bool,
250 /// Also generate ros2_idl/ — the canonical ROS 2 message overlay
251 /// (source). Build it with `colcon build` in a ROS 2 environment and
252 /// source install/setup.bash so rclpy types are Robonix's.
253 #[arg(long)]
254 ros2: bool,
255 /// Remove previous generated outputs before regenerating (never removes rbnx-build/ws/)
256 #[arg(long)]
257 clean: bool,
258 /// Directory (relative to package root, or absolute) containing generated artifact directories.
259 /// Defaults to `<package>/rbnx-build/codegen`.
260 #[arg(long)]
261 out_dir: Option<PathBuf>,
262 /// Python interpreter used for grpcio-tools generation and import validation.
263 /// Precedence: this flag, then RBNX_CODEGEN_PYTHON; it must have the pinned
264 /// protobuf, grpcio-tools and grpcio. Without either, rbnx uses the toolchain
265 /// it manages under the robonix home.
266 #[arg(long, value_name = "PATH")]
267 python: Option<PathBuf>,
268 },
269 /// Regenerate the mdBook contract + ROS IDL reference
270 ///
271 /// Rebuilds `docs/src/reference/{contracts,idl}.md` from `capabilities/`.
272 /// Auto-generated + version-stamped — run after changing any contract or
273 /// IDL so the browsable reference stays in sync.
274 Docs {
275 /// Output directory (default: `<root>/docs/src/reference`).
276 #[arg(long)]
277 out_dir: Option<PathBuf>,
278 },
279 /// Register this directory as the robonix source tree
280 ///
281 /// Persists to ~/.robonix/config.yaml. Call once from a cloned robonix
282 /// repo so packages anywhere on disk can find capabilities/IDL.
283 Setup {
284 /// Path to the robonix repo root (default: $RBNX_INVOCATION_CWD or process cwd).
285 /// If the given path is a sub-directory, walks up to find the root.
286 path: Option<PathBuf>,
287 },
288 /// Print an absolute path in the robonix source tree (for build scripts)
289 ///
290 /// Keys: root, rust, capabilities, interfaces-lib, runtime-proto, robonix-api.
291 Path {
292 /// Path key to resolve (see above).
293 key: String,
294 },
295 /// Print the version and the git commit this binary was built from
296 Version {
297 /// Print one JSON object, with the source tree `rbnx path root` resolves.
298 #[arg(long)]
299 json: bool,
300 },
301
302 /// List registered capabilities (one row per provider)
303 ///
304 /// Pass -v to expand the per-provider capability list, lspci -tv style.
305 #[command(alias = "nodes")]
306 Caps {
307 /// robonix-atlas endpoint
308 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
309 server: String,
310 /// Output as JSON (forces full detail regardless of -v)
311 #[arg(long)]
312 json: bool,
313 /// Expand each provider's capability list; without this, only the
314 /// summary header line per provider is printed.
315 #[arg(short = 'v', long)]
316 verbose: bool,
317 },
318 /// List atlas's loaded contract registry
319 ///
320 /// Every `<root>/capabilities/**/*.toml` atlas parsed at startup. -v for
321 /// field-level schemas + source paths; -p/--prefix filters by namespace.
322 Contracts {
323 /// robonix-atlas endpoint
324 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
325 server: String,
326 /// Filter by id prefix (e.g. `robonix/primitive/camera/`)
327 #[arg(short = 'p', long)]
328 prefix: Option<String>,
329 /// Output as JSON (forces full detail)
330 #[arg(long)]
331 json: bool,
332 /// Expand each contract's field schema + source toml path
333 #[arg(short = 'v', long)]
334 verbose: bool,
335 },
336 /// Show CAPABILITY.md for registered providers (all, or one with --provider)
337 Describe {
338 /// robonix-atlas endpoint
339 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
340 server: String,
341 /// Show full CAPABILITY.md content for a specific provider_id
342 #[arg(long, alias = "node")]
343 provider: Option<String>,
344 /// Output as JSON
345 #[arg(long)]
346 json: bool,
347 },
348 /// Print every MCP-callable tool visible to the agent (executor builtins + provider capabilities)
349 Tools {
350 /// robonix-atlas endpoint
351 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
352 server: String,
353 /// Output as JSON
354 #[arg(long)]
355 json: bool,
356 },
357 /// Show active channels (consumer→provider connections opened via ConnectCapability)
358 Channels {
359 /// robonix-atlas endpoint
360 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
361 server: String,
362 },
363 /// Dump full runtime state as JSON (providers, capabilities, channels)
364 Inspect {
365 /// robonix-atlas endpoint
366 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
367 server: String,
368 },
369
370 /// Chat with the Robonix agent in an interactive TUI
371 Chat {
372 /// robonix-atlas endpoint (used to discover agent)
373 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
374 server: String,
375 },
376
377 /// Initialize a new robot deployment directory (creates robonix_manifest.yaml)
378 Init {
379 /// Robot deployment directory name
380 name: String,
381 /// Parent directory (default: current directory)
382 #[arg(long)]
383 path: Option<PathBuf>,
384 },
385
386 /// Create a new package under the appropriate role directory
387 PackageNew {
388 /// Package name
389 name: String,
390 /// Package type: primitive, service, or skill
391 #[arg(short = 't', long = "type", default_value = "service")]
392 pkg_type: String,
393 /// Target package directory to create (when given, --type is ignored)
394 #[arg(long)]
395 path: Option<PathBuf>,
396 },
397
398 /// One-shot non-interactive prompt to the agent (stdout, then exit)
399 ///
400 /// Same gRPC path as `rbnx chat` (atlas connect → SubmitTask → stream
401 /// PilotEvent) but prints events to stdout and exits when the stream
402 /// closes. Useful for scripted tests / CI / agent-driven runs.
403 Ask {
404 /// The user message to send to the pilot.
405 prompt: String,
406 /// robonix-atlas endpoint
407 #[arg(long, env = "ROBONIX_ATLAS", default_value = DEFAULT_ENDPOINT)]
408 server: String,
409 /// Emit one JSON object per pilot event on stdout (line-delimited).
410 /// Default is human-readable text with tool-call summaries.
411 #[arg(long)]
412 json: bool,
413 /// Continue this Pilot session instead of starting a new one. Sent
414 /// while an earlier task of the session runs, the prompt steers it.
415 #[arg(long)]
416 session: Option<String>,
417 },
418 /// Read Scribe JSON-lines log files and render them with optional
419 /// tag / level filtering. Point at a log directory or read the
420 /// default `<manifest-dir>/rbnx-boot/logs`.
421 Logs {
422 /// Log directory (default: `./rbnx-boot/logs` or `$SCRIBE_LOG_DIR`).
423 #[arg(short = 'd', long)]
424 log_dir: Option<PathBuf>,
425 /// Filter to one or more tags (OR semantics).
426 #[arg(short = 't', long)]
427 tag: Vec<String>,
428 /// Minimum level to show (debug < info < warn < error).
429 #[arg(short = 'l', long)]
430 level: Option<String>,
431 /// Follow mode — keep reading new lines as they arrive (tail -f).
432 #[arg(short = 'f', long)]
433 follow: bool,
434 /// Output raw JSON lines instead of logcat-style rendering.
435 #[arg(long)]
436 json: bool,
437 /// List the distinct tags present in the logs (with record counts)
438 /// instead of printing records — handy for discovering `-t` values.
439 #[arg(long)]
440 list_tags: bool,
441 },
442 /// Sum the per-request model usage records by consumer, operation, host
443 /// and model: requests, outcomes and reported tokens.
444 LlmUsage {
445 /// Records directory (default: `$ROBONIX_LLM_METRICS_DIR`, else
446 /// `./rbnx-boot/llm-metrics`).
447 #[arg(short = 'd', long)]
448 dir: Option<PathBuf>,
449 /// Only records of this boot (`RBNX_BOOT_ID`, `boot_id` in a record).
450 #[arg(long)]
451 boot: Option<String>,
452 /// Print the totals as JSON lines instead of a table.
453 #[arg(long)]
454 json: bool,
455 },
456}
457
458pub async fn execute(command: Commands, config: Config) -> Result<()> {
459 match command {
460 Commands::Build {
461 file,
462 path,
463 global,
464 clean,
465 no_update_check,
466 } => run_package::execute_build(config, file, path, global, clean, no_update_check).await,
467 Commands::Start {
468 package,
469 endpoint,
470 config: cfg_file,
471 set,
472 manifest,
473 } => {
474 run_package::execute_start(
475 &config,
476 package.as_deref(),
477 endpoint.as_deref(),
478 cfg_file.as_deref(),
479 &set,
480 manifest.as_deref(),
481 )
482 .await
483 }
484 Commands::Boot {
485 file,
486 log_dir,
487 skip_system,
488 no_update_check,
489 verbose,
490 } => deploy::execute(config, file, log_dir, skip_system, no_update_check, verbose).await,
491 Commands::WatchBoot {
492 state,
493 boot_pid,
494 boot_start_time_ticks,
495 boot_id,
496 } => boot_watchdog::execute(state, boot_pid, boot_start_time_ticks, boot_id).await,
497 Commands::Update {
498 path,
499 file,
500 yes,
501 check,
502 json,
503 } => update::execute(config, path, file, yes, check, json).await,
504 Commands::Shutdown { file } => shutdown::execute(file).await,
505 Commands::Clean {
506 package,
507 file,
508 cache,
509 sessions,
510 llm_metrics,
511 } => clean::execute(config, package, file, cache, sessions, llm_metrics).await,
512 Commands::Install { github, path } => install::execute(config, github, path).await,
513 Commands::List => list::execute(config).await,
514 Commands::Info { name } => info::execute(config, &name).await,
515 Commands::Validate { path } => validate::execute(path).await,
516 Commands::Config {
517 set_storage_path,
518 show,
519 } => config::execute(config, set_storage_path, show).await,
520 Commands::Codegen {
521 package,
522 mcp,
523 ros2,
524 clean,
525 out_dir,
526 python,
527 } => codegen::execute(config, package, mcp, ros2, clean, out_dir, python).await,
528 Commands::Docs { out_dir } => docs::execute(config, out_dir).await,
529 Commands::Setup { path } => setup::execute(config, path).await,
530 Commands::Path { key } => path::execute(config, key).await,
531 Commands::Version { json } => version::execute(&config, json),
532 Commands::Caps {
533 server,
534 json,
535 verbose,
536 } => inspect::providers(&server, json, verbose).await,
537 Commands::Contracts {
538 server,
539 prefix,
540 json,
541 verbose,
542 } => inspect::contracts(&server, prefix.as_deref(), json, verbose).await,
543 Commands::Describe {
544 server,
545 provider,
546 json,
547 } => inspect::describe(&server, provider.as_deref(), json).await,
548 Commands::Tools { server, json } => inspect::tools(&server, json).await,
549 Commands::Channels { server } => inspect::channels(&server).await,
550 Commands::Inspect { server } => inspect::inspect(&server).await,
551 Commands::Chat { server } => chat::execute(&server).await,
552 Commands::Init { name, path } => init::execute(&name, path.as_deref()).await,
553 Commands::PackageNew {
554 name,
555 pkg_type,
556 path,
557 } => package_new::execute(&name, &pkg_type, path.as_deref()).await,
558 Commands::Ask {
559 prompt,
560 server,
561 json,
562 session,
563 } => ask::execute(&server, &prompt, json, session).await,
564 Commands::Logs {
565 log_dir,
566 tag,
567 level,
568 follow,
569 json,
570 list_tags,
571 } => logs::execute(log_dir, tag, level, follow, json, list_tags).await,
572 Commands::LlmUsage { dir, boot, json } => llm_usage::execute(dir, boot.as_deref(), json),
573 }
574}