Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
refactor(events): unify scoped runtime notifications across clients (#5670)
chengyongru192e2e90dc3f
diff --git a/.agent/design.md b/.agent/design.mdindex e598d99be..1eb925ae8 100644--- a/.agent/design.md+++ b/.agent/design.md@@ -6,7 +6,7 @@ These rules govern architectural decisions. When adding a feature or fixing a buNew capabilities should be added via `channels/`, `tools/`, skills, or MCP servers. The files `agent/loop.py` and `agent/runner.py` form the critical core path; changes there should be minimal and justified. If a feature can live in a channel adapter, a tool, or an external MCP server, it should not be inlined into the agent loop.-Runtime state fan-out follows the same boundary. `AgentLoop` may publish generic runtime events from `nanobot.bus.runtime_events` for turn/run/model/goal state changes, but WebUI/WebSocket wire details such as `_turn_end`, `_goal_status`, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter.+Runtime state fan-out follows the same boundary. `MessageBus.publish` awaits local subscribers for turn/run/model/goal state changes; `MessageBus.publish_event` queues routed channel delivery without waiting for network sends. Both carry `AgentEvent` values. Runner hooks publish typed output through the turn's scoped `EventSink`; direct-call callbacks are adapted at the execution boundary. WebUI/WebSocket wire details, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter.## Less structure, more intelligencediff --git a/Dockerfile b/Dockerfileindex 6cca60fe1..397957a89 100644--- a/Dockerfile+++ b/Dockerfile@@ -5,6 +5,7 @@ COPY webui/package.json webui/package-lock.json ./webui/WORKDIR /app/webuiRUN npm ciCOPY webui/ ./+COPY packages/client-events/ /app/packages/client-events/RUN mkdir -p /app/nanobot/web && npm run buildFROM ghcr.io/astral-sh/uv:python3.12-bookworm-slimdiff --git a/nanobot/agent/autocompact.py b/nanobot/agent/autocompact.pyindex a02b579ef..3fe87116b 100644--- a/nanobot/agent/autocompact.py+++ b/nanobot/agent/autocompact.py@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutinefrom loguru import logger-from nanobot.bus.outbound_events import ContextCompactionCallback+from nanobot.events import NO_EVENTS, EventSinkfrom nanobot.session.manager import MIN_COMPACTED_REPLAY_MESSAGES, Session, SessionManagerfrom nanobot.session.summary import SessionSummary, session_summary_from_metadata@@ -16,7 +16,7 @@ if TYPE_CHECKING:from nanobot.agent.memory import Consolidatorfrom nanobot.utils.llm_runtime import LLMRuntime-IdleCompactionCallback = Callable[[str], ContextCompactionCallback | None]+SessionEventFactory = Callable[[str], EventSink]class AutoCompact:@@ -25,13 +25,13 @@ class AutoCompact:def __init__(self, sessions: SessionManager, consolidator: Consolidator,session_ttl_minutes: int = 0,- bind_compaction: IdleCompactionCallback | None = None):+ bind_events: SessionEventFactory | None = None):self.sessions = sessionsself.consolidator = consolidatorself._ttl = session_ttl_minutesself._archiving: set[str] = set()self._summaries: dict[str, SessionSummary] = {}- self._bind_compaction = bind_compaction+ self._bind_events = bind_eventsdef _is_expired(self, ts: datetime | str | None,now: datetime | None = None) -> bool:@@ -96,7 +96,7 @@ class AutoCompact:key,runtime=runtime,max_suffix=self._RECENT_SUFFIX_MESSAGES,- on_compaction=self._bind_compaction(key) if self._bind_compaction else None,+ events=self._bind_events(key) if self._bind_events else NO_EVENTS,)if summary and summary != "(nothing)":session = self.sessions.get_or_create(key)diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.pyindex e552ff133..5b8a55198 100644--- a/nanobot/agent/context_governance.py+++ b/nanobot/agent/context_governance.py@@ -20,11 +20,7 @@ from uuid import uuid4from loguru import loggerfrom nanobot.agent.context import TranscriptInput-from nanobot.bus.outbound_events import (- ContextCompactionCallback,- ContextCompactionEvent,- emit_context_compaction,-)+from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSinkfrom nanobot.providers.base import (LLMResponse,LLMUsage,@@ -204,7 +200,7 @@ class ModelRequestState:tool_definitions: list[dict[str, Any]] | None = Nonecompaction: ContextCompactionState | None = Noneprovider_compaction_applied: bool = False- compaction_callback: ContextCompactionCallback | None = None+ events: EventSink = NO_EVENTSclass ContextGovernor:@@ -474,8 +470,7 @@ class ContextGovernor:returncompaction_id = uuid4().hex- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="started"),)try:@@ -485,8 +480,7 @@ class ContextGovernor:compaction.active_summary,)except (Exception, asyncio.CancelledError) as exc:- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id,phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",@@ -494,8 +488,7 @@ class ContextGovernor:)raiseif not summary:- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),)return@@ -504,8 +497,7 @@ class ContextGovernor:summary=summary,transcript_boundary=transcript_boundary,)- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id,phase="succeeded",@@ -524,8 +516,7 @@ class ContextGovernor:"""Replace accepted history H with a checkpoint while preserving delta."""measured, _source = pressurecompaction_id = uuid4().hex- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="started"),)try:@@ -570,16 +561,14 @@ class ContextGovernor:transcript_boundary=compaction.raw_accepted_boundary,)except (Exception, asyncio.CancelledError) as exc:- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id,phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",),)raise- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id,phase="succeeded",@@ -628,8 +617,7 @@ class ContextGovernor:)if pressure is not None:compaction_id = uuid4().hex- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="started"),)try:@@ -639,13 +627,11 @@ class ContextGovernor:tool_definitions=tool_definitions,)except Exception:- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),)raise- await emit_context_compaction(- state.compaction_callback,+ await state.events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="succeeded"),)request_was_fitted = True@@ -681,6 +667,10 @@ class ContextGovernor:context_window_tokens=state.config.context_window_tokens,))+ if state.events.publish is not None:+ provider_context = replace(+ provider_context or ProviderCallContext(), events=state.events,+ )state.messages = deepcopy(prepared)state.tool_definitions = deepcopy(tool_definitions)return prepared, provider_contextdiff --git a/nanobot/agent/hook.py b/nanobot/agent/hook.pyindex 2455c4b56..136e57db2 100644--- a/nanobot/agent/hook.py+++ b/nanobot/agent/hook.py@@ -2,13 +2,14 @@from __future__ import annotations-from collections.abc import Awaitable, Callable+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Anyfrom loguru import logger+from nanobot.events import NO_EVENTS, EventSinkfrom nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest@@ -51,7 +52,7 @@ class AgentRunHookContext:class AgentTurnHookContext:"""Turn-local inputs available when constructing per-turn hooks."""- on_progress: Callable[..., Awaitable[None]] | None = None+ events: EventSink = NO_EVENTSworkspace: Path | None = Nonechannel: str = "cli"chat_id: str = "direct"diff --git a/nanobot/agent/hooks/file_edit_activity.py b/nanobot/agent/hooks/file_edit_activity.pyindex f45c56d4a..7c70c21e8 100644--- a/nanobot/agent/hooks/file_edit_activity.py+++ b/nanobot/agent/hooks/file_edit_activity.py@@ -2,7 +2,6 @@from __future__ import annotations-from collections.abc import Awaitable, Callablefrom pathlib import Pathfrom typing import Any, cast@@ -12,6 +11,8 @@ from nanobot.agent.hook import (AgentRunHookContext,AgentTurnHookContext,)+from nanobot.bus.outbound_events import FileEditEvent+from nanobot.events import EventSinkfrom nanobot.providers.base import ToolCallRequestfrom nanobot.utils.file_edit_events import (FileEditTracker,@@ -20,10 +21,6 @@ from nanobot.utils.file_edit_events import (build_file_edit_start_event,prepare_file_edit_trackers,)-from nanobot.utils.progress_events import (- invoke_file_edit_progress,- on_progress_accepts_file_edit_events,-)class FileEditActivityHook(AgentHook):@@ -32,15 +29,11 @@ class FileEditActivityHook(AgentHook):def __init__(self,*,- on_progress: Callable[..., Awaitable[None]] | None,+ events: EventSink,workspace: Path | None,) -> None:super().__init__()- self._on_progress = (- on_progress- if on_progress is not None and on_progress_accepts_file_edit_events(on_progress)- else None- )+ self._publish = events.publish if events.accepts(FileEditEvent) else Noneself._workspace = workspaceself._trackers_by_call: dict[str, list[FileEditTracker]] = {}@@ -54,7 +47,7 @@ class FileEditActivityHook(AgentHook):tool: Any,params: Any,) -> None:- if self._on_progress is None or not isinstance(params, dict):+ if self._publish is None or not isinstance(params, dict):returntyped_params = cast(dict[str, Any], params)trackers = prepare_file_edit_trackers(@@ -120,8 +113,8 @@ class FileEditActivityHook(AgentHook):])async def _emit(self, events: list[dict[str, Any]]) -> None:- if self._on_progress is not None:- await invoke_file_edit_progress(self._on_progress, events)+ if self._publish is not None:+ await self._publish(FileEditEvent(file_edit_events=events))@staticmethoddef _tool_call_key(tool_call: ToolCallRequest) -> str:@@ -131,9 +124,9 @@ class FileEditActivityHook(AgentHook):def create_file_edit_activity_hook(context: AgentTurnHookContext) -> AgentHook | None:"""Create the default file-edit observer for one agent turn."""- if context.on_progress is None:+ if not context.events.accepts(FileEditEvent):return Nonereturn FileEditActivityHook(- on_progress=context.on_progress,+ events=context.events,workspace=context.workspace,)diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex 583bd3d83..09f52ae1d 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -6,7 +6,6 @@ from __future__ import annotationsimport asyncioimport dataclasses-import inspectimport osimport timeimport weakref@@ -51,14 +50,15 @@ from nanobot.agent.turn_delivery import TurnRoute as TurnRoutefrom nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hookfrom nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessagefrom nanobot.bus.outbound_events import (- ContextCompactionCallback,+ StreamDeltaEvent,StreamedResponseEvent,+ StreamEndEvent,)from nanobot.bus.queue import MessageBus-from nanobot.bus.runtime_events import RuntimeEventBusfrom nanobot.command import CommandContext, CommandRouter, register_builtin_commandsfrom nanobot.command.router import normalize_command_textfrom nanobot.config.schema import AgentDefaults, ModelPresetConfig+from nanobot.events import NO_EVENTS, AgentEvent, EventSinkfrom nanobot.llm_usage.context import source_from_requestfrom nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationStatefrom nanobot.providers.factory import ProviderSnapshot@@ -109,6 +109,7 @@ from nanobot.utils.document import reference_non_image_attachmentsfrom nanobot.utils.helpers import image_placeholder_textfrom nanobot.utils.helpers import truncate_text as truncate_text_fnfrom nanobot.utils.llm_runtime import LLMRuntime+from nanobot.utils.progress_events import output_eventsfrom nanobot.utils.runtime import (EMPTY_FINAL_RESPONSE_MESSAGE,)@@ -162,11 +163,9 @@ class TurnContext:outbound: OutboundMessage | None = Nonesuppress_response: bool = False- on_progress: Callable[..., Awaitable[None]] | None = None- on_stream: Callable[[str], Awaitable[None]] | None = None- on_stream_end: Callable[..., Awaitable[None]] | None = None+ events: EventSink = NO_EVENTS+ streaming: bool = Falseon_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None- on_retry_wait: Callable[[str], Awaitable[None]] | None = Nonepending_queue: asyncio.Queue[InboundMessage] | None = Nonepending_summary: SessionSummary | None = None@@ -298,7 +297,6 @@ class AgentLoop:model_preset: str | None = None,dream_model_preset: str | None = None,preset_snapshot_loader: preset_helpers.PresetSnapshotLoader | None = None,- runtime_events: RuntimeEventBus | None = None,turn_delivery_factory: TurnDeliveryFactory | None = None,runtime_model_publisher: Callable[[str, str | None], None] | None = None,restart_mode: str = "auto",@@ -315,16 +313,9 @@ class AgentLoop:if turn_delivery_factory is not None:if turn_delivery_factory.bus is not bus:raise ValueError("turn delivery factory must use the agent message bus")- if (- runtime_events is not None- and turn_delivery_factory.runtime_events is not runtime_events- ):- raise ValueError("turn delivery factory must use the agent runtime event bus")self.turn_delivery_factory = turn_delivery_factory- self.runtime_events = turn_delivery_factory.runtime_eventselse:- self.runtime_events = runtime_events or RuntimeEventBus()- self.turn_delivery_factory = TurnDeliveryFactory(bus, self.runtime_events)+ self.turn_delivery_factory = TurnDeliveryFactory(bus)self.runtime_event_publisher = self.turn_delivery_factory.runtime_event_publisherself.channels_config = channels_configself.restart_mode = restart_mode@@ -458,7 +449,7 @@ class AgentLoop:sessions=self.sessions,consolidator=self.consolidator,session_ttl_minutes=session_ttl_minutes,- bind_compaction=self._idle_compaction_callback,+ bind_events=self._idle_events,)self._idle_compact_check_interval_s = idle_compact_check_interval_secondsself._next_idle_compact_check_at = time.monotonic()@@ -647,7 +638,6 @@ class AgentLoop:image_generation_provider_configs=self._image_generation_provider_configs,timezone=self.context.timezone or "UTC",workspace_sandbox=self.workspace_scopes.sandbox_status,- runtime_events=self.runtime_events,runtime_control=AgentRuntimeControl(self),)loader = ToolLoader()@@ -919,13 +909,13 @@ class AgentLoop:return UNIFIED_SESSION_KEYreturn msg.session_key- def _idle_compaction_callback(+ def _idle_events(self,session_key: str,- ) -> ContextCompactionCallback | None:+ ) -> EventSink:"""Bind one idle compaction to its current user-facing destination."""session = self.sessions.get_or_create(session_key)- return self.turn_delivery_factory.session_compaction_callback(+ return self.turn_delivery_factory.session_events(session_key, session.metadata,)@@ -954,11 +944,8 @@ class AgentLoop:async def _run_agent_loop(self,transcript_input: TranscriptInput,- on_progress: Callable[..., Awaitable[None]] | None = None,- on_stream: Callable[[str], Awaitable[None]] | None = None,- on_stream_end: Callable[..., Awaitable[None]] | None = None,- on_retry_wait: Callable[[str], Awaitable[None]] | None = None,- on_context_compaction: ContextCompactionCallback | None = None,+ events: EventSink = NO_EVENTS,+ streaming: bool = False,*,runtime: LLMRuntime,session: Session | None = None,@@ -974,8 +961,8 @@ class AgentLoop:) -> AgentRunResult:"""Run the agent iteration loop.- *on_stream*: called with each content delta during streaming.- *on_stream_end(resuming, merge_next)*: called when a streaming session finishes.+ *events*: scoped operation and output events.+ *streaming*: request incremental output from the runner.``resuming=True`` means the active turn continues. ``merge_next=True`` meansthe next text segment belongs to the same user-visible assistant message.@@ -1168,9 +1155,8 @@ class AgentLoop:for scope in turn_scopes or ():turn_scope_stack.enter_context(scope)hook = build_agent_turn_hook(AgentTurnHookSpec(- on_progress=on_progress,- on_stream=on_stream,- on_stream_end=on_stream_end,+ events=events,+ streaming=streaming,channel=request_ctx.channel,chat_id=request_ctx.chat_id,message_id=request_ctx.message_id,@@ -1199,7 +1185,6 @@ class AgentLoop:workspace=effective_scope.project_path,session_key=session.key if session else None,provider_retry_mode=self.provider_retry_mode,- retry_wait_callback=on_retry_wait,checkpoint_callback=_checkpoint,consolidate_history=(partial(@@ -1243,7 +1228,7 @@ class AgentLoop:channel=request_ctx.channel,metadata=request_metadata,),- compaction_callback=on_context_compaction,+ events=events,))finally:turn_scope_stack.close()@@ -1262,14 +1247,14 @@ class AgentLoop:)# Push final content through stream so streaming channels (e.g. Feishu)# update the card instead of leaving it empty.- if on_stream and on_stream_end and should_stream:+ if events.publish is not None and streaming and should_stream:stream_content = (result.pending_stream_contentif result.pending_stream_content is not Noneelse result.final_content or "")- await on_stream(stream_content)- await on_stream_end(resuming=False)+ await events.publish(StreamDeltaEvent(content=stream_content))+ await events.publish(StreamEndEvent())elif result.stop_reason == "error":logger.error("LLM returned error: {}", (result.final_content or "")[:200])return result@@ -1456,8 +1441,6 @@ class AgentLoop:)response = await self._process_message(msg,- on_stream=delivery.on_stream,- on_stream_end=delivery.on_stream_end,pending_queue=pending,delivery=delivery,)@@ -1652,10 +1635,6 @@ class AgentLoop:delivery = self.turn_delivery_factory.create(msg, key)elif delivery.session_key != key:raise ValueError("turn delivery session does not match the processing session")- if on_stream is None:- on_stream = delivery.on_stream- if on_stream_end is None:- on_stream_end = delivery.on_stream_endt0 = time.time()ctx = TurnContext(msg=msg,@@ -1675,9 +1654,13 @@ class AgentLoop:visible_run_started_at=turn_continuation.internal_continuation_run_started_at(msg.metadata,),- on_progress=on_progress,- on_stream=on_stream,- on_stream_end=on_stream_end,+ events=output_events(+ default=delivery.events,+ on_progress=on_progress,+ on_stream=on_stream,+ on_stream_end=on_stream_end,+ ),+ streaming=on_stream is not None or delivery.streaming,on_runtime_admitted=on_runtime_admitted,pending_queue=pending_queue,ephemeral=ephemeral,@@ -1690,46 +1673,21 @@ class AgentLoop:# A streaming callback may be present even when the final text comes from a# non-streaming recovery. Only the last completed segment can suppress the# regular outbound message.- if ctx.on_stream is not None:- stream_callback = ctx.on_stream- stream_end_callback = ctx.on_stream_end- stream_end_accepts_merge_next = False- if stream_end_callback is not None:- try:- stream_end_signature = inspect.signature(stream_end_callback)- stream_end_accepts_merge_next = (- "merge_next" in stream_end_signature.parameters- or any(- parameter.kind is inspect.Parameter.VAR_KEYWORD- for parameter in stream_end_signature.parameters.values()- )- )- except (TypeError, ValueError):- pass+ if ctx.streaming:+ publish = ctx.events.publishsegment_streamed_content = False- async def _tracked_stream(delta: str) -> None:+ async def track_output(event: AgentEvent) -> None:nonlocal segment_streamed_content- if delta:+ if isinstance(event, StreamDeltaEvent) and event.content:segment_streamed_content = True- await stream_callback(delta)-- async def _tracked_stream_end(- *,- resuming: bool = False,- merge_next: bool = False,- ) -> None:- nonlocal segment_streamed_content- ctx.streamed_content = segment_streamed_content- segment_streamed_content = False- if stream_end_callback is not None:- if merge_next and stream_end_accepts_merge_next:- await stream_end_callback(resuming=resuming, merge_next=True)- else:- await stream_end_callback(resuming=resuming)+ elif isinstance(event, StreamEndEvent):+ ctx.streamed_content = segment_streamed_content+ segment_streamed_content = False+ if publish is not None:+ await publish(event)- ctx.on_stream = _tracked_stream- ctx.on_stream_end = _tracked_stream_end+ ctx.events = EventSink(track_output, ctx.events.accepts)await self._run_turn_stage(ctx, "restore", self._restore_turn)await self._run_turn_stage(ctx, "compact", self._compact_session)@@ -2025,10 +1983,6 @@ class AgentLoop:self.sessions.save(session)ctx.transcript_input = self._build_transcript_input(ctx)- if ctx.on_progress is None:- ctx.on_progress = ctx.delivery.progress_callback()- if ctx.on_retry_wait is None:- ctx.on_retry_wait = ctx.delivery.retry_wait_callback()async def _run_turn(self, ctx: TurnContext) -> None:runtime = ctx.require_runtime()@@ -2040,10 +1994,7 @@ class AgentLoop:result = await self._run_agent_loop(ctx.transcript_input,runtime=runtime,- on_progress=ctx.on_progress,- on_stream=ctx.on_stream,- on_stream_end=ctx.on_stream_end,- on_retry_wait=ctx.on_retry_wait,+ streaming=ctx.streaming,session=ctx.session,pending_queue=ctx.pending_queue,ephemeral=ctx.ephemeral,@@ -2054,7 +2005,7 @@ class AgentLoop:tools=ctx.tools,request_context=ctx.request_context,provider_state=ctx.provider_state,- on_context_compaction=ctx.delivery.context_compaction,+ events=ctx.events,)ctx.final_content = result.final_contentctx.all_messages = result.messagesdiff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.pyindex 37046aa8d..5c1ec77a5 100644--- a/nanobot/agent/memory.py+++ b/nanobot/agent/memory.py@@ -21,11 +21,7 @@ from uuid import uuid4from loguru import logger-from nanobot.bus.outbound_events import (- ContextCompactionCallback,- ContextCompactionEvent,- emit_context_compaction,-)+from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSinkfrom nanobot.llm_usage.context import llm_usage_sourcefrom nanobot.providers.base import ProviderCallContext, ProviderConversationStatefrom nanobot.runtime_context import public_history_messages@@ -1192,7 +1188,7 @@ class Consolidator:*,runtime: LLMRuntime,max_suffix: int = MIN_COMPACTED_REPLAY_MESSAGES,- on_compaction: ContextCompactionCallback | None = None,+ events: EventSink = NO_EVENTS,) -> str | None:"""Archive the full idle tail while keeping recent messages replayable.@@ -1218,8 +1214,7 @@ class Consolidator:return ""compaction_id = uuid4().hex- await emit_context_compaction(- on_compaction,+ await events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="started"),)last_active = session.updated_at@@ -1242,8 +1237,7 @@ class Consolidator:session.last_archived = archive_endself.sessions.save(session)except (Exception, asyncio.CancelledError) as exc:- await emit_context_compaction(- on_compaction,+ await events.emit(ContextCompactionEvent(compaction_id=compaction_id,phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",@@ -1251,14 +1245,12 @@ class Consolidator:)raiseif summary is None:- await emit_context_compaction(- on_compaction,+ await events.emit(ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),)return None- await emit_context_compaction(- on_compaction,+ await events.emit(ContextCompactionEvent(compaction_id=compaction_id,phase="succeeded",diff --git a/nanobot/agent/progress_hook.py b/nanobot/agent/progress_hook.pyindex c6134ab35..515cb2048 100644--- a/nanobot/agent/progress_hook.py+++ b/nanobot/agent/progress_hook.py@@ -2,20 +2,19 @@from __future__ import annotations-import inspectimport json-from typing import Any, Awaitable, Callable, cast+from typing import Anyfrom loguru import loggerfrom nanobot.agent.hook import AgentHook, AgentHookContext+from nanobot.bus.outbound_events import ProgressEvent, StreamDeltaEvent, StreamEndEvent+from nanobot.events import NO_EVENTS, EventSinkfrom nanobot.providers.base import ToolCallRequestfrom nanobot.utils.helpers import IncrementalThinkExtractor, strip_thinkfrom nanobot.utils.progress_events import (build_tool_event_finish_payloads,build_tool_event_start_payload,- invoke_on_progress,- on_progress_accepts_tool_events,)from nanobot.utils.tool_hints import format_tool_hints@@ -25,17 +24,15 @@ class AgentProgressHook(AgentHook):def __init__(self,- on_progress: Callable[..., Awaitable[None]] | None = None,- on_stream: Callable[[str], Awaitable[None]] | None = None,- on_stream_end: Callable[..., Awaitable[None]] | None = None,+ events: EventSink = NO_EVENTS,*,+ streaming: bool = False,session_key: str | None = None,tool_hint_max_length: int = 40,) -> None:super().__init__(reraise=True)- self._on_progress = on_progress- self._on_stream = on_stream- self._on_stream_end = on_stream_end+ self._publish = events.publish+ self._streaming = streamingself._session_key = session_keyself._tool_hint_max_length = tool_hint_max_lengthself._stream_buf = ""@@ -43,7 +40,7 @@ class AgentProgressHook(AgentHook):self._reasoning_open = Falsedef wants_streaming(self) -> bool:- return self._on_stream is not None+ return self._streaming@staticmethoddef _strip_think(text: str | None) -> str | None:@@ -54,16 +51,6 @@ class AgentProgressHook(AgentHook):def _tool_hint(self, tool_calls: list[Any]) -> str:return format_tool_hints(tool_calls, max_length=self._tool_hint_max_length)- @staticmethod- def _on_progress_accepts(cb: Callable[..., Any], name: str) -> bool:- try:- sig = inspect.signature(cb)- except (TypeError, ValueError):- return False- if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):- return True- return name in sig.parameters-async def on_stream(self, context: AgentHookContext, delta: str) -> None:prev_clean = strip_think(self._stream_buf)self._stream_buf += delta@@ -77,19 +64,15 @@ class AgentProgressHook(AgentHook):# Answer text has started; close the reasoning segment so the UI can# lock the bubble before the answer renders below it.await self.emit_reasoning_end()- if self._on_stream:- await self._on_stream(incremental)+ if self._publish and self._streaming:+ await self._publish(StreamDeltaEvent(content=incremental))async def on_stream_end(self, context: AgentHookContext, *, resuming: bool) -> None:await self.emit_reasoning_end()- if self._on_stream_end:- kwargs: dict[str, bool] = {"resuming": resuming}- if (- context.stream_continues_current_message- and self._on_progress_accepts(self._on_stream_end, "merge_next")- ):- kwargs["merge_next"] = True- await self._on_stream_end(**kwargs)+ if self._publish and self._streaming:+ await self._publish(StreamEndEvent(+ resuming=resuming, merge_next=context.stream_continues_current_message,+ ))self._stream_buf = ""self._think_extractor.reset()@@ -105,7 +88,7 @@ class AgentProgressHook(AgentHook):context: AgentHookContext,event: dict[str, Any],) -> None:- if not self._on_progress:+ if not self._publish:returnphase = event.get("phase")name = event.get("name")@@ -135,77 +118,55 @@ class AgentProgressHook(AgentHook):await self.emit_reasoning_end()tool_call = ToolCallRequest(id=str(call_id), name=name, arguments=arguments)tool_hint = self._strip_think(self._tool_hint([tool_call])) or name- await invoke_on_progress(- self._on_progress,- tool_hint,- tool_hint=True,- tool_events=[payload],- )+ await self._publish(ProgressEvent(+ content=tool_hint, tool_hint=True, tool_events=[payload],+ ))logger.info("Provider-hosted tool call: {}({})",name,json.dumps(arguments, ensure_ascii=False)[:200],)return- if on_progress_accepts_tool_events(self._on_progress):- await invoke_on_progress(- self._on_progress,- "",- tool_hint=False,- tool_events=[payload],- )+ await self._publish(ProgressEvent(tool_events=[payload]))async def before_execute_tools(self, context: AgentHookContext) -> None:- if self._on_progress:- if not self._on_stream and not context.streamed_content:+ if self._publish:+ if not self._streaming and not context.streamed_content:thought = self._strip_think(context.response.content if context.response else None)if thought:- await self._on_progress(thought)+ await self._publish(ProgressEvent(content=thought))tool_hint = self._strip_think(self._tool_hint(context.tool_calls))tool_events = [build_tool_event_start_payload(tc) for tc in context.tool_calls]- await invoke_on_progress(- self._on_progress,- cast(str, tool_hint),- tool_hint=True,- tool_events=tool_events,- )+ await self._publish(ProgressEvent(+ content=tool_hint or "", tool_hint=True, tool_events=tool_events,+ ))for tc in context.tool_calls:args_str = json.dumps(tc.arguments, ensure_ascii=False)logger.info("Tool call: {}({})", tc.name, args_str[:200])async def emit_reasoning(self, reasoning_content: str | None) -> None:"""Publish a reasoning chunk; channel plugins decide whether to render."""- if (- self._on_progress- and reasoning_content- and self._on_progress_accepts(self._on_progress, "reasoning")- ):+ if self._publish and reasoning_content:self._reasoning_open = True- await self._on_progress(reasoning_content, reasoning=True)+ await self._publish(ProgressEvent(content=reasoning_content, reasoning_delta=True))async def emit_reasoning_end(self) -> None:"""Close the current reasoning stream segment, if any was open."""- if self._reasoning_open and self._on_progress:+ if self._reasoning_open and self._publish:self._reasoning_open = False- await self._on_progress("", reasoning_end=True)+ await self._publish(ProgressEvent(reasoning_end=True))else:self._reasoning_open = Falseasync def after_iteration(self, context: AgentHookContext) -> None:if (- self._on_progress+ self._publishand context.tool_callsand context.tool_events- and on_progress_accepts_tool_events(self._on_progress)):tool_events = build_tool_event_finish_payloads(context)if tool_events:- await invoke_on_progress(- self._on_progress,- "",- tool_hint=False,- tool_events=tool_events,- )+ await self._publish(ProgressEvent(tool_events=tool_events))u = context.usagelogger.debug("LLM usage: input={} output={} cache_read={} cache_write={} source={}",diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.pyindex 689b8d90b..808b91acb 100644--- a/nanobot/agent/runner.py+++ b/nanobot/agent/runner.py@@ -27,7 +27,7 @@ from nanobot.agent.context_governance import (from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContextfrom nanobot.agent.tools.execution import execute_tool_callsfrom nanobot.agent.tools.registry import ToolRegistry-from nanobot.bus.outbound_events import ContextCompactionCallback+from nanobot.events import NO_EVENTS, EventSinkfrom nanobot.llm_usage.context import (LLMUsageSource,bind_llm_usage_source,@@ -60,7 +60,6 @@ from nanobot.utils.runtime import ()ContinuationCallback = Callable[[], str | None]-RetryWaitCallback = Callable[[str], Awaitable[None]]CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]InjectionCallback = Callable[..., Awaitable[Iterable[Any] | None]]@@ -105,7 +104,6 @@ class AgentRunSpec:workspace: Path | None = Nonesession_key: str | None = Noneprovider_retry_mode: str = "standard"- retry_wait_callback: RetryWaitCallback | None = Nonecheckpoint_callback: CheckpointCallback | None = Noneconsolidate_history: HistoryConsolidator | None = Noneconsolidate_provider_compaction: ProviderCompactionConsolidator | None = None@@ -116,7 +114,7 @@ class AgentRunSpec:finalize_on_max_iterations: bool = Trueprovider_state: ProviderConversationState | None = Nonellm_usage_source: LLMUsageSource | None = None- compaction_callback: ContextCompactionCallback | None = None+ events: EventSink = NO_EVENTS@dataclass(slots=True)@@ -431,7 +429,7 @@ class AgentRunner:config=governance_config,conversation=conversation_state,compaction=compaction,- compaction_callback=spec.compaction_callback,+ events=spec.events,)for iteration in range(spec.max_iterations):@@ -853,7 +851,6 @@ class AgentRunner:"tools": tools,"model": spec.runtime.model,"retry_mode": spec.provider_retry_mode,- "on_retry_wait": spec.retry_wait_callback,}generation = spec.runtime.generationkwargs["temperature"] = generation.temperaturediff --git a/nanobot/agent/tools/context.py b/nanobot/agent/tools/context.pyindex d1cb46c38..5124f7798 100644--- a/nanobot/agent/tools/context.py+++ b/nanobot/agent/tools/context.py@@ -13,7 +13,6 @@ if TYPE_CHECKING:from nanobot.agent.tools.file_state import FileStatesfrom nanobot.agent.tools.runtime_control import RuntimeControlfrom nanobot.bus.queue import MessageBus- from nanobot.bus.runtime_events import RuntimeEventBusfrom nanobot.config.schema import ProviderConfig, ToolsConfigfrom nanobot.cron.service import CronServicefrom nanobot.providers.factory import ProviderSnapshot@@ -90,5 +89,4 @@ class ToolContext:image_generation_provider_configs: dict[str, ProviderConfig] | None = Nonetimezone: str = "UTC"workspace_sandbox: WorkspaceSandboxStatus | None = None- runtime_events: RuntimeEventBus | None = Noneruntime_control: RuntimeControl | None = Nonediff --git a/nanobot/agent/tools/long_task.py b/nanobot/agent/tools/long_task.pyindex 359b60c6c..cbb922b0e 100644--- a/nanobot/agent/tools/long_task.py+++ b/nanobot/agent/tools/long_task.py@@ -15,7 +15,8 @@ from nanobot.agent.goal_permission import (from nanobot.agent.tools.base import Tool, ToolResult, tool_parametersfrom nanobot.agent.tools.context import RequestContext, ToolContext, current_request_contextfrom nanobot.agent.tools.schema import StringSchema, tool_parameters_schema-from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventBus, RuntimeEventContext+from nanobot.bus.queue import MessageBus+from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContextfrom nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_linesfrom nanobot.session.goal_state import (GOAL_STATE_KEY,@@ -55,10 +56,10 @@ class _GoalToolsMixin:def __init__(self,sessions: SessionManager,- runtime_events: RuntimeEventBus | None = None,+ bus: MessageBus | None = None,) -> None:self._sessions = sessions- self._runtime_events = runtime_events+ self._bus = busdef _session(self):request_ctx = current_request_context()@@ -92,14 +93,14 @@ class _GoalToolsMixin:raiseasync def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:- runtime_events = self._runtime_events+ bus = self._busrc = current_request_context()- if runtime_events is None or rc is None:+ if bus is None or rc is None:returncid = (rc.chat_id or "").strip()if not cid:return- await runtime_events.publish(+ await bus.publish(GoalStateChanged(context=RuntimeEventContext(channel=rc.channel,@@ -135,9 +136,9 @@ class CreateGoalTool(Tool, _GoalToolsMixin):def __init__(self,sessions: SessionManager,- runtime_events: RuntimeEventBus | None = None,+ bus: MessageBus | None = None,) -> None:- _GoalToolsMixin.__init__(self, sessions, runtime_events)+ _GoalToolsMixin.__init__(self, sessions, bus)@classmethoddef create(cls, ctx: ToolContext) -> Tool:@@ -146,7 +147,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):raise RuntimeError("CreateGoalTool requires an initialized session manager")return cls(sessions=sess,- runtime_events=ctx.runtime_events,+ bus=ctx.bus,)@classmethod@@ -266,9 +267,9 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):def __init__(self,sessions: SessionManager,- runtime_events: RuntimeEventBus | None = None,+ bus: MessageBus | None = None,) -> None:- _GoalToolsMixin.__init__(self, sessions, runtime_events)+ _GoalToolsMixin.__init__(self, sessions, bus)@classmethoddef create(cls, ctx: ToolContext) -> Tool:@@ -277,7 +278,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):raise RuntimeError("UpdateGoalTool requires an initialized session manager")return cls(sessions=sess,- runtime_events=ctx.runtime_events,+ bus=ctx.bus,)@classmethoddiff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.pyindex a5a08af3b..e06b4379b 100644--- a/nanobot/agent/turn_delivery.py+++ b/nanobot/agent/turn_delivery.py@@ -4,24 +4,22 @@ from __future__ import annotationsimport dataclassesimport time-from collections.abc import Awaitable, Callable+from collections.abc import Callablefrom copy import deepcopyfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, castfrom nanobot.bus.events import InboundMessage, OutboundMessage+from nanobot.bus.notification_delivery import notification_is_deliverablefrom nanobot.bus.outbound_events import (- ContextCompactionCallback,- ContextCompactionEvent,- RetryWaitEvent,StreamDeltaEvent,StreamedResponseEvent,StreamEndEvent,- outbound_message_for_event,)-from nanobot.bus.progress import build_bus_progress_callbackfrom 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, EventSinkfrom nanobot.providers.base import LLMUsagefrom 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_policydef 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 = routemetadata = {}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))@staticmethoddef _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 Nonedef 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 Nonereturn 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 += 1async 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())diff --git a/nanobot/agent/turn_hooks.py b/nanobot/agent/turn_hooks.pyindex 0cbf92f0d..6720f69cf 100644--- a/nanobot/agent/turn_hooks.py+++ b/nanobot/agent/turn_hooks.py@@ -2,7 +2,6 @@from __future__ import annotations-from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any@@ -16,15 +15,15 @@ from nanobot.agent.hook import (CompositeHook,)from nanobot.agent.progress_hook import AgentProgressHook+from nanobot.events import NO_EVENTS, EventSink@dataclass(slots=True)class AgentTurnHookSpec:"""Inputs needed to build the hook chain for one agent turn."""- on_progress: Callable[..., Awaitable[None]] | None = None- on_stream: Callable[[str], Awaitable[None]] | None = None- on_stream_end: Callable[..., Awaitable[None]] | None = None+ events: EventSink = NO_EVENTS+ streaming: bool = Falsechannel: str = "cli"chat_id: str = "direct"message_id: str | None = None@@ -44,9 +43,8 @@ class AgentTurnHookSpec:def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:"""Build the hook chain used by ``AgentRunner`` for one turn."""progress_hook = AgentProgressHook(- on_progress=spec.on_progress,- on_stream=spec.on_stream,- on_stream_end=spec.on_stream_end,+ events=spec.events,+ streaming=spec.streaming,session_key=spec.session_key,tool_hint_max_length=spec.tool_hint_max_length,)@@ -54,7 +52,7 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:return progress_hookturn_context = AgentTurnHookContext(- on_progress=spec.on_progress,+ events=spec.events,workspace=spec.workspace,channel=spec.channel,chat_id=spec.chat_id,diff --git a/nanobot/bus/events.py b/nanobot/bus/events.pyindex ffe5c06aa..7d0f24728 100644--- a/nanobot/bus/events.py+++ b/nanobot/bus/events.py@@ -5,7 +5,7 @@ from datetime import datetimefrom typing import TYPE_CHECKING, Any, Literalif TYPE_CHECKING:- from nanobot.bus.outbound_events import OutboundEvent+ from nanobot.events import AgentEvent# Optional ``OutboundMessage.metadata`` key for structured, channel-agnostic UI# payloads. Value is JSON-serializable with at least ``kind``; rich clients may@@ -65,4 +65,4 @@ class OutboundMessage:media: list[str] = field(default_factory=list)metadata: dict[str, Any] = field(default_factory=dict)buttons: list[list[str]] = field(default_factory=list)- event: "OutboundEvent | None" = None+ event: "AgentEvent | None" = Nonediff --git a/nanobot/bus/notification_delivery.py b/nanobot/bus/notification_delivery.pynew file mode 100644index 000000000..21a45d0c3--- /dev/null+++ b/nanobot/bus/notification_delivery.py@@ -0,0 +1,37 @@+"""Explicit audience policy for operation notifications."""++from typing import Literal++from nanobot.bus.outbound_events import (+ FileEditEvent,+ ProgressEvent,+ StreamDeltaEvent,+ StreamEndEvent,+)+from nanobot.events import AgentEvent, ContextCompactionEvent, RecoveryStateEvent, RetryWaitEvent++NotificationAudience = Literal["channel", "lifecycle", "interactive"]++NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {+ ProgressEvent: "lifecycle",+ FileEditEvent: "lifecycle",+ StreamDeltaEvent: "channel",+ StreamEndEvent: "channel",+ ContextCompactionEvent: "channel",+ RetryWaitEvent: "lifecycle",+ RecoveryStateEvent: "interactive",+}+++def notification_is_deliverable(+ event_type: type[AgentEvent], *, channel: str, publish_lifecycle: bool,+) -> bool:+ """Admit operation notifications to a channel only by explicit policy."""+ audience = NOTIFICATION_AUDIENCES.get(event_type)+ if audience is None:+ return False+ if audience == "lifecycle":+ return publish_lifecycle+ if audience == "interactive":+ return channel == "websocket"+ return Truediff --git a/nanobot/bus/outbound_events.py b/nanobot/bus/outbound_events.pyindex 04a3654e2..a24d484ea 100644--- a/nanobot/bus/outbound_events.py+++ b/nanobot/bus/outbound_events.py@@ -7,22 +7,20 @@ message's explicit ``event`` field rather than in reserved metadata flags.from __future__ import annotations-from collections.abc import Awaitable, Callable, Mapping+from collections.abc import Mappingfrom dataclasses import dataclass, replace-from typing import Any, Literal, cast--from loguru import logger+from typing import Anyfrom nanobot.bus.events import OutboundMessage+from nanobot.events import AgentEvent+from nanobot.events import ContextCompactionEvent as ContextCompactionEvent+from nanobot.events import RecoveryStateEvent as RecoveryStateEvent+from nanobot.events import RetryWaitEvent as RetryWaitEventfrom nanobot.providers.base import LLMUsage-class OutboundEvent:- """Marker base for internal outbound runtime events."""--@dataclass(frozen=True)-class ProgressEvent(OutboundEvent):+class ProgressEvent(AgentEvent):content: str = ""tool_hint: bool = Falsereasoning: bool = False@@ -34,18 +32,18 @@ class ProgressEvent(OutboundEvent):@dataclass(frozen=True)-class RetryWaitEvent(OutboundEvent):- content: str = ""+class FileEditEvent(ProgressEvent):+ """File activity whose snapshot collection requires an interested consumer."""@dataclass(frozen=True)-class StreamDeltaEvent(OutboundEvent):+class StreamDeltaEvent(AgentEvent):content: str = ""stream_id: str | None = None@dataclass(frozen=True)-class StreamEndEvent(OutboundEvent):+class StreamEndEvent(AgentEvent):content: str = ""stream_id: str | None = Noneresuming: bool = False@@ -53,12 +51,12 @@ class StreamEndEvent(OutboundEvent):@dataclass(frozen=True)-class StreamedResponseEvent(OutboundEvent):+class StreamedResponseEvent(AgentEvent):pass@dataclass(frozen=True)-class TurnEndEvent(OutboundEvent):+class TurnEndEvent(AgentEvent):latency_ms: int | None = Nonegoal_state: dict[str, Any] | None = Noneusage: LLMUsage | None = None@@ -67,32 +65,23 @@ class TurnEndEvent(OutboundEvent):@dataclass(frozen=True)-class RecoveryStateEvent(OutboundEvent):- status: str- recovery_id: str- reason: str | None = None- attempts: int = 0- can_continue: bool | None = None---@dataclass(frozen=True)-class GoalStatusEvent(OutboundEvent):+class GoalStatusEvent(AgentEvent):status: strstarted_at: float | None = None@dataclass(frozen=True)-class GoalStateSyncEvent(OutboundEvent):+class GoalStateSyncEvent(AgentEvent):goal_state: dict[str, Any]@dataclass(frozen=True)-class SessionUpdatedEvent(OutboundEvent):+class SessionUpdatedEvent(AgentEvent):scope: str | None = None@dataclass(frozen=True)-class UserInputEvent(OutboundEvent):+class UserInputEvent(AgentEvent):"""A user-input row projected by an edge adapter."""content: str@@ -101,13 +90,13 @@ class UserInputEvent(OutboundEvent):@dataclass(frozen=True)-class RuntimeModelUpdatedEvent(OutboundEvent):+class RuntimeModelUpdatedEvent(AgentEvent):model: str | Nonemodel_preset: str | None = None@dataclass(frozen=True)-class TurnModelUpdatedEvent(OutboundEvent):+class TurnModelUpdatedEvent(AgentEvent):"""The canonical preset and concrete model handling one chat turn."""model: str@@ -116,35 +105,11 @@ class TurnModelUpdatedEvent(OutboundEvent):fallback: bool = False-@dataclass(frozen=True)-class ContextCompactionEvent(OutboundEvent):- """A channel-safe transition for one logical context compaction."""-- compaction_id: str- phase: Literal["started", "succeeded", "failed", "cancelled"]---ContextCompactionCallback = Callable[[ContextCompactionEvent], Awaitable[None]]---async def emit_context_compaction(- callback: ContextCompactionCallback | None,- event: ContextCompactionEvent,-) -> None:- """Notify observers without allowing delivery failure to alter compaction."""- if callback is None:- return- try:- await callback(event)- except Exception:- logger.exception("Failed to publish context compaction event")--def outbound_message_for_event(*,channel: str,chat_id: str,- event: OutboundEvent,+ event: AgentEvent,content: str | None = None,metadata: Mapping[str, Any] | None = None,) -> OutboundMessage:@@ -159,17 +124,9 @@ def outbound_message_for_event()-def outbound_event_from_message(msg: OutboundMessage) -> OutboundEvent | None:- """Return the typed outbound event carried by *msg*, if any."""-- if msg.event is not None:- return msg.event- return _legacy_event_from_metadata(msg)--def replace_outbound_event(msg: OutboundMessage,- event: OutboundEvent,+ event: AgentEvent,*,content: str | None = None,) -> OutboundMessage:@@ -182,7 +139,7 @@ def replace_outbound_event()-def _event_content(event: OutboundEvent) -> str:+def _event_content(event: AgentEvent) -> str:if isinstance(event,ProgressEvent | RetryWaitEvent | StreamDeltaEvent | StreamEndEvent | UserInputEvent,@@ -197,110 +154,3 @@ def _event_content(event: OutboundEvent) -> str:return "Context compaction cancelled."return "Context compacted."return ""---def _legacy_event_from_metadata(msg: OutboundMessage) -> OutboundEvent | None:- """Bridge pre-typed outbound metadata flags into typed events.-- New code should set ``OutboundMessage.event`` directly. The fallback keeps- older in-process extensions and channel plugins from losing runtime events- while they migrate off reserved metadata flags.- """-- meta = msg.metadata or {}- if meta.get("_runtime_model_updated"):- return RuntimeModelUpdatedEvent(- model=_metadata_str(meta, "model"),- model_preset=_metadata_str(meta, "model_preset"),- )- if meta.get("_goal_state_sync"):- goal_state = meta.get("goal_state")- return GoalStateSyncEvent(- cast(dict[str, Any], goal_state)- if isinstance(goal_state, dict)- else {"active": False}- )- if meta.get("_goal_status"):- status = meta.get("goal_status")- if not isinstance(status, str) or not status:- return None- return GoalStatusEvent(- status=status,- started_at=_metadata_float(meta, "started_at", "goal_started_at"),- )- if meta.get("_turn_end"):- goal_state = meta.get("goal_state")- return TurnEndEvent(- latency_ms=_metadata_int(meta, "latency_ms"),- goal_state=cast(dict[str, Any], goal_state) if isinstance(goal_state, dict) else None,- context_window_tokens=_metadata_int(meta, "context_window_tokens"),- )- if meta.get("_session_updated"):- return SessionUpdatedEvent(scope=_metadata_str(meta, "_session_update_scope"))- if meta.get("_retry_wait"):- return RetryWaitEvent(content=msg.content)- if meta.get("_stream_end"):- return StreamEndEvent(- content=msg.content,- stream_id=_metadata_str(meta, "_stream_id"),- resuming=bool(meta.get("_resuming")),- merge_next=bool(meta.get("_merge_next")),- )- if meta.get("_stream_delta"):- return StreamDeltaEvent(- content=msg.content,- stream_id=_metadata_str(meta, "_stream_id"),- )- if meta.get("_streamed"):- return StreamedResponseEvent()- if (- meta.get("_progress")- or meta.get("_reasoning_delta")- or meta.get("_reasoning_end")- or meta.get("_reasoning")- or meta.get("_file_edit_events")- or meta.get("_tool_events")- ):- tool_events = meta.get("_tool_events")- file_edit_events = meta.get("_file_edit_events")- return ProgressEvent(- content=msg.content,- tool_hint=bool(meta.get("_tool_hint")),- reasoning=bool(meta.get("_reasoning")),- reasoning_delta=bool(meta.get("_reasoning_delta")),- reasoning_end=bool(meta.get("_reasoning_end")),- stream_id=_metadata_str(meta, "_stream_id"),- tool_events=cast(list[dict[str, Any]], tool_events)- if isinstance(tool_events, list)- else None,- file_edit_events=cast(list[dict[str, Any]], file_edit_events)- if isinstance(file_edit_events, list)- else None,- )- return None---def _metadata_str(meta: Mapping[str, Any], key: str) -> str | None:- value = meta.get(key)- return value if isinstance(value, str) and value else None---def _metadata_int(meta: Mapping[str, Any], key: str) -> int | None:- value = meta.get(key)- if isinstance(value, bool):- return None- if isinstance(value, int):- return value- if isinstance(value, float) and value.is_integer():- return int(value)- return None---def _metadata_float(meta: Mapping[str, Any], *keys: str) -> float | None:- for key in keys:- value = meta.get(key)- if isinstance(value, bool):- continue- if isinstance(value, int | float):- return float(value)- return Nonediff --git a/nanobot/bus/progress.py b/nanobot/bus/progress.pydeleted file mode 100644index 4dbb48499..000000000--- a/nanobot/bus/progress.py+++ /dev/null@@ -1,67 +0,0 @@-"""Progress callback helpers for user-visible output.--These helpers convert agent progress callbacks into outbound chat messages.-Runtime state notifications such as turn lifecycle and model changes live in-``nanobot.bus.runtime_events``.-"""--from __future__ import annotations--from collections.abc import Awaitable, Callable-from typing import Any--from nanobot.bus.events import InboundMessage-from nanobot.bus.outbound_events import ProgressEvent, outbound_message_for_event-from nanobot.bus.queue import MessageBus---def build_bus_progress_callback(- bus: MessageBus,- msg: InboundMessage,-) -> Callable[..., Awaitable[None]]:- """Return a callback that publishes progress as outbound messages."""-- async def _publish_progress(- content: str,- *,- tool_hint: bool = False,- tool_events: list[dict[str, Any]] | None = None,- file_edit_events: list[dict[str, Any]] | None = None,- reasoning: bool = False,- reasoning_end: bool = False,- ) -> None:- await bus.publish_outbound(- outbound_message_for_event(- channel=msg.channel,- chat_id=msg.chat_id,- event=ProgressEvent(- content=content,- tool_hint=tool_hint,- reasoning_delta=reasoning,- reasoning_end=reasoning_end,- tool_events=tool_events,- file_edit_events=file_edit_events,- ),- metadata=msg.metadata,- )- )-- async def _bus_progress(- content: str,- *,- tool_hint: bool = False,- tool_events: list[dict[str, Any]] | None = None,- file_edit_events: list[dict[str, Any]] | None = None,- reasoning: bool = False,- reasoning_end: bool = False,- ) -> None:- await _publish_progress(- content,- tool_hint=tool_hint,- tool_events=tool_events,- file_edit_events=file_edit_events,- reasoning=reasoning,- reasoning_end=reasoning_end,- )-- return _bus_progressdiff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.pyindex 7c0616f0b..16b4b129f 100644--- a/nanobot/bus/queue.py+++ b/nanobot/bus/queue.py@@ -1,21 +1,38 @@-"""Async message queue for decoupled channel-agent communication."""+"""Queued delivery of messages and typed events between core and channels."""import asyncio+import contextlib+import inspect+from collections.abc import Awaitable, Callable, Mapping+from typing import Any, TypeVar, overload++from loguru import loggerfrom nanobot.bus.events import InboundMessage, OutboundMessage+from nanobot.bus.outbound_events import outbound_message_for_event+from nanobot.events import AgentEvent++_EventT = TypeVar("_EventT", bound=AgentEvent)+EventHandler = Callable[[AgentEvent], Awaitable[None] | None]class MessageBus:"""Async message bus that decouples chat channels from the agent core.- Channels push messages to the inbound queue, and the agent processes- them and pushes responses to the outbound queue.+ Channels push messages to the inbound queue. Core operations publish text,+ media, or typed events to the same routed outbound queue, independently of+ whether an LLM produced them. Channel adapters own their wire projection.++ Local subscribers are awaited by ``publish``; channel delivery is queued by+ ``publish_event``. Local state transitions never wait for network sends."""def __init__(self):self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()+ self._handlers: list[EventHandler] = []+ self._pending: set[asyncio.Task[None]] = set()async def publish_inbound(self, msg: InboundMessage) -> None:"""Publish a message from a channel to the agent."""@@ -26,9 +43,27 @@ class MessageBus:return await self.inbound.get()async def publish_outbound(self, msg: OutboundMessage) -> None:- """Publish a response from the agent to channels."""+ """Queue a routed message or event for its channel."""await self.outbound.put(msg)+ async def publish_event(+ self,+ event: AgentEvent,+ *,+ channel: str,+ chat_id: str,+ metadata: Mapping[str, Any] | None = None,+ ) -> None:+ """Queue a typed event using the existing outbound delivery contract.++ The bus transports event values without inspecting their fields. Known+ events retain their text fallback; channel adapters decide how to render+ or ignore events they receive.+ """+ await self.publish_outbound(outbound_message_for_event(+ channel=channel, chat_id=chat_id, event=event, metadata=metadata,+ ))+async def consume_outbound(self) -> OutboundMessage:"""Consume the next outbound message (blocks until available)."""return await self.outbound.get()@@ -42,3 +77,72 @@ class MessageBus:def outbound_size(self) -> int:"""Number of pending outbound messages."""return self.outbound.qsize()++ @overload+ def subscribe(+ self, handler: Callable[[_EventT], Awaitable[None] | None],+ event_type: type[_EventT],+ ) -> Callable[[], None]: ...++ @overload+ def subscribe(+ self, handler: EventHandler, event_type: None = None,+ ) -> Callable[[], None]: ...++ def subscribe(+ self,+ handler: Callable[..., Awaitable[None] | None],+ event_type: type[AgentEvent] | None = None,+ ) -> Callable[[], None]:+ """Connect an ordered, awaited handler; return its idempotent disconnect.++ The overloads bind handler and event type. The erased callable exists+ only at this heterogeneous dispatch boundary, behind the type filter.+ """+ active = True++ def entry(event: AgentEvent) -> Awaitable[None] | None:+ if active and (event_type is None or isinstance(event, event_type)):+ return handler(event)+ return None+ self._handlers.append(entry)++ def _unsubscribe() -> None:+ nonlocal active+ active = False+ with contextlib.suppress(ValueError):+ self._handlers.remove(entry)++ return _unsubscribe++ async def publish(self, event: AgentEvent) -> None:+ """Await local subscribers in registration order, without channel delivery."""+ for handler in list(self._handlers):+ try:+ result = handler(event)+ if inspect.isawaitable(result):+ await result+ except Exception:+ logger.exception("event handler failed for {}", type(event).__name__)++ def publish_nowait(self, event: AgentEvent) -> asyncio.Task[None] | None:+ """Schedule local dispatch, retaining it until completion.++ Unlike ``publish``, the caller does not wait for handlers. This does not+ turn individual handlers into independent workers or change their order.+ Separate publications may interleave; this is not a global event FIFO.+ """+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ logger.debug("dropping event without a running loop: {}", type(event).__name__)+ return None+ task = loop.create_task(self.publish(event))+ self._pending.add(task)+ task.add_done_callback(self._pending.discard)+ return task++ async def drain(self) -> None:+ """Finish scheduled dispatches after producers stop, before disconnecting."""+ while self._pending:+ await asyncio.gather(*self._pending, return_exceptions=True)diff --git a/nanobot/bus/runtime_events.py b/nanobot/bus/runtime_events.pyindex 3cacbf858..9fb76d2b8 100644--- a/nanobot/bus/runtime_events.py+++ b/nanobot/bus/runtime_events.py@@ -1,25 +1,16 @@-"""Runtime event bus for agent state notifications.--This bus is separate from :mod:`nanobot.bus.queue`: message bus events are-user/chat delivery, while runtime events are in-process state notifications-that optional subscribers such as WebUI adapters may render.-"""+"""Runtime state facts and turn-scoped publication through MessageBus."""from __future__ import annotations-import asyncio-import contextlib-import inspect-from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any-from loguru import logger-from nanobot.bus.events import InboundMessage+from nanobot.events import AgentEventfrom nanobot.providers.base import LLMUsageif TYPE_CHECKING:+ from nanobot.bus.queue import MessageBusfrom nanobot.utils.llm_runtime import LLMRuntime@@ -35,14 +26,14 @@ class RuntimeEventContext:@dataclass(frozen=True)-class SessionTurnStarted:+class SessionTurnStarted(AgentEvent):"""A user/system turn has loaded its session and is about to build context."""context: RuntimeEventContext@dataclass(frozen=True)-class UserInputAccepted:+class UserInputAccepted(AgentEvent):"""User input was accepted for dispatch or injection into a session."""context: RuntimeEventContext@@ -50,7 +41,7 @@ class UserInputAccepted:@dataclass(frozen=True)-class TurnRuntimeAdmitted:+class TurnRuntimeAdmitted(AgentEvent):"""The immutable model runtime selected for one admitted turn."""context: RuntimeEventContext@@ -58,7 +49,7 @@ class TurnRuntimeAdmitted:@dataclass(frozen=True)-class TurnRunStatusChanged:+class TurnRunStatusChanged(AgentEvent):"""Visible run status changed for a turn."""context: RuntimeEventContext@@ -67,7 +58,7 @@ class TurnRunStatusChanged:@dataclass(frozen=True)-class TurnCompleted:+class TurnCompleted(AgentEvent):"""A turn has delivered its final user-visible response."""context: RuntimeEventContext@@ -79,7 +70,7 @@ class TurnCompleted:@dataclass(frozen=True)-class SessionTurnPersisted:+class SessionTurnPersisted(AgentEvent):"""A completed turn has been written to local session storage."""context: RuntimeEventContext@@ -88,7 +79,7 @@ class SessionTurnPersisted:@dataclass(frozen=True)-class GoalStateChanged:+class GoalStateChanged(AgentEvent):"""A session's sustained-goal state changed."""context: RuntimeEventContext@@ -96,82 +87,13 @@ class GoalStateChanged:@dataclass(frozen=True)-class RuntimeModelChanged:+class RuntimeModelChanged(AgentEvent):"""The active runtime model/preset changed."""model: strmodel_preset: str | None-RuntimeEvent = (- UserInputAccepted- | SessionTurnStarted- | TurnRuntimeAdmitted- | SessionTurnPersisted- | TurnRunStatusChanged- | TurnCompleted- | GoalStateChanged- | RuntimeModelChanged-)-RuntimeEventType = (- type[UserInputAccepted]- | type[SessionTurnStarted]- | type[TurnRuntimeAdmitted]- | type[SessionTurnPersisted]- | type[TurnRunStatusChanged]- | type[TurnCompleted]- | type[GoalStateChanged]- | type[RuntimeModelChanged]-)-RuntimeEventHandler = Callable[[Any], Awaitable[None] | None]-_HandlerEntry = tuple[RuntimeEventType | None, RuntimeEventHandler]---class RuntimeEventBus:- """Small in-process pub/sub bus for runtime state.-- Subscribers run in registration order. ``publish`` awaits async handlers so- callers can preserve ordering when a runtime event must follow a user- message. ``publish_nowait`` is available for synchronous call sites.- """-- def __init__(self) -> None:- self._handlers: list[_HandlerEntry] = []-- def subscribe(- self,- handler: RuntimeEventHandler,- event_type: RuntimeEventType | None = None,- ) -> Callable[[], None]:- entry = (event_type, handler)- self._handlers.append(entry)-- def _unsubscribe() -> None:- with contextlib.suppress(ValueError):- self._handlers.remove(entry)-- return _unsubscribe-- async def publish(self, event: RuntimeEvent) -> None:- for event_type, handler in list(self._handlers):- if event_type is not None and not isinstance(event, event_type):- continue- try:- result = handler(event)- if inspect.isawaitable(result):- await result- except Exception:- logger.exception("runtime event handler failed for {}", type(event).__name__)-- def publish_nowait(self, event: RuntimeEvent) -> None:- try:- loop = asyncio.get_running_loop()- except RuntimeError:- logger.debug("dropping runtime event without a running loop: {}", type(event).__name__)- return- loop.create_task(self.publish(event))--class RuntimeEventPublisher:"""Convenience publisher for turn-scoped runtime events.@@ -179,8 +101,8 @@ class RuntimeEventPublisher:the mechanics of building event contexts and carrying per-turn metadata."""- def __init__(self, bus: RuntimeEventBus | None = None) -> None:- self.bus = bus or RuntimeEventBus()+ def __init__(self, bus: MessageBus) -> None:+ self.bus = busself._turn_latency_ms: dict[str, int] = {}self._turn_runtime: dict[str, LLMRuntime] = {}self._turn_usage: dict[str, LLMUsage] = {}diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.pyindex f5ad7a04a..1da6aad9a 100644--- a/nanobot/channels/manager.py+++ b/nanobot/channels/manager.py@@ -21,7 +21,6 @@ from nanobot.bus.outbound_events import (StreamDeltaEvent,StreamedResponseEvent,StreamEndEvent,- outbound_event_from_message,replace_outbound_event,)from nanobot.bus.queue import MessageBus@@ -59,6 +58,8 @@ def _default_webui_dist() -> Path | None:# Retry delays for message sending (exponential backoff: 1s, 2s, 4s)_SEND_RETRY_DELAYS = (1, 2, 4)+_OUTBOUND_CONCURRENCY = 32+_OUTBOUND_PENDING_LIMIT = 256_RESTART_NOTICE_START_TIMEOUT_S = 30.0_RESTART_NOTICE_START_POLL_S = 0.25ORIGIN_REPLY_FINGERPRINTS_MAX_SIZE = 1000@@ -138,6 +139,11 @@ class ChannelManager:self._channel_errors: dict[str, str] = {}self._channel_tasks: dict[str, asyncio.Task[None]] = {}self._dispatch_task: asyncio.Task[None] | None = None+ self._outbound_tasks: dict[asyncio.Task[None], tuple[str, str]] = {}+ self._outbound_tails: dict[tuple[str, str], asyncio.Task[None]] = {}+ self._outbound_slots = asyncio.Semaphore(_OUTBOUND_PENDING_LIMIT)+ self._outbound_sends = asyncio.Semaphore(_OUTBOUND_CONCURRENCY)+ self._stopping_channels: set[str] = set()self._started = Falseself._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()@@ -389,6 +395,14 @@ class ChannelManager:return taskasync def _stop_channel(self, name: str) -> bool:+ self._stopping_channels.add(name)+ try:+ await self._cancel_outbound(name)+ return await self._stop_channel_runtime(name)+ finally:+ self._stopping_channels.discard(name)++ async def _stop_channel_runtime(self, name: str) -> bool:channel = self.channels.get(name)if channel is None:self._channel_tasks.pop(name, None)@@ -683,7 +697,7 @@ class ChannelManager:def _should_suppress_outbound(self, msg: OutboundMessage) -> bool:metadata = msg.metadata or {}- if isinstance(outbound_event_from_message(msg), ProgressEvent):+ if isinstance(msg.event, ProgressEvent):return Falsefingerprint = self._fingerprint_content(msg.content)if not fingerprint:@@ -704,7 +718,53 @@ class ChannelManager:return False+ async def _cancel_outbound(self, channel: str | None = None) -> None:+ tasks = [task for task, key in self._outbound_tasks.items()+ if channel is None or key[0] == channel]+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)++ async def _queue_outbound(self, channel: BaseChannel, msg: OutboundMessage) -> None:+ """Bound scheduled sends; preserve FIFO per destination, not across chats.++ Retry waits occupy only their destination and one send slot. Saturation+ pauses dispatch rather than creating unbounded tasks or dropping messages.+ """+ await self._outbound_slots.acquire()+ if msg.channel in self._stopping_channels or self.channels.get(msg.channel) is not channel:+ self._outbound_slots.release()+ return+ key = (msg.channel, msg.chat_id)+ previous = self._outbound_tails.get(key)++ async def send() -> None:+ if previous is not None:+ await asyncio.shield(asyncio.gather(previous, return_exceptions=True))+ async with self._outbound_sends:+ await self._send_with_retry(channel, msg)++ task = asyncio.create_task(send(), name=f"outbound-{msg.channel}-{msg.chat_id}")+ self._outbound_tasks[task] = key+ self._outbound_tails[key] = task++ def finished(done: asyncio.Task[None]) -> None:+ self._outbound_tasks.pop(done, None)+ if self._outbound_tails.get(key) is done:+ self._outbound_tails.pop(key, None)+ self._outbound_slots.release()+ if not done.cancelled() and (error := done.exception()) is not None:+ logger.error("Outbound delivery to {}:{} failed: {}", *key, error)++ task.add_done_callback(finished)+async def _dispatch_outbound(self) -> None:+ try:+ await self._dispatch_outbound_loop()+ finally:+ await self._cancel_outbound()++ async def _dispatch_outbound_loop(self) -> None:"""Dispatch outbound messages to the appropriate channel."""logger.info("Outbound dispatcher started")@@ -723,7 +783,7 @@ class ChannelManager:timeout=1.0)- event = outbound_event_from_message(msg)+ event = msg.eventprogress_event = event if isinstance(event, ProgressEvent) else Noneif progress_event and (progress_event.reasoning_delta@@ -737,7 +797,7 @@ class ChannelManager:# content silently drops here.channel = self.channels.get(msg.channel)if channel is not None and channel.show_reasoning:- await self._send_with_retry(channel, msg)+ await self._queue_outbound(channel, msg)continueif progress_event:@@ -765,7 +825,7 @@ class ChannelManager:if isinstance(event, StreamDeltaEvent):msg, extra_pending = self._coalesce_stream_deltas(msg)pending.extend(extra_pending)- event = outbound_event_from_message(msg)+ event = msg.eventchannel = self.channels.get(msg.channel)if channel:@@ -780,7 +840,7 @@ class ChannelManager:if self._should_suppress_outbound(msg):logger.info("Suppressing duplicate outbound message to {}:{}", msg.channel, msg.chat_id)continue- await self._send_with_retry(channel, msg)+ await self._queue_outbound(channel, msg)else:logger.warning("Unknown channel: {}", msg.channel)@@ -848,7 +908,7 @@ class ChannelManager:@staticmethodasync def _send_once(channel: BaseChannel, msg: OutboundMessage) -> None:"""Send one outbound message without retry policy."""- event = outbound_event_from_message(msg)+ event = msg.eventif isinstance(event, ProgressEvent) and event.reasoning_end:await ChannelManager._send_reasoning_end(channel, msg, event)elif isinstance(event, ProgressEvent) and event.reasoning_delta:@@ -881,7 +941,7 @@ class ChannelManager:Returns:tuple of (merged_message, list_of_non_matching_messages)"""- first_event = outbound_event_from_message(first_msg)+ first_event = first_msg.eventfirst_stream_id = first_event.stream_id if isinstance(first_event, StreamDeltaEvent) else Nonetarget_key = (first_msg.channel, first_msg.chat_id, first_stream_id)combined_content = first_msg.content@@ -901,7 +961,7 @@ class ChannelManager:break# Check if this message belongs to the same stream- next_event = outbound_event_from_message(next_msg)+ next_event = next_msg.eventnext_stream_id = (next_event.stream_idif isinstance(next_event, StreamDeltaEvent | StreamEndEvent)diff --git a/nanobot/channels/notification_routes.py b/nanobot/channels/notification_routes.pynew file mode 100644index 000000000..d07429b29--- /dev/null+++ b/nanobot/channels/notification_routes.py@@ -0,0 +1,23 @@+"""Channel-owned address metadata retained for later session notifications."""++from collections.abc import Mapping+from copy import deepcopy+from typing import Any, cast+++def notification_metadata(channel: str, source: Mapping[str, Any]) -> dict[str, Any]:+ """Keep thread addresses without retaining sender data or a completed turn owner."""+ channel_type = 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}+ return deepcopy(metadata)diff --git a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.pyindex 6670fdca6..7442be16d 100644--- a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py+++ b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py@@ -12,8 +12,10 @@ import pytestfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.queue import MessageBus+from nanobot.channels.manager import ChannelManagerfrom nanobot.channels.websocket import runtimefrom nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig+from nanobot.config.schema import Configfrom nanobot.webui.gateway_services import build_gateway_services@@ -104,6 +106,39 @@ async def _wait_for_retire_tasks(channel: WebSocketChannel) -> None:await asyncio.sleep(0)+async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() -> None:+ channel = _channel()+ bus = MessageBus()+ config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})+ manager = ChannelManager(config, bus)+ manager.channels["websocket"] = channel+ connections = [_RecordingConnection(block_first_send=i == 0) for i in range(10)]+ for i, connection in enumerate(connections):+ channel._attach(cast(Any, connection), f"chat-{i}")+ dispatcher = asyncio.create_task(manager._dispatch_outbound())+ try:+ for text in ("first", "last"):+ for i in range(10):+ await bus.publish_outbound(_message(f"chat-{i}", text))+ await asyncio.wait_for(connections[0].send_started.wait(), 2)+ for connection in connections[1:]:+ assert await _next_text(connection) == "first"+ assert await _next_text(connection) == "last"+ assert connections[0].sent.empty()+ connections[0].release_send.set()+ assert await _next_text(connections[0]) == "first"+ assert await _next_text(connections[0]) == "last"+ finally:+ dispatcher.cancel()+ await asyncio.gather(dispatcher, return_exceptions=True)+ for connection in connections:+ await channel._cleanup_connection(cast(Any, connection))+ assert not manager._outbound_tasks+ assert not manager._outbound_tails+ assert not channel._connection_outbound++@pytest.mark.asyncioasync def test_slow_tui_does_not_block_a_different_topic() -> None:channel = _channel()diff --git a/nanobot/cli/agent.py b/nanobot/cli/agent.pyindex 45a617813..d8abff9a0 100644--- a/nanobot/cli/agent.py+++ b/nanobot/cli/agent.py@@ -124,7 +124,6 @@ def agent(StreamDeltaEvent,StreamedResponseEvent,StreamEndEvent,- outbound_event_from_message,)from nanobot.bus.queue import MessageBusfrom nanobot.cli import terminal as cli_terminal@@ -312,7 +311,7 @@ def agent(while True:try:msg = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0)- event = outbound_event_from_message(msg)+ event = msg.eventif isinstance(event, StreamDeltaEvent):if renderer:diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.pyindex 295c99ce7..87a02c761 100644--- a/nanobot/cli/gateway_runtime.py+++ b/nanobot/cli/gateway_runtime.py@@ -357,7 +357,6 @@ def _run_gateway(from nanobot.agent.tools.message import MessageToolfrom nanobot.agent.turn_delivery import TurnDeliveryFactoryfrom nanobot.bus.queue import MessageBus- from nanobot.bus.runtime_events import RuntimeEventBusfrom nanobot.channels.manager import ChannelManagerfrom nanobot.config.watcher import watch_config_filefrom nanobot.cron.bound_runner import run_bound_cron_job@@ -410,7 +409,6 @@ def _run_gateway()sync_workspace_templates(config.workspace_path)bus = MessageBus()- runtime_events = RuntimeEventBus()fallback_model_observer = build_webui_fallback_model_observer(bus)def _observe_provider(snapshot: ProviderSnapshot) -> ProviderSnapshot:@@ -468,7 +466,6 @@ def _run_gateway(turn_delivery_factory = TurnDeliveryFactory(bus,- runtime_events,route_policy=WebuiTurnRoutePolicy(session_manager),)@@ -492,7 +489,6 @@ def _run_gateway(image_generation_provider_configs=image_gen_provider_configs(config),provider_snapshot_loader=_load_gateway_provider_snapshot,preset_catalog_loader=load_model_preset_catalog,- runtime_events=runtime_events,turn_delivery_factory=turn_delivery_factory,provider_signature=provider_snapshot.signature,local_trigger_store=trigger_store,@@ -510,7 +506,6 @@ def _run_gateway(schedule_background=_schedule_webui_background,recovery=recovery,)- webui_turn_coordinator.subscribe(runtime_events)from nanobot.bus.events import OutboundMessagefrom nanobot.session.keys import session_key_for_channel@@ -1020,6 +1015,7 @@ def _run_gateway(tasks,runtime_tasks,)+ await bus.drain()# Flush all cached sessions to durable storage before exit.# This prevents data loss on filesystems with write-back# caching (rclone VFS, NFS, FUSE mounts, etc.).@@ -1029,7 +1025,10 @@ def _run_gateway(finally:restore_shutdown_handlers()- with gateway_runtime.foreground_instance(gateway_start_options):+ with (+ gateway_runtime.foreground_instance(gateway_start_options),+ webui_turn_coordinator.connected(),+ ):if health_server_enabled:gateway_runtime.publish_health_host(config.gateway.host)asyncio.run(run())diff --git a/nanobot/cli/terminal.py b/nanobot/cli/terminal.pyindex 03f71c44e..6fe49a1d9 100644--- a/nanobot/cli/terminal.py+++ b/nanobot/cli/terminal.py@@ -27,7 +27,6 @@ from nanobot.bus.outbound_events import (ContextCompactionEvent,ProgressEvent,RetryWaitEvent,- outbound_event_from_message,)from nanobot.cli.stream import StreamRenderer, ThinkingSpinnerfrom nanobot.utils.helpers import sanitize_surrogates as _sanitize_surrogates@@ -369,7 +368,7 @@ async def _maybe_print_interactive_progress(renderer: StreamRenderer | None = None,reasoning_buffer: _ReasoningBuffer | None = None,) -> bool:- event = outbound_event_from_message(msg)+ event = msg.eventif isinstance(event, ContextCompactionEvent):await _print_interactive_progress_line(msg.content, thinking, renderer)return Truediff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.pyindex 29be24be8..27021b9b5 100644--- a/nanobot/command/builtin.py+++ b/nanobot/command/builtin.py@@ -356,7 +356,7 @@ async def cmd_compact(ctx: CommandContext) -> None:summary = await loop.consolidator.compact_idle_session(ctx.key,runtime=runtime,- on_compaction=delivery.context_compaction,+ events=delivery.events,)except Exception:logger.exception("Manual context compaction failed for {}", ctx.key)diff --git a/nanobot/events.py b/nanobot/events.pynew file mode 100644index 000000000..9e0c7de15--- /dev/null+++ b/nanobot/events.py@@ -0,0 +1,64 @@+"""Transport-independent notifications emitted by agent operations."""++from __future__ import annotations++from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Literal++from loguru import logger+++class AgentEvent:+ """A typed event; only explicitly projected events cross a client boundary."""+++@dataclass(frozen=True)+class ContextCompactionEvent(AgentEvent):+ compaction_id: str+ phase: Literal["started", "succeeded", "failed", "cancelled"]+++@dataclass(frozen=True)+class RetryWaitEvent(AgentEvent):+ content: str = ""+++@dataclass(frozen=True)+class RecoveryStateEvent(AgentEvent):+ status: str+ recovery_id: str+ reason: str | None = None+ attempts: int = 0+ can_continue: bool | None = None+++@dataclass(frozen=True)+class EventSink:+ """A thin send callback bound to one operation's MessageBus route.++ Operations use best-effort emit; execution hooks await publish directly so+ output failures retain their runner error semantics. Both propagate+ cancellation. This owns no queue or subscribers. accepts lets expensive+ producers skip work when the bound consumer cannot use their event type.+ """++ publish: Callable[[AgentEvent], Awaitable[None]] | None = None+ accepts_type: Callable[[type[AgentEvent]], bool] | None = None++ def accepts(self, event_type: type[AgentEvent]) -> bool:+ """Whether producing this event has a consumer in the bound scope."""+ return self.publish is not None and (+ self.accepts_type is None or self.accepts_type(event_type)+ )++ async def emit(self, event: AgentEvent) -> None:+ if self.publish is None:+ return+ try:+ await self.publish(event)+ except Exception:+ logger.exception("Failed to publish {}", type(event).__name__)+++NO_EVENTS = EventSink()diff --git a/nanobot/providers/base.py b/nanobot/providers/base.pyindex 062dbbd93..08ec497f9 100644--- a/nanobot/providers/base.py+++ b/nanobot/providers/base.py@@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Literal, castimport json_repairfrom loguru import logger+from nanobot.events import NO_EVENTS, EventSink, RetryWaitEventfrom nanobot.utils.helpers import sanitize_surrogates_deepif TYPE_CHECKING:@@ -260,6 +261,7 @@ class ProviderCallContext:conversation_state: ProviderConversationState | None = field(default=None, repr=False)context_window_tokens: int | None = Nonesession_id: str | None = field(default=None, repr=False)+ events: EventSink = field(default=NO_EVENTS, repr=False, compare=False)@dataclass(frozen=True, slots=True)@@ -1487,13 +1489,16 @@ class LLMProvider(ABC):kw["provider_context"] = provider_contextif on_stream_recover and getattr(self, "supports_stream_recover_callback", False):kw["on_stream_recover"] = _recover_stream+ on_retry_wait, on_retry_exhausted = self._retry_notifications(+ provider_context, on_retry_wait, on_retry_exhausted,+ )return await self._run_chat_with_retry(kw,messages,stream=True,retry_mode=retry_mode,on_retry_wait=on_retry_wait,- on_retry_exhausted=on_retry_exhausted or on_retry_wait,+ on_retry_exhausted=on_retry_exhausted,should_retry_guard=lambda: not has_streamed_content,on_stream_recover=_recover_stream if on_stream_recover else None,)@@ -1535,15 +1540,36 @@ class LLMProvider(ABC):)if provider_context is not None:kw["provider_context"] = provider_context+ on_retry_wait, on_retry_exhausted = self._retry_notifications(+ provider_context, on_retry_wait, on_retry_exhausted,+ )return await self._run_chat_with_retry(kw,messages,stream=False,retry_mode=retry_mode,on_retry_wait=on_retry_wait,- on_retry_exhausted=on_retry_exhausted or on_retry_wait,+ on_retry_exhausted=on_retry_exhausted,)+ @staticmethod+ def _retry_notifications(+ context: ProviderCallContext | None,+ on_wait: RetryEventCallback | None,+ on_exhausted: RetryEventCallback | None,+ ) -> tuple[RetryEventCallback | None, RetryEventCallback | None]:+ """Adapt once at the retry-chain boundary, before candidate callbacks.++ Explicit callbacks retain precedence. In particular a fallback candidate+ exhaustion callback captures its result; it must not also notify the UI.+ """+ if on_wait is None and context is not None and context.events.publish is not None:+ async def publish(content: str) -> None:+ await context.events.emit(RetryWaitEvent(content))++ on_wait = publish+ return on_wait, on_exhausted or on_wait+async def _run_chat_with_retry(self,kw: dict[str, Any],@@ -1737,6 +1763,7 @@ class LLMProvider(ABC):provider_context.context_window_tokens),session_id=provider_context.session_id,+ events=provider_context.events,)if stripped is not None or stripped_context is not None:logger.warning(diff --git a/nanobot/providers/fallback_provider.py b/nanobot/providers/fallback_provider.pyindex 427bf44f4..018235200 100644--- a/nanobot/providers/fallback_provider.py+++ b/nanobot/providers/fallback_provider.py@@ -185,6 +185,7 @@ class FallbackProvider(LLMProvider):conversation_state=provider_context.conversation_state,context_window_tokens=context_window_tokens,session_id=provider_context.session_id,+ events=provider_context.events,)def _primary_available(self) -> bool:@@ -548,6 +549,7 @@ class FallbackProvider(LLMProvider):conversation_state=state,context_window_tokens=context_window_tokens,session_id=provider_context.session_id,+ events=provider_context.events,)if fallback.reasoning_effort is None:fallback_kwargs.pop("reasoning_effort", None)diff --git a/nanobot/sdk/clients.py b/nanobot/sdk/clients.pyindex 59a534b48..21b88aeea 100644--- a/nanobot/sdk/clients.py+++ b/nanobot/sdk/clients.py@@ -206,7 +206,7 @@ class RuntimeClient:handler: Callable[[SessionTurnPersisted], Awaitable[None] | None],) -> Callable[[], None]:"""Register a persisted-turn callback and return an unsubscribe callback."""- return self._loop.runtime_events.subscribe(handler, SessionTurnPersisted)+ return self._loop.bus.subscribe(handler, SessionTurnPersisted)async def compact_session(self, session_key: str) -> SessionSnapshot:"""Archive one session through the shared idle-compaction path."""diff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.pyindex 10cf8abea..dd67c42ac 100644--- a/nanobot/session/webui_turns.py+++ b/nanobot/session/webui_turns.py@@ -4,7 +4,8 @@ from __future__ import annotationsimport reimport time-from collections.abc import Awaitable, Callable+from collections.abc import Awaitable, Callable, Generator+from contextlib import contextmanagerfrom dataclasses import dataclass, replacefrom typing import Any, castfrom uuid import uuid4@@ -13,7 +14,6 @@ from loguru import loggerfrom nanobot.agent.tools.context import current_request_contextfrom nanobot.agent.turn_delivery import TurnRoute-from nanobot.bus import progress as bus_progressfrom nanobot.bus.events import InboundMessagefrom nanobot.bus.outbound_events import (GoalStateSyncEvent,@@ -28,7 +28,6 @@ from nanobot.bus.outbound_events import (from nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import (GoalStateChanged,- RuntimeEventBus,RuntimeEventContext,RuntimeModelChanged,SessionTurnStarted,@@ -417,14 +416,6 @@ def clear_websocket_turns(chat_id: str) -> None:_sync_websocket_turn_projection(chat_id)-def build_bus_progress_callback(- bus: MessageBus,- msg: InboundMessage,-) -> Callable[..., Awaitable[None]]:- """Compatibility wrapper for the generic bus progress callback."""- return bus_progress.build_bus_progress_callback(bus, msg)--async def publish_turn_run_status(bus: MessageBus,msg: InboundMessage,@@ -568,34 +559,34 @@ class WebuiTurnCoordinator:schedule_background: Callable[[Awaitable[None]], None]recovery: RecoveryCoordinator | None = None- def subscribe(self, runtime_events: RuntimeEventBus) -> Callable[[], None]:+ def subscribe(self) -> Callable[[], None]:"""Subscribe this coordinator to runtime events."""unsubscribe = [- runtime_events.subscribe(+ self.bus.subscribe(self._handle_user_input_accepted,UserInputAccepted,),- runtime_events.subscribe(+ self.bus.subscribe(self._handle_session_turn_started,SessionTurnStarted,),- runtime_events.subscribe(+ self.bus.subscribe(self._handle_run_status_changed,TurnRunStatusChanged,),- runtime_events.subscribe(+ self.bus.subscribe(self._handle_turn_runtime_admitted,TurnRuntimeAdmitted,),- runtime_events.subscribe(+ self.bus.subscribe(self._handle_turn_completed_event,TurnCompleted,),- runtime_events.subscribe(+ self.bus.subscribe(self._handle_goal_state_changed,GoalStateChanged,),- runtime_events.subscribe(+ self.bus.subscribe(self._handle_runtime_model_changed,RuntimeModelChanged,),@@ -607,6 +598,15 @@ class WebuiTurnCoordinator:return _unsubscribe+ @contextmanager+ def connected(self) -> Generator[None, None, None]:+ """Keep connections alive through shutdown, then release the coordinator."""+ disconnect = self.subscribe()+ try:+ yield+ finally:+ disconnect()+@staticmethoddef _ctx_msg(ctx: RuntimeEventContext) -> InboundMessage:return InboundMessage(diff --git a/nanobot/utils/progress_events.py b/nanobot/utils/progress_events.pyindex e3fd72406..e7b76caff 100644--- a/nanobot/utils/progress_events.py+++ b/nanobot/utils/progress_events.py@@ -7,14 +7,13 @@ from collections.abc import Awaitable, Callablefrom typing import Any, castfrom nanobot.agent.hook import AgentHookContext---def on_progress_accepts_tool_events(cb: Callable[..., Any]) -> bool:- return _on_progress_accepts(cb, "tool_events")---def on_progress_accepts_file_edit_events(cb: Callable[..., Any]) -> bool:- return _on_progress_accepts(cb, "file_edit_events")+from nanobot.bus.outbound_events import (+ FileEditEvent,+ ProgressEvent,+ StreamDeltaEvent,+ StreamEndEvent,+)+from nanobot.events import NO_EVENTS, AgentEvent, EventSinkdef _on_progress_accepts(cb: Callable[..., Any], name: str) -> bool:@@ -27,26 +26,61 @@ def _on_progress_accepts(cb: Callable[..., Any], name: str) -> bool:return name in sig.parameters-async def invoke_on_progress(- on_progress: Callable[..., Awaitable[None]],- content: str,+def output_events(*,- tool_hint: bool = False,- tool_events: list[dict[str, Any]] | None = None,-) -> None:- if tool_events and on_progress_accepts_tool_events(on_progress):- await on_progress(content, tool_hint=tool_hint, tool_events=tool_events)- return- await on_progress(content, tool_hint=tool_hint)---async def invoke_file_edit_progress(- on_progress: Callable[..., Awaitable[None]],- file_edit_events: list[dict[str, Any]],-) -> None:- if not file_edit_events or not on_progress_accepts_file_edit_events(on_progress):- return- await on_progress("", file_edit_events=file_edit_events)+ default: EventSink = NO_EVENTS,+ on_progress: Callable[..., Awaitable[None]] | None = None,+ on_stream: Callable[[str], Awaitable[None]] | None = None,+ on_stream_end: Callable[..., Awaitable[None]] | None = None,+) -> EventSink:+ """Adapt direct-call output callbacks once, outside the runner and hooks."""+ if on_progress is None and on_stream is None and on_stream_end is None:+ return default+ progress_fields = {+ name for name in ("tool_events", "file_edit_events", "reasoning", "reasoning_end")+ if on_progress is not None and _on_progress_accepts(on_progress, name)+ }+ merge_next = on_stream_end is not None and _on_progress_accepts(on_stream_end, "merge_next")++ def accepts(event_type: type[AgentEvent]) -> bool:+ if issubclass(event_type, FileEditEvent) and on_progress is not None:+ return "file_edit_events" in progress_fields+ if issubclass(event_type, ProgressEvent) and on_progress is not None:+ return True+ if issubclass(event_type, StreamDeltaEvent) and on_stream is not None:+ return True+ if issubclass(event_type, StreamEndEvent) and on_stream_end is not None:+ return True+ return default.accepts(event_type)++ async def publish(event: AgentEvent) -> None:+ if isinstance(event, ProgressEvent) and on_progress is not None:+ if event.file_edit_events:+ if "file_edit_events" in progress_fields:+ await on_progress(event.content, file_edit_events=event.file_edit_events)+ return+ if event.reasoning_delta or event.reasoning_end:+ name = "reasoning" if event.reasoning_delta else "reasoning_end"+ if name in progress_fields:+ await on_progress(event.content, **{name: True})+ return+ if event.tool_events and not event.tool_hint and "tool_events" not in progress_fields:+ return+ kwargs: dict[str, Any] = {"tool_hint": event.tool_hint}+ if event.tool_events and "tool_events" in progress_fields:+ kwargs["tool_events"] = event.tool_events+ await on_progress(event.content, **kwargs)+ elif isinstance(event, StreamDeltaEvent) and on_stream is not None:+ await on_stream(event.content)+ elif isinstance(event, StreamEndEvent) and on_stream_end is not None:+ kwargs = {"resuming": event.resuming}+ if event.merge_next and merge_next:+ kwargs["merge_next"] = True+ await on_stream_end(**kwargs)+ elif default.publish is not None:+ await default.publish(event)++ return EventSink(publish, accepts)def _tool_event_arguments(tool_call: Any) -> dict[str, Any]:diff --git a/nanobot/webui/build.py b/nanobot/webui/build.pyindex ef8a247e6..6129aa425 100644--- a/nanobot/webui/build.py+++ b/nanobot/webui/build.py@@ -90,6 +90,9 @@ def iter_webui_source_files(source_dir: Path) -> list[Path]:if not root.is_dir():continuefiles.extend(path for path in root.rglob("*") if path.is_file())+ shared_root = source_dir.parent / "packages" / "client-events"+ if shared_root.is_dir():+ files.extend(path for path in shared_root.rglob("*") if path.is_file())channel_root = source_dir.parent / "nanobot" / "channels"if channel_root.is_dir():for channel_webui in channel_root.glob("*/webui"):diff --git a/nanobot/webui/outbound_projection.py b/nanobot/webui/outbound_projection.pyindex f1d3aa7d0..01037efa2 100644--- a/nanobot/webui/outbound_projection.py+++ b/nanobot/webui/outbound_projection.py@@ -12,13 +12,11 @@ from nanobot.bus.outbound_events import (GoalStateSyncEvent,GoalStatusEvent,ProgressEvent,- RecoveryStateEvent,RuntimeModelUpdatedEvent,SessionUpdatedEvent,TurnEndEvent,TurnModelUpdatedEvent,UserInputEvent,- outbound_event_from_message,)from nanobot.session.webui_turns import clear_websocket_turn_if_currentfrom nanobot.webui.metadata import (@@ -29,9 +27,8 @@ from nanobot.webui.metadata import (from nanobot.webui.outbound_wire import (WebUIWirePayload,WebUIWirePersistence,- encode_context_compaction,- encode_recovery_state,encode_turn_end,+ project_notification,)from nanobot.webui.session_identity import webui_session_keyfrom nanobot.webui.session_projection import WebUISessionProjection@@ -136,7 +133,7 @@ class WebUIOutboundProjector:)async def send(self, msg: OutboundMessage) -> None:- event = outbound_event_from_message(msg)+ event = msg.eventprogress_event = event if isinstance(event, ProgressEvent) else Noneif isinstance(event, RuntimeModelUpdatedEvent):await self._transport.send_runtime_model_updated(@@ -182,22 +179,18 @@ class WebUIOutboundProjector:provenance=event.provenance,)return- if isinstance(event, RecoveryStateEvent):- if conns:+ notification = project_notification(msg.chat_id, event)+ if notification is not None:+ if conns or notification.deliver_offline:+ kwargs: dict[str, Any] = (+ {"metadata": msg.metadata} if notification.attach_turn_metadata else {}+ )await self._transport.send_payload(- msg.chat_id,- encode_recovery_state(msg.chat_id, event),- persistence="transient",+ msg.chat_id, notification.payload,+ persistence=notification.persistence,+ **kwargs,)return- if isinstance(event, ContextCompactionEvent):- await self._transport.send_payload(- msg.chat_id,- encode_context_compaction(msg.chat_id, event),- persistence="transient" if event.phase == "started" else "turn_activity",- metadata=msg.metadata,- )- returnif isinstance(event, GoalStateSyncEvent):if conns:await self._transport.send_goal_state(diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.pyindex 0cd5af283..b29bcab3f 100644--- a/nanobot/webui/outbound_wire.py+++ b/nanobot/webui/outbound_wire.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom collections.abc import Mapping+from dataclasses import dataclassfrom typing import Any, Literal, NotRequired, TypeAlias, TypedDictfrom nanobot.bus.outbound_events import (@@ -10,6 +11,7 @@ from nanobot.bus.outbound_events import (RecoveryStateEvent,TurnEndEvent,)+from nanobot.events import AgentEventfrom nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY@@ -39,7 +41,7 @@ class TurnEndWirePayload(_ChatWirePayload):class ContextCompactionWirePayload(_ChatWirePayload):event: Literal["context_compaction"]compaction_id: str- phase: str+ phase: Literal["started", "succeeded", "failed", "cancelled"]WebUIWirePayload: TypeAlias = (@@ -85,6 +87,30 @@ def encode_context_compaction(return payload+@dataclass(frozen=True)+class NotificationProjection:+ """Allowlisted public payload and its durability policy."""++ payload: WebUIWirePayload+ persistence: WebUIWirePersistence = "transient"+ deliver_offline: bool = False+ attach_turn_metadata: bool = False+++def project_notification(chat_id: str, event: AgentEvent | None) -> NotificationProjection | None:+ """Keep notification serialization and persistence decisions at one boundary."""+ if isinstance(event, ContextCompactionEvent):+ return NotificationProjection(+ encode_context_compaction(chat_id, event),+ persistence="transient" if event.phase == "started" else "turn_activity",+ deliver_offline=True,+ attach_turn_metadata=True,+ )+ if isinstance(event, RecoveryStateEvent):+ return NotificationProjection(encode_recovery_state(chat_id, event))+ return None++def encode_turn_end(chat_id: str,event: TurnEndEvent,diff --git a/packages/client-events/fixtures.json b/packages/client-events/fixtures.jsonnew file mode 100644index 000000000..509716526--- /dev/null+++ b/packages/client-events/fixtures.json@@ -0,0 +1,10 @@+[+ {"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"started"},+ {"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"succeeded"},+ {"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"failed"},+ {"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"cancelled"},+ {"event":"recovery_state","chat_id":"chat","status":"resuming","recovery_id":"r1","attempts":0},+ {"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r1","attempts":1,"reason":"tool_state_unknown","can_continue":false},+ {"event":"recovery_state","chat_id":"chat","status":"recovered","recovery_id":"r1","attempts":1},+ {"event":"recovery_state","chat_id":"chat","status":"failed","recovery_id":"r1","attempts":2}+]diff --git a/packages/client-events/notifications.ts b/packages/client-events/notifications.tsnew file mode 100644index 000000000..e47e96f1e--- /dev/null+++ b/packages/client-events/notifications.ts@@ -0,0 +1,67 @@+/** Transport notifications shared by the browser and terminal clients. */+export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed"++export interface RecoveryState {+ status: RecoveryStatus+ recovery_id: string+ reason?: string+ attempts?: number+ can_continue?: boolean+}++export interface ContextCompaction {+ id: string+ phase: "started" | "succeeded" | "failed" | "cancelled"+}++export type NotificationEvent =+ | ({ event: "recovery_state"; chat_id: string; turn_id?: string } & RecoveryState)+ | {+ event: "context_compaction"+ chat_id: string+ turn_id?: string+ compaction_id: string+ phase: ContextCompaction["phase"]+ }++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value)+}++function optional(value: unknown, type: "boolean" | "number" | "string"): boolean {+ return value === undefined || typeof value === type+}++export function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] {+ return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled"+}++export function isRecoveryState(value: unknown): value is RecoveryState {+ return isRecord(value)+ && typeof value.status === "string"+ && ["resuming", "awaiting_user", "recovered", "failed"].includes(value.status)+ && typeof value.recovery_id === "string"+ && optional(value.reason, "string")+ && optional(value.attempts, "number")+ && optional(value.can_continue, "boolean")+}++/** Undefined means another protocol family; null means a malformed notification. */+export function decodeNotification(value: unknown): NotificationEvent | null | undefined {+ if (!isRecord(value)) return undefined+ if (value.event !== "recovery_state" && value.event !== "context_compaction") return undefined+ if (typeof value.chat_id !== "string" || !optional(value.turn_id, "string")) return null+ if (value.event === "recovery_state") {+ return isRecoveryState(value) ? value as unknown as NotificationEvent : null+ }+ return typeof value.compaction_id === "string" && value.compaction_id.length > 0+ && isCompactionPhase(value.phase) ? value as unknown as NotificationEvent : null+}++/** A terminal history row must not regress when an older live event arrives. */+export function acceptsCompactionPhase(+ current: ContextCompaction["phase"] | undefined,+ incoming: ContextCompaction["phase"],+): boolean {+ return current === undefined || (current === "started" && incoming !== "started")+}diff --git a/tests/agent/test_auto_compact.py b/tests/agent/test_auto_compact.pyindex 9fcbd599b..2faac8404 100644--- a/tests/agent/test_auto_compact.py+++ b/tests/agent/test_auto_compact.py@@ -13,6 +13,7 @@ from nanobot.bus.events import InboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.command import CommandContextfrom nanobot.config.schema import AgentDefaults, Config+from nanobot.events import NO_EVENTSfrom nanobot.providers.base import LLMResponse@@ -89,7 +90,7 @@ def _make_fake_compact(runtime,max_suffix: int = 8,trigger: str = "policy",- on_compaction=None,+ events=NO_EVENTS,) -> str:state["count"] += 1session = loop.sessions.get_or_create(key)diff --git a/tests/agent/test_autocompact_unit.py b/tests/agent/test_autocompact_unit.pyindex 7a66aa8d1..84eb4561e 100644--- a/tests/agent/test_autocompact_unit.py+++ b/tests/agent/test_autocompact_unit.py@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom nanobot.agent.autocompact import AutoCompact-from nanobot.bus.outbound_events import ContextCompactionEvent+from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSinkfrom nanobot.session.manager import Session, SessionManager@@ -269,7 +269,7 @@ class TestCheckExpired:"cli:old",runtime=admitted,max_suffix=ac._RECENT_SUFFIX_MESSAGES,- on_compaction=None,+ events=NO_EVENTS,)@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])@@ -445,7 +445,7 @@ class TestArchiveDelegates:"cli:test",runtime=runtime,max_suffix=ac._RECENT_SUFFIX_MESSAGES,- on_compaction=None,+ events=NO_EVENTS,)@pytest.mark.asyncio@@ -457,11 +457,11 @@ class TestArchiveDelegates:def bind(key: str):async def publish(event: ContextCompactionEvent) -> None:observed.append((key, event))- return publish+ return EventSink(publish)async def compact(key: str, **kwargs):event = ContextCompactionEvent(compaction_id="compact-1", phase="started")- await kwargs["on_compaction"](event)+ await kwargs["events"].emit(event)return "Summary."consolidator.compact_idle_session = AsyncMock(side_effect=compact)@@ -469,7 +469,7 @@ class TestArchiveDelegates:sessions=sessions,consolidator=consolidator,session_ttl_minutes=15,- bind_compaction=bind,+ bind_events=bind,)await ac._archive("cli:test", runtime=_runtime())diff --git a/tests/agent/test_consolidator.py b/tests/agent/test_consolidator.pyindex 5e11942b7..79b50bea9 100644--- a/tests/agent/test_consolidator.py+++ b/tests/agent/test_consolidator.py@@ -10,7 +10,7 @@ from nanobot.agent.memory import (Consolidator,MemoryStore,)-from nanobot.bus.outbound_events import ContextCompactionEvent+from nanobot.events import AgentEvent, ContextCompactionEvent, EventSinkfrom nanobot.providers.base import (GenerationSettings,LLMResponse,@@ -569,13 +569,14 @@ class TestCompactIdleSession:real_consolidator.sessions.save(session)events: list[ContextCompactionEvent] = []- async def observe(event: ContextCompactionEvent) -> None:- events.append(event)+ async def observe(event: AgentEvent) -> None:+ if isinstance(event, ContextCompactionEvent):+ events.append(event)result = await real_consolidator.compact_idle_session("cli:events",runtime=runtime,- on_compaction=observe,+ events=EventSink(observe),)assert result == "Summary."@@ -593,13 +594,13 @@ class TestCompactIdleSession:session.add_message("user", "question")real_consolidator.sessions.save(session)- async def fail_observer(_event: ContextCompactionEvent) -> None:+ async def fail_observer(_event: AgentEvent) -> None:raise RuntimeError("channel unavailable")result = await real_consolidator.compact_idle_session("cli:event-callback-failure",runtime=runtime,- on_compaction=fail_observer,+ events=EventSink(fail_observer),)assert result == "Summary."diff --git a/tests/agent/test_hook_composite.py b/tests/agent/test_hook_composite.pyindex 3cde0a2c4..4eb8faae7 100644--- a/tests/agent/test_hook_composite.py+++ b/tests/agent/test_hook_composite.py@@ -15,6 +15,7 @@ from nanobot.agent.hook import (CompositeHook,)from nanobot.agent.tools.context import RequestContext+from nanobot.utils.progress_events import output_eventsdef _ctx() -> AgentHookContext:@@ -507,7 +508,7 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):await loop._run_agent_loop(TranscriptInput(history=[{"role": "user", "content": "hi"}], current_message=None),runtime=runtime,- on_progress=on_progress,+ events=output_events(on_progress=on_progress),request_context=RequestContext(channel="websocket",chat_id="chat-1",@@ -521,7 +522,8 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):assert events == ["registered:0", "turn:0"]assert [label for label, _ in captured] == ["registered", "turn"]- assert [context.on_progress for _, context in captured] == [on_progress, on_progress]+ assert captured[0][1].events is captured[1][1].events+ assert captured[0][1].events.publish is not Noneassert [context.workspace for _, context in captured] == [tmp_path, tmp_path]assert [context.channel for _, context in captured] == ["websocket", "websocket"]assert [context.chat_id for _, context in captured] == ["chat-1", "chat-1"]@@ -580,7 +582,7 @@ async def test_agent_loop_extra_hooks_do_not_swallow_loop_hook_errors(tmp_path):await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=bad_progress,+ events=output_events(on_progress=bad_progress),)diff --git a/tests/agent/test_loop_direct_websocket_status.py b/tests/agent/test_loop_direct_websocket_status.pyindex 19cdac492..82f589d34 100644--- a/tests/agent/test_loop_direct_websocket_status.py+++ b/tests/agent/test_loop_direct_websocket_status.py@@ -34,7 +34,7 @@ def _make_loop(tmp_path):bus=bus,sessions=loop.sessions,schedule_background=lambda coro: loop.schedule_background(coro),- ).subscribe(loop.runtime_events)+ ).subscribe()loop.turn_delivery_factory.route_policy = WebuiTurnRoutePolicy(loop.sessions)loop.tools.get_definitions = MagicMock(return_value=[])return loopdiff --git a/tests/agent/test_loop_progress.py b/tests/agent/test_loop_progress.pyindex cc18f1540..9d71115a2 100644--- a/tests/agent/test_loop_progress.py+++ b/tests/agent/test_loop_progress.py@@ -25,10 +25,7 @@ from nanobot.bus.queue import MessageBusfrom nanobot.providers.base import LLMResponse, ToolCallRequestfrom nanobot.providers.factory import ProviderSnapshotfrom nanobot.session.webui_turns import WebuiTurnCoordinator, WebuiTurnRoutePolicy-from nanobot.utils.progress_events import (- invoke_file_edit_progress,- on_progress_accepts_file_edit_events,-)+from nanobot.utils.progress_events import output_eventsfrom nanobot.webui.metadata import (WEBSOCKET_TURN_OWNER_METADATA_KEY,WEBUI_TURN_METADATA_KEY,@@ -55,7 +52,7 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:sessions=loop.sessions,schedule_background=lambda coro: loop.schedule_background(coro),)- coordinator.subscribe(loop.runtime_events)+ coordinator.subscribe()class TestToolEventProgress:@@ -87,7 +84,7 @@ class TestToolEventProgress:result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=on_progress,+ events=output_events(on_progress=on_progress),)assert result.final_content == "Done"@@ -160,7 +157,7 @@ class TestToolEventProgress:result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=on_progress,+ events=output_events(on_progress=on_progress),)assert result.final_content == "Done"@@ -232,7 +229,7 @@ class TestToolEventProgress:result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=on_progress,+ events=output_events(on_progress=on_progress),)assert result.final_content == "Done"@@ -272,7 +269,7 @@ class TestToolEventProgress:await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=on_progress,+ events=output_events(on_progress=on_progress),)assert file_events == []@@ -368,10 +365,8 @@ class TestToolEventProgress:chat_id="chat1",content="edit",)- progress = loop.turn_delivery_factory.create(msg, msg.session_key).progress_callback()- assert progress is not None- assert on_progress_accepts_file_edit_events(progress) is True- await invoke_file_edit_progress(progress, edit_events)+ events = loop.turn_delivery_factory.create(msg, msg.session_key).events+ await events.emit(ProgressEvent(file_edit_events=edit_events))outbound = await bus.consume_outbound()assert outbound.channel == "telegram"assert isinstance(outbound.event, ProgressEvent)@@ -685,14 +680,12 @@ class TestToolEventProgress:async def cancel_after_merge(_msg: InboundMessage,*,- on_stream,- on_stream_end,+ delivery,**_kwargs,):- assert on_stream is not None- assert on_stream_end is not None- await on_stream("partial")- await on_stream_end(resuming=True, merge_next=True)+ assert delivery.streaming+ await delivery.events.emit(StreamDeltaEvent(content="partial"))+ await delivery.events.emit(StreamEndEvent(resuming=True, merge_next=True))raise asyncio.CancelledErrorloop._process_message = cancel_after_merge # type: ignore[method-assign]@@ -1019,8 +1012,8 @@ class TestToolEventProgress:result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=on_progress,- on_stream=on_stream,+ events=output_events(on_progress=on_progress, on_stream=on_stream),+ streaming=True,)assert result.final_content == "Done"diff --git a/tests/agent/test_loop_runner_integration.py b/tests/agent/test_loop_runner_integration.pyindex e99b8b6cd..9cd02fab7 100644--- a/tests/agent/test_loop_runner_integration.py+++ b/tests/agent/test_loop_runner_integration.py@@ -22,6 +22,7 @@ from nanobot.runtime_context import ()from nanobot.session.goal_state import GOAL_STATE_KEYfrom nanobot.utils.llm_runtime import LLMRuntime+from nanobot.utils.progress_events import output_events_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars_GOAL_RUNTIME_GUIDANCE_TAG = "[Goal Runtime Guidance — host instructions]"@@ -400,8 +401,8 @@ async def test_loop_stream_filter_handles_think_only_prefix_without_crashing(tmpresult = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_stream=on_stream,- on_stream_end=on_stream_end,+ events=output_events(on_stream=on_stream, on_stream_end=on_stream_end),+ streaming=True,)assert result.final_content == "Hello"@@ -427,7 +428,8 @@ async def test_loop_stream_filter_hides_partial_trailing_think_prefix(tmp_path):result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_stream=on_stream,+ events=output_events(on_stream=on_stream),+ streaming=True,)assert result.final_content == "Hello World"@@ -452,7 +454,8 @@ async def test_loop_stream_filter_hides_complete_trailing_think_tag(tmp_path):result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_stream=on_stream,+ events=output_events(on_stream=on_stream),+ streaming=True,)assert result.final_content == "Hello World"diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.pyindex b3928874c..34bfaafaf 100644--- a/tests/agent/test_loop_save_turn.py+++ b/tests/agent/test_loop_save_turn.py@@ -129,7 +129,7 @@ def _make_full_loop(tmp_path: Path) -> AgentLoop:bus=loop.bus,sessions=loop.sessions,schedule_background=lambda coro: loop.schedule_background(coro),- ).subscribe(loop.runtime_events)+ ).subscribe()return loop@@ -1452,7 +1452,7 @@ async def test_internal_continuation_preserves_streaming_route_metadata(calls = 0- async def fake_run_agent_loop(transcript_input, *, on_stream=None, on_stream_end=None, **_kwargs):+ async def fake_run_agent_loop(transcript_input, *, events, streaming, **_kwargs):nonlocal callsinitial_messages = _assembled_messages(loop.context, transcript_input)calls += 1@@ -1462,10 +1462,9 @@ async def test_internal_continuation_preserves_streaming_route_metadata([*initial_messages, {"role": "assistant", "content": "paused"}],stop_reason="max_iterations",)- assert on_stream is not None- assert on_stream_end is not None- await on_stream("done")- await on_stream_end(resuming=False)+ assert streaming+ await events.emit(StreamDeltaEvent(content="done"))+ await events.emit(StreamEndEvent())return _agent_run_result("done",[*initial_messages, {"role": "assistant", "content": "done"}],diff --git a/tests/agent/test_runner_core.py b/tests/agent/test_runner_core.pyindex b68448115..4ffb180a0 100644--- a/tests/agent/test_runner_core.py+++ b/tests/agent/test_runner_core.py@@ -1281,9 +1281,10 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():@pytest.mark.asyncio-async def test_runner_binds_on_retry_wait_callback():- """Provider retry heartbeats use the explicitly supplied callback."""+async def test_runner_carries_retry_notifications_in_provider_context():+ """The runner carries a generic scope, not an event-specific callback."""from nanobot.agent.runner import AgentRunner+ from nanobot.events import EventSink, RetryWaitEventcaptured: dict = {}@@ -1308,10 +1309,13 @@ async def test_runner_binds_on_retry_wait_callback():model="test-model",max_iterations=1,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,- retry_wait_callback=retry_wait_cb,+ events=EventSink(retry_wait_cb),))- assert captured["on_retry_wait"] is retry_wait_cb+ assert "on_retry_wait" not in captured+ event = RetryWaitEvent("waiting")+ await captured["provider_context"].events.emit(event)+ retry_wait_cb.assert_awaited_once_with(event)# ---------------------------------------------------------------------------diff --git a/tests/agent/test_runner_fallback.py b/tests/agent/test_runner_fallback.pyindex 5cff85679..aeefe8af7 100644--- a/tests/agent/test_runner_fallback.py+++ b/tests/agent/test_runner_fallback.py@@ -169,6 +169,28 @@ def test_fallback_models_accept_preset_refs_and_inline_configs() -> None:)+async def test_fallback_preserves_the_operation_event_sink():+ from nanobot.events import EventSink++ async def observe(event):+ pass++ events = EventSink(observe)+ primary = _FakeProvider("primary", _error_response())+ fallback = _FakeProvider("fallback", _make_response("fallback ok"))+ fb = FallbackProvider(+ primary=primary, fallback_presets=[_fallback("fallback-a")],+ provider_factory=MagicMock(return_value=fallback),+ )+ result = await fb.chat_with_context(+ messages=[{"role": "user", "content": "hello"}], model="primary",+ provider_context=ProviderCallContext(events=events),+ )+ assert result.content == "fallback ok"+ assert primary.context_calls[0].events is events+ assert fallback.context_calls[0].events is events++def test_fallback_model_preset_ref_must_exist() -> None:from nanobot.config.schema import Config@@ -1047,6 +1069,48 @@ class TestFailoverOnTransientError:class TestRetryBeforeFailover:+ @pytest.mark.parametrize("stream", [False, True])+ async def test_scoped_retry_events_preserve_fallback_chain_ownership(self, stream):+ from nanobot.events import EventSink, RetryWaitEvent++ primary = _FakeProvider("primary", _retryable_error("primary unavailable"))+ fallback = _FakeProvider("fallback", _make_response("fallback ok"))+ provider = FallbackProvider(primary, [_fallback("fallback-a")],+ MagicMock(return_value=fallback))+ observe = AsyncMock()+ call = provider.chat_stream_with_retry if stream else provider.chat_with_retry+ with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):+ result = await call(+ [{"role": "user", "content": "hi"}],+ provider_context=ProviderCallContext(events=EventSink(observe)),+ )+ assert result.content == "fallback ok"+ events = [call.args[0] for call in observe.await_args_list]+ assert len(events) == 3+ assert all(isinstance(event, RetryWaitEvent) for event in events)+ assert not any("giving up" in event.content for event in events)++ async def test_scoped_persistent_retry_includes_chain_wait_and_one_terminal(self):+ from nanobot.events import EventSink++ primary = _FakeProvider("primary", _retryable_error("primary unavailable"))+ fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))+ provider = FallbackProvider(primary, [_fallback("fallback-a")],+ MagicMock(return_value=fallback))+ provider._PERSISTENT_IDENTICAL_ERROR_LIMIT = 2+ observe = AsyncMock()+ with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):+ result = await provider.chat_with_retry(+ [{"role": "user", "content": "hi"}], retry_mode="persistent",+ provider_context=ProviderCallContext(events=EventSink(observe)),+ )+ assert result.finish_reason == "error"+ notices = [call.args[0].content for call in observe.await_args_list]+ # Two candidates, three waits each, for two chains, plus one chain wait.+ assert len(notices) == 14+ assert sum("Persistent retry stopped" in text for text in notices) == 1+ assert not any("giving up" in text for text in notices)+@pytest.mark.asyncio@pytest.mark.parametrize("retry_mode", ["standard", "persistent"])async def test_primary_recovers_before_fallback(self, retry_mode: str) -> None:diff --git a/tests/agent/test_runner_governance.py b/tests/agent/test_runner_governance.pyindex 5f9c32f22..6341ab169 100644--- a/tests/agent/test_runner_governance.py+++ b/tests/agent/test_runner_governance.py@@ -16,8 +16,8 @@ from nanobot.agent.context_governance import (ModelRequestState,)from nanobot.agent.runner import AgentRunner, AgentRunSpec-from nanobot.bus.outbound_events import ContextCompactionEventfrom nanobot.config.schema import AgentDefaults+from nanobot.events import ContextCompactionEvent, EventSinkfrom nanobot.providers.base import (LLMProvider,LLMResponse,@@ -76,6 +76,32 @@ def _make_loop(tmp_path):return loop+async def test_provider_can_emit_without_an_event_specific_runner_callback():+ from nanobot.events import AgentEvent++ event = AgentEvent()+ received = []++ async def observe(value):+ received.append(value)++ async def request(*, provider_context, **kwargs):+ await provider_context.events.emit(event)+ return LLMResponse(content="done")++ provider = MagicMock(spec=LLMProvider)+ provider.chat_with_retry = request+ tools = MagicMock()+ tools.get_definitions.return_value = []+ await AgentRunner().run(make_run_spec(+ provider, model="test-model", tools=tools, max_iterations=1,+ max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,+ initial_messages=[{"role": "user", "content": "hello"}],+ events=EventSink(observe),+ ))+ assert received == [event]++async def test_runner_propagates_context_governance_failure():from nanobot.agent.runner import AgentRunner@@ -394,7 +420,7 @@ async def test_native_compaction_uses_provider_request_boundary(max_tokens=100,max_iterations=2,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,- compaction_callback=observe_compaction,+ events=EventSink(observe_compaction),))consolidate.assert_not_awaited()@@ -534,7 +560,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):max_tokens=100,max_iterations=3,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,- compaction_callback=observe_compaction,+ events=EventSink(observe_compaction),))assert consolidate.await_count == 2diff --git a/tests/agent/test_runner_progress_deltas.py b/tests/agent/test_runner_progress_deltas.pyindex 6961b685c..30e9794f9 100644--- a/tests/agent/test_runner_progress_deltas.py+++ b/tests/agent/test_runner_progress_deltas.py@@ -12,6 +12,7 @@ from nanobot.agent.runner import AgentRunnerfrom nanobot.agent.tools.filesystem import EditFileTool, WriteFileToolfrom nanobot.config.schema import AgentDefaultsfrom nanobot.providers.base import LLMResponse, ToolCallRequest+from nanobot.utils.progress_events import output_events_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars@@ -61,7 +62,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():async def stream_cb(content: str) -> None:streamed_text.append(content)- hook = AgentProgressHook(on_progress=progress_cb, on_stream=stream_cb)+ hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)result = await AgentRunner().run(make_run_spec(provider,initial_messages=[{"role": "user", "content": "search X"}],@@ -135,7 +136,7 @@ async def test_runner_fails_pending_hosted_tool_when_model_request_fails():async def stream_cb(_content: str) -> None:pass- hook = AgentProgressHook(on_progress=progress_cb, on_stream=stream_cb)+ hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)result = await AgentRunner().run(make_run_spec(provider,initial_messages=[{"role": "user", "content": "search X"}],@@ -213,7 +214,7 @@ async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_pamax_iterations=2,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,workspace=tmp_path,- hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),+ hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),))assert result.final_content == "done"@@ -283,7 +284,7 @@ async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_patmax_iterations=2,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,workspace=tmp_path,- hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),+ hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),))assert result.final_content == "done"@@ -345,7 +346,7 @@ async def test_runner_marks_file_edit_activity_failed_when_tool_errors(tmp_path)max_iterations=2,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,workspace=tmp_path,- hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),+ hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),))assert result.stop_reason == "completed"@@ -405,7 +406,7 @@ async def test_runner_marks_file_edit_activity_failed_when_cancelled(tmp_path):max_iterations=2,max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,workspace=tmp_path,- hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),+ hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),)))await asyncio.wait_for(executing.wait(), timeout=1)diff --git a/tests/agent/test_runner_reasoning.py b/tests/agent/test_runner_reasoning.pyindex dca0abec9..f5c074416 100644--- a/tests/agent/test_runner_reasoning.py+++ b/tests/agent/test_runner_reasoning.py@@ -20,6 +20,7 @@ from nanobot.agent.hook import AgentHook, AgentHookContextfrom nanobot.agent.progress_hook import AgentProgressHookfrom nanobot.config.schema import AgentDefaultsfrom nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest+from nanobot.utils.progress_events import output_events_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars@@ -324,7 +325,7 @@ async def test_runner_does_not_double_emit_when_inline_think_already_streamed():async def _stream(_content: str) -> None:pass- hook = AgentProgressHook(on_progress=_progress, on_stream=_stream)+ hook = AgentProgressHook(output_events(on_progress=_progress, on_stream=_stream), streaming=True)runner = AgentRunner()result = await runner.run(make_run_spec(provider,initial_messages=[{"role": "user", "content": "question"}],diff --git a/tests/agent/test_runtime_refresh.py b/tests/agent/test_runtime_refresh.pyindex 7af7ee31f..b996c6988 100644--- a/tests/agent/test_runtime_refresh.py+++ b/tests/agent/test_runtime_refresh.py@@ -224,7 +224,7 @@ async def test_config_invalidation_defers_canonical_notification_until_default_rmodel_preset="fast",preset_snapshot_loader=load_preset,)- loop.runtime_events.subscribe(published.append, RuntimeModelChanged)+ loop.bus.subscribe(published.append, RuntimeModelChanged)session = loop.sessions.get_or_create("websocket:chat")session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"current_model = "model-b"@@ -275,7 +275,7 @@ async def test_config_refresh_publishes_renamed_canonical_preset(tmp_path: Path)model_preset="fast",preset_snapshot_loader=load_preset,)- loop.runtime_events.subscribe(published.append, RuntimeModelChanged)+ loop.bus.subscribe(published.append, RuntimeModelChanged)catalog["Codex"] = catalog.pop("fast")default_name = "Codex"diff --git a/tests/agent/test_task_cancel.py b/tests/agent/test_task_cancel.pyindex 0e71e8a7f..562081e90 100644--- a/tests/agent/test_task_cancel.py+++ b/tests/agent/test_task_cancel.py@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEventfrom nanobot.config.schema import AgentDefaultsfrom nanobot.providers.base import GenerationSettingsfrom nanobot.session.keys import UNIFIED_SESSION_KEY@@ -277,7 +278,6 @@ class TestDispatch:@pytest.mark.asyncioasync def test_dispatch_streaming_preserves_message_metadata(self):from nanobot.bus.events import InboundMessage- from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEventloop, bus = _make_loop()msg = InboundMessage(@@ -292,11 +292,10 @@ class TestDispatch:},)- async def fake_process(_msg, *, on_stream=None, on_stream_end=None, **kwargs):- assert on_stream is not None- assert on_stream_end is not None- await on_stream("hi")- await on_stream_end(resuming=False)+ async def fake_process(_msg, *, delivery, **kwargs):+ assert delivery.streaming+ await delivery.events.emit(StreamDeltaEvent(content="hi"))+ await delivery.events.emit(StreamEndEvent())return Noneloop._process_message = fake_processdiff --git a/tests/agent/test_turn_delivery.py b/tests/agent/test_turn_delivery.pyindex 10e862288..9b7ef235a 100644--- a/tests/agent/test_turn_delivery.py+++ b/tests/agent/test_turn_delivery.py@@ -6,7 +6,6 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactoryfrom nanobot.bus.events import InboundMessagefrom nanobot.bus.outbound_events import ContextCompactionEventfrom nanobot.bus.queue import MessageBus-from nanobot.bus.runtime_events import RuntimeEventBusfrom nanobot.session.manager import SessionManagerfrom nanobot.session.webui_turns import WebuiTurnRoutePolicyfrom nanobot.webui.metadata import (@@ -31,7 +30,7 @@ from nanobot.webui.metadata import (async def test_idle_compaction_uses_the_session_delivery_route(key, channel, chat_id, metadata, unified,) -> None:- factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())+ factory = TurnDeliveryFactory(MessageBus())event = ContextCompactionEvent(compaction_id="compact-1", phase="started")key = "unified:default" if unified else keymsg = InboundMessage(@@ -45,9 +44,9 @@ async def test_idle_compaction_uses_the_session_delivery_route(session_metadata = {}delivery.remember_session_route(session_metadata)- callback = factory.session_compaction_callback(key, session_metadata)- assert callback is not None- await callback(event)+ sink = factory.session_events(key, session_metadata)+ assert sink.publish is not None+ await sink.emit(event)outbound = factory.bus.outbound.get_nowait()assert (outbound.channel, outbound.chat_id, outbound.metadata) == (channel, chat_id, metadata)@@ -55,7 +54,7 @@ async def test_idle_compaction_uses_the_session_delivery_route(async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:- factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())+ factory = TurnDeliveryFactory(MessageBus())key = "unified:default"session_metadata = {}original = InboundMessage(@@ -63,15 +62,15 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->metadata={"slack": {"thread_ts": "1700000000.000100"}},)factory.create(original, key).remember_session_route(session_metadata)- callback = factory.session_compaction_callback(key, session_metadata)- assert callback is not None- await callback(ContextCompactionEvent("compact-1", "started"))+ sink = factory.session_events(key, session_metadata)+ assert sink.publish is not None+ await sink.emit(ContextCompactionEvent("compact-1", "started"))latest = InboundMessage(channel="telegram", sender_id="user", chat_id="42", content="next question",)factory.create(latest, key).remember_session_route(session_metadata)- await callback(ContextCompactionEvent("compact-1", "succeeded"))+ await sink.emit(ContextCompactionEvent("compact-1", "succeeded"))events = [factory.bus.outbound.get_nowait() for _ in range(2)]assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [@@ -80,11 +79,11 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> None:- factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())+ factory = TurnDeliveryFactory(MessageBus())event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded")- callback = factory.session_compaction_callback("websocket:chat", {})- assert callback is not None- await callback(event)+ sink = factory.session_events("websocket:chat", {})+ assert sink.publish is not None+ await sink.emit(event)outbound = factory.bus.outbound.get_nowait()assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event)@@ -92,7 +91,6 @@ async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> Nodef test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None:factory = TurnDeliveryFactory(MessageBus(),- RuntimeEventBus(),route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),)first_msg = InboundMessage(@@ -141,7 +139,6 @@ def test_websocket_lifecycle_reuses_registered_ingress_owner(tmp_path: Path) ->)factory = TurnDeliveryFactory(MessageBus(),- RuntimeEventBus(),route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),)@@ -163,7 +160,6 @@ def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> Nsessions.save(target)factory = TurnDeliveryFactory(MessageBus(),- RuntimeEventBus(),route_policy=WebuiTurnRoutePolicy(sessions),)msg = InboundMessage(@@ -194,7 +190,6 @@ async def test_same_chat_different_sessions_restore_previous_active_projection(factory = TurnDeliveryFactory(MessageBus(),- RuntimeEventBus(),route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),)first_msg = InboundMessage(@@ -253,7 +248,6 @@ def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> Nonsessions = SessionManager(tmp_path)factory = TurnDeliveryFactory(MessageBus(),- RuntimeEventBus(),route_policy=WebuiTurnRoutePolicy(sessions),)session_key = "websocket:chat-a"diff --git a/tests/agent/tools/test_long_task.py b/tests/agent/tools/test_long_task.pyindex 0889b061b..423f9f4af 100644--- a/tests/agent/tools/test_long_task.py+++ b/tests/agent/tools/test_long_task.py@@ -21,7 +21,6 @@ from nanobot.agent.tools.long_task import (from nanobot.agent.tools.registry import ToolRegistryfrom nanobot.bus.outbound_events import GoalStateSyncEventfrom nanobot.bus.queue import MessageBus-from nanobot.bus.runtime_events import RuntimeEventBusfrom nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARSfrom nanobot.session.manager import SessionManagerfrom nanobot.session.turn_continuation import should_finalize_on_max_iterations@@ -378,17 +377,16 @@ async def test_registry_does_not_reuse_goal_context_after_request_scope(tmp_path@pytest.mark.asyncioasync def test_goal_state_events_publish_active_then_inactive(tmp_path):- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()- runtime_events = RuntimeEventBus()sm = SessionManager(tmp_path)WebuiTurnCoordinator(bus=bus,sessions=sm,schedule_background=lambda _coro: None,- ).subscribe(runtime_events)- create = CreateGoalTool(sessions=sm, runtime_events=runtime_events)- update = UpdateGoalTool(sessions=sm, runtime_events=runtime_events)+ ).subscribe()+ create = CreateGoalTool(sessions=sm, bus=bus)+ update = UpdateGoalTool(sessions=sm, bus=bus)rc = _request_context(chat_id="chat-99")await _execute(create,diff --git a/tests/bus/test_notifications.py b/tests/bus/test_notifications.pynew file mode 100644index 000000000..c2a3ddffe--- /dev/null+++ b/tests/bus/test_notifications.py@@ -0,0 +1,175 @@+import asyncio+from dataclasses import dataclass++import pytest++from nanobot.agent.turn_delivery import TurnDeliveryFactory, TurnRoute+from nanobot.bus.events import InboundMessage, OutboundMessage+from nanobot.bus.notification_delivery import NOTIFICATION_AUDIENCES+from nanobot.bus.outbound_events import (+ FileEditEvent,+ ProgressEvent,+ StreamDeltaEvent,+ StreamEndEvent,+)+from nanobot.bus.queue import MessageBus+from nanobot.events import AgentEvent, ContextCompactionEvent, EventSink, RetryWaitEvent+from nanobot.utils.progress_events import output_events+from nanobot.webui.outbound_wire import project_notification+++async def test_sink_isolates_observer_failure_but_propagates_cancellation():+ async def broken(event):+ raise ValueError("observer failed")++ await EventSink(broken).emit(AgentEvent())++ async def cancelled(event):+ raise asyncio.CancelledError++ with pytest.raises(asyncio.CancelledError):+ await EventSink(cancelled).emit(AgentEvent())+++async def test_scoped_output_preserves_routing_and_stream_segment_ownership():+ bus = MessageBus()+ delivery = TurnDeliveryFactory(bus).create(InboundMessage(+ channel="websocket", sender_id="u", chat_id="chat", content="",+ metadata={"_wants_stream": True, "origin_message_id": "original"},+ ), "websocket:chat", enable_stream=True)+ events = [+ ProgressEvent(content="thinking"),+ FileEditEvent(file_edit_events=[{"phase": "start", "path": "a.py"}]),+ StreamDeltaEvent(content="first"),+ StreamEndEvent(resuming=True, merge_next=True),+ StreamDeltaEvent(content="tail"),+ ]+ for event in events:+ await delivery.events.emit(event)+ await delivery.abort_stream()+ messages = [bus.outbound.get_nowait() for _ in range(6)]+ assert [message.content for message in messages] == ["thinking", "", "first", "", "tail", ""]+ assert all(message.chat_id == "chat" for message in messages)+ assert all(message.metadata["origin_message_id"] == "original" for message in messages)+ streams = [message.event for message in messages[2:]]+ assert all(isinstance(event, StreamDeltaEvent | StreamEndEvent) for event in streams)+ assert len({event.stream_id for event in streams}) == 1+ assert isinstance(streams[-1], StreamEndEvent)+ assert streams[-1].merge_next is False+ await delivery.abort_stream()+ assert bus.outbound.empty()+++async def test_output_consumer_capability_survives_callback_adaptation():+ bus = MessageBus()+ quiet = TurnDeliveryFactory(bus, lambda *_: TurnRoute("websocket", "chat")).create(+ InboundMessage(channel="system", sender_id="job", chat_id="websocket:chat", content=""),+ "websocket:chat",+ )+ assert quiet.events.accepts(ContextCompactionEvent)+ assert not quiet.events.accepts(FileEditEvent)++ received = []++ async def text_only(content, *, tool_hint=False):+ received.append(content)++ events = output_events(default=quiet.events, on_progress=text_only)+ assert events.accepts(ProgressEvent)+ assert not events.accepts(FileEditEvent)+ await events.emit(ProgressEvent(content="working"))+ await events.emit(ContextCompactionEvent("compact", "succeeded"))+ assert received == ["working"]+ assert bus.outbound.get_nowait().event == ContextCompactionEvent("compact", "succeeded")+++async def test_scope_snapshots_route_and_queues_events_in_order():+ bus = MessageBus()+ metadata = {"slack": {"thread_ts": "original"}}+ factory = TurnDeliveryFactory(bus)+ delivery = factory.create(InboundMessage(+ channel="slack", sender_id="u", chat_id="chat", content="", metadata=metadata,+ ), "unified:default")+ metadata["slack"]["thread_ts"] = "moved"+ for phase in ("started", "succeeded"):+ await delivery.events.emit(ContextCompactionEvent("c1", phase))+ for phase in ("started", "succeeded"):+ message = bus.outbound.get_nowait()+ assert message.metadata == {"slack": {"thread_ts": "original"}}+ assert message.event == ContextCompactionEvent("c1", phase)+ assert bus.outbound.empty()+++async def test_new_internal_event_needs_explicit_audience(monkeypatch):+ @dataclass(frozen=True)+ class RetryStatus(AgentEvent):+ state: str = "waiting"+ attempt: int = 1++ bus = MessageBus()+ factory = TurnDeliveryFactory(bus)+ delivery = factory.create(InboundMessage(+ channel="websocket", sender_id="u", chat_id="chat", content="",+ ), "websocket:chat")+ event = RetryStatus()+ await delivery.events.emit(event)+ assert bus.outbound.empty()+ assert project_notification("chat", event) is None++ monkeypatch.setitem(NOTIFICATION_AUDIENCES, RetryStatus, "interactive")+ await delivery.events.emit(event)+ assert bus.outbound.get_nowait().event is event+ # Routing registration alone does not authorize serialization of private fields.+ assert project_notification("chat", event) is None+++async def test_background_scope_keeps_retry_quiet_but_delivers_compaction():+ bus = MessageBus()+ factory = TurnDeliveryFactory(bus,+ lambda *_: TurnRoute("websocket", "chat"))+ delivery = factory.create(InboundMessage(+ channel="system", sender_id="job", chat_id="websocket:chat", content="",+ ), "websocket:chat")+ await delivery.events.emit(RetryWaitEvent("waiting"))+ assert bus.outbound.empty()+ event = ContextCompactionEvent("c1", "cancelled")+ await delivery.events.emit(event)+ assert bus.outbound.get_nowait().event is event++[email protected]("channel", ["websocket", "cli", "slack", "custom"])+async def test_bus_routes_arbitrary_events_and_text_through_one_queue(channel):+ @dataclass(frozen=True)+ class JobFinished(AgentEvent):+ job_id: str++ bus = MessageBus()+ text = OutboundMessage(channel=channel, chat_id="chat", content="hello")+ event = JobFinished("job-1")+ await bus.publish_outbound(text)+ await bus.publish_event(event, channel=channel, chat_id="chat", metadata={"thread": "1"})+ assert await bus.consume_outbound() is text+ delivered = await bus.consume_outbound()+ assert (delivered.channel, delivered.chat_id) == (channel, "chat")+ assert delivered.event is event+ assert delivered.content == ""+ assert delivered.metadata == {"thread": "1"}+ assert bus.outbound.empty()+++async def test_bus_event_preserves_existing_text_fallback():+ bus = MessageBus()+ event = RetryWaitEvent("waiting")+ await bus.publish_event(event, channel="slack", chat_id="chat")+ delivered = await bus.consume_outbound()+ assert delivered.event is event+ assert delivered.content == "waiting"++[email protected]("phase", ["started", "succeeded", "failed", "cancelled"])+def test_compaction_durability_is_independent_of_subscribers(phase):+ projection = project_notification("chat", ContextCompactionEvent("c1", phase))+ assert projection is not None+ assert projection.deliver_offline+ assert projection.attach_turn_metadata+ assert projection.persistence == ("transient" if phase == "started" else "turn_activity")diff --git a/tests/bus/test_outbound_events.py b/tests/bus/test_outbound_events.pyindex f6a60b98e..6b6f254ee 100644--- a/tests/bus/test_outbound_events.py+++ b/tests/bus/test_outbound_events.py@@ -3,17 +3,10 @@ from __future__ import annotationsfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import (ContextCompactionEvent,- GoalStateSyncEvent,- GoalStatusEvent,ProgressEvent,- RetryWaitEvent,- RuntimeModelUpdatedEvent,- SessionUpdatedEvent,StreamDeltaEvent,StreamedResponseEvent,StreamEndEvent,- TurnEndEvent,- outbound_event_from_message,outbound_message_for_event,replace_outbound_event,)@@ -52,7 +45,7 @@ def test_progress_event_lives_on_outbound_message_event_field() -> None:assert msg.content == "working"assert msg.metadata == {"origin_message_id": "m1"}- event = outbound_event_from_message(msg)+ event = msg.eventassert isinstance(event, ProgressEvent)assert event.content == "working"assert event.tool_hint is True@@ -65,169 +58,12 @@ def test_progress_event_lives_on_outbound_message_event_field() -> None:def test_normal_outbound_message_has_no_runtime_event() -> None:msg = OutboundMessage(channel="websocket", chat_id="chat-1", content="hello")- assert outbound_event_from_message(msg) is None+ assert msg.event is None-def test_legacy_progress_metadata_flags_create_runtime_event() -> None:- tool_events = [{"phase": "start", "name": "read_file"}]- file_edit_events = [{"phase": "end", "path": "app.py"}]- msg = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="legacy progress",- metadata={- "_progress": True,- "_tool_hint": True,- "_reasoning_delta": True,- "_stream_id": "r1",- "_tool_events": tool_events,- "_file_edit_events": file_edit_events,- "message_id": "platform-routing-context",- },- )-- event = outbound_event_from_message(msg)- assert isinstance(event, ProgressEvent)- assert event.content == "legacy progress"- assert event.tool_hint is True- assert event.reasoning_delta is True- assert event.stream_id == "r1"- assert event.tool_events == tool_events- assert event.file_edit_events == file_edit_events---def test_legacy_stream_metadata_flags_create_runtime_events() -> None:- delta = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="hello",- metadata={"_stream_delta": True, "_stream_id": "s1"},- )- end = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={- "_stream_end": True,- "_stream_id": "s1",- "_resuming": True,- "_merge_next": True,- },- )-- delta_event = outbound_event_from_message(delta)- assert isinstance(delta_event, StreamDeltaEvent)- assert delta_event.content == "hello"- assert delta_event.stream_id == "s1"-- end_event = outbound_event_from_message(end)- assert isinstance(end_event, StreamEndEvent)- assert end_event.stream_id == "s1"- assert end_event.resuming is True- assert end_event.merge_next is True---def test_legacy_webui_runtime_metadata_flags_create_runtime_events() -> None:- runtime = OutboundMessage(- channel="websocket",- chat_id="*",- content="",- metadata={- "_runtime_model_updated": True,- "model": "gpt-5.5",- "model_preset": "high",- },- )- goal_state = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={"_goal_state_sync": True, "goal_state": {"active": True}},- )- goal_status = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={"_goal_status": True, "goal_status": "running", "started_at": 1.25},- )- turn_end = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={"_turn_end": True, "latency_ms": 42.0, "goal_state": {"active": False}},- )- session_updated = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={"_session_updated": True, "_session_update_scope": "metadata"},- )-- runtime_event = outbound_event_from_message(runtime)- assert isinstance(runtime_event, RuntimeModelUpdatedEvent)- assert runtime_event.model == "gpt-5.5"- assert runtime_event.model_preset == "high"-- goal_state_event = outbound_event_from_message(goal_state)- assert isinstance(goal_state_event, GoalStateSyncEvent)- assert goal_state_event.goal_state == {"active": True}-- goal_status_event = outbound_event_from_message(goal_status)- assert isinstance(goal_status_event, GoalStatusEvent)- assert goal_status_event.status == "running"- assert goal_status_event.started_at == 1.25-- turn_end_event = outbound_event_from_message(turn_end)- assert isinstance(turn_end_event, TurnEndEvent)- assert turn_end_event.latency_ms == 42- assert turn_end_event.goal_state == {"active": False}-- session_updated_event = outbound_event_from_message(session_updated)- assert isinstance(session_updated_event, SessionUpdatedEvent)- assert session_updated_event.scope == "metadata"---def test_legacy_metadata_numbers_ignore_bool_values() -> None:- goal_status = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={"_goal_status": True, "goal_status": "running", "started_at": True},- )- turn_end = OutboundMessage(- channel="websocket",- chat_id="chat-1",- content="",- metadata={"_turn_end": True, "latency_ms": True},- )-- goal_status_event = outbound_event_from_message(goal_status)- assert isinstance(goal_status_event, GoalStatusEvent)- assert goal_status_event.started_at is None-- turn_end_event = outbound_event_from_message(turn_end)- assert isinstance(turn_end_event, TurnEndEvent)- assert turn_end_event.latency_ms is None-def test_legacy_retry_wait_and_streamed_flags_create_runtime_events() -> None:- retry = OutboundMessage(- channel="cli",- chat_id="direct",- content="waiting",- metadata={"_retry_wait": True},- )- streamed = OutboundMessage(- channel="cli",- chat_id="direct",- content="final answer",- metadata={"_streamed": True},- )- retry_event = outbound_event_from_message(retry)- assert isinstance(retry_event, RetryWaitEvent)- assert retry_event.content == "waiting"- assert isinstance(outbound_event_from_message(streamed), StreamedResponseEvent)def test_replace_outbound_event_keeps_routing_metadata() -> None:@@ -261,4 +97,4 @@ def test_streamed_response_event_keeps_final_content_outside_event_payload() ->)assert msg.content == "final answer"- assert isinstance(outbound_event_from_message(msg), StreamedResponseEvent)+ assert isinstance(msg.event, StreamedResponseEvent)diff --git a/tests/bus/test_runtime_events.py b/tests/bus/test_runtime_events.pyindex 610c799d8..fbd694618 100644--- a/tests/bus/test_runtime_events.py+++ b/tests/bus/test_runtime_events.py@@ -1,8 +1,11 @@+import asyncio+import pytestfrom nanobot.bus.events import InboundMessage+from nanobot.bus.outbound_events import ProgressEvent+from nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import (- RuntimeEventBus,RuntimeEventContext,RuntimeEventPublisher,RuntimeModelChanged,@@ -15,9 +18,101 @@ from nanobot.bus.runtime_events import (from nanobot.providers.base import LLMUsage+async def test_local_state_subscriber_does_not_block_routed_delivery():+ bus = MessageBus()+ entered, release = asyncio.Event(), asyncio.Event()++ async def observe(event):+ entered.set()+ await release.wait()++ bus.subscribe(observe, RuntimeModelChanged)+ dispatch = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))+ try:+ await asyncio.wait_for(entered.wait(), timeout=1)+ await asyncio.wait_for(+ bus.publish_event(ProgressEvent(content="working"), channel="cli", chat_id="other"),+ timeout=1,+ )+ message = await asyncio.wait_for(bus.consume_outbound(), timeout=1)+ assert (message.chat_id, message.content) == ("other", "working")+ assert not dispatch.done()+ finally:+ release.set()+ await dispatch+++async def test_disconnect_skips_a_handler_in_an_existing_dispatch_snapshot():+ bus = MessageBus()+ seen = []++ def first(event):+ disconnect()++ bus.subscribe(first)+ disconnect = bus.subscribe(seen.append)+ await bus.publish(RuntimeModelChanged("model", None))+ disconnect()+ assert seen == []+++async def test_awaited_dispatch_preserves_order_and_propagates_cancellation():+ bus = MessageBus()+ entered, release = asyncio.Event(), asyncio.Event()+ seen = []++ async def slow(event):+ entered.set()+ await release.wait()+ seen.append("first")++ bus.subscribe(slow)+ bus.subscribe(lambda event: seen.append("second"))+ task = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))+ await entered.wait()+ assert not task.done()+ assert seen == []+ release.set()+ await task+ assert seen == ["first", "second"]++ release.clear()+ entered.clear()+ task = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))+ await entered.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert seen == ["first", "second"]+++async def test_scheduled_dispatch_is_owned_and_can_be_drained():+ bus = MessageBus()+ entered, release = asyncio.Event(), asyncio.Event()+ seen = []++ async def slow(event):+ entered.set()+ await release.wait()+ seen.append(event.model)++ bus.subscribe(slow, RuntimeModelChanged)+ task = bus.publish_nowait(RuntimeModelChanged("model", None))+ assert task is not None+ assert not entered.is_set()+ await entered.wait()+ draining = asyncio.create_task(bus.drain())+ assert seen == []+ release.set()+ await draining+ assert task.done()+ assert seen == ["model"]+ await bus.drain()++@pytest.mark.asyncioasync def test_runtime_event_bus_filters_by_event_type() -> None:- bus = RuntimeEventBus()+ bus = MessageBus()seen: list[str] = []async def handle_run_status(event: TurnRunStatusChanged) -> None:@@ -42,7 +137,7 @@ async def test_runtime_event_bus_filters_by_event_type() -> None:@pytest.mark.asyncioasync def test_runtime_event_bus_keeps_catch_all_subscription() -> None:- bus = RuntimeEventBus()+ bus = MessageBus()seen: list[str] = []def handle_any(event) -> None:@@ -57,7 +152,7 @@ async def test_runtime_event_bus_keeps_catch_all_subscription() -> None:@pytest.mark.asyncioasync def test_runtime_event_publisher_builds_context_from_inbound_message() -> None:- bus = RuntimeEventBus()+ bus = MessageBus()seen: list[object] = []publisher = RuntimeEventPublisher(bus)msg = InboundMessage(@@ -93,7 +188,7 @@ async def test_runtime_event_publisher_builds_context_from_inbound_message() ->@pytest.mark.asyncioasync def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> None:- bus = RuntimeEventBus()+ bus = MessageBus()seen: list[object] = []publisher = RuntimeEventPublisher(bus)@@ -134,7 +229,7 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N@pytest.mark.asyncioasync def test_runtime_event_publisher_exposes_admitted_runtime() -> None:- bus = RuntimeEventBus()+ bus = MessageBus()seen: list[object] = []publisher = RuntimeEventPublisher(bus)msg = InboundMessage(@@ -165,7 +260,7 @@ async def test_runtime_event_publisher_exposes_admitted_runtime() -> None:@pytest.mark.asyncioasync def test_runtime_event_publisher_emits_persisted_turn_attributes() -> None:- bus = RuntimeEventBus()+ bus = MessageBus()seen: list[object] = []publisher = RuntimeEventPublisher(bus)msg = InboundMessage(diff --git a/tests/channels/test_channel_manager_concurrency.py b/tests/channels/test_channel_manager_concurrency.pynew file mode 100644index 000000000..4ae168cc6--- /dev/null+++ b/tests/channels/test_channel_manager_concurrency.py@@ -0,0 +1,187 @@+import asyncio+from unittest.mock import AsyncMock, MagicMock++from nanobot.bus.events import OutboundMessage+from nanobot.bus.queue import MessageBus+from nanobot.channels import manager as manager_module+from nanobot.channels.base import BaseChannel+from nanobot.channels.manager import ChannelManager+from nanobot.config.schema import Config+++def make_manager():+ config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})+ manager = ChannelManager(config, MessageBus())+ channel = MagicMock(spec=BaseChannel)+ channel.send = AsyncMock()+ channel.stop = AsyncMock()+ manager.channels["websocket"] = channel+ return manager, channel+++async def wait_until(predicate):+ async with asyncio.timeout(2):+ while not predicate():+ await asyncio.sleep(0)+++async def test_ten_chats_keep_order_while_one_destination_is_blocked():+ manager, channel = make_manager()+ release = asyncio.Event()+ started = asyncio.Event()+ received = {str(i): [] for i in range(10)}++ async def send(msg):+ if msg.chat_id == "0":+ started.set()+ await release.wait()+ received[msg.chat_id].append(msg.content)++ channel.send.side_effect = send+ manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())+ try:+ for content in ("first", "last"):+ for i in range(10):+ await manager.bus.publish_outbound(OutboundMessage("websocket", str(i), content))+ await asyncio.wait_for(started.wait(), 2)+ await wait_until(lambda: all(len(received[str(i)]) == 2 for i in range(1, 10)))+ assert received["0"] == []+ assert all(received[str(i)] == ["first", "last"] for i in range(1, 10))+ release.set()+ await wait_until(lambda: not manager._outbound_tasks)+ assert received["0"] == ["first", "last"]+ assert manager._outbound_tails == {}+ finally:+ await manager.stop_all()+++async def test_retry_does_not_block_other_chats(monkeypatch):+ monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.1,))+ manager, channel = make_manager()+ retry_started = asyncio.Event()+ healthy_sent = asyncio.Event()+ attempts = 0++ async def send(msg):+ nonlocal attempts+ if msg.chat_id == "retry":+ attempts += 1+ if attempts == 1:+ retry_started.set()+ raise OSError("temporary failure")+ assert healthy_sent.is_set()+ else:+ healthy_sent.set()++ channel.send.side_effect = send+ channel.should_retry_send_error.return_value = True+ try:+ await manager._queue_outbound(channel, OutboundMessage("websocket", "retry", "a"))+ await asyncio.wait_for(retry_started.wait(), 2)+ await manager._queue_outbound(channel, OutboundMessage("websocket", "healthy", "b"))+ await wait_until(lambda: not manager._outbound_tasks)+ assert attempts == 2+ assert healthy_sent.is_set()+ finally:+ await manager._cancel_outbound()+++async def test_pending_and_concurrent_sends_are_bounded_and_cancellable(monkeypatch):+ monkeypatch.setattr(manager_module, "_OUTBOUND_PENDING_LIMIT", 4)+ monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 2)+ manager, channel = make_manager()+ blocked = asyncio.Event()+ active = 0+ peak = 0++ async def send(msg):+ nonlocal active, peak+ active += 1+ peak = max(peak, active)+ try:+ await blocked.wait()+ finally:+ active -= 1++ channel.send.side_effect = send+ for i in range(4):+ await manager._queue_outbound(channel, OutboundMessage("websocket", str(i), "a"))+ extra = asyncio.create_task(manager._queue_outbound(+ channel, OutboundMessage("websocket", "extra", "a"),+ ))+ try:+ await wait_until(lambda: active == 2)+ assert not extra.done()+ assert len(manager._outbound_tasks) == 4+ extra.cancel()+ await asyncio.gather(extra, return_exceptions=True)+ await manager._cancel_outbound()+ assert peak == 2+ assert active == 0+ assert not manager._outbound_tasks+ assert not manager._outbound_tails+ # Cancellation returns admission permits, including tasks not yet sending.+ for i in range(4):+ await asyncio.wait_for(manager._queue_outbound(+ channel, OutboundMessage("websocket", str(i), "b"),+ ), 2)+ finally:+ extra.cancel()+ await asyncio.gather(extra, return_exceptions=True)+ await manager._cancel_outbound()+++async def test_channel_stop_cancels_only_its_sends_before_stopping_runtime():+ manager, channel = make_manager()+ active = asyncio.Event()+ cancelled = asyncio.Event()++ async def send(msg):+ active.set()+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ async def stop():+ assert cancelled.is_set()++ channel.send.side_effect = send+ channel.stop.side_effect = stop+ other = MagicMock(spec=BaseChannel)+ other.send = AsyncMock()+ manager.channels["other"] = other+ await manager._queue_outbound(channel, OutboundMessage("websocket", "a", "1"))+ await asyncio.wait_for(active.wait(), 2)+ await manager._stop_channel("websocket")+ await manager._queue_outbound(other, OutboundMessage("other", "b", "2"))+ await wait_until(lambda: not manager._outbound_tasks)+ other.send.assert_awaited_once()+ assert not manager._outbound_tails+++async def test_dispatcher_shutdown_cleans_active_and_waiting_destination_tasks():+ manager, channel = make_manager()+ active = asyncio.Event()+ cancelled = asyncio.Event()++ async def send(msg):+ active.set()+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ channel.send.side_effect = send+ manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())+ try:+ for content in ("one", "two", "three"):+ await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", content))+ await asyncio.wait_for(active.wait(), 2)+ await wait_until(lambda: len(manager._outbound_tasks) == 3)+ finally:+ await manager.stop_all()+ assert cancelled.is_set()+ channel.send.assert_awaited_once()+ assert not manager._outbound_tasks+ assert not manager._outbound_tailsdiff --git a/tests/channels/test_channel_manager_delta_coalescing.py b/tests/channels/test_channel_manager_delta_coalescing.pyindex 91b6a4a98..db4099ea1 100644--- a/tests/channels/test_channel_manager_delta_coalescing.py+++ b/tests/channels/test_channel_manager_delta_coalescing.py@@ -11,7 +11,6 @@ from nanobot.bus.outbound_events import (RetryWaitEvent,StreamDeltaEvent,StreamEndEvent,- outbound_event_from_message,outbound_message_for_event,)from nanobot.bus.queue import MessageBus@@ -120,13 +119,13 @@ class TestDeltaCoalescing:async def process_one():try:m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)- event = outbound_event_from_message(m)+ event = m.eventif isinstance(event, StreamDeltaEvent):m, pending = manager._coalesce_stream_deltas(m)for p in pending:await bus.publish_outbound(p)channel = manager.channels.get(m.channel)- event = outbound_event_from_message(m)+ event = m.eventif channel and isinstance(event, StreamDeltaEvent):await channel.send_delta(m.chat_id,@@ -274,13 +273,13 @@ class TestDispatchOutboundWithCoalescing:processed = []msg = pending.pop(0) if pending else await bus.consume_outbound()- event = outbound_event_from_message(msg)+ event = msg.eventif isinstance(event, StreamDeltaEvent):msg, extra_pending = manager._coalesce_stream_deltas(msg)pending.extend(extra_pending)channel = manager.channels.get(msg.channel)- event = outbound_event_from_message(msg)+ event = msg.eventif channel and isinstance(event, StreamDeltaEvent):await channel.send_delta(msg.chat_id,@@ -394,38 +393,6 @@ class TestProgressFiltering:assert send_mock.await_count == 1assert send_mock.await_args_list[0].args[0].content == "final answer"- @pytest.mark.asyncio- async def test_legacy_progress_flag_uses_runtime_progress_filter(self, manager, bus):- manager.channels["mock"].send_progress = False- await bus.publish_outbound(OutboundMessage(- channel="mock",- chat_id="chat1",- content="legacy progress-shaped message",- metadata={"_progress": True},- ))- await bus.publish_outbound(OutboundMessage(- channel="mock",- chat_id="chat1",- content="processing sentinel",- ))-- task = asyncio.create_task(manager._dispatch_outbound())- try:- for _ in range(30):- if manager.channels["mock"]._send_mock.await_count >= 1:- break- await asyncio.sleep(0.05)- finally:- task.cancel()- try:- await task- except asyncio.CancelledError:- pass-- send_mock = manager.channels["mock"]._send_mock- assert send_mock.await_count == 1- assert send_mock.await_args.args[0].content == "processing sentinel"-@pytest.mark.asyncioasync def test_channel_override_can_enable_tool_hints(self, manager, bus):manager.channels["mock"].send_tool_hints = Truediff --git a/tests/channels/test_channel_manager_reasoning.py b/tests/channels/test_channel_manager_reasoning.pyindex a2434e81b..a916567ff 100644--- a/tests/channels/test_channel_manager_reasoning.py+++ b/tests/channels/test_channel_manager_reasoning.py@@ -23,7 +23,6 @@ import pytestfrom nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import (ProgressEvent,- outbound_event_from_message,outbound_message_for_event,)from nanobot.bus.queue import MessageBus@@ -282,7 +281,7 @@ async def _pump_one(manager: ChannelManager) -> None:"""Process currently queued messages through the reasoning dispatch branch."""async def dispatch_one(msg: OutboundMessage) -> None:- event = outbound_event_from_message(msg)+ event = msg.eventif isinstance(event, ProgressEvent) and (event.reasoning_deltaor event.reasoning_enddiff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.pyindex bdf989f5f..1624449d0 100644--- a/tests/channels/test_channel_plugins.py+++ b/tests/channels/test_channel_plugins.py@@ -3534,6 +3534,8 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():ch = _StartableChannel(fake_config, mgr.bus)mgr.channels = {"startable": ch}mgr._channel_tasks = {}+ mgr._outbound_tasks = {}+ mgr._stopping_channels = set()# Create a real cancelled taskasync def dummy_task():@@ -3612,6 +3614,8 @@ async def test_stop_all_handles_channel_exception():mgr.bus = MessageBus()mgr.channels = {"stopfailing": _StopFailingChannel(fake_config, mgr.bus)}mgr._channel_tasks = {}+ mgr._outbound_tasks = {}+ mgr._stopping_channels = set()mgr._dispatch_task = None# Should not raise even if channel.stop() raises@@ -3651,6 +3655,8 @@ async def test_stop_all_handles_channel_stop_cancelled_task():"next": next_channel,}mgr._channel_tasks = {}+ mgr._outbound_tasks = {}+ mgr._stopping_channels = set()mgr._dispatch_task = Noneawait mgr.stop_all()diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex d669bca78..9096c0768 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -17,6 +17,7 @@ from nanobot.agent.memory import MemoryStorefrom nanobot.agent.tools.registry import ToolRegistryfrom nanobot.agent.turn_delivery import TurnDeliveryFactoryfrom nanobot.bus.events import InboundMessage, OutboundMessage+from nanobot.bus.queue import MessageBusfrom nanobot.cli import commands as cli_commandsfrom nanobot.cli import gateway_runtime as cli_gateway_runtimefrom nanobot.cli import provider as provider_commands@@ -2871,7 +2872,7 @@ def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),)monkeypatch.setattr("nanobot.cli.commands.AgentLoop", _FakeAgentLoop)@@ -2938,7 +2939,7 @@ def test_gateway_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path:_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),cron_service=_StopCron,)@@ -3290,7 +3291,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(config.agents.defaults.workspace = str(tmp_path / "config-workspace")config.agents.defaults.dream.enabled = Falseconfig.gateway.heartbeat.enabled = False- bus = MagicMock()+ bus = MessageBus()seen: dict[str, object] = {}_patch_cli_command_runtime(@@ -3444,7 +3445,7 @@ def test_gateway_workspace_override_does_not_migrate_legacy_cron(_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),cron_service=_StopCron,get_cron_dir=lambda: legacy_dir,@@ -3483,7 +3484,7 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),cron_service=_StopCron,get_cron_dir=lambda: legacy_dir,@@ -3684,7 +3685,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),)monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)@@ -3895,7 +3896,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),)monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)@@ -4024,7 +4025,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(_patch_cli_command_runtime(monkeypatch,config,- message_bus=lambda: object(),+ message_bus=MessageBus,session_manager=lambda _workspace: _EmptyGatewaySessionManager(),)monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)diff --git a/tests/command/test_compact_command.py b/tests/command/test_compact_command.pyindex 8d5ba2586..ed1304a1f 100644--- a/tests/command/test_compact_command.py+++ b/tests/command/test_compact_command.py@@ -98,7 +98,7 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archivsession.add_message("assistant", "Nothing to compact.", _command=True)loop.sessions.save(session)completions = []- loop.runtime_events.subscribe(completions.append, TurnCompleted)+ loop.bus.subscribe(completions.append, TurnCompleted)await loop._dispatch(InboundMessage(channel="websocket", sender_id="user", chat_id="test", content="/compact",@@ -155,7 +155,7 @@ async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loometadata={"webui_turn_id": "queued-compact"},)completions = []- loop.runtime_events.subscribe(completions.append, TurnCompleted)+ loop.bus.subscribe(completions.append, TurnCompleted)async with loop._get_session_lock(key):await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch)reply = await cmd_stop(CommandContext(@@ -181,7 +181,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:loop.provider.chat_with_retry.side_effect = wait_for_cancelcompletions = []- loop.runtime_events.subscribe(completions.append, TurnCompleted)+ loop.bus.subscribe(completions.append, TurnCompleted)msg = InboundMessage(channel="websocket", sender_id="user", chat_id="test", content="/compact",metadata={"webui_turn_id": "compact-turn"},diff --git a/tests/test_openai_api.py b/tests/test_openai_api.pyindex ad63cc479..86a1a04e2 100644--- a/tests/test_openai_api.py+++ b/tests/test_openai_api.py@@ -517,11 +517,12 @@ async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:async def test_process_direct_accepts_media() -> None:"""process_direct should forward media paths to _process_message."""from nanobot.agent.loop import AgentLoop+ from nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import RuntimeEventPublisherloop = AgentLoop.__new__(AgentLoop)loop._session_locks = {}- loop.runtime_event_publisher = RuntimeEventPublisher()+ loop.runtime_event_publisher = RuntimeEventPublisher(MessageBus())captured_msg = Nonediff --git a/tests/tools/test_message_tool_suppress.py b/tests/tools/test_message_tool_suppress.pyindex 1a04ccbd4..787caa708 100644--- a/tests/tools/test_message_tool_suppress.py+++ b/tests/tools/test_message_tool_suppress.py@@ -12,6 +12,7 @@ from nanobot.agent.tools.message import MessageToolfrom nanobot.bus.events import InboundMessage, OutboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.providers.base import LLMResponse, ToolCallRequest+from nanobot.utils.progress_events import output_eventsdef _make_loop(tmp_path: Path) -> AgentLoop:@@ -181,7 +182,7 @@ class TestMessageToolSuppressLogic:result = await loop._run_agent_loop(TranscriptInput(history=[], current_message=None),runtime=loop.llm_runtime(),- on_progress=on_progress,+ events=output_events(on_progress=on_progress),)assert result.final_content == "Done"diff --git a/tests/utils/test_webui_turn_helpers.py b/tests/utils/test_webui_turn_helpers.pyindex 955d85060..a466c317c 100644--- a/tests/utils/test_webui_turn_helpers.py+++ b/tests/utils/test_webui_turn_helpers.py@@ -7,8 +7,8 @@ import pytestfrom nanobot.agent.tools.context import RequestContext, request_contextfrom nanobot.bus.events import InboundMessagefrom nanobot.bus.outbound_events import GoalStatusEvent, TurnModelUpdatedEvent, UserInputEvent+from nanobot.bus.queue import MessageBusfrom nanobot.bus.runtime_events import (- RuntimeEventBus,RuntimeEventContext,TurnRuntimeAdmitted,UserInputAccepted,@@ -37,7 +37,7 @@ def _clear_turn_wall_clock() -> None:@pytest.mark.asyncioasync def test_publish_turn_run_status_running_records_wall_clock() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()msg = InboundMessage(channel="websocket",@@ -61,7 +61,7 @@ async def test_publish_turn_run_status_running_records_wall_clock() -> None:@pytest.mark.asyncioasync def test_publish_turn_run_status_reuses_explicit_wall_clock() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()msg = InboundMessage(channel="websocket", sender_id="u", chat_id="chat-a", content="hi")@@ -75,7 +75,7 @@ async def test_publish_turn_run_status_reuses_explicit_wall_clock() -> None:@pytest.mark.asyncioasync def test_publish_turn_run_status_idle_retains_registry_until_delivery() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()msg = InboundMessage(channel="websocket",@@ -110,7 +110,7 @@ def test_clear_websocket_turn_only_clears_matching_owner() -> None:@pytest.mark.asyncioasync def test_ownerless_turns_receive_distinct_internal_owners() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()first = InboundMessage(channel="websocket",@@ -139,7 +139,7 @@ async def test_ownerless_turns_receive_distinct_internal_owners() -> None:@pytest.mark.asyncioasync def test_publish_turn_run_status_non_websocket_noop_registry() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()msg = InboundMessage(channel="telegram", sender_id="u", chat_id="1", content="hi")@@ -151,7 +151,7 @@ async def test_publish_turn_run_status_non_websocket_noop_registry() -> None:@pytest.mark.asyncioasync def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()observer = wth.build_webui_fallback_model_observer(bus)@@ -182,16 +182,38 @@ async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:@pytest.mark.asyncio+async def test_coordinator_connections_end_on_scope_exit_and_can_reconnect(tmp_path):+ from nanobot.bus.runtime_events import RuntimeModelChanged++ bus = MessageBus()+ bus.publish_outbound = AsyncMock()+ coordinator = wth.WebuiTurnCoordinator(+ bus=bus, sessions=SessionManager(tmp_path),+ schedule_background=lambda coro: coro.close(),+ )+ event = RuntimeModelChanged("model", None)+ with pytest.raises(RuntimeError, match="shutdown"):+ with coordinator.connected():+ await bus.publish(event)+ raise RuntimeError("shutdown")+ bus.publish_outbound.assert_awaited_once()+ await bus.publish(event)+ bus.publish_outbound.assert_awaited_once()+ with coordinator.connected():+ bus.publish_nowait(event)+ await bus.drain()+ assert bus.publish_outbound.await_count == 2++async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path) -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()- runtime_events = RuntimeEventBus()coordinator = wth.WebuiTurnCoordinator(bus=bus,sessions=SessionManager(tmp_path),schedule_background=lambda coro: coro.close(),)- coordinator.subscribe(runtime_events)+ coordinator.subscribe()runtime = LLMRuntime(provider=MagicMock(),model="openai-codex/gpt-5.6",@@ -200,7 +222,7 @@ async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path)model_preset="Codex",)- await runtime_events.publish(+ await bus.publish(TurnRuntimeAdmitted(context=RuntimeEventContext(channel="websocket",@@ -225,7 +247,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(tmp_path,monkeypatch,) -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()sessions = SessionManager(tmp_path)target_session = sessions.get_or_create("websocket:target")@@ -242,15 +264,14 @@ async def test_session_input_is_projected_by_the_webui_coordinator(}append_input = MagicMock()monkeypatch.setattr(wth, "append_session_message_input", append_input)- runtime_events = RuntimeEventBus()coordinator = wth.WebuiTurnCoordinator(bus=bus,sessions=sessions,schedule_background=lambda coro: coro.close(),)- coordinator.subscribe(runtime_events)+ coordinator.subscribe()- await runtime_events.publish(UserInputAccepted(+ await bus.publish(UserInputAccepted(context=RuntimeEventContext(channel="system",chat_id="websocket:target",@@ -274,7 +295,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(@pytest.mark.asyncioasync def test_fallback_model_ignores_non_websocket_requests() -> None:- bus = MagicMock()+ bus = MessageBus()bus.publish_outbound = AsyncMock()observer = wth.build_webui_fallback_model_observer(bus)diff --git a/tests/webui/test_build.py b/tests/webui/test_build.pyindex ff811ca1c..692552d22 100644--- a/tests/webui/test_build.py+++ b/tests/webui/test_build.py@@ -76,6 +76,18 @@ def test_inspect_webui_bundle_detects_channel_owned_ui_source(tmp_path: Path) ->assert status.newest_source == channel_ui+def test_shared_notifications_make_existing_bundle_stale(tmp_path: Path) -> None:+ source = tmp_path / "webui"+ dist = tmp_path / "nanobot/web/dist"+ shared = tmp_path / "packages/client-events/notifications.ts"+ _touch(source / "package.json", mtime_ns=10)+ _touch(dist / "index.html", mtime_ns=20)+ _touch(shared, mtime_ns=30)+ status = inspect_webui_bundle(source_dir=source, dist_dir=dist)+ assert status.needs_build+ assert status.newest_source == shared++def test_channel_owned_ui_sources_are_included_in_distributions() -> None:project_root = Path(__file__).resolve().parents[2]pyproject = tomllib.loads((project_root / "pyproject.toml").read_text(encoding="utf-8"))diff --git a/tests/webui/test_notification_contract.py b/tests/webui/test_notification_contract.pynew file mode 100644index 000000000..3110d1a1f--- /dev/null+++ b/tests/webui/test_notification_contract.py@@ -0,0 +1,34 @@+import importlib.util+import io+import json+import tarfile+from pathlib import Path++from nanobot.events import ContextCompactionEvent, RecoveryStateEvent+from nanobot.webui.outbound_wire import project_notification++ROOT = Path(__file__).resolve().parents[2]+++def test_wire_fixtures_are_real_python_projections():+ fixtures = json.loads((ROOT / "packages/client-events/fixtures.json").read_text())+ for expected in fixtures:+ fields = {key: value for key, value in expected.items() if key not in {"event", "chat_id"}}+ event_type = (+ ContextCompactionEvent if expected["event"] == "context_compaction" else RecoveryStateEvent+ )+ projection = project_notification(expected["chat_id"], event_type(**fields))+ assert projection is not None+ assert projection.payload == expected+++def test_tui_source_archive_preserves_shared_module_import_path():+ spec = importlib.util.spec_from_file_location("package_release", ROOT / "tui/scripts/package-release.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ with tarfile.open(fileobj=io.BytesIO(module._source_archive(ROOT / "tui"))) as archive:+ names = set(archive.getnames())+ assert "nanobot-tui-source/tui/src/protocol.ts" in names+ assert "nanobot-tui-source/packages/client-events/notifications.ts" in names+ assert "nanobot-tui-source/tui/bun.lock" in names+ assert "nanobot-tui-source/LICENSE" in namesdiff --git a/tui/RELINKING.md b/tui/RELINKING.mdindex 84b2ed7ff..986f0e9f7 100644--- a/tui/RELINKING.md+++ b/tui/RELINKING.md@@ -8,7 +8,7 @@ LGPL 2.1 license texts.Corresponding upstream source:-- nanobot TUI: the `tui/` directory in the GitHub release tag that contains this archive+- nanobot TUI: the `tui/` and `packages/client-events/` directories in the GitHub release tag that contains this archive- Bun 1.3.13 (`bf2e2cecf27e800962b1e7f03d66278f9d5d2e79`):<https://github.com/oven-sh/bun/tree/bun-v1.3.13>- Bun's patched WebKit (`4d5e75ebd84a14edbc7ae264245dcd77fe597c10`):@@ -21,7 +21,7 @@ build instructions. Then unpack`nanobot-tui-source.tar.gz` from the release archive and run the resulting Bun executable:```bash-cd nanobot-tui-source+cd nanobot-tui-source/tui/path/to/modified/bun install --frozen-lockfile/path/to/modified/bun run build -- <target>```diff --git a/tui/scripts/package-release.py b/tui/scripts/package-release.pyindex bc72b17e1..88e1dc56d 100644--- a/tui/scripts/package-release.py+++ b/tui/scripts/package-release.py@@ -43,7 +43,10 @@ def _source_archive(root: Path) -> bytes:path = root / relativeif not path.exists():raise FileNotFoundError(path)- archive.add(path, arcname=Path("nanobot-tui-source") / relative)+ archive.add(path, arcname=Path("nanobot-tui-source/tui") / relative)+ archive.add(root.parent / "packages/client-events",+ arcname="nanobot-tui-source/packages/client-events")+ archive.add(root.parent / "LICENSE", arcname="nanobot-tui-source/LICENSE")return output.getvalue()diff --git a/tui/src/protocol.ts b/tui/src/protocol.tsindex 0724726d3..0d4fdda02 100644--- a/tui/src/protocol.ts+++ b/tui/src/protocol.ts@@ -1,3 +1,7 @@+import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications"+import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications"+export type { ContextCompaction, RecoveryState, RecoveryStatus } from "../../packages/client-events/notifications"+export type ConnectionStatus =| "starting"| "connecting"@@ -76,21 +80,6 @@ export interface RuntimeControls {canUseFullAccess: boolean}-export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed"--export interface RecoveryState {- status: RecoveryStatus- recovery_id: string- reason?: string- attempts?: number- can_continue?: boolean-}--export interface ContextCompaction {- id: string- phase: "started" | "succeeded" | "failed" | "cancelled"-}-export type InboundEvent =| { event: "ready"; chat_id: string; client_id: string }| {@@ -156,13 +145,7 @@ export type InboundEvent =turn_id?: string}| { event: "goal_state"; chat_id: string; goal_state: Record<string, unknown> }- | ({ event: "recovery_state"; chat_id: string } & RecoveryState)- | {- event: "context_compaction"- chat_id: string- compaction_id: string- phase: ContextCompaction["phase"]- }+ | NotificationEvent| {event: "session_updated"chat_id: string@@ -382,10 +365,6 @@ function optional(value: unknown, type: "boolean" | "number" | "string"): booleareturn value === undefined || typeof value === type}-function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] {- return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled"-}-function isToolEvent(value: unknown): value is ToolProgressEvent {if (!isRecord(value)) return falsereturn optional(value.version, "number")@@ -456,15 +435,6 @@ function isWorkspaceScope(value: unknown): value is WorkspaceScopePayload {&& optional(value.restrict_to_workspace, "boolean")}-function isRecoveryState(value: unknown): value is RecoveryState {- return isRecord(value)- && ["resuming", "awaiting_user", "recovered", "failed"].includes(String(value.status))- && typeof value.recovery_id === "string"- && optional(value.reason, "string")- && optional(value.attempts, "number")- && optional(value.can_continue, "boolean")-}-interface WebUIResponseEvent {event: "webui_response"request_id: string@@ -560,13 +530,7 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {) return nullif (name === "goal_status" && record.status !== "running" && record.status !== "idle") return nullif (name === "goal_state" && !isRecord(record.goal_state)) return null- if (name === "recovery_state" && !isRecoveryState(record)) return null- if (- name === "context_compaction"- && (typeof record.compaction_id !== "string"- || !record.compaction_id- || !isCompactionPhase(record.phase))- ) return null+ if (decodeNotification(record) === null) return nullif (name === "session_updated"&& (!optional(record.scope, "string")diff --git a/tui/src/transcript.ts b/tui/src/transcript.tsindex 9fd8d5283..3842d11ec 100644--- a/tui/src/transcript.ts+++ b/tui/src/transcript.ts@@ -1,3 +1,4 @@+import { acceptsCompactionPhase } from "../../packages/client-events/notifications"import {BoxRenderable,CodeRenderable,@@ -331,7 +332,7 @@ export class Transcript {compaction(compaction: ContextCompaction, index?: number): boolean {let entry = this.compactions.get(compaction.id)// Hydration can replay a terminal state before an already queued start event.- if (entry && (entry.phase !== "started" || entry.phase === compaction.phase)) return false+ if (!acceptsCompactionPhase(entry?.phase, compaction.phase)) return falseconst added = !entryif (index === undefined) {this.noteOutput()diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.tsindex d7a44357b..662298648 100644--- a/webui/src/hooks/useNanobotStream.ts+++ b/webui/src/hooks/useNanobotStream.ts@@ -1,3 +1,4 @@+import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";@@ -782,6 +783,7 @@ export function useNanobotStream(setMessages((prev) => {const id = `compaction-${ev.compaction_id}`;const existing = prev.findIndex((message) => message.id === id);+ if (!acceptsCompactionPhase(prev[existing]?.compaction?.phase, ev.phase)) return prev;const next = {id,role: "assistant" as const,diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.tsindex 3175edd29..e094b33b2 100644--- a/webui/src/lib/nanobot-client.ts+++ b/webui/src/lib/nanobot-client.ts@@ -1,3 +1,4 @@+import { decodeNotification } from "../../../packages/client-events/notifications";import type {ConnectionStatus,InboundEvent,@@ -1072,6 +1073,7 @@ export class NanobotClient {let parsed: InboundEvent;try {parsed = JSON.parse(typeof ev.data === "string" ? ev.data : "") as InboundEvent;+ if (decodeNotification(parsed) === null) return;} catch {if (wsInboundDebugEnabled()) {const raw = typeof ev.data === "string" ? ev.data : String(ev.data);diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 546b8d392..22638cea2 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -1,12 +1,13 @@+import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../../packages/client-events/notifications";+export type { RecoveryState, RecoveryStatus } from "../../../packages/client-events/notifications";+type Role = "user" | "assistant" | "tool" | "system";/** "trace" rows are intermediate agent breadcrumbs (tool-call hints,* progress pings) that should not be rendered as conversational replies. */type MessageKind = "message" | "trace" | "compaction";-export interface UIContextCompaction {- id: string;- phase: "started" | "succeeded" | "failed" | "cancelled";+export interface UIContextCompaction extends ContextCompaction {/** Live wire transitions announce; hydrated transcript rows stay silent. */announce?: boolean;}@@ -63,16 +64,6 @@ export interface TurnUsage {export type RoundUsage = TurnUsage;-export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed";--export interface RecoveryState {- status: RecoveryStatus;- recovery_id: string;- reason?: string;- attempts?: number;- can_continue?: boolean;-}-export interface UIMessage {id: string;role: Role;@@ -1373,16 +1364,7 @@ export type InboundEvent =/** Optional structured payload on progress frames (channel-specific). */agent_ui?: AgentUIBlob;} & InboundTurnMetadata)- | ({- event: "recovery_state";- chat_id: string;- } & RecoveryState)- | ({- event: "context_compaction";- chat_id: string;- compaction_id: string;- phase: UIContextCompaction["phase"];- } & InboundTurnMetadata)+ | (NotificationEvent & InboundTurnMetadata)| ({event: "file_edit";chat_id: string;diff --git a/webui/src/tests/notifications.test.ts b/webui/src/tests/notifications.test.tsnew file mode 100644index 000000000..7a40cd844--- /dev/null+++ b/webui/src/tests/notifications.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import fixtures from "../../../packages/client-events/fixtures.json";+import { acceptsCompactionPhase, decodeNotification } from "../../../packages/client-events/notifications";++describe("shared notification contract", () => {+ it.each(fixtures)("accepts the Python wire fixture %#", (event) => {+ expect(decodeNotification(event)).toEqual(event);+ expect(decodeNotification({ ...event, turn_id: "turn" })).toMatchObject(event);+ expect(decodeNotification({ ...event, chat_id: 42 })).toBeNull();+ expect(decodeNotification({ ...event, turn_id: 42 })).toBeNull();+ });++ it("does not mistake other event families for invalid notifications", () => {+ expect(decodeNotification({ event: "delta", text: "hello" })).toBeUndefined();+ expect(decodeNotification({ ...fixtures[0], phase: "unknown" })).toBeNull();+ expect(decodeNotification({ ...fixtures[0], compaction_id: "" })).toBeNull();+ });++ it("allows one terminal transition, including terminal-first hydration", () => {+ for (const phase of ["started", "succeeded", "failed", "cancelled"] as const) {+ expect(acceptsCompactionPhase(undefined, phase)).toBe(true);+ expect(acceptsCompactionPhase("started", phase)).toBe(phase !== "started");+ for (const terminal of ["succeeded", "failed", "cancelled"] as const) {+ expect(acceptsCompactionPhase(terminal, phase)).toBe(false);+ }+ }+ });+});diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsxindex a9bf860fa..d6f5d0873 100644--- a/webui/src/tests/useNanobotStream.test.tsx+++ b/webui/src/tests/useNanobotStream.test.tsx@@ -245,6 +245,19 @@ describe("useNanobotStream", () => {});});+ it("keeps a hydrated terminal compaction when a queued start arrives", () => {+ const fake = fakeClient();+ const initial = [{ id: "compaction-c1", role: "assistant" as const, content: "",+ kind: "compaction" as const, createdAt: 123,+ compaction: { id: "c1", phase: "succeeded" as const } }];+ const { result } = renderHook(() => useNanobotStream("chat", initial), {+ wrapper: wrap(fake.client),+ });+ act(() => fake.emit("chat", { event: "context_compaction", chat_id: "chat",+ compaction_id: "c1", phase: "started" }));+ expect(result.current.messages).toEqual(initial);+ });+it("batches answer deltas into one animation-frame update", async () => {const fake = fakeClient();const requestFrame = vi.spyOn(window, "requestAnimationFrame");