|
| 1 | +import typing as t |
| 2 | +from abc import ABC, abstractmethod |
| 3 | + |
| 4 | +from loguru import logger |
| 5 | + |
| 6 | +if t.TYPE_CHECKING: |
| 7 | + import httpx |
| 8 | + |
| 9 | + from dreadnode.agent.events import AgentEvent |
| 10 | + |
| 11 | + |
| 12 | +class NotificationBackend(ABC): |
| 13 | + @abstractmethod |
| 14 | + async def send(self, event: "AgentEvent", message: str) -> None: |
| 15 | + """Send a notification for the given event.""" |
| 16 | + |
| 17 | + |
| 18 | +class LogNotificationBackend(NotificationBackend): |
| 19 | + async def send(self, event: "AgentEvent", message: str) -> None: |
| 20 | + logger.info(f"[{event.agent.name}] {message}") |
| 21 | + |
| 22 | + |
| 23 | +class TerminalNotificationBackend(NotificationBackend): |
| 24 | + async def send(self, event: "AgentEvent", message: str) -> None: |
| 25 | + import sys |
| 26 | + |
| 27 | + print(f"[{event.agent.name}] {message}", file=sys.stderr) |
| 28 | + |
| 29 | + |
| 30 | +class WebhookNotificationBackend(NotificationBackend): |
| 31 | + def __init__(self, url: str, headers: dict[str, str] | None = None, timeout: float = 5.0): |
| 32 | + self.url = url |
| 33 | + self.headers = headers or {} |
| 34 | + self.timeout = timeout |
| 35 | + self._client: httpx.AsyncClient | None = None |
| 36 | + |
| 37 | + async def __aenter__(self) -> "WebhookNotificationBackend": |
| 38 | + import httpx |
| 39 | + |
| 40 | + self._client = httpx.AsyncClient(timeout=self.timeout) |
| 41 | + return self |
| 42 | + |
| 43 | + async def __aexit__(self, *args: object) -> None: |
| 44 | + if self._client: |
| 45 | + await self._client.aclose() |
| 46 | + |
| 47 | + async def send(self, event: "AgentEvent", message: str) -> None: |
| 48 | + import httpx |
| 49 | + |
| 50 | + if not self._client: |
| 51 | + self._client = httpx.AsyncClient(timeout=self.timeout) |
| 52 | + |
| 53 | + payload = self._build_payload(event, message) |
| 54 | + await self._client.post(self.url, json=payload, headers=self.headers) |
| 55 | + |
| 56 | + def _build_payload(self, event: "AgentEvent", message: str) -> dict[str, str]: |
| 57 | + """Override this to customize webhook payload.""" |
| 58 | + return { |
| 59 | + "agent": event.agent.name, |
| 60 | + "event": event.__class__.__name__, |
| 61 | + "message": message, |
| 62 | + "timestamp": event.timestamp.isoformat(), |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | +def notify( |
| 67 | + event_type: "type[AgentEvent] | t.Callable[[AgentEvent], bool]", |
| 68 | + message: str | t.Callable[["AgentEvent"], str] | None = None, |
| 69 | + backend: NotificationBackend | None = None, |
| 70 | +) -> t.Callable[["AgentEvent"], t.Awaitable[None]]: |
| 71 | + """ |
| 72 | + Create a notification hook that sends notifications when events occur. |
| 73 | +
|
| 74 | + Unlike other hooks, notification hooks don't affect agent execution - they return |
| 75 | + None (no reaction) and run asynchronously to deliver notifications. |
| 76 | +
|
| 77 | + Args: |
| 78 | + event_type: Event type to trigger on, or predicate function |
| 79 | + message: Static message or callable that generates message from event. |
| 80 | + If None, uses event.format_notification() |
| 81 | + backend: Notification backend (defaults to terminal output) |
| 82 | +
|
| 83 | + Returns: |
| 84 | + Hook that sends notifications |
| 85 | +
|
| 86 | + Example: |
| 87 | + ```python |
| 88 | + from dreadnode.agent import Agent |
| 89 | + from dreadnode.agent.events import ToolStart |
| 90 | + from dreadnode.agent.hooks.notification import notify |
| 91 | +
|
| 92 | + agent = Agent( |
| 93 | + name="analyzer", |
| 94 | + hooks=[ |
| 95 | + notify(ToolStart), # Uses default formatting |
| 96 | + notify( |
| 97 | + ToolStart, |
| 98 | + lambda e: f"Starting tool: {e.tool_name}", |
| 99 | + ), |
| 100 | + ], |
| 101 | + ) |
| 102 | + ``` |
| 103 | + """ |
| 104 | + notification_backend = backend or TerminalNotificationBackend() |
| 105 | + |
| 106 | + async def notification_hook(event: "AgentEvent") -> None: |
| 107 | + should_notify = False |
| 108 | + |
| 109 | + if isinstance(event_type, type): |
| 110 | + should_notify = isinstance(event, event_type) |
| 111 | + elif callable(event_type): |
| 112 | + should_notify = event_type(event) |
| 113 | + |
| 114 | + if not should_notify: |
| 115 | + return |
| 116 | + |
| 117 | + # Use custom message if provided, otherwise delegate to event |
| 118 | + if message is None: |
| 119 | + msg = event.format_notification() |
| 120 | + else: |
| 121 | + msg = message(event) if callable(message) else message |
| 122 | + |
| 123 | + try: |
| 124 | + await notification_backend.send(event, msg) |
| 125 | + except Exception: # noqa: BLE001 |
| 126 | + logger.exception("Notification hook failed") |
| 127 | + |
| 128 | + return |
| 129 | + |
| 130 | + return notification_hook |
0 commit comments