Files
ai-agent/backend/plugins/carryover.py
gabrielvidalandClaude Opus 5.5 68f495c5b6 Merge branch 'prompt-shortcuts-plugin' into keyboard-shortcuts-plugin
Settings → Keyboard is a nav "settings" plugin page like Prompt shortcuts:
both core entries are gone, the old keys map onto the plugin pages in saved
layouts, a settings page may say desktopOnly, and the mock lists both.

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

866 lines
38 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.
* **Keyboard shortcuts** (2026-11-27): Settings → Keyboard left for the
``keyboard-shortcuts`` plugin. Each person's ``state.keyboard`` in their
``ai-agent-settings`` blob (``{enabled, bindings}``) becomes their
``keymap.json`` in the plugin's per-user dir, where they have none — the
switch off or any binding of their own; the defaults carry nothing. Once,
then a ``.carried-over`` marker; the old key stays, unread.
* **Prompt shortcuts** (2026-11-27): the core's prompt-shortcut library left
for the ``prompt-shortcuts`` plugin (seeded at start, ``"seed": true``). The
owner's library — ``ui-state`` ``ai-agent-settings`` → ``promptShortcuts``,
each shortcut's audience made explicit (``shared``, ``runners``, ``guests``;
a pre-v4 blob first folds in the old guest list like ``upgrade_owner`` did) —
becomes the plugin's shared ``library.json``; each guest's own shortcuts and
preferences (``u.<id>.ai-agent-settings`` → ``promptShortcuts`` +
``shortcutPrefs``, their pre-v4 copies of the old guest list dropped) their
``personal.json``. Files the plugin already has are kept; the ui-state blobs
are left as they are (the frontend's v5 migration drops the keys); a marker
makes it run once.
* **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``.
* **What's new** (2026-11-26): the core's guests' feature carousel
(``backend/whatsnew/``: the ``whats_new`` and ``whats_new_seen`` tables of
``ai-agent.db``) becomes the ``whats-new`` plugin's shared ``entries.json``
(``{"entries": [{id, title, body, mockup, status, publishedAt, createdAt,
updatedAt, sessionId}]}``) and ``seen.json`` (``{"seen": {uid: {entry id:
seen at}}}``) — where the plugin has none yet; the tables are left as they
are, unread. Each guest whose ``users.json`` switch ``whatsNew`` was off gets
the plugin's managed grant with ``autoOpen: false`` once the plugin is
installed (until then, the next start tries again); a ``.carried-over``
marker in its shared dir makes it all run once.
"""
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"
WHATS_NEW_PLUGIN = "whats-new"
KEYBOARD_PLUGIN = "keyboard-shortcuts"
SHORTCUTS_PLUGIN = "prompt-shortcuts"
# The frontend's settings store and the persist version (v4) since which every
# shortcut says who gets it.
_SETTINGS_KEY, _AUDIENCE_VERSION = "ai-agent-settings", 4
# Shared across runners when a config from before ``shared`` (v3) doesn't say
# — the frontend's old ``SHARED_DEFAULT_IDS``.
_SHARED_DEFAULT_IDS = frozenset({"worktree", "commit", "pr", "notify", "ask", "clarify",
"tasks", "changes", "form"})
_SHORTCUT_KEYS = ("id", "label", "icon", "guideline", "defaultOn", "labelOff",
"guidelineOff", "children", "triggers", "shared", "runners", "guests")
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
def _iso(t) -> str | None:
if t is None:
return None
import datetime as dt
try:
return dt.datetime.fromtimestamp(float(t), dt.timezone.utc).isoformat(
timespec="milliseconds").replace("+00:00", "Z")
except (TypeError, ValueError, OverflowError, OSError):
return None
def _whats_new_rows(db_path: str) -> tuple[list[dict], dict[str, dict[str, str]]] | None:
"""The core's What's new tables, read-only; None when there are none."""
import sqlite3
if not db_path or not pathlib.Path(db_path).is_file():
return None
try:
con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=5)
except sqlite3.Error:
return None
try:
names = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}
if "whats_new" not in names:
return None
entries = [{"id": r[0], "title": r[1], "body": r[2], "mockup": r[3] or "", "status": r[4],
"publishedAt": _iso(r[5]), "createdAt": _iso(r[6]), "updatedAt": _iso(r[7]),
"sessionId": r[8]}
for r in con.execute(
"SELECT id, title, body, mockup, status, published_at, created_at, updated_at,"
" session_id FROM whats_new ORDER BY created_at")]
seen: dict[str, dict[str, str]] = {}
if "whats_new_seen" in names:
for uid, eid, at in con.execute("SELECT user_id, entry_id, seen_at FROM whats_new_seen"):
seen.setdefault(str(uid), {})[str(eid)] = _iso(at) or ""
return entries, seen
except sqlite3.Error as e:
log.warning("whats-new carry-over: reading %s: %s", db_path, e)
return None
finally:
con.close()
def whats_new(store: PluginStore, users=None, db_path: str | None = None) -> bool:
"""The core's What's new → the ``whats-new`` plugin's shared files, and
the guests it was switched off for → its grant's ``autoOpen: false``."""
if db_path is None:
from core.config import DB_PATH as db_path # noqa: N811
shared = store.shared_data_dir(WHATS_NEW_PLUGIN)
marker = shared / ".carried-over"
if marker.exists():
return False
moved = False
dst = shared / "entries.json"
if not dst.exists():
rows = _whats_new_rows(db_path)
if rows is not None:
entries, seen = rows
try:
shared.mkdir(parents=True, exist_ok=True)
(shared / "seen.json").write_text(json.dumps({"seen": seen}, ensure_ascii=False, indent=1))
dst.write_text(json.dumps({"entries": entries}, ensure_ascii=False, indent=1))
for f in (dst, shared / "seen.json"):
os.chmod(f, 0o644)
log.info("whats-new: carried %d entries and %d guests' seen marks over",
len(entries), len(seen))
moved = True
except OSError as e:
log.warning("whats-new carry-over: %s", e)
return False
if users is None:
return moved
try:
rec = store.get_raw(OWNER_UID, WHATS_NEW_PLUGIN)
except Exception:
rec = None
if not rec or not (rec.get("manifest") or {}).get("managed"):
return moved # not installed yet: the switches wait for the next start
try:
for u in users.all():
uid = u.get("id")
if uid and u.get("whatsNew") is False:
store.set_grant(uid, WHATS_NEW_PLUGIN, enabled=True, config={"autoOpen": False})
log.info("whats-new: %s keeps the carousel off (autoOpen: false)", uid)
marker.write_text("1")
moved = True
except Exception as e:
log.warning("whats-new carry-over (switches): %s", e)
return moved
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 — and every *app* plugin there that
declares ``"seed": true`` (the prompt-shortcuts plugin, which replaced a
core feature every composer used). 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 / "plugin.json").is_file():
continue
typed = child.name.startswith(("provider-", "harness-"))
if not typed and not _asks_seed(child):
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"]
app = (mf.get("kind") or "app") == "app"
if (app and not mf.get("seed")) 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)
# (a managed app reaches guests through its grant — not the catalog)
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 plugins: %s", ", ".join(out))
return out
def _settings_keyboard(ui_state, key: str) -> dict | None:
"""``state.keyboard`` of one settings blob, when it holds anything."""
raw = ui_state.get(key)
if not raw:
return None
try:
blob = json.loads(raw)
except ValueError:
return None
kb = ((blob or {}).get("state") or {}).get("keyboard") if isinstance(blob, dict) else None
if not isinstance(kb, dict):
return None
bindings = kb.get("bindings") if isinstance(kb.get("bindings"), dict) else {}
clean = {str(k): [str(b) for b in v if isinstance(b, str)][:4]
for k, v in bindings.items() if isinstance(v, list)}
enabled = kb.get("enabled") is not False
if enabled and not clean:
return None # the defaults: nothing to carry
return {"enabled": enabled, "bindings": clean}
def keyboard(store: PluginStore, ui_state, users=None) -> int:
"""Each person's Settings → Keyboard (``state.keyboard`` of their
``ai-agent-settings`` blob: the switch and their own bindings, an action
id → its keys, ``[]`` = unbound) → the ``keyboard-shortcuts`` plugin's
per-user ``keymap.json`` (same shape, same action ids), where they have
none yet. Runs whether or not the plugin is installed yet (it only writes
the user's data dir); a ``.carried-over`` marker makes it run once. The
old key stays in the blob, unread. Returns how many people it carried."""
if ui_state is None:
return 0
marker = store.shared_data_dir(KEYBOARD_PLUGIN) / ".carried-over"
if marker.exists():
return 0
who: list[tuple[str, str]] = [(OWNER_UID, "ai-agent-settings")]
if users is not None:
try:
who += [(u["id"], f"u.{u['id']}.ai-agent-settings") for u in users.all()
if u.get("id") and u["id"] != OWNER_UID]
except Exception as e: # noqa: BLE001
log.warning("keyboard carry-over: listing users: %s", e)
return 0
moved = 0
try:
for uid, key in who:
kb = _settings_keyboard(ui_state, key)
if kb is None:
continue
dst = store.user_data_dir(uid, KEYBOARD_PLUGIN) / "keymap.json"
if dst.exists():
continue
dst.write_text(json.dumps(kb, ensure_ascii=False, indent=1))
moved += 1
marker.write_text("")
except OSError as e:
log.warning("keyboard carry-over: %s", e)
return moved
if moved:
log.info("keyboard-shortcuts: carried %d people's keyboard settings over", moved)
return moved
def _asks_seed(child: pathlib.Path) -> bool:
"""An app plugin's ``plugin.json`` says ``"seed": true`` — read before the
full validation, so the other plugins of the seed dir cost one small read."""
try:
raw = json.loads((child / "plugin.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return False
return isinstance(raw, dict) and raw.get("seed") is True
def _settings_state(value: str | None) -> tuple[dict, int] | None:
"""(state, persist version) of a settings blob, None when unreadable."""
try:
blob = json.loads(value) if value else None
except ValueError:
return None
if not isinstance(blob, dict) or not isinstance(blob.get("state"), dict):
return None
v = blob.get("version")
return blob["state"], v if isinstance(v, int) else 0
def _norm_shortcut(sc) -> dict | None:
"""A stored shortcut with its audience spelled out: ``shared``, else its
``runners`` (v3's single ``runner``, else the lab — what the frontend's
``runnersOf`` read), and ``guests``."""
if not isinstance(sc, dict) or not str(sc.get("id") or "").strip() \
or not str(sc.get("label") or "").strip():
return None
out = {k: sc[k] for k in _SHORTCUT_KEYS if k in sc}
shared = sc.get("shared")
out["shared"] = shared if isinstance(shared, bool) else sc["id"] in _SHARED_DEFAULT_IDS
if not out["shared"] and not isinstance(out.get("runners"), list):
out["runners"] = [sc["runner"]] if isinstance(sc.get("runner"), str) and sc["runner"] else ["local"]
out["guests"] = sc.get("guests") is True
return out
def _fold_legacy(lib: list, legacy: list[dict]) -> list:
"""Before v4 guests got a separate list: one the owner has word for word
just gains ``guests``; any other joins as a guests-only shortcut (no
runner; ``guest-<id>`` when the id is taken) — what the core's
``upgrade_owner`` did on read."""
lib = [dict(sc) if isinstance(sc, dict) else sc for sc in lib]
by_id = {sc.get("id"): sc for sc in lib if isinstance(sc, dict)}
for g in legacy:
mine = by_id.get(g["id"])
if mine is not None and all(mine.get(k) == g.get(k) for k in ("label", "guideline")):
mine["guests"] = True
continue
gid = g["id"] if mine is None else f"guest-{g['id']}"
if gid in by_id:
continue
add = {**g, "id": gid, "guests": True, "shared": False, "runners": []}
lib.append(add)
by_id[gid] = add
return lib
def _write_json(path: pathlib.Path, data) -> None:
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
os.replace(tmp, path)
def prompt_shortcuts(store: PluginStore, ui_state, users=None) -> bool:
"""The core's prompt shortcuts → the ``prompt-shortcuts`` plugin's files,
once (see the module docstring). Needs no install: the files wait in the
plugin's dirs for the seeded install to read them."""
if ui_state is None:
return False
shared = store.shared_data_dir(SHORTCUTS_PLUGIN)
marker = shared / ".carried-over"
if marker.exists():
return False
legacy: list[dict] = []
if users is not None and hasattr(users, "legacy_guest_shortcuts"):
try:
legacy = users.legacy_guest_shortcuts()
except Exception: # noqa: BLE001
legacy = []
legacy_ids = {g["id"] for g in legacy}
moved = False
try:
owner = _settings_state(ui_state.get(_SETTINGS_KEY))
lib = owner[0].get("promptShortcuts") if owner else None
dst = shared / "library.json"
if isinstance(lib, list) and not dst.exists():
has_audience = any(isinstance(sc, dict) and "guests" in sc for sc in lib)
if owner[1] < _AUDIENCE_VERSION and not has_audience:
lib = _fold_legacy(lib, legacy)
clean = [n for n in map(_norm_shortcut, lib) if n]
_write_json(dst, {"version": 1, "shortcuts": clean})
log.info("prompt-shortcuts: carried the owner's %d shortcuts over to %s", len(clean), dst)
moved = True
for u in (users.all() if users is not None else []):
uid = u.get("id")
if not uid:
continue
got = _settings_state(ui_state.get(f"u.{uid}.{_SETTINGS_KEY}"))
if not got:
continue
state, version = got
mine = state.get("promptShortcuts") if isinstance(state.get("promptShortcuts"), list) else []
if version < _AUDIENCE_VERSION: # their frozen copies of the old guest list
mine = [sc for sc in mine if not (isinstance(sc, dict) and sc.get("id") in legacy_ids)]
personal = [{**n, "shared": True, "guests": True}
for n in map(_norm_shortcut, mine) if n]
prefs = state.get("shortcutPrefs") if isinstance(state.get("shortcutPrefs"), dict) else {}
prefs = {k: {pk: pv for pk, pv in v.items() if pk in ("hidden", "defaultOn") and isinstance(pv, bool)}
for k, v in prefs.items() if isinstance(k, str) and isinstance(v, dict)}
prefs = {k: v for k, v in prefs.items() if v}
if not personal and not prefs:
continue
try:
pdst = store.user_data_dir(uid, SHORTCUTS_PLUGIN) / "personal.json"
except ValueError:
continue
if pdst.exists():
continue
_write_json(pdst, {"shortcuts": personal, "prefs": prefs})
log.info("prompt-shortcuts: carried %s's %d shortcuts over", uid, len(personal))
moved = True
marker.write_text("1")
except Exception as e: # noqa: BLE001 — never stop the boot; the next start retries
log.warning("prompt-shortcuts carry-over: %s", e)
return moved
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)
whats_new(store, users)
keyboard(store, ui_state, users)
prompt_shortcuts(store, ui_state, users)