Files
ai-agent/backend/plugins/schedule_bridge.py

114 lines
4.3 KiB
Python

"""Scheduled conversations ("Send later") — the host's side, now that they
are a live plugin (``scheduled-conversations``, since 2026-11-26: the core's
``backend/scheduled/`` — store, scheduler thread, service — is gone).
The plugin that ``provides: {"runs.schedule": "<action>"}`` owns the entries,
fires them (its own every-minute job, through the ``runs.start`` /
``conversations.send`` bridges) and draws them (the drawer, the Send later…
modal, the edit modal, its page). The core keeps two readers:
* the week's budget (``usage/budget.py``): ``{"op": "upcoming"}``, cached
:data:`UPCOMING_TTL_S`;
* the app (the stopped-run card's *Resume at…*) calls the action itself
through ``/api/plugins/<id>/actions/<action>`` (``ui.providers``).
The CLI and the MCP reach it through the plugin's own ``commands``
(``ai-agent plugin scheduled-conversations ls | show | add | cancel | start``,
MCP ``plugin_scheduled-conversations_*``) — the core's ``/api/scheduled*``
doors, ``ai-agent later`` / ``scheduled`` / ``unschedule`` and the MCP
``schedule_conversation`` / ``cancel_scheduled`` / ``browse scheduled`` went
on 2026-11-28. A connection bound to a worker has no plugin tools (no
``plugins.use``): it can't schedule — the owner's own CLI or a full
connection does.
No plugin: the budget counts nothing, *Resume at…* isn't offered.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Any
from fastapi import HTTPException
from plugins.store import OWNER_UID
log = logging.getLogger(__name__)
PROVIDES = "runs.schedule"
UPCOMING_TTL_S = 30.0
NO_PROVIDER = {"message": "the Scheduled conversations plugin isn't installed or is off "
"(Settings → Plugins)", "kind": "no_provider"}
_cache_lock = threading.Lock()
_upcoming: tuple[float, list[dict]] | None = None
def _provider(deps) -> tuple[dict[str, Any], dict[str, Any]] | None:
"""The owner's active plugin providing ``runs.schedule`` → (rec, its action)."""
from plugins.waiting import _providers_for
try:
found = _providers_for(deps, OWNER_UID, PROVIDES)
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
return None
for rec, _grant in found:
mf = rec.get("manifest") or {}
act = (mf.get("actions") or {}).get((mf.get("provides") or {}).get(PROVIDES))
if act:
return rec, act
return None
def available(deps) -> bool:
return _provider(deps) is not None
def run_op(deps, op: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
"""The provider's answer to ``{"op": op, **payload}``, run as the owner.
Raises HTTPException: 404 ``no_provider``, or the plugin's own refusal
(its ``_error`` status, kind and message)."""
hit = _provider(deps)
if hit is None:
raise HTTPException(404, NO_PROVIDER)
rec, act = hit
from plugins.runner import ActionError, run_script
try:
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
payload={**(payload or {}), "op": op},
timeout_sec=int(act.get("timeoutSec") or 60))
except ActionError as e:
raise HTTPException(e.status, {"message": e.message, "kind": e.kind}) from None
if op != "upcoming":
drop_cache()
return res if isinstance(res, dict) else {}
def drop_cache() -> None:
global _upcoming
with _cache_lock:
_upcoming = None
def upcoming(deps) -> list[dict]:
"""The entries still to start — ``[{id, title, shouldStartAt, model,
account, worker}]`` — for the week's budget; ``[]`` without the plugin
or when it fails (a broken plugin never breaks the budget)."""
global _upcoming
now = time.monotonic()
with _cache_lock:
if _upcoming and now - _upcoming[0] < UPCOMING_TTL_S:
return list(_upcoming[1])
if not available(deps):
return []
try:
items = run_op(deps, "upcoming").get("items")
except Exception as e: # noqa: BLE001
log.warning("runs.schedule upcoming failed: %s", getattr(e, "detail", e))
return []
items = [i for i in items if isinstance(i, dict)] if isinstance(items, list) else []
with _cache_lock:
_upcoming = (now, items)
return list(items)