Orca's layout in the app's own look (form plugins-page-rework_rhce3j): a category sidebar with counts (a chip row on a phone), search, All / Installed / Available, a sort (Installed first, Name, Recently updated — per person), and cover cards or compact rows (the grid / list toggle is kept). - New manifest field `category` (backend/plugins/categories.py), strict: an app picks dev, data, agents, chat, scheduling, media or other (the default); a provider / harness / translation sits under its kind's shelf. Not in the approval fingerprint. Every row of GET /api/plugins carries the resolved category; a record from before the field reads its source's plugin.json. - Translations works as soon as the translation kind exists; an empty category is hidden. - ?cat= / ?show= addresses; the old ?tab= / ?kind= links still land. - Docs: docs/plugins.md → "Categories and the Plugins page", CLAUDE.md. Deploy this before installing ai-agent-plugins' plugin-categories branch: an older core refuses the unknown `category` key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1352 lines
64 KiB
Python
1352 lines
64 KiB
Python
"""Plugin registry, hub catalog, write-only per-user secrets, per-user storage
|
|
and live-skill materialization.
|
|
|
|
Directory layout under ``PLUGINS_DIR`` (default ``/data/plugins``):
|
|
* ``installed.json`` — per-user installs + hub catalog entries
|
|
* ``secrets/<uid>/<id>.json`` (0600) — write-only user secrets (``_hub`` for hub-scoped)
|
|
* ``data/<uid>/<id>/`` — per-user plugin data & snapshots (quota enforced)
|
|
* ``live-skills/<uid>/<id>/`` — materialized ``skill/`` copy for runs & labsync
|
|
* ``repos/<hash>/`` — shallow clones of git-URL plugins
|
|
* ``live-harnesses/<id>/`` + ``index.json`` — the owner's enabled ``kind:
|
|
"harness"`` plugins' sidecar driver (+ runner dir) and ``plugin.json``, what
|
|
the host sidecar loads (``POST /harnesses/reload``) and labsync ships
|
|
* ``live-providers/<id>/`` + ``index.json`` — the enabled ``kind: "provider"``
|
|
plugins' usage reader, ``plugin.json`` and non-secret config (accounts)
|
|
* ``live-hooks/index.json`` (+ ``<id>/<script>``) — the owner's plugins'
|
|
``harnessHooks`` that apply to the lab (plugins/harness_hooks.py)
|
|
* ``discovery/<vendor>.json``, ``pricing-snapshot.json`` — plugins/providers.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import secrets
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
from typing import Any
|
|
|
|
from core.config import WORKSPACE
|
|
from plugins.categories import category_of
|
|
from plugins.manifest import (
|
|
ManifestError,
|
|
capability_fingerprint,
|
|
capability_summary,
|
|
requires_operator,
|
|
validate_manifest,
|
|
)
|
|
|
|
OWNER_UID = "owner"
|
|
HUB_SECRET_UID = "_hub"
|
|
_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
|
|
_GIT_URL_RE = re.compile(r"^(https?://|ssh://|git@)[^\s]+$")
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
_UNSET = object()
|
|
|
|
|
|
class DependencyError(ValueError):
|
|
"""Raised when an install/enable is missing required plugins or a
|
|
disable/uninstall is blocked by enabled dependents."""
|
|
|
|
def __init__(self, message: str, *, missing: list[str] | None = None,
|
|
dependents: list[str] | None = None):
|
|
super().__init__(message)
|
|
self.missing = list(missing or [])
|
|
self.dependents = list(dependents or [])
|
|
|
|
|
|
def _projects_roots() -> tuple[pathlib.Path, str]:
|
|
"""(container projects dir, host projects prefix if known)."""
|
|
proj = pathlib.Path(os.environ.get("PROJECTS_DIR", str(WORKSPACE / "projects"))).resolve()
|
|
host_proj = os.environ.get("PROJECTS_HOST_DIR") or "/home/gabrielvidal/projects"
|
|
return proj, host_proj.rstrip("/")
|
|
|
|
|
|
def _worktrees_roots() -> tuple[pathlib.Path, str]:
|
|
"""(container worktrees dir, host worktrees prefix if known)."""
|
|
wt = pathlib.Path(os.environ.get("WORKTREES_DIR", "/worktrees")).resolve()
|
|
host_wt = os.environ.get("WORKTREES_HOST_DIR") or "/home/gabrielvidal/worktrees"
|
|
return wt, host_wt.rstrip("/")
|
|
|
|
|
|
def clean_provider_accounts(value: Any, manifest: dict[str, Any]) -> list[dict[str, Any]]:
|
|
"""The owner's edits to a provider's accounts (its settings): a list of
|
|
``{id, …fields}`` — an override of a declared account (only the fields it
|
|
sets), a new account (every field normalized), or ``{id, removed: true}``.
|
|
Invalid entries are refused (``ManifestError``), not dropped."""
|
|
from plugins.typed_manifest import ACCOUNT_EDITABLE, _ACCOUNT_RE, clean_account
|
|
if not isinstance(value, list) or len(value) > 64:
|
|
raise ManifestError(["accounts must be an array (<= 64)"])
|
|
declared = {a["id"] for a in ((manifest.get("provider") or {}).get("accounts") or [])}
|
|
out: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
errors: list[str] = []
|
|
for i, a in enumerate(value):
|
|
if not isinstance(a, dict):
|
|
errors.append(f"accounts[{i}] must be an object")
|
|
continue
|
|
aid = str(a.get("id") or "").strip().lower()
|
|
if not _ACCOUNT_RE.match(aid) or aid.startswith("guest-") or aid in seen:
|
|
errors.append(f"accounts[{i}].id invalid or duplicate: {aid!r}")
|
|
continue
|
|
seen.add(aid)
|
|
if a.get("removed"):
|
|
out.append({"id": aid, "removed": True})
|
|
continue
|
|
unknown = sorted(set(a) - set(ACCOUNT_EDITABLE) - {"id", "removed"})
|
|
if unknown:
|
|
errors.append(f"accounts[{i}]: unknown keys {', '.join(unknown)}")
|
|
continue
|
|
full = clean_account(aid, a, f"accounts[{i}]", errors)
|
|
if aid in declared:
|
|
out.append({"id": aid, **{k: full[k] for k in a if k in ACCOUNT_EDITABLE}})
|
|
else:
|
|
out.append(full)
|
|
if errors:
|
|
raise ManifestError(errors)
|
|
return out
|
|
|
|
|
|
def art_fields(pid: str, mf: dict[str, Any]) -> dict[str, Any]:
|
|
"""The card art of a plugin, as the browser uses it: URLs of the SVG icon
|
|
and the illustration (cache-busted by ``artVersion``), the accent colour
|
|
and whether it has a README."""
|
|
v = mf.get("artVersion") or ""
|
|
base = f"/api/plugins/{pid}/asset"
|
|
return {
|
|
"iconUrl": f"{base}/icon?v={v}" if mf.get("iconSvg") else None,
|
|
"illustrationUrl": f"{base}/illustration?v={v}" if mf.get("illustration") else None,
|
|
"color": mf.get("color"),
|
|
"author": mf.get("author") or "",
|
|
"hasReadme": bool(mf.get("readme")),
|
|
}
|
|
|
|
|
|
class PluginStore:
|
|
def __init__(self, root: str | pathlib.Path | None = None):
|
|
self.root = pathlib.Path(root or os.environ.get("PLUGINS_DIR", "/data/plugins"))
|
|
self.index_path = self.root / "installed.json"
|
|
self.secrets_dir = self.root / "secrets"
|
|
self.data_dir = self.root / "data"
|
|
self.live_skills_dir = self.root / "live-skills"
|
|
self.repos_dir = self.root / "repos"
|
|
self.live_harnesses_dir = self.root / "live-harnesses"
|
|
self.live_providers_dir = self.root / "live-providers"
|
|
# The owner's plugins' harnessHooks that apply to the lab, what the
|
|
# host sidecar's launches read (plugins/harness_hooks.py).
|
|
self.live_hooks_dir = self.root / "live-hooks"
|
|
# Called (no arguments) after the live harness / provider bundles
|
|
# changed on disk — core/state.py points it at the host sidecar's
|
|
# ``POST /harnesses/reload`` (best effort, off the request thread).
|
|
self.on_typed_change = None
|
|
self._lock = threading.RLock()
|
|
self._state = self._load()
|
|
# Bumped on every write: what derives from installed plugins (the
|
|
# conversation resource registry, plugins/resources.py) rebuilds on it.
|
|
self.version = 0
|
|
|
|
def _load(self) -> dict[str, Any]:
|
|
try:
|
|
raw = json.loads(self.index_path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
raw = {}
|
|
if not isinstance(raw, dict):
|
|
raw = {}
|
|
return {
|
|
"users": raw.get("users") if isinstance(raw.get("users"), dict) else {},
|
|
"catalog": raw.get("catalog") if isinstance(raw.get("catalog"), dict) else {},
|
|
"grants": raw.get("grants") if isinstance(raw.get("grants"), dict) else {},
|
|
"keyHealth": raw.get("keyHealth") if isinstance(raw.get("keyHealth"), dict) else {},
|
|
"keySettings": raw.get("keySettings") if isinstance(raw.get("keySettings"), dict) else {},
|
|
"secretHints": raw.get("secretHints") if isinstance(raw.get("secretHints"), dict) else {},
|
|
# typed plugins the hub seeded once (carryover.seed_typed_plugins):
|
|
# id → when — an uninstalled one is never seeded again
|
|
"seeded": raw.get("seeded") if isinstance(raw.get("seeded"), dict) else {},
|
|
}
|
|
|
|
def _save(self) -> None:
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
tmp = self.index_path.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps(self._state, indent=2, sort_keys=True), encoding="utf-8")
|
|
os.replace(tmp, self.index_path)
|
|
self.version += 1
|
|
|
|
@staticmethod
|
|
def norm_uid(uid: str | None) -> str:
|
|
u = (uid or OWNER_UID).strip().lower()
|
|
if u == OWNER_UID:
|
|
return OWNER_UID
|
|
if not _UID_RE.match(u):
|
|
raise ValueError(f"invalid uid: {uid!r}")
|
|
return u
|
|
|
|
# ── source resolution (local path or git URL#subdir) ─────────────────────
|
|
def resolve_source(self, source: str, *, allow_any_path: bool = False,
|
|
refresh_git: bool = False) -> tuple[pathlib.Path, dict[str, str]]:
|
|
"""Resolve ``source`` (local path or ``https://…/repo.git#plugins/foo``)
|
|
into a readable directory on disk + normalized source descriptor."""
|
|
raw = (source or "").strip()
|
|
if not raw:
|
|
raise ManifestError(["source path or git URL is required"])
|
|
if _GIT_URL_RE.match(raw):
|
|
repo_url, _, subpath = raw.partition("#")
|
|
key = hashlib.sha256(repo_url.encode()).hexdigest()[:16]
|
|
dest = self.repos_dir / key
|
|
self.repos_dir.mkdir(parents=True, exist_ok=True)
|
|
if not dest.is_dir():
|
|
p = subprocess.run(
|
|
["git", "clone", "--depth", "1", repo_url, str(dest)],
|
|
capture_output=True, text=True, timeout=60,
|
|
)
|
|
if p.returncode != 0:
|
|
raise ManifestError([f"git clone failed: {(p.stderr or p.stdout).strip()[:200]}"])
|
|
elif refresh_git:
|
|
subprocess.run(["git", "-C", str(dest), "pull", "--ff-only"],
|
|
capture_output=True, text=True, timeout=60)
|
|
rev = subprocess.run(["git", "-C", str(dest), "rev-parse", "--short", "HEAD"],
|
|
capture_output=True, text=True, timeout=10).stdout.strip()
|
|
target = (dest / subpath.strip("/")).resolve() if subpath.strip("/") else dest.resolve()
|
|
try:
|
|
target.relative_to(dest.resolve())
|
|
except ValueError:
|
|
raise ManifestError(["git subpath escapes repository"]) from None
|
|
return target, {"kind": "git", "url": raw, "rev": rev}
|
|
|
|
# Local path: map ~/projects/... -> PROJECTS_DIR and ~/worktrees/... -> /worktrees
|
|
proj_dir, host_proj = _projects_roots()
|
|
wt_dir, host_wt = _worktrees_roots()
|
|
expanded = raw
|
|
if expanded.startswith("~/projects/"):
|
|
candidate = (proj_dir / expanded[len("~/projects/"):]).resolve()
|
|
elif expanded.startswith(host_proj + "/"):
|
|
candidate = (proj_dir / expanded[len(host_proj) + 1:]).resolve()
|
|
elif expanded.startswith("/workspace/projects/"):
|
|
candidate = (proj_dir / expanded[len("/workspace/projects/"):]).resolve()
|
|
elif expanded.startswith("~/worktrees/"):
|
|
candidate = (wt_dir / expanded[len("~/worktrees/"):]).resolve()
|
|
elif expanded.startswith(host_wt + "/"):
|
|
candidate = (wt_dir / expanded[len(host_wt) + 1:]).resolve()
|
|
elif expanded.startswith("/worktrees/"):
|
|
candidate = (wt_dir / expanded[len("/worktrees/"):]).resolve()
|
|
else:
|
|
candidate = pathlib.Path(os.path.expanduser(expanded)).resolve()
|
|
|
|
if not allow_any_path:
|
|
# Non-owners (and standard installs) must resolve under PROJECTS_DIR
|
|
try:
|
|
candidate.relative_to(proj_dir)
|
|
except ValueError:
|
|
raise ManifestError(["local plugin paths must live under projects/"]) from None
|
|
if not candidate.is_dir():
|
|
raise ManifestError([f"plugin directory not found: {raw}"])
|
|
return candidate, {"kind": "path", "path": raw, "resolved": str(candidate)}
|
|
|
|
def inspect_source(self, source: str, *, allow_any_path: bool = False,
|
|
refresh_git: bool = False) -> dict[str, Any]:
|
|
"""Validate a source without installing it (preview for consent UI)."""
|
|
path, src_info = self.resolve_source(source, allow_any_path=allow_any_path,
|
|
refresh_git=refresh_git)
|
|
manifest = validate_manifest(path)
|
|
return {
|
|
"manifest": manifest,
|
|
"source": src_info,
|
|
"dir": str(path),
|
|
"fingerprint": capability_fingerprint(manifest),
|
|
"capabilities": capability_summary(manifest),
|
|
"requiresOperator": requires_operator(manifest),
|
|
"kind": manifest.get("kind") or "app",
|
|
}
|
|
|
|
# ── live skill materialization ───────────────────────────────────────────
|
|
def _sync_live_skill(self, uid: str, pid: str, plugin_dir: pathlib.Path,
|
|
manifest: dict[str, Any], enabled: bool) -> None:
|
|
dest = self.live_skills_dir / uid / pid
|
|
if dest.exists():
|
|
shutil.rmtree(dest, ignore_errors=True)
|
|
sk = manifest.get("skill")
|
|
if not enabled or not sk:
|
|
return
|
|
src = (plugin_dir / sk["dir"]).resolve()
|
|
if not (src / "SKILL.md").is_file():
|
|
return
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copytree(src, dest, symlinks=False,
|
|
ignore=shutil.ignore_patterns("__pycache__", ".git", "*.pyc"))
|
|
|
|
def live_skill_dirs(self, uid: str | None) -> list[dict[str, Any]]:
|
|
"""Enabled live plugins with a skill for ``uid`` (personal installs +
|
|
owner-managed grants for guests): ``[{id, name, dir, hasProxy}]``."""
|
|
u = self.norm_uid(uid)
|
|
out: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
with self._lock:
|
|
entries = dict(self._state["users"].get(u) or {})
|
|
for pid, rec in sorted(entries.items()):
|
|
if not rec.get("enabled") or rec.get("needsApproval"):
|
|
continue
|
|
mf = rec.get("manifest") or {}
|
|
sk = mf.get("skill")
|
|
if not sk:
|
|
continue
|
|
d = self.live_skills_dir / u / pid
|
|
if not (d / "SKILL.md").is_file():
|
|
# Re-materialize lazily if live-skills was wiped
|
|
try:
|
|
pdir, _ = self.resolve_source(rec["sourceRaw"], allow_any_path=True)
|
|
self._sync_live_skill(u, pid, pdir, mf, True)
|
|
except Exception:
|
|
continue
|
|
if (d / "SKILL.md").is_file():
|
|
seen.add(pid)
|
|
out.append({
|
|
"id": pid,
|
|
"name": sk["name"],
|
|
"ref": f"plugin:{u}/{pid}",
|
|
"dir": d,
|
|
"hasProxy": bool(mf.get("proxy") or mf.get("actions") or mf.get("storage")),
|
|
})
|
|
# Guests also receive skills from every active owner-managed grant.
|
|
if u != OWNER_UID:
|
|
for rec in self.managed_plugins():
|
|
pid = rec["id"]
|
|
if pid in seen:
|
|
continue
|
|
g = self.effective_grant(u, pid, rec["manifest"])
|
|
if not g["enabled"]:
|
|
continue
|
|
mf = rec.get("manifest") or {}
|
|
sk = mf.get("skill")
|
|
if not sk:
|
|
continue
|
|
d = self.live_skills_dir / OWNER_UID / pid
|
|
if not (d / "SKILL.md").is_file():
|
|
try:
|
|
pdir, _ = self.resolve_source(rec["sourceRaw"], allow_any_path=True)
|
|
self._sync_live_skill(OWNER_UID, pid, pdir, mf, True)
|
|
except Exception:
|
|
continue
|
|
if (d / "SKILL.md").is_file():
|
|
seen.add(pid)
|
|
out.append({
|
|
"id": pid,
|
|
"name": sk["name"],
|
|
# The owner's copy (the dir above): the sidecar reads
|
|
# ``live-skills/<uid>/<id>`` straight from the ref —
|
|
# ``plugin:managed/…`` named a folder that never existed.
|
|
"ref": f"plugin:{OWNER_UID}/{pid}",
|
|
"dir": d,
|
|
"hasProxy": bool(mf.get("proxy") or mf.get("actions") or mf.get("storage")),
|
|
})
|
|
return out
|
|
|
|
# ── dependencies (requires) ──────────────────────────────────────────────
|
|
def missing_requires(self, uid: str | None, requires: list[str] | None) -> list[str]:
|
|
"""Required plugin ids that are not currently active for ``uid``."""
|
|
u = self.norm_uid(uid)
|
|
missing = []
|
|
for dep in requires or []:
|
|
rec, _g, _m = self.resolve_active_for_caller(u, dep)
|
|
if rec is None:
|
|
missing.append(dep)
|
|
return missing
|
|
|
|
def enabled_dependents(self, uid: str | None, pid: str) -> list[str]:
|
|
"""Enabled, approved plugins for ``uid`` that list ``pid`` in ``requires``."""
|
|
u = self.norm_uid(uid)
|
|
out: list[str] = []
|
|
with self._lock:
|
|
u_map = dict(self._state["users"].get(u) or {})
|
|
for other_id, rec in sorted(u_map.items()):
|
|
if other_id == pid or not rec.get("enabled") or rec.get("needsApproval"):
|
|
continue
|
|
if pid in ((rec.get("manifest") or {}).get("requires") or []):
|
|
out.append(other_id)
|
|
return out
|
|
|
|
# ── install / reload / update / uninstall ────────────────────────────────
|
|
def install(self, uid: str | None, source: str, *, is_owner: bool,
|
|
approve: bool = True, catalog_id: str | None = None) -> dict[str, Any]:
|
|
u = self.norm_uid(uid)
|
|
cat_entry = None
|
|
if catalog_id:
|
|
with self._lock:
|
|
cat_entry = self._state["catalog"].get(catalog_id)
|
|
if not cat_entry:
|
|
raise ManifestError([f"catalog plugin '{catalog_id}' not found"])
|
|
source = cat_entry["sourceRaw"]
|
|
info = self.inspect_source(source, allow_any_path=is_owner or bool(cat_entry),
|
|
refresh_git=True)
|
|
mf = info["manifest"]
|
|
if info["requiresOperator"] and not is_owner:
|
|
# Non-owners may install an operator-privileged plugin ONLY from the
|
|
# hub catalog whose fingerprint matches the operator's approved one.
|
|
if not cat_entry or cat_entry.get("fingerprint") != info["fingerprint"]:
|
|
raise ManifestError(["this plugin requires operator approval (internal host or hub secret)"])
|
|
if not approve:
|
|
raise ManifestError(["approval required before installing"])
|
|
if (mf.get("kind") or "app") != "app" and u != OWNER_UID:
|
|
raise ManifestError([f"a {mf['kind']} plugin is the operator's own: it can't be installed for {u}"])
|
|
|
|
missing = self.missing_requires(u, mf.get("requires"))
|
|
if missing:
|
|
raise DependencyError(
|
|
f"plugin '{mf['id']}' requires {', '.join(missing)} to be installed and enabled first",
|
|
missing=missing,
|
|
)
|
|
|
|
pid = mf["id"]
|
|
now = _now_iso()
|
|
with self._lock:
|
|
u_map = self._state["users"].setdefault(u, {})
|
|
prev = u_map.get(pid) or {}
|
|
wh_tokens = dict(prev.get("webhookTokens") or {})
|
|
for wh in mf.get("webhooks") or []:
|
|
wh_tokens.setdefault(wh["id"], secrets.token_urlsafe(24))
|
|
# Preserve existing non-secret config defaults
|
|
cfg = dict(prev.get("config") or {})
|
|
for f in (mf.get("settings") or {}).get("fields") or []:
|
|
if f["key"] not in cfg and f.get("default") is not None:
|
|
cfg[f["key"]] = f["default"]
|
|
rec = {
|
|
"id": pid,
|
|
"sourceRaw": source,
|
|
"source": info["source"],
|
|
"dir": info["dir"],
|
|
"manifest": mf,
|
|
"fingerprint": info["fingerprint"],
|
|
"capabilities": info["capabilities"],
|
|
"requiresOperator": info["requiresOperator"],
|
|
"enabled": True,
|
|
"needsApproval": False,
|
|
"fromCatalog": catalog_id or prev.get("fromCatalog"),
|
|
"config": cfg,
|
|
"webhookTokens": wh_tokens,
|
|
"schedulesState": dict(prev.get("schedulesState") or {}),
|
|
"installedAt": prev.get("installedAt") or now,
|
|
"updatedAt": now,
|
|
}
|
|
u_map[pid] = rec
|
|
self._save()
|
|
self._sync_live_skill(u, pid, pathlib.Path(info["dir"]), mf, True)
|
|
self._typed_touched(u, mf)
|
|
return self._public_record(u, rec)
|
|
|
|
def reload(self, uid: str | None, pid: str, *, is_owner: bool,
|
|
approve: bool = False) -> dict[str, Any]:
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
rec = (self._state["users"].get(u) or {}).get(pid)
|
|
if not rec:
|
|
raise KeyError(pid)
|
|
source = rec["sourceRaw"]
|
|
from_cat = rec.get("fromCatalog")
|
|
info = self.inspect_source(source, allow_any_path=is_owner or bool(from_cat),
|
|
refresh_git=True)
|
|
mf = info["manifest"]
|
|
widened = info["fingerprint"] != rec.get("fingerprint")
|
|
if info["requiresOperator"] and not is_owner:
|
|
cat = self._state["catalog"].get(from_cat or "")
|
|
if not cat or cat.get("fingerprint") != info["fingerprint"]:
|
|
raise ManifestError(["reloaded plugin asks for operator-only capability"])
|
|
needs = widened and not approve
|
|
with self._lock:
|
|
rec = self._state["users"][u][pid]
|
|
wh_tokens = dict(rec.get("webhookTokens") or {})
|
|
for wh in mf.get("webhooks") or []:
|
|
wh_tokens.setdefault(wh["id"], secrets.token_urlsafe(24))
|
|
rec.update({
|
|
"source": info["source"],
|
|
"dir": info["dir"],
|
|
"manifest": mf,
|
|
"capabilities": info["capabilities"],
|
|
"requiresOperator": info["requiresOperator"],
|
|
"webhookTokens": wh_tokens,
|
|
"updatedAt": _now_iso(),
|
|
})
|
|
if not needs:
|
|
rec["fingerprint"] = info["fingerprint"]
|
|
rec["needsApproval"] = False
|
|
else:
|
|
rec["pendingFingerprint"] = info["fingerprint"]
|
|
rec["needsApproval"] = True
|
|
self._save()
|
|
enabled = bool(rec.get("enabled")) and not rec.get("needsApproval")
|
|
out = self._public_record(u, rec)
|
|
self._sync_live_skill(u, pid, pathlib.Path(info["dir"]), mf, enabled)
|
|
self._typed_touched(u, mf)
|
|
return out
|
|
|
|
def update(self, uid: str | None, pid: str, *, enabled: bool | None = None,
|
|
config: dict[str, Any] | None = None, force: bool = False) -> dict[str, Any]:
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
rec = (self._state["users"].get(u) or {}).get(pid)
|
|
if not rec:
|
|
raise KeyError(pid)
|
|
if enabled is True and not rec.get("enabled"):
|
|
missing = self.missing_requires(u, (rec.get("manifest") or {}).get("requires"))
|
|
if missing:
|
|
raise DependencyError(
|
|
f"cannot enable '{pid}': requires {', '.join(missing)}",
|
|
missing=missing,
|
|
)
|
|
if enabled is False and rec.get("enabled") and not force:
|
|
deps_on = self.enabled_dependents(u, pid)
|
|
if deps_on:
|
|
raise DependencyError(
|
|
f"cannot disable '{pid}': required by {', '.join(deps_on)}",
|
|
dependents=deps_on,
|
|
)
|
|
if enabled is not None:
|
|
rec["enabled"] = bool(enabled)
|
|
if config is not None:
|
|
mf0 = rec.get("manifest") or {}
|
|
allowed = {f["key"] for f in (mf0.get("settings") or {}).get("fields") or []}
|
|
cur = dict(rec.get("config") or {})
|
|
for k, v in config.items():
|
|
if k in allowed:
|
|
cur[k] = v
|
|
# A provider's accounts are editable from its settings.
|
|
if mf0.get("kind") == "provider" and "accounts" in config:
|
|
cur["accounts"] = clean_provider_accounts(config["accounts"], mf0)
|
|
rec["config"] = cur
|
|
rec["updatedAt"] = _now_iso()
|
|
self._save()
|
|
pdir = pathlib.Path(rec["dir"])
|
|
mf = rec["manifest"]
|
|
active = bool(rec.get("enabled")) and not rec.get("needsApproval")
|
|
out = self._public_record(u, rec)
|
|
self._sync_live_skill(u, pid, pdir, mf, active)
|
|
self._typed_touched(u, mf)
|
|
return out
|
|
|
|
def uninstall(self, uid: str | None, pid: str, *, purge: bool = False,
|
|
force: bool = False) -> bool:
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
u_map = self._state["users"].get(u) or {}
|
|
if pid not in u_map:
|
|
return False
|
|
if not force:
|
|
deps_on = self.enabled_dependents(u, pid)
|
|
if deps_on:
|
|
raise DependencyError(
|
|
f"cannot uninstall '{pid}': required by {', '.join(deps_on)}",
|
|
dependents=deps_on,
|
|
)
|
|
mf_gone = (u_map[pid].get("manifest") or {})
|
|
del u_map[pid]
|
|
self._save()
|
|
shutil.rmtree(self.live_skills_dir / u / pid, ignore_errors=True)
|
|
self._typed_touched(u, mf_gone)
|
|
if purge:
|
|
shutil.rmtree(self.data_dir / u / pid, ignore_errors=True)
|
|
sp = self._secret_path(u, pid)
|
|
try:
|
|
sp.unlink(missing_ok=True)
|
|
except OSError:
|
|
pass
|
|
return True
|
|
|
|
# ── hub catalog (operator-curated plugins any user can 1-click install) ──
|
|
def promote_catalog(self, source: str, *, guests_allowed: bool = True) -> dict[str, Any]:
|
|
info = self.inspect_source(source, allow_any_path=True, refresh_git=True)
|
|
mf = info["manifest"]
|
|
pid = mf["id"]
|
|
entry = {
|
|
"id": pid,
|
|
"name": mf["name"],
|
|
"version": mf["version"],
|
|
"description": mf["description"],
|
|
"icon": mf["icon"],
|
|
"kind": mf.get("kind") or "app",
|
|
**art_fields(pid, mf),
|
|
"manifest": mf,
|
|
"sourceRaw": source,
|
|
"source": info["source"],
|
|
"dir": info["dir"],
|
|
"fingerprint": info["fingerprint"],
|
|
"capabilities": info["capabilities"],
|
|
"requiresOperator": info["requiresOperator"],
|
|
"guestsAllowed": bool(guests_allowed),
|
|
"promotedAt": _now_iso(),
|
|
}
|
|
with self._lock:
|
|
self._state["catalog"][pid] = entry
|
|
self._save()
|
|
return dict(entry)
|
|
|
|
def remove_catalog(self, pid: str) -> bool:
|
|
with self._lock:
|
|
if pid not in self._state["catalog"]:
|
|
return False
|
|
del self._state["catalog"][pid]
|
|
self._save()
|
|
return True
|
|
|
|
def catalog(self, *, is_owner: bool) -> list[dict[str, Any]]:
|
|
with self._lock:
|
|
items = [json.loads(json.dumps(c)) for c in self._state["catalog"].values()]
|
|
out = []
|
|
for c in sorted(items, key=lambda x: x["id"]):
|
|
if not (is_owner or c.get("guestsAllowed")):
|
|
continue
|
|
if "manifest" not in c: # promoted before plugins had art
|
|
try:
|
|
mf = validate_manifest(pathlib.Path(c["dir"]))
|
|
c.update({"manifest": mf, **art_fields(c["id"], mf)})
|
|
except Exception:
|
|
pass
|
|
c.setdefault("kind", (c.get("manifest") or {}).get("kind") or "app")
|
|
c["category"] = category_of(c.get("manifest") or {"kind": c["kind"]}, c.get("dir"))
|
|
out.append(c)
|
|
return out
|
|
|
|
# ── reads ────────────────────────────────────────────────────────────────
|
|
def get_raw(self, uid: str | None, pid: str) -> dict[str, Any] | None:
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
rec = (self._state["users"].get(u) or {}).get(pid)
|
|
return json.loads(json.dumps(rec)) if rec else None
|
|
|
|
_ART_KEYS = ("icon", "iconSvg", "illustration", "color", "readme", "artVersion")
|
|
|
|
def _ensure_art(self, uid: str, rec: dict[str, Any]) -> dict[str, Any]:
|
|
"""A record installed before plugins had art gets it once from its
|
|
source, art keys only: nothing it may do changes, so no re-approval."""
|
|
mf = rec.get("manifest") or {}
|
|
if "artVersion" in mf:
|
|
return rec
|
|
try:
|
|
fresh = validate_manifest(pathlib.Path(rec["dir"]))
|
|
except Exception:
|
|
fresh = None
|
|
art = {k: fresh.get(k) for k in self._ART_KEYS} if fresh and fresh.get("id") == rec["id"] else {"artVersion": ""}
|
|
with self._lock:
|
|
live = (self._state["users"].get(uid) or {}).get(rec["id"])
|
|
if live is not None:
|
|
live.setdefault("manifest", {}).update(art)
|
|
self._save()
|
|
rec = json.loads(json.dumps(rec))
|
|
rec.setdefault("manifest", {}).update(art)
|
|
return rec
|
|
|
|
def list_for(self, uid: str | None) -> list[dict[str, Any]]:
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
u_map = json.loads(json.dumps(self._state["users"].get(u) or {}))
|
|
return [self._public_record(u, self._ensure_art(u, rec)) for _, rec in sorted(u_map.items())]
|
|
|
|
def active_manifests(self, uid: str | None) -> list[tuple[str, dict[str, Any], dict[str, Any]]]:
|
|
"""``(id, manifest, config)`` of a user's enabled, approved plugins —
|
|
copies, cheap (no secret or art lookups)."""
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
recs = [r for r in (self._state["users"].get(u) or {}).values()
|
|
if r.get("enabled") and not r.get("needsApproval")]
|
|
return [(r["id"], json.loads(json.dumps(r.get("manifest") or {})),
|
|
json.loads(json.dumps(r.get("config") or {})))
|
|
for r in sorted(recs, key=lambda r: r["id"])]
|
|
|
|
def active_ids(self, uid: str | None) -> list[str]:
|
|
"""The ids of ``uid``'s enabled, approved installs — no copies (every
|
|
action run hands the list to its handler)."""
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
return sorted(pid for pid, r in (self._state["users"].get(u) or {}).items()
|
|
if r.get("enabled") and not r.get("needsApproval"))
|
|
|
|
def active_providing(self, uid: str | None, key: str) -> list[dict[str, Any]]:
|
|
"""Copies of ``uid``'s enabled, approved records whose manifest
|
|
``provides`` ``key`` through a declared action — only those are
|
|
copied (the composer and inbox ask on every page load; copying every
|
|
record to find one or two cost more than the answer)."""
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
hits = []
|
|
for pid in sorted(self._state["users"].get(u) or {}):
|
|
r = self._state["users"][u][pid]
|
|
if not r.get("enabled") or r.get("needsApproval"):
|
|
continue
|
|
mf = r.get("manifest") or {}
|
|
act = (mf.get("provides") or {}).get(key)
|
|
if act and act in (mf.get("actions") or {}):
|
|
hits.append(r)
|
|
return [json.loads(json.dumps(r)) for r in hits]
|
|
|
|
def active_declaring(self, uid: str | None, key: str) -> list[dict[str, Any]]:
|
|
"""Copies of ``uid``'s enabled, approved records whose manifest has a
|
|
non-empty top-level ``key`` (e.g. ``commands``) — only those copied."""
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
hits = [r for _, r in sorted((self._state["users"].get(u) or {}).items())
|
|
if r.get("enabled") and not r.get("needsApproval")
|
|
and (r.get("manifest") or {}).get(key)]
|
|
return [json.loads(json.dumps(r)) for r in hits]
|
|
|
|
def all_installed(self) -> list[tuple[str, dict[str, Any]]]:
|
|
with self._lock:
|
|
out = []
|
|
for u, u_map in self._state["users"].items():
|
|
for rec in u_map.values():
|
|
out.append((u, json.loads(json.dumps(rec))))
|
|
return out
|
|
|
|
def find_by_webhook_token(self, pid: str, hook_id: str, token: str) -> tuple[str, dict[str, Any]] | None:
|
|
if not token:
|
|
return None
|
|
import hmac
|
|
with self._lock:
|
|
for u, u_map in self._state["users"].items():
|
|
rec = u_map.get(pid)
|
|
if not rec or not rec.get("enabled") or rec.get("needsApproval"):
|
|
continue
|
|
expected = (rec.get("webhookTokens") or {}).get(hook_id)
|
|
if expected and hmac.compare_digest(expected, token):
|
|
return u, json.loads(json.dumps(rec))
|
|
return None
|
|
|
|
def record_schedule_run(self, uid: str, pid: str, sched_id: str,
|
|
ok: bool, message: str = "") -> None:
|
|
with self._lock:
|
|
rec = (self._state["users"].get(uid) or {}).get(pid)
|
|
if not rec:
|
|
return
|
|
st = rec.setdefault("schedulesState", {})
|
|
st[sched_id] = {"at": _now_iso(), "ok": ok, "message": message[:300]}
|
|
self._save()
|
|
|
|
def _public_record(self, uid: str, rec: dict[str, Any]) -> dict[str, Any]:
|
|
mf = rec.get("manifest") or {}
|
|
sec_present = self.secret_presence(uid, rec["id"], mf)
|
|
has_settings = bool(mf.get("settings") or mf.get("secrets")
|
|
or (mf.get("ui") or {}).get("settingsHtml"))
|
|
return {
|
|
"id": rec["id"],
|
|
"kind": mf.get("kind") or "app",
|
|
"category": category_of(mf, rec.get("dir")),
|
|
"name": mf.get("name") or rec["id"],
|
|
"version": mf.get("version") or "1.0.0",
|
|
"description": mf.get("description") or "",
|
|
"icon": mf.get("icon") or "puzzle",
|
|
"sourceRaw": rec.get("sourceRaw") or "",
|
|
"source": rec.get("source") or {},
|
|
"enabled": bool(rec.get("enabled")),
|
|
"needsApproval": bool(rec.get("needsApproval")),
|
|
"fingerprint": rec.get("fingerprint") or "",
|
|
"capabilities": rec.get("capabilities") or [],
|
|
"requiresOperator": bool(rec.get("requiresOperator")),
|
|
"fromCatalog": rec.get("fromCatalog"),
|
|
"hasSettings": has_settings,
|
|
"skillName": (mf.get("skill") or {}).get("name"),
|
|
"secretsPresent": sec_present,
|
|
"config": dict(rec.get("config") or {}),
|
|
"schedulesState": dict(rec.get("schedulesState") or {}),
|
|
"manifest": mf,
|
|
"requires": list(mf.get("requires") or []),
|
|
"optionalRequires": list(mf.get("optionalRequires") or []),
|
|
"exports": list(mf.get("exports") or []),
|
|
"emits": list(mf.get("emits") or []),
|
|
"dependents": self.enabled_dependents(uid, rec["id"]),
|
|
"installedAt": rec.get("installedAt"),
|
|
"updatedAt": rec.get("updatedAt"),
|
|
**art_fields(rec["id"], mf),
|
|
}
|
|
|
|
# ── write-only secrets (0600) ────────────────────────────────────────────
|
|
def _secret_path(self, uid: str, pid: str) -> pathlib.Path:
|
|
return self.secrets_dir / uid / f"{pid}.json"
|
|
|
|
def _read_secrets_file(self, uid: str, pid: str) -> dict[str, str]:
|
|
p = self._secret_path(uid, pid)
|
|
try:
|
|
data = json.loads(p.read_text(encoding="utf-8"))
|
|
return {str(k): str(v) for k, v in data.items() if isinstance(v, str)} if isinstance(data, dict) else {}
|
|
except (OSError, ValueError):
|
|
return {}
|
|
|
|
def _write_secrets_file(self, uid: str, pid: str, data: dict[str, str]) -> None:
|
|
p = self._secret_path(uid, pid)
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = p.with_suffix(".tmp")
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
json.dump(data, f, indent=1, sort_keys=True)
|
|
os.replace(tmp, p)
|
|
|
|
def set_secret(self, uid: str | None, pid: str, key: str, value: str, *,
|
|
scope: str = "user") -> None:
|
|
"""Store a secret (0600 file) and, in ``installed.json``, its non-secret
|
|
hint — the last four characters, what Settings shows as ``…abcd``."""
|
|
bucket = HUB_SECRET_UID if scope == "hub" else self.norm_uid(uid)
|
|
with self._lock:
|
|
cur = self._read_secrets_file(bucket, pid)
|
|
cur[key] = value
|
|
self._write_secrets_file(bucket, pid, cur)
|
|
self._set_hint(bucket, pid, key, value)
|
|
self._save()
|
|
|
|
@staticmethod
|
|
def _last4(value: str) -> str:
|
|
# Too short a secret and four characters are most of it: no hint.
|
|
return value[-4:] if len(value) >= 12 else ""
|
|
|
|
def _set_hint(self, bucket: str, pid: str, key: str, value: str | None) -> None:
|
|
hints = self._state.setdefault("secretHints", {}).setdefault(bucket, {}).setdefault(pid, {})
|
|
if value:
|
|
hints[key] = {"last4": self._last4(value), "setAt": _now_iso()}
|
|
else:
|
|
hints.pop(key, None)
|
|
|
|
def secret_hint(self, uid: str | None, pid: str, key: str, *,
|
|
scope: str = "user") -> dict[str, str] | None:
|
|
"""``{last4, setAt}`` of a stored secret (never its value), or None.
|
|
A secret stored before hints existed gets its hint now."""
|
|
bucket = HUB_SECRET_UID if scope == "hub" else self.norm_uid(uid)
|
|
with self._lock:
|
|
h = ((self._state.get("secretHints") or {}).get(bucket) or {}).get(pid, {}).get(key)
|
|
if h:
|
|
return dict(h)
|
|
val = self._read_secrets_file(bucket, pid).get(key)
|
|
if not val:
|
|
return None
|
|
self._state.setdefault("secretHints", {}).setdefault(bucket, {}).setdefault(pid, {})[key] = {
|
|
"last4": self._last4(val), "setAt": ""}
|
|
self._save()
|
|
return {"last4": self._last4(val), "setAt": ""}
|
|
|
|
def delete_secret(self, uid: str | None, pid: str, key: str, *,
|
|
scope: str = "user") -> None:
|
|
bucket = HUB_SECRET_UID if scope == "hub" else self.norm_uid(uid)
|
|
with self._lock:
|
|
cur = self._read_secrets_file(bucket, pid)
|
|
if key in cur:
|
|
del cur[key]
|
|
self._write_secrets_file(bucket, pid, cur)
|
|
self._set_hint(bucket, pid, key, None)
|
|
self._save()
|
|
|
|
def get_secret(self, uid: str | None, pid: str, key: str, *,
|
|
scope: str = "user") -> str | None:
|
|
bucket = HUB_SECRET_UID if scope == "hub" else self.norm_uid(uid)
|
|
with self._lock:
|
|
return self._read_secrets_file(bucket, pid).get(key)
|
|
|
|
def all_secret_values(self, uid: str | None, pid: str) -> list[str]:
|
|
"""Every stored secret value for ``(uid, pid)`` + hub-scoped secrets,
|
|
used by the proxy to scrub secrets out of responses and errors."""
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
vals = list(self._read_secrets_file(u, pid).values())
|
|
vals += list(self._read_secrets_file(HUB_SECRET_UID, pid).values())
|
|
return [v for v in vals if len(v) >= 6]
|
|
|
|
def secret_presence(self, uid: str | None, pid: str,
|
|
manifest: dict[str, Any]) -> dict[str, bool]:
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
user_s = self._read_secrets_file(u, pid)
|
|
hub_s = self._read_secrets_file(HUB_SECRET_UID, pid)
|
|
out: dict[str, bool] = {}
|
|
for s in manifest.get("secrets") or []:
|
|
k = s["key"]
|
|
out[k] = bool(hub_s.get(k) if s.get("scope") == "hub" else user_s.get(k))
|
|
return out
|
|
|
|
# ── managed plugins (owner-installed, granted per guest) ─────────────────
|
|
def managed_plugins(self) -> list[dict[str, Any]]:
|
|
"""Every enabled owner-installed plugin that declares a ``managed`` block."""
|
|
with self._lock:
|
|
u_map = dict(self._state["users"].get(OWNER_UID) or {})
|
|
out = []
|
|
for pid, rec in sorted(u_map.items()):
|
|
if not rec.get("enabled") or rec.get("needsApproval"):
|
|
continue
|
|
if (rec.get("manifest") or {}).get("managed"):
|
|
out.append(json.loads(json.dumps(rec)))
|
|
return [self._ensure_art(OWNER_UID, r) for r in out]
|
|
|
|
def effective_grant(self, uid: str, pid: str,
|
|
manifest: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
"""Effective managed grant for guest ``uid`` on ``pid`` (falls back to
|
|
``managed.defaultForGuests`` and field/budget defaults when no explicit
|
|
row exists)."""
|
|
u = self.norm_uid(uid)
|
|
with self._lock:
|
|
if manifest is None:
|
|
owner_rec = (self._state["users"].get(OWNER_UID) or {}).get(pid)
|
|
manifest = (owner_rec or {}).get("manifest") or {}
|
|
mg = manifest.get("managed") or {}
|
|
raw = (self._state["grants"].get(u) or {}).get(pid)
|
|
cfg: dict[str, Any] = {}
|
|
for f in mg.get("grantFields") or []:
|
|
if f.get("default") is not None:
|
|
cfg[f["key"]] = f["default"]
|
|
default_budget = (mg.get("limits") or {}).get("defaultMonthlyBudgetUsd")
|
|
if raw is None:
|
|
return {
|
|
"enabled": bool(mg.get("defaultForGuests", False)),
|
|
"config": cfg,
|
|
"monthlyBudgetUsd": default_budget,
|
|
"isDefault": True,
|
|
}
|
|
if isinstance(raw.get("config"), dict):
|
|
cfg.update(raw["config"])
|
|
budget = raw["monthlyBudgetUsd"] if "monthlyBudgetUsd" in raw else default_budget
|
|
return {
|
|
"enabled": bool(raw.get("enabled", False)),
|
|
"config": cfg,
|
|
"monthlyBudgetUsd": budget,
|
|
"isDefault": False,
|
|
"updatedAt": raw.get("updatedAt"),
|
|
}
|
|
|
|
def set_grant(self, uid: str, pid: str, *, enabled: bool | None = None,
|
|
config: dict[str, Any] | None = None,
|
|
monthly_budget_usd: Any = _UNSET) -> dict[str, Any]:
|
|
u = self.norm_uid(uid)
|
|
if u == OWNER_UID:
|
|
raise ValueError("owner always has access to own managed plugins")
|
|
with self._lock:
|
|
owner_rec = (self._state["users"].get(OWNER_UID) or {}).get(pid)
|
|
if not owner_rec or not (owner_rec.get("manifest") or {}).get("managed"):
|
|
raise KeyError(pid)
|
|
mf = owner_rec["manifest"]
|
|
mg = mf["managed"]
|
|
u_grants = self._state["grants"].setdefault(u, {})
|
|
cur = dict(u_grants.get(pid) or {})
|
|
if not cur:
|
|
eff = self.effective_grant(u, pid, mf)
|
|
cur = {"enabled": eff["enabled"], "config": eff["config"],
|
|
"monthlyBudgetUsd": eff["monthlyBudgetUsd"]}
|
|
if enabled is not None:
|
|
cur["enabled"] = bool(enabled)
|
|
if config is not None:
|
|
allowed = {f["key"] for f in (mg.get("grantFields") or [])}
|
|
cdict = dict(cur.get("config") or {})
|
|
for k, v in config.items():
|
|
if k in allowed:
|
|
cdict[k] = v
|
|
cur["config"] = cdict
|
|
if monthly_budget_usd is not _UNSET:
|
|
if monthly_budget_usd is None or monthly_budget_usd == "":
|
|
cur["monthlyBudgetUsd"] = None
|
|
else:
|
|
cur["monthlyBudgetUsd"] = round(max(0.0, float(monthly_budget_usd)), 2)
|
|
cur["updatedAt"] = _now_iso()
|
|
u_grants[pid] = cur
|
|
self._save()
|
|
return self.effective_grant(u, pid, mf)
|
|
|
|
def resolve_active_for_caller(self, uid: str | None, pid: str) -> tuple[dict[str, Any] | None, dict[str, Any] | None, bool]:
|
|
"""Resolve an active plugin for caller ``uid``:
|
|
returns ``(record, grant_or_None, is_managed)``.
|
|
Checks personal install first; for non-owners, falls back to an active
|
|
owner-managed plugin granted to ``uid``."""
|
|
u = self.norm_uid(uid)
|
|
rec = self.get_raw(u, pid)
|
|
if rec and rec.get("enabled") and not rec.get("needsApproval"):
|
|
return rec, None, bool(u == OWNER_UID and (rec.get("manifest") or {}).get("managed"))
|
|
if u == OWNER_UID:
|
|
return None, None, False
|
|
owner_rec = self.get_raw(OWNER_UID, pid)
|
|
if not owner_rec or not owner_rec.get("enabled") or owner_rec.get("needsApproval"):
|
|
return None, None, False
|
|
mf = owner_rec.get("manifest") or {}
|
|
if not mf.get("managed"):
|
|
return None, None, False
|
|
grant = self.effective_grant(u, pid, mf)
|
|
if not grant.get("enabled"):
|
|
return None, None, False
|
|
return owner_rec, grant, True
|
|
|
|
def get_secret_for_caller(self, uid: str | None, pid: str, key: str,
|
|
manifest: dict[str, Any], *,
|
|
override_secret: str | None = None) -> tuple[str | None, bool]:
|
|
"""Resolve secret ``key`` for caller ``uid``: returns ``(value, using_own_secret)``.
|
|
When a managed plugin declares ``allowUserSecretOverride: true``, a
|
|
guest's own stored secret takes precedence over the hub secret (BYOK)."""
|
|
if override_secret is not None:
|
|
return override_secret, False
|
|
u = self.norm_uid(uid)
|
|
mg = manifest.get("managed") or {}
|
|
if u != OWNER_UID and mg.get("allowUserSecretOverride"):
|
|
user_val = self.get_secret(u, pid, key, scope="user")
|
|
if user_val:
|
|
return user_val, True
|
|
spec = next((s for s in (manifest.get("secrets") or []) if s["key"] == key), None)
|
|
scope = spec.get("scope", "user") if spec else "user"
|
|
return self.get_secret(u, pid, key, scope=scope), False
|
|
|
|
def has_user_override_secret(self, uid: str | None, pid: str,
|
|
manifest: dict[str, Any]) -> bool:
|
|
u = self.norm_uid(uid)
|
|
if u == OWNER_UID:
|
|
return False
|
|
mg = manifest.get("managed") or {}
|
|
if not mg.get("allowUserSecretOverride"):
|
|
return False
|
|
with self._lock:
|
|
user_s = self._read_secrets_file(u, pid)
|
|
return any(bool(user_s.get(s["key"])) for s in (manifest.get("secrets") or []))
|
|
|
|
# ── key health & spend alerts (managed plugins) ──────────────────────────
|
|
KEY_STATES = ("ok", "no-credit", "invalid", "denied", "capped")
|
|
BROKEN_STATES = ("no-credit", "invalid", "denied", "capped")
|
|
|
|
def record_key_health(self, pid: str, status: str, message: str = "", *,
|
|
who: dict[str, Any] | None = None,
|
|
model: str | None = None, test: bool = False,
|
|
http_status: int = 0, push: bool = True,
|
|
now: float | None = None) -> dict[str, Any]:
|
|
"""Record one observation of the hub key of ``pid``.
|
|
|
|
``status`` is ``ok``, a broken state (``no-credit`` / ``invalid`` /
|
|
``denied`` / ``capped``) — both set the key's state — or a transient
|
|
failure (``error``, ``rate-limited``…) that is listed among the
|
|
failures but leaves the state alone. Returns the record plus
|
|
``_push``: ``"break"`` when the key just moved into a broken state
|
|
not pushed yet, ``"recover"`` when it is back to ``ok`` after a
|
|
pushed break, else None (``push=False``: the owner turned break
|
|
pushes off — nothing is marked as pushed)."""
|
|
import time as _time
|
|
t = _time.time() if now is None else now
|
|
at = dt.datetime.fromtimestamp(t, dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
out_push = None
|
|
with self._lock:
|
|
kh = self._state["keyHealth"].setdefault(pid, {})
|
|
prev = kh.get("status") or "unknown"
|
|
kh["checkedAt"] = at
|
|
if status == "ok":
|
|
kh["lastOk"] = at
|
|
else:
|
|
who_d = who if isinstance(who, dict) else {}
|
|
ev = {"at": at, "t": t, "status": status, "message": message[:300],
|
|
**({"httpStatus": int(http_status)} if http_status else {}),
|
|
**({"model": model} if model else {}),
|
|
**({"test": True} if test else {}),
|
|
**{k: who_d[k] for k in ("who", "guest", "worker", "via") if who_d.get(k)}}
|
|
kh["lastError"] = at
|
|
kh["lastErrorEvent"] = ev
|
|
fails = list(kh.get("failures") or [])
|
|
fails.append(ev)
|
|
kh["failures"] = fails[-40:]
|
|
if status in self.KEY_STATES:
|
|
kh["status"] = status
|
|
kh["message"] = message[:300]
|
|
if status != prev:
|
|
kh["since"] = at
|
|
kh["sinceT"] = t
|
|
if push:
|
|
if status in self.BROKEN_STATES and kh.get("pushedState") != status:
|
|
kh["pushedState"] = status
|
|
out_push = "break"
|
|
elif status == "ok" and kh.get("pushedState") in self.BROKEN_STATES:
|
|
kh["pushedState"] = None
|
|
out_push = "recover"
|
|
self._save()
|
|
res = json.loads(json.dumps(kh))
|
|
res["_prev"] = prev
|
|
res["_push"] = out_push
|
|
return res
|
|
|
|
def mark_key_replaced(self, pid: str) -> None:
|
|
"""A new hub key: its state is unknown until its first reply (a break
|
|
already pushed for the old key doesn't push again)."""
|
|
with self._lock:
|
|
kh = self._state["keyHealth"].setdefault(pid, {})
|
|
kh["replacedAt"] = _now_iso()
|
|
kh["status"] = "unknown"
|
|
kh["message"] = ""
|
|
kh["since"] = kh["replacedAt"]
|
|
self._save()
|
|
|
|
def get_key_health(self, pid: str) -> dict[str, Any] | None:
|
|
with self._lock:
|
|
kh = self._state["keyHealth"].get(pid)
|
|
return json.loads(json.dumps(kh)) if kh else None
|
|
|
|
def mark_spend_alert(self, pid: str, month: str, pct: int) -> bool:
|
|
"""Record that a monthly spend alert was sent; returns True only the first time."""
|
|
tag = f"{month}:{pct}"
|
|
with self._lock:
|
|
kh = self._state["keyHealth"].setdefault(pid, {})
|
|
sent = set(kh.get("spendAlertsSent") or [])
|
|
if tag in sent:
|
|
return False
|
|
sent.add(tag)
|
|
kh["spendAlertsSent"] = sorted(sent)[-24:]
|
|
self._save()
|
|
return True
|
|
|
|
# The owner's runtime overrides of ``managed.keyHealth`` (Settings → the
|
|
# plugin's page): the alert line and when to push.
|
|
KEY_SETTINGS = ("alertLimit", "currency", "pushAtPct", "pushOnBreak")
|
|
|
|
def key_settings(self, pid: str, manifest: dict[str, Any]) -> dict[str, Any]:
|
|
base = dict(((manifest.get("managed") or {}).get("keyHealth")) or {})
|
|
out = {
|
|
"alertLimit": float(base.get("alertLimit", base.get("alertLimitEur", 20.0)) or 0),
|
|
"currency": base.get("currency") or "EUR",
|
|
"pushAtPct": int(base.get("pushAtPct") or 80),
|
|
"pushOnBreak": bool(base.get("pushOnBreak", True)),
|
|
}
|
|
with self._lock:
|
|
over = dict(self._state.get("keySettings", {}).get(pid) or {})
|
|
out.update({k: v for k, v in over.items() if k in self.KEY_SETTINGS})
|
|
return out
|
|
|
|
def update_key_settings(self, pid: str, manifest: dict[str, Any],
|
|
changes: dict[str, Any]) -> dict[str, Any]:
|
|
clean: dict[str, Any] = {}
|
|
for k, v in (changes or {}).items():
|
|
if k not in self.KEY_SETTINGS or v is None:
|
|
continue
|
|
if k == "alertLimit":
|
|
clean[k] = round(max(0.0, min(100000.0, float(v))), 2)
|
|
elif k == "currency":
|
|
if str(v).upper() not in ("EUR", "USD"):
|
|
raise ValueError("currency must be EUR or USD")
|
|
clean[k] = str(v).upper()
|
|
elif k == "pushAtPct":
|
|
clean[k] = max(1, min(100, int(v)))
|
|
elif k == "pushOnBreak":
|
|
clean[k] = bool(v)
|
|
with self._lock:
|
|
self._state.setdefault("keySettings", {}).setdefault(pid, {}).update(clean)
|
|
self._save()
|
|
return self.key_settings(pid, manifest)
|
|
|
|
# ── per-user plugin storage (quota-enforced) ─────────────────────────────
|
|
# ── typed plugins: providers & harnesses ─────────────────────────────────
|
|
def active_by_kind(self, kind: str) -> list[dict[str, Any]]:
|
|
"""The owner's enabled, approved plugins of ``kind`` (``app`` /
|
|
``provider`` / ``harness``): ``[{id, manifest, config, dir}]``, copies."""
|
|
with self._lock:
|
|
recs = [r for r in (self._state["users"].get(OWNER_UID) or {}).values()
|
|
if r.get("enabled") and not r.get("needsApproval")
|
|
and ((r.get("manifest") or {}).get("kind") or "app") == kind]
|
|
return [{"id": r["id"], "manifest": json.loads(json.dumps(r.get("manifest") or {})),
|
|
"config": json.loads(json.dumps(r.get("config") or {})), "dir": r.get("dir")}
|
|
for r in sorted(recs, key=lambda r: r["id"])]
|
|
|
|
def sync_hooks(self) -> bool:
|
|
"""Re-materialize ``live-hooks/`` (best effort): True when it changed."""
|
|
from plugins import harness_hooks
|
|
try:
|
|
return harness_hooks.materialize(self)
|
|
except Exception: # noqa: BLE001 — a failed copy keeps the last index
|
|
import logging
|
|
logging.getLogger(__name__).exception("harness hooks materialization failed")
|
|
return False
|
|
|
|
def _hooks_touched(self, uid: str, mf: dict[str, Any]) -> None:
|
|
if uid != OWNER_UID:
|
|
return
|
|
if (mf.get("harnessHooks") or mf.get("pathShims")
|
|
or (self.live_hooks_dir / "index.json").is_file()):
|
|
self.sync_hooks()
|
|
|
|
def _typed_touched(self, uid: str, mf: dict[str, Any]) -> None:
|
|
self._hooks_touched(uid, mf)
|
|
if uid != OWNER_UID or (mf.get("kind") or "app") == "app":
|
|
return
|
|
try:
|
|
changed = self.sync_typed()
|
|
except Exception: # noqa: BLE001 — a failed copy keeps the last bundle
|
|
import logging
|
|
logging.getLogger(__name__).exception("typed plugin materialization failed")
|
|
return
|
|
if changed and self.on_typed_change is not None:
|
|
try:
|
|
self.on_typed_change()
|
|
except Exception: # noqa: BLE001 — best effort
|
|
pass
|
|
|
|
@staticmethod
|
|
def _tree_hash(root: pathlib.Path) -> str:
|
|
h = hashlib.sha256()
|
|
for p in sorted(root.rglob("*")):
|
|
if p.is_file() and not p.is_symlink():
|
|
h.update(p.relative_to(root).as_posix().encode() + b"\0")
|
|
h.update(hashlib.sha256(p.read_bytes()).digest())
|
|
return h.hexdigest()
|
|
|
|
@staticmethod
|
|
def _copy_tree(src: pathlib.Path, dest: pathlib.Path) -> None:
|
|
shutil.copytree(src, dest, symlinks=False,
|
|
ignore=shutil.ignore_patterns("__pycache__", ".git", "*.pyc", "node_modules"))
|
|
|
|
def _materialize(self, base: pathlib.Path, items: dict[str, dict[str, Any]], key: str,
|
|
plural: str, extra: dict[str, Any] | None = None) -> bool:
|
|
"""Swap ``base/<plugin id>/`` dirs to ``items`` (id → {"build": fn(dest),
|
|
"meta": {...}}) and write ``index.json``; True when the bundle changed."""
|
|
base.mkdir(parents=True, exist_ok=True)
|
|
idx_path = base / "index.json"
|
|
try:
|
|
prev = json.loads(idx_path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
prev = {}
|
|
entries: dict[str, Any] = {}
|
|
for pid, it in items.items():
|
|
tmp = base / f".tmp-{pid}-{secrets.token_hex(4)}"
|
|
it["build"](tmp)
|
|
digest = self._tree_hash(tmp)
|
|
dest = base / pid
|
|
old = base / f".old-{pid}-{secrets.token_hex(4)}"
|
|
if dest.exists():
|
|
os.replace(dest, old)
|
|
os.replace(tmp, dest)
|
|
shutil.rmtree(old, ignore_errors=True)
|
|
entries[it["meta"][key]] = {**it["meta"], "pluginId": pid, "dir": str(dest), "hash": digest}
|
|
keep = set(items)
|
|
for child in base.iterdir():
|
|
if child.is_dir() and (child.name not in keep or child.name.startswith(".")):
|
|
shutil.rmtree(child, ignore_errors=True)
|
|
top = hashlib.sha256(json.dumps(entries, sort_keys=True).encode()).hexdigest()
|
|
changed = top != prev.get("hash")
|
|
version = int(prev.get("version") or 0) + (1 if changed else 0)
|
|
index = {"version": version, "hash": top, plural: entries, **(extra or {})}
|
|
tmpi = idx_path.with_suffix(".tmp")
|
|
tmpi.write_text(json.dumps(index, indent=2, sort_keys=True), encoding="utf-8")
|
|
os.replace(tmpi, idx_path)
|
|
return changed
|
|
|
|
def sync_typed(self) -> bool:
|
|
"""Materialize the owner's enabled harness and provider plugins into
|
|
``live-harnesses/`` and ``live-providers/``. True when either changed."""
|
|
with self._lock:
|
|
harnesses = self.active_by_kind("harness")
|
|
providers = self.active_by_kind("provider")
|
|
h_items: dict[str, dict[str, Any]] = {}
|
|
for rec in harnesses:
|
|
mf, src = rec["manifest"], pathlib.Path(rec["dir"] or "")
|
|
hv = mf.get("harness") or {}
|
|
sc = hv.get("sidecar") or {}
|
|
if not sc.get("dir") or not (src / sc["dir"]).is_dir():
|
|
continue
|
|
|
|
def build(dest, src=src, sc=sc, mf=mf):
|
|
dest.mkdir(parents=True)
|
|
self._copy_tree(src / sc["dir"], dest / "sidecar")
|
|
if sc.get("runnerDir") and (src / sc["runnerDir"]).is_dir():
|
|
self._copy_tree(src / sc["runnerDir"], dest / "runner")
|
|
shutil.copy2(src / "plugin.json", dest / "plugin.json")
|
|
h_items[rec["id"]] = {"build": build, "meta": {
|
|
"harnessId": hv["harnessId"], "entry": sc.get("entry") or "driver.py",
|
|
"sidecarDir": "sidecar", "runnerDir": "runner" if sc.get("runnerDir") else None,
|
|
"guestAllowed": bool(hv.get("guestAllowed")), "runsOn": hv.get("runsOn") or "any",
|
|
"version": mf.get("version") or ""}}
|
|
p_items: dict[str, dict[str, Any]] = {}
|
|
for rec in providers:
|
|
mf, src = rec["manifest"], pathlib.Path(rec["dir"] or "")
|
|
pv = mf.get("provider") or {}
|
|
# Its sidecar code: a usage reader, or a plain sidecar module (one per provider).
|
|
ur = pv.get("usageReader") or pv.get("sidecar") or {}
|
|
cfg = {k: v for k, v in (rec["config"] or {}).items() if k != "accounts"}
|
|
|
|
def build(dest, src=src, ur=ur, cfg=cfg, rec=rec):
|
|
dest.mkdir(parents=True)
|
|
if ur.get("dir") and (src / ur["dir"]).is_dir():
|
|
self._copy_tree(src / ur["dir"], dest / "sidecar")
|
|
shutil.copy2(src / "plugin.json", dest / "plugin.json")
|
|
(dest / "config.json").write_text(json.dumps(
|
|
{"config": cfg, "accounts": (rec["config"] or {}).get("accounts") or []},
|
|
indent=2, sort_keys=True), encoding="utf-8")
|
|
p_items[rec["id"]] = {"build": build, "meta": {
|
|
"vendorId": pv["vendorId"], "keyless": bool(pv.get("keyless")),
|
|
"local": bool(pv.get("local")),
|
|
"entry": ur.get("entry") if ur else None, "sidecarDir": "sidecar" if ur else None,
|
|
"accounts": [a["id"] for a in pv.get("accounts") or []]
|
|
+ [a["id"] for a in (rec["config"] or {}).get("accounts") or []
|
|
if isinstance(a, dict) and a.get("id") and not a.get("removed")
|
|
and a["id"] not in {x["id"] for x in pv.get("accounts") or []}],
|
|
"version": mf.get("version") or ""}}
|
|
with self._lock:
|
|
ch = self._materialize(self.live_harnesses_dir, h_items, "harnessId", "harnesses")
|
|
cp = self._materialize(self.live_providers_dir, p_items, "vendorId", "providers")
|
|
return ch or cp
|
|
|
|
def _bundle(self, base: pathlib.Path, plural: str) -> dict[str, Any]:
|
|
try:
|
|
idx = json.loads((base / "index.json").read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
self.sync_typed()
|
|
try:
|
|
idx = json.loads((base / "index.json").read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
idx = {}
|
|
return {"version": int(idx.get("version") or 0), "hash": idx.get("hash") or "",
|
|
plural: dict(idx.get(plural) or {}), "root": str(base)}
|
|
|
|
def live_harness_bundle(self, guest_only: bool = False) -> dict[str, Any]:
|
|
"""``live-harnesses/index.json``; ``guest_only`` keeps the harnesses
|
|
whose plugin says ``guestAllowed`` (what a guest's computer gets) and
|
|
re-hashes what is left."""
|
|
b = self._bundle(self.live_harnesses_dir, "harnesses")
|
|
if guest_only:
|
|
b["harnesses"] = {k: v for k, v in b["harnesses"].items() if v.get("guestAllowed")}
|
|
b["hash"] = hashlib.sha256(json.dumps(b["harnesses"], sort_keys=True).encode()).hexdigest()
|
|
return b
|
|
|
|
def live_provider_bundle(self) -> dict[str, Any]:
|
|
"""``live-providers/index.json`` (owner machines only — a guest's
|
|
computer gets no provider usage reader)."""
|
|
return self._bundle(self.live_providers_dir, "providers")
|
|
|
|
def seeded(self) -> dict[str, str]:
|
|
with self._lock:
|
|
return dict(self._state.get("seeded") or {})
|
|
|
|
def mark_seeded(self, pid: str) -> None:
|
|
with self._lock:
|
|
self._state.setdefault("seeded", {})[pid] = _now_iso()
|
|
self._save()
|
|
|
|
def user_data_dir(self, uid: str | None, pid: str) -> pathlib.Path:
|
|
u = self.norm_uid(uid)
|
|
d = (self.data_dir / u / pid).resolve()
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
return d
|
|
|
|
def shared_data_dir(self, pid: str) -> pathlib.Path:
|
|
"""The plugin's hub-scoped dir, shared by every user's handler runs
|
|
(``AIA_PLUGIN_SHARED_DIR``) and never served by the data API —
|
|
``_hub`` can't be a uid."""
|
|
d = (self.data_dir / "_hub" / pid).resolve()
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
return d
|
|
|
|
def resolve_data_file(self, uid: str | None, pid: str, rel: str) -> pathlib.Path:
|
|
base = self.user_data_dir(uid, pid)
|
|
clean = (rel or "").strip().lstrip("/")
|
|
if not clean or "\\" in clean or ".." in pathlib.PurePosixPath(clean).parts:
|
|
raise ValueError("invalid data path")
|
|
target = (base / clean).resolve()
|
|
try:
|
|
target.relative_to(base)
|
|
except ValueError:
|
|
raise ValueError("path escapes plugin data dir") from None
|
|
return target
|
|
|
|
def data_usage_bytes(self, uid: str | None, pid: str) -> int:
|
|
base = self.user_data_dir(uid, pid)
|
|
total = 0
|
|
for root, _, files in os.walk(base):
|
|
for fn in files:
|
|
try:
|
|
total += os.path.getsize(os.path.join(root, fn))
|
|
except OSError:
|
|
pass
|
|
return total
|