Files
ai-agent/backend/plugins/carryover.py
gabrielvidal a4be4da003 Merge branch 'plugin-scheduled-conversations': Send later leaves the core for the scheduled-conversations plugin
# Conflicts:
#	backend/plugins/carryover.py
#	backend/plugins/hubruns.py
#	backend/plugins/manifest.py
#	backend/plugins/routes.py
2026-11-26 23:28:45 +01:00

538 lines
23 KiB
Python

"""One-time carry-overs of a core feature's data into the live plugin that
replaced it — run at start, each a no-op once done.
* **Left to do** (2026-11-25): the core's ``/data/leftovers.json`` becomes the
owner's ``left-to-do`` plugin data (``results.json``, same shape), then is
renamed ``leftovers.json.migrated`` so a purge of the plugin's data never
brings stale results back.
* **Mail trigger** (2026-11-25): Settings → Mail trigger's sender list,
``/data/mail-trigger-senders.json``, becomes the ``mail-agents`` plugin's
``senders.json`` (same shape, in its hub-scoped dir, which mail-ui reads),
then is renamed ``….migrated``. The plugin seeds its default agent's
senders from it.
* **Home Assistant push** (2026-11-25): the hub's own webhook list (Settings →
Webhooks, kept in the notification store) gave way to channel plugins. Its
Home Assistant entry — the webhook URL and the phone's PWA package — becomes
the owner's ``home-assistant-push`` plugin data (``legacy-webhook.json``,
which the plugin reads until its own settings say otherwise); the list is
then dropped from the store.
* **Approvals** (2026-11-25): the core's ``/data/approvals.json`` (every
request and the *always allow* rules, ``{"requests": {…}, "rules": {…}}``)
becomes the ``approvals`` plugin's ``approvals.json`` in its hub-scoped dir
(same shape, records unchanged), then is renamed ``….migrated`` — so the
history and the standing rules survive the move to the plugin.
* **New project** (2026-11-25): the core's ``/data/new-projects.json`` (every
New project form and what became of it) becomes the ``new-project``
plugin's shared ``requests.json`` (same ``{"requests": {…}}`` shape), then
is renamed ``….migrated``; the owner's ``guestDefaults.newProjects`` policy
seeds the plugin's config (where the owner hasn't set one), and every guest
who held ``projects.create`` gets the managed ``new-project`` grant.
* **Ship** (2026-11-26): the core deploy broker's ``/data/deploy-hosts.json``
(``{"projects": {<slug>: [host, …]}, "seeded": bool}`` — the owner's
per-project allowlist) becomes the ``ship`` plugin's ``deploy-hosts.json`` in
its hub-scoped dir (same shape), then is renamed ``….migrated``.
* **MCP servers** (2026-11-26): the core's Claude-only MCP setup
(``workers/mcpservers.py``) left for the ``mcp-servers`` plugin. Once that
plugin is installed and enabled for the owner, ``/data/mcp-servers.json``'s
servers become its ``_private/servers.json`` (``accounts: ["x"]`` →
``["claude:x"]``, ``mode: "direct"``) and the Homelab's and every worker's
ticks (``lab.overrides``, a worker record's ``mcpServerOverrides``) its
``_private/overrides.json`` (``{"local" | <worker id>: {name: bool}}``) —
merged under what the plugin already has, then a ``.carried-over`` marker.
The old file is never deleted (nor renamed: the plugin's own copy is the
live one).
* **Handoffs** (2026-11-26): the core's handoff link left for the ``handoff``
plugin. A conversation's ``meta.handoffFrom`` / ``meta.handoffTo`` (stamped
by ``/api/spawn`` since 2026-11-24) become that plugin's own data on it,
``meta.plugins.handoff.from`` / ``.to`` (same shapes), where it has none
yet — so the plugin's banners link the handoffs made before it. The old keys
stay, unread.
* **Scheduled conversations** (2026-11-26): the core's scheduled conversations (``/data/scheduled.json``,
``SCHEDULED_PATH``) become the ``scheduled-conversations`` plugin's
``scheduled.json`` in its hub-scoped dir (same shape, entries unchanged —
a failed one keeps its push's ``notifyId``, so its Retry button still
answers), then are renamed ``….migrated``.
"""
from __future__ import annotations
import json
import logging
import os
import pathlib
import re
import shutil
from plugins.store import OWNER_UID, PluginStore
log = logging.getLogger(__name__)
LEFTOVERS_PATH = os.environ.get("LEFTOVERS_PATH", "/data/leftovers.json")
MAIL_SENDERS_PATH = os.environ.get("MAIL_TRIGGER_SENDERS_PATH", "/data/mail-trigger-senders.json")
CLARIFIER_LEGACY_PATH = os.environ.get("CLARIFIER_PATH", "/data/clarifier.json")
APPROVALS_LEGACY_PATH = os.environ.get("APPROVALS_PATH", "/data/approvals.json")
NEW_PROJECTS_PATH = os.environ.get("NEW_PROJECTS_PATH", "/data/new-projects.json")
DEPLOY_HOSTS_LEGACY_PATH = os.environ.get("DEPLOY_HOSTS_PATH", "/data/deploy-hosts.json")
MCP_SERVERS_LEGACY_PATH = os.environ.get("MCP_SERVERS_PATH", "/data/mcp-servers.json")
SCHEDULED_LEGACY_PATH = os.environ.get("SCHEDULED_PATH", "/data/scheduled.json")
SCHEDULED_PLUGIN = "scheduled-conversations"
MCP_PLUGIN = "mcp-servers"
NEW_PROJECT_PLUGIN = "new-project"
# guestDefaults.newProjects keys the plugin's settings carry over.
_NP_POLICY_KEYS = ("quota", "templates", "approve", "visibility", "visibilityDefault",
"level", "domain")
def leftovers(store: PluginStore, legacy: str = LEFTOVERS_PATH) -> bool:
src = pathlib.Path(legacy)
if not src.is_file():
return False
dst = store.user_data_dir(OWNER_UID, "left-to-do") / "results.json"
try:
if not dst.exists():
shutil.copy2(src, dst)
log.info("left-to-do: carried %s over to %s", src, dst)
src.rename(src.with_name(src.name + ".migrated"))
except OSError as e:
log.warning("left-to-do carry-over: %s", e)
return False
return True
def mail_senders(store: PluginStore, legacy: str = MAIL_SENDERS_PATH) -> bool:
src = pathlib.Path(legacy)
if not src.is_file():
return False
dst = store.shared_data_dir("mail-agents") / "senders.json"
try:
if not dst.exists():
shutil.copy2(src, dst)
os.chmod(dst, 0o644)
log.info("mail-agents: carried %s over to %s", src, dst)
src.rename(src.with_name(src.name + ".migrated"))
except OSError as e:
log.warning("mail-agents carry-over: %s", e)
return False
return True
def approvals(store: PluginStore, legacy: str = APPROVALS_LEGACY_PATH) -> bool:
"""The core's approvals store → the ``approvals`` plugin's ``approvals.json``."""
src = pathlib.Path(legacy)
if not src.is_file():
return False
dst = store.shared_data_dir("approvals") / "approvals.json"
try:
if not dst.exists():
shutil.copy2(src, dst)
log.info("approvals: carried %s over to %s", src, dst)
src.rename(src.with_name(src.name + ".migrated"))
except OSError as e:
log.warning("approvals carry-over: %s", e)
return False
return True
def ship(store: PluginStore, legacy: str = DEPLOY_HOSTS_LEGACY_PATH) -> bool:
"""The core broker's host allowlist → the ``ship`` plugin's ``deploy-hosts.json``."""
src = pathlib.Path(legacy)
if not src.is_file():
return False
dst = store.shared_data_dir("ship") / "deploy-hosts.json"
try:
if not dst.exists():
shutil.copy2(src, dst)
os.chmod(dst, 0o644)
log.info("ship: carried %s over to %s", src, dst)
src.rename(src.with_name(src.name + ".migrated"))
except OSError as e:
log.warning("ship carry-over: %s", e)
return False
return True
HANDOFF_PLUGIN = "handoff"
def handoffs(meta_store) -> int:
"""The core's handoff stamps → the ``handoff`` plugin's data on each
conversation (``meta.plugins.handoff.{from,to}``); how many moved."""
if meta_store is None:
return 0
patches: dict[str, dict] = {}
for cid, m in meta_store.items():
old = {k: m.get(f"handoff{k.title()}") for k in ("from", "to")}
old = {k: v for k, v in old.items() if isinstance(v, dict) and v.get("sessionId")}
if not old:
continue
plugins = dict(m.get("plugins") or {})
mine = dict(plugins.get(HANDOFF_PLUGIN) or {})
missing = {k: v for k, v in old.items() if k not in mine}
if not missing:
continue
plugins[HANDOFF_PLUGIN] = {**mine, **missing}
patches[cid] = {"plugins": plugins}
if not patches:
return 0
try:
n = meta_store.stamp_many(patches)
except Exception as e: # noqa: BLE001 — a carry-over never stops the boot
log.warning("handoff carry-over: %s", e)
return 0
log.info("handoffs: carried %d conversations' links over to the handoff plugin", n)
return n
def scheduled(store: PluginStore, legacy: str = SCHEDULED_LEGACY_PATH) -> bool:
"""The core's scheduled conversations → the plugin's ``scheduled.json``."""
src = pathlib.Path(legacy)
if not src.is_file():
return False
dst = store.shared_data_dir(SCHEDULED_PLUGIN) / "scheduled.json"
try:
if not dst.exists():
shutil.copy2(src, dst)
os.chmod(dst, 0o644)
log.info("scheduled-conversations: carried %s over to %s", src, dst)
src.rename(src.with_name(src.name + ".migrated"))
except OSError as e:
log.warning("scheduled carry-over: %s", e)
return False
return True
HA_PLUGIN = "home-assistant-push"
def ha_webhook(store: PluginStore, notify_store) -> bool:
"""The core's Home Assistant webhook → the plugin's ``legacy-webhook.json``."""
if notify_store is None:
return False
hooks = notify_store.legacy_webhooks()
if not hooks:
return False
ha = next((w for w in hooks if "/api/webhook/" in str(w.get("url") or "")), None)
try:
if ha:
dst = store.user_data_dir(OWNER_UID, HA_PLUGIN) / "legacy-webhook.json"
if not dst.exists():
dst.write_text(json.dumps({
"url": ha.get("url") or "", "pwaPackage": ha.get("pwaPackage") or "",
"enabled": bool(ha.get("enabled", True)),
"events": ha.get("events") or ["notify", "ask"]}, indent=2))
log.info("home-assistant-push: carried the webhook %s over", ha.get("url"))
others = [w.get("url") for w in hooks if w is not ha]
if others:
log.warning("webhooks dropped with the channel plugins: %s", others)
notify_store.drop_legacy_webhooks()
except OSError as e:
log.warning("home-assistant-push carry-over: %s", e)
return False
return True
def _merge_plugin_prefs(ui_state, key: str, pid: str, patch: dict) -> bool:
if ui_state is None or not patch:
return False
raw = ui_state.get(key)
try:
blob = json.loads(raw) if raw else {"state": {}, "version": 6}
except ValueError:
blob = {"state": {}, "version": 6}
if not isinstance(blob, dict):
blob = {"state": {}, "version": 6}
state = blob.setdefault("state", {})
if not isinstance(state, dict):
return False
prefs = state.setdefault("pluginPrefs", {})
if not isinstance(prefs, dict):
return False
if prefs.get(pid):
return False
prefs[pid] = dict(patch)
ui_state.set(key, json.dumps(blob))
return True
def clarifier(ui_state, users=None, legacy: str = CLARIFIER_LEGACY_PATH) -> bool:
"""Carry over ``/data/clarifier.json`` and per-guest ``users.json``
``clarifier`` overrides into ``ui-state`` ``pluginPrefs.clarifier``."""
moved = False
src = pathlib.Path(legacy)
if src.is_file():
try:
raw = json.loads(src.read_text(encoding="utf-8"))
if isinstance(raw, dict):
patch = {k: raw[k] for k in ("enabled", "model", "effort") if k in raw and raw[k] is not None}
if patch and _merge_plugin_prefs(ui_state, "ai-agent-settings", "clarifier", patch):
log.info("clarifier: carried %s over to owner pluginPrefs", src)
moved = True
src.rename(src.with_name(src.name + ".migrated"))
except (OSError, ValueError) as e:
log.warning("clarifier carry-over: %s", e)
if users is not None and ui_state is not None:
try:
for u in users.all():
uid = u.get("id")
c = u.get("clarifier")
if not uid or not isinstance(c, dict) or not c:
continue
patch = {k: c[k] for k in ("enabled", "model", "effort") if k in c and c[k] is not None}
if patch and _merge_plugin_prefs(ui_state, f"u.{uid}.ai-agent-settings", "clarifier", patch):
log.info("clarifier: carried guest %s override over to pluginPrefs", uid)
moved = True
except Exception as e:
log.warning("clarifier guest carry-over: %s", e)
return moved
def _np_marker(store: PluginStore) -> pathlib.Path:
return store.shared_data_dir(NEW_PROJECT_PLUGIN) / ".carried-over"
def new_project(store: PluginStore, users=None, legacy: str = NEW_PROJECTS_PATH) -> bool:
"""The core New project's data → the ``new-project`` live plugin, once.
* ``/data/new-projects.json`` → the plugin's shared ``requests.json``
(kept as is when the plugin already has one), the legacy file renamed
``….migrated``;
* ``guestDefaults.newProjects`` → the plugin's config, where the owner's
install has none of its own yet;
* every guest with ``projects.create`` → an enabled ``new-project``
managed grant.
The config and the grants need the plugin installed: until it is, they
wait (the next start tries again); a marker in the plugin's shared dir
makes the whole thing run once."""
moved = False
src = pathlib.Path(legacy)
if src.is_file():
dst = store.shared_data_dir(NEW_PROJECT_PLUGIN) / "requests.json"
try:
if not dst.exists():
shutil.copy2(src, dst)
os.chmod(dst, 0o644)
log.info("new-project: carried %s over to %s", src, dst)
src.rename(src.with_name(src.name + ".migrated"))
moved = True
except OSError as e:
log.warning("new-project carry-over: %s", e)
marker = _np_marker(store)
if users is None or marker.exists():
return moved
try:
rec = store.get_raw(OWNER_UID, NEW_PROJECT_PLUGIN)
except Exception:
rec = None
if not rec:
return moved # not installed yet: the next start carries the rest over
try:
pol = (users.defaults() or {}).get("newProjects") or {}
cfg = dict(rec.get("config") or {})
patch = {k: pol[k] for k in _NP_POLICY_KEYS if k in pol and k not in cfg}
if patch:
store.update(OWNER_UID, NEW_PROJECT_PLUGIN, config=patch)
log.info("new-project: carried the guest policy over (%s)", sorted(patch))
for u in users.all():
uid = u.get("id")
if uid and _had_create_projects(u):
store.set_grant(uid, NEW_PROJECT_PLUGIN, enabled=True)
log.info("new-project: granted %s (had projects.create)", uid)
marker.write_text("1")
moved = True
except Exception as e:
log.warning("new-project carry-over (config / grants): %s", e)
return moved
def _had_create_projects(u: dict) -> bool:
"""The retired ``projects.create`` permission, read off the raw record (the
catalog no longer knows it): an ``allow`` override, or the pre-roles
``createProjects`` switch."""
return "projects.create" in (u.get("allow") or ()) or bool(u.get("createProjects"))
_MCP_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_MCP_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$")
def _mcp_server(old: dict) -> dict | None:
"""One server of the core's file → the plugin's shape (§5.2)."""
if not isinstance(old, dict):
return None
t = old.get("transport") or "http"
if t not in ("http", "sse", "stdio"):
return None
accounts = []
for a in old.get("accounts") or []:
if not isinstance(a, str):
continue
if ":" in a:
accounts.append(a)
elif _MCP_ACCOUNT_RE.match(a) and not a.startswith("guest-"):
accounts.append(f"claude:{a}")
out = {"transport": t, "accounts": sorted(set(accounts)), "mode": "direct",
"preset": old.get("preset") if isinstance(old.get("preset"), str) else None,
"createdAt": old.get("createdAt")}
if t in ("http", "sse"):
if not isinstance(old.get("url"), str):
return None
out["url"] = old["url"]
out["headers"] = {k: v for k, v in (old.get("headers") or {}).items()
if isinstance(k, str) and isinstance(v, str)}
else:
if not isinstance(old.get("command"), str):
return None
out["command"] = old["command"]
out["args"] = [a for a in old.get("args") or [] if isinstance(a, str)]
out["env"] = {k: v for k, v in (old.get("env") or {}).items()
if isinstance(k, str) and isinstance(v, str)}
return out
def _bool_map(raw) -> dict[str, bool]:
return {k: v for k, v in (raw or {}).items()
if isinstance(k, str) and _MCP_NAME_RE.match(k) and isinstance(v, bool)} \
if isinstance(raw, dict) else {}
def _read_json(path: pathlib.Path) -> dict:
try:
v = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return v if isinstance(v, dict) else {}
def _write_private(path: pathlib.Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f".{path.name}.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=2)
os.chmod(tmp, 0o600)
os.replace(tmp, path)
def mcp_servers(store: PluginStore, workers=None, legacy: str = MCP_SERVERS_LEGACY_PATH) -> bool:
"""The core's MCP servers → the ``mcp-servers`` plugin, once (see the
module's docstring). Waits (False) until the plugin is installed and
enabled for the owner; True when it carried something over now."""
src = pathlib.Path(legacy)
if not src.is_file():
return False
try:
rec = store.get_raw(OWNER_UID, MCP_PLUGIN)
except Exception:
rec = None
if not rec or not rec.get("enabled") or rec.get("needsApproval"):
return False # not installed yet: the install (or the next start) carries it over
shared = store.shared_data_dir(MCP_PLUGIN)
marker = shared / ".carried-over"
if marker.exists():
return False
raw = _read_json(src)
try:
priv = shared / "_private"
cur = _read_json(priv / "servers.json")
servers = dict(cur.get("servers") or {}) if isinstance(cur.get("servers"), dict) else {}
added = []
for name, old in (raw.get("servers") or {}).items() if isinstance(raw.get("servers"), dict) else ():
if not isinstance(name, str) or not _MCP_NAME_RE.match(name) or name in servers:
continue
s = _mcp_server(old)
if s:
servers[name] = s
added.append(name)
ov_cur = _read_json(priv / "overrides.json")
overrides = {k: dict(v) for k, v in ov_cur.items() if isinstance(v, dict)}
lab = _bool_map(((raw.get("lab") or {}) if isinstance(raw.get("lab"), dict) else {}).get("overrides"))
machines = {"local": lab} if lab else {}
for w in (workers.list() if workers is not None else []):
if w.get("owner"):
continue
ov = _bool_map(w.get("mcpServerOverrides"))
if ov:
machines[w["id"]] = ov
for mid, ov in machines.items():
overrides[mid] = {**ov, **overrides.get(mid, {})}
_write_private(priv / "servers.json", {**cur, "servers": servers})
if overrides or (priv / "overrides.json").exists():
_write_private(priv / "overrides.json", overrides)
marker.write_text("1")
log.info("mcp-servers: carried %s over (%d server(s): %s; ticks of %d machine(s))",
src, len(added), ", ".join(added) or "none", len(machines))
except Exception as e: # noqa: BLE001 — never keep the hub from starting
log.warning("mcp-servers carry-over: %s", e)
return False
return True
def _seed_dirs() -> list[pathlib.Path]:
env = os.environ.get("PLUGINS_SEED_DIR")
if env is not None: # set but empty: seeding off
return [pathlib.Path(env)] if env else []
return [pathlib.Path("/workspace/projects/ai-agent-plugins/plugins"),
pathlib.Path.home() / "projects" / "ai-agent-plugins" / "plugins"]
def seed_typed_plugins(store: PluginStore | None, seed_dir: str | os.PathLike | None = None) -> list[str]:
"""Install + promote to the hub catalog every ``provider-*`` / ``harness-*``
plugin of the seed dir (``PLUGINS_SEED_DIR``, else the plugins repo
checkout) the owner doesn't have yet. Each is seeded **once**: the store
remembers it (``seeded``), so a plugin the owner uninstalled stays gone and
a later start never re-installs it. Returns the ids installed now."""
if store is None:
return []
from plugins.manifest import ManifestError, validate_manifest
dirs = [pathlib.Path(seed_dir)] if seed_dir else _seed_dirs()
root = next((d for d in dirs if d.is_dir()), None)
if root is None:
return []
seeded = store.seeded()
installed = {r["id"] for r in store.list_for(OWNER_UID)}
out: list[str] = []
for child in sorted(root.iterdir()):
if not child.is_dir() or not child.name.startswith(("provider-", "harness-")):
continue
if not (child / "plugin.json").is_file():
continue
try:
mf = validate_manifest(child)
except ManifestError as e:
log.warning("seed plugin %s is invalid: %s", child.name, e)
continue
pid = mf["id"]
if (mf.get("kind") or "app") == "app" or pid in seeded:
continue
if pid in installed: # the owner installed it by hand: just remember it
store.mark_seeded(pid)
continue
try:
store.install(OWNER_UID, str(child), is_owner=True, approve=True)
store.promote_catalog(str(child), guests_allowed=False)
except Exception as e: # noqa: BLE001 — one bad plugin doesn't stop the others
log.warning("seeding %s failed: %s", pid, e)
continue
store.mark_seeded(pid)
out.append(pid)
if out:
log.info("seeded typed plugins: %s", ", ".join(out))
return out
def run_all(store: PluginStore | None, notify_store=None, ui_state=None, users=None,
workers=None, meta_store=None) -> None:
if store is None:
return
leftovers(store)
mail_senders(store)
approvals(store)
ship(store)
scheduled(store)
ha_webhook(store, notify_store)
clarifier(ui_state, users)
new_project(store, users)
mcp_servers(store, workers)
handoffs(meta_store)