notification.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """
  2. agentpaas.services.notification — Multi-channel notification service
  3. Channels: terminal, macos, webhook, email, wechat
  4. """
  5. from __future__ import annotations
  6. import json
  7. import os
  8. import subprocess
  9. import time
  10. from dataclasses import dataclass, asdict
  11. from typing import Any, Dict, List, Optional
  12. @dataclass
  13. class Notification:
  14. message: str
  15. channel: str = "terminal"
  16. priority: str = "normal" # low / normal / high / urgent
  17. title: str = ""
  18. source: str = ""
  19. timestamp: float = 0
  20. def __post_init__(self):
  21. if self.timestamp == 0:
  22. self.timestamp = time.time()
  23. class NotificationService:
  24. """Multi-channel notification dispatcher."""
  25. def __init__(self):
  26. self._history: List[Notification] = []
  27. self._max_history = 100
  28. def send(self, message: str, channel: str = "terminal",
  29. priority: str = "normal", title: str = "", source: str = "") -> str:
  30. notif = Notification(
  31. message=message, channel=channel, priority=priority,
  32. title=title or "lambda 🐑", source=source,
  33. )
  34. self._history.append(notif)
  35. if len(self._history) > self._max_history:
  36. self._history = self._history[-self._max_history:]
  37. if channel == "terminal":
  38. return self._send_terminal(notif)
  39. elif channel == "macos":
  40. return self._send_macos(notif)
  41. elif channel == "webhook":
  42. return self._send_webhook(notif)
  43. else:
  44. return self._send_terminal(notif) # fallback
  45. def _send_terminal(self, n: Notification) -> str:
  46. icon = {"low": "ℹ️", "normal": "📌", "high": "⚠️", "urgent": "🚨"}.get(n.priority, "📌")
  47. print(f"\n{icon} [{n.title}] {n.message}")
  48. return f"[OK] Terminal notification sent"
  49. def _send_macos(self, n: Notification) -> str:
  50. try:
  51. script = (
  52. f'display notification "{n.message}" '
  53. f'with title "{n.title}" '
  54. f'sound name "default"'
  55. )
  56. subprocess.run(["osascript", "-e", script], capture_output=True, timeout=5)
  57. return f"[OK] macOS notification sent"
  58. except Exception as e:
  59. # Fallback to terminal
  60. self._send_terminal(n)
  61. return f"[FALLBACK] macOS failed ({e}), sent to terminal"
  62. def _send_webhook(self, n: Notification) -> str:
  63. url = os.environ.get("LAMBDAGENT_WEBHOOK_URL", "")
  64. if not url:
  65. self._send_terminal(n)
  66. return "[FALLBACK] No webhook URL configured, sent to terminal"
  67. try:
  68. import urllib.request
  69. data = json.dumps(asdict(n)).encode()
  70. req = urllib.request.Request(url, data=data,
  71. headers={"Content-Type": "application/json"})
  72. urllib.request.urlopen(req, timeout=10)
  73. return f"[OK] Webhook notification sent to {url}"
  74. except Exception as e:
  75. return f"[ERROR] Webhook failed: {e}"
  76. def history(self, limit: int = 20) -> List[Notification]:
  77. return self._history[-limit:]
  78. # ════════════════════════════════════════════════════════════
  79. # Agent-side tool function
  80. # ════════════════════════════════════════════════════════════
  81. _default_service = None
  82. def _get_service() -> NotificationService:
  83. global _default_service
  84. if _default_service is None:
  85. _default_service = NotificationService()
  86. return _default_service
  87. def notify(input_val: Any) -> str:
  88. """Send notification. Input: {message, channel?, priority?, title?}"""
  89. params = _parse(input_val)
  90. message = params.get("message", "")
  91. if not message:
  92. return "[ERROR] message is required"
  93. return _get_service().send(
  94. message=message,
  95. channel=params.get("channel", "terminal"),
  96. priority=params.get("priority", "normal"),
  97. title=params.get("title", "lambda 🐑"),
  98. source=params.get("source", "agent"),
  99. )
  100. def _parse(input_val: Any) -> dict:
  101. if isinstance(input_val, dict):
  102. return input_val
  103. if isinstance(input_val, str):
  104. try:
  105. return json.loads(input_val)
  106. except (json.JSONDecodeError, ValueError):
  107. return {"message": input_val}
  108. return {}