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

204 lines
8.3 KiB
Python

"""
Who is calling: the :class:`Caller` every ``/api`` request carries in
``request.state.caller`` (``core/auth.py`` resolves it), and what a guest may
reach.
Two kinds of people:
* the **owner** — whoever reaches the admin host (Authelia at Traefik), the
trusted loopback / docker gateway, or presents ``INTERNAL_API_TOKEN``. This is
every caller the app had before guests existed, and it keeps full access.
* a **guest** — a user from ``users.json`` holding a session cookie (the
built-in login). They reach the routes their permissions allow (their
role's, plus their overrides — authz/; default deny), and within them only
the conversations they own or were shared and the projects they were
granted.
The **guest surface** (``GUEST_HOSTS``, e.g. ``ai-agent.gabvdl.xyz``) is a
host on which nothing is ever owner: a request without a session there is
anonymous and may only log in.
"""
from __future__ import annotations
import dataclasses
import os
import typing
from fastapi import Depends, HTTPException, Request
from core.i18n import effective_lang, primary_lang, tr
from users.store import LEVELS
OWNER_ID = "owner"
OWNER_NAME = os.environ.get("OWNER_NAME", "Gabriel")
SESSION_COOKIE = "aia_session"
GUEST_HOSTS = frozenset(h.strip().lower() for h in
os.environ.get("GUEST_HOSTS", "").split(",") if h.strip())
# The owner's internet address (remoteaccess/, docs/remote-access.md): the
# whole app as the owner, no Authelia in front — the owner's own short
# session (a passkey sign-in) is the only way to be anyone there.
OWNER_HOSTS = frozenset(h.strip().lower() for h in
os.environ.get("OWNER_HOSTS", "").split(",") if h.strip()) - GUEST_HOSTS
@dataclasses.dataclass(frozen=True)
class Caller:
id: str
role: str # "owner" | "guest"
name: str
email: str | None = None
readonly: bool = False
projects: dict = dataclasses.field(default_factory=dict) # slug → level
models: tuple = ()
budget_usd: float | None = None
# Set when the owner is looking through this guest's eyes (Settings →
# Users → Impersonate): who is really at the keyboard.
impersonator: str | None = None
# The language the app speaks to them (core/i18n.py): their ``lang``
# unless auto, else their browser's. The owner is always English.
lang: str = "en"
# Set when the call is the ``ai-agent`` CLI run for one of this guest's
# sessions by the guard's broker (users/cli.py): that session's id — the
# parent of any conversation the call starts.
via_session: str | None = None
# Set when the call is an MCP connection bound to one of the owner's
# workers (workers/bound.py), or that worker's `ai-agent past`: the
# worker's id. The owner, narrowed — ``profile`` is then the only profile
# whose conversations it sees (users/access.py), and it runs on that
# worker only; ``worker_mode`` is ``read`` | ``run``.
via_worker: str | None = None
profile: str | None = None
worker_mode: str | None = None
# What they may do (authz/): their role's permissions plus their
# overrides — the owner holds them all. ``read_perms`` are the ones a
# credential scope left them for safe methods only; ``scope`` names it.
# None ⇒ derived from ``role`` (every permission for the owner, the guest
# role's for a guest) — what a Caller built by hand gets.
perms: frozenset | None = None
read_perms: frozenset = frozenset()
scope: str | None = None
role_id: str | None = None
def __post_init__(self):
if self.perms is None:
from authz import catalog, roles
object.__setattr__(self, "perms", catalog.ALL if self.role == "owner"
else roles.store().perms(roles.DEFAULT_ROLE))
@property
def is_owner(self) -> bool:
return self.role == "owner"
def has(self, perm: str) -> bool:
"""Do they hold ``perm`` (any method)?"""
return perm in self.perms
def allows(self, perm: str | None, method: str) -> bool:
"""May they call a route that needs ``perm`` with ``method``? A route
no table entry covers (``None``) needs every permission."""
from authz.routes import PUBLIC
from authz.scopes import SAFE_METHODS
if perm == PUBLIC:
# signing in: anyone at a browser — not a credential acting for someone
return self.scope is None
if perm is None:
from authz.catalog import ALL
return self.perms >= ALL
return perm in self.perms or (method in SAFE_METHODS and perm in self.read_perms)
@property
def cli(self) -> bool:
"""Their runs may use the ``ai-agent`` CLI."""
return "cli.use" in self.perms
@property
def mcp(self) -> bool:
"""They may connect AI apps to the hub's MCP server."""
return "mcp.connect" in self.perms
def narrowed(self, scope_name: str) -> "Caller":
"""This caller through a credential scope (authz/scopes.py): fewer
route permissions, never more."""
from authz.scopes import SCOPES, narrow
full, read = narrow(self.perms, SCOPES[scope_name])
return dataclasses.replace(self, perms=full, read_perms=read, scope=scope_name)
def level(self, slug: str | None) -> str | None:
if self.is_owner:
return "ship"
return self.projects.get(slug or "")
def can(self, slug: str | None, need: str = "view") -> bool:
lvl = self.level(slug)
return lvl is not None and LEVELS.index(lvl) >= LEVELS.index(need)
OWNER = Caller(id=OWNER_ID, role="owner", name=OWNER_NAME)
OWNER_READONLY = dataclasses.replace(OWNER, readonly=True)
def guest_from_record(u: dict, accept_language: str | None = None) -> Caller:
"""The guest a record is; ``accept_language`` (the request's header)
settles an ``auto`` language no browser language was recorded for yet."""
from authz import policy
return Caller(id=u["id"], role="guest", name=u.get("name") or u["id"],
email=u.get("email"), projects=dict(u.get("projects") or {}),
models=tuple(u.get("models") or ()),
budget_usd=u.get("budgetUsd"),
perms=policy.effective(u), role_id=policy.role_of(u),
lang=effective_lang(u, accept_language))
def request_lang(request: Request) -> str:
"""The language to answer a request in: the caller's, else (nobody
signed in — the login page) the browser's, else English."""
c = getattr(request.state, "caller", None)
if c is not None:
return c.lang
return primary_lang(request.headers.get("accept-language")) or "en"
def request_host(request: Request) -> str:
"""The Host header's name, lower-cased, without port or trailing dots —
``ai-agent.gabvdl.xyz.`` is the same host to DNS and to Traefik's
``Host()`` rule, so it must be to GUEST_HOSTS too."""
return (request.headers.get("host") or "").split(":")[0].strip().rstrip(".").lower()
def on_guest_surface(request: Request) -> bool:
return bool(GUEST_HOSTS) and request_host(request) in GUEST_HOSTS
def on_owner_surface(request: Request) -> bool:
"""The owner's internet address (``OWNER_HOSTS``)."""
return bool(OWNER_HOSTS) and request_host(request) in OWNER_HOSTS
def on_public_surface(request: Request) -> bool:
"""A host the internet reaches (the guest surface or the owner's internet
address): what serves machines over the tailnet only is refused there."""
return on_guest_surface(request) or on_owner_surface(request)
# ── route dependencies ───────────────────────────────────────────────────────
def get_caller(request: Request) -> Caller:
c = getattr(request.state, "caller", None)
if c is None:
raise HTTPException(401, {"message": tr(request_lang(request), "login required"),
"kind": "login_required"})
return c
CallerDep = typing.Annotated[Caller, Depends(get_caller)]
def require_owner(request: Request) -> Caller:
c = get_caller(request)
if not c.is_owner:
raise HTTPException(403, "owner only")
return c
OwnerDep = typing.Annotated[Caller, Depends(require_owner)]