Files
gabrielvidalandClaude Opus 5.5 4d0dcfa3ff refactor(toolproxy): the tools are plugins — retire the core brokers, the guests' tool groups and the hub editions
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 on 41665fa2,
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>
2026-11-27 11:44:24 +01:00

490 lines
22 KiB
Python

"""The retired core tool proxy's switches and data → the tool plugins, once.
Until 2026-11-26 the hub had two ways to a guest's paid tools: the core's
per-tool brokers (``toolproxy/meta.py``, ``matomo.py``, ``media.py``, the Nano
Banana / 3d-gen / 3d-render / video-extract routes) behind per-guest **tool
groups** (``users.json`` ``tools: {groups, pro, budgetUsd}``), and the live
plugins that replaced them (``nanobanana``, ``video-extract``, ``video-dl``,
``3d-gen``, ``3d-render``, ``matomo``, ``movies``, ``meta``). The brokers left;
this carries what they held over to the plugins (Gabriel's picks, form
``ai-agent-moves-to-ai-agent-plugins_o2qxmd``: carry the switches over to
grants, carry the guests' Meta keys over):
* **Tool groups → grants** (:func:`tool_grants`). For every guest, each group
maps onto its plugins — ``images`` → nanobanana (``allowPro`` = their Pro
switch, the grant's monthly budget = their tools budget), ``video`` →
video-extract + video-dl, ``3d`` → 3d-gen + 3d-render, ``analytics`` →
matomo, ``media`` → movies, ``meta`` → meta. A **managed** plugin gets a
grant: on when the group was, explicitly off when it wasn't and the plugin is
on for guests by default (Movies — so a guest the owner had switched Movies
off for stays off). A plain plugin (video-dl, meta) is installed for the
guest from the owner's own install (else the hub catalog). A guest with no
``tools`` had the core default, Movies on. **An explicit grant is never
overridden**, and a plugin the owner hasn't installed yet waits: the next
start (or its install, ``plugins/routes._plugin_changed``) carries it over.
* **Matomo sites** (:func:`matomo_sites`): ``tools.matomoSites`` (the site
ids the owner granted a guest beyond the ones on their address — Cel's
``[11]``, calamite.net) → their matomo grant's ``extraSites`` (the plugin's
``list`` grantField), and the grant on for a guest with ``analytics`` — per
guest rather than per plugin, so a guest switched to analytics after the
groups above were carried over still gets it. An explicit grant is never
overridden: it only gets ``extraSites`` when it has none. A plugin without
the field yet (an older matomo) waits for its update.
* **Meta connections** (:func:`meta_connections`): ``/data/tools-meta.json``
(``{uid: {token, user, scopes, adAccounts, pages, instagram, connectedAt,
checkedAt, error, snapshot, …}}``) → the guest's meta plugin: the key as its
``token`` user secret, the rest (no key, no Page tokens) as
``connection.json`` and ``snapshot.json`` in their data dir, and every saved
day of ``/data/meta-snapshots/<uid>/`` (the same ``YYYY-MM-DD.json`` the
plugin writes) where the plugin has none of its own.
* **Matomo viewers** (:func:`matomo_viewers`): ``/data/tools-matomo.json``
(``{uid: {login, password, token}}``) → ``_private/viewer.json`` (0600) in
that guest's matomo data dir — their view-only key keeps working.
* **Seerr users and requests** (:func:`movies_users`): ``/data/tools-media.json``
(``{users: {uid: seerrId}, requests: {rid: {uid, session, type, tmdb, …}}}``)
→ each person's movies ``state.json`` (``seerrUser``, ``requests``) and, for
the titles not told yet, the plugin's shared ``requests.json`` index — so
Seerr's webhook (now aimed at the plugin) still pushes them.
* **3d-gen ownership** (:func:`threed_owned`): ``/data/tools-owned.json``
(``{jobs: {id: {uid, t}}, folders: {name: {uid, t}}}``) → each guest's
3d-gen ``_private/owned.json`` — their models stay theirs.
Each part writes a ``.carried-over-tools`` marker in its plugin's hub-scoped
dir once done; a legacy file is renamed ``….migrated`` once every entry in it
made it (a Meta key waits for its guest's install).
"""
from __future__ import annotations
import json
import logging
import os
import pathlib
import re
import shutil
import time
from plugins.store import OWNER_UID, PluginStore
log = logging.getLogger(__name__)
TOOLS_META_PATH = os.environ.get("TOOLS_META_PATH", "/data/tools-meta.json")
META_SNAPSHOT_DIR = os.environ.get("META_SNAPSHOT_DIR", "/data/meta-snapshots")
TOOLS_MATOMO_PATH = os.environ.get("TOOLS_MATOMO_PATH", "/data/tools-matomo.json")
TOOLS_MEDIA_PATH = os.environ.get("TOOLS_MEDIA_PATH", "/data/tools-media.json")
TOOLS_OWNED_PATH = os.environ.get("TOOLS_OWNED_PATH", "/data/tools-owned.json")
# The core's groups (users/store.TOOL_GROUPS until 2026-11-26) and the plugins
# that took each over.
GROUP_PLUGINS: dict[str, tuple[str, ...]] = {
"images": ("nanobanana",),
"video": ("video-extract", "video-dl"),
"3d": ("3d-gen", "3d-render"),
"analytics": ("matomo",),
"media": ("movies",),
"meta": ("meta",),
}
TOOL_PLUGINS = frozenset(p for ps in GROUP_PLUGINS.values() for p in ps)
# A guest with no ``tools`` (or no ``groups`` in it) had these on.
DEFAULT_GROUPS = ("media",)
DEFAULT_BUDGET_USD = 10.0
MARKER = ".carried-over-tools"
_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
_DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}\.json$")
_JOB_RE = re.compile(r"^[0-9a-f]{12}$")
_FOLDER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$")
# ── helpers ──────────────────────────────────────────────────────────────────
def _read_json(path: pathlib.Path) -> dict:
try:
v = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return v if isinstance(v, dict) else {}
def _write_json(path: pathlib.Path, data, *, private: bool = False) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f".{path.name}.carry.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 if private else 0o644)
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, separators=(",", ":"))
os.chmod(tmp, 0o600 if private else 0o644)
os.replace(tmp, path)
def _owner_rec(store: PluginStore, pid: str) -> dict | None:
try:
rec = store.get_raw(OWNER_UID, pid)
except Exception: # noqa: BLE001
return None
return rec if rec and rec.get("enabled") and not rec.get("needsApproval") else None
def _marker(store: PluginStore, pid: str) -> pathlib.Path:
return store.shared_data_dir(pid) / MARKER
def _done(store: PluginStore, pid: str) -> bool:
return _marker(store, pid).exists()
def _mark(store: PluginStore, pid: str) -> None:
_marker(store, pid).write_text(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
def _retire(path: pathlib.Path) -> None:
try:
if path.is_file():
path.rename(path.with_name(path.name + ".migrated"))
except OSError as e:
log.warning("tool carry-over: renaming %s: %s", path, e)
def legacy_tools(u: dict) -> dict:
"""A guest's old ``tools`` as the core read it (``users/store.clean_tools``):
``{groups, pro, budgetUsd}``, Movies on when they had none."""
raw = u.get("tools") if isinstance(u.get("tools"), dict) else {}
groups = raw.get("groups") if isinstance(raw.get("groups"), (list, tuple)) else DEFAULT_GROUPS
try:
budget = min(10000.0, max(0.0, float(raw.get("budgetUsd"))))
except (TypeError, ValueError):
budget = DEFAULT_BUDGET_USD
return {"groups": [g for g in GROUP_PLUGINS if g in groups], "pro": bool(raw.get("pro")),
"budgetUsd": budget, "matomoSites": matomo_site_ids(raw.get("matomoSites"))}
def matomo_site_ids(raw) -> list[int]:
"""``tools.matomoSites`` as ``users/store.clean_matomo_sites`` kept it:
positive ints, deduplicated, in order (a string of ids too)."""
out: list[int] = []
items = raw.replace(",", " ").split() if isinstance(raw, str) else raw
for v in items if isinstance(items, (list, tuple)) else []:
try:
n = int(str(v).strip())
except (TypeError, ValueError):
continue
if 0 < n < 10**9 and n not in out:
out.append(n)
return out[:50]
def _installed_for(store: PluginStore, uid: str, pid: str) -> bool:
try:
return bool(store.get_raw(uid, pid))
except Exception: # noqa: BLE001
return False
def _in_catalog(store: PluginStore, pid: str) -> bool:
try:
return any(c.get("id") == pid for c in store.catalog(is_owner=True))
except Exception: # noqa: BLE001
return False
def _install_for(store: PluginStore, uid: str, pid: str) -> bool:
"""Install plain plugin ``pid`` for guest ``uid``: from the owner's own
install's source, else the hub catalog. True when it is (now) theirs."""
if _installed_for(store, uid, pid):
return True
rec = _owner_rec(store, pid)
try:
if rec and rec.get("sourceRaw"):
store.install(uid, rec["sourceRaw"], is_owner=True)
else:
store.install(uid, "", is_owner=False, catalog_id=pid)
except Exception as e: # noqa: BLE001 — not installable yet: the next start tries again
log.info("tool carry-over: %s for %s waits (%s)", pid, uid, e)
return False
log.info("tool carry-over: installed %s for %s", pid, uid)
return True
# ── tool groups → grants / installs ─────────────────────────────────────────
def tool_grants(store: PluginStore, users) -> list[str]:
"""Each guest's old tool groups → their grants (managed plugins) or
installs (plain ones), per plugin once; the plugin ids carried over."""
if users is None:
return []
guests = [u for u in users.all() if _UID_RE.match(str(u.get("id") or ""))]
out = []
for pid in sorted(TOOL_PLUGINS):
if _done(store, pid):
continue
rec = _owner_rec(store, pid)
managed = bool(rec and (rec.get("manifest") or {}).get("managed"))
if not rec and not _in_catalog(store, pid):
continue # not on this hub yet: wait for its install
groups_of = [g for g, ps in GROUP_PLUGINS.items() if pid in ps]
ok = True
for u in guests:
uid = u["id"]
t = legacy_tools(u)
on = any(g in t["groups"] for g in groups_of)
try:
if managed:
mf = rec["manifest"]
if not store.effective_grant(uid, pid, mf).get("isDefault"):
continue # the owner already decided for this guest
default_on = bool((mf.get("managed") or {}).get("defaultForGuests"))
if on and pid == "nanobanana":
store.set_grant(uid, pid, enabled=True, config={"allowPro": t["pro"]},
monthly_budget_usd=t["budgetUsd"])
elif on != default_on:
store.set_grant(uid, pid, enabled=on)
else:
continue # the plugin's default already says the same
log.info("tool carry-over: %s grant for %s → %s", pid, uid, on)
elif on:
ok = _install_for(store, uid, pid) and ok
except Exception as e: # noqa: BLE001
ok = False
log.warning("tool carry-over: %s for %s: %s", pid, uid, e)
if ok:
_mark(store, pid)
out.append(pid)
return out
# ── Matomo: the analytics switch and the extra sites, per guest ─────────────
MATOMO_EXTRA = "extraSites"
def matomo_sites(store: PluginStore, users) -> list[str]:
"""Each guest's ``analytics`` group and ``tools.matomoSites`` → their
matomo grant (on, ``extraSites``), once per guest; the guests carried over
this time. Never over an explicit grant, except ``extraSites`` where it
has none; a guest whose sites the plugin can't hold yet (no ``extraSites``
grantField) waits."""
if users is None:
return []
rec = _owner_rec(store, "matomo")
mf = (rec or {}).get("manifest") or {}
if not mf.get("managed"):
return []
has_field = any(f.get("key") == MATOMO_EXTRA
for f in (mf["managed"].get("grantFields") or []))
shared = store.shared_data_dir("matomo")
done = _read_json(shared / ".carried-over-sites.json")
out = []
for u in users.all():
uid = str(u.get("id") or "")
if not _UID_RE.match(uid) or uid in done:
continue
t = legacy_tools(u)
on, sites = "analytics" in t["groups"], t["matomoSites"]
if not on and not sites:
continue
try:
g = store.effective_grant(uid, "matomo", mf)
waits = bool(sites) and not has_field
cfg = {MATOMO_EXTRA: sites} if sites and has_field else None
if g.get("isDefault"):
if not on:
continue # sites without the switch: nothing to open
if not g.get("enabled") or cfg:
store.set_grant(uid, "matomo", enabled=True, config=cfg)
elif cfg and not (g.get("config") or {}).get(MATOMO_EXTRA):
store.set_grant(uid, "matomo", config=cfg)
except Exception as e: # noqa: BLE001
log.warning("tool carry-over: matomo sites for %s: %s", uid, e)
continue
if waits:
log.info("tool carry-over: matomo sites of %s wait for the extraSites field", uid)
continue
done[uid] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
_write_json(shared / ".carried-over-sites.json", done)
log.info("tool carry-over: matomo for %s → on, extra sites %s", uid, sites)
out.append(uid)
return out
# ── Meta Business connections ───────────────────────────────────────────────
_META_PUBLIC = ("user", "scopes", "adAccounts", "pages", "instagram", "connectedAt",
"checkedAt", "error", "expiresAt")
def meta_connections(store: PluginStore, legacy: str = TOOLS_META_PATH,
snaps: str = META_SNAPSHOT_DIR) -> int:
"""The guests' Meta keys and saved days → their meta plugin; the number of
guests carried over this time."""
src = pathlib.Path(legacy)
if _done(store, "meta") and not src.is_file():
return 0
data = _read_json(src)
if not data:
return 0
shared = store.shared_data_dir("meta")
done = _read_json(shared / ".carried-over-keys.json")
n, waiting = 0, 0
for uid, rec in sorted(data.items()):
if not _UID_RE.match(str(uid)) or not isinstance(rec, dict) or not rec.get("token"):
continue
if uid in done:
continue
if not _install_for(store, uid, "meta"):
waiting += 1
continue
try:
if not store.get_secret(uid, "meta", "token", scope="user"):
store.set_secret(uid, "meta", "token", str(rec["token"]), scope="user")
d = store.user_data_dir(uid, "meta")
conn = {k: rec[k] for k in _META_PUBLIC if rec.get(k) is not None}
if conn and not (d / "connection.json").exists():
_write_json(d / "connection.json", conn)
if isinstance(rec.get("snapshot"), dict) and not (d / "snapshot.json").exists():
_write_json(d / "snapshot.json", rec["snapshot"])
days = pathlib.Path(snaps) / uid
if days.is_dir():
for f in sorted(days.iterdir()):
if _DAY_RE.match(f.name) and not (d / f.name).exists():
shutil.copy2(f, d / f.name)
os.chmod(d / f.name, 0o644)
except Exception as e: # noqa: BLE001
waiting += 1
log.warning("tool carry-over: meta for %s: %s", uid, e)
continue
done[uid] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
_write_json(shared / ".carried-over-keys.json", done, private=True)
log.info("tool carry-over: Meta connection of %s → the meta plugin", uid)
n += 1
if not waiting:
_retire(src)
return n
# ── Matomo view-only users ───────────────────────────────────────────────────
def matomo_viewers(store: PluginStore, legacy: str = TOOLS_MATOMO_PATH) -> int:
src = pathlib.Path(legacy)
if not src.is_file() or not _owner_rec(store, "matomo"):
return 0
n = 0
for uid, rec in sorted(_read_json(src).items()):
if not _UID_RE.match(str(uid)) or not isinstance(rec, dict) or not rec:
continue
dst = store.user_data_dir(uid, "matomo") / "_private" / "viewer.json"
if dst.exists():
continue
_write_json(dst, rec, private=True)
n += 1
log.info("tool carry-over: %d Matomo viewer(s) → the matomo plugin", n)
_retire(src)
return n
# ── Seerr users and requests ─────────────────────────────────────────────────
def movies_users(store: PluginStore, legacy: str = TOOLS_MEDIA_PATH) -> int:
"""Each person's Seerr id and requests → their movies ``state.json``; the
requests not told yet → the shared ``requests.json`` index too."""
src = pathlib.Path(legacy)
if not src.is_file() or not _owner_rec(store, "movies"):
return 0
data = _read_json(src)
users = data.get("users") if isinstance(data.get("users"), dict) else {}
reqs = data.get("requests") if isinstance(data.get("requests"), dict) else {}
by_uid: dict[str, dict] = {}
for rid, r in reqs.items():
if not isinstance(r, dict):
continue
uid = r.get("uid") or OWNER_UID
if uid != OWNER_UID and not _UID_RE.match(str(uid)):
continue
by_uid.setdefault(uid, {})[str(rid)] = r
n = 0
for uid in sorted(set(users) | set(by_uid)):
if uid != OWNER_UID and not _UID_RE.match(str(uid)):
continue
path = store.user_data_dir(uid, "movies") / "state.json"
st = _read_json(path)
if users.get(uid) and not st.get("seerrUser"):
try:
st["seerrUser"] = int(users[uid])
except (TypeError, ValueError):
pass
mine = st.setdefault("requests", {})
for rid, r in (by_uid.get(uid) or {}).items():
mine.setdefault(rid, r)
# The index below gets this person's pending titles now — the plugin
# mustn't copy them again on their next op (lib.migrate).
st["indexed"] = st.get("indexed") or int(time.time())
_write_json(path, st)
n += 1
index_path = store.shared_data_dir("movies") / "requests.json"
index = _read_json(index_path)
titles = index.setdefault("titles", {})
for rid, r in reqs.items():
if not isinstance(r, dict) or r.get("told") or r.get("type") not in ("movie", "tv"):
continue
try:
tmdb = int(r.get("tmdb") or 0)
except (TypeError, ValueError):
continue
if not tmdb:
continue
who = r.get("uid") or OWNER_UID
e = titles.setdefault(f"{r['type']}:{tmdb}", {}).setdefault(who, {
"uid": r.get("uid"), "type": r["type"], "tmdb": tmdb, "requests": [],
"at": r.get("at") or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
e.setdefault("label", r.get("label") or r.get("title") or "")
e.setdefault("lang", r.get("lang") or "en")
for k in ("session", "seasons", "watchUntil", "held", "heldUrl"):
if r.get(k) is not None:
e.setdefault(k, r[k])
if str(rid).isdigit() and int(rid) not in e["requests"]:
e["requests"].append(int(rid))
if r.get("watchOnly") and not e["requests"]:
e["watchOnly"] = True
_write_json(index_path, index)
log.info("tool carry-over: %d Seerr user(s) and their requests → the movies plugin", n)
_retire(src)
return n
# ── 3d-gen jobs and folders ──────────────────────────────────────────────────
def threed_owned(store: PluginStore, legacy: str = TOOLS_OWNED_PATH) -> int:
src = pathlib.Path(legacy)
if not src.is_file() or not _owner_rec(store, "3d-gen"):
return 0
data = _read_json(src)
per: dict[str, dict] = {}
for jid, v in (data.get("jobs") or {}).items():
if isinstance(v, dict) and _JOB_RE.match(str(jid)) and _UID_RE.match(str(v.get("uid") or "")):
per.setdefault(v["uid"], {"jobs": {}, "folders": {}})["jobs"][jid] = {
"t": v.get("t") or time.time()}
for name, v in (data.get("folders") or {}).items():
if isinstance(v, dict) and _FOLDER_RE.match(str(name)) and _UID_RE.match(str(v.get("uid") or "")):
per.setdefault(v["uid"], {"jobs": {}, "folders": {}})["folders"][name] = {
"t": v.get("t") or time.time()}
for uid, mine in per.items():
path = store.user_data_dir(uid, "3d-gen") / "_private" / "owned.json"
cur = _read_json(path)
jobs = cur.get("jobs") if isinstance(cur.get("jobs"), dict) else {}
folders = cur.get("folders") if isinstance(cur.get("folders"), dict) else {}
for k, v in mine["jobs"].items():
jobs.setdefault(k, v)
for k, v in mine["folders"].items():
folders.setdefault(k, v)
_write_json(path, {"jobs": jobs, "folders": folders})
log.info("tool carry-over: 3d-gen jobs of %d guest(s) → the 3d-gen plugin", len(per))
_retire(src)
return len(per)
def tools(store: PluginStore | None, users=None) -> None:
"""Every part above; each a no-op once done (or until its plugin is in)."""
if store is None:
return
for name, fn in (("grants", lambda: tool_grants(store, users)),
("matomo sites", lambda: matomo_sites(store, users)),
("meta", lambda: meta_connections(store)),
("matomo", lambda: matomo_viewers(store)),
("movies", lambda: movies_users(store)),
("3d-gen", lambda: threed_owned(store))):
try:
fn()
except Exception: # noqa: BLE001 — one part's failure never stops the others
log.exception("tool carry-over (%s) failed", name)