@sedge-hq/calendar 0.0.0-stage → 0.0.0

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 (3) hide show
  1. package/README.md +25 -2
  2. package/package.json +48 -5
  3. package/src/calendar.ts +350 -0
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # @sedge-hq/calendar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Calendars for [sedge](https://sedge.sh), the always-on agent. One signal, **`calendar`**: it
4
+ wakes sedge a while before each event, and, if you like, each morning with the day ahead.
5
+
6
+ It reads the calendar's iCal address (`.ics`, or `webcal://`), which every calendar app gives:
7
+
8
+ - **Google Calendar:** the calendar's settings → "Secret address in iCal format".
9
+ - **iCloud:** share the calendar as a public calendar and copy its link.
10
+ - **Outlook:** Settings → Calendar → Shared calendars → Publish a calendar.
11
+
12
+ No login is needed. Anyone with the address can read the calendar, so it's kept in your keychain.
13
+
14
+ - **`before`** (default `10 minutes`): how long before each event to wake sedge, with the event's
15
+ title, times, place, organizer and notes. Several are fine (`1 day`, `10 minutes`).
16
+ - **`agenda`**: a time like `07:30` to hand sedge the day's events each morning.
17
+ - **`refresh`**: how often to fetch the calendar, in minutes (default 5).
18
+
19
+ In `sedge`, say "brief me ten minutes before each meeting, with what you know about who's in it"
20
+ or "every morning at 7:30, tell me what's on today". The agent can also ask, with the **`events`**
21
+ action: "what's on tomorrow?".
22
+
23
+ Recurring events, single occurrences that moved or were cancelled, and all-day events are read as
24
+ the calendar has them; times in a zone the calendar names are read in that zone.
25
+
26
+ [Channels and signals](https://github.com/sedge-hq/sedge/blob/main/docs/channels-and-signals.md) · MIT
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
- "name": "@sedge-hq/calendar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@sedge-hq/calendar",
3
+ "version": "0.0.0",
4
+ "description": "Calendars for sedge: a word before each meeting, and the day ahead each morning.",
5
+ "keywords": [
6
+ "calendar",
7
+ "ical",
8
+ "ics",
9
+ "sedge",
10
+ "sedge-kit"
11
+ ],
12
+ "homepage": "https://sedge.sh",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/sedge-hq/sedge.git",
17
+ "directory": "packages/calendar"
18
+ },
19
+ "files": [
20
+ "src",
21
+ "!src/**/*.test.ts"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": "./src/calendar.ts"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "typecheck": "tsc --noEmit",
32
+ "test": "bun --bun vitest run --passWithNoTests"
33
+ },
34
+ "dependencies": {
35
+ "@sedge-hq/kit": "0.4.0",
36
+ "ical.js": "2.2.1"
37
+ },
38
+ "devDependencies": {
39
+ "@sedge-hq/config": "0.0.0",
40
+ "@types/bun": "1.4.5",
41
+ "typescript": "7.0.2",
42
+ "vitest": "5.1.2"
43
+ },
44
+ "sedge": {
45
+ "plugins": [
46
+ "./src/calendar.ts"
47
+ ]
48
+ }
49
+ }
@@ -0,0 +1,350 @@
1
+ import { defineSignal, field, type Happening, type Kit, secret } from '@sedge-hq/kit';
2
+ import ICAL from 'ical.js';
3
+
4
+ /** One occurrence of an event: a recurring event has one per time it happens. */
5
+ export interface Occurrence {
6
+ readonly uid: string;
7
+ readonly title: string;
8
+ readonly start: Date;
9
+ readonly end: Date;
10
+ readonly allDay: boolean;
11
+ readonly location?: string;
12
+ readonly description?: string;
13
+ readonly organizer?: string;
14
+ }
15
+
16
+ // ── Reading a calendar ─────────────────────────────────────────────────────────────────────────
17
+
18
+ /** The offset of `zone` from UTC at `at`, in ms. */
19
+ const offsetIn = (zone: string, at: number) => {
20
+ const parts = Object.fromEntries(
21
+ new Intl.DateTimeFormat('en-US', {
22
+ timeZone: zone,
23
+ hourCycle: 'h23',
24
+ year: 'numeric',
25
+ month: 'numeric',
26
+ day: 'numeric',
27
+ hour: 'numeric',
28
+ minute: 'numeric',
29
+ second: 'numeric',
30
+ })
31
+ .formatToParts(new Date(at))
32
+ .map((part) => [part.type, Number(part.value)]),
33
+ ) as Record<string, number>;
34
+ const wall = Date.UTC(
35
+ parts.year!,
36
+ parts.month! - 1,
37
+ parts.day!,
38
+ parts.hour!,
39
+ parts.minute!,
40
+ parts.second!,
41
+ );
42
+ return wall - Math.floor(at / 1000) * 1000;
43
+ };
44
+
45
+ const isZone = (zone: string) => {
46
+ try {
47
+ new Intl.DateTimeFormat('en-US', { timeZone: zone });
48
+ return true;
49
+ } catch {
50
+ return false;
51
+ }
52
+ };
53
+
54
+ /**
55
+ * A calendar time as an instant. Feeds often name a zone (`TZID=Europe/Berlin`) without
56
+ * describing it in a VTIMEZONE; ical.js then reads the time as this machine's, so here the named
57
+ * zone is applied instead.
58
+ */
59
+ const instant = (time: ICAL.Time, tzid: string | undefined): Date => {
60
+ if (
61
+ !time.isDate &&
62
+ tzid &&
63
+ time.zone === ICAL.Timezone.localTimezone &&
64
+ !ICAL.TimezoneService.has(tzid) &&
65
+ isZone(tzid)
66
+ ) {
67
+ const wall = Date.UTC(
68
+ time.year,
69
+ time.month - 1,
70
+ time.day,
71
+ time.hour,
72
+ time.minute,
73
+ time.second,
74
+ );
75
+ const guess = wall - offsetIn(tzid, wall);
76
+ return new Date(wall - offsetIn(tzid, guess));
77
+ }
78
+ return time.toJSDate();
79
+ };
80
+
81
+ /** The zone a property's time is in, as the feed names it. */
82
+ const zoneOf = (component: ICAL.Component, property: string) => {
83
+ const value = component.getFirstProperty(property)?.getParameter('tzid');
84
+ return typeof value === 'string' ? value : undefined;
85
+ };
86
+
87
+ const text = (value: unknown) =>
88
+ typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
89
+
90
+ /** Every occurrence that overlaps `from`–`to`, soonest first. Cancelled ones are left out. */
91
+ export const occurrences = (ics: string, from: Date, to: Date): Array<Occurrence> => {
92
+ const root = new ICAL.Component(ICAL.parse(ics));
93
+ for (const zone of root.getAllSubcomponents('vtimezone')) {
94
+ const tzid = zone.getFirstPropertyValue('tzid');
95
+ if (typeof tzid === 'string' && !ICAL.TimezoneService.has(tzid))
96
+ ICAL.TimezoneService.register(zone);
97
+ }
98
+ const vevents = root.getAllSubcomponents('vevent');
99
+ // Changes to single occurrences of a recurring event (RECURRENCE-ID) belong to it.
100
+ const exceptions = new Map<string, Array<ICAL.Component>>();
101
+ for (const vevent of vevents) {
102
+ if (!vevent.hasProperty('recurrence-id')) continue;
103
+ const uid = String(vevent.getFirstPropertyValue('uid'));
104
+ exceptions.set(uid, [...(exceptions.get(uid) ?? []), vevent]);
105
+ }
106
+ const found: Array<Occurrence> = [];
107
+ const add = (item: ICAL.Event, start: ICAL.Time, end: ICAL.Time) => {
108
+ if (
109
+ String(item.component.getFirstPropertyValue('status') ?? '').toUpperCase() ===
110
+ 'CANCELLED'
111
+ )
112
+ return;
113
+ const zone = zoneOf(item.component, 'dtstart');
114
+ const at = instant(start, zone);
115
+ // An event with no end lasts no time, or all day when it's a date (RFC 5545).
116
+ const until = end
117
+ ? instant(end, zoneOf(item.component, 'dtend') ?? zone)
118
+ : start.isDate
119
+ ? new Date(at.getTime() + 86_400_000)
120
+ : at;
121
+ if (until <= from || at >= to) return;
122
+ const organizer = item.component.getFirstProperty('organizer');
123
+ found.push({
124
+ uid: item.uid,
125
+ title: text(item.summary) ?? '(untitled)',
126
+ start: at,
127
+ end: until,
128
+ allDay: start.isDate,
129
+ ...(text(item.location) ? { location: text(item.location)! } : {}),
130
+ ...(text(item.description) ? { description: text(item.description)! } : {}),
131
+ ...(organizer
132
+ ? {
133
+ organizer:
134
+ text(organizer.getParameter('cn')) ??
135
+ String(organizer.getFirstValue()).replace(/^mailto:/i, ''),
136
+ }
137
+ : {}),
138
+ });
139
+ };
140
+ for (const vevent of vevents) {
141
+ if (vevent.hasProperty('recurrence-id')) continue;
142
+ const event = new ICAL.Event(vevent, {
143
+ exceptions: exceptions.get(String(vevent.getFirstPropertyValue('uid'))) ?? [],
144
+ });
145
+ if (!event.startDate) continue;
146
+ if (!event.isRecurring()) {
147
+ add(event, event.startDate, event.endDate);
148
+ continue;
149
+ }
150
+ const iterator = event.iterator();
151
+ // Bounded, so a feed with a rule that never gets there can't hang it.
152
+ for (let i = 0, next = iterator.next(); next && i < 50_000; i++, next = iterator.next()) {
153
+ const details = event.getOccurrenceDetails(next);
154
+ if (instant(details.startDate, zoneOf(vevent, 'dtstart')) >= to) break;
155
+ add(details.item, details.startDate, details.endDate);
156
+ }
157
+ }
158
+ return found.sort((a, b) => a.start.getTime() - b.start.getTime());
159
+ };
160
+
161
+ // ── What it tells sedge ────────────────────────────────────────────────────────────────────────
162
+
163
+ const UNITS: Record<string, number> = { m: 60_000, h: 3_600_000, d: 86_400_000 };
164
+
165
+ /** `10 minutes`, `1 hour`, `2 days`, `30m`: in ms. */
166
+ export const parseLead = (lead: string) => {
167
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(m|mins?|minutes?|h|hrs?|hours?|d|days?)\s*$/i.exec(lead);
168
+ if (!match)
169
+ throw new Error(`"${lead}" isn't a time before: say like 10 minutes, 1 hour or 1 day.`);
170
+ return Number(match[1]) * UNITS[match[2]!.charAt(0).toLowerCase()]!;
171
+ };
172
+
173
+ const clock = (date: Date) =>
174
+ date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
175
+ const day = (date: Date) =>
176
+ date.toLocaleDateString(undefined, { weekday: 'short', day: 'numeric', month: 'short' });
177
+
178
+ /** One line: `Tue 2 Dec 10:00–10:45 Standup (Room 3)`. */
179
+ export const lineOf = (event: Occurrence, withDay = true) =>
180
+ `${withDay ? `${day(event.start)} ` : ''}${event.allDay ? 'all day' : `${clock(event.start)}–${clock(event.end)}`} ${event.title}${event.location ? ` (${event.location})` : ''}`;
181
+
182
+ const details = (event: Occurrence) => ({
183
+ title: event.title,
184
+ start: event.start.toISOString(),
185
+ end: event.end.toISOString(),
186
+ allDay: event.allDay,
187
+ ...(event.location ? { location: event.location } : {}),
188
+ ...(event.organizer ? { organizer: event.organizer } : {}),
189
+ ...(event.description
190
+ ? {
191
+ description:
192
+ event.description.length > 4000
193
+ ? `${event.description.slice(0, 4000)}…`
194
+ : event.description,
195
+ }
196
+ : {}),
197
+ });
198
+
199
+ const until = (ms: number) => {
200
+ const minutes = Math.max(1, Math.round(ms / 60_000));
201
+ if (minutes < 90) return `in ${minutes} minute${minutes === 1 ? '' : 's'}`;
202
+ const hours = Math.round(minutes / 60);
203
+ return hours < 36 ? `in ${hours} hours` : `in ${Math.round(hours / 24)} days`;
204
+ };
205
+
206
+ /** The events starting within one of the `leads` from `now`: one happening per event and lead. */
207
+ export const reminders = (
208
+ events: ReadonlyArray<Occurrence>,
209
+ leads: ReadonlyArray<number>,
210
+ now: Date,
211
+ ): Array<Happening> =>
212
+ events.flatMap((event) => {
213
+ const left = event.start.getTime() - now.getTime();
214
+ if (event.allDay || left <= 0) return [];
215
+ // Only the shortest lead it's within: a 1-day and a 10-minute reminder don't both fire late.
216
+ const lead = [...leads].sort((a, b) => a - b).find((lead) => left <= lead);
217
+ if (lead === undefined) return [];
218
+ return [
219
+ {
220
+ text: `Starting ${until(left)}: ${lineOf(event, left > 18 * 3_600_000)}`,
221
+ key: `${event.uid}@${event.start.toISOString()}:${lead}`,
222
+ details: details(event),
223
+ },
224
+ ];
225
+ });
226
+
227
+ /** `07:30` today, on this machine's clock. */
228
+ const todayAt = (time: string, now: Date) => {
229
+ const match = /^\s*(\d{1,2}):(\d{2})\s*$/.exec(time);
230
+ if (!match) throw new Error(`"${time}" isn't a time of day: say like 07:30.`);
231
+ const at = new Date(now);
232
+ at.setHours(Number(match[1]), Number(match[2]), 0, 0);
233
+ return at;
234
+ };
235
+
236
+ /** The day's events, once, in the three hours after `time` (so a late start still gets it). */
237
+ export const agenda = (ics: string, time: string, now: Date): Happening | undefined => {
238
+ const at = todayAt(time, now);
239
+ if (now < at || now.getTime() - at.getTime() > 3 * 3_600_000) return undefined;
240
+ const start = new Date(now);
241
+ start.setHours(0, 0, 0, 0);
242
+ const end = new Date(start);
243
+ end.setDate(end.getDate() + 1);
244
+ const today = occurrences(ics, start, end);
245
+ return {
246
+ text:
247
+ today.length === 0
248
+ ? `Today (${day(start)}): nothing on the calendar.`
249
+ : `Today (${day(start)}): ${today.length} event${today.length === 1 ? '' : 's'}.\n${today.map((e) => `- ${lineOf(e, false)}`).join('\n')}`,
250
+ key: `agenda:${start.getFullYear()}-${start.getMonth() + 1}-${start.getDate()}`,
251
+ details: { events: today.map(details) },
252
+ };
253
+ };
254
+
255
+ // ── Fetching ───────────────────────────────────────────────────────────────────────────────────
256
+
257
+ const cache = new Map<string, { readonly at: number; readonly ics: string }>();
258
+
259
+ /** The feed, fetched again when it's older than `refresh` minutes. */
260
+ const load = async (url: string, refresh: number, kit: Kit) => {
261
+ const cached = cache.get(url);
262
+ if (cached && Date.now() - cached.at < refresh * 60_000) return cached.ics;
263
+ const response = await fetch(url.replace(/^webcal:/i, 'https:'), {
264
+ headers: { accept: 'text/calendar' },
265
+ signal: AbortSignal.any([kit.signal, AbortSignal.timeout(60_000)]),
266
+ });
267
+ if (!response.ok)
268
+ throw new Error(`The calendar answered ${response.status} ${response.statusText}.`);
269
+ const ics = await response.text();
270
+ if (!/BEGIN:VCALENDAR/i.test(ics))
271
+ throw new Error("That address doesn't give an iCal calendar.");
272
+ cache.set(url, { at: Date.now(), ics });
273
+ return ics;
274
+ };
275
+
276
+ /** `today`, `tomorrow` or a date like 2026-12-24, as the start of that day here. */
277
+ const dayFrom = (text: string | undefined, now: Date) => {
278
+ const start = new Date(now);
279
+ start.setHours(0, 0, 0, 0);
280
+ const word = (text ?? 'today').trim().toLowerCase();
281
+ if (word === 'today') return start;
282
+ if (word === 'tomorrow') {
283
+ start.setDate(start.getDate() + 1);
284
+ return start;
285
+ }
286
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(word);
287
+ if (!match)
288
+ throw new Error(`"${text}" isn't a day: say today, tomorrow or a date like 2026-12-24.`);
289
+ return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
290
+ };
291
+
292
+ /**
293
+ * A calendar as a sedge signal: it wakes the agent a while before each event (ten minutes, by
294
+ * default) and, if you like, each morning with the day ahead. It reads the calendar's iCal
295
+ * address, which every calendar app can give, so no login is needed; the address is kept as a
296
+ * secret, since anyone with it can read the calendar.
297
+ */
298
+ export default defineSignal({
299
+ name: 'calendar',
300
+ summary: 'your calendar: a word before each event, and the day ahead each morning',
301
+ settings: {
302
+ url: secret(
303
+ 'The calendar’s iCal address (.ics; webcal:// works). Google: the calendar’s settings → Secret address in iCal format. iCloud: share it as a public calendar. Outlook: Settings → Calendar → Shared calendars → Publish.',
304
+ ),
305
+ before: field.optional(
306
+ field.list(
307
+ 'How long before an event to wake sedge, like 10 minutes or 1 hour (several are fine). Default: 10 minutes.',
308
+ ),
309
+ ),
310
+ agenda: field.optional(
311
+ field.text(
312
+ 'A time each day, like 07:30, to hand sedge the day’s events. Default: none.',
313
+ ),
314
+ ),
315
+ refresh: field.optional(
316
+ field.number('How often to fetch the calendar again, in minutes. Default: 5.'),
317
+ ),
318
+ },
319
+ actions: {
320
+ events: {
321
+ description:
322
+ 'List the calendar’s events: from a day (today, tomorrow, or a date like 2026-12-24; default today) for some days (default 1).',
323
+ input: {
324
+ from: field.optional(field.text('today, tomorrow, or a date like 2026-12-24.')),
325
+ days: field.optional(field.number('How many days. Default: 1.')),
326
+ },
327
+ run: async ({ from, days }, { url, refresh }, kit) => {
328
+ const start = dayFrom(from, new Date());
329
+ const end = new Date(start);
330
+ end.setDate(end.getDate() + Math.max(1, Math.min(days ?? 1, 92)));
331
+ const found = occurrences(await load(url, refresh ?? 5, kit), start, end);
332
+ return found.length === 0
333
+ ? `Nothing on the calendar from ${day(start)} to ${day(new Date(end.getTime() - 1))}.`
334
+ : found.map((event) => lineOf(event)).join('\n');
335
+ },
336
+ },
337
+ },
338
+ every: '1 minute',
339
+ check: async ({ url, before, agenda: time, refresh }, kit) => {
340
+ const leads = (before?.length ? before : ['10 minutes']).map(parseLead);
341
+ const ics = await load(url, refresh ?? 5, kit);
342
+ const now = new Date();
343
+ const ahead = new Date(now.getTime() + Math.max(...leads));
344
+ const upcoming = occurrences(ics, now, ahead);
345
+ const next = upcoming.find((event) => !event.allDay && event.start > now);
346
+ kit.status(next ? `next: ${lineOf(next)}` : 'nothing coming up');
347
+ const day = time ? agenda(ics, time, now) : undefined;
348
+ return [...(day ? [day] : []), ...reminders(upcoming, leads, now)];
349
+ },
350
+ });