Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(host): read Claude's exact usage resets and count a hit limit as used up
leepokai739965b1ee36
diff --git a/host/src/usage/claude.rs b/host/src/usage/claude.rsindex 852915dd..93db2ab0 100644--- a/host/src/usage/claude.rs+++ b/host/src/usage/claude.rs@@ -5,13 +5,15 @@ use serde_json::Value;use super::Window;-/// Flags for `claude -p /usage`. The empty strict MCP config keeps the check-/// from starting every MCP server the user has set up.-const USAGE_ARGS: [&str; 8] = [+/// Flags for `claude -p /usage`. Stream JSON carries the structured+/// `usage_report`. The empty strict MCP config keeps the check from starting+/// every MCP server the user has set up.+const USAGE_ARGS: [&str; 9] = ["-p","/usage","--output-format",- "json",+ "stream-json",+ "--verbose","--no-session-persistence","--strict-mcp-config","--mcp-config",@@ -33,11 +35,40 @@ pub(super) async fn collect() -> Option<Vec<Window>> {.await.ok()?.ok()?;- let v: Value = serde_json::from_slice(&out.stdout).ok()?;- let windows = parse_claude_usage(v["result"].as_str()?);+ let windows = parse_usage_stream(&String::from_utf8_lossy(&out.stdout));(!windows.is_empty()).then_some(windows)}+/// The `usage_report` event's limits, exact instants included; a CLI without+/// one leaves its report text in the `result` event. The text's reset times+/// follow the CLI's date formatting, which differs between platforms.+fn parse_usage_stream(stdout: &str) -> Vec<Window> {+ let events: Vec<Value> = stdout.lines().filter_map(|line| serde_json::from_str(line).ok()).collect();+ if let Some(limits) = events.iter().find_map(|e| e["usage_report"]["rate_limits"]["limits"].as_array()) {+ return limits.iter().filter_map(report_window).collect();+ }+ events.iter().find_map(|e| e["result"].as_str()).map(parse_claude_usage).unwrap_or_default()+}++/// One of `usage_report.rate_limits.limits`:+/// `{"kind": "weekly_scoped", "percent": 0, "resets_at": "2026-10-31T03:59:59+00:00", "scope": {"model": {"display_name": "Fable"}}}`.+fn report_window(limit: &Value) -> Option<Window> {+ let (id, label) = match limit["kind"].as_str()? {+ "session" => ("five_hour".to_owned(), "5-hour".to_owned()),+ "weekly_all" => ("seven_day".to_owned(), "Weekly".to_owned()),+ "weekly_scoped" => {+ let model = limit["scope"]["model"]["display_name"].as_str()?;+ (format!("seven_day_{}", model.to_lowercase()), format!("Weekly · {model}"))+ }+ _ => return None,+ };+ let resets = limit["resets_at"]+ .as_str()+ .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())+ .map(|t| t.timestamp_millis());+ Some(Window::new(id, label, limit["percent"].as_f64()?, resets))+}+/// Lines like `Current week (all models): 53% used · resets Sep 26 at 12pm (Asia/Taipei)`.pub fn parse_claude_usage(text: &str) -> Vec<Window> {text.lines()@@ -89,9 +120,14 @@ fn claude_window(info: &Value) -> Option<Window> {"seven_day_sonnet" => "Weekly · Sonnet",_ => return None,};- let u = info["utilization"].as_f64()?;- // The SDK reports a 0–1 fraction (from the unified rate-limit headers).- let percent = if u <= 1.0 { u * 100.0 } else { u };+ // The SDK reports a 0–1 fraction (from the unified rate-limit headers). A+ // limit that refused a request comes without one: it is used up.+ let percent = match info["utilization"].as_f64() {+ Some(u) if u <= 1.0 => u * 100.0,+ Some(u) => u,+ None if info["status"] == "rejected" => 100.0,+ None => return None,+ };// Seconds, but accept milliseconds too.let resets = info["resetsAt"].as_i64().map(|t| if t > 100_000_000_000 { t } else { t.saturating_mul(1000) });Some(Window::new(kind, label, percent, resets))@@ -123,6 +159,28 @@ mod tests {assert_eq!(w[2].label, "Weekly · Fable");}+ #[test]+ fn usage_report_gives_exact_resets() {+ let stream = [+ r#"{"type":"system","subtype":"init"}"#,+ r#"{"type":"assistant","usage_report":{"rate_limits":{"limits":[{"kind":"session","percent":4,"resets_at":"2026-10-29T20:10:00.568718+00:00"},{"kind":"weekly_all","percent":97,"resets_at":"2026-10-31T04:00:00+00:00"},{"kind":"weekly_scoped","percent":0,"resets_at":"2026-10-31T03:59:59+00:00","scope":{"model":{"display_name":"Fable"}}},{"kind":"extra","percent":1}]}}}"#,+ r#"{"type":"result","result":"Current session: 50% used"}"#,+ ]+ .join("\n");+ let w = parse_usage_stream(&stream);+ assert_eq!(w.len(), 3);+ assert_eq!((w[0].id.as_str(), w[0].resets_at), ("five_hour", Some(1_793_304_600_568)));+ assert!((w[1].percent - 97.0).abs() < f64::EPSILON);+ assert_eq!((w[2].id.as_str(), w[2].label.as_str()), ("seven_day_fable", "Weekly · Fable"));+ }++ #[test]+ fn report_text_when_the_cli_has_no_usage_report() {+ let w =+ parse_usage_stream(r#"{"type":"result","result":"Current session: 11% used · resets 2pm (Asia/Taipei)"}"#);+ assert_eq!((w.len(), w[0].resets_text.as_deref()), (1, Some("2pm (Asia/Taipei)")));+ }+#[test]fn claude_rate_limit_fraction_becomes_percent() {let w = claude_window(&json!({"rateLimitType": "five_hour", "utilization": 0.42, "resetsAt": 1_790_000_000}))@@ -131,4 +189,12 @@ mod tests {assert_eq!(w.resets_at, Some(1_790_000_000_000));assert!(claude_window(&json!({"rateLimitType": "overage", "utilization": 0.1})).is_none());}++ #[test]+ fn a_refused_limit_is_used_up() {+ let w = claude_window(&json!({"status": "rejected", "rateLimitType": "five_hour", "resetsAt": 1_790_000_000}))+ .unwrap();+ assert!((w.percent - 100.0).abs() < f64::EPSILON);+ assert!(claude_window(&json!({"status": "allowed", "rateLimitType": "five_hour"})).is_none());+ }}