- settings.fields[].type model (uses runs|complete, effortKey), worker,
workers; unit on numbers, group headings, placeholder; a save checks the
typed values (manifest.check_config, PUT /api/plugins/{id} → 400)
- runs.start: a model key without harness runs where Settings → Models puts
it (hubruns.with_model_route → models.presets.route_key); complete.run takes
model: "preset:<id>" and a bare key the same way (hubcomplete.model_value)
- run_router.sources(): each plugin's model fields with their value, for
Agent presets' Plugins that use a model
- settings page: PluginModelField (Presets / Models tabs, effort chips),
PluginWorkersField, PluginStatusCard (message + count chips, JSON behind
Details), ui.settingsHtmlFirst
- an app.modal slot with palette: true is listed by the command palette
- docs/plugins.md: Settings fields section; tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
400 lines
17 KiB
Python
400 lines
17 KiB
Python
"""Hub bridges for one-shot completions and conversation labels (owner only).
|
|
|
|
* ``complete.run`` — ``POST /proxy/tools/plugins/{id}/hub/complete``: one
|
|
short answer from any model through the host sidecar's ``POST /complete``
|
|
(``sidecar/complete.py``: a harness driver's ``complete()``, or the EVOX2 /
|
|
OpenRouter over HTTP), with a fallback model. No transcript is left, so the
|
|
spend is booked here, in the side-call ledger (``usage_store.add_side_call``,
|
|
the ``kind`` / ``ref`` the plugin names). ``preset: "default"`` routes the
|
|
call on the agent preset the owner set for source ``plugin:<id>`` (Settings
|
|
→ Agent presets), ``preset: "<id>"`` on that preset — through the
|
|
``runs.route`` provider (``plugins/run_router.py``), on the ``profile``'s
|
|
logins; the plugin's own ``model`` / ``harness`` / ``account`` become the
|
|
fallback, and answer alone when no default is set.
|
|
``GET …/hub/complete/route?preset=&profile=`` — that route, without a call
|
|
(a settings page's "Titles use …").
|
|
* ``conversations.label``:
|
|
- ``GET …/hub/labels/pending?days=&limit=&sid=`` — the conversations still
|
|
without an action badge (``conversations/look_pending.py``);
|
|
- ``POST …/hub/labels/look {sessionId, action, model}`` — ``meta.lookAuto``
|
|
(an action outside ``look.ACTIONS`` is stored as None: never asked again);
|
|
- ``POST …/hub/labels/short-title {id, title, source}`` — the short header
|
|
title cache (``short_titles``) and its ``short-title`` event;
|
|
- ``GET …/hub/labels/untitled?harness=agy,pi&days=&limit=&sid=`` — the
|
|
conversations of those harnesses still without a title
|
|
(``conversations/title_pending.py``);
|
|
- ``POST …/hub/labels/title {sessionId, title, model}`` — ``meta.autoTitle``,
|
|
read like Claude's own ``ai-title`` (an empty one is stored as None: never
|
|
asked again).
|
|
|
|
Users: the ``conversation-labels`` plugin (badges, short titles) and the
|
|
``conversation-titles`` one (agy / pi titles).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import logging
|
|
import re
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from plugins.hubruns import _body, _bridge, _detail
|
|
from plugins.proxyroutes import _error
|
|
|
|
log = logging.getLogger(__name__)
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
_SPEC_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$")
|
|
_HARNESS_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
|
|
_ACCOUNT_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
|
|
_KIND_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
|
|
_SID_RE = re.compile(r"^[A-Za-z0-9-]{8,64}$")
|
|
# ``default`` (the source's preset) or a preset id (agent-presets' ``_ID_RE``)
|
|
_PRESET_RE = re.compile(r"^(default|[a-z0-9][a-z0-9-]{0,39})$")
|
|
_PROFILE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
|
_HARNESSES_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}(,[a-z][a-z0-9-]{0,31}){0,15}$")
|
|
MAX_TITLE = 120
|
|
MAX_SYSTEM = 12_000
|
|
MAX_PROMPT = 30_000
|
|
# Engines priced from the CLI's tokens with the provider book (as transcripts
|
|
# are); the direct-HTTP ones carry their own figure (OpenRouter's, the EVOX2's 0).
|
|
_PRICED_BY_USAGE = ("claude", "agy", "opencode")
|
|
|
|
|
|
def _now() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def _opt(body: dict, key: str, rx: re.Pattern) -> str | None:
|
|
v = body.get(key)
|
|
if v in (None, ""):
|
|
return None
|
|
v = str(v).strip()
|
|
if not rx.match(v):
|
|
raise ValueError(f"bad {key}")
|
|
return v
|
|
|
|
|
|
def norm_complete(body: dict) -> dict:
|
|
"""A ``complete.run`` body → the sidecar's ``/complete`` body (ValueError
|
|
on anything off)."""
|
|
prompt = str(body.get("prompt") or "").strip()
|
|
if not prompt:
|
|
raise ValueError("prompt is required")
|
|
out = {"system": str(body.get("system") or "")[:MAX_SYSTEM], "prompt": prompt[:MAX_PROMPT],
|
|
"wakeLocal": bool(body.get("wakeLocal")),
|
|
"timeout": max(5, min(int(body.get("timeout") or 30), 120))}
|
|
for k, rx in (("model", _SPEC_RE), ("harness", _HARNESS_RE), ("account", _ACCOUNT_RE),
|
|
("fallbackModel", _SPEC_RE), ("fallbackHarness", _HARNESS_RE),
|
|
("fallbackAccount", _ACCOUNT_RE)):
|
|
v = _opt(body, k, rx)
|
|
if v:
|
|
out[k] = v
|
|
return out
|
|
|
|
|
|
def book(deps, out: dict, kind: str, ref: str | None) -> dict:
|
|
"""Record one ``/complete`` answer's spend; returns ``{costUsd, units}``."""
|
|
from conversations import pricing
|
|
import accounts as accounts_mod
|
|
model = out.get("model") or ""
|
|
raw = out.get("usage") if isinstance(out.get("usage"), dict) else None
|
|
cost, units = float(out.get("costUsd") or 0.0), 0.0
|
|
if raw and out.get("harness") in _PRICED_BY_USAGE:
|
|
try:
|
|
u = pricing.norm_usage(raw)
|
|
cost, units = pricing.usage_cost(u, model), pricing.plan_units(u, model)
|
|
except Exception: # noqa: BLE001 — a model the book doesn't know: its own figure
|
|
pass
|
|
try:
|
|
deps.usage_store.add_side_call(kind, ref, out.get("account") or accounts_mod.DEFAULT,
|
|
model or None, cost, units, raw)
|
|
except Exception: # noqa: BLE001
|
|
log.exception("booking a %s side call", kind)
|
|
return {"costUsd": round(cost, 6), "units": round(units, 4)}
|
|
|
|
|
|
def run_complete(deps, body: dict, kind: str, ref: str | None) -> dict:
|
|
from runs.sidecar_client import _sidecar_call
|
|
out = _sidecar_call(deps, "/complete", body, timeout=float(body["timeout"]) * 2 + 15)
|
|
spent = book(deps, out, kind, ref)
|
|
return {"text": out.get("text") or "", "model": out.get("model"),
|
|
"harness": out.get("harness"), "account": out.get("account"),
|
|
"usage": out.get("usage"), "fallbackUsed": bool(out.get("fallbackUsed")),
|
|
"primaryError": out.get("primaryError"), "seconds": out.get("seconds"), **spent}
|
|
|
|
|
|
def model_value(raw: dict) -> dict:
|
|
"""A plugin's ``model`` settings field handed as is: ``model:
|
|
"preset:<id>"`` is that preset (``preset: "<id>"``, the plugin's model
|
|
then no fallback); a model key without a ``harness`` runs where Settings
|
|
→ Models puts it (``gpt-6-sol`` → opencode). Anything else unchanged."""
|
|
m = raw.get("model")
|
|
if not isinstance(m, str) or not m.strip():
|
|
return raw
|
|
if m.strip().lower().startswith("preset:"):
|
|
out = {k: v for k, v in raw.items() if k not in ("model", "harness", "account")}
|
|
if out.get("preset") in (None, "", False):
|
|
out["preset"] = m.strip()
|
|
return out
|
|
if raw.get("harness"):
|
|
return raw
|
|
from models import presets as presets_mod
|
|
try:
|
|
r = presets_mod.route_key(m)
|
|
except Exception: # noqa: BLE001
|
|
return raw
|
|
return {**raw, "model": r["model"], "harness": r["harness"]} if r else raw
|
|
|
|
|
|
def preset_arg(raw: dict) -> tuple[str | None, str | None]:
|
|
"""A body's ``(preset, profile)``: ``preset: true`` is ``"default"``;
|
|
``(None, None)`` when it names none (ValueError on anything off)."""
|
|
p = raw.get("preset")
|
|
if p in (None, "", False):
|
|
return None, None
|
|
p = "default" if p is True else str(p).strip().lower()
|
|
if p.startswith("preset:"):
|
|
p = p[len("preset:"):].strip()
|
|
if not _PRESET_RE.match(p):
|
|
raise ValueError("bad preset")
|
|
return p, _opt(raw, "profile", _PROFILE_RE)
|
|
|
|
|
|
def route_preset(deps, pid: str, preset: str, profile: str | None) -> dict | None:
|
|
"""The route a ``complete.run`` call's ``preset`` takes now, from the
|
|
``runs.route`` provider: ``default`` is the preset the owner set for
|
|
source ``plugin:<pid>`` — None when there is none (or no provider, or it
|
|
failed); a named preset raises HTTPException when unknown or unroutable."""
|
|
from plugins import run_router
|
|
explicit = preset != "default"
|
|
res = run_router.resolve_new_run(
|
|
deps, model=f"{run_router.PREFIX}{preset}" if explicit else None, harness=None,
|
|
account=None, worker=None, profile=profile, stamp={"plugin": pid},
|
|
run_as=None, scope=None)
|
|
if not res or not res.get("model"):
|
|
return None
|
|
return {"preset": res["preset"], "name": res["name"], "i": res["i"], "n": res["n"],
|
|
"harness": res["harness"], "model": res["model"],
|
|
"modelId": res.get("modelId") or res["model"], "account": res.get("account"),
|
|
"full": bool(res.get("full"))}
|
|
|
|
|
|
def apply_route(raw: dict, route: dict) -> dict:
|
|
"""``raw`` with the preset's route as the model; the plugin's own model
|
|
(with its harness and account) becomes the fallback when it names one and
|
|
no fallback of its own."""
|
|
out = {k: v for k, v in raw.items() if k not in ("model", "harness", "account")}
|
|
out.update(model=route["model"], harness=route["harness"])
|
|
if route.get("account"):
|
|
out["account"] = route["account"]
|
|
own_m, own_h = raw.get("model"), raw.get("harness")
|
|
if own_m and not raw.get("fallbackModel") and \
|
|
(str(own_m), str(own_h or "")) != (str(route["model"]), str(route["harness"])):
|
|
out["fallbackModel"] = own_m
|
|
if own_h:
|
|
out["fallbackHarness"] = own_h
|
|
if raw.get("account"):
|
|
out["fallbackAccount"] = raw["account"]
|
|
return out
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/complete")
|
|
async def plugin_hub_complete(pid: str, request: Request):
|
|
rec, err = _bridge(request, pid, "complete.run")
|
|
if err:
|
|
return err
|
|
raw = await _body(request)
|
|
deps = request.app.state.ai
|
|
raw = await run_in_threadpool(model_value, raw)
|
|
try:
|
|
preset, profile = preset_arg(raw)
|
|
except ValueError as e:
|
|
return _error(400, str(e), "bad_request")
|
|
route = None
|
|
if preset:
|
|
try:
|
|
route = await run_in_threadpool(route_preset, deps, pid, preset, profile)
|
|
except HTTPException as e:
|
|
msg, k = _detail(e)
|
|
return _error(e.status_code, msg, k)
|
|
if route:
|
|
raw = apply_route(raw, route)
|
|
try:
|
|
body = norm_complete(raw)
|
|
kind = _opt(raw, "kind", _KIND_RE) or f"plugin-{pid}"[:32]
|
|
except (ValueError, TypeError) as e:
|
|
return _error(400, str(e), "bad_request")
|
|
ref = str(raw.get("ref") or "")[:128] or None
|
|
try:
|
|
out = await run_in_threadpool(run_complete, deps, body, kind, ref)
|
|
except HTTPException as e:
|
|
msg, k = _detail(e)
|
|
return _error(e.status_code, msg, k)
|
|
return {**out, "route": route} if preset else out
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/complete/route")
|
|
async def plugin_hub_complete_route(pid: str, request: Request):
|
|
"""The route ``preset`` (``default``: the source's) takes right now, no
|
|
call made: ``{source, route}`` — ``route`` None when no preset is set for
|
|
the source (the plugin's own model answers then)."""
|
|
rec, err = _bridge(request, pid, "complete.run")
|
|
if err:
|
|
return err
|
|
q = request.query_params
|
|
try:
|
|
preset, profile = preset_arg({"preset": q.get("preset") or "default",
|
|
"profile": q.get("profile")})
|
|
except ValueError as e:
|
|
return _error(400, str(e), "bad_request")
|
|
try:
|
|
route = await run_in_threadpool(route_preset, request.app.state.ai, pid, preset, profile)
|
|
except HTTPException as e:
|
|
msg, k = _detail(e)
|
|
return _error(e.status_code, msg, k)
|
|
return {"source": f"plugin:{pid}", "route": route}
|
|
|
|
|
|
# ── conversations.label ─────────────────────────────────────────────────────
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/labels/pending")
|
|
async def plugin_hub_labels_pending(pid: str, request: Request):
|
|
rec, err = _bridge(request, pid, "conversations.label")
|
|
if err:
|
|
return err
|
|
q = request.query_params
|
|
sid = q.get("sid") or None
|
|
if sid and not _SID_RE.match(sid):
|
|
return _error(400, "bad session id", "bad_request")
|
|
try:
|
|
days = max(0.01, min(float(q.get("days") or 2), 90))
|
|
limit = max(1, min(int(q.get("limit") or 50), 500))
|
|
except ValueError:
|
|
return _error(400, "bad days / limit", "bad_request")
|
|
from conversations import look as look_mod
|
|
from conversations import look_pending
|
|
|
|
def _go():
|
|
return {"items": look_pending.pending(request.app.state.ai, days, limit, sid),
|
|
"actions": look_mod.ACTIONS, "system": look_mod.SYSTEM_PROMPT}
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
def write_look(deps, sid: str, action: Any, model: Any, source: str | None = None) -> str | None:
|
|
from conversations import look as look_mod
|
|
a = str(action or "").strip().lower()
|
|
a = a if a in look_mod.ACTIONS else None
|
|
entry: dict[str, Any] = {"action": a, "at": _now(), "model": str(model or "")[:128] or None}
|
|
if source:
|
|
entry["source"] = source[:32]
|
|
deps.meta_store.update(sid, {"lookAuto": entry})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
return a
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/labels/look")
|
|
async def plugin_hub_labels_look(pid: str, request: Request):
|
|
rec, err = _bridge(request, pid, "conversations.label")
|
|
if err:
|
|
return err
|
|
body = await _body(request)
|
|
sid = str(body.get("sessionId") or "")
|
|
if not _SID_RE.match(sid):
|
|
return _error(400, "bad session id", "bad_request")
|
|
deps = request.app.state.ai
|
|
a = await run_in_threadpool(write_look, deps, sid, body.get("action"), body.get("model"),
|
|
f"plugin:{pid}")
|
|
return {"sessionId": sid, "action": a}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/labels/short-title")
|
|
async def plugin_hub_labels_short_title(pid: str, request: Request):
|
|
rec, err = _bridge(request, pid, "conversations.label")
|
|
if err:
|
|
return err
|
|
body = await _body(request)
|
|
cid = str(body.get("id") or "")
|
|
if not re.match(r"^[A-Za-z0-9._/-]{8,200}$", cid) or ".." in cid:
|
|
return _error(400, "bad conversation id", "bad_request")
|
|
title = str(body.get("title") or "").strip()[:120] or None
|
|
source = str(body.get("source") or "")[:400]
|
|
if not source:
|
|
return _error(400, "source (the long title it stands for) is required", "bad_request")
|
|
deps = request.app.state.ai
|
|
|
|
def _go():
|
|
deps.store.set_short_title(cid, title, source)
|
|
if title:
|
|
deps.hub.publish({"type": "short-title", "id": cid, "title": title})
|
|
await run_in_threadpool(_go)
|
|
return {"id": cid, "title": title}
|
|
|
|
|
|
# ── generated titles (conversations.label) ──────────────────────────────────
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/labels/untitled")
|
|
async def plugin_hub_labels_untitled(pid: str, request: Request):
|
|
"""The conversations of ``harness`` (comma-separated) still without a
|
|
title (``conversations/title_pending.py``)."""
|
|
rec, err = _bridge(request, pid, "conversations.label")
|
|
if err:
|
|
return err
|
|
q = request.query_params
|
|
sid = q.get("sid") or None
|
|
if sid and not _SID_RE.match(sid):
|
|
return _error(400, "bad session id", "bad_request")
|
|
raw_h = (q.get("harness") or "").replace(" ", "")
|
|
if not _HARNESSES_RE.match(raw_h):
|
|
return _error(400, "harness: one or more harness ids, comma-separated", "bad_request")
|
|
try:
|
|
days = max(0.01, min(float(q.get("days") or 2), 90))
|
|
limit = max(1, min(int(q.get("limit") or 50), 500))
|
|
except ValueError:
|
|
return _error(400, "bad days / limit", "bad_request")
|
|
from conversations import title_pending
|
|
harnesses = set(raw_h.split(","))
|
|
|
|
def _go():
|
|
return {"items": title_pending.pending(request.app.state.ai, harnesses, days, limit, sid)}
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
def clean_title(title: Any) -> str | None:
|
|
"""One line, no wrapping quotes or final full stop, ≤ ``MAX_TITLE``."""
|
|
t = " ".join(str(title or "").split()).strip().strip("\"'`*").strip()
|
|
t = t.rstrip(".").strip()
|
|
return t[:MAX_TITLE].strip() or None
|
|
|
|
|
|
def write_title(deps, sid: str, title: Any, model: Any, source: str | None = None) -> str | None:
|
|
"""``meta.autoTitle`` — an empty answer is stored as ``None`` (never
|
|
asked again) but never replaces a title already written (two passes
|
|
racing on one conversation)."""
|
|
t = clean_title(title)
|
|
if t is None:
|
|
prev = (deps.meta_store.peek(sid) or {}).get("autoTitle")
|
|
if isinstance(prev, dict) and prev.get("title"):
|
|
return prev["title"]
|
|
entry: dict[str, Any] = {"title": t, "at": _now(), "model": str(model or "")[:128] or None}
|
|
if source:
|
|
entry["source"] = source[:32]
|
|
deps.meta_store.update(sid, {"autoTitle": entry})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
return t
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/labels/title")
|
|
async def plugin_hub_labels_title(pid: str, request: Request):
|
|
rec, err = _bridge(request, pid, "conversations.label")
|
|
if err:
|
|
return err
|
|
body = await _body(request)
|
|
sid = str(body.get("sessionId") or "")
|
|
if not _SID_RE.match(sid):
|
|
return _error(400, "bad session id", "bad_request")
|
|
t = await run_in_threadpool(write_title, request.app.state.ai, sid, body.get("title"),
|
|
body.get("model"), f"plugin:{pid}")
|
|
return {"sessionId": sid, "title": t}
|