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.
";
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() {
"while" | "--" if words.is_empty() => {
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(),
[] | ["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)
}
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."
))
}
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())
}
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))
}
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),
}
}
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)?
}
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::<()>();
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,
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();
}
}
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(" ")
);
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)))
}
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()
}
}
fn ai_sample(watch: &mut ai::Watch) -> Option<String> {
let (seen, gpu, cpu) = activity::look();
watch.sample(activity::now(), &seen, gpu, cpu)
}
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);
}
}
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 "))
}