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>
319 lines
12 KiB
Python
319 lines
12 KiB
Python
"""
|
|
Realtime fan-out for the ai-agent backend.
|
|
|
|
* ``Hub`` — a tiny thread-safe pub/sub: each SSE client gets a queue, and
|
|
``publish`` drops a JSON event onto every live queue.
|
|
* ``Watcher`` — a daemon thread that polls the metadata sidecar and watches
|
|
the live transcript files (inotify, see fswatch — a full re-walk of them
|
|
only as a safety net, or each tick where inotify isn't available); when
|
|
either changes it re-indexes (cheap/incremental) and publishes a ``meta`` /
|
|
``transcript`` event so the frontend can update without a manual refresh.
|
|
"""
|
|
|
|
import asyncio
|
|
import collections
|
|
import json
|
|
import os
|
|
import queue
|
|
import threading
|
|
import time
|
|
import typing
|
|
|
|
import fsscan
|
|
import fswatch
|
|
from telemetry import metrics as tm
|
|
|
|
# Behind inotify (fswatch), how often the transcript watcher still re-walks
|
|
# every source dir: the safety net for an event that never came.
|
|
RESCAN_SECS = float(os.environ.get("WATCH_RESCAN_SECS", "60"))
|
|
|
|
|
|
def _rel(path: str, base: str) -> str:
|
|
"""``os.path.relpath`` for a path joined under ``base`` (what scandir and
|
|
inotify hand back) — a slice, not relpath's normalising walk."""
|
|
return path[len(base) + 1:] if base != "/" else path[1:]
|
|
|
|
|
|
def _put_nowait_safe(aq: asyncio.Queue, item) -> None:
|
|
try:
|
|
aq.put_nowait(item)
|
|
except asyncio.QueueFull:
|
|
pass
|
|
|
|
|
|
class Hub:
|
|
"""Each subscriber may bring a ``filter(event) -> event | None``: a guest's
|
|
stream (``core/routes.py``) drops what isn't theirs and trims the rest."""
|
|
|
|
# How many past events a reconnecting client can catch up on (see
|
|
# ``replay_since``). Minutes' worth at the busiest; a client that was
|
|
# away longer resyncs by refetching.
|
|
RING = 1024
|
|
|
|
def __init__(self) -> None:
|
|
self._subs: dict[queue.Queue, typing.Callable | None] = {}
|
|
self._async_subs: dict[
|
|
asyncio.Queue, tuple[asyncio.AbstractEventLoop, typing.Callable | None]
|
|
] = {}
|
|
self._lock = threading.Lock()
|
|
self._seq = 0
|
|
# Ids are `<epoch>-<seq>`: the epoch names this process, so a client
|
|
# resuming across a backend restart is told to resync instead of
|
|
# being replayed a counter that restarted from 1.
|
|
self.epoch = f"{int(time.time()):x}"
|
|
# (seq, raw event dict) — unfiltered; replay re-applies each
|
|
# subscriber's own filter.
|
|
self._ring: collections.deque[tuple[int, dict]] = collections.deque(maxlen=self.RING)
|
|
self.listeners: list[typing.Callable[[dict], None]] = []
|
|
|
|
def subscribe(self, filter: typing.Callable | None = None) -> queue.Queue:
|
|
q: queue.Queue = queue.Queue(maxsize=100)
|
|
with self._lock:
|
|
self._subs[q] = filter
|
|
return q
|
|
|
|
def unsubscribe(self, q: queue.Queue) -> None:
|
|
with self._lock:
|
|
self._subs.pop(q, None)
|
|
|
|
def subscribe_async(
|
|
self, loop: asyncio.AbstractEventLoop, filter: typing.Callable | None = None
|
|
) -> asyncio.Queue:
|
|
aq: asyncio.Queue = asyncio.Queue(maxsize=100)
|
|
with self._lock:
|
|
self._async_subs[aq] = (loop, filter)
|
|
return aq
|
|
|
|
def unsubscribe_async(self, aq: asyncio.Queue) -> None:
|
|
with self._lock:
|
|
self._async_subs.pop(aq, None)
|
|
|
|
def subscriber_count(self) -> int:
|
|
"""Streams subscribed now (telemetry's ``aiagent_sse_subscribers``)."""
|
|
return len(self._subs) + len(self._async_subs)
|
|
|
|
@staticmethod
|
|
def _deliver(flt: typing.Callable | None, event: dict, data: str) -> str | None:
|
|
if flt is None:
|
|
return data
|
|
try:
|
|
ev = flt(event)
|
|
except Exception:
|
|
return None
|
|
if ev is None:
|
|
return None
|
|
return data if ev is event else json.dumps(ev)
|
|
|
|
def publish(self, event: dict) -> None:
|
|
"""Fan ``event`` out as ``(seq, json)``; every event gets a monotonic
|
|
id so a stream can resume (``Last-Event-ID``) where it dropped."""
|
|
data = json.dumps(event)
|
|
try:
|
|
tm.SSE_EVENTS.labels(str(event.get("type") or "other")[:32]).inc()
|
|
except Exception:
|
|
pass
|
|
with self._lock:
|
|
self._seq += 1
|
|
seq = self._seq
|
|
self._ring.append((seq, event))
|
|
subs = list(self._subs.items())
|
|
async_subs = list(self._async_subs.items())
|
|
eid = self.event_id(seq)
|
|
for q, flt in subs:
|
|
out = self._deliver(flt, event, data)
|
|
if out is None:
|
|
continue
|
|
try:
|
|
q.put_nowait((eid, out))
|
|
except queue.Full:
|
|
pass
|
|
for aq, (loop, flt) in async_subs:
|
|
out = self._deliver(flt, event, data)
|
|
if out is None:
|
|
continue
|
|
try:
|
|
loop.call_soon_threadsafe(_put_nowait_safe, aq, (eid, out))
|
|
except RuntimeError:
|
|
pass # event loop already closed
|
|
for fn in list(self.listeners):
|
|
try:
|
|
fn(event)
|
|
except Exception:
|
|
pass
|
|
|
|
def replay_since(self, last_id: str,
|
|
flt: typing.Callable | None = None) -> list[tuple[str, str]] | None:
|
|
"""The events published after ``last_id`` (through ``flt``), or None
|
|
when it can't be honoured — an id from another backend process (the
|
|
epoch differs: whatever happened across the restart is unknown), or
|
|
older than the ring — and the client has to resync by refetching."""
|
|
epoch, _, n = last_id.rpartition("-")
|
|
if epoch != self.epoch or not n.isdigit():
|
|
return None
|
|
last = int(n)
|
|
with self._lock:
|
|
ring = list(self._ring)
|
|
seq = self._seq
|
|
if last > seq:
|
|
return None
|
|
if ring and last < ring[0][0] - 1:
|
|
return None
|
|
if not ring and last != seq:
|
|
return None
|
|
out = []
|
|
for sq, ev in ring:
|
|
if sq <= last:
|
|
continue
|
|
data = self._deliver(flt, ev, json.dumps(ev))
|
|
if data is not None:
|
|
out.append((self.event_id(sq), data))
|
|
return out
|
|
|
|
def event_id(self, seq: int) -> str:
|
|
return f"{self.epoch}-{seq}"
|
|
|
|
@property
|
|
def last_id(self) -> str:
|
|
return self.event_id(self._seq)
|
|
|
|
|
|
class Watcher(threading.Thread):
|
|
def __init__(self, source_dir, meta_store, indexer, hub, interval: float = 2.0,
|
|
cards_for: typing.Callable[[list[str]], dict] | None = None,
|
|
deps=None):
|
|
super().__init__(daemon=True)
|
|
# The app state, for the event's spawn-parent links (conversations/card.py).
|
|
self.deps = deps
|
|
# Builds the list cards of the conversations a batch of changed
|
|
# transcripts touched, attached to the `transcript` event so clients
|
|
# patch their cached lists without a request per ping.
|
|
self.cards_for = cards_for
|
|
# One or many live transcript dirs (Claude Code + the pi runner mirror).
|
|
if source_dir is None:
|
|
self.source_dirs = []
|
|
elif isinstance(source_dir, (list, tuple)):
|
|
self.source_dirs = [d for d in source_dir if d]
|
|
else:
|
|
self.source_dirs = [source_dir]
|
|
self.meta_store = meta_store
|
|
self.indexer = indexer
|
|
self.hub = hub
|
|
self.interval = interval
|
|
# Behind inotify, the full re-walk that catches anything it missed.
|
|
self.rescan_secs = RESCAN_SECS
|
|
self._sig: dict[str, tuple] = {}
|
|
self._stop = threading.Event()
|
|
self._tw: fswatch.TreeWatch | None = None
|
|
self._full_at = 0.0
|
|
|
|
def stop(self) -> None:
|
|
self._stop.set()
|
|
|
|
def run(self) -> None:
|
|
self._scan_sources() # prime signatures so we don't fire on boot
|
|
self._full_at = time.monotonic()
|
|
# Opened after the prime: what's on disk by now is in `_sig`, and
|
|
# every write from here on is an event.
|
|
self._tw = fswatch.TreeWatch.open(
|
|
[str(d) for d in self.source_dirs], file_mask=fswatch.FILE_CHANGES)
|
|
while not self._stop.wait(self.interval):
|
|
t0 = time.perf_counter()
|
|
try:
|
|
self._tick()
|
|
except Exception:
|
|
pass
|
|
tm.WATCH_TICK.observe(time.perf_counter() - t0)
|
|
|
|
def _scan_sources(self) -> list[str]:
|
|
"""Return rel paths of transcripts whose (mtime,size) changed.
|
|
|
|
The full walk over every source dir (~1 500 files, with ``os.scandir``
|
|
— see fsscan — rather than ``rglob``). Each tick when inotify isn't
|
|
available; behind it, every ``rescan_secs`` and after the kernel
|
|
dropped events."""
|
|
changed: list[str] = []
|
|
for source_dir in self.source_dirs:
|
|
if not source_dir.is_dir():
|
|
continue
|
|
base = str(source_dir)
|
|
for path, mtime, size in fsscan.walk_files(source_dir, ".jsonl"):
|
|
rel = _rel(path, base)
|
|
sig = (mtime, size)
|
|
if self._sig.get(rel) != sig:
|
|
self._sig[rel] = sig
|
|
changed.append(rel)
|
|
return changed
|
|
|
|
def _check(self, paths) -> list[str]:
|
|
"""`_scan_sources` for just ``paths`` (what inotify reported): the
|
|
same (mtime, size) signature test, so an event that changed nothing
|
|
— the close after a write — reports nothing."""
|
|
changed: list[str] = []
|
|
bases = [str(d) for d in self.source_dirs]
|
|
for path in sorted(paths):
|
|
if not path.endswith(".jsonl"):
|
|
continue
|
|
base = max((b for b in bases if path.startswith(b + "/")), key=len,
|
|
default=None)
|
|
if base is None:
|
|
continue
|
|
try:
|
|
st = os.stat(path)
|
|
except OSError:
|
|
continue # gone again: a deletion was never reported either
|
|
rel = _rel(path, base)
|
|
sig = (st.st_mtime, st.st_size)
|
|
if self._sig.get(rel) != sig:
|
|
self._sig[rel] = sig
|
|
changed.append(rel)
|
|
return changed
|
|
|
|
def _changed(self) -> list[str]:
|
|
"""The transcripts that moved since the last tick: inotify's report
|
|
when the watch is up (a full rescan every ``rescan_secs`` behind it,
|
|
or right away when events were lost), else the full poll."""
|
|
tw = self._tw
|
|
if tw is not None and not tw.ok: # hit the watch limit: poll again
|
|
tw.close()
|
|
self._tw = tw = None
|
|
if tw is None:
|
|
return self._scan_sources()
|
|
paths, lost = tw.changes()
|
|
now = time.monotonic()
|
|
if lost or not tw.ok or now - self._full_at >= self.rescan_secs:
|
|
self._full_at = now
|
|
return self._scan_sources()
|
|
return self._check(paths)
|
|
|
|
def _tick(self) -> None:
|
|
if self.meta_store.reload_if_changed():
|
|
self.hub.publish({"type": "meta"})
|
|
changed = self._changed()
|
|
if changed:
|
|
tm.WATCH_CHANGED.inc(len(changed))
|
|
try:
|
|
# Targeted: import + re-parse only what changed. The indexer's
|
|
# own periodic sweep still does the full pass (discovery+prune).
|
|
self.indexer.scan_transcripts(only=changed)
|
|
except Exception:
|
|
pass
|
|
# Public ids only: each changed rel path → its UUIDv7, plus each
|
|
# subagent's root (conversations/card.py).
|
|
from conversations.card import transcript_event
|
|
try:
|
|
ev: dict = transcript_event(changed, self.deps)
|
|
except Exception:
|
|
ev = transcript_event(changed)
|
|
if self.cards_for is not None:
|
|
try:
|
|
cards = self.cards_for(changed)
|
|
except Exception:
|
|
cards = None
|
|
if cards:
|
|
ev["cards"] = cards
|
|
self.hub.publish(ev)
|
|
# How stale the news was when it went out: its newest write → now.
|
|
newest = max((self._sig[r][0] for r in changed if r in self._sig), default=None)
|
|
if newest is not None and 0 <= time.time() - newest < 600:
|
|
tm.PUBLISH_LAG.observe(time.time() - newest)
|