Files
gabrielvidalandClaude Opus 5.5 61ecbdd993 feat(plugins): handoffs leave the core for the Handoff plugin
The handoff link, the conversation menu's Hand off ▸, HandoffDialog, the
Continued from / Continued in banners and POST /api/handoff move to the
handoff live plugin (ai-agent-plugins). What the core keeps is generic:

- ui.menuItems (conversation.menu): a plugin row in the conversation menu
  opening the plugin's sandboxed dialog; frame bridges close() and toast()
- slot places conversation.threadHeader / conversation.threadEnd, whose
  update carries the plugin's own meta.plugins.<id> (pluginData)
- ConversationDetail.pluginData (owner only)
- conversations.data: GET|POST hub/conversations/{sid}/data, a plugin's
  own data on a conversation (handler only, owner only, operator approval)
- runs.start takes test; hub/conversations rows carry model and harness
- carryover.handoffs moves the old meta.handoffFrom / handoffTo stamps
  into meta.plugins.handoff once

Removed: runs/handoff.py, /api/handoff, SpawnBody.handoffFrom and the
spawn's handoff origin, meta.handoffFrom/handoffTo and their resolved refs,
Handoff.tsx, the Handoffs eye switch (the plugin's vis switch replaces it).
The CLI's --handoff-from and MCP handoff_from are left alone (inert) until
the CLI/MCP plugin-commands mechanism lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:20:16 +01:00

151 lines
5.9 KiB
Python

"""``conversations.data`` — a plugin's own data on a conversation (since
2026-11-26; the handoff plugin's links, which left the core).
Each plugin keeps one JSON object per conversation, ``meta.plugins.<id>`` —
the same key a ``runs.start`` run's ``data`` lands in (plugins/hubruns.py).
The conversation page hands it to the plugin's own thread slots as
``update.pluginData`` (``conversation.threadHeader`` / ``threadEnd`` — the
frontend's ``ConversationThreadSlots``), and ``ConversationDetail.pluginData``
carries every plugin's for the owner.
Owner only, operator approval, the plugin's own handlers only (its rules live
there):
* ``GET …/plugins/{pid}/hub/conversations/{sid}/data`` → ``{sessionId, data}``
(``data`` null when it wrote none);
* ``POST …/plugins/{pid}/hub/conversations/{sid}/data`` ``{"data": {…} | null,
"merge": true}`` → sets it (``merge``: a shallow merge of the top-level keys,
a ``null`` value dropping one; ``data: null`` without merge clears it), then
an SSE ``meta`` for the conversation; answers ``{ok, sessionId, data}``.
``sid`` is a session id or a conversation id (resolved to its session); a
conversation the hub knows neither a transcript nor meta for is 404
``not_found`` — a run just started has its meta from the spawn, so it counts.
A guest's conversation is refused (``capability``), as ``conversations.send``.
"""
from __future__ import annotations
import json
import re
from typing import Any
from fastapi import APIRouter, Request
from starlette.concurrency import run_in_threadpool
from plugins.proxyroutes import _active_plugin, _error, _who
router = APIRouter(include_in_schema=False)
CAP = "conversations.data"
MAX_DATA = 16_000
_SID_RE = re.compile(r"^[A-Za-z0-9-]{8,64}$")
def _bridge(request: Request, pid: str):
"""(rec, error): the plugin's own handler, run for the owner, holding the cap."""
who, err = _who(request, pid)
if err:
return None, err
if who.handler != pid:
return None, _error(403, f"{CAP} is only available to the plugin's own handlers",
"handler_only")
if not who.is_owner:
return None, _error(403, f"{CAP} is owner-only", "capability")
_, rec, _, _, err = _active_plugin(request.app.state.ai, 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 rec, None
def session_of(deps, raw: str) -> str | None:
"""The session id ``raw`` names (a session or a conversation id), when the
hub knows that conversation — a transcript or meta; None otherwise."""
if not _SID_RE.match(raw or ""):
return None
if deps.meta_store.peek(raw):
return raw
from conversations import ids
path = ids.path_of(raw) if ids.is_uid(raw) else None
s = deps.store.get_summary(path) if path else None
if s and s.get("sessionId"):
return s["sessionId"]
from conversations.catalog import _conv_ids_by_session
return raw if raw in _conv_ids_by_session(deps) else None
def merged(cur: dict | None, data: dict | None, merge: bool) -> dict | None:
"""What the plugin's entry becomes: ``data`` over ``cur`` key by key (a
``None`` value drops the key), or ``data`` itself without ``merge``."""
if not merge:
return dict(data) if data else None
out = dict(cur or {})
for k, v in (data or {}).items():
if v is None:
out.pop(k, None)
else:
out[k] = v
return out or None
def write(deps, pid: str, sid: str, data: dict | None, merge: bool = True) -> dict | None:
"""Set ``meta.plugins[pid]`` on ``sid``; the new entry (None = cleared)."""
plugins = dict((deps.meta_store.peek(sid) or {}).get("plugins") or {})
entry = merged(plugins.get(pid), data, merge)
if entry is None:
plugins.pop(pid, None)
else:
plugins[pid] = entry
# ``update`` skips None values: an emptied map is written as {}.
deps.meta_store.update(sid, {"plugins": plugins})
deps.hub.publish({"type": "meta", "id": sid})
return entry
def _target(request: Request, sid: str):
deps = request.app.state.ai
real = session_of(deps, sid)
if not real:
return deps, None, _error(404, "conversation not found", "not_found")
if (deps.meta_store.peek(real) or {}).get("owner"):
return deps, None, _error(403, "a guest's conversation", "capability")
return deps, real, None
@router.get("/proxy/tools/plugins/{pid}/hub/conversations/{sid}/data")
async def plugin_hub_conv_data_get(pid: str, sid: str, request: Request):
_, err = _bridge(request, pid)
if err:
return err
deps, real, err = await run_in_threadpool(_target, request, sid)
if err:
return err
data = ((deps.meta_store.peek(real) or {}).get("plugins") or {}).get(pid)
return {"sessionId": real, "data": data}
@router.post("/proxy/tools/plugins/{pid}/hub/conversations/{sid}/data")
async def plugin_hub_conv_data_set(pid: str, sid: str, request: Request):
_, err = _bridge(request, pid)
if err:
return err
try:
body: Any = await request.json()
except (ValueError, UnicodeDecodeError):
body = None
if not isinstance(body, dict):
return _error(400, "the body is a JSON object {data, merge}", "bad_request")
data = body.get("data")
if data is not None and not isinstance(data, dict):
return _error(400, "data must be a JSON object or null", "bad_request")
if data is not None and len(json.dumps(data)) > MAX_DATA:
return _error(400, f"data must be under {MAX_DATA} bytes", "bad_request")
merge = body.get("merge", True) is not False
deps, real, err = await run_in_threadpool(_target, request, sid)
if err:
return err
entry = await run_in_threadpool(write, deps, pid, real, data, merge)
return {"ok": True, "sessionId": real, "data": entry}