The core still hard-coded links into plugin pages (Files → Goals / Skills / Agents / Forms cards and drawer links, Dashboards → Performance, Settings → What's new and its editor, the home Analytics icon, skill/agent pills) and ~25 old addresses that forwarded to them (/goals, /skills, /dashboards/plan, /whats-new, /memories/<slug>…). On a hub without those plugins (raw-hub) they opened 404 pages. Now every link to a plugin page comes from its manifest: - bottom-bar drawers: every `files` / `dashboards` plugin page joins its section's drawer (past five slots into the stash), key `<section>/p:<plugin>:<page>`; saved slots of the core's old links map to the plugins' (SUB_RENAMED); - Files landing: the plugins' Files pages are its cards; Files panel: the hard-coded Goals row is gone; - What's new + editor leave the settings registry (the plugin's own `nav: "settings"` pages); - new optional page fields (written only when set — `ui` is in the approval fingerprint): `perm` (the page reaches its holders only), `header: "home"` (a button in the home page's head — Analytics), `tag` (the tag kind whose pills open the page at <page>/<slug> — skill, agent), `feature` (the App usage id its visits count under, so a former core page keeps its history; else plugin.<plugin>.<page>, in the frontend and telemetry/views.registry); - the old addresses and their redirect components are dropped; the owner's usage rings, the burn gauge and the Stats redirect link nowhere into a plugin; the plan-usage and /tmp-full pushes open /dashboards. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
369 lines
15 KiB
Python
369 lines
15 KiB
Python
"""Wiring: the daily recalibration loop, the plan tracker's readings and
|
||
the shift / plan-change notifications."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import threading
|
||
import time
|
||
|
||
from . import calibrate, plans
|
||
|
||
# The push when an account's plan (tier or limit windows) changes; 0 = the
|
||
# dashboard only.
|
||
NOTIFY_PLAN = os.environ.get("USAGE_NOTIFY_PLAN_CHANGE", "1") not in ("0", "false", "")
|
||
|
||
CHECK_S = 3600
|
||
EVERY_S = 86400
|
||
|
||
|
||
def guest(account: str) -> bool:
|
||
"""A guest's own Claude (``guest-<uid>``): its % is recorded and shown to
|
||
them (``/api/me/usage``) and on the owner's Guests strip, but it is no
|
||
plan of the owner's — no calibration, no plan tracking, no pushes."""
|
||
import accounts as accounts_mod
|
||
return bool(accounts_mod.guest_of(account))
|
||
|
||
|
||
def metered(deps) -> list[str]:
|
||
"""The owner's accounts with a usage source — what gets calibrated."""
|
||
return [a for a in deps.usage_poller.accounts() if not guest(a)]
|
||
|
||
|
||
def _notify(deps, account: str, text: str) -> None:
|
||
from notifications.service import _create_notify
|
||
import accounts as accounts_mod
|
||
label = (accounts_mod.get(account) or {}).get("label") or account
|
||
try:
|
||
_create_notify(deps, {"title": f"📏 {label} plan rate shifted", "message": text,
|
||
"type": "ai", "url": "/dashboards"})
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# The pre-plugin usage route of each vendor's reader — what a runner still on
|
||
# an older sidecar (no ``GET /usage/{vendor}``) answers instead.
|
||
LEGACY_USAGE_PATH = {"anthropic": "/claude/usage", "openai": "/opencode/usage",
|
||
"google": "/agy/usage"}
|
||
# A worker record's per-vendor login list before machines reported
|
||
# ``logins: {vendor: [accounts]}``.
|
||
_LEGACY_WORKER_FIELD = {"openai": "opencodeAccounts", "google": "agyAccounts"}
|
||
|
||
|
||
def _usage_vendors() -> list[str]:
|
||
"""The active providers that ship a plan-usage reader (``usageReader``),
|
||
in the registry's order."""
|
||
from conversations import pricing
|
||
return [vid for vid, p in pricing.registry().providers.items() if p.spec.get("usageReader")]
|
||
|
||
|
||
def _vendor_accounts(vendor: str) -> set[str]:
|
||
from conversations import pricing
|
||
return {a["id"] for a in pricing.registry().accounts_for_vendor(vendor)}
|
||
|
||
|
||
def _lab_usage(vendor: str) -> dict:
|
||
"""The host sidecar's snapshots of a vendor (``{account: rate-limits}``):
|
||
``GET /usage/{vendor}``, else the vendor's legacy route; {} when neither
|
||
answers."""
|
||
from runs import sidecar_client
|
||
got = sidecar_client._sidecar_get(f"/usage/{vendor}", timeout=10)
|
||
if got is None and vendor in LEGACY_USAGE_PATH:
|
||
got = sidecar_client._sidecar_get(LEGACY_USAGE_PATH[vendor], timeout=10)
|
||
return (got or {}).get("accounts") or {}
|
||
|
||
|
||
def _worker_usage(w: dict, vendor: str) -> dict | None:
|
||
"""One worker's snapshots of a vendor: ``GET /usage/{vendor}``, the legacy
|
||
route only when the worker hasn't updated yet (a 404); None when it can't
|
||
be read."""
|
||
from fastapi import HTTPException
|
||
from workers.store import sidecar_request
|
||
paths = [f"/usage/{vendor}"] + ([LEGACY_USAGE_PATH[vendor]] if vendor in LEGACY_USAGE_PATH else [])
|
||
for i, path in enumerate(paths):
|
||
try:
|
||
got = sidecar_request(w["url"], w["token"], path, None,
|
||
method="GET", timeout=10, label="worker")
|
||
except HTTPException as e:
|
||
if e.status_code == 404 and i + 1 < len(paths):
|
||
continue
|
||
return None
|
||
except Exception:
|
||
return None
|
||
return (got or {}).get("accounts") or {}
|
||
return None
|
||
|
||
|
||
def _worker_held(w: dict, vendor: str, vaccts: set[str]) -> set[str]:
|
||
"""The accounts of ``vendor`` a worker declares it holds."""
|
||
held = set((w.get("logins") or {}).get(vendor) or []) & vaccts
|
||
field = _LEGACY_WORKER_FIELD.get(vendor)
|
||
if field:
|
||
held |= set(w.get(field) or [])
|
||
return held
|
||
|
||
|
||
def remote_snapshots(deps) -> dict[str, dict]:
|
||
"""Every plan-usage snapshot the hub doesn't read off a mounted dir, one
|
||
pass over the active providers that ship a ``usageReader``: each machine
|
||
serves its own (``GET /usage/{vendor}`` — the lab's sidecar and every
|
||
online worker holding a login of that vendor). How a vendor's readings
|
||
merge is its policy (``_MERGE``): the Claude logins' come from the lab
|
||
only (the guests' own logins whole, the owner's per-model weekly limits
|
||
only — the status line has the rest); a ChatGPT seat's from the machine
|
||
that hosts it (a worker's reading wins over the lab's); a Google account
|
||
is one quota every machine reads, so the freshest reading wins."""
|
||
host = getattr(deps, "account_health", None)
|
||
try:
|
||
lab = host.host_accounts() if host else set()
|
||
except Exception:
|
||
lab = set()
|
||
out: dict[str, dict] = {}
|
||
for vendor in _usage_vendors():
|
||
merge = _MERGE.get(vendor, _freshest_snapshots)
|
||
try:
|
||
out.update(merge(deps, vendor, lab))
|
||
except Exception:
|
||
continue
|
||
return out
|
||
|
||
|
||
def _claude_snapshots(deps, vendor: str, lab: set[str]) -> dict[str, dict]:
|
||
"""Anthropic: the lab sidecar's reads (provider-anthropic's ``sidecar/usage.py``) of the
|
||
guests' own Claude logins (their tokens stay there) and of the lab's own
|
||
Claude logins' per-model weekly limits — only what the status line can't
|
||
say: its own week stays the one figure (the two reads differ by a point
|
||
— no flicker)."""
|
||
import accounts as accounts_mod
|
||
out: dict[str, dict] = {}
|
||
claude = _vendor_accounts(vendor)
|
||
for acct, body in _lab_usage(vendor).items():
|
||
if accounts_mod.guest_of(acct):
|
||
out[acct] = body
|
||
elif acct in claude and isinstance(body, dict):
|
||
scoped = {k: v for k, v in (body.get("rate_limits") or {}).items()
|
||
if k.startswith("seven_day_")}
|
||
if scoped:
|
||
out[acct] = {**body, "rate_limits": scoped}
|
||
return out
|
||
|
||
|
||
def _hosted_snapshots(deps, vendor: str, lab: set[str]) -> dict[str, dict]:
|
||
"""OpenAI: each online worker that hosts a ChatGPT login serves it — and
|
||
the lab's own sidecar for one it holds (the one workers bill through the
|
||
opencode proxy); a worker's reading wins over the lab's."""
|
||
out: dict[str, dict] = {}
|
||
if lab - {a for a in lab if (_account(a) or {}).get("keyless")}:
|
||
for acct, body in _lab_usage(vendor).items():
|
||
if acct in lab:
|
||
out[acct] = body
|
||
vaccts = _vendor_accounts(vendor)
|
||
store = deps.worker_store
|
||
for w in store.list():
|
||
held = _worker_held(w, vendor, vaccts)
|
||
if not held or not store.online(w["id"]):
|
||
continue
|
||
got = _worker_usage(w, vendor)
|
||
if got is None:
|
||
continue
|
||
for acct, body in got.items():
|
||
if acct in held:
|
||
out[acct] = body
|
||
return out
|
||
|
||
|
||
def _freshest_snapshots(deps, vendor: str, lab: set[str]) -> dict[str, dict]:
|
||
"""A vendor whose accounts every machine reads alike (Google's
|
||
Antigravity quota — harness-agy's ``sidecar/usage.py``): from the lab's sidecar for
|
||
an account it declares and from every online owner worker that declares
|
||
one. Each machine holds its own login of the **same** account — one quota
|
||
— so the freshest reading wins (``updated_at``)."""
|
||
vaccts = _vendor_accounts(vendor)
|
||
if not vaccts:
|
||
return {}
|
||
got: dict[str, dict] = {}
|
||
|
||
def keep(acct: str, body) -> None:
|
||
if acct not in vaccts or not isinstance(body, dict):
|
||
return
|
||
cur = got.get(acct)
|
||
try:
|
||
newer = cur is None or float(body.get("updated_at") or 0) \
|
||
> float(cur.get("updated_at") or 0)
|
||
except (TypeError, ValueError):
|
||
newer = cur is None
|
||
if newer:
|
||
got[acct] = body
|
||
|
||
if vaccts & lab:
|
||
for acct, body in _lab_usage(vendor).items():
|
||
if acct in lab:
|
||
keep(acct, body)
|
||
store = deps.worker_store
|
||
for w in store.list():
|
||
held = _worker_held(w, vendor, vaccts) & vaccts
|
||
if not held or not store.online(w["id"]) or w.get("owner"):
|
||
continue
|
||
body = _worker_usage(w, vendor)
|
||
if body is None:
|
||
continue
|
||
for acct, b in body.items():
|
||
if acct in held:
|
||
keep(acct, b)
|
||
return got
|
||
|
||
|
||
def _agy_snapshots(deps, lab: set[str]) -> dict[str, dict]:
|
||
"""The Google (agy) accounts' Antigravity quota — ``_freshest_snapshots``
|
||
for ``google``."""
|
||
return _freshest_snapshots(deps, "google", lab)
|
||
|
||
|
||
# vendor → how its readings merge (a vendor not listed: the freshest wins)
|
||
_MERGE = {"anthropic": _claude_snapshots, "openai": _hosted_snapshots,
|
||
"google": _freshest_snapshots}
|
||
|
||
|
||
def _account(account: str) -> dict | None:
|
||
import accounts as accounts_mod
|
||
return accounts_mod.get(account)
|
||
|
||
|
||
def limit_alert(deps, account: str, window: str, pct: float, threshold: float,
|
||
resets_at) -> None:
|
||
"""The push when an account's window crosses one of its ``limitAlerts``."""
|
||
from notifications.service import _create_notify
|
||
import accounts as accounts_mod
|
||
label = (accounts_mod.get(account) or {}).get("label") or account
|
||
span = {"seven_day": "weekly", "five_hour": "5-hour"}.get(window) or (
|
||
f"{window[10:].replace('_', ' ').title()} weekly" if window.startswith("seven_day_")
|
||
else window)
|
||
when = ""
|
||
try:
|
||
left = float(resets_at) - time.time()
|
||
if left > 0:
|
||
d, h = int(left // 86400), int(left % 86400 // 3600)
|
||
when = f" — resets in {d}d {h}h" if d else f" — resets in {h}h"
|
||
except (TypeError, ValueError):
|
||
pass
|
||
_create_notify(deps, {"title": f"⚠️ {label} at {pct:.0f}% of its {span} limit",
|
||
"message": f"Past the {threshold:.0f}% alert{when}.",
|
||
"type": "ai", "url": "/dashboards"})
|
||
|
||
|
||
def _resets_in(resets_at) -> str:
|
||
""""2d 3h" until ``resets_at``, or "" when unknown / past."""
|
||
try:
|
||
left = float(resets_at) - time.time()
|
||
except (TypeError, ValueError):
|
||
return ""
|
||
if left <= 0:
|
||
return ""
|
||
d, h = int(left // 86400), int(left % 86400 // 3600)
|
||
return f"{d}d {h}h" if d else f"{h}h"
|
||
|
||
|
||
def behind_alert(deps, account: str, pct: float, target: float, resets_at) -> None:
|
||
"""The push when an account's week falls more than its ``behindAlert``
|
||
points under the target line (usage/target.py): where it is, where the
|
||
line is, and how many nonstop Opus runs would still use the rest
|
||
(``budget``'s streams, when it can tell)."""
|
||
from notifications.service import _create_notify
|
||
import accounts as accounts_mod
|
||
from . import budget as budget_mod
|
||
from . import target as target_mod
|
||
label = (accounts_mod.get(account) or {}).get("label") or account
|
||
goal = (target_mod.of(account) or {}).get("goal") or 100
|
||
when = _resets_in(resets_at)
|
||
streams = ""
|
||
try:
|
||
s = ((budget_mod.budget(deps, account).get("families") or {}).get("opus") or {}).get("streams")
|
||
if s:
|
||
streams = f" ≈ {s:.1f} Opus run{'s' if s >= 1.05 else ''} nonstop would use the rest."
|
||
except Exception:
|
||
pass
|
||
_create_notify(deps, {"title": f"🎯 {label} week behind its target",
|
||
"message": f"{pct:.0f}% used, the target is {target:.0f}% by now "
|
||
f"({goal:.0f}% at the reset{f', in {when}' if when else ''})."
|
||
f"{streams}",
|
||
"type": "ai", "url": "/"})
|
||
|
||
|
||
def track_plans(deps) -> None:
|
||
"""One plan reading per account (after every usage poll): its login's
|
||
tier — the login-health monitor's last ``/accounts`` row — and the
|
||
windows its fresh rate-limits.json reports."""
|
||
tracker = getattr(deps, "usage_plans", None)
|
||
if tracker is None:
|
||
return
|
||
health = getattr(deps, "account_health", None)
|
||
rows = health.live_rows() if health is not None else {}
|
||
started = False
|
||
for acct, snap in list(deps.usage_poller.latest.items()):
|
||
if guest(acct):
|
||
continue
|
||
row = rows.get(acct) or {}
|
||
seg = tracker.observe(acct, plans.tier_of(row), plans.windows_of(snap),
|
||
info=row.get("plan"))
|
||
started = started or seg is not None
|
||
if started and deps.usage_poller.publish:
|
||
deps.usage_poller.publish({"type": "usage"})
|
||
|
||
|
||
def plan_changed(deps, account: str, old: dict, new: dict) -> None:
|
||
"""The push when an account's plan changes: what changed, and the rate
|
||
the new plan starts from until it has a fit of its own."""
|
||
if not NOTIFY_PLAN:
|
||
return
|
||
from notifications.service import _create_notify
|
||
import accounts as accounts_mod
|
||
label = (accounts_mod.get(account) or {}).get("label") or account
|
||
seed = calibrate.seed_for(deps, account, new)
|
||
wk = (seed.get("week") or {}).get("unitsPerPct")
|
||
how = {"scaled": f"scaled ×{seed.get('scale') or 1:g} from the previous plan",
|
||
"carried": "carried over from the previous plan",
|
||
}.get(seed.get("source"), "the default")
|
||
rate = (f" Until it is refitted, 1 % of the week ≈ {wk:.1f} plan units ({how})."
|
||
if wk else "")
|
||
try:
|
||
_create_notify(deps, {"title": f"📏 {label} plan: {(new.get('data') or {}).get('reason')}",
|
||
"message": f"Recalibrating on the new plan's own hours.{rate}",
|
||
"type": "ai", "url": "/dashboards"})
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def calibrate_all(deps, notify: bool = True) -> tuple[dict, list[str]]:
|
||
cals, shifted = {}, []
|
||
for acct in metered(deps):
|
||
cal, moved = calibrate.run(deps, acct, (lambda a, t: _notify(deps, a, t))
|
||
if notify else None)
|
||
if cal:
|
||
cals[acct] = cal
|
||
if moved:
|
||
shifted.append(acct)
|
||
return cals, shifted
|
||
|
||
|
||
def _loop(deps) -> None:
|
||
time.sleep(120) # let the first index pass land
|
||
while True:
|
||
try:
|
||
for acct in metered(deps):
|
||
fits = deps.usage_store.calibrations(acct)
|
||
if not fits:
|
||
calibrate.backfill(deps, acct)
|
||
last = max((c["fittedAt"] for c in deps.usage_store.calibrations(acct)),
|
||
default=0)
|
||
if time.time() - last >= EVERY_S:
|
||
calibrate.run(deps, acct, lambda a, t: _notify(deps, a, t))
|
||
except Exception:
|
||
pass
|
||
time.sleep(CHECK_S)
|
||
|
||
|
||
def start(deps) -> None:
|
||
deps.usage_poller.start()
|
||
threading.Thread(target=_loop, args=(deps,), daemon=True,
|
||
name="usage-calibration").start()
|