A session started with `continues` (POST /api/spawn, the plugin bridge's
runs.start, `ai-agent new --continue`) becomes the last part of the
conversation its target belongs to; `ai-agent continue-link` and
POST …/hub/conversations/{sid}/continues adopt a sequel that already exists.
- runs/continues.py: resolve to the tail (404 for a conversation the caller
may not send to), 409 for a running tail unless stop (a tail handing itself
over is let through), inherit what is unset (projects, model settings,
machine; the working directory only on the same machine), brief folded into
the prompt with briefChars, stamp meta.continues; adopt with its conditions.
- conversations/chain_cards.py: the list shows one card per conversation —
the head's, sums over the parts, the tail's state — with `parts`; search
rows fold the parts' messages into the head's.
- conversations/catalog.py, card.py, spawned.py, routes.py: any part's
session or uid answers with the head (session map, ?sessions=, summary,
conversation-meta writes, hub children of any part roll up to the head).
- live control (/api/resume, /api/interrupt, runs.stop, conversations.send)
goes to the tail, resolved at the door; forms by session cover every part.
- events: conversation.started / finished carry conversationSessionId.
- plugins/carryover.py: handoff and agent-presets links stamped before the
chain become meta.continues once (continues_links).
- plugins/proxyroutes.py: GET …/hub/conversations/{sid} answers for the
conversation: head identity, the tail's live fields, tailSessionId, parts.
- authz: POST /api/continues (runs.start); golden updated.
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
1041 lines
44 KiB
Python
1041 lines
44 KiB
Python
"""Hub capability bridges for live plugins (mounted under ``/proxy/tools/plugins/{pid}/hub/*``):
|
|
|
|
* ``askform.bridge`` — create, list, inspect, revoke, close, recheck and check
|
|
health of forms via the hub's ask-form mirror (``backend/askform/``).
|
|
* ``conversations.reply`` — post an app-tagged turn into a conversation via
|
|
``runs/reply.py`` (always preserving guest scope and active-user checks).
|
|
* ``notify.send`` clear — ``POST …/hub/notify/clear`` dismisses a push tag on
|
|
devices (``users/deliver.py``).
|
|
* ``users.read`` — safe user metadata (name, email, lang, web address, projects);
|
|
for a managed plugin's owner handlers also ``hub/grants`` — read / write its
|
|
own per-guest grants.
|
|
* ``scaffold.run`` — host sidecar ``/scaffold/check``, ``/scaffold``,
|
|
``/relocate``, template catalog and project grant (owner/managed handler only).
|
|
* ``home.read`` — ``GET …/hub/home``: the caller's own home page as data —
|
|
every plugin's ``home.tiles``, and how many conversations run and wait on
|
|
them (what a notification or a widget outside the app draws); ``lists=1``
|
|
adds the lists themselves and the person's machines (a menu bar).
|
|
* ``runs.stop`` — ``POST …/hub/conversations/{cid}/stop``: the app's Stop on
|
|
one of the handler's user's own running conversations (404 for any other).
|
|
* ``ship.run`` — the zipgo deploy broker: host sidecar ``/ship/deploy``, a
|
|
project's deploy-config scan and the security log (owner handler only; a
|
|
guest's run reaches it through a ``runAs: "owner"`` action, its requester in
|
|
``AIA_USER_CONTEXT.requester``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import re
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from plugins.proxyroutes import _active_plugin, _error, _who
|
|
from plugins.store import OWNER_UID
|
|
|
|
log = logging.getLogger("plugins.hubbridge")
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
_SID_RE = re.compile(r"^[A-Za-z0-9-]{4,64}$")
|
|
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
|
|
_NOT_APPS = ("homelab-service", "skill-cli")
|
|
SCAFFOLD_TIMEOUT_S = float(os.environ.get("NEW_PROJECT_SCAFFOLD_TIMEOUT_S", "960"))
|
|
|
|
|
|
async def _json_body(request: Request) -> dict[str, Any]:
|
|
try:
|
|
b = await request.json()
|
|
except Exception:
|
|
return {}
|
|
return b if isinstance(b, dict) else {}
|
|
|
|
|
|
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 "error")
|
|
return str(d), "error"
|
|
|
|
|
|
def _check_cap(request: Request, pid: str, cap: str, *, owner_only: bool = False,
|
|
handler_only: bool = False):
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, None, None, err
|
|
if handler_only and who.handler != pid:
|
|
return None, None, None, _error(403, f"{cap} is only available to the plugin's own handlers", "handler_only")
|
|
if owner_only and not who.is_owner:
|
|
return None, None, None, _error(403, f"{cap} is owner-only", "capability")
|
|
deps = request.app.state.ai
|
|
uid, rec, _g, _m, err = _active_plugin(deps, who, pid)
|
|
if err:
|
|
return None, None, None, err
|
|
if cap not in (rec["manifest"].get("capabilities") or []):
|
|
return None, None, None, _error(403, f"plugin lacks {cap} capability", "capability")
|
|
return deps, who, rec, None
|
|
|
|
|
|
def _caller_for_who(deps, who):
|
|
from users.caller import OWNER, guest_from_record
|
|
if who.is_owner:
|
|
return OWNER
|
|
u = deps.users.active(who.uid)
|
|
return guest_from_record(u) if u else None
|
|
|
|
|
|
# ── askform.bridge ───────────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/askform/create")
|
|
async def hub_askform_create(pid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
if not body.get("title"):
|
|
return _error(400, "title is required")
|
|
fields = body.get("fields")
|
|
if not isinstance(fields, list) or not fields:
|
|
return _error(400, "fields must be a non-empty list")
|
|
meta = dict(body.get("meta") or {}) if isinstance(body.get("meta"), dict) else {}
|
|
if body.get("sessionId") and not meta.get("session"):
|
|
meta["session"] = str(body["sessionId"]).strip()
|
|
if body.get("ownerOnly"):
|
|
if not who.is_owner:
|
|
return _error(403, "ownerOnly forms require owner context", "capability")
|
|
meta["ownerOnly"] = True
|
|
if body.get("noPush"):
|
|
meta["noPush"] = True
|
|
# Non-owners may only stamp their own sessions
|
|
if not who.is_owner and meta.get("session"):
|
|
from toolproxy import access as tp_access
|
|
if not tp_access.session_of(deps, who, str(meta["session"])):
|
|
return _error(403, "that conversation isn't yours", "session")
|
|
payload: dict[str, Any] = {
|
|
"title": str(body["title"])[:200],
|
|
"fields": fields,
|
|
"meta": meta,
|
|
}
|
|
for k in ("name", "description", "ttl", "lang", "multi", "maxAnswers",
|
|
"hideCount", "public", "noSnapshot", "assets"):
|
|
if k in body and body[k] is not None:
|
|
payload[k] = body[k]
|
|
machine = str(body.get("machine") or "lab").strip() or "lab"
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
rec = af.create_form(deps, payload, machine=machine)
|
|
return af.public(deps, caller, [rec], lite=False)[0]
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/askform/forms")
|
|
async def hub_askform_list(pid: str, request: Request, session: str = "",
|
|
status: str = "", limit: int = 100):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
from users import access
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
items = deps.askform_store.list(status=status or None, session=session or None,
|
|
limit=max(1, min(500, int(limit))))
|
|
if not caller.is_owner:
|
|
items = [r for r in items if not af.is_owner_only(r)
|
|
and r.get("sessionId") and access.visible(deps, caller, r["sessionId"])]
|
|
pub = af.public(deps, caller, items, lite=True)
|
|
return {"forms": pub, "count": len(pub)}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/askform/forms/{fid}")
|
|
async def hub_askform_get(pid: str, fid: str, request: Request, fields: int = 1, refresh: int = 0):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
af.visible(deps, caller, deps.askform_store.get(fid))
|
|
if refresh:
|
|
rec = af.recheck(deps, fid)
|
|
elif fields:
|
|
rec = af.with_fields(deps, fid)
|
|
else:
|
|
rec = deps.askform_store.get(fid)
|
|
return af.public(deps, caller, [rec], lite=not bool(fields))[0]
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/askform/forms/{fid}/{verb}")
|
|
async def hub_askform_verb(pid: str, fid: str, verb: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "askform.bridge", handler_only=True)
|
|
if err:
|
|
return err
|
|
if verb not in ("revoke", "close", "recheck"):
|
|
return _error(400, f"unknown verb {verb!r}")
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
raise HTTPException(403, "user is not active")
|
|
af.visible(deps, caller, deps.askform_store.get(fid))
|
|
if verb == "recheck":
|
|
rec = af.recheck(deps, fid)
|
|
else:
|
|
rec = af.end(deps, fid, close=(verb == "close"))
|
|
return af.public(deps, caller, [rec], lite=(verb != "recheck"))[0]
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/askform/health")
|
|
async def hub_askform_health(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "askform.bridge",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from askform import service as af
|
|
from workers.store import sidecar_request
|
|
out = []
|
|
for m in af.machines(deps):
|
|
try:
|
|
h = sidecar_request(m["url"], m["token"], "/ask-form/health", None,
|
|
method="GET", timeout=6, label=m["label"])
|
|
except HTTPException as e:
|
|
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
h = {"installed": None, "ok": False, "error": d.get("message")}
|
|
out.append({"machine": m["id"], "label": m["label"], **h})
|
|
return {"machines": out}
|
|
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
# ── notify.send clear ────────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/notify/clear")
|
|
async def hub_notify_clear(pid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "notify.send")
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
tag = str(body.get("tag") or "").strip()[:120]
|
|
if not tag:
|
|
return _error(400, "tag is required")
|
|
kind = str(body.get("kind") or "notify")[:24]
|
|
sid = str(body.get("session") or body.get("sessionId") or "").strip()
|
|
if not who.is_owner and sid:
|
|
from toolproxy import access as tp_access
|
|
if not tp_access.session_of(deps, who, sid):
|
|
return _error(403, "that conversation isn't yours", "session")
|
|
if body.get("ownerOnly"):
|
|
sid = ""
|
|
|
|
def _go():
|
|
from users import deliver
|
|
deliver.clear(deps, sid, tag, kind)
|
|
|
|
await run_in_threadpool(_go)
|
|
return {"ok": True}
|
|
|
|
|
|
# ── conversations.reply ──────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/conversations/{sid}/reply")
|
|
async def hub_conversation_reply(pid: str, sid: str, request: Request):
|
|
"""Post an app-tagged turn into ``sid`` via ``runs/reply.py.say`` (preserves
|
|
guest scope and active-user check)."""
|
|
deps, who, _rec, err = _check_cap(request, pid, "conversations.reply", handler_only=True)
|
|
if err:
|
|
return err
|
|
if not _SID_RE.match(sid):
|
|
return _error(400, "bad session id")
|
|
body = await _json_body(request)
|
|
text = str(body.get("text") or body.get("prompt") or "").strip()
|
|
if not text or len(text) > 100_000:
|
|
return _error(400, "text is required (<= 100 000 chars)")
|
|
if not who.is_owner:
|
|
meta = deps.meta_store.peek(sid) or {}
|
|
if meta.get("owner") != who.uid:
|
|
return _error(403, "that conversation isn't yours", "session")
|
|
tag_name = str(body.get("tagName") or pid)[:40]
|
|
tag_user = re.sub(r"[^a-z0-9_-]", "", str(body.get("tagUser") or pid).lower()) or pid
|
|
tag = f'<ai-agent-from user="{tag_user}" name="{tag_name}" role="app"/>'
|
|
harness = body.get("harness") if "harness" in body else "claude"
|
|
if harness is not None and harness not in ("claude", "pi", "opencode", "agy"):
|
|
return _error(400, "bad harness")
|
|
inbox_only = bool(body.get("inboxOnly", False))
|
|
|
|
def _go():
|
|
from runs.reply import say
|
|
out = say(deps, sid, text, tag=tag, harness=harness, inbox_only=inbox_only)
|
|
return {"ok": out is not None, "result": out}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
# ── users.read ───────────────────────────────────────────────────────────────
|
|
def _safe_user(deps, uid: str) -> dict[str, Any] | None:
|
|
from users import domains as user_domains
|
|
from users.caller import OWNER_ID, OWNER_NAME
|
|
dom_default = user_domains.default_domain(deps)
|
|
if uid == OWNER_ID:
|
|
return {
|
|
"id": OWNER_ID, "name": OWNER_NAME, "email": "", "lang": "en",
|
|
"isOwner": True, "active": True, "domain": "", "bucket": "",
|
|
"projects": {},
|
|
"address": {"bucket": None, "domain": dom_default, "base": None, "apex": False},
|
|
}
|
|
u = deps.users.get(uid)
|
|
if not u:
|
|
return None
|
|
bucket, domain = user_domains.address_of(u, dom_default)
|
|
return {
|
|
"id": u["id"],
|
|
"name": u.get("name") or u["id"],
|
|
"email": u.get("email") or "",
|
|
"lang": u.get("lang") or "en",
|
|
"isOwner": False,
|
|
"active": bool(deps.users.active(u["id"])),
|
|
"createdAt": u.get("createdAt"),
|
|
"domain": (u.get("domain") or "").strip(),
|
|
"bucket": (u.get("bucket") or "").strip(),
|
|
"projects": dict(u.get("projects") or {}),
|
|
"address": {
|
|
"bucket": bucket,
|
|
"domain": domain,
|
|
"base": user_domains.base_of(bucket, domain),
|
|
"apex": bool((u.get("domain") or "").strip()) and not bucket,
|
|
},
|
|
}
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/users")
|
|
async def hub_users_list(pid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "users.read", handler_only=True)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from users.caller import OWNER_ID
|
|
if not who.is_owner:
|
|
me = _safe_user(deps, who.uid)
|
|
return {"users": [me] if me else []}
|
|
rows = [_safe_user(deps, OWNER_ID)]
|
|
for u in deps.users.all():
|
|
if u.get("id"):
|
|
su = _safe_user(deps, u["id"])
|
|
if su:
|
|
rows.append(su)
|
|
return {"users": rows}
|
|
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/users/{uid}")
|
|
async def hub_user_one(pid: str, uid: str, request: Request):
|
|
deps, who, _rec, err = _check_cap(request, pid, "users.read", handler_only=True)
|
|
if err:
|
|
return err
|
|
if not who.is_owner and uid != who.uid:
|
|
return _error(403, "users.read for other users is owner-only", "capability")
|
|
|
|
def _go():
|
|
from users.caller import OWNER_ID
|
|
target = OWNER_ID if uid == OWNER_UID else uid
|
|
return _safe_user(deps, target)
|
|
|
|
out = await run_in_threadpool(_go)
|
|
if not out:
|
|
return _error(404, "unknown user")
|
|
return out
|
|
|
|
|
|
# ── users.read: a managed plugin's own per-guest grants ─────────────────────
|
|
# The plugin's Settings page reads and writes the very grants Settings → Users
|
|
# → <guest> → Managed plugins does (PluginStore is the one source of truth).
|
|
# Owner-only, the plugin's own handlers only, its own grants only (``pid``).
|
|
def _managed_rec(rec) -> tuple[dict[str, Any] | None, Any]:
|
|
mf = rec.get("manifest") or {}
|
|
if not mf.get("managed"):
|
|
return None, _error(400, "plugin is not managed")
|
|
return mf, None
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/grants")
|
|
async def hub_grants_list(pid: str, request: Request):
|
|
deps, _who_, rec, err = _check_cap(request, pid, "users.read", owner_only=True,
|
|
handler_only=True)
|
|
if err:
|
|
return err
|
|
mf, err = _managed_rec(rec)
|
|
if err:
|
|
return err
|
|
|
|
def _go():
|
|
from plugins import metering
|
|
rows = []
|
|
for u in deps.users.all():
|
|
gid = u.get("id")
|
|
if not gid:
|
|
continue
|
|
rows.append({
|
|
"uid": gid,
|
|
"name": u.get("name") or gid,
|
|
"email": u.get("email") or "",
|
|
"active": bool(deps.users.active(gid)),
|
|
"grant": deps.plugin_store.effective_grant(gid, pid, mf),
|
|
"usage": metering.plugin_usage_by_who(gid, pid),
|
|
})
|
|
return {"grants": rows, "managed": mf.get("managed")}
|
|
|
|
return await run_in_threadpool(_go)
|
|
|
|
|
|
@router.put("/proxy/tools/plugins/{pid}/hub/grants/{uid}")
|
|
async def hub_grant_update(pid: str, uid: str, request: Request):
|
|
deps, _who_, rec, err = _check_cap(request, pid, "users.read", owner_only=True,
|
|
handler_only=True)
|
|
if err:
|
|
return err
|
|
_mf, err = _managed_rec(rec)
|
|
if err:
|
|
return err
|
|
if uid == OWNER_UID or not deps.users.get(uid):
|
|
return _error(404, "unknown user")
|
|
body = await _json_body(request)
|
|
|
|
def _go():
|
|
from plugins.routes import apply_managed_grant
|
|
grant = apply_managed_grant(deps, uid, pid, body)
|
|
deps.hub.publish({"type": "users"})
|
|
return {"ok": True, "uid": uid, "grant": grant}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
# ── scaffold.run ─────────────────────────────────────────────────────────────
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/scaffold/templates")
|
|
async def hub_scaffold_templates(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
return await run_in_threadpool(_app_templates)
|
|
|
|
|
|
def _templates_dir() -> pathlib.Path:
|
|
return pathlib.Path(os.environ.get("TEMPLATES_DIR", "/workspace/projects/templates")).resolve()
|
|
|
|
|
|
def _template_description(d: pathlib.Path) -> str:
|
|
"""package.json's ``description``, else the README's first prose line —
|
|
an unfilled ``@@PLACEHOLDER@@`` reads as none (the Templates plugin's rule)."""
|
|
try:
|
|
desc = json.loads((d / "package.json").read_text(encoding="utf-8", errors="replace")).get("description")
|
|
if isinstance(desc, str) and desc.strip() and "@@" not in desc:
|
|
return desc.strip()
|
|
except (OSError, ValueError, AttributeError):
|
|
pass
|
|
for cand in ("README.md", "README", "readme.md"):
|
|
try:
|
|
text = (d / cand).read_text(encoding="utf-8", errors="replace")
|
|
except OSError:
|
|
continue
|
|
for line in text.splitlines():
|
|
t = line.strip()
|
|
if t and not t.startswith(("#", "![")) and "@@" not in t:
|
|
return t
|
|
return ""
|
|
return ""
|
|
|
|
|
|
def _app_templates() -> dict[str, Any]:
|
|
"""The scaffoldable app templates (a ``package.json`` / ``pyproject.toml``
|
|
at the root; not the service / skill ones) with their description."""
|
|
root = _templates_dir()
|
|
out = []
|
|
if root.is_dir():
|
|
for d in sorted(root.iterdir()):
|
|
if not d.is_dir() or d.name.startswith(".") or d.name.startswith(_NOT_APPS):
|
|
continue
|
|
if (d / "package.json").is_file() or (d / "pyproject.toml").is_file():
|
|
out.append({"name": d.name, "description": _template_description(d)})
|
|
return {"templates": out}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/check")
|
|
async def hub_scaffold_check(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
template = str(body.get("template") or "").strip()
|
|
vars_in = body.get("vars") if isinstance(body.get("vars"), dict) else {}
|
|
if not _SLUG_RE.match(template):
|
|
return _error(400, "invalid template name")
|
|
|
|
def _go():
|
|
from runs.sidecar_client import _sidecar_call
|
|
return _sidecar_call(deps, "/scaffold/check", {"template": template, "vars": vars_in}, timeout=90)
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/run")
|
|
async def hub_scaffold_run(pid: str, request: Request):
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
template = str(body.get("template") or "").strip()
|
|
vars_in = body.get("vars") if isinstance(body.get("vars"), dict) else {}
|
|
if not _SLUG_RE.match(template):
|
|
return _error(400, "invalid template name")
|
|
payload = {
|
|
"template": template,
|
|
"vars": vars_in,
|
|
"password": bool(body.get("password", False)),
|
|
}
|
|
|
|
def _go():
|
|
from runs.sidecar_client import _sidecar_call
|
|
return _sidecar_call(deps, "/scaffold", payload, timeout=SCAFFOLD_TIMEOUT_S)
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/grant-project")
|
|
async def hub_scaffold_grant_project(pid: str, request: Request):
|
|
"""Grant a guest access to a newly scaffolded project."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
uid = str(body.get("uid") or "").strip()
|
|
slug = str(body.get("slug") or "").strip()
|
|
level = str(body.get("level") or "ship").strip()
|
|
if not uid or not _SLUG_RE.match(slug) or level not in ("read", "chat", "ship"):
|
|
return _error(400, "uid, valid slug and level (read|chat|ship) required")
|
|
|
|
def _go():
|
|
u = deps.users.get(uid)
|
|
if not u:
|
|
raise HTTPException(404, f"unknown user {uid}")
|
|
deps.users.update(uid, {"projects": {**(u.get("projects") or {}), slug: level}})
|
|
deps.hub.publish({"type": "users"})
|
|
return {"ok": True, "uid": uid, "slug": slug, "level": level}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/scaffold/relocate")
|
|
async def hub_scaffold_relocate(pid: str, request: Request):
|
|
"""Relocate session ``sid`` into project ``slug`` and resume it with ``prompt``."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "scaffold.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
sid = str(body.get("sessionId") or "").strip()
|
|
slug = str(body.get("slug") or "").strip()
|
|
prompt = str(body.get("prompt") or "").strip()
|
|
if not _SID_RE.match(sid) or not _SLUG_RE.match(slug) or not prompt:
|
|
return _error(400, "sessionId, slug and prompt are required")
|
|
|
|
def _go():
|
|
from runs.reply import caller_of, requester_of
|
|
from runs.service import _send_message, _session_account
|
|
from runs.sidecar_client import _sidecar_call
|
|
from users import runs as guest_runs
|
|
from users.caller import OWNER_ID
|
|
|
|
cwd = guest_runs.project_cwd(slug)
|
|
_sidecar_call(deps, "/relocate", {"sessionId": sid, "cwd": cwd,
|
|
"account": _session_account(deps, sid)}, timeout=30)
|
|
deps.meta_store.update(sid, {"projects": [slug], "state": "running"})
|
|
deps.hub.publish({"type": "meta", "id": sid})
|
|
requester = requester_of(deps, sid)
|
|
scope = None
|
|
if requester != OWNER_ID:
|
|
caller = caller_of(deps, requester)
|
|
if caller is None:
|
|
raise HTTPException(403, f"guest {requester} is not active")
|
|
scope = guest_runs.scope_for(caller, slug, caller.level(slug),
|
|
guest_runs.shared_skills(deps),
|
|
new_projects=guest_runs.new_project_line(deps, caller),
|
|
deps=deps)
|
|
out = _send_message(deps, prompt, session_id=sid, cwd=cwd, harness="claude", scope=scope)
|
|
return {"ok": True, "sessionId": out.get("sessionId") or sid, "cwd": cwd}
|
|
|
|
try:
|
|
return await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
|
|
|
|
# ── ship.run ─────────────────────────────────────────────────────────────────
|
|
_HOST_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$")
|
|
_DEPLOY_HOST_RE = re.compile(r"""(?:\bHOST=["']?|\s-d\s+["']?|--domain[= ]["']?)([a-z0-9.-]+\.[a-z]{2,})""")
|
|
_BUILD_DIR_RE = re.compile(r"^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$")
|
|
_SHIP_AUDIT_KINDS = ("guard_block", "ship_deploy")
|
|
|
|
|
|
def _ship_project(slug: Any) -> tuple[str, pathlib.Path] | None:
|
|
from projects.catalog import _safe_entry
|
|
if not isinstance(slug, str) or not _SLUG_RE.match(slug.strip()):
|
|
return None
|
|
entry = _safe_entry(slug.strip())
|
|
return (entry.name, entry) if entry is not None else None
|
|
|
|
|
|
def _zipgo_deploy(root: pathlib.Path) -> dict[str, Any]:
|
|
try:
|
|
z = json.loads((root / "package.json").read_text()).get("zipgo") or {}
|
|
dep = z.get("deploy") if isinstance(z, dict) else None
|
|
return dep if isinstance(dep, dict) else {}
|
|
except (OSError, ValueError, AttributeError):
|
|
return {}
|
|
|
|
|
|
def ship_scan(root: pathlib.Path) -> dict[str, Any]:
|
|
"""The hosts a project's own deploy config names — ``package.json``
|
|
``zipgo.deploy`` keys and ``scripts/deploy*.sh`` ``HOST=`` / ``-d`` /
|
|
``--domain`` — and each ``zipgo.deploy`` host's build dir (``ship/service.py``'s
|
|
scan). A seed for the owner's list, never an allowlist by itself."""
|
|
dep = _zipgo_deploy(root)
|
|
hosts: set[str] = {h.lower() for h in dep if isinstance(h, str)}
|
|
for f in sorted((root / "scripts").glob("deploy*.sh"))[:10]:
|
|
try:
|
|
hosts.update(m.group(1) for m in _DEPLOY_HOST_RE.finditer(f.read_text()[:200_000]))
|
|
except OSError:
|
|
pass
|
|
build_dirs = {h.lower(): v.strip().strip("/") for h, v in dep.items()
|
|
if isinstance(h, str) and isinstance(v, str) and v.strip().strip("/")}
|
|
return {"hosts": sorted(h for h in hosts if _HOST_RE.match(h)), "buildDirs": build_dirs}
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/ship/scan")
|
|
async def hub_ship_scan(pid: str, request: Request, project: str = ""):
|
|
_deps, _who_c, _rec, err = _check_cap(request, pid, "ship.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
hit = _ship_project(project)
|
|
if hit is None:
|
|
return _error(404, "unknown project")
|
|
out = await run_in_threadpool(ship_scan, hit[1])
|
|
return {"project": hit[0], **out}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/ship/deploy")
|
|
async def hub_ship_deploy(pid: str, request: Request):
|
|
"""Publish ``project``'s build dir to ``host`` through the host sidecar's
|
|
zipgo broker. The plugin decided it may (its rules: the guest's ``ship``
|
|
grant, the host allowlist); the hub checks the shape, runs it and writes
|
|
the tamper-proof ``ship_deploy`` security event naming ``actor``."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "ship.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
hit = _ship_project(body.get("project"))
|
|
if hit is None:
|
|
return _error(404, "unknown project")
|
|
slug, root = hit
|
|
host = str(body.get("host") or "").strip().lower()
|
|
if not _HOST_RE.match(host):
|
|
return _error(400, "invalid host")
|
|
bdir = body.get("dir")
|
|
if bdir is None or not str(bdir).strip():
|
|
sub = _zipgo_deploy(root).get(host)
|
|
bdir = sub.strip().strip("/") if isinstance(sub, str) and sub.strip().strip("/") else "dist"
|
|
bdir = str(bdir).strip().strip("/")
|
|
if not _BUILD_DIR_RE.match(bdir) or ".." in bdir.split("/"):
|
|
return _error(400, "invalid build dir")
|
|
actor = str(body.get("actor") or "owner")[:64]
|
|
sid = str(body.get("sessionId") or "")[:80] or None
|
|
|
|
def _go():
|
|
from runs.sidecar_client import _sidecar_call
|
|
from security import service as security
|
|
out = _sidecar_call(deps, "/ship/deploy", {"project": slug, "host": host, "dir": bdir},
|
|
timeout=280)
|
|
security.record(deps, "ship_deploy", who=actor, sid=sid,
|
|
detail=f"{slug} → {host}", data={"plugin": pid, "dir": bdir})
|
|
return out
|
|
|
|
try:
|
|
out = await run_in_threadpool(_go)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code, msg, kind)
|
|
out = out if isinstance(out, dict) else {}
|
|
return {"ok": True, "url": out.get("url") or f"https://{host}", "host": host,
|
|
"project": slug, "dir": bdir, "output": out.get("output") or ""}
|
|
|
|
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/ship/audit")
|
|
async def hub_ship_audit(pid: str, request: Request):
|
|
"""A ``guard_block`` (a refused deploy) or ``ship_deploy`` event in the
|
|
hub's security log, from the ship plugin's own handlers."""
|
|
deps, _who_c, _rec, err = _check_cap(request, pid, "ship.run",
|
|
owner_only=True, handler_only=True)
|
|
if err:
|
|
return err
|
|
body = await _json_body(request)
|
|
kind = body.get("kind")
|
|
if kind not in _SHIP_AUDIT_KINDS:
|
|
return _error(400, f"kind must be one of {', '.join(_SHIP_AUDIT_KINDS)}")
|
|
actor = str(body.get("actor") or "").strip()[:64]
|
|
if not actor:
|
|
return _error(400, "actor is required")
|
|
project = str(body.get("project") or "")[:64]
|
|
host = str(body.get("host") or "")[:253]
|
|
detail = str(body.get("detail") or "").strip()
|
|
if not detail:
|
|
detail = f"ship deploy to {host or '?'} refused" if kind == "guard_block" else f"{project} → {host}"
|
|
sid = str(body.get("sessionId") or "")[:80] or None
|
|
|
|
def _go():
|
|
from security import service as security
|
|
return security.record(deps, kind, who=actor, sid=sid, detail=detail[:500],
|
|
data={"plugin": pid, **({"project": project} if project else {}),
|
|
**({"host": host} if host else {})})
|
|
|
|
await run_in_threadpool(_go)
|
|
return {"ok": True}
|
|
|
|
|
|
# ── home.read ────────────────────────────────────────────────────────────────
|
|
RUNNING_LIST_MAX = 6
|
|
WAITING_LIST_MAX = 4
|
|
WAITING_OPTIONS_MAX = 4
|
|
WAITING_OPTION_CHARS = 24
|
|
|
|
|
|
def _epoch(iso) -> int | None:
|
|
from datetime import datetime, timezone
|
|
if not isinstance(iso, str) or not iso:
|
|
return None
|
|
try:
|
|
d = datetime.fromisoformat(iso.replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
if d.tzinfo is None:
|
|
d = d.replace(tzinfo=timezone.utc)
|
|
return int(d.timestamp())
|
|
|
|
|
|
def _mine(caller, meta: dict, account: str | None = None) -> bool:
|
|
"""Is this conversation the caller's **own** — one they started? Narrower
|
|
than what they may see: a guest's excludes the ones shared with them, the
|
|
owner's excludes every guest's (which the owner can read and stop in the
|
|
app, but which a phone or menu-bar channel acting *for them* never lists
|
|
or stops)."""
|
|
from profiles.store import guest_owner
|
|
g = guest_owner(meta, account)
|
|
return g is None if caller.is_owner else g == caller.id
|
|
|
|
|
|
def _model_labels() -> dict[str, str]:
|
|
try:
|
|
from models import catalog
|
|
rows = catalog.list_models()
|
|
except Exception: # noqa: BLE001 — no registry: the raw ids
|
|
return {}
|
|
out: dict[str, str] = {}
|
|
for e in rows:
|
|
name = str(e.get("label") or e.get("displayName") or "")
|
|
if e.get("id") and name:
|
|
out.setdefault(e["id"], name[7:] if name.startswith("Claude ") else name)
|
|
return out
|
|
|
|
|
|
_CLAUDE_ID = re.compile(r"^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$")
|
|
|
|
|
|
def _model_label(model: str, labels: dict[str, str]) -> str:
|
|
"""The catalogue's name for a model id; an Anthropic id it doesn't list
|
|
(an older snapshot) reads ``Opus 4.5``; anything else as it is."""
|
|
if model in labels:
|
|
return labels[model]
|
|
m = _CLAUDE_ID.match(model)
|
|
if m:
|
|
return f"{m.group(1).capitalize()} {m.group(2)}" + (f".{m.group(3)}" if m.group(3) else "")
|
|
return model
|
|
|
|
|
|
def _machine_names(deps) -> dict[str, str]:
|
|
return {w["id"]: w.get("name") or w["id"] for w in deps.worker_store.list()}
|
|
|
|
|
|
def _running_list(deps, caller, cards: list[dict]) -> list[dict]:
|
|
"""The caller's own running conversations, newest first — what their home
|
|
page's Running section lists: no archived one, no hub child that wasn't
|
|
promoted (it shows inside its parent)."""
|
|
rows = []
|
|
for c in cards:
|
|
meta = c.get("meta") or {}
|
|
if meta.get("state") != "running" or meta.get("archived"):
|
|
continue
|
|
if meta.get("spawnedBy") and not meta.get("promoted"):
|
|
continue
|
|
if not _mine(caller, meta, meta.get("account")):
|
|
continue
|
|
rows.append((_epoch(c.get("startedAt")) or 0, c))
|
|
rows.sort(key=lambda r: (-r[0], str(r[1].get("id"))))
|
|
labels, names = _model_labels(), _machine_names(deps)
|
|
out = []
|
|
for started, c in rows[:RUNNING_LIST_MAX]:
|
|
meta = c.get("meta") or {}
|
|
wid = meta.get("worker") or meta.get("workerSource")
|
|
model = str(c.get("model") or "")
|
|
try:
|
|
cost = round(float(c.get("cost") or 0.0), 2)
|
|
except (TypeError, ValueError):
|
|
cost = 0.0
|
|
out.append({"id": c.get("id"), "title": str(c.get("title") or "")[:120],
|
|
"machine": names.get(wid, wid) if wid else "Homelab",
|
|
"model": _model_label(model, labels), "startedAt": started or None,
|
|
"costUsd": cost, "url": f"/conversation/{c.get('id')}"})
|
|
return out
|
|
|
|
|
|
def _pending_asks(deps, caller) -> list[dict]:
|
|
"""The pending, unexpired asks the caller hears (``push_is_for`` — the
|
|
rule their phone channel acts under)."""
|
|
import time
|
|
from notifications.routes import push_is_for
|
|
now, out = time.time(), []
|
|
for e in deps.notify_store.log(limit=500):
|
|
if e.get("kind") != "ask" or e.get("status") != "pending" or not e.get("id"):
|
|
continue
|
|
exp = _epoch(e.get("expiresAt"))
|
|
if exp is not None and exp <= now:
|
|
continue
|
|
if push_is_for(deps, caller, e):
|
|
out.append(e)
|
|
return out
|
|
|
|
|
|
def _waiting_list(deps, caller, items: list[dict], cards: list[dict]) -> tuple[list[dict], int]:
|
|
"""(the caller's *Waiting for feedback* list, oldest first and capped; how
|
|
many wait in all) — the plugins' ``inbox.waiting`` items and the pending
|
|
asks, one row per id."""
|
|
by_sid = {c.get("sessionId"): c for c in cards if c.get("sessionId")}
|
|
rows: dict[str, tuple[str, dict]] = {}
|
|
|
|
def conv(sid: str) -> tuple[str, str]:
|
|
c = by_sid.get(sid) if sid else None
|
|
return (str(c.get("title") or "")[:80], f"/conversation/{c.get('id')}") if c else ("", "")
|
|
|
|
for e in _pending_asks(deps, caller):
|
|
title, url = conv(e.get("sessionId") or "")
|
|
opts = [str(o) for o in (e.get("options") or []) if isinstance(o, str)]
|
|
row = {"id": e["id"], "kind": "ask", "title": str(e.get("body") or "").strip()[:240],
|
|
"conv": title, "options": [o[:WAITING_OPTION_CHARS] for o in opts[:WAITING_OPTIONS_MAX]],
|
|
"optionCount": len(opts), "url": url or str(e.get("url") or "")}
|
|
if len(opts) > WAITING_OPTIONS_MAX or any(len(o) > WAITING_OPTION_CHARS for o in opts):
|
|
row["truncated"] = True # the rest: notify.respond's push/<id>
|
|
rows[e["id"]] = (str(e.get("at") or ""), row)
|
|
for it in items:
|
|
iid = str(it.get("id") or "")
|
|
if not iid or iid in rows:
|
|
continue
|
|
title, url = conv(it.get("sessionId") or "")
|
|
fid = str(it.get("formId") or "")
|
|
if url and fid and re.fullmatch(r"[A-Za-z0-9_-]{1,80}", fid):
|
|
url = f"{url}?form={fid}"
|
|
rows[iid] = (str(it.get("at") or ""), {
|
|
"id": iid, "kind": "form", "title": str(it.get("title") or "")[:240],
|
|
"conv": title, "url": url or str(it.get("url") or "")})
|
|
ordered = sorted(rows.values(), key=lambda r: (r[0] == "", r[0], r[1]["id"]))
|
|
return [r for _at, r in ordered[:WAITING_LIST_MAX]], len(ordered)
|
|
|
|
|
|
def _machines(deps, caller) -> list[dict]:
|
|
"""The owner: the lab then their workers. A guest: their own computers."""
|
|
if caller.is_owner:
|
|
from plugins.hubruns import workers_payload
|
|
return [{"id": w["id"], "name": w["name"], "online": w.get("status") == "online"}
|
|
for w in workers_payload(deps)["workers"]]
|
|
from users import computers
|
|
return [{"id": w["id"], "name": w.get("name") or w["id"],
|
|
"online": deps.worker_store.online(w["id"])}
|
|
for w in computers.of(deps, caller.id)]
|
|
|
|
|
|
@router.get("/proxy/tools/plugins/{pid}/hub/home")
|
|
async def hub_home(pid: str, request: Request, scope: str = "all", profileScope: str = "all",
|
|
tzOffset: int = 0, lists: int = 0):
|
|
"""``home.read``: the caller's home page as data — ``tiles`` (every active
|
|
plugin's ``provides: home.tiles``, as ``GET /api/plugins/home-tiles``
|
|
answers them: sanitized, each with its ``pluginId``), ``running`` (their
|
|
conversations at work now, archived ones left out) and ``waiting`` (their
|
|
*Waiting for feedback* count, ``provides: inbox.waiting``). The person's
|
|
own data only: a guest's plugin reads that guest's tiles.
|
|
|
|
``lists=1`` adds what a menu bar draws: ``runningList`` (≤ 6, newest
|
|
first: ``id``, ``title``, ``machine``, ``model``, ``startedAt`` — epoch s —,
|
|
``costUsd``, ``url``) — the conversations the person **started**
|
|
(``_mine``), as their home lists them —, ``waitingList`` (≤ 4, oldest
|
|
first: ``id``, ``kind`` ``ask`` | ``form``, ``title``, ``conv``, ``url``;
|
|
an ask's ``options`` — at most 4 labels of 24 characters —, its
|
|
``optionCount`` and ``truncated`` when either cut something), ``waitingTotal`` (every row of that list, pending asks
|
|
included — ``waiting`` counts the plugins' items alone) and ``machines``
|
|
(``id``, ``name``, ``online``: the owner's workers and the lab; a guest's
|
|
own computers). Without it the answer is unchanged."""
|
|
deps, who, _rec, err = _check_cap(request, pid, "home.read")
|
|
if err:
|
|
return err
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
return _error(403, "unknown user", "auth")
|
|
try:
|
|
tz = max(-960, min(960, int(tzOffset)))
|
|
except (TypeError, ValueError):
|
|
tz = 0
|
|
|
|
def _build():
|
|
from conversations.catalog import _conversation_cards
|
|
from plugins import home_tiles, waiting
|
|
from users import access
|
|
tiles = home_tiles.tiles_for(deps, caller, scope, profileScope, "", tz)
|
|
running = 0
|
|
cards = access.filter_cards(caller, list(_conversation_cards(deps, False)))
|
|
for c in cards:
|
|
meta = c.get("meta") or {}
|
|
if meta.get("state") == "running" and not meta.get("archived"):
|
|
running += 1
|
|
try:
|
|
items = waiting.waiting_for(deps, caller)
|
|
except Exception: # noqa: BLE001 — a broken inbox provider never hides the tiles
|
|
log.exception("hub/home: waiting count failed")
|
|
items = []
|
|
out = {"tiles": tiles, "running": running, "waiting": len(items)}
|
|
if lists:
|
|
out["runningList"] = _running_list(deps, caller, cards)
|
|
try:
|
|
out["waitingList"], out["waitingTotal"] = _waiting_list(deps, caller, items, cards)
|
|
except Exception: # noqa: BLE001 — the lists are extras: never a 500
|
|
log.exception("hub/home: waiting list failed")
|
|
out["waitingList"], out["waitingTotal"] = [], len(items)
|
|
out["machines"] = _machines(deps, caller)
|
|
return out
|
|
|
|
return JSONResponse(await run_in_threadpool(_build))
|
|
|
|
|
|
# ── runs.stop ────────────────────────────────────────────────────────────────
|
|
@router.post("/proxy/tools/plugins/{pid}/hub/conversations/{cid}/stop")
|
|
async def hub_run_stop(pid: str, cid: str, request: Request):
|
|
"""``runs.stop``: stop one of the handler's user's **own** running
|
|
conversations — the app's Stop (``runs.routes.stop_run``). ``cid`` is a
|
|
conversation id or a session id. A conversation that isn't theirs
|
|
(``_mine``: one they started — not one shared with a guest, not a
|
|
guest's for the owner), that they may not stop, or that the hub doesn't
|
|
know: **404**, never a hint that it exists. Theirs but not running: 409
|
|
``not_running``. The plugin's own handlers only."""
|
|
deps, who, _rec, err = _check_cap(request, pid, "runs.stop", handler_only=True)
|
|
if err:
|
|
return err
|
|
caller = _caller_for_who(deps, who)
|
|
if caller is None:
|
|
return _error(403, "unknown user", "auth")
|
|
gone = _error(404, "unknown conversation", "not_found")
|
|
if not _SID_RE.match(cid or ""):
|
|
return gone
|
|
|
|
def _go():
|
|
from conversations import chain
|
|
from conversations.catalog import _conv_ids_by_session, _conversation_cards
|
|
from core import liveruns
|
|
from plugins.hubchecks import locate
|
|
from runs.routes import stop_run
|
|
from users import access
|
|
hit = locate(deps, cid)
|
|
if not hit or hit[2].get("isSidechain"):
|
|
return gone
|
|
# The conversation's tail runs: the stop goes there (docs/conversation-chain.md).
|
|
head = chain.head_of(deps, hit[2]["sessionId"])
|
|
sid = chain.tail_of(deps, head)
|
|
card = next((c for c in _conversation_cards(deps, False) if c.get("sessionId") == head), None)
|
|
cmeta = (card or {}).get("meta") or {}
|
|
meta = deps.meta_store.peek(sid) or {}
|
|
if not access.visible(deps, caller, sid) \
|
|
or not _mine(caller, meta, cmeta.get("account") or meta.get("account")) \
|
|
or not access.can_send(deps, caller, sid, stop=True):
|
|
return gone
|
|
state = cmeta.get("state")
|
|
if state != "running" and not liveruns.alive(sid):
|
|
return _error(409, "not running", "not_running")
|
|
try:
|
|
out = stop_run(deps, sid)
|
|
except HTTPException as e:
|
|
msg, kind = _detail(e)
|
|
return _error(e.status_code if e.status_code >= 400 else 502, msg, kind)
|
|
return {"ok": True, "sessionId": sid,
|
|
"conversationId": _conv_ids_by_session(deps).get(head) or hit[0],
|
|
**{k: v for k, v in out.items() if k == "note"}}
|
|
|
|
return await run_in_threadpool(_go)
|