Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

21.4 KB
Raw Blame
//! Antigravity CLI 官方登录的剩余额度:问 agy 自己的 `/usage` 命令
//! (`agy -p /usage --output-format json`),这条命令不调模型、不新建会话,启动 agy 要七八秒。
//!
//! 这是唯一的查询方式:CC Switch 不拿 agy 的令牌、也不冒充 agy 的客户端标识去问 Google,
//! 所以只能查 agy 现在登着的那个号(别的号显示切走前最后一次查到的,见 `agy_account`)。

use std::process::{Output, Stdio};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use futures::future::try_join3;
use process_wrap::tokio::{ChildWrapper, CommandWrap, KillOnDrop};
use serde::Deserialize;
use tokio::io::{AsyncRead, AsyncReadExt};

use super::agy_account::{
    keychain::{self, AgyLoginStore, SystemKeychain},
    refresh_token_of,
};
use super::subscription::{CredentialStatus, QuotaTier, SubscriptionQuota};
use crate::error::AppError;

const TOOL: &str = "agy";
const TIMEOUT: Duration = Duration::from_secs(30);

pub const TIER_AGY_GEMINI_FIVE_HOUR: &str = "agy_gemini_five_hour";
pub const TIER_AGY_GEMINI_WEEKLY: &str = "agy_gemini_weekly";
pub const TIER_AGY_GEMINI_ARGON_WEEKLY: &str = "agy_gemini_argon_weekly";
pub const TIER_AGY_THIRD_PARTY_FIVE_HOUR: &str = "agy_third_party_five_hour";
pub const TIER_AGY_THIRD_PARTY_WEEKLY: &str = "agy_third_party_weekly";

#[derive(Deserialize)]
struct UsageOutput {
    status: Option<String>,
    command: Option<UsageCommand>,
}

#[derive(Deserialize)]
struct UsageCommand {
    data: Option<UsageData>,
}

#[derive(Deserialize)]
struct UsageData {
    #[serde(default)]
    groups: Vec<UsageGroup>,
}

#[derive(Deserialize)]
struct UsageGroup {
    #[serde(default)]
    buckets: Vec<UsageBucket>,
}

#[derive(Deserialize)]
struct UsageBucket {
    id: Option<String>,
    remaining_fraction: Option<f64>,
    reset_time: Option<String>,
}

/// agy 的额度分组:Gemini 一组,Claude 和 GPT 共用一组,每组各有 5 小时和每周两档;
/// Pro 档的 Gemini 组另有 Gemini 4 Argon 单独的每周额度。
/// 不认识的桶(以后新增的组)跳过,免得显示成没有文案的档。
fn tier_name(bucket_id: &str) -> Option<&'static str> {
    match bucket_id {
        "gemini-5h" => Some(TIER_AGY_GEMINI_FIVE_HOUR),
        "gemini-weekly" => Some(TIER_AGY_GEMINI_WEEKLY),
        "gemini-argon-wtu-weekly" => Some(TIER_AGY_GEMINI_ARGON_WEEKLY),
        "3p-5h" => Some(TIER_AGY_THIRD_PARTY_FIVE_HOUR),
        "3p-weekly" => Some(TIER_AGY_THIRD_PARTY_WEEKLY),
        _ => None,
    }
}

fn sort_order(name: &str) -> usize {
    match name {
        TIER_AGY_GEMINI_FIVE_HOUR => 0,
        TIER_AGY_GEMINI_WEEKLY => 1,
        TIER_AGY_GEMINI_ARGON_WEEKLY => 2,
        TIER_AGY_THIRD_PARTY_FIVE_HOUR => 3,
        _ => 4,
    }
}

fn parse_usage(stdout: &[u8]) -> Option<Vec<QuotaTier>> {
    let output: UsageOutput = serde_json::from_slice(stdout).ok()?;
    if output.status.as_deref() != Some("SUCCESS") {
        return None;
    }
    let groups = output.command?.data?.groups;
    collect_tiers(
        groups
            .into_iter()
            .flat_map(|group| group.buckets)
            .map(|bucket| (bucket.id, bucket.remaining_fraction, bucket.reset_time)),
    )
}

/// 一组额度桶(id、剩余比例、重置时间)→ 排好序的档;一档都认不出时返回 `None`。
fn collect_tiers(
    buckets: impl IntoIterator<Item = (Option<String>, Option<f64>, Option<String>)>,
) -> Option<Vec<QuotaTier>> {
    let mut tiers: Vec<QuotaTier> = buckets
        .into_iter()
        .filter_map(|(id, remaining, reset_time)| {
            let name = tier_name(id.as_deref()?)?;
            let remaining = remaining?.clamp(0.0, 1.0);
            Some(QuotaTier {
                name: name.to_string(),
                utilization: (1.0 - remaining) * 100.0,
                resets_at: reset_time,
                used_value_usd: None,
                max_value_usd: None,
            })
        })
        .collect();
    if tiers.is_empty() {
        return None;
    }
    tiers.sort_by_key(|tier| sort_order(&tier.name));
    Some(tiers)
}

#[derive(Debug)]
enum CommandExecError {
    Io(std::io::Error),
    Timeout,
}

struct ChildTreeGuard(Option<Box<dyn ChildWrapper>>);

impl Drop for ChildTreeGuard {
    fn drop(&mut self) {
        if let Some(mut child) = self.0.take() {
            // Unix 上 ProcessGroupChild 不在 Drop 时发 killpg,必须显式调用 start_kill()
            let _ = child.start_kill();
        }
    }
}

fn wrap_background_command(mut command: tokio::process::Command) -> CommandWrap {
    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let mut wrapped = CommandWrap::from(command);
    wrapped.wrap(KillOnDrop);
    // 超时或被取消时清理整棵子进程树,避免 Windows/Unix 上残留子进程
    #[cfg(unix)]
    wrapped.wrap(process_wrap::tokio::ProcessGroup::leader());
    #[cfg(windows)]
    {
        let mut flags = process_wrap::tokio::CreationFlags(Default::default());
        flags.0 .0 = 0x0800_0000; // CREATE_NO_WINDOW
        wrapped.wrap(flags).wrap(process_wrap::tokio::JobObject);
    }
    wrapped
}

async fn run_command_output(
    command: tokio::process::Command,
    timeout: Duration,
) -> Result<Output, CommandExecError> {
    let mut wrapped = wrap_background_command(command);
    let mut guard = ChildTreeGuard(Some(wrapped.spawn().map_err(CommandExecError::Io)?));
    let outcome = tokio::time::timeout(timeout, async {
        async fn read_to_end<A: AsyncRead + Unpin>(io: &mut Option<A>) -> std::io::Result<Vec<u8>> {
            let mut vec = Vec::new();
            if let Some(io) = io.as_mut() {
                io.read_to_end(&mut vec).await?;
            }
            Ok(vec)
        }

        let mut stdout_pipe = guard.0.as_mut().expect("child present").stdout().take();
        let mut stderr_pipe = guard.0.as_mut().expect("child present").stderr().take();

        let child = guard.0.as_mut().expect("child present");
        let (status, stdout, stderr) = try_join3(
            child.wait(),
            read_to_end(&mut stdout_pipe),
            read_to_end(&mut stderr_pipe),
        )
        .await?;

        drop(stdout_pipe);
        drop(stderr_pipe);
        guard.0 = None;
        Ok::<_, std::io::Error>(Output {
            status,
            stdout,
            stderr,
        })
    })
    .await;

    match outcome {
        Ok(Ok(output)) => Ok(output),
        Ok(Err(error)) => Err(CommandExecError::Io(error)),
        Err(_) => Err(CommandExecError::Timeout),
    }
}

/// `config.json` 开着网关(启用的是第三方卡):agy 走网关,官方登录没在用,`/usage` 只会
/// 返回空的额度组。按「只查正在用的登录」,这时谁的额度都不实时查。
pub(crate) async fn gateway_in_use() -> bool {
    tokio::task::spawn_blocking(crate::agy_config::live_gateway_enabled)
        .await
        .unwrap_or(false)
}

/// 构造后台查询 Antigravity 额度的命令:带全局代理与自动更新禁用,固定中性工作目录,
/// 并在 Windows 上对原生 `.exe` 清空 `PATH` 与当前目录回退以防拉起外部控制台子进程。
fn build_usage_command(bin: &std::path::Path) -> tokio::process::Command {
    let mut command = crate::agy_config::background_command(bin);
    if let Some(dir) = crate::agy_config::override_root_dir() {
        command.arg(format!("--gemini_dir={}", dir.display()));
    }
    command
        .args(["--print", "/usage", "--output-format", "json"])
        // 只问官方登录:GUI 进程里残留的 Key 会让 agy 改走 Key 模式。
        .env_remove("GEMINI_API_KEY")
        .env_remove("GOOGLE_GEMINI_BASE_URL");
    crate::agy_config::apply_neutral_current_dir(&mut command);
    crate::agy_config::isolate_windows_background_exe(&mut command, bin);
    command
}

fn uses_file_token_storage(is_set: impl FnMut(&str) -> bool) -> bool {
    [
        "SSH_CONNECTION",
        "SSH_CLIENT",
        "SSH_TTY",
        "AGY_CLI_FORCE_FILE_TOKEN_STORAGE",
    ]
    .into_iter()
    .any(is_set)
}

fn keychain_quota_failure(read: Result<Option<String>, AppError>) -> Option<SubscriptionQuota> {
    let raw = match read {
        Ok(raw) => raw,
        Err(_) => {
            return Some(SubscriptionQuota::error(
                TOOL,
                CredentialStatus::Valid,
                "Could not read the Antigravity sign-in. Check keychain access and try again."
                    .to_string(),
            ));
        }
    };
    if let Some(credential) = raw.as_deref().and_then(|raw| keychain::decode(raw).ok()) {
        if refresh_token_of(&credential).is_some() {
            return None;
        }
        let has_access_token = credential
            .pointer("/token/access_token")
            .and_then(serde_json::Value::as_str)
            .is_some_and(|token| !token.is_empty());
        let access_token_current = match credential.pointer("/token/expiry") {
            None | Some(serde_json::Value::Null) => true,
            Some(expiry) => expiry
                .as_str()
                .and_then(|expiry| chrono::DateTime::parse_from_rfc3339(expiry).ok())
                .is_some_and(|expiry| expiry.timestamp() > chrono::Utc::now().timestamp()),
        };
        if has_access_token && access_token_current {
            return None;
        }
    }
    Some(SubscriptionQuota::error(
        TOOL,
        CredentialStatus::Expired,
        "Sign in with Antigravity before checking quota.".to_string(),
    ))
}

/// 由 `subscription::get_subscription_quota("agy")` 分发。没装 agy、或网关在用(官方登录没在用)
/// 时按「没有凭据」处理(卡片不显示);已找到可执行文件但启动失败、超时、没登录或输出看不懂
/// 都写成查询失败,错误里不带 agy 的原始输出。
pub(crate) async fn get_agy_subscription_quota() -> Result<SubscriptionQuota, String> {
    if gateway_in_use().await {
        return Ok(SubscriptionQuota::not_found(TOOL));
    }
    let Some(bin) = tokio::task::spawn_blocking(crate::agy_config::real_agy_bin)
        .await
        .map_err(|e| e.to_string())?
    else {
        log::debug!("[AgyQuota] 未找到 agy 可执行文件,跳过额度查询");
        return Ok(SubscriptionQuota::not_found(TOOL));
    };
    // 查额度是后台操作,缺少可用的钥匙串凭据时别让 agy 回退到交互式登录。
    // ADC 和文件凭据模式不依赖这个钥匙串条目。
    if keychain::supported()
        && !std::env::var("AGY_ADC_AUTH").is_ok_and(|value| value.eq_ignore_ascii_case("true"))
        && !uses_file_token_storage(|name| std::env::var_os(name).is_some())
    {
        let failure =
            tokio::task::spawn_blocking(|| keychain_quota_failure(SystemKeychain::agy().read()))
                .await
                .map_err(|e| e.to_string())?;
        if let Some(quota) = failure {
            return Ok(quota);
        }
    }
    // build_usage_command 带上设置里的全局代理并隔离后台子进程环境;进程树的清理
    // 和 Windows 隐藏窗口由 run_command_output 负责。
    let command = build_usage_command(&bin);
    quota_from_command_result(run_command_output(command, TIMEOUT).await)
}

fn quota_from_command_result(
    result: Result<Output, CommandExecError>,
) -> Result<SubscriptionQuota, String> {
    let output = match result {
        Ok(output) => output,
        Err(CommandExecError::Io(error)) => {
            log::warn!("[AgyQuota] 启动或执行 agy 失败: {error}");
            return Ok(SubscriptionQuota::error(
                TOOL,
                CredentialStatus::Valid,
                "Failed to run agy to query quota. Check your agy installation and try again."
                    .to_string(),
            ));
        }
        Err(CommandExecError::Timeout) => {
            log::warn!("[AgyQuota] agy /usage 查询超时({}s)", TIMEOUT.as_secs());
            return Err("Antigravity quota query timed out".to_string());
        }
    };
    let tiers = output
        .status
        .success()
        .then(|| parse_usage(&output.stdout))
        .flatten();
    let Some(tiers) = tiers else {
        log::warn!(
            "[AgyQuota] agy /usage 未返回有效额度(exit={:?}, stdout={}B, stderr={}B)",
            output.status.code(),
            output.stdout.len(),
            output.stderr.len()
        );
        return Ok(SubscriptionQuota::error(
            TOOL,
            CredentialStatus::Valid,
            "Antigravity did not return quota. Sign in with agy and try again.".to_string(),
        ));
    };
    Ok(SubscriptionQuota {
        tool: TOOL.to_string(),
        credential_status: CredentialStatus::Valid,
        credential_message: None,
        success: true,
        tiers,
        extra_usage: None,
        reset_credits: None,
        credits_balance: None,
        plan_name: None,
        error: None,
        queried_at: Some(now_millis()),
    })
}

fn now_millis() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as i64
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ssh_or_explicit_file_storage_skips_keychain_precheck() {
        assert!(!uses_file_token_storage(|_| false));
        for name in [
            "SSH_CONNECTION",
            "SSH_CLIENT",
            "SSH_TTY",
            "AGY_CLI_FORCE_FILE_TOKEN_STORAGE",
        ] {
            assert!(uses_file_token_storage(|candidate| candidate == name));
        }
    }

    #[test]
    fn quota_requires_a_usable_local_login() {
        for raw in [
            None,
            Some("not JSON"),
            Some(r#"{"writer_id":"fixture","auth_method":"consumer"}"#),
            Some(r#"{"token":{"refresh_token":""}}"#),
            Some(r#"{"token":{"access_token":"fixture","expiry":"2000-01-01T00:00:00Z"}}"#),
        ] {
            let quota = keychain_quota_failure(Ok(raw.map(str::to_owned))).unwrap();
            assert!(matches!(quota.credential_status, CredentialStatus::Expired));
            assert!(!quota.success);
        }

        for raw in [
            r#"{"token":{"refresh_token":"fixture","expiry":"2000-01-01T00:00:00Z"}}"#,
            r#"{"token":{"access_token":"fixture","expiry":"2099-01-01T00:00:00Z"}}"#,
        ] {
            assert!(keychain_quota_failure(Ok(Some(raw.to_owned()))).is_none());
        }

        let quota = keychain_quota_failure(Err(AppError::Config("PRIVATE".into()))).unwrap();
        assert!(matches!(quota.credential_status, CredentialStatus::Valid));
        assert!(!quota.error.unwrap().contains("PRIVATE"));
    }

    // agy 1.4.3 `/usage --output-format json` 的真实结构(数值改过)
    const SAMPLE: &str = r#"{
      "conversation_id": "", "status": "SUCCESS", "response": "...",
      "usage": {"input_tokens": 0, "output_tokens": 0},
      "command": {"name": "usage", "data": {"description": "...", "groups": [
        {"name": "Gemini Models", "buckets": [
          {"id": "gemini-weekly", "window": "weekly", "remaining_fraction": 0.75, "reset_time": "2026-10-27T15:13:36Z"},
          {"id": "gemini-5h", "window": "5h", "remaining_fraction": 1, "reset_time": "2026-10-21T04:16:37Z"},
          {"id": "gemini-argon-wtu-weekly", "window": "weekly", "remaining_fraction": 0.8, "reset_time": "2026-10-27T18:00:00Z"}
        ]},
        {"name": "Claude and GPT models", "buckets": [
          {"id": "3p-weekly", "window": "weekly", "remaining_fraction": 0.1, "reset_time": "2026-10-27T23:16:37Z"},
          {"id": "3p-5h", "window": "5h", "remaining_fraction": 0, "reset_time": "2026-10-21T04:16:37Z"},
          {"id": "future-bucket", "remaining_fraction": 0.5}
        ]}
      ]}}
    }"#;

    #[test]
    fn keeps_each_group_and_window_as_its_own_tier() {
        let tiers = parse_usage(SAMPLE.as_bytes()).unwrap();
        let names: Vec<_> = tiers.iter().map(|t| t.name.as_str()).collect();
        assert_eq!(
            names,
            [
                TIER_AGY_GEMINI_FIVE_HOUR,
                TIER_AGY_GEMINI_WEEKLY,
                TIER_AGY_GEMINI_ARGON_WEEKLY,
                TIER_AGY_THIRD_PARTY_FIVE_HOUR,
                TIER_AGY_THIRD_PARTY_WEEKLY,
            ]
        );
        let used: Vec<_> = tiers.iter().map(|t| t.utilization.round()).collect();
        assert_eq!(used, [0.0, 25.0, 20.0, 100.0, 90.0]);
        assert_eq!(tiers[1].resets_at.as_deref(), Some("2026-10-27T15:13:36Z"));
        assert_eq!(tiers[2].resets_at.as_deref(), Some("2026-10-27T18:00:00Z"));
    }

    /// 网关在用时不起 agy:直接按「没有凭据」返回,不会把空的额度组报成「没登录」。
    #[tokio::test]
    #[serial_test::serial]
    async fn no_live_query_while_the_gateway_is_in_use() {
        let _home = crate::test_support::TestHome::new();
        let path = crate::agy_config::gateway_config_path();
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            r#"{"gateway":{"enabled":true,"url":"https://relay.example","apiKey":"k"}}"#,
        )
        .unwrap();
        let quota = get_agy_subscription_quota().await.unwrap();
        assert!(!quota.success);
        assert_eq!(
            serde_json::to_value(&quota).unwrap(),
            serde_json::to_value(SubscriptionQuota::not_found(TOOL)).unwrap()
        );
    }

    #[test]
    fn failed_or_empty_output_is_not_quota() {
        assert!(parse_usage(b"not json").is_none());
        assert!(parse_usage(br#"{"status":"ERROR","command":null}"#).is_none());
        assert!(parse_usage(br#"{"status":"SUCCESS","command":{"data":{"groups":[]}}}"#).is_none());
        // 缺比例的桶不当成满额
        assert!(parse_usage(
            br#"{"status":"SUCCESS","command":{"data":{"groups":[{"buckets":[{"id":"gemini-5h"}]}]}}}"#
        )
        .is_none());
    }

    #[tokio::test]
    async fn run_command_output_captures_stdout_and_times_out_cleanly() {
        #[cfg(windows)]
        let ok_cmd = {
            let mut cmd = tokio::process::Command::new("cmd");
            cmd.args(["/C", "echo agy-ok"]);
            cmd
        };
        #[cfg(not(windows))]
        let ok_cmd = {
            let mut cmd = tokio::process::Command::new("sh");
            cmd.args(["-c", "printf 'agy-ok\\n'"]);
            cmd
        };
        let output = run_command_output(ok_cmd, Duration::from_secs(5))
            .await
            .unwrap();
        assert!(output.status.success());
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "agy-ok");

        #[cfg(windows)]
        let slow_cmd = {
            let mut cmd = tokio::process::Command::new("cmd");
            cmd.args(["/C", "ping -n 10 127.0.0.1 >nul"]);
            cmd
        };
        #[cfg(not(windows))]
        let slow_cmd = {
            let mut cmd = tokio::process::Command::new("sh");
            cmd.args(["-c", "sleep 10"]);
            cmd
        };
        let err = run_command_output(slow_cmd, Duration::from_millis(150))
            .await
            .unwrap_err();
        assert!(matches!(err, CommandExecError::Timeout));
    }

    #[test]
    fn usage_command_disables_auto_update_and_isolates_windows_exe() {
        use std::ffi::OsStr;
        use std::path::Path;

        let exe_cmd = build_usage_command(Path::new(r"C:\agy\agy.exe"));
        let std_exe = exe_cmd.as_std();
        let envs: Vec<(&OsStr, Option<&OsStr>)> = std_exe.get_envs().collect();
        assert!(envs.contains(&(
            OsStr::new("AGY_CLI_DISABLE_AUTO_UPDATE"),
            Some(OsStr::new("true"))
        )));
        assert!(envs.contains(&(OsStr::new("GEMINI_API_KEY"), None)));
        assert!(envs.contains(&(OsStr::new("GOOGLE_GEMINI_BASE_URL"), None)));
        assert!(std_exe.get_current_dir().is_some());

        #[cfg(windows)]
        {
            assert!(envs.contains(&(
                OsStr::new("NoDefaultCurrentDirectoryInExePath"),
                Some(OsStr::new("1"))
            )));
            assert!(envs.contains(&(OsStr::new("PATH"), Some(OsStr::new("")))));

            let cmd_wrapper = build_usage_command(Path::new(r"C:\agy\agy.cmd"));
            let cmd_envs: Vec<(&OsStr, Option<&OsStr>)> = cmd_wrapper.as_std().get_envs().collect();
            assert!(cmd_envs.contains(&(
                OsStr::new("NoDefaultCurrentDirectoryInExePath"),
                Some(OsStr::new("1"))
            )));
            assert!(!cmd_envs
                .iter()
                .any(|(k, _)| k.to_str().is_some_and(|s| s.eq_ignore_ascii_case("PATH"))));
        }
    }

    #[cfg(windows)]
    #[test]
    fn wrap_background_command_preserves_create_no_window_with_job_object() {
        use std::path::Path;

        let cmd = build_usage_command(Path::new(r"C:\agy\agy.exe"));
        let wrapped = wrap_background_command(cmd);
        let flags = wrapped
            .get_wrap::<process_wrap::tokio::CreationFlags>()
            .expect("CreationFlags wrapper must be present");
        assert_eq!(flags.0 .0, 0x0800_0000);
        assert!(wrapped.has_wrap::<process_wrap::tokio::JobObject>());
    }

    #[test]
    fn io_exec_error_maps_to_valid_credential_error_instead_of_not_found() {
        let quota = quota_from_command_result(Err(CommandExecError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "spawn failed",
        ))))
        .unwrap();
        assert!(!quota.success);
        assert!(matches!(quota.credential_status, CredentialStatus::Valid));
        assert_eq!(
            quota.error.as_deref(),
            Some("Failed to run agy to query quota. Check your agy installation and try again.")
        );
    }
}