evented 1.0.3__tar.gz

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-1.0.3/LICENSE ADDED
@@ -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
+
evented-1.0.3/PKG-INFO ADDED
@@ -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
+ [![PyPI License](https://img.shields.io/pypi/l/evented.svg)](https://pypi.org/project/evented/)
42
+ [![Package status](https://img.shields.io/pypi/status/evented.svg)](https://pypi.org/project/evented/)
43
+ [![Monthly downloads](https://img.shields.io/pypi/dm/evented.svg)](https://pypi.org/project/evented/)
44
+ [![Distribution format](https://img.shields.io/pypi/format/evented.svg)](https://pypi.org/project/evented/)
45
+ [![Wheel availability](https://img.shields.io/pypi/wheel/evented.svg)](https://pypi.org/project/evented/)
46
+ [![Python version](https://img.shields.io/pypi/pyversions/evented.svg)](https://pypi.org/project/evented/)
47
+ [![Implementation](https://img.shields.io/pypi/implementation/evented.svg)](https://pypi.org/project/evented/)
48
+ [![Releases](https://img.shields.io/github/downloads/phil65/evented/total.svg)](https://github.com/phil65/evented/releases)
49
+ [![Github Contributors](https://img.shields.io/github/contributors/phil65/evented)](https://github.com/phil65/evented/graphs/contributors)
50
+ [![Github Discussions](https://img.shields.io/github/discussions/phil65/evented)](https://github.com/phil65/evented/discussions)
51
+ [![Github Forks](https://img.shields.io/github/forks/phil65/evented)](https://github.com/phil65/evented/forks)
52
+ [![Github Issues](https://img.shields.io/github/issues/phil65/evented)](https://github.com/phil65/evented/issues)
53
+ [![Github Issues](https://img.shields.io/github/issues-pr/phil65/evented)](https://github.com/phil65/evented/pulls)
54
+ [![Github Watchers](https://img.shields.io/github/watchers/phil65/evented)](https://github.com/phil65/evented/watchers)
55
+ [![Github Stars](https://img.shields.io/github/stars/phil65/evented)](https://github.com/phil65/evented/stars)
56
+ [![Github Repository size](https://img.shields.io/github/repo-size/phil65/evented)](https://github.com/phil65/evented)
57
+ [![Github last commit](https://img.shields.io/github/last-commit/phil65/evented)](https://github.com/phil65/evented/commits)
58
+ [![Github release date](https://img.shields.io/github/release-date/phil65/evented)](https://github.com/phil65/evented/releases)
59
+ [![Github language count](https://img.shields.io/github/languages/count/phil65/evented)](https://github.com/phil65/evented)
60
+ [![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/evented)](https://github.com/phil65/evented)
61
+ [![Package status](https://codecov.io/gh/phil65/evented/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/evented/)
62
+ [![PyUp](https://pyup.io/repos/github/phil65/evented/shield.svg)](https://pyup.io/repos/github/phil65/evented/)
63
+
64
+ [Read the documentation!](https://phil65.github.io/evented/)
@@ -0,0 +1,26 @@
1
+ # Evented
2
+
3
+ [![PyPI License](https://img.shields.io/pypi/l/evented.svg)](https://pypi.org/project/evented/)
4
+ [![Package status](https://img.shields.io/pypi/status/evented.svg)](https://pypi.org/project/evented/)
5
+ [![Monthly downloads](https://img.shields.io/pypi/dm/evented.svg)](https://pypi.org/project/evented/)
6
+ [![Distribution format](https://img.shields.io/pypi/format/evented.svg)](https://pypi.org/project/evented/)
7
+ [![Wheel availability](https://img.shields.io/pypi/wheel/evented.svg)](https://pypi.org/project/evented/)
8
+ [![Python version](https://img.shields.io/pypi/pyversions/evented.svg)](https://pypi.org/project/evented/)
9
+ [![Implementation](https://img.shields.io/pypi/implementation/evented.svg)](https://pypi.org/project/evented/)
10
+ [![Releases](https://img.shields.io/github/downloads/phil65/evented/total.svg)](https://github.com/phil65/evented/releases)
11
+ [![Github Contributors](https://img.shields.io/github/contributors/phil65/evented)](https://github.com/phil65/evented/graphs/contributors)
12
+ [![Github Discussions](https://img.shields.io/github/discussions/phil65/evented)](https://github.com/phil65/evented/discussions)
13
+ [![Github Forks](https://img.shields.io/github/forks/phil65/evented)](https://github.com/phil65/evented/forks)
14
+ [![Github Issues](https://img.shields.io/github/issues/phil65/evented)](https://github.com/phil65/evented/issues)
15
+ [![Github Issues](https://img.shields.io/github/issues-pr/phil65/evented)](https://github.com/phil65/evented/pulls)
16
+ [![Github Watchers](https://img.shields.io/github/watchers/phil65/evented)](https://github.com/phil65/evented/watchers)
17
+ [![Github Stars](https://img.shields.io/github/stars/phil65/evented)](https://github.com/phil65/evented/stars)
18
+ [![Github Repository size](https://img.shields.io/github/repo-size/phil65/evented)](https://github.com/phil65/evented)
19
+ [![Github last commit](https://img.shields.io/github/last-commit/phil65/evented)](https://github.com/phil65/evented/commits)
20
+ [![Github release date](https://img.shields.io/github/release-date/phil65/evented)](https://github.com/phil65/evented/releases)
21
+ [![Github language count](https://img.shields.io/github/languages/count/phil65/evented)](https://github.com/phil65/evented)
22
+ [![Github commits this month](https://img.shields.io/github/commit-activity/m/phil65/evented)](https://github.com/phil65/evented)
23
+ [![Package status](https://codecov.io/gh/phil65/evented/branch/main/graph/badge.svg)](https://codecov.io/gh/phil65/evented/)
24
+ [![PyUp](https://pyup.io/repos/github/phil65/evented/shield.svg)](https://pyup.io/repos/github/phil65/evented/)
25
+
26
+ [Read the documentation!](https://phil65.github.io/evented/)
@@ -0,0 +1,273 @@
1
+ [project]
2
+ name = "evented"
3
+ version = "1.0.3"
4
+ description = "Event emitters."
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [
10
+ { name = "Philipp Temminghoff", email = "philipptemminghoff@googlemail.com" },
11
+ ]
12
+ keywords = []
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Framework :: Pydantic",
16
+ "Framework :: Pydantic :: 2",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Topic :: Documentation",
25
+ "Topic :: Software Development",
26
+ "Topic :: Utilities",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = [
30
+ "pydantic",
31
+ "schemez",
32
+ # Only add below (Copier)
33
+ ]
34
+
35
+ [project.urls]
36
+ "Code coverage" = "https://app.codecov.io/gh/phil65/evented"
37
+ Discussions = "https://github.com/phil65/evented/discussions"
38
+ Documentation = "https://phil65.github.io/evented/"
39
+ Issues = "https://github.com/phil65/evented/issues"
40
+ Source = "https://github.com/phil65/evented"
41
+
42
+ [project.optional-dependencies]
43
+ events = [
44
+ "watchfiles",
45
+ "aioimaplib>=2.0.1",
46
+ "croniter>=6.0.0",
47
+ "fastapi",
48
+ ]
49
+
50
+ [dependency-groups]
51
+ dev = [
52
+ "devtools",
53
+ "pyreadline3",
54
+ "pytest",
55
+ "pytest-cov",
56
+ # Only add below (Copier)
57
+ ]
58
+ benchmark = ["pyinstrument"]
59
+ docs = [
60
+ "mkdocs-material",
61
+ "mkdocs-mknodes",
62
+ # Only add below (Copier)
63
+ ]
64
+ lint = [
65
+ "mypy; python_version >= '3.14'",
66
+ "mypy[faster-cache]; python_version < '3.14'",
67
+ "ruff",
68
+ # Only add below (Copier)
69
+ ]
70
+
71
+ [build-system]
72
+ requires = ["uv_build>=0.8.22"]
73
+ build-backend = "uv_build"
74
+
75
+ [tool.coverage.report]
76
+ exclude_lines = [
77
+ "pragma: no cover",
78
+ "if TYPE_CHECKING:",
79
+ "@overload",
80
+ "except ImportError",
81
+ 'if __name__ == "__main__":',
82
+ ]
83
+
84
+ [tool.mknodes]
85
+ allowed-commit-types = [
86
+ "fix",
87
+ "feat",
88
+ "refactor",
89
+ "docs",
90
+ "test",
91
+ "build",
92
+ "chore",
93
+ ]
94
+ docstring-style = "google"
95
+
96
+ [tool.mypy]
97
+ python_version = "3.13"
98
+ disable_error_code = ["misc", "import"]
99
+ pretty = true
100
+ check_untyped_defs = true
101
+ exclude = ["venv/", ".venv/", "tests/"]
102
+ plugins = ["pydantic.mypy"]
103
+
104
+ [tool.pyright]
105
+ venvPath = "."
106
+ venv = ".venv"
107
+ pythonVersion = "3.13"
108
+ pythonPlatform = "All"
109
+ typeCheckingMode = "basic"
110
+ deprecateTypingAliases = true
111
+ reportMissingTypeStubs = false
112
+ reportUnusedCallResult = false
113
+ reportUnknownVariableType = false
114
+ reportAny = false
115
+ reportImplicitOverride = false
116
+ reportUnusedFunction = false
117
+ reportImplicitStringConcatenation = false
118
+ reportIgnoreCommentWithoutRule = false
119
+ reportUnannotatedClassAttribute = false
120
+ reportSelfClsParameterName = false
121
+ reportPrivateImportUsage = false
122
+
123
+ [tool.pytest.ini_options]
124
+ log_cli = true
125
+ log_date_format = "%Y-%m-%d %H:%M:%S"
126
+ log_format = "%(asctime)s %(levelname)s %(message)s"
127
+ testpaths = "tests/"
128
+ asyncio_mode = "auto"
129
+
130
+ [tool.ruff]
131
+ line-length = 90
132
+ extend-exclude = ["docs"]
133
+ target-version = "py313"
134
+
135
+ [tool.ruff.lint]
136
+ future-annotations = true
137
+ select = [
138
+ "A", # Flake8-builtins
139
+ # "ANN", # Flake8-Annotations
140
+ # "ASYNC", # Flake8-Async
141
+ # "ARG", # # Flake8-Unused-Arguments
142
+ "B", # flake8-bugbear
143
+ "BLE", # Flake8-blind-except
144
+ "C",
145
+ "C4", # flake8-comprehensions
146
+ # "C90", # MCCabe
147
+ "COM", # Flake8-commas
148
+ # "CPY", # Copyright-related rules
149
+ "D", # PyDocStyle
150
+ # "DTZ", # Flake8- Datetimez
151
+ "E", # PyCodeStyle Error
152
+ "EM", # flake8-errmsg
153
+ # "ERA", # Eradicate
154
+ "EXE", # flake8-executable
155
+ "F", # PyFlakes
156
+ "FA", # flake8-future-annotations
157
+ # "FBT", # flake8-boolean-trap
158
+ # "FIX", # flake8-fixme
159
+ "FLY", # flynt
160
+ "G", # flake8-logging-format
161
+ "I", # ISort
162
+ "ICN", # Flake8-import-conventions
163
+ "INP", # flake8-no-pep420
164
+ "INT", # flake8-gettext
165
+ "ISC", # flake8-implicit-str-concat
166
+ "N", # pep8-naming
167
+ # "NPY", # numpy-specific rules
168
+ # "PD", # pandas-vet
169
+ "PERF", # perflint
170
+ # "PGH", # pygrep-hooks
171
+ "PIE", # flake8-pie
172
+ "PLE", # PyLint Error
173
+ "PLC", # PyLint convention
174
+ # "PLW", # PyLint Warning
175
+ "PLR", # PyLint refactor
176
+ "PT", # flake8-pytest-style
177
+ "PTH", # flake8-use-pathlib
178
+ "PYI", # flake8-pyi
179
+ "Q", # flake8-quotes
180
+ "RET", # flake8-return
181
+ "RSE", # flake8-raise
182
+ "RUF", # ruff-specific rules
183
+ # "S", # flake8-bandit
184
+ "SIM", # flake8-simplify
185
+ "SLF", # flake8-self
186
+ "SLOT", # flake8-slots
187
+ # "T",
188
+ # "TD", # flake8-todos
189
+ "T10", # flake8-debugger
190
+ # "T20", # flake8-print
191
+ "TC", # flake8-type-checking
192
+ "TID", # flake8-tidy-imports
193
+ "TRY", # tryceratops
194
+ "UP", # PyUpgrade
195
+ "W", # PyCodeStyle warning
196
+ "YTT", # flake8-2020
197
+ ]
198
+ ignore = [
199
+ "C408", # Unnecessary {obj_type} call (rewrite as a literal)
200
+ "B905", # zip() without an explicit strict= parameter
201
+ "C901", # {name} is too complex ({complexity} > {max_complexity})
202
+ "COM812",
203
+ # "CPY001", # Missing copyright notice at top of file
204
+ "D100", # Missing docstring in public module
205
+ "D101", # Missing docstring in public class
206
+ "D102", # Missing docstring in public method
207
+ "D103", # Missing docstring in public function
208
+ "D104", # Missing docstring in public package
209
+ "D105", # Missing docstring in magic method
210
+ "D106", # Missing docstring in public nested class
211
+ "D107", # Missing docstring in __init__
212
+ "D203", # 1 blank line required before class docstring
213
+ "D204", # 1 blank line required after class docstring
214
+ "D213", # Multi-line docstring summary should start at the second line
215
+ "D215", # Section underline is over-indented ("{name}")
216
+ "D400", # First line should end with a period
217
+ "D401", # First line of docstring should be in imperative mood: "{first_line}"
218
+ "D404", # First word of the docstring should not be "This"
219
+ "D406", # Section name should end with a newline ("{name}")
220
+ "D407", # Missing dashed underline after section ("{name}")
221
+ "D408", # Section underline should be in the line following the section's name ("{name}")
222
+ "D409", # Section underline should match the length of its name ("{name}")
223
+ "D413", # Missing blank line after last section ("{name}")
224
+ "ISC001",
225
+ "PLC0415",
226
+ "PLR0912", # Too many branches
227
+ "PLR0913", # Too many arguments to function call
228
+ "PLR0915", # Too many statements
229
+ # "PLR2004", # Magic values instead of named consts
230
+ "SLF001", # Private member accessed
231
+ "TRY003", # Avoid specifying long messages outside the exception class
232
+ "TC006", # runtime-cast-value
233
+ ]
234
+
235
+ [tool.ruff.lint.flake8-quotes]
236
+ docstring-quotes = "double"
237
+
238
+ [tool.ruff.lint.flake8-type-checking]
239
+ runtime-evaluated-base-classes = [
240
+ "pydantic.BaseModel",
241
+ "sqlalchemy.orm.DeclarativeBase",
242
+ "schemez.Schema",
243
+ "sqlmodel.SQLModel",
244
+ ]
245
+ runtime-evaluated-decorators = [
246
+ "pydantic.validate_call",
247
+ "fastapi.FastAPI.get",
248
+ "fastapi.FastAPI.post",
249
+ "fastmcp.FastMCP.tool",
250
+ "typer.Typer.command",
251
+ ]
252
+
253
+ [tool.ruff.lint.isort]
254
+ lines-after-imports = 2
255
+ # lines-between-types = 1
256
+ # atomic = true
257
+ force-sort-within-sections = true
258
+ combine-as-imports = true
259
+
260
+ [tool.ruff.lint.per-file-ignores]
261
+ "__init__.py" = ["E402", "I001"]
262
+ "scripts/*" = ["INP001"]
263
+ "*tests/*" = ["D100"]
264
+
265
+ [tool.ruff.format]
266
+ preview = true
267
+
268
+ [tool.ty.environment]
269
+ python-version = "3.13"
270
+ python-platform = "all"
271
+
272
+ [tool.uv]
273
+ default-groups = ["dev", "lint", "docs"]
@@ -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
+ ]
@@ -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)
@@ -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
+ ]
@@ -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)
@@ -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)}"
@@ -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)
@@ -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}")
File without changes
@@ -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)