use std::time::Duration;
use serde::Deserialize;
use thiserror::Error;
use super::auth::{self, ClaudeAuthError};
use super::rate_limit::{self, RateLimitState};
use super::{executable, usage_report::ReportedLimits};
use crate::{
cli_runtime::run_bounded_probe, session_environment::Ambient, usage_limits::UsageFailure,
};
pub(crate) const LIVE_TTL: Duration = Duration::from_secs(60);
const PRINT_BUDGET: Duration = Duration::from_secs(30);
const PRINT_ARGS: &[&str] = &[
executable::CLI,
"-p",
"/usage",
"--output-format",
"stream-json",
"--verbose",
"--setting-sources",
"",
"--strict-mcp-config",
"--no-session-persistence",
"--max-turns",
"1",
"--tools",
"",
];
const USAGE_LOCAL_COMMAND: &str = "usage";
#[derive(Debug, Error)]
pub(crate) enum UsageProbeError {
#[error("claude code: could not run /usage: {0}")]
Run(String),
#[error("claude code: /usage did not run as a local command: {0}")]
NotLocal(String),
#[error("claude code: /usage output was not readable: {0}")]
Unparseable(String),
#[error("claude code: Claude could not fetch usage rows")]
NoReport,
#[error("claude code: auth preflight failed: {0}")]
Auth(#[from] ClaudeAuthError),
}
impl UsageProbeError {
pub(crate) fn failure(&self) -> UsageFailure {
match self {
Self::Run(_)
| Self::NotLocal(_)
| Self::Unparseable(_)
| Self::NoReport
| Self::Auth(_) => UsageFailure::Other,
}
}
}
#[derive(Debug)]
pub(crate) enum UsageProbeOutcome {
Ready(RateLimitState),
Unavailable,
}
pub(crate) async fn fetch_usage() -> Result<UsageProbeOutcome, UsageProbeError> {
let adapter = match executable::resolve(&Ambient::ThisProcess) {
Ok(adapter) => adapter,
Err(ClaudeAuthError::BinaryMissing) => return Ok(UsageProbeOutcome::Unavailable),
Err(error) => return Err(error.into()),
};
if !auth::query_executable(&adapter).await?.logged_in {
return Ok(UsageProbeOutcome::Unavailable);
}
let output = run_bounded_probe(&adapter, PRINT_ARGS, PRINT_BUDGET)
.await
.map_err(|error| UsageProbeError::Run(error.to_string()))?;
if !output.status.success() {
return Err(UsageProbeError::Run(format!(
"exited with {}: {}",
output.status,
output.stderr_lossy_trimmed()
)));
}
let mut state = parse_print_output(&output.stdout)?;
state.stamp_probe_snapshot();
Ok(UsageProbeOutcome::Ready(persist_probe_state(state)))
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum PrintLine {
Assistant {
#[serde(default)]
usage_report: Option<UsageReport>,
},
Result {
#[serde(default)]
is_error: bool,
#[serde(default)]
local_command: Option<String>,
#[serde(default)]
result: String,
},
#[serde(other)]
Other,
}
#[derive(Deserialize)]
struct UsageReport {
#[serde(default)]
rate_limits: Option<ReportedLimits>,
}
fn parse_print_output(stdout: &[u8]) -> Result<RateLimitState, UsageProbeError> {
let mut limits = None;
let mut finished = None;
for line in stdout.split(|byte| *byte == b'\n') {
if line.iter().all(u8::is_ascii_whitespace) {
continue;
}
match serde_json::from_slice(line)
.map_err(|error| UsageProbeError::Unparseable(error.to_string()))?
{
PrintLine::Assistant { usage_report } => {
if let Some(rate_limits) = usage_report.and_then(|report| report.rate_limits) {
limits = Some(rate_limits);
}
}
PrintLine::Result {
is_error,
local_command,
result,
} => finished = Some((is_error, local_command, result)),
PrintLine::Other => {}
}
}
let Some((is_error, local_command, result)) = finished else {
return Err(UsageProbeError::Unparseable("no result line".into()));
};
if local_command.as_deref() != Some(USAGE_LOCAL_COMMAND) {
return Err(UsageProbeError::NotLocal(result));
}
if is_error {
return Err(UsageProbeError::Run(result));
}
let mut state = RateLimitState::default();
let windows = limits
.and_then(ReportedLimits::windows)
.ok_or(UsageProbeError::NoReport)?;
for info in windows {
state.merge_window(rate_limit::RateLimitObservation::capture(info));
}
Ok(state)
}
fn persist_probe_state(state: RateLimitState) -> RateLimitState {
let path = match rate_limit::default_state_path() {
Ok(path) => path,
Err(error) => {
tracing::debug!(
error = %error,
"claude rate-limit cache path unavailable; returning unpersisted probe"
);
return state;
}
};
match rate_limit::store_probe_snapshot(&path, state.clone()) {
Ok(merged) => merged,
Err(error) => {
tracing::warn!(error = %error, "failed to persist claude rate-limit cache");
state
}
}
}
pub(crate) fn live_is_fresh(fetched_at_unix: i64, now_unix: i64) -> bool {
now_unix.saturating_sub(fetched_at_unix) < i64::try_from(LIVE_TTL.as_secs()).unwrap_or(i64::MAX)
}
#[cfg(test)]
#[path = "usage_probe_tests.rs"]
mod tests;