rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Read Claude Code `/usage` through print mode.
//!
//! Claude owns the subscription token. Rho never reads credential files; it
//! runs the Claude CLI bundled in `claude-agent-acp` (`--cli`) as
//! `-p /usage --output-format stream-json --verbose`, which answers the local
//! command without a model turn, and reads the structured report beside the
//! panel text ([`super::usage_report`]). The call took 0.9 to 1.1 s
//! (adapter 0.114.0, Agent SDK 0.3.333, four runs).

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,
};

/// Reuse a successful read briefly so reopening `/limits` in quick
/// succession does not hit Anthropic's usage endpoint, which throttles. A
/// read costs about 1 s, so a short window keeps the numbers current.
pub(crate) const LIVE_TTL: Duration = Duration::from_secs(60);

/// Spawn to exit: about 1 s measured. The PTY probe this replaced saw a slow
/// usage endpoint refresh land 20-30 s in, so the budget leaves that room and
/// only a hung CLI or endpoint reaches it.
const PRINT_BUDGET: Duration = Duration::from_secs(30);

const PRINT_ARGS: &[&str] = &[
    executable::CLI,
    "-p",
    "/usage",
    "--output-format",
    "stream-json",
    // stream-json in print mode requires it.
    "--verbose",
    "--setting-sources",
    "",
    "--strict-mcp-config",
    // A usage read is not a conversation the user should find in `--resume`.
    "--no-session-persistence",
    // A CLI too old to answer `/usage` locally sends it to the model; keep
    // that turn short and unable to touch the workspace.
    "--max-turns",
    "1",
    "--tools",
    "",
];

/// The `local_command` print mode reports when `/usage` ran locally.
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 {
    /// The report says only that the usage fetch failed, not why, so every
    /// error is a plain failure.
    pub(crate) fn failure(&self) -> UsageFailure {
        match self {
            Self::Run(_)
            | Self::NotLocal(_)
            | Self::Unparseable(_)
            | Self::NoReport
            | Self::Auth(_) => UsageFailure::Other,
        }
    }
}

/// `Unavailable`: no live read (signed out, adapter missing). `/limits`
/// keeps disk windows.
#[derive(Debug)]
pub(crate) enum UsageProbeOutcome {
    Ready(RateLimitState),
    Unavailable,
}

/// Auth preflight, then one print-mode `/usage` read.
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)?;
    // Capture stamps parse time per window. Restamp the read instant so
    // `/limits` age is one moment, and so this read sorts ahead of
    // observations from before it.
    state.stamp_probe_snapshot();
    Ok(UsageProbeOutcome::Ready(persist_probe_state(state)))
}

/// One stream-json line. Only the two that carry the read matter.
#[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 {
    /// Null while Claude cannot fetch usage.
    #[serde(default)]
    rate_limits: Option<ReportedLimits>,
}

/// stream-json lines → windows. Rejects a model answer, a failed command,
/// and a read without the server's rows.
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)
}

/// Merge into the disk cache; a cache failure still returns the read.
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;