swarmy 0.2.12

Real-time analytics dashboard for coding agents (Claude Code, Antigravity, Codex): live swarm, history, API-equivalent spend, weekly limits, and a vault for OAuth logins
Documentation
//! `swarmy guard`: Claude Code's `PreToolUse` hook (`swarmy setup --guard`) that keeps agents
//! within the limit lines the user set (`[guard]` in config.toml).
//!
//! Claude Code runs it before every tool call in a guarded seat, subagents included. Hooks are
//! not given the limits, but the status line is: `swarmy statusline` keeps the exact numbers of
//! each response in `<data>/statusline/<seat id>.json`, naming their account. The guard reads
//! those files (no index, no scan, a few small files) and decides with `core::guard`:
//!
//! - below the wrap-up zone: nothing, the call goes on;
//! - in it: the call goes on, and each agent is told once to wrap up;
//! - at the line: the call is refused, and the agent is asked to write where it stopped; an
//!   agent that calls a tool after that has its turn stopped (`continue: false`). Calls made
//!   with the refused one (a model often calls several tools at once) are refused too, so the
//!   agent still gets to write its summary.
//!
//! It never stands in the way by mistake: anything it cannot read lets the call go on. The only
//! files it writes are its own marks of what it already told whom, in `<data>/guard/`.

pub mod input;

use std::path::Path;

use chrono::{DateTime, Duration, Local, Utc};
use serde_json::json;

use crate::config::{Config, Dirs};
use crate::core::guard::{Crossing, Lines, State};
use crate::core::ids::{AccountId, SeatId};
use crate::core::limits::{Reading, WindowKind};
use crate::core::units::Pct;
use crate::statusline::reading;
use crate::vault::Login;
use input::HookInput;

/// How long a mark of what an agent was told is kept: past the longest window.
const MARKS_KEPT_DAYS: i64 = 8;

/// Calls this soon after an agent's first refusal are refused again rather than ending its
/// turn: they came in the same response (parallel tool calls, verified on Claude Code 2.1.337,
/// where the turn otherwise ended before the agent could write where it stopped). A call after
/// the agent read the refusal needs another response, which takes longer; one refused twice
/// still does not run.
const STOP_GRACE_S: i64 = 10;

/// What the guard answers Claude Code.
#[derive(Debug, Clone, PartialEq)]
pub enum Answer {
    /// Nothing: the call goes on as usual.
    Go,
    /// The call goes on; the agent reads `context`, the user sees `user`.
    WrapUp { context: String, user: String },
    /// The call is refused; the agent reads `reason`.
    Refuse { reason: String },
    /// The call is refused and the turn ends; the user sees `user`.
    StopTurn { reason: String, user: String },
}

impl Answer {
    /// The hook's output (Claude Code's hook JSON), or nothing to print.
    pub fn json(&self) -> Option<String> {
        let deny = |reason: &str| {
            json!({
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": reason,
            })
        };
        let v = match self {
            Answer::Go => return None,
            Answer::WrapUp { context, user } => json!({
                "systemMessage": user,
                "hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": context},
            }),
            Answer::Refuse { reason } => json!({"hookSpecificOutput": deny(reason)}),
            Answer::StopTurn { reason, user } => json!({
                "continue": false,
                "stopReason": user,
                "hookSpecificOutput": deny(reason),
            }),
        };
        Some(v.to_string())
    }
}

/// `swarmy guard`: the answer for the Claude Code that runs us (its seat from
/// `CLAUDE_CONFIG_DIR`). `bypass` (`SWARMY_GUARD=off`) lets everything through.
pub fn run(dirs: &Dirs, config: &Config, stdin: &str, now: DateTime<Utc>, bypass: bool) -> Answer {
    if bypass || !config.guard.is_set() {
        return Answer::Go;
    }
    let seat = crate::claude::seats::seat_id(&crate::statusline::current_config_dir(&dirs.home));
    decide(dirs, config, &seat, &input::parse(stdin), now)
}

/// The answer for a call in `seat`.
pub fn decide(
    dirs: &Dirs,
    config: &Config,
    seat: &SeatId,
    input: &HookInput,
    now: DateTime<Utc>,
) -> Answer {
    let Some((account, readings)) = seat_readings(&dirs.data, &dirs.vault_dir(), seat) else {
        return Answer::Go;
    };
    let vault = dirs.vault_dir();
    // The saved logins name accounts; read only when a name is needed.
    let logins = || {
        crate::vault::saved_logins(&vault).unwrap_or_else(|e| {
            crate::diag::log("guard", &format!("vault unreadable: {e:#}"));
            Vec::new()
        })
    };
    let mut known: Option<Vec<Login>> = None;
    let lines = if config.guard.account.is_empty() {
        config.guard.lines_for(&[])
    } else {
        let l = known.get_or_insert_with(&logins);
        lines_of(&account, config, l)
    };
    let v = crate::core::guard::verdict(&readings, &lines, now);
    let Some(c) = v.crossing else {
        return Answer::Go;
    };
    let label = label_of(&account, config, known.get_or_insert_with(&logins));
    let marks = dirs.data.join("guard");
    let who = input.who();
    match v.state {
        State::Go => Answer::Go,
        State::WrapUp => {
            if !matches!(mark(&marks, &who, "wrap", &c, now), Mark::New) {
                return Answer::Go;
            }
            Answer::WrapUp {
                context: format!(
                    "swarmy guard: account {label} has used {} of its {}; the user stops agents at {} \
                     (resets {}). Finish the step you are on, leave the work where someone can \
                     pick it up, and write down briefly what is done and what is left. Tools stop \
                     working at {}.",
                    pct(c.used),
                    window(c.kind),
                    pct(c.line),
                    when(c.resets_at),
                    pct(c.line),
                ),
                user: format!(
                    "swarmy guard: {label} {} used {} · agents stop at {}",
                    window(c.kind),
                    pct(c.used),
                    pct(c.line)
                ),
            }
        }
        State::Stop => {
            let reason = format!(
                "swarmy guard: account {label} has used {} of its {}, at or past the {} line the \
                 user set (resets {}). Do not call any more tools. Reply with a short summary: \
                 what is done, what is left, and where to pick up.",
                pct(c.used),
                window(c.kind),
                pct(c.line),
                when(c.resets_at),
            );
            let just_refused = match mark(&marks, &who, "stop", &c, now) {
                Mark::New => true,
                // Unreadable: being written by a call made at the same moment.
                Mark::Made(at) => at.is_none_or(|t| now - t < Duration::seconds(STOP_GRACE_S)),
            };
            if just_refused {
                return Answer::Refuse { reason };
            }
            Answer::StopTurn {
                reason,
                user: format!(
                    "swarmy guard: {label} {} used {}, line {} (resets {}). To go on: put another \
                     login into this seat (S in swarmy, or swarmy accounts switch), raise the line \
                     in config.toml [guard], or start Claude Code with SWARMY_GUARD=off.",
                    window(c.kind),
                    pct(c.used),
                    pct(c.line),
                    when(c.resets_at),
                ),
            }
        }
    }
}

/// The account a seat's last status-line reading names, and that account's newest reading of
/// each window from every seat's file (seats on one account share its limit). None when the
/// seat has no reading, or the vault switched its login after it: those numbers are another
/// account's, and the next response brings the new one's.
fn seat_readings(data: &Path, vault: &Path, seat: &SeatId) -> Option<(AccountId, Vec<Reading>)> {
    let own_file = reading::file_of(data, seat);
    let own = reading::read(&own_file)?;
    match crate::vault::last_switch(vault, seat) {
        Ok(Some(sw)) if sw.at > own.at => return None,
        Ok(_) => {}
        Err(e) => {
            crate::diag::log("guard", &format!("vault unreadable: {e:#}"));
            return None;
        }
    }
    let mut all = own.readings();
    if let Ok(entries) = std::fs::read_dir(data.join("statusline")) {
        for path in entries.flatten().map(|e| e.path()) {
            if path == own_file || path.extension().is_none_or(|x| x != "json") {
                continue;
            }
            // `fleet.json` lives here too; it is no reading and reads as none.
            if let Some(l) = reading::read(&path).filter(|l| l.account == own.account) {
                all.extend(l.readings());
            }
        }
    }
    Some((own.account, newest_per_kind(all)))
}

fn newest_per_kind(readings: Vec<Reading>) -> Vec<Reading> {
    let mut out: Vec<Reading> = Vec::new();
    for r in readings {
        match out.iter_mut().find(|o| o.kind == r.kind) {
            Some(o) if o.fetched_at < r.fetched_at => *o = r,
            Some(_) => {}
            None => out.push(r),
        }
    }
    out
}

/// The names an account goes by, for the keys of `[guard.account.*]`: its id and uuids, its
/// `[accounts]` name, and the labels and emails of the saved logins of it.
pub fn names_of(id: &AccountId, config: &Config, logins: &[Login]) -> Vec<String> {
    let mut names = vec![id.as_str().to_string(), id.user_uuid().to_string()];
    names.extend(id.org_uuid().map(str::to_string));
    for (uuid, name) in &config.accounts {
        if uuid == id.as_str() || uuid == id.user_uuid() {
            names.push(name.clone());
        }
    }
    for l in logins.iter().filter(|l| login_of(l, id)) {
        names.push(l.label.clone());
        names.extend(l.email.clone());
    }
    names
}

/// The lines in force for an account.
pub fn lines_of(id: &AccountId, config: &Config, logins: &[Login]) -> Lines {
    config.guard.lines_for(&names_of(id, config, logins))
}

/// How the guard names an account to the agent and the user: its `[accounts]` name, else a
/// saved login's label, else its email, else its short id.
pub fn label_of(id: &AccountId, config: &Config, logins: &[Login]) -> String {
    let configured = config
        .accounts
        .iter()
        .find(|(uuid, _)| *uuid == id.as_str() || *uuid == id.user_uuid())
        .map(|(_, name)| name.clone());
    let saved = || logins.iter().find(|l| login_of(l, id));
    configured
        .or_else(|| saved().map(|l| l.label.clone()))
        .or_else(|| saved().and_then(|l| l.email.clone()))
        .unwrap_or_else(|| format!("acct-{}", crate::core::ids::short_account(id.as_str())))
}

/// A saved login of the account: the same id, or the same user when the login's account was
/// saved without its organization.
fn login_of(l: &Login, id: &AccountId) -> bool {
    l.account_uuid.as_deref().is_some_and(|a| {
        let a = AccountId::new(a);
        a == *id || (!a.has_org() && a.user_uuid() == id.user_uuid())
    })
}

/// Whether this agent was told `what` in this window before.
enum Mark {
    /// No: the mark is made now.
    New,
    /// Yes, at that time (none when the mark cannot be read).
    Made(Option<DateTime<Utc>>),
}

/// The mark that says this agent heard `what` in this window, made here when missing (holding
/// the time it was made). Two calls at once make it once (`create_new`). A mark that cannot be
/// made tells again next time: better twice than never.
fn mark(dir: &Path, who: &(String, String), what: &str, c: &Crossing, now: DateTime<Utc>) -> Mark {
    let name = format!(
        "{}.{}.{what}.{}.{}",
        who.0,
        who.1,
        c.kind.key(),
        c.resets_at.timestamp()
    );
    let path = dir.join(name);
    if let Err(e) = std::fs::create_dir_all(dir) {
        crate::diag::log("guard", &format!("cannot make {}: {e}", dir.display()));
        return Mark::New;
    }
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
    {
        Ok(mut f) => {
            if let Err(e) = std::io::Write::write_all(&mut f, now.to_rfc3339().as_bytes()) {
                crate::diag::log("guard", &format!("cannot write {}: {e}", path.display()));
            }
            prune(dir, now);
            Mark::New
        }
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Mark::Made(
            std::fs::read_to_string(&path)
                .ok()
                .and_then(|t| DateTime::parse_from_rfc3339(t.trim()).ok())
                .map(|t| t.with_timezone(&Utc)),
        ),
        Err(e) => {
            crate::diag::log("guard", &format!("cannot write {}: {e}", path.display()));
            Mark::New
        }
    }
}

/// Marks older than the longest window go; run only when a mark is made, which is rare.
fn prune(dir: &Path, now: DateTime<Utc>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    let cutoff = now - Duration::days(MARKS_KEPT_DAYS);
    for e in entries.flatten() {
        let old = e
            .metadata()
            .and_then(|m| m.modified())
            .is_ok_and(|t| DateTime::<Utc>::from(t) < cutoff);
        if old && let Err(err) = std::fs::remove_file(e.path()) {
            crate::diag::log("guard", &format!("cannot remove an old mark: {err}"));
        }
    }
}

/// The window as the dashboard says it: "week", "5-hour".
fn window(kind: WindowKind) -> &'static str {
    match kind {
        WindowKind::SevenDay => "week",
        WindowKind::FiveHour => "5-hour window",
        WindowKind::SevenDayOpus | WindowKind::SevenDaySonnet => kind.label(),
    }
}

/// `85%`, `84.6%`.
fn pct(p: Pct) -> String {
    let s = format!("{:.1}", p.get());
    format!("{}%", s.strip_suffix(".0").unwrap_or(&s))
}

fn when(t: DateTime<Utc>) -> String {
    t.with_timezone(&Local).format("%a %H:%M").to_string()
}

#[cfg(test)]
mod tests;