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,248 @@
|
|
|
1
|
+
"""Email destination: one run, one mail (issue #148).
|
|
2
|
+
|
|
3
|
+
Mail is the one surface a person reads without being in a workspace. Everything
|
|
4
|
+
else this repo can deliver to — Slack, Signal — asks the reader to be somewhere
|
|
5
|
+
already.
|
|
6
|
+
|
|
7
|
+
"destination": {
|
|
8
|
+
"type": "email",
|
|
9
|
+
"to": ["someone@example.test"],
|
|
10
|
+
"subject": "Leads",
|
|
11
|
+
"min_score": 60,
|
|
12
|
+
"show_reasons": true,
|
|
13
|
+
"footer": "Verify by hand before any contact."
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
Sent through AgentMail, whose key `agentmail_source` already reads: there is one
|
|
17
|
+
mail layer in this deployment, not two. The inbox comes from `inbox` or
|
|
18
|
+
`$AGENTMAIL_EMAIL`, and the key only ever from the environment.
|
|
19
|
+
|
|
20
|
+
## One mail per run, structurally
|
|
21
|
+
|
|
22
|
+
`send()` buffers and `flush()` sends. There is no streaming mode, unlike the
|
|
23
|
+
Slack destination, and that is deliberate rather than unfinished: an agent that
|
|
24
|
+
mails per signal is a spam cannon pointed at its owner, and a busy fetch would
|
|
25
|
+
empty a mailbox of anything else. `flush()` exists for exactly this (#26/#27).
|
|
26
|
+
|
|
27
|
+
A run with nothing above the gate sends **nothing at all**. An empty digest
|
|
28
|
+
teaches its reader to ignore the sender, and a daily "no leads" mail is how a
|
|
29
|
+
channel that matters becomes one that does not.
|
|
30
|
+
|
|
31
|
+
## A failed send fails the run
|
|
32
|
+
|
|
33
|
+
`requests` is given no quiet path here. A non-2xx reply raises, which fails the
|
|
34
|
+
run, which means the runner does not mark those signals seen — so they go out
|
|
35
|
+
on the next good run instead of being burned. Mail that silently drops is worse
|
|
36
|
+
than mail that errors precisely because the dedupe state has already moved on.
|
|
37
|
+
|
|
38
|
+
The send carries an `Idempotency-Key` derived from the signal ids in the batch,
|
|
39
|
+
so a retry after a timeout that the server actually accepted does not deliver
|
|
40
|
+
the same mail twice. **A 409 is therefore success, not failure.** AgentMail
|
|
41
|
+
answers 409 when that key has already been accepted with a different payload,
|
|
42
|
+
which is exactly what the retry of an ambiguous send looks like: the runner
|
|
43
|
+
never marked those signals seen, so the next run re-scored them, and a score or
|
|
44
|
+
a reason moved. Treating it as an error would wedge the agent permanently --
|
|
45
|
+
every subsequent run rebuilding the same batch, re-deriving the same key, and
|
|
46
|
+
failing on it again -- while the mail the operator is waiting for has in fact
|
|
47
|
+
been delivered.
|
|
48
|
+
|
|
49
|
+
What that leaves is the framework's documented at-least-once guarantee, not a
|
|
50
|
+
stronger one. If a *new* signal joins the batch before the retry, the key
|
|
51
|
+
changes with the membership, and the signals already delivered go out a second
|
|
52
|
+
time inside the new digest. Closing that needs a durable record of the pending
|
|
53
|
+
delivery, which destinations have no state of their own to hold; the README's
|
|
54
|
+
"at-least-once, not durable queueing" section is the same property seen from
|
|
55
|
+
the runner's side.
|
|
56
|
+
|
|
57
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
58
|
+
"""
|
|
59
|
+
from __future__ import annotations
|
|
60
|
+
|
|
61
|
+
import hashlib
|
|
62
|
+
import os
|
|
63
|
+
import sys
|
|
64
|
+
|
|
65
|
+
import requests
|
|
66
|
+
|
|
67
|
+
from framework.interfaces import Destination, ScoredSignal
|
|
68
|
+
from framework.registry import register_destination
|
|
69
|
+
|
|
70
|
+
_API_BASE = "https://api.agentmail.to/v0"
|
|
71
|
+
_LABEL = "email destination"
|
|
72
|
+
# AgentMail's reply when this idempotency key has already been accepted.
|
|
73
|
+
_ALREADY_ACCEPTED = 409
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class EmailDestination:
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
api_key: str,
|
|
80
|
+
inbox: str,
|
|
81
|
+
to: list[str],
|
|
82
|
+
subject: str = "",
|
|
83
|
+
min_score: int = 0,
|
|
84
|
+
footer: str = "",
|
|
85
|
+
show_reasons: bool = True,
|
|
86
|
+
timeout: int = 30,
|
|
87
|
+
):
|
|
88
|
+
self.api_key = api_key
|
|
89
|
+
self.inbox = inbox
|
|
90
|
+
self.to = to
|
|
91
|
+
self.subject = subject
|
|
92
|
+
self.min_score = min_score
|
|
93
|
+
self.footer = footer
|
|
94
|
+
self.show_reasons = show_reasons
|
|
95
|
+
self.timeout = timeout
|
|
96
|
+
self._buffered: list[str] = []
|
|
97
|
+
self._ids: list[str] = []
|
|
98
|
+
|
|
99
|
+
def _format(self, scored: ScoredSignal) -> str:
|
|
100
|
+
"""One signal, in the shape the Slack and Signal destinations stream.
|
|
101
|
+
|
|
102
|
+
Score first because it is what a reader triages on, then the signal's
|
|
103
|
+
own words, then its link, then the scorer's reasons set apart — ours
|
|
104
|
+
about them rather than theirs. Plain text: this is the `text` part of
|
|
105
|
+
the mail, and a reader's client decides the typography.
|
|
106
|
+
"""
|
|
107
|
+
sig = scored.signal
|
|
108
|
+
text = f"[{scored.score}] {sig.text}"
|
|
109
|
+
if sig.url:
|
|
110
|
+
text += f"\n{sig.url}"
|
|
111
|
+
if self.show_reasons and scored.reasons:
|
|
112
|
+
text += "\n\n" + "\n".join(f"- {reason}" for reason in scored.reasons)
|
|
113
|
+
retval = text
|
|
114
|
+
return retval
|
|
115
|
+
|
|
116
|
+
def accepts(self, scored: ScoredSignal) -> bool:
|
|
117
|
+
"""Whether this signal clears the gate. No send, no model call."""
|
|
118
|
+
retval = scored.score >= self.min_score
|
|
119
|
+
return retval
|
|
120
|
+
|
|
121
|
+
def render_signal(self, scored: ScoredSignal) -> dict | None:
|
|
122
|
+
"""The text this would carry, without sending it (issue #65).
|
|
123
|
+
|
|
124
|
+
The footer is kept apart, as in every other destination, because the
|
|
125
|
+
`approval` destination posts through its own transport and appends it.
|
|
126
|
+
"""
|
|
127
|
+
if not self.accepts(scored):
|
|
128
|
+
return None
|
|
129
|
+
retval = {"text": self._format(scored), "footer": self.footer}
|
|
130
|
+
return retval
|
|
131
|
+
|
|
132
|
+
def send(self, scored: ScoredSignal) -> None:
|
|
133
|
+
"""Buffer. Nothing leaves until `flush()`; see the module docstring."""
|
|
134
|
+
if not self.accepts(scored):
|
|
135
|
+
return
|
|
136
|
+
self._buffered.append(self._format(scored))
|
|
137
|
+
self._ids.append(scored.signal.id)
|
|
138
|
+
|
|
139
|
+
def _body(self) -> str:
|
|
140
|
+
count = len(self._buffered)
|
|
141
|
+
header = f"{count} signal(s)"
|
|
142
|
+
parts = [header, ""] + ["\n\n---\n\n".join(self._buffered)]
|
|
143
|
+
if self.footer:
|
|
144
|
+
parts += ["", "---", "", self.footer]
|
|
145
|
+
retval = "\n".join(parts)
|
|
146
|
+
return retval
|
|
147
|
+
|
|
148
|
+
def _idempotency_key(self) -> str:
|
|
149
|
+
"""Stable for the same batch, different for a different one.
|
|
150
|
+
|
|
151
|
+
The signal ids, not the rendered text: a retry re-scores, and the llm
|
|
152
|
+
scorer renders the rung it landed on into the reasons, so the text
|
|
153
|
+
moves between runs while the ids do not. The same reasoning as
|
|
154
|
+
`SignalDestination.send`'s seed.
|
|
155
|
+
"""
|
|
156
|
+
seed = "\n".join(sorted(self._ids))
|
|
157
|
+
retval = hashlib.sha1(seed.encode("utf-8")).hexdigest()
|
|
158
|
+
return retval
|
|
159
|
+
|
|
160
|
+
def flush(self) -> None:
|
|
161
|
+
"""Send one mail, or none at all."""
|
|
162
|
+
if not self._buffered:
|
|
163
|
+
return
|
|
164
|
+
subject = f"{self.subject} — {len(self._buffered)} signal(s)".strip(" —")
|
|
165
|
+
payload = {"to": self.to, "subject": subject, "text": self._body()}
|
|
166
|
+
url = f"{_API_BASE}/inboxes/{self.inbox}/messages/send"
|
|
167
|
+
resp = requests.post(
|
|
168
|
+
url,
|
|
169
|
+
headers={
|
|
170
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
171
|
+
"Content-Type": "application/json",
|
|
172
|
+
"Idempotency-Key": self._idempotency_key(),
|
|
173
|
+
},
|
|
174
|
+
json=payload,
|
|
175
|
+
timeout=self.timeout,
|
|
176
|
+
)
|
|
177
|
+
if resp.status_code == _ALREADY_ACCEPTED:
|
|
178
|
+
# Delivered under this key by an earlier attempt whose reply we
|
|
179
|
+
# never saw. See the module docstring: raising here would wedge the
|
|
180
|
+
# agent on a batch that has already arrived.
|
|
181
|
+
print(
|
|
182
|
+
f"{_LABEL}: this batch was already accepted under its idempotency key, "
|
|
183
|
+
f"so an earlier send reached the inbox and this one did not repeat it. "
|
|
184
|
+
f"Treating {len(self._buffered)} signal(s) as delivered.",
|
|
185
|
+
file=sys.stderr,
|
|
186
|
+
)
|
|
187
|
+
elif not resp.ok:
|
|
188
|
+
# The body carries AgentMail's own `name`/`message`, which says
|
|
189
|
+
# whether this was a rejected recipient, a bad inbox or a bad key.
|
|
190
|
+
# Truncated because an HTML error page would otherwise fill the log.
|
|
191
|
+
detail = (resp.text or "")[:500]
|
|
192
|
+
raise RuntimeError(
|
|
193
|
+
f"{_LABEL}: send to inbox {self.inbox} returned "
|
|
194
|
+
f"{resp.status_code} {resp.reason} — {detail}"
|
|
195
|
+
)
|
|
196
|
+
# Only on success, so a retry of a failed run re-sends the same batch
|
|
197
|
+
# under the same idempotency key rather than a shorter one.
|
|
198
|
+
self._buffered = []
|
|
199
|
+
self._ids = []
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@register_destination("email")
|
|
203
|
+
def build(cfg: dict) -> Destination:
|
|
204
|
+
key_env = cfg.get("api_key_env", "AGENTMAIL_API_KEY")
|
|
205
|
+
api_key = os.environ.get(key_env) or ""
|
|
206
|
+
if not api_key:
|
|
207
|
+
raise RuntimeError(
|
|
208
|
+
f"{_LABEL} needs the AgentMail API key in ${key_env} — it is a secret, "
|
|
209
|
+
"so it is never accepted from config"
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
inbox = cfg.get("inbox") or os.environ.get("AGENTMAIL_EMAIL") or ""
|
|
213
|
+
if not inbox:
|
|
214
|
+
raise RuntimeError(
|
|
215
|
+
f"{_LABEL} needs 'inbox' in config or AGENTMAIL_EMAIL in the environment"
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
to = cfg.get("to")
|
|
219
|
+
if not isinstance(to, list) or not to:
|
|
220
|
+
raise RuntimeError(f"{_LABEL} needs a non-empty 'to' list")
|
|
221
|
+
if any(not isinstance(address, str) or "@" not in address for address in to):
|
|
222
|
+
raise RuntimeError(
|
|
223
|
+
f"{_LABEL}: every entry in 'to' must be an address containing '@'"
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
show_reasons = cfg.get("show_reasons", True)
|
|
227
|
+
if not isinstance(show_reasons, bool):
|
|
228
|
+
raise RuntimeError(f"{_LABEL}: 'show_reasons' must be true or false")
|
|
229
|
+
|
|
230
|
+
footer = cfg.get("footer", "")
|
|
231
|
+
if not isinstance(footer, str):
|
|
232
|
+
raise RuntimeError(f"{_LABEL}: 'footer' must be a string")
|
|
233
|
+
|
|
234
|
+
subject = cfg.get("subject", "")
|
|
235
|
+
if not isinstance(subject, str):
|
|
236
|
+
raise RuntimeError(f"{_LABEL}: 'subject' must be a string")
|
|
237
|
+
|
|
238
|
+
retval = EmailDestination(
|
|
239
|
+
api_key=api_key,
|
|
240
|
+
inbox=str(inbox),
|
|
241
|
+
to=[address.strip() for address in to],
|
|
242
|
+
subject=subject,
|
|
243
|
+
min_score=int(cfg.get("min_score", 0)),
|
|
244
|
+
footer=footer,
|
|
245
|
+
show_reasons=show_reasons,
|
|
246
|
+
timeout=int(cfg.get("timeout", 30)),
|
|
247
|
+
)
|
|
248
|
+
return retval
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Fanout destination: one run, several destinations (issue #57).
|
|
2
|
+
|
|
3
|
+
The same digest to two Slack channels, because two audiences want it and neither
|
|
4
|
+
should have to join the other's channel.
|
|
5
|
+
|
|
6
|
+
"destination": {
|
|
7
|
+
"type": "fanout",
|
|
8
|
+
"destinations": [
|
|
9
|
+
{"type": "digest", "webhook_env": "HOOK_A", "channel": "#a", "prompt": "..."},
|
|
10
|
+
{"type": "digest", "webhook_env": "HOOK_B", "channel": "#b", "prompt": "..."}
|
|
11
|
+
]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
## Every child sees every signal, and a digest child drafts once per child
|
|
15
|
+
|
|
16
|
+
`send()` forwards to each child; `flush()` calls each child's, in order. Two
|
|
17
|
+
`digest` children therefore make two LLM calls and write two summaries of the
|
|
18
|
+
same run, which will not be word-for-word identical.
|
|
19
|
+
|
|
20
|
+
That is accepted rather than worked around, and the reason is cost: at a weekly
|
|
21
|
+
cadence it is two calls a week. Sharing one draft between children would mean
|
|
22
|
+
either reaching into a child's buffer — the fanout does not know what kind of
|
|
23
|
+
child it holds, and must not — or a new protocol method for "render once, post
|
|
24
|
+
many", which is wider than the problem. **A config whose two channels must show
|
|
25
|
+
byte-identical text should not use fanout**; it should post once and let Slack
|
|
26
|
+
share the message.
|
|
27
|
+
|
|
28
|
+
## A failure in one child does not spare the others
|
|
29
|
+
|
|
30
|
+
`send()` and `flush()` both attempt **every** child before raising, then raise
|
|
31
|
+
naming all the failures. Stopping at the first would mean a dead webhook on the
|
|
32
|
+
first child silently costing the second child its digest, with the run reporting
|
|
33
|
+
one failure that looks like one problem.
|
|
34
|
+
|
|
35
|
+
The ordering matters for `flush()` in particular: that is where a digest child
|
|
36
|
+
does its real posting, so "attempt them all" is the difference between one
|
|
37
|
+
channel missing a digest and both missing it.
|
|
38
|
+
|
|
39
|
+
This is the same reasoning as issue #82's per-step `on_error` for approval
|
|
40
|
+
actions, reached independently: one dead channel must not cancel the others.
|
|
41
|
+
|
|
42
|
+
**A partial failure still fails the run.** The exception propagates after every
|
|
43
|
+
child has been attempted, so the runner reports `failed`, nothing is marked seen,
|
|
44
|
+
and the next run re-delivers — to every child, including the ones that already
|
|
45
|
+
got it. At-least-once, matching the framework's stated bias (`framework/runner.py`):
|
|
46
|
+
a duplicate digest is recoverable, a missing one is not noticed. A config that
|
|
47
|
+
would rather keep the successful children's delivery than re-send it has no
|
|
48
|
+
option here, deliberately — that is `on_error` semantics, and it belongs in one
|
|
49
|
+
place for actions and destinations alike rather than being invented here first.
|
|
50
|
+
|
|
51
|
+
## Children are built with the parent's injected keys
|
|
52
|
+
|
|
53
|
+
`agent run` injects `_workspace` and `_root` into the top-level destination
|
|
54
|
+
block, and anything built on `framework.llm` needs them — which every `digest`
|
|
55
|
+
child is. The registry hands a factory only its own block, so a nested child
|
|
56
|
+
would not see them and would fail to build its LLM client. They are copied down.
|
|
57
|
+
|
|
58
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
59
|
+
"""
|
|
60
|
+
from __future__ import annotations
|
|
61
|
+
|
|
62
|
+
from typing import Any
|
|
63
|
+
|
|
64
|
+
from framework.interfaces import Destination, ScoredSignal
|
|
65
|
+
from framework.registry import build_destination, register_destination
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class FanoutDestination:
|
|
69
|
+
def __init__(self, children: list[tuple[str, Destination]]):
|
|
70
|
+
# (label, destination). The label is for error messages only — unlike a
|
|
71
|
+
# multi source's child name it is not part of any dedupe key, because a
|
|
72
|
+
# destination mints no ids.
|
|
73
|
+
self.children = children
|
|
74
|
+
|
|
75
|
+
def send(self, scored: ScoredSignal) -> None:
|
|
76
|
+
self._each("send", lambda child: child.send(scored))
|
|
77
|
+
|
|
78
|
+
def flush(self) -> None:
|
|
79
|
+
def flush_one(child: Destination) -> None:
|
|
80
|
+
child_flush = getattr(child, "flush", None)
|
|
81
|
+
if callable(child_flush):
|
|
82
|
+
child_flush()
|
|
83
|
+
|
|
84
|
+
self._each("flush", flush_one)
|
|
85
|
+
|
|
86
|
+
def _each(self, what: str, call) -> None:
|
|
87
|
+
"""Call `call` on every child, then raise if any of them failed.
|
|
88
|
+
|
|
89
|
+
Attempting all of them before raising is the whole point: the first
|
|
90
|
+
child's dead webhook must not cost the second child its digest.
|
|
91
|
+
"""
|
|
92
|
+
failures: list[tuple[str, str]] = []
|
|
93
|
+
for label, child in self.children:
|
|
94
|
+
try:
|
|
95
|
+
call(child)
|
|
96
|
+
except Exception as exc:
|
|
97
|
+
failures.append((label, f"{type(exc).__name__}: {exc}".replace("\n", " ")))
|
|
98
|
+
if failures:
|
|
99
|
+
detail = "; ".join(f"{label}: {why}" for label, why in failures)
|
|
100
|
+
raise RuntimeError(
|
|
101
|
+
f"fanout destination: {len(failures)} of {len(self.children)} "
|
|
102
|
+
f"child destination(s) failed on {what}() — {detail}"
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _child_cfg(parent: dict, declared: dict) -> dict[str, Any]:
|
|
107
|
+
"""A child's block with the parent's injected run-level keys carried in.
|
|
108
|
+
|
|
109
|
+
See `framework/cli.py`: `_workspace` and `_root` are injected into the
|
|
110
|
+
top-level destination block, and every `digest` child needs them to build
|
|
111
|
+
its LLM client. A child that sets one itself keeps its own value.
|
|
112
|
+
"""
|
|
113
|
+
retval = dict(declared)
|
|
114
|
+
for key in ("_workspace", "_root"):
|
|
115
|
+
if key in parent and key not in retval:
|
|
116
|
+
retval[key] = parent[key]
|
|
117
|
+
return retval
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _label(declared: dict, index: int) -> str:
|
|
121
|
+
"""How a child is named in an error message.
|
|
122
|
+
|
|
123
|
+
`channel` first because it is what an operator recognises, then the
|
|
124
|
+
destination type, then the position. No `name` key is required the way the
|
|
125
|
+
multi source requires one: nothing here is a dedupe key, so there is no
|
|
126
|
+
silent-redelivery trap to guard against.
|
|
127
|
+
"""
|
|
128
|
+
channel = str(declared.get("channel") or "").strip()
|
|
129
|
+
kind = str(declared.get("type") or "?")
|
|
130
|
+
retval = f"{kind}[{index}] {channel}".strip() if channel else f"{kind}[{index}]"
|
|
131
|
+
return retval
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@register_destination("fanout")
|
|
135
|
+
def build(cfg: dict) -> Destination:
|
|
136
|
+
declared = cfg.get("destinations")
|
|
137
|
+
if not isinstance(declared, list) or not declared:
|
|
138
|
+
raise RuntimeError(
|
|
139
|
+
"fanout destination needs a non-empty 'destinations' list, each entry "
|
|
140
|
+
"a destination block with its own 'type'"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
children: list[tuple[str, Destination]] = []
|
|
144
|
+
for index, child_declared in enumerate(declared):
|
|
145
|
+
if not isinstance(child_declared, dict):
|
|
146
|
+
raise RuntimeError(
|
|
147
|
+
f"fanout destination: destinations[{index}] is "
|
|
148
|
+
f"{type(child_declared).__name__}, not a destination block"
|
|
149
|
+
)
|
|
150
|
+
label = _label(child_declared, index)
|
|
151
|
+
try:
|
|
152
|
+
child = build_destination(_child_cfg(cfg, child_declared))
|
|
153
|
+
except Exception as exc:
|
|
154
|
+
raise RuntimeError(
|
|
155
|
+
f"fanout destination: child {label} could not be built — {exc}"
|
|
156
|
+
) from exc
|
|
157
|
+
children.append((label, child))
|
|
158
|
+
|
|
159
|
+
retval = FanoutDestination(children=children)
|
|
160
|
+
return retval
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""GitHub org source: what shipped across an organisation's repos (issue #13).
|
|
2
|
+
|
|
3
|
+
Enumerates repos under an org and yields merged pull requests and closed issues
|
|
4
|
+
as Signals, for the weekly release-notes agent to summarize.
|
|
5
|
+
|
|
6
|
+
Auth comes from the `gh` CLI rather than a token in config. `gh` is already
|
|
7
|
+
authenticated on any machine where this runs, it refreshes itself, and it keeps
|
|
8
|
+
one more credential out of the environment. The cost is a hard dependency on the
|
|
9
|
+
binary, which is checked up front with a clear error rather than a confusing
|
|
10
|
+
JSON parse failure later.
|
|
11
|
+
|
|
12
|
+
**Merged PRs and closed issues, not commits.** The issue asks to look at
|
|
13
|
+
"commits/PRs/issues", but commits are the wrong altitude for a feature summary —
|
|
14
|
+
a week of `fix typo` and `bump deps` drowns the one thing worth writing about,
|
|
15
|
+
and squash-merged repos duplicate every PR as a commit anyway. PR titles and
|
|
16
|
+
bodies are what humans wrote to describe their own change, which is exactly the
|
|
17
|
+
input a summarizer wants. Set `include_commits: true` to add them for repos that
|
|
18
|
+
merge without PRs.
|
|
19
|
+
|
|
20
|
+
**No time window is applied here.** The runner's SeenStore already guarantees
|
|
21
|
+
each item is summarized once, so the source over-fetches a generous window and
|
|
22
|
+
lets dedupe do the filtering. That is also what makes a missed run harmless: the
|
|
23
|
+
next one picks up everything not yet seen, rather than silently skipping a week
|
|
24
|
+
the way a strict since-last-run timestamp would.
|
|
25
|
+
|
|
26
|
+
Private repos are excluded by default — this feeds a public blog post.
|
|
27
|
+
|
|
28
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
29
|
+
"""
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import shutil
|
|
35
|
+
import subprocess
|
|
36
|
+
|
|
37
|
+
from framework.interfaces import Signal, Source
|
|
38
|
+
from framework.registry import register_source
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class GitHubCLIError(RuntimeError):
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _gh(args: list[str]) -> list[dict]:
|
|
46
|
+
if not shutil.which("gh"):
|
|
47
|
+
raise GitHubCLIError(
|
|
48
|
+
"github-org source needs the `gh` CLI on PATH (brew install gh; gh auth login)"
|
|
49
|
+
)
|
|
50
|
+
# Extend the parent environment rather than replacing it: gh reads its auth
|
|
51
|
+
# from GH_TOKEN/GITHUB_TOKEN or from ~/.config/gh (which needs HOME) when
|
|
52
|
+
# neither is set. A bare {"GH_PAGER": ..., "PATH": ...} env drops all of
|
|
53
|
+
# that and gh reports "not logged into any GitHub hosts" even when it is.
|
|
54
|
+
proc = subprocess.run(
|
|
55
|
+
["gh", *args],
|
|
56
|
+
capture_output=True,
|
|
57
|
+
text=True,
|
|
58
|
+
env={**os.environ, "GH_PAGER": "cat"},
|
|
59
|
+
)
|
|
60
|
+
if proc.returncode != 0:
|
|
61
|
+
raise GitHubCLIError(f"gh {' '.join(args)} failed: {proc.stderr.strip()[:300]}")
|
|
62
|
+
retval = json.loads(proc.stdout or "[]")
|
|
63
|
+
return retval
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class GitHubOrgSource:
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
org: str,
|
|
70
|
+
days: int = 14,
|
|
71
|
+
include_private: bool = False,
|
|
72
|
+
include_commits: bool = False,
|
|
73
|
+
include_issues: bool = True,
|
|
74
|
+
max_repos: int = 50,
|
|
75
|
+
per_repo_limit: int = 50,
|
|
76
|
+
):
|
|
77
|
+
self.org = org
|
|
78
|
+
self.days = days
|
|
79
|
+
self.include_private = include_private
|
|
80
|
+
self.include_commits = include_commits
|
|
81
|
+
self.include_issues = include_issues
|
|
82
|
+
self.max_repos = max_repos
|
|
83
|
+
self.per_repo_limit = per_repo_limit
|
|
84
|
+
self.skipped: list[tuple[str, str]] = []
|
|
85
|
+
|
|
86
|
+
def _repos(self) -> list[dict]:
|
|
87
|
+
visibility = [] if self.include_private else ["--visibility", "public"]
|
|
88
|
+
rows = _gh(
|
|
89
|
+
[
|
|
90
|
+
"repo", "list", self.org,
|
|
91
|
+
"--limit", str(self.max_repos),
|
|
92
|
+
*visibility,
|
|
93
|
+
"--json", "name,isArchived,pushedAt",
|
|
94
|
+
]
|
|
95
|
+
)
|
|
96
|
+
retval = [r for r in rows if not r.get("isArchived")]
|
|
97
|
+
return retval
|
|
98
|
+
|
|
99
|
+
def _pulls(self, repo: str) -> list[Signal]:
|
|
100
|
+
rows = _gh(
|
|
101
|
+
[
|
|
102
|
+
"pr", "list", "-R", f"{self.org}/{repo}",
|
|
103
|
+
"--state", "merged", "--limit", str(self.per_repo_limit),
|
|
104
|
+
"--json", "number,title,body,url,mergedAt,author",
|
|
105
|
+
]
|
|
106
|
+
)
|
|
107
|
+
signals = []
|
|
108
|
+
for pr in rows:
|
|
109
|
+
signals.append(
|
|
110
|
+
Signal(
|
|
111
|
+
id=f"{self.org}/{repo}#pr{pr['number']}",
|
|
112
|
+
text=f"{pr['title']}\n\n{(pr.get('body') or '').strip()}",
|
|
113
|
+
url=pr.get("url", ""),
|
|
114
|
+
source="github",
|
|
115
|
+
meta={
|
|
116
|
+
"title": f"{repo}: {pr['title']}",
|
|
117
|
+
"repo": repo,
|
|
118
|
+
"kind": "pull",
|
|
119
|
+
"merged_at": pr.get("mergedAt", ""),
|
|
120
|
+
"author": (pr.get("author") or {}).get("login", ""),
|
|
121
|
+
},
|
|
122
|
+
)
|
|
123
|
+
)
|
|
124
|
+
return signals
|
|
125
|
+
|
|
126
|
+
def _issues(self, repo: str) -> list[Signal]:
|
|
127
|
+
rows = _gh(
|
|
128
|
+
[
|
|
129
|
+
"issue", "list", "-R", f"{self.org}/{repo}",
|
|
130
|
+
"--state", "closed", "--limit", str(self.per_repo_limit),
|
|
131
|
+
"--json", "number,title,body,url,closedAt",
|
|
132
|
+
]
|
|
133
|
+
)
|
|
134
|
+
signals = []
|
|
135
|
+
for it in rows:
|
|
136
|
+
signals.append(
|
|
137
|
+
Signal(
|
|
138
|
+
id=f"{self.org}/{repo}#i{it['number']}",
|
|
139
|
+
text=f"{it['title']}\n\n{(it.get('body') or '').strip()}",
|
|
140
|
+
url=it.get("url", ""),
|
|
141
|
+
source="github",
|
|
142
|
+
meta={
|
|
143
|
+
"title": f"{repo}: {it['title']}",
|
|
144
|
+
"repo": repo,
|
|
145
|
+
"kind": "issue",
|
|
146
|
+
"closed_at": it.get("closedAt", ""),
|
|
147
|
+
},
|
|
148
|
+
)
|
|
149
|
+
)
|
|
150
|
+
return signals
|
|
151
|
+
|
|
152
|
+
def _commits(self, repo: str) -> list[Signal]:
|
|
153
|
+
rows = _gh(
|
|
154
|
+
[
|
|
155
|
+
"api", f"repos/{self.org}/{repo}/commits",
|
|
156
|
+
"--jq", "[.[] | {sha: .sha, message: .commit.message, url: .html_url}]",
|
|
157
|
+
]
|
|
158
|
+
)
|
|
159
|
+
signals = []
|
|
160
|
+
for c in rows[: self.per_repo_limit]:
|
|
161
|
+
head = (c.get("message") or "").splitlines()[0]
|
|
162
|
+
signals.append(
|
|
163
|
+
Signal(
|
|
164
|
+
id=f"{self.org}/{repo}@{c['sha'][:12]}",
|
|
165
|
+
text=c.get("message", ""),
|
|
166
|
+
url=c.get("url", ""),
|
|
167
|
+
source="github",
|
|
168
|
+
meta={"title": f"{repo}: {head}", "repo": repo, "kind": "commit"},
|
|
169
|
+
)
|
|
170
|
+
)
|
|
171
|
+
return signals
|
|
172
|
+
|
|
173
|
+
def fetch(self) -> list[Signal]:
|
|
174
|
+
self.skipped = []
|
|
175
|
+
signals: list[Signal] = []
|
|
176
|
+
repos = self._repos()
|
|
177
|
+
|
|
178
|
+
attempted = 0
|
|
179
|
+
succeeded = 0
|
|
180
|
+
for repo in repos:
|
|
181
|
+
name = repo["name"]
|
|
182
|
+
for label, fn, enabled in (
|
|
183
|
+
("pulls", self._pulls, True),
|
|
184
|
+
("issues", self._issues, self.include_issues),
|
|
185
|
+
("commits", self._commits, self.include_commits),
|
|
186
|
+
):
|
|
187
|
+
if not enabled:
|
|
188
|
+
continue
|
|
189
|
+
attempted += 1
|
|
190
|
+
try:
|
|
191
|
+
signals.extend(fn(name))
|
|
192
|
+
succeeded += 1
|
|
193
|
+
except GitHubCLIError as exc:
|
|
194
|
+
# One inaccessible repo must not sink the whole run, but the
|
|
195
|
+
# gap has to be visible rather than looking like a quiet week.
|
|
196
|
+
self.skipped.append((f"{name}:{label}", str(exc)[:120]))
|
|
197
|
+
|
|
198
|
+
# Compare feed calls against feed calls. Counting failures against the
|
|
199
|
+
# *repo* count meant one failing feed per repo (say issues disabled
|
|
200
|
+
# org-wide) tripped the all-failed guard even though pulls and commits
|
|
201
|
+
# had succeeded everywhere -- turning a good run into a hard error.
|
|
202
|
+
if attempted and not succeeded:
|
|
203
|
+
raise GitHubCLIError(
|
|
204
|
+
f"github-org: all {attempted} feed call(s) failed — "
|
|
205
|
+
f"{self.skipped[0][1] if self.skipped else ''}"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
retval = signals
|
|
209
|
+
return retval
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@register_source("github-org")
|
|
213
|
+
def build(cfg: dict) -> Source:
|
|
214
|
+
org = cfg.get("org")
|
|
215
|
+
if not org:
|
|
216
|
+
raise RuntimeError("github-org source needs an 'org'")
|
|
217
|
+
retval = GitHubOrgSource(
|
|
218
|
+
org=org,
|
|
219
|
+
days=int(cfg.get("days", 14)),
|
|
220
|
+
include_private=bool(cfg.get("include_private", False)),
|
|
221
|
+
include_commits=bool(cfg.get("include_commits", False)),
|
|
222
|
+
include_issues=bool(cfg.get("include_issues", True)),
|
|
223
|
+
max_repos=int(cfg.get("max_repos", 50)),
|
|
224
|
+
per_repo_limit=int(cfg.get("per_repo_limit", 50)),
|
|
225
|
+
)
|
|
226
|
+
return retval
|