Skip to main content

agent_hub_runtime/core/agent_usage/
mod.rs

1//! Subscription quota queries, independent of projects, terminals and Skill storage.
2//! Secrets stay in provider adapters; only quota snapshots cross the IPC boundary.
3mod claude;
4mod codex;
5mod credentials;
6mod reset;
7mod subscription;
8pub use reset::{ResetOutcome, ResetResult};
9
10use serde::Serialize;
11use std::{
12    future::Future,
13    time::{Duration, Instant},
14};
15use tokio::sync::Mutex;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
18#[serde(rename_all = "snake_case")]
19pub enum UsageProvider {
20    Claude,
21    Codex,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
25#[serde(rename_all = "snake_case")]
26pub enum UsageStatus {
27    Ready,
28    NotInstalled,
29    SignedOut,
30    Unsupported,
31    CredentialsUnavailable,
32    AuthExpired,
33    PermissionDenied,
34    RateLimited,
35    NetworkError,
36    InvalidResponse,
37    NoData,
38    QueryFailed,
39}
40
41#[derive(Clone, Debug, Serialize)]
42pub struct UsageWindow {
43    pub key: String,
44    pub used_percent: f64,
45    /// Unix seconds, matching provider reset timestamps.
46    pub resets_at: Option<i64>,
47    pub window_minutes: Option<u64>,
48}
49
50#[derive(Clone, Debug, Serialize)]
51pub struct ResetCredit {
52    pub id: Option<String>,
53    pub reset_type: String,
54    pub title: Option<String>,
55    pub expires_at: Option<i64>,
56}
57
58#[derive(Clone, Debug, Serialize)]
59pub struct ResetCredits {
60    pub available_count: u64,
61    /// None means the service returned only the count; rows may be capped.
62    pub credits: Option<Vec<ResetCredit>>,
63}
64
65#[derive(Clone, Debug, Serialize)]
66pub struct SubscriptionPeriod {
67    pub active_until: i64,
68    pub last_checked_at: Option<i64>,
69}
70
71#[derive(Clone, Debug, Serialize)]
72pub struct ProviderUsage {
73    pub provider: UsageProvider,
74    pub status: UsageStatus,
75    pub windows: Vec<UsageWindow>,
76    pub reset_credits: Option<ResetCredits>,
77    pub subscription: Option<SubscriptionPeriod>,
78    pub updated_at: i64,
79    pub retry_after_seconds: Option<u64>,
80}
81
82impl ProviderUsage {
83    fn empty(provider: UsageProvider, status: UsageStatus) -> Self {
84        Self {
85            provider,
86            status,
87            windows: Vec::new(),
88            reset_credits: None,
89            subscription: None,
90            updated_at: chrono::Utc::now().timestamp(),
91            retry_after_seconds: None,
92        }
93    }
94
95    fn ready(provider: UsageProvider, windows: Vec<UsageWindow>) -> Self {
96        let status = if windows.is_empty() {
97            UsageStatus::NoData
98        } else {
99            UsageStatus::Ready
100        };
101        Self {
102            windows,
103            ..Self::empty(provider, status)
104        }
105    }
106}
107
108struct CachedUsage {
109    snapshot: ProviderUsage,
110    checked_at: Instant,
111}
112
113/// One cache/lock per provider merges concurrent windows and manual refreshes.
114/// Nothing is persisted or placed in the portable backup.
115#[derive(Default)]
116pub struct AgentUsage {
117    claude: Mutex<Option<CachedUsage>>,
118    codex: Mutex<Option<CachedUsage>>,
119}
120
121impl AgentUsage {
122    /// Serialize redemption with Codex queries and replace the cached quota immediately.
123    pub async fn consume_reset(
124        &self,
125        idempotency_key: String,
126        credit_id: Option<String>,
127        proxy: Option<String>,
128    ) -> Result<ResetResult, UsageStatus> {
129        let mut cache = self.codex.lock().await;
130        let result = reset::consume(idempotency_key, credit_id, proxy.as_deref()).await;
131        // Even an interrupted response may have consumed a credit. Do not serve stale data.
132        *cache = result
133            .as_ref()
134            .ok()
135            .and_then(|result| result.snapshot.clone())
136            .map(|snapshot| CachedUsage {
137                snapshot,
138                checked_at: Instant::now(),
139            });
140        result
141    }
142
143    pub async fn query(&self, refresh: bool, proxy: Option<String>) -> Vec<ProviderUsage> {
144        let (claude, codex) = tokio::join!(
145            cached_query(&self.claude, refresh, || claude::query(proxy.as_deref())),
146            cached_query(&self.codex, refresh, || codex::query(proxy.as_deref())),
147        );
148        vec![claude, codex]
149    }
150}
151
152async fn cached_query<F, Fut>(
153    cache: &Mutex<Option<CachedUsage>>,
154    refresh: bool,
155    fetch: F,
156) -> ProviderUsage
157where
158    F: FnOnce() -> Fut,
159    Fut: Future<Output = ProviderUsage>,
160{
161    let mut cached = cache.lock().await;
162    if let Some(entry) = cached.as_ref() {
163        let transient = matches!(
164            entry.snapshot.status,
165            UsageStatus::NetworkError | UsageStatus::QueryFailed | UsageStatus::InvalidResponse
166        );
167        let minimum = if refresh || transient { 15 } else { 120 };
168        let cooldown = if entry.snapshot.status == UsageStatus::RateLimited {
169            300
170        } else {
171            0
172        };
173        let ttl = minimum.max(entry.snapshot.retry_after_seconds.unwrap_or(cooldown));
174        if entry.checked_at.elapsed() < Duration::from_secs(ttl) {
175            return entry.snapshot.clone();
176        }
177    }
178    let snapshot = fetch().await;
179    *cached = Some(CachedUsage {
180        snapshot: snapshot.clone(),
181        checked_at: Instant::now(),
182    });
183    snapshot
184}
185
186fn valid_percent(value: &serde_json::Value) -> Option<f64> {
187    value
188        .as_f64()
189        .filter(|n| n.is_finite() && *n >= 0.0 && *n <= 100.0)
190}
191
192#[cfg(test)]
193mod tests;