Skip to main content

agent_commander/
usage_windows.rs

1//! Normalized usage windows (issue #57).
2//!
3//! Claude Code streams `rate_limit_event.rate_limit_info` (one window per
4//! event, `utilization` as a 0-1 fraction). Codex reports
5//! `rate_limits.{primary,secondary}` in rollout `token_count` events
6//! (`used_percent`, `window_minutes`, `resets_at`) and in app-server
7//! `account/rateLimits/*` (`usedPercent`, `windowDurationMins`, `resetsAt`).
8//! Both become one [`UsageWindow`] shape; `resets_at` stays in epoch seconds
9//! like `limit_resets_at`.
10
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::BTreeMap;
14
15const SESSION_MINS: u64 = 5 * 60;
16const WEEK_MINS: u64 = 7 * 24 * 60;
17const MONTH_MINS: u64 = 30 * 24 * 60;
18
19/// Window kinds, shortest first.
20pub const USAGE_WINDOW_KINDS: &[&str] = &["session", "weekly", "monthly", "other"];
21
22/// One provider usage window
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct UsageWindow {
26    /// Native window name (`five_hour`, `seven_day_opus`, `primary`, ...)
27    pub id: String,
28    /// `session`, `weekly`, `monthly` or `other`
29    pub kind: String,
30    pub label: String,
31    /// Used share of the window, 0-100
32    pub used_percent: f64,
33    /// Reset epoch in seconds
34    pub resets_at: Option<i64>,
35    pub window_duration_mins: Option<u64>,
36}
37
38fn finite(value: Option<&Value>) -> Option<f64> {
39    let number = match value? {
40        Value::Number(number) => number.as_f64(),
41        Value::String(text) => text.trim().parse::<f64>().ok(),
42        _ => None,
43    }?;
44    number.is_finite().then_some(number)
45}
46
47/// Clamp to 0-100 and round to 4 decimals (0.41 * 100 is 41.00000000000001).
48fn clamp_percent(value: f64) -> f64 {
49    (value.clamp(0.0, 100.0) * 1e4).round() / 1e4
50}
51
52#[allow(clippy::cast_possible_truncation)]
53fn epoch_seconds(value: Option<&Value>) -> Option<i64> {
54    finite(value)
55        .filter(|seconds| *seconds > 0.0)
56        .map(|seconds| seconds as i64)
57}
58
59fn label_for(kind: &str) -> &'static str {
60    match kind {
61        "session" => "Session",
62        "weekly" => "Weekly",
63        "monthly" => "Monthly",
64        _ => "Other",
65    }
66}
67
68fn make_window(
69    id: &str,
70    kind: &str,
71    label: Option<String>,
72    used_percent: f64,
73    resets_at: Option<&Value>,
74    mins: Option<u64>,
75) -> UsageWindow {
76    UsageWindow {
77        id: id.to_string(),
78        kind: kind.to_string(),
79        label: label.unwrap_or_else(|| label_for(kind).to_string()),
80        used_percent: clamp_percent(used_percent),
81        resets_at: epoch_seconds(resets_at),
82        window_duration_mins: mins,
83    }
84}
85
86/// Normalize one Claude `rate_limit_info`.
87///
88/// `five_hour` is the session window and every `seven_day*` type (all
89/// models, per-model, overage-included) is a weekly window keyed by its type.
90pub fn claude_rate_limit_windows(info: Option<&Value>) -> Vec<UsageWindow> {
91    let Some(info) = info.filter(|info| info.is_object()) else {
92        return Vec::new();
93    };
94    let kind = info.get("rateLimitType").and_then(Value::as_str);
95    let (Some(kind), Some(utilization)) = (
96        kind.filter(|kind| !kind.is_empty()),
97        finite(info.get("utilization")),
98    ) else {
99        return Vec::new();
100    };
101    let resets_at = info.get("resetsAt");
102    let used = utilization * 100.0;
103    let window = if kind.starts_with("five_hour") {
104        make_window(kind, "session", None, used, resets_at, Some(SESSION_MINS))
105    } else if let Some(scope) = kind.strip_prefix("seven_day") {
106        let scope = scope.strip_prefix('_').unwrap_or(scope);
107        let label = if scope.is_empty() {
108            "Weekly".to_string()
109        } else {
110            format!("Weekly ยท {scope}")
111        };
112        make_window(
113            kind,
114            "weekly",
115            Some(label),
116            used,
117            resets_at,
118            Some(WEEK_MINS),
119        )
120    } else {
121        make_window(kind, "other", Some(kind.to_string()), used, resets_at, None)
122    };
123    vec![window]
124}
125
126const fn kind_for_minutes(mins: u64) -> &'static str {
127    if mins >= MONTH_MINS {
128        "monthly"
129    } else if mins >= WEEK_MINS {
130        "weekly"
131    } else {
132        "session"
133    }
134}
135
136fn either<'a>(value: &'a Value, snake: &str, camel: &str) -> Option<&'a Value> {
137    value
138        .get(snake)
139        .filter(|item| !item.is_null())
140        .or_else(|| value.get(camel))
141}
142
143/// Normalize a Codex `rate_limits` snapshot (rollout snake_case or
144/// app-server camelCase).
145///
146/// `primary` / `secondary` are positions, not durations: without a window
147/// length, paid plans mean 5 hours / 1 week and Free or Go plans a monthly
148/// primary allowance. Snapshots of another `limit_id` are skipped.
149#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
150pub fn codex_rate_limit_windows(snapshot: Option<&Value>) -> Vec<UsageWindow> {
151    let Some(snapshot) = snapshot.filter(|snapshot| snapshot.is_object()) else {
152        return Vec::new();
153    };
154    let limit_id = either(snapshot, "limit_id", "limitId").and_then(Value::as_str);
155    if limit_id.is_some_and(|id| !id.is_empty() && id != "codex") {
156        return Vec::new();
157    }
158    let plan = either(snapshot, "plan_type", "planType").and_then(Value::as_str);
159    let monthly_plan = matches!(plan, Some("free" | "go"));
160    let positions = [
161        (
162            "primary",
163            if monthly_plan {
164                MONTH_MINS
165            } else {
166                SESSION_MINS
167            },
168        ),
169        ("secondary", WEEK_MINS),
170    ];
171    let mut windows = Vec::new();
172    for (id, fallback) in positions {
173        let Some(window) = snapshot.get(id).filter(|window| window.is_object()) else {
174            continue;
175        };
176        let Some(used) = finite(either(window, "used_percent", "usedPercent")) else {
177            continue;
178        };
179        let mins = finite(either(window, "window_minutes", "windowDurationMins"))
180            .map_or(fallback, |mins| mins.max(0.0) as u64);
181        windows.push(make_window(
182            id,
183            kind_for_minutes(mins),
184            None,
185            used,
186            either(window, "resets_at", "resetsAt"),
187            Some(mins),
188        ));
189    }
190    windows
191}
192
193fn kind_rank(kind: &str) -> usize {
194    USAGE_WINDOW_KINDS
195        .iter()
196        .position(|known| *known == kind)
197        .unwrap_or(USAGE_WINDOW_KINDS.len())
198}
199
200/// Merge a partial update into known windows by `id`.
201///
202/// Windows the update omits are kept (Claude names one window per event),
203/// and so is a known reset the update leaves out. Sorted by kind, then id.
204pub fn merge_usage_windows(windows: &[UsageWindow], update: &[UsageWindow]) -> Vec<UsageWindow> {
205    let mut by_id: BTreeMap<String, UsageWindow> = windows
206        .iter()
207        .map(|window| (window.id.clone(), window.clone()))
208        .collect();
209    for window in update {
210        let resets_at = window
211            .resets_at
212            .or_else(|| by_id.get(&window.id).and_then(|known| known.resets_at));
213        by_id.insert(
214            window.id.clone(),
215            UsageWindow {
216                resets_at,
217                ..window.clone()
218            },
219        );
220    }
221    let mut merged: Vec<UsageWindow> = by_id.into_values().collect();
222    merged.sort_by(|a, b| {
223        kind_rank(&a.kind)
224            .cmp(&kind_rank(&b.kind))
225            .then_with(|| a.id.cmp(&b.id))
226    });
227    merged
228}
229
230/// The windows one stream or rollout message carries.
231pub fn usage_windows_from_message(message: &Value) -> Vec<UsageWindow> {
232    if !message.is_object() {
233        return Vec::new();
234    }
235    if message.get("type").and_then(Value::as_str) == Some("rate_limit_event") {
236        return claude_rate_limit_windows(message.get("rate_limit_info"));
237    }
238    let snapshot = message
239        .get("rate_limits")
240        .or_else(|| message.pointer("/payload/rate_limits"))
241        .or_else(|| message.pointer("/params/rateLimits"))
242        .or_else(|| message.get("rateLimits"));
243    codex_rate_limit_windows(snapshot)
244}
245
246/// Fold every usage window a run reported, newest value per window.
247pub fn extract_usage_windows(messages: &[Value]) -> Vec<UsageWindow> {
248    messages.iter().fold(Vec::new(), |windows, message| {
249        merge_usage_windows(&windows, &usage_windows_from_message(message))
250    })
251}