Files

155 lines
6.3 KiB
Python

"""
What the opencode driver reads of an account's ChatGPT plan usage — the
*Check again* probe (``account_probe``) and the ``usage`` an account's status
shows. Ported from the sidecar's ``opencode_usage.py`` (its read, not its
poll loop: polling every account is the provider-openai plugin's usage
reader's job, ``usage_loader``).
``GET https://chatgpt.com/backend-api/wham/usage`` with the account's access
token → ``<OPENCODE_RUNNER_DIR>/usage/<account>/rate-limits.json``, the shape
the Claude status line writes (the hub's usage poller reads both alike). The
token is never refreshed here (refresh tokens rotate): when it is about to
expire, opencode is asked to refresh it itself (``cli.refresh_token``),
unless a run on that account is live.
"""
from __future__ import annotations
import json
import os
import pathlib
import sys
import time
import urllib.error
import urllib.request
import pids
from config import LOG_DIR, OPENCODE_RUNNER_DIR
from . import cli
USAGE_URL = os.environ.get("SIDECAR_CHATGPT_USAGE_URL",
"https://chatgpt.com/backend-api/wham/usage")
REFRESH_MARGIN_S = 300
VENDOR = "openai"
_last: dict[str, dict] = {} # account → {at, ok, error?, planType?}
def state_dir(account: str) -> pathlib.Path:
return OPENCODE_RUNNER_DIR / "usage" / account
def window_name(seconds: float | None) -> str:
"""The Claude status line's window keys, by duration."""
s = float(seconds or 0)
if s >= 6 * 86400:
return "seven_day"
if 4 * 3600 <= s <= 6 * 3600:
return "five_hour"
return f"window_{int(s)}s" if s else "window"
def parse(data: dict, now: float | None = None) -> dict:
"""``wham/usage`` → ``{plan_type, limit_reached, rate_limits: {name:
{used_percentage, resets_at, window_seconds}}}``."""
now = now or time.time()
rl = data.get("rate_limit") or data.get("rateLimit") or {}
out: dict = {}
for key in ("primary_window", "secondary_window", "primary", "secondary"):
w = rl.get(key)
if not isinstance(w, dict):
continue
secs = (w.get("limit_window_seconds") or w.get("window_seconds")
or (w.get("window_minutes") or 0) * 60)
pct = w.get("used_percent", w.get("usedPercent"))
if not isinstance(pct, (int, float)):
continue
resets = w.get("reset_at") or w.get("resets_at")
if not resets and isinstance(w.get("reset_after_seconds"), (int, float)):
resets = now + w["reset_after_seconds"]
out[window_name(secs)] = {"used_percentage": float(pct), "resets_at": resets,
"window_seconds": secs or None}
return {"plan_type": data.get("plan_type") or data.get("planType"),
"limit_reached": bool(rl.get("limit_reached")), "rate_limits": out}
def _live_on(account: str) -> bool:
"""A run on this opencode account is in flight right now."""
if not LOG_DIR.is_dir():
return False
for p in LOG_DIR.glob("*.pid"):
rec = pids._live_record(p.stem)
if rec and rec.get("harness") == "opencode" and rec.get("account") == account:
return True
return False
def fetch(account: str) -> dict | None:
"""One read of the account's usage; None when it can't be read now."""
cred = cli.credential(account)
if not cred or cred["value"].get("methodID") not in ("chatgpt-headless", "chatgpt-browser"):
_last[account] = {"at": time.time(), "ok": False,
"error": "not logged in with the Codex method" if cred else "logged out"}
return None
v = cred["value"]
if (v.get("expires") or 0) / 1000 <= time.time() + REFRESH_MARGIN_S:
if _live_on(account) or not cli.refresh_token(account, dict(os.environ)):
_last[account] = {"at": time.time(), "ok": False, "error": "access token expired"}
return None
cred = cli.credential(account) or cred
v = cred["value"]
if (v.get("expires") or 0) / 1000 <= time.time():
_last[account] = {"at": time.time(), "ok": False, "error": "access token expired"}
return None
headers = {"Authorization": f"Bearer {v.get('access')}", "Accept": "application/json",
"User-Agent": "opencode (ai-agent usage poller)", "originator": "opencode"}
acct_id = (v.get("metadata") or {}).get("accountID")
if acct_id:
headers["ChatGPT-Account-Id"] = acct_id
try:
with urllib.request.urlopen(urllib.request.Request(USAGE_URL, headers=headers),
timeout=20) as r:
data = json.loads(r.read().decode())
except urllib.error.HTTPError as e:
_last[account] = {"at": time.time(), "ok": False, "error": f"HTTP {e.code}"}
return None
except (urllib.error.URLError, OSError, ValueError) as e:
_last[account] = {"at": time.time(), "ok": False, "error": str(e)[:200]}
return None
snap = parse(data)
_last[account] = {"at": time.time(), "ok": True, "planType": snap["plan_type"],
"limitReached": snap["limit_reached"]}
return snap
def write(account: str, snap: dict) -> None:
d = state_dir(account)
d.mkdir(parents=True, exist_ok=True)
tmp = d / "rate-limits.json.tmp"
tmp.write_text(json.dumps({"updated_at": time.time(), "source": "chatgpt", **snap}))
os.replace(tmp, d / "rate-limits.json")
def last(account: str) -> dict | None:
"""The latest read of the account's usage, whoever made it: the live
provider-openai reader's (when it keeps one), the sidecar's built-in
poller's (only when already loaded — never imported from here), or this
driver's own probe — the most recent wins."""
seen = [_last.get(account)]
try:
import usage_loader
r = usage_loader.get(VENDOR)
fn = getattr(r, "last", None)
if callable(fn):
seen.append(fn(account))
except Exception: # noqa: BLE001 — a reader that can't answer isn't one
pass
legacy = sys.modules.get("opencode_usage")
if legacy is not None and callable(getattr(legacy, "last", None)):
try:
seen.append(legacy.last(account))
except Exception: # noqa: BLE001
pass
seen = [s for s in seen if isinstance(s, dict)]
return max(seen, key=lambda s: s.get("at") or 0) if seen else None