-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
260 lines (209 loc) · 7.98 KB
/
Copy pathreport.py
File metadata and controls
260 lines (209 loc) · 7.98 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
"""Turn raw API payloads into summaries, day breakdowns and CSV rows."""
import csv
from collections import OrderedDict
from datetime import datetime, timezone
# --- field extraction -----------------------------------------------------
def _i(d, k):
try:
return int(d.get(k, 0) or 0)
except (TypeError, ValueError):
return 0
def _f(d, k):
try:
return float(d.get(k, 0) or 0)
except (TypeError, ValueError):
return 0.0
def event_row(ev):
"""Flatten one ``usageEventsDisplay`` entry into a plain dict."""
tu = ev.get("tokenUsage") or {}
ts_ms = _i(ev, "timestamp")
local = datetime.fromtimestamp(ts_ms / 1000).astimezone() if ts_ms else None
return OrderedDict([
("datetime_local", local.isoformat() if local else ""),
("timestamp_ms", ts_ms),
("date", local.strftime("%Y-%m-%d") if local else ""),
("model", ev.get("model", "")),
("kind", ev.get("kind", "")),
("input_tokens", _i(tu, "inputTokens")),
("output_tokens", _i(tu, "outputTokens")),
("cache_read_tokens", _i(tu, "cacheReadTokens")),
("cache_write_tokens", _i(tu, "cacheWriteTokens")),
("value_cents", round(_f(tu, "totalCents"), 6)),
("charged_cents", round(_f(ev, "chargedCents"), 6)),
("requests_costs", ev.get("requestsCosts", 0)),
("is_headless", bool(ev.get("isHeadless", False))),
("owning_user", ev.get("owningUser", "")),
])
# --- formatting helpers ---------------------------------------------------
def _money(cents):
return "$%s" % format(cents / 100.0, ",.2f")
def _n(x):
return format(int(x), ",")
def _rule(width=78):
return "-" * width
# --- summary (from aggregated endpoint) -----------------------------------
def render_summary(agg, meta):
rows = agg.get("aggregations", []) or []
cents = lambda r: _f(r, "totalCents")
total = sum(cents(r) for r in rows)
ti = sum(_i(r, "inputTokens") for r in rows)
to = sum(_i(r, "outputTokens") for r in rows)
tcr = sum(_i(r, "cacheReadTokens") for r in rows)
tcw = sum(_i(r, "cacheWriteTokens") for r in rows)
out = ["=" * 78]
out.append("CURSOR USAGE | %s | %s -> %s"
% (meta["email"], meta["start"], meta["end"]))
out.append("=" * 78)
out.append("Included value used : %s (compute consumed; included in plan)" % _money(total))
out.append("Tokens in=%s out=%s" % (_n(ti), _n(to)))
out.append(" cacheRead=%s cacheWrite=%s" % (_n(tcr), _n(tcw)))
out.append(_rule())
out.append("%-36s%10s%14s%12s" % ("model", "$ value", "in tok", "out tok"))
out.append(_rule())
for r in sorted(rows, key=lambda x: -cents(x)):
out.append("%-36s%10s%14s%12s" % (
r.get("modelIntent", "?"),
format(cents(r) / 100.0, ",.2f"),
_n(_i(r, "inputTokens")),
_n(_i(r, "outputTokens")),
))
return "\n".join(out)
# --- per-day breakdown (from events) --------------------------------------
def render_by_day(events, meta):
days = OrderedDict()
for ev in events:
row = event_row(ev)
d = row["date"] or "unknown"
b = days.setdefault(d, {"n": 0, "in": 0, "out": 0, "cents": 0.0})
b["n"] += 1
b["in"] += row["input_tokens"]
b["out"] += row["output_tokens"]
b["cents"] += row["value_cents"]
out = ["=" * 78]
out.append("CURSOR USAGE BY DAY | %s | %s -> %s"
% (meta["email"], meta["start"], meta["end"]))
out.append("=" * 78)
out.append("%-12s%9s%12s%15s%13s" % ("date", "events", "$ value", "in tok", "out tok"))
out.append(_rule())
tot = {"n": 0, "in": 0, "out": 0, "cents": 0.0}
for d in sorted(days):
b = days[d]
out.append("%-12s%9s%12s%15s%13s" % (
d, _n(b["n"]), format(b["cents"] / 100.0, ",.2f"), _n(b["in"]), _n(b["out"])))
for k in tot:
tot[k] += b[k]
out.append(_rule())
out.append("%-12s%9s%12s%15s%13s" % (
"TOTAL", _n(tot["n"]), format(tot["cents"] / 100.0, ",.2f"),
_n(tot["in"]), _n(tot["out"])))
return "\n".join(out)
# --- CSV ------------------------------------------------------------------
def write_csv(events, path):
rows = [event_row(e) for e in events]
rows.sort(key=lambda r: r["timestamp_ms"])
fields = list(event_row({}).keys())
with open(path, "w", newline="", encoding="utf-8") as fh:
writer = csv.DictWriter(fh, fieldnames=fields)
writer.writeheader()
writer.writerows(rows)
return len(rows)
def to_iso(ms):
return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
# --- cycle limits (from get-current-period-usage / usage-summary) --------
def _optional_f(d, k):
if k not in d:
return None
try:
v = d[k]
if v is None:
return None
return float(v or 0)
except (TypeError, ValueError):
return None
def _optional_i(d, k):
if k not in d:
return None
try:
v = d[k]
if v is None:
return None
return int(v or 0)
except (TypeError, ValueError):
return None
def _parse_reset_date(payload):
raw = payload.get("billingCycleEnd")
if raw is None:
return None
try:
s = str(raw).strip()
if s.isdigit():
ms = int(s)
return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).strftime(
"%Y-%m-%d")
return datetime.fromisoformat(s.replace("Z", "+00:00")).strftime(
"%Y-%m-%d")
except (TypeError, ValueError, OSError):
return None
def _limit_bar(pct, width=30):
filled = int(round(pct / 100.0 * width))
filled = max(0, min(width, filled))
return "#" * filled + "." * (width - filled)
def _limit_bucket_line(label, pct):
if pct is None:
return None
bar = _limit_bar(pct)
left = max(0.0, 100.0 - pct)
return "%-16s[%s] %6.1f%% used, %6.1f%% left" % (label, bar, pct, left)
def render_limits(payload):
"""Render cycle-limit % bars and included-usage dollars, or None."""
if not payload or not isinstance(payload, dict):
return None
plan = (payload.get("planUsage")
or (payload.get("individualUsage") or {}).get("plan")
or {})
enabled = payload.get("enabled", plan.get("enabled", True))
if not enabled:
return None
is_unlimited = bool(payload.get("isUnlimited"))
auto_pct = _optional_f(plan, "autoPercentUsed")
api_pct = _optional_f(plan, "apiPercentUsed")
used = None
if "totalSpend" in plan:
used = _optional_i(plan, "totalSpend")
if used is None and "used" in plan:
used = _optional_i(plan, "used")
limit = _optional_i(plan, "limit") if "limit" in plan else None
remaining = None
if "remaining" in plan:
remaining = _optional_i(plan, "remaining")
if remaining is None and limit is not None and used is not None:
remaining = max(0, limit - used)
money_line = None
if limit is not None and limit > 0 and used is not None and remaining is not None:
money_line = "%-16s%s of %s used (%s left)" % (
"Included usage", _money(used), _money(limit), _money(remaining))
if (not is_unlimited and auto_pct is None and api_pct is None
and not money_line):
return None
reset = _parse_reset_date(payload)
out = ["=" * 78]
header = "CURSOR CYCLE LIMITS"
if reset:
header += " | resets %s" % reset
out.append(header)
out.append("=" * 78)
if is_unlimited:
out.append("Plan reports unlimited usage for this cycle.")
if money_line:
out.append(money_line)
return "\n".join(out)
for label, pct in [("Composer / Auto", auto_pct),
("Other models", api_pct)]:
line = _limit_bucket_line(label, pct)
if line:
out.append(line)
if money_line:
out.append(money_line)
if len(out) <= 3:
return None
return "\n".join(out)