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.
Files changed (50) hide show
  1. agents_framework-0.3.0.dist-info/METADATA +1364 -0
  2. agents_framework-0.3.0.dist-info/RECORD +50 -0
  3. agents_framework-0.3.0.dist-info/WHEEL +5 -0
  4. agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
  5. agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
  6. agents_framework-0.3.0.dist-info/top_level.txt +1 -0
  7. framework/__init__.py +0 -0
  8. framework/__main__.py +9 -0
  9. framework/action_page.py +1102 -0
  10. framework/approval_buttons.py +775 -0
  11. framework/approvals.py +678 -0
  12. framework/calendar_card.py +276 -0
  13. framework/cli.py +273 -0
  14. framework/codex_llm.py +401 -0
  15. framework/config.py +126 -0
  16. framework/drafter.py +263 -0
  17. framework/interfaces.py +96 -0
  18. framework/llm.py +744 -0
  19. framework/plugins/__init__.py +147 -0
  20. framework/plugins/agentmail_source.py +355 -0
  21. framework/plugins/approval_destination.py +478 -0
  22. framework/plugins/command_action.py +248 -0
  23. framework/plugins/digest_destination.py +546 -0
  24. framework/plugins/email_destination.py +248 -0
  25. framework/plugins/fanout_destination.py +160 -0
  26. framework/plugins/github_org_source.py +226 -0
  27. framework/plugins/github_releases_source.py +420 -0
  28. framework/plugins/ics_source.py +594 -0
  29. framework/plugins/llm_scorer.py +411 -0
  30. framework/plugins/multi_source.py +241 -0
  31. framework/plugins/reddit_source.py +625 -0
  32. framework/plugins/regex_scorer.py +93 -0
  33. framework/plugins/rss_source.py +346 -0
  34. framework/plugins/signal_destination.py +133 -0
  35. framework/plugins/slack_destination.py +461 -0
  36. framework/plugins/slack_draft_action.py +137 -0
  37. framework/plugins/slack_post_action.py +65 -0
  38. framework/plugins/slack_workspace_source.py +992 -0
  39. framework/plugins/twitter_action.py +210 -0
  40. framework/plugins/websearch_source.py +761 -0
  41. framework/plugins/wordpress_action.py +413 -0
  42. framework/proposals.py +246 -0
  43. framework/registry.py +166 -0
  44. framework/runlog.py +125 -0
  45. framework/runner.py +243 -0
  46. framework/schedule.py +571 -0
  47. framework/signal_messenger.py +1418 -0
  48. framework/slack.py +801 -0
  49. framework/state.py +39 -0
  50. framework/templating.py +76 -0
@@ -0,0 +1,420 @@
1
+ """GitHub releases source: what an organisation *released* since the last run (issue #46).
2
+
3
+ `github-org` (#13) yields merged PRs and closed issues. Summarising those gives
4
+ a changelog. The weekly release-notes post wants release notes, and the repos
5
+ that cut releases already wrote them: the release body is the text the project
6
+ chose to describe what shipped. This source yields one Signal per release,
7
+ body intact, and nothing else.
8
+
9
+ Auth and transport are the `gh` CLI, as in `github_org_source`, including the
10
+ lesson recorded there: the subprocess environment *extends* `os.environ`
11
+ (`{**os.environ, "GH_PAGER": "cat"}`). Replacing it drops HOME and the token
12
+ and gh reports "not logged into any GitHub hosts" while it plainly is. Both
13
+ the repo listing and each repo's releases are read with `--paginate`, so an org
14
+ past 100 repos or a repo past 100 releases is read whole.
15
+
16
+ **The window is explicit, and it is state.** The other sources over-fetch and
17
+ let SeenStore dedupe. That works for a rolling feed; it does not work for
18
+ releases, where "everything a repo ever released" is unbounded and the question
19
+ is precisely "what is new since we last looked". So `since` is either an ISO
20
+ date used literally (hand re-runs: `since: "2026-09-01"`) or the string
21
+ `"state"`, meaning: read `<state_dir>/github-releases.json`, use its `last_run`,
22
+ and on the first run (no file, no `last_run`) fall back to `first_run_since`,
23
+ which is required in that mode. A release is kept if `published_at >=` the
24
+ window start, it is not a draft, it is not a prerelease unless
25
+ `include_prereleases` is set, and its tagged commit is recent enough (below).
26
+ `>=` rather than `>`: a release published in the same second the window starts
27
+ costs one duplicate that SeenStore drops, whereas `>` would lose it.
28
+
29
+ Timestamps are parsed with dateutil's `isoparse`, not `datetime.fromisoformat`:
30
+ GitHub writes a trailing `Z`, which `fromisoformat` rejects before Python 3.11,
31
+ and the project supports 3.10.
32
+
33
+ **Backfilled releases.** A release created today for an old tag has
34
+ `published_at` = today and would land in this week's window as though it had
35
+ just shipped. So a release is also skipped when its tagged commit is older than
36
+ the window start minus `max_commit_age_days` (default 30), and every such skip
37
+ is logged to stderr with `repo@tag` and the commit date, so a skipped release is
38
+ visible rather than silently absent. The slack is measured against the commit
39
+ on purpose: a release cut from a commit that sat for a week or two is ordinary;
40
+ a tag months old is a backfill.
41
+
42
+ The commit date is resolved per release, with `gh api
43
+ repos/<org>/<repo>/commits/refs/tags/<tag>` (the committer date; the endpoint
44
+ peels an annotated tag to its commit), and only for releases already inside the
45
+ `published_at` window, so a weekly run costs a handful of calls. The release's
46
+ own `created_at` would have been free, and GitHub describes it as the date of
47
+ the commit used for the release, so that was checked against the real org on
48
+ 2026-09-14 before being ruled out. It is the *tag's* date. For a lightweight
49
+ tag that is the commit's date: `shmobster` v0.1.0 has `created_at`
50
+ 2026-08-15T23:57:14Z, `published_at` four days later, and its commit is dated
51
+ 2026-08-15T23:57:14Z. For an annotated tag it is the tagger date: `voitta-yolt`
52
+ v0.2.0, backfilled on 2026-09-14, has `created_at` 2026-07-27T23:06:34Z, which
53
+ is its tag object's tagger date, while the commit is dated 2026-07-27T22:22:37Z.
54
+ The gap there is 44 minutes, but nothing bounds it: an annotated tag created
55
+ today on a months-old commit, which is one way to backfill, would carry today's
56
+ `created_at` and pass as new.
57
+
58
+ **How `last_run` moves, and why not at fetch time.** If `fetch()` wrote
59
+ `last_run = now` the window would advance even when the run then failed to
60
+ deliver, and last week's releases would be gone from the next run's window
61
+ while never having been seen: exactly the silent skip this source exists to
62
+ prevent. So `fetch()` notes the time it *started* (started, not finished, so a
63
+ release published mid-fetch lands in the next window rather than between
64
+ windows), and `commit()` writes that time as `last_run`. The runner calls
65
+ `commit()` only after `seen.save()` has succeeded, and only on a `status=ok`
66
+ run (see `framework/runner.py`). The consequences:
67
+
68
+ - A run that fails anywhere before `commit()` leaves `last_run` where it
69
+ was. The next run re-fetches the same window and SeenStore drops whatever
70
+ was in fact delivered. At-least-once, never at-most-once.
71
+ - A `partial` run (some signal's scorer raised `ScoreError`) does not
72
+ advance the window either: the unscored release is retried next run only
73
+ if it is still inside the next run's window.
74
+ - A runner that does not call `commit()` never advances the window. The
75
+ source still works, it just re-fetches from `first_run_since` every time
76
+ and relies on SeenStore. Correct, and increasingly slow; the summary line's
77
+ `fetched=` count is the tell.
78
+ - `since` as a literal date never touches the state file, in either
79
+ direction. A hand re-run must not move the scheduled agent's window.
80
+
81
+ The fetch start time is held on the source instance, not written to the state
82
+ file for `commit()` to read back. One run's `fetch()` and `commit()` always act
83
+ on the same instance, whereas a value read from disk at commit time could be
84
+ an overlapping run's (a hand re-run while the scheduled one is in flight),
85
+ which would promote a window that other run never delivered. Two overlapping
86
+ runs can at worst move `last_run` backwards, which costs duplicates SeenStore
87
+ drops, never a skip.
88
+
89
+ The issue sketched a runner-free variant: promote a pending timestamp at the
90
+ *next* fetch if that run's ids are all in SeenStore. The source cannot see
91
+ SeenStore, and promoting unconditionally at the next fetch is wrong (the next
92
+ fetch is the next run, whether or not the previous one delivered). The smallest
93
+ honest mechanism is the optional `commit()` hook, discovered by getattr exactly
94
+ as `Destination.flush()` is, so no existing source changes.
95
+
96
+ **Where the state file lives.** `agent run` injects `state_dir =
97
+ <workspace>/state` into this block (an explicit `state_dir` wins), so the file
98
+ sits beside the dedupe state and configs need not name it. Building this source
99
+ any other way with `since: "state"` and no `state_dir` raises rather than guess
100
+ a directory. The file is `github-releases.json`:
101
+
102
+ {"last_run": "<ISO, UTC>"}
103
+
104
+ `last_run` is absent until the first successful run. It is written to a
105
+ temporary file and renamed into place, so a crash mid-write leaves the previous
106
+ value; a file that is not a JSON object raises rather than restart the window.
107
+
108
+ **Failure policy.** The repo listing failing is fatal at once. A single repo's
109
+ releases call, or the commit lookup for one of its tags, failing is recorded
110
+ and the loop continues so that the error names *every* failing repo, then `fetch()` raises after the loop: a partial
111
+ window must not be committed as complete. Zero releases across the org is
112
+ `[]`, not an error.
113
+
114
+ Config keys:
115
+
116
+ org required. The GitHub organisation.
117
+ visibility "public" (default), "private" or "all". Archived repos
118
+ are always excluded; this feeds a public post.
119
+ include_prereleases false by default.
120
+ exclude_repos list of repo names to skip (forks, mirrors).
121
+ since "state" (default) or an ISO date/datetime.
122
+ first_run_since ISO date/datetime; required when since is "state".
123
+ max_commit_age_days 30 by default. Skip a release whose tagged commit is
124
+ older than the window start minus this many days.
125
+ state_dir directory holding github-releases.json; injected by
126
+ `agent run`, see above.
127
+
128
+ Contract: see docs/PLUGIN-CONTRACT.md.
129
+ """
130
+ from __future__ import annotations
131
+
132
+ import json
133
+ import os
134
+ import shutil
135
+ import subprocess
136
+ import sys
137
+ from datetime import datetime, timedelta, timezone
138
+ from pathlib import Path
139
+ from urllib.parse import quote
140
+
141
+ from dateutil.parser import isoparse
142
+
143
+ from framework.interfaces import Signal, Source
144
+ from framework.registry import register_source
145
+
146
+ STATE_FILENAME = "github-releases.json"
147
+ _VISIBILITIES = ("public", "private", "all")
148
+ DEFAULT_MAX_COMMIT_AGE_DAYS = 30
149
+
150
+
151
+ class GitHubCLIError(RuntimeError):
152
+ pass
153
+
154
+
155
+ def _run_gh(path: str, *flags: str) -> str:
156
+ """Run `gh api <path> <flags...>` and return its stdout."""
157
+ if not shutil.which("gh"):
158
+ raise GitHubCLIError(
159
+ "github-releases source needs the `gh` CLI on PATH (brew install gh; gh auth login)"
160
+ )
161
+ proc = subprocess.run(
162
+ ["gh", "api", path, *flags],
163
+ capture_output=True,
164
+ text=True,
165
+ env={**os.environ, "GH_PAGER": "cat"},
166
+ )
167
+ if proc.returncode != 0:
168
+ raise GitHubCLIError(f"gh api {path} failed: {proc.stderr.strip()[:300]}")
169
+ retval = proc.stdout
170
+ return retval
171
+
172
+
173
+ def _gh_api(path: str) -> list[dict]:
174
+ """Run `gh api` over every page and return the rows as one list."""
175
+ # --slurp wraps the pages in an outer array: [[page1...], [page2...]].
176
+ pages = json.loads(_run_gh(path, "--paginate", "--slurp") or "[]")
177
+ retval = [row for page in pages for row in page]
178
+ return retval
179
+
180
+
181
+ def _tag_commit_date(org: str, repo: str, tag: str) -> str:
182
+ """Committer date of the commit a tag points at (annotated tags peeled)."""
183
+ path = f"repos/{org}/{repo}/commits/refs/tags/{quote(tag, safe='/')}"
184
+ retval = _run_gh(path, "--jq", ".commit.committer.date").strip()
185
+ return retval
186
+
187
+
188
+ def _parse_iso(value: str, label: str) -> datetime:
189
+ """ISO date or datetime -> aware UTC datetime. A bare date is midnight UTC."""
190
+ try:
191
+ parsed = isoparse(value)
192
+ except (TypeError, ValueError) as exc:
193
+ raise RuntimeError(f"github-releases: {label} is not an ISO date: {value!r}") from exc
194
+ if parsed.tzinfo is None:
195
+ parsed = parsed.replace(tzinfo=timezone.utc)
196
+ retval = parsed.astimezone(timezone.utc)
197
+ return retval
198
+
199
+
200
+ def _now_iso() -> str:
201
+ retval = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
202
+ return retval
203
+
204
+
205
+ class GitHubReleasesSource:
206
+ def __init__(
207
+ self,
208
+ org: str,
209
+ state_path: Path | None,
210
+ visibility: str = "public",
211
+ include_prereleases: bool = False,
212
+ exclude_repos: list[str] | None = None,
213
+ since: str = "state",
214
+ first_run_since: str | None = None,
215
+ max_commit_age_days: int = DEFAULT_MAX_COMMIT_AGE_DAYS,
216
+ ):
217
+ self.org = org
218
+ self.state_path = state_path
219
+ self.visibility = visibility
220
+ self.include_prereleases = include_prereleases
221
+ self.exclude_repos = set(exclude_repos or [])
222
+ self.since = since
223
+ self.first_run_since = first_run_since
224
+ self.max_commit_age_days = max_commit_age_days
225
+ self.failed: list[tuple[str, str]] = []
226
+ # This run's fetch start, promoted to last_run by commit().
227
+ self._pending: str | None = None
228
+
229
+ # -- state --------------------------------------------------------------
230
+
231
+ @property
232
+ def tracks_state(self) -> bool:
233
+ retval = self.since == "state"
234
+ return retval
235
+
236
+ def _state_file(self) -> Path:
237
+ if self.state_path is None:
238
+ raise RuntimeError("github-releases: since is 'state' but no state_dir is set")
239
+ retval = self.state_path
240
+ return retval
241
+
242
+ def _read_state(self) -> dict:
243
+ path = self._state_file()
244
+ retval: dict = {}
245
+ if path.exists():
246
+ loaded = json.loads(path.read_text())
247
+ if not isinstance(loaded, dict):
248
+ raise RuntimeError(f"github-releases: state file {path} is not a JSON object")
249
+ retval = loaded
250
+ return retval
251
+
252
+ def _write_state(self, state: dict) -> None:
253
+ path = self._state_file()
254
+ path.parent.mkdir(parents=True, exist_ok=True)
255
+ tmp = path.with_suffix(".json.tmp")
256
+ tmp.write_text(json.dumps(state, indent=2) + "\n")
257
+ os.replace(tmp, path)
258
+
259
+ def _window_start(self) -> datetime:
260
+ if not self.tracks_state:
261
+ retval = _parse_iso(self.since, "since")
262
+ return retval
263
+ last_run = self._read_state().get("last_run")
264
+ if last_run:
265
+ retval = _parse_iso(last_run, f"last_run in {self.state_path}")
266
+ else:
267
+ retval = _parse_iso(self.first_run_since or "", "first_run_since")
268
+ return retval
269
+
270
+ def commit(self) -> None:
271
+ """Write this run's fetch start as `last_run`. The runner calls this after seen.save()."""
272
+ if not self.tracks_state or self._pending is None:
273
+ return
274
+ state = self._read_state()
275
+ state["last_run"] = self._pending
276
+ self._write_state(state)
277
+ self._pending = None
278
+
279
+ # -- GitHub -------------------------------------------------------------
280
+
281
+ def _repos(self) -> list[str]:
282
+ type_param = "all" if self.visibility == "all" else self.visibility
283
+ rows = _gh_api(f"orgs/{self.org}/repos?per_page=100&type={type_param}")
284
+ names = []
285
+ for repo in rows:
286
+ if repo.get("archived"):
287
+ continue
288
+ if self.visibility != "all" and repo.get("visibility") != self.visibility:
289
+ continue
290
+ if repo["name"] in self.exclude_repos:
291
+ continue
292
+ names.append(repo["name"])
293
+ retval = sorted(names)
294
+ return retval
295
+
296
+ def _releases(self, repo: str, start: datetime, oldest_commit: datetime) -> list[Signal]:
297
+ rows = _gh_api(f"repos/{self.org}/{repo}/releases?per_page=100")
298
+ signals = []
299
+ for rel in rows:
300
+ if rel.get("draft"):
301
+ continue
302
+ if rel.get("prerelease") and not self.include_prereleases:
303
+ continue
304
+ published_at = rel.get("published_at") or ""
305
+ if not published_at:
306
+ continue
307
+ tag = rel["tag_name"]
308
+ label = f"{repo}@{tag}"
309
+ if _parse_iso(published_at, f"published_at of {label}") < start:
310
+ continue
311
+ # Not created_at: for an annotated tag that is the tag's date (module docstring).
312
+ committed_at = _tag_commit_date(self.org, repo, tag)
313
+ if _parse_iso(committed_at, f"commit date of {label}") < oldest_commit:
314
+ print(
315
+ f"github-releases: skipped {label}: tag commit dated {committed_at}, "
316
+ f"before {oldest_commit.isoformat()} "
317
+ f"(max_commit_age_days={self.max_commit_age_days})",
318
+ file=sys.stderr,
319
+ )
320
+ continue
321
+ name = (rel.get("name") or tag).strip()
322
+ body = (rel.get("body") or "").strip()
323
+ signals.append(
324
+ Signal(
325
+ id=label,
326
+ text=f"{repo} {tag} — {name}\n\n{body}",
327
+ url=rel.get("html_url", ""),
328
+ source="github-releases",
329
+ meta={
330
+ "repo": repo,
331
+ "tag": tag,
332
+ "published_at": published_at,
333
+ "author": (rel.get("author") or {}).get("login", ""),
334
+ },
335
+ )
336
+ )
337
+ retval = signals
338
+ return retval
339
+
340
+ def fetch(self) -> list[Signal]:
341
+ self.failed = []
342
+ self._pending = None
343
+ start = self._window_start()
344
+ oldest_commit = start - timedelta(days=self.max_commit_age_days)
345
+ # Taken before any API call: a release published while this loop runs
346
+ # falls into the *next* window rather than between the two.
347
+ fetch_started = _now_iso()
348
+
349
+ signals: list[Signal] = []
350
+ for repo in self._repos():
351
+ try:
352
+ signals.extend(self._releases(repo, start, oldest_commit))
353
+ except GitHubCLIError as exc:
354
+ self.failed.append((repo, str(exc)[:200]))
355
+
356
+ if self.failed:
357
+ names = ", ".join(repo for repo, _ in self.failed)
358
+ detail = "; ".join(f"{repo}: {why}" for repo, why in self.failed[:3])
359
+ raise GitHubCLIError(
360
+ f"github-releases: {len(self.failed)} repo(s) failed ({names}) — {detail}"
361
+ )
362
+
363
+ self._pending = fetch_started
364
+ signals.sort(key=lambda s: s.meta["published_at"])
365
+ retval = signals
366
+ return retval
367
+
368
+
369
+ @register_source("github-releases")
370
+ def build(cfg: dict) -> Source:
371
+ org = cfg.get("org")
372
+ if not org:
373
+ raise RuntimeError("github-releases source needs an 'org'")
374
+ visibility = str(cfg.get("visibility", "public"))
375
+ if visibility not in _VISIBILITIES:
376
+ raise RuntimeError(
377
+ f"github-releases: visibility must be one of {', '.join(_VISIBILITIES)}, "
378
+ f"got {visibility!r}"
379
+ )
380
+ since = str(cfg.get("since", "state"))
381
+ first_run_since = cfg.get("first_run_since")
382
+ state_dir = cfg.get("state_dir")
383
+ if since == "state":
384
+ if not first_run_since:
385
+ raise RuntimeError(
386
+ "github-releases: since is 'state', so 'first_run_since' (ISO date) is required"
387
+ )
388
+ _parse_iso(str(first_run_since), "first_run_since")
389
+ if not state_dir:
390
+ raise RuntimeError(
391
+ "github-releases: since is 'state', so 'state_dir' is required "
392
+ "(`agent run` injects <workspace>/state)"
393
+ )
394
+ else:
395
+ _parse_iso(since, "since")
396
+ max_commit_age_days = cfg.get("max_commit_age_days", DEFAULT_MAX_COMMIT_AGE_DAYS)
397
+ if (
398
+ isinstance(max_commit_age_days, bool)
399
+ or not isinstance(max_commit_age_days, int)
400
+ or max_commit_age_days < 0
401
+ ):
402
+ raise RuntimeError(
403
+ "github-releases: 'max_commit_age_days' must be a non-negative integer, "
404
+ f"got {max_commit_age_days!r}"
405
+ )
406
+ exclude_repos = cfg.get("exclude_repos") or []
407
+ if not isinstance(exclude_repos, list):
408
+ raise RuntimeError("github-releases: 'exclude_repos' must be a list of repo names")
409
+ state_path = Path(state_dir).expanduser() / STATE_FILENAME if state_dir else None
410
+ retval = GitHubReleasesSource(
411
+ org=str(org),
412
+ state_path=state_path,
413
+ visibility=visibility,
414
+ include_prereleases=bool(cfg.get("include_prereleases", False)),
415
+ exclude_repos=[str(r) for r in exclude_repos],
416
+ since=since,
417
+ first_run_since=str(first_run_since) if first_run_since else None,
418
+ max_commit_age_days=max_commit_age_days,
419
+ )
420
+ return retval