Files
ai-agent/backend/plugins/scheduler.py
gabrielvidalandClaude Fable 5.2 dda5ee80c1 feat(runs): agent limits per machine — a start queue, the runs.limits provider and subagent hook events
A plugin that provides runs.limits sets how many agents each machine runs
at once. A launch over the limit waits in the hub's queue (runs/queue.py)
and starts when the machine is back under it; the limit rides every launch
to the sidecar, which hands it to the run for the plugin's hooks.
SubagentStart / SubagentStop join the script hook events.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-29 12:10:43 +01:00

181 lines
7.4 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 core.cronexpr 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, run_limits
machine_attention.touched(self.deps, rec)
machine_wake.touched(self.deps, rec)
run_limits.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)