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:
1 parent
3495281282
commit
192e2e90dc
78 files changed
+1620
-1194
No files matched your search
+1
-1
@@ -6,7 +6,7 @@ These rules govern architectural decisions. When adding a feature or fixing a bu
|
||||
|
||||
New capabilities should be added via `channels/`, `tools/`, skills, or MCP servers. The files `agent/loop.py` and `agent/runner.py` form the critical core path; changes there should be minimal and justified. If a feature can live in a channel adapter, a tool, or an external MCP server, it should not be inlined into the agent loop.
|
||||
|
||||
Runtime state fan-out follows the same boundary. `AgentLoop` may publish generic runtime events from `nanobot.bus.runtime_events` for turn/run/model/goal state changes, but WebUI/WebSocket wire details such as `_turn_end`, `_goal_status`, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter.
|
||||
Runtime state fan-out follows the same boundary. `MessageBus.publish` awaits local subscribers for turn/run/model/goal state changes; `MessageBus.publish_event` queues routed channel delivery without waiting for network sends. Both carry `AgentEvent` values. Runner hooks publish typed output through the turn's scoped `EventSink`; direct-call callbacks are adapted at the execution boundary. WebUI/WebSocket wire details, title refreshes, and goal-state sync belong in `nanobot.session.webui_turns.WebuiTurnCoordinator` or the relevant channel adapter.
|
||||
|
||||
## Less structure, more intelligence
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ COPY webui/package.json webui/package-lock.json ./webui/
|
||||
WORKDIR /app/webui
|
||||
RUN npm ci
|
||||
COPY webui/ ./
|
||||
COPY packages/client-events/ /app/packages/client-events/
|
||||
RUN mkdir -p /app/nanobot/web && npm run build
|
||||
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
@@ -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
@@ -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",
|
||||
|
||||
@@ -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={}",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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())
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
@@ -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
@@ -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)
|
||||
@@ -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] = {}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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())
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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"):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
[
|
||||
{"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"started"},
|
||||
{"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"succeeded"},
|
||||
{"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"failed"},
|
||||
{"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"cancelled"},
|
||||
{"event":"recovery_state","chat_id":"chat","status":"resuming","recovery_id":"r1","attempts":0},
|
||||
{"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r1","attempts":1,"reason":"tool_state_unknown","can_continue":false},
|
||||
{"event":"recovery_state","chat_id":"chat","status":"recovered","recovery_id":"r1","attempts":1},
|
||||
{"event":"recovery_state","chat_id":"chat","status":"failed","recovery_id":"r1","attempts":2}
|
||||
]
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Transport notifications shared by the browser and terminal clients. */
|
||||
export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed"
|
||||
|
||||
export interface RecoveryState {
|
||||
status: RecoveryStatus
|
||||
recovery_id: string
|
||||
reason?: string
|
||||
attempts?: number
|
||||
can_continue?: boolean
|
||||
}
|
||||
|
||||
export interface ContextCompaction {
|
||||
id: string
|
||||
phase: "started" | "succeeded" | "failed" | "cancelled"
|
||||
}
|
||||
|
||||
export type NotificationEvent =
|
||||
| ({ event: "recovery_state"; chat_id: string; turn_id?: string } & RecoveryState)
|
||||
| {
|
||||
event: "context_compaction"
|
||||
chat_id: string
|
||||
turn_id?: string
|
||||
compaction_id: string
|
||||
phase: ContextCompaction["phase"]
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function optional(value: unknown, type: "boolean" | "number" | "string"): boolean {
|
||||
return value === undefined || typeof value === type
|
||||
}
|
||||
|
||||
export function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] {
|
||||
return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled"
|
||||
}
|
||||
|
||||
export function isRecoveryState(value: unknown): value is RecoveryState {
|
||||
return isRecord(value)
|
||||
&& typeof value.status === "string"
|
||||
&& ["resuming", "awaiting_user", "recovered", "failed"].includes(value.status)
|
||||
&& typeof value.recovery_id === "string"
|
||||
&& optional(value.reason, "string")
|
||||
&& optional(value.attempts, "number")
|
||||
&& optional(value.can_continue, "boolean")
|
||||
}
|
||||
|
||||
/** Undefined means another protocol family; null means a malformed notification. */
|
||||
export function decodeNotification(value: unknown): NotificationEvent | null | undefined {
|
||||
if (!isRecord(value)) return undefined
|
||||
if (value.event !== "recovery_state" && value.event !== "context_compaction") return undefined
|
||||
if (typeof value.chat_id !== "string" || !optional(value.turn_id, "string")) return null
|
||||
if (value.event === "recovery_state") {
|
||||
return isRecoveryState(value) ? value as unknown as NotificationEvent : null
|
||||
}
|
||||
return typeof value.compaction_id === "string" && value.compaction_id.length > 0
|
||||
&& isCompactionPhase(value.phase) ? value as unknown as NotificationEvent : null
|
||||
}
|
||||
|
||||
/** A terminal history row must not regress when an older live event arrives. */
|
||||
export function acceptsCompactionPhase(
|
||||
current: ContextCompaction["phase"] | undefined,
|
||||
incoming: ContextCompaction["phase"],
|
||||
): boolean {
|
||||
return current === undefined || (current === "started" && incoming !== "started")
|
||||
}
|
||||
@@ -13,6 +13,7 @@ from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command import CommandContext
|
||||
from nanobot.config.schema import AgentDefaults, Config
|
||||
from nanobot.events import NO_EVENTS
|
||||
from nanobot.providers.base import LLMResponse
|
||||
|
||||
|
||||
@@ -89,7 +90,7 @@ def _make_fake_compact(
|
||||
runtime,
|
||||
max_suffix: int = 8,
|
||||
trigger: str = "policy",
|
||||
on_compaction=None,
|
||||
events=NO_EVENTS,
|
||||
) -> str:
|
||||
state["count"] += 1
|
||||
session = loop.sessions.get_or_create(key)
|
||||
|
||||
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.autocompact import AutoCompact
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent
|
||||
from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ class TestCheckExpired:
|
||||
"cli:old",
|
||||
runtime=admitted,
|
||||
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
|
||||
on_compaction=None,
|
||||
events=NO_EVENTS,
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])
|
||||
@@ -445,7 +445,7 @@ class TestArchiveDelegates:
|
||||
"cli:test",
|
||||
runtime=runtime,
|
||||
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
|
||||
on_compaction=None,
|
||||
events=NO_EVENTS,
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -457,11 +457,11 @@ class TestArchiveDelegates:
|
||||
def bind(key: str):
|
||||
async def publish(event: ContextCompactionEvent) -> None:
|
||||
observed.append((key, event))
|
||||
return publish
|
||||
return EventSink(publish)
|
||||
|
||||
async def compact(key: str, **kwargs):
|
||||
event = ContextCompactionEvent(compaction_id="compact-1", phase="started")
|
||||
await kwargs["on_compaction"](event)
|
||||
await kwargs["events"].emit(event)
|
||||
return "Summary."
|
||||
|
||||
consolidator.compact_idle_session = AsyncMock(side_effect=compact)
|
||||
@@ -469,7 +469,7 @@ class TestArchiveDelegates:
|
||||
sessions=sessions,
|
||||
consolidator=consolidator,
|
||||
session_ttl_minutes=15,
|
||||
bind_compaction=bind,
|
||||
bind_events=bind,
|
||||
)
|
||||
|
||||
await ac._archive("cli:test", runtime=_runtime())
|
||||
|
||||
@@ -10,7 +10,7 @@ from nanobot.agent.memory import (
|
||||
Consolidator,
|
||||
MemoryStore,
|
||||
)
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent
|
||||
from nanobot.events import AgentEvent, ContextCompactionEvent, EventSink
|
||||
from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
LLMResponse,
|
||||
@@ -569,13 +569,14 @@ class TestCompactIdleSession:
|
||||
real_consolidator.sessions.save(session)
|
||||
events: list[ContextCompactionEvent] = []
|
||||
|
||||
async def observe(event: ContextCompactionEvent) -> None:
|
||||
events.append(event)
|
||||
async def observe(event: AgentEvent) -> None:
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
events.append(event)
|
||||
|
||||
result = await real_consolidator.compact_idle_session(
|
||||
"cli:events",
|
||||
runtime=runtime,
|
||||
on_compaction=observe,
|
||||
events=EventSink(observe),
|
||||
)
|
||||
|
||||
assert result == "Summary."
|
||||
@@ -593,13 +594,13 @@ class TestCompactIdleSession:
|
||||
session.add_message("user", "question")
|
||||
real_consolidator.sessions.save(session)
|
||||
|
||||
async def fail_observer(_event: ContextCompactionEvent) -> None:
|
||||
async def fail_observer(_event: AgentEvent) -> None:
|
||||
raise RuntimeError("channel unavailable")
|
||||
|
||||
result = await real_consolidator.compact_idle_session(
|
||||
"cli:event-callback-failure",
|
||||
runtime=runtime,
|
||||
on_compaction=fail_observer,
|
||||
events=EventSink(fail_observer),
|
||||
)
|
||||
|
||||
assert result == "Summary."
|
||||
|
||||
@@ -15,6 +15,7 @@ from nanobot.agent.hook import (
|
||||
CompositeHook,
|
||||
)
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.utils.progress_events import output_events
|
||||
|
||||
|
||||
def _ctx() -> AgentHookContext:
|
||||
@@ -507,7 +508,7 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[{"role": "user", "content": "hi"}], current_message=None),
|
||||
runtime=runtime,
|
||||
on_progress=on_progress,
|
||||
events=output_events(on_progress=on_progress),
|
||||
request_context=RequestContext(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
@@ -521,7 +522,8 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):
|
||||
|
||||
assert events == ["registered:0", "turn:0"]
|
||||
assert [label for label, _ in captured] == ["registered", "turn"]
|
||||
assert [context.on_progress for _, context in captured] == [on_progress, on_progress]
|
||||
assert captured[0][1].events is captured[1][1].events
|
||||
assert captured[0][1].events.publish is not None
|
||||
assert [context.workspace for _, context in captured] == [tmp_path, tmp_path]
|
||||
assert [context.channel for _, context in captured] == ["websocket", "websocket"]
|
||||
assert [context.chat_id for _, context in captured] == ["chat-1", "chat-1"]
|
||||
@@ -580,7 +582,7 @@ async def test_agent_loop_extra_hooks_do_not_swallow_loop_hook_errors(tmp_path):
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=bad_progress,
|
||||
events=output_events(on_progress=bad_progress),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ def _make_loop(tmp_path):
|
||||
bus=bus,
|
||||
sessions=loop.sessions,
|
||||
schedule_background=lambda coro: loop.schedule_background(coro),
|
||||
).subscribe(loop.runtime_events)
|
||||
).subscribe()
|
||||
loop.turn_delivery_factory.route_policy = WebuiTurnRoutePolicy(loop.sessions)
|
||||
loop.tools.get_definitions = MagicMock(return_value=[])
|
||||
return loop
|
||||
|
||||
@@ -25,10 +25,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
from nanobot.providers.factory import ProviderSnapshot
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator, WebuiTurnRoutePolicy
|
||||
from nanobot.utils.progress_events import (
|
||||
invoke_file_edit_progress,
|
||||
on_progress_accepts_file_edit_events,
|
||||
)
|
||||
from nanobot.utils.progress_events import output_events
|
||||
from nanobot.webui.metadata import (
|
||||
WEBSOCKET_TURN_OWNER_METADATA_KEY,
|
||||
WEBUI_TURN_METADATA_KEY,
|
||||
@@ -55,7 +52,7 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:
|
||||
sessions=loop.sessions,
|
||||
schedule_background=lambda coro: loop.schedule_background(coro),
|
||||
)
|
||||
coordinator.subscribe(loop.runtime_events)
|
||||
coordinator.subscribe()
|
||||
|
||||
|
||||
class TestToolEventProgress:
|
||||
@@ -87,7 +84,7 @@ class TestToolEventProgress:
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=on_progress,
|
||||
events=output_events(on_progress=on_progress),
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
@@ -160,7 +157,7 @@ class TestToolEventProgress:
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=on_progress,
|
||||
events=output_events(on_progress=on_progress),
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
@@ -232,7 +229,7 @@ class TestToolEventProgress:
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=on_progress,
|
||||
events=output_events(on_progress=on_progress),
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
@@ -272,7 +269,7 @@ class TestToolEventProgress:
|
||||
await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=on_progress,
|
||||
events=output_events(on_progress=on_progress),
|
||||
)
|
||||
|
||||
assert file_events == []
|
||||
@@ -368,10 +365,8 @@ class TestToolEventProgress:
|
||||
chat_id="chat1",
|
||||
content="edit",
|
||||
)
|
||||
progress = loop.turn_delivery_factory.create(msg, msg.session_key).progress_callback()
|
||||
assert progress is not None
|
||||
assert on_progress_accepts_file_edit_events(progress) is True
|
||||
await invoke_file_edit_progress(progress, edit_events)
|
||||
events = loop.turn_delivery_factory.create(msg, msg.session_key).events
|
||||
await events.emit(ProgressEvent(file_edit_events=edit_events))
|
||||
outbound = await bus.consume_outbound()
|
||||
assert outbound.channel == "telegram"
|
||||
assert isinstance(outbound.event, ProgressEvent)
|
||||
@@ -685,14 +680,12 @@ class TestToolEventProgress:
|
||||
async def cancel_after_merge(
|
||||
_msg: InboundMessage,
|
||||
*,
|
||||
on_stream,
|
||||
on_stream_end,
|
||||
delivery,
|
||||
**_kwargs,
|
||||
):
|
||||
assert on_stream is not None
|
||||
assert on_stream_end is not None
|
||||
await on_stream("partial")
|
||||
await on_stream_end(resuming=True, merge_next=True)
|
||||
assert delivery.streaming
|
||||
await delivery.events.emit(StreamDeltaEvent(content="partial"))
|
||||
await delivery.events.emit(StreamEndEvent(resuming=True, merge_next=True))
|
||||
raise asyncio.CancelledError
|
||||
|
||||
loop._process_message = cancel_after_merge # type: ignore[method-assign]
|
||||
@@ -1019,8 +1012,8 @@ class TestToolEventProgress:
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=on_progress,
|
||||
on_stream=on_stream,
|
||||
events=output_events(on_progress=on_progress, on_stream=on_stream),
|
||||
streaming=True,
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
|
||||
@@ -22,6 +22,7 @@ from nanobot.runtime_context import (
|
||||
)
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.utils.progress_events import output_events
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
_GOAL_RUNTIME_GUIDANCE_TAG = "[Goal Runtime Guidance — host instructions]"
|
||||
@@ -400,8 +401,8 @@ async def test_loop_stream_filter_handles_think_only_prefix_without_crashing(tmp
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_stream=on_stream,
|
||||
on_stream_end=on_stream_end,
|
||||
events=output_events(on_stream=on_stream, on_stream_end=on_stream_end),
|
||||
streaming=True,
|
||||
)
|
||||
|
||||
assert result.final_content == "Hello"
|
||||
@@ -427,7 +428,8 @@ async def test_loop_stream_filter_hides_partial_trailing_think_prefix(tmp_path):
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_stream=on_stream,
|
||||
events=output_events(on_stream=on_stream),
|
||||
streaming=True,
|
||||
)
|
||||
|
||||
assert result.final_content == "Hello World"
|
||||
@@ -452,7 +454,8 @@ async def test_loop_stream_filter_hides_complete_trailing_think_tag(tmp_path):
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_stream=on_stream,
|
||||
events=output_events(on_stream=on_stream),
|
||||
streaming=True,
|
||||
)
|
||||
|
||||
assert result.final_content == "Hello World"
|
||||
|
||||
@@ -129,7 +129,7 @@ def _make_full_loop(tmp_path: Path) -> AgentLoop:
|
||||
bus=loop.bus,
|
||||
sessions=loop.sessions,
|
||||
schedule_background=lambda coro: loop.schedule_background(coro),
|
||||
).subscribe(loop.runtime_events)
|
||||
).subscribe()
|
||||
return loop
|
||||
|
||||
|
||||
@@ -1452,7 +1452,7 @@ async def test_internal_continuation_preserves_streaming_route_metadata(
|
||||
|
||||
calls = 0
|
||||
|
||||
async def fake_run_agent_loop(transcript_input, *, on_stream=None, on_stream_end=None, **_kwargs):
|
||||
async def fake_run_agent_loop(transcript_input, *, events, streaming, **_kwargs):
|
||||
nonlocal calls
|
||||
initial_messages = _assembled_messages(loop.context, transcript_input)
|
||||
calls += 1
|
||||
@@ -1462,10 +1462,9 @@ async def test_internal_continuation_preserves_streaming_route_metadata(
|
||||
[*initial_messages, {"role": "assistant", "content": "paused"}],
|
||||
stop_reason="max_iterations",
|
||||
)
|
||||
assert on_stream is not None
|
||||
assert on_stream_end is not None
|
||||
await on_stream("done")
|
||||
await on_stream_end(resuming=False)
|
||||
assert streaming
|
||||
await events.emit(StreamDeltaEvent(content="done"))
|
||||
await events.emit(StreamEndEvent())
|
||||
return _agent_run_result(
|
||||
"done",
|
||||
[*initial_messages, {"role": "assistant", "content": "done"}],
|
||||
|
||||
@@ -1281,9 +1281,10 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runner_binds_on_retry_wait_callback():
|
||||
"""Provider retry heartbeats use the explicitly supplied callback."""
|
||||
async def test_runner_carries_retry_notifications_in_provider_context():
|
||||
"""The runner carries a generic scope, not an event-specific callback."""
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.events import EventSink, RetryWaitEvent
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
@@ -1308,10 +1309,13 @@ async def test_runner_binds_on_retry_wait_callback():
|
||||
model="test-model",
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
retry_wait_callback=retry_wait_cb,
|
||||
events=EventSink(retry_wait_cb),
|
||||
))
|
||||
|
||||
assert captured["on_retry_wait"] is retry_wait_cb
|
||||
assert "on_retry_wait" not in captured
|
||||
event = RetryWaitEvent("waiting")
|
||||
await captured["provider_context"].events.emit(event)
|
||||
retry_wait_cb.assert_awaited_once_with(event)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -169,6 +169,28 @@ def test_fallback_models_accept_preset_refs_and_inline_configs() -> None:
|
||||
)
|
||||
|
||||
|
||||
async def test_fallback_preserves_the_operation_event_sink():
|
||||
from nanobot.events import EventSink
|
||||
|
||||
async def observe(event):
|
||||
pass
|
||||
|
||||
events = EventSink(observe)
|
||||
primary = _FakeProvider("primary", _error_response())
|
||||
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
|
||||
fb = FallbackProvider(
|
||||
primary=primary, fallback_presets=[_fallback("fallback-a")],
|
||||
provider_factory=MagicMock(return_value=fallback),
|
||||
)
|
||||
result = await fb.chat_with_context(
|
||||
messages=[{"role": "user", "content": "hello"}], model="primary",
|
||||
provider_context=ProviderCallContext(events=events),
|
||||
)
|
||||
assert result.content == "fallback ok"
|
||||
assert primary.context_calls[0].events is events
|
||||
assert fallback.context_calls[0].events is events
|
||||
|
||||
|
||||
def test_fallback_model_preset_ref_must_exist() -> None:
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
@@ -1047,6 +1069,48 @@ class TestFailoverOnTransientError:
|
||||
|
||||
|
||||
class TestRetryBeforeFailover:
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
async def test_scoped_retry_events_preserve_fallback_chain_ownership(self, stream):
|
||||
from nanobot.events import EventSink, RetryWaitEvent
|
||||
|
||||
primary = _FakeProvider("primary", _retryable_error("primary unavailable"))
|
||||
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
|
||||
provider = FallbackProvider(primary, [_fallback("fallback-a")],
|
||||
MagicMock(return_value=fallback))
|
||||
observe = AsyncMock()
|
||||
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
|
||||
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
|
||||
result = await call(
|
||||
[{"role": "user", "content": "hi"}],
|
||||
provider_context=ProviderCallContext(events=EventSink(observe)),
|
||||
)
|
||||
assert result.content == "fallback ok"
|
||||
events = [call.args[0] for call in observe.await_args_list]
|
||||
assert len(events) == 3
|
||||
assert all(isinstance(event, RetryWaitEvent) for event in events)
|
||||
assert not any("giving up" in event.content for event in events)
|
||||
|
||||
async def test_scoped_persistent_retry_includes_chain_wait_and_one_terminal(self):
|
||||
from nanobot.events import EventSink
|
||||
|
||||
primary = _FakeProvider("primary", _retryable_error("primary unavailable"))
|
||||
fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))
|
||||
provider = FallbackProvider(primary, [_fallback("fallback-a")],
|
||||
MagicMock(return_value=fallback))
|
||||
provider._PERSISTENT_IDENTICAL_ERROR_LIMIT = 2
|
||||
observe = AsyncMock()
|
||||
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
|
||||
result = await provider.chat_with_retry(
|
||||
[{"role": "user", "content": "hi"}], retry_mode="persistent",
|
||||
provider_context=ProviderCallContext(events=EventSink(observe)),
|
||||
)
|
||||
assert result.finish_reason == "error"
|
||||
notices = [call.args[0].content for call in observe.await_args_list]
|
||||
# Two candidates, three waits each, for two chains, plus one chain wait.
|
||||
assert len(notices) == 14
|
||||
assert sum("Persistent retry stopped" in text for text in notices) == 1
|
||||
assert not any("giving up" in text for text in notices)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("retry_mode", ["standard", "persistent"])
|
||||
async def test_primary_recovers_before_fallback(self, retry_mode: str) -> None:
|
||||
|
||||
@@ -16,8 +16,8 @@ from nanobot.agent.context_governance import (
|
||||
ModelRequestState,
|
||||
)
|
||||
from nanobot.agent.runner import AgentRunner, AgentRunSpec
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import ContextCompactionEvent, EventSink
|
||||
from nanobot.providers.base import (
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
@@ -76,6 +76,32 @@ def _make_loop(tmp_path):
|
||||
return loop
|
||||
|
||||
|
||||
async def test_provider_can_emit_without_an_event_specific_runner_callback():
|
||||
from nanobot.events import AgentEvent
|
||||
|
||||
event = AgentEvent()
|
||||
received = []
|
||||
|
||||
async def observe(value):
|
||||
received.append(value)
|
||||
|
||||
async def request(*, provider_context, **kwargs):
|
||||
await provider_context.events.emit(event)
|
||||
return LLMResponse(content="done")
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider.chat_with_retry = request
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
await AgentRunner().run(make_run_spec(
|
||||
provider, model="test-model", tools=tools, max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
initial_messages=[{"role": "user", "content": "hello"}],
|
||||
events=EventSink(observe),
|
||||
))
|
||||
assert received == [event]
|
||||
|
||||
|
||||
async def test_runner_propagates_context_governance_failure():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
@@ -394,7 +420,7 @@ async def test_native_compaction_uses_provider_request_boundary(
|
||||
max_tokens=100,
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
compaction_callback=observe_compaction,
|
||||
events=EventSink(observe_compaction),
|
||||
))
|
||||
|
||||
consolidate.assert_not_awaited()
|
||||
@@ -534,7 +560,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
|
||||
max_tokens=100,
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
compaction_callback=observe_compaction,
|
||||
events=EventSink(observe_compaction),
|
||||
))
|
||||
|
||||
assert consolidate.await_count == 2
|
||||
|
||||
@@ -12,6 +12,7 @@ from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.agent.tools.filesystem import EditFileTool, WriteFileTool
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
from nanobot.utils.progress_events import output_events
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
|
||||
@@ -61,7 +62,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
|
||||
async def stream_cb(content: str) -> None:
|
||||
streamed_text.append(content)
|
||||
|
||||
hook = AgentProgressHook(on_progress=progress_cb, on_stream=stream_cb)
|
||||
hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "search X"}],
|
||||
@@ -135,7 +136,7 @@ async def test_runner_fails_pending_hosted_tool_when_model_request_fails():
|
||||
async def stream_cb(_content: str) -> None:
|
||||
pass
|
||||
|
||||
hook = AgentProgressHook(on_progress=progress_cb, on_stream=stream_cb)
|
||||
hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
initial_messages=[{"role": "user", "content": "search X"}],
|
||||
@@ -213,7 +214,7 @@ async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_pa
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
workspace=tmp_path,
|
||||
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
|
||||
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
|
||||
))
|
||||
|
||||
assert result.final_content == "done"
|
||||
@@ -283,7 +284,7 @@ async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_pat
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
workspace=tmp_path,
|
||||
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
|
||||
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
|
||||
))
|
||||
|
||||
assert result.final_content == "done"
|
||||
@@ -345,7 +346,7 @@ async def test_runner_marks_file_edit_activity_failed_when_tool_errors(tmp_path)
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
workspace=tmp_path,
|
||||
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
|
||||
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
|
||||
))
|
||||
|
||||
assert result.stop_reason == "completed"
|
||||
@@ -405,7 +406,7 @@ async def test_runner_marks_file_edit_activity_failed_when_cancelled(tmp_path):
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
workspace=tmp_path,
|
||||
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
|
||||
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
|
||||
)))
|
||||
await asyncio.wait_for(executing.wait(), timeout=1)
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||
from nanobot.agent.progress_hook import AgentProgressHook
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest
|
||||
from nanobot.utils.progress_events import output_events
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
|
||||
@@ -324,7 +325,7 @@ async def test_runner_does_not_double_emit_when_inline_think_already_streamed():
|
||||
async def _stream(_content: str) -> None:
|
||||
pass
|
||||
|
||||
hook = AgentProgressHook(on_progress=_progress, on_stream=_stream)
|
||||
hook = AgentProgressHook(output_events(on_progress=_progress, on_stream=_stream), streaming=True)
|
||||
runner = AgentRunner()
|
||||
result = await runner.run(make_run_spec(provider,
|
||||
initial_messages=[{"role": "user", "content": "question"}],
|
||||
|
||||
@@ -224,7 +224,7 @@ async def test_config_invalidation_defers_canonical_notification_until_default_r
|
||||
model_preset="fast",
|
||||
preset_snapshot_loader=load_preset,
|
||||
)
|
||||
loop.runtime_events.subscribe(published.append, RuntimeModelChanged)
|
||||
loop.bus.subscribe(published.append, RuntimeModelChanged)
|
||||
session = loop.sessions.get_or_create("websocket:chat")
|
||||
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"
|
||||
current_model = "model-b"
|
||||
@@ -275,7 +275,7 @@ async def test_config_refresh_publishes_renamed_canonical_preset(tmp_path: Path)
|
||||
model_preset="fast",
|
||||
preset_snapshot_loader=load_preset,
|
||||
)
|
||||
loop.runtime_events.subscribe(published.append, RuntimeModelChanged)
|
||||
loop.bus.subscribe(published.append, RuntimeModelChanged)
|
||||
catalog["Codex"] = catalog.pop("fast")
|
||||
default_name = "Codex"
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.providers.base import GenerationSettings
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY
|
||||
@@ -277,7 +278,6 @@ class TestDispatch:
|
||||
@pytest.mark.asyncio
|
||||
async def test_dispatch_streaming_preserves_message_metadata(self):
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
|
||||
|
||||
loop, bus = _make_loop()
|
||||
msg = InboundMessage(
|
||||
@@ -292,11 +292,10 @@ class TestDispatch:
|
||||
},
|
||||
)
|
||||
|
||||
async def fake_process(_msg, *, on_stream=None, on_stream_end=None, **kwargs):
|
||||
assert on_stream is not None
|
||||
assert on_stream_end is not None
|
||||
await on_stream("hi")
|
||||
await on_stream_end(resuming=False)
|
||||
async def fake_process(_msg, *, delivery, **kwargs):
|
||||
assert delivery.streaming
|
||||
await delivery.events.emit(StreamDeltaEvent(content="hi"))
|
||||
await delivery.events.emit(StreamEndEvent())
|
||||
return None
|
||||
|
||||
loop._process_message = fake_process
|
||||
|
||||
@@ -6,7 +6,6 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import ContextCompactionEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventBus
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
|
||||
from nanobot.webui.metadata import (
|
||||
@@ -31,7 +30,7 @@ from nanobot.webui.metadata import (
|
||||
async def test_idle_compaction_uses_the_session_delivery_route(
|
||||
key, channel, chat_id, metadata, unified,
|
||||
) -> None:
|
||||
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
|
||||
factory = TurnDeliveryFactory(MessageBus())
|
||||
event = ContextCompactionEvent(compaction_id="compact-1", phase="started")
|
||||
key = "unified:default" if unified else key
|
||||
msg = InboundMessage(
|
||||
@@ -45,9 +44,9 @@ async def test_idle_compaction_uses_the_session_delivery_route(
|
||||
session_metadata = {}
|
||||
delivery.remember_session_route(session_metadata)
|
||||
|
||||
callback = factory.session_compaction_callback(key, session_metadata)
|
||||
assert callback is not None
|
||||
await callback(event)
|
||||
sink = factory.session_events(key, session_metadata)
|
||||
assert sink.publish is not None
|
||||
await sink.emit(event)
|
||||
|
||||
outbound = factory.bus.outbound.get_nowait()
|
||||
assert (outbound.channel, outbound.chat_id, outbound.metadata) == (channel, chat_id, metadata)
|
||||
@@ -55,7 +54,7 @@ async def test_idle_compaction_uses_the_session_delivery_route(
|
||||
|
||||
|
||||
async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:
|
||||
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
|
||||
factory = TurnDeliveryFactory(MessageBus())
|
||||
key = "unified:default"
|
||||
session_metadata = {}
|
||||
original = InboundMessage(
|
||||
@@ -63,15 +62,15 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
|
||||
metadata={"slack": {"thread_ts": "1700000000.000100"}},
|
||||
)
|
||||
factory.create(original, key).remember_session_route(session_metadata)
|
||||
callback = factory.session_compaction_callback(key, session_metadata)
|
||||
assert callback is not None
|
||||
await callback(ContextCompactionEvent("compact-1", "started"))
|
||||
sink = factory.session_events(key, session_metadata)
|
||||
assert sink.publish is not None
|
||||
await sink.emit(ContextCompactionEvent("compact-1", "started"))
|
||||
|
||||
latest = InboundMessage(
|
||||
channel="telegram", sender_id="user", chat_id="42", content="next question",
|
||||
)
|
||||
factory.create(latest, key).remember_session_route(session_metadata)
|
||||
await callback(ContextCompactionEvent("compact-1", "succeeded"))
|
||||
await sink.emit(ContextCompactionEvent("compact-1", "succeeded"))
|
||||
|
||||
events = [factory.bus.outbound.get_nowait() for _ in range(2)]
|
||||
assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [
|
||||
@@ -80,11 +79,11 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
|
||||
|
||||
|
||||
async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> None:
|
||||
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
|
||||
factory = TurnDeliveryFactory(MessageBus())
|
||||
event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded")
|
||||
callback = factory.session_compaction_callback("websocket:chat", {})
|
||||
assert callback is not None
|
||||
await callback(event)
|
||||
sink = factory.session_events("websocket:chat", {})
|
||||
assert sink.publish is not None
|
||||
await sink.emit(event)
|
||||
outbound = factory.bus.outbound.get_nowait()
|
||||
assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event)
|
||||
|
||||
@@ -92,7 +91,6 @@ async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> No
|
||||
def test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None:
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
RuntimeEventBus(),
|
||||
route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),
|
||||
)
|
||||
first_msg = InboundMessage(
|
||||
@@ -141,7 +139,6 @@ def test_websocket_lifecycle_reuses_registered_ingress_owner(tmp_path: Path) ->
|
||||
)
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
RuntimeEventBus(),
|
||||
route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),
|
||||
)
|
||||
|
||||
@@ -163,7 +160,6 @@ def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> N
|
||||
sessions.save(target)
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
RuntimeEventBus(),
|
||||
route_policy=WebuiTurnRoutePolicy(sessions),
|
||||
)
|
||||
msg = InboundMessage(
|
||||
@@ -194,7 +190,6 @@ async def test_same_chat_different_sessions_restore_previous_active_projection(
|
||||
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
RuntimeEventBus(),
|
||||
route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),
|
||||
)
|
||||
first_msg = InboundMessage(
|
||||
@@ -253,7 +248,6 @@ def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> Non
|
||||
sessions = SessionManager(tmp_path)
|
||||
factory = TurnDeliveryFactory(
|
||||
MessageBus(),
|
||||
RuntimeEventBus(),
|
||||
route_policy=WebuiTurnRoutePolicy(sessions),
|
||||
)
|
||||
session_key = "websocket:chat-a"
|
||||
|
||||
@@ -21,7 +21,6 @@ from nanobot.agent.tools.long_task import (
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.outbound_events import GoalStateSyncEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventBus
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARS
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.turn_continuation import should_finalize_on_max_iterations
|
||||
@@ -378,17 +377,16 @@ async def test_registry_does_not_reuse_goal_context_after_request_scope(tmp_path
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_state_events_publish_active_then_inactive(tmp_path):
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
runtime_events = RuntimeEventBus()
|
||||
sm = SessionManager(tmp_path)
|
||||
WebuiTurnCoordinator(
|
||||
bus=bus,
|
||||
sessions=sm,
|
||||
schedule_background=lambda _coro: None,
|
||||
).subscribe(runtime_events)
|
||||
create = CreateGoalTool(sessions=sm, runtime_events=runtime_events)
|
||||
update = UpdateGoalTool(sessions=sm, runtime_events=runtime_events)
|
||||
).subscribe()
|
||||
create = CreateGoalTool(sessions=sm, bus=bus)
|
||||
update = UpdateGoalTool(sessions=sm, bus=bus)
|
||||
rc = _request_context(chat_id="chat-99")
|
||||
await _execute(
|
||||
create,
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory, TurnRoute
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.notification_delivery import NOTIFICATION_AUDIENCES
|
||||
from nanobot.bus.outbound_events import (
|
||||
FileEditEvent,
|
||||
ProgressEvent,
|
||||
StreamDeltaEvent,
|
||||
StreamEndEvent,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.events import AgentEvent, ContextCompactionEvent, EventSink, RetryWaitEvent
|
||||
from nanobot.utils.progress_events import output_events
|
||||
from nanobot.webui.outbound_wire import project_notification
|
||||
|
||||
|
||||
async def test_sink_isolates_observer_failure_but_propagates_cancellation():
|
||||
async def broken(event):
|
||||
raise ValueError("observer failed")
|
||||
|
||||
await EventSink(broken).emit(AgentEvent())
|
||||
|
||||
async def cancelled(event):
|
||||
raise asyncio.CancelledError
|
||||
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await EventSink(cancelled).emit(AgentEvent())
|
||||
|
||||
|
||||
async def test_scoped_output_preserves_routing_and_stream_segment_ownership():
|
||||
bus = MessageBus()
|
||||
delivery = TurnDeliveryFactory(bus).create(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="chat", content="",
|
||||
metadata={"_wants_stream": True, "origin_message_id": "original"},
|
||||
), "websocket:chat", enable_stream=True)
|
||||
events = [
|
||||
ProgressEvent(content="thinking"),
|
||||
FileEditEvent(file_edit_events=[{"phase": "start", "path": "a.py"}]),
|
||||
StreamDeltaEvent(content="first"),
|
||||
StreamEndEvent(resuming=True, merge_next=True),
|
||||
StreamDeltaEvent(content="tail"),
|
||||
]
|
||||
for event in events:
|
||||
await delivery.events.emit(event)
|
||||
await delivery.abort_stream()
|
||||
messages = [bus.outbound.get_nowait() for _ in range(6)]
|
||||
assert [message.content for message in messages] == ["thinking", "", "first", "", "tail", ""]
|
||||
assert all(message.chat_id == "chat" for message in messages)
|
||||
assert all(message.metadata["origin_message_id"] == "original" for message in messages)
|
||||
streams = [message.event for message in messages[2:]]
|
||||
assert all(isinstance(event, StreamDeltaEvent | StreamEndEvent) for event in streams)
|
||||
assert len({event.stream_id for event in streams}) == 1
|
||||
assert isinstance(streams[-1], StreamEndEvent)
|
||||
assert streams[-1].merge_next is False
|
||||
await delivery.abort_stream()
|
||||
assert bus.outbound.empty()
|
||||
|
||||
|
||||
async def test_output_consumer_capability_survives_callback_adaptation():
|
||||
bus = MessageBus()
|
||||
quiet = TurnDeliveryFactory(bus, lambda *_: TurnRoute("websocket", "chat")).create(
|
||||
InboundMessage(channel="system", sender_id="job", chat_id="websocket:chat", content=""),
|
||||
"websocket:chat",
|
||||
)
|
||||
assert quiet.events.accepts(ContextCompactionEvent)
|
||||
assert not quiet.events.accepts(FileEditEvent)
|
||||
|
||||
received = []
|
||||
|
||||
async def text_only(content, *, tool_hint=False):
|
||||
received.append(content)
|
||||
|
||||
events = output_events(default=quiet.events, on_progress=text_only)
|
||||
assert events.accepts(ProgressEvent)
|
||||
assert not events.accepts(FileEditEvent)
|
||||
await events.emit(ProgressEvent(content="working"))
|
||||
await events.emit(ContextCompactionEvent("compact", "succeeded"))
|
||||
assert received == ["working"]
|
||||
assert bus.outbound.get_nowait().event == ContextCompactionEvent("compact", "succeeded")
|
||||
|
||||
|
||||
async def test_scope_snapshots_route_and_queues_events_in_order():
|
||||
bus = MessageBus()
|
||||
metadata = {"slack": {"thread_ts": "original"}}
|
||||
factory = TurnDeliveryFactory(bus)
|
||||
delivery = factory.create(InboundMessage(
|
||||
channel="slack", sender_id="u", chat_id="chat", content="", metadata=metadata,
|
||||
), "unified:default")
|
||||
metadata["slack"]["thread_ts"] = "moved"
|
||||
for phase in ("started", "succeeded"):
|
||||
await delivery.events.emit(ContextCompactionEvent("c1", phase))
|
||||
for phase in ("started", "succeeded"):
|
||||
message = bus.outbound.get_nowait()
|
||||
assert message.metadata == {"slack": {"thread_ts": "original"}}
|
||||
assert message.event == ContextCompactionEvent("c1", phase)
|
||||
assert bus.outbound.empty()
|
||||
|
||||
|
||||
async def test_new_internal_event_needs_explicit_audience(monkeypatch):
|
||||
@dataclass(frozen=True)
|
||||
class RetryStatus(AgentEvent):
|
||||
state: str = "waiting"
|
||||
attempt: int = 1
|
||||
|
||||
bus = MessageBus()
|
||||
factory = TurnDeliveryFactory(bus)
|
||||
delivery = factory.create(InboundMessage(
|
||||
channel="websocket", sender_id="u", chat_id="chat", content="",
|
||||
), "websocket:chat")
|
||||
event = RetryStatus()
|
||||
await delivery.events.emit(event)
|
||||
assert bus.outbound.empty()
|
||||
assert project_notification("chat", event) is None
|
||||
|
||||
monkeypatch.setitem(NOTIFICATION_AUDIENCES, RetryStatus, "interactive")
|
||||
await delivery.events.emit(event)
|
||||
assert bus.outbound.get_nowait().event is event
|
||||
# Routing registration alone does not authorize serialization of private fields.
|
||||
assert project_notification("chat", event) is None
|
||||
|
||||
|
||||
async def test_background_scope_keeps_retry_quiet_but_delivers_compaction():
|
||||
bus = MessageBus()
|
||||
factory = TurnDeliveryFactory(bus,
|
||||
lambda *_: TurnRoute("websocket", "chat"))
|
||||
delivery = factory.create(InboundMessage(
|
||||
channel="system", sender_id="job", chat_id="websocket:chat", content="",
|
||||
), "websocket:chat")
|
||||
await delivery.events.emit(RetryWaitEvent("waiting"))
|
||||
assert bus.outbound.empty()
|
||||
event = ContextCompactionEvent("c1", "cancelled")
|
||||
await delivery.events.emit(event)
|
||||
assert bus.outbound.get_nowait().event is event
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["websocket", "cli", "slack", "custom"])
|
||||
async def test_bus_routes_arbitrary_events_and_text_through_one_queue(channel):
|
||||
@dataclass(frozen=True)
|
||||
class JobFinished(AgentEvent):
|
||||
job_id: str
|
||||
|
||||
bus = MessageBus()
|
||||
text = OutboundMessage(channel=channel, chat_id="chat", content="hello")
|
||||
event = JobFinished("job-1")
|
||||
await bus.publish_outbound(text)
|
||||
await bus.publish_event(event, channel=channel, chat_id="chat", metadata={"thread": "1"})
|
||||
assert await bus.consume_outbound() is text
|
||||
delivered = await bus.consume_outbound()
|
||||
assert (delivered.channel, delivered.chat_id) == (channel, "chat")
|
||||
assert delivered.event is event
|
||||
assert delivered.content == ""
|
||||
assert delivered.metadata == {"thread": "1"}
|
||||
assert bus.outbound.empty()
|
||||
|
||||
|
||||
async def test_bus_event_preserves_existing_text_fallback():
|
||||
bus = MessageBus()
|
||||
event = RetryWaitEvent("waiting")
|
||||
await bus.publish_event(event, channel="slack", chat_id="chat")
|
||||
delivered = await bus.consume_outbound()
|
||||
assert delivered.event is event
|
||||
assert delivered.content == "waiting"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
|
||||
def test_compaction_durability_is_independent_of_subscribers(phase):
|
||||
projection = project_notification("chat", ContextCompactionEvent("c1", phase))
|
||||
assert projection is not None
|
||||
assert projection.deliver_offline
|
||||
assert projection.attach_turn_metadata
|
||||
assert projection.persistence == ("transient" if phase == "started" else "turn_activity")
|
||||
@@ -3,17 +3,10 @@ from __future__ import annotations
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
GoalStateSyncEvent,
|
||||
GoalStatusEvent,
|
||||
ProgressEvent,
|
||||
RetryWaitEvent,
|
||||
RuntimeModelUpdatedEvent,
|
||||
SessionUpdatedEvent,
|
||||
StreamDeltaEvent,
|
||||
StreamedResponseEvent,
|
||||
StreamEndEvent,
|
||||
TurnEndEvent,
|
||||
outbound_event_from_message,
|
||||
outbound_message_for_event,
|
||||
replace_outbound_event,
|
||||
)
|
||||
@@ -52,7 +45,7 @@ def test_progress_event_lives_on_outbound_message_event_field() -> None:
|
||||
assert msg.content == "working"
|
||||
assert msg.metadata == {"origin_message_id": "m1"}
|
||||
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
assert isinstance(event, ProgressEvent)
|
||||
assert event.content == "working"
|
||||
assert event.tool_hint is True
|
||||
@@ -65,169 +58,12 @@ def test_progress_event_lives_on_outbound_message_event_field() -> None:
|
||||
def test_normal_outbound_message_has_no_runtime_event() -> None:
|
||||
msg = OutboundMessage(channel="websocket", chat_id="chat-1", content="hello")
|
||||
|
||||
assert outbound_event_from_message(msg) is None
|
||||
assert msg.event is None
|
||||
|
||||
|
||||
def test_legacy_progress_metadata_flags_create_runtime_event() -> None:
|
||||
tool_events = [{"phase": "start", "name": "read_file"}]
|
||||
file_edit_events = [{"phase": "end", "path": "app.py"}]
|
||||
msg = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="legacy progress",
|
||||
metadata={
|
||||
"_progress": True,
|
||||
"_tool_hint": True,
|
||||
"_reasoning_delta": True,
|
||||
"_stream_id": "r1",
|
||||
"_tool_events": tool_events,
|
||||
"_file_edit_events": file_edit_events,
|
||||
"message_id": "platform-routing-context",
|
||||
},
|
||||
)
|
||||
|
||||
event = outbound_event_from_message(msg)
|
||||
assert isinstance(event, ProgressEvent)
|
||||
assert event.content == "legacy progress"
|
||||
assert event.tool_hint is True
|
||||
assert event.reasoning_delta is True
|
||||
assert event.stream_id == "r1"
|
||||
assert event.tool_events == tool_events
|
||||
assert event.file_edit_events == file_edit_events
|
||||
|
||||
|
||||
def test_legacy_stream_metadata_flags_create_runtime_events() -> None:
|
||||
delta = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="hello",
|
||||
metadata={"_stream_delta": True, "_stream_id": "s1"},
|
||||
)
|
||||
end = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={
|
||||
"_stream_end": True,
|
||||
"_stream_id": "s1",
|
||||
"_resuming": True,
|
||||
"_merge_next": True,
|
||||
},
|
||||
)
|
||||
|
||||
delta_event = outbound_event_from_message(delta)
|
||||
assert isinstance(delta_event, StreamDeltaEvent)
|
||||
assert delta_event.content == "hello"
|
||||
assert delta_event.stream_id == "s1"
|
||||
|
||||
end_event = outbound_event_from_message(end)
|
||||
assert isinstance(end_event, StreamEndEvent)
|
||||
assert end_event.stream_id == "s1"
|
||||
assert end_event.resuming is True
|
||||
assert end_event.merge_next is True
|
||||
|
||||
|
||||
def test_legacy_webui_runtime_metadata_flags_create_runtime_events() -> None:
|
||||
runtime = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="*",
|
||||
content="",
|
||||
metadata={
|
||||
"_runtime_model_updated": True,
|
||||
"model": "gpt-5.5",
|
||||
"model_preset": "high",
|
||||
},
|
||||
)
|
||||
goal_state = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"_goal_state_sync": True, "goal_state": {"active": True}},
|
||||
)
|
||||
goal_status = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"_goal_status": True, "goal_status": "running", "started_at": 1.25},
|
||||
)
|
||||
turn_end = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"_turn_end": True, "latency_ms": 42.0, "goal_state": {"active": False}},
|
||||
)
|
||||
session_updated = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"_session_updated": True, "_session_update_scope": "metadata"},
|
||||
)
|
||||
|
||||
runtime_event = outbound_event_from_message(runtime)
|
||||
assert isinstance(runtime_event, RuntimeModelUpdatedEvent)
|
||||
assert runtime_event.model == "gpt-5.5"
|
||||
assert runtime_event.model_preset == "high"
|
||||
|
||||
goal_state_event = outbound_event_from_message(goal_state)
|
||||
assert isinstance(goal_state_event, GoalStateSyncEvent)
|
||||
assert goal_state_event.goal_state == {"active": True}
|
||||
|
||||
goal_status_event = outbound_event_from_message(goal_status)
|
||||
assert isinstance(goal_status_event, GoalStatusEvent)
|
||||
assert goal_status_event.status == "running"
|
||||
assert goal_status_event.started_at == 1.25
|
||||
|
||||
turn_end_event = outbound_event_from_message(turn_end)
|
||||
assert isinstance(turn_end_event, TurnEndEvent)
|
||||
assert turn_end_event.latency_ms == 42
|
||||
assert turn_end_event.goal_state == {"active": False}
|
||||
|
||||
session_updated_event = outbound_event_from_message(session_updated)
|
||||
assert isinstance(session_updated_event, SessionUpdatedEvent)
|
||||
assert session_updated_event.scope == "metadata"
|
||||
|
||||
|
||||
def test_legacy_metadata_numbers_ignore_bool_values() -> None:
|
||||
goal_status = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"_goal_status": True, "goal_status": "running", "started_at": True},
|
||||
)
|
||||
turn_end = OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-1",
|
||||
content="",
|
||||
metadata={"_turn_end": True, "latency_ms": True},
|
||||
)
|
||||
|
||||
goal_status_event = outbound_event_from_message(goal_status)
|
||||
assert isinstance(goal_status_event, GoalStatusEvent)
|
||||
assert goal_status_event.started_at is None
|
||||
|
||||
turn_end_event = outbound_event_from_message(turn_end)
|
||||
assert isinstance(turn_end_event, TurnEndEvent)
|
||||
assert turn_end_event.latency_ms is None
|
||||
|
||||
|
||||
def test_legacy_retry_wait_and_streamed_flags_create_runtime_events() -> None:
|
||||
retry = OutboundMessage(
|
||||
channel="cli",
|
||||
chat_id="direct",
|
||||
content="waiting",
|
||||
metadata={"_retry_wait": True},
|
||||
)
|
||||
streamed = OutboundMessage(
|
||||
channel="cli",
|
||||
chat_id="direct",
|
||||
content="final answer",
|
||||
metadata={"_streamed": True},
|
||||
)
|
||||
|
||||
retry_event = outbound_event_from_message(retry)
|
||||
assert isinstance(retry_event, RetryWaitEvent)
|
||||
assert retry_event.content == "waiting"
|
||||
assert isinstance(outbound_event_from_message(streamed), StreamedResponseEvent)
|
||||
|
||||
|
||||
def test_replace_outbound_event_keeps_routing_metadata() -> None:
|
||||
@@ -261,4 +97,4 @@ def test_streamed_response_event_keeps_final_content_outside_event_payload() ->
|
||||
)
|
||||
|
||||
assert msg.content == "final answer"
|
||||
assert isinstance(outbound_event_from_message(msg), StreamedResponseEvent)
|
||||
assert isinstance(msg.event, StreamedResponseEvent)
|
||||
@@ -1,8 +1,11 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import (
|
||||
RuntimeEventBus,
|
||||
RuntimeEventContext,
|
||||
RuntimeEventPublisher,
|
||||
RuntimeModelChanged,
|
||||
@@ -15,9 +18,101 @@ from nanobot.bus.runtime_events import (
|
||||
from nanobot.providers.base import LLMUsage
|
||||
|
||||
|
||||
async def test_local_state_subscriber_does_not_block_routed_delivery():
|
||||
bus = MessageBus()
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def observe(event):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
|
||||
bus.subscribe(observe, RuntimeModelChanged)
|
||||
dispatch = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), timeout=1)
|
||||
await asyncio.wait_for(
|
||||
bus.publish_event(ProgressEvent(content="working"), channel="cli", chat_id="other"),
|
||||
timeout=1,
|
||||
)
|
||||
message = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
|
||||
assert (message.chat_id, message.content) == ("other", "working")
|
||||
assert not dispatch.done()
|
||||
finally:
|
||||
release.set()
|
||||
await dispatch
|
||||
|
||||
|
||||
async def test_disconnect_skips_a_handler_in_an_existing_dispatch_snapshot():
|
||||
bus = MessageBus()
|
||||
seen = []
|
||||
|
||||
def first(event):
|
||||
disconnect()
|
||||
|
||||
bus.subscribe(first)
|
||||
disconnect = bus.subscribe(seen.append)
|
||||
await bus.publish(RuntimeModelChanged("model", None))
|
||||
disconnect()
|
||||
assert seen == []
|
||||
|
||||
|
||||
async def test_awaited_dispatch_preserves_order_and_propagates_cancellation():
|
||||
bus = MessageBus()
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
seen = []
|
||||
|
||||
async def slow(event):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
seen.append("first")
|
||||
|
||||
bus.subscribe(slow)
|
||||
bus.subscribe(lambda event: seen.append("second"))
|
||||
task = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))
|
||||
await entered.wait()
|
||||
assert not task.done()
|
||||
assert seen == []
|
||||
release.set()
|
||||
await task
|
||||
assert seen == ["first", "second"]
|
||||
|
||||
release.clear()
|
||||
entered.clear()
|
||||
task = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))
|
||||
await entered.wait()
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert seen == ["first", "second"]
|
||||
|
||||
|
||||
async def test_scheduled_dispatch_is_owned_and_can_be_drained():
|
||||
bus = MessageBus()
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
seen = []
|
||||
|
||||
async def slow(event):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
seen.append(event.model)
|
||||
|
||||
bus.subscribe(slow, RuntimeModelChanged)
|
||||
task = bus.publish_nowait(RuntimeModelChanged("model", None))
|
||||
assert task is not None
|
||||
assert not entered.is_set()
|
||||
await entered.wait()
|
||||
draining = asyncio.create_task(bus.drain())
|
||||
assert seen == []
|
||||
release.set()
|
||||
await draining
|
||||
assert task.done()
|
||||
assert seen == ["model"]
|
||||
await bus.drain()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_event_bus_filters_by_event_type() -> None:
|
||||
bus = RuntimeEventBus()
|
||||
bus = MessageBus()
|
||||
seen: list[str] = []
|
||||
|
||||
async def handle_run_status(event: TurnRunStatusChanged) -> None:
|
||||
@@ -42,7 +137,7 @@ async def test_runtime_event_bus_filters_by_event_type() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_event_bus_keeps_catch_all_subscription() -> None:
|
||||
bus = RuntimeEventBus()
|
||||
bus = MessageBus()
|
||||
seen: list[str] = []
|
||||
|
||||
def handle_any(event) -> None:
|
||||
@@ -57,7 +152,7 @@ async def test_runtime_event_bus_keeps_catch_all_subscription() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_event_publisher_builds_context_from_inbound_message() -> None:
|
||||
bus = RuntimeEventBus()
|
||||
bus = MessageBus()
|
||||
seen: list[object] = []
|
||||
publisher = RuntimeEventPublisher(bus)
|
||||
msg = InboundMessage(
|
||||
@@ -93,7 +188,7 @@ async def test_runtime_event_publisher_builds_context_from_inbound_message() ->
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> None:
|
||||
bus = RuntimeEventBus()
|
||||
bus = MessageBus()
|
||||
seen: list[object] = []
|
||||
publisher = RuntimeEventPublisher(bus)
|
||||
|
||||
@@ -134,7 +229,7 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_event_publisher_exposes_admitted_runtime() -> None:
|
||||
bus = RuntimeEventBus()
|
||||
bus = MessageBus()
|
||||
seen: list[object] = []
|
||||
publisher = RuntimeEventPublisher(bus)
|
||||
msg = InboundMessage(
|
||||
@@ -165,7 +260,7 @@ async def test_runtime_event_publisher_exposes_admitted_runtime() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_event_publisher_emits_persisted_turn_attributes() -> None:
|
||||
bus = RuntimeEventBus()
|
||||
bus = MessageBus()
|
||||
seen: list[object] = []
|
||||
publisher = RuntimeEventPublisher(bus)
|
||||
msg = InboundMessage(
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels import manager as manager_module
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def make_manager():
|
||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
||||
manager = ChannelManager(config, MessageBus())
|
||||
channel = MagicMock(spec=BaseChannel)
|
||||
channel.send = AsyncMock()
|
||||
channel.stop = AsyncMock()
|
||||
manager.channels["websocket"] = channel
|
||||
return manager, channel
|
||||
|
||||
|
||||
async def wait_until(predicate):
|
||||
async with asyncio.timeout(2):
|
||||
while not predicate():
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
async def test_ten_chats_keep_order_while_one_destination_is_blocked():
|
||||
manager, channel = make_manager()
|
||||
release = asyncio.Event()
|
||||
started = asyncio.Event()
|
||||
received = {str(i): [] for i in range(10)}
|
||||
|
||||
async def send(msg):
|
||||
if msg.chat_id == "0":
|
||||
started.set()
|
||||
await release.wait()
|
||||
received[msg.chat_id].append(msg.content)
|
||||
|
||||
channel.send.side_effect = send
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for content in ("first", "last"):
|
||||
for i in range(10):
|
||||
await manager.bus.publish_outbound(OutboundMessage("websocket", str(i), content))
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
await wait_until(lambda: all(len(received[str(i)]) == 2 for i in range(1, 10)))
|
||||
assert received["0"] == []
|
||||
assert all(received[str(i)] == ["first", "last"] for i in range(1, 10))
|
||||
release.set()
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert received["0"] == ["first", "last"]
|
||||
assert manager._outbound_tails == {}
|
||||
finally:
|
||||
await manager.stop_all()
|
||||
|
||||
|
||||
async def test_retry_does_not_block_other_chats(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.1,))
|
||||
manager, channel = make_manager()
|
||||
retry_started = asyncio.Event()
|
||||
healthy_sent = asyncio.Event()
|
||||
attempts = 0
|
||||
|
||||
async def send(msg):
|
||||
nonlocal attempts
|
||||
if msg.chat_id == "retry":
|
||||
attempts += 1
|
||||
if attempts == 1:
|
||||
retry_started.set()
|
||||
raise OSError("temporary failure")
|
||||
assert healthy_sent.is_set()
|
||||
else:
|
||||
healthy_sent.set()
|
||||
|
||||
channel.send.side_effect = send
|
||||
channel.should_retry_send_error.return_value = True
|
||||
try:
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "retry", "a"))
|
||||
await asyncio.wait_for(retry_started.wait(), 2)
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "healthy", "b"))
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert attempts == 2
|
||||
assert healthy_sent.is_set()
|
||||
finally:
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_pending_and_concurrent_sends_are_bounded_and_cancellable(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_PENDING_LIMIT", 4)
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 2)
|
||||
manager, channel = make_manager()
|
||||
blocked = asyncio.Event()
|
||||
active = 0
|
||||
peak = 0
|
||||
|
||||
async def send(msg):
|
||||
nonlocal active, peak
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
try:
|
||||
await blocked.wait()
|
||||
finally:
|
||||
active -= 1
|
||||
|
||||
channel.send.side_effect = send
|
||||
for i in range(4):
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", str(i), "a"))
|
||||
extra = asyncio.create_task(manager._queue_outbound(
|
||||
channel, OutboundMessage("websocket", "extra", "a"),
|
||||
))
|
||||
try:
|
||||
await wait_until(lambda: active == 2)
|
||||
assert not extra.done()
|
||||
assert len(manager._outbound_tasks) == 4
|
||||
extra.cancel()
|
||||
await asyncio.gather(extra, return_exceptions=True)
|
||||
await manager._cancel_outbound()
|
||||
assert peak == 2
|
||||
assert active == 0
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
# Cancellation returns admission permits, including tasks not yet sending.
|
||||
for i in range(4):
|
||||
await asyncio.wait_for(manager._queue_outbound(
|
||||
channel, OutboundMessage("websocket", str(i), "b"),
|
||||
), 2)
|
||||
finally:
|
||||
extra.cancel()
|
||||
await asyncio.gather(extra, return_exceptions=True)
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_channel_stop_cancels_only_its_sends_before_stopping_runtime():
|
||||
manager, channel = make_manager()
|
||||
active = asyncio.Event()
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def send(msg):
|
||||
active.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
async def stop():
|
||||
assert cancelled.is_set()
|
||||
|
||||
channel.send.side_effect = send
|
||||
channel.stop.side_effect = stop
|
||||
other = MagicMock(spec=BaseChannel)
|
||||
other.send = AsyncMock()
|
||||
manager.channels["other"] = other
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "a", "1"))
|
||||
await asyncio.wait_for(active.wait(), 2)
|
||||
await manager._stop_channel("websocket")
|
||||
await manager._queue_outbound(other, OutboundMessage("other", "b", "2"))
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
other.send.assert_awaited_once()
|
||||
assert not manager._outbound_tails
|
||||
|
||||
|
||||
async def test_dispatcher_shutdown_cleans_active_and_waiting_destination_tasks():
|
||||
manager, channel = make_manager()
|
||||
active = asyncio.Event()
|
||||
cancelled = asyncio.Event()
|
||||
|
||||
async def send(msg):
|
||||
active.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
channel.send.side_effect = send
|
||||
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for content in ("one", "two", "three"):
|
||||
await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", content))
|
||||
await asyncio.wait_for(active.wait(), 2)
|
||||
await wait_until(lambda: len(manager._outbound_tasks) == 3)
|
||||
finally:
|
||||
await manager.stop_all()
|
||||
assert cancelled.is_set()
|
||||
channel.send.assert_awaited_once()
|
||||
assert not manager._outbound_tasks
|
||||
assert not manager._outbound_tails
|
||||
@@ -11,7 +11,6 @@ from nanobot.bus.outbound_events import (
|
||||
RetryWaitEvent,
|
||||
StreamDeltaEvent,
|
||||
StreamEndEvent,
|
||||
outbound_event_from_message,
|
||||
outbound_message_for_event,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -120,13 +119,13 @@ class TestDeltaCoalescing:
|
||||
async def process_one():
|
||||
try:
|
||||
m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)
|
||||
event = outbound_event_from_message(m)
|
||||
event = m.event
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
m, pending = manager._coalesce_stream_deltas(m)
|
||||
for p in pending:
|
||||
await bus.publish_outbound(p)
|
||||
channel = manager.channels.get(m.channel)
|
||||
event = outbound_event_from_message(m)
|
||||
event = m.event
|
||||
if channel and isinstance(event, StreamDeltaEvent):
|
||||
await channel.send_delta(
|
||||
m.chat_id,
|
||||
@@ -274,13 +273,13 @@ class TestDispatchOutboundWithCoalescing:
|
||||
processed = []
|
||||
|
||||
msg = pending.pop(0) if pending else await bus.consume_outbound()
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
if isinstance(event, StreamDeltaEvent):
|
||||
msg, extra_pending = manager._coalesce_stream_deltas(msg)
|
||||
pending.extend(extra_pending)
|
||||
|
||||
channel = manager.channels.get(msg.channel)
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
if channel and isinstance(event, StreamDeltaEvent):
|
||||
await channel.send_delta(
|
||||
msg.chat_id,
|
||||
@@ -394,38 +393,6 @@ class TestProgressFiltering:
|
||||
assert send_mock.await_count == 1
|
||||
assert send_mock.await_args_list[0].args[0].content == "final answer"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_progress_flag_uses_runtime_progress_filter(self, manager, bus):
|
||||
manager.channels["mock"].send_progress = False
|
||||
await bus.publish_outbound(OutboundMessage(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
content="legacy progress-shaped message",
|
||||
metadata={"_progress": True},
|
||||
))
|
||||
await bus.publish_outbound(OutboundMessage(
|
||||
channel="mock",
|
||||
chat_id="chat1",
|
||||
content="processing sentinel",
|
||||
))
|
||||
|
||||
task = asyncio.create_task(manager._dispatch_outbound())
|
||||
try:
|
||||
for _ in range(30):
|
||||
if manager.channels["mock"]._send_mock.await_count >= 1:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
finally:
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
send_mock = manager.channels["mock"]._send_mock
|
||||
assert send_mock.await_count == 1
|
||||
assert send_mock.await_args.args[0].content == "processing sentinel"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_override_can_enable_tool_hints(self, manager, bus):
|
||||
manager.channels["mock"].send_tool_hints = True
|
||||
|
||||
@@ -23,7 +23,6 @@ import pytest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ProgressEvent,
|
||||
outbound_event_from_message,
|
||||
outbound_message_for_event,
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
@@ -282,7 +281,7 @@ async def _pump_one(manager: ChannelManager) -> None:
|
||||
"""Process currently queued messages through the reasoning dispatch branch."""
|
||||
|
||||
async def dispatch_one(msg: OutboundMessage) -> None:
|
||||
event = outbound_event_from_message(msg)
|
||||
event = msg.event
|
||||
if isinstance(event, ProgressEvent) and (
|
||||
event.reasoning_delta
|
||||
or event.reasoning_end
|
||||
|
||||
@@ -3534,6 +3534,8 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
|
||||
ch = _StartableChannel(fake_config, mgr.bus)
|
||||
mgr.channels = {"startable": ch}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
|
||||
# Create a real cancelled task
|
||||
async def dummy_task():
|
||||
@@ -3612,6 +3614,8 @@ async def test_stop_all_handles_channel_exception():
|
||||
mgr.bus = MessageBus()
|
||||
mgr.channels = {"stopfailing": _StopFailingChannel(fake_config, mgr.bus)}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
mgr._dispatch_task = None
|
||||
|
||||
# Should not raise even if channel.stop() raises
|
||||
@@ -3651,6 +3655,8 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
|
||||
"next": next_channel,
|
||||
}
|
||||
mgr._channel_tasks = {}
|
||||
mgr._outbound_tasks = {}
|
||||
mgr._stopping_channels = set()
|
||||
mgr._dispatch_task = None
|
||||
|
||||
await mgr.stop_all()
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.agent.memory import MemoryStore
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.cli import commands as cli_commands
|
||||
from nanobot.cli import gateway_runtime as cli_gateway_runtime
|
||||
from nanobot.cli import provider as provider_commands
|
||||
@@ -2871,7 +2872,7 @@ def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
|
||||
@@ -2938,7 +2939,7 @@ def test_gateway_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path:
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
cron_service=_StopCron,
|
||||
)
|
||||
@@ -3290,7 +3291,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
|
||||
config.agents.defaults.workspace = str(tmp_path / "config-workspace")
|
||||
config.agents.defaults.dream.enabled = False
|
||||
config.gateway.heartbeat.enabled = False
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
_patch_cli_command_runtime(
|
||||
@@ -3444,7 +3445,7 @@ def test_gateway_workspace_override_does_not_migrate_legacy_cron(
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
cron_service=_StopCron,
|
||||
get_cron_dir=lambda: legacy_dir,
|
||||
@@ -3483,7 +3484,7 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
cron_service=_StopCron,
|
||||
get_cron_dir=lambda: legacy_dir,
|
||||
@@ -3684,7 +3685,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
@@ -3895,7 +3896,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
@@ -4024,7 +4025,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
|
||||
_patch_cli_command_runtime(
|
||||
monkeypatch,
|
||||
config,
|
||||
message_bus=lambda: object(),
|
||||
message_bus=MessageBus,
|
||||
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
|
||||
|
||||
@@ -98,7 +98,7 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
|
||||
session.add_message("assistant", "Nothing to compact.", _command=True)
|
||||
loop.sessions.save(session)
|
||||
completions = []
|
||||
loop.runtime_events.subscribe(completions.append, TurnCompleted)
|
||||
loop.bus.subscribe(completions.append, TurnCompleted)
|
||||
|
||||
await loop._dispatch(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="test", content="/compact",
|
||||
@@ -155,7 +155,7 @@ async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loo
|
||||
metadata={"webui_turn_id": "queued-compact"},
|
||||
)
|
||||
completions = []
|
||||
loop.runtime_events.subscribe(completions.append, TurnCompleted)
|
||||
loop.bus.subscribe(completions.append, TurnCompleted)
|
||||
async with loop._get_session_lock(key):
|
||||
await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch)
|
||||
reply = await cmd_stop(CommandContext(
|
||||
@@ -181,7 +181,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
|
||||
|
||||
loop.provider.chat_with_retry.side_effect = wait_for_cancel
|
||||
completions = []
|
||||
loop.runtime_events.subscribe(completions.append, TurnCompleted)
|
||||
loop.bus.subscribe(completions.append, TurnCompleted)
|
||||
msg = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="test", content="/compact",
|
||||
metadata={"webui_turn_id": "compact-turn"},
|
||||
|
||||
@@ -517,11 +517,12 @@ async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:
|
||||
async def test_process_direct_accepts_media() -> None:
|
||||
"""process_direct should forward media paths to _process_message."""
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import RuntimeEventPublisher
|
||||
|
||||
loop = AgentLoop.__new__(AgentLoop)
|
||||
loop._session_locks = {}
|
||||
loop.runtime_event_publisher = RuntimeEventPublisher()
|
||||
loop.runtime_event_publisher = RuntimeEventPublisher(MessageBus())
|
||||
|
||||
captured_msg = None
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from nanobot.agent.tools.message import MessageTool
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import LLMResponse, ToolCallRequest
|
||||
from nanobot.utils.progress_events import output_events
|
||||
|
||||
|
||||
def _make_loop(tmp_path: Path) -> AgentLoop:
|
||||
@@ -181,7 +182,7 @@ class TestMessageToolSuppressLogic:
|
||||
result = await loop._run_agent_loop(
|
||||
TranscriptInput(history=[], current_message=None),
|
||||
runtime=loop.llm_runtime(),
|
||||
on_progress=on_progress,
|
||||
events=output_events(on_progress=on_progress),
|
||||
)
|
||||
|
||||
assert result.final_content == "Done"
|
||||
|
||||
@@ -7,8 +7,8 @@ import pytest
|
||||
from nanobot.agent.tools.context import RequestContext, request_context
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import GoalStatusEvent, TurnModelUpdatedEvent, UserInputEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import (
|
||||
RuntimeEventBus,
|
||||
RuntimeEventContext,
|
||||
TurnRuntimeAdmitted,
|
||||
UserInputAccepted,
|
||||
@@ -37,7 +37,7 @@ def _clear_turn_wall_clock() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_turn_run_status_running_records_wall_clock() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
msg = InboundMessage(
|
||||
channel="websocket",
|
||||
@@ -61,7 +61,7 @@ async def test_publish_turn_run_status_running_records_wall_clock() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_turn_run_status_reuses_explicit_wall_clock() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
msg = InboundMessage(channel="websocket", sender_id="u", chat_id="chat-a", content="hi")
|
||||
|
||||
@@ -75,7 +75,7 @@ async def test_publish_turn_run_status_reuses_explicit_wall_clock() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_turn_run_status_idle_retains_registry_until_delivery() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
msg = InboundMessage(
|
||||
channel="websocket",
|
||||
@@ -110,7 +110,7 @@ def test_clear_websocket_turn_only_clears_matching_owner() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ownerless_turns_receive_distinct_internal_owners() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
first = InboundMessage(
|
||||
channel="websocket",
|
||||
@@ -139,7 +139,7 @@ async def test_ownerless_turns_receive_distinct_internal_owners() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_turn_run_status_non_websocket_noop_registry() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
msg = InboundMessage(channel="telegram", sender_id="u", chat_id="1", content="hi")
|
||||
|
||||
@@ -151,7 +151,7 @@ async def test_publish_turn_run_status_non_websocket_noop_registry() -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
observer = wth.build_webui_fallback_model_observer(bus)
|
||||
|
||||
@@ -182,16 +182,38 @@ async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_coordinator_connections_end_on_scope_exit_and_can_reconnect(tmp_path):
|
||||
from nanobot.bus.runtime_events import RuntimeModelChanged
|
||||
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
coordinator = wth.WebuiTurnCoordinator(
|
||||
bus=bus, sessions=SessionManager(tmp_path),
|
||||
schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
event = RuntimeModelChanged("model", None)
|
||||
with pytest.raises(RuntimeError, match="shutdown"):
|
||||
with coordinator.connected():
|
||||
await bus.publish(event)
|
||||
raise RuntimeError("shutdown")
|
||||
bus.publish_outbound.assert_awaited_once()
|
||||
await bus.publish(event)
|
||||
bus.publish_outbound.assert_awaited_once()
|
||||
with coordinator.connected():
|
||||
bus.publish_nowait(event)
|
||||
await bus.drain()
|
||||
assert bus.publish_outbound.await_count == 2
|
||||
|
||||
|
||||
async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path) -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
runtime_events = RuntimeEventBus()
|
||||
coordinator = wth.WebuiTurnCoordinator(
|
||||
bus=bus,
|
||||
sessions=SessionManager(tmp_path),
|
||||
schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
coordinator.subscribe(runtime_events)
|
||||
coordinator.subscribe()
|
||||
runtime = LLMRuntime(
|
||||
provider=MagicMock(),
|
||||
model="openai-codex/gpt-5.6",
|
||||
@@ -200,7 +222,7 @@ async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path)
|
||||
model_preset="Codex",
|
||||
)
|
||||
|
||||
await runtime_events.publish(
|
||||
await bus.publish(
|
||||
TurnRuntimeAdmitted(
|
||||
context=RuntimeEventContext(
|
||||
channel="websocket",
|
||||
@@ -225,7 +247,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
tmp_path,
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
sessions = SessionManager(tmp_path)
|
||||
target_session = sessions.get_or_create("websocket:target")
|
||||
@@ -242,15 +264,14 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
}
|
||||
append_input = MagicMock()
|
||||
monkeypatch.setattr(wth, "append_session_message_input", append_input)
|
||||
runtime_events = RuntimeEventBus()
|
||||
coordinator = wth.WebuiTurnCoordinator(
|
||||
bus=bus,
|
||||
sessions=sessions,
|
||||
schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
coordinator.subscribe(runtime_events)
|
||||
coordinator.subscribe()
|
||||
|
||||
await runtime_events.publish(UserInputAccepted(
|
||||
await bus.publish(UserInputAccepted(
|
||||
context=RuntimeEventContext(
|
||||
channel="system",
|
||||
chat_id="websocket:target",
|
||||
@@ -274,7 +295,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_model_ignores_non_websocket_requests() -> None:
|
||||
bus = MagicMock()
|
||||
bus = MessageBus()
|
||||
bus.publish_outbound = AsyncMock()
|
||||
observer = wth.build_webui_fallback_model_observer(bus)
|
||||
|
||||
|
||||
@@ -76,6 +76,18 @@ def test_inspect_webui_bundle_detects_channel_owned_ui_source(tmp_path: Path) ->
|
||||
assert status.newest_source == channel_ui
|
||||
|
||||
|
||||
def test_shared_notifications_make_existing_bundle_stale(tmp_path: Path) -> None:
|
||||
source = tmp_path / "webui"
|
||||
dist = tmp_path / "nanobot/web/dist"
|
||||
shared = tmp_path / "packages/client-events/notifications.ts"
|
||||
_touch(source / "package.json", mtime_ns=10)
|
||||
_touch(dist / "index.html", mtime_ns=20)
|
||||
_touch(shared, mtime_ns=30)
|
||||
status = inspect_webui_bundle(source_dir=source, dist_dir=dist)
|
||||
assert status.needs_build
|
||||
assert status.newest_source == shared
|
||||
|
||||
|
||||
def test_channel_owned_ui_sources_are_included_in_distributions() -> None:
|
||||
project_root = Path(__file__).resolve().parents[2]
|
||||
pyproject = tomllib.loads((project_root / "pyproject.toml").read_text(encoding="utf-8"))
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.events import ContextCompactionEvent, RecoveryStateEvent
|
||||
from nanobot.webui.outbound_wire import project_notification
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_wire_fixtures_are_real_python_projections():
|
||||
fixtures = json.loads((ROOT / "packages/client-events/fixtures.json").read_text())
|
||||
for expected in fixtures:
|
||||
fields = {key: value for key, value in expected.items() if key not in {"event", "chat_id"}}
|
||||
event_type = (
|
||||
ContextCompactionEvent if expected["event"] == "context_compaction" else RecoveryStateEvent
|
||||
)
|
||||
projection = project_notification(expected["chat_id"], event_type(**fields))
|
||||
assert projection is not None
|
||||
assert projection.payload == expected
|
||||
|
||||
|
||||
def test_tui_source_archive_preserves_shared_module_import_path():
|
||||
spec = importlib.util.spec_from_file_location("package_release", ROOT / "tui/scripts/package-release.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
with tarfile.open(fileobj=io.BytesIO(module._source_archive(ROOT / "tui"))) as archive:
|
||||
names = set(archive.getnames())
|
||||
assert "nanobot-tui-source/tui/src/protocol.ts" in names
|
||||
assert "nanobot-tui-source/packages/client-events/notifications.ts" in names
|
||||
assert "nanobot-tui-source/tui/bun.lock" in names
|
||||
assert "nanobot-tui-source/LICENSE" in names
|
||||
+2
-2
@@ -8,7 +8,7 @@ LGPL 2.1 license texts.
|
||||
|
||||
Corresponding upstream source:
|
||||
|
||||
- nanobot TUI: the `tui/` directory in the GitHub release tag that contains this archive
|
||||
- nanobot TUI: the `tui/` and `packages/client-events/` directories in the GitHub release tag that contains this archive
|
||||
- Bun 1.3.13 (`bf2e2cecf27e800962b1e7f03d66278f9d5d2e79`):
|
||||
<https://github.com/oven-sh/bun/tree/bun-v1.3.13>
|
||||
- Bun's patched WebKit (`4d5e75ebd84a14edbc7ae264245dcd77fe597c10`):
|
||||
@@ -21,7 +21,7 @@ build instructions. Then unpack
|
||||
`nanobot-tui-source.tar.gz` from the release archive and run the resulting Bun executable:
|
||||
|
||||
```bash
|
||||
cd nanobot-tui-source
|
||||
cd nanobot-tui-source/tui
|
||||
/path/to/modified/bun install --frozen-lockfile
|
||||
/path/to/modified/bun run build -- <target>
|
||||
```
|
||||
|
||||
@@ -43,7 +43,10 @@ def _source_archive(root: Path) -> bytes:
|
||||
path = root / relative
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(path)
|
||||
archive.add(path, arcname=Path("nanobot-tui-source") / relative)
|
||||
archive.add(path, arcname=Path("nanobot-tui-source/tui") / relative)
|
||||
archive.add(root.parent / "packages/client-events",
|
||||
arcname="nanobot-tui-source/packages/client-events")
|
||||
archive.add(root.parent / "LICENSE", arcname="nanobot-tui-source/LICENSE")
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
|
||||
+6
-42
@@ -1,3 +1,7 @@
|
||||
import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications"
|
||||
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications"
|
||||
export type { ContextCompaction, RecoveryState, RecoveryStatus } from "../../packages/client-events/notifications"
|
||||
|
||||
export type ConnectionStatus =
|
||||
| "starting"
|
||||
| "connecting"
|
||||
@@ -76,21 +80,6 @@ export interface RuntimeControls {
|
||||
canUseFullAccess: boolean
|
||||
}
|
||||
|
||||
export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed"
|
||||
|
||||
export interface RecoveryState {
|
||||
status: RecoveryStatus
|
||||
recovery_id: string
|
||||
reason?: string
|
||||
attempts?: number
|
||||
can_continue?: boolean
|
||||
}
|
||||
|
||||
export interface ContextCompaction {
|
||||
id: string
|
||||
phase: "started" | "succeeded" | "failed" | "cancelled"
|
||||
}
|
||||
|
||||
export type InboundEvent =
|
||||
| { event: "ready"; chat_id: string; client_id: string }
|
||||
| {
|
||||
@@ -156,13 +145,7 @@ export type InboundEvent =
|
||||
turn_id?: string
|
||||
}
|
||||
| { event: "goal_state"; chat_id: string; goal_state: Record<string, unknown> }
|
||||
| ({ event: "recovery_state"; chat_id: string } & RecoveryState)
|
||||
| {
|
||||
event: "context_compaction"
|
||||
chat_id: string
|
||||
compaction_id: string
|
||||
phase: ContextCompaction["phase"]
|
||||
}
|
||||
| NotificationEvent
|
||||
| {
|
||||
event: "session_updated"
|
||||
chat_id: string
|
||||
@@ -382,10 +365,6 @@ function optional(value: unknown, type: "boolean" | "number" | "string"): boolea
|
||||
return value === undefined || typeof value === type
|
||||
}
|
||||
|
||||
function isCompactionPhase(value: unknown): value is ContextCompaction["phase"] {
|
||||
return value === "started" || value === "succeeded" || value === "failed" || value === "cancelled"
|
||||
}
|
||||
|
||||
function isToolEvent(value: unknown): value is ToolProgressEvent {
|
||||
if (!isRecord(value)) return false
|
||||
return optional(value.version, "number")
|
||||
@@ -456,15 +435,6 @@ function isWorkspaceScope(value: unknown): value is WorkspaceScopePayload {
|
||||
&& optional(value.restrict_to_workspace, "boolean")
|
||||
}
|
||||
|
||||
function isRecoveryState(value: unknown): value is RecoveryState {
|
||||
return isRecord(value)
|
||||
&& ["resuming", "awaiting_user", "recovered", "failed"].includes(String(value.status))
|
||||
&& typeof value.recovery_id === "string"
|
||||
&& optional(value.reason, "string")
|
||||
&& optional(value.attempts, "number")
|
||||
&& optional(value.can_continue, "boolean")
|
||||
}
|
||||
|
||||
interface WebUIResponseEvent {
|
||||
event: "webui_response"
|
||||
request_id: string
|
||||
@@ -560,13 +530,7 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {
|
||||
) return null
|
||||
if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null
|
||||
if (name === "goal_state" && !isRecord(record.goal_state)) return null
|
||||
if (name === "recovery_state" && !isRecoveryState(record)) return null
|
||||
if (
|
||||
name === "context_compaction"
|
||||
&& (typeof record.compaction_id !== "string"
|
||||
|| !record.compaction_id
|
||||
|| !isCompactionPhase(record.phase))
|
||||
) return null
|
||||
if (decodeNotification(record) === null) return null
|
||||
if (
|
||||
name === "session_updated"
|
||||
&& (!optional(record.scope, "string")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { acceptsCompactionPhase } from "../../packages/client-events/notifications"
|
||||
import {
|
||||
BoxRenderable,
|
||||
CodeRenderable,
|
||||
@@ -331,7 +332,7 @@ export class Transcript {
|
||||
compaction(compaction: ContextCompaction, index?: number): boolean {
|
||||
let entry = this.compactions.get(compaction.id)
|
||||
// Hydration can replay a terminal state before an already queued start event.
|
||||
if (entry && (entry.phase !== "started" || entry.phase === compaction.phase)) return false
|
||||
if (!acceptsCompactionPhase(entry?.phase, compaction.phase)) return false
|
||||
const added = !entry
|
||||
if (index === undefined) {
|
||||
this.noteOutput()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -782,6 +783,7 @@ export function useNanobotStream(
|
||||
setMessages((prev) => {
|
||||
const id = `compaction-${ev.compaction_id}`;
|
||||
const existing = prev.findIndex((message) => message.id === id);
|
||||
if (!acceptsCompactionPhase(prev[existing]?.compaction?.phase, ev.phase)) return prev;
|
||||
const next = {
|
||||
id,
|
||||
role: "assistant" as const,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { decodeNotification } from "../../../packages/client-events/notifications";
|
||||
import type {
|
||||
ConnectionStatus,
|
||||
InboundEvent,
|
||||
@@ -1072,6 +1073,7 @@ export class NanobotClient {
|
||||
let parsed: InboundEvent;
|
||||
try {
|
||||
parsed = JSON.parse(typeof ev.data === "string" ? ev.data : "") as InboundEvent;
|
||||
if (decodeNotification(parsed) === null) return;
|
||||
} catch {
|
||||
if (wsInboundDebugEnabled()) {
|
||||
const raw = typeof ev.data === "string" ? ev.data : String(ev.data);
|
||||
|
||||
+5
-23
@@ -1,12 +1,13 @@
|
||||
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../../packages/client-events/notifications";
|
||||
export type { RecoveryState, RecoveryStatus } from "../../../packages/client-events/notifications";
|
||||
|
||||
type Role = "user" | "assistant" | "tool" | "system";
|
||||
|
||||
/** "trace" rows are intermediate agent breadcrumbs (tool-call hints,
|
||||
* progress pings) that should not be rendered as conversational replies. */
|
||||
type MessageKind = "message" | "trace" | "compaction";
|
||||
|
||||
export interface UIContextCompaction {
|
||||
id: string;
|
||||
phase: "started" | "succeeded" | "failed" | "cancelled";
|
||||
export interface UIContextCompaction extends ContextCompaction {
|
||||
/** Live wire transitions announce; hydrated transcript rows stay silent. */
|
||||
announce?: boolean;
|
||||
}
|
||||
@@ -63,16 +64,6 @@ export interface TurnUsage {
|
||||
|
||||
export type RoundUsage = TurnUsage;
|
||||
|
||||
export type RecoveryStatus = "resuming" | "awaiting_user" | "recovered" | "failed";
|
||||
|
||||
export interface RecoveryState {
|
||||
status: RecoveryStatus;
|
||||
recovery_id: string;
|
||||
reason?: string;
|
||||
attempts?: number;
|
||||
can_continue?: boolean;
|
||||
}
|
||||
|
||||
export interface UIMessage {
|
||||
id: string;
|
||||
role: Role;
|
||||
@@ -1373,16 +1364,7 @@ export type InboundEvent =
|
||||
/** Optional structured payload on progress frames (channel-specific). */
|
||||
agent_ui?: AgentUIBlob;
|
||||
} & InboundTurnMetadata)
|
||||
| ({
|
||||
event: "recovery_state";
|
||||
chat_id: string;
|
||||
} & RecoveryState)
|
||||
| ({
|
||||
event: "context_compaction";
|
||||
chat_id: string;
|
||||
compaction_id: string;
|
||||
phase: UIContextCompaction["phase"];
|
||||
} & InboundTurnMetadata)
|
||||
| (NotificationEvent & InboundTurnMetadata)
|
||||
| ({
|
||||
event: "file_edit";
|
||||
chat_id: string;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import fixtures from "../../../packages/client-events/fixtures.json";
|
||||
import { acceptsCompactionPhase, decodeNotification } from "../../../packages/client-events/notifications";
|
||||
|
||||
describe("shared notification contract", () => {
|
||||
it.each(fixtures)("accepts the Python wire fixture %#", (event) => {
|
||||
expect(decodeNotification(event)).toEqual(event);
|
||||
expect(decodeNotification({ ...event, turn_id: "turn" })).toMatchObject(event);
|
||||
expect(decodeNotification({ ...event, chat_id: 42 })).toBeNull();
|
||||
expect(decodeNotification({ ...event, turn_id: 42 })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not mistake other event families for invalid notifications", () => {
|
||||
expect(decodeNotification({ event: "delta", text: "hello" })).toBeUndefined();
|
||||
expect(decodeNotification({ ...fixtures[0], phase: "unknown" })).toBeNull();
|
||||
expect(decodeNotification({ ...fixtures[0], compaction_id: "" })).toBeNull();
|
||||
});
|
||||
|
||||
it("allows one terminal transition, including terminal-first hydration", () => {
|
||||
for (const phase of ["started", "succeeded", "failed", "cancelled"] as const) {
|
||||
expect(acceptsCompactionPhase(undefined, phase)).toBe(true);
|
||||
expect(acceptsCompactionPhase("started", phase)).toBe(phase !== "started");
|
||||
for (const terminal of ["succeeded", "failed", "cancelled"] as const) {
|
||||
expect(acceptsCompactionPhase(terminal, phase)).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -245,6 +245,19 @@ describe("useNanobotStream", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a hydrated terminal compaction when a queued start arrives", () => {
|
||||
const fake = fakeClient();
|
||||
const initial = [{ id: "compaction-c1", role: "assistant" as const, content: "",
|
||||
kind: "compaction" as const, createdAt: 123,
|
||||
compaction: { id: "c1", phase: "succeeded" as const } }];
|
||||
const { result } = renderHook(() => useNanobotStream("chat", initial), {
|
||||
wrapper: wrap(fake.client),
|
||||
});
|
||||
act(() => fake.emit("chat", { event: "context_compaction", chat_id: "chat",
|
||||
compaction_id: "c1", phase: "started" }));
|
||||
expect(result.current.messages).toEqual(initial);
|
||||
});
|
||||
|
||||
it("batches answer deltas into one animation-frame update", async () => {
|
||||
const fake = fakeClient();
|
||||
const requestFrame = vi.spyOn(window, "requestAnimationFrame");
|
||||
|
||||
Reference in new issue
Block a user