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

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

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

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

* docs: remove runtime notification design write-up

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

* fix(channels): isolate outbound sends by destination

* style(events): group shared notification imports

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

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

No files matched your search

+5 -5
View File
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutine
from loguru import logger
from nanobot.bus.outbound_events import ContextCompactionCallback
from nanobot.events import NO_EVENTS, EventSink
from nanobot.session.manager import MIN_COMPACTED_REPLAY_MESSAGES, Session, SessionManager
from nanobot.session.summary import SessionSummary, session_summary_from_metadata
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
from nanobot.agent.memory import Consolidator
from 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 = sessions
self.consolidator = consolidator
self._ttl = session_ttl_minutes
self._archiving: set[str] = set()
self._summaries: dict[str, SessionSummary] = {}
self._bind_compaction = bind_compaction
self._bind_events = bind_events
def _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)
+16 -26
View File
@@ -20,11 +20,7 @@ from uuid import uuid4
from loguru import logger
from nanobot.agent.context import TranscriptInput
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
emit_context_compaction,
)
from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
from nanobot.providers.base import (
LLMResponse,
LLMUsage,
@@ -204,7 +200,7 @@ class ModelRequestState:
tool_definitions: list[dict[str, Any]] | None = None
compaction: ContextCompactionState | None = None
provider_compaction_applied: bool = False
compaction_callback: ContextCompactionCallback | None = None
events: EventSink = NO_EVENTS
class ContextGovernor:
@@ -474,8 +470,7 @@ class ContextGovernor:
return
compaction_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:
)
raise
if 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 = pressure
compaction_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_context
+3 -2
View File
@@ -2,13 +2,14 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from loguru import logger
from nanobot.events import NO_EVENTS, EventSink
from 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_EVENTS
workspace: Path | None = None
channel: str = "cli"
chat_id: str = "direct"
+9 -16
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
from pathlib import Path
from 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 EventSink
from nanobot.providers.base import ToolCallRequest
from 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 None
self._workspace = workspace
self._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):
return
typed_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))
@staticmethod
def _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 None
return FileEditActivityHook(
on_progress=context.on_progress,
events=context.events,
workspace=context.workspace,
)
+40 -89
View File
@@ -6,7 +6,6 @@ from __future__ import annotations
import asyncio
import dataclasses
import inspect
import os
import time
import weakref
@@ -51,14 +50,15 @@ from nanobot.agent.turn_delivery import TurnRoute as TurnRoute
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
)
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
from nanobot.command.router import normalize_command_text
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
from nanobot.llm_usage.context import source_from_request
from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState
from nanobot.providers.factory import ProviderSnapshot
@@ -109,6 +109,7 @@ from nanobot.utils.document import reference_non_image_attachments
from nanobot.utils.helpers import image_placeholder_text
from nanobot.utils.helpers import truncate_text as truncate_text_fn
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.progress_events import output_events
from nanobot.utils.runtime import (
EMPTY_FINAL_RESPONSE_MESSAGE,
)
@@ -162,11 +163,9 @@ class TurnContext:
outbound: OutboundMessage | None = None
suppress_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 = False
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None
on_retry_wait: Callable[[str], Awaitable[None]] | None = None
pending_queue: asyncio.Queue[InboundMessage] | None = None
pending_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_events
else:
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_publisher
self.channels_config = channels_config
self.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_seconds
self._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_KEY
return 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`` means
the 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_content
if result.pending_stream_content is not None
else 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_end
t0 = 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.publish
segment_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)
elif isinstance(event, StreamEndEvent):
ctx.streamed_content = segment_streamed_content
segment_streamed_content = False
if publish is not None:
await publish(event)
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)
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_content
ctx.all_messages = result.messages
+6 -14
View File
@@ -21,11 +21,7 @@ from uuid import uuid4
from loguru import logger
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
emit_context_compaction,
)
from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import ProviderCallContext, ProviderConversationState
from 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_end
self.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:
)
raise
if 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",
+31 -70
View File
@@ -2,20 +2,19 @@
from __future__ import annotations
import inspect
import json
from typing import Any, Awaitable, Callable, cast
from typing import Any
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.bus.outbound_events import ProgressEvent, StreamDeltaEvent, StreamEndEvent
from nanobot.events import NO_EVENTS, EventSink
from nanobot.providers.base import ToolCallRequest
from nanobot.utils.helpers import IncrementalThinkExtractor, strip_think
from 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 = streaming
self._session_key = session_key
self._tool_hint_max_length = tool_hint_max_length
self._stream_buf = ""
@@ -43,7 +40,7 @@ class AgentProgressHook(AgentHook):
self._reasoning_open = False
def wants_streaming(self) -> bool:
return self._on_stream is not None
return self._streaming
@staticmethod
def _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:
return
phase = 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 = False
async def after_iteration(self, context: AgentHookContext) -> None:
if (
self._on_progress
self._publish
and context.tool_calls
and 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.usage
logger.debug(
"LLM usage: input={} output={} cache_read={} cache_write={} source={}",
+3 -6
View File
@@ -27,7 +27,7 @@ from nanobot.agent.context_governance import (
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.execution import execute_tool_calls
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.outbound_events import ContextCompactionCallback
from nanobot.events import NO_EVENTS, EventSink
from 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 = None
session_key: str | None = None
provider_retry_mode: str = "standard"
retry_wait_callback: RetryWaitCallback | None = None
checkpoint_callback: CheckpointCallback | None = None
consolidate_history: HistoryConsolidator | None = None
consolidate_provider_compaction: ProviderCompactionConsolidator | None = None
@@ -116,7 +114,7 @@ class AgentRunSpec:
finalize_on_max_iterations: bool = True
provider_state: ProviderConversationState | None = None
llm_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.generation
kwargs["temperature"] = generation.temperature
-2
View File
@@ -13,7 +13,6 @@ if TYPE_CHECKING:
from nanobot.agent.tools.file_state import FileStates
from nanobot.agent.tools.runtime_control import RuntimeControl
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.config.schema import ProviderConfig, ToolsConfig
from nanobot.cron.service import CronService
from nanobot.providers.factory import ProviderSnapshot
@@ -90,5 +89,4 @@ class ToolContext:
image_generation_provider_configs: dict[str, ProviderConfig] | None = None
timezone: str = "UTC"
workspace_sandbox: WorkspaceSandboxStatus | None = None
runtime_events: RuntimeEventBus | None = None
runtime_control: RuntimeControl | None = None
+13 -12
View File
@@ -15,7 +15,8 @@ from nanobot.agent.goal_permission import (
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import RequestContext, ToolContext, current_request_context
from 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, RuntimeEventContext
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
from 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 = bus
def _session(self):
request_ctx = current_request_context()
@@ -92,14 +93,14 @@ class _GoalToolsMixin:
raise
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
runtime_events = self._runtime_events
bus = self._bus
rc = current_request_context()
if runtime_events is None or rc is None:
if bus is None or rc is None:
return
cid = (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)
@classmethod
def 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)
@classmethod
def 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,
)
@classmethod
+55 -115
View File
@@ -4,24 +4,22 @@ from __future__ import annotations
import dataclasses
import time
from collections.abc import Awaitable, Callable
from collections.abc import Callable
from copy import deepcopy
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import notification_is_deliverable
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
RetryWaitEvent,
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
outbound_message_for_event,
)
from nanobot.bus.progress import build_bus_progress_callback
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus, RuntimeEventPublisher
from nanobot.bus.runtime_events import RuntimeEventPublisher
from nanobot.channels.notification_routes import notification_metadata
from nanobot.events import AgentEvent, EventSink
from nanobot.providers.base import LLMUsage
from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata
@@ -40,10 +38,27 @@ class TurnRoute:
TurnRoutePolicy = Callable[[InboundMessage, str, TurnRoute], TurnRoute]
ProgressCallback = Callable[..., Awaitable[None]]
StreamCallback = Callable[[str], Awaitable[None]]
StreamEndCallback = Callable[..., Awaitable[None]]
RetryWaitCallback = Callable[[str], Awaitable[None]]
def _bind_events(
bus: MessageBus, route: TurnRoute,
) -> EventSink:
channel, chat_id = route.channel, route.chat_id
metadata = deepcopy(route.metadata)
def accepts(event_type: type[AgentEvent]) -> bool:
return notification_is_deliverable(
event_type, channel=channel, publish_lifecycle=route.publish_lifecycle,
)
async def publish(event: AgentEvent) -> None:
if not accepts(type(event)):
return
await bus.publish_event(
event, channel=channel, chat_id=chat_id, metadata=deepcopy(metadata),
)
return EventSink(publish, accepts)
class TurnDeliveryFactory:
@@ -52,12 +67,10 @@ class TurnDeliveryFactory:
def __init__(
self,
bus: MessageBus,
runtime_events: RuntimeEventBus,
route_policy: TurnRoutePolicy | None = None,
) -> None:
self.bus = bus
self.runtime_events = runtime_events
self.runtime_event_publisher = RuntimeEventPublisher(runtime_events)
self.runtime_event_publisher = RuntimeEventPublisher(bus)
self.route_policy = route_policy
def create(
@@ -95,11 +108,11 @@ class TurnDeliveryFactory:
),
)
def session_compaction_callback(
def session_events(
self,
session_key: str,
session_metadata: dict[str, Any],
) -> ContextCompactionCallback | None:
) -> EventSink:
"""Bind idle notifications to one route without acquiring a turn owner."""
saved_route = session_metadata.get("_compaction_route")
if isinstance(saved_route, dict):
@@ -107,9 +120,9 @@ class TurnDeliveryFactory:
channel, chat_id = saved_route.get("channel"), saved_route.get("chat_id")
metadata = saved_route.get("metadata", {})
if not isinstance(channel, str) or not isinstance(chat_id, str):
return
return EventSink()
if not isinstance(metadata, dict):
return
return EventSink()
metadata = cast(dict[str, Any], metadata)
else:
# Older sessions have no route snapshot. Only direct clients have a
@@ -120,19 +133,12 @@ class TurnDeliveryFactory:
else tuple(session_key.split(":", 1))
)
if not route or len(route) != 2 or route[0] not in {"websocket", "cli"}:
return
return EventSink()
channel, chat_id = route
metadata = {}
metadata = deepcopy(metadata)
async def publish(event: ContextCompactionEvent) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=channel, chat_id=chat_id, event=event, metadata=metadata,
)
)
return publish
return _bind_events(self.bus, TurnRoute(channel, chat_id, metadata))
@staticmethod
def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute:
@@ -174,8 +180,12 @@ class TurnDelivery:
_stream_base_id: str | None = field(init=False, default=None)
_stream_segment: int = field(init=False, default=0)
_stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False)
_routed_events: EventSink = field(init=False)
def __post_init__(self) -> None:
self._routed_events = _bind_events(self.bus, self.route)
self.events = EventSink(self._publish_event, self._routed_events.accepts)
self.delivery_message = dataclasses.replace(
self.input_message,
channel=self.route.channel,
@@ -189,67 +199,16 @@ class TurnDelivery:
self._stream_base_id = f"{self.session_key}:{time.time_ns()}"
@property
def on_stream(self) -> StreamCallback | None:
return self._publish_stream if self._stream_base_id is not None else None
@property
def on_stream_end(self) -> StreamEndCallback | None:
return self._publish_stream_end if self._stream_base_id is not None else None
def progress_callback(self) -> ProgressCallback | None:
if not self.route.publish_lifecycle:
return None
return build_bus_progress_callback(self.bus, self.delivery_message)
def retry_wait_callback(self) -> RetryWaitCallback | None:
if not self.route.publish_lifecycle:
return None
async def _on_retry_wait(content: str) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=RetryWaitEvent(content=content),
metadata=self.delivery_message.metadata,
)
)
return _on_retry_wait
async def context_compaction(self, event: ContextCompactionEvent) -> None:
"""Publish one compaction transition without completing the active turn."""
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=event,
metadata=self.delivery_message.metadata,
)
)
def streaming(self) -> bool:
return self._stream_base_id is not None
def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
"""Keep only routing fields needed to deliver a later idle notification."""
source = self.route.metadata
channel_type = self.route.channel.split(".", 1)[0]
fields = {
"telegram": ("message_thread_id",),
"matrix": ("thread_root_event_id", "thread_reply_to_event_id"),
"feishu": ("message_id", "thread_id", "chat_type"),
}.get(channel_type, ())
metadata = {
key: source[key] for key in fields if key in source
}
if channel_type in {"slack", "mattermost"}:
nested = source.get(channel_type)
if isinstance(nested, dict):
nested = cast(dict[str, Any], nested)
fields = ("thread_ts",) if channel_type == "slack" else ("root_id", "thread_ts")
metadata[channel_type] = {key: nested[key] for key in fields if key in nested}
# Keep the storage key readable by older gateways.
session_metadata["_compaction_route"] = {
"channel": self.route.channel,
"chat_id": self.route.chat_id,
"metadata": metadata,
"metadata": notification_metadata(self.route.channel, self.route.metadata),
}
async def started(self) -> None:
@@ -369,40 +328,21 @@ class TurnDelivery:
assert self._stream_base_id is not None
return f"{self._stream_base_id}:{self._stream_segment}"
async def _publish_stream(self, delta: str) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=StreamDeltaEvent(content=delta, stream_id=self._stream_id()),
metadata=self.delivery_message.metadata,
)
)
self._stream_open = True
async def _publish_stream_end(
self,
*,
resuming: bool = False,
merge_next: bool = False,
) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=StreamEndEvent(
stream_id=self._stream_id(),
resuming=resuming,
merge_next=merge_next,
),
metadata=self.delivery_message.metadata,
)
)
self._stream_open = merge_next
if not merge_next:
self._stream_segment += 1
async def _publish_event(self, event: AgentEvent) -> None:
if isinstance(event, StreamDeltaEvent | StreamEndEvent):
if not self.streaming:
return
event = dataclasses.replace(event, stream_id=self._stream_id())
if self._routed_events.publish is not None:
await self._routed_events.publish(event)
if isinstance(event, StreamDeltaEvent):
self._stream_open = True
elif isinstance(event, StreamEndEvent):
self._stream_open = event.merge_next
if not event.merge_next:
self._stream_segment += 1
async def abort_stream(self) -> None:
"""Close an interrupted stream so stateful channels can release its buffer."""
if self._stream_open:
await self._publish_stream_end()
await self._publish_event(StreamEndEvent())
+6 -8
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from pathlib import Path
from 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 = False
channel: 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_hook
turn_context = AgentTurnHookContext(
on_progress=spec.on_progress,
events=spec.events,
workspace=spec.workspace,
channel=spec.channel,
chat_id=spec.chat_id,
+2 -2
View File
@@ -5,7 +5,7 @@ from datetime import datetime
from typing import TYPE_CHECKING, Any, Literal
if 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" = None
+37
View File
@@ -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 True
+22 -172
View File
@@ -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 Mapping
from dataclasses import dataclass, replace
from typing import Any, Literal, cast
from loguru import logger
from typing import Any
from 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 RetryWaitEvent
from 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 = False
reasoning: 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 = None
resuming: 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 = None
goal_state: dict[str, Any] | None = None
usage: 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: str
started_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 | None
model_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 None
-67
View File
@@ -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_progress
+108 -4
View File
@@ -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 logger
from 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)
+13 -91
View File
@@ -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, Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
from loguru import logger
from nanobot.bus.events import InboundMessage
from nanobot.events import AgentEvent
from nanobot.providers.base import LLMUsage
if TYPE_CHECKING:
from nanobot.bus.queue import MessageBus
from 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: str
model_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 = bus
self._turn_latency_ms: dict[str, int] = {}
self._turn_runtime: dict[str, LLMRuntime] = {}
self._turn_usage: dict[str, LLMUsage] = {}
+69 -9
View File
@@ -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.25
ORIGIN_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 = False
self._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()
@@ -389,6 +395,14 @@ class ChannelManager:
return task
async 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 False
fingerprint = 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.event
progress_event = event if isinstance(event, ProgressEvent) else None
if 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)
continue
if 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.event
channel = 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:
@staticmethod
async def _send_once(channel: BaseChannel, msg: OutboundMessage) -> None:
"""Send one outbound message without retry policy."""
event = outbound_event_from_message(msg)
event = msg.event
if 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.event
first_stream_id = first_event.stream_id if isinstance(first_event, StreamDeltaEvent) else None
target_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.event
next_stream_id = (
next_event.stream_id
if isinstance(next_event, StreamDeltaEvent | StreamEndEvent)
+23
View File
@@ -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)
@@ -12,8 +12,10 @@ import pytest
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.manager import ChannelManager
from nanobot.channels.websocket import runtime
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.config.schema import Config
from 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)
@pytest.mark.asyncio
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.asyncio
async def test_slow_tui_does_not_block_a_different_topic() -> None:
channel = _channel()
+1 -2
View File
@@ -124,7 +124,6 @@ def agent(
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
outbound_event_from_message,
)
from nanobot.bus.queue import MessageBus
from 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.event
if isinstance(event, StreamDeltaEvent):
if renderer:
+5 -6
View File
@@ -357,7 +357,6 @@ def _run_gateway(
from nanobot.agent.tools.message import MessageTool
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.channels.manager import ChannelManager
from nanobot.config.watcher import watch_config_file
from 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 OutboundMessage
from 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())
+1 -2
View File
@@ -27,7 +27,6 @@ from nanobot.bus.outbound_events import (
ContextCompactionEvent,
ProgressEvent,
RetryWaitEvent,
outbound_event_from_message,
)
from nanobot.cli.stream import StreamRenderer, ThinkingSpinner
from 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.event
if isinstance(event, ContextCompactionEvent):
await _print_interactive_progress_line(msg.content, thinking, renderer)
return True
+1 -1
View File
@@ -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)
+64
View File
@@ -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()
+29 -2
View File
@@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
import json_repair
from loguru import logger
from nanobot.events import NO_EVENTS, EventSink, RetryWaitEvent
from nanobot.utils.helpers import sanitize_surrogates_deep
if TYPE_CHECKING:
@@ -260,6 +261,7 @@ class ProviderCallContext:
conversation_state: ProviderConversationState | None = field(default=None, repr=False)
context_window_tokens: int | None = None
session_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_context
if 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(
+2
View File
@@ -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)
+1 -1
View File
@@ -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."""
+19 -19
View File
@@ -4,7 +4,8 @@ from __future__ import annotations
import re
import time
from collections.abc import Awaitable, Callable
from collections.abc import Awaitable, Callable, Generator
from contextlib import contextmanager
from dataclasses import dataclass, replace
from typing import Any, cast
from uuid import uuid4
@@ -13,7 +14,6 @@ from loguru import logger
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.turn_delivery import TurnRoute
from nanobot.bus import progress as bus_progress
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import (
GoalStateSyncEvent,
@@ -28,7 +28,6 @@ from nanobot.bus.outbound_events import (
from nanobot.bus.queue import MessageBus
from 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()
@staticmethod
def _ctx_msg(ctx: RuntimeEventContext) -> InboundMessage:
return InboundMessage(
+59 -25
View File
@@ -7,14 +7,13 @@ from collections.abc import Awaitable, Callable
from typing import Any, cast
from 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, EventSink
def _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)
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 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)
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]:
+3
View File
@@ -90,6 +90,9 @@ def iter_webui_source_files(source_dir: Path) -> list[Path]:
if not root.is_dir():
continue
files.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"):
+11 -18
View File
@@ -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_current
from 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_key
from 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.event
progress_event = event if isinstance(event, ProgressEvent) else None
if isinstance(event, RuntimeModelUpdatedEvent):
await self._transport.send_runtime_model_updated(
@@ -182,21 +179,17 @@ 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,
)
return
if isinstance(event, GoalStateSyncEvent):
if conns:
+27 -1
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
from nanobot.bus.outbound_events import (
@@ -10,6 +11,7 @@ from nanobot.bus.outbound_events import (
RecoveryStateEvent,
TurnEndEvent,
)
from nanobot.events import AgentEvent
from 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,