creds="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json" fail() { jq -cn --arg e "$1" '{error: $e}' exit 0 } [ -r "$creds" ] || fail "not logged in" # The refresh token rotates, so the new one must be written back or the CLI's # next refresh fails and forces a re-login. refresh() { local rt scope body code tmp rt="$(jq -r '.claudeAiOauth.refreshToken // empty' "$creds")" [ -n "$rt" ] || fail "no refresh token" scope="$(jq -r '.claudeAiOauth.scopes // [] | join(" ")' "$creds")" body="$(mktemp)" code="$(jq -cn --arg rt "$rt" --arg s "$scope" \ '{grant_type: "refresh_token", refresh_token: $rt, client_id: "9d1c250a-e61b-44d9-88ed-5944d1962f5e", scope: $s}' \ | curl -s -m 20 -o "$body" -w '%{http_code}' \ https://platform.claude.com/v1/oauth/token \ -H 'Content-Type: application/json' --data-binary @-)" || code=000 if [ "$code" != 200 ]; then rm -f "$body" fail "token refresh HTTP $code" fi tmp="$(mktemp "$creds.XXXXXX")" chmod 600 "$tmp" jq --slurpfile r "$body" '.claudeAiOauth += { accessToken: $r[0].access_token, refreshToken: ($r[0].refresh_token // .claudeAiOauth.refreshToken), expiresAt: (now * 1000 + $r[0].expires_in * 1000 | floor) }' "$creds" > "$tmp" && mv "$tmp" "$creds" rm -f "$body" "$tmp" } expired() { jq -e '(.claudeAiOauth.expiresAt // 0) < (now * 1000 + 300000)' "$creds" >/dev/null } if expired; then exec 9>"${XDG_RUNTIME_DIR:-/tmp}/claude-usage.lock" flock 9 # Another run may have refreshed while this one waited. if expired; then refresh; fi fi token="$(jq -r '.claudeAiOauth.accessToken // empty' "$creds")" [ -n "$token" ] || fail "not logged in" body="$(curl -s -m 20 -w '\n%{http_code}' https://api.anthropic.com/api/oauth/usage \ -H "Authorization: Bearer $token" \ -H 'anthropic-beta: oauth-2025-04-20')" || fail "usage request failed" code="${body##*$'\n'}" [ "$code" = 200 ] || fail "usage HTTP $code" printf '%s' "${body%$'\n'*}" | jq -c . || fail "bad usage response"