The hub's own small model calls (action badges, short header titles, Send-later titles) leave the core for a plugin, on any model: - sidecar POST /complete (host only): one short answer, no transcript — a harness driver's optional complete() (claude / agy / opencode / pi), or the EVOX2 / OpenRouter over HTTP; wakeLocal:false never wakes the box or loads a model (asleep → fallback at once); fallback model/harness/account; usage returned in Anthropic's shape. - complete.run bridge (hub/complete): calls /complete, books the spend in the side-call ledger. conversations.label bridge: hub/labels/pending (look_pending.py), hub/labels/look (meta.lookAuto), hub/labels/short-title. - provides conversation.title (scheduled/title.py, short_title.py — no plugin: first words / no short title) and conversation.look. - removed: sidecar/title.py, sidecar/look.py, conversations/look_labeler.py and its thread; /api/look/pending rebuilt on look_pending. - docs/plugins.md, CLAUDE.md, sidecar README updated; tests: test_hubcomplete, test_complete, test_look, test_short_title. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
202 lines
8.3 KiB
Python
202 lines
8.3 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).
|
|
* ``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.
|
|
|
|
First user: the ``conversation-labels`` plugin.
|
|
"""
|
|
|
|
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}$")
|
|
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}
|
|
|
|
|
|
@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)
|
|
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:
|
|
return await run_in_threadpool(run_complete, request.app.state.ai, body, kind, ref)
|
|
except HTTPException as e:
|
|
msg, k = _detail(e)
|
|
return _error(e.status_code, msg, k)
|
|
|
|
|
|
# ── 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}
|