1use crate::cli;
8use crate::engine::cooldown;
9use crate::engine::router::Router;
10use std::sync::Arc;
11
12pub async fn list() -> anyhow::Result<()> {
14 let store = Arc::new(cli::init_store().await?);
15 cooldown::init_cooldown_store(Arc::clone(&store)).await;
17
18 let router = Router::from_config();
21 router.refresh_health(&store).await;
22
23 let entries = cooldown::list_all_cooldowns();
24 let degraded = cooldown::list_degraded_agents();
25 let windows = cooldown::list_rate_limit_windows(&store).await;
26 let now = chrono::Utc::now().timestamp();
27 if entries.is_empty() && degraded.is_empty() {
28 println!("No active cooldowns.");
29 print_windows(&windows, now);
30 return Ok(());
31 }
32
33 println!("{:<30} {:<12} REASON", "KEY", "REMAINING");
34 println!("{}", "-".repeat(72_usize));
35 for (key, until, reason) in &entries {
36 let remaining_secs = until - now;
37 let remaining = format_remaining(remaining_secs);
38 println!("{key:<30} {remaining:<12} {reason}");
39 }
40 for (agent, reason) in degraded {
41 if entries.iter().any(|(key, ..)| key == &agent) {
42 continue;
43 }
44 println!("{:<30} {:<12} {}", agent, "degraded", reason);
45 }
46 print_windows(&windows, now);
47 Ok(())
48}
49
50fn print_windows(windows: &[(String, cooldown::RateLimitWindow)], now: i64) {
51 if windows.is_empty() {
52 return;
53 }
54 println!();
55 println!(
56 "{:<12} {:<12} {:<10} {:<12} RESETS IN",
57 "AGENT", "WINDOW", "STATUS", "UTILIZATION"
58 );
59 for (agent, w) in windows {
60 let used = w
61 .utilization
62 .map_or_else(|| "-".to_string(), |u| format!("{:.0}%", u * 100.0));
63 let resets = w
64 .resets_at
65 .map_or_else(|| "-".to_string(), |at| format_remaining(at - now));
66 println!(
67 "{agent:<12} {:<12} {:<10} {used:<12} {resets}",
68 w.window_type, w.status
69 );
70 }
71}
72
73pub async fn clear(key: Option<String>, all: bool) -> anyhow::Result<()> {
75 let store = Arc::new(cli::init_store().await?);
76 cooldown::init_cooldown_store(Arc::clone(&store)).await;
78
79 if all {
80 let agents = Router::from_config().available_agents;
81 cooldown::clear_cooldown("*", &store).await;
82 cooldown::mark_rate_limits_cleared(&store, &agents).await;
83 println!("Cleared all cooldowns.");
84 } else if let Some(k) = key {
85 cooldown::clear_cooldown(&k, &store).await;
86 println!("Cleared cooldown: {k}");
87 } else {
88 anyhow::bail!("specify a key (e.g. 'claude' or 'claude:<model>') or use --all");
89 }
90 Ok(())
91}
92
93fn format_remaining(secs: i64) -> String {
94 if secs <= 0 {
95 return "expired".to_string();
96 }
97 if secs < 3600 {
98 format!("{}m", secs / 60)
99 } else if secs < 86400 {
100 let h = secs / 3600;
101 let m = (secs % 3600) / 60;
102 if m == 0 {
103 format!("{h}h")
104 } else {
105 format!("{h}h{m}m")
106 }
107 } else {
108 let d = secs / 86400;
109 let h = (secs % 86400) / 3600;
110 if h == 0 {
111 format!("{d}d")
112 } else {
113 format!("{d}d{h}h")
114 }
115 }
116}