-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_usage.py
More file actions
executable file
·347 lines (281 loc) · 11.1 KB
/
fetch_usage.py
File metadata and controls
executable file
·347 lines (281 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import json
import os
import sys
import tempfile
from datetime import datetime
from typing import Any
try:
import requests
except ImportError:
print(
json.dumps(
{
"error": "Python 'requests' module not installed. Run: python3 -m pip install requests"
}
)
)
sys.exit(0)
OAUTH_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"
OAUTH_TOKEN_URL = "https://console.anthropic.com/v1/oauth/token"
OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
CREDENTIALS_PATH = os.path.join(os.path.expanduser("~"), ".claude", ".credentials.json")
CACHE_DIR = os.path.join(
os.path.expanduser("~"), ".local", "share", "claude-usage-tracker"
)
def _atomic_write_json(filepath: str, data: Any, mode: int = 0o600) -> bool:
"""Write JSON to a file atomically using write-to-temp-then-rename.
Prevents data corruption if the process is interrupted mid-write.
Returns:
True on success, False on failure.
"""
dir_path = os.path.dirname(filepath)
fd, tmp_path = tempfile.mkstemp(dir=dir_path, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=2)
os.chmod(tmp_path, mode)
os.rename(tmp_path, filepath)
return True
except OSError:
try:
os.unlink(tmp_path)
except OSError:
pass
return False
def _is_token_expired(oauth_data: dict) -> bool:
"""Check if the access token is expired."""
expires_at = oauth_data.get("expiresAt")
if not expires_at or not isinstance(expires_at, (int, float)):
return True
if expires_at > 1e12: # milliseconds
expires_at = expires_at / 1000
return datetime.fromtimestamp(expires_at) < datetime.now()
def _refresh_token(credentials_data: dict) -> tuple[str | None, str | None]:
"""Refresh the OAuth access token using the refresh token.
Updates the credentials file on success.
Returns:
Tuple of (access_token, subscription_type) or (None, None) on failure.
"""
oauth_data = credentials_data.get("claudeAiOauth", {})
refresh_token = oauth_data.get("refreshToken")
if not refresh_token:
return None, None
try:
response = requests.post(
OAUTH_TOKEN_URL,
json={
"grant_type": "refresh_token",
"client_id": OAUTH_CLIENT_ID,
"refresh_token": refresh_token,
},
headers={"Content-Type": "application/json"},
timeout=15,
)
if response.status_code != 200:
return None, None
token_data = response.json()
new_access_token = token_data.get("access_token")
if not new_access_token:
return None, None
# Update credentials in memory and on disk
oauth_data["accessToken"] = new_access_token
if token_data.get("refresh_token"):
oauth_data["refreshToken"] = token_data["refresh_token"]
if token_data.get("expires_in"):
oauth_data["expiresAt"] = int(
(datetime.now().timestamp() + token_data["expires_in"]) * 1000
)
credentials_data["claudeAiOauth"] = oauth_data
_atomic_write_json(CREDENTIALS_PATH, credentials_data)
subscription_type = oauth_data.get("subscriptionType", "unknown")
return new_access_token, subscription_type
except (requests.exceptions.RequestException, json.JSONDecodeError):
return None, None
def load_credentials_from_file() -> tuple[str | None, str | None]:
"""Load OAuth credentials from the Claude Code CLI credentials file.
Automatically refreshes expired tokens using the refresh token.
Returns:
Tuple of (access_token, subscription_type) or (None, None) on failure.
"""
if not os.path.exists(CREDENTIALS_PATH):
return None, None
try:
with open(CREDENTIALS_PATH, "r") as f:
data = json.load(f)
oauth_data = data.get("claudeAiOauth", {})
token = oauth_data.get("accessToken")
subscription_type = oauth_data.get("subscriptionType", "unknown")
if not token:
return None, None
# If token is expired, try to refresh it
if _is_token_expired(oauth_data):
return _refresh_token(data)
return token, subscription_type
except (json.JSONDecodeError, IOError, OSError):
return None, None
def create_empty_result() -> dict[str, Any]:
"""Create an empty result structure."""
return {
"session": {"used": 0, "limit": 100},
"weekly": {"used": 0, "limit": 100},
"sonnet": {"used": 0, "limit": 100},
"opus": {"used": 0, "limit": 100},
"subscriptionType": "unknown",
"lastUpdated": datetime.now().strftime("%H:%M:%S"),
"error": None,
}
def parse_usage_item(data: dict, api_key: str) -> dict[str, Any]:
"""Parse a single usage item from the API response."""
item = data.get(api_key)
if not item or not isinstance(item, dict):
return {"used": 0, "limit": 100}
result: dict[str, Any] = {
"used": item.get("utilization", 0),
"limit": 100,
}
if item.get("resets_at"):
result["resetsAt"] = item["resets_at"]
return result
def _make_usage_request(token: str) -> requests.Response:
"""Make a GET request to the usage API."""
headers = {
"Authorization": f"Bearer {token}",
"anthropic-beta": "oauth-2025-04-20",
"Accept": "application/json",
}
return requests.get(OAUTH_USAGE_URL, headers=headers, timeout=15)
def fetch_usage() -> dict[str, Any]:
"""Fetch current usage data from Claude OAuth API."""
result = create_empty_result()
# Load credentials
token, subscription_type = load_credentials_from_file()
if not token:
result["error"] = "No credentials found. Run: claude login"
return result
result["subscriptionType"] = subscription_type or "unknown"
try:
response = _make_usage_request(token)
# On 401, try refreshing the token once
if response.status_code == 401:
try:
with open(CREDENTIALS_PATH, "r") as f:
cred_data = json.load(f)
new_token, new_sub = _refresh_token(cred_data)
if new_token:
token = new_token
result["subscriptionType"] = new_sub or "unknown"
response = _make_usage_request(token)
except (json.JSONDecodeError, IOError, OSError):
pass
if response.status_code == 401:
result["error"] = "Session expired. Run: claude login"
return result
if response.status_code == 403:
result["error"] = "Access denied. Check your subscription."
return result
if response.status_code == 429:
result["rateLimited"] = True
result["error"] = "Rate limited — using cached data"
return result
if response.status_code != 200:
result["error"] = f"API error: {response.status_code}"
return result
data = response.json()
result["session"] = parse_usage_item(data, "five_hour")
result["weekly"] = parse_usage_item(data, "seven_day")
result["sonnet"] = parse_usage_item(data, "seven_day_sonnet")
result["opus"] = parse_usage_item(data, "seven_day_opus")
# Extra usage (paid overage) — API returns credits in cents
extra = data.get("extra_usage")
if extra and isinstance(extra, dict) and extra.get("is_enabled"):
result["extra"] = {
"used": extra.get("used_credits", 0) / 100,
"limit": extra.get("monthly_limit", 0) / 100,
"utilization": extra.get("utilization", 0),
}
except requests.exceptions.Timeout:
result["error"] = "Request timeout"
except requests.exceptions.ConnectionError:
result["error"] = "Connection error"
except requests.exceptions.RequestException as e:
result["error"] = f"Request failed: {e}"
except json.JSONDecodeError:
result["error"] = "Invalid API response"
return result
def update_daily_history(usage: dict[str, Any]) -> list[dict[str, Any]]:
"""Update daily usage history and return the last 7 days as an array.
Each entry records the peak session usage observed for that date.
"""
history_file = os.path.join(CACHE_DIR, "history.json")
history: dict[str, dict[str, Any]] = {}
try:
if os.path.exists(history_file):
with open(history_file, "r") as f:
history = json.load(f)
except (json.JSONDecodeError, OSError):
history = {}
today = datetime.now().strftime("%Y-%m-%d")
session_pct = usage.get("session", {}).get("used", 0)
weekly_pct = usage.get("weekly", {}).get("used", 0)
# Keep the peak session usage for each day
existing = history.get(today, {})
prev_session = existing.get("session", 0)
history[today] = {
"session": max(session_pct, prev_session),
"weekly": weekly_pct,
}
# Prune entries older than 7 days
cutoff = datetime.now().timestamp() - 7 * 86400
pruned: dict[str, dict[str, Any]] = {}
for date, data in history.items():
try:
if datetime.strptime(date, "%Y-%m-%d").timestamp() >= cutoff:
pruned[date] = data
except ValueError:
pass # Skip corrupted date entries
history = pruned
_atomic_write_json(history_file, history)
# Convert to sorted array for QML consumption
day_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
result = []
for date_str in sorted(history.keys()):
dt = datetime.strptime(date_str, "%Y-%m-%d")
day_name = day_names[dt.weekday()]
entry = history[date_str]
result.append(
{
"day": day_name,
"date": date_str,
"percent": entry.get("session", 0),
}
)
return result
def main() -> None:
usage = fetch_usage()
os.makedirs(CACHE_DIR, mode=0o700, exist_ok=True)
cache_file = os.path.join(CACHE_DIR, "usage.json")
# On rate limit, serve cached data with rateLimited flag
if usage.get("rateLimited"):
try:
if os.path.exists(cache_file):
with open(cache_file, "r") as f:
cached = json.load(f)
cached["rateLimited"] = True
cached["error"] = None
print(json.dumps(cached))
return
except (json.JSONDecodeError, OSError):
pass
# No usable cache — fall through and output the error result
print(json.dumps(usage))
return
# Update daily history (only if no error)
if not usage.get("error"):
usage["dailyHistory"] = update_daily_history(usage)
# Cache result (after history is added so cached loads include it)
if not _atomic_write_json(cache_file, usage):
print("Warning: failed to write cache file", file=sys.stderr)
# Output to stdout for DataSource
print(json.dumps(usage))
if __name__ == "__main__":
main()