Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
581cae0
feat: add subscription usage command with Claude, Codex, and Z.ai pro…
shidevil May 1, 2026
5bdc3b4
Merge pull request #1 from shidevil/feat/usage-command
shidevil May 1, 2026
d1cba85
feat(usage): add Amp, Copilot, Kimi, MiniMax providers; refactor to m…
shidevil May 1, 2026
cde6ccc
Merge pull request #2 from shidevil/feat/usage-command
shidevil May 2, 2026
f1ca00d
fix(minimax): correct usage_count inversion and match openusage behavior
shidevil May 2, 2026
aca3b06
fix(kimi): persist rotated refresh token and expires_at to disk
shidevil May 2, 2026
8884232
fix(copilot): respect GH_CONFIG_DIR for gh hosts path resolution
shidevil May 2, 2026
d8ebd07
fix(usage): reject unsupported --home flag instead of silently ignori…
shidevil May 2, 2026
0f6f567
fix(codex): require access_token in credential lookup and add CODEX_H…
shidevil May 2, 2026
2035789
fix: batch-fix six remaining usage-provider issues
shidevil May 2, 2026
122c12a
perf(usage): skip providers without credentials and fetch in parallel
shidevil May 2, 2026
2dcc24f
feat(usage): cache subscription data to disk with 5-minute TTL
shidevil May 2, 2026
b8c7acb
fix(zai): order metrics as Session/Weekly/Web Search and widen label …
shidevil May 2, 2026
dcf905a
Merge pull request #3 from shidevil/feat/usage-command
shidevil May 2, 2026
3369e6a
fix(usage): batch reliability and security fixes
shidevil May 3, 2026
f849ba3
Merge pull request #4 from shidevil/feat/usage-command
shidevil May 3, 2026
9609d38
fix(copilot): support Windows and XDG config directories for gh hosts
shidevil May 3, 2026
9163b82
Merge pull request #5 from shidevil/feat/usage-command
shidevil May 3, 2026
8a24115
fix(usage): batch 2 — security, correctness, and UX fixes
shidevil May 3, 2026
5758e58
Merge pull request #6 from shidevil/feat/usage-command
shidevil May 3, 2026
01160fd
fix(tui): run usage fetch in background thread to prevent UI freeze
shidevil May 3, 2026
09b0bab
Merge pull request #7 from shidevil/feat/usage-command
shidevil May 3, 2026
1432448
fix(usage): runtime, credential fallback, and concurrency fixes
shidevil May 3, 2026
44a70c1
Merge pull request #8 from shidevil/feat/usage-command
shidevil May 3, 2026
3c3e1c1
fix(kimi): update stored refresh token after proactive refresh
shidevil May 3, 2026
8daaf04
Merge pull request #9 from shidevil/feat/usage-command
shidevil May 3, 2026
430ca9b
fix(usage): kimi labels, dedup, disconnected handling, copilot fallback
shidevil May 3, 2026
ff1722d
Merge pull request #10 from shidevil/feat/usage-command
shidevil May 3, 2026
dcf8c25
fix(tui): 'r' refreshes all tabs including usage
shidevil May 4, 2026
728e713
Merge branch 'junhoyeo:main' into feat/usage-command
shidevil May 4, 2026
ce65e57
Merge pull request #11 from shidevil/feat/usage-command
shidevil May 4, 2026
1741173
Merge branch 'junhoyeo:main' into main
shidevil May 13, 2026
e84ea37
merge: upstream tokscale v2.1.3 (Minutely tab, daily detail, bug fixes)
shidevil May 21, 2026
c6572f9
Merge remote-tracking branch 'origin/main' into shidevil/main
junhoyeo May 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 49 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ In the age of AI-assisted development, **tokens are the new energy**. They power
- [Social](#social)
- [Cursor IDE Commands](#cursor-ide-commands)
- [Antigravity Commands](#antigravity-commands)
- [Subscription Usage](#subscription-usage)
- [Example Output](#example-output---light-version)
- [Configuration](#configuration)
- [Environment Variables](#environment-variables)
Expand Down Expand Up @@ -242,7 +243,7 @@ tokscale models --json > report.json # Save to file

The interactive TUI mode provides:

- **6 Views**: Overview (chart + top models), Models, Daily, Hourly, Stats (contribution graph), Agents
- **6 Views**: Overview (chart + top models), Usage (subscription quotas), Models, Daily, Hourly, Stats (contribution graph), Agents
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
- **Keyboard Navigation**:
- `1-6` or `←/→/Tab`: Switch views
- `↑/↓`: Navigate lists
Expand Down Expand Up @@ -469,6 +470,53 @@ tokscale antigravity purge-cache

**How it works**: `tokscale antigravity sync` discovers local Antigravity session candidates, fetches confirmed usage data from the local language server RPC, and stores normalized JSONL artifacts for tokscale-core to parse later. Run sync before reports if you want the freshest Antigravity data.

### Subscription Usage

Tokscale can fetch and display your real-time subscription quota across AI providers. This shows how much of your plan you've used and when limits reset.

```bash
# Show subscription usage for all detected providers
tokscale usage

# Output as JSON (for scripting)
tokscale usage --json

# Lightweight terminal output (no TUI)
tokscale usage --light
```

In the TUI, press `2` or navigate to the **Usage** tab to see subscription data. Press `u` or `r` to refresh.
Comment thread
shidevil marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

#### Supported Providers

| Provider | Auth Method | Metrics | Setup |
|----------|-------------|---------|-------|
| **Claude** | OAuth (credentials file or macOS Keychain) | Session (5hr), Weekly, Opus quotas | Run `claude` to log in |
| **Codex** (OpenAI) | OAuth (`~/.config/codex/auth.json` or `~/.codex/auth.json`) | Session, Weekly quotas | Run `codex` to log in |
| **Z.ai** | API key (env var) | Token limits, Web Searches | Set `ZAI_API_KEY` or `GLM_API_KEY` |
| **Amp** | API key (`~/.local/share/amp/secrets.json`) | Free tier balance, Credits | Run `amp` to log in |
| **GitHub Copilot** | GitHub token (keychain or `~/.config/gh/hosts.yml`) | Premium interactions, Chat quotas | Run `gh auth login` |
| **Kimi** | OAuth (`~/.kimi/credentials/kimi-code.json`) | Session, Weekly quotas | Run `kimi` to log in |
| **MiniMax** | API key (env var) | Prompt quotas per model | Set `MINIMAX_API_KEY` or `MINIMAX_API_TOKEN` |

Providers are auto-detected — only those with valid credentials are shown. If a provider is missing, ensure you've logged in or set the required environment variable.

#### Example Output

```
╭──────────────────────────────────────────────────────────╮
│ Session 85% left [=========---] resets in 2h 15m │
│ Weekly 72% left [========----] resets Fri 3pm │
│ Plan Max 20x │
╰──────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────╮
│ Session 40% left [=====-------] resets in 4h 30m │
│ Weekly 90% left [==========--] resets Mon 12am │
│ Account user@example.com │
│ Plan Pro │
╰──────────────────────────────────────────────────────────╯
```

### Example Output (`--light` version)

<img alt="CLI Light" src="./.github/assets/cli-light.png" />
Expand Down
1 change: 1 addition & 0 deletions crates/tokscale-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod usage;
pub mod wrapped;
151 changes: 151 additions & 0 deletions crates/tokscale-cli/src/commands/usage/amp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
use anyhow::Result;
use serde::Deserialize;

use super::{UsageMetric, UsageOutput};

#[derive(Debug, Deserialize)]
struct Secrets {
#[serde(rename = "apiKey@https://ampcode.com/")]
api_key: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ApiResponse {
#[allow(dead_code)]
ok: Option<bool>,
result: Option<ApiResult>,
}

#[derive(Debug, Deserialize)]
struct ApiResult {
display_text: Option<String>,
}

fn read_credentials() -> Result<String> {
let home = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
let path = home.join(".local").join("share").join("amp").join("secrets.json");
if !path.exists() {
anyhow::bail!("No Amp credentials found. Run 'amp' to log in.");
}
let content = std::fs::read_to_string(&path)?;
let secrets: Secrets = serde_json::from_str(&content)?;
secrets
.api_key
.ok_or_else(|| anyhow::anyhow!("No Amp API key in secrets.json"))
}

/// Parse a dollar amount like "$4.50" or "$1,200.00" from text starting at the given prefix.
fn parse_dollar_after(text: &str, prefix: &str) -> Option<f64> {
let start = text.find(prefix)? + prefix.len();
let rest = &text[start..];
let end = rest
.find(|c: char| !c.is_ascii_digit() && c != '.' && c != ',')
.unwrap_or(rest.len());
let num_str = &rest[..end];
num_str.replace(',', "").parse().ok()
}

fn parse_display_text(text: &str) -> Vec<UsageMetric> {
let mut metrics = Vec::new();

// Parse free tier: "$X/$Y remaining"
// Look for pattern like "$4.50/$20.00 remaining"
if let Some(slash_pos) = text.find("/$") {
if let Some(dollar_before) = text[..slash_pos].rfind('$') {
let before = &text[dollar_before + 1..slash_pos];
if let Ok(remaining) = before.replace(',', "").parse::<f64>() {
// Find the total after /$
let after = &text[slash_pos + 2..];
if let Some(space_pos) = after.find(|c: char| c.is_ascii_whitespace()) {
if let Ok(total) = after[..space_pos].replace(',', "").parse::<f64>() {
if total > 0.0 {
let used = (total - remaining).max(0.0);
let used_pct = (used / total * 100.0).clamp(0.0, 100.0);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
let remaining_pct = 100.0 - used_pct;
let mut resets_at = None;

// Estimate reset time from hourly replenish rate
if let Some(rate) = parse_dollar_after(text, "+$") {
if rate > 0.0 && used > 0.0 {
let secs = (used / rate * 3600.0) as i64;
let resets = chrono::Utc::now() + chrono::Duration::seconds(secs);
resets_at = Some(resets.to_rfc3339());
}
}

metrics.push(UsageMetric {
label: "Free".into(),
used_percent: used_pct,
remaining_percent: remaining_pct,
remaining_label: Some(format!("${remaining:.2}/${total:.2}")),
resets_at,
});
}
}
}
}
}
}

// Parse credits: "Individual credits: $X remaining"
if let Some(credits) = parse_dollar_after(text, "Individual credits: $") {
metrics.push(UsageMetric {
label: "Credits".into(),
used_percent: 0.0,
remaining_percent: 100.0,
remaining_label: Some(format!("${credits:.2} left")),
resets_at: None,
});
}

metrics
}

fn detect_plan(metrics: &[UsageMetric]) -> Option<String> {
let has_free = metrics.iter().any(|m| m.label == "Free");
let has_credits = metrics.iter().any(|m| m.label == "Credits");
match (has_free, has_credits) {
(true, _) => Some("Free".into()),
(false, true) => Some("Credits".into()),
_ => None,
}
}

pub fn fetch() -> Result<UsageOutput> {
let api_key = read_credentials()?;

let rt = tokio::runtime::Runtime::new()?;
rt.block_on(async {
let client = reqwest::Client::new();
let resp = client
.post("https://ampcode.com/api/internal")
.header("Authorization", format!("Bearer {api_key}"))
.header("Content-Type", "application/json")
.json(&serde_json::json!({
"method": "userDisplayBalanceInfo",
"params": {}
}))
.send()
.await?;

if !resp.status().is_success() {
anyhow::bail!("Amp usage request failed (HTTP {})", resp.status());
}

let body: ApiResponse = resp.json().await?;
let display_text = body
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
.result
.and_then(|r| r.display_text)
.unwrap_or_default();

let metrics = parse_display_text(&display_text);
let plan = detect_plan(&metrics);

Ok(UsageOutput {
provider: "Amp".into(),
plan,
email: None,
metrics,
})
})
}
Loading