1pub 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
21pub 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
26pub const MAX_DURATION: Duration = Duration::from_secs(366 * 86_400);
29
30pub 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#[derive(Debug, Clone, Default, Args)]
64pub struct GlobalOpts {
65 #[arg(long, global = true, env = "OOMTOP_CONFIG", value_name = "PATH")]
67 pub config: Option<PathBuf>,
68 #[arg(long, global = true)]
70 pub no_learn: bool,
71 #[arg(long, global = true)]
73 pub plain: bool,
74 #[arg(long, global = true)]
76 pub ascii: bool,
77 #[arg(long, global = true, value_name = "NAME")]
79 pub theme: Option<String>,
80 #[arg(long, global = true, value_enum, value_name = "DEPTH")]
82 pub color: Option<ColorArg>,
83 #[arg(long, global = true)]
85 pub offline: bool,
86 #[arg(long, global = true, value_name = "FIXTURE")]
88 pub replay: Option<PathBuf>,
89 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
119pub enum Offload {
120 #[default]
122 Auto,
123 Gpu,
125 Cpu,
127}
128
129#[derive(Debug, Subcommand)]
130pub enum Cmd {
131 Headroom(HeadroomArgs),
133 Why {
135 #[arg(long)]
136 json: bool,
137 },
138 Reclaim(ReclaimArgs),
140 Stale {
142 #[arg(long)]
143 json: bool,
144 #[arg(long, value_name = "N", default_value_t = 10)]
146 limit: usize,
147 },
148 Sandboxes {
150 #[arg(long)]
151 json: bool,
152 },
153 Ns {
155 #[arg(long)]
156 json: bool,
157 },
158 Ports {
160 #[arg(long)]
161 json: bool,
162 #[arg(long)]
164 exposed: bool,
165 #[arg(long)]
167 links: bool,
168 },
169 Models {
171 #[arg(long)]
172 json: bool,
173 #[arg(long)]
175 no_hash: bool,
176 },
177 Json {
179 #[arg(long)]
181 compact: bool,
182 },
183 Ndjson {
185 #[arg(long, default_value = "2s", value_parser = parse_interval)]
187 interval: Duration,
188 #[arg(long, value_name = "N")]
190 count: Option<u64>,
191 #[arg(long, hide = true)]
193 discard: bool,
194 },
195 Serve {
197 #[arg(long, value_name = "ADDR")]
199 listen: Option<String>,
200 #[arg(long = "allow-host", value_name = "NAME")]
203 allow_host: Vec<String>,
204 #[arg(long, hide = true)]
206 max_requests: Option<usize>,
207 },
208 Mcp {
210 #[arg(long)]
212 allow_actions: bool,
213 },
214 Doctor {
216 #[arg(long)]
217 json: bool,
218 #[arg(long)]
220 no_probe: bool,
221 },
222 Config {
224 #[command(subcommand)]
225 cmd: ConfigCmd,
226 },
227 Theme {
229 #[command(subcommand)]
230 cmd: ThemeCmd,
231 },
232 Keys {
234 #[command(subcommand)]
235 cmd: KeysCmd,
236 },
237 Profile {
239 #[command(subcommand)]
240 cmd: ProfileCmd,
241 },
242}
243
244#[derive(Debug, Args)]
245pub struct HeadroomArgs {
246 #[arg(long, value_name = "SIZE", value_parser = parse_size, conflicts_with = "model")]
248 pub need: Option<u64>,
249 #[arg(long, value_name = "SIZE", value_parser = parse_size)]
251 pub gpu: Option<u64>,
252 #[arg(long, value_name = "PATH")]
254 pub model: Option<PathBuf>,
255 #[arg(long, value_name = "N", requires = "model")]
257 pub ctx: Option<u64>,
258 #[arg(long, value_name = "TYPE", default_value = "f16", requires = "model")]
260 pub kv_type: String,
261 #[arg(long, value_name = "N", default_value_t = 1, requires = "model")]
263 pub parallel: u64,
264 #[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 #[arg(long)]
275 pub dry_run: bool,
276 #[arg(long)]
278 pub yes: bool,
279 #[arg(long, value_delimiter = ',', value_name = "IDS")]
281 pub groups: Vec<String>,
282 #[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 Init {
293 #[arg(long)]
295 force: bool,
296 #[arg(long)]
298 print: bool,
299 },
300 Edit {
302 #[arg(long)]
303 host: bool,
304 },
305 Print {
307 #[arg(long)]
309 effective: bool,
310 #[arg(long)]
312 origin: bool,
313 #[arg(value_name = "KEY")]
315 key: Option<String>,
316 },
317 Validate,
319 Set {
321 key: String,
322 value: String,
323 #[arg(long, default_value = "user")]
325 layer: String,
326 },
327 Unset {
329 key: String,
330 #[arg(long, default_value = "user")]
331 layer: String,
332 },
333 Schema {
335 #[arg(default_value = "config")]
336 kind: String,
337 #[arg(long, value_name = "DIR")]
339 write: Option<PathBuf>,
340 },
341}
342
343#[derive(Debug, Subcommand)]
344pub enum ThemeCmd {
345 List,
347 Preview {
349 name: Option<String>,
351 #[arg(long, value_parser = ["dark", "light"])]
353 variant: Option<String>,
354 },
355 Check {
357 name: String,
358 #[arg(long, value_parser = ["dark", "light"])]
359 variant: Option<String>,
360 },
361 Import {
363 file: PathBuf,
364 #[arg(long)]
366 name: Option<String>,
367 #[arg(long)]
369 force: bool,
370 #[arg(long)]
372 print: bool,
373 },
374 Export {
376 name: String,
377 #[arg(long, value_parser = ["dark", "light"])]
378 variant: Option<String>,
379 #[arg(long, short, value_name = "FILE")]
381 output: Option<PathBuf>,
382 },
383}
384
385#[derive(Debug, Subcommand)]
386pub enum KeysCmd {
387 List {
389 #[arg(long)]
391 conflicts: bool,
392 #[arg(long)]
394 preset: Option<String>,
395 },
396}
397
398#[derive(Debug, Subcommand)]
399pub enum ProfileCmd {
400 Show {
402 #[arg(long)]
403 json: bool,
404 },
405 Export,
407 Reset {
409 #[arg(long)]
410 yes: bool,
411 },
412 Stats {
414 #[arg(long)]
415 json: bool,
416 },
417}
418
419pub 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 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}