Files
ai-agent/backend/plugins/shortcuts.py
gabrielvidalandClaude Opus 5.5 840fd8593f feat(plugins): prompt shortcuts leave the core for the prompt-shortcuts plugin
Gabriel's form prompt-shortcuts-into-a-plugin_dkhipt: everything moves —
the owner's library, its editor and audience matrix, the guest sharing,
guests' own shortcuts and prefs, the built-in Changes chip. The core keeps
the composer's chips engine, the always-on notify line and the prompt pills.

Platform hooks (generic, reused by the keyboard-shortcuts move):
- ui.pages[].nav "settings" (+ group, after): a Settings entry routed at
  /settings/p/<id>/<page>, listed in the panel, the drawers, the search and
  the palette, right after the entry `after` names (a core id or another
  plugin page's id; else the end of its group).
- top-level "seed": true: an app plugin installed once from the seed dir at
  start, like provider-* / harness-*.
- composer.shortcuts: "position": "first", runners: [] and hidden kept, 64
  chips; a POSTed action of a provider drops its cache and publishes
  composer-shortcuts (guests too) so every composer refetches.
- frame bridges aiAgentPlugin.pickIcon (the app's glyph picker in a host
  dialog) and iconSvg(keys); a page's init.lang.

The move:
- carryover.prompt_shortcuts: the owner's promptShortcuts (audience made
  explicit, a pre-v4 blob folding the old guest list) → library.json, each
  guest's promptShortcuts + shortcutPrefs → their personal.json, once.
- settings v7 drops promptShortcuts / shortcutPrefs; settings/shortcuts.py,
  /api/me sharedShortcuts and guest-defaults promptShortcuts are gone.
- Settings → Skills & agents (/settings/setup) is its own entry;
  /settings/shortcuts forwards to the plugin's page (#skills → setup), saved
  panel and drawer layouts keep the old slot.

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

185 lines
7.2 KiB
Python

"""Composer prompt shortcuts contributed by live plugins
(``provides: {"composer.shortcuts": "<action>"}``).
The composer's only source of chips since the prompt-shortcuts plugin took
the library out of the core (2026-11-27): each enabled, approved plugin active
for the caller that declares ``provides.composer.shortcuts`` runs its action
(cached per caller + plugin fingerprint + config, invalidated on plugin
mutations and after any POSTed action of the plugin — :func:`touched`) and
returns a list of declarative ``PromptShortcut`` objects rendered natively by
the core composer's ``RichInput`` with zero iframe latency.
An answer that says ``"position": "first"`` goes before the other plugins'
(the library before ask-form's Form chip); of two chips with one id the first
wins. A guest's answer may flag a chip ``hidden`` (they hid one of the owner's):
the composer leaves it out, the thread's prompt pills still name its line.
"""
from __future__ import annotations
import hashlib
import json
import logging
from typing import Any
from plugins.store import OWNER_UID
from plugins.swr import SWRCache
log = logging.getLogger(__name__)
PROVIDES = "composer.shortcuts"
TTL_SECS = 60.0
# Past the TTL the last answer is still served (the plugin runs again behind
# it) for this long; only an older or missing one makes the composer wait.
MAX_STALE_SECS = 3600.0
_cache = SWRCache(TTL_SECS, MAX_STALE_SECS, name="composer-shortcuts")
# A provider's chips per answer (an owner's whole library).
MAX_SHORTCUTS = 64
def invalidate(pid: str | None = None) -> None:
"""Drop cached shortcuts (all, or for one plugin id)."""
if pid is None:
_cache.clear()
else:
prefix = f":{pid}@"
_cache.drop(lambda k: prefix in k)
def _providers_for(deps, uid: str) -> list[tuple[dict[str, Any], dict[str, Any] | None]]:
store = getattr(deps, "plugin_store", None)
if store is None:
return []
try:
out: list[tuple[dict[str, Any], dict[str, Any] | None]] = [
(rec, None) for rec in store.active_providing(uid, PROVIDES)]
except Exception:
out = []
seen = {rec["id"] for rec, _ in out}
if uid != OWNER_UID:
for rec in store.managed_plugins():
pid = rec["id"]
if pid in seen:
continue
mf = rec.get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
if not (act and act in (mf.get("actions") or {})):
continue
grant = store.effective_grant(uid, pid, mf)
if grant.get("enabled"):
seen.add(pid)
out.append((rec, grant))
return out
def _cache_key(uid: str, rec: dict[str, Any], grant: dict[str, Any] | None) -> str:
cfg = json.dumps({"c": rec.get("config") or {}, "g": (grant or {}).get("config") or {}}, sort_keys=True)
ch = hashlib.sha256(cfg.encode("utf-8")).hexdigest()[:12]
return f"{uid}:{rec['id']}@{rec.get('fingerprint') or ''}:{ch}"
def _clean_shortcuts(pid: str, raw: Any) -> list[dict[str, Any]]:
items = raw.get("shortcuts") if isinstance(raw, dict) else None
if not isinstance(items, list):
return []
out: list[dict[str, Any]] = []
for sc in items[:MAX_SHORTCUTS]:
if not isinstance(sc, dict):
continue
sid = str(sc.get("id") or "").strip()[:64]
label = str(sc.get("label") or "").strip()[:60]
guideline = str(sc.get("guideline") or "").strip()[:2000]
if not sid or not label or not guideline:
continue
entry: dict[str, Any] = {
"id": sid,
"label": label,
"icon": str(sc.get("icon") or "Sparkles")[:48],
"guideline": guideline,
"defaultOn": bool(sc.get("defaultOn", False)),
"shared": bool(sc.get("shared", True)),
"guests": bool(sc.get("guests", True)),
"pluginId": pid,
}
if isinstance(sc.get("labelOff"), str) and sc["labelOff"].strip():
entry["labelOff"] = sc["labelOff"].strip()[:60]
if isinstance(sc.get("guidelineOff"), str) and sc["guidelineOff"].strip():
entry["guidelineOff"] = sc["guidelineOff"].strip()[:2000]
if isinstance(sc.get("triggers"), list):
tr = [str(x).strip()[:60] for x in sc["triggers"] if isinstance(x, str) and x.strip()][:20]
if tr:
entry["triggers"] = tr
if isinstance(sc.get("runners"), list):
# kept even when empty: no runner offers it (a guests-only chip)
entry["runners"] = [str(x).strip()[:64] for x in sc["runners"]
if isinstance(x, str) and x.strip()][:20]
if sc.get("hidden") is True:
entry["hidden"] = True
if isinstance(sc.get("children"), list):
ch = [str(x).strip()[:64] for x in sc["children"] if isinstance(x, str) and x.strip()][:20]
if ch:
entry["children"] = ch
out.append(entry)
return out
def _first(raw: Any) -> bool:
return isinstance(raw, dict) and raw.get("position") == "first"
def _run_one(deps, uid: str, rec: dict[str, Any],
grant: dict[str, Any] | None) -> tuple[bool, list[dict[str, Any]]]:
from plugins.runner import run_script
mf = rec["manifest"]
act = mf["actions"][mf["provides"][PROVIDES]]
try:
raw = run_script(
deps, deps.plugin_store, uid, rec, act["script"],
payload={"trigger": PROVIDES},
timeout_sec=min(15, int(act.get("timeoutSec") or 15)),
grant=grant,
)
except Exception as e:
log.warning("composer.shortcuts plugin %s failed: %s", rec.get("id"), e)
return False, []
return _first(raw), _clean_shortcuts(rec["id"], raw)
def shortcuts_for(deps, caller) -> list[dict[str, Any]]:
"""Every plugin-contributed composer shortcut active for ``caller``."""
uid = OWNER_UID if caller.is_owner else caller.id
answers: list[tuple[bool, list[dict[str, Any]]]] = []
for rec, grant in _providers_for(deps, uid):
key = _cache_key(uid, rec, grant)
answers.append(_cache.get(key, lambda rec=rec, grant=grant: _run_one(deps, uid, rec, grant)))
out: list[dict[str, Any]] = []
seen_ids: set[str] = set()
# the ones that asked to go first, then the rest — each in provider order
for first, items in sorted(answers, key=lambda a: not a[0]):
for sc in items:
if sc["id"] not in seen_ids:
seen_ids.add(sc["id"])
out.append(sc)
return out
def provides_shortcuts(rec: dict[str, Any] | None) -> bool:
mf = (rec or {}).get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
return bool(act and act in (mf.get("actions") or {}))
def touched(deps, rec: dict[str, Any] | None) -> None:
"""The plugin ``rec`` just ran a POSTed action (its page saved): when it
provides ``composer.shortcuts``, drop its cached chips — every caller's,
a guest's view reads the owner's library — and tell every app to refetch
them (``composer-shortcuts``)."""
if not provides_shortcuts(rec):
return
invalidate(rec["id"])
try:
deps.hub.publish({"type": "composer-shortcuts"})
except Exception: # noqa: BLE001 — no hub (tests)
pass