"""Event stream service for AstrBot-mounted routes.""" from __future__ import annotations from typing import Any from core.event_bus import Event, EventBus from core.webhook import WebhookEvent, event_from_bus, to_sse DEFAULT_EVENT_BUS = EventBus(history_limit=500) def get_default_event_bus() -> EventBus: return DEFAULT_EVENT_BUS class EventStreamService: def __init__(self, event_bus: EventBus | None = None): self.event_bus = event_bus or DEFAULT_EVENT_BUS def recent_events(self, *, event_type: str | None = None, limit: int = 50) -> dict[str, Any]: events = self.event_bus.history(event_type) normalized_limit = min(max(int(limit or 50), 1), 200) selected = events[-normalized_limit:] webhook_events = [_event_to_webhook(event) for event in selected] return { "content_type": "text/event-stream", "events": [event.to_dict() for event in webhook_events], "body": "".join(to_sse(event) for event in webhook_events), "count": len(webhook_events), } def _event_to_webhook(event: Event) -> WebhookEvent: webhook_event = event_from_bus(event.event_type, event.payload) return WebhookEvent( event_type=webhook_event.event_type, data=webhook_event.data, event_id=event.event_id, created_at=event.created_at, )