Files
ai-agent/backend/usage/poller.py
gabrielvidalandClaude Opus 5.5 604bc1dee6 feat(usage): usage widgets follow the picked model's provider; Fable weekly limit
- sidecar: read the lab's own Claude logins through /api/oauth/usage too
  (oauth-usage.json beside the status line's file) and keep the reply's
  weekly_scoped limits as seven_day_<model> (Fable)
- hub: take only the per-model windows from that read and merge them per
  window with the status line's snapshot; alert label 'Fable weekly'
- home usage strip follows the composer's pick (lib/composerPick): Claude ->
  week + Fable week (no empty 5-hour tile), Gemini -> agy 5h + week
- composer rings: Fable week ring while a Fable model is picked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:05:08 +01:00

243 lines
9.9 KiB
Python

"""Record the official /usage percentages as they change.
Claude Code hands its status line a ``rate_limits`` block (used % + reset time
per window); the homelab status line persists it to
``<config dir>/usage-state/rate-limits.json`` on every render, and a cron keeps
it fresh while no terminal is open (services/claude-usage-notifier). Those dirs
are mounted read-only per account (``USAGE_STATE_DIRS``); this thread reads them
every ``POLL_S`` and stores a point whenever a window's % or reset time moves —
plus a heartbeat every ``HEARTBEAT_S`` so an idle hour still has a level.
The opencode ChatGPT seats write the same file (the sidecar's
``opencode_usage.py`` reads ChatGPT's usage endpoint): a mounted dir when the
lab hosts the account, else — ``remote`` — the snapshot the hosting worker
serves (``GET /opencode/usage``), pulled on the same tick.
The Claude proxy (claudeproxy/) reads the same figures off every reply it
streams to a worker (the ``anthropic-ratelimit-unified-*`` headers) and hands
them in with ``observe`` — the freshest of the three wins each tick.
An account that declares ``limitAlerts`` (``accounts.ACCOUNTS``) gets one push
per window and reset period when its % crosses each threshold (``alert``) —
and one that declares ``weekTarget`` one push each time its week falls more
than ``behindAlert`` points under the target line (``behind``, usage/target.py).
"""
from __future__ import annotations
import json
import os
import pathlib
import threading
import time
POLL_S = 20
HEARTBEAT_S = 1800
STALE_S = 1800
FILE = "rate-limits.json"
def state_dirs() -> dict[str, pathlib.Path]:
"""``{account: dir}`` from ``USAGE_STATE_DIRS`` (``personal=/usage-state,…``)."""
raw = os.environ.get("USAGE_STATE_DIRS", "personal=/usage-state,work=/usage-state-work")
out = {}
for part in raw.split(","):
acct, _, path = part.partition("=")
if acct.strip() and path.strip():
out[acct.strip()] = pathlib.Path(path.strip())
return out
def read_snapshot(d: pathlib.Path) -> dict | None:
"""``{updatedAt, windows: {name: {pct, resetsAt}}}`` or None."""
try:
raw = json.loads((d / FILE).read_text())
except (OSError, ValueError):
return None
return parse_snapshot(raw)
def parse_snapshot(raw: dict) -> dict | None:
"""A ``rate-limits.json`` body → ``{updatedAt, windows}``."""
if not isinstance(raw, dict):
return None
rl = raw.get("rate_limits") or {}
windows = {}
for name, w in rl.items():
if isinstance(w, dict) and isinstance(w.get("used_percentage"), (int, float)):
windows[name] = {"pct": float(w["used_percentage"]),
"resetsAt": w.get("resets_at")}
return {"updatedAt": raw.get("updated_at"), "windows": windows}
def merge(snaps: list[dict]) -> dict | None:
"""The freshest snapshot, plus the windows a staler (but not stale)
source reports and it lacks: the status line never carries Fable's week,
the sidecar's /api/oauth/usage read carries only that (usage/service.py)
— so neither source's turn as the freshest hides the other's."""
if not snaps:
return None
snaps = sorted(snaps, key=lambda x: float(x["updatedAt"]))
best = snaps[-1]
extra = {}
for s in snaps[:-1]:
# A source that stopped reading says nothing about the window now.
if float(best["updatedAt"]) - float(s["updatedAt"]) > STALE_S:
continue
for name, w in (s.get("windows") or {}).items():
if name not in best["windows"]:
extra[name] = w
return {**best, "windows": {**extra, **best["windows"]}} if extra else best
class UsagePoller:
def __init__(self, store, publish=None, dirs: dict | None = None, remote=None,
alert=None):
self.store = store
self.publish = publish
self.dirs = dirs if dirs is not None else state_dirs()
# () → {account: rate-limits.json body} for the accounts a worker hosts
self.remote = remote
# (account, window, pct, threshold, resets_at) → push
self.alert = alert
# (account, pct, target, resets_at) → push: the week fell behind
self.behind = None
# () → called after every poll (the plan tracker reads ``latest``)
self.after_poll = None
self.latest: dict[str, dict] = {}
self._last: dict[tuple, tuple] = {}
self._remote: dict[str, dict] = {}
self._observed: dict[str, dict] = {}
def accounts(self) -> list[str]:
"""Every account with a usage source: a mounted dir, a worker, or the
Claude proxy's replies."""
return list(dict.fromkeys([*self.dirs, *self._remote, *self._observed]))
def observe(self, account: str, snap: dict) -> None:
"""A reading off a live API reply (``{updatedAt, windows}``), recorded
on the next tick like a file's."""
if snap and snap.get("windows"):
self._observed[account] = snap
def start(self) -> None:
if self.dirs:
threading.Thread(target=self._loop, daemon=True, name="usage-poller").start()
def _loop(self) -> None:
while True:
try:
self.poll_once()
except Exception:
pass
time.sleep(POLL_S)
def _snapshots(self) -> list[tuple[str, dict]]:
"""Each account's freshest reading: its mounted file, else (no file —
the account lives on a worker) what that worker served."""
if self.remote is not None:
try:
raw = self.remote() or {}
except Exception:
raw = {}
for acct, body in raw.items():
snap = parse_snapshot(body)
if snap:
self._remote[acct] = snap
out = []
for acct in self.accounts():
d = self.dirs.get(acct)
got = [x for x in (read_snapshot(d) if d else None, self._remote.get(acct),
self._observed.get(acct)) if x and x.get("updatedAt")]
out.append((acct, merge(got)))
return out
def poll_once(self) -> int:
rows = []
for acct, snap in self._snapshots():
if not snap or not snap["updatedAt"]:
continue
self.latest[acct] = snap
t = float(snap["updatedAt"])
for win, w in snap["windows"].items():
key = (acct, win)
last = self._last.get(key)
if last is None:
p = self.store.last_point(acct, win)
last = (p[0], p[1], p[2]) if p else None
if last:
self._last[key] = last
if last and t <= last[0]:
continue
moved = (last is None or w["pct"] != last[1]
or (w["resetsAt"] or 0) != (last[2] or 0))
if moved or t - last[0] >= HEARTBEAT_S:
rows.append((acct, win, t, w["pct"], w["resetsAt"], "live"))
self._last[key] = (t, w["pct"], w["resetsAt"])
self._check_alert(acct, win, last, w)
self._check_behind(acct, win, last, t, w)
n = self.store.add_points(rows)
if self.after_poll is not None:
try:
self.after_poll()
except Exception:
pass
if n and self.publish:
self.publish({"type": "usage"})
return n
def _check_alert(self, acct: str, win: str, last, w: dict) -> None:
"""Push once when a window crosses one of the account's thresholds
(``limitAlerts``) — a reset (``resetsAt`` moved or the % dropped)
re-arms it, and a restart never re-pushes a crossing it already saw."""
if self.alert is None or last is None:
return
import accounts as accounts_mod
prev = last[1] if (w["resetsAt"] or 0) == (last[2] or 0) else 0.0
for th in (accounts_mod.get(acct) or {}).get("limitAlerts") or []:
if prev < th <= w["pct"]:
try:
self.alert(acct, win, w["pct"], th, w["resetsAt"])
except Exception:
pass
def _check_behind(self, acct: str, win: str, last, t: float, w: dict) -> None:
"""Push when the week's gap under its target line crosses the
account's ``behindAlert`` between two recorded points. The line
keeps rising while the % sits still, so the heartbeat points (every
``HEARTBEAT_S``) are what catch an idle week falling behind; both
ends are stored points, so a restart never re-pushes a crossing.
Catching up re-arms it."""
if self.behind is None or last is None or win != "seven_day":
return
from . import target
wt = target.of(acct)
th = (wt or {}).get("behindAlert")
if not th:
return
now = target.gap(w["pct"], w["resetsAt"], t, wt["goal"])
if now is None or now <= th:
return
prev = target.gap(last[1], last[2], last[0], wt["goal"])
if prev is not None and prev > th:
return
try:
self.behind(acct, w["pct"], w["pct"] + now, w["resetsAt"])
except Exception:
pass
def limits(self) -> dict[str, dict]:
"""Latest snapshot per account (``stale`` past ``STALE_S``)."""
return {acct: self.limit(acct) for acct in self.accounts()}
def limit(self, acct: str) -> dict | None:
"""One account's latest snapshot, None when it has no usage source."""
if acct not in self.accounts():
return None
d = self.dirs.get(acct)
snap = (self.latest.get(acct) or (read_snapshot(d) if d else None)
or self._remote.get(acct) or self._observed.get(acct) or {})
up = snap.get("updatedAt")
return {"account": acct, "windows": snap.get("windows") or {},
"updatedAt": up, "stale": not up or time.time() - up > STALE_S}