Files
ai-agent/backend/plugins/schedule_bridge.py
gabrielvidalandClaude Opus 5.5 aee457cdbf Merge origin/main into hub-mcp-plugin
main moved cron jobs into the cron-jobs plugin (#37) and retired the core
Send later doors for the scheduled-conversations plugin's commands (#36),
both touching the core MCP files this branch moves into the hub-mcp plugin.

- The MCP stays out of core: backend/mcpserver/, cli/mcp_tools.py,
  cli/mcp_server.py, their tests and business/aiApps/ stay deleted (main's
  edits to them — no schedule group, no cron / schedule tools — are the
  plugin's to apply).
- Cron and Send later follow main: backend/cron/routes.py gone (its
  by-name worker pick is runs.start's at fire time now), no ai-agent
  later / scheduled / unschedule — so a worker's narrowed CLI drops them
  from its command lists (workers/cli.py) and schedules nothing; Full
  reaches the plugin's commands.
- authz: neither runs.schedule nor mcp.connect.
- Settings: neither Scheduled jobs nor AI apps in the registry; both old
  addresses redirect to their plugin's page.
- Regenerated openapi.json, src/generated, rolesCatalog.json,
  matrix.golden.txt and telemetry features.json.
- cli/test_library_surface.py: parse_when left with `ai-agent later`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:14:16 +01:00

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 hub-mcp plugin 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 core MCP ``schedule_conversation`` /
``cancel_scheduled`` / ``browse scheduled`` went on 2026-11-28. A worker's
CLI schedules only on its *Full* switch (plugin commands need
``plugins.use``, which the ``worker.read`` / ``worker.run`` scopes don't hold).
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)