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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user