Files
ai-agent/backend/agents/runconfig.py
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

195 lines
7.4 KiB
Python

"""How an agent file says its runs should be launched: the leading YAML
frontmatter of ``.claude/agents/<name>.md`` — ``harness``, ``model``,
``effort``, ``thinking``, ``account``, ``lean`` and ``fallback`` (see
:func:`run_config`). The agents page's *Run now* reads it, and the
``runs.start`` bridge normalizes a ``lean`` spec with :func:`norm_lean`.
It was ``cron/scheduler.py``'s until the cron jobs became the ``cron-jobs``
live plugin (2026-11-28) — the plugin reads a job's prompt file the same way
(its own copy of this file's rules)."""
import pathlib
import re
import yaml
import accounts as accounts_mod
# Prompt files must live here (relative to the workspace root).
PROMPT_DIR = ".claude/agents"
_FRONTMATTER_RE = re.compile(r"\A---\s*\n(?P<body>.*?)\n---\s*\n", re.DOTALL)
# The run knobs a job's frontmatter can set — the same closed sets the sidecar
# validates (``sidecar.py``: ``_valid_harness`` / ``EFFORT_LEVELS``), checked
# here too so a typo shows up as an unapplied chip in the UI instead of a
# rejected spawn.
def harnesses() -> tuple[str, ...]:
"""The active harness plugins' ids (``plugins/providers.py``)."""
from plugins import providers
return providers.current().harness_ids()
def __getattr__(name: str):
if name == "HARNESSES": # the old constant (PEP 562)
return harnesses()
raise AttributeError(name)
EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max")
# Spellings of "run with no --effort flag at all", distinct from an absent key
# only in that the UI can show it was a deliberate choice.
_EFFORT_NONE = ("none", "off", "default", "")
_MODEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/:-]{0,127}$")
# A lean run (`lean:` — the sidecar's launch.py "lean runs"): the tools it may
# have and the programs it may call. `lean: true` = the defaults, no allowlist.
LEAN_TOOLS = ("Bash", "Read", "Write", "Edit", "Grep", "Glob", "WebSearch", "WebFetch")
# A program name, or a path to one (`hosts/raspy2/kernel/kernel-try.sh`) —
# nothing that could bend a `Bash(<program>:*)` rule.
_PROGRAM_RE = re.compile(r"^[A-Za-z0-9._~+-][A-Za-z0-9._~/+-]{0,127}$")
def valid_prompt_file(rel: str) -> str:
"""Normalize + validate a prompt-file path: a ``.md`` directly under
``.claude/agents/``. Raises ValueError otherwise."""
rel = (rel or "").strip().lstrip("/")
p = pathlib.PurePosixPath(rel)
if ".." in p.parts:
raise ValueError("promptFile must not contain '..'")
if p.suffix.lower() != ".md":
raise ValueError("promptFile must be a .md file")
if str(p.parent) != PROMPT_DIR:
raise ValueError(f"promptFile must live in {PROMPT_DIR}/")
return str(p)
def strip_frontmatter(text: str) -> str:
"""Drop a leading YAML frontmatter block (``.claude/agents`` files double
as Claude Code agent definitions; the frontmatter isn't prompt text)."""
return _FRONTMATTER_RE.sub("", text, count=1)
def parse_frontmatter(text: str) -> dict:
"""The leading YAML frontmatter block as a mapping — ``{}`` when there is
none, or when it isn't parseable/isn't a mapping. Never raises: a prompt
file with a broken header still runs, just on the defaults."""
m = _FRONTMATTER_RE.match(text or "")
if not m:
return {}
try:
data = yaml.safe_load(m.group("body"))
except yaml.YAMLError:
return {}
return data if isinstance(data, dict) else {}
def _norm_thinking(v) -> bool | None:
if isinstance(v, bool):
return v
if isinstance(v, str):
s = v.strip().lower()
if s in ("true", "on", "yes", "enabled"):
return True
if s in ("false", "off", "no", "disabled"):
return False
return None
def run_config(text: str) -> dict:
"""How a job's prompt file says its runs should be launched.
Reads ``harness`` / ``model`` / ``effort`` / ``thinking`` / ``account`` /
``lean`` / ``fallback`` out of the frontmatter and normalizes them to the shape
``_send_message`` takes.
``None`` means "not set" (the spawn path's own default applies); an
``effort`` of ``""`` means the file explicitly asked for *no* ``--effort``
flag. Invalid values are dropped rather than raised — a firing on the
defaults beats a job that never fires, and the resolved config is echoed
back to the UI so an unapplied key is visible.
``model`` and ``effort`` are also valid Claude Code agent-definition keys,
so a job's prompt file stays a working ``.claude/agents`` subagent."""
fm = parse_frontmatter(text)
out: dict = {"harness": None, "model": None, "effort": None,
"thinking": None, "account": None, "lean": None, "fallback": None}
h = fm.get("harness")
if isinstance(h, str) and h.strip().lower() in harnesses():
out["harness"] = h.strip().lower()
m = fm.get("model")
if isinstance(m, str) and _MODEL_RE.match(m.strip()):
out["model"] = m.strip()
if "effort" in fm:
e = fm["effort"]
e = "" if e is None else str(e).strip().lower()
if e in EFFORT_LEVELS:
out["effort"] = e
elif e in _EFFORT_NONE:
out["effort"] = ""
out["thinking"] = _norm_thinking(fm.get("thinking"))
# Which Claude account the run bills (see accounts.py). Unknown ids drop
# like every other bad key; unset ⇒ the spawn path routes by cwd/default.
a = fm.get("account")
if isinstance(a, str) and accounts_mod.valid(a):
out["account"] = accounts_mod.valid(a)
out["lean"] = _norm_lean(fm.get("lean"))
out["fallback"] = _norm_fallback(fm.get("fallback"))
return out
# How long a local-model job may wait for the EVOX2 (asleep, or its GPU taken
# by another job) before it runs on its fallback instead — minutes.
FALLBACK_WAIT_MIN = 10
FALLBACK_WAIT_MAX_MIN = 30
def _norm_fallback(v) -> dict | None:
"""``fallback: {harness, model, effort?, wait?}`` — what a job on a local
model runs on when the EVOX2 can't take it within ``wait`` minutes
(the cron-jobs plugin). Anything unusable → None (no fallback)."""
if not isinstance(v, dict):
return None
h = str(v.get("harness") or "claude").strip().lower()
m = v.get("model")
if h not in harnesses() or not isinstance(m, str) or not _MODEL_RE.match(m.strip()):
return None
e = str(v.get("effort") or "").strip().lower()
try:
wait = float(v.get("wait", FALLBACK_WAIT_MIN))
except (TypeError, ValueError):
wait = FALLBACK_WAIT_MIN
return {"harness": h, "model": m.strip(), "effort": e if e in EFFORT_LEVELS else "",
"waitS": int(max(0.0, min(wait, FALLBACK_WAIT_MAX_MIN)) * 60)}
def _norm_lean(v) -> dict | None:
"""``lean: true`` → ``{}``; ``lean: {allow: [...], tools: [...]}`` → the
valid entries of each (a bad program name or tool is dropped, like any
other bad key); anything else → None (a normal run)."""
if v is True or (isinstance(v, str) and v.strip().lower() in ("true", "on", "yes")):
return {}
if not isinstance(v, dict):
return None
out: dict = {}
allow = [p for p in (v.get("allow") or []) if isinstance(p, str) and _PROGRAM_RE.match(p)]
if allow:
out["allow"] = allow
tools = [t for t in (v.get("tools") or []) if t in LEAN_TOOLS]
if tools:
out["tools"] = tools
return out
def norm_lean(v) -> dict | None:
"""The public spelling of :func:`_norm_lean` (the ``runs.start`` bridge)."""
return _norm_lean(v)
PROGRAM_RE = _PROGRAM_RE