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>
280 lines
11 KiB
Python
280 lines
11 KiB
Python
"""The skills and agents catalogs for a plugin (since 2026-11-26, the
|
|
``skills-agents`` plugin — Files → Skills and Files → Agents left the core).
|
|
|
|
The data stays core: ``/api/skills`` and ``/api/agents`` (``dashboards/``,
|
|
``agents/``) feed the composer's mentions, the tag pills, ``ai-agent
|
|
skills`` / ``agents``, the MCP tools and ``cli/tag_looks.py``. These bridges
|
|
hand the same answers to a plugin's handlers, plus the profile scope switch's
|
|
``profiles``. All owner only, operator approval:
|
|
|
|
* ``catalog.read`` (read-only):
|
|
|
|
- ``GET …/plugins/{pid}/hub/skills?account=<scope>`` → ``/api/skills``'
|
|
answer + ``{scope, profiles}``;
|
|
- ``GET …/hub/skills/{name}/prompt`` → ``/api/skills/{name}/prompt`` (a
|
|
built-in skill's newest injected prompt; 404 ``not_found`` when none);
|
|
- ``GET …/hub/agents?account=<scope>`` → ``/api/agents`` + ``{scope,
|
|
profiles}``;
|
|
- ``GET …/hub/agents/{name}?account=<scope>`` → ``/api/agents/{name}``
|
|
(definition, stats, recent runs, runs per day, its cron job,
|
|
``canSchedule``) + ``{scope, profiles}``.
|
|
|
|
* ``skills.share`` — ``POST …/hub/skills/share {"ref", "on"}``: hand a
|
|
catalog skill to every guest run (``sharedSkills``, Settings → Users) or
|
|
stop; ``ref`` must be a share ref the catalog lists. Answers
|
|
``{sharedSkills}`` and publishes SSE ``users``.
|
|
|
|
* ``agents.run`` (the plugin's own handlers only):
|
|
|
|
- ``POST …/hub/agents/{name}/run {"prompt"?}`` → ``POST
|
|
/api/agents/{name}/run`` (its definition as its own session, the extra
|
|
task appended): ``{sessionId, …}``;
|
|
- ``POST …/hub/agents/{name}/schedule {"schedule"}`` → a cron job on the
|
|
definition — created in the cron-jobs plugin (the ``runs.cron``
|
|
provider's ``create``, ``plugins/cron_bridge.py``) with its path as the
|
|
prompt file — only when ``/api/agents/{name}`` says ``canSchedule``.
|
|
|
|
Refusals are ``{"error": {message, kind}}``: ``capability`` (a guest, or the
|
|
cap missing), ``handler_only``, ``bad_request``, ``not_found``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
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
|
|
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
BASE = "/proxy/tools/plugins/{pid}/hub"
|
|
READ, SHARE, RUN = "catalog.read", "skills.share", "agents.run"
|
|
# An ``?account=`` scope: ``all``, ``totals``, ``profile:<id>`` (comma-listable),
|
|
# account ids — profiles/store ``selector``'s grammar.
|
|
_SCOPE_RE = re.compile(r"^[a-z0-9:_.,-]{0,160}$")
|
|
_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
|
|
MAX_TASK = 8000
|
|
|
|
|
|
def _gate(request: Request, pid: str, cap: str, *, handler_only: bool = False):
|
|
"""(deps, error): the owner, through the plugin, holding ``cap``."""
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, err
|
|
if handler_only and who.handler != pid:
|
|
return None, _error(403, f"{cap} is only available to the plugin's own handlers",
|
|
"handler_only")
|
|
if not who.is_owner:
|
|
return None, _error(403, f"{cap} is owner-only", "capability")
|
|
deps = request.app.state.ai
|
|
_, rec, _, _, err = _active_plugin(deps, 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 deps, None
|
|
|
|
|
|
def _scope(account: str | None) -> tuple[str | None, Any]:
|
|
a = (account or "").strip().lower()
|
|
if not _SCOPE_RE.fullmatch(a):
|
|
return None, _error(400, "account must be a scope (all, profile:<id>, …)", "bad_request")
|
|
return a or None, None
|
|
|
|
|
|
def _body_of(fn, deps, **kwargs) -> dict:
|
|
"""A route's answer as a dict (its ``@_json_in_worker`` JSONResponse
|
|
decoded), called as the owner."""
|
|
from plugins.graphdata import _call
|
|
return _call(fn, deps, **kwargs)
|
|
|
|
|
|
def _with_scope(deps, out: dict, account: str | None) -> dict:
|
|
from plugins.footprintdata import profiles
|
|
return {**out, "scope": account or "", "profiles": profiles(deps)}
|
|
|
|
|
|
def _http_error(e: HTTPException):
|
|
d = e.detail
|
|
msg = d.get("message") if isinstance(d, dict) else str(d)
|
|
kind = "not_found" if e.status_code == 404 else "bad_request"
|
|
return _error(e.status_code, str(msg), kind)
|
|
|
|
|
|
async def _json(request: Request) -> dict | None:
|
|
try:
|
|
body = await request.json()
|
|
except (ValueError, json.JSONDecodeError):
|
|
return None
|
|
return body if isinstance(body, dict) else None
|
|
|
|
|
|
# ── catalog.read ─────────────────────────────────────────────────────────────
|
|
@router.get(BASE + "/skills")
|
|
async def hub_skills(pid: str, request: Request, account: str = ""):
|
|
deps, err = _gate(request, pid, READ)
|
|
if err:
|
|
return err
|
|
scope, err = _scope(account)
|
|
if err:
|
|
return err
|
|
|
|
def _read():
|
|
from dashboards.routes import skills_list
|
|
return _with_scope(deps, _body_of(skills_list, deps, account=scope), scope)
|
|
|
|
return await run_in_threadpool(_read)
|
|
|
|
|
|
@router.get(BASE + "/skills/{name}/prompt")
|
|
async def hub_skill_prompt(pid: str, name: str, request: Request):
|
|
deps, err = _gate(request, pid, READ)
|
|
if err:
|
|
return err
|
|
if not _NAME_RE.fullmatch(name):
|
|
return _error(400, "not a skill name", "bad_request")
|
|
|
|
def _read():
|
|
from dashboards.routes import skill_prompt
|
|
return _body_of(skill_prompt, deps, name=name)
|
|
|
|
try:
|
|
return await run_in_threadpool(_read)
|
|
except HTTPException as e:
|
|
return _http_error(e)
|
|
|
|
|
|
@router.get(BASE + "/agents")
|
|
async def hub_agents(pid: str, request: Request, account: str = ""):
|
|
deps, err = _gate(request, pid, READ)
|
|
if err:
|
|
return err
|
|
scope, err = _scope(account)
|
|
if err:
|
|
return err
|
|
|
|
def _read():
|
|
from agents.routes import agents_list
|
|
return _with_scope(deps, _body_of(agents_list, deps, account=scope), scope)
|
|
|
|
return await run_in_threadpool(_read)
|
|
|
|
|
|
@router.get(BASE + "/agents/{name}")
|
|
async def hub_agent(pid: str, name: str, request: Request, account: str = ""):
|
|
deps, err = _gate(request, pid, READ)
|
|
if err:
|
|
return err
|
|
if not _NAME_RE.fullmatch(name):
|
|
return _error(400, "not an agent name", "bad_request")
|
|
scope, err = _scope(account)
|
|
if err:
|
|
return err
|
|
|
|
def _read():
|
|
from agents.routes import agent_detail
|
|
return _with_scope(deps, _body_of(agent_detail, deps, name=name, account=scope), scope)
|
|
|
|
try:
|
|
return await run_in_threadpool(_read)
|
|
except HTTPException as e:
|
|
return _http_error(e)
|
|
|
|
|
|
# ── skills.share ─────────────────────────────────────────────────────────────
|
|
def share_skill(deps, ref: str, on: bool) -> dict:
|
|
"""Add ``ref`` to (or drop it from) the guests' shared skills — the
|
|
Skills page's *share* chip. ``ref`` must be one the catalog offers
|
|
(``dashboards/skills.share_ref``) to be added; dropping any is fine."""
|
|
from dashboards import skills as skills_mod
|
|
cur = list(deps.users.defaults()["sharedSkills"])
|
|
if on:
|
|
refs = set()
|
|
for s in skills_mod.catalog():
|
|
r = skills_mod.share_ref(s)
|
|
if r:
|
|
refs.add(r)
|
|
if ref not in refs:
|
|
raise ValueError(f"no skill to share as {ref!r}")
|
|
nxt = [r for r in cur if r != ref] + [ref]
|
|
else:
|
|
nxt = [r for r in cur if r != ref]
|
|
out = deps.users.set_defaults({"sharedSkills": nxt})
|
|
deps.hub.publish({"type": "users"})
|
|
return {"sharedSkills": out["sharedSkills"]}
|
|
|
|
|
|
@router.post(BASE + "/skills/share")
|
|
async def hub_skill_share(pid: str, request: Request):
|
|
deps, err = _gate(request, pid, SHARE)
|
|
if err:
|
|
return err
|
|
body = await _json(request)
|
|
ref = (body or {}).get("ref")
|
|
if not isinstance(ref, str) or not ref.strip() or len(ref) > 200:
|
|
return _error(400, "ref must be a skill's share ref", "bad_request")
|
|
try:
|
|
return await run_in_threadpool(share_skill, deps, ref.strip(), bool(body.get("on")))
|
|
except ValueError as e:
|
|
return _error(400, str(e), "bad_request")
|
|
|
|
|
|
# ── agents.run ───────────────────────────────────────────────────────────────
|
|
@router.post(BASE + "/agents/{name}/run")
|
|
async def hub_agent_run(pid: str, name: str, request: Request):
|
|
deps, err = _gate(request, pid, RUN, handler_only=True)
|
|
if err:
|
|
return err
|
|
if not _NAME_RE.fullmatch(name):
|
|
return _error(400, "not an agent name", "bad_request")
|
|
body = await _json(request) or {}
|
|
task = body.get("prompt")
|
|
if task is not None and (not isinstance(task, str) or len(task) > MAX_TASK):
|
|
return _error(400, f"prompt must be text of at most {MAX_TASK} characters", "bad_request")
|
|
|
|
def _run():
|
|
from agents.routes import AgentRunBody, agent_run
|
|
return agent_run(deps, name, AgentRunBody(prompt=task))
|
|
|
|
try:
|
|
return await run_in_threadpool(_run)
|
|
except HTTPException as e:
|
|
return _http_error(e)
|
|
|
|
|
|
@router.post(BASE + "/agents/{name}/schedule")
|
|
async def hub_agent_schedule(pid: str, name: str, request: Request):
|
|
deps, err = _gate(request, pid, RUN, handler_only=True)
|
|
if err:
|
|
return err
|
|
if not _NAME_RE.fullmatch(name):
|
|
return _error(400, "not an agent name", "bad_request")
|
|
body = await _json(request) or {}
|
|
schedule = body.get("schedule")
|
|
if not isinstance(schedule, str) or not schedule.strip() or len(schedule) > 100:
|
|
return _error(400, "schedule must be a cron expression", "bad_request")
|
|
|
|
def _schedule():
|
|
from agents import runconfig
|
|
from agents.routes import _agent_entry
|
|
from plugins import cron_bridge
|
|
entry = _agent_entry(name)
|
|
if entry is None:
|
|
raise HTTPException(404, "agent not found")
|
|
try:
|
|
runconfig.valid_prompt_file(entry["path"])
|
|
except ValueError:
|
|
raise HTTPException(400, "only a definition directly in .claude/agents/ can be scheduled")
|
|
# the job is the cron-jobs plugin's (404 no_provider without it)
|
|
return cron_bridge.create(deps, name=name, schedule=schedule.strip(),
|
|
prompt_file=entry["path"])
|
|
|
|
try:
|
|
return await run_in_threadpool(_schedule)
|
|
except HTTPException as e:
|
|
return _http_error(e)
|