Files
ai-agent/backend/plugins/scheduler.py
gabrielvidalandClaude Opus 5.5 83d1827119 feat(plugins): keyboard shortcuts leave the core for the keyboard-shortcuts plugin — app.keymap, optionalRequires, commands() / keyChord bridges
Which keys run which command is now a live plugin's (`keyboard-shortcuts`,
ai-agent-plugins): the defaults, each person's own bindings, the on/off
switch, Settings → Keyboard (a nav "settings" page) and the cheat sheet (an
app.modal slot). The core keeps what a sandboxed frame can't do: the one
keydown listener, the commands and their handlers. No plugin, no shortcuts.

- provides `app.keymap` → GET /api/plugins/keymap (plugins/keymap.py):
  the provider run as the caller, sanitized, cached; dropped on any plugin
  change and after a write of the provider (SSE `keymap` to that user).
- commands: the app's (lib/keyboard/actions.ts, no defaults any more) plus
  `composer.shortcut:<chip id>` (a named guideline chip) and
  `modal:<pluginId>:<slotId>` (a plugin's modal — the cheat sheet).
- `optionalRequires`: optional peers — no install/enable checks, their
  exports and plugin events open while they are on; the info page's
  "Works with" row. prompt-shortcuts is the keyboard plugin's.
- frame bridges `commands()` and `keyChord()`; a frame's unused keys go on
  to the app's key layer while it has the focus (g h on a plugin page).
- carryover.keyboard: each person's state.keyboard → the plugin's
  keymap.json, once.
- the core Keyboard page, CheatSheet and settings.keyboard are gone;
  /settings/keyboard redirects to the plugin's page.

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

180 lines
7.3 KiB
Python

"""Scheduled non-LLM jobs (v1) and outbound hub event dispatch (v2) for live
plugins."""
from __future__ import annotations
import datetime as dt
import hashlib
import hmac
import json
import logging
import threading
import time
from typing import Any
import httpx
from cron.scheduler import due as cron_due, parse_schedule
from plugins.egress import check_public_url
from plugins.runner import ActionError, run_script
from plugins.store import OWNER_UID, PluginStore
log = logging.getLogger("plugins.scheduler")
class PluginScheduler(threading.Thread):
"""Evaluates every enabled plugin's 5-field cron ``schedules[]`` once per
minute and runs due scripts in the stripped-env sandbox."""
def __init__(self, deps, store: PluginStore):
super().__init__(name="plugin-scheduler", daemon=True)
self.deps = deps
self.store = store
self._fired: set[tuple[str, str, str, str]] = set()
self._stop = threading.Event()
def stop(self) -> None:
self._stop.set()
def run(self) -> None:
time.sleep(15)
while not self._stop.is_set():
try:
self.tick(dt.datetime.now())
except Exception:
log.exception("plugin scheduler tick failed")
# A second past each half minute: a ``* * * * *`` job (the
# scheduled-conversations plugin's start) fires at :01, not
# anywhere in the minute's first 30 s.
self._stop.wait(30 - (time.time() % 30) + 1)
def tick(self, now: dt.datetime) -> int:
minute_key = now.strftime("%Y-%m-%dT%H:%M")
# Keep memory bounded
if len(self._fired) > 5000:
self._fired = {k for k in self._fired if k[3] == minute_key}
ran = 0
for uid, rec in self.store.all_installed():
if not rec.get("enabled") or rec.get("needsApproval"):
continue
mf = rec.get("manifest") or {}
pid = mf.get("id") or ""
for sc in mf.get("schedules") or []:
sid = sc["id"]
fire_key = (uid, pid, sid, minute_key)
if fire_key in self._fired:
continue
try:
spec = parse_schedule(sc["cron"])
except Exception:
continue
if not cron_due(spec, now):
continue
self._fired.add(fire_key)
ran += 1
threading.Thread(
target=self._run_one,
args=(uid, rec, sc),
name=f"plugin-job-{uid}-{pid}-{sid}",
daemon=True,
).start()
return ran
def _run_one(self, uid: str, rec: dict[str, Any], sc: dict[str, Any]) -> None:
pid = rec["id"]
sid = sc["id"]
try:
res = run_script(
self.deps, self.store, uid, rec, sc["script"],
payload={"trigger": "schedule", "scheduleId": sid},
timeout_sec=int(sc.get("timeoutSec") or 180),
)
msg = str(res.get("message") or "ok")
self.store.record_schedule_run(uid, pid, sid, True, msg)
except ActionError as e:
log.warning("plugin job %s/%s/%s failed: %s", uid, pid, sid, e.message)
self.store.record_schedule_run(uid, pid, sid, False, e.message)
except Exception as e:
log.exception("plugin job %s/%s/%s crashed", uid, pid, sid)
self.store.record_schedule_run(uid, pid, sid, False, str(e))
finally:
if uid == OWNER_UID:
# a reconcile may have moved what the machines' Needs you say
from plugins import machine_attention, machine_wake
machine_attention.touched(self.deps, rec)
machine_wake.touched(self.deps, rec)
# ── v2 outbound hub event dispatch ───────────────────────────────────────────
def dispatch_event(deps, event_type: str, payload: dict[str, Any], *,
owner_uid: str | None = None,
source_plugin: str | None = None) -> None:
"""Fan out a hub event (``conversation.finished``, ``notify``, ``deploy``…)
or a plugin event (``plugin:<src>:<name>``) to every enabled plugin
subscribing to ``event_type`` for ``owner_uid`` (or owner when ``owner_uid``
is None). Runs off-thread, fire-and-forget."""
store: PluginStore | None = getattr(deps, "plugin_store", None)
if store is None:
return
target_uid = store.norm_uid(owner_uid)
matches: list[tuple[str, dict[str, Any], dict[str, Any]]] = []
for uid, rec in store.all_installed():
if uid != target_uid or not rec.get("enabled") or rec.get("needsApproval"):
continue
mf = rec.get("manifest") or {}
if source_plugin and source_plugin not in (
(mf.get("requires") or []) + (mf.get("optionalRequires") or [])):
continue
for ev in mf.get("events") or []:
if event_type in (ev.get("on") or []):
matches.append((uid, rec, ev))
if not matches:
return
threading.Thread(
target=_deliver_batch,
args=(deps, store, event_type, payload, matches, source_plugin),
name=f"plugin-ev-{event_type}",
daemon=True,
).start()
def _deliver_batch(deps, store: PluginStore, event_type: str,
payload: dict[str, Any],
matches: list[tuple[str, dict[str, Any], dict[str, Any]]],
source_plugin: str | None = None) -> None:
for uid, rec, ev in matches:
mf = rec.get("manifest") or {}
pid = mf["id"]
if ev.get("action"):
act = (mf.get("actions") or {}).get(ev["action"])
if act:
try:
ev_payload: dict[str, Any] = {"event": event_type, "data": payload}
if source_plugin:
ev_payload["source"] = source_plugin
run_script(deps, store, uid, rec, act["script"],
payload=ev_payload,
timeout_sec=int(act.get("timeoutSec") or 30),
caller_plugin=source_plugin)
except Exception as e:
log.warning("plugin event action %s/%s failed: %s", pid, ev["action"], e)
if ev.get("url"):
url = ev["url"]
if not ev.get("internal"):
ok, why = check_public_url(url)
if not ok:
log.warning("plugin event webhook %s blocked: %s", pid, why)
continue
body = json.dumps({"event": event_type, "plugin": pid, "data": payload}).encode("utf-8")
headers = {"Content-Type": "application/json", "X-AI-Agent-Event": event_type}
if ev.get("secret"):
sec = store.get_secret(uid, pid, ev["secret"])
if sec:
sig = hmac.new(sec.encode("utf-8"), body, hashlib.sha256).hexdigest()
headers["X-AI-Agent-Signature"] = f"sha256={sig}"
try:
httpx.post(url, content=body, headers=headers, timeout=10.0)
except Exception as e:
log.warning("plugin event POST %s -> %s failed: %s", pid, url, e)