Files
ai-agent/backend/plugins/metering.py
Gabriel VidalandClaude Opus 5.5 d969112d92 feat(pricing): cut pricing, the parser's UsageMeter, project costs and the usage service over to ProviderRegistry (Wave 3B)
- conversations/pricing.py holds no table any more (MODEL_PRICES, FAMILY_FALLBACK,
  FAST_MULT, HAIKU_LONG, OPENAI_*, GEMINI_*, OTHER_PRICES, LOCAL_WATTS,
  ELECTRICITY_EUR_PER_KWH, EVOX2_*, PLAN_METER_AS, PLAN_FABLE_WEIGHT gone): a
  facade over the provider plugins' registry, same names and signatures;
  PRICE_BOOK / USD_PER_EUR / LOCAL_* derived lazily from the plugins;
  book_key() replaces openai_model / gemini_model; price_call() exposed.
- plugins/seed_registry.py: effective() = the bound store's registry when it
  has ever known a provider (strict plugin-only), else the default plugins
  read from PLUGINS_SEED_DIR / the plugins checkout / fixtures — offline
  parses, scripts and unit tests price with zero setup, no network.
- parser: each API call priced once through ProviderRegistry.price_call
  (UsageMeter.price) — list cost, cache share and the EVOX2's time from the
  CallCost, plan units passed apart into the meter; priceBook = price_book().
- projects/costs.py: rates + local outputWeight from provider-evox2's pricing.
- usage/service.remote_snapshots: one loop over the providers with a
  usageReader, GET /usage/{vendor} on the lab and online workers, the legacy
  /claude|opencode|agy/usage only on a 404 (or the lab not answering);
  per-vendor merge policies keep the exact old results.
- providers.py: per-id memo of the claiming pricer and the token-table key
  (fixed per registry) — the parse prices at the old speed.
- plugins/metering.py reads USD_PER_EUR at use time.

A/B: scripts/ab/pricing-dump.py --base 1e431f52 → identical (10104 lines);
scripts/ab/parse-ab.py --base 1e431f52 --chunked → 499 files × 2 modes,
0 differing; chunked == one-shot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:41:01 +01:00

319 lines
11 KiB
Python

"""Metering, per-plugin monthly USD budgets, rate limits (in-flight / daily
jobs), and hub key-health alerting for managed live plugins."""
from __future__ import annotations
import logging
import threading
import time
from typing import Any
from conversations import pricing
from toolproxy import access
from toolproxy.ledger import LEDGER, month_of
log = logging.getLogger("plugins.metering")
_lock = threading.Lock()
_in_flight: dict[tuple[str, str], int] = {}
_daily_jobs: dict[tuple[str, str, str], int] = {}
_minute_hits: dict[str, list[float]] = {}
PER_MINUTE = 120
BROKEN_STATES = frozenset({"no-credit", "invalid", "denied", "capped"})
KEY_STATES = frozenset({"ok"}) | BROKEN_STATES
def enter(who_key: str, pid: str) -> None:
with _lock:
k = (who_key, pid)
_in_flight[k] = _in_flight.get(k, 0) + 1
def leave(who_key: str, pid: str) -> None:
with _lock:
k = (who_key, pid)
n = _in_flight.get(k, 0) - 1
if n > 0:
_in_flight[k] = n
else:
_in_flight.pop(k, None)
def count_job(who_key: str, pid: str) -> None:
day = time.strftime("%Y-%m-%d", time.gmtime())
with _lock:
k = (who_key, pid, day)
_daily_jobs[k] = _daily_jobs.get(k, 0) + 1
def _take_minute(who_key: str) -> bool:
now = time.time()
with _lock:
hits = [t for t in _minute_hits.get(who_key, []) if now - t < 60]
if len(hits) >= PER_MINUTE:
_minute_hits[who_key] = hits
return False
hits.append(now)
_minute_hits[who_key] = hits
return True
def plugin_spent_by_who(who_key: str, pid: str, month: str | None = None) -> float:
summary = LEDGER.summary("who", who_key, month=month)
tool_entry = (summary.get("byTool") or {}).get(f"plugin:{pid}") or {}
return float(tool_entry.get("usd") or 0.0)
def plugin_usage_by_who(who_key: str, pid: str, month: str | None = None) -> dict[str, Any]:
summary = LEDGER.summary("who", who_key, month=month)
tool_entry = (summary.get("byTool") or {}).get(f"plugin:{pid}") or {}
return {
"month": summary.get("month") or month_of(),
"usd": round(float(tool_entry.get("usd") or 0.0), 4),
"calls": int(tool_entry.get("calls") or 0),
"units": dict(tool_entry.get("units") or {}),
}
def check_limits(
deps,
who: access.Who,
pid: str,
manifest: dict[str, Any],
grant: dict[str, Any] | None,
*,
using_own_secret: bool = False,
creates: bool = False,
) -> tuple[int, str, str] | None:
"""Return ``(status, message, kind)`` if the caller may not run this managed
plugin call right now, else ``None``."""
if who.is_owner:
return None
u = deps.users.active(who.uid)
if not u:
return 403, "your guest account is disabled", "disabled"
if deps.security_state.guests_locked():
return 403, "guest access is paused for now", "locked"
if who.worker and who.worker.get("paused"):
return 403, "this computer is paused — switch it back on in Settings → My computers", "paused"
mg = manifest.get("managed") or {}
limits = mg.get("limits") or {}
if not _take_minute(who.key):
return 429, f"more than {PER_MINUTE} plugin calls in a minute — slow down", "rate"
# Per-plugin monthly USD budget (skipped when guest uses their own BYOK key)
if mg.get("metered") and not using_own_secret:
budget = (grant or {}).get("monthlyBudgetUsd")
if budget is None:
budget = limits.get("defaultMonthlyBudgetUsd")
if budget is not None:
spent = plugin_spent_by_who(who.key, pid)
if spent >= float(budget):
return (
429,
f"your monthly budget for {manifest.get('name', pid)} is spent "
f"(${spent:.2f} of ${float(budget):.2f}) — resets on the 1st",
"budget",
)
day = time.strftime("%Y-%m-%d", time.gmtime())
with _lock:
busy = _in_flight.get((who.key, pid), 0)
today_jobs = _daily_jobs.get((who.key, pid, day), 0)
max_in_flight = int(limits.get("inFlight") or 6)
if busy >= max_in_flight:
return 429, f"{max_in_flight} {pid} calls are already running for you — wait for one to finish", "inflight"
max_daily = limits.get("jobsPerDay")
if creates and max_daily is not None and today_jobs >= int(max_daily):
return 429, f"{max_daily} {pid} jobs today is the daily limit — resets at midnight UTC", "daily"
return None
def apply_meter(
deps,
who: access.Who,
pid: str,
manifest: dict[str, Any],
meter: dict[str, Any],
*,
session_header: str | None = None,
using_own_secret: bool = False,
) -> None:
"""Record a plugin action's ``_meter`` envelope in the ledger, update
conversation tools metadata, count daily jobs, and fire owner key-health
/ spend alerts."""
if not isinstance(meter, dict):
return
usd = round(max(0.0, float(meter.get("usd") or 0.0)), 6)
# BYOK calls are still counted in units, with $0 against the owner's spend
billed_usd = 0.0 if using_own_secret else usd
units = meter.get("units") if isinstance(meter.get("units"), dict) else {}
sid = access.session_of(deps, who, session_header)
entry: dict[str, Any] = {
"tool": f"plugin:{pid}",
**who.row(),
"usd": billed_usd,
"units": units,
}
if sid:
entry["session"] = sid
if meter.get("model"):
entry["model"] = str(meter["model"])[:80]
if meter.get("op"):
entry["op"] = str(meter["op"])[:80]
if using_own_secret:
entry["byok"] = True
LEDGER.record(entry)
if sid:
try:
deps.meta_store.update(sid, {"tools": LEDGER.session(sid)})
deps.hub.publish({"type": "meta", "id": sid})
except Exception:
pass
if meter.get("creates"):
count_job(who.key, pid)
# Key health & monthly owner spend alerts (only for hub-owned secret calls)
if using_own_secret or not (manifest.get("managed") or {}).get("keyHealth"):
return
kh = meter.get("keyHealth")
if isinstance(kh, dict) and kh.get("status"):
observe_key_health(
deps, pid, manifest, str(kh["status"]), str(kh.get("message") or ""),
who_row=who.row(), model=str(meter.get("model") or "") or None,
test=who.via == "test",
)
if billed_usd > 0:
check_spend(deps, pid, manifest)
# ── the hub key: its health, its monthly alert line ─────────────────────────
def key_health_spec(manifest: dict[str, Any]) -> dict[str, Any] | None:
"""``managed.keyHealth`` of a manifest (None: the plugin has no hub key
to watch)."""
kh = (manifest.get("managed") or {}).get("keyHealth")
return kh if isinstance(kh, dict) else None
def key_settings(deps, pid: str, manifest: dict[str, Any]) -> dict[str, Any]:
"""The effective alert settings: the manifest's defaults under the
owner's runtime overrides."""
return deps.plugin_store.key_settings(pid, manifest)
def limit_usd(settings: dict[str, Any]) -> float:
amount = float(settings.get("alertLimit") or 0)
return amount * pricing.USD_PER_EUR if (settings.get("currency") or "EUR") == "EUR" else amount
def money(usd: float, currency: str) -> str:
return f"€{usd / USD_PER_EUR:.2f}" if currency == "EUR" else f"${usd:.2f}"
def ledger_tools(pid: str, manifest: dict[str, Any]) -> list[str]:
"""The ledger tools whose rows are this plugin's spend: ``plugin:<id>``
and, for a plugin that took over a core tool, that tool's older rows
(``managed.keyHealth.legacyLedgerTool``)."""
tools = [f"plugin:{pid}"]
legacy = (key_health_spec(manifest) or {}).get("legacyLedgerTool")
if legacy:
tools.append(str(legacy))
return tools
def month_spent(pid: str, manifest: dict[str, Any], month: str | None = None) -> float:
month = month or month_of()
return float(sum(LEDGER.tool_spent(t, month) for t in ledger_tools(pid, manifest)))
_BREAK_TEXT = {
"no-credit": "the provider's prepaid credit is used up — every call fails until it's topped up.",
"invalid": "the provider says the key isn't valid any more — replace it on the plugin's page.",
"denied": "the provider refused the key (permission denied) — check its project and API "
"restrictions, or replace it.",
"capped": "the key's spend cap is reached — the provider pauses it until it's raised or "
"the month turns.",
}
def observe_key_health(deps, pid: str, manifest: dict[str, Any], status: str,
message: str = "", *, who_row: dict[str, Any] | None = None,
model: str | None = None, test: bool = False,
http_status: int = 0) -> dict[str, Any]:
"""Record one reply's verdict on the hub key and push the owner when it
moved the key into a broken state (``type: error``) or back to working
(``type: success``) — each transition once, so a restart or the
blue-green deploy's second backend doesn't push twice."""
settings = key_settings(deps, pid, manifest)
rec = deps.plugin_store.record_key_health(
pid, status, message[:300], who=who_row, model=model, test=test,
http_status=http_status, push=bool(settings.get("pushOnBreak", True)),
)
name = manifest.get("name") or pid
url = f"/settings/plugin/{pid}"
if rec.get("_push") == "break":
_notify_owner(
deps, title=f"🔑 {name} key stopped working",
message=f"{_BREAK_TEXT.get(status, status)}"
+ (f" ({message[:200]})" if message else ""),
url=url, type_="error",
)
elif rec.get("_push") == "recover":
_notify_owner(
deps, title=f"✅ {name} key works again",
message=f"{name} calls go through again.", url=url, type_="success",
)
return rec
def check_spend(deps, pid: str, manifest: dict[str, Any], month: str | None = None) -> list[int]:
"""Push once a month at the owner's % of the alert line and once at 100 %
(an alert only — calls keep going). Returns the thresholds pushed now."""
settings = key_settings(deps, pid, manifest)
lim = limit_usd(settings)
if lim <= 0:
return []
month = month or month_of()
spent = month_spent(pid, manifest, month)
pct = spent / lim * 100
push_at = int(settings.get("pushAtPct") or 80)
due = [p for p in sorted({push_at, 100}) if pct >= p]
fresh = [p for p in due if deps.plugin_store.mark_spend_alert(pid, month, p)]
if not fresh:
return []
top = max(fresh)
name = manifest.get("name") or pid
cur = settings.get("currency") or "EUR"
title = (f"💸 {name}: monthly limit reached" if top >= 100
else f"💸 {name}: {top} % of the monthly limit")
_notify_owner(
deps, title=title,
message=f"{money(spent, cur)} of {money(lim, cur)} spent this month ({month}) — "
"an alert only, calls keep going.",
url=f"/settings/plugin/{pid}", type_="warn",
)
return fresh
def _notify_owner(deps, *, title: str, message: str, url: str = "", type_: str = "warn") -> None:
try:
from notifications.routes import _create_notify
_create_notify(deps, {
"title": title[:120],
"message": message[:400],
"type": type_,
"url": url,
"to": None,
})
except Exception as e:
log.warning("plugin metering notify failed: %s", e)