Files
gabrielvidalandClaude Opus 5.5 5670313285 feat(cron): cron jobs leave the core for the cron-jobs plugin
Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's
(forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b,
cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/,
schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread,
Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron`
(now a pointer), MCP run_cron_job / set_cron_job / browse cron, the
scheduled-jobs core skill, guestDefaults.cronLimits.

The core keeps thin contracts:
- runs.guest bridge (runs/guestjob.py): a guest's job run as that guest,
  confined by the core from their record; the plugin only names it.
- runs.start's cron stamp → meta.cron.
- delivery of a guest job's result (push, mail, mailHtml) off the stamp.
- « Discuter »: POST /api/cron-runs/discuss.
- runs.cron provider readers (plugins/cron_bridge.py): budget,
  auto-archive, agents catalog, the agents page's Schedule.
- core/cronexpr.py, agents/runconfig.py; context.write create for a new
  agent definition; ui.pages[].unless; setRoute keeps a Settings page
  under /settings/p/.
- carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json,
  cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's
  decision, superseded).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:57:41 +01:00

176 lines
6.4 KiB
Python

"""Cron jobs — the host's side, now that they are a live plugin
(``cron-jobs``, since 2026-11-28: the core's ``backend/cron/`` — store,
scheduler thread, routes, guest jobs — is gone; Gabriel's form
``move-ai-agent-cron-jobs-into-a-plugin_u0wa6b``).
The plugin that ``provides: {"runs.cron": "<action>"}`` owns the jobs (owner
jobs and guests' own), fires them (its every-minute job, through the
``runs.start`` / ``runs.guest`` bridges), draws them (its Settings pages) and
answers the CLI / MCP (its ``commands``). The core keeps a few readers, each
asking that action as the owner with ``{"op": …}``:
* ``index`` — every job without its run config (``id``, ``name``, ``owner``,
``promptFile``, ``enabled``, ``schedule``, ``worker``, ``archiveOnSuccess``,
``history`` ``{iso: sessionId}``): auto-archive's per-job
``archiveOnSuccess``, the agents catalog's cron runs (a job whose prompt
file is an agent definition), the agent page's "its cron job";
* ``list`` — the same plus ``runConfig`` and ``nextRun``: the week's budget
(``usage/budget.py``);
* ``get`` ``{id}`` — one job (delivering a run fired before the move);
* ``create`` ``{name, schedule, promptFile}`` — the agents page's *Schedule*
(``plugins/hubcatalog.py``).
The two reads are cached (:data:`TTL_S`) and refreshed off the caller's
thread once stale — the catalog and the auto-archive sweep ask on hot paths
and must never wait on a plugin subprocess. No plugin, or a failing one: an
empty list (the budget counts no cron job, nothing is "its cron job", a cron
run archives on success as the default says).
"""
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.cron"
TTL_S = 30.0
NO_PROVIDER = {"message": "the Cron jobs plugin isn't installed or is off "
"(Settings → Plugins)", "kind": "no_provider"}
_lock = threading.Lock()
_cache: dict[str, tuple[float, list[dict]]] = {}
_refreshing: set[str] = set()
def _provider(deps) -> tuple[dict[str, Any], dict[str, Any]] | None:
"""The owner's active plugin providing ``runs.cron`` → (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."""
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 not in ("index", "list", "get"):
drop_cache()
return res if isinstance(res, dict) else {}
def drop_cache() -> None:
with _lock:
_cache.clear()
def _fetch(deps, op: str) -> list[dict]:
try:
jobs = run_op(deps, op).get("jobs")
except Exception as e: # noqa: BLE001 — a broken plugin never breaks a reader
log.warning("runs.cron %s failed: %s", op, getattr(e, "detail", e))
return []
return [j for j in jobs if isinstance(j, dict)] if isinstance(jobs, list) else []
def _refresh(deps, op: str) -> None:
try:
jobs = _fetch(deps, op)
with _lock:
_cache[op] = (time.monotonic(), jobs)
finally:
with _lock:
_refreshing.discard(op)
def _cached(deps, op: str, *, wait: bool) -> list[dict]:
"""``op``'s jobs: fresh from the cache; stale → the stale ones while a
thread refreshes them; none yet → fetched now when ``wait``, else ``[]``
and a refresh started."""
now = time.monotonic()
with _lock:
hit = _cache.get(op)
fresh = hit is not None and now - hit[0] < TTL_S
start = not fresh and op not in _refreshing
if start and (hit is not None or not wait):
_refreshing.add(op)
if fresh:
return list(hit[1])
if not available(deps):
return []
if hit is None and wait:
jobs = _fetch(deps, op)
with _lock:
_cache[op] = (time.monotonic(), jobs)
return list(jobs)
if start:
threading.Thread(target=_refresh, args=(deps, op), daemon=True,
name=f"cron-bridge-{op}").start()
return list(hit[1]) if hit else []
def index(deps, *, wait: bool = False) -> list[dict]:
"""Every job, without run configs (see the module docstring). ``wait``:
a first call may block on the plugin (a request); else it answers ``[]``
until the first fetch lands (a background sweep, a memo build)."""
return _cached(deps, "index", wait=wait)
def jobs(deps) -> list[dict]:
"""Every job with its ``runConfig`` and ``nextRun`` (the budget)."""
return _cached(deps, "list", wait=True)
def get(deps, job_id: str) -> dict | None:
if not available(deps):
return None
try:
return run_op(deps, "get", {"id": job_id}).get("job")
except HTTPException:
return None
def by_prompt_file(deps, path: str) -> dict | None:
"""The job scheduled on an agent file — what turns an agent page's
*Schedule* into a "scheduled" state."""
p = (path or "").lstrip("/")
for j in index(deps, wait=True):
if not j.get("owner") and (j.get("promptFile") or "").lstrip("/") == p:
return j
return None
def create(deps, *, name: str, schedule: str, prompt_file: str) -> dict:
"""A new owner job on an agent definition (raises HTTPException)."""
return run_op(deps, "create", {"name": name, "schedule": schedule,
"promptFile": prompt_file}).get("job") or {}