# Conflicts: # backend/plugins/carryover.py # backend/plugins/hubruns.py # backend/plugins/manifest.py # backend/plugins/routes.py
1100 lines
45 KiB
Python
1100 lines
45 KiB
Python
"""``/proxy/tools/plugins/{pid}/*`` — bearer-authenticated runtime endpoints for
|
||
skills, scheduled jobs, sandboxed actions, paired computers, v2 inbound
|
||
webhooks, and hub capability bridges (``conversations.read``, ``goals.read``,
|
||
``goals.work``, ``notify.send``).
|
||
|
||
Mounted under ``/proxy/tools/`` so it works out of the box on BOTH
|
||
``ai-agent.lab.gabvdl.xyz`` and ``ai-agent.gabvdl.xyz`` with the existing
|
||
Traefik routers and ``hubclient.py``!
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import datetime as dt
|
||
import os
|
||
import pathlib
|
||
import re
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Request
|
||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||
from starlette.background import BackgroundTask
|
||
from starlette.concurrency import run_in_threadpool
|
||
|
||
from plugins import banner, machine_attention, machine_wake, metering
|
||
from plugins.proxy import (ProxyError, candidate_for, forward, limited, match_rule, open_stream,
|
||
rule_handler_only)
|
||
from plugins.runner import ActionError, requester_context, run_script
|
||
from plugins.store import OWNER_UID
|
||
from toolproxy import access
|
||
from toolproxy.ledger import LEDGER
|
||
from users.caller import on_public_surface
|
||
from workers import guests
|
||
|
||
router = APIRouter()
|
||
|
||
_TMPL_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}")
|
||
|
||
|
||
def _error(status: int, message: str, kind: str = "error") -> JSONResponse:
|
||
return JSONResponse({"error": {"message": message, "kind": kind}}, status_code=status)
|
||
|
||
|
||
def _bearer(request: Request) -> str:
|
||
auth = request.headers.get("authorization") or ""
|
||
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
|
||
|
||
|
||
def _http():
|
||
from toolproxy.routes import _http as shared
|
||
return shared()
|
||
|
||
|
||
MAX_PLUGIN_CALL_DEPTH = 4
|
||
|
||
|
||
def _who(request: Request, pid: str | None = None, *, allow_cross_plugin: bool = False):
|
||
"""The caller a bearer names. A plugin handler's own token (``aiah1``) is
|
||
honoured here only, and normally only for the plugin it was minted for;
|
||
when ``allow_cross_plugin`` is True, a handler of plugin A may call an
|
||
exported action of plugin B if A declares ``requires: [B]``."""
|
||
if guests.ip_locked(request):
|
||
return None, _error(429, "too many bad tokens from this address", "locked")
|
||
deps = request.app.state.ai
|
||
who = access.resolve(deps, _bearer(request), guest_surface=on_public_surface(request),
|
||
allow_handler=True)
|
||
if who is None:
|
||
guests.bad_token(deps, request, "/proxy/tools/plugins")
|
||
return None, _error(401, "unknown or expired tool token", "auth")
|
||
if who.handler and who.handler != pid and not allow_cross_plugin:
|
||
return None, _error(403, "this handler token is for another plugin", "auth")
|
||
return who, None
|
||
|
||
|
||
def _active_plugin(deps, who, pid: str):
|
||
uid = OWNER_UID if who.is_owner else who.uid
|
||
rec, grant, is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
|
||
if not rec:
|
||
return uid, None, None, False, _error(404, f"plugin '{pid}' is not active for this user", "not_installed")
|
||
return uid, rec, grant, is_managed, None
|
||
|
||
|
||
def _render_fields(tmpl: str, data: dict[str, Any]) -> str:
|
||
def repl(m: re.Match) -> str:
|
||
cur: Any = data
|
||
for part in m.group(1).split("."):
|
||
if isinstance(cur, dict) and part in cur:
|
||
cur = cur[part]
|
||
else:
|
||
return ""
|
||
return str(cur)
|
||
return _TMPL_RE.sub(repl, tmpl)
|
||
|
||
|
||
# ── allowlisted outbound HTTP proxy ──────────────────────────────────────────
|
||
def _owned_ok(deps, uid: str, pid: str, rule: dict[str, Any], path: str) -> bool:
|
||
"""A guest's call on an ``owned`` rule: the path's named group must be in
|
||
``json(<their data dir>/<file>)[key]`` (a ``_private/`` file only the
|
||
plugin's handlers write)."""
|
||
ow = rule.get("owned")
|
||
if not ow:
|
||
return True
|
||
try:
|
||
m = re.fullmatch(rule["path"], path.lstrip("/"))
|
||
val = m.group(ow["group"]) if m else None
|
||
if not val:
|
||
return False
|
||
target = deps.plugin_store.resolve_data_file(uid, pid, ow["file"])
|
||
import json as _json
|
||
data = _json.loads(target.read_text()) if target.is_file() else {}
|
||
coll = data.get(ow["key"]) if isinstance(data, dict) else None
|
||
if isinstance(coll, (dict, list)):
|
||
return val in coll
|
||
except (ValueError, OSError, IndexError, re.error):
|
||
return False
|
||
return False
|
||
|
||
|
||
def _form_params(request: Request, body: bytes | None) -> dict[str, str]:
|
||
from urllib.parse import parse_qsl
|
||
out = dict(request.query_params)
|
||
ct = (request.headers.get("content-type") or "").lower()
|
||
if body and "application/x-www-form-urlencoded" in ct:
|
||
try:
|
||
for k, v in parse_qsl(body.decode("utf-8"), keep_blank_values=True):
|
||
out.setdefault(k, v)
|
||
except UnicodeDecodeError:
|
||
pass
|
||
return out
|
||
|
||
|
||
# ── allowlisted outbound HTTP proxy ──────────────────────────────────────────
|
||
# Out of the OpenAPI spec: plugin scripts call it, never the frontend, and its
|
||
# six methods would share one operation id (orval then emits duplicates).
|
||
@router.api_route("/proxy/tools/plugins/{pid}/proxy/{path:path}",
|
||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"],
|
||
include_in_schema=False)
|
||
async def plugin_proxy_call(pid: str, path: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, rec, grant, is_managed, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
|
||
# Optional owner override (`X-Plugin-As: <guest>`) for operator runs reading
|
||
# a guest's personal plugin (e.g. `meta --as cel`).
|
||
as_uid = (request.headers.get("x-plugin-as") or "").strip().lower()
|
||
if as_uid and who.is_owner:
|
||
other = deps.plugin_store.get_raw(as_uid, pid)
|
||
if not other or not other.get("enabled"):
|
||
return _error(404, f"plugin '{pid}' not active for '{as_uid}'")
|
||
uid, rec, grant, is_managed = as_uid, other, None, False
|
||
|
||
mf = rec["manifest"]
|
||
pr = mf.get("proxy") or {}
|
||
if not pr:
|
||
return _error(404, "this plugin has no outbound proxy", "plugin_proxy")
|
||
stream = bool(pr.get("stream"))
|
||
has_body = request.method in ("POST", "PUT", "PATCH")
|
||
body = None if (stream or not has_body) else (await request.body() or None)
|
||
|
||
rule = match_rule(pr, request.method, path, _form_params(request, body))
|
||
if rule is None:
|
||
return _error(403, f"plugin proxy refuses {request.method.upper()} /{path.lstrip('/')}",
|
||
"plugin_proxy")
|
||
handler = bool(who.handler)
|
||
if rule_handler_only(pr, rule) and not handler:
|
||
return _error(403, f"{mf.get('name', pid)}: this call is only open to the plugin's own "
|
||
"actions — use its skill", "handler_only")
|
||
if not handler and not who.is_owner and not _owned_ok(deps, uid, pid, rule, path):
|
||
return _error(404, "not found (not one of yours)", "not_owned")
|
||
|
||
# The plugin's own handler: its action already checked the limits, holds
|
||
# the in-flight slot and writes the ledger row (``_meter``).
|
||
using_own = deps.plugin_store.has_user_override_secret(uid, pid, mf) if is_managed else False
|
||
creates = bool(rule.get("creates")) and not handler
|
||
if is_managed and not who.is_owner and not handler:
|
||
no = await run_in_threadpool(
|
||
metering.check_limits, deps, who, pid, mf, grant,
|
||
using_own_secret=using_own, creates=creates,
|
||
)
|
||
if no:
|
||
return _error(no[0], no[1], no[2])
|
||
|
||
q = list(request.query_params.multi_items())
|
||
trusted = handler or who.is_owner
|
||
units = dict(rule.get("units") or {"calls": 1})
|
||
|
||
def _record(ok: bool) -> None:
|
||
if handler:
|
||
return
|
||
if ok and creates:
|
||
metering.count_job(who.key, pid)
|
||
sid = access.session_of(deps, who, request.headers.get("x-claude-code-session-id"))
|
||
LEDGER.record({
|
||
"tool": f"plugin:{pid}", **who.row(),
|
||
"usd": 0, "units": units if ok else {"calls": 1},
|
||
"op": f"{request.method} /{path[:80]}",
|
||
**({"session": sid} if sid else {}),
|
||
})
|
||
|
||
if not handler:
|
||
metering.enter(who.key, pid)
|
||
|
||
def _leave() -> None:
|
||
if not handler:
|
||
metering.leave(who.key, pid)
|
||
|
||
# Streaming mode for large binary uploads/downloads (e.g. 3d-render, video-extract)
|
||
if stream:
|
||
try:
|
||
resp, headers, _scrub_vals, _scrub = await open_stream(
|
||
_http(), deps, deps.plugin_store, uid, rec,
|
||
method=request.method,
|
||
rel_path=path,
|
||
query_params=q,
|
||
req_headers=dict(request.headers),
|
||
body_iter=request.stream() if has_body else None,
|
||
rule=rule, trusted=trusted,
|
||
)
|
||
except ProxyError as e:
|
||
_leave()
|
||
return _error(e.status, e.message, e.kind)
|
||
|
||
_record(resp.status_code < 400)
|
||
max_bytes = int(pr.get("maxBytes") or 20 * 1024 * 1024)
|
||
|
||
async def _done():
|
||
await resp.aclose()
|
||
_leave()
|
||
|
||
return StreamingResponse(
|
||
limited(resp.aiter_raw(), max_bytes),
|
||
status_code=resp.status_code,
|
||
headers=headers,
|
||
background=BackgroundTask(_done),
|
||
)
|
||
|
||
# A key being checked before it is saved: only that run's handler token
|
||
# carries one (``plugins.proxy.register_candidate``).
|
||
candidate = candidate_for(_bearer(request)) if handler else None
|
||
try:
|
||
status, headers, raw = await forward(
|
||
_http(), deps, deps.plugin_store, uid, rec,
|
||
method=request.method,
|
||
rel_path=path,
|
||
query_params=q,
|
||
req_headers=dict(request.headers),
|
||
body=body,
|
||
rule=rule, trusted=trusted,
|
||
override_secret=candidate,
|
||
)
|
||
except ProxyError as e:
|
||
return _error(e.status, e.message, e.kind)
|
||
finally:
|
||
_leave()
|
||
|
||
_record(status < 400)
|
||
return Response(content=raw, status_code=status, headers=headers)
|
||
|
||
|
||
# ── per-user plugin storage ──────────────────────────────────────────────────
|
||
def _private(path: str) -> bool:
|
||
parts = [p for p in (path or "").replace("\\", "/").split("/") if p and p != "."]
|
||
return bool(parts) and parts[0] == "_private"
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/data")
|
||
async def plugin_data_list(pid: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, _rec, _g, _m, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
as_uid = (request.headers.get("x-plugin-as") or "").strip().lower()
|
||
if as_uid and who.is_owner:
|
||
uid = as_uid
|
||
base = deps.plugin_store.user_data_dir(uid, pid)
|
||
files = []
|
||
for root, _, names in os.walk(base):
|
||
for fn in sorted(names):
|
||
full = os.path.join(root, fn)
|
||
rel = os.path.relpath(full, base).replace(os.sep, "/")
|
||
try:
|
||
st = os.stat(full)
|
||
files.append({"path": rel, "size": st.st_size, "mtime": int(st.st_mtime)})
|
||
except OSError:
|
||
pass
|
||
return {"files": sorted(files, key=lambda x: x["path"])}
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/data/{path:path}")
|
||
async def plugin_data_get(pid: str, path: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, _, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
as_uid = (request.headers.get("x-plugin-as") or "").strip().lower()
|
||
if as_uid and who.is_owner:
|
||
uid = as_uid
|
||
try:
|
||
target = deps.plugin_store.resolve_data_file(uid, pid, path)
|
||
except ValueError as e:
|
||
return _error(400, str(e))
|
||
if not target.is_file():
|
||
return _error(404, "file not found")
|
||
return Response(content=target.read_bytes(), media_type="application/octet-stream")
|
||
|
||
|
||
@router.put("/proxy/tools/plugins/{pid}/data/{path:path}")
|
||
async def plugin_data_put(pid: str, path: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
body = await request.body()
|
||
max_bytes = int(((rec["manifest"].get("storage") or {}).get("maxMb") or 50)) * 1024 * 1024
|
||
if _private(path) and not who.handler:
|
||
return _error(403, "_private/ is written by the plugin's own actions only", "private")
|
||
try:
|
||
target = deps.plugin_store.resolve_data_file(uid, pid, path)
|
||
except ValueError as e:
|
||
return _error(400, str(e))
|
||
existing = target.stat().st_size if target.is_file() else 0
|
||
if deps.plugin_store.data_usage_bytes(uid, pid) - existing + len(body) > max_bytes:
|
||
return _error(413, "plugin storage quota exceeded", "quota")
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
tmp = target.with_suffix(target.suffix + ".tmp")
|
||
tmp.write_bytes(body)
|
||
os.replace(tmp, target)
|
||
return {"ok": True, "path": path, "size": len(body)}
|
||
|
||
|
||
@router.delete("/proxy/tools/plugins/{pid}/data/{path:path}")
|
||
async def plugin_data_delete(pid: str, path: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, _, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if _private(path) and not who.handler:
|
||
return _error(403, "_private/ is written by the plugin's own actions only", "private")
|
||
try:
|
||
target = deps.plugin_store.resolve_data_file(uid, pid, path)
|
||
except ValueError as e:
|
||
return _error(400, str(e))
|
||
if not target.is_file():
|
||
return _error(404, "file not found")
|
||
target.unlink()
|
||
return {"ok": True}
|
||
|
||
|
||
# ── config, status & v3 actions ──────────────────────────────────────────────
|
||
@router.get("/proxy/tools/plugins/{pid}/config")
|
||
async def plugin_config_get(pid: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, rec, grant, is_managed, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
mf = rec["manifest"]
|
||
out: dict[str, Any] = {"config": rec.get("config") or {}, "id": pid, "managed": is_managed}
|
||
if is_managed:
|
||
using_own = deps.plugin_store.has_user_override_secret(uid, pid, mf)
|
||
out["grant"] = {
|
||
**dict((grant or {}).get("config") or {}),
|
||
"monthlyBudgetUsd": (grant or {}).get("monthlyBudgetUsd"),
|
||
"usingOwnSecret": using_own,
|
||
}
|
||
out["usage"] = metering.plugin_usage_by_who(who.key, pid)
|
||
return out
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/actions/{action}")
|
||
async def plugin_proxy_action(pid: str, action: str, request: Request):
|
||
who, err = _who(request, pid, allow_cross_plugin=True)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, rec, grant, is_managed, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
mf = rec["manifest"]
|
||
act = (mf.get("actions") or {}).get(action)
|
||
if not act:
|
||
return _error(404, f"action '{action}' not declared")
|
||
if act.get("ownerOnly") and not who.is_owner:
|
||
return _error(403, f"action '{action}' is owner-only", "capability")
|
||
|
||
caller_plugin: str | None = None
|
||
call_depth = 0
|
||
if who.handler and who.handler != pid:
|
||
# Cross-plugin call: caller plugin must be active for uid, declare
|
||
# ``pid`` in ``requires``, and target must declare ``action`` in ``exports``.
|
||
caller_rec, _cg, _cm = deps.plugin_store.resolve_active_for_caller(uid, who.handler)
|
||
if not caller_rec:
|
||
return _error(403, f"caller plugin '{who.handler}' is not active", "auth")
|
||
if pid not in ((caller_rec.get("manifest") or {}).get("requires") or []):
|
||
return _error(403, f"plugin '{who.handler}' does not require '{pid}'", "requires")
|
||
if action not in (mf.get("exports") or []):
|
||
return _error(403, f"plugin '{pid}' does not export action '{action}'", "exports")
|
||
try:
|
||
call_depth = int(request.headers.get("x-plugin-call-depth") or "0") + 1
|
||
except ValueError:
|
||
call_depth = 1
|
||
if call_depth > MAX_PLUGIN_CALL_DEPTH:
|
||
return _error(508, f"plugin call depth exceeded ({MAX_PLUGIN_CALL_DEPTH})", "loop")
|
||
caller_plugin = who.handler
|
||
|
||
try:
|
||
payload = await request.json()
|
||
except Exception:
|
||
payload = {}
|
||
if not isinstance(payload, dict):
|
||
payload = {}
|
||
|
||
using_own = deps.plugin_store.has_user_override_secret(uid, pid, mf) if is_managed else False
|
||
if is_managed and not who.is_owner:
|
||
no = await run_in_threadpool(
|
||
metering.check_limits, deps, who, pid, mf, grant,
|
||
using_own_secret=using_own,
|
||
creates=bool(payload.get("_creates") or action in ("create", "run", "generate", "request")),
|
||
)
|
||
if no:
|
||
return _error(no[0], no[1], no[2])
|
||
|
||
run_uid = uid
|
||
session_id = access.session_of(deps, who, request.headers.get("x-claude-code-session-id"))
|
||
requester_ctx: dict[str, Any] | None = None
|
||
if act.get("runAs") == "owner" and is_managed and not who.is_owner:
|
||
# Owner-managed plugin action running with owner hub context while
|
||
# preserving who initiated it (and from which conversation) in
|
||
# ``AIA_USER_CONTEXT.requester``.
|
||
requester_ctx = requester_context(deps, uid, grant, session_id)
|
||
run_uid = OWNER_UID
|
||
|
||
metering.enter(who.key, pid)
|
||
try:
|
||
res = await run_in_threadpool(
|
||
run_script, deps, deps.plugin_store, run_uid, rec, act["script"],
|
||
payload=payload,
|
||
timeout_sec=int(act.get("timeoutSec") or 30),
|
||
grant=grant,
|
||
using_own_secret=using_own,
|
||
session_id=session_id,
|
||
call_depth=call_depth,
|
||
caller_plugin=caller_plugin,
|
||
requester=requester_ctx,
|
||
)
|
||
except ActionError as e:
|
||
return _error(e.status, e.message, e.kind)
|
||
finally:
|
||
metering.leave(who.key, pid)
|
||
banner.touched(deps, rec)
|
||
machine_attention.touched(deps, rec, action=action)
|
||
machine_wake.touched(deps, rec, action=action)
|
||
|
||
# Extract optional `_meter` envelope returned by the action handler
|
||
if isinstance(res, dict) and isinstance(res.get("_meter"), dict):
|
||
meter = res.pop("_meter")
|
||
await run_in_threadpool(
|
||
metering.apply_meter, deps, who, pid, mf, meter,
|
||
session_header=request.headers.get("x-claude-code-session-id"),
|
||
using_own_secret=using_own,
|
||
)
|
||
return res
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/hub/emit")
|
||
async def plugin_hub_emit(pid: str, request: Request):
|
||
"""Emit a declared plugin event (``emits[]``) to every enabled plugin
|
||
subscribing to ``plugin:<pid>:<event>`` (and declaring ``requires: [pid]``).
|
||
Only the plugin's own handler token may emit its events."""
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
if who.handler != pid:
|
||
return _error(403, "only the plugin's own handlers may emit plugin events", "handler_only")
|
||
deps = request.app.state.ai
|
||
uid, rec, _, is_managed, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
body = {}
|
||
if not isinstance(body, dict) or not isinstance(body.get("event"), str):
|
||
return _error(400, "event name is required")
|
||
ev_name = body["event"].strip()
|
||
if ev_name not in ((rec.get("manifest") or {}).get("emits") or []):
|
||
return _error(403, f"plugin '{pid}' does not declare event '{ev_name}' in emits", "emits")
|
||
payload = body.get("payload") if isinstance(body.get("payload"), dict) else {}
|
||
target_uid = OWNER_UID if is_managed else uid
|
||
from plugins.scheduler import dispatch_event
|
||
dispatch_event(deps, f"plugin:{pid}:{ev_name}", payload,
|
||
owner_uid=target_uid, source_plugin=pid)
|
||
return {"ok": True, "event": f"plugin:{pid}:{ev_name}"}
|
||
|
||
|
||
# ── hub capability bridges (conversations.read, goals.read/work, graph.read, footprint.read, telemetry.read, analytics.read, activity.read, usage.read/calibrate, notify.send) ─
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/conversations")
|
||
async def plugin_hub_conversations(pid: str, request: Request, days: float = 30.0,
|
||
limit: int = 200, sids: str = "", metrics: bool = False,
|
||
memories: bool = False, memory: str = ""):
|
||
"""The caller's conversations that ended in the last ``days`` (newest
|
||
first), or the specific comma-separated ``sids`` when given. With
|
||
``metrics=1``, also returns ``tokens``, ``costUsd`` and ``durationMs``;
|
||
with ``memories=1``, ``memoriesRead`` (the memory slugs recalled into it)
|
||
and ``model``. ``memory=<slug>`` returns, from the whole archive (no
|
||
``days`` window), the conversations that read that memory."""
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if "conversations.read" not in (rec["manifest"].get("capabilities") or []):
|
||
return _error(403, "plugin lacks conversations.read capability", "capability")
|
||
want_sids = {x.strip() for x in (sids or "").split(",") if x.strip()}
|
||
want_mem = (memory or "").strip()
|
||
since = "" if (want_sids or want_mem) else (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=max(1.0, min(365.0, days)))).strftime("%Y-%m-%dT%H:%M:%S")
|
||
cap = max(1, min(2000, int(limit)))
|
||
|
||
def _collect():
|
||
rows = []
|
||
for path, s in deps.store.all_summaries():
|
||
sid = s.get("sessionId")
|
||
if not sid:
|
||
continue
|
||
if want_sids:
|
||
if sid not in want_sids:
|
||
continue
|
||
elif since and (s.get("endedAt") or "") < since:
|
||
continue
|
||
if want_mem and want_mem not in (s.get("memoriesRead") or []):
|
||
continue
|
||
m = deps.meta_store.peek(sid) or {}
|
||
owner = m.get("owner")
|
||
if who.is_owner:
|
||
if owner:
|
||
continue
|
||
else:
|
||
if owner != who.uid:
|
||
continue
|
||
row = _conv_row(path, s, m)
|
||
if metrics:
|
||
row["tokens"] = int(s.get("totalTokens") or s.get("tokens") or 0)
|
||
row["costUsd"] = float(s.get("costUsd") or s.get("cost") or 0.0)
|
||
row["durationMs"] = int(s.get("durationMs") or s.get("workingMs") or 0)
|
||
if memories or want_mem:
|
||
row["memoriesRead"] = [x for x in (s.get("memoriesRead") or []) if isinstance(x, str)]
|
||
row["model"] = (s.get("models") or [None])[0] or s.get("model") or None
|
||
rows.append(row)
|
||
rows.sort(key=lambda r: r.get("endedAt") or "", reverse=True)
|
||
return {"conversations": rows[:cap]}
|
||
|
||
return await run_in_threadpool(_collect)
|
||
|
||
|
||
def _conv_id(path: str, sid: str) -> str:
|
||
"""The conversation's UUIDv7 (what ``/conversation/<id>`` takes)."""
|
||
try:
|
||
from conversations import ids
|
||
return ids.uid_for_path(path)
|
||
except Exception: # noqa: BLE001 — no registry (tests): the session id opens it too
|
||
return sid
|
||
|
||
|
||
def _conv_row(path: str, s: dict, m: dict) -> dict:
|
||
sid = s.get("sessionId")
|
||
return {
|
||
"id": _conv_id(path, sid),
|
||
"sessionId": sid,
|
||
"title": m.get("title") or s.get("title") or "",
|
||
"startedAt": s.get("startedAt"),
|
||
"endedAt": s.get("endedAt"),
|
||
"state": m.get("state") or ("finished" if s.get("turnEnded") else "idle"),
|
||
"projects": list(m.get("projects") or s.get("projectsAuto") or [])[:4],
|
||
"isSidechain": bool(s.get("isSidechain")),
|
||
"archived": bool(m.get("archived")),
|
||
"userTurns": int(s.get("userTurns") or 0),
|
||
"turnEnded": bool(s.get("turnEnded")),
|
||
"cron": bool(m.get("cron")),
|
||
"agentRun": bool(m.get("agentRun")),
|
||
"test": bool(m.get("test")),
|
||
"spawnedBy": bool(m.get("spawnedBy")),
|
||
# The machine it runs on ("local" = the lab): Approvals refuses a
|
||
# request from a worker, its approved run being the lab's.
|
||
"worker": m.get("worker") or "local",
|
||
# What it runs on (the handoff plugin's links and its warm path).
|
||
"model": s.get("contextModel") or s.get("model"),
|
||
"harness": m.get("harness") or s.get("harness") or "claude",
|
||
}
|
||
|
||
|
||
def _last_answer(path: pathlib.Path) -> str:
|
||
"""A run's answer, whole — not the 8,000 chars its thread item ships
|
||
(``ParserState._set_clipped``)."""
|
||
import conversations
|
||
st = conversations.ParserState(path, full=True)
|
||
conversations.feed_lines(st, path, 0)
|
||
return st.last_answer()
|
||
|
||
|
||
def final_answer(thread: list[dict]) -> str:
|
||
"""The last assistant text of a parsed thread (the CLI's ``final_answer``)."""
|
||
for it in reversed(thread or []):
|
||
if it.get("role") == "assistant" and it.get("kind") == "text" and (it.get("text") or "").strip():
|
||
return str(it["text"]).strip()
|
||
return ""
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/conversations/{sid}")
|
||
async def plugin_hub_conversation_one(pid: str, sid: str, request: Request):
|
||
"""One conversation of the caller's, with its final answer (the newest
|
||
transcript of the session — a resumed one may have several)."""
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
_, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if "conversations.read" not in (rec["manifest"].get("capabilities") or []):
|
||
return _error(403, "plugin lacks conversations.read capability", "capability")
|
||
|
||
def _read():
|
||
best = None
|
||
for path, s in deps.store.all_summaries():
|
||
if s.get("sessionId") != sid or s.get("isSidechain"):
|
||
continue
|
||
if best is None or (s.get("endedAt") or "") > (best[1].get("endedAt") or ""):
|
||
best = (path, s)
|
||
if best is None:
|
||
return None
|
||
path, s = best
|
||
m = deps.meta_store.peek(sid) or {}
|
||
if not who.is_owner and m.get("owner") != who.uid:
|
||
return None
|
||
return {**_conv_row(path, s, m), "finalAnswer": _last_answer(pathlib.Path(path))[:32000]}
|
||
|
||
out = await run_in_threadpool(_read)
|
||
if out is None:
|
||
return _error(404, "conversation not found")
|
||
return out
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/goals")
|
||
async def plugin_hub_goals(pid: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
if not who.is_owner:
|
||
return _error(403, "goals.read is owner-only", "capability")
|
||
deps = request.app.state.ai
|
||
_, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if "goals.read" not in (rec["manifest"].get("capabilities") or []):
|
||
return _error(403, "plugin lacks goals.read capability", "capability")
|
||
|
||
def _load_goals():
|
||
from goals.routes import goals_list
|
||
return goals_list(deps)
|
||
|
||
return await run_in_threadpool(_load_goals)
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/graph")
|
||
async def plugin_hub_graph(pid: str, request: Request):
|
||
"""``graph.read``: projects, services, conversations, plans, memories and
|
||
subagents as the Graph plugin draws them (``plugins/graphdata.py``)."""
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
if not who.is_owner:
|
||
return _error(403, "graph.read is owner-only", "capability")
|
||
deps = request.app.state.ai
|
||
_, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if "graph.read" not in (rec["manifest"].get("capabilities") or []):
|
||
return _error(403, "plugin lacks graph.read capability", "capability")
|
||
from plugins import graphdata
|
||
out = await run_in_threadpool(graphdata.build, deps)
|
||
return JSONResponse(out)
|
||
|
||
|
||
def _owner_bridge(request: Request, pid: str, cap: str):
|
||
"""(deps, None) for the owner's active plugin holding ``cap``, else
|
||
(None, an error response)."""
|
||
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")
|
||
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
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/footprint")
|
||
async def plugin_hub_footprint(pid: str, request: Request, account: str = "", range: str = "sub"):
|
||
"""``footprint.read``: each conversation's estimated carbon, water and
|
||
energy in a profile scope and date range (``plugins/footprintdata.py``)."""
|
||
deps, err = _owner_bridge(request, pid, "footprint.read")
|
||
if err:
|
||
return err
|
||
from plugins import footprintdata
|
||
out = await run_in_threadpool(footprintdata.build, deps, account, range)
|
||
return JSONResponse(out)
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/telemetry/usage")
|
||
async def plugin_hub_telemetry_usage(pid: str, request: Request, range: str = "30d", who: str = "all"):
|
||
"""``telemetry.read``: ``/api/telemetry/usage``'s answer (which features
|
||
were used, by whom, on what device; What's new seen; where conversations
|
||
started) plus ``registry``, the app's feature registry
|
||
(``telemetry/features.json``, generated from lib/telemetry/features.ts)."""
|
||
deps, err = _owner_bridge(request, pid, "telemetry.read")
|
||
if err:
|
||
return err
|
||
from telemetry import views
|
||
if range not in views.USAGE_RANGES:
|
||
return _error(400, f"range must be one of {', '.join(views.USAGE_RANGES)}", "range")
|
||
|
||
def _build():
|
||
out = views.usage(deps, range, who)
|
||
out["registry"] = views.registry()
|
||
return out
|
||
return JSONResponse(await run_in_threadpool(_build))
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/analytics")
|
||
async def plugin_hub_analytics(pid: str, request: Request, account: str = "", range: str = "30d",
|
||
tzOffset: int = 0, cron: bool = False):
|
||
"""``analytics.read``: each top-level conversation's start, working time,
|
||
turns and breakdown keys in a profile scope and range — usage, never cost
|
||
(``plugins/analyticsdata.py``)."""
|
||
deps, err = _owner_bridge(request, pid, "analytics.read")
|
||
if err:
|
||
return err
|
||
from plugins import analyticsdata
|
||
out = await run_in_threadpool(analyticsdata.build, deps, account, range,
|
||
max(-840, min(840, int(tzOffset))), bool(cron))
|
||
return JSONResponse(out)
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/activity")
|
||
async def plugin_hub_activity(pid: str, request: Request, account: str = "", tzOffset: int = 0):
|
||
"""``activity.read``: the Activity rollup — per local day, per 5-minute
|
||
bin per model (distinct agents working), per model (runs, active time,
|
||
tokens, cost) — in a profile scope, plus the scope switch's ``profiles``
|
||
(``plugins/activitydata.py``). Owner only."""
|
||
deps, err = _owner_bridge(request, pid, "activity.read")
|
||
if err:
|
||
return err
|
||
from plugins import activitydata
|
||
out = await run_in_threadpool(activitydata.build, deps, account or None,
|
||
max(-960, min(960, int(tzOffset))))
|
||
return JSONResponse(out)
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/usage/overview")
|
||
async def plugin_hub_usage_overview(pid: str, request: Request, scope: str = "", days: int = 14):
|
||
"""``usage.read``: one scope's Plan usage — the accounts it shows (with
|
||
their Settings → Logins subscription), each one's ``/api/usage/limits``
|
||
entry, ``history`` over ``days``, ``plans`` and ``calibration``, and the
|
||
scope switch's ``profiles`` (``plugins/usagedata.py``). Owner only."""
|
||
deps, err = _owner_bridge(request, pid, "usage.read")
|
||
if err:
|
||
return err
|
||
from plugins import usagedata
|
||
out = await run_in_threadpool(usagedata.overview, deps, scope, max(1, min(120, int(days))))
|
||
return JSONResponse(out)
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/usage/home")
|
||
async def plugin_hub_usage_home(pid: str, request: Request, profileScope: str = "",
|
||
composerHarness: str = ""):
|
||
"""``usage.read``: what the home usage strip draws — ``limits`` (as
|
||
``GET /api/usage/limits``), ``burn`` (as ``GET /api/usage/burn``), the
|
||
``accounts`` list (``GET /api/accounts``) and the ``profiles``
|
||
(``GET /api/profiles``); a ``home.tiles`` action turns it into tiles.
|
||
``profileScope`` / ``composerHarness`` are echoed back for the handler.
|
||
Owner only."""
|
||
deps, err = _owner_bridge(request, pid, "usage.read")
|
||
if err:
|
||
return err
|
||
|
||
def _build():
|
||
from accounts.routes import list_accounts
|
||
from profiles.routes import _payload as profiles_payload
|
||
from usage.routes import burn_payload, limits_payload
|
||
accts = list_accounts(deps)
|
||
return {
|
||
"limits": limits_payload(deps),
|
||
"burn": burn_payload(deps),
|
||
"accounts": (accts or {}).get("accounts") or [],
|
||
"profiles": (profiles_payload(deps) or {}).get("profiles") or [],
|
||
"profileScope": profileScope[:120],
|
||
"composerHarness": composerHarness[:40],
|
||
}
|
||
|
||
return JSONResponse(await run_in_threadpool(_build))
|
||
|
||
|
||
@router.get("/proxy/tools/plugins/{pid}/hub/activity/daily")
|
||
async def plugin_hub_activity_daily(pid: str, request: Request, days: int = 7, scope: str = "",
|
||
tzOffset: int = 0):
|
||
"""``activity.read``: the last ``days`` local days ``{date, cost, tokens,
|
||
conversations}`` in the ``scope`` profile scope — ``GET /api/usage/daily``'s
|
||
body. Owner only."""
|
||
deps, err = _owner_bridge(request, pid, "activity.read")
|
||
if err:
|
||
return err
|
||
from usage.routes import daily_usage
|
||
out = await run_in_threadpool(daily_usage, deps, max(1, min(90, int(days))),
|
||
max(-960, min(960, int(tzOffset))), scope or None)
|
||
return JSONResponse(out)
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/hub/usage/calibrate")
|
||
async def plugin_hub_usage_calibrate(pid: str, request: Request):
|
||
"""``usage.calibrate``: fit every account now, as ``POST
|
||
/api/usage/calibrate`` (``{backfill}``: the weekly fits over the whole
|
||
history first). Owner only."""
|
||
deps, err = _owner_bridge(request, pid, "usage.calibrate")
|
||
if err:
|
||
return err
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
body = {}
|
||
backfill = bool((body or {}).get("backfill")) if isinstance(body, dict) else False
|
||
from plugins import usagedata
|
||
return JSONResponse(await run_in_threadpool(usagedata.calibrate_now, deps, backfill))
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/hub/goals/work")
|
||
async def plugin_hub_goals_work(pid: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
if not who.is_owner:
|
||
return _error(403, "goals.work is owner-only", "capability")
|
||
deps = request.app.state.ai
|
||
_, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
caps = set(rec["manifest"].get("capabilities") or [])
|
||
if "goals.work" not in caps:
|
||
return _error(403, "plugin lacks goals.work capability", "capability")
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
body = {}
|
||
|
||
def _work():
|
||
from goals.routes import GoalWorkBody, goal_work
|
||
return goal_work(deps, GoalWorkBody(**(body or {})))
|
||
|
||
try:
|
||
return await run_in_threadpool(_work)
|
||
except Exception as e:
|
||
from fastapi import HTTPException
|
||
if isinstance(e, HTTPException):
|
||
d = e.detail
|
||
msg = d.get("message") if isinstance(d, dict) else str(d)
|
||
kind = d.get("kind") if isinstance(d, dict) else "goals"
|
||
return _error(e.status_code, str(msg), str(kind or "goals"))
|
||
return _error(400, str(e))
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/hub/notify")
|
||
async def plugin_hub_notify(pid: str, request: Request):
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, rec, _, is_managed, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if "notify.send" not in (rec["manifest"].get("capabilities") or []):
|
||
return _error(403, "plugin lacks notify.send capability", "capability")
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
body = {}
|
||
if not isinstance(body, dict) or not body.get("title"):
|
||
return _error(400, "title is required")
|
||
target = body.get("to")
|
||
# Non-owners may only notify themselves or the owner (e.g. movie request alert)
|
||
if not who.is_owner and target not in (None, "owner", who.uid):
|
||
target = who.uid
|
||
to_uid = None if target in (None, "owner") else str(target)
|
||
# A conversation to push in: its audience hears it, threaded there. A
|
||
# guest may only name their own conversations (access.session_of).
|
||
sid = access.session_of(deps, who, str(body.get("session") or "")) if body.get("session") else None
|
||
if body.get("session") and not sid:
|
||
return _error(403, "that conversation isn't yours", "session")
|
||
i18n = None
|
||
if isinstance(body.get("i18n"), dict):
|
||
i18n = {}
|
||
for lang, v in list(body["i18n"].items())[:4]:
|
||
if isinstance(v, dict) and str(lang) in ("en", "fr"):
|
||
i18n[str(lang)] = {"title": str(v.get("title") or "")[:120],
|
||
"message": str(v.get("message") or "")[:500]}
|
||
owner_only = bool(body.get("ownerOnly"))
|
||
url = str(body.get("url") or "")[:300]
|
||
if url.startswith("/") and not url.startswith("//"):
|
||
# an app path: the viewer's address in front (a push is opened from
|
||
# the phone, outside the app)
|
||
from notifications.service import VIEW_URL
|
||
url = f"{VIEW_URL}{url}"[:600]
|
||
d: dict[str, Any] = {
|
||
"title": str(body["title"])[:120],
|
||
"message": str(body.get("message") or "")[:500],
|
||
"type": str(body.get("type") or "service")[:24],
|
||
"url": url,
|
||
}
|
||
if body.get("spoken"):
|
||
d["spoken"] = str(body["spoken"])[:500]
|
||
# Buttons on the push (≤ 3 titles): a tap comes back to the plugin as the
|
||
# ``notify.action`` event ``{notifyId, index, title}`` (owner's plugins).
|
||
nid = None
|
||
titles = body.get("actions")
|
||
if titles is not None:
|
||
if not isinstance(titles, list) or len(titles) > 3 \
|
||
or not all(isinstance(t, str) and 0 < len(t.strip()) <= 24 for t in titles):
|
||
return _error(400, "actions: up to 3 button titles (1–24 characters)")
|
||
if titles:
|
||
import uuid
|
||
nid = f"ntf_{uuid.uuid4().hex[:12]}"
|
||
d["id"] = nid
|
||
d["actions"] = [{"action": f"{nid}__{i}", "title": t.strip()} for i, t in enumerate(titles)]
|
||
if body.get("tag"):
|
||
d["tag"] = str(body["tag"]).strip()[:120]
|
||
if body.get("pushKind") == "form":
|
||
d["pushKind"] = "form"
|
||
if owner_only:
|
||
from users.caller import OWNER_ID
|
||
d["recipients"] = [OWNER_ID]
|
||
if sid and not d["url"]:
|
||
from notifications.service import _conversation_url
|
||
d["url"] = _conversation_url(deps, sid)
|
||
elif sid:
|
||
d["sessionId"] = sid
|
||
elif to_uid and to_uid != OWNER_UID:
|
||
d["recipients"] = [to_uid]
|
||
if i18n:
|
||
d["i18n"] = i18n
|
||
from notifications.routes import _create_notify
|
||
entry = await run_in_threadpool(_create_notify, deps, d)
|
||
return {"ok": True, "id": (entry or {}).get("id") or nid}
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/hub/changed")
|
||
async def plugin_hub_changed(pid: str, request: Request):
|
||
"""The plugin's data changed (a handler or job wrote it): the app's open
|
||
frames of this plugin read it again — SSE ``{"type": "plugin-data", id}``,
|
||
to its installer only. No capability: it only says *look again*."""
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
deps = request.app.state.ai
|
||
uid, _rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
deps.hub.publish({"type": "plugin-data", "id": pid, "uid": uid})
|
||
return {"ok": True}
|
||
|
||
|
||
@router.post("/proxy/tools/plugins/{pid}/hub/title")
|
||
async def plugin_hub_title(pid: str, request: Request):
|
||
"""``conversations.title`` (owner only): a prompt's title and one
|
||
sentence from the plugin that ``provides: {"conversation.title": …}``
|
||
(plugins/labels_bridge.py) — ``{}`` when there is none or it couldn't
|
||
answer (the caller falls back on the prompt's first words)."""
|
||
who, err = _who(request, pid)
|
||
if err:
|
||
return err
|
||
if not who.is_owner:
|
||
return _error(403, "conversations.title is owner-only", "capability")
|
||
deps = request.app.state.ai
|
||
_uid, rec, _, _, err = _active_plugin(deps, who, pid)
|
||
if err:
|
||
return err
|
||
if "conversations.title" not in (rec["manifest"].get("capabilities") or []):
|
||
return _error(403, "plugin lacks conversations.title capability", "capability")
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
body = {}
|
||
text = str((body or {}).get("text") or "").strip() if isinstance(body, dict) else ""
|
||
if not text:
|
||
return _error(400, "text is required")
|
||
kind = str(body.get("kind") or "scheduled-title")[:40]
|
||
ref = str(body["ref"])[:80] if body.get("ref") else None
|
||
acct = str(body["account"])[:64] if body.get("account") else None
|
||
from plugins import labels_bridge
|
||
ans = await run_in_threadpool(labels_bridge.title, deps, text, kind, ref, acct)
|
||
return ans or {}
|
||
|
||
|
||
# ── v2 inbound webhook ───────────────────────────────────────────────────────
|
||
@router.post("/proxy/tools/plugins/{pid}/webhook/{hook_id}")
|
||
async def plugin_inbound_webhook(pid: str, hook_id: str, request: Request):
|
||
"""Per-install token-authenticated inbound webhook: notifies, spawns a
|
||
conversation (when ``conversations.spawn`` is approved), or runs a v3
|
||
action."""
|
||
token = (request.query_params.get("token")
|
||
or request.headers.get("x-plugin-webhook-token")
|
||
or _bearer(request) or "").strip()
|
||
deps = request.app.state.ai
|
||
hit = deps.plugin_store.find_by_webhook_token(pid, hook_id, token)
|
||
if not hit:
|
||
return _error(401, "invalid webhook token", "auth")
|
||
uid, rec = hit
|
||
mf = rec["manifest"]
|
||
wh = next((w for w in (mf.get("webhooks") or []) if w["id"] == hook_id), None)
|
||
if not wh or (wh.get("internalOnly") and on_public_surface(request)):
|
||
return _error(404, "webhook not declared")
|
||
try:
|
||
body = await request.json()
|
||
except Exception:
|
||
raw = (await request.body()).decode("utf-8", "replace")
|
||
body = {"body": raw}
|
||
if not isinstance(body, dict):
|
||
body = {"body": body}
|
||
try:
|
||
return await _run_webhook(deps, pid, hook_id, uid, rec, mf, wh, body)
|
||
finally:
|
||
banner.touched(deps, rec)
|
||
if uid == OWNER_UID:
|
||
machine_attention.touched(deps, rec)
|
||
machine_wake.touched(deps, rec)
|
||
|
||
|
||
async def _run_webhook(deps, pid: str, hook_id: str, uid: str, rec: dict, mf: dict,
|
||
wh: dict, body: dict):
|
||
mode = wh.get("mode") or "notify"
|
||
if mode == "notify":
|
||
title = _render_fields(wh.get("titleTemplate") or f"{mf['name']}", body) or mf["name"]
|
||
msg = str(body.get("message") or body.get("body") or "Webhook received")[:500]
|
||
from notifications.routes import _create_notify
|
||
_create_notify(deps, {
|
||
"title": title[:120],
|
||
"message": msg,
|
||
"type": "service",
|
||
**({} if uid == OWNER_UID else {"recipients": [uid]}),
|
||
})
|
||
return {"ok": True, "mode": "notify"}
|
||
|
||
if mode == "spawn":
|
||
if "conversations.spawn" not in (mf.get("capabilities") or []):
|
||
return _error(403, "plugin lacks conversations.spawn capability")
|
||
prompt = _render_fields(wh.get("promptTemplate") or "{{body}}", body).strip()
|
||
if not prompt:
|
||
return _error(400, "empty rendered prompt")
|
||
from runs.service import _send_message
|
||
if uid == OWNER_UID:
|
||
out = _send_message(deps, prompt, stamp={"plugin": pid, "origin": "webhook"})
|
||
return {"ok": True, "mode": "spawn", "sessionId": out.get("sessionId")}
|
||
return _error(403, "guest webhook spawn requires explicit project target")
|
||
|
||
if mode == "action":
|
||
act = (mf.get("actions") or {}).get(wh.get("action") or "")
|
||
if not act:
|
||
return _error(404, "webhook action not declared")
|
||
try:
|
||
res = await run_in_threadpool(
|
||
run_script, deps, deps.plugin_store, uid, rec, act["script"],
|
||
payload={"trigger": "webhook", "hookId": hook_id, "body": body},
|
||
timeout_sec=int(act.get("timeoutSec") or 30),
|
||
)
|
||
return {"ok": True, "mode": "action", "result": res}
|
||
except ActionError as e:
|
||
return _error(e.status, e.message, e.kind)
|
||
|
||
return _error(400, f"unsupported webhook mode: {mode}")
|