Files
ai-agent/backend/conversations/spawned_live.py
gabrielvidalandClaude Opus 5.5 1f1cd8e9da feat(conversations): hub children that report back keep their parent running, listed with its subagents
spawned_live.py: the reporting children still at work, per parent (memoized),
merged into runningAgents and _resolve_state (never over interrupted/review).
spawnedChildren carry startedAt/messages/tokens/subagentCount/shortTitle/prompt/report;
spawnedByChain for the breadcrumb; SSE parent cards + roots for child writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:14:55 +01:00

142 lines
5.4 KiB
Python

"""Which hub children (``ai-agent new`` runs that report back —
``meta.reportTo``, runs/children.py) are still at work, by parent.
A child is the hub's subagent whatever the harness on either side, so while
one runs it keeps its parent ``running`` (``cards._resolve_state``'s
``children_running``) and shows in the parent's running agents, like a native
Task/Agent call. Only an *armed* report counts: chatting in an old child by
hand, or a ``--no-report`` spawn, never wakes the parent.
A child is at work when its process is alive, when it was armed less than
``LAUNCH_S`` ago and still says ``running`` (not on a runner's list yet), or
when its own card resolves ``running`` — a grandchild still at work included
(recursively, cycle-safe). An arming older than ``STALE_S`` is ignored: the
exit watcher missed it.
One pass over the metadata, memoized on the metadata and summaries versions,
the live/held runs and a 15 s bucket (the recency window moves with time
alone) — every card of a list build asks, for a dict lookup."""
import datetime
import time
from core import liveruns
from core.memo import _Memo
from core.state import AppState
STALE_S = 6 * 3600
LAUNCH_S = 30
BUCKET_S = 15
def _age_s(at: str | None) -> float:
try:
dt = datetime.datetime.fromisoformat((at or "").replace("Z", "+00:00"))
except ValueError:
return float("inf")
return (datetime.datetime.now(datetime.timezone.utc) - dt).total_seconds()
def _armed_kids(deps: AppState) -> dict[str, list[tuple[str, dict]]]:
out: dict[str, list[tuple[str, dict]]] = {}
for sid, m in deps.meta_store.items():
rt = m.get("reportTo") or {}
parent = rt.get("sessionId")
if parent and parent != sid and _age_s(rt.get("at")) < STALE_S:
out.setdefault(parent, []).append((sid, m))
return out
def _build(deps: AppState) -> dict[str, list[dict]]:
"""``{parent sid: [RunningAgent-shaped dict, …]}`` — the direct children
at work, oldest armed first."""
kids_of = _armed_kids(deps)
if not kids_of:
return {}
from conversations import ids
from conversations.cards import _conv_title, _resolve_state, _subagent_activity
from conversations.catalog import _conv_ids_by_session
by_sid = _conv_ids_by_session(deps)
alive_set = liveruns.snapshot()
held_set = liveruns.held_snapshot()
metas = {sid: m for ks in kids_of.values() for sid, m in ks}
memo: dict[str, bool] = {}
summaries: dict[str, dict | None] = {}
def summary(sid: str) -> dict | None:
if sid not in summaries:
cid = by_sid.get(sid)
summaries[sid] = deps.store.get_summary(ids.path_of(cid)) if cid else None
return summaries[sid]
def active(sid: str, path: frozenset) -> bool:
if sid in memo:
return memo[sid]
m = metas.get(sid) or deps.meta_store.peek(sid)
grand = any(active(k, path | {k}) for k, _ in kids_of.get(sid, []) if k not in path)
if sid in alive_set:
res = True
elif (m.get("state") in (None, "running")
and _age_s((m.get("reportTo") or {}).get("at")) < LAUNCH_S):
res = True
else:
s = summary(sid)
notified = m.get("notified") or ((s or {}).get("lifecycleAuto") or {}).get("notified")
res = bool(s) and _resolve_state(
s, m, notified, _subagent_activity(deps, s),
False, sid in held_set, children_running=grand) == "running"
memo[sid] = res
return res
out: dict[str, list[dict]] = {}
for parent, ks in kids_of.items():
live = []
for sid, m in ks:
if not active(sid, frozenset({parent, sid})):
continue
s = summary(sid) or {}
live.append({
"toolUseId": f"child:{sid}",
"agentType": None,
"description": (m.get("title") or (_conv_title(deps, s) if s else None)
or (s.get("firstPrompt") or "")[:90] or "conversation"),
"startedAt": (m.get("reportTo") or {}).get("at") or s.get("startedAt"),
"harness": m.get("harness") or s.get("harness") or "claude",
"model": s.get("contextModel") or s.get("model") or m.get("model"),
"conversationId": by_sid.get(sid),
})
if live:
live.sort(key=lambda a: a["startedAt"] or "")
out[parent] = live
return out
_memo = _Memo(_build)
def _key(deps: AppState) -> tuple:
return (id(deps.meta_store), getattr(deps.meta_store, "version", 0),
id(deps.store), deps.store.summaries_version,
liveruns.snapshot(), liveruns.held_snapshot(), int(time.time() // BUCKET_S))
def by_parent(deps: AppState) -> dict[str, list[dict]]:
try:
return _memo.get(_key(deps), deps)
except Exception: # never fail a card over this
return {}
def has_running_children(deps: AppState, sid: str | None) -> bool:
return bool(sid) and sid in by_parent(deps)
def running_child_agents(deps: AppState, sid: str | None) -> list[dict]:
return list(by_parent(deps).get(sid or "", []))
def active_sids(deps: AppState, sid: str | None) -> list[str]:
"""The session ids of ``sid``'s direct children at work — what a cached
card checks it was built with."""
return [a["toolUseId"][6:] for a in by_parent(deps).get(sid or "", [])]