Files
ai-agent/backend/services/enrich.py
gabrielvidalandClaude Opus 5.5 ea29553d8b feat(services): the Services catalogue moves to the services live plugin
The core keeps the services index (names, README line, GOAL.md, last commit)
that service: tags, goals, artefacts and file chips need, and the service
page's shell (README, CLAUDE.md, commits, conversations, memories). Compose /
Traefik parsing, containers, URLs, auth chain, env keys and the file browser
(/api/service-file) leave services/catalog.py (667 → 186 lines) for the
services plugin in ai-agent-plugins.

Two plugin extension points make it work: provides.service.cards (the host
runs the plugin's action and merges whitelisted card fields into
/api/services and /api/service, services/enrich.py) and the services.read
capability (AIA_SERVICES_DIR for the owner's handler runs). ui.slots now
render (PluginSlots, service.detail with {slug}), and every plugin frame gets
the app's theme tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:41:37 +01:00

161 lines
5.4 KiB
Python

"""Card fields a plugin hands the services index (``provides: service.cards``).
The core's index (:mod:`services.catalog`) knows a service's name, README line,
goal and last commit. What its compose and Traefik files declare is the
``services`` plugin's: the host runs that plugin's ``cards`` action as the
owner — every owner install that is enabled, approved and declares
``provides.service.cards`` — and merges the whitelisted fields below into each
card by dir. Cached 30 s, stale-while-revalidate, so a request never waits on
a plugin subprocess after the first one; a failing plugin just leaves the
cards bare.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Any
log = logging.getLogger(__name__)
PROVIDES = "service.cards"
# What a plugin may set on a card (description / icon / group only fill an
# empty one: the README's line wins over the homepage's).
FIELDS = ("urls", "containers", "containerCount", "images", "profiles", "auth",
"hasCompose", "hasTraefik", "routerCount", "icon", "group")
_FILL = {"homepageDescription": "description"}
_LISTS = {"urls", "containers", "images", "profiles"}
TTL_SECS = 30.0
_lock = threading.Lock()
_cache: dict[str, tuple[float, dict[str, dict]]] = {}
_refreshing: set[str] = set()
def _providers(deps) -> list[dict[str, Any]]:
from plugins.store import OWNER_UID
store = getattr(deps, "plugin_store", None)
if store is None:
return []
out = []
try:
u_map = store._state["users"].get(OWNER_UID) or {} # noqa: SLF001 — read-only peek
pids = list(u_map)
except Exception:
return []
for pid in pids:
rec = store.get_raw(OWNER_UID, pid)
if not rec or not rec.get("enabled") or rec.get("needsApproval"):
continue
mf = rec.get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
if act and act in (mf.get("actions") or {}):
out.append(rec)
return out
def _key(rec: dict) -> str:
return f"{rec['id']}@{rec.get('fingerprint') or ''}:{rec.get('dir') or ''}"
def _clean(raw: Any) -> dict[str, dict]:
svc = raw.get("services") if isinstance(raw, dict) else None
if not isinstance(svc, dict):
return {}
out: dict[str, dict] = {}
for d, v in svc.items():
if not isinstance(d, str) or not isinstance(v, dict):
continue
rec: dict[str, Any] = {}
for k in FIELDS:
if k not in v or v[k] is None:
continue
val = v[k]
if k in _LISTS:
if not isinstance(val, list):
continue
val = [str(x) for x in val][:200]
elif k == "containerCount" or k == "routerCount":
if not isinstance(val, int):
continue
elif k in ("hasCompose", "hasTraefik"):
val = bool(val)
else:
val = str(val)[:500]
rec[k] = val
for src, dst in _FILL.items():
if isinstance(v.get(src), str) and v[src]:
rec["_fill_" + dst] = v[src][:500]
out[d] = rec
return out
def _run(deps, rec: dict) -> dict[str, dict]:
from plugins.runner import run_script
from plugins.store import OWNER_UID
mf = rec["manifest"]
act = mf["actions"][mf["provides"][PROVIDES]]
try:
raw = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
payload={"trigger": PROVIDES}, timeout_sec=int(act.get("timeoutSec") or 30))
except Exception as e: # a broken plugin leaves the cards bare
log.warning("services plugin %s: %s", rec.get("id"), e)
return {}
return _clean(raw)
def _refresh_bg(deps, rec: dict, key: str) -> None:
try:
data = _run(deps, rec)
with _lock:
_cache[key] = (time.monotonic(), data)
finally:
with _lock:
_refreshing.discard(key)
def _cards_of(deps, rec: dict) -> dict[str, dict]:
key = _key(rec)
now = time.monotonic()
with _lock:
hit = _cache.get(key)
if hit is not None:
if now - hit[0] >= TTL_SECS and key not in _refreshing:
_refreshing.add(key)
threading.Thread(target=_refresh_bg, args=(deps, rec, key), daemon=True,
name="services-cards-refresh").start()
return hit[1]
data = _run(deps, rec)
with _lock:
_cache[key] = (time.monotonic(), data)
return data
def card_fields(deps) -> dict[str, dict]:
"""dir → extra card fields, from every provider (first one wins a field)."""
merged: dict[str, dict] = {}
for rec in _providers(deps):
for d, fields in _cards_of(deps, rec).items():
dst = merged.setdefault(d, {})
for k, v in fields.items():
dst.setdefault(k, v)
return merged
def apply(card: dict, fields: dict | None) -> dict:
"""Merge one service's plugin fields into its index card (a copy)."""
out = dict(card)
for k, v in (fields or {}).items():
if k.startswith("_fill_"):
dst = k[len("_fill_"):]
if not out.get(dst):
out[dst] = v
else:
out[k] = v
return out
def enrich(deps, cards: list[dict]) -> list[dict]:
fields = card_fields(deps)
return [apply(c, fields.get(c.get("dir"))) for c in cards]