agent-alerts 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_alerts-0.1.0.dist-info/METADATA +161 -0
- agent_alerts-0.1.0.dist-info/RECORD +23 -0
- agent_alerts-0.1.0.dist-info/WHEEL +5 -0
- agent_alerts-0.1.0.dist-info/entry_points.txt +2 -0
- agent_alerts-0.1.0.dist-info/licenses/LICENSE +21 -0
- agent_alerts-0.1.0.dist-info/top_level.txt +1 -0
- alerts/__init__.py +110 -0
- alerts/channels/__init__.py +14 -0
- alerts/channels/agent.py +178 -0
- alerts/channels/base.py +16 -0
- alerts/channels/email.py +85 -0
- alerts/channels/imessage.py +119 -0
- alerts/channels/telegram.py +62 -0
- alerts/config.py +203 -0
- alerts/evaluator.py +205 -0
- alerts/feedback.py +39 -0
- alerts/gateway_client.py +221 -0
- alerts/mcp_server.py +61 -0
- alerts/models.py +67 -0
- alerts/prompt_builder.py +60 -0
- alerts/quiet_hours.py +61 -0
- alerts/rate_limiter.py +36 -0
- alerts/router.py +121 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-alerts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Structured alert routing to humans and AI agents
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/henrychien/agent-alerts
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: PyYAML>=6.0
|
|
11
|
+
Provides-Extra: mcp
|
|
12
|
+
Requires-Dist: fastmcp>=0.1.0; extra == "mcp"
|
|
13
|
+
Provides-Extra: agent
|
|
14
|
+
Requires-Dist: httpx>=0.27.0; extra == "agent"
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest; extra == "dev"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# agent-alerts
|
|
20
|
+
|
|
21
|
+
Structured alert routing to humans and AI agents.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install agent-alerts
|
|
27
|
+
pip install "agent-alerts[mcp]"
|
|
28
|
+
pip install "agent-alerts[agent]"
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Python imports stay under `alerts`.
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
Send a simple alert directly to Telegram:
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from alerts import send
|
|
39
|
+
|
|
40
|
+
send("Screen complete: 4 names passed", channel="telegram")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
That reads `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` from your environment unless you pass `token=` and `chat_id=` explicitly.
|
|
44
|
+
|
|
45
|
+
Use `AlertRouter` for structured routing, thresholds, quiet hours, and agent follow-up:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from alerts import Alert, AlertCategory, AlertLevel, AlertRouter
|
|
49
|
+
|
|
50
|
+
router = AlertRouter(config_path="alerting.yaml")
|
|
51
|
+
|
|
52
|
+
result = router.send(
|
|
53
|
+
Alert(
|
|
54
|
+
title="Estimate revisions turning negative",
|
|
55
|
+
body="NVDA revisions rolled over after guidance.",
|
|
56
|
+
level=AlertLevel.HIGH,
|
|
57
|
+
category=AlertCategory.SIGNAL,
|
|
58
|
+
source="portfolio-system",
|
|
59
|
+
source_type="estimate_revisions",
|
|
60
|
+
metadata={"passed_count": 1},
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
print(result.delivered_channels)
|
|
65
|
+
print(result.agent_dispatched)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Channels
|
|
69
|
+
|
|
70
|
+
| Channel | Purpose | Required config |
|
|
71
|
+
| --- | --- | --- |
|
|
72
|
+
| `telegram` | Fast human notification | `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` |
|
|
73
|
+
| `imessage` | Local macOS delivery | `IMESSAGE_TARGET` or `channels.imessage.recipient`; optional `backend`, `service` |
|
|
74
|
+
| `email` | SMTP delivery | `smtp_host`, `smtp_port`, `from`, `to` plus `EMAIL_USERNAME`, `EMAIL_PASSWORD` |
|
|
75
|
+
| `agent` | Background agent analysis with human feedback | `gateway_url`, `gateway_api_key_env`; optional `model`, `feedback_channel` |
|
|
76
|
+
|
|
77
|
+
## Router Config
|
|
78
|
+
|
|
79
|
+
Example `alerting.yaml`:
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
schema_version: 2
|
|
83
|
+
on_config_error: use_last_good
|
|
84
|
+
|
|
85
|
+
channels:
|
|
86
|
+
telegram:
|
|
87
|
+
enabled: true
|
|
88
|
+
imessage:
|
|
89
|
+
enabled: false
|
|
90
|
+
recipient: "+15555551212"
|
|
91
|
+
backend: applescript
|
|
92
|
+
email:
|
|
93
|
+
enabled: false
|
|
94
|
+
smtp_host: smtp.gmail.com
|
|
95
|
+
smtp_port: 587
|
|
96
|
+
from: alerts@example.com
|
|
97
|
+
to:
|
|
98
|
+
- user@example.com
|
|
99
|
+
agent:
|
|
100
|
+
enabled: true
|
|
101
|
+
gateway_url: "http://127.0.0.1:8002"
|
|
102
|
+
gateway_api_key_env: "ALERTS_GATEWAY_API_KEY"
|
|
103
|
+
model: "claude-sonnet-4-6"
|
|
104
|
+
feedback_channel: telegram
|
|
105
|
+
|
|
106
|
+
routing:
|
|
107
|
+
critical: [telegram, agent]
|
|
108
|
+
high: [telegram, agent]
|
|
109
|
+
normal: [telegram]
|
|
110
|
+
low: []
|
|
111
|
+
by_category:
|
|
112
|
+
signal:
|
|
113
|
+
critical: [telegram, agent]
|
|
114
|
+
screen_result:
|
|
115
|
+
high: [telegram, agent]
|
|
116
|
+
|
|
117
|
+
quiet_hours:
|
|
118
|
+
enabled: true
|
|
119
|
+
start: "22:00"
|
|
120
|
+
end: "07:00"
|
|
121
|
+
timezone: "America/New_York"
|
|
122
|
+
per_channel:
|
|
123
|
+
agent:
|
|
124
|
+
enabled: false
|
|
125
|
+
|
|
126
|
+
rate_limits:
|
|
127
|
+
enabled: true
|
|
128
|
+
global_max_per_hour: 20
|
|
129
|
+
agent_max_per_hour: 5
|
|
130
|
+
|
|
131
|
+
thresholds:
|
|
132
|
+
_default:
|
|
133
|
+
min_passed_count: 1
|
|
134
|
+
default_level: normal
|
|
135
|
+
max_per_hour: 3
|
|
136
|
+
estimate_revisions:
|
|
137
|
+
min_passed_count: 1
|
|
138
|
+
level_rules:
|
|
139
|
+
- when:
|
|
140
|
+
passed_count_gte: 3
|
|
141
|
+
level: critical
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## MCP Server
|
|
145
|
+
|
|
146
|
+
The package exposes an MCP server entry point:
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
alerts-mcp
|
|
150
|
+
python -m alerts.mcp_server
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
It provides three tools:
|
|
154
|
+
|
|
155
|
+
- `notify_send`
|
|
156
|
+
- `notify_list_channels`
|
|
157
|
+
- `notify_test_channel`
|
|
158
|
+
|
|
159
|
+
## License
|
|
160
|
+
|
|
161
|
+
MIT
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
agent_alerts-0.1.0.dist-info/licenses/LICENSE,sha256=W9LQ0As1ojxIvLCcOJUn_aYKO5J17Y5w5J-StiwVPeY,1072
|
|
2
|
+
alerts/__init__.py,sha256=8IHvcy2Eai9TxPMpM4wWeLfit8ZIooR3cB3U0jLvvqU,3585
|
|
3
|
+
alerts/config.py,sha256=-_PIcs10naW3re8uLQRT5OdDQrQ6VTRqz-fx6s_sL1E,7743
|
|
4
|
+
alerts/evaluator.py,sha256=0vYJFJ-psbyXEsmKMff2Tpq_oy9-UZG0rMGou-Wm_SY,8165
|
|
5
|
+
alerts/feedback.py,sha256=OA1NqWvCzRtxBzcfkUB7zGkA0PYUQ4IQnSY7vrD_GZA,1102
|
|
6
|
+
alerts/gateway_client.py,sha256=mkRpjsz_Q28A9vKoNhjIZNtXI_TQ6XhtkfEUVyEhYak,6685
|
|
7
|
+
alerts/mcp_server.py,sha256=8uGTU2ylqX7d2wBsXzyhQURnbHvWWJfOWqxyuNQDptw,1850
|
|
8
|
+
alerts/models.py,sha256=xgsiHvS5Py4IpFGpciwH5D_f8VT5dhljJNzzPreXL7A,1911
|
|
9
|
+
alerts/prompt_builder.py,sha256=SA758FyPmXOzRGApY9msbt5-hzcbu1QFN-sU5IMksuU,2429
|
|
10
|
+
alerts/quiet_hours.py,sha256=fpPv1LFU9cJUoiDKwkbKN7K6GoZyPtlYOH50jOuM-CU,2150
|
|
11
|
+
alerts/rate_limiter.py,sha256=gYhKrdJvf-y8UCDvV4HRcugtfTmL2c7kzqjtOCRPBZE,1404
|
|
12
|
+
alerts/router.py,sha256=2CU_nngevmZ5AABYk_cJ1VNhfPdSvHNLd6QzafADfm0,4663
|
|
13
|
+
alerts/channels/__init__.py,sha256=Rq1lkwF57ScdLHc5IA5jHvNU_72-ndt5KSfZt09gNLY,346
|
|
14
|
+
alerts/channels/agent.py,sha256=MV9WFGjVX91SbquCzIxOn9LTx3uiULduxOx6puG7tf8,6209
|
|
15
|
+
alerts/channels/base.py,sha256=8blSY4Bv-b2F1wICynT0iblMda-5JO2bH4rkEUdsjhk,359
|
|
16
|
+
alerts/channels/email.py,sha256=LULks6MTbyUwFBKu2_NRakr4LbKOQeYBnN3q65ysp0M,2706
|
|
17
|
+
alerts/channels/imessage.py,sha256=hgiTB2KY8ynRX71I4PBl3tO4IQHC3nGnQIZOpTViivg,3726
|
|
18
|
+
alerts/channels/telegram.py,sha256=IYcn6WliDU7TeIRJanS835zpCWuixVdq52QT_VAPhzk,2012
|
|
19
|
+
agent_alerts-0.1.0.dist-info/METADATA,sha256=h0FGsfaEXvb0f3XtjHK4nEXnyey9CbvNd0BIuz7SFMY,3620
|
|
20
|
+
agent_alerts-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
21
|
+
agent_alerts-0.1.0.dist-info/entry_points.txt,sha256=o5oWTu9HKy8jGbrxcW0whaJkMxZ0qq0y6I8bF7Sd7ug,54
|
|
22
|
+
agent_alerts-0.1.0.dist-info/top_level.txt,sha256=Mt78CGdVX-gAJ1lmcACyKsRN1hsKY--PPj8WNhjWlL4,7
|
|
23
|
+
agent_alerts-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Henry Chien LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
alerts
|
alerts/__init__.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Mapping
|
|
5
|
+
|
|
6
|
+
from .channels.email import send_email
|
|
7
|
+
from .channels.imessage import send_imessage
|
|
8
|
+
from .channels.telegram import send_telegram
|
|
9
|
+
from .config import _load_dotenv, get_imessage_target, get_telegram_config
|
|
10
|
+
from .evaluator import AlertDecision, AlertEvaluator
|
|
11
|
+
from .models import Alert, AlertCategory, AlertLevel, AlertResult, coerce_alert_category, coerce_alert_level
|
|
12
|
+
from .router import AlertRouter, DEFAULT_CONFIG_PATH
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def send(message: str, channel: str = "telegram", **kwargs) -> dict | bool:
|
|
16
|
+
env = _resolve_env(kwargs.pop("env", None), kwargs.pop("env_file", None))
|
|
17
|
+
|
|
18
|
+
if channel == "telegram":
|
|
19
|
+
token = kwargs.pop("token", None)
|
|
20
|
+
chat_id = kwargs.pop("chat_id", None)
|
|
21
|
+
if not token or not chat_id:
|
|
22
|
+
env_token, env_chat_id = get_telegram_config(env)
|
|
23
|
+
token = token or env_token
|
|
24
|
+
chat_id = chat_id or env_chat_id
|
|
25
|
+
return send_telegram(message, token, chat_id, **kwargs)
|
|
26
|
+
|
|
27
|
+
if channel == "imessage":
|
|
28
|
+
target = kwargs.pop("target", None) or get_imessage_target(env)
|
|
29
|
+
service = kwargs.pop("service", "imessage")
|
|
30
|
+
backend = kwargs.pop("backend", None)
|
|
31
|
+
return send_imessage(message, target, service=service, backend=backend)
|
|
32
|
+
|
|
33
|
+
if channel == "email":
|
|
34
|
+
channel_config = kwargs.pop("channel_config", None)
|
|
35
|
+
return send_email(message, channel_config=channel_config, env=env)
|
|
36
|
+
|
|
37
|
+
raise ValueError(f"Unknown channel: {channel}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def send_alert(
|
|
41
|
+
alert: Alert,
|
|
42
|
+
*,
|
|
43
|
+
router: AlertRouter | None = None,
|
|
44
|
+
config_path: str | Path | None = None,
|
|
45
|
+
env_file: str | Path | None = None,
|
|
46
|
+
env: Mapping[str, str] | None = None,
|
|
47
|
+
) -> AlertResult:
|
|
48
|
+
active_router = router or AlertRouter(config_path=_require_config_path(config_path), env_file=env_file, env=env)
|
|
49
|
+
return active_router.send(alert)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def send_alert_message(
|
|
53
|
+
message: str,
|
|
54
|
+
*,
|
|
55
|
+
title: str = "",
|
|
56
|
+
level: AlertLevel | str = AlertLevel.NORMAL,
|
|
57
|
+
category: AlertCategory | str = AlertCategory.CUSTOM,
|
|
58
|
+
source: str = "",
|
|
59
|
+
source_type: str = "",
|
|
60
|
+
metadata: dict[str, Any] | None = None,
|
|
61
|
+
channel: str | None = None,
|
|
62
|
+
router: AlertRouter | None = None,
|
|
63
|
+
config_path: str | Path | None = None,
|
|
64
|
+
env_file: str | Path | None = None,
|
|
65
|
+
env: Mapping[str, str] | None = None,
|
|
66
|
+
) -> AlertResult:
|
|
67
|
+
alert = Alert(
|
|
68
|
+
title=title,
|
|
69
|
+
body=message,
|
|
70
|
+
level=coerce_alert_level(level),
|
|
71
|
+
category=coerce_alert_category(category),
|
|
72
|
+
source=source,
|
|
73
|
+
source_type=source_type,
|
|
74
|
+
metadata=dict(metadata or {}),
|
|
75
|
+
)
|
|
76
|
+
active_router = router or AlertRouter(config_path=_require_config_path(config_path), env_file=env_file, env=env)
|
|
77
|
+
if channel:
|
|
78
|
+
return active_router.send_channel(alert, channel=channel, level=alert.level)
|
|
79
|
+
return active_router.send(alert)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _resolve_env(env: Mapping[str, str] | None, env_file: str | Path | None) -> Mapping[str, str] | None:
|
|
83
|
+
if env is not None:
|
|
84
|
+
return dict(env)
|
|
85
|
+
if env_file is not None:
|
|
86
|
+
return _load_dotenv(env_file)
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _require_config_path(config_path: str | Path | None) -> str | Path:
|
|
91
|
+
return config_path or DEFAULT_CONFIG_PATH
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
__all__ = [
|
|
95
|
+
"Alert",
|
|
96
|
+
"AlertCategory",
|
|
97
|
+
"AlertDecision",
|
|
98
|
+
"AlertEvaluator",
|
|
99
|
+
"AlertLevel",
|
|
100
|
+
"AlertResult",
|
|
101
|
+
"AlertRouter",
|
|
102
|
+
"get_imessage_target",
|
|
103
|
+
"get_telegram_config",
|
|
104
|
+
"send",
|
|
105
|
+
"send_alert",
|
|
106
|
+
"send_alert_message",
|
|
107
|
+
"send_email",
|
|
108
|
+
"send_imessage",
|
|
109
|
+
"send_telegram",
|
|
110
|
+
]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .base import ChannelAdapter
|
|
2
|
+
from .email import EmailChannel, send_email
|
|
3
|
+
from .imessage import IMessageChannel, send_imessage
|
|
4
|
+
from .telegram import TelegramChannel, send_telegram
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ChannelAdapter",
|
|
8
|
+
"EmailChannel",
|
|
9
|
+
"IMessageChannel",
|
|
10
|
+
"TelegramChannel",
|
|
11
|
+
"send_email",
|
|
12
|
+
"send_imessage",
|
|
13
|
+
"send_telegram",
|
|
14
|
+
]
|
alerts/channels/agent.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from ..feedback import FeedbackHandler, SUPPORTED_FEEDBACK_CHANNELS
|
|
11
|
+
from ..gateway_client import GatewayClient
|
|
12
|
+
from ..models import Alert, AlertLevel
|
|
13
|
+
from ..prompt_builder import DefaultPromptBuilder
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AgentChannel:
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
*,
|
|
22
|
+
prompt_builder: DefaultPromptBuilder | None = None,
|
|
23
|
+
feedback_handler: FeedbackHandler | None = None,
|
|
24
|
+
gateway_client_cls: type[GatewayClient] = GatewayClient,
|
|
25
|
+
thread_factory: Callable[..., threading.Thread] = threading.Thread,
|
|
26
|
+
) -> None:
|
|
27
|
+
self._prompt_builder = prompt_builder or DefaultPromptBuilder()
|
|
28
|
+
self._feedback_handler = feedback_handler or FeedbackHandler()
|
|
29
|
+
self._gateway_client_cls = gateway_client_cls
|
|
30
|
+
self._thread_factory = thread_factory
|
|
31
|
+
|
|
32
|
+
def send(
|
|
33
|
+
self,
|
|
34
|
+
alert: Alert,
|
|
35
|
+
*,
|
|
36
|
+
level: AlertLevel,
|
|
37
|
+
channel_config: dict[str, Any] | None = None,
|
|
38
|
+
env: Mapping[str, str] | None = None,
|
|
39
|
+
) -> bool:
|
|
40
|
+
import httpx
|
|
41
|
+
|
|
42
|
+
_ = httpx
|
|
43
|
+
config = channel_config or {}
|
|
44
|
+
feedback_channel = str(config.get("feedback_channel", "telegram")).strip().lower() or "telegram"
|
|
45
|
+
if feedback_channel not in SUPPORTED_FEEDBACK_CHANNELS:
|
|
46
|
+
raise ValueError(f"Unsupported feedback channel: {feedback_channel}")
|
|
47
|
+
|
|
48
|
+
gateway_url = str(config.get("gateway_url", "")).strip()
|
|
49
|
+
if not gateway_url:
|
|
50
|
+
raise ValueError("Missing required agent channel config: gateway_url")
|
|
51
|
+
|
|
52
|
+
api_key_env_name = str(config.get("gateway_api_key_env", "ALERTS_GATEWAY_API_KEY")).strip()
|
|
53
|
+
if not api_key_env_name:
|
|
54
|
+
raise ValueError("Missing required agent channel config: gateway_api_key_env")
|
|
55
|
+
|
|
56
|
+
credentials = dict(os.environ if env is None else env)
|
|
57
|
+
gateway_api_key = str(credentials.get(api_key_env_name, "")).strip()
|
|
58
|
+
if not gateway_api_key:
|
|
59
|
+
raise ValueError(f"Missing required environment variable: {api_key_env_name}")
|
|
60
|
+
|
|
61
|
+
model = str(config.get("model", "")).strip() or None
|
|
62
|
+
prompt = self._prompt_builder.build(alert, level)
|
|
63
|
+
thread = self._thread_factory(
|
|
64
|
+
target=self._run_thread,
|
|
65
|
+
kwargs={
|
|
66
|
+
"alert": alert,
|
|
67
|
+
"prompt": prompt,
|
|
68
|
+
"gateway_url": gateway_url,
|
|
69
|
+
"gateway_api_key": gateway_api_key,
|
|
70
|
+
"model": model,
|
|
71
|
+
"feedback_channel": feedback_channel,
|
|
72
|
+
"env": dict(env) if env is not None else None,
|
|
73
|
+
},
|
|
74
|
+
daemon=False,
|
|
75
|
+
name=f"alerts-agent-{alert.alert_id}",
|
|
76
|
+
)
|
|
77
|
+
thread.start()
|
|
78
|
+
return True
|
|
79
|
+
|
|
80
|
+
def _run_thread(
|
|
81
|
+
self,
|
|
82
|
+
*,
|
|
83
|
+
alert: Alert,
|
|
84
|
+
prompt: str,
|
|
85
|
+
gateway_url: str,
|
|
86
|
+
gateway_api_key: str,
|
|
87
|
+
model: str | None,
|
|
88
|
+
feedback_channel: str,
|
|
89
|
+
env: Mapping[str, str] | None,
|
|
90
|
+
) -> None:
|
|
91
|
+
loop = asyncio.new_event_loop()
|
|
92
|
+
try:
|
|
93
|
+
asyncio.set_event_loop(loop)
|
|
94
|
+
loop.run_until_complete(
|
|
95
|
+
self._stream_and_feedback(
|
|
96
|
+
alert=alert,
|
|
97
|
+
prompt=prompt,
|
|
98
|
+
gateway_url=gateway_url,
|
|
99
|
+
gateway_api_key=gateway_api_key,
|
|
100
|
+
model=model,
|
|
101
|
+
feedback_channel=feedback_channel,
|
|
102
|
+
env=env,
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
except Exception:
|
|
106
|
+
log.warning("Agent channel failed for alert %s", alert.alert_id, exc_info=True)
|
|
107
|
+
finally:
|
|
108
|
+
asyncio.set_event_loop(None)
|
|
109
|
+
loop.close()
|
|
110
|
+
|
|
111
|
+
async def _stream_and_feedback(
|
|
112
|
+
self,
|
|
113
|
+
*,
|
|
114
|
+
alert: Alert,
|
|
115
|
+
prompt: str,
|
|
116
|
+
gateway_url: str,
|
|
117
|
+
gateway_api_key: str,
|
|
118
|
+
model: str | None,
|
|
119
|
+
feedback_channel: str,
|
|
120
|
+
env: Mapping[str, str] | None,
|
|
121
|
+
) -> None:
|
|
122
|
+
import httpx
|
|
123
|
+
|
|
124
|
+
client = httpx.AsyncClient(timeout=120)
|
|
125
|
+
try:
|
|
126
|
+
gateway = self._gateway_client_cls(
|
|
127
|
+
gateway_url,
|
|
128
|
+
gateway_api_key,
|
|
129
|
+
http_client=client,
|
|
130
|
+
)
|
|
131
|
+
response_parts: list[str] = []
|
|
132
|
+
success = False
|
|
133
|
+
stream = gateway.stream_chat(
|
|
134
|
+
[{"role": "user", "content": prompt}],
|
|
135
|
+
model=model,
|
|
136
|
+
)
|
|
137
|
+
try:
|
|
138
|
+
async for event in stream:
|
|
139
|
+
event_type = str(event.get("type", "") or "")
|
|
140
|
+
if event_type == "text_delta":
|
|
141
|
+
delta = str(event.get("text", "") or "")
|
|
142
|
+
if delta:
|
|
143
|
+
response_parts.append(delta)
|
|
144
|
+
continue
|
|
145
|
+
if event_type == "tool_approval_request":
|
|
146
|
+
await gateway.submit_approval(
|
|
147
|
+
str(event.get("tool_call_id", "") or ""),
|
|
148
|
+
str(event.get("nonce", "") or ""),
|
|
149
|
+
approved=False,
|
|
150
|
+
)
|
|
151
|
+
continue
|
|
152
|
+
if event_type == "stream_complete":
|
|
153
|
+
success = True
|
|
154
|
+
break
|
|
155
|
+
if event_type in {"stream_error", "error"}:
|
|
156
|
+
log.warning(
|
|
157
|
+
"Agent channel stream error for alert %s: %s",
|
|
158
|
+
alert.alert_id,
|
|
159
|
+
event.get("error", "unknown"),
|
|
160
|
+
)
|
|
161
|
+
break
|
|
162
|
+
finally:
|
|
163
|
+
close_stream = getattr(stream, "aclose", None)
|
|
164
|
+
if close_stream is not None:
|
|
165
|
+
await close_stream()
|
|
166
|
+
|
|
167
|
+
if success and response_parts:
|
|
168
|
+
self._feedback_handler.send(
|
|
169
|
+
"".join(response_parts),
|
|
170
|
+
alert,
|
|
171
|
+
channel=feedback_channel,
|
|
172
|
+
env=env,
|
|
173
|
+
)
|
|
174
|
+
finally:
|
|
175
|
+
await client.aclose()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
__all__ = ["AgentChannel"]
|
alerts/channels/base.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Mapping, Protocol
|
|
4
|
+
|
|
5
|
+
from ..models import Alert, AlertLevel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ChannelAdapter(Protocol):
|
|
9
|
+
def send(
|
|
10
|
+
self,
|
|
11
|
+
alert: Alert,
|
|
12
|
+
*,
|
|
13
|
+
level: AlertLevel,
|
|
14
|
+
channel_config: dict[str, Any] | None = None,
|
|
15
|
+
env: Mapping[str, str] | None = None,
|
|
16
|
+
) -> bool: ...
|
alerts/channels/email.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import smtplib
|
|
5
|
+
from email.message import EmailMessage
|
|
6
|
+
from typing import Any, Mapping
|
|
7
|
+
|
|
8
|
+
from ..models import Alert, AlertLevel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def send_email(
|
|
12
|
+
message: str,
|
|
13
|
+
*,
|
|
14
|
+
channel_config: dict[str, Any] | None = None,
|
|
15
|
+
env: Mapping[str, str] | None = None,
|
|
16
|
+
) -> bool:
|
|
17
|
+
config = channel_config or {}
|
|
18
|
+
smtp_host = str(config.get("smtp_host", "")).strip()
|
|
19
|
+
sender = str(config.get("from", "")).strip()
|
|
20
|
+
recipients_raw = config.get("to", [])
|
|
21
|
+
if isinstance(recipients_raw, str):
|
|
22
|
+
recipients = [recipients_raw.strip()] if recipients_raw.strip() else []
|
|
23
|
+
elif isinstance(recipients_raw, list):
|
|
24
|
+
recipients = [str(recipient).strip() for recipient in recipients_raw if str(recipient).strip()]
|
|
25
|
+
else:
|
|
26
|
+
recipients = []
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
smtp_port = int(config.get("smtp_port", 0))
|
|
30
|
+
except (TypeError, ValueError):
|
|
31
|
+
smtp_port = 0
|
|
32
|
+
|
|
33
|
+
if not smtp_host or not smtp_port or not sender or not recipients:
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
credentials = dict(os.environ if env is None else env)
|
|
37
|
+
username = str(credentials.get("EMAIL_USERNAME", "")).strip()
|
|
38
|
+
password = str(credentials.get("EMAIL_PASSWORD", "")).strip()
|
|
39
|
+
if not username or not password:
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
msg = EmailMessage()
|
|
43
|
+
msg["Subject"] = str(config.get("subject", "Investment Tools Alert"))
|
|
44
|
+
msg["From"] = sender
|
|
45
|
+
msg["To"] = ", ".join(recipients)
|
|
46
|
+
msg.set_content(message)
|
|
47
|
+
|
|
48
|
+
timeout = float(config.get("timeout_seconds", 10))
|
|
49
|
+
use_ssl = bool(config.get("use_ssl", smtp_port == 465))
|
|
50
|
+
use_starttls = bool(config.get("starttls", not use_ssl and smtp_port == 587))
|
|
51
|
+
|
|
52
|
+
if use_ssl:
|
|
53
|
+
with smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=timeout) as server:
|
|
54
|
+
server.login(username, password)
|
|
55
|
+
server.send_message(msg)
|
|
56
|
+
return True
|
|
57
|
+
|
|
58
|
+
with smtplib.SMTP(smtp_host, smtp_port, timeout=timeout) as server:
|
|
59
|
+
server.ehlo()
|
|
60
|
+
if use_starttls:
|
|
61
|
+
server.starttls()
|
|
62
|
+
server.ehlo()
|
|
63
|
+
server.login(username, password)
|
|
64
|
+
server.send_message(msg)
|
|
65
|
+
return True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class EmailChannel:
|
|
69
|
+
def send(
|
|
70
|
+
self,
|
|
71
|
+
alert: Alert,
|
|
72
|
+
*,
|
|
73
|
+
level: AlertLevel,
|
|
74
|
+
channel_config: dict[str, Any] | None = None,
|
|
75
|
+
env: Mapping[str, str] | None = None,
|
|
76
|
+
) -> bool:
|
|
77
|
+
return send_email(_render_message(alert, level), channel_config=channel_config, env=env)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _render_message(alert: Alert, level: AlertLevel) -> str:
|
|
81
|
+
parts = [part for part in (alert.title.strip(), alert.body) if part]
|
|
82
|
+
message = "\n\n".join(parts)
|
|
83
|
+
if level is AlertLevel.CRITICAL:
|
|
84
|
+
return f"** ALERT ** {message}"
|
|
85
|
+
return message
|