Files
nanobot/nanobot/events.py
T
chengyongru 394a78e82d fix(sessions): preserve cross-session input ownership and history (#6613)
* fix(webui): reconcile cross-session history by message ID

* fix(sessions): preserve target authority and input ownership

Resolve cross-session follow-ups through the target route, carry stable input IDs through admission and recovery, and associate live and replayed answers with the inputs actually consumed.

Keep ordinary input scope isolation and omit historical anomaly repair. Resolves NAN-430.

* fix(sessions): complete input identity integration across boundaries

Carry input identity explicitly in projected input events, keep runner annotations out of public history, and reuse the canonical WebUI session parser during recovery.

Type validated recovery metadata and align existing channel and subagent regressions with explicit response ownership. All nine failed compatibility cases and adjacent recovery coverage pass in a focused 58-test run.

* fix(sessions): unify input recording and block remote commands

* fix(webui): keep input ownership checks page-bounded

Look up referenced inputs through the existing identity index before invoking transcript backfill. Complete pages no longer scan the full prompt history, including answers whose inputs live on earlier pages.

Cover cold-cache pagination and cross-turn ownership in existing regressions. Focused pagination, replay and follow-up recovery checks: 88 passed.

* fix(webui): preserve response ownership during history replay

* fix: resolve strict typing in response replay

* fix: preserve continuation ownership during recovery

* test: diagnose stuck gateway asyncio shutdown

* test: retain gateway thread stack diagnostics

* test(webui): stabilize native autoscroll browser setup
2026-11-11 10:46:44 +08:00

126 lines
3.6 KiB
Python

from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Literal
from loguru import logger
from nanobot.llm_usage.types import LLMUsage
class AgentEvent:
"""A typed event; only explicitly projected events cross a client boundary."""
@dataclass(frozen=True)
class ModelRequestEvent(AgentEvent):
"""Bounded snapshot of logical calls (provider retries stay inside a call)."""
request_id: str
run_id: str
sequence: int
phase: Literal["started", "completed", "failed", "cancelled"]
usage: LLMUsage | None = None
round_usages: tuple[LLMUsage, ...] = ()
context_window_tokens: int | None = None
request_usage: LLMUsage | None = None
@dataclass(frozen=True)
class ResponseInputsEvent(AgentEvent):
"""Identify the inputs being answered by the next model request."""
input_ids: tuple[str, ...]
@dataclass(frozen=True)
class ResponseSource:
"""Display-safe identity captured at the actual provider invocation."""
provider: str
model: str
preset: str
fallback: bool = False
@dataclass(frozen=True)
class ResponseSourceEvent(AgentEvent):
"""Set the source of subsequent answer text in this operation only."""
source: ResponseSource | None
# Completed provider text authorizes attribution of a non-streamed reply;
# synthetic runner/command messages must not inherit the last model's name.
content: str | None = None
CompactionReason = Literal["idle", "context_pressure", "manual", "provider_native"]
@dataclass(frozen=True)
class ContextCompactionEvent(AgentEvent):
compaction_id: str
phase: Literal["started", "succeeded", "failed", "cancelled"]
# Request a chat notice (e.g. /compact), not event delivery or persistence.
# Interactive clients still consume every phase when this is false.
notify: bool = False
reason: CompactionReason | None = None
@dataclass(frozen=True)
class RetryWaitEvent(AgentEvent):
content: str = ""
@dataclass(frozen=True)
class RetryStatusEvent(AgentEvent):
"""Sanitized retry lifecycle for one model request chain."""
state: Literal["waiting", "recovered", "cleared", "exhausted"]
attempt: int
max_attempts: int | None
error_kind: str
next_retry_at: float | None = None
@dataclass(frozen=True)
class RecoveryStateEvent(AgentEvent):
status: str
recovery_id: str
reason: str | None = None
attempts: int = 0
can_continue: bool | None = None
failure_error_kind: str | None = None
reply_preserved: 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()