rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Antigravity quota for `/limits`, read from `agy usage --json`.
//!
//! agy 1.5.22 added `agy usage`. Its JSON names model groups that share a
//! 5-hour and a weekly bucket, each with the fraction left and a reset time.
//! The whole call took 1.2 s (agy 1.5.22, three runs) and printed 2 KB.

use std::time::Duration;

use serde::Deserialize;

use crate::{
    cli_runtime::{run_bounded_probe, CliExecutable},
    session_environment::Ambient,
    usage_limits::{ProviderUsageLimits, UsageLimitWindow, UsageLimitsError},
};

/// `/limits` section label.
pub(crate) const PROVIDER: &str = "Antigravity";

/// Spawn to exit: 1.2 s measured, so only a hung agy reaches this.
const USAGE_BUDGET: Duration = Duration::from_secs(10);

const USAGE_ARGS: &[&str] = &["usage", "--json"];

/// `agy` on this process's `PATH`, which `/limits` also runs it in. Sign-in
/// is agy's own, so an installed agy is what makes the section show.
pub(crate) fn installed() -> Option<CliExecutable> {
    // cargo test must not run the real agy from `/limits`; `fetch` is
    // covered with a fake binary.
    if cfg!(test) {
        return None;
    }
    super::executable::resolve(&Ambient::ThisProcess).ok()
}

/// The section's windows, or `None` without an installed agy.
pub(crate) async fn fetch_limits() -> Result<Option<ProviderUsageLimits>, UsageLimitsError> {
    let Some(agy) = installed() else {
        return Ok(None);
    };
    Ok(Some(ProviderUsageLimits {
        provider: PROVIDER.into(),
        windows: fetch(&agy).await?,
    }))
}

/// Runs `agy usage --json` and returns its buckets as `/limits` rows.
async fn fetch(agy: &CliExecutable) -> Result<Vec<UsageLimitWindow>, UsageLimitsError> {
    let failed = |detail: String| UsageLimitsError::Command {
        provider: PROVIDER,
        detail,
    };
    let output = run_bounded_probe(agy, USAGE_ARGS, USAGE_BUDGET)
        .await
        .map_err(|error| failed(error.to_string()))?;
    if !output.status.success() {
        return Err(failed(format!(
            "`agy usage` exited with {}: {}",
            output.status,
            output.stderr_lossy_trimmed()
        )));
    }
    parse(&output.stdout).map_err(failed)
}

/// `agy usage --json` stdout → rows: each group's 5-hour bucket, then its
/// weekly one, in agy's group order.
fn parse(stdout: &[u8]) -> Result<Vec<UsageLimitWindow>, String> {
    let report: UsageReport = serde_json::from_slice(stdout)
        .map_err(|error| format!("could not read `agy usage --json`: {error}"))?;
    if report.status != "SUCCESS" {
        return Err(format!("`agy usage` reported status {}", report.status));
    }
    let mut windows = Vec::new();
    for group in report.command.data.groups {
        let group_label = group_label(&group.name);
        let mut buckets = group.buckets;
        buckets.sort_by(|a, b| a.window.cmp(&b.window));
        windows.extend(buckets.into_iter().map(|bucket| UsageLimitWindow {
            label: format!("{group_label} {}", bucket.window.label()),
            remaining_percent: Some((bucket.remaining_fraction * 100.0).clamp(0.0, 100.0)),
            resets_at_unix: reset_unix(&bucket.reset_time),
            note: None,
        }));
    }
    Ok(windows)
}

/// "Gemini Models" → "Gemini"; "Claude and GPT models" → "Claude and GPT".
fn group_label(name: &str) -> &str {
    let name = name.trim();
    name.strip_suffix(" Models")
        .or_else(|| name.strip_suffix(" models"))
        .unwrap_or(name)
}

/// A bucket's `window`. Declaration order is row order: 5-hour before
/// weekly, as the other `/limits` sections show them.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(from = "String")]
enum BucketWindow {
    FiveHour,
    Weekly,
    Other(String),
}

impl From<String> for BucketWindow {
    fn from(window: String) -> Self {
        match window.as_str() {
            "5h" => Self::FiveHour,
            "weekly" => Self::Weekly,
            _ => Self::Other(window),
        }
    }
}

impl BucketWindow {
    fn label(&self) -> &str {
        match self {
            Self::FiveHour => "5-hour",
            Self::Weekly => "Weekly",
            Self::Other(window) => window,
        }
    }
}

/// agy stamps a bucket nothing has drawn from with the Unix epoch.
fn reset_unix(reset_time: &str) -> Option<i64> {
    chrono::DateTime::parse_from_rfc3339(reset_time)
        .ok()
        .map(|reset| reset.timestamp())
        .filter(|&unix| unix > 0)
}

#[derive(Deserialize)]
struct UsageReport {
    status: String,
    command: UsageCommand,
}

#[derive(Deserialize)]
struct UsageCommand {
    data: UsageData,
}

#[derive(Deserialize)]
struct UsageData {
    groups: Vec<UsageGroup>,
}

#[derive(Deserialize)]
struct UsageGroup {
    name: String,
    buckets: Vec<UsageBucket>,
}

#[derive(Deserialize)]
struct UsageBucket {
    window: BucketWindow,
    remaining_fraction: f64,
    reset_time: String,
}

#[cfg(test)]
#[path = "usage_tests.rs"]
mod tests;