Files
ai-agent/backend/test_tool_proxy.py
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

209 lines
11 KiB
Python

"""The tool proxy door (toolproxy/) after the tools left for their plugins
(2026-11-26): who a bearer is (a guest's run token, a worker's proxy token),
``whoami``, the tool ledger, a guest's run scope carrying their live plugins'
skills and the hub's tool-proxy token, and the workers' lab sync — a plugin
skill wins over a lab skill of the same name, and carries its ``hub.json``.
``python -m pytest test_tool_proxy.py`` from ``backend/``."""
import base64
import json
import os
import pathlib
import tempfile
import unittest
from unittest import mock
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects", "PROXY_LEDGER_DIR": TMP / "ledger",
"WORKER_ENROLL_PATH": TMP / "enroll.json",
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
"TOOLS_TOKEN_KEY": TMP / "tools.key",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"GUEST_PUBLIC_URL": "https://claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": "",
"PLUGINS_DIR": TMP / "plugins"}.items():
os.environ[k] = str(v)
(TMP / "projects" / "film").mkdir(parents=True)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from toolproxy import access # noqa: E402
from toolproxy.ledger import LEDGER, ToolLedger # noqa: E402
from users.caller import guest_from_record # noqa: E402
from users.runs import TOOLS_LINE, scope_for, scratch_scope, tool_scope # noqa: E402
from workers import labsync # noqa: E402
DEPS = main.app.state.ai
REPO = pathlib.Path(__file__).resolve().parent.parent
SID = "0190e0a1-0000-7000-8000-000000000001"
def _skill_dir(name: str) -> pathlib.Path:
d = TMP / "skills" / name
d.mkdir(parents=True, exist_ok=True)
(d / "SKILL.md").write_text(f"---\nname: {name}\ndescription: the {name} skill\n---\n")
return d
class ToolProxyTest(unittest.TestCase):
def setUp(self):
try:
u = DEPS.users.create("ana@example.test", "Ana")
except ValueError:
u = DEPS.users.by_email("ana@example.test")
DEPS.users.update(u["id"], {"projects": {"film": "chat"}})
self.uid = u["id"]
self.client = TestClient(main.app)
# Ana's live plugins: Movies (granted) and Nano Banana (granted).
self.live = [{"id": "movies", "name": "movies", "ref": f"plugin:{self.uid}/movies",
"dir": _skill_dir("movies"), "hasProxy": True},
{"id": "nanobanana", "name": "nanobanana",
"ref": f"plugin:{self.uid}/nanobanana",
"dir": _skill_dir("nanobanana"), "hasProxy": True}]
p = mock.patch.object(DEPS.plugin_store, "live_skill_dirs",
side_effect=lambda uid: self.live if uid == self.uid else [])
p.start()
self.addCleanup(p.stop)
def h(self, uid=None):
return {"Authorization": f"Bearer {access.mint(uid or self.uid)}"}
# ── tokens ───────────────────────────────────────────────────────────────
def test_run_token_names_the_guest_until_it_expires(self):
tok = access.mint("ana")
self.assertEqual(access.verify(tok), "ana")
self.assertIsNone(access.verify(tok[:-2] + "xx"))
self.assertIsNone(access.verify(tok.replace(".ana.", ".bob.")))
self.assertIsNone(access.verify(access.mint("ana", ttl=-5)))
self.assertIsNone(access.verify("nope"))
def test_the_internal_token_is_the_owner_on_the_lab_only(self):
who = access.resolve(DEPS, "tok", guest_surface=False)
self.assertTrue(who.is_owner)
self.assertEqual(who.via, "lab")
self.assertIsNone(access.resolve(DEPS, "tok", guest_surface=True))
def test_an_unknown_token_is_refused(self):
r = self.client.get("/proxy/tools/whoami", headers={"Authorization": "Bearer junk"})
self.assertEqual(r.status_code, 401)
def test_whoami_names_the_caller_and_their_plugins(self):
r = self.client.get("/proxy/tools/whoami", headers=self.h())
self.assertEqual(r.status_code, 200, r.text)
d = r.json()
self.assertEqual((d["who"], d["name"], d["via"]), (self.uid, "Ana", "run"))
self.assertEqual(d["plugins"], ["movies", "nanobanana"])
self.assertIn("spentUsd", d)
def test_the_retired_brokers_are_gone(self):
for path in ("nanobanana/gemini-2.5-flash-image", "matomo/sites", "meta/status",
"movies/search", "movies/webhook", "video-extract/run", "3d-render"):
r = self.client.post(f"/proxy/tools/{path}", headers=self.h(), json={})
self.assertIn(r.status_code, (404, 405), path) # no route (the SPA catch-all is GET)
self.assertFalse((REPO / "cli" / "skills" / "movies").exists())
# ── a guest's run ────────────────────────────────────────────────────────
def test_the_run_scope_carries_their_plugins_and_the_tools_token(self):
caller = guest_from_record(DEPS.users.get(self.uid))
scope = scope_for(caller, "film", "chat", ["screenshot"], deps=DEPS)
self.assertEqual(scope["tools"]["url"], "https://claude.example.test/proxy/tools")
self.assertEqual(access.verify(scope["tools"]["token"]), self.uid)
sk = scope["skills"]
self.assertLess(sk.index(f"plugin:{self.uid}/movies"), sk.index("screenshot"))
self.assertIn("Tools the hub shares with them: `shared:movies`, `shared:nanobanana`",
scope["systemPrompt"])
self.assertNotIn("Paid tools switched on", scope["systemPrompt"])
self.assertTrue(TOOLS_LINE.startswith("- Tools the hub shares"))
def test_a_scratch_run_gets_them_too(self):
caller = guest_from_record(DEPS.users.get(self.uid))
scope = scratch_scope(caller, [], None, bash=True, deps=DEPS)
self.assertIn(f"plugin:{self.uid}/nanobanana", scope["skills"])
self.assertIn("tools", scope)
self.assertNotIn("tools", scratch_scope(caller, [], None, bash=False, deps=DEPS))
def test_no_plugin_no_tools(self):
self.live = []
caller = guest_from_record(DEPS.users.get(self.uid))
self.assertIsNone(tool_scope(caller, DEPS))
self.assertIsNone(tool_scope(caller))
self.assertNotIn("tools", scope_for(caller, "film", "chat", [], deps=DEPS))
# ── the workers' lab sync ────────────────────────────────────────────────
def _sync(self, w, lab=("movies", "screenshot")):
"""``for_worker`` with a lab catalog of ``lab`` skills, and Ana's /
the owner's plugins as the live ones."""
items = [{"key": f"skill:{n}", "kind": "skill", "name": n, "portable": True,
"path": _skill_dir(f"lab-{n}"), "description": ""} for n in lab]
owner_live = [{"id": "movies", "name": "movies", "dir": _skill_dir("movies"),
"hasProxy": True}]
patches = [mock.patch.object(labsync, "catalog", lambda source=None: items),
mock.patch.object(labsync, "guest_skills", lambda: list(lab)),
mock.patch.object(labsync, "user_plugins",
lambda uid: self.live if uid == self.uid
else owner_live if uid == "owner" else []),
mock.patch.object(labsync, "plugin_bundles", lambda **kw: {}),
mock.patch.object(labsync, "hooks_bundle", lambda w: {}),
mock.patch.object(labsync, "with_plugins", lambda b, p: b)]
for p in patches:
p.start()
try:
return labsync.for_worker(w)
finally:
for p in patches:
p.stop()
def test_a_guest_computer_gets_their_plugin_skills_with_its_token(self):
DEPS.worker_store.put({"id": "gpc", "name": "pc", "url": "http://x", "token": "t",
"owner": self.uid, "proxyToken": "p" * 43})
try:
b = self._sync(DEPS.worker_store.get("gpc"))
self.assertEqual(sorted(b["skills"]), ["movies", "nanobanana", "screenshot"])
# The plugin's movies, not the lab's shim of the same name.
self.assertIn("the movies skill", base64.b64decode(
b["skills"]["movies"]["SKILL.md"]).decode())
hub = json.loads(base64.b64decode(b["skills"]["nanobanana"]["hub.json"]))
self.assertEqual(hub, {"url": "https://claude.example.test/proxy/tools",
"token": "p" * 43})
self.assertNotIn("hub.json", b["skills"]["screenshot"])
DEPS.worker_store.patch("gpc", {"proxyToken": "q" * 43})
self.assertNotEqual(self._sync(DEPS.worker_store.get("gpc"))["hash"], b["hash"])
finally:
DEPS.worker_store.delete("gpc")
def test_an_owner_worker_gets_the_plugin_edition_over_the_lab_shim(self):
b = self._sync({"id": "mac"})
self.assertEqual(sorted(b["skills"]), ["movies", "screenshot"])
self.assertIn("the movies skill", base64.b64decode(
b["skills"]["movies"]["SKILL.md"]).decode())
class LedgerTest(unittest.TestCase):
def test_sums_per_caller_tool_and_session(self):
led = ToolLedger(TMP / "ledger-unit")
led.record({"tool": "nanobanana", "who": "ana", "guest": "ana", "usd": 0.04,
"units": {"images": 1}, "session": SID})
led.record({"tool": "3d-gen", "who": "ana", "guest": "ana", "usd": 0,
"units": {"jobs": 1}, "session": SID})
self.assertAlmostEqual(led.spent("ana"), 0.04)
again = ToolLedger(TMP / "ledger-unit") # rebuilt from the file
s = again.summary("who", "ana")
self.assertEqual((s["calls"], s["byTool"]["3d-gen"]["units"]["jobs"]), (2, 1))
self.assertEqual(again.session(SID)["tools"], {"nanobanana": 1, "3d-gen": 1})
self.assertIsNotNone(LEDGER)
if __name__ == "__main__":
unittest.main()