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

258 lines
11 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.
"""What is left of an account's week before it resets, and what it still buys.
The week's % (rate-limits.json) and the rate in force (``calibrate.current``)
give the plan units left; from them comes what is already spoken for before
the reset — every enabled cron job's firings (the cron-jobs plugin's — the
provider of ``runs.cron``, plugins/cron_bridge.py), priced at the median of
its last runs, and the scheduled conversations ("Send later" — the plugin providing
``runs.schedule``, plugins/schedule_bridge.py), priced at a typical
single-prompt run of their model — and the rest is **free**: as a %, plan
units, list $ and tokens per model family (each family's own tokens per plan
unit, measured on the account's last ``LOOKBACK_DAYS``).
The pace says whether the week gets there by itself: the % rise over the last
6 h (else 24 h) projected to the reset, against the pace that would use every
free % by then — and how many nonstop runs of each family that pace is (a
family's units per hour = the median of its single-prompt runs of at least
``MIN_RUN_H``, the shape an autonomous run has)."""
from __future__ import annotations
import datetime as dt
import statistics
import time
import accounts as accounts_mod
from core import cronexpr
from . import calibrate, plans
HOUR = 3600
LOOKBACK_DAYS = 14
RUN_SAMPLE = 8 # a cron job's cost = the median of its last N runs
MIN_RUN_H = 1 / 3 # shorter single-prompt runs say little about a pace
MAX_FIRINGS = 400 # per job and window (an every-minute job)
FAMILIES = ("fable", "opus", "sonnet", "haiku")
# Units per hour of a nonstop run, until the account has a few of its own
# (personal seat, 2026-10: Opus 5.5 xhigh median 33, Fable 5.1 ≈ 2.5×).
DEFAULT_RATE = {"fable": 80.0, "opus": 33.0, "sonnet": 8.0, "haiku": 4.0}
# A scheduled conversation whose model has no measured run yet.
DEFAULT_RUN_UNITS = 20.0
def family(model: str | None) -> str | None:
m = (model or "").lower()
return next((f for f in FAMILIES if f in m), None)
def _ts(iso: str | None) -> float | None:
if not iso:
return None
try:
return dt.datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp()
except (ValueError, TypeError):
return None
def firings(expr: str, start: float, end: float) -> list[float]:
"""The epochs a cron expression fires at in [start, end) — container-local
time, like the scheduler."""
out: list[float] = []
after = dt.datetime.fromtimestamp(start)
while len(out) < MAX_FIRINGS:
nxt = cronexpr.next_run(expr, after)
t = _ts(nxt)
if t is None or t >= end:
break
if t >= start:
out.append(t)
after = dt.datetime.fromtimestamp(t)
return out
def _sessions(deps) -> dict[str, dict]:
"""``{sessionId: {summary, units, account}}``: the newest copy of each
main transcript plus every subagent's units (``calibrate.session_totals``,
for all sessions in one pass)."""
from conversations.cards import _summaries_with_account
out: dict[str, dict] = {}
for path, s, acct in _summaries_with_account(deps):
sid = s.get("sessionId")
if not sid:
continue
e = out.setdefault(sid, {"summary": None, "rank": None, "units": 0.0,
"sub": 0.0, "account": acct})
if s.get("isSidechain"):
e["sub"] += s.get("planUnits") or 0.0
continue
rank = (s.get("endedAt") or "", s.get("messages") or 0, path)
if e["rank"] is None or rank > e["rank"]:
e["rank"], e["summary"], e["account"] = rank, s, acct
e["units"] = s.get("planUnits") or 0.0
for e in out.values():
e["units"] += e.pop("sub")
return {sid: e for sid, e in out.items() if e["summary"] is not None}
def _family_stats(deps, account: str, since: float, sessions: dict[str, dict]
) -> dict[str, dict]:
"""Per model family on ``account`` since ``since``: plan units and tokens
(subagents included, by the model that ran them), and its single-prompt
runs' units and units per hour."""
from conversations.cards import _summaries_with_account
st = {f: {"units": 0.0, "tokens": 0, "runUnits": [], "rates": []} for f in FAMILIES}
for _path, s, acct in _summaries_with_account(deps):
if acct != account or (_ts(s.get("endedAt")) or 0) < since:
continue
for model, v in (s.get("byModel") or {}).items():
f = family(model)
if f:
st[f]["units"] += v.get("planUnits") or 0.0
st[f]["tokens"] += v.get("tokens") or 0
for e in sessions.values():
s = e["summary"]
f = family(s.get("model"))
t0, t1 = _ts(s.get("startedAt")), _ts(s.get("endedAt"))
if (e["account"] != account or not f or not t0 or not t1 or t1 < since
or (s.get("userTurns") or 0) > 1 or not e["units"]):
continue
st[f]["runUnits"].append(e["units"])
hours = (t1 - t0) / HOUR
if hours >= MIN_RUN_H:
st[f]["rates"].append(e["units"] / hours)
return st
def _pace(deps, account: str, window: str, pct: float, resets_at: float | None,
now: float, hours: float) -> float | None:
"""% per hour over the last ``hours``, None when the window reset since or
there is no reading that old."""
pts = deps.usage_store.series(account, now - hours * HOUR - HOUR).get(window) or []
old = next((p for p in pts if p[0] >= now - hours * HOUR), None)
if old is None or now - old[0] < HOUR / 2:
return None
if old[1] > pct + 0.5 or (resets_at and old[2] and abs(old[2] - resets_at) > 120):
return None
return max(0.0, (pct - old[1]) / ((now - old[0]) / HOUR))
def _job_account(deps, job: dict, run_cfg: dict, last_run: dict | None) -> str:
if last_run:
return last_run["account"]
if job.get("worker"):
w = deps.worker_store.get(job["worker"]) or {}
if w.get("account"):
return w["account"]
return run_cfg.get("account") or "personal"
def budget(deps, account: str, now: float | None = None) -> dict:
now = time.time() if now is None else now
lim = deps.usage_poller.limits().get(account) or {}
wins = lim.get("windows") or {}
window = "seven_day" if "seven_day" in wins else next(iter(wins), None)
if window is None:
return {"account": account, "window": None, "stale": True}
pct = float(wins[window].get("pct") or 0.0)
resets_at = wins[window].get("resetsAt")
end = float(resets_at) if resets_at else now + 7 * 86400
hours_left = max(0.0, (end - now) / HOUR)
cal = calibrate.current(deps, account)
wk = cal.get("week") or {}
upp = wk.get("unitsPerPct") or 1.0
usd_pp = wk.get("usdPerPct")
sessions = _sessions(deps)
stats = _family_stats(deps, account, now - LOOKBACK_DAYS * 86400, sessions)
# ── what is already spoken for before the reset ─────────────────────────
from plugins import cron_bridge
by_job: dict[str, list[dict]] = {}
for sid, e in sessions.items():
cron = (deps.meta_store.peek(sid).get("cron") or {}).get("id")
if cron:
by_job.setdefault(cron, []).append(e)
items = []
for job in cron_bridge.jobs(deps):
if not job.get("enabled"):
continue
at = firings(job.get("schedule") or "", now, end)
if not at:
continue
runs = sorted(by_job.get(job["id"]) or [],
key=lambda e: e["summary"].get("startedAt") or "")[-RUN_SAMPLE:]
cfg = job.get("runConfig") or {}
if _job_account(deps, job, cfg, runs[-1] if runs else None) != account:
continue
per = statistics.median(e["units"] for e in runs) if runs else None
if per is None:
f = family(cfg.get("model")) or "sonnet"
per = statistics.median(stats[f]["runUnits"]) if stats[f]["runUnits"] else DEFAULT_RUN_UNITS
items.append({"kind": "cron", "id": job["id"], "name": job.get("name") or job["id"],
"runs": len(at), "next": at[0], "unitsPerRun": per,
"sampled": len(runs), "units": per * len(at)})
from plugins import schedule_bridge
for ent in schedule_bridge.upcoming(deps):
t = _ts(ent.get("shouldStartAt"))
if t is None or not now <= t < end:
continue
acct = ent.get("account")
if not acct and ent.get("worker") not in (None, "local"):
acct = (deps.worker_store.get(ent["worker"]) or {}).get("account")
if (acct or "personal") != account:
continue
f = family(ent.get("model")) or "opus"
ru = stats[f]["runUnits"]
per = statistics.median(ru) if ru else DEFAULT_RUN_UNITS
items.append({"kind": "scheduled", "id": ent.get("id"),
"name": ent.get("title") or ent.get("id"), "runs": 1, "next": t,
"unitsPerRun": per, "sampled": len(ru), "units": per})
items.sort(key=lambda i: -i["units"])
upcoming_units = sum(i["units"] for i in items)
# ── what is left, and what it buys ──────────────────────────────────────
left_pct = max(0.0, 100.0 - pct)
left_units = left_pct * upp
free_units = max(0.0, left_units - upcoming_units)
free_pct = free_units / upp
def money(units: float) -> float | None:
return units / upp * usd_pp if usd_pp else None
fams = {}
for f, s in stats.items():
rate = statistics.median(s["rates"]) if len(s["rates"]) >= 3 else DEFAULT_RATE[f]
tok_per_unit = s["tokens"] / s["units"] if s["units"] > 0 else None
fams[f] = {
"tokensPerPct": tok_per_unit * upp if tok_per_unit else None,
"freeTokens": tok_per_unit * free_units if tok_per_unit else None,
"unitsPerHour": rate,
"rateRuns": len(s["rates"]),
"streams": (free_units / (rate * hours_left)) if hours_left > 0 else None,
}
p6 = _pace(deps, account, window, pct, resets_at, now, 6)
p24 = _pace(deps, account, window, pct, resets_at, now, 24)
pace = p6 if p6 is not None else p24
return {
"account": account,
"label": (accounts_mod.get(account) or {}).get("label"),
"plan": plans.public(plans.current(deps.usage_store, account)),
"window": window,
"pct": pct,
"resetsAt": resets_at,
"hoursLeft": hours_left,
"stale": bool(lim.get("stale")),
"rate": {"unitsPerPct": upp, "usdPerPct": usd_pp, "source": cal.get("source"),
"trusted": bool(cal.get("trusted"))},
"left": {"pct": left_pct, "units": left_units, "usd": money(left_units)},
"upcoming": {"pct": upcoming_units / upp, "units": upcoming_units,
"items": items},
"free": {"pct": free_pct, "units": free_units, "usd": money(free_units)},
"pace": {"last6h": p6, "last24h": p24,
"projected": min(100.0, pct + pace * hours_left) if pace is not None else None,
"needed": free_pct / hours_left if hours_left > 0 else None},
"families": fams,
}