refactor(events): unify scoped runtime notifications across clients (#5670)

* refactor(events): unify scoped runtime notifications across clients

* style(tests): sort auto-compaction event imports

* refactor(events): scope connections and remove retry callback plumbing

* docs: remove runtime notification design write-up

* refactor(bus): route operation events through the message bus

* fix(channels): isolate outbound sends by destination

* style(events): group shared notification imports

* refactor(events): converge runtime and hook delivery on MessageBus

* test(events): migrate fixtures to unified message bus
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-06 02:11:19 +08:00
1 parent 3495281282
commit 192e2e90dc
78 files changed
+1620 -1194

No files matched your search

+55 -115
View File
@@ -4,24 +4,22 @@ from __future__ import annotations
import dataclasses
import time
from collections.abc import Awaitable, Callable
from collections.abc import Callable
from copy import deepcopy
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import notification_is_deliverable
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
RetryWaitEvent,
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
outbound_message_for_event,
)
from nanobot.bus.progress import build_bus_progress_callback
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus, RuntimeEventPublisher
from nanobot.bus.runtime_events import RuntimeEventPublisher
from nanobot.channels.notification_routes import notification_metadata
from nanobot.events import AgentEvent, EventSink
from nanobot.providers.base import LLMUsage
from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata
@@ -40,10 +38,27 @@ class TurnRoute:
TurnRoutePolicy = Callable[[InboundMessage, str, TurnRoute], TurnRoute]
ProgressCallback = Callable[..., Awaitable[None]]
StreamCallback = Callable[[str], Awaitable[None]]
StreamEndCallback = Callable[..., Awaitable[None]]
RetryWaitCallback = Callable[[str], Awaitable[None]]
def _bind_events(
bus: MessageBus, route: TurnRoute,
) -> EventSink:
channel, chat_id = route.channel, route.chat_id
metadata = deepcopy(route.metadata)
def accepts(event_type: type[AgentEvent]) -> bool:
return notification_is_deliverable(
event_type, channel=channel, publish_lifecycle=route.publish_lifecycle,
)
async def publish(event: AgentEvent) -> None:
if not accepts(type(event)):
return
await bus.publish_event(
event, channel=channel, chat_id=chat_id, metadata=deepcopy(metadata),
)
return EventSink(publish, accepts)
class TurnDeliveryFactory:
@@ -52,12 +67,10 @@ class TurnDeliveryFactory:
def __init__(
self,
bus: MessageBus,
runtime_events: RuntimeEventBus,
route_policy: TurnRoutePolicy | None = None,
) -> None:
self.bus = bus
self.runtime_events = runtime_events
self.runtime_event_publisher = RuntimeEventPublisher(runtime_events)
self.runtime_event_publisher = RuntimeEventPublisher(bus)
self.route_policy = route_policy
def create(
@@ -95,11 +108,11 @@ class TurnDeliveryFactory:
),
)
def session_compaction_callback(
def session_events(
self,
session_key: str,
session_metadata: dict[str, Any],
) -> ContextCompactionCallback | None:
) -> EventSink:
"""Bind idle notifications to one route without acquiring a turn owner."""
saved_route = session_metadata.get("_compaction_route")
if isinstance(saved_route, dict):
@@ -107,9 +120,9 @@ class TurnDeliveryFactory:
channel, chat_id = saved_route.get("channel"), saved_route.get("chat_id")
metadata = saved_route.get("metadata", {})
if not isinstance(channel, str) or not isinstance(chat_id, str):
return
return EventSink()
if not isinstance(metadata, dict):
return
return EventSink()
metadata = cast(dict[str, Any], metadata)
else:
# Older sessions have no route snapshot. Only direct clients have a
@@ -120,19 +133,12 @@ class TurnDeliveryFactory:
else tuple(session_key.split(":", 1))
)
if not route or len(route) != 2 or route[0] not in {"websocket", "cli"}:
return
return EventSink()
channel, chat_id = route
metadata = {}
metadata = deepcopy(metadata)
async def publish(event: ContextCompactionEvent) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=channel, chat_id=chat_id, event=event, metadata=metadata,
)
)
return publish
return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata))
@staticmethod
def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute:
@@ -174,8 +180,12 @@ class TurnDelivery:
_stream_base_id: str | None = field(init=False, default=None)
_stream_segment: int = field(init=False, default=0)
_stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False)
_routed_events: EventSink = field(init=False)
def __post_init__(self) -> None:
self._routed_events = _bind_events(self.bus, self.route)
self.events = EventSink(self._publish_event, self._routed_events.accepts)
self.delivery_message = dataclasses.replace(
self.input_message,
channel=self.route.channel,
@@ -189,67 +199,16 @@ class TurnDelivery:
self._stream_base_id = f"{self.session_key}:{time.time_ns()}"
@property
def on_stream(self) -> StreamCallback | None:
return self._publish_stream if self._stream_base_id is not None else None
@property
def on_stream_end(self) -> StreamEndCallback | None:
return self._publish_stream_end if self._stream_base_id is not None else None
def progress_callback(self) -> ProgressCallback | None:
if not self.route.publish_lifecycle:
return None
return build_bus_progress_callback(self.bus, self.delivery_message)
def retry_wait_callback(self) -> RetryWaitCallback | None:
if not self.route.publish_lifecycle:
return None
async def _on_retry_wait(content: str) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=RetryWaitEvent(content=content),
metadata=self.delivery_message.metadata,
)
)
return _on_retry_wait
async def context_compaction(self, event: ContextCompactionEvent) -> None:
"""Publish one compaction transition without completing the active turn."""
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=event,
metadata=self.delivery_message.metadata,
)
)
def streaming(self) -> bool:
return self._stream_base_id is not None
def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
"""Keep only routing fields needed to deliver a later idle notification."""
source = self.route.metadata
channel_type = self.route.channel.split(".", 1)[0]
fields = {
"telegram": ("message_thread_id",),
"matrix": ("thread_root_event_id", "thread_reply_to_event_id"),
"feishu": ("message_id", "thread_id", "chat_type"),
}.get(channel_type, ())
metadata = {
key: source[key] for key in fields if key in source
}
if channel_type in {"slack", "mattermost"}:
nested = source.get(channel_type)
if isinstance(nested, dict):
nested = cast(dict[str, Any], nested)
fields = ("thread_ts",) if channel_type == "slack" else ("root_id", "thread_ts")
metadata[channel_type] = {key: nested[key] for key in fields if key in nested}
# Keep the storage key readable by older gateways.
session_metadata["_compaction_route"] = {
"channel": self.route.channel,
"chat_id": self.route.chat_id,
"metadata": metadata,
"metadata": notification_metadata(self.route.channel, self.route.metadata),
}
async def started(self) -> None:
@@ -369,40 +328,21 @@ class TurnDelivery:
assert self._stream_base_id is not None
return f"{self._stream_base_id}:{self._stream_segment}"
async def _publish_stream(self, delta: str) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=StreamDeltaEvent(content=delta, stream_id=self._stream_id()),
metadata=self.delivery_message.metadata,
)
)
self._stream_open = True
async def _publish_stream_end(
self,
*,
resuming: bool = False,
merge_next: bool = False,
) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=StreamEndEvent(
stream_id=self._stream_id(),
resuming=resuming,
merge_next=merge_next,
),
metadata=self.delivery_message.metadata,
)
)
self._stream_open = merge_next
if not merge_next:
self._stream_segment += 1
async def _publish_event(self, event: AgentEvent) -> None:
if isinstance(event, StreamDeltaEvent | StreamEndEvent):
if not self.streaming:
return
event = dataclasses.replace(event, stream_id=self._stream_id())
if self._routed_events.publish is not None:
await self._routed_events.publish(event)
if isinstance(event, StreamDeltaEvent):
self._stream_open = True
elif isinstance(event, StreamEndEvent):
self._stream_open = event.merge_next
if not event.merge_next:
self._stream_segment += 1
async def abort_stream(self) -> None:
"""Close an interrupted stream so stateful channels can release its buffer."""
if self._stream_open:
await self._publish_stream_end()
await self._publish_event(StreamEndEvent())