evented 1.0.3__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.
- evented/__init__.py +21 -0
- evented/base.py +86 -0
- evented/configs.py +148 -0
- evented/email_watcher.py +150 -0
- evented/event_data.py +111 -0
- evented/file_watcher.py +108 -0
- evented/log.py +17 -0
- evented/py.typed +0 -0
- evented/timed_watcher.py +77 -0
- evented/webhook_watcher.py +80 -0
- evented-1.0.3.dist-info/METADATA +64 -0
- evented-1.0.3.dist-info/RECORD +14 -0
- evented-1.0.3.dist-info/WHEEL +4 -0
- evented-1.0.3.dist-info/licenses/LICENSE +22 -0
evented/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Evented: main package.
|
|
2
|
+
|
|
3
|
+
Event emitters.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from importlib.metadata import version
|
|
9
|
+
|
|
10
|
+
__version__ = version("evented")
|
|
11
|
+
__title__ = "Evented"
|
|
12
|
+
|
|
13
|
+
__author__ = "Philipp Temminghoff"
|
|
14
|
+
__author_email__ = "philipptemminghoff@googlemail.com"
|
|
15
|
+
__copyright__ = "Copyright (c) 2025 Philipp Temminghoff"
|
|
16
|
+
__license__ = "MIT"
|
|
17
|
+
__url__ = "https://github.com/phil65/evented"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"__version__",
|
|
21
|
+
]
|
evented/base.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Event sources for Eventic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from typing import TYPE_CHECKING, Self
|
|
7
|
+
|
|
8
|
+
from eventic.configs import EmailConfig, FileWatchConfig, TimeEventConfig, WebhookConfig
|
|
9
|
+
from eventic.log import get_logger
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import AsyncGenerator
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
|
|
16
|
+
from eventic.configs import EventConfig
|
|
17
|
+
from eventic.event_data import EventData
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
logger = get_logger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class EventSource(ABC):
|
|
24
|
+
"""Base class for event sources."""
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
async def __aenter__(self) -> Self:
|
|
28
|
+
"""Initialize connection to event source."""
|
|
29
|
+
|
|
30
|
+
@abstractmethod
|
|
31
|
+
async def __aexit__(
|
|
32
|
+
self,
|
|
33
|
+
exc_type: type[BaseException] | None,
|
|
34
|
+
exc_val: BaseException | None,
|
|
35
|
+
exc_tb: TracebackType | None,
|
|
36
|
+
) -> None:
|
|
37
|
+
"""Close connection to event source."""
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def events(self) -> AsyncGenerator[EventData]:
|
|
41
|
+
"""Get event iterator.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
AsyncIterator yielding events from this source
|
|
45
|
+
|
|
46
|
+
Note: This is a coroutine that returns an AsyncIterator
|
|
47
|
+
"""
|
|
48
|
+
raise NotImplementedError
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def from_config(cls, config: EventConfig) -> EventSource:
|
|
52
|
+
"""Create event source from configuration.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
config: Event source configuration
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
Configured event source instance
|
|
59
|
+
|
|
60
|
+
Raises:
|
|
61
|
+
ValueError: If source type is unknown or disabled
|
|
62
|
+
"""
|
|
63
|
+
if not config.enabled:
|
|
64
|
+
msg = f"Source {config.name} is disabled"
|
|
65
|
+
raise ValueError(msg)
|
|
66
|
+
logger.info("Creating event source: %s (%s)", config.name, config.type)
|
|
67
|
+
match config:
|
|
68
|
+
case FileWatchConfig():
|
|
69
|
+
from eventic.file_watcher import FileSystemEventSource
|
|
70
|
+
|
|
71
|
+
return FileSystemEventSource(config)
|
|
72
|
+
case WebhookConfig():
|
|
73
|
+
from eventic.webhook_watcher import WebhookEventSource
|
|
74
|
+
|
|
75
|
+
return WebhookEventSource(config)
|
|
76
|
+
case EmailConfig():
|
|
77
|
+
from eventic.email_watcher import EmailEventSource
|
|
78
|
+
|
|
79
|
+
return EmailEventSource(config)
|
|
80
|
+
case TimeEventConfig():
|
|
81
|
+
from eventic.timed_watcher import TimeEventSource
|
|
82
|
+
|
|
83
|
+
return TimeEventSource(config)
|
|
84
|
+
case _:
|
|
85
|
+
msg = f"Unknown event source type: {config.type}"
|
|
86
|
+
raise ValueError(msg)
|
evented/configs.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Event sources for LLMling agent."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Annotated, Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import ConfigDict, Field, SecretStr
|
|
8
|
+
from schemez import Schema
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
DEFAULT_TEMPLATE = """
|
|
12
|
+
{%- if include_timestamp %}at {{ timestamp }}{% endif %}
|
|
13
|
+
Event from {{ source }}:
|
|
14
|
+
{%- if include_metadata %}
|
|
15
|
+
Metadata:
|
|
16
|
+
{% for key, value in metadata.items() %}
|
|
17
|
+
{{ key }}: {{ value }}
|
|
18
|
+
{% endfor %}
|
|
19
|
+
{% endif %}
|
|
20
|
+
{{ content }}
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class EventSourceConfig(Schema):
|
|
25
|
+
"""Base configuration for event sources."""
|
|
26
|
+
|
|
27
|
+
type: str = Field(init=False)
|
|
28
|
+
"""Discriminator field for event source types."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
"""Unique identifier for this event source."""
|
|
32
|
+
|
|
33
|
+
enabled: bool = True
|
|
34
|
+
"""Whether this event source is active."""
|
|
35
|
+
|
|
36
|
+
template: str = DEFAULT_TEMPLATE
|
|
37
|
+
"""Jinja2 template for formatting events."""
|
|
38
|
+
|
|
39
|
+
include_metadata: bool = True
|
|
40
|
+
"""Control metadata visibility in template."""
|
|
41
|
+
|
|
42
|
+
include_timestamp: bool = True
|
|
43
|
+
"""Control timestamp visibility in template."""
|
|
44
|
+
|
|
45
|
+
model_config = ConfigDict(frozen=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class FileWatchConfig(EventSourceConfig):
|
|
49
|
+
"""File watching event source."""
|
|
50
|
+
|
|
51
|
+
type: Literal["file"] = Field("file", init=False)
|
|
52
|
+
"""File / folder content change events."""
|
|
53
|
+
|
|
54
|
+
paths: list[str]
|
|
55
|
+
"""Paths or patterns to watch for changes."""
|
|
56
|
+
|
|
57
|
+
extensions: list[str] | None = None
|
|
58
|
+
"""File extensions to monitor (e.g. ['.py', '.md'])."""
|
|
59
|
+
|
|
60
|
+
ignore_paths: list[str] | None = None
|
|
61
|
+
"""Paths or patterns to ignore."""
|
|
62
|
+
|
|
63
|
+
recursive: bool = True
|
|
64
|
+
"""Whether to watch subdirectories."""
|
|
65
|
+
|
|
66
|
+
debounce: int = 1600
|
|
67
|
+
"""Minimum time (ms) between trigger events."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class WebhookConfig(EventSourceConfig):
|
|
71
|
+
"""Webhook event source."""
|
|
72
|
+
|
|
73
|
+
type: Literal["webhook"] = Field("webhook", init=False)
|
|
74
|
+
"""webhook-based event."""
|
|
75
|
+
|
|
76
|
+
port: int = Field(default=..., ge=1, le=65535)
|
|
77
|
+
"""Port to listen on."""
|
|
78
|
+
|
|
79
|
+
path: str
|
|
80
|
+
"""URL path to handle requests."""
|
|
81
|
+
|
|
82
|
+
secret: SecretStr | None = None
|
|
83
|
+
"""Optional secret for request validation."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class TimeEventConfig(EventSourceConfig):
|
|
87
|
+
"""Time-based event source configuration."""
|
|
88
|
+
|
|
89
|
+
type: Literal["time"] = Field("time", init=False)
|
|
90
|
+
"""Time event."""
|
|
91
|
+
|
|
92
|
+
schedule: str
|
|
93
|
+
"""Cron expression for scheduling (e.g. '0 9 * * 1-5' for weekdays at 9am)"""
|
|
94
|
+
|
|
95
|
+
prompt: str
|
|
96
|
+
"""Prompt to send to the agent when the schedule triggers."""
|
|
97
|
+
|
|
98
|
+
timezone: str | None = None
|
|
99
|
+
"""Timezone for schedule (defaults to system timezone)"""
|
|
100
|
+
|
|
101
|
+
skip_missed: bool = False
|
|
102
|
+
"""Whether to skip executions missed while agent was inactive"""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class EmailConfig(EventSourceConfig):
|
|
106
|
+
"""Email event source configuration.
|
|
107
|
+
|
|
108
|
+
Monitors an email inbox for new messages and converts them to events.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
type: Literal["email"] = Field("email", init=False)
|
|
112
|
+
"""Email event."""
|
|
113
|
+
|
|
114
|
+
host: str
|
|
115
|
+
"""IMAP server hostname (e.g. 'imap.gmail.com')"""
|
|
116
|
+
|
|
117
|
+
port: int = Field(ge=1, le=65535, default=993)
|
|
118
|
+
"""Server port (defaults to 993 for IMAP SSL)"""
|
|
119
|
+
|
|
120
|
+
username: str
|
|
121
|
+
"""Email account username/address"""
|
|
122
|
+
|
|
123
|
+
password: SecretStr
|
|
124
|
+
"""Account password or app-specific password"""
|
|
125
|
+
|
|
126
|
+
folder: str = "INBOX"
|
|
127
|
+
"""Folder/mailbox to monitor"""
|
|
128
|
+
|
|
129
|
+
ssl: bool = True
|
|
130
|
+
"""Whether to use SSL/TLS connection"""
|
|
131
|
+
|
|
132
|
+
check_interval: int = Field(default=60, gt=0)
|
|
133
|
+
"""How often to check for new emails (in seconds)"""
|
|
134
|
+
|
|
135
|
+
mark_seen: bool = True
|
|
136
|
+
"""Whether to mark processed emails as seen"""
|
|
137
|
+
|
|
138
|
+
filters: dict[str, str] = Field(default_factory=dict)
|
|
139
|
+
"""Filtering rules for emails (subject, from, etc)"""
|
|
140
|
+
|
|
141
|
+
max_size: int | None = Field(default=None, ge=0)
|
|
142
|
+
"""Size limit for processed emails in bytes"""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
EventConfig = Annotated[
|
|
146
|
+
FileWatchConfig | WebhookConfig | EmailConfig | TimeEventConfig,
|
|
147
|
+
Field(discriminator="type"),
|
|
148
|
+
]
|
evented/email_watcher.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Email event source."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import TYPE_CHECKING, Self
|
|
7
|
+
|
|
8
|
+
from eventic.base import EventSource
|
|
9
|
+
from eventic.event_data import EmailEventData
|
|
10
|
+
from eventic.log import get_logger
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import AsyncGenerator
|
|
15
|
+
from types import TracebackType
|
|
16
|
+
|
|
17
|
+
import aioimaplib
|
|
18
|
+
|
|
19
|
+
from eventic.configs import EmailConfig
|
|
20
|
+
from eventic.event_data import EventData
|
|
21
|
+
|
|
22
|
+
logger = get_logger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class EmailEventSource(EventSource):
|
|
26
|
+
"""Monitors email inbox for events."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, config: EmailConfig):
|
|
29
|
+
import ssl
|
|
30
|
+
|
|
31
|
+
import aioimaplib
|
|
32
|
+
|
|
33
|
+
self.config = config
|
|
34
|
+
self._stop_event = asyncio.Event()
|
|
35
|
+
|
|
36
|
+
# Create client object (no IO)
|
|
37
|
+
if self.config.ssl:
|
|
38
|
+
ssl_context = ssl.create_default_context()
|
|
39
|
+
self._client: aioimaplib.IMAP4_SSL | aioimaplib.IMAP4 = aioimaplib.IMAP4_SSL(
|
|
40
|
+
self.config.host, self.config.port, ssl_context=ssl_context
|
|
41
|
+
)
|
|
42
|
+
else:
|
|
43
|
+
self._client = aioimaplib.IMAP4(self.config.host, self.config.port)
|
|
44
|
+
|
|
45
|
+
async def __aenter__(self) -> Self:
|
|
46
|
+
"""Connect to email server with configured protocol."""
|
|
47
|
+
await self._client.login(
|
|
48
|
+
self.config.username, self.config.password.get_secret_value()
|
|
49
|
+
)
|
|
50
|
+
await self._client.select(self.config.folder)
|
|
51
|
+
return self
|
|
52
|
+
|
|
53
|
+
async def __aexit__(
|
|
54
|
+
self,
|
|
55
|
+
exc_type: type[BaseException] | None,
|
|
56
|
+
exc_val: BaseException | None,
|
|
57
|
+
exc_tb: TracebackType | None,
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Close connection and cleanup."""
|
|
60
|
+
self._stop_event.set()
|
|
61
|
+
try:
|
|
62
|
+
await self._client.close()
|
|
63
|
+
await self._client.logout()
|
|
64
|
+
except Exception:
|
|
65
|
+
logger.exception("Error during email client cleanup")
|
|
66
|
+
|
|
67
|
+
def _build_search_criteria(self) -> str:
|
|
68
|
+
"""Build IMAP search string from filters."""
|
|
69
|
+
criteria = ["UNSEEN"] if not self.config.mark_seen else []
|
|
70
|
+
|
|
71
|
+
# Add configured filters
|
|
72
|
+
for key, value in self.config.filters.items():
|
|
73
|
+
# Convert filter keys to IMAP criteria
|
|
74
|
+
match key.upper():
|
|
75
|
+
case "FROM":
|
|
76
|
+
criteria.append(f'FROM "{value}"')
|
|
77
|
+
case "SUBJECT":
|
|
78
|
+
criteria.append(f'SUBJECT "{value}"')
|
|
79
|
+
case "TO":
|
|
80
|
+
criteria.append(f'TO "{value}"')
|
|
81
|
+
case _:
|
|
82
|
+
logger.warning("Unsupported email filter: %s", key)
|
|
83
|
+
|
|
84
|
+
return " ".join(criteria)
|
|
85
|
+
|
|
86
|
+
def _process_email(self, email_bytes: bytes) -> EventData:
|
|
87
|
+
from email.parser import BytesParser
|
|
88
|
+
|
|
89
|
+
parser = BytesParser()
|
|
90
|
+
email_msg = parser.parsebytes(email_bytes)
|
|
91
|
+
if self.config.max_size and len(email_bytes) > self.config.max_size:
|
|
92
|
+
msg = f"Email exceeds size limit of {self.config.max_size} bytes"
|
|
93
|
+
raise ValueError(msg)
|
|
94
|
+
|
|
95
|
+
# Extract content (prefer text/plain)
|
|
96
|
+
content = ""
|
|
97
|
+
for part in email_msg.walk():
|
|
98
|
+
content_type = part.get_content_type()
|
|
99
|
+
match content_type:
|
|
100
|
+
case "text/plain":
|
|
101
|
+
payload = part.get_payload(decode=True)
|
|
102
|
+
if isinstance(payload, bytes):
|
|
103
|
+
content = payload.decode()
|
|
104
|
+
break
|
|
105
|
+
case "text/html":
|
|
106
|
+
payload = part.get_payload(decode=True)
|
|
107
|
+
if isinstance(payload, bytes):
|
|
108
|
+
content = payload.decode()
|
|
109
|
+
|
|
110
|
+
meta = {"date": email_msg["date"], "message_id": email_msg["message-id"]}
|
|
111
|
+
return EmailEventData(
|
|
112
|
+
source=self.config.name,
|
|
113
|
+
subject=email_msg["subject"],
|
|
114
|
+
sender=email_msg["from"],
|
|
115
|
+
body=content,
|
|
116
|
+
metadata=meta,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
async def events(self) -> AsyncGenerator[EventData]:
|
|
120
|
+
"""Monitor inbox and yield new email events."""
|
|
121
|
+
while not self._stop_event.is_set():
|
|
122
|
+
try:
|
|
123
|
+
search_criteria = self._build_search_criteria()
|
|
124
|
+
_, messages = await self._client.search(search_criteria)
|
|
125
|
+
|
|
126
|
+
for num in messages[0].split(): # Process each message
|
|
127
|
+
try:
|
|
128
|
+
# Fetch full message
|
|
129
|
+
_, msg_data = await self._client.fetch(num, "(RFC822)")
|
|
130
|
+
if not msg_data:
|
|
131
|
+
continue
|
|
132
|
+
|
|
133
|
+
email_bytes = msg_data[0][1]
|
|
134
|
+
event = self._process_email(email_bytes)
|
|
135
|
+
|
|
136
|
+
if self.config.mark_seen: # Mark as seen if configured
|
|
137
|
+
await self._client.store(num, "+FLAGS", "\\Seen")
|
|
138
|
+
|
|
139
|
+
yield event
|
|
140
|
+
|
|
141
|
+
except Exception:
|
|
142
|
+
logger.exception("Error processing email")
|
|
143
|
+
|
|
144
|
+
await asyncio.sleep(self.config.check_interval) # Wait before next check
|
|
145
|
+
|
|
146
|
+
except asyncio.CancelledError:
|
|
147
|
+
break
|
|
148
|
+
except Exception:
|
|
149
|
+
logger.exception("Error checking emails")
|
|
150
|
+
await asyncio.sleep(self.config.check_interval)
|
evented/event_data.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Event sources."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import abstractmethod
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Literal, Self
|
|
8
|
+
|
|
9
|
+
from llmling_agent.utils.now import get_now
|
|
10
|
+
from pydantic import ConfigDict, Field
|
|
11
|
+
from schemez import Schema
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from llmling_agent_config.events import EventSourceConfig
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
ChangeType = Literal["added", "modified", "deleted"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class EventData(Schema):
|
|
22
|
+
"""Base class for event data."""
|
|
23
|
+
|
|
24
|
+
source: str
|
|
25
|
+
timestamp: datetime = Field(default_factory=get_now)
|
|
26
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def create(cls, source: str, **kwargs: Any) -> Self:
|
|
32
|
+
"""Create event with current timestamp."""
|
|
33
|
+
return cls(source=source, **kwargs)
|
|
34
|
+
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def to_prompt(self) -> str:
|
|
37
|
+
"""Convert event to agent prompt."""
|
|
38
|
+
|
|
39
|
+
async def format(self, config: EventSourceConfig) -> str:
|
|
40
|
+
"""Wraps core message with configurable template."""
|
|
41
|
+
from jinjarope import Environment
|
|
42
|
+
|
|
43
|
+
env = Environment(trim_blocks=True, lstrip_blocks=True, enable_async=True)
|
|
44
|
+
template = env.from_string(config.template)
|
|
45
|
+
|
|
46
|
+
return await template.render_async(
|
|
47
|
+
source=self.source,
|
|
48
|
+
content=self.to_prompt(), # Use the core message
|
|
49
|
+
metadata=self.metadata,
|
|
50
|
+
timestamp=self.timestamp,
|
|
51
|
+
include_metadata=config.include_metadata,
|
|
52
|
+
include_timestamp=config.include_timestamp,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class FileEventData(EventData):
|
|
57
|
+
"""File system event."""
|
|
58
|
+
|
|
59
|
+
path: str
|
|
60
|
+
type: ChangeType
|
|
61
|
+
|
|
62
|
+
def to_prompt(self) -> str:
|
|
63
|
+
return f"File {self.type}: {self.path}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class FunctionResultEventData(EventData):
|
|
67
|
+
"""Event from a function execution result."""
|
|
68
|
+
|
|
69
|
+
result: Any
|
|
70
|
+
|
|
71
|
+
def to_prompt(self) -> str:
|
|
72
|
+
"""Convert result to prompt format."""
|
|
73
|
+
return str(self.result)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class EmailEventData(EventData):
|
|
77
|
+
"""Email event with specific content structure."""
|
|
78
|
+
|
|
79
|
+
subject: str
|
|
80
|
+
sender: str
|
|
81
|
+
body: str
|
|
82
|
+
|
|
83
|
+
def to_prompt(self) -> str:
|
|
84
|
+
"""Core email message."""
|
|
85
|
+
return f"Email from {self.sender} with subject: {self.subject}\n\n{self.body}"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TimeEventData(EventData):
|
|
89
|
+
"""Time-based event."""
|
|
90
|
+
|
|
91
|
+
schedule: str
|
|
92
|
+
"""Cron expression that triggered this event."""
|
|
93
|
+
|
|
94
|
+
prompt: str
|
|
95
|
+
"""Cron expression that triggered this event."""
|
|
96
|
+
|
|
97
|
+
def to_prompt(self) -> str:
|
|
98
|
+
"""Format scheduled event."""
|
|
99
|
+
return f"Scheduled task triggered by {self.schedule}: {self.prompt}"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class WebhookEventData(EventData):
|
|
103
|
+
"""Webhook payload with formatting."""
|
|
104
|
+
|
|
105
|
+
payload: dict[str, Any]
|
|
106
|
+
|
|
107
|
+
def to_prompt(self) -> str:
|
|
108
|
+
"""Format webhook payload."""
|
|
109
|
+
import anyenv
|
|
110
|
+
|
|
111
|
+
return f"Webhook received:\n{anyenv.dump_json(self.payload, indent=True)}"
|
evented/file_watcher.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""File event source."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import TYPE_CHECKING, Self
|
|
7
|
+
|
|
8
|
+
from eventic.base import EventSource
|
|
9
|
+
from eventic.event_data import FileEventData
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import AsyncGenerator, AsyncIterator
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
|
|
16
|
+
from watchfiles import Change
|
|
17
|
+
from watchfiles.main import FileChange
|
|
18
|
+
|
|
19
|
+
from eventic.configs import FileWatchConfig
|
|
20
|
+
from eventic.event_data import ChangeType, EventData
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ExtensionFilter:
|
|
24
|
+
"""Filter for specific file extensions."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, extensions: list[str], ignore_paths: list[str] | None = None):
|
|
27
|
+
"""Initialize filter.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
extensions: File extensions to watch (e.g. ['.py', '.md'])
|
|
31
|
+
ignore_paths: Paths to ignore
|
|
32
|
+
"""
|
|
33
|
+
from watchfiles.filters import DefaultFilter
|
|
34
|
+
|
|
35
|
+
self.extensions = tuple(e if e.startswith(".") else f".{e}" for e in extensions)
|
|
36
|
+
self._default_filter = DefaultFilter(ignore_paths=ignore_paths)
|
|
37
|
+
|
|
38
|
+
def __call__(self, change: Change, path: str) -> bool:
|
|
39
|
+
"""Check if file should be watched."""
|
|
40
|
+
return path.endswith(self.extensions) and self._default_filter(change, path)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class FileSystemEventSource(EventSource):
|
|
44
|
+
"""Watch file system changes using watchfiles."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, config: FileWatchConfig):
|
|
47
|
+
"""Initialize file system watcher.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
config: File watch configuration
|
|
51
|
+
"""
|
|
52
|
+
self.config = config
|
|
53
|
+
self._watch: AsyncIterator[set[FileChange]] | None = None
|
|
54
|
+
self._stop_event: asyncio.Event | None = None
|
|
55
|
+
|
|
56
|
+
async def __aenter__(self) -> Self:
|
|
57
|
+
"""Set up watchfiles watcher."""
|
|
58
|
+
if not self.config.paths:
|
|
59
|
+
msg = "No paths specified to watch"
|
|
60
|
+
raise ValueError(msg)
|
|
61
|
+
|
|
62
|
+
from watchfiles.main import awatch
|
|
63
|
+
|
|
64
|
+
self._stop_event = asyncio.Event()
|
|
65
|
+
watch_filter = None # Create filter from extensions if provided
|
|
66
|
+
if self.config.extensions:
|
|
67
|
+
to_ignore = self.config.ignore_paths
|
|
68
|
+
watch_filter = ExtensionFilter(self.config.extensions, ignore_paths=to_ignore)
|
|
69
|
+
|
|
70
|
+
self._watch = awatch(
|
|
71
|
+
*self.config.paths,
|
|
72
|
+
watch_filter=watch_filter,
|
|
73
|
+
debounce=self.config.debounce,
|
|
74
|
+
stop_event=self._stop_event,
|
|
75
|
+
recursive=self.config.recursive,
|
|
76
|
+
)
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
async def __aexit__(
|
|
80
|
+
self,
|
|
81
|
+
exc_type: type[BaseException] | None,
|
|
82
|
+
exc_val: BaseException | None,
|
|
83
|
+
exc_tb: TracebackType | None,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Stop watchfiles watcher."""
|
|
86
|
+
if self._stop_event:
|
|
87
|
+
self._stop_event.set()
|
|
88
|
+
self._watch = None
|
|
89
|
+
self._stop_event = None
|
|
90
|
+
|
|
91
|
+
async def events(self) -> AsyncGenerator[EventData]:
|
|
92
|
+
"""Get file system events."""
|
|
93
|
+
from watchfiles import Change
|
|
94
|
+
|
|
95
|
+
if not self._watch:
|
|
96
|
+
msg = "Source not connected"
|
|
97
|
+
raise RuntimeError(msg)
|
|
98
|
+
change_to_type: dict[Change, ChangeType] = {
|
|
99
|
+
Change.added: "added",
|
|
100
|
+
Change.modified: "modified",
|
|
101
|
+
Change.deleted: "deleted",
|
|
102
|
+
}
|
|
103
|
+
async for changes in self._watch:
|
|
104
|
+
for change, path in changes:
|
|
105
|
+
if change not in change_to_type:
|
|
106
|
+
continue
|
|
107
|
+
typ = change_to_type[change]
|
|
108
|
+
yield FileEventData.create(self.config.name, path=str(path), type=typ)
|
evented/log.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Logging configuration for evented."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get_logger(name: str) -> logging.Logger:
|
|
9
|
+
"""Get a logger for the given name.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
name: The name of the logger, will be prefixed with 'llmling_agent.'
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
A logger instance
|
|
16
|
+
"""
|
|
17
|
+
return logging.getLogger(f"evented.{name}")
|
evented/py.typed
ADDED
|
File without changes
|
evented/timed_watcher.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Time-based event source for scheduling agent actions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import TYPE_CHECKING, Self
|
|
8
|
+
|
|
9
|
+
from eventic.base import EventSource
|
|
10
|
+
from eventic.event_data import TimeEventData
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import AsyncGenerator
|
|
15
|
+
from types import TracebackType
|
|
16
|
+
|
|
17
|
+
from eventic.configs import TimeEventConfig
|
|
18
|
+
from eventic.event_data import EventData
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TimeEventSource(EventSource):
|
|
22
|
+
"""Generates events based on cron schedule."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, config: TimeEventConfig):
|
|
25
|
+
import zoneinfo
|
|
26
|
+
|
|
27
|
+
self.config = config
|
|
28
|
+
self._stop_event = asyncio.Event()
|
|
29
|
+
self._tz = zoneinfo.ZoneInfo(config.timezone) if config.timezone else None
|
|
30
|
+
|
|
31
|
+
async def __aenter__(self) -> Self:
|
|
32
|
+
"""Validate cron expression."""
|
|
33
|
+
from croniter import croniter
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
now = datetime.now(self._tz)
|
|
37
|
+
croniter(self.config.schedule, now)
|
|
38
|
+
except Exception as e:
|
|
39
|
+
msg = f"Invalid cron expression: {e}"
|
|
40
|
+
raise ValueError(msg) from e
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
async def __aexit__(
|
|
44
|
+
self,
|
|
45
|
+
exc_type: type[BaseException] | None,
|
|
46
|
+
exc_val: BaseException | None,
|
|
47
|
+
exc_tb: TracebackType | None,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""Stop event generation."""
|
|
50
|
+
self._stop_event.set()
|
|
51
|
+
|
|
52
|
+
async def events(self) -> AsyncGenerator[EventData]:
|
|
53
|
+
"""Generate events based on schedule."""
|
|
54
|
+
from croniter import croniter
|
|
55
|
+
|
|
56
|
+
while not self._stop_event.is_set():
|
|
57
|
+
now = datetime.now(self._tz)
|
|
58
|
+
cron = croniter(self.config.schedule, now)
|
|
59
|
+
next_run = cron.get_next(datetime)
|
|
60
|
+
delay = (next_run - now).total_seconds() # Sleep until next run
|
|
61
|
+
if delay > 0:
|
|
62
|
+
try:
|
|
63
|
+
await asyncio.sleep(delay)
|
|
64
|
+
except asyncio.CancelledError:
|
|
65
|
+
break
|
|
66
|
+
|
|
67
|
+
# Skip if we missed the schedule and skip_missed is True
|
|
68
|
+
if self.config.skip_missed:
|
|
69
|
+
current = datetime.now(self._tz)
|
|
70
|
+
if (current - next_run).total_seconds() > 1:
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
yield TimeEventData(
|
|
74
|
+
source=self.config.name,
|
|
75
|
+
schedule=self.config.schedule,
|
|
76
|
+
prompt=self.config.prompt,
|
|
77
|
+
)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Webhook event source."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import TYPE_CHECKING, Self
|
|
7
|
+
|
|
8
|
+
from eventic.base import EventSource
|
|
9
|
+
from eventic.event_data import EventData
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import AsyncGenerator
|
|
14
|
+
from types import TracebackType
|
|
15
|
+
|
|
16
|
+
from fastapi import Request
|
|
17
|
+
|
|
18
|
+
from eventic.configs import WebhookConfig
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class WebhookEventSource(EventSource):
|
|
22
|
+
"""Listens for webhook events on configured endpoint."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, config: WebhookConfig):
|
|
25
|
+
from fastapi import FastAPI
|
|
26
|
+
|
|
27
|
+
self.config = config
|
|
28
|
+
self.app = FastAPI()
|
|
29
|
+
self._queue = asyncio.Queue[EventData]()
|
|
30
|
+
|
|
31
|
+
@self.app.post(config.path)
|
|
32
|
+
async def handle_webhook(request: Request):
|
|
33
|
+
if self.config.secret: # Verify signature if secret configured
|
|
34
|
+
signature = request.headers.get("X-Hub-Signature")
|
|
35
|
+
if not self._verify_signature(await request.body(), signature):
|
|
36
|
+
return {"status": "invalid signature"}
|
|
37
|
+
|
|
38
|
+
payload = await request.json() # Process payload
|
|
39
|
+
event = EventData.create(source=self.config.name, content=payload)
|
|
40
|
+
await self._queue.put(event)
|
|
41
|
+
return {"status": "ok"}
|
|
42
|
+
|
|
43
|
+
async def __aenter__(self) -> Self:
|
|
44
|
+
"""Start webhook server."""
|
|
45
|
+
import uvicorn
|
|
46
|
+
|
|
47
|
+
cfg = uvicorn.Config(
|
|
48
|
+
self.app, host="0.0.0.0", port=self.config.port, log_level="error"
|
|
49
|
+
)
|
|
50
|
+
self.server = uvicorn.Server(config=cfg)
|
|
51
|
+
await self.server.serve()
|
|
52
|
+
return self
|
|
53
|
+
|
|
54
|
+
async def __aexit__(
|
|
55
|
+
self,
|
|
56
|
+
exc_type: type[BaseException] | None,
|
|
57
|
+
exc_val: BaseException | None,
|
|
58
|
+
exc_tb: TracebackType | None,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Stop webhook server."""
|
|
61
|
+
if self.server:
|
|
62
|
+
await self.server.shutdown()
|
|
63
|
+
|
|
64
|
+
async def events(self) -> AsyncGenerator[EventData]:
|
|
65
|
+
"""Yield events as they arrive."""
|
|
66
|
+
while True:
|
|
67
|
+
event = await self._queue.get()
|
|
68
|
+
yield event
|
|
69
|
+
|
|
70
|
+
def _verify_signature(self, payload: bytes, signature: str | None) -> bool:
|
|
71
|
+
"""Verify webhook signature."""
|
|
72
|
+
import hashlib
|
|
73
|
+
import hmac
|
|
74
|
+
|
|
75
|
+
if not signature or not self.config.secret:
|
|
76
|
+
return False
|
|
77
|
+
key = self.config.secret.get_secret_value().encode()
|
|
78
|
+
expected = hmac.new(key, payload, hashlib.sha256).hexdigest()
|
|
79
|
+
|
|
80
|
+
return hmac.compare_digest(signature, expected)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: evented
|
|
3
|
+
Version: 1.0.3
|
|
4
|
+
Summary: Event emitters.
|
|
5
|
+
Keywords:
|
|
6
|
+
Author: Philipp Temminghoff
|
|
7
|
+
Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Framework :: Pydantic
|
|
12
|
+
Classifier: Framework :: Pydantic :: 2
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Documentation
|
|
21
|
+
Classifier: Topic :: Software Development
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Dist: pydantic
|
|
25
|
+
Requires-Dist: schemez
|
|
26
|
+
Requires-Dist: watchfiles ; extra == 'events'
|
|
27
|
+
Requires-Dist: aioimaplib>=2.0.1 ; extra == 'events'
|
|
28
|
+
Requires-Dist: croniter>=6.0.0 ; extra == 'events'
|
|
29
|
+
Requires-Dist: fastapi ; extra == 'events'
|
|
30
|
+
Requires-Python: >=3.13
|
|
31
|
+
Project-URL: Code coverage, https://app.codecov.io/gh/phil65/evented
|
|
32
|
+
Project-URL: Discussions, https://github.com/phil65/evented/discussions
|
|
33
|
+
Project-URL: Documentation, https://phil65.github.io/evented/
|
|
34
|
+
Project-URL: Issues, https://github.com/phil65/evented/issues
|
|
35
|
+
Project-URL: Source, https://github.com/phil65/evented
|
|
36
|
+
Provides-Extra: events
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# Evented
|
|
40
|
+
|
|
41
|
+
[](https://pypi.org/project/evented/)
|
|
42
|
+
[](https://pypi.org/project/evented/)
|
|
43
|
+
[](https://pypi.org/project/evented/)
|
|
44
|
+
[](https://pypi.org/project/evented/)
|
|
45
|
+
[](https://pypi.org/project/evented/)
|
|
46
|
+
[](https://pypi.org/project/evented/)
|
|
47
|
+
[](https://pypi.org/project/evented/)
|
|
48
|
+
[](https://github.com/phil65/evented/releases)
|
|
49
|
+
[](https://github.com/phil65/evented/graphs/contributors)
|
|
50
|
+
[](https://github.com/phil65/evented/discussions)
|
|
51
|
+
[](https://github.com/phil65/evented/forks)
|
|
52
|
+
[](https://github.com/phil65/evented/issues)
|
|
53
|
+
[](https://github.com/phil65/evented/pulls)
|
|
54
|
+
[](https://github.com/phil65/evented/watchers)
|
|
55
|
+
[](https://github.com/phil65/evented/stars)
|
|
56
|
+
[](https://github.com/phil65/evented)
|
|
57
|
+
[](https://github.com/phil65/evented/commits)
|
|
58
|
+
[](https://github.com/phil65/evented/releases)
|
|
59
|
+
[](https://github.com/phil65/evented)
|
|
60
|
+
[](https://github.com/phil65/evented)
|
|
61
|
+
[](https://codecov.io/gh/phil65/evented/)
|
|
62
|
+
[](https://pyup.io/repos/github/phil65/evented/)
|
|
63
|
+
|
|
64
|
+
[Read the documentation!](https://phil65.github.io/evented/)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
evented/__init__.py,sha256=WTc6S9B993b3dGC71u-tvPs1zWBlH5BFPyQKrAfX6tI,427
|
|
2
|
+
evented/base.py,sha256=iTF1lu70uNfMT4gxolzHDygdPzoS_PD8WkKMOMGT2j4,2605
|
|
3
|
+
evented/configs.py,sha256=lBDuf3a54Wq7ffoMuHV240geWyHZ9qVSt5k-q5f_9Pk,3809
|
|
4
|
+
evented/email_watcher.py,sha256=haOgJ3PFB4OmwwJ3MF_vKETfsV2H3_oowM3uW6l8Oi0,5360
|
|
5
|
+
evented/event_data.py,sha256=wquzG8EeSd3Qcs-FrCOgqd200OiHksirZl3rPNPQkS0,2927
|
|
6
|
+
evented/file_watcher.py,sha256=VqANeI1obNRhDG9cIcJXvOeuNkfyltAtoSJJNKWOorw,3603
|
|
7
|
+
evented/log.py,sha256=DHh9IhCUKzSoj_c64hU8T6cKwnsKwh4MQ39OCf_uefw,364
|
|
8
|
+
evented/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
evented/timed_watcher.py,sha256=lWJpbE1YhftMfFKU3BYoYfqD5P8WPya1B8nXrotza50,2473
|
|
10
|
+
evented/webhook_watcher.py,sha256=rtTZ2V4xAmWFcgrZPMe39XisHx3zbSEnrrY_88QyuUc,2565
|
|
11
|
+
evented-1.0.3.dist-info/licenses/LICENSE,sha256=AteGCH9r177TxxrOFEiOARrastASsf7yW6MQxlAHdwA,1078
|
|
12
|
+
evented-1.0.3.dist-info/WHEEL,sha256=X16MKk8bp2DRsAuyteHJ-9qOjzmnY0x1aj0P1ftqqWA,78
|
|
13
|
+
evented-1.0.3.dist-info/METADATA,sha256=u8FFKUJt1kvWqfJvW-TbJyXQCpNxnFTOSFU0Ywwdv5U,4112
|
|
14
|
+
evented-1.0.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024, Philipp Temminghoff
|
|
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.
|
|
22
|
+
|