Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## Unreleased

### Fixes

- Claude accounts whose sign-in cannot read the organization's usage credits (a Team plan member gets HTTP 403 from `prepaid/credits`) no longer ask for them on every refresh. Nothing was recorded for a refusal, so each widget instance and each refresh asked again, and the account was soon rate limited (HTTP 429) on the usage endpoint that feeds the Claude card. A 403 or 404 is now remembered for 24 hours per organization and shows no credits, a 429 there pauses the usage endpoint as well, credits are not asked while that pause holds, and switching organization re-checks at once instead of reusing the other organization's balance (#123).

### Thanks

- Thanks to [@guidi-injenia](https://github.com/guidi-injenia) for the report and for logging every request, which showed the refused credits call repeating while the usage request was still served from its cache.

## 2.4.0 - 2026-11-09

A feature release for Dux Shell 2.0 and 2.1. **Detect providers** finds the AI tools, sign-ins and API keys already set up on this computer and tracks them in one click, from a 🔍 button in the dashboard header or the settings. Every quota bar now shows its **pace**: an even-use tick, and a flame when the window runs out before it resets. An optional **Claude Code status line bridge** lets Claude Code hand over its own 5 hour and weekly usage, so the Claude cards stay current while you work and Anthropic's usage endpoint is asked far less often. The dashboard hero is tidier, and DeepSeek reads the right currency of a multi-currency balance. Settings, profiles, pins and history carry over unchanged; run `dms restart` once after updating.
Expand Down
2 changes: 1 addition & 1 deletion docs/provider-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ This document records the upstream surface used by each adapter. It was reviewed
| Command Code | [Provider API](https://commandcode.ai/docs/provider) — experimental `GET https://api.commandcode.ai/alpha/billing/credits`, plus `/alpha/whoami` and `/alpha/billing/subscriptions` | Uses `COMMAND_CODE_API_KEY`, or the `apiKey` written by `cmd login` to protected `~/.commandcode/auth.json`; the explicit environment variable wins. Reports the 5-hour/weekly windows and monthly credit balance when supplied. The experimental response may return null windows for an account; the adapter then exposes the available credit information without fabricating a percentage. |
| OpenCode Go | [Go plan documentation](https://opencode.ai/docs/go/) and the [upstream usage handler](https://github.com/anomalyco/opencode/blob/b5caa022/packages/console/app/src/routes/zen/go/v1/usage.ts) — `GET https://opencode.ai/zen/go/v1/usage` | Uses `OPENCODE_API_KEY`, or the OpenCode CLI key at `${XDG_DATA_HOME:-$HOME/.local/share}/opencode/auth.json`. Returns server-computed 5-hour, weekly, and monthly `usagePercent` plus `resetInSec`; the adapter accepts only a complete valid three-window payload, otherwise it falls back to the documented `/zen/go/v1/models` auth-only endpoint. `useBalance: true` is shown as enabled fallback, never as a made-up balance. The endpoint is upstream-implemented but not a documented public contract, so it is treated as unstable. |
| 9Router | Local provider-owned SQLite/JSON usage store | Requests, tokens, and tracked cost; no network request. |
| Claude Code | Provider-owned local JSONL and credentials under `~/.claude` (or `$CLAUDE_CONFIG_DIR` when set); OAuth `api.anthropic.com/api/oauth/usage` | Local analytics plus the account's own usage endpoint. Since the Claude 5 rollout the response carries a canonical `limits[]` array (`kind`: `session`, `weekly_all`, `weekly_scoped` with `scope.model.display_name`, e.g. a weekly Fable allowance); the adapter prefers it and falls back to the flat `five_hour`/`seven_day` objects. `extra_usage` exposes usage-credit state (`monthly_limit`, `used_credits`, `currency`). The endpoint is account-scoped and undocumented — treated as best-effort. The request adds `?cedar_ember=1` (with a `claude-cli/<version> (external, cli)` User-Agent, which the endpoint requires for that block) to read limit-reset grants (`grants[]`: `resets_left`, `ends_at`, `usable_now`, `paused`), and `spend` gives the monthly spend limit and spend as minor units plus an exponent. Usage credits come from `GET /api/oauth/organizations/<org>/prepaid/credits` (balance and `promo_tranches`), cached for 10 minutes; the organization UUID is read from Claude Code's `.claude.json`. A confirmed reset posts `{program:"cedar_ember", grant_id, request_id}` to `/api/organizations/<org>/reset_rate_limits`, as the Claude Code CLI does. |
| Claude Code | Provider-owned local JSONL and credentials under `~/.claude` (or `$CLAUDE_CONFIG_DIR` when set); OAuth `api.anthropic.com/api/oauth/usage` | Local analytics plus the account's own usage endpoint. Since the Claude 5 rollout the response carries a canonical `limits[]` array (`kind`: `session`, `weekly_all`, `weekly_scoped` with `scope.model.display_name`, e.g. a weekly Fable allowance); the adapter prefers it and falls back to the flat `five_hour`/`seven_day` objects. `extra_usage` exposes usage-credit state (`monthly_limit`, `used_credits`, `currency`). The endpoint is account-scoped and undocumented — treated as best-effort. The request adds `?cedar_ember=1` (with a `claude-cli/<version> (external, cli)` User-Agent, which the endpoint requires for that block) to read limit-reset grants (`grants[]`: `resets_left`, `ends_at`, `usable_now`, `paused`), and `spend` gives the monthly spend limit and spend as minor units plus an exponent. Usage credits come from `GET /api/oauth/organizations/<org>/prepaid/credits` (balance and `promo_tranches`), cached for 10 minutes per organization; the organization UUID is read from Claude Code's `.claude.json`. A `403`/`404` there (a Team member, a plan without usage credits) is recorded and not asked again for 24 hours, and a `429` pauses the usage endpoint too, since both share the account's rate limit. A confirmed reset posts `{program:"cedar_ember", grant_id, request_id}` to `/api/organizations/<org>/reset_rate_limits`, as the Claude Code CLI does. |
| GitHub Copilot | Authenticated `copilot_internal/user` response used by GitHub's Copilot clients | `quota_snapshots.premium_interactions` — `remaining`, `entitlement`, `percent_remaining`, `overage_count`, `unlimited`, `has_quota`. Reset date from top-level `quota_reset_date_utc`. Chat/completions suppressed when `unlimited: true` and `entitlement: 0` (no cap). `token_based_billing: true` marks accounts migrated to GitHub AI Credits (usage-based billing, 2026-06-01); `access_type_sku` distinguishes Education/Student grants (`free_educational_quota`) and free tier from paid Pro, and the adapter surfaces it in the account label. This endpoint is not a documented public API and may change. |
| Antigravity | Local OAuth from the `agy` token file, desktop keyring, or IDE state; Cloud Code Assist `loadCodeAssist` + `retrieveUserQuotaSummary` on `daily-cloudcode-pa.googleapis.com` (fallback `fetchAvailableModels`) | Per-account Gemini / Claude & OpenAI 5-hour and weekly quota windows and resets. Fixture-backed tests cover both methods, malformed windows, fallback, partial account failure, and file-token discovery. The internal endpoints remain explicitly unstable. |
| Z.ai / GLM | [Z.ai API reference](https://docs.z.ai/api-reference/introduction) — `GET /api/monitor/usage/quota/limit`; China mirror on `open.bigmodel.cn` | Timed quota windows, percentages, reset timestamps, remaining units, and plan tier. Falls back to `GET /paas/v4/models` when the quota endpoint is unavailable. |
Expand Down
2 changes: 2 additions & 0 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ If the Claude card shows **Stale** and an older **Updated** time than the last r

After a 429 or 5xx the adapter stops asking until a backoff ends (120 s, doubling per consecutive failure up to 30 minutes, or the server's `Retry-After` when longer), and the card's **Updated** line shows **Rate limited · next try HH:MM**. A manual refresh honours that backoff too, since asking again only extends the limit. The limit is per account and shared with Claude Code and with any other tool polling the same endpoint (another quota widget, a status line script): if the backoff keeps returning, raise **Refresh interval** and stop the other pollers. `./providers/get-claude-usage | grep -E '^USAGE_RETRY_(AT|REASON)='` shows the current backoff, and `claude-usage-backoff.json` under `~/.cache/AiOverviewControl/claude-profiles/<hash>/` holds it; deleting that file ends it early.

Usage credits come from a separate organization endpoint that shares the same rate limit. A Team plan member, or a plan without usage credits, gets HTTP 403 there; the card then shows no credits and the adapter does not ask again for 24 hours (`claude-prepaid-cache.json` in the same folder records the answer; deleting it re-checks at the next refresh). A 429 on that endpoint starts the same backoff as the usage endpoint.

## Copilot

```bash
Expand Down
45 changes: 38 additions & 7 deletions providers/get-claude-usage
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ USAGE_BACKOFF="${ACCOUNT_CACHE}/claude-usage-backoff.json"
USAGE_BACKOFF_MAX=1800 # seconds: cap of the doubling
USAGE_RETRY_AFTER_MAX=3600 # seconds: the longest Retry-After honoured
PREPAID_CACHE_TTL=600 # seconds: the credit balance moves with spend, not per poll
# A 403 or 404 means the organization's credits cannot be read with this
# sign-in (a Team member, a plan without usage credits). That answer does not
# change per poll, so it is not asked again for a day (issue #123).
PREPAID_UNAVAILABLE_TTL=86400 # seconds
# Rate limits Claude Code passed to providers/claude-statusline-bridge. A
# reading confirmed within STATUSLINE_MAX_AGE replaces the endpoint's session
# and weekly numbers when it is newer, and stretches the endpoint's cache to
Expand Down Expand Up @@ -495,28 +499,55 @@ elif [ -f "$CREDENTIALS" ]; then
| .usableNow = any(.items[]; .usableNow and (.paused | not) and .resetsLeft > 0)' 2>/dev/null || true)

# Usage credits (prepaid and promotional) live on an organization
# endpoint. A failed read keeps the last good balance.
# endpoint. Every answer is recorded with the organization it is for, so
# each widget instance and refresh asks at most once per TTL: a refusal
# (403, 404) for PREPAID_UNAVAILABLE_TTL and shows no balance, any other
# failure for PREPAID_CACHE_TTL and keeps the last good balance.
ORG_UUID="$(claude_org_uuid "$CLAUDE_DIR" || true)"
if [ -f "$PREPAID_CACHE" ] && [ -n "$ORG_UUID" ] && ! jq -e --arg org "$ORG_UUID" \
'(.org // $org) == $org' "$PREPAID_CACHE" >/dev/null 2>&1; then
# Another organization's balance or refusal: never show or honour it.
rm -f "$PREPAID_CACHE"
fi
PREPAID_FRESH=false
if [ -f "$PREPAID_CACHE" ]; then
prepaid_ts=$(jq -r '.cached_at // 0' "$PREPAID_CACHE" 2>/dev/null || echo 0)
IFS=$'\t' read -r prepaid_ts prepaid_last < <(jq -r '
[((.checked_at // .cached_at) | numbers | floor) // 0,
((.status | strings | select(test("^[0-9]{3}$"))) // "200")] | @tsv' \
"$PREPAID_CACHE" 2>/dev/null) || true
case "${prepaid_ts:-}" in '' | *[!0-9]*) prepaid_ts=0 ;; esac
prepaid_ttl="$PREPAID_CACHE_TTL"
case "${prepaid_last:-}" in 403 | 404) prepaid_ttl="$PREPAID_UNAVAILABLE_TTL" ;; esac
prepaid_age=$(( $(date +%s) - prepaid_ts ))
[ "$prepaid_age" -lt 0 ] || [ "$prepaid_age" -ge "$PREPAID_CACHE_TTL" ] || PREPAID_FRESH=true
[ "$prepaid_age" -lt 0 ] || [ "$prepaid_age" -ge "$prepaid_ttl" ] || PREPAID_FRESH=true
fi
# A backoff covers this endpoint too: it shares the account's rate limit.
if [ "$PREPAID_FRESH" != true ] && [ -z "$USAGE_ERROR_KIND" ] && [ -z "$USAGE_RETRY_AT" ] \
&& ORG_UUID="$(claude_org_uuid "$CLAUDE_DIR")"; then
&& ! usage_backoff_active && [ -n "$ORG_UUID" ]; then
TOKEN=$(jq -r '(.claudeAiOauth.accessToken | strings | select(test("^[^\\s]+$"))) // ""' "$CREDENTIALS")
prepaid_body=$(mktemp)
declare -a prepaid_request=(-sS --max-time 8 -o "$prepaid_body" -w '%{http_code}'
prepaid_headers=$(mktemp)
declare -a prepaid_request=(-sS --max-time 8 -o "$prepaid_body" -D "$prepaid_headers" -w '%{http_code}'
-H "Accept: application/json"
-H "User-Agent: claude-cli/${CLAUDE_VERSION} (external, cli)"
-H "anthropic-beta: oauth-2025-04-20"
"https://api.anthropic.com/api/oauth/organizations/${ORG_UUID}/prepaid/credits")
prepaid_status=$(curl "${prepaid_request[@]}" --config <(curl_header_config "Authorization: Bearer ${TOKEN}") 2>/dev/null || true)
case "$prepaid_status" in [0-9][0-9][0-9]) ;; *) prepaid_status="000" ;; esac
# The answer and its time, with the balance to show until the next one.
prepaid_data="null"
if [ "$prepaid_status" = "200" ] && jq -e 'type == "object"' "$prepaid_body" >/dev/null 2>&1; then
jq -c '{cached_at: (now | floor), data: .}' "$prepaid_body" > "$PREPAID_CACHE" 2>/dev/null || true
prepaid_data="$(jq -c . "$prepaid_body")"
else
[ "$prepaid_status" != "200" ] || prepaid_status="000"
# The usage endpoint shares this rate limit: a 429 here pauses both.
[ "$prepaid_status" != "429" ] || record_usage_backoff "$prepaid_status" "$prepaid_headers"
# A refusal shows no balance; any other failure keeps the last one.
case "$prepaid_status" in 403 | 404) ;; *) prepaid_data="$(jq -c '.data // null' "$PREPAID_CACHE" 2>/dev/null || echo null)" ;; esac
fi
rm -f "$prepaid_body"
[ -n "$prepaid_data" ] || prepaid_data="null"
jq -cn --arg org "$ORG_UUID" --arg status "$prepaid_status" --argjson data "$prepaid_data" '{checked_at: (now | floor), status: $status, org: $org, data: $data}' > "$PREPAID_CACHE" 2>/dev/null || true
rm -f "$prepaid_body" "$prepaid_headers"
fi
if [ -f "$PREPAID_CACHE" ]; then
CLAUDE_PREPAID=$(jq -c '
Expand Down
Loading
Loading