Skip to main content

oomtop_cli/
lib.rs

1//! # oomtop-cli
2//!
3//! The `oomtop` binary (SPEC §12.2, UX §12.9, §6): every subcommand wired to the other crates through the
4//! APIs in `docs/CONTRACTS.md`. The pipeline lives in [`engine::Engine`]; signals only ever go through
5//! [`actuator::SignalActuator`] after an explicit confirmation.
6//!
7//! Exit codes: `0` ok / yes · `1` error · `2` usage · `3` yes after reclaim · `4` no.
8
9pub mod actuator;
10pub mod ansi;
11pub mod commands;
12pub mod engine;
13pub mod profile;
14pub mod termprobe;
15
16use clap::{Args, Parser, Subcommand, ValueEnum};
17use std::ffi::OsString;
18use std::path::PathBuf;
19use std::time::Duration;
20
21/// `13G`, `500M`, `1.5GiB` → bytes (clap value parser; a bad value is a usage error, exit 2).
22pub fn parse_size(s: &str) -> Result<u64, String> {
23    oomtop_core::units::parse_bytes(s).map_err(|e| format!("{e} (examples: 13G, 500M, 1.5GiB)"))
24}
25
26/// Longest `--interval` / `--wait` accepted: one year. Anything longer is a typo, and durations near
27/// `u64::MAX` seconds cannot be represented (or added to a clock) at all.
28pub const MAX_DURATION: Duration = Duration::from_secs(366 * 86_400);
29
30/// `2s`, `500ms`, `1m` → duration (clap value parser). Zero, negative, non-finite and absurdly long values
31/// are usage errors (exit 2), never a panic.
32pub fn parse_interval(s: &str) -> Result<Duration, String> {
33    let secs =
34        oomtop_core::units::parse_duration_s(s).map_err(|e| format!("{e} (examples: 2s, 500ms, 1m)"))?;
35    if !secs.is_finite() || secs <= 0.0 {
36        return Err("must be greater than zero".into());
37    }
38    match Duration::try_from_secs_f64(secs) {
39        Ok(d) if d <= MAX_DURATION => Ok(d),
40        _ => Err("too long (at most 366d)".into()),
41    }
42}
43
44#[derive(Debug, Parser)]
45#[command(
46    name = "oomtop",
47    version,
48    about = "Know before you run out of memory: what's using it, what you can stop, whether the next model fits.",
49    long_about = "oomtop: true memory accounting (GPU/Metal, compressed, swapped), attribution of every process \
50                  to the agent session / app / sandbox / model server that owns it, headroom checks, OOM \
51                  forecast and throttle explanations. Run without a subcommand for the TUI.",
52    after_help = "Exit codes: 0 ok/yes · 1 error · 2 usage · 3 yes after reclaim · 4 no.\n\
53                  Docs: oomtop <command> --help · oomtop config init --print (every setting) · oomtop doctor"
54)]
55pub struct Cli {
56    #[command(subcommand)]
57    pub command: Option<Cmd>,
58    #[command(flatten)]
59    pub global: GlobalOpts,
60}
61
62/// Flags accepted by every subcommand.
63#[derive(Debug, Clone, Default, Args)]
64pub struct GlobalOpts {
65    /// Config file to use instead of ~/.config/oomtop/config.toml (drop-ins are read next to it).
66    #[arg(long, global = true, env = "OOMTOP_CONFIG", value_name = "PATH")]
67    pub config: Option<PathBuf>,
68    /// Don't learn from this session (personalization off). Also OOMTOP_NO_LEARN=1.
69    #[arg(long, global = true)]
70    pub no_learn: bool,
71    /// Linear, screen-reader-friendly output instead of the TUI.
72    #[arg(long, global = true)]
73    pub plain: bool,
74    /// ASCII glyphs only.
75    #[arg(long, global = true)]
76    pub ascii: bool,
77    /// Theme name (overrides appearance.theme for this run).
78    #[arg(long, global = true, value_name = "NAME")]
79    pub theme: Option<String>,
80    /// Color depth (overrides appearance.color for this run).
81    #[arg(long, global = true, value_enum, value_name = "DEPTH")]
82    pub color: Option<ColorArg>,
83    /// Don't contact local adapter endpoints (process-level detection only).
84    #[arg(long, global = true)]
85    pub offline: bool,
86    /// Replay a recorded fixture instead of sampling this machine (actions are disabled).
87    #[arg(long, global = true, value_name = "FIXTURE")]
88    pub replay: Option<PathBuf>,
89    /// Override any setting for this run, e.g. --set appearance.theme=none (repeatable).
90    #[arg(long = "set", global = true, value_name = "KEY=VALUE")]
91    pub set: Vec<String>,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
95pub enum ColorArg {
96    Auto,
97    Truecolor,
98    #[value(name = "256")]
99    C256,
100    #[value(name = "16")]
101    C16,
102    None,
103}
104
105impl ColorArg {
106    pub fn as_str(self) -> &'static str {
107        match self {
108            ColorArg::Auto => "auto",
109            ColorArg::Truecolor => "truecolor",
110            ColorArg::C256 => "256",
111            ColorArg::C16 => "16",
112            ColorArg::None => "none",
113        }
114    }
115}
116
117/// Where a model's weights are expected to live when estimating `--model`.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
119pub enum Offload {
120    /// GPU-resident on unified-memory Macs with a Metal budget (llama.cpp/Ollama default), host RAM otherwise.
121    #[default]
122    Auto,
123    /// Offloaded to the GPU: the need must also fit the GPU budget.
124    Gpu,
125    /// CPU only: host RAM.
126    Cpu,
127}
128
129#[derive(Debug, Subcommand)]
130pub enum Cmd {
131    /// Can I load this now? Exit 0 yes · 3 yes after reclaim · 4 no · 1 unmeasurable.
132    Headroom(HeadroomArgs),
133    /// Ranked causes of slowness / memory pressure, with evidence.
134    Why {
135        #[arg(long)]
136        json: bool,
137    },
138    /// Idle build daemons, orphans and idle model servers; stops only after confirmation (or --yes).
139    Reclaim(ReclaimArgs),
140    /// Stale groups ranked with their evidence, leftovers of ended agent sessions, duplicates.
141    Stale {
142        #[arg(long)]
143        json: bool,
144        /// Show at most N groups.
145        #[arg(long, value_name = "N", default_value_t = 10)]
146        limit: usize,
147    },
148    /// Containers, VMs and local Kubernetes: limits with OOM ETAs, the cluster tree, VM slack, stale containers.
149    Sandboxes {
150        #[arg(long)]
151        json: bool,
152    },
153    /// Linux namespace sets: processes grouped by the namespaces they do not share with oomtop.
154    Ns {
155        #[arg(long)]
156        json: bool,
157    },
158    /// Listening ports → process → group, exposure, tunnels, conflicts, and who talks to whom.
159    Ports {
160        #[arg(long)]
161        json: bool,
162        /// Only listeners on all interfaces (0.0.0.0 / ::) and the exposure findings.
163        #[arg(long)]
164        exposed: bool,
165        /// Also show local connections between groups (loopback TCP, unix sockets where visible).
166        #[arg(long)]
167        links: bool,
168    },
169    /// Model files on disk: size, last use, duplicates, and which server has each loaded.
170    Models {
171        #[arg(long)]
172        json: bool,
173        /// Skip the partial hash of same-size files (duplicate detection).
174        #[arg(long)]
175        no_hash: bool,
176    },
177    /// One snapshot as JSON (schema_version 1, command lines redacted).
178    Json {
179        /// Single-line output.
180        #[arg(long)]
181        compact: bool,
182    },
183    /// Snapshots as newline-delimited JSON (one per interval).
184    Ndjson {
185        /// Time between snapshots (min 250ms).
186        #[arg(long, default_value = "2s", value_parser = parse_interval)]
187        interval: Duration,
188        /// Stop after N snapshots (0 prints none). A replay also stops after its last frame.
189        #[arg(long, value_name = "N")]
190        count: Option<u64>,
191        /// Run the sampling pipeline but print nothing (perf measurement, SPEC §14).
192        #[arg(long, hide = true)]
193        discard: bool,
194    },
195    /// HTTP JSON + Prometheus /metrics (binds 127.0.0.1 unless told otherwise).
196    Serve {
197        /// Listen address (default from serve.listen: 127.0.0.1:9469).
198        #[arg(long, value_name = "ADDR")]
199        listen: Option<String>,
200        /// Also accept requests whose Host header is NAME (repeatable), e.g. a reverse proxy's public name.
201        /// Always accepted: loopback names; on a non-loopback bind also IP addresses and this host's name.
202        #[arg(long = "allow-host", value_name = "NAME")]
203        allow_host: Vec<String>,
204        /// Exit after N requests (testing).
205        #[arg(long, hide = true)]
206        max_requests: Option<usize>,
207    },
208    /// MCP server over stdio (read-only tools unless --allow-actions).
209    Mcp {
210        /// Register the elicitation-gated reclaim tool.
211        #[arg(long)]
212        allow_actions: bool,
213    },
214    /// Detected capabilities, each source's status and why, config/state locations.
215    Doctor {
216        #[arg(long)]
217        json: bool,
218        /// Don't query the terminal (OSC 11 / Kitty keyboard / DECRQM); report environment-based guesses only.
219        #[arg(long)]
220        no_probe: bool,
221    },
222    /// Configuration files (layered, comment-preserving).
223    Config {
224        #[command(subcommand)]
225        cmd: ConfigCmd,
226    },
227    /// Themes (semantic tokens).
228    Theme {
229        #[command(subcommand)]
230        cmd: ThemeCmd,
231    },
232    /// Key bindings.
233    Keys {
234        #[command(subcommand)]
235        cmd: KeysCmd,
236    },
237    /// Local personalization profile (never leaves this machine).
238    Profile {
239        #[command(subcommand)]
240        cmd: ProfileCmd,
241    },
242}
243
244#[derive(Debug, Args)]
245pub struct HeadroomArgs {
246    /// Host RAM needed, e.g. 13G, 500M.
247    #[arg(long, value_name = "SIZE", value_parser = parse_size, conflicts_with = "model")]
248    pub need: Option<u64>,
249    /// GPU memory that must also fit the GPU budget (discrete GPUs), e.g. 8G.
250    #[arg(long, value_name = "SIZE", value_parser = parse_size)]
251    pub gpu: Option<u64>,
252    /// Model file or directory (.gguf, safetensors/MLX dir); reads headers only, never weights.
253    #[arg(long, value_name = "PATH")]
254    pub model: Option<PathBuf>,
255    /// Context length for the KV-cache estimate (default: the model's, capped at 8192).
256    #[arg(long, value_name = "N", requires = "model")]
257    pub ctx: Option<u64>,
258    /// KV cache type: f16 | q8_0 | q4_0 | … (llama.cpp --cache-type-k).
259    #[arg(long, value_name = "TYPE", default_value = "f16", requires = "model")]
260    pub kv_type: String,
261    /// Parallel sequences (llama.cpp -np / OLLAMA_NUM_PARALLEL).
262    #[arg(long, value_name = "N", default_value_t = 1, requires = "model")]
263    pub parallel: u64,
264    /// Where the model runs.
265    #[arg(long, value_enum, default_value_t = Offload::Auto, requires = "model")]
266    pub offload: Offload,
267    #[arg(long)]
268    pub json: bool,
269}
270
271#[derive(Debug, Args)]
272pub struct ReclaimArgs {
273    /// Show what would be stopped and the estimated gain; do nothing.
274    #[arg(long)]
275    pub dry_run: bool,
276    /// Don't ask: confirm the listed plan (SIGTERM / gentle unload only; SIGKILL always asks again).
277    #[arg(long)]
278    pub yes: bool,
279    /// Only these group ids (comma separated; must be reclaim candidates).
280    #[arg(long, value_delimiter = ',', value_name = "IDS")]
281    pub groups: Vec<String>,
282    /// How long to wait for stopped groups to exit before offering SIGKILL.
283    #[arg(long, default_value = "5s", value_parser = parse_interval)]
284    pub wait: Duration,
285    #[arg(long)]
286    pub json: bool,
287}
288
289#[derive(Debug, Subcommand)]
290pub enum ConfigCmd {
291    /// Write a fully commented config.toml (every option at its default) and the JSON Schemas.
292    Init {
293        /// Overwrite an existing config.toml.
294        #[arg(long)]
295        force: bool,
296        /// Print to stdout instead of writing.
297        #[arg(long)]
298        print: bool,
299    },
300    /// Open config.toml (or this host's override) in $VISUAL / $EDITOR, then validate it.
301    Edit {
302        #[arg(long)]
303        host: bool,
304    },
305    /// Print the configuration (merged TOML, or every leaf with --effective).
306    Print {
307        /// One `key = value` line per setting.
308        #[arg(long)]
309        effective: bool,
310        /// Show which layer set each value (implies --effective).
311        #[arg(long)]
312        origin: bool,
313        /// Only this key (or section prefix).
314        #[arg(value_name = "KEY")]
315        key: Option<String>,
316    },
317    /// Check every file (config layers, themes, keymap, layouts, rules) with file:line errors.
318    Validate,
319    /// Set a value with a comment-preserving edit (validated before writing).
320    Set {
321        key: String,
322        value: String,
323        /// user | host | dropin:<name>
324        #[arg(long, default_value = "user")]
325        layer: String,
326    },
327    /// Remove a key from a layer (falls back to lower layers / defaults).
328    Unset {
329        key: String,
330        #[arg(long, default_value = "user")]
331        layer: String,
332    },
333    /// Print a JSON Schema (config | theme | keymap | layout | rules), or write all with --write.
334    Schema {
335        #[arg(default_value = "config")]
336        kind: String,
337        /// Write every schema plus a .taplo.toml into DIR.
338        #[arg(long, value_name = "DIR")]
339        write: Option<PathBuf>,
340    },
341}
342
343#[derive(Debug, Subcommand)]
344pub enum ThemeCmd {
345    /// Built-in and user themes.
346    List,
347    /// Show every token rendered in this terminal.
348    Preview {
349        /// Theme name (default: the configured theme).
350        name: Option<String>,
351        /// Variant for truecolor themes (default: detected from the terminal background).
352        #[arg(long, value_parser = ["dark", "light"])]
353        variant: Option<String>,
354    },
355    /// Validate a theme: unknown tokens/colors, blue/purple defaults, contrast.
356    Check {
357        name: String,
358        #[arg(long, value_parser = ["dark", "light"])]
359        variant: Option<String>,
360    },
361    /// Import a base16/base24, iTerm2, Ghostty, Kitty or Alacritty scheme into ~/.config/oomtop/themes/.
362    Import {
363        file: PathBuf,
364        /// Theme name (default: from the scheme).
365        #[arg(long)]
366        name: Option<String>,
367        /// Overwrite an existing user theme of the same name.
368        #[arg(long)]
369        force: bool,
370        /// Print the theme instead of writing it.
371        #[arg(long)]
372        print: bool,
373    },
374    /// Print a theme as an editable theme file (resolved, all tokens).
375    Export {
376        name: String,
377        #[arg(long, value_parser = ["dark", "light"])]
378        variant: Option<String>,
379        /// Write to this file instead of stdout.
380        #[arg(long, short, value_name = "FILE")]
381        output: Option<PathBuf>,
382    },
383}
384
385#[derive(Debug, Subcommand)]
386pub enum KeysCmd {
387    /// Effective bindings per context (preset + keymap.toml).
388    List {
389        /// Only print conflicting bindings (exit 1 if any).
390        #[arg(long)]
391        conflicts: bool,
392        /// Preset to show instead of the configured one (default | vim | emacs | htop).
393        #[arg(long)]
394        preset: Option<String>,
395    },
396}
397
398#[derive(Debug, Subcommand)]
399pub enum ProfileCmd {
400    /// Machine profile, detected roles and learned entities.
401    Show {
402        #[arg(long)]
403        json: bool,
404    },
405    /// Everything learned, as JSON (no command lines, no environments).
406    Export,
407    /// Forget pins, mutes, renames, learned ranking and the machine profile (lineage is kept).
408    Reset {
409        #[arg(long)]
410        yes: bool,
411    },
412    /// Local UX metrics: Hit@3, keystrokes to target, reformulation and dismiss rates.
413    Stats {
414        #[arg(long)]
415        json: bool,
416    },
417}
418
419/// Parses args and runs; returns the process exit code.
420pub fn run<I, T>(args: I) -> i32
421where
422    I: IntoIterator<Item = T>,
423    T: Into<OsString> + Clone,
424{
425    let cli = match Cli::try_parse_from(args) {
426        Ok(c) => c,
427        Err(e) => {
428            let code = e.exit_code();
429            let _ = e.print();
430            return code;
431        }
432    };
433    match commands::dispatch(cli) {
434        Ok(code) => code,
435        Err(e) => {
436            if let Some(u) = e.downcast_ref::<commands::UsageError>() {
437                eprintln!("oomtop: {u}");
438                return oomtop_core::can_fit::EXIT_USAGE;
439            }
440            eprintln!("oomtop: {e:#}");
441            oomtop_core::can_fit::EXIT_ERROR
442        }
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use clap::CommandFactory;
450
451    #[test]
452    fn cli_definition_is_valid() {
453        Cli::command().debug_assert();
454    }
455
456    #[test]
457    fn usage_errors_exit_2() {
458        assert_eq!(run(["oomtop", "headroom", "--need", "1G", "--model", "x"]), 2);
459        assert_eq!(run(["oomtop", "headroom", "--need", "banana"]), 2);
460        assert_eq!(
461            run(["oomtop", "headroom", "--ctx", "4096"]),
462            2,
463            "--ctx requires --model"
464        );
465        assert_eq!(run(["oomtop", "ndjson", "--interval", "0s"]), 2);
466        // Out-of-range durations are usage errors too (these used to abort in `Duration::from_secs_f64`).
467        assert_eq!(
468            run([
469                "oomtop",
470                "ndjson",
471                "--interval",
472                "99999999999999999999s",
473                "--count",
474                "1"
475            ]),
476            2
477        );
478        assert_eq!(
479            run([
480                "oomtop",
481                "reclaim",
482                "--dry-run",
483                "--wait",
484                "99999999999999999999s"
485            ]),
486            2
487        );
488        assert_eq!(
489            run(["oomtop", "reclaim", "--dry-run", "--wait", "9000000000000000000s"]),
490            2
491        );
492        assert_eq!(run(["oomtop", "ndjson", "--interval", "400d"]), 2);
493        assert_eq!(run(["oomtop", "--color", "purple", "json"]), 2);
494        assert_eq!(run(["oomtop", "nope"]), 2);
495        assert_eq!(run(["oomtop", "--version"]), 0);
496    }
497
498    #[test]
499    fn value_parsers() {
500        assert_eq!(parse_size("13G").unwrap(), 13 << 30);
501        assert!(parse_size("13 bananas").is_err());
502        assert_eq!(parse_interval("500ms").unwrap(), Duration::from_millis(500));
503        assert!(parse_interval("-1s").is_err());
504        assert_eq!(parse_interval("366d").unwrap(), MAX_DURATION);
505        assert!(parse_interval("367d").unwrap_err().contains("too long"));
506        assert!(parse_interval("99999999999999999999s")
507            .unwrap_err()
508            .contains("too long"));
509        assert!(parse_interval(&format!("{}s", "9".repeat(400))).is_err());
510    }
511
512    #[test]
513    fn global_flags_anywhere() {
514        let c =
515            Cli::try_parse_from(["oomtop", "json", "--offline", "--set", "a.b=1", "--color", "256"]).unwrap();
516        assert!(c.global.offline);
517        assert_eq!(c.global.set, vec!["a.b=1"]);
518        assert_eq!(c.global.color, Some(ColorArg::C256));
519    }
520}