pub mod actuator;
pub mod ansi;
pub mod commands;
pub mod engine;
pub mod profile;
pub mod termprobe;
use clap::{Args, Parser, Subcommand, ValueEnum};
use std::ffi::OsString;
use std::path::PathBuf;
use std::time::Duration;
pub fn parse_size(s: &str) -> Result<u64, String> {
oomtop_core::units::parse_bytes(s).map_err(|e| format!("{e} (examples: 13G, 500M, 1.5GiB)"))
}
pub const MAX_DURATION: Duration = Duration::from_secs(366 * 86_400);
pub fn parse_interval(s: &str) -> Result<Duration, String> {
let secs =
oomtop_core::units::parse_duration_s(s).map_err(|e| format!("{e} (examples: 2s, 500ms, 1m)"))?;
if !secs.is_finite() || secs <= 0.0 {
return Err("must be greater than zero".into());
}
match Duration::try_from_secs_f64(secs) {
Ok(d) if d <= MAX_DURATION => Ok(d),
_ => Err("too long (at most 366d)".into()),
}
}
#[derive(Debug, Parser)]
#[command(
name = "oomtop",
version,
about = "Know before you run out of memory: what's using it, what you can stop, whether the next model fits.",
long_about = "oomtop: true memory accounting (GPU/Metal, compressed, swapped), attribution of every process \
to the agent session / app / sandbox / model server that owns it, headroom checks, OOM \
forecast and throttle explanations. Run without a subcommand for the TUI.",
after_help = "Exit codes: 0 ok/yes · 1 error · 2 usage · 3 yes after reclaim · 4 no.\n\
Docs: oomtop <command> --help · oomtop config init --print (every setting) · oomtop doctor"
)]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Cmd>,
#[command(flatten)]
pub global: GlobalOpts,
}
#[derive(Debug, Clone, Default, Args)]
pub struct GlobalOpts {
#[arg(long, global = true, env = "OOMTOP_CONFIG", value_name = "PATH")]
pub config: Option<PathBuf>,
#[arg(long, global = true)]
pub no_learn: bool,
#[arg(long, global = true)]
pub plain: bool,
#[arg(long, global = true)]
pub ascii: bool,
#[arg(long, global = true, value_name = "NAME")]
pub theme: Option<String>,
#[arg(long, global = true, value_enum, value_name = "DEPTH")]
pub color: Option<ColorArg>,
#[arg(long, global = true)]
pub offline: bool,
#[arg(long, global = true, value_name = "FIXTURE")]
pub replay: Option<PathBuf>,
#[arg(long = "set", global = true, value_name = "KEY=VALUE")]
pub set: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ColorArg {
Auto,
Truecolor,
#[value(name = "256")]
C256,
#[value(name = "16")]
C16,
None,
}
impl ColorArg {
pub fn as_str(self) -> &'static str {
match self {
ColorArg::Auto => "auto",
ColorArg::Truecolor => "truecolor",
ColorArg::C256 => "256",
ColorArg::C16 => "16",
ColorArg::None => "none",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
pub enum Offload {
#[default]
Auto,
Gpu,
Cpu,
}
#[derive(Debug, Subcommand)]
pub enum Cmd {
Headroom(HeadroomArgs),
Why {
#[arg(long)]
json: bool,
},
Reclaim(ReclaimArgs),
Stale {
#[arg(long)]
json: bool,
#[arg(long, value_name = "N", default_value_t = 10)]
limit: usize,
},
Sandboxes {
#[arg(long)]
json: bool,
},
Ns {
#[arg(long)]
json: bool,
},
Ports {
#[arg(long)]
json: bool,
#[arg(long)]
exposed: bool,
#[arg(long)]
links: bool,
},
Models {
#[arg(long)]
json: bool,
#[arg(long)]
no_hash: bool,
},
Json {
#[arg(long)]
compact: bool,
},
Ndjson {
#[arg(long, default_value = "2s", value_parser = parse_interval)]
interval: Duration,
#[arg(long, value_name = "N")]
count: Option<u64>,
#[arg(long, hide = true)]
discard: bool,
},
Serve {
#[arg(long, value_name = "ADDR")]
listen: Option<String>,
#[arg(long = "allow-host", value_name = "NAME")]
allow_host: Vec<String>,
#[arg(long, hide = true)]
max_requests: Option<usize>,
},
Mcp {
#[arg(long)]
allow_actions: bool,
},
Doctor {
#[arg(long)]
json: bool,
#[arg(long)]
no_probe: bool,
},
Config {
#[command(subcommand)]
cmd: ConfigCmd,
},
Theme {
#[command(subcommand)]
cmd: ThemeCmd,
},
Keys {
#[command(subcommand)]
cmd: KeysCmd,
},
Profile {
#[command(subcommand)]
cmd: ProfileCmd,
},
}
#[derive(Debug, Args)]
pub struct HeadroomArgs {
#[arg(long, value_name = "SIZE", value_parser = parse_size, conflicts_with = "model")]
pub need: Option<u64>,
#[arg(long, value_name = "SIZE", value_parser = parse_size)]
pub gpu: Option<u64>,
#[arg(long, value_name = "PATH")]
pub model: Option<PathBuf>,
#[arg(long, value_name = "N", requires = "model")]
pub ctx: Option<u64>,
#[arg(long, value_name = "TYPE", default_value = "f16", requires = "model")]
pub kv_type: String,
#[arg(long, value_name = "N", default_value_t = 1, requires = "model")]
pub parallel: u64,
#[arg(long, value_enum, default_value_t = Offload::Auto, requires = "model")]
pub offload: Offload,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Args)]
pub struct ReclaimArgs {
#[arg(long)]
pub dry_run: bool,
#[arg(long)]
pub yes: bool,
#[arg(long, value_delimiter = ',', value_name = "IDS")]
pub groups: Vec<String>,
#[arg(long, default_value = "5s", value_parser = parse_interval)]
pub wait: Duration,
#[arg(long)]
pub json: bool,
}
#[derive(Debug, Subcommand)]
pub enum ConfigCmd {
Init {
#[arg(long)]
force: bool,
#[arg(long)]
print: bool,
},
Edit {
#[arg(long)]
host: bool,
},
Print {
#[arg(long)]
effective: bool,
#[arg(long)]
origin: bool,
#[arg(value_name = "KEY")]
key: Option<String>,
},
Validate,
Set {
key: String,
value: String,
#[arg(long, default_value = "user")]
layer: String,
},
Unset {
key: String,
#[arg(long, default_value = "user")]
layer: String,
},
Schema {
#[arg(default_value = "config")]
kind: String,
#[arg(long, value_name = "DIR")]
write: Option<PathBuf>,
},
}
#[derive(Debug, Subcommand)]
pub enum ThemeCmd {
List,
Preview {
name: Option<String>,
#[arg(long, value_parser = ["dark", "light"])]
variant: Option<String>,
},
Check {
name: String,
#[arg(long, value_parser = ["dark", "light"])]
variant: Option<String>,
},
Import {
file: PathBuf,
#[arg(long)]
name: Option<String>,
#[arg(long)]
force: bool,
#[arg(long)]
print: bool,
},
Export {
name: String,
#[arg(long, value_parser = ["dark", "light"])]
variant: Option<String>,
#[arg(long, short, value_name = "FILE")]
output: Option<PathBuf>,
},
}
#[derive(Debug, Subcommand)]
pub enum KeysCmd {
List {
#[arg(long)]
conflicts: bool,
#[arg(long)]
preset: Option<String>,
},
}
#[derive(Debug, Subcommand)]
pub enum ProfileCmd {
Show {
#[arg(long)]
json: bool,
},
Export,
Reset {
#[arg(long)]
yes: bool,
},
Stats {
#[arg(long)]
json: bool,
},
}
pub fn run<I, T>(args: I) -> i32
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let cli = match Cli::try_parse_from(args) {
Ok(c) => c,
Err(e) => {
let code = e.exit_code();
let _ = e.print();
return code;
}
};
match commands::dispatch(cli) {
Ok(code) => code,
Err(e) => {
if let Some(u) = e.downcast_ref::<commands::UsageError>() {
eprintln!("oomtop: {u}");
return oomtop_core::can_fit::EXIT_USAGE;
}
eprintln!("oomtop: {e:#}");
oomtop_core::can_fit::EXIT_ERROR
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
#[test]
fn cli_definition_is_valid() {
Cli::command().debug_assert();
}
#[test]
fn usage_errors_exit_2() {
assert_eq!(run(["oomtop", "headroom", "--need", "1G", "--model", "x"]), 2);
assert_eq!(run(["oomtop", "headroom", "--need", "banana"]), 2);
assert_eq!(
run(["oomtop", "headroom", "--ctx", "4096"]),
2,
"--ctx requires --model"
);
assert_eq!(run(["oomtop", "ndjson", "--interval", "0s"]), 2);
assert_eq!(
run([
"oomtop",
"ndjson",
"--interval",
"99999999999999999999s",
"--count",
"1"
]),
2
);
assert_eq!(
run([
"oomtop",
"reclaim",
"--dry-run",
"--wait",
"99999999999999999999s"
]),
2
);
assert_eq!(
run(["oomtop", "reclaim", "--dry-run", "--wait", "9000000000000000000s"]),
2
);
assert_eq!(run(["oomtop", "ndjson", "--interval", "400d"]), 2);
assert_eq!(run(["oomtop", "--color", "purple", "json"]), 2);
assert_eq!(run(["oomtop", "nope"]), 2);
assert_eq!(run(["oomtop", "--version"]), 0);
}
#[test]
fn value_parsers() {
assert_eq!(parse_size("13G").unwrap(), 13 << 30);
assert!(parse_size("13 bananas").is_err());
assert_eq!(parse_interval("500ms").unwrap(), Duration::from_millis(500));
assert!(parse_interval("-1s").is_err());
assert_eq!(parse_interval("366d").unwrap(), MAX_DURATION);
assert!(parse_interval("367d").unwrap_err().contains("too long"));
assert!(parse_interval("99999999999999999999s")
.unwrap_err()
.contains("too long"));
assert!(parse_interval(&format!("{}s", "9".repeat(400))).is_err());
}
#[test]
fn global_flags_anywhere() {
let c =
Cli::try_parse_from(["oomtop", "json", "--offline", "--set", "a.b=1", "--color", "256"]).unwrap();
assert!(c.global.offline);
assert_eq!(c.global.set, vec!["a.b=1"]);
assert_eq!(c.global.color, Some(ColorArg::C256));
}
}