Files
ai-agent/backend/usage/plans.py
gabrielvidalandClaude Opus 5.5 4f5c594349 feat(backend): agy accounts, Gemini models + prices, per-machine Google logins, quota
google-personal (harness agy, 5-hour + week windows, out of totals); Neon /
Hydrogen / Argon / 3.8 Flash in the catalogue with their own effort levels;
GEMINI_PRICES; agy transcripts ingested from AGY_TRANSCRIPTS_DIR and the worker
feed (@agy/<account>/); runs routed to a machine that declares the account,
guests refused, fork and harness switches refused; logins per machine (hosts,
?worker=); quota read from the lab and the workers' /agy/usage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 02:48:52 +01:00

224 lines
9.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Which subscription plan each account is on, and since when.
A plan is the login's **rate-limit tier** (``default_claude_max_20x``: the
sidecar reads it from the CLI's cached profile, ``/accounts`` → ``plan``) and
the **limit windows** it enforces (the windows its rate-limits.json reports —
the personal Max dropped its 5-hour one on 2026-10-31). Both are read on every
usage poll; a change that holds for ``CONFIRM_S`` starts a new **segment**
(``usage_plans``), dated from when it was first seen.
calibrate.py fits each segment on its own hours only, so a new tier's
% per plan unit is measured independently of the old one. Until the segment
has enough hours, it starts from the previous segment's rate scaled by the
tiers' multipliers (Max 5× → Max 20× = ×4 the units per 1 %).
The first reading of an account writes its past: one ``assumed`` segment from
its first recorded % point on the current tier, split where a window it no
longer reports went quiet.
"""
from __future__ import annotations
import re
import time
# Fit names → usage_limits window keys.
WINDOWS = {"week": "seven_day", "h5": "five_hour"}
CONFIRM_S = 3600 # a change must hold this long before it is a new plan
FRESH_S = 2 * 3600 # an older rate-limits.json says nothing about the windows
_MAX_RE = re.compile(r"max_(\d+)x")
def describe(tier: str | None) -> dict:
"""``{label, multiplier}`` of a rate-limit tier. The Max tiers carry their
multiple of Pro (``default_claude_max_20x`` → Max 20×, 20); a tier whose
size isn't known has no multiplier (a rate carries over unscaled)."""
t = (tier or "").lower()
if t.startswith("google_"):
# agy's plan tier (``google_ai_pro``, ``google_ai_ultra``…).
rest = t[7:].replace("_", " ").title().replace("Ai ", "AI ")
return {"label": f"Google {rest}", "multiplier": None}
m = _MAX_RE.search(t)
if m:
return {"label": f"Max {m.group(1)}×", "multiplier": float(m.group(1))}
if t.endswith("_pro") or t == "pro":
return {"label": "Pro", "multiplier": 1.0}
if t.startswith("chatgpt_"):
return {"label": f"ChatGPT {t[8:].replace('_', ' ').title()}", "multiplier": None}
return {"label": tier or "Unknown plan", "multiplier": None}
def ratio(from_tier: str | None, to_tier: str | None) -> float:
"""How many times more plan units 1 % of ``to_tier`` holds than 1 % of
``from_tier`` — 1 when either size is unknown."""
a, b = describe(from_tier)["multiplier"], describe(to_tier)["multiplier"]
return b / a if a and b else 1.0
def ordered(names) -> list[str]:
s = set(names)
return [n for n in WINDOWS if n in s]
def windows_of(snap: dict | None, now: float | None = None) -> list[str] | None:
"""The fit windows a fresh rate-limits snapshot reports; None when it is
missing, stale or reports none (unknown — never "no windows")."""
if not snap or not snap.get("updatedAt"):
return None
if (now or time.time()) - float(snap["updatedAt"]) > FRESH_S:
return None
keys = set(snap.get("windows") or {})
got = [n for n, k in WINDOWS.items() if k in keys]
return got or None
def tier_of(row: dict | None) -> str | None:
"""A login's tier from the sidecar's ``/accounts`` row: the Claude
profile's, or an opencode ChatGPT seat's plan type."""
row = row or {}
tier = (row.get("plan") or {}).get("tier")
if tier:
return tier
if row.get("harness") == "opencode" and row.get("subscriptionType"):
return f"chatgpt_{row['subscriptionType']}"
if row.get("harness") == "agy" and row.get("subscriptionType"):
st = str(row["subscriptionType"]).lower()
return st if st.startswith("google_") else f"google_{st}"
return None
def public(seg: dict | None) -> dict | None:
"""A segment as the API serves it (label + multiplier spelled out)."""
if not seg:
return None
d = describe(seg.get("tier"))
info = seg.get("data") or {}
return {"account": seg["account"], "since": seg["since"], "until": seg.get("until"),
"tier": seg.get("tier"), "label": d["label"], "multiplier": d["multiplier"],
"displayName": info.get("displayName"),
"subscriptionType": info.get("subscriptionType"),
"windows": list(seg.get("windows") or []),
"source": seg.get("source") or "detected", "reason": info.get("reason")}
def at(store, account: str, t: float) -> dict | None:
"""The segment in force at ``t`` (before the first one: the first one —
it is the account's assumed past)."""
segs = store.plans(account)
cur = None
for s in segs:
if s["since"] <= t:
cur = s
else:
break
return cur or (segs[0] if segs else None)
def current(store, account: str) -> dict | None:
segs = store.plans(account)
return segs[-1] if segs else None
def history(store, account: str) -> list[dict]:
"""Every segment, oldest first, each with its ``until`` and — when it
didn't store one — what changed from the segment before."""
segs = store.plans(account)
out = []
for i, s in enumerate(segs):
p = public({**s, "until": segs[i + 1]["since"] if i + 1 < len(segs) else None})
if i and not p["reason"]:
p["reason"] = _reason(segs[i - 1], (s.get("tier"), tuple(s["windows"])))
out.append(p)
return out
class PlanTracker:
"""Turns readings (tier, windows) into plan segments."""
def __init__(self, store, notify=None):
self.store = store
# (account, old segment, new segment) → push; new-plan news only
self.notify = notify
self._pending: dict[str, tuple[tuple, float, dict | None]] = {}
def observe(self, account: str, tier: str | None, windows: list[str] | None,
info: dict | None = None, now: float | None = None) -> dict | None:
"""One reading — ``tier``/``windows`` None = unknown this time. Returns
the segment it started, if any."""
now = now if now is not None else time.time()
cur = current(self.store, account)
if cur is None:
return self._first(account, tier, windows, info, now) if windows else None
if tier:
# A tier unknown when a segment was written is this one: the
# current segment's (same plan), and the assumed past's (it is
# assumed to be on the current tier).
stale = [g for g in self.store.plans(account)
if not g.get("tier") and (g is cur or g.get("source") == "assumed")]
for g in stale:
self.store.update_plan(account, g["since"], tier, info)
if stale:
cur = current(self.store, account)
new = (tier or cur.get("tier"), tuple(ordered(windows or cur["windows"])))
if new == (cur.get("tier"), tuple(cur["windows"])):
self._pending.pop(account, None)
return None
pend = self._pending.get(account)
if not pend or pend[0] != new:
self._pending[account] = (new, now, info)
return None
if now - pend[1] < CONFIRM_S:
return None
self._pending.pop(account, None)
reason = _reason(cur, new)
seg = {"account": account, "since": pend[1], "tier": new[0], "windows": list(new[1]),
"source": "detected", "data": {**(info or {}), "reason": reason}}
self.store.add_plan(seg)
if self.notify:
try:
self.notify(account, cur, seg)
except Exception:
pass
return seg
def _first(self, account: str, tier: str | None, windows: list[str],
info: dict | None, now: float) -> dict:
"""An account's first reading: its past as one assumed segment from
its first % point, split where a window it no longer reports stopped."""
spans = self.store.window_spans(account)
first = min((s[0] for s in spans.values()), default=now)
gone = [n for n, k in WINDOWS.items()
if k in spans and n not in windows and spans[k][1] < now - CONFIRM_S]
segs = []
if gone:
cut = max(spans[WINDOWS[n]][1] for n in gone) + 1
segs.append({"account": account, "since": first, "tier": tier,
"windows": ordered([*windows, *gone]), "source": "assumed",
"data": dict(info or {})})
segs.append({"account": account, "since": cut, "tier": tier,
"windows": ordered(windows), "source": "detected",
"data": {**(info or {}), "reason": _reason(
segs[0], (tier, tuple(ordered(windows))))}})
else:
segs.append({"account": account, "since": first, "tier": tier,
"windows": ordered(windows), "source": "assumed",
"data": dict(info or {})})
for s in segs:
self.store.add_plan(s)
return segs[-1]
def _reason(old: dict, new: tuple) -> str:
"""``Max 5× → Max 20×``, ``5-hour window gone``… — what changed."""
parts = []
if (old.get("tier") or None) != (new[0] or None):
parts.append(f"{describe(old.get('tier'))['label']} → {describe(new[0])['label']}")
names = {"week": "weekly", "h5": "5-hour"}
for n in WINDOWS:
if n in old["windows"] and n not in new[1]:
parts.append(f"{names[n]} window gone")
elif n not in old["windows"] and n in new[1]:
parts.append(f"new {names[n]} window")
return ", ".join(parts) or "plan changed"