A sandboxed frame may now ask the host to install or uninstall a plugin of
the public catalog — never do it itself (form
plugin-catalog-and-public-plugins-repo_al2ibd):
- New operator-only capability `plugins.manage` (in the approval
fingerprint). aiAgentPlugin.plugins.list() / .install({source}) /
.uninstall({id}) answer only the operator, and only a plugin of theirs that
holds it (enabled, approved); anyone else gets a refusal.
- An install source must be `<catalogRepo>#plugins/<id>`; the host validates
it (refreshed clone), checks the folder holds that id and draws the
confirmation — name, version, source, every capability, what an update
replaces — before its own POST /api/plugins/install. An uninstall asks keep
or delete data and secrets each time. A plugin can't uninstall itself.
- PLUGIN_CATALOG_REPO (plugins/catalog_repo.py, default the public mirror
gabrielvidal/ai-agent-plugins-public.git), served as `catalogRepo` on
GET /api/plugins to the operator only.
- Settings → Plugins (operator): All / Installed / Available gives way to
*Browse the catalog* (the page that opens `plugin-catalog`); promoted hub
catalog entries wear *For guests*; old ?show=available / ?tab=catalog&kind=
links redirect to the plugin's page on that shelf; with the plugin off, a
note offers to install it again. Guests' page unchanged.
Tests: test_plugin_catalog_bridge.py (capability, repo rule, guest kept out),
catalogBridge.test.tsx (refusals, confirm-then-install, cancel, keep/delete).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1439 lines
68 KiB
Python
1439 lines
68 KiB
Python
"""``/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, Request, Response
|
||
from fastapi.responses import JSONResponse, 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 chrome_bridge
|
||
from plugins import keymap as plugin_keymap_mod
|
||
from plugins import commands as plugin_commands
|
||
from plugins import home_tiles as plugin_home_tiles
|
||
from plugins import launch as plugin_launch
|
||
from plugins import batch as plugin_batch
|
||
from plugins import keyspend, metering, singleflight
|
||
from plugins import catalog_repo as plugin_catalog_repo
|
||
from plugins import machine_attention, machine_wake
|
||
from plugins import shortcuts as plugin_shortcuts
|
||
from plugins import waiting as plugin_waiting
|
||
from plugins.categories import category_of
|
||
from plugins.manifest import _SLOT_PLACES, ManifestError, capability_summary, svg_problem
|
||
from plugins.proxy import ProxyError, run_inspect
|
||
from plugins.runner import ActionError, run_script
|
||
from plugins.store import OWNER_UID, DependencyError, _UNSET, art_fields
|
||
from toolproxy import access
|
||
from users.caller import CallerDep, OwnerDep
|
||
|
||
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),
|
||
"category": category_of(mf, rec.get("dir")),
|
||
"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 []:
|
||
# a page that names a permission is the holders' only (the
|
||
# whats-new plugin's editor: users.manage)
|
||
if pg.get("perm") and not caller.has(pg["perm"]):
|
||
continue
|
||
# …and one that names ``unless`` isn't theirs (the cron-jobs
|
||
# plugin's guest page, hidden from the owner: automation.manage)
|
||
if pg.get("unless") and caller.has(pg["unless"]):
|
||
continue
|
||
pages.append({**pg, "pluginId": pid, "pluginName": p["name"],
|
||
"description": mf.get("description") or "",
|
||
# a Settings entry lives under /settings (its
|
||
# panel, its section); the rest under /plugins
|
||
"to": f"/settings/p/{pid}/{pg['id']}" if pg.get("nav") == "settings"
|
||
else 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/keymap")
|
||
def plugin_keymap(deps: State, caller: CallerDep):
|
||
"""The caller's keyboard shortcuts from the plugin providing
|
||
``app.keymap`` (``plugins/keymap.py``): ``{enabled, bindings: [{command,
|
||
keys}], pluginId}`` — ``enabled: false`` and no bindings without one."""
|
||
return plugin_keymap_mod.keymap_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/services-index", responses=_r(schemas.ServicesIndexResponse))
|
||
def plugin_services_index(deps: State, _: OwnerDep):
|
||
"""The homelab services catalogue from the plugin providing
|
||
``services.index`` (``plugins/services_bridge.py``, cached 30 s): what the
|
||
tag registry, the composer's service chips and ``ai-agent tags`` read —
|
||
``[]`` without the plugin (``/api/services`` left the core on 2026-11-28)."""
|
||
from plugins import services_bridge
|
||
return {"services": services_bridge.list_services(deps)}
|
||
|
||
|
||
@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/plugins/app-launch", responses=_r(schemas.AppLaunchResponse))
|
||
def plugin_app_launch(deps: State, caller: CallerDep, reason: str = "load", path: str = "/"):
|
||
"""What the caller's active plugins open on their own as the app opens
|
||
(``provides: app.launch`` — ``plugins/launch.py``): a load, or the app back
|
||
in the foreground. Each item is one of the plugin's ``app.modal`` slots."""
|
||
return {"open": plugin_launch.launch_for(deps, caller, reason, path)}
|
||
|
||
|
||
@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 (and of the lab browser)
|
||
may have changed, and the ``mcp-servers`` / ``lab-chrome`` plugins may now
|
||
carry the core's old data over."""
|
||
if uid != OWNER_UID:
|
||
return
|
||
machine_attention.changed()
|
||
machine_wake.changed()
|
||
chrome_bridge.invalidate()
|
||
try:
|
||
deps.hub.publish({"type": "machine-attention"})
|
||
deps.hub.publish({"type": "machine-wake"})
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
if pid == "lab-chrome":
|
||
# Settings → Browser's old settings, into the plugin's config now
|
||
# that it is installed (carryover.chrome — once).
|
||
from plugins import carryover
|
||
try:
|
||
carryover.chrome(deps.plugin_store)
|
||
except Exception: # noqa: BLE001 — a carry-over never fails the change
|
||
import logging
|
||
logging.getLogger(__name__).exception("lab-chrome carry-over failed")
|
||
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")
|
||
from plugins import carryover
|
||
if pid in carryover.TOOL_PLUGINS:
|
||
# The retired core tool proxy's switches and data (2026-11-26): the
|
||
# plugin that takes them over has just come in.
|
||
try:
|
||
carryover.tools(deps.plugin_store, deps.users)
|
||
except Exception: # noqa: BLE001 — a carry-over never fails the change
|
||
import logging
|
||
logging.getLogger(__name__).exception("tool 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"),
|
||
# where the plugin-catalog plugin's Install buttons may install from
|
||
# (plugins/catalog_repo.py) — the operator's only
|
||
"catalogRepo": plugin_catalog_repo.repo() if caller.is_owner else None,
|
||
"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,
|
||
root: Any = 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}
|
||
if kind == "translation" and mf.get("translation"):
|
||
return translation_summary(mf, root)
|
||
return None
|
||
|
||
|
||
def translation_summary(mf: dict[str, Any], root: Any = None) -> dict[str, Any]:
|
||
"""A translation's section: its language, whether it is the one the app
|
||
uses for that code, and how many of the core's English strings it is
|
||
missing (``plugins/translations.coverage``) — from the active copy, else
|
||
read off its folder (a catalog entry, a disabled install)."""
|
||
import pathlib
|
||
from plugins import translations as tr_mod
|
||
from plugins.typed_manifest import load_dictionary
|
||
tv = mf["translation"]
|
||
held = tr_mod.current().get(tv.get("lang"))
|
||
t = held if held is not None and held.plugin_id == mf.get("id") else None
|
||
if t is None and root:
|
||
dicts = {}
|
||
for key in ("ui", "backend"):
|
||
errs: list[str] = []
|
||
dicts[key] = load_dictionary(pathlib.Path(root) / tv[key], key, errs) if tv.get(key) else {}
|
||
t = tr_mod.Translation(lang=tv["lang"], plugin_id=mf.get("id") or "", name=tv.get("name") or "",
|
||
english_name=tv.get("englishName") or "", flag=tv.get("flag"),
|
||
locale=tv.get("locale") or "", prompt_line=tv.get("promptLine"),
|
||
ui=dicts["ui"], backend=dicts["backend"])
|
||
return {"kind": "translation", "lang": tv.get("lang"), "name": tv.get("name"),
|
||
"englishName": tv.get("englishName"), "flag": tv.get("flag"),
|
||
"locale": tv.get("locale"), "promptLine": tv.get("promptLine"),
|
||
"uiCount": tv.get("uiCount") or 0, "backendCount": tv.get("backendCount") or 0,
|
||
"active": held is not None and held.plugin_id == mf.get("id"),
|
||
"heldBy": held.plugin_id if held is not None and held.plugin_id != mf.get("id") else None,
|
||
"coverage": tr_mod.coverage(t) if t is not None else 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_keymap_mod.invalidate()
|
||
plugin_home_tiles.invalidate(rec["id"])
|
||
plugin_waiting.invalidate(rec["id"])
|
||
plugin_batch.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_keymap_mod.invalidate()
|
||
plugin_home_tiles.invalidate(pid)
|
||
plugin_waiting.invalidate(pid)
|
||
plugin_batch.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_keymap_mod.invalidate()
|
||
plugin_home_tiles.invalidate(pid)
|
||
plugin_waiting.invalidate(pid)
|
||
plugin_batch.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_keymap_mod.invalidate()
|
||
plugin_home_tiles.invalidate(pid)
|
||
plugin_waiting.invalidate(pid)
|
||
plugin_batch.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
|
||
plugin_batch.invalidate(str((entry or {}).get("id") or "") or None)
|
||
deps.hub.publish({"type": "plugins"})
|
||
_plugin_changed(deps, str((entry or {}).get("id") or ""), OWNER_UID)
|
||
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")
|
||
grant = apply_managed_grant(deps, uid, pid, body)
|
||
return {"uid": uid, "id": pid, "grant": grant}
|
||
|
||
|
||
def apply_managed_grant(deps, uid: str, pid: str, body: dict) -> dict[str, Any]:
|
||
"""Write guest ``uid``'s grant for managed plugin ``pid`` from a body
|
||
``{enabled?, config?, monthlyBudgetUsd?}`` (an omitted budget is left
|
||
alone, ``null`` clears it; config keys merge, limited to ``grantFields``),
|
||
drop the caches that read grants and publish the change. Shared by the
|
||
owner's Users page and the ``hub/grants`` bridge (plugins/hubbridge.py)."""
|
||
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
|
||
was_on = False
|
||
try:
|
||
rec = deps.plugin_store.get_raw("owner", pid)
|
||
if rec and (rec.get("manifest") or {}).get("managed"):
|
||
was_on = bool(deps.plugin_store.effective_grant(uid, pid, rec["manifest"]).get("enabled"))
|
||
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, TypeError) as e:
|
||
raise HTTPException(400, str(e)) from None
|
||
if grant.get("enabled") and not was_on:
|
||
_granted(deps, uid, pid)
|
||
plugin_shortcuts.invalidate(pid)
|
||
plugin_keymap_mod.invalidate()
|
||
plugin_home_tiles.invalidate(pid)
|
||
plugin_waiting.invalidate(pid)
|
||
plugin_batch.invalidate(pid)
|
||
deps.hub.publish({"type": "plugins", "id": pid, "uid": uid})
|
||
return grant
|
||
|
||
|
||
def _granted(deps: State, uid: str, pid: str) -> None:
|
||
"""A managed plugin just came on for guest ``uid``: what the core does then.
|
||
Today one thing — Movies brings their Jellyfin app (``users/routes``)."""
|
||
from users import routes as user_routes
|
||
if pid != user_routes.MOVIES_PLUGIN:
|
||
return
|
||
try:
|
||
if user_routes.movies_bring_jellyfin(deps, uid):
|
||
from users import idp
|
||
if idp.enabled():
|
||
idp.sync(deps, deps.users.get(uid) or {})
|
||
deps.hub.publish({"type": "users"})
|
||
except Exception: # noqa: BLE001 — the grant itself already went through
|
||
import logging
|
||
logging.getLogger(__name__).warning("movies grant: Jellyfin for %s", uid, exc_info=True)
|
||
|
||
|
||
# ── 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",
|
||
"languages": mf.get("languages") or ["en"],
|
||
"typed": typed_summary(deps, mf, rec.get("config"), rec.get("dir")),
|
||
"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)
|
||
plugin_batch.invalidate(pid)
|
||
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)
|
||
plugin_batch.invalidate(pid)
|
||
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)
|
||
plugin_batch.invalidate(pid)
|
||
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):
|
||
# Who runs it and with what: one rule set, shared with the batch read.
|
||
call = plugin_batch.resolve_call(deps, caller, pid, action, read=read)
|
||
payload = body if isinstance(body, dict) else {}
|
||
rec = call.rec
|
||
uid = call.uid
|
||
try:
|
||
if call.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.
|
||
return await singleflight.shared(call.flight_key(payload), lambda: call.run(deps, payload))
|
||
return await call.run(deps, payload)
|
||
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)
|
||
chrome_bridge.touched(deps, rec)
|
||
plugin_keymap_mod.touched(deps, rec, uid)
|
||
plugin_shortcuts.touched(deps, rec)
|
||
machine_attention.touched(deps, rec, action=action)
|
||
machine_wake.touched(deps, rec, action=action)
|
||
if not call.act.get("readOnly"):
|
||
# a write may change what the plugin's reads answer
|
||
plugin_batch.invalidate(pid)
|
||
|
||
|
||
# ── many reads in one request; every slot document of one place ──────────────
|
||
@router.post("/api/plugins/batch-read")
|
||
async def batch_read_post(deps: State, caller: CallerDep, request: Request):
|
||
"""Up to 32 ``readOnly`` actions at once — ``{items: [{key, pluginId,
|
||
action, payload?, fresh?}], fresh?}`` → ``{results: {key: …}}``, each
|
||
item answered on its own (plugins/batch.py)."""
|
||
raw = await request.body()
|
||
if len(raw) > plugin_batch.BODY_MAX:
|
||
raise HTTPException(413, "batch too large")
|
||
try:
|
||
body = json.loads(raw or b"{}")
|
||
except ValueError:
|
||
raise HTTPException(400, "body must be JSON") from None
|
||
if not isinstance(body, dict):
|
||
raise HTTPException(400, "body must be a JSON object")
|
||
items = plugin_batch.parse_items(body.get("items", []))
|
||
return await plugin_batch.batch_read(deps, caller, items, fresh=bool(body.get("fresh")))
|
||
|
||
|
||
@router.get("/api/plugins/batch-read")
|
||
async def batch_read_get(deps: State, caller: CallerDep, items: str = "[]", fresh: bool = False):
|
||
"""The same by GET (``?items=<JSON array>``), for a caller limited to safe
|
||
methods (the screenshot bot)."""
|
||
if len(items) > plugin_batch.GET_ITEMS_MAX:
|
||
raise HTTPException(413, "items too large for a GET")
|
||
try:
|
||
parsed = json.loads(items or "[]")
|
||
except ValueError:
|
||
raise HTTPException(400, "items must be JSON") from None
|
||
return await plugin_batch.batch_read(deps, caller, plugin_batch.parse_items(parsed), fresh=fresh)
|
||
|
||
|
||
@router.get("/api/plugins/ui-bundle")
|
||
def plugin_ui_bundle(deps: State, caller: CallerDep, request: Request, where: str = ""):
|
||
"""Every active slot document for ``where`` in one body —
|
||
``{where, version, docs: {"<pid>:<slot>": html}}``, ETag'd (304)."""
|
||
if where not in _SLOT_PLACES:
|
||
raise HTTPException(400, f"where must be one of {sorted(_SLOT_PLACES)}")
|
||
version, body = plugin_batch.ui_bundle(deps, caller, where, request.headers.get("if-none-match"))
|
||
headers = {"ETag": f'"{version}"', "Cache-Control": "private, no-cache"}
|
||
if body is None:
|
||
return Response(status_code=304, headers=headers)
|
||
return JSONResponse(body, headers=headers)
|
||
|
||
|
||
# ── 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",
|
||
"languages": mf.get("languages") or ["en"],
|
||
"typed": typed_summary(deps, mf, (rec or {}).get("config"), root) 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 []),
|
||
# the optional peers, and which of them are active for the caller now
|
||
"optionalRequires": list(mf.get("optionalRequires") or []),
|
||
"peersActive": [p for p in (mf.get("optionalRequires") or [])
|
||
if deps.plugin_store.resolve_active_for_caller(_uid(caller), p)[0]],
|
||
"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}
|