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>
178 lines
7.9 KiB
Python
178 lines
7.9 KiB
Python
"""
|
|
What the tool proxy serves: the tool groups the owner switches on per guest,
|
|
the skills each group brings to their runs, and the Nano Banana price book.
|
|
|
|
Four groups (Gabriel's picks, form ``guest-paid-tools_zhs72t``, 2026-11-06;
|
|
``analytics`` since form ``ouliapo-analytics-via-matomo_9qad10``, 2026-11-11):
|
|
|
|
* ``images`` — Nano Banana (Gemini image models), billed at Google's list
|
|
price from each reply's ``usageMetadata``, against the guest's **tools
|
|
budget** (``tools.budgetUsd``, apart from their Claude budget);
|
|
* ``video`` — video-dl (runs where the run is: no key, no proxy) and
|
|
video-extract (runs on the lab / EVOX2 through the host sidecar);
|
|
* ``3d`` — 3d-gen (TRELLIS on the EVOX2, the lab's 3d-gen service) and
|
|
3d-render (the lab's CPU rasteriser);
|
|
* ``analytics`` — the lab's Matomo (``matomo.py``) for the guest's own sites
|
|
(the ones on their address): add one, read its reports, mint a view-only key
|
|
for a page of theirs;
|
|
* ``media`` — movies on the lab's Jellyfin through Seerr (``media.py``, form
|
|
``seerr-for-the-movie-skill_z5gm4h``, 2026-11-16): search, request (3 a week,
|
|
auto-approved — Seerr's quota), a push once it's there; series for the owner;
|
|
* ``meta`` — the guest's own Meta Business, read-only (``meta.py``, form
|
|
``meta-business-read-only-for-cel_qbacrq``, 2026-11-25): ad insights, their
|
|
Instagram account and Facebook Page, with a key they connect themselves, and
|
|
a free daily snapshot.
|
|
|
|
The lab's own jobs (EVOX2 / CPU) are **free but counted**: a ledger row with
|
|
``usd: 0`` and what it did (``units``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import pathlib
|
|
import re
|
|
|
|
GROUPS = ("images", "video", "3d", "analytics", "media", "meta")
|
|
GROUP_LABELS = {"images": "Images · Nano Banana", "video": "Video · download + understanding",
|
|
"3d": "3D · generation + render", "analytics": "Analytics · Matomo",
|
|
"media": "Movies · Seerr", "meta": "Meta Business · read-only"}
|
|
# tool → group
|
|
GROUP_OF = {"nanobanana": "images", "video-extract": "video",
|
|
"3d-gen": "3d", "3d-render": "3d", "matomo": "analytics", "movies": "media",
|
|
"meta": "meta"}
|
|
TOOLS = tuple(GROUP_OF)
|
|
# The skills a group brings: ``@name`` = this repo's hub edition
|
|
# (``cli/skills/<name>``, a stdlib client of this proxy), a plain name = the
|
|
# homelab repo's own skill (video-dl needs no key: it runs where the run is).
|
|
GROUP_SKILLS = {"images": ["@nanobanana"], "video": ["video-dl", "@video-extract"],
|
|
"3d": ["@3d-gen", "@3d-render"], "analytics": ["@matomo"],
|
|
"media": ["@movies"], "meta": ["@meta"]}
|
|
# The hub editions, by name (what a worker's lab sync carries).
|
|
HUB_SKILLS = ("nanobanana", "video-extract", "3d-gen", "3d-render", "matomo", "movies", "meta")
|
|
|
|
|
|
def builtin_dir() -> pathlib.Path:
|
|
"""``cli/skills``: next to the backend in the image (``/app/cli``), one
|
|
level up in a checkout."""
|
|
env = os.environ.get("TOOLPROXY_SKILLS_DIR")
|
|
if env:
|
|
return pathlib.Path(env)
|
|
here = pathlib.Path(__file__).resolve().parent
|
|
for base in (here.parent, here.parent.parent):
|
|
d = base / "cli" / "skills"
|
|
if d.is_dir():
|
|
return d
|
|
return here.parent.parent / "cli" / "skills"
|
|
|
|
|
|
# ── Nano Banana: models and prices ───────────────────────────────────────────
|
|
# USD per 1M tokens — Google's Standard (paid) tier, read 2026-11-06 off
|
|
# aistudio.google.com/docs/pricing: input (text/image), output text +
|
|
# thinking, output images. ``pro`` models need the guest's Pro switch.
|
|
NB_MODELS: dict[str, dict] = {
|
|
"gemini-2.5-flash-image": {"in": 0.30, "text": 2.50, "image": 30.0, "pro": False,
|
|
"label": "Nano Banana"},
|
|
"gemini-3.1-flash-image": {"in": 0.50, "text": 3.0, "image": 60.0, "pro": False,
|
|
"label": "Nano Banana 2"},
|
|
"gemini-3.1-flash-lite-image": {"in": 0.25, "text": 1.50, "image": 30.0, "pro": False,
|
|
"label": "Nano Banana 2 Lite"},
|
|
"gemini-nano-banana-2.1": {"in": 1.50, "text": 7.50, "image": 30.0, "pro": False,
|
|
"label": "Nano Banana 2.1"},
|
|
"gemini-3-pro-image": {"in": 2.0, "text": 12.0, "image": 120.0, "pro": True,
|
|
"label": "Nano Banana Pro"},
|
|
}
|
|
NB_DEFAULT = "gemini-2.5-flash-image"
|
|
_MODEL_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{2,80}$")
|
|
|
|
|
|
def nb_model(model: str | None) -> tuple[str, dict] | None:
|
|
"""The price-book entry of a model id — ``-preview`` / dated suffixes
|
|
included (``gemini-3-pro-image-preview`` is Pro) — else None."""
|
|
m = (model or "").strip().lower()
|
|
if not _MODEL_RE.match(m):
|
|
return None
|
|
for name in sorted(NB_MODELS, key=len, reverse=True):
|
|
if m == name or m.startswith(name + "-"):
|
|
return name, NB_MODELS[name]
|
|
return None
|
|
|
|
|
|
def nb_cost(model: str, usage: dict | None) -> float:
|
|
"""The USD of one generateContent reply from its ``usageMetadata``:
|
|
prompt tokens at the input price, image tokens at the image price, text +
|
|
thinking tokens at the text price."""
|
|
hit = nb_model(model)
|
|
if not hit or not isinstance(usage, dict):
|
|
return 0.0
|
|
p = hit[1]
|
|
prompt = int(usage.get("promptTokenCount") or 0)
|
|
thoughts = int(usage.get("thoughtsTokenCount") or 0)
|
|
cand = int(usage.get("candidatesTokenCount") or 0)
|
|
image = text = 0
|
|
details = usage.get("candidatesTokensDetails")
|
|
if isinstance(details, list) and details:
|
|
for d in details:
|
|
if not isinstance(d, dict):
|
|
continue
|
|
n = int(d.get("tokenCount") or 0)
|
|
if str(d.get("modality") or "").upper() == "IMAGE":
|
|
image += n
|
|
else:
|
|
text += n
|
|
else:
|
|
image = cand
|
|
usd = (prompt * p["in"] + image * p["image"] + (text + thoughts) * p["text"]) / 1e6
|
|
return round(usd, 6)
|
|
|
|
|
|
def count_images(reply: dict) -> int:
|
|
n = 0
|
|
for c in (reply or {}).get("candidates") or []:
|
|
for part in ((c or {}).get("content") or {}).get("parts") or []:
|
|
if isinstance(part, dict) and (part.get("inlineData") or part.get("inline_data")):
|
|
n += 1
|
|
return n
|
|
|
|
|
|
# ── Google's replies → the key's state (the nanobanana plugin's
|
|
# ``handlers/nblib.py`` ``classify_raw`` is the same — keep them in step) ─────
|
|
GEMINI_UPSTREAM = os.environ.get("GEMINI_UPSTREAM",
|
|
"https://generativelanguage.googleapis.com/v1beta").rstrip("/")
|
|
NB_BROKEN = ("no-credit", "invalid", "denied", "capped")
|
|
|
|
|
|
def _gemini_error(reply) -> tuple[str, set[str]]:
|
|
err = reply.get("error") if isinstance(reply, dict) else None
|
|
if not isinstance(err, dict):
|
|
return "", set()
|
|
details = err.get("details")
|
|
reasons = {str(d["reason"]) for d in details if isinstance(d, dict) and d.get("reason")} \
|
|
if isinstance(details, list) else set()
|
|
return str(err.get("message") or err.get("status") or ""), reasons
|
|
|
|
|
|
def nb_classify(status: int, reply) -> tuple[str, str]:
|
|
"""``(state, message)`` of one Gemini reply: ``ok``, a :data:`NB_BROKEN`
|
|
state, or ``rate-limited`` / ``bad-request`` / ``error`` (that call
|
|
failed, the key is fine)."""
|
|
if status == 200:
|
|
return "ok", ""
|
|
msg, reasons = _gemini_error(reply)
|
|
msg = msg or f"HTTP {status}"
|
|
low = msg.lower()
|
|
if status == 402 or "prepayment" in low or "credits are depleted" in low:
|
|
return "no-credit", msg
|
|
if "API_KEY_INVALID" in reasons or "api key not valid" in low or "api key expired" in low:
|
|
return "invalid", msg
|
|
if "spend cap" in low or "spending cap" in low or "spend limit" in low:
|
|
return "capped", msg
|
|
if status == 403:
|
|
return "denied", msg
|
|
if status == 429:
|
|
return "rate-limited", msg
|
|
if status == 400:
|
|
return "bad-request", msg
|
|
return "error", msg
|
|
|