pitboard-core 0.22.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
Documentation
//! A run of agy itself, `agy -p "/usage" --output-format json`, with one account's login in a
//! home of Pitboard's: what the account has left, and the login as agy left it, renewed where
//! its access token had lapsed (`agy_usage_command`). Pitboard sends Google nothing: agy asks.

use super::document;
use crate::context::Context;
use crate::duty::warm::run::{self as tool_run, Headless};
use crate::permit::Permit;
use crate::provider::{ProviderError, ProviderId};
use crate::time::{DAY, HOUR, WEEK};
use crate::usage::{LimitKind, Snapshot, Source, Window};
use serde_json::Value;

const GOOGLE: &str = "Google";

/// What a run is given of the login.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Plant {
    /// All of it, for a parked login, which agy may renew in the run's home.
    Whole,
    /// Its access token alone, for the login in use, which only agy renews where it keeps it.
    AccessOnly,
}

/// What a run came to.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Ran {
    pub(crate) usage: Snapshot,
    /// The login as agy left it, where it renewed it: the same account's, a new access token.
    pub(crate) left: Option<Value>,
}

/// Runs agy on `login` in a home of its own under Pitboard's directory, made afresh and removed
/// after, so nothing of the person's own agy is read or written and no keyring item is touched.
pub(crate) fn usage(
    ctx: &Context,
    permit: Permit,
    login: &Value,
    plant: Plant,
) -> Result<Ran, ProviderError> {
    let email = document::email(login).ok_or_else(|| ProviderError::ShapeUnexpected {
        provider: ProviderId::Agy,
        detail: "it names no account".into(),
    })?;
    let home = crate::home::dir(ctx)
        .join("runs")
        .join(format!("agy-{}", crate::store::fingerprint(email)));
    let failed = |e: std::io::Error| ProviderError::Network {
        service: GOOGLE,
        detail: format!("agy could not be run ({e})"),
    };
    tool_run::prepare(permit, &home).map_err(failed)?;
    let ran = plant_and_run(ctx, permit, &home, login, plant);
    let left = ran
        .as_ref()
        .ok()
        .and_then(|_| left_by_the_run(&home, login));
    tool_run::clear(permit, &home);
    let ran = ran.map_err(failed)?;
    if ran.timed_out {
        return Err(ProviderError::Network {
            service: GOOGLE,
            detail: "agy did not answer in time".into(),
        });
    }
    let usage = answered(&ran.stdout, ran.exit, ctx.now())?;
    Ok(Ran { usage, left })
}

fn plant_and_run(
    ctx: &Context,
    permit: Permit,
    home: &std::path::Path,
    login: &Value,
    plant: Plant,
) -> std::io::Result<tool_run::Ran> {
    let mut planted = login.clone();
    if plant == Plant::AccessOnly
        && let Some(token) = planted["token"].as_object_mut()
    {
        token.remove("refresh_token");
    }
    let file = cli_file_in(home);
    for dir in [
        file.parent().and_then(std::path::Path::parent),
        file.parent(),
    ]
    .into_iter()
    .flatten()
    {
        if !dir.is_dir() {
            crate::host::fs::create_private_dir(permit, dir)?;
        }
    }
    crate::atomic::write(
        permit,
        &file,
        planted.to_string().as_bytes(),
        crate::atomic::Perms::Secret,
    )?;
    let mut command = tool_run::command(ctx, permit, ProviderId::Agy, home)?;
    command
        .args(["-p", "/usage", "--output-format", "json"])
        .env("AGY_CLI_FORCE_FILE_TOKEN_STORAGE", "true");
    tool_run::run(
        ctx,
        permit,
        Headless {
            command,
            token: None,
        },
    )
}

// The CLI's own token file in the run's home, which `tool_run::command` makes its `HOME`.
fn cli_file_in(home: &std::path::Path) -> std::path::PathBuf {
    home.join("home")
        .join(".gemini")
        .join("antigravity-cli")
        .join("antigravity-oauth-token")
}

// Kept only where it is the same account's and agy changed it: a token it renewed.
fn left_by_the_run(home: &std::path::Path, planted: &Value) -> Option<Value> {
    let text = std::fs::read_to_string(cli_file_in(home)).ok()?;
    let left: Value = serde_json::from_str(&text).ok()?;
    let same_account = document::email(&left) == document::email(planted);
    let renewed = left["token"] != planted["token"] && document::has_token(&left);
    (same_account && renewed && document::refresh_token(&left).is_some()).then_some(left)
}

/// What agy's answer says, or why it gave none (`agy_usage_command`).
fn answered(stdout: &str, exit: Option<i32>, now: i64) -> Result<Snapshot, ProviderError> {
    let reply: Option<Value> = stdout
        .lines()
        .rev()
        .find(|line| !line.trim().is_empty())
        .and_then(|line| serde_json::from_str(line).ok());
    let said = reply
        .as_ref()
        .and_then(|reply| reply["error"].as_str())
        .unwrap_or_default()
        .to_owned();
    match exit {
        Some(0) => {}
        Some(2) => {
            return Err(ProviderError::Unsupported {
                provider: ProviderId::Agy,
                reason: format!("agy will not read this login's usage: {said}"),
            });
        }
        _ if said.contains("authentication") || said.contains("auth") => {
            return Err(ProviderError::Unauthorized);
        }
        other => {
            return Err(ProviderError::Network {
                service: GOOGLE,
                detail: match other {
                    Some(code) => format!("agy exited {code}: {said}"),
                    None => "agy was stopped".into(),
                },
            });
        }
    }
    let malformed = |detail: &str| ProviderError::Malformed {
        service: GOOGLE,
        detail: detail.to_owned(),
    };
    let reply = reply.ok_or_else(|| malformed("agy printed no JSON"))?;
    let groups = reply["command"]["data"]["groups"]
        .as_array()
        .ok_or_else(|| malformed("agy's answer holds no quota groups"))?;
    let windows = groups
        .iter()
        .flat_map(|group| group["buckets"].as_array().into_iter().flatten())
        .filter_map(window)
        .collect();
    Ok(Snapshot {
        windows,
        observed_at: Some(now),
        answered_at: Some(now),
        lists_every_limit: true,
        source: Source::Live,
    })
}

// A bucket as a window: what it has used of its fraction, when it resets, and how long it runs.
// One that is turned off, or counted in amounts rather than a share, is no window to draw.
fn window(bucket: &Value) -> Option<Window> {
    if bucket["disabled"].as_bool() == Some(true) {
        return None;
    }
    let remaining = bucket["remaining_fraction"].as_f64()?;
    let name = bucket["name"].as_str().unwrap_or_default();
    let length = bucket["window"].as_str().and_then(length_of);
    let kind = match length {
        Some(seconds) if seconds == 5 * HOUR => LimitKind::Session,
        Some(seconds) if seconds == WEEK => LimitKind::WeeklyAll,
        _ => LimitKind::Other(
            bucket["window"]
                .as_str()
                .filter(|window| !window.is_empty())
                .unwrap_or(name)
                .to_owned(),
        ),
    };
    Some(Window {
        kind,
        scope: Some(name.to_owned()).filter(|name| !name.is_empty()),
        percent: ((1.0 - remaining.clamp(0.0, 1.0)) * 100.0).clamp(0.0, 100.0),
        resets_at: bucket["reset_time"].as_str().and_then(crate::time::parse),
        is_active: true,
        severity: None,
        length_seconds: length,
    })
}

// How long a window agy names runs, in seconds: `5h`, `7d`, `1w`, `weekly`. The names agy gives
// are not measured, so one it is not read as is kept by its name.
fn length_of(window: &str) -> Option<i64> {
    let window = window.trim().to_ascii_lowercase();
    match window.as_str() {
        "weekly" | "week" => return Some(WEEK),
        "daily" | "day" => return Some(DAY),
        _ => {}
    }
    let digits: String = window.chars().take_while(char::is_ascii_digit).collect();
    let count: i64 = digits.parse().ok()?;
    let unit = window[digits.len()..].trim();
    let each = match unit {
        "h" | "hr" | "hour" | "hours" => HOUR,
        "d" | "day" | "days" => DAY,
        "w" | "wk" | "week" | "weeks" => WEEK,
        _ => return None,
    };
    Some(count * each)
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test plays agy, which renews the login in its home's file"
)]
mod tests {
    use super::*;
    use serde_json::json;

    // agy 1.5.19's shape (`agy_usage_command`), with the float32 a fraction comes as.
    fn reply(buckets: Value) -> String {
        json!({
            "conversation_id": "",
            "status": "SUCCESS",
            "response": "Gemini\tPro\t20%\t2026-11-29T12:00:00Z",
            "command": {"name": "usage", "data": {"groups": [{"name": "Gemini", "buckets": buckets}]}},
        })
        .to_string()
    }

    #[test]
    fn a_bucket_is_a_window_of_what_it_has_used() {
        let said = reply(json!([
            {"name": "Five hours", "window": "5h", "remaining_fraction": 0.800000011920929,
             "reset_time": "2026-11-29T12:00:00Z"},
            {"name": "Week", "window": "7d", "remaining_fraction": 0.25},
            {"name": "Credits", "remaining_amount": 40},
            {"name": "Off", "window": "5h", "remaining_fraction": 1.0, "disabled": true},
        ]));
        let snapshot = answered(&said, Some(0), 1_800_000_000).unwrap();
        assert_eq!(snapshot.windows.len(), 2, "{:?}", snapshot.windows);
        let five = &snapshot.windows[0];
        assert_eq!(five.kind, LimitKind::Session);
        assert!((five.percent - 20.0).abs() < 0.001, "{}", five.percent);
        assert_eq!(five.resets_at, crate::time::parse("2026-11-29T12:00:00Z"));
        assert_eq!(five.scope.as_deref(), Some("Five hours"));
        assert_eq!(snapshot.windows[1].kind, LimitKind::WeeklyAll);
        assert!((snapshot.windows[1].percent - 75.0).abs() < 0.001);
        assert!(snapshot.lists_every_limit);
        assert_eq!(snapshot.answered_at, Some(1_800_000_000));
    }

    #[test]
    fn a_window_agy_names_otherwise_is_kept_by_its_name() {
        let said = reply(json!([{"name": "Pro", "window": "monthly", "remaining_fraction": 0.5}]));
        let snapshot = answered(&said, Some(0), 0).unwrap();
        assert_eq!(snapshot.windows[0].kind, LimitKind::Other("monthly".into()));
        assert_eq!(length_of("5 hours"), Some(5 * HOUR));
        assert_eq!(length_of("1w"), Some(WEEK));
        assert_eq!(length_of("weekly"), Some(WEEK));
        assert_eq!(length_of("soon"), None);
    }

    // agy as a test plays it: it answers, and renews the login in its home where it was whole.
    #[derive(Debug)]
    struct Agy {
        renews: bool,
    }

    impl tool_run::WarmScript for Agy {
        fn run(&self, started: &tool_run::Started) -> tool_run::Ran {
            assert_eq!(started.args, ["-p", "/usage", "--output-format", "json"]);
            let env = |name: &str| {
                started
                    .env
                    .iter()
                    .find(|(n, _)| n == name)
                    .map(|(_, v)| v.clone())
            };
            assert_eq!(
                env("AGY_CLI_FORCE_FILE_TOKEN_STORAGE").as_deref(),
                Some("true")
            );
            let file = std::path::PathBuf::from(env("HOME").expect("a home of its own"))
                .join(".gemini/antigravity-cli/antigravity-oauth-token");
            let mut login: Value =
                serde_json::from_str(&std::fs::read_to_string(&file).expect("planted")).unwrap();
            if self.renews && login["token"]["refresh_token"].is_string() {
                login["token"]["access_token"] = json!("renewed");
                std::fs::write(&file, login.to_string()).unwrap();
            }
            tool_run::Ran {
                exit: Some(0),
                stdout: reply(json!([{"name": "Pro", "window": "5h", "remaining_fraction": 0.5}])),
                timed_out: false,
            }
        }
    }

    #[test]
    fn a_run_reads_usage_and_brings_back_what_it_renewed_and_leaves_nothing() {
        let home = tempfile::tempdir().unwrap();
        let program = super::super::program_for_a_test(home.path());
        let m = crate::context::ScratchMachine::at(home.path(), |ctx| {
            ctx.with_warm_script(std::sync::Arc::new(Agy { renews: true }))
                .with_agy_program(program)
        });
        let login = super::super::login_for_a_test("a@example.com", "a", "r");
        let ran = usage(&m.ctx, Permit::for_a_test(), &login, Plant::Whole).unwrap();
        assert_eq!(ran.usage.windows.len(), 1);
        let left = ran.left.expect("renewed");
        assert_eq!(left["token"]["access_token"], "renewed");
        assert_eq!(left["token"]["refresh_token"], "r");
        let runs = crate::home::dir(&m.ctx).join("runs");
        assert!(
            std::fs::read_dir(&runs).unwrap().next().is_none(),
            "nothing left"
        );

        // The login in use is given no refresh token, so the run can renew nothing of it.
        let ran = usage(&m.ctx, Permit::for_a_test(), &login, Plant::AccessOnly).unwrap();
        assert_eq!(ran.left, None);
    }

    #[test]
    fn why_agy_gave_no_answer_is_said_as_its_exit_says() {
        let error = json!({"status": "ERROR", "error": "authentication failed or timed out"});
        assert!(matches!(
            answered(&error.to_string(), Some(1), 0),
            Err(ProviderError::Unauthorized)
        ));
        let error = json!({"status": "ERROR", "error": "retrieving quota summary: 503"});
        assert!(matches!(
            answered(&error.to_string(), Some(1), 0),
            Err(ProviderError::Network { .. })
        ));
        assert!(matches!(
            answered("", Some(2), 0),
            Err(ProviderError::Unsupported { .. })
        ));
        assert!(matches!(
            answered("not json", Some(0), 0),
            Err(ProviderError::Malformed { .. })
        ));
    }
}