Files
ai-agent/backend/plugins/scheduler.py
gabrielvidalandClaude Opus 5.5 8c7264f6e2 feat(wol): Wake-on-LAN core support for the wake-on-lan plugin
- sidecar: POST /wol (routes_wol.py, host only) — strict MAC / IPv4 /
  port checks, a UDP magic packet with SO_BROADCAST.
- manifest: the machines.wake capability (operator-approved) and
  provides: machine.wake.
- plugins/hubwake.py: the machines.wake bridge for the plugin's own
  handlers — POST …/hub/wol, POST …/hub/workers/{wid}/probe,
  GET …/hub/wake/workers (each also under …/bridge/…).
- plugins/machine_wake.py: list_wakeable (30 s cache, dropped on the
  provider's actions / install changes, SSE machine-wake), wake_machine,
  maybe_wake_and_wait, probe_in_background.
- runs/service.py: a run pinned to an offline worker, and a resume of a
  session on one, wait for an auto-wake before the 409 worker_offline;
  an unpinned run still falls back to the next runner up, no wake.
- GET /api/machines/wakeable (lab.read), POST /api/machines/{id}/wake
  (workers.manage), schemas + regenerated openapi / orval types.
- Settings → Machines: ⚡ Wake on an offline worker the plugin has
  configured (Waking… until the workers SSE flips it online).
- tests: sidecar/test_wol.py, backend/test_machine_wake.py,
  WakeButton.test.tsx; docs/plugins.md.

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

176 lines
7.1 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")
self._stop.wait(30)
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 []):
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)