Since 2026-11-25 nanobanana, video-extract, 3d-gen, 3d-render, matomo, movies and meta are live plugins with their own proxies and managed grants, but the core still served the old path next to them — and its hub editions won over the plugin skills on workers. This finishes the move (form ai-agent-moves-to-ai-agent-plugins_o2qxmd, move A). Rebased on41665fa2, which had already removed the core's Meta Business. - gone: toolproxy/{matomo,media,webroutes,owned,catalog}.py, the nanobanana / 3d-gen / 3d-render / video-extract / matomo / movies routes and the movies webhook, cli/skills/{nanobanana,3d-gen,3d-render,video-extract,matomo, movies}, the guests' `tools` groups (users store, Caller.tool_groups, Me/GuestUser.tools, tools.matomoSites), the User page's Paid tools and Tools budget panels - kept: the /proxy/tools door (tokens, whoami — now the caller's plugins and spend — and the shared client), the tool ledger, the tools chip, a guest job's tool token (c6e15991: tool_scope still gives one with plugin skills) - labsync: a plugin skill wins over a lab skill of the same name; plugin skills with a proxy keep their hub.json - guest runs get their plugins' skills on spawn, resume, reply, fork and No project runs alike (deps passed to scope_for / scratch_scope everywhere) - Movies brings Jellyfin when the movies grant comes on (new guest, or the owner's switch) - plugins/carryover_tools.py: tool groups → grants / installs (never over an explicit grant), Meta keys + saved days (only where the plugin has none), Matomo viewers, Seerr users and pending requests, 3d-gen ownership → the plugins' data, once - matomo_sites: users.json tools.matomoSites → the matomo grant's `extraSites` (list grantField, sibling ai-agent-plugins PR), and the grant on for an `analytics` guest — once per guest, so Cel (analytics + site 11 after the groups moved) gets it; an explicit grant only gets extraSites when it has none; waits for a matomo manifest with the field - Me → Budget's Tools card reads the guest's managed plugins Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
7.2 KiB
Python
174 lines
7.2 KiB
Python
"""
|
|
The tool ledger: one JSON line per tool call that did something, in
|
|
``PROXY_LEDGER_DIR/tools/<YYYY-MM>.jsonl`` — beside the Claude proxy's
|
|
ledger but apart from it, because a guest's tools have **budgets of their
|
|
own** (each managed plugin grant's ``monthlyBudgetUsd``, ``plugins/metering.py``;
|
|
the core's one ``tools.budgetUsd`` until 2026-11-26): nothing here counts
|
|
toward their Claude budget.
|
|
|
|
A row: ``{t, tool, who, guest?, worker?, session?, usd, units, model?, job?}``
|
|
— ``who`` is the guest's id or ``owner`` (the owner's workers go through the
|
|
proxy too, unlimited). ``units`` says what the call did (``images``,
|
|
``jobs``, ``videos``, ``renders``): the lab's own jobs are free but counted.
|
|
|
|
Sums are kept in memory per (month, kind, key) — kind ``who`` / ``worker`` —
|
|
and per session over every month (the conversation's cost chip).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import threading
|
|
import time
|
|
|
|
LEDGER_DIR = pathlib.Path(os.environ.get("PROXY_LEDGER_DIR", "/data/proxy-ledger")) / "tools"
|
|
|
|
|
|
def month_of(ts: float | None = None) -> str:
|
|
return datetime.datetime.fromtimestamp(ts if ts is not None else time.time(),
|
|
datetime.timezone.utc).strftime("%Y-%m")
|
|
|
|
|
|
def _zero() -> dict:
|
|
return {"usd": 0.0, "calls": 0, "byTool": {}}
|
|
|
|
|
|
class ToolLedger:
|
|
def __init__(self, root: pathlib.Path = LEDGER_DIR):
|
|
self.root = pathlib.Path(root)
|
|
self._lock = threading.Lock()
|
|
self._sums: dict[tuple[str, str, str], dict] = {}
|
|
self._sessions: dict[str, dict] = {}
|
|
self._loaded: set[str] = set()
|
|
self._all = False
|
|
|
|
# ── loading ──────────────────────────────────────────────────────────────
|
|
def _load(self, month: str) -> None:
|
|
if month in self._loaded:
|
|
return
|
|
self._loaded.add(month)
|
|
try:
|
|
lines = (self.root / f"{month}.jsonl").read_text(encoding="utf-8").splitlines()
|
|
except OSError:
|
|
return
|
|
for line in lines:
|
|
try:
|
|
e = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(e, dict):
|
|
self._add(month, e)
|
|
|
|
def _load_all(self) -> None:
|
|
if self._all:
|
|
return
|
|
self._all = True
|
|
try:
|
|
months = sorted(p.stem for p in self.root.glob("*.jsonl"))
|
|
except OSError:
|
|
months = []
|
|
for m in months:
|
|
self._load(m)
|
|
|
|
def _add(self, month: str, e: dict) -> None:
|
|
usd = float(e.get("usd") or 0)
|
|
tool = str(e.get("tool") or "")
|
|
units = e.get("units") if isinstance(e.get("units"), dict) else {}
|
|
for kind, key in (("who", e.get("who")), ("worker", e.get("worker"))):
|
|
if not key:
|
|
continue
|
|
s = self._sums.setdefault((month, kind, str(key)), _zero())
|
|
s["usd"] += usd
|
|
s["calls"] += 1
|
|
t = s["byTool"].setdefault(tool, {"usd": 0.0, "calls": 0, "units": {}})
|
|
t["usd"] += usd
|
|
t["calls"] += 1
|
|
for u, n in units.items():
|
|
if isinstance(n, (int, float)) and not isinstance(n, bool):
|
|
t["units"][u] = t["units"].get(u, 0) + n
|
|
sid = e.get("session")
|
|
if sid:
|
|
s = self._sessions.setdefault(str(sid), {"usd": 0.0, "calls": 0, "tools": {}})
|
|
s["usd"] += usd
|
|
s["calls"] += 1
|
|
s["tools"][tool] = s["tools"].get(tool, 0) + 1
|
|
|
|
# ── writing ──────────────────────────────────────────────────────────────
|
|
def record(self, entry: dict) -> None:
|
|
entry = {"t": time.time(), **entry}
|
|
month = month_of(entry["t"])
|
|
line = json.dumps(entry, separators=(",", ":"))
|
|
with self._lock:
|
|
self._load(month)
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
with open(self.root / f"{month}.jsonl", "a", encoding="utf-8") as f:
|
|
f.write(line + "\n")
|
|
self._add(month, entry)
|
|
|
|
# ── reading ──────────────────────────────────────────────────────────────
|
|
def spent(self, who: str, month: str | None = None) -> float:
|
|
month = month or month_of()
|
|
with self._lock:
|
|
self._load(month)
|
|
s = self._sums.get((month, "who", who))
|
|
return float(s["usd"]) if s else 0.0
|
|
|
|
def tool_spent(self, tool: str, month: str | None = None) -> float:
|
|
"""Everyone's USD on one tool in a month (the API key's spend)."""
|
|
month = month or month_of()
|
|
with self._lock:
|
|
self._load(month)
|
|
return float(sum(((s["byTool"].get(tool) or {}).get("usd") or 0.0)
|
|
for (m, kind, _k), s in self._sums.items()
|
|
if m == month and kind == "who"))
|
|
|
|
def summary(self, kind: str, key: str, month: str | None = None) -> dict:
|
|
"""``{month, usd, calls, byTool: {tool: {usd, calls, units}}}``."""
|
|
month = month or month_of()
|
|
with self._lock:
|
|
self._load(month)
|
|
s = self._sums.get((month, kind, key)) or _zero()
|
|
return {"month": month, "usd": round(s["usd"], 4), "calls": s["calls"],
|
|
"byTool": {k: {"usd": round(v["usd"], 4), "calls": v["calls"],
|
|
"units": dict(v["units"])}
|
|
for k, v in s["byTool"].items()}}
|
|
|
|
def rows(self, months: list[str], tool: str | None = None) -> list[dict]:
|
|
"""The raw rows of some months (oldest first), read from disk —
|
|
a plugin's Hub key section (plugins/keyspend.py): days, callers, recent calls."""
|
|
out: list[dict] = []
|
|
for month in sorted(set(months)):
|
|
try:
|
|
lines = (self.root / f"{month}.jsonl").read_text(encoding="utf-8").splitlines()
|
|
except OSError:
|
|
continue
|
|
for line in lines:
|
|
try:
|
|
e = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(e, dict) and (tool is None or e.get("tool") == tool):
|
|
out.append(e)
|
|
out.sort(key=lambda e: float(e.get("t") or 0))
|
|
return out
|
|
|
|
def session(self, sid: str) -> dict | None:
|
|
"""``{usd, calls, tools: {tool: calls}}`` of one conversation, any month."""
|
|
with self._lock:
|
|
self._load_all()
|
|
s = self._sessions.get(sid)
|
|
return {"usd": round(s["usd"], 6), "calls": s["calls"], "tools": dict(s["tools"])} \
|
|
if s else None
|
|
|
|
def sessions(self) -> dict[str, dict]:
|
|
with self._lock:
|
|
self._load_all()
|
|
return {k: {"usd": round(v["usd"], 6), "calls": v["calls"], "tools": dict(v["tools"])}
|
|
for k, v in self._sessions.items()}
|
|
|
|
|
|
LEDGER = ToolLedger()
|