288 lines
12 KiB
Python
288 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""Build the public plugin catalog: ``site/dist/`` — the static site
|
||
(``ai-agent.plugins.gabvdl.xyz``) and the ``catalog.json`` the ai-agent's
|
||
``plugin-catalog`` plugin draws in the app.
|
||
|
||
Only the plugins listed in ``catalog/public.json`` (``{"public": [...]}``) are
|
||
published; nothing else under ``plugins/`` is ever read past its id. Stdlib
|
||
only::
|
||
|
||
python3 scripts/build-catalog.py # → site/dist/
|
||
python3 scripts/build-catalog.py --out /tmp/x # elsewhere
|
||
python3 scripts/build-catalog.py --repo https://git.example/x.git
|
||
|
||
``catalog.json``::
|
||
|
||
{"schema": 1, "generatedAt", "commit", "repo",
|
||
"plugins": [{id, name, version, description, kind, category, author,
|
||
color, icon, iconSvg, illustration, readme, languages,
|
||
capabilities, declares, schedules, webhooks, pages, skill,
|
||
seed, requires, optionalRequires, source}]}
|
||
|
||
``source`` is what the ai-agent installs: ``<repo>#plugins/<id>`` (``repo`` is
|
||
the public mirror — ``PUBLIC_REPO`` below, or ``--repo`` /
|
||
``PLUGIN_CATALOG_REPO``; the hub's own setting of the same name must match).
|
||
Art goes to ``art/<id>/`` (``icon.svg``, ``illustration.<ext>``), the README
|
||
ships as markdown (a leading ``# Title`` dropped, as the app does).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import datetime as dt
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
|
||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||
PLUGINS = ROOT / "plugins"
|
||
ALLOW = ROOT / "catalog" / "public.json"
|
||
SITE = ROOT / "site"
|
||
# The one-way public mirror of this repository (the published plugins only).
|
||
PUBLIC_REPO = "https://git.gabvdl.xyz/gabrielvidal/ai-agent-plugins-public.git"
|
||
|
||
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
|
||
LUCIDE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||
COLOR_RE = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
|
||
ILLUSTRATION_EXTS = (".svg", ".webp", ".png", ".jpg", ".jpeg")
|
||
SVG_FORBIDDEN = re.compile(
|
||
r"<\s*(script|foreignObject|iframe|embed|object|audio|video)|\bon[a-z]+\s*=|javascript:"
|
||
r"|<!ENTITY|<!DOCTYPE|(?:xlink:)?href\s*=\s*[\"']?\s*(?:https?:|data:|//)|@import",
|
||
re.IGNORECASE,
|
||
)
|
||
# What the site copies from site/ into dist/ (never deploy.sh, README, dist).
|
||
SITE_FILES = ("index.html", "app.js", "style.css", "icon.svg", "og-image.png", "robots.txt")
|
||
README_MAX = 64 * 1024
|
||
|
||
|
||
class BuildError(Exception):
|
||
pass
|
||
|
||
|
||
def allow_list(path: pathlib.Path = ALLOW) -> list[str]:
|
||
"""The published ids, checked: plain ids, no duplicates."""
|
||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||
ids = raw.get("public") if isinstance(raw, dict) else None
|
||
if not isinstance(ids, list) or not all(isinstance(i, str) for i in ids):
|
||
raise BuildError(f"{path}: expected {{\"public\": [ids…]}}")
|
||
bad = [i for i in ids if not ID_RE.match(i)]
|
||
if bad:
|
||
raise BuildError(f"{path}: invalid ids {bad}")
|
||
dup = sorted({i for i in ids if ids.count(i) > 1})
|
||
if dup:
|
||
raise BuildError(f"{path}: duplicate ids {dup}")
|
||
return list(ids)
|
||
|
||
|
||
def _safe(root: pathlib.Path, rel: str) -> pathlib.Path | None:
|
||
if not isinstance(rel, str) or not rel or rel.startswith("/") or ".." in pathlib.PurePosixPath(rel).parts:
|
||
return None
|
||
p = (root / rel).resolve()
|
||
try:
|
||
p.relative_to(root.resolve())
|
||
except ValueError:
|
||
return None
|
||
return p if p.is_file() else None
|
||
|
||
|
||
def _readme(text: str) -> str:
|
||
lines = text.lstrip("").splitlines()
|
||
while lines and not lines[0].strip():
|
||
lines.pop(0)
|
||
if lines and re.match(r"^#\s+\S", lines[0]):
|
||
lines.pop(0)
|
||
return "\n".join(lines).strip() + "\n"
|
||
|
||
|
||
def _host(url: str) -> str:
|
||
m = re.match(r"^[a-z]+://([^/:?#]+)", url or "")
|
||
return m.group(1) if m else ""
|
||
|
||
|
||
def declares(mf: dict) -> list[str]:
|
||
"""Plain lines of what a plugin declares — the info a visitor reads before
|
||
installing. The hub shows its own, authoritative list in the confirmation."""
|
||
out: list[str] = []
|
||
kind = mf.get("kind") or "app"
|
||
if kind == "provider":
|
||
pv = mf.get("provider") or {}
|
||
out.append(f"A model provider ({pv.get('label') or pv.get('vendorId') or mf['id']}): its models, prices and accounts")
|
||
elif kind == "harness":
|
||
hv = mf.get("harness") or {}
|
||
out.append(f"An agent harness ({hv.get('label') or hv.get('harnessId') or mf['id']}): a driver the machines' sidecar runs")
|
||
elif kind == "translation":
|
||
tv = mf.get("translation") or {}
|
||
out.append(f"A translation of the app into {tv.get('englishName') or tv.get('lang')}")
|
||
pr = mf.get("proxy")
|
||
if pr:
|
||
host = _host(pr.get("baseUrl") or "")
|
||
out.append(f"Calls {'a service on your network' if pr.get('internal') else host or 'a web API'} through the hub's proxy")
|
||
secrets = mf.get("secrets") or []
|
||
if secrets:
|
||
names = ", ".join(str(s.get("label") or s.get("key")) for s in secrets)
|
||
out.append(f"Keeps {len(secrets)} secret{'s' if len(secrets) != 1 else ''} on the hub, write-only: {names}")
|
||
sk = mf.get("skill")
|
||
if sk:
|
||
out.append(f"Gives agent runs the `{sk.get('name') or mf['id']}` skill")
|
||
ui = mf.get("ui") or {}
|
||
pages = ui.get("pages") or []
|
||
if pages:
|
||
out.append("Pages: " + ", ".join(str(p.get("label") or p.get("id")) for p in pages))
|
||
n_cards = len(ui.get("toolCards") or []) + len(ui.get("fences") or [])
|
||
if n_cards:
|
||
out.append(f"Draws {n_cards} kind{'s' if n_cards != 1 else ''} of card in conversations")
|
||
if ui.get("slots"):
|
||
out.append(f"Adds {len(ui['slots'])} panel{'s' if len(ui['slots']) != 1 else ''} to the app's pages")
|
||
if ui.get("overlays"):
|
||
out.append("Draws an overlay over the app's pages")
|
||
sch = mf.get("schedules") or []
|
||
if sch:
|
||
out.append(f"Runs {len(sch)} scheduled job{'s' if len(sch) != 1 else ''} on the hub (no model calls)")
|
||
wh = mf.get("webhooks") or []
|
||
if wh:
|
||
out.append(f"Receives {len(wh)} webhook{'s' if len(wh) != 1 else ''}")
|
||
if mf.get("harnessHooks"):
|
||
out.append("Hooks into the agent harness's tool calls")
|
||
if mf.get("pathShims"):
|
||
out.append("Wraps commands every run calls (" + ", ".join(s.get("command", "?") for s in mf["pathShims"]) + ")")
|
||
if (mf.get("managed") or {}).get("defaultForGuests"):
|
||
out.append("Can be given to your guests (on for them by default)")
|
||
return out
|
||
|
||
|
||
def plugin_entry(pid: str, repo: str, art_out: pathlib.Path | None) -> dict:
|
||
root = PLUGINS / pid
|
||
mf_path = root / "plugin.json"
|
||
if not mf_path.is_file():
|
||
raise BuildError(f"{pid}: plugins/{pid}/plugin.json not found")
|
||
mf = json.loads(mf_path.read_text(encoding="utf-8"))
|
||
if mf.get("id") != pid:
|
||
raise BuildError(f"{pid}: plugin.json says id {mf.get('id')!r}")
|
||
|
||
icon_raw = str(mf.get("icon") or "puzzle").strip()
|
||
icon_svg = None
|
||
if icon_raw.lower().endswith(".svg"):
|
||
icon_svg = _safe(root, icon_raw)
|
||
elif (root / "icon.svg").is_file():
|
||
icon_svg = root / "icon.svg"
|
||
icon_name = icon_raw if LUCIDE_RE.match(icon_raw) else "puzzle"
|
||
if icon_svg is None:
|
||
# a lucide name: the site's own copy of that glyph (site/lucide/)
|
||
icon_svg = next((g for g in (SITE / "lucide" / f"{icon_name}.svg", SITE / "lucide" / "puzzle.svg")
|
||
if g.is_file()), None)
|
||
ill = mf.get("illustration")
|
||
ill_path = _safe(root, ill) if isinstance(ill, str) else next(
|
||
(root / f"illustration{e}" for e in ILLUSTRATION_EXTS if (root / f"illustration{e}").is_file()), None)
|
||
readme_rel = mf.get("readme") if isinstance(mf.get("readme"), str) else "README.md"
|
||
readme_path = _safe(root, readme_rel)
|
||
|
||
entry: dict = {
|
||
"id": pid,
|
||
"name": str(mf.get("name") or pid),
|
||
"version": str(mf.get("version") or "0.0.0"),
|
||
"description": str(mf.get("description") or ""),
|
||
"kind": mf.get("kind") or "app",
|
||
"category": mf.get("category") or {"provider": "providers", "harness": "harnesses",
|
||
"translation": "translations"}.get(mf.get("kind") or "", "other"),
|
||
"author": str(mf.get("author") or ""),
|
||
"color": mf["color"].lower() if isinstance(mf.get("color"), str) and COLOR_RE.match(mf["color"]) else None,
|
||
"icon": icon_name,
|
||
"iconSvg": None,
|
||
"illustration": None,
|
||
"readme": None,
|
||
"languages": [str(x) for x in mf.get("languages") or []],
|
||
"capabilities": sorted(str(c) for c in mf.get("capabilities") or []),
|
||
"declares": declares(mf),
|
||
"schedules": [{"id": s.get("id"), "cron": s.get("cron"), "description": s.get("description") or ""}
|
||
for s in mf.get("schedules") or []],
|
||
"webhooks": [{"id": w.get("id"), "mode": w.get("mode")} for w in mf.get("webhooks") or []],
|
||
"pages": [{"id": p.get("id"), "label": p.get("label"), "nav": p.get("nav") or "dashboards"}
|
||
for p in (mf.get("ui") or {}).get("pages") or []],
|
||
"skill": (mf.get("skill") or {}).get("name"),
|
||
"seed": bool(mf.get("seed")),
|
||
"requires": [str(x) for x in mf.get("requires") or []],
|
||
"optionalRequires": [str(x) for x in mf.get("optionalRequires") or []],
|
||
"source": f"{repo}#plugins/{pid}",
|
||
}
|
||
if icon_svg is not None:
|
||
data = icon_svg.read_bytes()
|
||
if len(data) <= 32 * 1024 and not SVG_FORBIDDEN.search(data.decode("utf-8", "replace")):
|
||
entry["iconSvg"] = f"art/{pid}/icon.svg"
|
||
if art_out is not None:
|
||
(art_out / pid).mkdir(parents=True, exist_ok=True)
|
||
(art_out / pid / "icon.svg").write_bytes(data)
|
||
if ill_path is not None and ill_path.suffix.lower() in ILLUSTRATION_EXTS and ill_path.stat().st_size <= 1024 * 1024:
|
||
if ill_path.suffix.lower() != ".svg" or not SVG_FORBIDDEN.search(ill_path.read_text("utf-8", "replace")):
|
||
name = f"illustration{ill_path.suffix.lower()}"
|
||
entry["illustration"] = f"art/{pid}/{name}"
|
||
if art_out is not None:
|
||
(art_out / pid).mkdir(parents=True, exist_ok=True)
|
||
shutil.copyfile(ill_path, art_out / pid / name)
|
||
if readme_path is not None and readme_path.stat().st_size <= README_MAX:
|
||
entry["readme"] = _readme(readme_path.read_text(encoding="utf-8", errors="replace"))
|
||
return entry
|
||
|
||
|
||
def _commit() -> str:
|
||
try:
|
||
return subprocess.run(["git", "-C", str(ROOT), "rev-parse", "--short", "HEAD"], capture_output=True,
|
||
text=True, timeout=10).stdout.strip()
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
def build_catalog(repo: str, art_out: pathlib.Path | None = None, ids: list[str] | None = None) -> dict:
|
||
ids = allow_list() if ids is None else ids
|
||
plugins = [plugin_entry(pid, repo, art_out) for pid in ids]
|
||
published = set(ids)
|
||
for p in plugins:
|
||
missing = [r for r in p["requires"] if r not in published]
|
||
if missing:
|
||
raise BuildError(f"{p['id']} requires {missing}, which aren't published (catalog/public.json)")
|
||
p["optionalRequires"] = [r for r in p["optionalRequires"] if r in published]
|
||
plugins.sort(key=lambda p: p["name"].lower())
|
||
return {
|
||
"schema": 1,
|
||
"generatedAt": dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
|
||
"commit": _commit(),
|
||
"repo": repo,
|
||
"plugins": plugins,
|
||
}
|
||
|
||
|
||
def build(out: pathlib.Path, repo: str) -> dict:
|
||
if not re.match(r"^https://[A-Za-z0-9.-]+(:\d+)?(/[A-Za-z0-9._~-]+)+\.git$", repo):
|
||
raise BuildError(f"--repo must be an https://…/x.git URL, not {repo!r}")
|
||
if out.exists():
|
||
shutil.rmtree(out)
|
||
(out / "art").mkdir(parents=True)
|
||
cat = build_catalog(repo, out / "art")
|
||
(out / "catalog.json").write_text(json.dumps(cat, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
||
for name in SITE_FILES:
|
||
src = SITE / name
|
||
if src.is_file():
|
||
shutil.copyfile(src, out / name)
|
||
return cat
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||
ap.add_argument("--out", default=str(SITE / "dist"))
|
||
ap.add_argument("--repo", default=os.environ.get("PLUGIN_CATALOG_REPO") or PUBLIC_REPO)
|
||
a = ap.parse_args(argv)
|
||
try:
|
||
cat = build(pathlib.Path(a.out), a.repo)
|
||
except BuildError as e:
|
||
print(f"build-catalog: {e}", file=sys.stderr)
|
||
return 1
|
||
print(f"build-catalog: {len(cat['plugins'])} plugins → {a.out}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|