Files
ai-agent/backend/plugins/keyspend.py
gabrielvidalandClaude Opus 5.5 74dbc55d03 feat(plugins): Settings → API keys folds into the plugin's Hub key section
The core API keys page (backend/apikeys/, business/apiKeys/) and the host
sidecar's /homelab-env writer are retired: a managed plugin that declares
managed.keyHealth gets the same page on its Settings page, generic.

Manifest
- settings.links[]: {label, url} https:// links with {{config.<field>}}
  placeholders (URL-quoted; a link whose field is empty is left out).
- managed.keyHealth: alertLimit + currency (alertLimitEur still reads),
  secretKey (default: the first hub secret), legacyLedgerTool (a core ledger
  tool whose rows count as the plugin's spend: nanobanana → plugin:nanobanana).

Store / metering
- set_secret keeps a non-secret last-4 hint (installed.json → secretHints);
  secrets stored before hints get theirs on first read.
- Runtime key settings per plugin (alertLimit, currency, pushAtPct,
  pushOnBreak) over the manifest defaults.
- Key health: ok / broken states set the state, other failures are listed
  only; a break pushes once (type error), the recovery once ("✅ <Plugin> key
  works again", type success); the month pushes at pushAtPct and at 100 %,
  each once per month; spend merges the legacy ledger tool.

Routes
- GET /api/plugins/{pid}/spend (plugins.manage): health + hint, settings,
  month, byCaller, byModel, 30 days with failures, recent successes +
  failures with session links, the links filled in (plugins/keyspend.py).
- PUT /api/plugins/{pid}/key-settings (plugins.manage).
- POST /api/plugins/{pid}/test records the testAction's verdict (its _meter
  billed as via "test", or a structured _error whose kind is a key state).
- PUT /api/plugins/{pid}/secrets/{key} on the watched hub key: checked with
  testAction before saving — the run's handler token carries the candidate in
  memory (plugins.proxy.register_candidate) so its proxy calls use it;
  invalid / denied → 400, no-credit / capped → saved, anything else → 502.
- /proxy/tools/nanobanana/<model> (the cli hub edition) reads the plugin's hub
  key and feeds its health; Gemini's classify moves to toolproxy/catalog.

Frontend
- PluginKeyHealthSection (status + hint + Test / Replace + links, month with
  progress, threshold marker and the limit / currency / alerts form, by caller
  / model + 30-day bars with failure dots, recent calls) on PluginSettingsPage
  for the owner; /settings/api-keys redirects to /settings/plugin/nanobanana;
  the settings entry, mock, lazy page and unused French strings go.

openapi.json is not re-dumped here (the coordinator does it after Batch 2).

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

253 lines
9.5 KiB
Python

"""
What a plugin's page shows of its hub key (``GET /api/plugins/{id}/spend``,
for any owner plugin with ``managed.keyHealth``): the key's health and its
last-4 hint, the owner's alert settings, this month against the alert line,
who and which model spent it, the last 30 days and the recent calls — the
ledger's successes beside the recorded failures.
The spend is the tool ledger's (``toolproxy/ledger.py``): every call the
plugin's actions bill lands there as ``plugin:<id>``; the rows a core tool
wrote before the plugin took it over (``managed.keyHealth.legacyLedgerTool``,
e.g. ``nanobanana``) count too.
"""
from __future__ import annotations
import datetime as dt
import re
import time
from typing import Any
from urllib.parse import quote
from plugins import metering
from plugins.store import OWNER_UID
from toolproxy.ledger import LEDGER, month_of
DAYS = 30
RECENT = 30
_VAR_RE = re.compile(r"\{\{\s*config\.([A-Za-z0-9_]+)\s*\}\}")
def _prev_month(month: str) -> str:
y, m = (int(x) for x in month.split("-"))
return f"{y - 1}-12" if m == 1 else f"{y}-{m - 1:02d}"
def _day(ts: float) -> str:
return time.strftime("%Y-%m-%d", time.localtime(ts))
def _epoch(iso: str | None) -> float | None:
if not iso:
return None
try:
return dt.datetime.strptime(iso, "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=dt.timezone.utc).timestamp()
except ValueError:
return None
def effective_config(rec: dict[str, Any]) -> dict[str, Any]:
"""The plugin's settings values: the fields' defaults under what was saved."""
mf = rec.get("manifest") or {}
cfg = {f["key"]: f.get("default") for f in ((mf.get("settings") or {}).get("fields") or [])
if f.get("default") not in (None, "")}
cfg.update({k: v for k, v in (rec.get("config") or {}).items() if v not in (None, "")})
return cfg
def links(rec: dict[str, Any]) -> list[dict[str, str]]:
"""``settings.links`` with ``{{config.<key>}}`` filled in (URL-quoted); a
link whose placeholder has no value is left out rather than broken."""
cfg = effective_config(rec)
out: list[dict[str, str]] = []
for ln in (((rec.get("manifest") or {}).get("settings") or {}).get("links") or []):
missing = False
def fill(m: re.Match) -> str:
nonlocal missing
v = cfg.get(m.group(1))
if v in (None, ""):
missing = True
return ""
return quote(str(v), safe="")
url = _VAR_RE.sub(fill, ln["url"])
if not missing:
out.append({"label": ln["label"], "url": url})
return out
class _Names:
"""Caller labels: you on the lab, your Macs by name, guests by name."""
def __init__(self, deps):
self.deps = deps
self._w: dict[str, str] = {}
self._u: dict[str, str] = {}
def worker(self, wid: str) -> str:
if wid not in self._w:
w = None
try:
w = self.deps.worker_store.get(wid)
except Exception:
pass
self._w[wid] = str((w or {}).get("name") or wid)
return self._w[wid]
def user(self, uid: str) -> str:
if uid not in self._u:
u = None
try:
u = self.deps.users.get(uid)
except Exception:
pass
self._u[uid] = str((u or {}).get("name") or uid)
return self._u[uid]
def of(self, row: dict) -> tuple[str, str, str]:
"""``(key, label, kind)`` of a ledger row / failure."""
who = str(row.get("who") or "owner")
wid = row.get("worker")
if row.get("test") or row.get("via") == "test":
return "test", "Key test", "test"
if who == "owner":
if wid:
return f"owner:{wid}", self.worker(str(wid)), "worker"
return "owner", "You · lab", "owner"
name = self.user(who)
if wid:
return f"{who}:{wid}", f"{name} · {self.worker(str(wid))}", "guest"
return who, f"{name} · lab run", "guest"
def _add_units(into: dict[str, int], units: Any) -> None:
for k, v in (units or {}).items() if isinstance(units, dict) else []:
try:
into[str(k)] = into.get(str(k), 0) + int(v)
except (TypeError, ValueError):
pass
def hint(deps, pid: str, manifest: dict[str, Any]) -> str:
key = (metering.key_health_spec(manifest) or {}).get("secretKey")
if not key:
return ""
h = deps.plugin_store.secret_hint(OWNER_UID, pid, key, scope="hub")
return f"…{h['last4']}" if h and h.get("last4") else ("set" if h else "")
def health_view(deps, pid: str, names: _Names | None = None) -> dict[str, Any]:
kh = deps.plugin_store.get_key_health(pid) or {}
names = names or _Names(deps)
last = kh.get("lastErrorEvent")
last_err = None
if isinstance(last, dict):
last_err = {"t": last.get("t") or _epoch(last.get("at")), "status": last.get("httpStatus") or 0,
"kind": last.get("status"), "message": last.get("message") or "",
"model": last.get("model"), "caller": names.of(last)[1],
"test": bool(last.get("test"))}
return {
"status": kh.get("status") or "unknown",
"message": kh.get("message") or "",
"since": kh.get("sinceT") or _epoch(kh.get("since")),
"checkedAt": _epoch(kh.get("checkedAt")),
"lastOk": _epoch(kh.get("lastOk")),
"lastError": last_err,
"replacedAt": _epoch(kh.get("replacedAt")),
}
def build(deps, pid: str, rec: dict[str, Any], now: float | None = None) -> dict[str, Any]:
now = time.time() if now is None else now
mf = rec.get("manifest") or {}
spec = metering.key_health_spec(mf) or {}
settings = metering.key_settings(deps, pid, mf)
lim_usd = metering.limit_usd(settings)
month = month_of(now)
prev = _prev_month(month)
rows: list[dict] = []
for tool in metering.ledger_tools(pid, mf):
rows += LEDGER.rows([prev, month], tool=tool)
rows.sort(key=lambda r: float(r.get("t") or 0))
names = _Names(deps)
month_rows = [r for r in rows if month_of(float(r.get("t") or 0)) == month]
callers: dict[str, dict] = {}
models: dict[str, dict] = {}
m_usd, m_units = 0.0, {}
for r in month_rows:
usd = float(r.get("usd") or 0)
m_usd += usd
_add_units(m_units, r.get("units"))
ck, label, kind = names.of(r)
c = callers.setdefault(ck, {"key": ck, "label": label, "kind": kind,
"usd": 0.0, "calls": 0, "units": {}})
c["usd"] += usd
c["calls"] += 1
_add_units(c["units"], r.get("units"))
model = str(r.get("model") or "?")
mlabel = "Key test" if (r.get("via") == "test" or r.get("op") == "test") else model
mm = models.setdefault(f"{model}|{mlabel}", {"model": model, "label": mlabel,
"usd": 0.0, "calls": 0, "units": {}})
mm["usd"] += usd
mm["calls"] += 1
_add_units(mm["units"], r.get("units"))
# The last 30 local days, today included.
today = dt.date.fromtimestamp(now)
order = [(today - dt.timedelta(days=i)).isoformat() for i in range(DAYS - 1, -1, -1)]
days = {d: {"date": d, "usd": 0.0, "calls": 0, "failures": 0} for d in order}
for r in rows:
d = days.get(_day(float(r.get("t") or 0)))
if d:
d["usd"] += float(r.get("usd") or 0)
d["calls"] += 1
kh = deps.plugin_store.get_key_health(pid) or {}
failures = [f for f in (kh.get("failures") or []) if isinstance(f, dict)]
for f in failures:
f.setdefault("t", _epoch(f.get("at")) or 0)
d = days.get(_day(float(f["t"] or 0)))
if d:
d["failures"] += 1
recent: list[dict] = []
for r in rows[-RECENT:]:
recent.append({"t": float(r.get("t") or 0), "ok": True, "caller": names.of(r)[1],
"model": r.get("model"), "usd": round(float(r.get("usd") or 0), 6),
"units": dict(r.get("units") or {}), "session": r.get("session"),
"test": r.get("via") == "test"})
for f in failures[-RECENT:]:
recent.append({"t": float(f.get("t") or 0), "ok": False, "caller": names.of(f)[1],
"model": f.get("model"), "test": bool(f.get("test")),
"status": f.get("httpStatus") or 0, "kind": f.get("status"),
"message": f.get("message") or "", "session": f.get("session")})
recent.sort(key=lambda e: e["t"], reverse=True)
prev_usd = sum(float(r.get("usd") or 0) for r in rows
if month_of(float(r.get("t") or 0)) == prev)
def rnd(xs):
return [{**x, "usd": round(x["usd"], 4)} for x in xs]
return {
"id": pid,
"name": mf.get("name") or pid,
"secretKey": spec.get("secretKey"),
"hint": hint(deps, pid, mf),
"keyHealth": health_view(deps, pid, names),
"settings": settings,
"month": {
"month": month, "usd": round(m_usd, 4), "calls": len(month_rows),
"units": m_units, "prevUsd": round(prev_usd, 4),
"limitUsd": round(lim_usd, 4),
"pct": round(m_usd / lim_usd * 100, 1) if lim_usd > 0 else 0,
},
"byCaller": rnd(sorted(callers.values(), key=lambda c: -c["usd"])),
"byModel": rnd(sorted(models.values(), key=lambda m: -m["usd"])),
"days": rnd(list(days.values())),
"recent": recent[:RECENT],
"links": links(rec),
}