Strict plugin-only: no model / account / harness table left in core.
- plugins/providers: an unbound or never-seeded store reads the seed dir's
provider-*/harness-* manifests (PLUGINS_SEED_DIR, else the plugins
checkout, else backend/fixtures/typed_plugins) — once seeded, only what is
installed. Harness↔vendor helpers (vendors_of_harness, login_harness,
hosted_harnesses, accounts_for_harness, provider_config/secret).
- models/catalog + presets: list_models / is_local / context_window /
opencode_model / agy_model / pi_provider / key_of / vendor_of / guest pool
delegate to the registry; DEFAULT_MODEL, FAMILIES… computed (PEP 562).
openrouter.py reads the provider-openrouter plugin's catalogueUrl and its
api_key hub secret (OPENROUTER_API_KEY fallback).
- accounts: provider-owned; vendor-native helpers (accounts_for_vendor,
vendor_of_account, resolve_alias, wire_id) + compat for_harness /
valid_for / harness_of joined through harness.supports[]. Clean provider
accounts: keyless evox2 (alias opencode-lab, still sent to the sidecar as
opencode-lab), openrouter's own account — pi no longer bills `personal`.
- profiles: profile-level ★ per vendor (profile.accounts), per-machine
overrides on workers[i].accounts; idempotent migration of the harness-keyed
runner ★ on load (file version 3); default_login takes a vendor or a
harness; PUT|PATCH /api/profiles/{id} edits accounts. The API keeps
harness keys beside vendor keys in each runner's accounts/logins.
- runs/cron/scheduled: harness tuples → the registry (caps lean/fork,
runsOn lab, hosted harnesses); a new run routes model → vendor → the
profile's ★ for it.
- cli: --harness accepts any active harness (checked against
/api/providers); MCP drops its static enum.
- tests: golden-tables.json pins the old tables' answers; new
test_provider_accounts.py (migration, clean accounts, routing by vendor).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
154 lines
7.1 KiB
Python
154 lines
7.1 KiB
Python
"""Firing a cron job: prompt file → spawn → history + conversation tag."""
|
|
|
|
import pathlib
|
|
import threading
|
|
|
|
from fastapi import HTTPException
|
|
|
|
import cron as cron_mod
|
|
from cron import guests
|
|
from conversations.catalog import _session_conv_map
|
|
from core.config import WORKSPACE
|
|
from core.state import AppState
|
|
from runs.service import LOCAL_RUNNER, _send_message
|
|
from runs.sidecar_client import _detail_text, _sidecar_call
|
|
|
|
|
|
def job_run_config(job: dict) -> dict:
|
|
"""How a job's firings run: a guest job's from its ``model`` word
|
|
(cron/guests.py), an owner job's from its prompt file's frontmatter."""
|
|
if guests.is_guest_job(job):
|
|
return guests.run_config(job)
|
|
return cron_mod.run_config(_cron_prompt_text(job))
|
|
|
|
|
|
def _cron_job_out(deps: AppState, job: dict,
|
|
sid2conv: dict[str, str] | None = None) -> dict:
|
|
"""A stored job + the computed fields the UI shows: the next fire time, the
|
|
run config read out of its prompt file's frontmatter, and the run history
|
|
enriched with conversation ids (newest first). A guest's job also carries
|
|
its guest's name (``ownerName``)."""
|
|
out = dict(job)
|
|
out["nextRun"] = (cron_mod.next_run(job.get("schedule") or "")
|
|
if job.get("enabled") else None)
|
|
out["runConfig"] = job_run_config(job)
|
|
if guests.is_guest_job(job):
|
|
out["promptFile"] = None
|
|
u = deps.users.get(job["owner"]) or {}
|
|
out["ownerName"] = u.get("name") or job["owner"]
|
|
# Unset = on: a successful run folds into the archive by default.
|
|
out["archiveOnSuccess"] = job.get("archiveOnSuccess") is not False
|
|
if sid2conv is None:
|
|
sid2conv = _session_conv_map(deps)
|
|
out["runs"] = [{"at": at, "sessionId": sid,
|
|
"conversationId": sid2conv.get(sid)}
|
|
for at, sid in sorted((job.get("history") or {}).items(),
|
|
reverse=True)]
|
|
return out
|
|
|
|
|
|
def _cron_prompt_path(job: dict) -> tuple[pathlib.Path, str]:
|
|
rel = cron_mod.valid_prompt_file(job.get("promptFile") or "")
|
|
return (WORKSPACE / rel), rel
|
|
|
|
|
|
def _cron_prompt_text(job: dict) -> str:
|
|
"""The job's prompt file verbatim (frontmatter included), or ``""`` if it
|
|
isn't readable — a missing file is reported when the job fires, not here."""
|
|
try:
|
|
ap, _ = _cron_prompt_path(job)
|
|
return ap.read_text(encoding="utf-8")
|
|
except (OSError, ValueError):
|
|
return ""
|
|
|
|
|
|
def _fire_cron_job(deps: AppState, job: dict, *, fallback: str | None = None) -> dict:
|
|
"""Run a cron job once: read its prompt file, spawn a session on the
|
|
harness/model/parameters its frontmatter declares — on the job's
|
|
``worker`` (unset ⇒ the lab's own sidecar, never auto-routed) — record the
|
|
run in the job's history and tag the conversation with the job.
|
|
|
|
``fallback`` (why the local model couldn't take it — :func:`_fire_local`)
|
|
runs it on the frontmatter's ``fallback`` harness/model instead; the lean
|
|
spec stays. Stamped ``meta.cron.fallback``. A guest's job runs as that
|
|
guest (cron/guests.py)."""
|
|
if guests.is_guest_job(job):
|
|
return guests.fire(deps, job, fallback=fallback)
|
|
_, rel = _cron_prompt_path(job)
|
|
raw = _cron_prompt_text(job)
|
|
cfg = cron_mod.run_config(raw)
|
|
if fallback and cfg.get("fallback"):
|
|
fb = cfg["fallback"]
|
|
cfg = {**cfg, "harness": fb["harness"], "model": fb["model"],
|
|
"effort": fb["effort"], "thinking": None}
|
|
prompt = cron_mod.strip_frontmatter(raw).strip()
|
|
if not prompt:
|
|
deps.cron_store.record_run(job["id"], "",
|
|
status=f"error: prompt file {rel} missing/empty")
|
|
deps.hub.publish({"type": "cron"})
|
|
raise HTTPException(409, f"prompt file {rel} is missing or empty")
|
|
# Frontmatter wins; the store's `model` is the pre-frontmatter fallback.
|
|
out = _send_message(deps, prompt, model=cfg["model"] or job.get("model"),
|
|
harness=cfg["harness"], thinking=cfg["thinking"],
|
|
effort=cfg["effort"], account=cfg.get("account"),
|
|
lean=cfg.get("lean"),
|
|
worker=job.get("worker") or LOCAL_RUNNER)
|
|
sid = out["sessionId"]
|
|
deps.meta_store.update(sid, {"cron": {"id": job["id"], "name": job.get("name"),
|
|
**({"fallback": fallback} if fallback else {})}})
|
|
deps.cron_store.record_run(job["id"], sid,
|
|
status=f"ok (fallback: {fallback})" if fallback else "ok")
|
|
deps.hub.publish({"type": "cron"})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
return out
|
|
|
|
|
|
def _fire_local(deps: AppState, job: dict, cfg: dict) -> None:
|
|
"""A job on a local model with a ``fallback``: ask the lab sidecar to wake
|
|
the EVOX2 and load the model (``/local-ready``, up to the fallback's
|
|
``wait``), then fire on it — or, when it never came up (asleep and not
|
|
waking, down, its GPU held by another job), on the fallback."""
|
|
fb = cfg["fallback"]
|
|
try:
|
|
r = _sidecar_call(deps, "/local-ready", {"harness": cfg["harness"],
|
|
"model": cfg["model"],
|
|
"waitS": fb["waitS"]},
|
|
timeout=fb["waitS"] + 300)
|
|
except HTTPException as e:
|
|
r = {"ready": False, "reason": _detail_text(e)}
|
|
reason = None if r.get("ready") else (r.get("reason") or "not ready")[:160]
|
|
try:
|
|
_scheduler_fire(deps, job, fallback=reason, probed=True)
|
|
except Exception as e: # a thread's exception would vanish: record it
|
|
deps.cron_store.record_run(job["id"], "", status=f"error: {e}")
|
|
deps.hub.publish({"type": "cron"})
|
|
|
|
|
|
def _runs_local(harness: str | None) -> bool:
|
|
"""Whether a harness runs a local provider's models (pi, opencode on the
|
|
EVOX2) — a job on one may need the box woken first."""
|
|
from plugins import providers
|
|
reg = providers.current()
|
|
return any((reg.providers[v].spec.get("local")) for v in reg.vendors_of_harness(harness or ""))
|
|
|
|
|
|
def _scheduler_fire(deps: AppState, job: dict, *, fallback: str | None = None,
|
|
probed: bool = False) -> None:
|
|
"""The scheduler-thread wrapper: outcomes land in the store (surfaced as
|
|
the job's lastStatus), never raise into the loop. A lab job on a local
|
|
model with a ``fallback`` is probed first, on its own thread — the wait
|
|
for the EVOX2 must not hold up the other jobs' firings."""
|
|
if guests.is_guest_job(job):
|
|
return guests.scheduler_fire(deps, job, probed=probed, fallback=fallback)
|
|
if not probed and not job.get("worker"):
|
|
cfg = cron_mod.run_config(_cron_prompt_text(job))
|
|
if cfg.get("fallback") and _runs_local(cfg.get("harness")):
|
|
threading.Thread(target=_fire_local, args=(deps, job, cfg), daemon=True,
|
|
name=f"cron-local-{job['id']}").start()
|
|
return
|
|
try:
|
|
_fire_cron_job(deps, job, fallback=fallback)
|
|
except HTTPException as e:
|
|
deps.cron_store.record_run(job["id"], "", status=f"error: {_detail_text(e)}")
|
|
deps.hub.publish({"type": "cron"})
|