Repository navigation
Expand file tree
/
Copy pathcodex-usage
More file actions
executable file
·394 lines (349 loc) · 16.4 KB
/
Copy pathcodex-usage
File metadata and controls
executable file
·394 lines (349 loc) · 16.4 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#!/usr/bin/env python3
"""Per-session usage view for the OpenAI Codex CLI — the codex analogue of
claude-usage (claude/cost in ArduPilot/DevTools).
Codex writes one rollout transcript per session under
$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<ts>-<UUID>.jsonl. Every assistant turn
emits an `event_msg` of type `token_count` that records BOTH:
* per-turn token usage (`info.last_token_usage`: input / cached_input / output /
reasoning_output / total), and
* the live account rate-limit meter (`rate_limits.primary` and
`rate_limits.secondary`), each with `used_percent`, `resets_at` and
`window_minutes`, plus `plan_type`. The primary/secondary slots do NOT
have fixed window lengths — the weekly (10080-minute) window shows up in
`primary` too — so each window is labelled from its own window_minutes.
So unlike claude-usage (which has to calibrate the 5h ceiling), this reads the
REAL quota percentage straight from the data. It shows that headline meter, then
breaks down per-session/project token consumption so you can see which open
Codex session is eating the most — subagent threads are rolled into the parent
that spawned them.
Usage:
codex-usage # quota meter + sessions active in the last 24h
codex-usage --window 5h # attribute over the 5h quota window (or 24h, 7d, total)
codex-usage --all # every session ever
codex-usage --top N # rows to show (default 20)
codex-usage --by-project # aggregate by project dir instead of per session
codex-usage --api-cost # show USD at OpenAI API list prices instead of tokens
"""
import argparse
import json
import os
from datetime import datetime, timezone, timedelta
from glob import glob
CODEX_HOME = os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
SESSIONS = os.path.join(CODEX_HOME, "sessions")
# OpenAI API list price, USD per token, for the --api-cost estimate (what the
# usage WOULD cost billed pay-as-you-go; on a Codex subscription you are not
# actually charged this). Keyed by model-name substring; unknown -> gpt-5.5.
# gpt-5.5: $5/1M input, $0.50/1M cached input, $30/1M output (output incl. reasoning)
PRICING = {
"gpt-5.5": dict(inp=5e-6, cached=0.5e-6, out=30e-6),
"gpt-5": dict(inp=5e-6, cached=0.5e-6, out=30e-6),
}
DEFAULT_PRICE = PRICING["gpt-5.5"]
def price_for(model):
m = (model or "").lower()
for k, v in PRICING.items():
if k in m:
return v
return DEFAULT_PRICE
def cost_of(last, model):
"""USD API-list-price estimate for one token_count delta."""
p = price_for(model)
din = last.get("input_tokens", 0) or 0
dcached = last.get("cached_input_tokens", 0) or 0
dout = last.get("output_tokens", 0) or 0
return max(0, din - dcached) * p["inp"] + dcached * p["cached"] + dout * p["out"]
def parse_ts(s):
if not s:
return None
try:
return datetime.fromisoformat(s.replace("Z", "+00:00"))
except ValueError:
return None
def short(s, n=46):
return " ".join((s or "").split())[:n]
def human_age(dt, now):
if dt is None:
return "?"
sec = (now - dt).total_seconds()
if sec < 90:
return f"{int(sec)}s"
if sec < 5400:
return f"{int(sec//60)}m"
if sec < 36 * 3600:
return f"{int(sec//3600)}h"
return f"{int(sec//86400)}d"
def human_until(epoch, now):
if not epoch:
return "?"
sec = epoch - now.timestamp()
if sec <= 0:
return "now"
if sec < 5400:
return f"{int(sec//60)}m"
if sec < 86400:
return f"{int(sec//3600)}h{int((sec%3600)//60):02d}m"
return f"{int(sec//86400)}d{int((sec%86400)//3600)}h"
def fmt_tok(x):
x = int(x)
if x >= 1_000_000:
return f"{x/1e6:.1f}M"
if x >= 1000:
return f"{x/1e3:.0f}k"
return str(x)
def fmt_money(x):
if x >= 1000:
return f"${x/1000:.1f}k"
return f"${x:.2f}"
def scan():
"""Return (sessions dict, latest_rate_limits or None, now)."""
now = datetime.now(timezone.utc)
S = {}
latest_rl = None # (epoch, rate_limits dict)
files = glob(os.path.join(SESSIONS, "*", "*", "*", "rollout-*.jsonl"))
files += glob(os.path.join(CODEX_HOME, "archived_sessions", "rollout-*.jsonl"))
for fp in files:
sid = None
rec = None
try:
fh = open(fp, "r", errors="ignore")
except OSError:
continue
with fh:
for line in fh:
if '"type"' not in line:
continue
try:
o = json.loads(line)
except json.JSONDecodeError:
continue
typ = o.get("type")
p = o.get("payload") or {}
if typ == "session_meta":
sid = p.get("id")
if sid is None:
continue
parent = None
if p.get("thread_source") == "subagent":
def dig(d, *ks):
for k in ks:
d = d.get(k) if isinstance(d, dict) else None
return d
parent = dig(p, "source", "subagent", "thread_spawn", "parent_thread_id") \
or p.get("forked_from_id")
rec = S.setdefault(sid, dict(
id=sid, cwd=p.get("cwd", ""), parent=parent,
is_sub=p.get("thread_source") == "subagent",
model=p.get("model_provider", ""), title="",
first=None, last=None, turns=0,
tok={"5h": 0, "24h": 0, "7d": 0, "total": 0},
out={"5h": 0, "24h": 0, "7d": 0, "total": 0},
cost={"5h": 0.0, "24h": 0.0, "7d": 0.0, "total": 0.0}))
if rec["parent"] is None and parent:
rec["parent"] = parent
continue
if rec is None:
# transcript without a leading session_meta we parsed; skip
continue
# the actual model (e.g. gpt-5.5) lives in turn_context, not session_meta
if typ == "turn_context" and p.get("model"):
rec["model"] = p["model"]
continue
ts = parse_ts(o.get("timestamp"))
# title: first real (non-context) user message
if not rec["title"]:
txt = None
if typ == "event_msg" and p.get("type") == "user_message":
txt = p.get("message") or p.get("text")
elif typ == "response_item" and p.get("type") == "message" \
and p.get("role") == "user":
c = p.get("content")
if isinstance(c, list):
txt = " ".join(x.get("text", "") for x in c if isinstance(x, dict))
elif isinstance(c, str):
txt = c
if txt and not txt.lstrip().startswith("<"):
rec["title"] = short(txt)
if typ != "event_msg" or p.get("type") != "token_count":
continue
info = p.get("info") or {}
last = info.get("last_token_usage") or {}
if ts:
rec["first"] = ts if rec["first"] is None else min(rec["first"], ts)
rec["last"] = ts if rec["last"] is None else max(rec["last"], ts)
rl = p.get("rate_limits")
if rl and rl.get("primary") and ts:
e = ts.timestamp()
if latest_rl is None or e > latest_rl[0]:
latest_rl = (e, rl)
# rate-limit-only events have no usage, and a repeated event has an
# unchanged running total: neither is a new turn
total = (info.get("total_token_usage") or {}).get("total_tokens")
if not last or (total is not None and total == rec.get("prev_total")):
continue
rec["prev_total"] = total
dtot = last.get("total_tokens", 0) or 0
dout = last.get("output_tokens", 0) or 0
dcost = cost_of(last, rec["model"])
rec["turns"] += 1
# window buckets
for w, secs in (("5h", 5 * 3600), ("24h", 86400), ("7d", 7 * 86400)):
if ts and (now - ts).total_seconds() <= secs:
rec["tok"][w] += dtot
rec["out"][w] += dout
rec["cost"][w] += dcost
rec["tok"]["total"] += dtot
rec["out"]["total"] += dout
rec["cost"]["total"] += dcost
return S, latest_rl, now
def root_of(sid, S, _seen=None):
"""Resolve a subagent session to the parent that spawned it (follow chain)."""
_seen = _seen or set()
rec = S.get(sid)
if not rec or not rec.get("parent") or sid in _seen:
return sid
_seen.add(sid)
if rec["parent"] in S:
return root_of(rec["parent"], S, _seen)
return rec["parent"] # parent not scanned -> use its id as the root key
def window_label(minutes):
"""Name a rate-limit window from its length.
The meter's `primary`/`secondary` slots do not have fixed meanings — the
weekly window turns up in `primary` too — so always derive the label from
window_minutes rather than from which slot it arrived in.
"""
if minutes is None:
return "?"
if minutes >= 10080:
return "weekly"
if minutes >= 1440:
return f"{int(round(minutes / 1440))}d"
if minutes >= 60:
return f"{int(round(minutes / 60))}h"
return f"{int(minutes)}m"
def bar(pct, width=20):
pct = max(0.0, min(100.0, pct))
n = int(round(pct / 100 * width))
return "#" * n + "." * (width - n)
def main():
ap = argparse.ArgumentParser(description="Per-session Codex usage + real rate-limit meter.")
ap.add_argument("--window", default="24h", choices=["5h", "24h", "7d", "total"],
help="window to attribute session tokens over (default 24h). 5h = the quota window, 7d = the weekly window")
ap.add_argument("--all", action="store_true", help="show all sessions, no active-window filter")
ap.add_argument("--top", type=int, default=20, help="max rows (default 20)")
ap.add_argument("--by-project", action="store_true", help="aggregate by project dir, not per session")
ap.add_argument("--api-cost", "--dollars", dest="api_cost", action="store_true",
help="show what the usage WOULD cost at OpenAI API pay-as-you-go rates "
"(USD est.) instead of token counts; you are not billed this on a subscription")
args = ap.parse_args()
win_s = None if args.window == "total" else {"5h": 5 * 3600, "24h": 86400, "7d": 7 * 86400}[args.window]
S, latest_rl, now = scan()
# ---- merge subagents into their root session ----
roots = {}
for sid, rec in S.items():
rk = root_of(sid, S)
r = roots.get(rk)
if r is None:
base = S.get(rk, rec)
r = roots[rk] = dict(id=rk, cwd=base.get("cwd", "") or rec["cwd"],
title=base.get("title", ""), model=base.get("model", ""),
first=None, last=None, turns=0, subs=0,
tok={k: 0 for k in rec["tok"]}, out={k: 0 for k in rec["out"]},
cost={k: 0.0 for k in rec["cost"]})
if rec["is_sub"] and rk != sid:
r["subs"] += 1
r["turns"] += rec["turns"]
for k in r["tok"]:
r["tok"][k] += rec["tok"][k]
r["out"][k] += rec["out"][k]
r["cost"][k] += rec["cost"][k]
for f in ("first",):
if rec[f] and (r[f] is None or rec[f] < r[f]):
r[f] = rec[f]
if rec["last"] and (r["last"] is None or rec["last"] > r["last"]):
r["last"] = rec["last"]
if not r["title"] and rec["title"]:
r["title"] = rec["title"]
if not r["cwd"] and rec["cwd"]:
r["cwd"] = rec["cwd"]
rows = list(roots.values())
if not args.all and win_s is not None:
cut = now - timedelta(seconds=win_s)
rows = [r for r in rows if r["last"] and r["last"] >= cut]
# ---- optional project aggregation ----
if args.by_project:
proj = {}
for r in rows:
key = r["cwd"] or "?"
q = proj.get(key)
if q is None:
q = proj[key] = dict(cwd=key, title="", model=r["model"], turns=0, subs=0,
first=None, last=None,
tok={k: 0 for k in r["tok"]}, out={k: 0 for k in r["out"]},
cost={k: 0.0 for k in r["cost"]}, nsess=0)
q["nsess"] += 1
q["turns"] += r["turns"]
for k in q["tok"]:
q["tok"][k] += r["tok"][k]
q["out"][k] += r["out"][k]
q["cost"][k] += r["cost"][k]
if r["last"] and (q["last"] is None or r["last"] > q["last"]):
q["last"] = r["last"]
rows = list(proj.values())
wkey = args.window # one of 5h/24h/7d/total, all precomputed
store = "cost" if args.api_cost else "tok"
fmt = fmt_money if args.api_cost else fmt_tok
rows.sort(key=lambda r: r[store][wkey], reverse=True)
# ---- headline: real rate-limit meter ----
print(f"Codex usage — {now.astimezone().strftime('%Y-%m-%d %H:%M %Z')}")
if latest_rl:
e, rl = latest_rl
plan = rl.get("plan_type") or "?"
prim = rl.get("primary") or {}
sec = rl.get("secondary") or {}
age = human_age(datetime.fromtimestamp(e, timezone.utc), now)
print(f"plan: {plan} (meter as of {age} ago)")
# label each window from its window_minutes: the weekly one can arrive as primary
for w in (prim, sec):
if not w:
continue
print(f" {window_label(w.get('window_minutes')):<7}: "
f"{w.get('used_percent',0):5.1f}% used "
f"[{bar(w.get('used_percent',0))}] "
f"resets in {human_until(w.get('resets_at'), now)}")
else:
print(" (no rate-limit data found in session files)")
print()
metric = "est. API $" if args.api_cost else "tokens"
scope = "all-time" if win_s is None else f"active in last {args.window}"
print(f"per-{'project' if args.by_project else 'session'} {metric} — sorted by {wkey} — {len(rows)} {scope}")
subcol = "SESS" if args.by_project else "SUBS"
hdr = f"{'LAST':>5} {'PROJECT':<22} {'TURNS':>5} {subcol:>4} {'5h':>8} {'24h':>8} {'7d':>8} {'TOTAL':>9} TITLE"
print(hdr)
print("-" * len(hdr))
tot = {k: 0 for k in ("5h", "24h", "7d", "total")}
for r in rows:
for k in tot:
tot[k] += r[store][k]
for r in rows[: args.top]:
proj = os.path.basename((r["cwd"] or "?").rstrip("/")) or "?"
subs = r.get("subs", 0) if not args.by_project else r.get("nsess", 0)
title = (r.get("title") or (r["id"][:8] if not args.by_project else "")) or ""
print(f"{human_age(r['last'], now):>5} {proj[:22]:<22} {r['turns']:>5} {subs:>4} "
f"{fmt(r[store]['5h']):>8} {fmt(r[store]['24h']):>8} {fmt(r[store]['7d']):>8} "
f"{fmt(r[store]['total']):>9} {title}")
print("-" * len(hdr))
print(f"{'ALL':>5} {'('+str(len(rows))+(' projects' if args.by_project else ' sessions')+')':<22} {'':>5} {'':>4} "
f"{fmt(tot['5h']):>8} {fmt(tot['24h']):>8} {fmt(tot['7d']):>8} {fmt(tot['total']):>9}")
print()
print("The 5h / weekly % are Codex's REAL account meter (read from the data, no calibration).")
if args.api_cost:
print("$ columns = what the usage WOULD cost at OpenAI API list prices (gpt-5.5: $5/$0.50/$30")
print("per 1M in/cached/out). On a Codex subscription you are NOT billed this — it's an estimate")
print("of the value. SUBS = subagent threads rolled into the parent.")
else:
print("Token columns are per-session totals (a proxy for which session drove that usage); SUBS =")
print("subagent threads rolled into the parent. The account meter is global, so session tokens")
print("explain the share, not the absolute %. (--api-cost shows USD at API rates instead.)")
if __name__ == "__main__":
main()