latest changes
This commit is contained in:
+240
@@ -0,0 +1,240 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Portable, dependency-free Codex usage display (Python 3.8+)."""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import tempfile
|
||||
import hashlib
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def clean(value):
|
||||
# Never allow API text to inject terminal control sequences.
|
||||
return "".join(c for c in str(value) if c.isprintable())
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
try:
|
||||
if isinstance(value, str):
|
||||
result = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
else:
|
||||
result = dt.datetime.fromtimestamp(value, dt.timezone.utc)
|
||||
return result.astimezone().strftime("%d %b %H:%M %Z")
|
||||
except (ValueError, TypeError, OverflowError, OSError):
|
||||
return "unknown"
|
||||
|
||||
|
||||
def window_line(label, window, width):
|
||||
if not isinstance(window, dict):
|
||||
return [label + ": unavailable"]
|
||||
used = window.get("usedPercent")
|
||||
if isinstance(used, (int, float)) and not isinstance(used, bool) and math.isfinite(used):
|
||||
used = max(0, min(100, used))
|
||||
size = max(5, min(30, width - 40))
|
||||
filled = round(size * used / 100)
|
||||
bar = "#" * filled + "-" * (size - filled)
|
||||
summary = "{} [{}] {:g}% used / {:g}% left".format(label, bar, used, 100 - used)
|
||||
else:
|
||||
summary = label + ": usage unknown"
|
||||
reset = window.get("resetsAt")
|
||||
countdown = ""
|
||||
if isinstance(reset, (int, float)) and math.isfinite(reset):
|
||||
seconds = max(0, int(reset - time.time()))
|
||||
hours, minutes = divmod(seconds // 60, 60)
|
||||
countdown = " (in {}h {:02d}m)".format(hours, minutes) if seconds else " (awaiting fresh poll)"
|
||||
return [summary, " Reset: " + timestamp(reset) + countdown]
|
||||
|
||||
|
||||
def render(data, failure, width):
|
||||
lines = ["CODEX USAGE", ""]
|
||||
if failure:
|
||||
lines += ["OFFLINE - " + failure, "Showing last successful response" if data else "No usage data yet", ""]
|
||||
if data:
|
||||
stale = data.get("stale") or data.get("status") != "ok" or bool(failure)
|
||||
raw = data.get("raw") or {}
|
||||
if not isinstance(raw, dict):
|
||||
raw = {}
|
||||
allowed = raw.get("ordinaryUsageAllowed")
|
||||
lines += ["State: {} | Allowed: {}".format("STALE" if stale else "OK", {True: "yes", False: "no"}.get(allowed, "unknown")),
|
||||
"Last server poll: " + timestamp(data.get("last_checked")), ""]
|
||||
buckets = raw.get("rateLimitsByLimitId")
|
||||
if not isinstance(buckets, dict) or not buckets:
|
||||
buckets = {"codex": raw.get("rateLimits")}
|
||||
for name, bucket in list(buckets.items())[:20]:
|
||||
if not isinstance(bucket, dict):
|
||||
continue
|
||||
lines.append("{} | Plan: {}".format(clean(name), clean(bucket.get("planType") or "unknown")))
|
||||
for key in ("primary", "secondary"):
|
||||
window = bucket.get(key)
|
||||
duration = window.get("windowDurationMins") if isinstance(window, dict) else None
|
||||
label = {300: "5-hour", 10080: "Weekly"}.get(duration, "{} min".format(duration) if duration else key.title())
|
||||
lines.extend(window_line(label, window, width))
|
||||
credits = bucket.get("credits")
|
||||
if isinstance(credits, dict):
|
||||
lines.append("Credits: " + ("unlimited" if credits.get("unlimited") else clean(credits.get("balance", "unknown"))))
|
||||
lines.append("")
|
||||
lines.append("Display: {} | Ctrl-C to quit".format(time.strftime("%H:%M:%S")))
|
||||
return [clean(line)[:width] for line in lines]
|
||||
|
||||
|
||||
def fetch(url, timeout=5):
|
||||
request = urllib.request.Request(url, headers={"Accept": "application/json"})
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=timeout)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 503:
|
||||
raise
|
||||
response = exc
|
||||
with response:
|
||||
body = response.read(1024 * 1024 + 1)
|
||||
if len(body) > 1024 * 1024:
|
||||
raise ValueError("response exceeds 1 MiB")
|
||||
data = json.loads(body)
|
||||
if not isinstance(data, dict) or data.get("service") != "codex":
|
||||
raise ValueError("endpoint did not return Codex usage data")
|
||||
return data
|
||||
|
||||
|
||||
def cache_path(url):
|
||||
digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16]
|
||||
return os.path.join(tempfile.gettempdir(), "codex-usage-{}-{}.json".format(os.getuid(), digest))
|
||||
|
||||
|
||||
def cached_fetch(url, ttl, timeout):
|
||||
path = cache_path(url)
|
||||
cached = None
|
||||
try:
|
||||
info = os.lstat(path)
|
||||
if info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 1024 * 1024:
|
||||
with open(path, "r") as stream:
|
||||
cached = json.load(stream)
|
||||
if (not isinstance(cached, dict) or not isinstance(cached.get("data"), dict)
|
||||
or not isinstance(cached.get("fetched_at"), (int, float))):
|
||||
cached = None
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass
|
||||
if cached and 0 <= time.time() - cached["fetched_at"] < ttl:
|
||||
return cached["data"], None
|
||||
try:
|
||||
data = fetch(url, timeout)
|
||||
if data.get("status") == "unavailable":
|
||||
return cached["data"] if cached else None, "offline"
|
||||
fd, temporary = tempfile.mkstemp(prefix=".codex-usage-", dir=tempfile.gettempdir())
|
||||
try:
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
json.dump({"fetched_at": time.time(), "data": data}, stream)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
return data, None
|
||||
except (urllib.error.URLError, OSError, ValueError, TimeoutError):
|
||||
return cached["data"] if cached else None, "offline"
|
||||
|
||||
|
||||
def tmux_line(data, failure, compact=True, width=30):
|
||||
if failure or not data:
|
||||
return "C OFFLINE" if compact or width < 22 else "CODEX OFFLINE"
|
||||
if data.get("stale") or data.get("status") != "ok":
|
||||
return "C STALE" if compact or width < 22 else "CODEX STALE"
|
||||
raw = data.get("raw")
|
||||
if not isinstance(raw, dict):
|
||||
return "C STALE" if compact or width < 22 else "CODEX STALE"
|
||||
buckets = raw.get("rateLimitsByLimitId")
|
||||
if not isinstance(buckets, dict) or not buckets:
|
||||
buckets = {"codex": raw.get("rateLimits")}
|
||||
values = {}
|
||||
for bucket in list(buckets.values())[:20]:
|
||||
if not isinstance(bucket, dict):
|
||||
continue
|
||||
for key in ("primary", "secondary"):
|
||||
window = bucket.get(key)
|
||||
if not isinstance(window, dict):
|
||||
continue
|
||||
duration = window.get("windowDurationMins")
|
||||
used = window.get("usedPercent")
|
||||
if isinstance(used, (int, float)) and not isinstance(used, bool) and math.isfinite(used):
|
||||
if duration == 300:
|
||||
values.setdefault("5h", round(max(0, min(100, 100 - used))))
|
||||
elif duration == 10080:
|
||||
values.setdefault("W", round(max(0, min(100, 100 - used))))
|
||||
if not values:
|
||||
return "C STALE" if compact or width < 22 else "CODEX STALE"
|
||||
short = compact or width < 30
|
||||
prefix = "C" if short else "CODEX"
|
||||
parts = [prefix]
|
||||
if "5h" in values:
|
||||
parts.append(("" if short else "5h ") + "{}%".format(values["5h"]))
|
||||
if "W" in values:
|
||||
parts.append("W {}%".format(values["W"]))
|
||||
return " ".join(parts)[:width]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--url", default=os.environ.get("CODEX_USAGE_URL", "http://127.0.0.1:3100"), help="server base URL or full /api/usage URL (env: CODEX_USAGE_URL)")
|
||||
parser.add_argument("--interval", type=float, default=10, help="display fetch interval in seconds (default: 10)")
|
||||
parser.add_argument("--once", action="store_true", help="print once without terminal controls")
|
||||
parser.add_argument("--tmux", action="store_true", help="print one compact status-bar line")
|
||||
parser.add_argument("--compact", action="store_true", help="use short status labels")
|
||||
parser.add_argument("--width", type=int, default=30, help="maximum tmux output width (default: 30)")
|
||||
parser.add_argument("--cache-ttl", type=float, default=45, help="cache lifetime in seconds (default: 45)")
|
||||
args = parser.parse_args()
|
||||
if not math.isfinite(args.interval) or args.interval < 1:
|
||||
parser.error("--interval must be at least 1 second")
|
||||
if args.width < 8 or not math.isfinite(args.cache_ttl) or args.cache_ttl < 0:
|
||||
parser.error("--width must be at least 8 and --cache-ttl must be nonnegative")
|
||||
url = args.url.rstrip("/")
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.query or parsed.fragment or parsed.username:
|
||||
parser.error("--url must be an HTTP(S) URL without credentials, query or fragment")
|
||||
if not parsed.path or parsed.path == "/":
|
||||
url += "/api/usage"
|
||||
if args.tmux:
|
||||
data, failure = cached_fetch(url, args.cache_ttl, 2)
|
||||
print(tmux_line(data, failure, True, args.width))
|
||||
return 1 if failure else 0
|
||||
interactive = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and not args.once
|
||||
data, failure = None, None
|
||||
if interactive:
|
||||
sys.stdout.write("\033[?1049h\033[?25l")
|
||||
try:
|
||||
while True:
|
||||
failure = None
|
||||
try:
|
||||
received, cache_failure = cached_fetch(url, 0, 5)
|
||||
if cache_failure:
|
||||
raise ValueError("usage API unavailable")
|
||||
if received.get("status") == "unavailable":
|
||||
failure = "server has no successful usage snapshot"
|
||||
else:
|
||||
data = received
|
||||
except (urllib.error.URLError, OSError, ValueError, TimeoutError):
|
||||
failure = "cannot fetch usage; check endpoint, network and service"
|
||||
width, height = shutil.get_terminal_size((80, 24))
|
||||
lines = render(data, failure, width)
|
||||
if interactive:
|
||||
sys.stdout.write("\033[H\033[2J")
|
||||
lines = lines[:max(1, height - 1)]
|
||||
print("\n".join(lines), flush=True)
|
||||
if args.once:
|
||||
return 1 if failure else 0
|
||||
time.sleep(args.interval)
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
finally:
|
||||
if interactive:
|
||||
sys.stdout.write("\033[?25h\033[?1049l")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user