rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The structured `/usage` report Claude prints in stream-json mode.
//!
//! `claude -p /usage --output-format stream-json --verbose` sends, beside the
//! panel text, a `usage_report` whose `rate_limits` are the claude.ai usage
//! endpoint's rows as the server sent them. The Agent SDK types it as
//! `SDKUsageReport` (marked experimental; Agent SDK 0.3.333) and says to
//! classify a row on its `kind`, never its label. `rate_limits` is null while
//! the usage fetch fails, never a snapshot of an earlier reply, so its rows
//! are always live.

use serde::Deserialize;

use super::window_kind::WindowKind;
use crate::cli_runtime::stream_effect::RateLimitInfo;

/// `usage_report.rate_limits`.
#[derive(Debug, Deserialize)]
pub(crate) struct ReportedLimits {
    /// Empty when the server reports no meters; null when its body carried
    /// no rows at all (a server that predates them).
    #[serde(default)]
    limits: Option<Vec<ReportedLimit>>,
    #[serde(default)]
    extra_usage: Option<ReportedExtraUsage>,
}

/// One server usage row.
#[derive(Debug, Deserialize)]
struct ReportedLimit {
    /// `session`, `weekly_all`, `weekly_scoped`, or a newer meter.
    kind: String,
    /// Share of the window used, 0-100.
    percent: f64,
    /// ISO 8601.
    #[serde(default)]
    resets_at: Option<String>,
    #[serde(default)]
    scope: Option<ReportedScope>,
    /// The server's grade: `normal`, `warning`, `critical`.
    #[serde(default)]
    severity: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ReportedScope {
    #[serde(default)]
    model: Option<DisplayName>,
    #[serde(default)]
    surface: Option<DisplayName>,
}

#[derive(Debug, Deserialize)]
struct DisplayName {
    display_name: String,
}

/// Overage spend; amounts in minor units of the plan's currency.
#[derive(Debug, Deserialize)]
struct ReportedExtraUsage {
    is_enabled: bool,
    #[serde(default)]
    monthly_limit: Option<f64>,
    #[serde(default)]
    used_credits: Option<f64>,
}

impl ReportedLimits {
    /// Rows as rate-limit windows keyed like stream observations, plus extra
    /// usage when it is on and has a limit. `None` when the server sent no
    /// rows at all, which says nothing about the cached windows; an empty
    /// row list means the plan has no meters now.
    pub(crate) fn windows(self) -> Option<Vec<RateLimitInfo>> {
        let mut windows: Vec<RateLimitInfo> = self
            .limits?
            .into_iter()
            .map(ReportedLimit::window)
            .collect();
        if let Some(extra) = self.extra_usage.and_then(ReportedExtraUsage::window) {
            windows.push(extra);
        }
        Some(windows)
    }
}

impl ReportedLimit {
    fn window(self) -> RateLimitInfo {
        let kind = match self.kind.as_str() {
            "session" => WindowKind::FiveHour,
            "weekly_all" => WindowKind::SevenDay,
            "weekly_scoped" => {
                let scope = self.scope.and_then(|scope| scope.model.or(scope.surface));
                WindowKind::from_week_scope(
                    &scope.map_or_else(String::new, |name| name.display_name),
                )
            }
            other => WindowKind::Other(other.to_owned()),
        };
        RateLimitInfo {
            // `notable_rate_limit_status` shows any status but `allowed`.
            status: self.severity.filter(|severity| severity != "normal"),
            rate_limit_type: Some(kind.key().to_owned()),
            resets_at: self.resets_at.as_deref().and_then(|resets_at| {
                chrono::DateTime::parse_from_rfc3339(resets_at)
                    .ok()
                    .map(|reset| reset.timestamp())
            }),
            utilization: Some(self.percent.clamp(0.0, 100.0) / 100.0),
            overage_status: None,
            overage_resets_at: None,
            is_using_overage: None,
        }
    }
}

impl ReportedExtraUsage {
    fn window(self) -> Option<RateLimitInfo> {
        let limit = self.monthly_limit.filter(|limit| *limit > 0.0)?;
        if !self.is_enabled {
            return None;
        }
        Some(RateLimitInfo {
            status: None,
            rate_limit_type: Some(WindowKind::ExtraUsage.key().to_owned()),
            resets_at: None,
            utilization: Some((self.used_credits.unwrap_or(0.0) / limit).clamp(0.0, 1.0)),
            overage_status: None,
            overage_resets_at: None,
            is_using_overage: None,
        })
    }
}