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

226 lines
9.3 KiB
Python

"""The parent ↔ child links of conversations started with the ``ai-agent``
CLI (``meta.spawnedBy``, stamped by runs/children.py), resolved for the
thread view: the parent a child links back to ("Started by …") and the
children a parent lists.
Cheap on purpose — the detail endpoint runs on every live poll: one pass over
the in-memory metadata (no copy), the memoized session → conversation map and
the stored summaries; a child's state only for the few that exist."""
import re
from conversations.cards import _conv_meta, _conv_title
from conversations import ids
from conversations.catalog import _conv_ids_by_session
from core.state import AppState
from users import access
# A parent rarely has more; a runaway fan-out shouldn't bloat every poll.
MAX_LISTED = 30
def _ref(deps: AppState, caller, sid: str, by_sid: dict, *, state: bool) -> dict | None:
cid = by_sid.get(sid)
if not cid or not access.visible(deps, caller, cid):
return None
s = deps.store.get_summary(ids.path_of(cid))
out = {"id": cid, "sessionId": sid, "title": (_conv_title(deps, s) if s else None)}
if state and s:
m = _conv_meta(deps, s)
out.update(state=m.get("state"), endedAt=s.get("endedAt"), cost=s.get("cost"),
harness=m.get("harness") or s.get("harness") or "claude",
model=s.get("contextModel") or s.get("model"))
return out
def _kids_of(deps: AppState) -> dict[str, list[tuple[str, str]]]:
"""``{parent sid: [(spawn time, child sid), …]}`` off the metadata."""
out: dict[str, list[tuple[str, str]]] = {}
for k, m in deps.meta_store.items():
p = (m.get("spawnedBy") or {}).get("sessionId")
if p and p != k:
out.setdefault(p, []).append(((m.get("spawnedBy") or {}).get("at") or "", k))
return out
def _native_rollup(path: str, s: dict, deps: AppState) -> tuple[int, float, int]:
"""A child's own native subagents: ``(how many, their tokens, their cost)``."""
from conversations.tree import _subagent_descendants
import pathlib
n, toks, cost = 0, 0, 0.0
try:
for d in _subagent_descendants(pathlib.Path(path)):
ds = deps.store.get_summary(str(d))
if ds:
n += 1
toks += ds.get("tokens") or 0
cost += ds.get("cost") or 0.0
except Exception:
pass
return n, toks, cost
def _clip(text: str | None, n: int = 4000) -> str | None:
text = (text or "").strip()
return (text[:n] + "…" if len(text) > n else text) or None
def _child_card(deps: AppState, ref: dict, kids_of: dict) -> None:
"""Fill a child ref in, the way a native subagent's card reads: its start,
size (its native subagents rolled in) and how many agents it started."""
s = deps.store.get_summary(ids.path_of(ref["id"])) or {}
n, toks, cost = _native_rollup(ids.path_of(ref["id"]), s, deps)
ref.update(startedAt=s.get("startedAt"), messages=s.get("messages"),
tokens=(s.get("tokens") or 0) + toks or None,
cost=round((s.get("cost") or 0.0) + cost, 6) if (s.get("cost") or cost) else s.get("cost"),
subagentCount=n + len(kids_of.get(ref["sessionId"], [])))
def _texts(deps: AppState, refs: list[dict]) -> None:
"""Each child's opening prompt and — once it no longer runs — its last
answer, off the search corpus in one read; and its cached short title."""
from conversations import refs as refs_mod, short_title
if not refs:
return
corpus = deps.store.search_msgs(ids.path_of(r["id"]) for r in refs)
shorts = short_title.cached(deps, {r["id"]: r.get("title") for r in refs})
for r in refs:
first, last = refs_mod._texts(corpus.get(ids.path_of(r["id"])))
if not first:
s = deps.store.get_summary(ids.path_of(r["id"])) or {}
first = refs_mod._own(s.get("firstPrompt"))
r["prompt"] = _clip(first)
r["report"] = _clip(last) if r.get("state") != "running" else None
r["shortTitle"] = shorts.get(r["id"])
def _chain(deps: AppState, caller, meta: dict, by_sid: dict) -> list[dict]:
"""The spawn chain above a child, root first — cycle-safe."""
out: list[dict] = []
seen: set[str] = set()
up = (meta.get("spawnedBy") or {}).get("sessionId")
while up and up not in seen and len(out) < 8:
seen.add(up)
r = _ref(deps, caller, up, by_sid, state=False)
if not r:
break
out.append(r)
up = (deps.meta_store.peek(up).get("spawnedBy") or {}).get("sessionId")
return out[::-1]
def links(deps: AppState, caller, sid: str | None, meta: dict) -> dict:
"""``{spawnedByConversation, spawnedByChain, spawnedChildren}`` for the
detail payload."""
if not sid:
return {"spawnedByConversation": None, "spawnedByChain": None, "spawnedChildren": []}
by_sid = _conv_ids_by_session(deps)
chain = _chain(deps, caller, meta, by_sid) if (meta.get("spawnedBy") or {}).get("sessionId") else []
parent = chain[-1] if chain else None
kids_of = _kids_of(deps)
kids = sorted(kids_of.get(sid, []))
children = [r for _, k in kids[-MAX_LISTED:]
if (r := _ref(deps, caller, k, by_sid, state=True))]
for r in children:
_child_card(deps, r, kids_of)
_texts(deps, children)
return {"spawnedByConversation": parent, "spawnedByChain": chain or None,
"spawnedChildren": children}
def descendant_stats(deps: AppState, sid: str | None) -> tuple[int, float, int]:
"""``(children, their cost, how many still at work)`` for one parent, a
child's own children included — :func:`child_costs` for a single card
(the SSE ``transcript`` event's)."""
if not sid:
return 0, 0.0, 0
from conversations import spawned_live
by_sid = _conv_ids_by_session(deps)
kids_of = _kids_of(deps)
live = spawned_live.by_parent(deps)
n, cost, running = 0, 0.0, 0
stack, seen = [sid], {sid}
while stack:
p = stack.pop()
running += len(live.get(p, []))
for _, k in kids_of.get(p, []):
if k in seen:
continue
seen.add(k)
stack.append(k)
n += 1
cid = by_sid.get(k)
s = deps.store.get_summary(ids.path_of(cid)) if cid else None
cost += float((s or {}).get("cost") or 0)
return n, cost, running
def spawn_parent(deps: AppState, sid: str | None) -> str | None:
"""The session that started ``sid`` with the ``ai-agent`` CLI, if any."""
return (deps.meta_store.peek(sid).get("spawnedBy") or {}).get("sessionId") if sid else None
# A Bash call that started or continued a child: `ai-agent new …` (or the
# `agents` / `goals --work` spawns) prints the child's session id, `send` too.
_SPAWN_CMD = re.compile(r"\bai-agent\s+(?:new|send|agents|goals)\b")
_SID = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b")
def attach_calls(thread: list[dict], kids: list[dict]) -> None:
"""Stamp ``childConvs`` on each Bash call of ``thread`` whose output names
one of ``kids`` (the ``spawnedChildren`` refs) — the parent's thread
draws the child there, like a native subagent's Agent card. In place."""
if not kids:
return
by_sid = {k["sessionId"]: k for k in kids}
for it in thread:
if it.get("name") != "shell" or it.get("kind") != "tool_use":
continue
if not _SPAWN_CMD.search(str((it.get("input") or {}).get("command") or "")):
continue
res = it.get("result")
if not isinstance(res, str):
continue
hits = list(dict.fromkeys(s for s in _SID.findall(res) if s in by_sid))
if hits:
it["childConvs"] = [by_sid[s] for s in hits]
def child_costs(cards: list[dict]) -> dict[str, tuple[int, float, int]]:
"""``{parent sid: (children, their cost, how many still run)}`` over
``cards`` — a child's own children included, so a chain rolls up to the
conversation on top."""
kids: dict[str, list[dict]] = {}
for c in cards:
p = ((c.get("meta") or {}).get("spawnedBy") or {}).get("sessionId")
if p and c.get("sessionId") and p != c["sessionId"]:
kids.setdefault(p, []).append(c)
out: dict[str, tuple[int, float, int]] = {}
def total(sid: str, seen: frozenset) -> tuple[int, float, int]:
if sid in out:
return out[sid]
n, cost, live = 0, 0.0, 0
for k in kids.get(sid, []):
if k["sessionId"] in seen:
continue
kn, kc, kl = total(k["sessionId"], seen | {k["sessionId"]})
n, cost = n + 1 + kn, cost + float(k.get("cost") or 0) + kc
live += kl + ((k.get("meta") or {}).get("state") == "running")
out[sid] = (n, cost, live)
return out[sid]
for p in kids:
total(p, frozenset({p}))
return {p: v for p, v in out.items() if v[0]}
def with_child_costs(page: list[dict], costs: dict[str, tuple[int, float, int]]) -> list[dict]:
"""``page`` with ``childCount`` / ``childCost`` / ``childRunning`` on the
parents — copies: the cards are the shared memo's."""
out = []
for c in page:
v = costs.get(c.get("sessionId") or "")
out.append({**c, "childCount": v[0], "childCost": round(v[1], 6),
"childRunning": v[2]} if v else c)
return out