Skip to main content

agentmux_srv_core/backend/
account_usage.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How much of an account's usage windows is used, from the report Claude Code sends with every
5//! request.
6//!
7//! Every request's `rate_limit_event` frame carries
8//! `rate_limit_info.unifiedWindows.<window>.{utilization, resetsAt}` for each plan window
9//! (`five_hour`, `seven_day`, ...), whatever its `status` (CLI 2.1.301: `utilization` is a fraction
10//! from 0 to 1, `resetsAt` is unix seconds). Every agent on one account reports the same windows, so
11//! the readings are kept per **account**, not per pane: the newest frame from any pane wins, a pane
12//! closing loses nothing, and a window's reading is dropped once its reset has passed.
13//!
14//! A reading that crosses a notice threshold (`agent:usagenoticeat`, `agent:usagenoticehighat`; a
15//! percent of the window, 0 turns one off) gives the leaders of the account's agents one
16//! `[AgentMux]` note, once per window per threshold. The note is held for the leader's next turn or
17//! joins the turn it is in: it never starts one.
18//!
19//! Providers other than Claude report nothing here; [`UsageStatus::NotReported`] says so.
20
21use std::collections::{BTreeMap, HashMap};
22use std::sync::{Arc, LazyLock, OnceLock};
23
24use serde::Serialize;
25use serde_json::Value;
26
27use crate::backend::agent_state::RUN_ACCOUNT_META_KEY;
28use crate::backend::obj::{self, Block};
29use crate::backend::storage::store::Store;
30
31/// `agent:usagenoticeat`: the percent of a usage window from which the account's leaders get a note.
32pub const SETTING_NOTICE_AT: &str = "agent:usagenoticeat";
33pub const DEFAULT_NOTICE_AT: u64 = 75; // plain digits: settings-defaults.test.ts reads it
34/// `agent:usagenoticehighat`: the percent from which they get a second, stronger one.
35pub const SETTING_NOTICE_HIGH_AT: &str = "agent:usagenoticehighat";
36pub const DEFAULT_NOTICE_HIGH_AT: u64 = 90; // plain digits, as above
37
38/// One window's latest reading for an account.
39#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
40#[ts(export, export_to = "../../../frontend/types/rpc/")]
41pub struct UsageWindow {
42    /// How much of the window is used, 0 to 100 (it may pass 100 when the limit is hit).
43    pub used_percent: f64,
44    /// When the window resets (unix ms).
45    #[ts(type = "number")]
46    pub resets_at_ms: u64,
47    /// When this reading was taken (unix ms).
48    #[ts(type = "number")]
49    pub observed_at_ms: u64,
50    /// How old the reading is now.
51    #[ts(type = "number")]
52    pub age_ms: u64,
53}
54
55/// Whether an account's usage is known.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
57#[ts(export, export_to = "../../../frontend/types/rpc/")]
58#[serde(rename_all = "snake_case")]
59pub enum UsageStatus {
60    /// At least one window has a reading that has not reset.
61    Reported,
62    /// A provider that reports usage, with no reading yet (nothing has run on the account since
63    /// srv started, or its windows have reset).
64    NotYet,
65    /// A provider whose CLI reports nothing srv reads.
66    NotReported,
67}
68
69/// An account's usage as an agent or a window reads it.
70#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
71#[ts(export, export_to = "../../../frontend/types/rpc/")]
72pub struct AccountUsage {
73    pub status: UsageStatus,
74    /// By the provider's name for the window (`five_hour`, `seven_day`, ...).
75    pub windows: BTreeMap<String, UsageWindow>,
76}
77
78impl AccountUsage {
79    /// What `provider`'s account at `now_ms` reads.
80    pub fn of(provider: &str, account_id: &str, now_ms: u64) -> Self {
81        if !reports_usage(provider) {
82            return Self { status: UsageStatus::NotReported, windows: BTreeMap::new() };
83        }
84        let windows = of_account(account_id, now_ms);
85        let status = if windows.is_empty() { UsageStatus::NotYet } else { UsageStatus::Reported };
86        Self { status, windows }
87    }
88}
89
90/// Whether the provider's CLI reports usage windows that srv reads: Claude's `rate_limit_event`.
91/// Codex and Gemini report nothing srv reads, so their accounts say `not_reported`.
92pub fn reports_usage(provider: &str) -> bool {
93    provider.eq_ignore_ascii_case("claude") || provider.eq_ignore_ascii_case("anthropic")
94}
95
96struct Entry {
97    reading: UsageWindow,
98    /// The thresholds already told for this window's current reset (bit 0: the first, bit 1: the high one).
99    told: u8,
100}
101
102static BY_ACCOUNT: LazyLock<parking_lot::Mutex<HashMap<String, HashMap<String, Entry>>>> = LazyLock::new(Default::default);
103static CONFIG: OnceLock<Arc<crate::backend::wconfig::ConfigState>> = OnceLock::new();
104
105/// Attach the live settings (bootstrap), so the notice thresholds can be read.
106pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
107    let _ = CONFIG.set(config);
108}
109
110/// The two notice thresholds, in percent; 0 is off.
111fn thresholds() -> [u64; 2] {
112    let read = |key: &str, default: u64| CONFIG.get().and_then(|c| c.extra_u64(key)).unwrap_or(default);
113    [read(SETTING_NOTICE_AT, DEFAULT_NOTICE_AT), read(SETTING_NOTICE_HIGH_AT, DEFAULT_NOTICE_HIGH_AT)]
114}
115
116/// The windows a `rate_limit_event` frame reports: name, utilization (0 to 1) and reset (unix
117/// seconds). Empty for any other frame, and for a window with no utilization.
118pub fn windows_of_frame(frame: &Value) -> Vec<(String, f64, u64)> {
119    if frame.get("type").and_then(Value::as_str) != Some("rate_limit_event") {
120        return Vec::new();
121    }
122    let Some(windows) = frame.pointer("/rate_limit_info/unifiedWindows").and_then(Value::as_object) else {
123        return Vec::new();
124    };
125    windows
126        .iter()
127        .filter_map(|(name, w)| {
128            let utilization = w.get("utilization").and_then(Value::as_f64).filter(|u| u.is_finite() && *u >= 0.0)?;
129            Some((name.clone(), utilization, w.get("resetsAt").and_then(Value::as_u64)?))
130        })
131        .collect()
132}
133
134/// A threshold a reading has newly crossed.
135#[derive(Debug, Clone, PartialEq)]
136pub struct Crossing {
137    pub window: String,
138    /// The threshold, in percent.
139    pub threshold: u64,
140    pub used_percent: f64,
141    pub resets_at_ms: u64,
142}
143
144/// Keep `windows` (from [`windows_of_frame`]) as `account`'s latest at `now_ms`, and say which
145/// thresholds they newly cross. A reading for a window that resets earlier than the one kept is a
146/// frame from the window before: ignored. A later reset is a new window, and tells again.
147pub fn observe(account: &str, windows: &[(String, f64, u64)], now_ms: u64) -> Vec<Crossing> {
148    let limits = thresholds();
149    let mut by_account = BY_ACCOUNT.lock();
150    let kept = by_account.entry(account.to_string()).or_default();
151    let mut out = Vec::new();
152    for (name, utilization, resets_at_s) in windows {
153        let resets_at_ms = resets_at_s.saturating_mul(1000);
154        let used_percent = utilization * 100.0;
155        let told = match kept.get(name) {
156            Some(old) if old.reading.resets_at_ms > resets_at_ms => continue,
157            Some(old) if old.reading.resets_at_ms == resets_at_ms => old.told,
158            _ => 0,
159        };
160        let mut told = told;
161        // The highest threshold crossed and not yet told; a jump over both says only the high one.
162        let mut crossed = None;
163        for (bit, limit) in limits.iter().enumerate() {
164            if *limit > 0 && used_percent >= *limit as f64 && told & (1 << bit) == 0 {
165                told |= 1 << bit;
166                crossed = Some(*limit);
167            }
168        }
169        if let Some(threshold) = crossed {
170            out.push(Crossing { window: name.clone(), threshold, used_percent, resets_at_ms });
171        }
172        let reading = UsageWindow { used_percent, resets_at_ms, observed_at_ms: now_ms, age_ms: 0 };
173        kept.insert(name.clone(), Entry { reading, told });
174    }
175    out
176}
177
178/// `account`'s windows that have not reset at `now_ms`, with their age.
179pub fn of_account(account: &str, now_ms: u64) -> BTreeMap<String, UsageWindow> {
180    let mut by_account = BY_ACCOUNT.lock();
181    let Some(kept) = by_account.get_mut(account) else { return BTreeMap::new() };
182    kept.retain(|_, e| e.reading.resets_at_ms > now_ms);
183    let out = kept
184        .iter()
185        .map(|(name, e)| (name.clone(), UsageWindow { age_ms: now_ms.saturating_sub(e.reading.observed_at_ms), ..e.reading.clone() }))
186        .collect();
187    if kept.is_empty() {
188        by_account.remove(account);
189    }
190    out
191}
192
193/// The account a pane's run launched on.
194fn account_of(block: &Block) -> Option<String> {
195    block.meta.get(RUN_ACCOUNT_META_KEY).and_then(|a| a.as_str()).filter(|a| !a.is_empty()).map(str::to_string)
196}
197
198/// Any frame of `block_id`'s CLI: a `rate_limit_event` with usage is kept for the pane's account, and
199/// its leaders told when it crosses a threshold. The persistent stdout reader calls it for every
200/// frame; anything else returns at once.
201pub fn observe_claude_frame(block_id: &str, store: &Arc<Store>, frame: &Value) {
202    let windows = windows_of_frame(frame);
203    if windows.is_empty() {
204        return;
205    }
206    let Some(account) = store.get::<Block>(block_id).ok().flatten().as_ref().and_then(account_of) else { return };
207    let crossings = observe(&account, &windows, agentmux_common::time::now_ms_u64());
208    if crossings.is_empty() {
209        return;
210    }
211    let store = Arc::clone(store);
212    tokio::task::spawn_blocking(move || {
213        for crossing in &crossings {
214            notify_leaders(&store, &account, crossing);
215        }
216    });
217}
218
219/// The panes that hear of a crossing: for each live agent pane on `account`, its lead's first open
220/// pane on this machine, or the pane itself when it has none (it reports to the person). Each once.
221pub(crate) fn note_targets(store: &Store, account: &str) -> Vec<String> {
222    let blocks = store.get_all::<Block>().unwrap_or_default();
223    let mut targets: Vec<String> = Vec::new();
224    for block in blocks.iter().filter(|b| account_of(b).as_deref() == Some(account)) {
225        let def_id = obj::meta_get_string(&block.meta, "agentId", "");
226        if def_id.is_empty() || super::blockcontroller::get_controller(&block.oid).is_none() {
227            continue;
228        }
229        let target = super::worker_notes::leader_pane_of(store, &def_id).unwrap_or_else(|| block.oid.clone());
230        if !targets.contains(&target) {
231            targets.push(target);
232        }
233    }
234    targets
235}
236
237/// "Sat 3:10 PM", in this machine's time zone.
238fn local_label(ms: u64) -> String {
239    chrono::DateTime::from_timestamp_millis(ms as i64)
240        .map(|t| t.with_timezone(&chrono::Local).format("%a %-I:%M %p").to_string())
241        .unwrap_or_default()
242}
243
244/// What a window is called to a reader.
245fn window_words(window: &str) -> String {
246    match window {
247        "five_hour" => "5-hour".to_string(),
248        "seven_day" => "weekly".to_string(),
249        other => other.replace('_', " "),
250    }
251}
252
253/// The note's body (the `[AgentMux]` prefix is added by the sender).
254pub(crate) fn note_body(crossing: &Crossing) -> String {
255    let used = crossing.used_percent.floor();
256    let advice = if crossing.used_percent >= 90.0 {
257        "At 100% every agent on it stops until the reset: finish what is running and hold new work that can wait."
258    } else {
259        "Slow work that can wait; at 100% every agent on it stops until the reset."
260    };
261    format!(
262        "An account that some of your agents run on has used {used}% of its {} usage window (it resets {}). {advice} \
263         Read it any time with Identity accounts.",
264        window_words(&crossing.window),
265        local_label(crossing.resets_at_ms),
266    )
267}
268
269fn notify_leaders(store: &Store, account: &str, crossing: &Crossing) {
270    let targets = note_targets(store, account);
271    let body = note_body(crossing);
272    let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(&body));
273    // One key per window: the high note replaces the first one if it has not been read yet.
274    let key = format!("usage-{}", crossing.window);
275    for block in &targets {
276        super::blockcontroller::system_note_into_turn_or_hold(block, &key, &text);
277    }
278}
279
280#[cfg(test)]
281#[path = "account_usage_tests.rs"]
282mod tests;