Files
ai-agent/backend/plugins/manifest.py
gabrielvidalandClaude Opus 5.5 efa87b21cf feat(plugins): perf.read / perf.act bridges; Performance and Storage move to the performance plugin
- backend: plugins/hubperf.py — perf.read (GET hub/perf/live, history,
  conversations, commands, conversation/{sid}?series=, conversation/{sid}/storage,
  storage, storage/history, storage/writers, storage/config, settings; live and
  storage add profiles + guestNames), perf.act (POST hub/perf/kill, keep,
  settings, storage/rm, storage/scan, storage/config — the plugin's own
  handlers only), and telemetry.read's hub/telemetry/hub. Owner-only,
  operator-approved caps. backend/perf and every /api/perf/* route stay.
- frontend: the Performance and Storage pages, perfLive/perfTotals/perfViz/
  perfStorage/storageItems/storageWriters/HubCard/guestPill, hubAnalysis,
  telemetryApi, perfApi and the conversation's PerfCards/StorageCards go;
  /dashboards/performance and /dashboards/storage redirect to
  /plugins/performance/performance|storage (else the overview);
  DETAIL_CARD_RENAMES maps the six retired card ids onto the plugin's
  conv-perf / conv-storage slots; the slot update carries drawerOpen and
  prompts. The header chips, CallCost / CommandPlayback and the guest Stats
  stay core.
- docs: CLAUDE.md, docs/plugins.md; tests: test_plugin_perf_bridge.py.

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

2117 lines
105 KiB
Python

"""Plugin manifest parsing, strict validation (v1 + v2 + v3), capability
summaries and deterministic approval fingerprints.
Every field is checked before a plugin can be installed or reloaded:
* relative paths must stay inside the plugin directory (no ``..`` or symlinks
escaping the root);
* regex patterns must compile cleanly;
* ``proxy.baseUrl`` must be ``https://`` unless ``internal: true`` (which only
the operator may approve);
* unknown top-level keys are refused so typos fail loudly instead of silently
doing nothing.
"""
from __future__ import annotations
import hashlib
import json
import pathlib
import re
from typing import Any
from urllib.parse import urlsplit
SCHEMA_VERSION = 1
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_-]{0,47}$")
_SKILL_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,47}$")
_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"})
_AUTH_INS = frozenset({"header", "query", "basic"})
_SECRET_SCOPES = frozenset({"user", "hub"})
_WAKE_SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,62}$")
_FIELD_TYPES = frozenset({"text", "textarea", "number", "checkbox", "select", "list"})
# ``none``: routable at ``/plugins/<id>/<page>`` and shown in no nav (an
# OAuth callback page).
_NAV_GROUPS = frozenset({"dashboards", "tools", "main", "files", "none"})
# ``machine.detail``: a machine page's Tools tab (init ``{machineId, name, kind}``).
_SLOT_PLACES = frozenset({"project.card", "project.detail", "service.card", "service.detail",
"conversation.header", "conversation.details", "machine.detail",
# widget-platform places: a full-width home section, a
# bar above the composer, the strip under the last
# message, a pill in the thread's corner row.
"home.section", "conversation.pinned",
"conversation.threadFooter", "conversation.gizmos",
# the thread's first line (under the fork banner) and
# its last (after the summary) — the Handoff plugin's
# "Continued from" / "Continued in".
"conversation.threadHeader", "conversation.threadEnd",
# the conversations drawer's body behind a toggle in
# its count row; an item of both composers' send
# menus (the frozen payload, in the app's modal); a
# document in the app's modal (``openModal`` /
# ``?modal=<pid>:<slot>``) — the scheduled-conversations
# plugin's drawer, Send later… and edit view.
"conversations.drawer", "composer.send", "app.modal"})
# ``ui.menuItems[].where``: the conversation list's right-click / long-press
# menu — a row that opens the item's sandboxed dialog.
_MENU_PLACES = frozenset({"conversation.menu"})
_MENU_ITEMS_MAX = 8
# Slot places whose host draws a control of its own (a toggle, a menu item):
# they name a lucide ``icon`` (and the drawer's toggle a ``badge`` read).
_ICON_SLOTS = frozenset({"conversations.drawer", "composer.send"})
_LUCIDE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
# Host SSE event types a slot / tool card frame may ask to be forwarded.
_UI_EVENTS = frozenset({"askform", "meta", "transcript", "usage"})
# ThreadItem fields a tool card's ``match.hasField`` may require.
_HAS_FIELDS = frozenset({"deploy", "commits", "subagent", "bashDiff"})
# ``ui.fences[].lang``: the info string of a fenced block in an agent's message
# that the plugin draws (```chart → its frame). A language people write code in
# stays a code block, and ``notify`` is the closing push the parser cuts out.
_FENCE_LANG_RE = re.compile(r"^[a-z][a-z0-9_+-]{1,31}$")
_FENCE_RESERVED = frozenset({
"notify", "text", "txt", "plain", "plaintext", "md", "markdown", "diff", "patch", "log",
"sh", "bash", "zsh", "fish", "shell", "console", "powershell", "ps1", "bat", "cmd",
"js", "jsx", "javascript", "ts", "tsx", "typescript", "json", "jsonc", "json5", "yaml", "yml",
"toml", "ini", "xml", "html", "css", "scss", "sass", "less", "svg", "csv", "tsv", "sql",
"py", "python", "rb", "ruby", "go", "rs", "rust", "java", "kt", "kotlin", "swift", "c", "cpp",
"c++", "cs", "csharp", "php", "lua", "r", "dart", "scala", "ex", "elixir", "erl", "hs",
"dockerfile", "makefile", "nginx", "graphql", "proto", "env", "vue", "svelte",
})
# A transparent sandboxed frame over a whole page (docs/plugins.md → "Overlays"):
# ``conversation`` = a conversation page, ``home`` = the home page. What each
# place hands the frame is fixed by the host (lib/overlay/feed.ts), never more.
_OVERLAY_PLACES = frozenset({"conversation", "home"})
# Clicks: ``none`` = every click goes to the page; ``hits`` = the frame takes
# the pointer only inside the small boxes it reports (a pet to pat or throw).
_OVERLAY_POINTER = frozenset({"none", "hits"})
# Per-person preferences the host keeps for a plugin (in the person's
# own settings, guests included) and draws on the plugin's page.
_PREF_TYPES = frozenset({"switch", "range", "color", "select"})
_PREF_SCOPES = frozenset({"user", "default+override"})
_PREF_OPTIONS_FROM = frozenset({"user.modelFamilies"})
# ``notify.action``: a button of a push was tapped (``/api/notify/{id}/action``)
# — ``{notifyId, index, title}``; a plugin's push buttons (``hub/notify``
# ``actions``) come back to it this way.
_EVENT_TYPES = frozenset({"conversation.finished", "conversation.started", "notify", "deploy",
"notify.action"})
_EVENT_NAME_RE = re.compile(r"^[a-z][a-z0-9._-]{0,63}$")
_PLUGIN_EVENT_RE = re.compile(r"^plugin:([a-z0-9][a-z0-9-]{0,47}):([a-z][a-z0-9._-]{0,63})$")
_WEBHOOK_MODES = frozenset({"notify", "spawn", "action"})
_CAPABILITIES = frozenset({
"conversations.read", "conversations.spawn", "conversations.reply", "notify.send",
"goals.read", "goals.work", "graph.read", "footprint.read", "telemetry.read", "analytics.read",
# The host's services dir, for this plugin's handlers (AIA_SERVICES_DIR):
# the owner's runs only — the Services catalogue plugin.
"services.read",
# Owner-only run bridges (plugins/hubruns.py) — the mail-agents plugin.
"runs.start", "conversations.send", "models.read", "workers.read",
# Hub bridges for ask-form, approvals, new-project and plans plugins.
"askform.bridge", "users.read", "scaffold.run", "plans.read", "plans.write",
# Batch 1 owner-only host data (AIA_TEMPLATES_DIR / AIA_MEMORIES_DIR /
# AIA_PROJECTS_DIR for the owner's handler runs; activity + ship bridges).
"templates.read", "memories.read", "projects.env", "activity.read", "ship.run",
# Plan usage (plugins/usagedata.py) — the plan-usage plugin.
"usage.read", "usage.calibrate",
# One-shot completions on any model + writing conversation labels
# (plugins/hubcomplete.py) — the conversation-labels plugin.
"complete.run", "conversations.label",
# The owner's machines and their sidecar's /mcp-servers routes
# (plugins/hubmachines.py), and authenticated streaming relays to
# upstreams the plugin holds the credentials of (plugins/relay.py) — the
# mcp-servers plugin.
"machines.mcp", "relay.serve",
# Wake-on-LAN through the host sidecar's /wol and a worker probe
# (plugins/hubwake.py) — the wake-on-lan plugin.
"machines.wake",
# A plugin's own data on a conversation (``meta.plugins.<id>``, read and
# written through hub/conversations/{sid}/data — plugins/hubconvdata.py)
# — the handoff plugin's links.
"conversations.data",
# A prompt's title from the ``conversation.title`` provider (hub/title)
# — the scheduled-conversations plugin.
"conversations.title",
# The Performance / Storage dashboards' data and their Kill / Keep /
# Remove / Measure (plugins/hubperf.py) — the performance plugin.
"perf.read", "perf.act",
})
# Capabilities only the operator may approve (and shown as privileged).
_OPERATOR_CAPS = frozenset({
"conversations.spawn", "conversations.reply",
"goals.read", "goals.work", "services.read", "graph.read", "footprint.read", "telemetry.read",
"analytics.read", "runs.start", "conversations.send", "models.read", "workers.read",
"askform.bridge", "users.read", "scaffold.run", "plans.read", "plans.write",
"templates.read", "memories.read", "projects.env", "activity.read", "ship.run",
# Plan usage (plugins/usagedata.py) — the plan-usage plugin.
"usage.read", "usage.calibrate",
"complete.run", "conversations.label",
"machines.mcp", "relay.serve", "machines.wake", "conversations.data",
"conversations.title", "perf.read", "perf.act",
})
# Data a plugin hands the host itself: name → the action the host runs (as the
# owner) and merges into its own answer. ``service.cards``: per service dir,
# the extra fields of a /api/services card (whitelisted in services/enrich.py).
# ``notify.channel``: delivers its installer's pushes, asks and clears
# (notifications/channels.py) — run as that user, not the owner.
# ``composer.shortcuts``: additive prompt shortcuts rendered natively in the
# composer (plugins/shortcuts.py).
# ``inbox.waiting``: pending questions surfaced in Waiting for feedback,
# FeedbackBell, ConversationWaiting and auto-archive (plugins/waiting.py).
# ``composer.mode``: composer mode descriptor (e.g. New project).
# ``plans.index``: plan metadata consumed by core integrations (e.g. graph).
# ``memories.index``: memory metadata for core integrations (plugins/memories_bridge.py).
# ``notify.audio``: renders a push's spoken audio (the desk-phone replay button).
# ``app.banner``: an owner-only floating status banner (plugins/banner.py).
# ``conversation.title``: a scheduled prompt's title and a long title's short
# header stand-in; ``conversation.look``: label a conversation's action badge
# now (plugins/labels_bridge.py).
# ``machine.attention``: what on each of the owner's machines waits for him —
# the Needs-you rows and the Setup checklist (plugins/machine_attention.py).
# ``machine.wake``: which of the owner's workers can be woken (Wake-on-LAN),
# and the wake itself — before a run pinned to a sleeping one, and the Wake
# button on its card (plugins/machine_wake.py).
# ``runs.schedule``: scheduled conversations — ``{op: list|get|create|edit|
# cancel|start|title|upcoming, …}`` (plugins/schedule_bridge.py).
_PROVIDES = frozenset({
"service.cards", "notify.channel", "composer.shortcuts",
"inbox.waiting", "composer.mode", "plans.index",
"memories.index", "notify.audio", "app.banner",
"conversation.title", "conversation.look",
# declarative native tiles for the home usage strip (plugins/home_tiles.py)
"home.tiles",
"machine.attention", "machine.wake",
# Scheduled conversations ("Send later"): the ``/api/scheduled`` routes,
# the week's budget and the stopped-run card's Resume at… ask it
# (plugins/schedule_bridge.py).
"runs.schedule",
})
_TOP_KEYS = frozenset({
"schema", "id", "name", "version", "description", "icon", "author",
"skill", "secrets", "settings", "proxy", "storage", "schedules",
"ui", "events", "webhooks", "actions", "resources", "capabilities",
"managed", "illustration", "color", "readme", "provides",
"requires", "exports", "emits", "agents",
# typed plugins (plugins/typed_manifest.py): what a plugin *is* — an app
# (the default), a model provider or an agent harness.
"kind", "provider", "harness",
# hooks into the agent harness's own hook points (plugins/harness_hooks.py)
"harnessHooks",
# ai-agent CLI commands + MCP tools over declared actions (plugins/commands.py)
"commands",
})
class ManifestError(ValueError):
"""Raised when ``plugin.json`` or its referenced files are invalid."""
def __init__(self, errors: list[str]):
self.errors = errors
super().__init__("; ".join(errors))
def _overlays(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""``ui.overlays[]``: one transparent frame per page place. Only keys that
are set are written (``ui`` is in the approval fingerprint)."""
if raw is None:
return []
if not isinstance(raw, list):
errors.append("ui.overlays must be a list")
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
for i, ov in enumerate(raw):
if not isinstance(ov, dict):
errors.append(f"ui.overlays[{i}] must be an object")
continue
oid = str(ov.get("id") or "").strip()
where = str(ov.get("where") or "")
if not _KEY_RE.match(oid) or where not in _OVERLAY_PLACES:
errors.append(f"ui.overlays[{i}]: invalid id or where ({sorted(_OVERLAY_PLACES)})")
continue
if where in seen:
errors.append(f"ui.overlays[{i}]: one overlay per place ('{where}' twice)")
continue
seen.add(where)
pointer = str(ov.get("pointer") or "none")
if pointer not in _OVERLAY_POINTER:
errors.append(f"ui.overlays[{i}].pointer must be one of {sorted(_OVERLAY_POINTER)}")
continue
_safe_rel(root, ov.get("html"), f"ui.overlays[{i}].html", errors)
item: dict[str, Any] = {"id": oid, "where": where, "html": str(ov.get("html") or ""), "pointer": pointer}
if ov.get("cursor") is True:
item["cursor"] = True
out.append(item)
return out
def _prefs(raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""``ui.prefs[]``: switch / range / color / select fields, per person."""
if raw is None:
return []
if not isinstance(raw, list):
errors.append("ui.prefs must be a list")
return []
out: list[dict[str, Any]] = []
for i, f in enumerate(raw[:12]):
if not isinstance(f, dict):
errors.append(f"ui.prefs[{i}] must be an object")
continue
key = str(f.get("key") or "")
typ = str(f.get("type") or "")
if not _KEY_RE.match(key) or typ not in _PREF_TYPES:
errors.append(f"ui.prefs[{i}]: invalid key or type ({sorted(_PREF_TYPES)})")
continue
item: dict[str, Any] = {"key": key, "type": typ, "label": str(f.get("label") or key)[:60]}
if f.get("help"):
item["help"] = str(f["help"])[:300]
if isinstance(f.get("labels"), dict): # {"fr": {"label", "help"}}
item["labels"] = {str(k)[:5]: {kk: str(vv)[:300] for kk, vv in v.items() if kk in ("label", "help")}
for k, v in f["labels"].items() if isinstance(v, dict)}
scope = str(f.get("scope") or "user")
if scope not in _PREF_SCOPES:
errors.append(f"ui.prefs[{i}].scope must be one of {sorted(_PREF_SCOPES)}")
continue
if scope != "user":
item["scope"] = scope
d = f.get("default")
if typ == "switch":
item["default"] = bool(d) if d is not None else True
elif typ == "range":
try:
lo, hi = float(f.get("min", 0)), float(f.get("max", 100))
step = float(f.get("step", 1))
dv = float(d if d is not None else lo)
except (TypeError, ValueError):
errors.append(f"ui.prefs[{i}]: range needs numeric min / max / step / default")
continue
if not lo < hi or not lo <= dv <= hi or step <= 0:
errors.append(f"ui.prefs[{i}]: range needs min < default ≤ max")
continue
item.update({"min": lo, "max": hi, "step": step, "default": dv})
if f.get("unit"):
item["unit"] = str(f["unit"])[:8]
elif typ == "color":
dv = str(d or "#888888")
if not re.fullmatch(r"#[0-9a-fA-F]{6}", dv):
errors.append(f"ui.prefs[{i}]: color default must be #rrggbb")
continue
item["default"] = dv.lower()
sw = [str(c).lower() for c in (f.get("swatches") or []) if re.fullmatch(r"#[0-9a-fA-F]{6}", str(c))]
if sw:
item["swatches"] = sw[:12]
else:
opt_from = f.get("optionsFrom")
if opt_from is not None:
opt_from = str(opt_from)
if opt_from not in _PREF_OPTIONS_FROM:
errors.append(f"ui.prefs[{i}].optionsFrom must be one of {sorted(_PREF_OPTIONS_FROM)}")
continue
item["optionsFrom"] = opt_from
opts = [str(o)[:40] for o in (f.get("options") or [])][:20]
if not opts and opt_from == "user.modelFamilies":
opts = ["haiku", "sonnet", "opus"]
if not opts or str(d if d is not None else opts[0]) not in opts:
errors.append(f"ui.prefs[{i}]: select needs options and a default among them")
continue
item.update({"options": opts, "default": str(d if d is not None else opts[0])})
if isinstance(f.get("optionLabels"), dict):
item["optionLabels"] = {str(k)[:40]: str(v)[:60] for k, v in f["optionLabels"].items()}
out.append(item)
return out
def _safe_rel(root: pathlib.Path, rel: str, label: str, errors: list[str],
*, must_exist: bool = True, want_dir: bool = False) -> pathlib.Path | None:
if not isinstance(rel, str) or not rel.strip() or rel.startswith("/") or "\\" in rel:
errors.append(f"{label}: must be a relative POSIX path")
return None
parts = pathlib.PurePosixPath(rel).parts
if not parts or any(p in ("", ".", "..") for p in parts):
errors.append(f"{label}: path must not contain '..' or '.' segments")
return None
resolved_root = root.resolve()
target = (resolved_root / rel).resolve()
try:
target.relative_to(resolved_root)
except ValueError:
errors.append(f"{label}: path escapes plugin directory")
return None
if must_exist:
if want_dir and not target.is_dir():
errors.append(f"{label}: directory '{rel}' not found")
return None
if not want_dir and not target.is_file():
errors.append(f"{label}: file '{rel}' not found")
return None
return target
# ── art: SVG icon, illustration, accent colour, README ───────────────────────
_ICON_MAX = 32 * 1024
_ILLUSTRATION_MAX = 1024 * 1024
_README_MAX = 64 * 1024
_ILLUSTRATION_EXTS = (".svg", ".webp", ".png", ".jpg", ".jpeg")
_COLOR_RE = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
_LUCIDE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
# An SVG is served sandboxed and drawn through <img> / CSS masks, where
# scripts never run — but a plugin anyone can write must not ship active
# content at all: refused at install instead of trusting the serving path.
_SVG_FORBIDDEN = re.compile(
r"<\s*(script|foreignObject|iframe|embed|object|audio|video|use\b[^>]*href\s*=\s*(?![\"']?#))"
r"|\bon[a-z]+\s*="
r"|javascript:"
r"|<!ENTITY|<!DOCTYPE"
r"|(?:xlink:)?href\s*=\s*[\"']?\s*(?:https?:|data:|//)"
r"|@import|url\(\s*[\"']?\s*(?:https?:|data:|//)",
re.IGNORECASE,
)
def svg_problem(data: bytes) -> str | None:
"""Why an SVG can't be used as plugin art, or ``None`` when it is inert."""
try:
text = data.decode("utf-8")
except UnicodeDecodeError:
return "is not UTF-8"
if "<svg" not in text.lower():
return "is not an SVG"
m = _SVG_FORBIDDEN.search(text)
if m:
return f"contains active or external content ({m.group(0)[:30]!r})"
return None
def _art_file(root: pathlib.Path, rel: Any, label: str, errors: list[str], *,
exts: tuple[str, ...], max_bytes: int) -> str | None:
target = _safe_rel(root, rel, label, errors)
if target is None:
return None
if target.suffix.lower() not in exts:
errors.append(f"{label}: must be one of {', '.join(exts)}")
return None
size = target.stat().st_size
if size > max_bytes:
errors.append(f"{label}: {size // 1024} KB is over the {max_bytes // 1024} KB limit")
return None
if target.suffix.lower() == ".svg":
why = svg_problem(target.read_bytes())
if why:
errors.append(f"{label}: SVG {why}")
return None
return str(rel)
def _parse_art(root: pathlib.Path, raw: dict[str, Any], errors: list[str]) -> dict[str, Any]:
"""``icon`` (a lucide name, or a path to an ``.svg``), ``illustration``,
``color`` and ``readme``. Without a declaration, ``icon.svg``,
``illustration.{svg,webp,png,jpg}`` and ``README.md`` at the plugin root
are picked up by name. ``artVersion`` changes whenever one of the files
does, so the asset URLs can be cached for good."""
icon_raw = str(raw.get("icon") or "puzzle").strip()
icon_name = "puzzle"
icon_svg_rel: Any = None
if icon_raw.lower().endswith(".svg"):
icon_svg_rel = icon_raw
elif _LUCIDE_RE.match(icon_raw):
icon_name = icon_raw
else:
errors.append("icon must be a lucide icon name or a path to an .svg")
if icon_svg_rel is None and (root / "icon.svg").is_file():
icon_svg_rel = "icon.svg"
icon_svg = (_art_file(root, icon_svg_rel, "icon", errors, exts=(".svg",), max_bytes=_ICON_MAX)
if icon_svg_rel else None)
ill_rel: Any = raw.get("illustration")
if ill_rel is None:
ill_rel = next((f"illustration{e}" for e in _ILLUSTRATION_EXTS if (root / f"illustration{e}").is_file()), None)
illustration = (_art_file(root, ill_rel, "illustration", errors,
exts=_ILLUSTRATION_EXTS, max_bytes=_ILLUSTRATION_MAX)
if ill_rel else None)
color = raw.get("color")
if color is not None and (not isinstance(color, str) or not _COLOR_RE.match(color.strip())):
errors.append("color must be a hex colour like #3a2f7d")
color = None
readme_rel: Any = raw.get("readme")
if readme_rel is None and (root / "README.md").is_file():
readme_rel = "README.md"
readme = (_art_file(root, readme_rel, "readme", errors, exts=(".md",), max_bytes=_README_MAX)
if readme_rel else None)
h = hashlib.sha256()
for rel in (icon_svg, illustration, readme):
if rel:
h.update(rel.encode())
h.update((root / rel).read_bytes())
return {
"icon": icon_name,
"iconSvg": icon_svg,
"illustration": illustration,
"color": color.strip().lower() if isinstance(color, str) else None,
"readme": readme,
"artVersion": h.hexdigest()[:12],
}
def _check_regex(pattern: Any, label: str, errors: list[str]) -> str | None:
if not isinstance(pattern, str) or not pattern or len(pattern) > 512:
errors.append(f"{label}: regex must be a non-empty string (<= 512 chars)")
return None
try:
re.compile(pattern)
except re.error as e:
errors.append(f"{label}: invalid regex ({e})")
return None
return pattern
# A quantified group that itself ends on a quantifier — `(a+)+`, `(\w*)*`,
# `(x{1,3})+`: the shape behind catastrophic backtracking. Resource regexes
# run over every prompt and tool result of every transcript, so they are
# held to it (a heuristic, not a proof: it refuses the classic shapes).
_REDOS_RE = re.compile(r"\((?:[^()\\]|\\.)*(?:[+*]|\{\d*,?\d*\})\??\)(?:[+*]|\{\d*,\d*\})")
def _check_safe_regex(pattern: Any, label: str, errors: list[str]) -> str | None:
pat = _check_regex(pattern, label, errors)
if pat and _REDOS_RE.search(pat):
errors.append(f"{label}: nested quantifiers (catastrophic backtracking) are not allowed")
return None
return pat
# ── resources[] (conversation resource kinds, plugins/resources.py) ─────────
_CORE_RESOURCE_KINDS = frozenset({"branch", "url"})
_GROUP_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]{0,31}|\d)$")
_CLICK_ACTIONS = frozenset({"open", "copy"})
_HUE_ROLES = frozenset({"hue", "shade"})
_FIELD_PATH_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,47}(?:\[\])?(?:\.[A-Za-z_][A-Za-z0-9_]{0,47}(?:\[\])?){0,3}$")
_TPL_MAX = 300
def _tpl(v: Any, label: str, errors: list[str]) -> str | None:
if v is None:
return None
if not isinstance(v, str) or not v.strip() or len(v) > _TPL_MAX:
errors.append(f"{label}: a template string (<= {_TPL_MAX} chars)")
return None
return v
def _tpl_rules(v: Any, label: str, errors: list[str]) -> list[dict[str, str]] | None:
"""A template, or rules ``[{"match": "<regex on the id>", "template"}]``
— the first whose ``match`` hits (none = always) wins; ``""`` = nothing."""
if v is None:
return None
if isinstance(v, str):
t = _tpl(v, label, errors)
return [{"template": t}] if t else None
if not isinstance(v, list) or not v or len(v) > 8:
errors.append(f"{label}: a template or 1-8 rules")
return None
out = []
for i, rule in enumerate(v):
if not isinstance(rule, dict) or not isinstance(rule.get("template"), str) \
or len(rule["template"]) > _TPL_MAX:
errors.append(f"{label}[{i}]: {{match?, template}}")
continue
item = {"template": rule["template"]}
if rule.get("match") is not None:
m = _check_safe_regex(rule["match"], f"{label}[{i}].match", errors)
if m:
item["match"] = m
out.append(item)
return out or None
def _paths(v: Any, label: str, errors: list[str]) -> list[str] | None:
if v is None:
return None
if isinstance(v, str):
v = [v]
if not isinstance(v, list) or len(v) > 6 or not all(
isinstance(x, str) and _FIELD_PATH_RE.match(x) for x in v):
errors.append(f"{label}: 1-6 field paths (a.b, labels[].name)")
return None
return list(v) or None
def _tool_extractors(raw: Any, label: str, errors: list[str]) -> list[dict[str, Any]]:
if raw is None:
return []
if not isinstance(raw, list) or len(raw) > 10:
errors.append(f"{label} must be a list (10 max)")
return []
out: list[dict[str, Any]] = []
for i, ex in enumerate(raw):
lb = f"{label}[{i}]"
if not isinstance(ex, dict):
errors.append(f"{lb} must be an object")
continue
tool = ex.get("tool")
if not isinstance(tool, str) or not tool.strip() or len(tool) > 120:
errors.append(f"{lb}.tool: a tool name or glob (\"shell\", \"mcp__*__get_issue\", \"*\")")
continue
item: dict[str, Any] = {"tool": tool.strip()}
if ex.get("kind") is not None:
if not isinstance(ex["kind"], str) or not _ID_RE.match(ex["kind"]):
errors.append(f"{lb}.kind invalid")
continue
item["kind"] = ex["kind"]
if ex.get("commandRegex") is not None:
pat = _check_safe_regex(ex["commandRegex"], f"{lb}.commandRegex", errors)
if pat:
item["commandRegex"] = pat
inp = _tpl(ex.get("inputTemplate"), f"{lb}.inputTemplate", errors)
if inp:
item["inputTemplate"] = inp
for f in ("idFields", "urlFields", "titleFields", "stateFields", "xrefFields"):
p = _paths(ex.get(f), f"{lb}.{f}", errors)
if p:
item[f] = p
mf = ex.get("metaFields")
if mf is not None:
if not isinstance(mf, dict) or len(mf) > 8 or not all(
isinstance(k, str) and _KEY_RE.match(k) and isinstance(v, str)
and _FIELD_PATH_RE.match(v) for k, v in mf.items()):
errors.append(f"{lb}.metaFields: up to 8 name → field path")
else:
item["metaFields"] = dict(mf)
sf = ex.get("stateFlags")
if sf is not None:
if not isinstance(sf, dict) or len(sf) > 4 or not all(
isinstance(k, str) and _FIELD_PATH_RE.match(k) and isinstance(v, str)
and 0 < len(v) <= 40 for k, v in sf.items()):
errors.append(f"{lb}.stateFlags: up to 4 field path → state")
else:
item["stateFlags"] = dict(sf)
cm = ex.get("channelMapRegex")
if cm is not None:
pats = [cm] if isinstance(cm, str) else cm
ok = []
if not isinstance(pats, list) or len(pats) > 4:
errors.append(f"{lb}.channelMapRegex: a regex or up to 4")
else:
for j, pat in enumerate(pats):
pat = _check_safe_regex(pat, f"{lb}.channelMapRegex[{j}]", errors)
if pat and not {"id", "name"} <= set(re.compile(pat).groupindex):
errors.append(f"{lb}.channelMapRegex[{j}]: needs (?P<id>…) and (?P<name>…)")
elif pat:
ok.append(pat)
if ok:
item["channelMapRegex"] = ok
th = ex.get("textHint")
if th is not None:
th = [th] if isinstance(th, str) else th
if not isinstance(th, list) or len(th) > 4 or not all(
isinstance(x, str) and 0 < len(x) <= 60 for x in th):
errors.append(f"{lb}.textHint: up to 4 substrings")
else:
item["textHint"] = list(th)
if ex.get("tagOnCall"):
item["tagOnCall"] = True
if not any(k in item for k in ("commandRegex", "inputTemplate", "idFields", "urlFields",
"channelMapRegex")):
errors.append(f"{lb}: extracts nothing (commandRegex / inputTemplate / idFields / "
"urlFields / channelMapRegex)")
continue
out.append(item)
return out
def _resources(raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""``resources[]``: the conversation resource kinds a plugin declares —
pure data the host's in-process registry (``plugins/resources.py``)
matches; no code of the plugin ever runs for it. The v3 shape
``{id, label, urlRegex, color}`` stays valid."""
if raw is None:
return []
if not isinstance(raw, list) or len(raw) > 8:
errors.append("resources must be a list (8 max)")
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
for i, r in enumerate(raw):
lb = f"resources[{i}]"
if not isinstance(r, dict):
errors.append(f"{lb} must be an object")
continue
rid = str(r.get("id") or "").strip()
if not _ID_RE.match(rid) or rid in seen:
errors.append(f"{lb}.id invalid or duplicate")
continue
if rid in _CORE_RESOURCE_KINDS:
errors.append(f"{lb}.id: '{rid}' is a core kind")
continue
n_err = len(errors)
item: dict[str, Any] = {"id": rid, "label": str(r.get("label") or rid)[:40]}
for f in ("urlRegex", "idRegex", "bareKeyRegex", "branchKeyPattern", "ignoreUrlRegex"):
if r.get(f) is not None:
pat = _check_safe_regex(r[f], f"{lb}.{f}", errors)
if pat:
item[f] = pat
if not item.get("urlRegex") and not item.get("idRegex"):
if len(errors) == n_err:
errors.append(f"{lb}: needs a urlRegex or an idRegex")
continue
# idTemplate: a template, or up to 4 tried in order (the first whose
# placeholders all resolve) — `["{repo|config.githubRepo}#{num}", "#{num}"]`.
idt = r.get("idTemplate")
if idt is not None:
idts = [idt] if isinstance(idt, str) else idt
if not isinstance(idts, list) or not 0 < len(idts) <= 4:
errors.append(f"{lb}.idTemplate: a template or up to 4")
else:
ok = [t for j, x in enumerate(idts) if (t := _tpl(x, f"{lb}.idTemplate[{j}]", errors))]
if ok:
item["idTemplate"] = ok
t = _tpl(r.get("urlTemplate"), f"{lb}.urlTemplate", errors)
if t:
item["urlTemplate"] = t
for f in ("labelTemplate", "titleToken"):
t = _tpl_rules(r.get(f), f"{lb}.{f}", errors)
if t:
item[f] = t
for f in ("slugTitleGroup", "bareKeyTeamGroup", "namesGroup", "dateGroup"):
v = r.get(f)
if v is None:
continue
if not isinstance(v, (str, int)) or not _GROUP_RE.match(str(v)):
errors.append(f"{lb}.{f}: a capture group name or index")
else:
item[f] = str(v)
if item.get("bareKeyRegex") and not item.get("bareKeyTeamGroup"):
errors.append(f"{lb}.bareKeyRegex needs bareKeyTeamGroup (bare keys are gated on "
"the teams seen in real links)")
nd = r.get("needles")
if nd is not None:
if not isinstance(nd, list) or len(nd) > 8 or not all(
isinstance(x, str) and 0 < len(x) <= 80 for x in nd):
errors.append(f"{lb}.needles: up to 8 templates")
else:
item["needles"] = list(nd)
item["toolExtractors"] = _tool_extractors(r.get("toolExtractors"),
f"{lb}.toolExtractors", errors)
if r.get("icon") is not None:
if not isinstance(r["icon"], str) or not re.match(r"^[A-Za-z0-9:_-]{1,64}$", r["icon"]):
errors.append(f"{lb}.icon: a lucide name")
else:
item["icon"] = r["icon"]
item["color"] = str(r.get("color") or "")[:32]
st = r.get("stateTones")
if st is not None:
if not isinstance(st, dict) or len(st) > 12 or not all(
isinstance(k, str) and 0 < len(k) <= 40 and isinstance(v, str) and 0 < len(v) <= 32
for k, v in st.items()):
errors.append(f"{lb}.stateTones: up to 12 state → tone")
else:
item["stateTones"] = {k.lower(): v for k, v in st.items()}
ca = r.get("clickAction", "open")
if ca not in _CLICK_ACTIONS:
errors.append(f"{lb}.clickAction must be one of {sorted(_CLICK_ACTIONS)}")
item["clickAction"] = ca if ca in _CLICK_ACTIONS else "open"
pr = r.get("priority", 100)
if not isinstance(pr, int) or isinstance(pr, bool) or not 0 <= pr <= 1000:
errors.append(f"{lb}.priority: an integer 0-1000 (lower = the primary first)")
pr = 100
item["priority"] = pr
hr = r.get("hueRole")
if hr is not None:
if hr not in _HUE_ROLES:
errors.append(f"{lb}.hueRole must be one of {sorted(_HUE_ROLES)}")
else:
item["hueRole"] = hr
item["statusAction"] = str(r.get("statusAction") or "")
if len(errors) == n_err:
seen.add(rid)
out.append(item)
for item in out:
for ex in item["toolExtractors"]:
if ex.get("kind") and ex["kind"] not in seen:
errors.append(f"resources.{item['id']}.toolExtractors: kind '{ex['kind']}' "
"is not one of this plugin's resources")
return out
def _check_cron(expr: Any, label: str, errors: list[str]) -> str | None:
if not isinstance(expr, str) or len(expr.strip().split()) != 5:
errors.append(f"{label}: cron must be a 5-field expression")
return None
try:
from cron.scheduler import parse_schedule
parse_schedule(expr.strip())
except Exception as e:
errors.append(f"{label}: invalid cron expression ({e})")
return None
return expr.strip()
_PARAM_RE = re.compile(r"^[A-Za-z0-9_.\[\]-]{1,64}$")
_UNIT_RE = re.compile(r"^[a-z][a-zA-Z0-9_]{0,31}$")
def _clean_rule(rule: dict[str, Any], method: str, pat: str, label: str,
errors: list[str]) -> dict[str, Any]:
"""One ``proxy.allow`` rule: method + path, plus the optional per-rule
policy (handlerOnly, query, forcedParams, noAuth, units, creates, owned)."""
out: dict[str, Any] = {"method": method, "path": pat}
if rule.get("handlerOnly") is not None:
out["handlerOnly"] = bool(rule["handlerOnly"])
q = rule.get("query")
if q is not None:
if not isinstance(q, dict) or not q:
errors.append(f"{label}.query must be a non-empty object of param → regex")
else:
qo = {}
for k, v in q.items():
if not _PARAM_RE.match(str(k)):
errors.append(f"{label}.query: bad param name {k!r}")
continue
rx = _check_regex(v, f"{label}.query.{k}", errors)
if rx:
qo[str(k)] = rx
out["query"] = qo
fp = rule.get("forcedParams")
if fp is not None:
if not isinstance(fp, dict):
errors.append(f"{label}.forcedParams must be an object")
else:
fo = {}
for k, v in fp.items():
if not _PARAM_RE.match(str(k)):
errors.append(f"{label}.forcedParams: bad param name {k!r}")
continue
fo[str(k)] = str(v)[:200]
out["forcedParams"] = fo
if rule.get("noAuth"):
out["noAuth"] = True
if rule.get("creates"):
out["creates"] = True
un = rule.get("units")
if un is not None:
if not isinstance(un, dict) or not all(_UNIT_RE.match(str(k)) for k in un):
errors.append(f"{label}.units must be an object of unit name → count")
else:
try:
out["units"] = {str(k): max(0, min(1000, int(v))) for k, v in un.items()}
except (TypeError, ValueError):
errors.append(f"{label}.units counts must be integers")
ow = rule.get("owned")
if ow is not None:
ok = isinstance(ow, dict) and all(isinstance(ow.get(k), str) and ow.get(k)
for k in ("group", "file", "key"))
if ok:
try:
ok = ow["group"] in re.compile(pat).groupindex
except re.error:
ok = False
if not ok or ".." in ow.get("file", "").split("/") or ow.get("file", "").startswith("/"):
errors.append(f"{label}.owned needs group (a named group of the path), file, key")
else:
out["owned"] = {"group": ow["group"], "file": ow["file"], "key": ow["key"]}
return out
def _ui_vis(raw: Any, where: str, errors: list[str]) -> dict[str, Any] | None:
"""A slot's / tool card's ``vis`` toggle: ``{key, label, hint, defaultOff?}``
(stored host-side as ``plugin:<pluginId>:<key>``)."""
if raw is None:
return None
if not isinstance(raw, dict):
errors.append(f"{where}.vis must be an object")
return None
key = str(raw.get("key") or "").strip()
if not _KEY_RE.match(key):
errors.append(f"{where}.vis.key invalid")
return None
if raw.get("defaultOff") is not None and not isinstance(raw.get("defaultOff"), bool):
errors.append(f"{where}.vis.defaultOff must be true or false")
out: dict[str, Any] = {
"key": key,
"label": str(raw.get("label") or key)[:48],
"hint": str(raw.get("hint") or "")[:160],
}
if raw.get("defaultOff") is True:
out["defaultOff"] = True
return out
def _menu_items(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""``ui.menuItems[]``: rows a plugin adds to a menu of the app —
``{id, where, label, icon?, html, height?, title?}``. A click opens the
item's ``html`` in a sandboxed dialog (docs/plugins.md → "Menu items and
dialogs")."""
if raw is None:
return []
if not isinstance(raw, list):
errors.append("ui.menuItems must be a list")
return []
if len(raw) > _MENU_ITEMS_MAX:
errors.append(f"ui.menuItems: at most {_MENU_ITEMS_MAX}")
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
for i, it in enumerate(raw):
where = f"ui.menuItems[{i}]"
if not isinstance(it, dict):
errors.append(f"{where} must be an object")
continue
mid = str(it.get("id") or "").strip()
if not _KEY_RE.match(mid) or mid in seen:
errors.append(f"{where}.id invalid or repeated")
continue
seen.add(mid)
place = str(it.get("where") or "")
if place not in _MENU_PLACES:
errors.append(f"{where}.where must be one of {sorted(_MENU_PLACES)}")
continue
label = str(it.get("label") or "").strip()
if not label or len(label) > 40:
errors.append(f"{where}.label must be 1..40 characters")
continue
if not it.get("html"):
errors.append(f"{where}.html required")
continue
_safe_rel(root, it.get("html"), f"{where}.html", errors)
item: dict[str, Any] = {"id": mid, "where": place, "label": label,
"html": str(it["html"])}
if it.get("icon") is not None:
ic = str(it.get("icon") or "").strip()
if not re.match(r"^[a-z0-9][a-z0-9-]{0,39}$", ic):
errors.append(f"{where}.icon must be a lucide icon name")
else:
item["icon"] = ic
if it.get("title") is not None:
ti = str(it.get("title") or "").strip()
if not ti or len(ti) > 60:
errors.append(f"{where}.title must be 1..60 characters")
else:
item["title"] = ti
if it.get("height") is not None:
try:
h = int(it["height"])
except (TypeError, ValueError):
h = 0
if not 80 <= h <= 900:
errors.append(f"{where}.height must be 80..900")
else:
item["height"] = h
out.append(item)
return out
def _ui_events(raw: Any, where: str, errors: list[str]) -> list[str] | None:
"""A frame's forwarded SSE event types, a subset of ``_UI_EVENTS``."""
if raw is None:
return None
if not isinstance(raw, list) or not all(isinstance(e, str) for e in raw):
errors.append(f"{where}.events must be a list of strings")
return None
bad = [e for e in raw if e not in _UI_EVENTS]
if bad:
errors.append(f"{where}.events: unknown {bad} (one of {sorted(_UI_EVENTS)})")
return None
out: list[str] = []
for e in raw:
if e not in out:
out.append(e)
return out or None
def _fences(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""``ui.fences[]``: a fenced block of an agent's message the plugin draws —
```` ```chart ```` → its sandboxed frame, ``init {fence, code, …}``
(docs/plugins.md → "Fenced blocks in messages"). ``{id, lang, html,
height?, label?, vis?}``; one language per fence, unique in the plugin."""
if raw is None:
return []
if not isinstance(raw, list):
errors.append("ui.fences must be a list")
return []
out: list[dict[str, Any]] = []
langs: set[str] = set()
for i, fe in enumerate(raw[:8]):
if not isinstance(fe, dict):
errors.append(f"ui.fences[{i}] must be an object")
continue
fid = str(fe.get("id") or "").strip()
if not _KEY_RE.match(fid):
errors.append(f"ui.fences[{i}].id invalid")
continue
lang = str(fe.get("lang") or "").strip()
if not _FENCE_LANG_RE.match(lang):
errors.append(f"ui.fences[{i}].lang must be 2-32 lowercase letters, digits, _ + -")
continue
if lang in _FENCE_RESERVED:
errors.append(f"ui.fences[{i}].lang '{lang}' is a code language (or the closing notify block)")
continue
if lang in langs:
errors.append(f"ui.fences[{i}].lang '{lang}' declared twice")
continue
langs.add(lang)
_safe_rel(root, fe.get("html"), f"ui.fences[{i}].html", errors)
height = fe.get("height", 240)
if not isinstance(height, int) or isinstance(height, bool) or not 40 <= height <= 1200:
errors.append(f"ui.fences[{i}].height must be an integer 40..1200")
height = 240
fe_out: dict[str, Any] = {
"id": fid,
"lang": lang,
"label": str(fe.get("label") or fid)[:60],
"html": str(fe.get("html") or ""),
"height": height,
}
fe_vis = _ui_vis(fe.get("vis"), f"ui.fences[{i}]", errors)
if fe_vis:
fe_out["vis"] = fe_vis
out.append(fe_out)
if isinstance(raw, list) and len(raw) > 8:
errors.append("ui.fences: at most 8")
return out
def validate_manifest(plugin_dir: pathlib.Path) -> dict[str, Any]:
"""Read and validate ``plugin_dir/plugin.json``. Returns the normalized
manifest dict or raises :class:`ManifestError`."""
root = pathlib.Path(plugin_dir)
mf = root / "plugin.json"
if not mf.is_file():
raise ManifestError(["plugin.json not found in plugin directory"])
try:
raw = json.loads(mf.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
raise ManifestError([f"plugin.json is not valid JSON: {e}"]) from None
if not isinstance(raw, dict):
raise ManifestError(["plugin.json must be a JSON object"])
errors: list[str] = []
unknown = sorted(set(raw) - _TOP_KEYS)
if unknown:
errors.append(f"unknown manifest keys: {', '.join(unknown)}")
if raw.get("schema") != SCHEMA_VERSION:
errors.append(f"schema must be {SCHEMA_VERSION}")
pid = str(raw.get("id") or "").strip()
if not _ID_RE.match(pid):
errors.append("id must be lowercase alphanumeric/dashes (1-48 chars)")
name = str(raw.get("name") or "").strip()
if not name or len(name) > 80:
errors.append("name is required (<= 80 chars)")
version = str(raw.get("version") or "1.0.0").strip()[:32]
description = str(raw.get("description") or "").strip()[:300]
art = _parse_art(root, raw, errors)
icon = art["icon"]
author = str(raw.get("author") or "").strip()[:64]
out: dict[str, Any] = {
"schema": SCHEMA_VERSION,
"id": pid,
"name": name,
"version": version,
"description": description,
"icon": icon,
"author": author,
"iconSvg": art["iconSvg"],
"illustration": art["illustration"],
"color": art["color"],
"readme": art["readme"],
"artVersion": art["artVersion"],
}
# ── skill ────────────────────────────────────────────────────────────────
if raw.get("skill") is not None:
sk = raw["skill"]
if not isinstance(sk, dict):
errors.append("skill must be an object")
else:
sdir = str(sk.get("dir") or "skill")
sname = str(sk.get("name") or pid).strip()
if not _SKILL_RE.match(sname):
errors.append("skill.name must be lowercase alphanumeric/._- (1-48 chars)")
target = _safe_rel(root, sdir, "skill.dir", errors, want_dir=True)
if target and not (target / "SKILL.md").is_file():
errors.append(f"skill.dir '{sdir}' must contain SKILL.md")
out["skill"] = {"dir": sdir, "name": sname}
# ── secrets ──────────────────────────────────────────────────────────────
secret_keys: set[str] = set()
secrets_out: list[dict[str, Any]] = []
if raw.get("secrets") is not None:
if not isinstance(raw["secrets"], list):
errors.append("secrets must be an array")
else:
for i, s in enumerate(raw["secrets"]):
if not isinstance(s, dict):
errors.append(f"secrets[{i}] must be an object")
continue
key = str(s.get("key") or "").strip()
if not _KEY_RE.match(key):
errors.append(f"secrets[{i}].key invalid: {key!r}")
continue
if key in secret_keys:
errors.append(f"duplicate secret key: {key}")
continue
scope = str(s.get("scope") or "user")
if scope not in _SECRET_SCOPES:
errors.append(f"secrets[{i}].scope must be 'user' or 'hub'")
continue
secret_keys.add(key)
secrets_out.append({
"key": key,
"label": str(s.get("label") or key)[:80],
"placeholder": str(s.get("placeholder") or "")[:80],
"help": str(s.get("help") or "")[:300],
"scope": scope,
"required": bool(s.get("required", True)),
})
out["secrets"] = secrets_out
# ── actions (v3) ─────────────────────────────────────────────────────────
actions_out: dict[str, dict[str, Any]] = {}
if raw.get("actions") is not None:
if not isinstance(raw["actions"], dict):
errors.append("actions must be an object")
else:
for ak, av in raw["actions"].items():
if not _KEY_RE.match(str(ak)):
errors.append(f"actions.{ak}: invalid action name")
continue
if not isinstance(av, dict):
errors.append(f"actions.{ak}: must be an object")
continue
script = av.get("script")
_safe_rel(root, script, f"actions.{ak}.script", errors)
timeout = int(av.get("timeoutSec") or 30)
if not 1 <= timeout <= 1200:
errors.append(f"actions.{ak}.timeoutSec must be 1..1200")
act_item: dict[str, Any] = {
"script": str(script or ""),
"timeoutSec": timeout,
"description": str(av.get("description") or "")[:200],
}
if av.get("ownerOnly") is True:
act_item["ownerOnly"] = True
# Reads only: also callable by GET, so a read-only account
# (the screenshot bot) sees the data a plugin page lists.
if av.get("readOnly") is True:
act_item["readOnly"] = True
run_as = av.get("runAs")
if run_as is not None:
if str(run_as) not in ("caller", "owner"):
errors.append(f"actions.{ak}.runAs must be 'caller' or 'owner'")
elif str(run_as) == "owner":
act_item["runAs"] = "owner"
actions_out[str(ak)] = act_item
out["actions"] = actions_out
# ── settings (declarative) ───────────────────────────────────────────────
if raw.get("settings") is not None:
st = raw["settings"]
if not isinstance(st, dict):
errors.append("settings must be an object")
else:
fields_out: list[dict[str, Any]] = []
seen_fk: set[str] = set()
for i, f in enumerate(st.get("fields") or []):
if not isinstance(f, dict):
errors.append(f"settings.fields[{i}] must be an object")
continue
fk = str(f.get("key") or "").strip()
ft = str(f.get("type") or "text")
if not _KEY_RE.match(fk) or fk in seen_fk:
errors.append(f"settings.fields[{i}].key invalid or duplicate")
continue
if ft not in _FIELD_TYPES:
errors.append(f"settings.fields[{i}].type must be one of {sorted(_FIELD_TYPES)}")
continue
seen_fk.add(fk)
item = {
"key": fk,
"label": str(f.get("label") or fk)[:80],
"type": ft,
"help": str(f.get("help") or "")[:300],
"default": f.get("default"),
"required": bool(f.get("required", False)),
}
if ft == "select":
opts = f.get("options") or []
if not isinstance(opts, list) or not opts:
errors.append(f"settings.fields[{i}].options required for select")
item["options"] = opts
fields_out.append(item)
test_act = st.get("testAction")
status_act = st.get("statusAction")
if test_act and test_act not in actions_out and test_act != "inspect":
errors.append(f"settings.testAction '{test_act}' is not in actions (or 'inspect')")
if status_act and status_act not in actions_out:
errors.append(f"settings.statusAction '{status_act}' is not in actions")
links_out: list[dict[str, str]] = []
links_raw = st.get("links")
if links_raw is not None and not isinstance(links_raw, list):
errors.append("settings.links must be a list")
links_raw = []
for i, ln in enumerate(links_raw or []):
if not isinstance(ln, dict):
errors.append(f"settings.links[{i}] must be an object")
continue
label = str(ln.get("label") or "").strip()[:60]
url = str(ln.get("url") or "").strip()
if not label:
errors.append(f"settings.links[{i}].label is required")
continue
if not _LINK_URL_RE.match(url) or len(url) > 500:
errors.append(f"settings.links[{i}].url must be an https:// URL "
"(with optional {{config.<key>}} placeholders)")
continue
bad = [k for k in _LINK_VAR_RE.findall(url) if k not in seen_fk]
if bad:
errors.append(f"settings.links[{i}].url names unknown settings field(s): "
f"{', '.join(bad)}")
continue
links_out.append({"label": label, "url": url})
if len(links_out) > 12:
errors.append("settings.links: at most 12 links")
out["settings"] = {
"subtitle": str(st.get("subtitle") or "")[:140],
"instructions": str(st.get("instructions") or "")[:12000],
"fields": fields_out,
"links": links_out[:12],
"testAction": str(test_act) if test_act else None,
"statusAction": str(status_act) if status_act else None,
}
# ── proxy (v1) ───────────────────────────────────────────────────────────
if raw.get("proxy") is not None:
pr = raw["proxy"]
if not isinstance(pr, dict):
errors.append("proxy must be an object")
else:
base = str(pr.get("baseUrl") or "").strip().rstrip("/")
internal = bool(pr.get("internal", False))
parts = urlsplit(base)
if not parts.scheme or not parts.hostname:
errors.append("proxy.baseUrl must be a valid URL")
elif not internal and parts.scheme != "https":
errors.append("proxy.baseUrl must use https:// (set internal: true for local services)")
elif internal and parts.scheme not in ("http", "https"):
errors.append("proxy.baseUrl must use http:// or https://")
auth_out = None
if pr.get("auth") is not None:
a = pr["auth"]
if not isinstance(a, dict):
errors.append("proxy.auth must be an object")
else:
ain = str(a.get("in") or "header")
asec = str(a.get("secret") or "")
if ain not in _AUTH_INS:
errors.append(f"proxy.auth.in must be one of {sorted(_AUTH_INS)}")
if asec and asec not in secret_keys:
errors.append(f"proxy.auth.secret '{asec}' not declared in secrets")
auth_out = {
"in": ain,
"name": str(a.get("name") or "Authorization")[:64],
"prefix": str(a.get("prefix") or ""),
"secret": asec,
"username": str(a.get("username") or ""),
}
allow_out: list[dict[str, str]] = []
allow = pr.get("allow") or []
if not isinstance(allow, list) or not allow:
errors.append("proxy.allow must be a non-empty array of {method, path}")
else:
for i, rule in enumerate(allow):
if not isinstance(rule, dict):
errors.append(f"proxy.allow[{i}] must be an object")
continue
method = str(rule.get("method") or "GET").upper()
if method not in _METHODS:
errors.append(f"proxy.allow[{i}].method invalid: {method}")
continue
pat = _check_regex(rule.get("path"), f"proxy.allow[{i}].path", errors)
if pat:
allow_out.append(_clean_rule(rule, method, pat, f"proxy.allow[{i}]", errors))
headers_out = {}
if pr.get("headers") is not None:
if not isinstance(pr["headers"], dict):
errors.append("proxy.headers must be an object")
else:
headers_out = {str(k): str(v) for k, v in pr["headers"].items()}
inspect_out = None
if pr.get("inspect") is not None:
ins = pr["inspect"]
if not isinstance(ins, dict) or not ins.get("path"):
errors.append("proxy.inspect must be an object with 'path'")
else:
im = str(ins.get("method") or "GET").upper()
if im not in _METHODS:
errors.append(f"proxy.inspect.method invalid: {im}")
inspect_out = {
"method": im,
"path": str(ins["path"]).lstrip("/"),
"params": dict(ins.get("params") or {}),
"requireOnlyScopes": [str(s) for s in (ins.get("requireOnlyScopes") or [])],
}
stream = bool(pr.get("stream", False))
max_cap = 2 * 1024 * 1024 * 1024 if (stream and internal) else 250 * 1024 * 1024
max_bytes = int(pr.get("maxBytes") or 20 * 1024 * 1024)
if not 1024 <= max_bytes <= max_cap:
errors.append(f"proxy.maxBytes must be between 1 KB and {max_cap // (1024 * 1024)} MB")
strip_keys: list[str] = []
if pr.get("stripResponseKeys") is not None:
if not isinstance(pr["stripResponseKeys"], list):
errors.append("proxy.stripResponseKeys must be an array of field names")
else:
strip_keys = [str(k).strip() for k in pr["stripResponseKeys"] if str(k).strip()][:50]
# A Dynamic service the homelab's services-manager stops when idle:
# the proxy wakes it before calling (plugins/proxy.ensure_awake).
# Internal only — a public API has nothing to wake.
wake_out = None
if pr.get("wake") is not None:
wk = pr["wake"]
if not internal:
errors.append("proxy.wake needs internal: true")
elif not isinstance(wk, dict):
errors.append("proxy.wake must be an object {service, holdMinutes}")
else:
svc = str(wk.get("service") or "")
if not _WAKE_SERVICE_RE.fullmatch(svc):
errors.append("proxy.wake.service must match ^[a-z0-9][a-z0-9_.-]{0,62}$")
hold = wk.get("holdMinutes", 15)
if isinstance(hold, bool) or not isinstance(hold, int) or not 1 <= hold <= 240:
errors.append("proxy.wake.holdMinutes must be an integer 1..240")
hold = 15
wake_out = {"service": svc, "holdMinutes": hold}
out["proxy"] = {
"baseUrl": base,
"internal": internal,
"stream": stream,
"auth": auth_out,
"headers": headers_out,
"allow": allow_out,
"denyParams": [str(p).lower() for p in (pr.get("denyParams") or [])],
"stripResponseKeys": strip_keys,
"scrubSecrets": bool(pr.get("scrubSecrets", True)),
"maxBytes": max_bytes,
"inspect": inspect_out,
"handlerOnly": bool(pr.get("handlerOnly", False)),
"wake": wake_out,
}
# ── storage (v1) ─────────────────────────────────────────────────────────
st_cfg = raw.get("storage") or {}
if not isinstance(st_cfg, dict):
errors.append("storage must be an object")
st_cfg = {}
max_mb = int(st_cfg.get("maxMb") or 50)
if not 1 <= max_mb <= 500:
errors.append("storage.maxMb must be 1..500")
out["storage"] = {"maxMb": max_mb}
# ── schedules (v1) ───────────────────────────────────────────────────────
sched_out: list[dict[str, Any]] = []
seen_sc: set[str] = set()
for i, sc in enumerate(raw.get("schedules") or []):
if not isinstance(sc, dict):
errors.append(f"schedules[{i}] must be an object")
continue
sid = str(sc.get("id") or f"job-{i}").strip()
if not _KEY_RE.match(sid) or sid in seen_sc:
errors.append(f"schedules[{i}].id invalid or duplicate")
continue
seen_sc.add(sid)
cron_expr = _check_cron(sc.get("cron"), f"schedules[{i}].cron", errors)
script = sc.get("script")
_safe_rel(root, script, f"schedules[{i}].script", errors)
timeout = int(sc.get("timeoutSec") or 180)
if not 5 <= timeout <= 900:
errors.append(f"schedules[{i}].timeoutSec must be 5..900")
sched_out.append({
"id": sid,
"cron": cron_expr or "",
"script": str(script or ""),
"timeoutSec": timeout,
"description": str(sc.get("description") or "")[:200],
})
out["schedules"] = sched_out
# ── ui (v2 + v3 slots) ───────────────────────────────────────────────────
ui_raw = raw.get("ui")
if ui_raw is not None:
if not isinstance(ui_raw, dict):
errors.append("ui must be an object")
else:
ui_out: dict[str, Any] = {"pages": [], "toolCards": [], "slots": []}
overlays = _overlays(root, ui_raw.get("overlays"), errors)
if overlays:
ui_out["overlays"] = overlays
prefs = _prefs(ui_raw.get("prefs"), errors)
if prefs:
ui_out["prefs"] = prefs
if ui_raw.get("settingsHtml"):
_safe_rel(root, ui_raw["settingsHtml"], "ui.settingsHtml", errors)
ui_out["settingsHtml"] = str(ui_raw["settingsHtml"])
for i, pg in enumerate(ui_raw.get("pages") or []):
if not isinstance(pg, dict):
errors.append(f"ui.pages[{i}] must be an object")
continue
pgid = str(pg.get("id") or "").strip()
if not _ID_RE.match(pgid):
errors.append(f"ui.pages[{i}].id invalid")
continue
nav = str(pg.get("nav") or "dashboards")
if nav not in _NAV_GROUPS:
errors.append(f"ui.pages[{i}].nav must be one of {sorted(_NAV_GROUPS)}")
_safe_rel(root, pg.get("html"), f"ui.pages[{i}].html", errors)
page_out = {
"id": pgid,
"label": str(pg.get("label") or pgid)[:60],
"nav": nav,
"icon": str(pg.get("icon") or icon)[:40],
"html": str(pg.get("html") or ""),
}
# A full-page canvas: the frame fills the page below its header
# instead of growing with its content. Only written when set —
# ``ui`` is in the approval fingerprint.
if pg.get("fill") is True:
page_out["fill"] = True
if pg.get("subpath") is True:
page_out["subpath"] = True
ui_out["pages"].append(page_out)
for i, tc in enumerate(ui_raw.get("toolCards") or []):
if not isinstance(tc, dict):
errors.append(f"ui.toolCards[{i}] must be an object")
continue
tcid = str(tc.get("id") or "").strip()
if not _KEY_RE.match(tcid):
errors.append(f"ui.toolCards[{i}].id invalid")
continue
match = tc.get("match") or {}
if not isinstance(match, dict) or not match.get("tool"):
errors.append(f"ui.toolCards[{i}].match.tool required")
if match.get("commandRegex"):
_check_regex(match["commandRegex"], f"ui.toolCards[{i}].match.commandRegex", errors)
if match.get("filePathRegex"):
_check_regex(match["filePathRegex"], f"ui.toolCards[{i}].match.filePathRegex", errors)
_safe_rel(root, tc.get("html"), f"ui.toolCards[{i}].html", errors)
match_out: dict[str, Any] = {
"tool": str(match.get("tool") or ""),
"commandRegex": str(match.get("commandRegex") or ""),
}
if match.get("filePathRegex"):
match_out["filePathRegex"] = str(match["filePathRegex"])
if match.get("hasField") is not None:
hf = str(match.get("hasField") or "")
if hf not in _HAS_FIELDS:
errors.append(f"ui.toolCards[{i}].match.hasField must be one of {sorted(_HAS_FIELDS)}")
else:
match_out["hasField"] = hf
tc_out: dict[str, Any] = {
"id": tcid,
"label": str(tc.get("label") or tcid)[:60],
"match": match_out,
"html": str(tc.get("html") or ""),
"height": int(tc.get("height") or 180),
}
if tc.get("replace") is True:
tc_out["replace"] = True
if tc.get("verb"):
tc_out["verb"] = str(tc["verb"])[:40]
# Stands in the chat where its call happened instead of inside
# the call's row (which folds away with the tools); `keyRegex`
# (its first non-empty group, over the command + the output)
# keeps one card per key — a later call on it is a plain row.
if tc.get("inThread") is not None and not isinstance(tc.get("inThread"), bool):
errors.append(f"ui.toolCards[{i}].inThread must be true or false")
elif tc.get("inThread"):
tc_out["inThread"] = True
if tc.get("keyRegex"):
kr = _check_regex(tc["keyRegex"], f"ui.toolCards[{i}].keyRegex", errors)
if kr:
try:
groups = re.compile(kr).groups
except re.error:
groups = 0
if not groups:
errors.append(f"ui.toolCards[{i}].keyRegex needs a capture group (the key)")
elif not tc.get("inThread"):
errors.append(f"ui.toolCards[{i}].keyRegex only applies with inThread: true")
else:
tc_out["keyRegex"] = kr
# Optional keys are only written when set: ``ui`` is in the
# approval fingerprint.
tc_vis = _ui_vis(tc.get("vis"), f"ui.toolCards[{i}]", errors)
if tc_vis:
tc_out["vis"] = tc_vis
tc_ev = _ui_events(tc.get("events"), f"ui.toolCards[{i}]", errors)
if tc_ev:
tc_out["events"] = tc_ev
ui_out["toolCards"].append(tc_out)
for i, sl in enumerate(ui_raw.get("slots") or []):
if not isinstance(sl, dict):
errors.append(f"ui.slots[{i}] must be an object")
continue
slid = str(sl.get("id") or "").strip()
where = str(sl.get("where") or "")
if not _KEY_RE.match(slid) or where not in _SLOT_PLACES:
errors.append(f"ui.slots[{i}]: invalid id or where ({sorted(_SLOT_PLACES)})")
continue
_safe_rel(root, sl.get("html"), f"ui.slots[{i}].html", errors)
sl_out: dict[str, Any] = {
"id": slid,
"where": where,
"html": str(sl.get("html") or ""),
"height": int(sl.get("height") or 120),
}
# Optional keys only when set (approval fingerprint).
if sl.get("label") is not None:
lab = str(sl.get("label") or "").strip()
if not lab or len(lab) > 48:
errors.append(f"ui.slots[{i}].label must be 1..48 characters")
else:
sl_out["label"] = lab
if sl.get("defaultStashed") is not None:
if not isinstance(sl.get("defaultStashed"), bool):
errors.append(f"ui.slots[{i}].defaultStashed must be true or false")
elif sl["defaultStashed"]:
sl_out["defaultStashed"] = True
sl_vis = _ui_vis(sl.get("vis"), f"ui.slots[{i}]", errors)
if sl_vis:
sl_out["vis"] = sl_vis
sl_ev = _ui_events(sl.get("events"), f"ui.slots[{i}]", errors)
if sl_ev:
sl_out["events"] = sl_ev
if sl.get("icon") is not None:
ic = str(sl.get("icon") or "").strip()
if where not in _ICON_SLOTS or not _LUCIDE_RE.match(ic):
errors.append(f"ui.slots[{i}].icon: a lucide name, on {sorted(_ICON_SLOTS)} only")
else:
sl_out["icon"] = ic
if sl.get("badge") is not None:
bd = str(sl.get("badge") or "")
if where != "conversations.drawer":
errors.append(f"ui.slots[{i}].badge: only on conversations.drawer")
elif not (actions_out.get(bd) or {}).get("readOnly"):
errors.append(f"ui.slots[{i}].badge must name a declared readOnly action")
else:
sl_out["badge"] = bd
ui_out["slots"].append(sl_out)
menu_items = _menu_items(root, ui_raw.get("menuItems"), errors)
if menu_items: # only when set: ``ui`` is in the approval fingerprint
ui_out["menuItems"] = menu_items
fences = _fences(root, ui_raw.get("fences"), errors)
if fences:
ui_out["fences"] = fences
out["ui"] = ui_out
# ── requires / exports / emits (plugin-to-plugin dependencies) ───────────
requires_out: list[str] = []
if raw.get("requires") is not None:
if not isinstance(raw["requires"], list):
errors.append("requires must be a list of plugin ids")
else:
seen_req: set[str] = set()
for i, dep in enumerate(raw["requires"]):
d = str(dep or "").strip()
if not _ID_RE.match(d):
errors.append(f"requires[{i}]: invalid plugin id {dep!r}")
continue
if d == pid:
errors.append(f"requires[{i}]: plugin cannot require itself")
continue
if d not in seen_req:
seen_req.add(d)
requires_out.append(d)
if requires_out:
out["requires"] = requires_out
exports_out: list[str] = []
if raw.get("exports") is not None:
if not isinstance(raw["exports"], list):
errors.append("exports must be a list of action names")
else:
seen_exp: set[str] = set()
for i, ex in enumerate(raw["exports"]):
name_ex = str(ex or "").strip()
if name_ex not in actions_out:
errors.append(f"exports[{i}]: '{name_ex}' is not a declared action")
continue
if name_ex not in seen_exp:
seen_exp.add(name_ex)
exports_out.append(name_ex)
if exports_out:
out["exports"] = exports_out
emits_out: list[str] = []
if raw.get("emits") is not None:
if not isinstance(raw["emits"], list):
errors.append("emits must be a list of event names")
else:
seen_em: set[str] = set()
for i, em in enumerate(raw["emits"]):
evn = str(em or "").strip()
if not _EVENT_NAME_RE.match(evn):
errors.append(f"emits[{i}]: invalid event name {em!r}")
continue
if evn not in seen_em:
seen_em.add(evn)
emits_out.append(evn)
if emits_out:
out["emits"] = emits_out
# ── agents (declarative Claude --agents contributions) ───────────────────
pref_keys = {p["key"] for p in ((out.get("ui") or {}).get("prefs") or [])}
agents_out: list[dict[str, Any]] = []
if raw.get("agents") is not None:
if not isinstance(raw["agents"], list):
errors.append("agents must be a list")
else:
seen_ag: set[str] = set()
for i, ag in enumerate(raw["agents"][:5]):
if not isinstance(ag, dict):
errors.append(f"agents[{i}] must be an object")
continue
aname = str(ag.get("name") or "").strip()
if not _KEY_RE.match(aname) or aname in seen_ag:
errors.append(f"agents[{i}].name invalid or duplicate")
continue
desc = str(ag.get("description") or "").strip()[:2000]
if not desc:
errors.append(f"agents[{i}].description is required")
continue
pf = ag.get("promptFile")
target_pf = _safe_rel(root, pf, f"agents[{i}].promptFile", errors)
if target_pf and target_pf.stat().st_size > 64 * 1024:
errors.append(f"agents[{i}].promptFile exceeds 64 KB")
continue
tools = [str(t_name)[:64] for t_name in (ag.get("tools") or []) if isinstance(t_name, str) and t_name.strip()][:32]
item_ag: dict[str, Any] = {
"name": aname,
"description": desc,
"promptFile": str(pf or ""),
"tools": tools,
}
if ag.get("omitClaudeMd") is True:
item_ag["omitClaudeMd"] = True
for pk_field in ("enabledPref", "modelPref", "effortPref"):
if ag.get(pk_field):
pkv = str(ag[pk_field]).strip()
if pkv not in pref_keys:
errors.append(f"agents[{i}].{pk_field} '{pkv}' not declared in ui.prefs")
else:
item_ag[pk_field] = pkv
if ag.get("defaultModel"):
item_ag["defaultModel"] = str(ag["defaultModel"]).strip()[:40]
if ag.get("defaultEffort"):
item_ag["defaultEffort"] = str(ag["defaultEffort"]).strip()[:20]
seen_ag.add(aname)
agents_out.append(item_ag)
if agents_out:
out["agents"] = agents_out
# ── events (v2 outbound + plugin:<dep>:<event>) ──────────────────────────
events_out: list[dict[str, Any]] = []
req_set = set(requires_out)
for i, ev in enumerate(raw.get("events") or []):
if not isinstance(ev, dict):
errors.append(f"events[{i}] must be an object")
continue
eid = str(ev.get("id") or f"ev-{i}").strip()
on = [str(x) for x in (ev.get("on") or [])]
bad_ev = []
for ev_name in on:
if ev_name in _EVENT_TYPES:
continue
m_pe = _PLUGIN_EVENT_RE.match(ev_name)
if m_pe and m_pe.group(1) in req_set:
continue
bad_ev.append(ev_name)
if not on or bad_ev:
errors.append(f"events[{i}].on has unknown events {bad_ev} (allowed: {sorted(_EVENT_TYPES)} or plugin:<required-id>:<event>)")
url = str(ev.get("url") or "").strip()
act = str(ev.get("action") or "").strip()
if not url and not act:
errors.append(f"events[{i}] needs 'url' or 'action'")
if act and act not in actions_out:
errors.append(f"events[{i}].action '{act}' not in actions")
if ev.get("secret") and ev["secret"] not in secret_keys:
errors.append(f"events[{i}].secret '{ev['secret']}' not in secrets")
events_out.append({
"id": eid, "on": on, "url": url,
"secret": str(ev.get("secret") or ""),
"action": act,
"internal": bool(ev.get("internal", False)),
})
out["events"] = events_out
# ── webhooks (v2 inbound) ────────────────────────────────────────────────
hooks_out: list[dict[str, Any]] = []
seen_wh: set[str] = set()
for i, wh in enumerate(raw.get("webhooks") or []):
if not isinstance(wh, dict):
errors.append(f"webhooks[{i}] must be an object")
continue
wid = str(wh.get("id") or "").strip()
mode = str(wh.get("mode") or "notify")
if not _ID_RE.match(wid) or wid in seen_wh:
errors.append(f"webhooks[{i}].id invalid or duplicate")
continue
if mode not in _WEBHOOK_MODES:
errors.append(f"webhooks[{i}].mode must be one of {sorted(_WEBHOOK_MODES)}")
continue
act = str(wh.get("action") or "").strip()
if mode == "action" and act not in actions_out:
errors.append(f"webhooks[{i}].action '{act}' not in actions")
seen_wh.add(wid)
hooks_out.append({
"id": wid,
"mode": mode,
"titleTemplate": str(wh.get("titleTemplate") or f"{name}: {{{{title}}}}")[:120],
"promptTemplate": str(wh.get("promptTemplate") or "{{body}}")[:2000],
"action": act,
"description": str(wh.get("description") or "")[:200],
"internalOnly": bool(wh.get("internalOnly", False)),
})
out["webhooks"] = hooks_out
# ── resources (conversation resource kinds — plugins/resources.py) ───────
out["resources"] = _resources(raw.get("resources"), errors)
# ── harnessHooks (hooks in the agent harness — plugins/harness_hooks.py) ─
from plugins import harness_hooks
hh = harness_hooks.parse(root, raw.get("harnessHooks"), errors)
if hh:
out["harnessHooks"] = hh
# ── provides (data the host merges into its own answers) ─────────────────
prov_raw = raw.get("provides") or {}
prov_out: dict[str, str] = {}
if not isinstance(prov_raw, dict):
errors.append("provides must be an object")
else:
for name, act in prov_raw.items():
if name not in _PROVIDES:
errors.append(f"provides.{name}: unknown (one of {sorted(_PROVIDES)})")
elif not isinstance(act, str) or act not in actions_out:
errors.append(f"provides.{name}: must name a declared action")
else:
prov_out[name] = act
out["provides"] = prov_out
# ── commands (the ai-agent CLI + MCP tools, over declared actions) ───────
from plugins import commands as plugin_commands
cmds = plugin_commands.parse(raw.get("commands"), pid, actions_out, errors)
if cmds:
out["commands"] = cmds
# ── capabilities ─────────────────────────────────────────────────────────
caps = [str(c) for c in (raw.get("capabilities") or [])]
bad_caps = sorted(set(caps) - _CAPABILITIES)
if bad_caps:
errors.append(f"unknown capabilities: {', '.join(bad_caps)}")
out["capabilities"] = sorted(set(caps))
# ── managed (hub-owned, granted per guest) ───────────────────────────────
if raw.get("managed") is not None:
mg = raw["managed"]
if not isinstance(mg, dict):
errors.append("managed must be an object")
else:
grant_fields: list[dict[str, Any]] = []
seen_gf: set[str] = set()
for i, f in enumerate(mg.get("grantFields") or []):
if not isinstance(f, dict):
errors.append(f"managed.grantFields[{i}] must be an object")
continue
fk = str(f.get("key") or "").strip()
ft = str(f.get("type") or "checkbox")
if not _KEY_RE.match(fk) or fk in seen_gf:
errors.append(f"managed.grantFields[{i}].key invalid or duplicate")
continue
if ft not in _FIELD_TYPES:
errors.append(f"managed.grantFields[{i}].type invalid: {ft}")
continue
seen_gf.add(fk)
gf_item: dict[str, Any] = {
"key": fk,
"label": str(f.get("label") or fk)[:80],
"type": ft,
"help": str(f.get("help") or "")[:300],
"default": f.get("default"),
}
if ft == "select":
gf_item["options"] = list(f.get("options") or [])
grant_fields.append(gf_item)
lim_raw = mg.get("limits") or {}
if not isinstance(lim_raw, dict):
errors.append("managed.limits must be an object")
lim_raw = {}
limits_out: dict[str, Any] = {}
if lim_raw.get("inFlight") is not None:
limits_out["inFlight"] = max(1, min(64, int(lim_raw["inFlight"])))
if lim_raw.get("jobsPerDay") is not None:
limits_out["jobsPerDay"] = max(1, min(10000, int(lim_raw["jobsPerDay"])))
if lim_raw.get("defaultMonthlyBudgetUsd") is not None:
limits_out["defaultMonthlyBudgetUsd"] = max(0.0, float(lim_raw["defaultMonthlyBudgetUsd"]))
kh_raw = mg.get("keyHealth")
kh_out = None
if kh_raw is not None and not isinstance(kh_raw, dict):
errors.append("managed.keyHealth must be an object")
elif isinstance(kh_raw, dict):
kh_out = _key_health(kh_raw, raw, errors)
out["managed"] = {
"defaultForGuests": bool(mg.get("defaultForGuests", False)),
"allowUserSecretOverride": bool(mg.get("allowUserSecretOverride", False)),
"metered": bool(mg.get("metered", False)),
"grantFields": grant_fields,
"limits": limits_out,
"keyHealth": kh_out,
}
# ── kind + provider / harness (typed plugins) ────────────────────────────
from plugins.typed_manifest import parse_typed
out.update(parse_typed(root, raw, pid, secret_keys, errors))
if errors:
raise ManifestError(errors)
return out
_LINK_URL_RE = re.compile(r"^https://[^\s<>\"']+$")
_LINK_VAR_RE = re.compile(r"\{\{\s*config\.([A-Za-z0-9_]+)\s*\}\}")
_TOOL_RE = re.compile(r"^[a-z0-9][a-z0-9:_-]{0,63}$")
def _key_health(kh_raw: dict[str, Any], raw: dict[str, Any], errors: list[str]) -> dict[str, Any]:
"""``managed.keyHealth``: the hub key's monthly alert line (``alertLimit``
+ ``currency``; ``alertLimitEur`` is the older spelling), when to push,
which hub secret is the key (``secretKey``, default: the first
``scope: "hub"`` secret) and the pre-plugin ledger tool whose rows count
as this plugin's (``legacyLedgerTool``)."""
cur = str(kh_raw.get("currency") or "EUR").upper()
if cur not in ("EUR", "USD"):
errors.append("managed.keyHealth.currency must be EUR or USD")
cur = "EUR"
limit = kh_raw.get("alertLimit")
if limit is None:
limit = kh_raw.get("alertLimitEur", 20.0)
if "alertLimitEur" in kh_raw and "currency" not in kh_raw:
cur = "EUR"
try:
limit_f = max(0.0, min(100000.0, float(limit)))
except (TypeError, ValueError):
errors.append("managed.keyHealth.alertLimit must be a number")
limit_f = 20.0
hub_secrets = [str(s.get("key")) for s in (raw.get("secrets") or [])
if isinstance(s, dict) and s.get("scope") == "hub"]
secret_key = kh_raw.get("secretKey")
if secret_key is not None:
secret_key = str(secret_key)
if secret_key not in hub_secrets:
errors.append(f"managed.keyHealth.secretKey '{secret_key}' is not a hub-scoped secret")
else:
secret_key = hub_secrets[0] if hub_secrets else None
legacy = kh_raw.get("legacyLedgerTool")
if legacy is not None:
legacy = str(legacy)
if not _TOOL_RE.match(legacy) or legacy.startswith("plugin:"):
errors.append("managed.keyHealth.legacyLedgerTool must be a plain ledger tool id")
legacy = None
return {
"alertLimit": round(limit_f, 2),
"currency": cur,
"pushAtPct": max(1, min(100, int(kh_raw.get("pushAtPct", 80)))),
"pushOnBreak": bool(kh_raw.get("pushOnBreak", True)),
"secretKey": secret_key,
"legacyLedgerTool": legacy,
}
def requires_operator(manifest: dict[str, Any]) -> bool:
"""True when the manifest asks for host/internal capabilities only the
operator may approve."""
# A model provider prices and bills every conversation; a harness ships
# code the sidecar runs on every machine — the operator's call only.
if manifest.get("kind") in ("provider", "harness"):
return True
if manifest.get("managed"):
return True
# a script hook is plugin code every machine's harness runs
from plugins.harness_hooks import has_script
if has_script(manifest):
return True
pr = manifest.get("proxy") or {}
if pr.get("internal"):
return True
if any(s.get("scope") == "hub" for s in (manifest.get("secrets") or [])):
return True
if any(ev.get("internal") for ev in (manifest.get("events") or [])):
return True
if any(c in _OPERATOR_CAPS and c != "conversations.spawn"
for c in (manifest.get("capabilities") or [])):
return True
return False
_OVERLAY_LABELS = {
"conversation": "Draws a transparent overlay on conversation pages — it sees the conversation's colour, state and lifecycle stamps and the page's box outlines, never its text",
"home": "Draws a transparent overlay on the home page — it sees the running conversations' colours and states and the page's box outlines, never their text",
}
_CAP_LABELS = {
"footprint.read": "Reads every conversation's estimated carbon, water and energy, with its model and projects (the operator's only)",
"telemetry.read": "Reads the hub's own telemetry: which pages and features people used, by whom, on which device, and where conversations started (the operator's only)",
"analytics.read": "Reads how many conversations ran and how long they worked, by model, harness, project, machine, person and origin — never costs (the operator's only)",
"graph.read": "Reads the lab's projects, services, conversations, subagents, plans and memories as graph nodes (the operator's only)",
"services.read": "Reads the host's services folder (compose and Traefik files, read-only; the operator's runs only)",
"runs.start": "Starts conversations as you — any model, machine, lean run or EVOX2 fallback (the operator's only)",
"conversations.send": "Sends a message into your conversations (the operator's only)",
"conversations.reply": "Posts an app-tagged turn into a conversation, preserving its owner/guest scope",
"models.read": "Reads the model catalogue and Settings → Models presets",
"complete.run": "Asks any model for one short answer (no tools, no transcript), billed to your logins (the operator's only)",
"conversations.label": "Reads your conversations' titles and first prompts, and writes their action badges and short titles (the operator's only)",
"conversations.title": "Asks your title plugin for a prompt's title (the operator's only)",
"workers.read": "Lists your machines and what each can run",
"askform.bridge": "Creates, reads and manages forms on the hub's ask-form mirror",
"users.read": "Reads user names, languages, web addresses and project grants",
"scaffold.run": "Scaffolds new projects on the host, grants access and relocates conversations into them",
"plans.read": "Reads implementation plan files under data/plans/ (the operator's only)",
"plans.write": "Updates implementation plan files under data/plans/ (the operator's only)",
"templates.read": "Reads the project scaffolding templates folder (read-only; the operator's runs only)",
"memories.read": "Reads Claude's memories folder (read-only; the operator's runs only)",
"projects.env": "Reads and writes the projects' .env files, secrets included (the operator's runs only)",
"activity.read": "Reads agent activity: 5-minute concurrency bins, subagents, tokens and cost per day (the operator's only)",
"usage.read": "Reads each plan's usage limits: the live /usage %, its history, the plans and the calibration's exchange rate (the operator's only)",
"usage.calibrate": "Refits the plan calibration (plan units and list $ per 1% of each window) now (the operator's only)",
"perf.read": "Reads the CPU, memory and disk use of every agent run and of the processes it started, on every machine (the operator's only)",
"perf.act": "Stops the processes ended conversations left running, keeps them from the auto-kill, removes scratch dirs and worktrees on a machine, measures its disk and changes those settings (the operator's handlers only)",
"ship.run": "Deploys projects to their hosts through the host's zipgo broker and reads their deploy configs (the operator's handlers only)",
"machines.mcp": "Lists your machines and reads, adds, removes and signs in the MCP servers of each one's harness logins (the operator's handlers only)",
"machines.wake": "Sends Wake-on-LAN packets onto your LAN from the host and checks whether your machines came up (the operator's handlers only)",
"relay.serve": "Serves authenticated relays from your machines to upstreams it holds the credentials of — the hub gateway (the operator's handlers only)",
"conversations.data": "Reads and writes its own notes on your conversations (links between them, shown in the thread; the operator's handlers only)",
}
def capability_summary(manifest: dict[str, Any]) -> list[dict[str, Any]]:
"""Plain-language capability bullets shown in the install consent card."""
items: list[dict[str, Any]] = []
if pv := manifest.get("provider"):
n_acc = len(pv.get("accounts") or [])
items.append({"kind": "provider", "privileged": True,
"label": f"Model provider `{pv['vendorId']}`: {len(pv.get('models') or [])} model(s), "
f"pricing ({(pv.get('pricing') or {}).get('kind') or 'none'}), "
f"{n_acc} account(s)"
+ (" · a usage reader the sidecar runs" if pv.get("usageReader") else "")
+ (" · a sidecar module (routes, run hooks)" if pv.get("sidecar") else "")
+ (" (operator only)")})
if hv := manifest.get("harness"):
vendors = ", ".join(s["vendor"] for s in hv.get("supports") or [])
items.append({"kind": "harness", "privileged": True,
"label": f"Agent harness `{hv['harnessId']}` (runs {vendors}): ships a sidecar driver "
f"every {'machine' if hv.get('runsOn') == 'any' else 'lab sidecar'} runs"
+ (", guests' computers included" if hv.get("guestAllowed") else "")
+ (f" · installs `{hv['workerSetup']['tool']}` on a worker from its Setup checklist"
if hv.get("workerSetup") else "")
+ " (operator only)"})
if mg := manifest.get("managed"):
bits = ["operator-owned"]
if mg.get("defaultForGuests"):
bits.append("default on for guests")
if mg.get("metered"):
bits.append("metered")
if mg.get("allowUserSecretOverride"):
bits.append("optional BYOK")
items.append({"kind": "managed", "privileged": True,
"label": f"Managed hub plugin ({', '.join(bits)})"})
if manifest.get("settings") or (manifest.get("ui") or {}).get("settingsHtml") or manifest.get("secrets"):
items.append({"kind": "settings", "label": f"Adds Settings page: {manifest['name']}"})
for s in manifest.get("secrets") or []:
scope_note = " (hub-wide, operator)" if s.get("scope") == "hub" else " (write-only)"
items.append({"kind": "secret", "label": f"Stores secret `{s['key']}`{scope_note}"})
if pr := manifest.get("proxy"):
methods = sorted({r["method"] for r in pr.get("allow") or []})
n = len(pr.get("allow") or [])
host_note = " (internal host — operator only)" if pr.get("internal") else ""
stream_note = " · streaming" if pr.get("stream") else ""
if wk := pr.get("wake"):
stream_note += f" · wakes service `{wk['service']}`"
items.append({
"kind": "proxy",
"privileged": bool(pr.get("internal")),
"label": f"Calls `{pr['baseUrl']}` ({', '.join(methods)} · {n} path{'s' if n != 1 else ''}{stream_note}){host_note}",
})
if sk := manifest.get("skill"):
items.append({"kind": "skill", "label": f"Adds skill `{sk['name']}` to your conversations & paired computers"})
for sc in manifest.get("schedules") or []:
items.append({"kind": "schedule", "label": f"Runs scheduled job `{sc['id']}` (`{sc['cron']}`)"})
ui = manifest.get("ui") or {}
if ui.get("settingsHtml"):
items.append({"kind": "ui", "label": "Renders custom sandboxed Settings UI"})
for pg in ui.get("pages") or []:
items.append({"kind": "ui", "label": f"Adds sandboxed page `{pg['label']}` ({pg['nav']})"})
for tc in ui.get("toolCards") or []:
items.append({"kind": "ui", "label": f"Adds sandboxed tool card `{tc['label']}`"})
for sl in ui.get("slots") or []:
items.append({"kind": "ui", "label": f"Adds sandboxed slot at `{sl['where']}`"})
for fe in ui.get("fences") or []:
items.append({"kind": "ui", "label": f"Draws ```{fe['lang']} blocks in agents' messages (sandboxed)"})
for ov in ui.get("overlays") or []:
items.append({"kind": "ui", "label": _OVERLAY_LABELS[ov["where"]]
+ (" · takes clicks on what it draws" if ov.get("pointer") == "hits" else " · clicks go through")
+ (" · sees where your pointer is" if ov.get("cursor") else "")})
for ev in manifest.get("events") or []:
items.append({"kind": "event", "label": f"Subscribes to hub events: {', '.join(ev['on'])}"})
for wh in manifest.get("webhooks") or []:
items.append({"kind": "webhook", "label": f"Opens inbound webhook `{wh['id']}` ({wh['mode']})"})
if acts := manifest.get("actions"):
items.append({"kind": "action", "label": f"Defines {len(acts)} sandboxed action(s): {', '.join(sorted(acts))}"})
from plugins.harness_hooks import summary as _hooks_summary
items.extend(_hooks_summary(manifest))
for r in manifest.get("resources") or []:
items.append({"kind": "resource", "label": f"Extracts `{r['label']}` resource pills in conversations"})
if reqs := manifest.get("requires"):
items.append({"kind": "requires", "label": f"Requires plugin(s): {', '.join(f'`{r}`' for r in reqs)}"})
if exps := manifest.get("exports"):
items.append({"kind": "exports", "label": f"Exports action(s) to dependent plugins: {', '.join(f'`{e}`' for e in exps)}"})
if ems := manifest.get("emits"):
items.append({"kind": "emits", "label": f"Emits plugin event(s): {', '.join(f'`{e}`' for e in ems)}"})
for ag in manifest.get("agents") or []:
items.append({"kind": "agent", "label": f"Adds Claude subagent `{ag['name']}` to conversations"})
for name, act in (manifest.get("provides") or {}).items():
if name == "notify.channel":
items.append({"kind": "provides", "label": f"Receives your pushes, questions and their clears to deliver them (action `{act}`)"})
elif name == "composer.shortcuts":
items.append({"kind": "provides", "label": f"Contributes prompt shortcut chips to the composer (action `{act}`)"})
elif name == "notify.audio":
items.append({"kind": "provides", "label": f"Renders the spoken audio of your pushes (action `{act}`)"})
elif name == "app.banner":
items.append({"kind": "provides", "privileged": True,
"label": f"Shows a floating status banner to the operator (action `{act}`)"})
elif name == "machine.attention":
items.append({"kind": "provides", "privileged": True,
"label": f"Adds rows to your machines' Needs you and Setup checklists (action `{act}`)"})
elif name == "runs.schedule":
items.append({"kind": "provides", "privileged": True,
"label": f"Schedules conversations for later: the hub's Send later, its CLI and budget ask it (action `{act}`)"})
elif name == "machine.wake":
items.append({"kind": "provides", "privileged": True,
"label": f"Wakes your sleeping machines before a run pinned to one, and from their Wake button (action `{act}`)"})
else:
items.append({"kind": "provides", "label": f"Adds `{name}` data to the hub's own pages (action `{act}`)"})
from plugins import commands as plugin_commands
items += plugin_commands.summary_items(manifest)
for c in manifest.get("capabilities") or []:
label = _CAP_LABELS.get(c, f"Hub capability: `{c}`")
items.append({"kind": "capability",
"privileged": c in _OPERATOR_CAPS and c not in ("models.read", "workers.read"),
"label": label})
return items
def capability_fingerprint(manifest: dict[str, Any]) -> str:
"""Deterministic SHA-256 over every security-relevant declaration.
Reloading a plugin whose fingerprint matches keeps approval automatically."""
pr = manifest.get("proxy")
mg = manifest.get("managed")
sig = {
"secrets": [(s["key"], s.get("scope", "user")) for s in (manifest.get("secrets") or [])],
"proxy": None if not pr else {
"baseUrl": pr["baseUrl"],
"internal": bool(pr.get("internal")),
"stream": bool(pr.get("stream")),
"auth": pr.get("auth"),
"headers": pr.get("headers") or {},
"allow": pr.get("allow") or [],
"denyParams": pr.get("denyParams") or [],
"stripResponseKeys": pr.get("stripResponseKeys") or [],
"inspect": pr.get("inspect"),
"handlerOnly": bool(pr.get("handlerOnly")),
# ``wake`` only when declared (below), so every plugin without it
# keeps its exact approval fingerprint.
},
"managed": None if not mg else {
"defaultForGuests": bool(mg.get("defaultForGuests")),
"allowUserSecretOverride": bool(mg.get("allowUserSecretOverride")),
"metered": bool(mg.get("metered")),
"limits": mg.get("limits") or {},
},
"skill": (manifest.get("skill") or {}).get("name"),
"schedules": [(s["id"], s["cron"], s["script"]) for s in (manifest.get("schedules") or [])],
# Preferences are a person's own knobs (size, a colour): not a capability.
"ui": None if manifest.get("ui") is None else {
k: v for k, v in manifest["ui"].items() if k != "prefs"},
"events": manifest.get("events") or [],
"webhooks": [(w["id"], w["mode"], w.get("action"), bool(w.get("internalOnly")))
for w in (manifest.get("webhooks") or [])],
"actions": {k: v["script"] for k, v in (manifest.get("actions") or {}).items()},
# (id, urlRegex) only: the rest of a resource kind (templates, tool
# extractors, look) mines text, it opens nothing — and installed
# plugins keep their approval.
"resources": [(r["id"], r.get("urlRegex") or "") for r in (manifest.get("resources") or [])],
"capabilities": manifest.get("capabilities") or [],
"provides": manifest.get("provides") or {},
}
# Only include new top-level keys when declared, so existing installed
# plugins keep their exact approval fingerprint across upgrades.
if pr and pr.get("wake"):
sig["proxy"]["wake"] = dict(pr["wake"])
if manifest.get("requires"):
sig["requires"] = list(manifest["requires"])
if manifest.get("exports"):
sig["exports"] = list(manifest["exports"])
if manifest.get("emits"):
sig["emits"] = list(manifest["emits"])
# A typed plugin's kind and everything its provider / harness block can
# reach (code it ships, URLs, accounts, how it launches) — app plugins
# leave all three out, so their fingerprints don't move.
if manifest.get("kind") not in (None, "app"):
sig["kind"] = manifest["kind"]
if pv := manifest.get("provider"):
sig["provider"] = {
"vendorId": pv.get("vendorId"),
"local": bool(pv.get("local")), "keyless": bool(pv.get("keyless")),
"discovery": pv.get("discovery"), "servers": pv.get("servers") or {},
"localInfra": pv.get("localInfra"),
"accounts": [(a["id"], a.get("configDir"), list(a.get("aliases") or []))
for a in pv.get("accounts") or []],
"usageReader": pv.get("usageReader"),
}
if pv.get("sidecar"): # only when declared: other fingerprints don't move
sig["provider"]["sidecar"] = pv["sidecar"]
if hv := manifest.get("harness"):
sig["harness"] = {
"harnessId": hv.get("harnessId"), "caps": hv.get("caps") or [],
"loginMode": hv.get("loginMode"), "loginFlow": hv.get("loginFlow"),
"runsOn": hv.get("runsOn"), "guestAllowed": bool(hv.get("guestAllowed")),
"entrypoint": hv.get("entrypoint"), "sidecar": hv.get("sidecar"),
"supports": [(s["vendor"], s.get("argTemplate"), bool(s.get("allowUnlisted")))
for s in hv.get("supports") or []],
}
if hv.get("workerSetup"): # what it may install on a worker (only when declared)
ws = hv["workerSetup"]
sig["harness"]["workerSetup"] = [ws.get("tool"), bool(ws.get("guestAllowed")),
bool(ws.get("update")), ws.get("installerEnv"),
ws.get("recipe")]
from plugins.harness_hooks import fingerprint_sig as _hooks_sig
if (hh := _hooks_sig(manifest)) is not None:
sig["harnessHooks"] = hh
if manifest.get("agents"):
sig["agents"] = [(a["name"], a["promptFile"], list(a.get("tools") or [])) for a in manifest["agents"]]
blob = json.dumps(sig, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(blob).hexdigest()[:24]