marathon-cli 0.1.3

Keep your Mac awake while AI agents and local models work. The `marathon` command.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! `marathon`: keep your Mac awake from the command line.
//!
//! `on` and `off` talk to whoever is serving: the menu bar app if it is
//! running, otherwise a small background holder this command starts and
//! that exits by itself once the session ends.

use std::io::{BufRead, BufReader, Write};
use std::os::unix::process::CommandExt;
use std::process::{Command, ExitCode, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use marathon_core::protocol::{Holder, Reply, Request, Status, from_line, to_line};
use marathon_core::rules::Rules;
use marathon_core::{Mode, TimeZone, Timestamp, Until, ai, format_clock, format_remaining};
use marathon_engine::Engine;
use marathon_engine::ipc::{self, Server};
use marathon_engine::store;
use marathon_power::Assertion;
use marathon_sensors::activity;

const HELP: &str = "\
marathon: keep your Mac awake.

  marathon on                  stay awake until you turn it off
  marathon on 2h               stay awake for 2 hours (or 45m, 1h30m, 90)
  marathon on until 6pm        stay awake until 6 PM (or 17:30)
  marathon off                 let the Mac sleep again
  marathon status              say what Marathon is doing

  marathon while COMMAND       stay awake while a command runs, then stop:
    marathon while claude          for your whole Claude Code session
    marathon while npm run build   until the build finishes

  marathon ai on               stay awake while AI agents or local models work
  marathon ai off              stop doing that
  marathon ai check            show which AI tools are running and how busy

Add --display-sleep-ok to on or while to let the screen turn off while the
Mac stays awake. `marathon help on` explains one command in more detail.
";

/// Help for one command, for `marathon help CMD` and `marathon CMD --help`.
fn command_help(cmd: &str) -> Option<&'static str> {
    Some(match cmd {
        "on" | "start" => {
            "\
marathon on              stay awake until `marathon off`
marathon on 2h           stay awake for a while: 45m, 2h, 1h30m, or 90 (minutes)
marathon on until 6pm    stay awake until a time: 6pm, 17:30 (tomorrow if past)

Running it again replaces the current one. Add --display-sleep-ok to let the
screen turn off while the Mac stays awake.
"
        }
        "off" | "stop" => {
            "\
marathon off

Let the Mac sleep normally again. Does nothing if Marathon is already off.
"
        }
        "toggle" => {
            "\
marathon toggle [2h]

Turn Marathon off if it is on, and on if it is off. Handy for one keyboard
shortcut.
"
        }
        "status" => {
            "\
marathon status

Say whether Marathon is on, how long is left, and why. Add --json for
scripts. Plain `marathon` does the same.
"
        }
        "while" | "--" | "run" => {
            "\
marathon while COMMAND

Run COMMAND and keep the Mac awake until it finishes. Marathon passes on the
command's exit code, and if Marathon is stopped the Mac may sleep again.

  marathon while claude              for your whole Claude Code session
  marathon while npm run build       until the build finishes
  marathon while ollama pull llama3  until the model has downloaded
  marathon while --display-sleep-ok rsync -a ~/Photos /Volumes/Backup
"
        }
        "ai" => {
            "\
marathon ai on       stay awake while AI works, in the menu bar app
marathon ai off      stop doing that
marathon ai check    show which AI tools are running and how busy

It covers coding agents (Claude Code, Codex, Cursor, Gemini, Grok, opencode,
pi, Aider, …) and local models (Ollama, llama.cpp, MLX, LM Studio, oMLX,
vLLM, …), including ones you install later. It counts them only while they
are actually working, not just open, and lets the Mac sleep after 15 quiet
minutes with the whole Mac under 10% CPU. Change those numbers, or pick just
agents or just local AI, in the menu bar app's Triggers window.
"
        }
        _ => return None,
    })
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match run(args) {
        Ok(code) => code,
        Err(msg) => {
            eprintln!("marathon: {msg}");
            ExitCode::from(2)
        }
    }
}

fn run(args: Vec<String>) -> Result<ExitCode, String> {
    let mut mode = Mode::Display;
    let mut json = false;
    let mut help = false;
    let mut words = Vec::new();
    let mut command = None;
    for (i, a) in args.iter().enumerate() {
        match a.as_str() {
            // Everything after `while` (or the older `--`) is the command.
            "while" | "--" if words.is_empty() => {
                // The screen option may also come right after `while`.
                let mut rest = &args[i + 1..];
                while let Some(("--display-sleep-ok" | "-s", tail)) =
                    rest.split_first().map(|(a, t)| (a.as_str(), t))
                {
                    mode = Mode::System;
                    rest = tail;
                }
                command = Some(rest.to_vec());
                break;
            }
            "--display-sleep-ok" | "-s" => mode = Mode::System,
            "--json" => json = true,
            "-h" | "--help" => help = true,
            "-V" | "--version" => {
                println!("marathon {}", env!("CARGO_PKG_VERSION"));
                return Ok(ExitCode::SUCCESS);
            }
            "__serve" => serve(args.get(1).map(String::as_str)),
            s if s.starts_with('-') => return Err(format!("unknown option {s}; see --help")),
            _ => words.push(a.as_str()),
        }
    }
    if help || words.first() == Some(&"help") {
        let topic = match words.as_slice() {
            ["help", cmd, ..] => Some(*cmd),
            [cmd, ..] if *cmd != "help" => Some(*cmd),
            _ if command.is_some() => Some("while"),
            _ => None,
        };
        print!("{}", topic.and_then(command_help).unwrap_or(HELP));
        return Ok(ExitCode::SUCCESS);
    }
    if let Some(command) = command {
        return run_command(mode, &command);
    }
    let (verb, rest) = words
        .split_first()
        .map_or(("status", &[][..]), |(v, r)| (*v, r));
    let status = match verb {
        "on" | "start" => turn_on(mode, rest)?,
        "off" | "stop" => no_extra(rest).and_then(|()| turn_off())?,
        "toggle" => match ask(&Request::Status)? {
            Some(s) if s.active => turn_off()?,
            _ => turn_on(mode, rest)?,
        },
        "ai" => {
            return match rest {
                ["on"] => set_ai(true),
                ["off"] => set_ai(false),
                ["check"] => check_ai(),
                // The older foreground watcher, for scripts that use it.
                [] | ["watch"] => watch_ai(mode),
                [w, ..] => Err(format!(
                    "unexpected {w:?}; try `marathon ai on`, `off` or `check`"
                )),
            };
        }
        "status" => no_extra(rest)
            .and_then(|()| ask(&Request::Status))?
            .unwrap_or_else(Status::idle),
        other => return Err(format!("unknown command {other:?}; see --help")),
    };
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&status).map_err(|e| e.to_string())?
        );
    } else {
        println!("{}", describe(&status));
        if verb == "status" {
            let rules = store::load::<Rules>(&store::rules_path()).unwrap_or_default();
            if let Some(ai) = ai_summary(&rules) {
                println!("{ai}");
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// What AI-aware mode watches, if anything, for `marathon status`.
fn ai_summary(rules: &Rules) -> Option<String> {
    let what = match (rules.ai_agents, rules.ai_local) {
        (true, true) => "AI agents and local AI",
        (true, false) => "AI agents",
        (false, true) => "local AI",
        (false, false) => return None,
    };
    Some(format!(
        "AI-aware mode is on: it keeps the Mac awake while {what} work."
    ))
}

/// Opens the menu bar app, if it is installed. Not with a custom
/// `MARATHON_DIR`, which the app doesn't use.
fn open_app() -> bool {
    if std::env::var_os("MARATHON_DIR").is_some() {
        return false;
    }
    Command::new("/usr/bin/open")
        .args(["-g", "-b", "com.github.abe238.marathon"])
        .stderr(Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// `marathon ai on|off`: turns AI-aware mode on or off in the menu bar
/// app, for both agents and local AI.
fn set_ai(on: bool) -> Result<ExitCode, String> {
    let path = store::rules_path();
    let mut rules: Rules = store::load(&path).unwrap_or_default();
    rules.ai_agents = on;
    rules.ai_local = on;
    store::save(&path, &rules).map_err(|e| format!("can't save the setting: {e}"))?;
    let app_running =
        matches!(ask(&Request::RulesChanged)?, Some(s) if s.holder == Some(Holder::App));
    if !on {
        println!("AI-aware mode is off.");
    } else if app_running {
        println!("AI-aware mode is on: the Mac stays awake while AI agents or local models work.");
    } else if open_app() {
        println!(
            "AI-aware mode is on. Opened the Marathon menu bar app, which keeps the Mac awake \
             while AI agents or local models work."
        );
    } else {
        println!(
            "AI-aware mode is on, and works while the Marathon menu bar app runs. To watch \
             from this terminal instead, run `marathon ai watch`."
        );
    }
    Ok(ExitCode::SUCCESS)
}

fn no_extra(rest: &[&str]) -> Result<(), String> {
    match rest.first() {
        None => Ok(()),
        Some(w) => Err(format!("unexpected {w:?}")),
    }
}

fn turn_on(mode: Mode, rest: &[&str]) -> Result<Status, String> {
    let until = if rest.is_empty() {
        None
    } else {
        Until::parse(&rest.join(" "))
            .map_err(|e| e.to_string())?
            .resolve(Timestamp::now(), &TimeZone::system())
    };
    let req = Request::On {
        mode,
        until,
        source: "cli".into(),
    };
    match ask(&req)? {
        Some(status) => Ok(status),
        None => start_holder(&req),
    }
}

fn turn_off() -> Result<Status, String> {
    Ok(ask(&Request::Off)?.unwrap_or_else(Status::idle))
}

/// Sends `req` to the running server; `None` when nothing is serving.
fn ask(req: &Request) -> Result<Option<Status>, String> {
    match ipc::request(req) {
        Err(e) if ipc::is_no_server(&e) => Ok(None),
        Err(e) => Err(format!("can't reach the Marathon service: {e}")),
        Ok(reply) => reply.map(Some),
    }
}

/// Starts the background holder with `req` as its first request and
/// returns its reply, which it writes to the pipe once it is serving.
fn start_holder(req: &Request) -> Result<Status, String> {
    let exe = std::env::current_exe().map_err(|e| e.to_string())?;
    let mut child = Command::new(exe)
        .arg("__serve")
        .arg(to_line(req).trim_end())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .process_group(0)
        .spawn()
        .map_err(|e| format!("can't start the background holder: {e}"))?;
    let mut line = String::new();
    let out = child
        .stdout
        .take()
        .ok_or("no pipe to the background holder")?;
    BufReader::new(out)
        .read_line(&mut line)
        .map_err(|e| e.to_string())?;
    if line.is_empty() {
        return Err("the background holder exited without answering".into());
    }
    from_line::<Reply>(&line)?
}

/// The hidden `__serve REQUEST` mode: answer `REQUEST`, then keep serving
/// until no session is left.
fn serve(first: Option<&str>) -> ! {
    let reply_and_exit = |reply: Reply| -> ! {
        print!("{}", to_line(&reply));
        let _ = std::io::stdout().flush();
        std::process::exit(0)
    };
    let req = match first.map(from_line::<Request>) {
        Some(Ok(req)) => req,
        Some(Err(e)) => reply_and_exit(Err(e)),
        None => reply_and_exit(Err("__serve needs a request".into())),
    };
    let (tx, rx) = mpsc::channel::<()>();
    // The state is saved while a session runs, so if the Mac crashes or
    // restarts the menu bar app brings it back. The engine removes it once
    // the session ends.
    let (engine, _) = Engine::with_state_file(
        Holder::Cli,
        Box::new(move |_| {
            let _ = tx.send(());
        }),
        store::state_path(),
    );
    let server = match Server::start(engine.clone(), Duration::ZERO) {
        Ok(server) => server,
        // Another process started serving first: pass the request on.
        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => reply_and_exit(forward(&req)),
        Err(e) => reply_and_exit(Err(format!("can't serve: {e}"))),
    };
    print!("{}", to_line(&engine.handle(req)));
    let _ = std::io::stdout().flush();
    loop {
        server.quiesce(|| {
            if !engine.status().active {
                std::process::exit(0)
            }
        });
        let _ = rx.recv();
    }
}

/// Sends `req` to the process that won the race to serve, waiting briefly
/// for it to finish binding its socket.
fn forward(req: &Request) -> Reply {
    let deadline = Instant::now() + Duration::from_secs(3);
    loop {
        match ipc::request(req) {
            Err(e) if ipc::is_no_server(&e) && Instant::now() < deadline => {
                std::thread::sleep(Duration::from_millis(10))
            }
            Err(e) => return Err(format!("can't reach the Marathon service: {e}")),
            Ok(reply) => return reply,
        }
    }
}

fn run_command(mode: Mode, argv: &[String]) -> Result<ExitCode, String> {
    let (program, args) = argv
        .split_first()
        .ok_or("give a command after `while`, like `marathon while cargo build`")?;
    let name = format!(
        "Marathon (command): {} while `{}` runs",
        mode.describe(),
        argv.join(" ")
    );
    // Held until this process exits, however it exits.
    let _held = Assertion::new(mode.assertion_type(), &name).map_err(|e| e.to_string())?;
    let status = Command::new(program)
        .args(args)
        .status()
        .map_err(|e| format!("can't run {program}: {e}"))?;
    Ok(ExitCode::from(exit_code(status)))
}

/// AI-aware mode's quiet period, from the triggers the app saved. The
/// command watches both categories, whichever the app's menu has on.
fn ai_settings() -> ai::Settings {
    let rules = store::load::<Rules>(&store::rules_path()).unwrap_or_default();
    ai::Settings {
        agents: true,
        local: true,
        ..rules.ai_settings()
    }
}

/// One look at the AI tools, the GPU and the Mac's CPU.
fn ai_sample(watch: &mut ai::Watch) -> Option<String> {
    let (seen, gpu, cpu) = activity::look();
    watch.sample(activity::now(), &seen, gpu, cpu)
}

/// `marathon ai`: holds an assertion while AI is working, until killed.
fn watch_ai(mode: Mode) -> Result<ExitCode, String> {
    let settings = ai_settings();
    let mut watch = ai::Watch::new(settings);
    let mut held: Option<(Assertion, String)> = None;
    println!(
        "Watching for AI at work (Ctrl-C to stop). {}. The Mac may sleep after {} with AI \
         tools quiet and the Mac under {:.0}% CPU.",
        mode.describe(),
        format_remaining(settings.grace),
        settings.idle_cpu * 100.0
    );
    loop {
        let reason = ai_sample(&mut watch);
        if reason != held.as_ref().map(|(_, r)| r.clone()) {
            let clock = format_clock(Timestamp::now(), &TimeZone::system());
            held = match reason {
                Some(r) => {
                    let name = format!("Marathon (ai): {} while {r}", mode.describe());
                    let a =
                        Assertion::new(mode.assertion_type(), &name).map_err(|e| e.to_string())?;
                    println!("{clock}  awake: {r}");
                    Some((a, r))
                }
                None => {
                    println!(
                        "{clock}  quiet for {}: the Mac may sleep",
                        format_remaining(settings.grace)
                    );
                    None
                }
            };
        }
        std::thread::sleep(ai::SAMPLE_EVERY);
    }
}

/// `marathon ai check`: one 3-second look, printed.
fn check_ai() -> Result<ExitCode, String> {
    let settings = ai_settings();
    let gap = Duration::from_secs(3);
    let mut watch = ai::Watch::new(settings);
    ai_sample(&mut watch);
    std::thread::sleep(gap);
    let after = activity::ai_processes();
    if after.is_empty() {
        println!("No AI tools running.");
    }
    for s in &after {
        let pct = watch.share(s, gap) * 100.0;
        println!("{:<15} pid {:<7} {pct:5.1}% CPU", s.tool.label, s.pid);
    }
    let gpu = activity::gpu_utilization();
    if let Some(g) = gpu {
        println!("{:<27} {g:4}% busy", "GPU");
    }
    let cpu = activity::cpu_ticks();
    if let Some(share) = cpu.and_then(|c| watch.system_share(c)) {
        println!("{:<27} {:4.0}% of all cores", "Whole Mac", share * 100.0);
    }
    let now = activity::now();
    match watch.sample(now, &after, gpu, cpu) {
        Some(r) => println!(
            "AI-aware mode would keep the Mac awake: {r}. It may sleep after {} of quiet \
             (AI tools idle, the Mac under {:.0}% CPU); countdown now: {}.",
            format_remaining(settings.grace),
            settings.idle_cpu * 100.0,
            watch.countdown(now).map_or("-".into(), format_remaining)
        ),
        None => println!("AI-aware mode would let the Mac sleep."),
    }
    Ok(ExitCode::SUCCESS)
}

fn exit_code(status: std::process::ExitStatus) -> u8 {
    use std::os::unix::process::ExitStatusExt;
    match (status.code(), status.signal()) {
        (Some(c), _) => c as u8,
        (None, Some(sig)) => 128u8.saturating_add(sig as u8),
        _ => 1,
    }
}

fn describe(s: &Status) -> String {
    if !s.active {
        let mut text = String::from("Off: your Mac sleeps normally.");
        if let Some(p) = &s.paused_trigger {
            text += &format!(" The trigger \"{p}\" is paused until that changes.");
        }
        if let Some(pct) = s.battery_low {
            text += &format!(" Marathon turned off at {pct}% battery to save power.");
        }
        return text;
    }
    let mut what = Vec::new();
    if let (Some(session), Some(when)) = (&s.session, s.time_left(&TimeZone::system())) {
        what.push(format!("{}, {when}", session.mode.describe()));
    }
    if let Some(t) = &s.trigger {
        what.push(format!("a trigger: {t}"));
    }
    if what.is_empty() {
        what.push("details unreadable; is the app a different version?".into());
    }
    let by = match (s.holder, s.pid) {
        (Some(Holder::App), _) => "the Marathon menu bar app".into(),
        (_, Some(pid)) => format!("a background helper (pid {pid})"),
        _ => "an unknown process".into(),
    };
    format!("On ({}). Held by {by}.", what.join("; and "))
}