agents-framework 0.3.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.
- agents_framework-0.3.0.dist-info/METADATA +1364 -0
- agents_framework-0.3.0.dist-info/RECORD +50 -0
- agents_framework-0.3.0.dist-info/WHEEL +5 -0
- agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
- agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
- agents_framework-0.3.0.dist-info/top_level.txt +1 -0
- framework/__init__.py +0 -0
- framework/__main__.py +9 -0
- framework/action_page.py +1102 -0
- framework/approval_buttons.py +775 -0
- framework/approvals.py +678 -0
- framework/calendar_card.py +276 -0
- framework/cli.py +273 -0
- framework/codex_llm.py +401 -0
- framework/config.py +126 -0
- framework/drafter.py +263 -0
- framework/interfaces.py +96 -0
- framework/llm.py +744 -0
- framework/plugins/__init__.py +147 -0
- framework/plugins/agentmail_source.py +355 -0
- framework/plugins/approval_destination.py +478 -0
- framework/plugins/command_action.py +248 -0
- framework/plugins/digest_destination.py +546 -0
- framework/plugins/email_destination.py +248 -0
- framework/plugins/fanout_destination.py +160 -0
- framework/plugins/github_org_source.py +226 -0
- framework/plugins/github_releases_source.py +420 -0
- framework/plugins/ics_source.py +594 -0
- framework/plugins/llm_scorer.py +411 -0
- framework/plugins/multi_source.py +241 -0
- framework/plugins/reddit_source.py +625 -0
- framework/plugins/regex_scorer.py +93 -0
- framework/plugins/rss_source.py +346 -0
- framework/plugins/signal_destination.py +133 -0
- framework/plugins/slack_destination.py +461 -0
- framework/plugins/slack_draft_action.py +137 -0
- framework/plugins/slack_post_action.py +65 -0
- framework/plugins/slack_workspace_source.py +992 -0
- framework/plugins/twitter_action.py +210 -0
- framework/plugins/websearch_source.py +761 -0
- framework/plugins/wordpress_action.py +413 -0
- framework/proposals.py +246 -0
- framework/registry.py +166 -0
- framework/runlog.py +125 -0
- framework/runner.py +243 -0
- framework/schedule.py +571 -0
- framework/signal_messenger.py +1418 -0
- framework/slack.py +801 -0
- framework/state.py +39 -0
- framework/templating.py +76 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Plugin implementations, imported for their registration side effects.
|
|
2
|
+
|
|
3
|
+
Each concrete plugin module calls `@register_source/scorer/destination(...)`
|
|
4
|
+
at import time. Add a new plugin by adding a row to `_PLUGIN_MODULES` below,
|
|
5
|
+
mapping its module name to the `type:` names it registers.
|
|
6
|
+
|
|
7
|
+
Wave 1 lands the first real plugins:
|
|
8
|
+
- `reddit` source (issue #2)
|
|
9
|
+
- `slack` destination (issue #3)
|
|
10
|
+
- `regex` scorer (issue #4)
|
|
11
|
+
- `agentmail` source (issue #12)
|
|
12
|
+
|
|
13
|
+
Later additions:
|
|
14
|
+
- `github-org` source (issue #13)
|
|
15
|
+
- `digest` destination (issues #13, #20) - summarizes a run into one message
|
|
16
|
+
- `slack-workspace` source (issue #19)
|
|
17
|
+
- `ics` source (issue #22)
|
|
18
|
+
- `llm` scorer (issue #9) - scores through the model waterfall
|
|
19
|
+
- `approval` destination and `slack-post` action (issue #21)
|
|
20
|
+
- `twitter-post` and `command` actions (issue #48)
|
|
21
|
+
- `slack-draft` action (issue #76) - the grounded drafter, run on approval
|
|
22
|
+
- `multi` source, `fanout` destination, `websearch` source (issue #57) - the
|
|
23
|
+
composites, and a search engine as a source
|
|
24
|
+
- `signal-messenger` destination (issue #120) - Signal, through the
|
|
25
|
+
`signal-cli` binary against an account this deployment owns
|
|
26
|
+
- `rss` source (issue #149) - a feed as a source, so something else can watch
|
|
27
|
+
continuously and we read what it found
|
|
28
|
+
- `email` destination (issue #148) - one run, one mail, through AgentMail
|
|
29
|
+
|
|
30
|
+
Why a table rather than eight import statements (issue #39). Importing every
|
|
31
|
+
plugin unconditionally means one plugin's optional third-party dependency can
|
|
32
|
+
break the import of all of them, and therefore every agent - including agents
|
|
33
|
+
that never touch that plugin. Merging #35 did exactly that: `ics_source` does
|
|
34
|
+
`import icalendar` at module scope, the live venv did not have `icalendar`, and
|
|
35
|
+
the Reddit agent, which has nothing to do with calendars, died at startup.
|
|
36
|
+
|
|
37
|
+
So `import_all()` imports each module in isolation and tolerates the failure of
|
|
38
|
+
an *external* import, recording which module failed and why.
|
|
39
|
+
|
|
40
|
+
What counts as external is the whole distinction, and `ImportError` alone is too
|
|
41
|
+
broad a test for it. It covers a missing third-party package, which is the
|
|
42
|
+
recoverable case, but it equally covers `cannot import name 'register_sourcee'
|
|
43
|
+
from 'framework.registry'` and a plugin importing a sibling module that no
|
|
44
|
+
longer exists - a plugin broken by a refactor, not a plugin missing an optional
|
|
45
|
+
dependency. Tolerating those would let a real regression degrade into a warning
|
|
46
|
+
line for every agent that happens not to use the broken plugin, which is the
|
|
47
|
+
failure class this repo keeps fighting.
|
|
48
|
+
|
|
49
|
+
`ImportError.name` separates them: it holds the module that could not be
|
|
50
|
+
imported, on both `ModuleNotFoundError` and the `cannot import name X from Y`
|
|
51
|
+
form. Anything under `framework` is our own code and re-raises; anything else
|
|
52
|
+
is an optional dependency and is recorded. A missing `name` re-raises too, since
|
|
53
|
+
an `ImportError` too unusual to classify is the wrong thing to swallow.
|
|
54
|
+
|
|
55
|
+
Nor does this catch `Exception`: a plugin whose module-level code raises
|
|
56
|
+
anything else is broken for a different reason and should stay just as loud.
|
|
57
|
+
|
|
58
|
+
Tolerating the failure here is only half of it. The registry turns a config
|
|
59
|
+
that names a failed plugin into an immediate, specific startup error (see
|
|
60
|
+
`framework/registry.py`), so tolerance never becomes silence for an agent that
|
|
61
|
+
actually asked for the plugin.
|
|
62
|
+
|
|
63
|
+
The table is what makes that error name the plugin rather than just the module:
|
|
64
|
+
a module that fails to import never reaches its `@register_source` call, so
|
|
65
|
+
after the failure nothing else in the process knows which `type:` names it was
|
|
66
|
+
going to claim. That knowledge has to be declared out-of-band, here.
|
|
67
|
+
"""
|
|
68
|
+
from __future__ import annotations
|
|
69
|
+
|
|
70
|
+
import importlib
|
|
71
|
+
from dataclasses import dataclass
|
|
72
|
+
|
|
73
|
+
_PLUGIN_MODULES: dict[str, tuple[str, ...]] = {
|
|
74
|
+
"agentmail_source": ("agentmail",),
|
|
75
|
+
"approval_destination": ("approval",),
|
|
76
|
+
"command_action": ("command",),
|
|
77
|
+
"digest_destination": ("digest",),
|
|
78
|
+
"email_destination": ("email",),
|
|
79
|
+
"fanout_destination": ("fanout",),
|
|
80
|
+
"github_org_source": ("github-org",),
|
|
81
|
+
"github_releases_source": ("github-releases",),
|
|
82
|
+
"ics_source": ("ics",),
|
|
83
|
+
"llm_scorer": ("llm",),
|
|
84
|
+
"multi_source": ("multi",),
|
|
85
|
+
"reddit_source": ("reddit",),
|
|
86
|
+
"regex_scorer": ("regex",),
|
|
87
|
+
"rss_source": ("rss",),
|
|
88
|
+
"signal_destination": ("signal-messenger",),
|
|
89
|
+
"slack_destination": ("slack",),
|
|
90
|
+
"slack_draft_action": ("slack-draft",),
|
|
91
|
+
"slack_post_action": ("slack-post",),
|
|
92
|
+
"slack_workspace_source": ("slack-workspace",),
|
|
93
|
+
"twitter_action": ("twitter-post",),
|
|
94
|
+
"websearch_source": ("websearch",),
|
|
95
|
+
"wordpress_action": ("wordpress-publish",),
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(frozen=True)
|
|
100
|
+
class PluginImportFailure:
|
|
101
|
+
"""One plugin module that could not be imported, and why."""
|
|
102
|
+
|
|
103
|
+
module: str
|
|
104
|
+
types: tuple[str, ...]
|
|
105
|
+
error: ImportError
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def qualified_module(self) -> str:
|
|
109
|
+
retval = f"{__name__}.{self.module}"
|
|
110
|
+
return retval
|
|
111
|
+
|
|
112
|
+
def reason(self) -> str:
|
|
113
|
+
retval = f"{type(self.error).__name__}: {self.error}"
|
|
114
|
+
return retval
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _is_external(exc: ImportError) -> bool:
|
|
118
|
+
"""Did this `ImportError` come from a dependency outside the framework?
|
|
119
|
+
|
|
120
|
+
Only those are tolerable. An import that fails inside `framework` means the
|
|
121
|
+
plugin itself is broken, and it propagates.
|
|
122
|
+
"""
|
|
123
|
+
origin = exc.name or ""
|
|
124
|
+
retval = bool(origin) and not origin.startswith("framework")
|
|
125
|
+
return retval
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def import_all() -> dict[str, PluginImportFailure]:
|
|
129
|
+
"""Import every plugin module; return failures keyed by `type:` name.
|
|
130
|
+
|
|
131
|
+
A module that imports cleanly has registered its factories by the time this
|
|
132
|
+
returns. A module that failed on an external dependency contributes one
|
|
133
|
+
entry per `type:` name it would have registered, so the registry can name
|
|
134
|
+
the plugin the config asked for rather than only the module that broke.
|
|
135
|
+
Any other import failure propagates.
|
|
136
|
+
"""
|
|
137
|
+
retval: dict[str, PluginImportFailure] = {}
|
|
138
|
+
for module, types in _PLUGIN_MODULES.items():
|
|
139
|
+
try:
|
|
140
|
+
importlib.import_module(f"{__name__}.{module}")
|
|
141
|
+
except ImportError as exc:
|
|
142
|
+
if not _is_external(exc):
|
|
143
|
+
raise
|
|
144
|
+
failure = PluginImportFailure(module=module, types=types, error=exc)
|
|
145
|
+
for type_name in types:
|
|
146
|
+
retval[type_name] = failure
|
|
147
|
+
return retval
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""AgentMail source — email-inbox Source implementation (issue #12).
|
|
2
|
+
|
|
3
|
+
Turns messages in an AgentMail inbox into Signals. Email is how several signal
|
|
4
|
+
types arrive with no usable API behind them: job-board notifications, community
|
|
5
|
+
digests, calendar invitations. Forward them to an inbox and this becomes the
|
|
6
|
+
ingestion path.
|
|
7
|
+
|
|
8
|
+
Credentials come from the environment, never config. The API key's env var is
|
|
9
|
+
named by `api_key_env` (default `AGENTMAIL_API_KEY`), matching the way the Slack
|
|
10
|
+
destination names its `webhook_env`, so an operator can run two agents against
|
|
11
|
+
different credentials without editing plugin code.
|
|
12
|
+
|
|
13
|
+
## Bodies are not in the list response
|
|
14
|
+
|
|
15
|
+
Measured against a live inbox, and the reason this plugin is not a thin wrapper:
|
|
16
|
+
|
|
17
|
+
- `GET /v0/inboxes/{inbox}/messages` returns `{count, limit, next_page_token,
|
|
18
|
+
messages}`, and each message carries `message_id`, `subject`, `from`, `to`,
|
|
19
|
+
`preview`, `timestamp`, `thread_id`, `labels` — but **no body and no URL**.
|
|
20
|
+
`preview` is capped at 200 characters.
|
|
21
|
+
- `GET /v0/inboxes/{inbox}/messages/{message_id}` additionally returns `text`,
|
|
22
|
+
`html` and `extracted_text`. On a sample message that was 1553 characters of
|
|
23
|
+
text versus a 200-character preview.
|
|
24
|
+
|
|
25
|
+
Scoring a truncated preview silently changes results — a keyword in paragraph
|
|
26
|
+
three simply is not there to match. So `fetch_body` (default on) hydrates each
|
|
27
|
+
message that passes the filters with a second request. Filtering happens
|
|
28
|
+
*before* hydration, so a shared inbox costs one request plus one per keeper,
|
|
29
|
+
not one per message.
|
|
30
|
+
|
|
31
|
+
Set `fetch_body: false` for high-volume inboxes where the subject line is
|
|
32
|
+
genuinely enough.
|
|
33
|
+
|
|
34
|
+
AgentMail exposes no permalink field, so `Signal.url` is empty; consumers should
|
|
35
|
+
render `meta.subject` and `meta.from` instead of relying on a link.
|
|
36
|
+
|
|
37
|
+
## Trashed messages are hidden by default
|
|
38
|
+
|
|
39
|
+
The list endpoint omits anything labelled `trash` unless `include_trash=true` is
|
|
40
|
+
passed. That label can be applied by something outside this repo — another
|
|
41
|
+
client on the same inbox, a provider-side rule — so an inbox can look empty
|
|
42
|
+
while holding everything an agent wants. Measured on a live inbox: the default
|
|
43
|
+
listing returned 1 message and `include_trash: true` returned 50, 49 of them
|
|
44
|
+
labelled `trash`.
|
|
45
|
+
|
|
46
|
+
`include_trash` (default `false`) is therefore a config key, not a heuristic.
|
|
47
|
+
Nothing here guesses that a quiet inbox means trashed mail; an operator seeing
|
|
48
|
+
an unexpectedly empty inbox checks the label and sets the key. Trashed messages
|
|
49
|
+
keep their labels in `meta.labels`, so a scorer can still tell them apart.
|
|
50
|
+
|
|
51
|
+
## Splitting one inbox between two agents
|
|
52
|
+
|
|
53
|
+
`from_contains` / `subject_contains` include; `from_excludes` /
|
|
54
|
+
`subject_excludes` exclude, and excludes win (issue #156). That precedence is
|
|
55
|
+
what makes the real case expressible in one config: one agent takes two named
|
|
56
|
+
senders, another takes everything else from the same domain.
|
|
57
|
+
|
|
58
|
+
"from_contains": ["notifications.example"],
|
|
59
|
+
"from_excludes": ["dm-reply@notifications.example"]
|
|
60
|
+
|
|
61
|
+
Listing the senders to include instead is a list nobody can keep correct -- it
|
|
62
|
+
needs editing whenever the sender adds a notification type, and the failure is
|
|
63
|
+
silent, because the mail simply stops matching.
|
|
64
|
+
|
|
65
|
+
**`limit` counts messages that match, not messages that exist.** The filters
|
|
66
|
+
are applied while paging rather than to a window of raw mail taken first.
|
|
67
|
+
Taking the newest `limit` messages and filtering afterwards means a burst of
|
|
68
|
+
mail this agent excludes can fill the window and push everything it wants out
|
|
69
|
+
of view — and because each run starts from the newest page again, the eligible
|
|
70
|
+
mail stays invisible for as long as the burst continues rather than arriving
|
|
71
|
+
late. That is precisely the shape this split creates: one agent deliberately
|
|
72
|
+
excludes most of a high-volume sender.
|
|
73
|
+
|
|
74
|
+
`max_scan` bounds the work, since "page until you find `limit` matches" has no
|
|
75
|
+
natural end on an inbox where nothing matches. Reaching it without filling the
|
|
76
|
+
limit prints a loud line rather than returning a quietly short run.
|
|
77
|
+
|
|
78
|
+
**Two agents on one inbox need different `agent` names.** Dedupe state is keyed
|
|
79
|
+
per agent, so sharing a name means each marks the other's mail seen and both
|
|
80
|
+
see half their mail, intermittently, depending on which ran last.
|
|
81
|
+
|
|
82
|
+
**The two configs are coupled, and nothing enforces it.** One agent's includes
|
|
83
|
+
and the other's excludes describe the same partition from opposite sides, so a
|
|
84
|
+
sender added to one must be added to the other in the same change. Miss it and
|
|
85
|
+
that sender's mail appears in both agents' output -- scored twice, delivered
|
|
86
|
+
twice, and marked seen by each of them independently. A list of senders that
|
|
87
|
+
was never verified complete is the usual way this happens: the split looks
|
|
88
|
+
right until the sender adds a notification type nobody listed.
|
|
89
|
+
|
|
90
|
+
**Exclude the senders that carry credentials, even when something upstream
|
|
91
|
+
already drops them.** Sign-in codes, password resets and verification links
|
|
92
|
+
have no business reaching a scorer, a model, a digest or a channel, and an
|
|
93
|
+
upstream mail filter is editable by someone who will not be thinking about this
|
|
94
|
+
agent when they edit it. An exclude here costs one config line and fails safe;
|
|
95
|
+
relying on the forwarding rule fails open, silently, at the moment someone
|
|
96
|
+
widens it.
|
|
97
|
+
|
|
98
|
+
## Pagination
|
|
99
|
+
|
|
100
|
+
The listing is paged: a response carries `next_page_token` when more messages
|
|
101
|
+
match, and `page_token` continues from it. `fetch()` follows that until it has
|
|
102
|
+
`limit` messages or the pages run out, so `limit` bounds the run rather than the
|
|
103
|
+
page. Unknown query parameters are ignored by the API rather than rejected,
|
|
104
|
+
which is why the token parameter is spelled exactly `page_token`. A response
|
|
105
|
+
that is not an object with a `messages` list raises: a source that cannot read
|
|
106
|
+
its own API must not report an empty inbox.
|
|
107
|
+
|
|
108
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
109
|
+
"""
|
|
110
|
+
from __future__ import annotations
|
|
111
|
+
|
|
112
|
+
import os
|
|
113
|
+
import sys
|
|
114
|
+
from urllib.parse import quote
|
|
115
|
+
|
|
116
|
+
import requests
|
|
117
|
+
|
|
118
|
+
from framework.interfaces import Signal, Source
|
|
119
|
+
from framework.registry import register_source
|
|
120
|
+
|
|
121
|
+
_API_BASE = "https://api.agentmail.to/v0"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class AgentMailSource:
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
inbox: str,
|
|
128
|
+
api_key: str,
|
|
129
|
+
limit: int = 50,
|
|
130
|
+
from_contains: list[str] | None = None,
|
|
131
|
+
subject_contains: list[str] | None = None,
|
|
132
|
+
from_excludes: list[str] | None = None,
|
|
133
|
+
subject_excludes: list[str] | None = None,
|
|
134
|
+
fetch_body: bool = True,
|
|
135
|
+
include_trash: bool = False,
|
|
136
|
+
label: str = "agentmail",
|
|
137
|
+
timeout: int = 30,
|
|
138
|
+
page_size: int = 50,
|
|
139
|
+
max_scan: int = 0,
|
|
140
|
+
):
|
|
141
|
+
self.inbox = inbox
|
|
142
|
+
self.limit = limit
|
|
143
|
+
self.include_trash = include_trash
|
|
144
|
+
# An inbox is often shared across agents, so filter to what this one
|
|
145
|
+
# cares about. Empty filters accept everything.
|
|
146
|
+
self.from_contains = [s.lower() for s in (from_contains or [])]
|
|
147
|
+
self.subject_contains = [s.lower() for s in (subject_contains or [])]
|
|
148
|
+
# Excludes exist because the includes cannot say "this domain except
|
|
149
|
+
# these two senders", which is how a shared inbox actually gets split:
|
|
150
|
+
# one agent owns a narrow slice, another owns the rest (issue #156).
|
|
151
|
+
# Writing out the senders to include instead is a list nobody can keep
|
|
152
|
+
# correct -- it needs editing whenever the sender adds a notification
|
|
153
|
+
# type, and the failure is silent, because the mail simply stops
|
|
154
|
+
# matching.
|
|
155
|
+
self.from_excludes = [s.lower() for s in (from_excludes or [])]
|
|
156
|
+
self.subject_excludes = [s.lower() for s in (subject_excludes or [])]
|
|
157
|
+
self.fetch_body = fetch_body
|
|
158
|
+
self.label = label
|
|
159
|
+
self.timeout = timeout
|
|
160
|
+
self.page_size = max(1, page_size)
|
|
161
|
+
# Ten pages' worth by default: enough that an ordinary burst of
|
|
162
|
+
# excluded mail does not hide an eligible message, bounded so that an
|
|
163
|
+
# inbox where nothing matches cannot page forever.
|
|
164
|
+
self.max_scan = max_scan if max_scan > 0 else max(self.limit * 10, 200)
|
|
165
|
+
self._api_key = api_key
|
|
166
|
+
|
|
167
|
+
@property
|
|
168
|
+
def _headers(self) -> dict[str, str]:
|
|
169
|
+
retval = {"Authorization": f"Bearer {self._api_key}"}
|
|
170
|
+
return retval
|
|
171
|
+
|
|
172
|
+
def _matches(self, sender: str, subject: str) -> bool:
|
|
173
|
+
"""Whether this message is for this agent. Excludes win over includes.
|
|
174
|
+
|
|
175
|
+
Exclude-last is the only precedence that makes the live case
|
|
176
|
+
expressible in one config -- everything from a domain except two of its
|
|
177
|
+
senders -- and so it is the only one worth having.
|
|
178
|
+
"""
|
|
179
|
+
sender_l, subject_l = sender.lower(), subject.lower()
|
|
180
|
+
if self.from_contains and not any(f in sender_l for f in self.from_contains):
|
|
181
|
+
return False
|
|
182
|
+
if self.subject_contains and not any(s in subject_l for s in self.subject_contains):
|
|
183
|
+
return False
|
|
184
|
+
if any(f in sender_l for f in self.from_excludes):
|
|
185
|
+
return False
|
|
186
|
+
if any(s in subject_l for s in self.subject_excludes):
|
|
187
|
+
return False
|
|
188
|
+
return True
|
|
189
|
+
|
|
190
|
+
def _list_messages(self) -> list[dict]:
|
|
191
|
+
"""Up to `limit` messages that match the filters, paging until found.
|
|
192
|
+
|
|
193
|
+
Filtering happens HERE, inside the paging loop, and not in `fetch()`
|
|
194
|
+
afterwards. See the module docstring: filtering a window of raw mail
|
|
195
|
+
taken from the newest page lets excluded mail crowd out everything this
|
|
196
|
+
agent wants, permanently rather than temporarily.
|
|
197
|
+
"""
|
|
198
|
+
messages: list[dict] = []
|
|
199
|
+
scanned = 0
|
|
200
|
+
page_token = ""
|
|
201
|
+
while len(messages) < self.limit and scanned < self.max_scan:
|
|
202
|
+
params: dict[str, str] = {
|
|
203
|
+
"limit": str(min(self.page_size, self.max_scan - scanned))
|
|
204
|
+
}
|
|
205
|
+
if self.include_trash:
|
|
206
|
+
params["include_trash"] = "true"
|
|
207
|
+
if page_token:
|
|
208
|
+
params["page_token"] = page_token
|
|
209
|
+
resp = requests.get(
|
|
210
|
+
f"{_API_BASE}/inboxes/{self.inbox}/messages",
|
|
211
|
+
headers=self._headers,
|
|
212
|
+
params=params,
|
|
213
|
+
timeout=self.timeout,
|
|
214
|
+
)
|
|
215
|
+
resp.raise_for_status()
|
|
216
|
+
payload = resp.json()
|
|
217
|
+
# Fail loud on a shape this code cannot read: a silently empty run
|
|
218
|
+
# is the failure mode this repo keeps paying for, and an API that
|
|
219
|
+
# changed shape is exactly when a source stops seeing anything.
|
|
220
|
+
if not isinstance(payload, dict) or not isinstance(payload.get("messages"), list):
|
|
221
|
+
raise RuntimeError(
|
|
222
|
+
f"agentmail source: unexpected response from the messages endpoint for "
|
|
223
|
+
f"{self.inbox}: expected an object with a 'messages' list, got "
|
|
224
|
+
f"{type(payload).__name__} with keys "
|
|
225
|
+
f"{sorted(payload) if isinstance(payload, dict) else 'n/a'}"
|
|
226
|
+
)
|
|
227
|
+
page = payload["messages"]
|
|
228
|
+
scanned += len(page)
|
|
229
|
+
for message in page:
|
|
230
|
+
if not isinstance(message, dict):
|
|
231
|
+
continue
|
|
232
|
+
sender = str(message.get("from") or "")
|
|
233
|
+
subject = str(message.get("subject") or "")
|
|
234
|
+
if not self._matches(sender, subject):
|
|
235
|
+
continue
|
|
236
|
+
messages.append(message)
|
|
237
|
+
if len(messages) >= self.limit:
|
|
238
|
+
break
|
|
239
|
+
page_token = payload.get("next_page_token") or ""
|
|
240
|
+
if not page_token or not page:
|
|
241
|
+
break
|
|
242
|
+
|
|
243
|
+
# Loud, because the alternative is a short run that looks like a quiet
|
|
244
|
+
# inbox -- the failure this source keeps being hardened against.
|
|
245
|
+
if len(messages) < self.limit and scanned >= self.max_scan and page_token:
|
|
246
|
+
print(
|
|
247
|
+
f"agentmail source: stopped after scanning {scanned} message(s) in "
|
|
248
|
+
f"{self.inbox} with {len(messages)} match(es), and more remain. Mail this "
|
|
249
|
+
f"agent wants may be older than that window: raise 'max_scan', or narrow "
|
|
250
|
+
f"the filters.",
|
|
251
|
+
file=sys.stderr,
|
|
252
|
+
)
|
|
253
|
+
retval = messages[: self.limit]
|
|
254
|
+
return retval
|
|
255
|
+
|
|
256
|
+
def _body_for(self, message_id: str) -> str:
|
|
257
|
+
"""Full text for one message. Message ids contain '<', '>' and '@', so
|
|
258
|
+
they must be percent-encoded into the path."""
|
|
259
|
+
resp = requests.get(
|
|
260
|
+
f"{_API_BASE}/inboxes/{self.inbox}/messages/{quote(message_id, safe='')}",
|
|
261
|
+
headers=self._headers,
|
|
262
|
+
timeout=self.timeout,
|
|
263
|
+
)
|
|
264
|
+
resp.raise_for_status()
|
|
265
|
+
msg = resp.json()
|
|
266
|
+
retval = msg.get("extracted_text") or msg.get("text") or msg.get("preview") or ""
|
|
267
|
+
return retval
|
|
268
|
+
|
|
269
|
+
def fetch(self) -> list[Signal]:
|
|
270
|
+
signals: list[Signal] = []
|
|
271
|
+
for msg in self._list_messages():
|
|
272
|
+
message_id = msg.get("message_id") or msg.get("id")
|
|
273
|
+
if not message_id:
|
|
274
|
+
continue
|
|
275
|
+
subject = msg.get("subject", "") or ""
|
|
276
|
+
sender = msg.get("from", "") or ""
|
|
277
|
+
# No _matches() here: _list_messages has already applied it, while
|
|
278
|
+
# paging, so that excluded mail cannot consume the window.
|
|
279
|
+
body = msg.get("preview", "") or ""
|
|
280
|
+
if self.fetch_body:
|
|
281
|
+
body = self._body_for(str(message_id)) or body
|
|
282
|
+
|
|
283
|
+
signals.append(
|
|
284
|
+
Signal(
|
|
285
|
+
id=str(message_id),
|
|
286
|
+
text=f"{subject}\n\n{body}".strip(),
|
|
287
|
+
url="", # AgentMail exposes no permalink
|
|
288
|
+
source=self.label,
|
|
289
|
+
meta={
|
|
290
|
+
"from": sender,
|
|
291
|
+
"to": msg.get("to", ""),
|
|
292
|
+
"subject": subject,
|
|
293
|
+
"timestamp": msg.get("timestamp", ""),
|
|
294
|
+
"thread_id": msg.get("thread_id", ""),
|
|
295
|
+
"labels": msg.get("labels", []),
|
|
296
|
+
},
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
retval = signals
|
|
300
|
+
return retval
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _filter_list(cfg: dict, key: str) -> list[str]:
|
|
304
|
+
"""One filter list from config, validated.
|
|
305
|
+
|
|
306
|
+
Unchecked, two ordinary-looking configurations silently drop mail. A bare
|
|
307
|
+
string is iterable, so `"someone@example.test"` becomes a list of single
|
|
308
|
+
characters and the entry `"@"` then excludes every sender with an address.
|
|
309
|
+
A blank entry is worse: the empty string is a substring of everything, so
|
|
310
|
+
one stray `""` matches every message. Both start cleanly and present as a
|
|
311
|
+
quiet inbox, which is the failure mode this plugin is repeatedly hardened
|
|
312
|
+
against, so both are refused by name instead.
|
|
313
|
+
"""
|
|
314
|
+
value = cfg.get(key)
|
|
315
|
+
if value is None:
|
|
316
|
+
return []
|
|
317
|
+
if not isinstance(value, list) or any(
|
|
318
|
+
not isinstance(item, str) or not item.strip() for item in value
|
|
319
|
+
):
|
|
320
|
+
raise RuntimeError(
|
|
321
|
+
f"agentmail source: '{key}' must be a list of non-empty strings. A bare "
|
|
322
|
+
"string would be matched character by character, and a blank entry matches "
|
|
323
|
+
"every message."
|
|
324
|
+
)
|
|
325
|
+
retval = [item.strip() for item in value]
|
|
326
|
+
return retval
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@register_source("agentmail")
|
|
330
|
+
def build(cfg: dict) -> Source:
|
|
331
|
+
inbox = cfg.get("inbox") or os.environ.get("AGENTMAIL_EMAIL")
|
|
332
|
+
if not inbox:
|
|
333
|
+
raise RuntimeError("agentmail source needs 'inbox' in config or AGENTMAIL_EMAIL in env")
|
|
334
|
+
|
|
335
|
+
key_env = cfg.get("api_key_env", "AGENTMAIL_API_KEY")
|
|
336
|
+
api_key = os.environ.get(key_env)
|
|
337
|
+
if not api_key:
|
|
338
|
+
raise RuntimeError(f"agentmail source needs the API key in ${key_env}")
|
|
339
|
+
|
|
340
|
+
retval = AgentMailSource(
|
|
341
|
+
inbox=inbox,
|
|
342
|
+
api_key=api_key,
|
|
343
|
+
limit=int(cfg.get("limit", 50)),
|
|
344
|
+
from_contains=_filter_list(cfg, "from_contains"),
|
|
345
|
+
subject_contains=_filter_list(cfg, "subject_contains"),
|
|
346
|
+
from_excludes=_filter_list(cfg, "from_excludes"),
|
|
347
|
+
subject_excludes=_filter_list(cfg, "subject_excludes"),
|
|
348
|
+
fetch_body=bool(cfg.get("fetch_body", True)),
|
|
349
|
+
include_trash=bool(cfg.get("include_trash", False)),
|
|
350
|
+
label=cfg.get("label", "agentmail"),
|
|
351
|
+
timeout=int(cfg.get("timeout", 30)),
|
|
352
|
+
page_size=int(cfg.get("page_size", 50)),
|
|
353
|
+
max_scan=int(cfg.get("max_scan", 0)),
|
|
354
|
+
)
|
|
355
|
+
return retval
|