Files
ai-agent/backend/plugins/hubruns.py
gabrielvidal a4be4da003 Merge branch 'plugin-scheduled-conversations': Send later leaves the core for the scheduled-conversations plugin
# Conflicts:
#	backend/plugins/carryover.py
#	backend/plugins/hubruns.py
#	backend/plugins/manifest.py
#	backend/plugins/routes.py
2026-11-26 23:28:45 +01:00

528 lines
22 KiB
Python

"""Hub bridges that let a plugin start and drive conversations (owner only).
Four capabilities, each declared in the manifest and approved like any other:
* ``runs.start`` — ``POST /proxy/tools/plugins/{id}/hub/runs``: a new
conversation through the composer's own send path (``_send_message``), with
what only cron could do before: a **lean** run, and a **local-model
fallback** (the EVOX2 is woken and probed through the sidecar's
``/local-ready``, as ``cron/service._fire_local`` does; when it can't take
the run within ``fallback.wait`` minutes the run goes to the fallback model,
and the answer says why). It names the machine (``worker``, ``local`` = the
lab), the title, the ``services`` tags and a ``data`` dict the plugin keeps
on the conversation's meta under its own id (``meta.plugins.<id>``);
``test: true`` makes it a throwaway run, archived once its turn ends.
The composer's whole payload reaches it too — ``account``, ``projects``,
``cwd``, ``newProject``, ``worker: "auto"`` (+ ``profile``: routed when it
starts, as an unpinned composer prompt) — and ``scheduled`` stamps
``meta.scheduled`` (the card's *scheduled* pill): the scheduled-conversations
plugin's start. ``POST …/hub/runs/resolve`` answers what such a run would
do without starting it: the runner and account routing picks, a session's
conversation, title, runner and harness, the owner's machines.
* ``conversations.send`` — ``POST …/hub/conversations/{sid}/send``: one more
turn into a conversation — its live run's inbox when it is running, a
resume otherwise (``inboxOnly`` never resumes); ``model``, ``harness``,
``thinking``, ``effort`` and ``cwd`` as the reply box sends them.
* ``models.read`` — ``GET …/hub/models``: the model catalogue and the
Settings → Models presets (``/api/models``'s owner shape).
* ``workers.read`` — ``GET …/hub/workers``: the owner's machines (``local``
first), their status and the harnesses each can run.
All four are owner-only: a run started here has the owner's permissions,
exactly like ``/api/spawn``. Only the plugin's own handlers (or the owner's
run token) reach them — the caller check is :func:`proxyroutes._who`.
"""
from __future__ import annotations
import logging
import re
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from plugins.proxyroutes import _active_plugin, _error, _who
log = logging.getLogger(__name__)
router = APIRouter(include_in_schema=False)
HARNESSES = ("claude", "pi", "opencode", "agy")
EFFORTS = ("", "none", "minimal", "low", "medium", "high", "xhigh", "max", "think")
LOCAL_HARNESSES = ("pi", "opencode")
_MODEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$")
_WORKER_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
_SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,40}$")
_PROFILE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@-]{0,63}$")
_PROJECT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_STAMP_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
_ISO_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T[0-9:.+Z-]{5,30}$")
_SID_RE = re.compile(r"^[A-Za-z0-9-]{8,64}$")
MAX_PROMPT = 200_000
MAX_DATA = 16_000
FALLBACK_WAIT_MAX_S = 30 * 60
def _bridge(request: Request, pid: str, cap: str):
"""(rec, error) for an owner caller of an active plugin holding ``cap``."""
who, err = _who(request, pid)
if err:
return None, err
if not who.is_owner:
return None, _error(403, f"{cap} is owner-only", "capability")
_, rec, _, _, err = _active_plugin(request.app.state.ai, who, pid)
if err:
return None, err
if cap not in (rec["manifest"].get("capabilities") or []):
return None, _error(403, f"plugin lacks {cap} capability", "capability")
return rec, None
def _detail(e: HTTPException) -> tuple[str, str]:
d = e.detail
if isinstance(d, dict):
return str(d.get("message") or d), str(d.get("kind") or "run")
return str(d), "run"
async def _body(request: Request) -> dict:
try:
body = await request.json()
except Exception:
return {}
return body if isinstance(body, dict) else {}
def _norm_effort(v: Any) -> str | None:
if v is None:
return None
e = str(v).strip().lower()
return e if e in EFFORTS else None
def norm_run(body: dict) -> tuple[dict | None, str | None]:
"""The run a ``runs.start`` body asks for, or (None, why not)."""
prompt = str(body.get("prompt") or "").strip()
if not prompt:
return None, "prompt is required"
if len(prompt) > MAX_PROMPT:
return None, f"prompt over {MAX_PROMPT} characters"
out: dict[str, Any] = {"prompt": prompt}
model = body.get("model")
if model is not None:
if not isinstance(model, str) or not _MODEL_RE.match(model.strip()):
return None, "bad model"
out["model"] = model.strip()
h = body.get("harness")
if h is not None:
if str(h) not in HARNESSES:
return None, "bad harness"
out["harness"] = str(h)
out["effort"] = _norm_effort(body.get("effort"))
th = body.get("thinking")
out["thinking"] = th if isinstance(th, bool) else None
worker = str(body.get("worker") or "local")
if not _WORKER_RE.match(worker):
return None, "bad worker"
out["worker"] = worker
# The composer's payload: who bills it, its tags, where it starts.
prof = body.get("profile")
if prof is not None and prof != "":
if not isinstance(prof, str) or not _PROFILE_RE.match(prof):
return None, "bad profile"
out["profile"] = prof
acct = body.get("account")
if acct is not None and acct != "":
if not isinstance(acct, str) or not _ACCOUNT_RE.match(acct):
return None, "bad account"
out["account"] = acct
projs = body.get("projects")
if projs is not None:
if not isinstance(projs, list) or len(projs) > 16 \
or not all(isinstance(x, str) and _PROJECT_RE.match(x) for x in projs):
return None, "bad projects"
if projs:
out["projects"] = list(dict.fromkeys(projs))
cwd, why = _norm_cwd(body.get("cwd"))
if why:
return None, why
if cwd:
out["cwd"] = cwd
if body.get("newProject") is True:
out["newProject"] = True
sch = body.get("scheduled")
if sch is not None:
if not isinstance(sch, dict) or not _STAMP_ID_RE.match(str(sch.get("id") or "")):
return None, "bad scheduled"
st: dict[str, Any] = {"id": str(sch["id"])}
for k in ("scheduledAt", "shouldStartAt"):
v = sch.get(k)
if v is not None:
if not isinstance(v, str) or not _ISO_RE.match(v):
return None, f"bad scheduled.{k}"
st[k] = v
if sch.get("manual") is True:
st["manual"] = True
out["scheduled"] = st
lean = body.get("lean")
if lean is not None and lean is not False:
from cron import scheduler as cron_mod
nl = cron_mod._norm_lean(lean)
if nl is None:
return None, "bad lean"
out["lean"] = nl
fb = body.get("fallback")
if fb:
if not isinstance(fb, dict):
return None, "bad fallback"
fm, fh = fb.get("model"), str(fb.get("harness") or "claude")
if not isinstance(fm, str) or not _MODEL_RE.match(fm.strip()) or fh not in HARNESSES:
return None, "bad fallback"
try:
wait = float(fb.get("wait", 10))
except (TypeError, ValueError):
wait = 10.0
out["fallback"] = {"model": fm.strip(), "harness": fh,
"effort": _norm_effort(fb.get("effort")),
"waitS": int(max(0.0, min(wait * 60, FALLBACK_WAIT_MAX_S)))}
title = str(body.get("title") or "").strip()
if title:
out["title"] = title[:120]
services = [s for s in (body.get("services") or []) if isinstance(s, str) and _SERVICE_RE.match(s)]
if services:
out["services"] = services[:8]
proj = body.get("project")
if proj is not None and str(proj).strip():
p = str(proj).strip()
if not re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", p):
return None, "bad project"
out["project"] = p
# A throwaway run (``ai-agent new --test``): archived once its turn ends.
if body.get("test") is True:
out["test"] = True
data = body.get("data")
if data is not None:
import json
if not isinstance(data, dict) or len(json.dumps(data)) > MAX_DATA:
return None, f"data must be a JSON object under {MAX_DATA} bytes"
out["data"] = data
return out, None
def _norm_cwd(v: Any) -> tuple[str | None, str | None]:
"""An absolute start directory (the runner checks it exists)."""
if v is None or v == "":
return None, None
if not isinstance(v, str) or not v.startswith(("/", "~")) or len(v) > 500 \
or any(c in v for c in "\x00\n\r"):
return None, "bad cwd"
return v, None
def local_ready(deps, run: dict) -> str | None:
"""None when the run's local model can take it (or it isn't local / has
no fallback); else why not — the run then goes to the fallback."""
fb = run.get("fallback")
if not fb or run.get("harness") not in LOCAL_HARNESSES or run.get("worker") != "local":
return None
from runs.sidecar_client import _sidecar_call
try:
r = _sidecar_call(deps, "/local-ready", {"harness": run["harness"], "model": run.get("model"),
"waitS": fb["waitS"]},
timeout=fb["waitS"] + 300)
except HTTPException as e:
return _detail(e)[0][:160] or "not ready"
return None if r.get("ready") else (r.get("reason") or "not ready")[:160]
def start_run(deps, pid: str, run: dict) -> dict:
"""Probe, then send; stamp the meta. Raises HTTPException from the send."""
from runs.service import _send_message
cwd = run.get("cwd")
proj = run.get("project")
acct = run.get("account")
if acct:
import accounts as accounts_mod
if not accounts_mod.valid(acct):
raise HTTPException(400, {"message": f"unknown account: {acct!r}", "kind": "account"})
if proj:
from projects.catalog import PROJECTS_DIR
from users.runs import project_cwd
if not (PROJECTS_DIR / proj).is_dir():
raise HTTPException(404, {"message": f"unknown project {proj!r}", "kind": "project"})
cwd = project_cwd(proj)
fallback = local_ready(deps, run)
cfg = dict(run)
if fallback:
fb = run["fallback"]
cfg.update(model=fb["model"], harness=fb["harness"], effort=fb["effort"], thinking=None)
# ``auto``: routed now, as the composer routes an unpinned prompt — the
# profile's default runner if it is up, else its next one that is.
auto = cfg["worker"] == "auto"
stamp: dict[str, Any] = {"plugin": pid, "origin": "plugin"}
if run.get("scheduled"):
stamp["scheduled"] = run["scheduled"]
if run.get("title"):
stamp["title"] = run["title"]
if run.get("newProject"):
stamp["newProject"] = True
if run.get("test"):
stamp["test"] = True
out = _send_message(deps, cfg["prompt"], cwd=cwd, model=cfg.get("model"), harness=cfg.get("harness"),
thinking=cfg.get("thinking"), effort=cfg.get("effort"),
account=acct, projects=run.get("projects"),
worker=None if auto else cfg["worker"],
profile=run.get("profile") if auto else None,
lean=cfg.get("lean"), stamp=stamp)
sid = out["sessionId"]
patch: dict[str, Any] = {}
if run.get("title"):
patch["title"] = run["title"]
if proj:
patch["projects"] = [proj]
if run.get("services"):
patch["services"] = run["services"]
if run.get("data") is not None or fallback:
cur = (deps.meta_store.peek(sid) or {}).get("plugins") or {}
data = dict(run.get("data") or {})
if fallback:
data["fallback"] = fallback
patch["plugins"] = {**cur, pid: data}
if patch:
deps.meta_store.update(sid, patch)
deps.hub.publish({"type": "meta", "id": sid})
m = deps.meta_store.peek(sid) or {}
return {"sessionId": sid, "fallback": fallback,
"harness": cfg.get("harness"), "model": cfg.get("model"),
# where it went (``auto``: routing's pick) and who it bills
"worker": m.get("worker") or "local", "account": m.get("account") or acct}
@router.post("/proxy/tools/plugins/{pid}/hub/runs")
async def plugin_hub_runs(pid: str, request: Request):
rec, err = _bridge(request, pid, "runs.start")
if err:
return err
run, why = norm_run(await _body(request))
if not run:
return _error(400, why or "bad run", "bad_request")
deps = request.app.state.ai
try:
return await run_in_threadpool(start_run, deps, pid, run)
except HTTPException as e:
msg, kind = _detail(e)
return _error(e.status_code, msg, kind)
@router.post("/proxy/tools/plugins/{pid}/hub/conversations/{sid}/send")
async def plugin_hub_send(pid: str, sid: str, request: Request):
rec, err = _bridge(request, pid, "conversations.send")
if err:
return err
body = await _body(request)
prompt = str(body.get("prompt") or "").strip()
if not prompt or len(prompt) > MAX_PROMPT:
return _error(400, "prompt is required (and under 200 000 characters)", "bad_request")
if not re.match(r"^[A-Za-z0-9-]{8,64}$", sid):
return _error(400, "bad session id", "bad_request")
opts, why = _turn_opts(body)
if why:
return _error(400, why, "bad_request")
deps = request.app.state.ai
meta = deps.meta_store.peek(sid) or {}
if meta.get("owner"):
return _error(403, "a guest's conversation", "capability")
def _go():
from runs.service import _send_message
return _send_message(deps, prompt, session_id=sid,
inbox_only=bool(body.get("inboxOnly")), **opts)
try:
out = await run_in_threadpool(_go)
except HTTPException as e:
msg, kind = _detail(e)
return _error(e.status_code, msg, kind)
return {"sessionId": out.get("sessionId") or sid, "delivered": out.get("delivered")}
def _turn_opts(body: dict) -> tuple[dict, str | None]:
"""A turn's own knobs, as the reply box sends them."""
out: dict[str, Any] = {}
model = body.get("model")
if model is not None and model != "":
if not isinstance(model, str) or not _MODEL_RE.match(model.strip()):
return {}, "bad model"
out["model"] = model.strip()
h = body.get("harness")
if h is not None and h != "":
if str(h) not in HARNESSES:
return {}, "bad harness"
out["harness"] = str(h)
if body.get("effort") is not None:
e = _norm_effort(body.get("effort"))
if e:
out["effort"] = e
if isinstance(body.get("thinking"), bool):
out["thinking"] = body["thinking"]
cwd, why = _norm_cwd(body.get("cwd"))
if why:
return {}, why
if cwd:
out["cwd"] = cwd
return out, None
# ── what a run would do, without starting it ─────────────────────────────────
def _profile_of(profiles: list[dict], runner: str) -> str | None:
"""The profile holding a runner (a retired one too), as the app's
``profileOfRunner`` reads it; None when no profile holds it."""
for p in profiles:
if any(e.get("id") == runner for e in p.get("workers") or []):
return p.get("id")
for p in profiles:
if runner in (p.get("retired") or []):
return p.get("id")
return None
def resolve_payload(deps, body: dict) -> dict:
"""``runners``: what routing picks for each ``{key, harness, account,
worker, profile, model, mode}`` — ``freeze`` (what to keep when it is
scheduled: an explicit pick as is, an offline one too; a refusal is an
``error``) or ``now`` (where it would start right now: the first runner
up, else the default one — the scheduled-conversations plugin's card).
``sessions``: each session's conversation id, title, runner and harness
(a follow-up runs where its session lives). ``workers``: the owner's
machines, ``local`` first — name, liveness, profile — and ``profiles``,
each profile's label."""
import accounts as accounts_mod
from runs.service import (LOCAL_RUNNER, _lab_only, _session_harness,
_session_worker, route_new_run)
out: dict[str, Any] = {}
runners: dict[str, Any] = {}
for item in (body.get("runners") or [])[:200]:
if not isinstance(item, dict) or not str(item.get("key") or "").strip():
continue
key = str(item["key"])[:64]
harness = str(item.get("harness") or "claude").lower()
account = item.get("account") or None
worker = item.get("worker") or None
if worker == "auto":
worker = None
bad = (None if harness in HARNESSES else "bad harness") \
or (None if account is None or (isinstance(account, str) and accounts_mod.valid(account))
else f"unknown account: {account!r}") \
or (None if worker is None or (isinstance(worker, str) and _WORKER_RE.match(worker))
else "bad worker")
if bad:
runners[key] = {"error": {"status": 400, "kind": "bad_request", "message": bad}}
continue
profile = item.get("profile") if isinstance(item.get("profile"), str) else None
model = item.get("model") if isinstance(item.get("model"), str) else None
checks = (True, False) if item.get("mode") == "now" else (False,)
got, last = None, None
for check in checks:
try:
got = route_new_run(deps, harness, account, worker, profile,
check_online=check, model=model)
break
except HTTPException as e:
last = e
if got is None:
msg, kind = _detail(last) if last else ("no runner", "run")
runners[key] = {"error": {"status": last.status_code if last else 409,
"kind": kind, "message": msg}}
continue
runners[key] = {"worker": got[0] or LOCAL_RUNNER, "account": got[1],
"labOnly": _lab_only(harness)}
if runners or body.get("runners") is not None:
out["runners"] = runners
sids = [s for s in (body.get("sessions") or [])[:500]
if isinstance(s, str) and _SID_RE.match(s)]
if sids or body.get("sessions") is not None:
from conversations import ids
from conversations.catalog import _conv_ids_by_session
by_sid = _conv_ids_by_session(deps)
sessions: dict[str, Any] = {}
for sid in dict.fromkeys(sids):
m = deps.meta_store.peek(sid) or {}
cid = by_sid.get(sid)
summ = deps.store.get_summary(ids.path_of(cid)) if cid else None
h = _session_harness(deps, sid)
lab = _lab_only(h)
sessions[sid] = {"conversationId": cid,
"title": m.get("title") or (summ or {}).get("title"),
"worker": (None if lab else _session_worker(deps, sid)) or LOCAL_RUNNER,
"harness": h, "labOnly": lab, "guest": bool(m.get("owner")),
"known": bool(m or cid)}
out["sessions"] = sessions
if body.get("workers"):
profiles = deps.profile_store.list()
ws: dict[str, Any] = {LOCAL_RUNNER: {"name": "Lab", "online": True,
"profile": _profile_of(profiles, LOCAL_RUNNER)}}
for w in deps.worker_store.list():
if w.get("owner"): # a guest's own computer
continue
ws[w["id"]] = {"name": w.get("name") or w["id"],
"online": deps.worker_store.online(w["id"]),
"profile": _profile_of(profiles, w["id"])}
out["workers"] = ws
# each profile's name (a failure push says "no Work worker was up")
out["profiles"] = {p["id"]: p.get("label") or p["id"] for p in profiles if p.get("id")}
return out
@router.post("/proxy/tools/plugins/{pid}/hub/runs/resolve")
async def plugin_hub_runs_resolve(pid: str, request: Request):
rec, err = _bridge(request, pid, "runs.start")
if err:
return err
return await run_in_threadpool(resolve_payload, request.app.state.ai, await _body(request))
@router.get("/proxy/tools/plugins/{pid}/hub/models")
async def plugin_hub_models(pid: str, request: Request):
rec, err = _bridge(request, pid, "models.read")
if err:
return err
deps = request.app.state.ai
def _go():
import models as models_mod
from models import presets as presets_mod
from models.routes import agy_down, for_caller, openrouter_down, with_availability
models = with_availability(models_mod.list_models(), openrouter_down())
presets = presets_mod.presets(models)
models = presets_mod.annotate(for_caller(models, True, agy_down(deps), presets, []))
keys = {m["key"] for m in models}
return {"models": models, "default": models_mod.DEFAULT_MODEL,
"presets": {k: p for k, p in presets.items() if k in keys}}
return await run_in_threadpool(_go)
def workers_payload(deps) -> dict:
"""``local`` (the lab) first, then each of the owner's machines."""
rows = [{"id": "local", "name": "Homelab", "status": "online",
"harnesses": list(HARNESSES)}]
for w in deps.worker_store.list():
if w.get("owner"): # a guest's own computer
continue
st = deps.worker_store.status(w["id"]) or {}
hs = ["claude"]
if w.get("opencodeAccounts") or st.get("opencodeAccounts"):
hs.append("opencode")
if w.get("agyAccounts") or st.get("agyAccounts") or st.get("agy"):
hs.append("agy")
rows.append({"id": w["id"], "name": w.get("name") or w["id"],
"status": st.get("status", "unknown"), "harnesses": hs})
return {"workers": rows}
@router.get("/proxy/tools/plugins/{pid}/hub/workers")
async def plugin_hub_workers(pid: str, request: Request):
rec, err = _bridge(request, pid, "workers.read")
if err:
return err
return await run_in_threadpool(workers_payload, request.app.state.ai)