Files
ai-agent/backend/plugins/schedule_bridge.py
gabrielvidalandClaude Opus 5.5 0e68e98795 feat(scheduled): Send later leaves the core for the scheduled-conversations plugin
Generic hooks the plugin builds on: the conversations.drawer, composer.send and
app.modal slot places (openModal / modal.setResult / modal.close, ?modal=
links), runs.start taking the composer's whole payload (auto routing,
account, projects, cwd, meta.scheduled) and hub/runs/resolve, a turn's knobs
on conversations.send, push buttons answered as the notify.action event,
hub/changed (SSE plugin-data), hub/title (conversations.title), the
runs.schedule provider behind /api/scheduled, the week's budget and the
stopped-run card, providers in /api/plugins/ui, carryover.scheduled.

backend/scheduled/ and frontend/src/business/scheduled/ are gone.

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

221 lines
8.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 three readers, each asking
that action as the owner with ``{"op": …}``:
* the ``/api/scheduled*`` routes (below) — the ``ai-agent later`` /
``scheduled`` / ``unschedule`` CLI and the MCP ``schedule_conversation`` /
``cancel_scheduled`` / ``browse scheduled`` tools still call them; a
connection bound to a worker (workers/bound.py) is passed on as
``AIA_USER_CONTEXT.viaWorker`` (+ ``viaWorkerName``, ``workerMode``) and
the plugin keeps it to that worker's entries;
* 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``).
No plugin: the list is empty, the budget counts nothing, every other route is
a 404 ``no_provider``.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import schemas
from core.http import _r
from core.state import State
from plugins.store import OWNER_UID
from users.caller import CallerDep
log = logging.getLogger(__name__)
router = APIRouter()
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, *,
context: 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), context=context)
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)
# ── /api/scheduled — the CLI's and the MCP tools' door ───────────────────────
class ScheduleBody(BaseModel):
# The spawn payload, as the composer would POST /api/spawn it.
prompt: str
text: str | None = None # what was typed (display + title)
model: str | None = None
harness: str | None = None
thinking: bool | None = None
effort: str | None = None
account: str | None = None
projects: list[str] | None = None
cwd: str | None = None
worker: str | None = None # unset ⇒ routed when it starts
profile: str | None = None # the profile it is sent from (routing)
newProject: bool = False
# A scheduled follow-up turn in this existing conversation (the reply
# box's Send later) instead of a new conversation.
targetSessionId: str | None = None
# When, and what it is called until it runs.
shouldStartAt: str
title: str | None = None
titleSource: str | None = None # haiku | user | prompt
summary: str | None = None
class SchedulePatch(BaseModel):
title: str | None = None
prompt: str | None = None
text: str | None = None
shouldStartAt: str | None = None
class TitleBody(BaseModel):
text: str
def _context(caller) -> dict[str, Any] | None:
"""A connection bound to a worker, for the plugin to keep it there."""
if not caller.via_worker:
return None
return {"viaWorker": caller.via_worker, "workerMode": caller.worker_mode}
def _op(deps, caller, op: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
if not caller.is_owner:
raise HTTPException(403, "only the owner schedules conversations")
ctx = _context(caller)
if ctx:
w = deps.worker_store.get(caller.via_worker) or {}
ctx["viaWorkerName"] = w.get("name") or caller.via_worker
return run_op(deps, op, payload, context=ctx)
def _clean(body: BaseModel) -> dict[str, Any]:
return {k: v for k, v in body.model_dump().items() if v not in (None, "", [])}
@router.get("/api/scheduled", responses=_r(schemas.ScheduledList))
def scheduled_list(deps: State, caller: CallerDep):
"""Every scheduled conversation: failed first, then soonest first (none
without the plugin)."""
if caller.is_owner and not available(deps):
return {"items": []}
return {"items": _op(deps, caller, "list").get("items") or []}
@router.post("/api/scheduled", responses=_r(schemas.ScheduledItem))
def scheduled_create(deps: State, caller: CallerDep, body: ScheduleBody):
"""Schedule a composer prompt to be spawned at ``shouldStartAt``."""
return _op(deps, caller, "create", _clean(body))
@router.post("/api/scheduled/title", responses=_r(schemas.ScheduledTitle))
def scheduled_title(deps: State, caller: CallerDep, body: TitleBody):
"""A 3–6 word title (+ one sentence) for a prompt that hasn't run."""
return _op(deps, caller, "title", {"text": body.text})
@router.get("/api/scheduled/{tid}", responses=_r(schemas.ScheduledItem))
def scheduled_get(deps: State, caller: CallerDep, tid: str):
return _op(deps, caller, "get", {"id": tid})
@router.patch("/api/scheduled/{tid}", responses=_r(schemas.ScheduledItem))
def scheduled_edit(deps: State, caller: CallerDep, tid: str, body: SchedulePatch):
"""Edit an entry that hasn't run; a new time reschedules a failed one."""
return _op(deps, caller, "edit", {**body.model_dump(exclude_none=True), "id": tid})
@router.delete("/api/scheduled/{tid}", responses=_r(schemas.OkResponse))
def scheduled_delete(deps: State, caller: CallerDep, tid: str):
_op(deps, caller, "cancel", {"id": tid})
return {"ok": True}
@router.post("/api/scheduled/{tid}/start", responses=_r(schemas.ScheduledItem))
def scheduled_start(deps: State, caller: CallerDep, tid: str):
"""Start it now (Start now / Retry), on the runner it was scheduled on."""
return _op(deps, caller, "start", {"id": tid})