Files
ai-agent/backend/plugins/routes.py
gabrielvidal b87eeda899 Merge branch 'plugin-fences': ui.fences — plugins draw fenced blocks in agents' messages (```chart)
# Conflicts:
#	backend/plugins/manifest.py
#	backend/plugins/routes.py
#	frontend/src/i18n/fr/plugins.ts
2026-11-26 23:29:10 +01:00

1260 lines
58 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""``/api/plugins/*`` — manage, validate, install, reload, configure and create
live plugins (v1 + v2 + v3).
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import subprocess
from typing import Any
from urllib.parse import urlsplit
import httpx
from fastapi import APIRouter, Body, HTTPException, Response
from fastapi.responses import PlainTextResponse
from starlette.concurrency import run_in_threadpool
import schemas
from core.http import _r
from core.state import State
from plugins import agents as plugin_agents
from plugins import banner as plugin_banner
from plugins import commands as plugin_commands
from plugins import home_tiles as plugin_home_tiles
from plugins import keyspend, metering, singleflight
from plugins import machine_attention, machine_wake
from plugins import shortcuts as plugin_shortcuts
from plugins import waiting as plugin_waiting
from plugins.manifest import ManifestError, capability_summary, svg_problem
from plugins.proxy import ProxyError, run_inspect
from plugins.runner import ActionError, requester_context, run_script
from plugins.store import OWNER_UID, DependencyError, _UNSET, art_fields
from toolproxy import access
from users.caller import CallerDep
router = APIRouter()
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
def _uid(caller) -> str:
return OWNER_UID if caller.is_owner else caller.id
def _http() -> httpx.AsyncClient:
from toolproxy.routes import _http as shared
return shared()
def _webhook_base_url(caller) -> str:
if not caller.is_owner:
from users.deliver import GUEST_PUBLIC_URL
if GUEST_PUBLIC_URL:
return f"{GUEST_PUBLIC_URL.rstrip('/')}/proxy/tools"
view = (os.environ.get("AI_AGENT_VIEW_URL") or "http://127.0.0.1:8096").rstrip("/")
return f"{view}/proxy/tools"
def _managed_for_guest(deps: State, uid: str) -> list[dict[str, Any]]:
"""Managed plugins actively granted to guest ``uid``, read-only view."""
out: list[dict[str, Any]] = []
for rec in deps.plugin_store.managed_plugins():
pid = rec["id"]
mf = rec["manifest"]
grant = deps.plugin_store.effective_grant(uid, pid, mf)
if not grant.get("enabled"):
continue
mg = mf.get("managed") or {}
usage = metering.plugin_usage_by_who(uid, pid)
byok_allowed = bool(mg.get("allowUserSecretOverride"))
has_own = deps.plugin_store.has_user_override_secret(uid, pid, mf) if byok_allowed else False
byok_keys = [
{"key": s["key"], "label": s.get("label") or s["key"],
"placeholder": s.get("placeholder") or "", "help": s.get("help") or "",
"present": bool(deps.plugin_store.get_secret(uid, pid, s["key"], scope="user"))}
for s in (mf.get("secrets") or [])
] if byok_allowed else []
out.append({
"id": pid,
"name": mf.get("name") or pid,
"version": mf.get("version") or "1.0.0",
"description": mf.get("description") or "",
"icon": mf.get("icon") or "puzzle",
**art_fields(pid, mf),
"skillName": (mf.get("skill") or {}).get("name"),
"metered": bool(mg.get("metered")),
"monthlyBudgetUsd": grant.get("monthlyBudgetUsd"),
"grantConfig": grant.get("config") or {},
"usage": usage,
"allowUserSecretOverride": byok_allowed,
"usingOwnSecret": has_own,
"byokSecrets": byok_keys,
})
return out
def _ui_descriptors(deps: State, caller: CallerDep, installed: list[dict[str, Any]]) -> dict[str, Any]:
"""Collect active v2/v3 UI contributions across caller's enabled plugins
(plus active managed grants for guests)."""
active_recs: list[dict[str, Any]] = [
p for p in installed if p.get("enabled") and not p.get("needsApproval")
]
if not caller.is_owner:
seen = {p["id"] for p in active_recs}
for rec in deps.plugin_store.managed_plugins():
pid = rec["id"]
if pid in seen:
continue
if deps.plugin_store.effective_grant(caller.id, pid, rec["manifest"]).get("enabled"):
active_recs.append({"id": pid, "name": rec["manifest"].get("name") or pid,
"manifest": rec["manifest"]})
pages: list[dict[str, Any]] = []
tool_cards: list[dict[str, Any]] = []
slots: list[dict[str, Any]] = []
menu_items: list[dict[str, Any]] = []
overlays: list[dict[str, Any]] = []
fences: list[dict[str, Any]] = []
prefs: dict[str, list[dict[str, Any]]] = {}
for p in active_recs:
mf = p.get("manifest") or {}
pid = p["id"]
ui = mf.get("ui") or {}
for pg in ui.get("pages") or []:
pages.append({**pg, "pluginId": pid, "pluginName": p["name"],
"description": mf.get("description") or "",
"to": f"/plugins/{pid}/{pg['id']}"})
for tc in ui.get("toolCards") or []:
tool_cards.append({**tc, "pluginId": pid, "pluginName": p["name"]})
for sl in ui.get("slots") or []:
slots.append({**sl, "pluginId": pid, "pluginName": p["name"]})
for mi in ui.get("menuItems") or []:
menu_items.append({**mi, "pluginId": pid, "pluginName": p["name"]})
for ov in ui.get("overlays") or []:
overlays.append({**ov, "pluginId": pid, "pluginName": p["name"]})
# One plugin per language: the first active one keeps it.
for fe in ui.get("fences") or []:
if not any(f["lang"] == fe["lang"] for f in fences):
fences.append({k: v for k, v in fe.items() if k != "html"}
| {"pluginId": pid, "pluginName": p["name"]})
if ui.get("prefs"):
prefs[pid] = plugin_agents.enrich_ui_prefs(
deps, pid, mf,
uid=_uid(caller), is_owner=caller.is_owner,
user_models=None if caller.is_owner else getattr(caller, "models", None),
)
# The conversation resource kinds the pills are drawn with: the owner's
# active plugins' (the cards' registry — plugins/resources.py), for
# everyone who sees a pill; display data only (no regexes).
from plugins import resources as plugin_resources
resources = plugin_resources.registry(deps).descriptors()
if not caller.is_owner:
resources = [{k: v for k, v in r.items() if k != "pluginId"} for r in resources]
provides = sorted({k for p in active_recs for k in ((p.get("manifest") or {}).get("provides") or {})
if k != plugin_banner.PROVIDES or caller.is_owner})
# Which plugin answers each key (the first, in plugin order) — what the app
# calls for a key it uses itself (``runs.schedule``: the stopped-run card's
# Resume at…), with the key's action name.
providers: dict[str, dict[str, str]] = {}
for p in active_recs:
for k, act in ((p.get("manifest") or {}).get("provides") or {}).items():
if k in provides and k not in providers:
providers[k] = {"pluginId": p["id"], "action": act}
return {"pages": pages, "toolCards": tool_cards, "slots": slots, "overlays": overlays,
"menuItems": menu_items, "fences": fences,
"prefs": prefs, "resources": resources, "provides": provides,
"providers": providers}
@router.get("/api/plugins/composer-shortcuts")
def list_plugin_composer_shortcuts(deps: State, caller: CallerDep):
"""Additive prompt shortcuts contributed by active plugins
(``provides: composer.shortcuts``)."""
return {"shortcuts": plugin_shortcuts.shortcuts_for(deps, caller)}
@router.get("/api/plugins/commands", responses=_r(schemas.PluginCommandsResponse))
def list_plugin_commands(deps: State, caller: CallerDep):
"""The ``ai-agent`` CLI commands and MCP tools of the plugins active for
the caller (``commands`` in their manifests — ``plugins/commands.py``):
what ``ai-agent plugin <id> <command>`` and the MCP server's
``plugin_<id>_<command>`` tools are built from."""
return {"commands": plugin_commands.commands_for(deps, caller)}
@router.get("/api/plugins/composer-modes")
def list_plugin_composer_modes(deps: State, caller: CallerDep):
"""Composer mode descriptors contributed by active plugins
(``provides: composer.mode``)."""
return {"modes": plugin_waiting.composer_modes_for(deps, caller)}
@router.get("/api/plugins/home-tiles", responses=_r(schemas.HomeTilesResponse))
def list_plugin_home_tiles(deps: State, caller: CallerDep, scope: str = "all",
profileScope: str = "personal", composerHarness: str = "",
tzOffset: int = 0):
"""Declarative tiles for the home usage strip from active plugins
(``provides: home.tiles`` — ``plugins/home_tiles.py``)."""
return {"tiles": plugin_home_tiles.tiles_for(deps, caller, scope, profileScope,
composerHarness, tzOffset)}
@router.get("/api/inbox/waiting")
def list_inbox_waiting(deps: State, caller: CallerDep):
"""Pending questions contributed by active plugins
(``provides: inbox.waiting``), filtered to what ``caller`` may see."""
return {"items": plugin_waiting.waiting_for(deps, caller)}
@router.get("/api/app-banner", responses=_r(schemas.BannerStatus))
def app_banner(deps: State, caller: CallerDep):
"""The owner's floating status banner from the plugin providing
``app.banner`` (``plugins/banner.py``), or ``null``. Owner only — never a
guest's (``lab.read``). Its ``sessionId`` resolves to the conversation's
in-app id and title (:func:`_attach_conversation`)."""
if not caller.is_owner:
raise HTTPException(403, "owner only")
snap = plugin_banner.status(deps)
if not snap:
return None
try:
_attach_conversation(deps, caller, snap)
except Exception: # noqa: BLE001 — a title lookup never hides the banner
pass
return snap
@router.get("/api/machines/attention", responses=_r(schemas.MachineAttention))
def machines_attention(deps: State, caller: CallerDep):
"""What waits for the owner on each of his machines, from the plugins
providing ``machine.attention`` (``plugins/machine_attention.py``),
cached 30 s — the machine pages' *Needs you* rows and a worker card's
Setup checklist. Owner only (``lab.read``)."""
if not caller.is_owner:
raise HTTPException(403, "owner only")
return {"items": machine_attention.items(deps)}
@router.get("/api/machines/wakeable", responses=_r(schemas.MachinesWakeable))
def machines_wakeable(deps: State, caller: CallerDep):
"""Which of the owner's workers the plugin providing ``machine.wake`` can
wake (Wake-on-LAN), cached 30 s (``plugins/machine_wake.py``) — the ⚡ Wake
button on an offline worker's card. Owner only (``lab.read``)."""
if not caller.is_owner:
raise HTTPException(403, "owner only")
return {"machines": machine_wake.list_wakeable(deps)}
@router.post("/api/machines/{worker_id}/wake", responses=_r(schemas.MachineWakeResult))
def machine_wake_now(deps: State, caller: CallerDep, worker_id: str):
"""*⚡ Wake*: the ``machine.wake`` plugin sends the worker its magic packet;
then it is probed every 3 s for a minute so the ``workers`` SSE flips its
card online by itself. Owner only (``workers.manage``)."""
if not caller.is_owner:
raise HTTPException(403, "owner only")
w = deps.worker_store.get(worker_id)
if not w or w.get("owner") or w.get("pending"):
raise HTTPException(404, {"message": f"unknown worker: {worker_id!r}", "kind": "worker_unknown"})
if not machine_wake.has_provider(deps):
raise HTTPException(409, {"message": "no plugin wakes machines — install wake-on-lan",
"kind": "no_provider"})
res = machine_wake.wake_machine(deps, worker_id)
if res.get("ok") and res.get("sent") and not deps.worker_store.online(worker_id):
machine_wake.probe_in_background(deps, worker_id)
return res
def _plugin_changed(deps, pid: str, uid: str) -> None:
"""After an install, reload, enable / disable / config change or
uninstall: the providers of machine attention may have changed, and the
``mcp-servers`` plugin may now carry the core's old servers over."""
if uid != OWNER_UID:
return
machine_attention.changed()
machine_wake.changed()
try:
deps.hub.publish({"type": "machine-attention"})
deps.hub.publish({"type": "machine-wake"})
except Exception: # noqa: BLE001
pass
if pid == "mcp-servers":
from plugins import carryover
try:
carryover.mcp_servers(deps.plugin_store, deps.worker_store)
except Exception: # noqa: BLE001 — a carry-over never fails the change
import logging
logging.getLogger(__name__).exception("mcp-servers carry-over failed")
def _attach_conversation(deps, caller, snap: dict) -> None:
"""Resolve the banner's conversation from the snapshot's ``sessionId``.
The plugin can only stamp the sidecar's custom ``title`` override, which
most conversations never set — the title the viewer shows is Claude's
``ai-title`` (else the first prompt), parsed from the transcript. So the
title and the in-app ``conversationId`` are looked up here, live; the
plugin's own ``convTitle`` is only the fallback. A caller who can't see the
conversation gets neither (nor the plugin's link).
"""
from conversations.cards import _conv_title
from conversations.tree import _conv_id, _is_sidechain_path
from users import access
sid = snap.get("sessionId")
if not sid:
return
if not access.visible(deps, caller, sid):
snap["convTitle"] = snap["convUrl"] = None
return
best = None
for path, s in deps.store.all_summaries():
if s.get("sessionId") != sid or _is_sidechain_path(path):
continue
if best is None or (s.get("endedAt") or "") > (best[1].get("endedAt") or ""):
best = (path, s)
if best:
snap["conversationId"] = _conv_id(best[0])
snap["convTitle"] = _conv_title(deps, best[1]) or snap.get("convTitle")
# The banner links the conversation's uid, never a transcript path.
snap["convUrl"] = f"/conversation/{snap['conversationId']}"
@router.get("/api/plugins")
def list_plugins(deps: State, caller: CallerDep):
"""Caller's installed plugins, managed plugins (for guests), available hub
catalog, permissions and live UI/resource descriptors."""
uid = _uid(caller)
installed = deps.plugin_store.list_for(uid)
catalog = deps.plugin_store.catalog(is_owner=caller.is_owner)
managed = [] if caller.is_owner else _managed_for_guest(deps, caller.id)
ui = _ui_descriptors(deps, caller, installed)
return {
# The `provides` keys active for the caller (``notify.audio``…), so a
# component can tell whether a provider is installed.
"provides": ui["provides"],
"installed": installed,
"managed": managed,
"catalog": catalog,
"canInstall": caller.is_owner or caller.has("plugins.install"),
"canCreate": caller.is_owner or caller.has("plugins.create"),
"canManage": caller.is_owner or caller.has("plugins.manage"),
"ui": ui,
}
@router.get("/api/plugins/ui")
def list_plugins_ui(deps: State, caller: CallerDep):
"""What the app draws plugins with outside Settings → Plugins: the live UI
descriptors (pages, tool cards, slots, overlays, prefs, resource kinds),
the active ``provides`` keys and each active plugin's glyph, name and
non-secret config. A few KB, where ``GET /api/plugins`` (every install's
full manifest, the catalog — ~250 KB) is only for the Settings pages."""
uid = _uid(caller)
store = deps.plugin_store
active = [{"id": pid, "name": mf.get("name") or pid, "manifest": mf, "config": cfg,
"enabled": True, "needsApproval": False}
for pid, mf, cfg in store.active_manifests(uid)]
ui = _ui_descriptors(deps, caller, active)
briefs: list[dict[str, Any]] = []
seen: set[str] = set()
def brief(pid: str, mf: dict[str, Any], config: dict[str, Any] | None) -> None:
if pid in seen:
return
seen.add(pid)
art = art_fields(pid, mf)
briefs.append({"id": pid, "name": mf.get("name") or pid, "kind": mf.get("kind") or "app",
"description": mf.get("description") or "", "icon": mf.get("icon") or "puzzle",
"iconUrl": art["iconUrl"], "color": art["color"], "config": config or {}})
for p in active:
brief(p["id"], p["manifest"], p["config"])
if not caller.is_owner:
for rec in store.managed_plugins():
if store.effective_grant(caller.id, rec["id"], rec["manifest"]).get("enabled"):
brief(rec["id"], rec["manifest"], None)
return {"provides": ui["provides"], "providers": ui["providers"], "plugins": briefs, "ui": ui}
def typed_summary(deps, mf: dict[str, Any], config: dict[str, Any] | None = None) -> dict[str, Any] | None:
"""A provider's / harness's own section on its settings and info pages:
what it declares and, for a provider, the accounts as the registry merged
them (the owner's edits included)."""
kind = mf.get("kind") or "app"
if kind == "provider" and mf.get("provider"):
pv = mf["provider"]
from plugins import providers as plugin_providers
reg = plugin_providers.registry(deps)
active = reg.providers.get(pv["vendorId"])
accounts = (reg.accounts_for_vendor(pv["vendorId"]) if active is not None
and active.plugin_id == mf.get("id") else list(pv.get("accounts") or []))
return {"kind": "provider", "vendorId": pv["vendorId"], "label": pv.get("label"),
"local": bool(pv.get("local")), "keyless": bool(pv.get("keyless")),
"families": sorted(pv.get("families") or {}),
"discovery": (pv.get("discovery") or {}).get("kind") or "static",
"models": [{"id": m["id"], "key": m.get("key"), "displayName": m.get("displayName"),
"family": m.get("family"), "contextWindow": m.get("contextWindow"),
"server": m.get("server")} for m in pv.get("models") or []],
"servers": pv.get("servers") or {},
"pricing": {"kind": (pv.get("pricing") or {}).get("kind"),
"bookDate": (pv.get("pricing") or {}).get("bookDate"),
"models": len(((pv.get("pricing") or {}).get("models") or {}))},
"planMeter": (pv.get("planMeter") or {}).get("kind") or "none",
"usageReader": bool(pv.get("usageReader")),
"accounts": accounts, "active": active is not None,
"accountEdits": list((config or {}).get("accounts") or [])}
if kind == "harness" and mf.get("harness"):
hv = mf["harness"]
from plugins import providers as plugin_providers
reg = plugin_providers.registry(deps)
return {"kind": "harness", "harnessId": hv["harnessId"], "label": hv.get("label"),
**{k: hv.get(k) for k in ("hint", "knob", "efforts", "modelEfforts", "caps", "loginMode",
"loginFlow", "runsOn", "guestAllowed", "defaultModel",
"defaultEffort")},
"supports": [{"vendor": x["vendor"], "argTemplate": x.get("argTemplate"),
"available": x["vendor"] in reg.providers}
for x in hv.get("supports") or []],
"active": hv["harnessId"] in reg.harnesses}
return None
@router.get("/api/providers")
def list_providers(deps: State, caller: CallerDep):
"""Every model provider and agent harness the hub runs (the owner's
enabled ``kind: provider|harness`` plugins): harnesses, vendors, model
families, price books and accounts. A guest gets the harnesses their
computers may run and no accounts."""
from plugins import providers as plugin_providers
return plugin_providers.registry(deps).api_payload(guest=not caller.is_owner)
@router.post("/api/plugins/validate")
def validate_plugin(deps: State, caller: CallerDep, body: dict = Body(...)):
"""Preview a plugin source (local path or git URL) before installing."""
if not (caller.is_owner or caller.has("plugins.install") or caller.has("plugins.create")):
raise HTTPException(403, "plugins.install permission required")
source = str((body or {}).get("source") or "").strip()
try:
return deps.plugin_store.inspect_source(source, allow_any_path=caller.is_owner,
refresh_git=bool((body or {}).get("refresh")))
except ManifestError as e:
raise HTTPException(400, {"message": "; ".join(e.errors), "errors": e.errors}) from None
@router.post("/api/plugins/install")
def install_plugin(deps: State, caller: CallerDep, body: dict = Body(...)):
"""Install (or re-approve) a plugin live for the caller."""
catalog_id = (body or {}).get("catalogId")
source = str((body or {}).get("source") or "").strip()
if catalog_id:
# Installing from the operator-curated catalog needs only plugins.use
if not (caller.is_owner or caller.has("plugins.use") or caller.has("plugins.install")):
raise HTTPException(403, "plugins.use permission required")
else:
if not (caller.is_owner or caller.has("plugins.install")):
raise HTTPException(403, "plugins.install permission required")
approve = bool((body or {}).get("approve", True))
as_uid = str((body or {}).get("asUid") or "").strip().lower()
target_uid = as_uid if (as_uid and caller.is_owner) else _uid(caller)
res_v0 = _res_version(deps)
try:
rec = deps.plugin_store.install(
target_uid, source, is_owner=caller.is_owner,
approve=approve, catalog_id=str(catalog_id) if catalog_id else None,
)
except DependencyError as e:
raise HTTPException(409, {"message": str(e), "missingRequires": e.missing}) from None
except ManifestError as e:
raise HTTPException(400, {"message": "; ".join(e.errors), "errors": e.errors}) from None
plugin_shortcuts.invalidate(rec["id"])
plugin_home_tiles.invalidate(rec["id"])
plugin_waiting.invalidate(rec["id"])
_resources_touched(deps, res_v0)
deps.hub.publish({"type": "plugins", "id": rec["id"], "uid": target_uid})
_plugin_changed(deps, rec["id"], target_uid)
return rec
def _res_version(deps) -> int:
from plugins import resources as plugin_resources
return plugin_resources.registry(deps).version
def _resources_touched(deps, before: int) -> None:
"""A plugin write that changed the resource kinds (an install, its
settings' scope or workspace): every card's pills may differ — tell the
lists to refetch (the cards' memo keys on the registry's version)."""
if _res_version(deps) != before:
deps.hub.publish({"type": "meta"})
@router.post("/api/plugins/{pid}/reload")
def reload_plugin(deps: State, caller: CallerDep, pid: str, body: dict | None = Body(default=None)):
"""Re-read a plugin from its source; keeps approval if capabilities didn't widen."""
approve = bool((body or {}).get("approve", False))
res_v0 = _res_version(deps)
try:
rec = deps.plugin_store.reload(_uid(caller), pid, is_owner=caller.is_owner, approve=approve)
except KeyError:
raise HTTPException(404, f"plugin '{pid}' not installed") from None
except ManifestError as e:
raise HTTPException(400, {"message": "; ".join(e.errors), "errors": e.errors}) from None
plugin_shortcuts.invalidate(pid)
plugin_home_tiles.invalidate(pid)
plugin_waiting.invalidate(pid)
_resources_touched(deps, res_v0)
deps.hub.publish({"type": "plugins", "id": pid, "uid": _uid(caller)})
_plugin_changed(deps, pid, _uid(caller))
return rec
@router.put("/api/plugins/{pid}")
def update_plugin(deps: State, caller: CallerDep, pid: str, body: dict = Body(...)):
"""Toggle enabled or update non-secret config fields."""
enabled = body.get("enabled") if isinstance(body, dict) and "enabled" in body else None
config = body.get("config") if isinstance(body, dict) and isinstance(body.get("config"), dict) else None
force = bool(body.get("force", False)) if isinstance(body, dict) else False
res_v0 = _res_version(deps)
try:
rec = deps.plugin_store.update(_uid(caller), pid, enabled=enabled, config=config, force=force)
except KeyError:
raise HTTPException(404, f"plugin '{pid}' not installed") from None
except DependencyError as e:
raise HTTPException(409, {"message": str(e), "missingRequires": e.missing, "dependents": e.dependents}) from None
except ManifestError as e: # a provider's account edits
raise HTTPException(400, {"message": "; ".join(e.errors), "errors": e.errors}) from None
plugin_shortcuts.invalidate(pid)
plugin_home_tiles.invalidate(pid)
plugin_waiting.invalidate(pid)
_resources_touched(deps, res_v0)
deps.hub.publish({"type": "plugins", "id": pid, "uid": _uid(caller)})
_plugin_changed(deps, pid, _uid(caller))
return rec
@router.delete("/api/plugins/{pid}")
def uninstall_plugin(deps: State, caller: CallerDep, pid: str, purge: bool = False, force: bool = False):
res_v0 = _res_version(deps)
try:
ok = deps.plugin_store.uninstall(_uid(caller), pid, purge=purge, force=force)
except DependencyError as e:
raise HTTPException(409, {"message": str(e), "dependents": e.dependents}) from None
if not ok:
raise HTTPException(404, f"plugin '{pid}' not installed")
plugin_shortcuts.invalidate(pid)
plugin_home_tiles.invalidate(pid)
plugin_waiting.invalidate(pid)
_resources_touched(deps, res_v0)
deps.hub.publish({"type": "plugins", "id": pid, "uid": _uid(caller)})
if _uid(caller) == OWNER_UID:
machine_attention.changed()
machine_wake.changed()
deps.hub.publish({"type": "machine-attention"})
deps.hub.publish({"type": "machine-wake"})
if purge:
# a relay route's headers are secrets: they go with the plugin's
from plugins import relay
relay.purge(deps, pid)
return {"ok": True}
# ── hub catalog (operator only) ──────────────────────────────────────────────
@router.post("/api/plugins/catalog")
def promote_catalog_plugin(deps: State, caller: CallerDep, body: dict = Body(...)):
if not caller.is_owner:
raise HTTPException(403, "operator only")
source = str((body or {}).get("source") or "").strip()
guests_allowed = bool((body or {}).get("guestsAllowed", True))
try:
entry = deps.plugin_store.promote_catalog(source, guests_allowed=guests_allowed)
except ManifestError as e:
raise HTTPException(400, {"message": "; ".join(e.errors), "errors": e.errors}) from None
deps.hub.publish({"type": "plugins"})
return entry
@router.delete("/api/plugins/catalog/{pid}")
def remove_catalog_plugin(deps: State, caller: CallerDep, pid: str):
if not caller.is_owner:
raise HTTPException(403, "operator only")
if not deps.plugin_store.remove_catalog(pid):
raise HTTPException(404, f"catalog plugin '{pid}' not found")
deps.hub.publish({"type": "plugins"})
return {"ok": True}
# ── managed plugin grants (operator only) ────────────────────────────────────
@router.get("/api/plugins/managed/grants/{uid}")
def list_user_managed_grants(deps: State, caller: CallerDep, uid: str):
"""Every owner-managed plugin with guest ``uid``'s current grant, config,
per-plugin monthly budget and this month's usage."""
if not caller.is_owner:
raise HTTPException(403, "operator only")
target = deps.plugin_store.norm_uid(uid)
rows = []
for rec in deps.plugin_store.managed_plugins():
pid = rec["id"]
mf = rec["manifest"]
grant = deps.plugin_store.effective_grant(target, pid, mf)
mg = mf.get("managed") or {}
usage = metering.plugin_usage_by_who(target, pid)
rows.append({
"id": pid,
"name": mf.get("name") or pid,
"description": mf.get("description") or "",
"icon": mf.get("icon") or "puzzle",
"skillName": (mf.get("skill") or {}).get("name"),
"managed": mg,
"grant": grant,
"usage": usage,
"usingOwnSecret": deps.plugin_store.has_user_override_secret(target, pid, mf),
})
return {"uid": target, "plugins": rows}
@router.put("/api/plugins/managed/grants/{uid}/{pid}")
def update_user_managed_grant(deps: State, caller: CallerDep, uid: str, pid: str,
body: dict = Body(...)):
"""Toggle or configure guest ``uid``'s grant for managed plugin ``pid``."""
if not caller.is_owner:
raise HTTPException(403, "operator only")
if not isinstance(body, dict):
raise HTTPException(400, "JSON object required")
enabled = body.get("enabled") if "enabled" in body else None
config = body.get("config") if isinstance(body.get("config"), dict) else None
budget = body["monthlyBudgetUsd"] if "monthlyBudgetUsd" in body else _UNSET
try:
grant = deps.plugin_store.set_grant(
uid, pid, enabled=enabled, config=config, monthly_budget_usd=budget,
)
except KeyError:
raise HTTPException(404, f"managed plugin '{pid}' not found") from None
except ValueError as e:
raise HTTPException(400, str(e)) from None
plugin_shortcuts.invalidate(pid)
plugin_home_tiles.invalidate(pid)
plugin_waiting.invalidate(pid)
deps.hub.publish({"type": "plugins", "id": pid, "uid": uid})
return {"uid": uid, "id": pid, "grant": grant}
# ── declarative settings, secrets, test & actions ────────────────────────────
@router.get("/api/plugins/{pid}/settings")
async def plugin_settings(deps: State, caller: CallerDep, pid: str):
uid = _uid(caller)
rec = deps.plugin_store.get_raw(uid, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not installed")
mf = rec["manifest"]
pub = deps.plugin_store._public_record(uid, rec)
base = _webhook_base_url(caller)
wh_tokens = rec.get("webhookTokens") or {}
webhooks = [
{
**wh,
"url": f"{base}/plugins/{pid}/webhook/{wh['id']}?token={wh_tokens.get(wh['id'], '')}",
}
for wh in (mf.get("webhooks") or [])
]
status_data = None
status_act = (mf.get("settings") or {}).get("statusAction")
if status_act and status_act in (mf.get("actions") or {}):
try:
act = mf["actions"][status_act]
status_data = await run_in_threadpool(
run_script, deps, deps.plugin_store, uid, rec, act["script"],
payload={"trigger": "status"}, timeout_sec=int(act.get("timeoutSec") or 20),
)
except Exception as e:
status_data = {"ok": False, "error": str(e)}
managed_owner_info = None
if caller.is_owner and mf.get("managed"):
guest_rows = []
for u in deps.users.all():
gid = u.get("id")
if not gid:
continue
g = deps.plugin_store.effective_grant(gid, pid, mf)
guest_rows.append({
"uid": gid,
"name": u.get("name") or gid,
"grant": g,
"usage": metering.plugin_usage_by_who(gid, pid),
"usingOwnSecret": deps.plugin_store.has_user_override_secret(gid, pid, mf),
})
managed_owner_info = {
"spec": mf["managed"],
"grants": guest_rows,
"keyHealth": deps.plugin_store.get_key_health(pid),
"monthlyHubSpendUsd": round(metering.month_spent(pid, mf), 4),
}
return {
"plugin": pub,
"kind": mf.get("kind") or "app",
"typed": typed_summary(deps, mf, rec.get("config")),
"settings": mf.get("settings") or {},
"secrets": [
{
**s,
"present": pub["secretsPresent"].get(s["key"], False),
"editable": caller.is_owner or s.get("scope", "user") == "user",
}
for s in (mf.get("secrets") or [])
],
"hasCustomHtml": bool((mf.get("ui") or {}).get("settingsHtml")),
"status": status_data,
"webhooks": webhooks,
"managed": managed_owner_info,
"dataBytes": deps.plugin_store.data_usage_bytes(uid, pid),
"dataMaxBytes": int((mf.get("storage") or {}).get("maxMb") or 50) * 1024 * 1024,
}
@router.put("/api/plugins/{pid}/secrets/{key}")
async def set_plugin_secret(deps: State, caller: CallerDep, pid: str, key: str,
body: dict = Body(...)):
uid = _uid(caller)
rec, _grant, is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
rec = deps.plugin_store.get_raw(uid, pid)
is_managed = False
if not rec:
raise HTTPException(404, f"plugin '{pid}' not installed")
mf = rec["manifest"]
spec = next((s for s in (mf.get("secrets") or []) if s["key"] == key), None)
if not spec:
raise HTTPException(404, f"secret '{key}' not declared by plugin '{pid}'")
scope = spec.get("scope", "user")
# Guests with a managed grant whose manifest opts into BYOK save a user-scoped override
byok_override = (
not caller.is_owner
and is_managed
and bool((mf.get("managed") or {}).get("allowUserSecretOverride"))
)
if scope == "hub" and not caller.is_owner:
if byok_override:
scope = "user"
else:
raise HTTPException(403, "hub-scoped secrets are operator-only")
val = str((body or {}).get("value") or "").strip()
if not val:
raise HTTPException(400, "secret value cannot be empty")
# The hub key of a plugin that watches it (``managed.keyHealth``): checked
# with the plugin's own test action before it replaces the stored one.
if (scope == "hub" and caller.is_owner and body.get("verify", True)
and _is_watched_key(mf, key)):
check = await _check_candidate_key(deps, rec, key, val)
await run_in_threadpool(deps.plugin_store.set_secret, uid, pid, key, val, scope=scope)
await run_in_threadpool(deps.plugin_store.mark_key_replaced, pid)
await run_in_threadpool(_note_check, deps, pid, mf, check)
deps.hub.publish({"type": "plugins", "id": pid, "uid": uid})
return {"ok": True, "key": key, "present": True, "check": check["public"],
"hint": keyspend.hint(deps, pid, mf)}
# Optional pre-save validation via proxy.inspect
inspect_out = None
pr = mf.get("proxy") or {}
if pr.get("inspect") and (pr.get("auth") or {}).get("secret") == key and body.get("verify", True):
try:
inspect_out = await run_inspect(_http(), deps, deps.plugin_store, uid, rec, override_secret=val)
except ProxyError as e:
raise HTTPException(e.status, e.message) from None
deps.plugin_store.set_secret(uid, pid, key, val, scope=scope)
deps.hub.publish({"type": "plugins", "id": pid, "uid": uid})
return {"ok": True, "key": key, "present": True, "inspect": inspect_out}
# ── a watched hub key (``managed.keyHealth``) ────────────────────────────────
# What the test action's verdict means for a key being saved: ``invalid`` and
# ``denied`` are the key's fault — refused; ``no-credit`` and ``capped`` are
# the billing's — the key itself is right, so it is kept.
_REFUSE_KEY = ("invalid", "denied")
_TEST_WHO = {"who": "owner", "via": "test"}
def _is_watched_key(mf: dict[str, Any], key: str) -> bool:
spec = metering.key_health_spec(mf) or {}
test_act = (mf.get("settings") or {}).get("testAction")
return bool(spec.get("secretKey") == key and test_act and test_act in (mf.get("actions") or {}))
def _run_test_action(deps, rec: dict[str, Any], candidate: str | None = None) -> dict[str, Any]:
"""Run the plugin's ``settings.testAction`` as the owner and sort its
outcome: ``{"kind", "message", "meter", "result", "error"}`` — ``kind`` is
``ok``, a broken state, or the action's own error kind."""
mf = rec["manifest"]
act = mf["actions"][mf["settings"]["testAction"]]
try:
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
payload={"trigger": "test"},
timeout_sec=int(act.get("timeoutSec") or 30),
candidate_secret=candidate)
except ActionError as e:
return {"kind": e.kind or "action_failed", "message": e.message, "meter": None,
"result": None, "error": e}
meter = res.pop("_meter", None) if isinstance(res, dict) else None
kh = (meter or {}).get("keyHealth") if isinstance(meter, dict) else None
kind = str((kh or {}).get("status") or ("ok" if res.get("ok", True) else "error"))
return {"kind": kind, "message": str((kh or {}).get("message") or res.get("message") or ""),
"meter": meter if isinstance(meter, dict) else None, "result": res, "error": None}
def _note_check(deps, pid: str, mf: dict[str, Any], check: dict[str, Any]) -> None:
"""Record a test action's verdict on the hub key (pushes a break or a
recovery) and bill its tiny call to the ledger."""
meter = check.get("meter")
who = access.Who(None, None, "test")
if meter:
metering.apply_meter(deps, who, pid, mf, meter)
if (meter.get("keyHealth") or {}).get("status"):
return
# A broken state moves the key's health; anything else (the provider
# unreachable, a rate limit, the script failing) is listed as a failure.
kind = check["kind"]
metering.observe_key_health(
deps, pid, mf, kind if kind in metering.KEY_STATES else "error",
check.get("message") or "", who_row=who.row(), test=True,
http_status=getattr(check.get("error"), "status", 0) or 0,
)
async def _check_candidate_key(deps, rec: dict[str, Any], key: str, val: str) -> dict[str, Any]:
pid = rec["id"]
if val == deps.plugin_store.get_secret(OWNER_UID, pid, key, scope="hub"):
raise HTTPException(409, "that's the key the hub already uses")
check = await run_in_threadpool(_run_test_action, deps, rec, val)
kind, msg = check["kind"], check["message"]
if kind in _REFUSE_KEY:
raise HTTPException(400, f"the provider refused this key — nothing was changed: {msg}")
if kind != "ok" and kind not in metering.BROKEN_STATES:
raise HTTPException(502, f"couldn't check the key, nothing was changed — try again: {msg}")
check["public"] = {"ok": kind == "ok", "kind": kind, "message": msg}
return check
def _owner_key_plugin(deps, caller, pid: str) -> dict[str, Any]:
if not caller.is_owner:
raise HTTPException(403, "operator only")
rec = deps.plugin_store.get_raw(OWNER_UID, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not installed")
if not metering.key_health_spec(rec["manifest"]):
raise HTTPException(404, f"plugin '{pid}' has no hub key to watch (managed.keyHealth)")
return rec
@router.get("/api/plugins/{pid}/spend")
def plugin_key_spend(deps: State, caller: CallerDep, pid: str):
"""The hub key of a ``managed.keyHealth`` plugin: its health and hint,
the alert settings, this month, by caller / model, 30 days, recent calls."""
rec = _owner_key_plugin(deps, caller, pid)
return keyspend.build(deps, pid, rec)
@router.put("/api/plugins/{pid}/key-settings")
def update_plugin_key_settings(deps: State, caller: CallerDep, pid: str,
body: dict = Body(...)):
"""The owner's alert line (``alertLimit`` + ``currency``), the % it pushes
at (and 100 %), and whether a break / recovery pushes."""
rec = _owner_key_plugin(deps, caller, pid)
if not isinstance(body, dict):
raise HTTPException(400, "JSON object required")
try:
deps.plugin_store.update_key_settings(pid, rec["manifest"], body)
except (TypeError, ValueError) as e:
raise HTTPException(400, str(e)) from None
deps.hub.publish({"type": "plugins", "id": pid, "uid": OWNER_UID})
return keyspend.build(deps, pid, rec)
@router.delete("/api/plugins/{pid}/secrets/{key}")
def delete_plugin_secret(deps: State, caller: CallerDep, pid: str, key: str):
uid = _uid(caller)
rec, _grant, is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
rec = deps.plugin_store.get_raw(uid, pid)
is_managed = False
if not rec:
raise HTTPException(404, f"plugin '{pid}' not installed")
mf = rec["manifest"]
spec = next((s for s in (mf.get("secrets") or []) if s["key"] == key), None)
if not spec:
raise HTTPException(404, f"secret '{key}' not declared")
scope = spec.get("scope", "user")
byok_override = (
not caller.is_owner
and is_managed
and bool((mf.get("managed") or {}).get("allowUserSecretOverride"))
)
if scope == "hub" and not caller.is_owner:
if byok_override:
scope = "user"
else:
raise HTTPException(403, "hub-scoped secrets are operator-only")
deps.plugin_store.delete_secret(uid, pid, key, scope=scope)
deps.hub.publish({"type": "plugins", "id": pid, "uid": uid})
return {"ok": True, "key": key, "present": False}
@router.post("/api/plugins/{pid}/test")
async def test_plugin(deps: State, caller: CallerDep, pid: str):
uid = _uid(caller)
rec = deps.plugin_store.get_raw(uid, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not installed")
mf = rec["manifest"]
test_act = (mf.get("settings") or {}).get("testAction")
if caller.is_owner and test_act and metering.key_health_spec(mf) \
and test_act in (mf.get("actions") or {}):
# The hub key's check: its verdict moves the key's health.
check = await run_in_threadpool(_run_test_action, deps, rec)
await run_in_threadpool(_note_check, deps, pid, mf, check)
e = check["error"]
if e is not None:
raise HTTPException(e.status, {"message": e.message, "kind": e.kind}) from None
return check["result"]
if test_act and test_act in (mf.get("actions") or {}):
act = mf["actions"][test_act]
try:
return await run_in_threadpool(
run_script, deps, deps.plugin_store, uid, rec, act["script"],
payload={"trigger": "test"}, timeout_sec=int(act.get("timeoutSec") or 30),
)
except ActionError as e:
raise HTTPException(e.status, {"message": e.message, "kind": e.kind}) from None
if (mf.get("proxy") or {}).get("inspect"):
try:
return await run_inspect(_http(), deps, deps.plugin_store, uid, rec)
except ProxyError as e:
raise HTTPException(e.status, e.message) from None
return {"ok": True, "message": "plugin has no test check"}
@router.post("/api/plugins/{pid}/actions/{action}")
async def invoke_plugin_action(deps: State, caller: CallerDep, pid: str, action: str,
body: dict | None = Body(default=None)):
return await _invoke_action(deps, caller, pid, action, body, read=False)
# The JSON payload a GET carries in ``?payload=`` — small: list/get filters.
_READ_PAYLOAD_MAX = 8 * 1024
@router.get("/api/plugins/{pid}/actions/{action}")
async def read_plugin_action(deps: State, caller: CallerDep, pid: str, action: str,
payload: str = ""):
"""The same action by GET, for actions the manifest marks ``readOnly`` —
what lets a read-only account (the screenshot bot, which may only use
safe methods) load a plugin page's data."""
body: dict = {}
if payload:
if len(payload) > _READ_PAYLOAD_MAX:
raise HTTPException(413, "payload too large for a GET")
try:
body = json.loads(payload)
except ValueError:
raise HTTPException(400, "payload must be JSON") from None
if not isinstance(body, dict):
raise HTTPException(400, "payload must be a JSON object")
return await _invoke_action(deps, caller, pid, action, body, read=True)
async def _invoke_action(deps, caller, pid: str, action: str, body: dict | None, *,
read: bool):
uid = _uid(caller)
rec, grant, is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not active")
act = (rec["manifest"].get("actions") or {}).get(action)
if not act:
raise HTTPException(404, f"action '{action}' not declared")
if read and not act.get("readOnly"):
raise HTTPException(405, f"action '{action}' is not read-only: POST it")
if act.get("ownerOnly") and not caller.is_owner:
raise HTTPException(403, f"action '{action}' is owner-only")
using_own = deps.plugin_store.has_user_override_secret(uid, pid, rec["manifest"]) if is_managed else False
run_uid = uid
requester_ctx = None
if act.get("runAs") == "owner" and is_managed and not caller.is_owner:
requester_ctx = requester_context(deps, uid, grant)
run_uid = OWNER_UID
payload = body if isinstance(body, dict) else {}
def run() -> Any:
return run_in_threadpool(
run_script, deps, deps.plugin_store, run_uid, rec, act["script"],
payload=payload,
timeout_sec=int(act.get("timeoutSec") or 30),
grant=grant,
using_own_secret=using_own,
requester=requester_ctx,
)
try:
if act.get("readOnly"):
# The same read asked twice at once (a page and its slot, two
# tabs) runs once: one handler process, one answer for both.
key = singleflight.key_of(uid, run_uid, pid, action, payload=payload)
return await singleflight.shared(key, run)
return await run()
except ActionError as e:
raise HTTPException(e.status, {"message": e.message, "kind": e.kind}) from None
finally:
if not read:
plugin_banner.touched(deps, rec)
machine_attention.touched(deps, rec, action=action)
machine_wake.touched(deps, rec, action=action)
# ── v2/v3 sandboxed HTML document loader ─────────────────────────────────────
@router.get("/api/plugins/{pid}/ui/{kind}/{sub_id}", response_class=PlainTextResponse)
def plugin_ui_html(deps: State, caller: CallerDep, pid: str, kind: str, sub_id: str):
"""Return the raw HTML document a sandboxed frame renders (never served as
text/html on the app origin — fetched by React and handed to
``/sandbox-frame.html`` via postMessage)."""
uid = _uid(caller)
rec, _grant, _is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not active")
ui = (rec["manifest"].get("ui") or {})
rel = None
if kind == "settings":
rel = ui.get("settingsHtml")
elif kind == "page":
hit = next((p for p in (ui.get("pages") or []) if p["id"] == sub_id), None)
rel = hit["html"] if hit else None
elif kind == "toolCard":
hit = next((t for t in (ui.get("toolCards") or []) if t["id"] == sub_id), None)
rel = hit["html"] if hit else None
elif kind == "slot":
hit = next((s for s in (ui.get("slots") or []) if s["id"] == sub_id), None)
rel = hit["html"] if hit else None
elif kind == "overlay":
hit = next((o for o in (ui.get("overlays") or []) if o["id"] == sub_id), None)
rel = hit["html"] if hit else None
elif kind == "menuItem":
hit = next((m for m in (ui.get("menuItems") or []) if m["id"] == sub_id), None)
rel = hit["html"] if hit else None
elif kind == "fence":
hit = next((f for f in (ui.get("fences") or []) if f["id"] == sub_id), None)
rel = hit["html"] if hit else None
if not rel:
raise HTTPException(404, "UI document not declared")
root = pathlib.Path(rec["dir"]).resolve()
target = (root / rel).resolve()
try:
target.relative_to(root)
except ValueError:
raise HTTPException(400, "invalid UI path") from None
if not target.is_file():
raise HTTPException(404, "UI file not found")
return target.read_text(encoding="utf-8", errors="replace")[:512 * 1024]
# ── art + info: what a plugin looks like and what it does ─────────────────────
_ASSET_TYPES = {".svg": "image/svg+xml", ".webp": "image/webp", ".png": "image/png",
".jpg": "image/jpeg", ".jpeg": "image/jpeg"}
# The files are drawn through <img> / CSS masks, never as a document; should
# one be opened directly, it has no origin, no scripts and nothing to load.
_ASSET_HEADERS = {
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox",
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, max-age=86400",
}
def _visible_plugin(deps: State, caller, pid: str) -> tuple[dict[str, Any], pathlib.Path, str, dict[str, Any] | None] | None:
"""``(manifest, plugin dir, how, own record)`` for a plugin the caller may
look at: their own install (in any state), an owner-managed plugin granted
to them, or an entry of the hub catalog they can see."""
uid = _uid(caller)
rec = deps.plugin_store.get_raw(uid, pid)
if rec:
return rec["manifest"], pathlib.Path(rec["dir"]), "installed", rec
if not caller.is_owner:
owner_rec, _grant, managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if owner_rec and managed:
return owner_rec["manifest"], pathlib.Path(owner_rec["dir"]), "managed", None
for c in deps.plugin_store.catalog(is_owner=caller.is_owner):
if c["id"] == pid and c.get("manifest"):
return c["manifest"], pathlib.Path(c["dir"]), "catalog", None
return None
def _plugin_file(root: pathlib.Path, rel: str | None, max_bytes: int) -> pathlib.Path | None:
if not rel:
return None
root = root.resolve()
target = (root / rel).resolve()
try:
target.relative_to(root)
except ValueError:
return None
if not target.is_file() or target.stat().st_size > max_bytes:
return None
return target
@router.get("/api/plugins/{pid}/asset/{kind}")
def plugin_asset(deps: State, caller: CallerDep, pid: str, kind: str):
"""A plugin's SVG icon or illustration (``kind`` = icon | illustration)."""
hit = _visible_plugin(deps, caller, pid)
if not hit or kind not in ("icon", "illustration"):
raise HTTPException(404, "no such plugin art")
mf, root, _how, _rec = hit
rel = mf.get("iconSvg") if kind == "icon" else mf.get("illustration")
target = _plugin_file(root, rel, 1024 * 1024)
media = _ASSET_TYPES.get(target.suffix.lower()) if target else None
if not target or not media:
raise HTTPException(404, "no such plugin art")
data = target.read_bytes()
# Checked again: the file may have changed on disk since the install.
if media == "image/svg+xml" and svg_problem(data):
raise HTTPException(404, "plugin art refused")
return Response(content=data, media_type=media, headers=_ASSET_HEADERS)
@router.get("/api/plugins/{pid}/info")
def plugin_info(deps: State, caller: CallerDep, pid: str):
"""The plugin's info page: what it does (README), what it can reach,
its jobs, webhooks, actions and pages, version, author and source."""
hit = _visible_plugin(deps, caller, pid)
if not hit:
raise HTTPException(404, f"plugin '{pid}' not found")
mf, root, how, rec = hit
readme_path = _plugin_file(root, mf.get("readme"), 64 * 1024)
readme = readme_path.read_text(encoding="utf-8", errors="replace") if readme_path else ""
sched_state = (rec or {}).get("schedulesState") or {}
proxy = mf.get("proxy") or {}
ui = mf.get("ui") or {}
return {
"id": pid,
"kind": mf.get("kind") or "app",
"typed": typed_summary(deps, mf, (rec or {}).get("config")) if caller.is_owner else None,
"name": mf.get("name") or pid,
"version": mf.get("version") or "",
"description": mf.get("description") or "",
"icon": mf.get("icon") or "puzzle",
**art_fields(pid, mf),
"how": how,
"readme": readme,
"capabilities": capability_summary(mf),
"skillName": (mf.get("skill") or {}).get("name"),
"proxyHost": urlsplit(proxy["baseUrl"]).netloc if proxy.get("baseUrl") else None,
"schedules": [
{"id": sc["id"], "cron": sc["cron"], "description": sc.get("description") or "",
"last": sched_state.get(sc["id"])}
for sc in (mf.get("schedules") or [])
],
"webhooks": [
{"id": w["id"], "mode": w["mode"], "description": w.get("description") or ""}
for w in (mf.get("webhooks") or [])
],
"actions": [
{"id": k, "description": v.get("description") or ""}
for k, v in sorted((mf.get("actions") or {}).items())
],
"pages": [
{"id": pg["id"], "label": pg["label"], "nav": pg["nav"], "to": f"/plugins/{pid}/{pg['id']}"}
for pg in (ui.get("pages") or [])
],
"requires": list(mf.get("requires") or []),
"exports": list(mf.get("exports") or []),
"emits": list(mf.get("emits") or []),
"dependents": deps.plugin_store.enabled_dependents(_uid(caller), pid),
"agents": [ag["name"] for ag in (mf.get("agents") or [])],
# Where it was installed from: only to whoever installed it, or the
# operator — a guest is not shown the owner's paths.
"source": (rec or {}).get("sourceRaw") if (rec or caller.is_owner) else None,
"installedAt": (rec or {}).get("installedAt"),
"updatedAt": (rec or {}).get("updatedAt"),
}
_STARTER_ICON = (
'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" '
'stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">'
'<path d="M9 3h6v3a2 2 0 1 0 4 0V3h0a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4z"/>'
'</svg>\n')
# ── + New plugin: scaffold & spawn a build conversation ──────────────────────
@router.post("/api/plugins/create-session")
def create_plugin_session(deps: State, caller: CallerDep, body: dict = Body(...)):
"""Scaffold a starter plugin directory and start a conversation using the
``create-plugin`` skill."""
if not (caller.is_owner or caller.has("plugins.create")):
raise HTTPException(403, "plugins.create permission required")
raw_name = str((body or {}).get("name") or "").strip()
slug = re.sub(r"[^a-z0-9]+", "-", raw_name.lower()).strip("-")[:40]
if not slug or not _SLUG_RE.match(slug):
raise HTTPException(400, "plugin name must contain letters or digits")
idea = str((body or {}).get("description") or "").strip()[:2000]
proj_dir = pathlib.Path(os.environ.get("PROJECTS_DIR", "/workspace/projects")).resolve()
host_proj = (os.environ.get("PROJECTS_HOST_DIR") or "/home/gabrielvidal/projects").rstrip("/")
if caller.is_owner:
# Owner plugins live in ~/projects/ai-agent-plugins/plugins/<slug>
repo_dir = proj_dir / "ai-agent-plugins"
target_dir = repo_dir / "plugins" / slug
host_dir = f"{host_proj}/ai-agent-plugins/plugins/{slug}"
cwd_host = f"{host_proj}/ai-agent-plugins"
project_slug = "ai-agent-plugins"
else:
# Guest plugins live in their own folder under ~/projects/plugin-<uid>-<slug>
project_slug = f"plugin-{caller.id}-{slug}"[:48]
target_dir = proj_dir / project_slug
host_dir = f"{host_proj}/{project_slug}"
cwd_host = host_dir
if not target_dir.exists():
(target_dir / "skill").mkdir(parents=True, exist_ok=True)
starter = {
"schema": 1,
"id": slug,
"name": raw_name or slug.replace("-", " ").title(),
"version": "0.1.0",
"description": idea[:200] or f"Live plugin: {slug}",
"icon": "puzzle",
"skill": {"dir": "skill", "name": slug},
}
(target_dir / "plugin.json").write_text(json.dumps(starter, indent=2) + "\n", encoding="utf-8")
(target_dir / "skill" / "SKILL.md").write_text(
f"---\nname: {slug}\ndescription: {starter['description']}\n---\n\n# {starter['name']}\n",
encoding="utf-8",
)
# Art the build replaces: a neutral icon (shown on a colour tile) and
# the README the plugin's info page shows.
(target_dir / "icon.svg").write_text(_STARTER_ICON, encoding="utf-8")
(target_dir / "README.md").write_text(
f"# {starter['name']}\n\n{starter['description']}\n", encoding="utf-8")
# Initialize git repo for guest standalone plugin if needed
if not caller.is_owner and not (target_dir / ".git").exists():
subprocess.run(["git", "init", "-b", "main", str(target_dir)], capture_output=True)
deps.users.grant_project(caller.id, project_slug, "ship")
prompt = (
f"Build a live ai-agent plugin `{slug}` in `{host_dir}` using the `create-plugin` skill.\n\n"
f"Goal: {idea or 'Ask me what this plugin should connect to and do.'}\n\n"
"Give it its art: an `icon.svg` (24×24, strokes in currentColor), an `illustration.webp` "
"(16:9, made with the nanobanana skill), a `color` in plugin.json, and a short user-facing "
"README.md (its info page).\n\n"
f"Validate it with `ai-agent plugin validate {host_dir}` and install it live once working."
)
from runs.routes import SpawnBody, spawn_run
res = spawn_run(
deps, caller,
SpawnBody(
prompt=prompt,
cwd=cwd_host if caller.is_owner else None,
projects=[project_slug],
),
request=None,
)
return {"ok": True, "slug": slug, "dir": host_dir, **res}