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,594 @@
1
+ """ICS calendar source (issue #22).
2
+
3
+ Reads a calendar's ICS feed and emits Signals for events that fall on
4
+ *tomorrow*, split by commitment:
5
+
6
+ - **must** — a personal commitment: the owner created the event, or has
7
+ personally accepted an invite to it. This is a reminder, not a suggestion.
8
+ - **may** — a group/optional event the owner has not (yet) accepted. This
9
+ is a suggestion.
10
+
11
+ The split is the entire point of the feature, so it is conservative by
12
+ design: an event the owner has already personally accepted can never come
13
+ out as "may", and an event whose owner-response cannot be determined at all
14
+ defaults to "may", never "must" (see `_classify`). A declined event is
15
+ dropped outright — the owner already said no, it should not haunt them as a
16
+ suggestion either.
17
+
18
+ This module only builds Signals; rendering the two named sections ("YOU MUST
19
+ ATTEND" / "YOU MAY CONSIDER ATTENDING") is a downstream scorer/destination
20
+ concern (`meta.commitment` and `meta.reason` carry what it needs).
21
+
22
+ ## Transport
23
+
24
+ The feed URL is a bearer secret (Google Calendar's private ICS URL grants
25
+ read access to the whole calendar to anyone who has it), so it is read from
26
+ an environment variable named by `url_env` (default `ICS_CALENDAR_URL`) and
27
+ never accepted from config, matching the `webhook_env`/`api_key_env`
28
+ convention the Slack destination and AgentMail source already use.
29
+
30
+ **Never swallow a failed fetch** (see reddit_source.py's `feed_errors`
31
+ lesson from PR #23): `_fetch_bytes` calls `raise_for_status()` and nothing
32
+ here catches the resulting exception. A broken feed must break the run.
33
+
34
+ ## Timezone — the thing ICS parsing gets wrong
35
+
36
+ "Tomorrow" is meaningless without a reference timezone, and the machine
37
+ running this agent (cron/launchd, likely UTC) is not the owner's timezone.
38
+ So `timezone` (an IANA name, e.g. `America/Los_Angeles`) is a *required*
39
+ config key — there is no default, because silently defaulting to UTC would
40
+ misfile events near midnight without ever raising an error.
41
+
42
+ Every datetime this module produces or compares — the "tomorrow" window,
43
+ each event's start/end, RRULE occurrences, EXDATE/RECURRENCE-ID instants —
44
+ is normalized into that one configured zone via `_to_owner_local`/
45
+ `_occurrence_instant`, regardless of what TZID (if any) the event itself
46
+ declares. An event declared in `America/New_York` and an owner configured
47
+ for `America/Los_Angeles` must land on the correct owner-local day and show
48
+ owner-local clock times; the fixture's "tz-not-UTC" case exists to prove
49
+ that conversion, not just that parsing doesn't crash.
50
+
51
+ All-day events (`DTSTART;VALUE=DATE`) have no timezone at all by design —
52
+ they are compared as dates, not instants.
53
+
54
+ ## Recurrence (RRULE / EXDATE / RECURRENCE-ID) — handled, not dropped
55
+
56
+ A recurring event with no per-instance overrides (e.g. a daily standup) is
57
+ expanded with `dateutil.rrule` and windowed to tomorrow. `EXDATE` entries
58
+ (a single cancelled instance) are excluded. A modified instance — a second
59
+ VEVENT sharing the series' UID and carrying `RECURRENCE-ID` — is used in
60
+ place of whatever the base rule would have generated for that original
61
+ slot, so a moved-30-minutes-later standup shows once, at its new time, not
62
+ twice. An instance whose override carries `STATUS:CANCELLED` is dropped
63
+ entirely, like a decline.
64
+
65
+ **Not handled, deliberately, and flagged rather than silently mishandled:**
66
+
67
+ - `RDATE` (ad hoc extra dates bolted onto a rule) is not read.
68
+ - A *recurring all-day* series (`VALUE=DATE` + `RRULE` on the same VEVENT)
69
+ is not expanded — only its literal `DTSTART` is considered. Recurring
70
+ meetings are the common case this exists for; recurring all-day series
71
+ (e.g. an annual holiday marked as a yearly rule rather than one event
72
+ per year) are rare enough, and date-only recurrence math different
73
+ enough from datetime recurrence, to cut for this PR rather than rush.
74
+
75
+ Both are real gaps for a feed that uses them — noted here so they read as a
76
+ scoping decision, not a bug someone finds by accident.
77
+
78
+ ## Dedupe id
79
+
80
+ `Signal.id` is `f"{uid}:{start_iso}"` — the ICS UID (stable across edits to
81
+ an event, per RFC 5545: editing a summary/time bumps SEQUENCE/DTSTAMP, not
82
+ UID) plus the *occurrence's own* start. That makes the id stable when an
83
+ event is edited without moving (an edited title still dedupes as "seen"),
84
+ while still giving every RRULE instance and every RECURRENCE-ID override its
85
+ own id (next week's standup is a different id from this week's, so it is not
86
+ silently swallowed by `SeenStore` treating last week's occurrence as
87
+ "already seen" forever). A rescheduled event gets a new id and is signalled
88
+ again — treated as a fresh notification for the new slot, which is the
89
+ correct behaviour for a reminder/suggestion digest.
90
+
91
+ Contract: see docs/PLUGIN-CONTRACT.md.
92
+ """
93
+ from __future__ import annotations
94
+
95
+ import os
96
+ import re
97
+ from datetime import date, datetime, time, timedelta
98
+ from datetime import timezone as dt_timezone
99
+ from zoneinfo import ZoneInfo
100
+
101
+ import icalendar
102
+ import requests
103
+ from dateutil.rrule import rrulestr
104
+
105
+ from framework.interfaces import Signal, Source
106
+ from framework.registry import register_source
107
+
108
+ _DEFAULT_LABEL = "ics-calendar"
109
+
110
+ # PARTSTAT values that mean "not attending" -> the event is dropped
111
+ # entirely, never resurfaced as a suggestion.
112
+ _DECLINED_PARTSTATS = {"DECLINED"}
113
+ # PARTSTAT values that promote an invite to MUST ATTEND. Everything else
114
+ # (NEEDS-ACTION, TENTATIVE, or PARTSTAT simply absent) is the safe default:
115
+ # MAY CONSIDER. Wrongly promoting an unanswered invite to MUST is the worse
116
+ # error, so absence never defaults to MUST.
117
+ _ACCEPTED_PARTSTATS = {"ACCEPTED"}
118
+
119
+
120
+ _WINDOW_RE = re.compile(r"^(\d+)\s*([dw])$")
121
+
122
+
123
+ def parse_window(spec: str) -> tuple[int, int]:
124
+ """`window` -> (days_from_today_to_start, length_in_days).
125
+
126
+ `tomorrow` is the default and the original behaviour: the single day after
127
+ today, in the owner's zone. The others exist because a calendar is read for
128
+ more than one reason (issue #59, and #57's meetups agent):
129
+
130
+ tomorrow (1, 1) a reminder: what is on tomorrow
131
+ today (0, 1) what is on now
132
+ week (0, 7) today through the next six days
133
+ <N>d (0, N) an arbitrary horizon in days
134
+ <N>w (0, N*7) the same in weeks
135
+
136
+ An arbitrary horizon is not decoration. A weekly events digest that tiers
137
+ events into "attend within 2 / 4 / 8 weeks" has to be shown eight weeks of
138
+ calendar, and `week` would silently hide everything past day seven -- the
139
+ digest would look complete while being wrong, which is the failure this
140
+ repo keeps guarding against.
141
+ """
142
+ # Only an absent key defaults. An explicit empty string is a typo, and
143
+ # silently reading it as "tomorrow" is the shape of bug this module exists
144
+ # to avoid: the window would be wrong and nothing would say so.
145
+ text = ("tomorrow" if spec is None else str(spec)).strip().lower()
146
+ if text == "tomorrow":
147
+ retval = (1, 1)
148
+ return retval
149
+ if text == "today":
150
+ retval = (0, 1)
151
+ return retval
152
+ if text == "week":
153
+ retval = (0, 7)
154
+ return retval
155
+ match = _WINDOW_RE.match(text)
156
+ if match:
157
+ count = int(match.group(1))
158
+ if count < 1:
159
+ raise ValueError(f"ics source: 'window' {spec!r} must cover at least one day")
160
+ retval = (0, count * (7 if match.group(2) == "w" else 1))
161
+ return retval
162
+ raise ValueError(
163
+ f"ics source: unknown 'window' {spec!r}; use 'tomorrow', 'today', 'week', "
164
+ "or a horizon like '14d' or '8w'"
165
+ )
166
+
167
+
168
+ def _mailto(value: object) -> str:
169
+ """ORGANIZER/ATTENDEE values are `mailto:` URIs; normalize to a bare,
170
+ lowercased email so they can be compared against the configured owner
171
+ email regardless of case or the scheme prefix."""
172
+ text = str(value or "")
173
+ if text.lower().startswith("mailto:"):
174
+ text = text[len("mailto:"):]
175
+ retval = text.strip().lower()
176
+ return retval
177
+
178
+
179
+ def _to_owner_local(value: datetime, owner_tz: ZoneInfo) -> datetime:
180
+ """Normalize a datetime — aware in its own TZID, aware in UTC, or a bare
181
+ floating-time value with no tzinfo at all — into the configured owner
182
+ timezone. Every windowing decision and every displayed clock time goes
183
+ through this, never through an event's own declared zone."""
184
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=owner_tz)
185
+ retval = aware.astimezone(owner_tz)
186
+ return retval
187
+
188
+
189
+ def _occurrence_instant(value: object, owner_tz: ZoneInfo) -> datetime:
190
+ """Normalize an EXDATE or RECURRENCE-ID value (date or datetime) to a
191
+ UTC instant, so it can be compared by absolute moment against an
192
+ RRULE-generated occurrence regardless of which tzinfo object each one
193
+ happens to carry."""
194
+ if isinstance(value, datetime):
195
+ aware = _to_owner_local(value, owner_tz)
196
+ else:
197
+ aware = datetime.combine(value, time.min, tzinfo=owner_tz)
198
+ retval = aware.astimezone(dt_timezone.utc)
199
+ return retval
200
+
201
+
202
+ def _is_cancelled(component: icalendar.Event) -> bool:
203
+ retval = str(component.get("status", "")).upper() == "CANCELLED"
204
+ return retval
205
+
206
+
207
+ def _event_span(
208
+ component: icalendar.Event, owner_tz: ZoneInfo
209
+ ) -> tuple[datetime | date, datetime | date, bool]:
210
+ """(start, end, all_day) for a single (non-expanded) VEVENT, in owner-local
211
+ time for timed events, or as bare dates for all-day events."""
212
+ dtstart_prop = component.get("dtstart")
213
+ dtend_prop = component.get("dtend")
214
+ start_val = dtstart_prop.dt
215
+
216
+ if isinstance(start_val, datetime):
217
+ start = _to_owner_local(start_val, owner_tz)
218
+ if dtend_prop is not None:
219
+ end = _to_owner_local(dtend_prop.dt, owner_tz)
220
+ else:
221
+ duration_prop = component.get("duration")
222
+ delta = duration_prop.dt if duration_prop is not None else timedelta(hours=1)
223
+ end = start + delta
224
+ retval = (start, end, False)
225
+ else:
226
+ # VALUE=DATE: no timezone concept. DTEND is exclusive per RFC 5545.
227
+ end_val = dtend_prop.dt if dtend_prop is not None else start_val + timedelta(days=1)
228
+ retval = (start_val, end_val, True)
229
+ return retval
230
+
231
+
232
+ def _all_day_covers(
233
+ start_date: date, end_date_exclusive: date, win_start: date, win_end_exclusive: date
234
+ ) -> bool:
235
+ """Does an all-day event overlap the window at all?
236
+
237
+ Overlap, not containment, and over a range rather than a single day: a
238
+ three-day all-day event that begins before the window still falls inside
239
+ it, and once a window can be eight weeks long, "starts on day X" would
240
+ drop most of what the digest exists to list. Both ends half-open, matching
241
+ RFC 5545's exclusive DTEND and `_timed_overlaps`.
242
+ """
243
+ retval = start_date < win_end_exclusive and end_date_exclusive > win_start
244
+ return retval
245
+
246
+
247
+ def _timed_overlaps(
248
+ start: datetime, end: datetime, window_start: datetime, window_end: datetime
249
+ ) -> bool:
250
+ """Whether a timed event intersects the window at all.
251
+
252
+ Deliberately overlap rather than start-in-window: an event that begins today
253
+ and runs past midnight is on tomorrow's calendar, and silently dropping it is
254
+ the exact failure this agent exists to prevent. Half-open on both sides, so
255
+ an event ending exactly at midnight does not count as tomorrow's."""
256
+ retval = start < window_end and end > window_start
257
+ return retval
258
+
259
+
260
+ def _exdate_instants(component: icalendar.Event, owner_tz: ZoneInfo) -> set[datetime]:
261
+ prop = component.get("exdate")
262
+ if prop is None:
263
+ return set()
264
+ entries = prop if isinstance(prop, list) else [prop]
265
+ retval: set[datetime] = set()
266
+ for entry in entries:
267
+ for wrapper in entry.dts:
268
+ retval.add(_occurrence_instant(wrapper.dt, owner_tz))
269
+ return retval
270
+
271
+
272
+ def _expand_master(
273
+ component: icalendar.Event,
274
+ owner_tz: ZoneInfo,
275
+ window_start: datetime,
276
+ window_end: datetime,
277
+ skip_instants: set[datetime],
278
+ ) -> list[tuple[datetime, datetime]]:
279
+ """RRULE occurrences of one (timed, non-all-day) master falling in the
280
+ tomorrow window, minus EXDATE entries and minus any instant a
281
+ RECURRENCE-ID override already covers (`skip_instants`)."""
282
+ dtstart_prop = component.get("dtstart")
283
+ start_val = dtstart_prop.dt
284
+ dtend_prop = component.get("dtend")
285
+ if dtend_prop is not None:
286
+ duration = dtend_prop.dt - start_val
287
+ else:
288
+ duration_prop = component.get("duration")
289
+ duration = duration_prop.dt if duration_prop is not None else timedelta(hours=1)
290
+
291
+ # Expand in the event's own declared zone (or owner zone, for a floating
292
+ # value) — RRULE stepping (e.g. "daily at 9am") is only correct relative
293
+ # to whichever zone the series' wall-clock time is actually anchored to.
294
+ native_dtstart = start_val if start_val.tzinfo is not None else start_val.replace(tzinfo=owner_tz)
295
+ rule = rrulestr(component.get("rrule").to_ical().decode(), dtstart=native_dtstart)
296
+ exdates = _exdate_instants(component, owner_tz)
297
+
298
+ occurrences: list[tuple[datetime, datetime]] = []
299
+ # Search back by one duration: an occurrence that starts before the window
300
+ # but runs into it overlaps tomorrow and must be reported.
301
+ search_start = window_start - duration
302
+ for occ_start_native in rule.between(search_start, window_end, inc=True):
303
+ occ_start = occ_start_native.astimezone(owner_tz)
304
+ if not _timed_overlaps(occ_start, occ_start + duration, window_start, window_end):
305
+ continue
306
+ instant = occ_start.astimezone(dt_timezone.utc)
307
+ if instant in exdates or instant in skip_instants:
308
+ continue
309
+ occurrences.append((occ_start, occ_start + duration))
310
+ return occurrences
311
+
312
+
313
+ def _expand_calendar(
314
+ cal: icalendar.Calendar, owner_tz: ZoneInfo, window_start: datetime, window_end: datetime
315
+ ) -> list[tuple[icalendar.Event, datetime | date, datetime | date, bool]]:
316
+ """Every occurrence — single events, RRULE expansions, and
317
+ RECURRENCE-ID overrides substituted in for the base occurrence they
318
+ replace — that falls on tomorrow, as (component, start, end, all_day)."""
319
+ win_start_date = window_start.date()
320
+ # `window_end` is the exclusive instant at midnight after the last day, so
321
+ # its date is already the exclusive end for all-day comparisons.
322
+ win_end_date = window_end.date()
323
+ by_uid: dict[str, list[icalendar.Event]] = {}
324
+ for component in cal.walk("VEVENT"):
325
+ by_uid.setdefault(str(component.get("uid", "")), []).append(component)
326
+
327
+ results: list[tuple[icalendar.Event, datetime | date, datetime | date, bool]] = []
328
+ for components in by_uid.values():
329
+ masters = [c for c in components if c.get("recurrence-id") is None]
330
+ overrides = [c for c in components if c.get("recurrence-id") is not None]
331
+
332
+ skip_instants: set[datetime] = set()
333
+ for override in overrides:
334
+ skip_instants.add(_occurrence_instant(override.get("recurrence-id").dt, owner_tz))
335
+ if _is_cancelled(override):
336
+ continue # this one instance was cancelled: drop it, like a decline
337
+ start, end, all_day = _event_span(override, owner_tz)
338
+ if all_day:
339
+ if _all_day_covers(start, end, win_start_date, win_end_date):
340
+ results.append((override, start, end, all_day))
341
+ elif _timed_overlaps(start, end, window_start, window_end):
342
+ results.append((override, start, end, all_day))
343
+
344
+ for master in masters:
345
+ if master.get("dtstart") is None or _is_cancelled(master):
346
+ continue
347
+ start_val = master.get("dtstart").dt
348
+ if isinstance(start_val, datetime) and master.get("rrule") is not None:
349
+ for occ_start, occ_end in _expand_master(
350
+ master, owner_tz, window_start, window_end, skip_instants
351
+ ):
352
+ results.append((master, occ_start, occ_end, False))
353
+ else:
354
+ start, end, all_day = _event_span(master, owner_tz)
355
+ if all_day:
356
+ if _all_day_covers(start, end, win_start_date, win_end_date):
357
+ results.append((master, start, end, all_day))
358
+ elif _timed_overlaps(start, end, window_start, window_end):
359
+ results.append((master, start, end, all_day))
360
+ return results
361
+
362
+
363
+ def _attendees(component: icalendar.Event) -> list[tuple[str, str]]:
364
+ raw = component.get("attendee")
365
+ if raw is None:
366
+ return []
367
+ items = raw if isinstance(raw, list) else [raw]
368
+ retval = [(_mailto(item), str(item.params.get("PARTSTAT", "")).upper()) for item in items]
369
+ return retval
370
+
371
+
372
+ def _organizer(component: icalendar.Event) -> str:
373
+ raw = component.get("organizer")
374
+ retval = _mailto(raw) if raw is not None else ""
375
+ return retval
376
+
377
+
378
+ def _classify(
379
+ owner_email: str, organizer_email: str, attendees: list[tuple[str, str]]
380
+ ) -> tuple[str, str] | None:
381
+ """(commitment, reason), or None if the event should be dropped
382
+ (declined). See the module docstring for the ordering rationale.
383
+
384
+ 1. No ATTENDEE at all -> a personal calendar entry, not an invite. No
385
+ one else's response to weigh, so it is the owner's own commitment
386
+ by construction.
387
+ 2. Owner is the ORGANIZER -> they created it -> must, no matter what
388
+ (or whether) the attendee list says.
389
+ 3. Owner appears as an ATTENDEE -> follow their own PARTSTAT.
390
+ 4. Owner does not appear among attendees at all (owner_email does not
391
+ match how this calendar lists itself, or hides behind a
392
+ distribution list) -> may. Same reasoning as PARTSTAT-absent: never
393
+ guess "must".
394
+ """
395
+ if not owner_email:
396
+ # A feed with no owner: a public calendar (a chamber of commerce, a
397
+ # venue) where every event is somebody else's. The must/may split is
398
+ # meaningless there -- it asks "did YOU accept this", and there is no
399
+ # you -- and defaulting to "must" would label a stranger's event a
400
+ # personal commitment, which is exactly the wrong answer for an events
401
+ # digest (issue #57). So the split is simply not made, and nothing is
402
+ # dropped for being declined, because no decline can be ours.
403
+ retval = ("", "Public calendar event.")
404
+ return retval
405
+ if not attendees:
406
+ retval = ("must", "Personal calendar entry.")
407
+ return retval
408
+ if owner_email and organizer_email == owner_email:
409
+ retval = ("must", "You organized it.")
410
+ return retval
411
+ for email, partstat in attendees:
412
+ if email == owner_email:
413
+ if partstat in _ACCEPTED_PARTSTATS:
414
+ retval = ("must", "You accepted.")
415
+ return retval
416
+ if partstat in _DECLINED_PARTSTATS:
417
+ retval = None
418
+ return retval
419
+ retval = ("may", "Group event, optional, you have not responded.")
420
+ return retval
421
+ retval = ("may", "Group event, optional; your response status could not be determined.")
422
+ return retval
423
+
424
+
425
+ class ICSSource:
426
+ def __init__(
427
+ self,
428
+ url: str,
429
+ owner_email: str,
430
+ tz: ZoneInfo,
431
+ label: str = _DEFAULT_LABEL,
432
+ timeout: int = 30,
433
+ window: str = "tomorrow",
434
+ dedupe: bool = True,
435
+ now: datetime | None = None,
436
+ ):
437
+ self.url = url
438
+ self.owner_email = owner_email.strip().lower()
439
+ self.window = window
440
+ self._offset_days, self._length_days = parse_window(window)
441
+ # Read by the runner through getattr, like `commit()`: False makes it
442
+ # skip the SeenStore for this source's signals. A window digest is not
443
+ # a stream -- it re-lists the same events every run on purpose -- and
444
+ # per-item dedupe turns the second run of a window into an empty one.
445
+ self.dedupe = dedupe
446
+ self.tz = tz
447
+ self.label = label
448
+ self.timeout = timeout
449
+ # Injectable reference "now", used only by the fixture demo so it can
450
+ # pin "tomorrow" to a fixed date. `build()` never sets this — real
451
+ # runs always use the real current time.
452
+ self._now = now
453
+
454
+ def _fetch_bytes(self) -> bytes:
455
+ resp = requests.get(self.url, timeout=self.timeout)
456
+ resp.raise_for_status() # never swallow a failed fetch
457
+ retval = resp.content
458
+ return retval
459
+
460
+ def _window(self) -> tuple[datetime, datetime]:
461
+ """The half-open [start, end) instants the configured `window` names,
462
+ in the owner's zone. Midnight-aligned at both ends, so a window is a
463
+ whole number of local days however long it is."""
464
+ now_local = self._now.astimezone(self.tz) if self._now is not None else datetime.now(self.tz)
465
+ first = now_local.date() + timedelta(days=self._offset_days)
466
+ start = datetime.combine(first, time.min, tzinfo=self.tz)
467
+ retval = (start, start + timedelta(days=self._length_days))
468
+ return retval
469
+
470
+ def parse(self, raw: bytes) -> list[Signal]:
471
+ """Split out from `fetch()` so it can be exercised directly against a
472
+ fixture file, with no network involved."""
473
+ try:
474
+ cal = icalendar.Calendar.from_ical(raw)
475
+ except Exception as exc:
476
+ raise RuntimeError(
477
+ f"ICS feed at {self.url} did not parse as a calendar: {exc}. "
478
+ "Treating this as a hard failure rather than an empty day - a "
479
+ "feed that stops being a calendar must not read as 'nothing "
480
+ "scheduled tomorrow'."
481
+ ) from exc
482
+
483
+ # An empty day is legitimate; a feed carrying no VEVENT at all is not.
484
+ # Distinguishing them is the whole point: the repo has already been
485
+ # bitten twice by a broken source that looked like a quiet one.
486
+ if not list(cal.walk("VEVENT")):
487
+ raise RuntimeError(
488
+ f"ICS feed at {self.url} contains no VEVENT components. "
489
+ "A calendar with zero events is almost always a broken or "
490
+ "wrong URL, an auth redirect, or an HTML error page - not a "
491
+ "genuinely empty calendar. Verify the URL before assuming "
492
+ "there is nothing scheduled."
493
+ )
494
+
495
+ window_start, window_end = self._window()
496
+
497
+ signals: list[Signal] = []
498
+ for component, start, end, all_day in _expand_calendar(cal, self.tz, window_start, window_end):
499
+ organizer_email = _organizer(component)
500
+ attendees = _attendees(component)
501
+ classification = _classify(self.owner_email, organizer_email, attendees)
502
+ if classification is None:
503
+ continue
504
+ commitment, reason = classification
505
+
506
+ uid = str(component.get("uid", ""))
507
+ summary = str(component.get("summary", "")).strip() or "(no title)"
508
+ time_label = "All day" if all_day else f"{start:%H:%M}-{end:%H:%M}"
509
+ text = f"{time_label} — {summary}. {reason}"
510
+ if attendees:
511
+ text += f" {len(attendees)} attendee(s)."
512
+
513
+ signals.append(
514
+ Signal(
515
+ id=f"{uid}:{start.isoformat()}",
516
+ text=text,
517
+ url=str(component.get("url", "") or ""),
518
+ source=self.label,
519
+ meta={
520
+ "uid": uid,
521
+ "title": summary,
522
+ "start": start.isoformat(),
523
+ "end": end.isoformat(),
524
+ "all_day": all_day,
525
+ # "must" | "may", or "" for an ownerless public feed
526
+ # where the distinction does not exist.
527
+ "commitment": commitment,
528
+ "reason": reason,
529
+ "organizer": organizer_email,
530
+ "is_organizer": bool(self.owner_email) and organizer_email == self.owner_email,
531
+ "attendee_count": len(attendees),
532
+ "location": str(component.get("location", "") or ""),
533
+ },
534
+ )
535
+ )
536
+
537
+ retval = signals
538
+ return retval
539
+
540
+ def fetch(self) -> list[Signal]:
541
+ raw = self._fetch_bytes()
542
+ retval = self.parse(raw)
543
+ return retval
544
+
545
+
546
+ @register_source("ics")
547
+ def build(cfg: dict) -> Source:
548
+ url_env = cfg.get("url_env", "ICS_CALENDAR_URL")
549
+ url = os.environ.get(url_env)
550
+ if not url:
551
+ raise RuntimeError(
552
+ f"ics source needs the feed URL in ${url_env} — it is a bearer secret "
553
+ "(Google's private ICS URL grants read access to the whole calendar), "
554
+ "so it is never accepted from config"
555
+ )
556
+
557
+ # Optional since #59/#57. With an owner the source splits MUST ATTEND from
558
+ # MAY CONSIDER; without one it reads a public calendar nobody owns and makes
559
+ # no such claim. Omitting it is a declaration, not an oversight, so it is not
560
+ # defaulted from the environment when the config says nothing -- an operator
561
+ # who wants the split states the address.
562
+ owner_email = cfg.get("owner_email") or os.environ.get("CALENDAR_OWNER_EMAIL") or ""
563
+
564
+ tz_name = cfg.get("timezone")
565
+ if not tz_name:
566
+ raise RuntimeError(
567
+ "ics source needs 'timezone' (an IANA name, e.g. 'America/Los_Angeles') — "
568
+ "'tomorrow' is evaluated in this zone, never UTC or the host machine's zone"
569
+ )
570
+ try:
571
+ tz = ZoneInfo(tz_name)
572
+ except Exception as exc:
573
+ raise RuntimeError(f"ics source: invalid 'timezone' {tz_name!r}: {exc}") from exc
574
+
575
+ window = cfg.get("window", "tomorrow")
576
+ try:
577
+ parse_window(window)
578
+ except ValueError as exc:
579
+ raise RuntimeError(str(exc)) from exc
580
+
581
+ dedupe = cfg.get("dedupe", True)
582
+ if not isinstance(dedupe, bool):
583
+ raise RuntimeError("ics source: 'dedupe' must be true or false")
584
+
585
+ retval = ICSSource(
586
+ url=url,
587
+ owner_email=owner_email,
588
+ tz=tz,
589
+ label=cfg.get("label", _DEFAULT_LABEL),
590
+ timeout=int(cfg.get("timeout", 30)),
591
+ window=window,
592
+ dedupe=dedupe,
593
+ )
594
+ return retval