agentmux_srv_core/backend/
account_usage.rs1use 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
31pub const SETTING_NOTICE_AT: &str = "agent:usagenoticeat";
33pub const DEFAULT_NOTICE_AT: u64 = 75; pub const SETTING_NOTICE_HIGH_AT: &str = "agent:usagenoticehighat";
36pub const DEFAULT_NOTICE_HIGH_AT: u64 = 90; #[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
40#[ts(export, export_to = "../../../frontend/types/rpc/")]
41pub struct UsageWindow {
42 pub used_percent: f64,
44 #[ts(type = "number")]
46 pub resets_at_ms: u64,
47 #[ts(type = "number")]
49 pub observed_at_ms: u64,
50 #[ts(type = "number")]
52 pub age_ms: u64,
53}
54
55#[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 Reported,
62 NotYet,
65 NotReported,
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
71#[ts(export, export_to = "../../../frontend/types/rpc/")]
72pub struct AccountUsage {
73 pub status: UsageStatus,
74 pub windows: BTreeMap<String, UsageWindow>,
76}
77
78impl AccountUsage {
79 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
90pub 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 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
105pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
107 let _ = CONFIG.set(config);
108}
109
110fn 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
116pub 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#[derive(Debug, Clone, PartialEq)]
136pub struct Crossing {
137 pub window: String,
138 pub threshold: u64,
140 pub used_percent: f64,
141 pub resets_at_ms: u64,
142}
143
144pub 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 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
178pub 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
193fn 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
198pub 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
219pub(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
237fn 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
244fn 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
253pub(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 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;