@mgcrea/mcp-apple-reminders 0.0.0-bootstrap

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.
@@ -0,0 +1,2027 @@
1
+ import { AppBusyError as RemindersBusyError, AppNotRunningError as RemindersNotRunningError, AppleAutomationError, AppleAutomationError as AppleRemindersError, BaseConfigSchema, CORE_DATA_EPOCH_OFFSET, PreconditionError, SchemaDriftError, columnsOf, confirmArg, createOsascriptRunner, describeStore, escapeLike, fingerprintSchema, limitArg, ok, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, readPackageIdentity, trimmed, withBusyRetry, wrap } from "@mgcrea/mcp-apple-core";
2
+ import { readdirSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { z } from "zod";
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ //#region src/build-info.ts
8
+ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
9
+ name: "@mgcrea/mcp-apple-reminders",
10
+ version: "0.0.0"
11
+ });
12
+ const BUILD_INFO = {
13
+ name: pkg.name,
14
+ version: pkg.version,
15
+ gitCommit: "df06e7f",
16
+ gitCommitDate: "2026-08-22T16:20:23+02:00"
17
+ };
18
+ //#endregion
19
+ //#region src/client/errors.ts
20
+ /**
21
+ * Reminders' error surface. The taxonomy lives in `@mgcrea/mcp-apple-core`;
22
+ * what belongs here is the identity those messages are written against, and the
23
+ * errors that are genuinely about reminders.
24
+ */
25
+ /** Named in every user-facing error and in the env vars they mention. */
26
+ const REMINDERS_SURFACE = {
27
+ appName: "Reminders",
28
+ envPrefix: "APPLE_REMINDERS"
29
+ };
30
+ /** A ReminderRef no longer resolves — completed-and-cleared, deleted, or stale. */
31
+ var ReminderNotFoundError = class extends AppleAutomationError {
32
+ name = "ReminderNotFoundError";
33
+ constructor(ref) {
34
+ super(`No reminder for ref "${ref}". It was probably deleted since the search ran — and note that completing a reminder can also remove it from the default view. Re-run the search to get a current ref.`);
35
+ }
36
+ };
37
+ /** A list was named that Reminders does not have. */
38
+ var ListNotFoundError = class extends AppleAutomationError {
39
+ name = "ListNotFoundError";
40
+ constructor(name, available = []) {
41
+ super(`No Reminders list named "${name}".` + (available.length ? ` Available: ${available.slice(0, 20).join(", ")}${available.length > 20 ? ", …" : ""}.` : ` Use apple_reminders_list_lists to see what exists.`), { requested: name });
42
+ }
43
+ };
44
+ /**
45
+ * A date argument could not be understood.
46
+ *
47
+ * Carries the accepted grammar rather than just rejecting, because the caller is
48
+ * usually a model that will retry once and needs to know what shape to retry in.
49
+ */
50
+ var InvalidDateError = class extends AppleAutomationError {
51
+ name = "InvalidDateError";
52
+ constructor(field, raw, reason) {
53
+ super(`Could not read ${field} from ${JSON.stringify(raw)}: ${reason}. Accepted: an ISO-8601 date "2026-08-20" (all-day) or date-time "2026-08-20T09:00" (timed), or a relative offset like "+2d", "+3h", "+45m", "+1w", "today", "tomorrow", or "next monday".`, {
54
+ field,
55
+ raw
56
+ });
57
+ }
58
+ };
59
+ //#endregion
60
+ //#region src/client/dates.ts
61
+ /**
62
+ * Date parsing for the Reminders tools.
63
+ *
64
+ * ## Why this module exists at all
65
+ *
66
+ * The scripting dictionary carries two separate due-date properties:
67
+ *
68
+ * due date "will set both date and time"
69
+ * allday due date "will only set a date"
70
+ *
71
+ * So the *shape of the input* has to pick the property. A caller that writes
72
+ * "2026-08-20" means a day; one that writes "2026-08-20T09:00" means an instant.
73
+ * Collapsing those into one field is how a reminder ends up silently due at
74
+ * midnight, which Reminders then renders as an all-day item anyway — the bug is
75
+ * invisible until someone misses something.
76
+ *
77
+ * ## The rule
78
+ *
79
+ * | Input names a… | Examples | Result |
80
+ * | ------------------- | ------------------------------------- | -------- |
81
+ * | day | `2026-08-20`, `today`, `next monday` | all-day |
82
+ * | instant | `2026-08-20T09:00`, `+3h`, `+2d` | timed |
83
+ * | day *and* a time | `tomorrow 09:00` | timed |
84
+ *
85
+ * `+2d` is timed rather than all-day on purpose: it names a duration from now,
86
+ * and the natural reading of "in two days" keeps the current time of day.
87
+ *
88
+ * ## Time zone
89
+ *
90
+ * Everything without an explicit offset resolves in **system local time**.
91
+ * Reminders is a local-calendar app: a reminder due "09:00" is due at nine
92
+ * o'clock where the person is, not at nine UTC. An input that *does* carry an
93
+ * offset (`…T09:00Z`, `…T09:00+02:00`) is honoured as the absolute instant it
94
+ * names.
95
+ *
96
+ * ## DST
97
+ *
98
+ * Day and week offsets are **calendar** arithmetic (`setDate`), so `+2d` across
99
+ * a clock change lands at the same wall-clock time — which is what "in two
100
+ * days" means to a person. Hour and minute offsets are **absolute** durations,
101
+ * so `+3h` is always three hours of elapsed time. That split is deliberate and
102
+ * pinned by tests; getting it backwards makes reminders drift by an hour twice
103
+ * a year.
104
+ *
105
+ * ## Testability
106
+ *
107
+ * `now` is an injected parameter with a `new Date()` default, mirroring how
108
+ * `loadConfig(env)` takes its environment — so tests are hermetic rather than
109
+ * having to freeze a global clock.
110
+ */
111
+ const DAY_NAMES = [
112
+ "sunday",
113
+ "monday",
114
+ "tuesday",
115
+ "wednesday",
116
+ "thursday",
117
+ "friday",
118
+ "saturday"
119
+ ];
120
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
121
+ const ISO_DATETIME = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/;
122
+ const OFFSET = /^\+(\d+)\s*(m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days|w|week|weeks)$/;
123
+ const DAY_WORD = /^(today|tomorrow)(?:\s+(\d{1,2}):(\d{2}))?$/;
124
+ const NEXT_DAY = /^next\s+([a-z]+)(?:\s+(\d{1,2}):(\d{2}))?$/;
125
+ /** `+02:00` / `-05:00` / `Z` for a given instant, in the system zone. */
126
+ const offsetOf = (d) => {
127
+ const mins = -d.getTimezoneOffset();
128
+ if (mins === 0) return "Z";
129
+ const sign = mins < 0 ? "-" : "+";
130
+ const abs = Math.abs(mins);
131
+ return `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`;
132
+ };
133
+ const pad = (n, w = 2) => String(n).padStart(w, "0");
134
+ /**
135
+ * Local wall-clock time rendered with its offset.
136
+ *
137
+ * Deliberately not `toISOString()`, which converts to UTC and would report a
138
+ * 09:00 reminder as `07:00Z` — correct as an instant, but unreadable in a tool
139
+ * result where the whole point is confirming what the caller asked for.
140
+ */
141
+ const toLocalIso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}${offsetOf(d)}`;
142
+ /** Local midnight on the given calendar day. */
143
+ const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
144
+ /** The last representable instant of the given calendar day, local. */
145
+ const endOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999);
146
+ /** Calendar-aware day arithmetic: same wall-clock time, n days later. */
147
+ const addDays = (d, n) => {
148
+ const out = new Date(d.getTime());
149
+ out.setDate(out.getDate() + n);
150
+ return out;
151
+ };
152
+ const at = (day, hours, minutes) => new Date(day.getFullYear(), day.getMonth(), day.getDate(), hours, minutes, 0, 0);
153
+ const result = (kind, when, raw) => ({
154
+ kind,
155
+ at: when,
156
+ iso: toLocalIso(when),
157
+ raw
158
+ });
159
+ /**
160
+ * Parse one date argument.
161
+ *
162
+ * @param field Named in the error, so a failure says *which* argument was bad.
163
+ * @param raw The caller's string.
164
+ * @param now Injected for hermetic tests.
165
+ */
166
+ const parseDate = (field, raw, now = /* @__PURE__ */ new Date()) => {
167
+ const text = String(raw ?? "").trim();
168
+ if (!text) throw new InvalidDateError(field, String(raw), "it is empty");
169
+ const lower = text.toLowerCase();
170
+ const dt = ISO_DATETIME.exec(text);
171
+ if (dt) {
172
+ const [, y, mo, d, hh, mm, ss, zone] = dt;
173
+ const when = zone ? new Date(text.replace(" ", "T")) : new Date(Number(y), Number(mo) - 1, Number(d), Number(hh), Number(mm), Number(ss ?? "0"), 0);
174
+ if (Number.isNaN(when.getTime())) throw new InvalidDateError(field, text, "it is not a real date");
175
+ return result("timed", when, text);
176
+ }
177
+ const only = ISO_DATE.exec(text);
178
+ if (only) {
179
+ const [, y, mo, d] = only;
180
+ const when = new Date(Number(y), Number(mo) - 1, Number(d), 0, 0, 0, 0);
181
+ if (Number.isNaN(when.getTime())) throw new InvalidDateError(field, text, "it is not a real date");
182
+ if (when.getMonth() !== Number(mo) - 1 || when.getDate() !== Number(d)) throw new InvalidDateError(field, text, `there is no day ${d} in month ${mo}`);
183
+ return result("allDay", when, text);
184
+ }
185
+ const off = OFFSET.exec(lower);
186
+ if (off) {
187
+ const n = Number(off[1]);
188
+ const unit = String(off[2]);
189
+ if (!Number.isFinite(n)) throw new InvalidDateError(field, text, "the amount is not a number");
190
+ if (unit.startsWith("d")) return result("timed", addDays(now, n), text);
191
+ if (unit.startsWith("w")) return result("timed", addDays(now, n * 7), text);
192
+ const ms = unit.startsWith("h") ? n * 36e5 : n * 6e4;
193
+ return result("timed", new Date(now.getTime() + ms), text);
194
+ }
195
+ const word = DAY_WORD.exec(lower);
196
+ if (word) {
197
+ const day = word[1] === "tomorrow" ? addDays(now, 1) : now;
198
+ if (word[2] === void 0) return result("allDay", startOfDay(day), text);
199
+ const [hh, mm] = [Number(word[2]), Number(word[3])];
200
+ if (hh > 23 || mm > 59) throw new InvalidDateError(field, text, `${hh}:${word[3]} is not a time`);
201
+ return result("timed", at(day, hh, mm), text);
202
+ }
203
+ const next = NEXT_DAY.exec(lower);
204
+ if (next) {
205
+ const idx = DAY_NAMES.findIndex((n) => n === next[1] || n.slice(0, 3) === next[1]);
206
+ if (idx === -1) throw new InvalidDateError(field, text, `"${next[1]}" is not a day of the week`);
207
+ const ahead = (idx - now.getDay() + 7) % 7 || 7;
208
+ const day = addDays(now, ahead);
209
+ if (next[2] === void 0) return result("allDay", startOfDay(day), text);
210
+ const [hh, mm] = [Number(next[2]), Number(next[3])];
211
+ if (hh > 23 || mm > 59) throw new InvalidDateError(field, text, `${hh}:${next[3]} is not a time`);
212
+ return result("timed", at(day, hh, mm), text);
213
+ }
214
+ throw new InvalidDateError(field, text, "it matches none of the accepted forms");
215
+ };
216
+ /**
217
+ * Parse a bound for a range filter (`dueBefore` / `dueAfter`).
218
+ *
219
+ * A bare day means the whole day, so the edge it resolves to depends on which
220
+ * side of the range it is: `dueBefore: "2026-08-20"` includes everything up to
221
+ * that evening, and `dueAfter: "2026-08-20"` includes everything from that
222
+ * morning. Resolving both to midnight would make `dueBefore` quietly exclude
223
+ * the day the caller named.
224
+ */
225
+ const parseBound = (field, raw, edge, now = /* @__PURE__ */ new Date()) => {
226
+ const parsed = parseDate(field, raw, now);
227
+ if (parsed.kind !== "allDay") return parsed.at;
228
+ return edge === "end" ? endOfDay(parsed.at) : startOfDay(parsed.at);
229
+ };
230
+ //#endregion
231
+ //#region src/client/locate.ts
232
+ /**
233
+ * Find Reminders' store.
234
+ *
235
+ * ## Why this is harder than Notes'
236
+ *
237
+ * Notes has one constant path, so its locator can `statSync` a known file and
238
+ * learn "exists but unreadable" — the signature of a TCC denial — without any
239
+ * permission at all. Reminders keeps its database under a **generated
240
+ * directory name**:
241
+ *
242
+ * ~/Library/Group Containers/group.com.apple.reminders/Container_v1/Stores/Data-<UUID>.sqlite
243
+ *
244
+ * Resolving that means *listing* a protected directory, which is itself the
245
+ * privileged operation. So without Full Disk Access there is not even a path to
246
+ * stat, and this returns `storePath: null` with a reason rather than reporting a
247
+ * file that does not exist. Those are different failures and lead to different
248
+ * fixes.
249
+ *
250
+ * ## Why it globs rather than hardcoding `Container_v1/Stores`
251
+ *
252
+ * That subpath is the observed layout, not a documented one, and Apple has
253
+ * moved this data before — `~/Library/Reminders/Container_v1/Stores` on older
254
+ * releases, and `~/Library/Calendars` in the EventKit era. A bounded walk for
255
+ * `*.sqlite` survives a reshuffle; a hardcoded path turns one into a total
256
+ * outage. The known layout is still *preferred* when present, so the common
257
+ * case costs one readdir.
258
+ */
259
+ /** `group.com.apple.reminders`, under `~/Library/Group Containers`. */
260
+ const GROUP_CONTAINER = "group.com.apple.reminders";
261
+ /** The observed layout. Preferred when it exists; not required. */
262
+ const PREFERRED = ["Container_v1", "Stores"];
263
+ /** Depth cap for the fallback walk. The real store sits at depth 2. */
264
+ const MAX_DEPTH = 4;
265
+ const defaultContainerPath = (home = homedir()) => join(home, "Library", "Group Containers", GROUP_CONTAINER);
266
+ const listDir = (dir) => {
267
+ try {
268
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? [] : [e.name]);
269
+ } catch {
270
+ return [];
271
+ }
272
+ };
273
+ const walk = (dir, depth, out) => {
274
+ if (depth > MAX_DEPTH) return out;
275
+ let entries;
276
+ try {
277
+ entries = readdirSync(dir, { withFileTypes: true });
278
+ } catch {
279
+ return out;
280
+ }
281
+ for (const e of entries) {
282
+ const p = join(dir, e.name);
283
+ if (e.isDirectory()) walk(p, depth + 1, out);
284
+ else if (e.name.endsWith(".sqlite")) out.push(p);
285
+ }
286
+ return out;
287
+ };
288
+ const FDA_HINT = "Grant Full Disk Access to the app running this server (System Settings > Privacy & Security > Full Disk Access) and restart it. Granting it to Reminders.app does nothing — the reader needs the permission.";
289
+ const locateStore = (opts = {}) => {
290
+ const containerPath = defaultContainerPath(opts.home);
291
+ if (opts.storePath) {
292
+ const facts = describeStore(opts.storePath);
293
+ return {
294
+ ...facts,
295
+ containerPath,
296
+ storePath: opts.storePath,
297
+ candidates: [{
298
+ ...facts,
299
+ path: opts.storePath
300
+ }],
301
+ containerListable: true,
302
+ reason: facts.readable ? null : facts.exists ? `The store at ${opts.storePath} exists but cannot be read. ${FDA_HINT}` : `No file at ${opts.storePath}. APPLE_REMINDERS_STORE points at nothing.`
303
+ };
304
+ }
305
+ const preferredDir = join(containerPath, ...PREFERRED);
306
+ const found = listDir(preferredDir).filter((n) => n.endsWith(".sqlite")).map((n) => join(preferredDir, n));
307
+ const paths = found.length ? found : walk(containerPath, 0, []);
308
+ const candidates = paths.map((p) => ({
309
+ ...describeStore(p),
310
+ path: p
311
+ })).toSorted((a, b) => (b.size ?? 0) - (a.size ?? 0));
312
+ const chosen = candidates.find((c) => c.readable) ?? candidates[0] ?? null;
313
+ const containerListable = paths.length > 0 || listDir(containerPath).length > 0;
314
+ const reason = chosen ? chosen.readable ? null : `Found the Reminders store but cannot read it. ${FDA_HINT}` : containerListable ? `No .sqlite file under ${containerPath}. Has Reminders ever been set up on this account?` : `Cannot list ${containerPath}, so the store cannot even be located — its filename carries a generated UUID. ${FDA_HINT}`;
315
+ return {
316
+ ...chosen ? {
317
+ exists: chosen.exists,
318
+ readable: chosen.readable,
319
+ size: chosen.size,
320
+ mtime: chosen.mtime,
321
+ walPresent: chosen.walPresent,
322
+ walSizeBytes: chosen.walSizeBytes
323
+ } : {
324
+ exists: false,
325
+ readable: false,
326
+ size: null,
327
+ mtime: null,
328
+ walPresent: false,
329
+ walSizeBytes: null
330
+ },
331
+ containerPath,
332
+ storePath: chosen?.path ?? null,
333
+ candidates,
334
+ containerListable,
335
+ reason
336
+ };
337
+ };
338
+ //#endregion
339
+ //#region src/client/priority.ts
340
+ const PRIORITY_NAMES = [
341
+ "none",
342
+ "low",
343
+ "medium",
344
+ "high"
345
+ ];
346
+ /** The value Reminders.app itself writes for each bucket. */
347
+ const CANONICAL = {
348
+ none: 0,
349
+ high: 1,
350
+ medium: 5,
351
+ low: 9
352
+ };
353
+ /** Name → wire value, for writes. */
354
+ const toPriorityValue = (name) => CANONICAL[name];
355
+ /**
356
+ * Wire value → name, for reads. Buckets the whole legal range, so a value
357
+ * written by another CalDAV client is still classified rather than dropped.
358
+ */
359
+ const toPriorityName = (value) => {
360
+ if (value === null || value === void 0 || !Number.isFinite(value)) return "none";
361
+ const n = Math.trunc(value);
362
+ if (n <= 0) return "none";
363
+ if (n <= 4) return "high";
364
+ if (n === 5) return "medium";
365
+ if (n <= 9) return "low";
366
+ return "low";
367
+ };
368
+ /**
369
+ * Sort key, ascending = most urgent first, with "none" last.
370
+ *
371
+ * The raw field cannot be used for this: 0 means "no priority" but sorts ahead
372
+ * of 1, which means "high".
373
+ */
374
+ const rank = (value) => {
375
+ const name = toPriorityName(value);
376
+ return name === "none" ? Number.MAX_SAFE_INTEGER : CANONICAL[name];
377
+ };
378
+ //#endregion
379
+ //#region src/client/ref.ts
380
+ /**
381
+ * ReminderRef — the one identifier any tool accepts or returns.
382
+ *
383
+ * Wire format: r1:<reminders-id>
384
+ *
385
+ * The `r1:` prefix follows the same reasoning as Notes' `n1:`: if the id scheme
386
+ * ever changes, a versioned prefix makes that an additive change instead of a
387
+ * silent reinterpretation of every ref already sitting in a conversation.
388
+ *
389
+ * Deliberately NOT shared with Notes' or Mail's codec. Mail's assumes an integer
390
+ * id; Notes' hardcodes `ICNote/p<N>` and returns a numeric `primaryKey`.
391
+ * Reminders' `id` is declared `type="text"` in the scripting dictionary and is
392
+ * opaque — so this codec validates the envelope and refuses to invent structure
393
+ * inside it.
394
+ *
395
+ * ## Why this is tolerant about the id's shape
396
+ *
397
+ * Apple Events ids are observed as `x-apple-reminder://<uuid>`, but that is a
398
+ * shape this server *observes*, not one Apple documents. Rejecting anything
399
+ * else would turn a harmless format change into total failure, and a reminder
400
+ * synced from a CalDAV account is exactly the case most likely to differ. So an
401
+ * id is carried through verbatim, and the UUID is extracted opportunistically —
402
+ * it is what joins a row in the store to a reminder in the app, and when it is
403
+ * absent the index lane simply cannot enrich that one result.
404
+ */
405
+ const REF_VERSION = "r1";
406
+ /** The observed Apple Events form. Used to *find* the uuid, never to require it. */
407
+ const UUID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
408
+ const encodeRef = (id) => `r1:${id}`;
409
+ const decodeRef = (raw) => {
410
+ const m = /^([a-z0-9]+):(.+)$/.exec(String(raw ?? ""));
411
+ if (!m) throw new PreconditionError(`Malformed reminder ref ${JSON.stringify(raw)}. Refs come from the search and list tools — construct them from those results rather than by hand.`, { expected: `r1:<reminders-id>` });
412
+ const [, version, id] = m;
413
+ if (version !== "r1") throw new PreconditionError(`Unknown reminder ref version "${version}". This server issues "r1:" refs.`);
414
+ return {
415
+ id,
416
+ uuid: UUID.exec(id ?? "")?.[1]?.toUpperCase() ?? null
417
+ };
418
+ };
419
+ /**
420
+ * Build a ref from an index row, which only ever knows the bare UUID.
421
+ *
422
+ * The scheme is measured, not assumed: the probe read a real id from Apple
423
+ * Events and found `x-apple-reminder://<uuid>`, then located the same UUID in
424
+ * `ZREMCDREMINDER.ZCKIDENTIFIER`. That round trip is what makes reconstructing
425
+ * an id from the store defensible.
426
+ */
427
+ const refFromUuid = (uuid) => encodeRef(`x-apple-reminder://${uuid.toUpperCase()}`);
428
+ /** The store keeps bare identifiers; normalise for comparison against a ref. */
429
+ const uuidOf = (id) => UUID.exec(String(id ?? ""))?.[1]?.toUpperCase() ?? null;
430
+ //#endregion
431
+ //#region src/client/jxa/core.ts
432
+ /**
433
+ * JXA script fragments.
434
+ *
435
+ * Every script here is a static constant. None of them may contain a template
436
+ * interpolation — `assertStaticScript` rejects any script containing a dollar
437
+ * sign followed by a brace, and that includes JavaScript template literals
438
+ * written *inside* the JXA source. Use string concatenation in JXA code.
439
+ *
440
+ * Every script follows the same contract:
441
+ * - it reads its parameters from `JSON.parse(argv[0])`
442
+ * - it returns `JSON.stringify({ok: true, data})` on success
443
+ * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an
444
+ * application-level failure, still exiting 0
445
+ * so that a non-zero exit always means infrastructure rather than "no such
446
+ * reminder".
447
+ *
448
+ * ## The read discipline
449
+ *
450
+ * A bulk array fetch (`R.reminders.name()`) is ONE Apple Event whatever the
451
+ * library holds. Reading the same property one reminder at a time is one event
452
+ * each. So every read here fetches columns, never rows: a server that reads
453
+ * twelve properties pays twelve round trips total, not twelve per reminder.
454
+ *
455
+ * Whether a `whose` specifier beats that for a *boolean* filter is a genuinely
456
+ * open question, and `scripts/probe-reminders.mjs` measures it. Notes settled
457
+ * the same question for `whose` over *text* — 6.9x slower, because the
458
+ * specifier evaluates per item across the bridge — but a boolean predicate can
459
+ * be pushed into the app in a way a substring match cannot, so that answer does
460
+ * not transfer. Until it is measured, these scripts use the form that is known
461
+ * to be size-independent.
462
+ *
463
+ * ## What the dictionary does not allow
464
+ *
465
+ * `reminder.container` and `list.container` are both declared `access="r"`.
466
+ * There is therefore **no way to move a reminder between lists by assignment** —
467
+ * see `write.ts`, where move is implemented as copy-then-delete and says so.
468
+ */
469
+ /**
470
+ * Shared prelude.
471
+ *
472
+ * The liveness gate matters more than it looks. `Application("Reminders").lists`
473
+ * *launches* Reminders if it isn't running — which steals focus and starts a
474
+ * sync as a side effect of a read. `NSRunningApplication` answers the same
475
+ * question without launching anything and without a second TCC prompt.
476
+ *
477
+ * Note the bundle identifier is lower-case `com.apple.reminders`. Notes uses
478
+ * `com.apple.Notes`, and `runningApplicationsWithBundleIdentifier` matches
479
+ * exactly — getting the case wrong makes every read report "not running".
480
+ *
481
+ * Deliberately NOT shared with Mail's or Notes' prelude. Mail's is 45% a
482
+ * UI-scripting workaround for its forced blockquote citation; Notes' knows
483
+ * about password-protected notes and folder trees. Neither is about reminders.
484
+ */
485
+ const PRELUDE = `
486
+ ObjC.import("AppKit");
487
+
488
+ function isRemindersRunning() {
489
+ var apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier("com.apple.reminders");
490
+ return apps.count > 0;
491
+ }
492
+
493
+ function ok(data) { return JSON.stringify({ ok: true, data: data }); }
494
+ function err(code, message) { return JSON.stringify({ ok: false, error: { code: code, message: String(message) } }); }
495
+
496
+ function iso(d) {
497
+ try { return d ? d.toISOString() : null; } catch (e) { return null; }
498
+ }
499
+
500
+ /** Read one property defensively: Reminders throws on properties it cannot supply. */
501
+ function prop(fn, fallback) {
502
+ try {
503
+ var v = fn();
504
+ return v === undefined ? fallback : v;
505
+ } catch (e) {
506
+ return fallback;
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Zip parallel bulk arrays into records.
512
+ *
513
+ * Bulk fetches are the only affordable read shape, and they come back as
514
+ * separate arrays that line up by index. Rebuilding records here keeps that
515
+ * assumption in one place.
516
+ */
517
+ function zip(keys, columns, count) {
518
+ var out = [];
519
+ for (var i = 0; i < count; i++) {
520
+ var row = {};
521
+ for (var k = 0; k < keys.length; k++) {
522
+ var col = columns[k];
523
+ row[keys[k]] = col && i < col.length ? col[i] : null;
524
+ }
525
+ out.push(row);
526
+ }
527
+ return out;
528
+ }
529
+
530
+ /**
531
+ * Walk the list tree.
532
+ *
533
+ * \`list.container\` is typed "account OR list", so lists nest — Reminders calls
534
+ * the nesting "groups" in its UI. A flat \`account.lists()\` would silently drop
535
+ * everything inside a group, which is why this recurses even on libraries where
536
+ * no group exists today.
537
+ */
538
+ function listTree(container, accountId, depth, out) {
539
+ if (depth > 8) return out;
540
+ var subs = [];
541
+ try { subs = container.lists(); } catch (e) { return out; }
542
+ for (var i = 0; i < subs.length; i++) {
543
+ var l = subs[i];
544
+ var id = prop(function () { return String(l.id()); }, null);
545
+ out.push({
546
+ id: id,
547
+ name: prop(function () { return String(l.name()); }, null),
548
+ accountId: accountId,
549
+ depth: depth,
550
+ color: prop(function () { return String(l.color()); }, null),
551
+ emblem: prop(function () { return String(l.emblem()); }, null)
552
+ });
553
+ listTree(l, accountId, depth + 1, out);
554
+ }
555
+ return out;
556
+ }
557
+
558
+ /**
559
+ * Build reminder-id -> list.
560
+ *
561
+ * MEASURED: a bulk property fetch costs ~700ms on this bridge whatever the
562
+ * library size (317 reminders, macOS 26.6), so round trips are the only thing
563
+ * that matters here. One call per list would be 12 events — 8 seconds — on a
564
+ * perfectly ordinary account.
565
+ *
566
+ * \`R.lists.reminders.id()\` is a chained element fetch that returns one array
567
+ * per list in a SINGLE event. It is not documented to work, so the per-list
568
+ * form stays as a fallback and the script reports which one answered.
569
+ */
570
+ function membership(lists) {
571
+ var map = {};
572
+ var app = Application("Reminders");
573
+
574
+ var nested = prop(function () { return app.lists.reminders.id(); }, null);
575
+ if (nested && nested.length === lists.length) {
576
+ for (var n = 0; n < lists.length; n++) {
577
+ var group = nested[n] || [];
578
+ for (var g = 0; g < group.length; g++) {
579
+ map[String(group[g])] = { listId: lists[n].id, list: lists[n].name, accountId: lists[n].accountId };
580
+ }
581
+ }
582
+ return { map: map, via: "nested" };
583
+ }
584
+
585
+ for (var i = 0; i < lists.length; i++) {
586
+ var l = lists[i];
587
+ var ids = prop(function () { return app.lists.byId(l.id).reminders.id(); }, []);
588
+ for (var j = 0; j < ids.length; j++) {
589
+ map[String(ids[j])] = { listId: l.id, list: l.name, accountId: l.accountId };
590
+ }
591
+ }
592
+ return { map: map, via: "per-list" };
593
+ }
594
+
595
+ /**
596
+ * Whether a due date names a whole day, and which day that is.
597
+ *
598
+ * MEASURED, and there are two traps stacked here.
599
+ *
600
+ * **First:** Reminders populates BOTH \`due date\` and \`allday due date\` for
601
+ * every dated reminder — 144 of each over 144 dated reminders, all carrying
602
+ * both. So presence discriminates nothing, and "allday is set, therefore
603
+ * all-day" marks every dated reminder as all-day.
604
+ *
605
+ * **Second:** the two lanes disagree about how an all-day date is stored, and
606
+ * verifying against only one of them gets the other backwards. The same
607
+ * reminder, due 9 November:
608
+ *
609
+ * Apple Events 2025-11-08T23:00:00Z = LOCAL midnight (Paris, UTC+1)
610
+ * ZDUEDATE 2025-11-09T00:00:00Z = UTC midnight
611
+ *
612
+ * Both mean the 9th. So the check here reads **local** time, because this
613
+ * script runs in the user's zone and that is the convention Apple Events uses.
614
+ * The store's UTC convention is converted separately, on the store's side.
615
+ *
616
+ * \`dayOf\` exists for the same reason: an all-day reminder names a day, and
617
+ * deriving that day from the UTC ISO string would land on the 8th for everyone
618
+ * east of Greenwich. Formatting it here, from local components, cannot.
619
+ *
620
+ * This is still a heuristic — a reminder deliberately set to local midnight
621
+ * defeats it — and is labelled as one. \`ZALLDAY\` in the store is the
622
+ * authoritative flag, so the index lane overrides it whenever it is live.
623
+ */
624
+ function isMidnight(d) {
625
+ try {
626
+ return Boolean(d) && d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0;
627
+ } catch (e) {
628
+ return false;
629
+ }
630
+ }
631
+
632
+ /** Local calendar day as YYYY-MM-DD. Never derive this from a UTC string. */
633
+ function dayOf(d) {
634
+ try {
635
+ if (!d) return null;
636
+ var m = d.getMonth() + 1;
637
+ var day = d.getDate();
638
+ return d.getFullYear() + "-" + (m < 10 ? "0" : "") + m + "-" + (day < 10 ? "0" : "") + day;
639
+ } catch (e) {
640
+ return null;
641
+ }
642
+ }
643
+ `;
644
+ /**
645
+ * Wrap a script body in the prelude and the liveness gate.
646
+ *
647
+ * `allowLaunch` is opt-in per script, and only tools whose whole purpose is to
648
+ * make Reminders do something set it. A read that silently launches Reminders is
649
+ * a read with a side effect.
650
+ */
651
+ const script = (body, opts = {}) => `
652
+ ${PRELUDE}
653
+ function run(argv) {
654
+ var p = JSON.parse(argv[0] || "{}");
655
+ if (!isRemindersRunning() && !${opts.allowLaunch ? "true" : "false"}) {
656
+ return err("APP_NOT_RUNNING", "Reminders is not running.");
657
+ }
658
+ try {
659
+ var R = Application("Reminders");
660
+ ${body}
661
+ } catch (e) {
662
+ var msg = String(e && e.message ? e.message : e);
663
+ if (msg.indexOf("-1743") !== -1) return err("NOT_AUTHORIZED", msg);
664
+ return err("SCRIPT_ERROR", msg);
665
+ }
666
+ }
667
+ `;
668
+ //#endregion
669
+ //#region src/client/jxa/read.ts
670
+ /** Accounts, with the list count each one holds. */
671
+ const LIST_ACCOUNTS = script(`
672
+ var accounts = R.accounts();
673
+ var out = [];
674
+ var defaultAccountId = prop(function () { return String(R.defaultAccount.id()); }, null);
675
+ var defaultListId = prop(function () { return String(R.defaultList.id()); }, null);
676
+ for (var i = 0; i < accounts.length; i++) {
677
+ var a = accounts[i];
678
+ var id = prop(function () { return String(a.id()); }, null);
679
+ out.push({
680
+ id: id,
681
+ name: prop(function () { return String(a.name()); }, null),
682
+ isDefault: id !== null && id === defaultAccountId,
683
+ listCount: prop(function () { return a.lists().length; }, 0),
684
+ reminderCount: prop(function () { return a.reminders().length; }, 0)
685
+ });
686
+ }
687
+ return ok({ accounts: out, defaultAccountId: defaultAccountId, defaultListId: defaultListId });
688
+ `);
689
+ /**
690
+ * The list tree. Lists nest inside other lists (Reminders calls them groups),
691
+ * so this is depth-first rather than a flat account.lists() read.
692
+ */
693
+ const LIST_LISTS = script(`
694
+ var accounts = R.accounts();
695
+ var out = [];
696
+ var defaultListId = prop(function () { return String(R.defaultList.id()); }, null);
697
+ for (var i = 0; i < accounts.length; i++) {
698
+ var a = accounts[i];
699
+ var accountId = prop(function () { return String(a.id()); }, null);
700
+ var accountName = prop(function () { return String(a.name()); }, null);
701
+ var lists = listTree(a, accountId, 1, []);
702
+ for (var j = 0; j < lists.length; j++) {
703
+ var l = lists[j];
704
+ l.accountName = accountName;
705
+ l.isDefault = l.id !== null && l.id === defaultListId;
706
+ // Counted per list, which is one Apple Event each — a handful, not one
707
+ // per reminder. Split so a caller can see a list's live workload without
708
+ // paging through years of finished items.
709
+ var counts = prop(function () {
710
+ var done = R.lists.byId(l.id).reminders.completed();
711
+ var total = done.length, open = 0;
712
+ for (var k = 0; k < done.length; k++) if (!done[k]) open++;
713
+ return { total: total, incomplete: open };
714
+ }, { total: null, incomplete: null });
715
+ l.reminderCount = counts.total;
716
+ l.incompleteCount = counts.incomplete;
717
+ out.push(l);
718
+ }
719
+ }
720
+ return ok(out);
721
+ `);
722
+ /**
723
+ * Every reminder's metadata, as bulk arrays.
724
+ *
725
+ * MEASURED on macOS 26.6 over 317 reminders: each bulk property fetch costs
726
+ * ~700ms and is independent of library size, so this is ~9 seconds of Apple
727
+ * Events. That is the price of the unprivileged lane, and it is why the result
728
+ * is cached on a TTL and why the index lane carries listing whenever it is
729
+ * live. The per-reminder alternative would be twelve events EACH.
730
+ *
731
+ * ## Subtasks are not reachable here
732
+ *
733
+ * The dictionary types `reminder.container` as "list OR reminder", which reads
734
+ * like subtasks are addressable over Apple Events. They are not: calling
735
+ * `container()` on a reminder threw on 60 of 60 attempts. So parentage is left
736
+ * null on this lane and the index fills it in from `ZPARENTREMINDER`.
737
+ *
738
+ * Subtasks are still LISTED — `R.reminders()` returns all 317, matching the
739
+ * store exactly — they simply arrive without a parent. Missing parentage and a
740
+ * missing reminder are very different claims, so `parentId` is null rather than
741
+ * the row being dropped.
742
+ */
743
+ const BULK_REMINDERS = script(`
744
+ var ids = R.reminders.id();
745
+ var count = ids.length;
746
+ var dueDates = prop(function () { return R.reminders.dueDate(); }, []);
747
+ var allDayDates = prop(function () { return R.reminders.alldayDueDate(); }, []);
748
+
749
+ var rows = zip(
750
+ ["id", "name", "body", "completed", "completionDate", "remindMeDate",
751
+ "priority", "flagged", "created", "modified"],
752
+ [
753
+ ids,
754
+ prop(function () { return R.reminders.name(); }, []),
755
+ prop(function () { return R.reminders.body(); }, []),
756
+ prop(function () { return R.reminders.completed(); }, []),
757
+ prop(function () { return R.reminders.completionDate(); }, []),
758
+ prop(function () { return R.reminders.remindMeDate(); }, []),
759
+ prop(function () { return R.reminders.priority(); }, []),
760
+ prop(function () { return R.reminders.flagged(); }, []),
761
+ prop(function () { return R.reminders.creationDate(); }, []),
762
+ prop(function () { return R.reminders.modificationDate(); }, [])
763
+ ],
764
+ count
765
+ );
766
+
767
+ var accounts = R.accounts();
768
+ var lists = [];
769
+ for (var i = 0; i < accounts.length; i++) {
770
+ var accountId = prop(function () { return String(accounts[i].id()); }, null);
771
+ lists = lists.concat(listTree(accounts[i], accountId, 1, []));
772
+ }
773
+ var member = membership(lists);
774
+ var listOf = member.map;
775
+ var accountNames = {};
776
+ for (var n = 0; n < accounts.length; n++) {
777
+ accountNames[String(prop(function () { return String(accounts[n].id()); }, ""))] =
778
+ prop(function () { return String(accounts[n].name()); }, null);
779
+ }
780
+
781
+ var unmapped = 0;
782
+ for (var r = 0; r < rows.length; r++) {
783
+ var row = rows[r];
784
+ row.id = String(row.id);
785
+ row.completionDate = iso(row.completionDate);
786
+ row.remindMeDate = iso(row.remindMeDate);
787
+ row.created = iso(row.created);
788
+ row.modified = iso(row.modified);
789
+
790
+ // Both properties are populated for every dated reminder, so the local
791
+ // time component is the only signal available without the index.
792
+ var due = r < dueDates.length ? dueDates[r] : null;
793
+ var allday = r < allDayDates.length ? allDayDates[r] : null;
794
+ row.dueDate = iso(due);
795
+ row.alldayDueDate = iso(allday);
796
+ row.allDayGuess = isMidnight(allday || due);
797
+ row.dueDay = dayOf(allday || due);
798
+
799
+ // Apple Events cannot answer this; the index does. Null means unknown.
800
+ row.parentId = null;
801
+
802
+ var where = listOf[row.id];
803
+ if (where) {
804
+ row.list = where.list;
805
+ row.listId = where.listId;
806
+ row.accountId = where.accountId;
807
+ row.account = accountNames[String(where.accountId)] || null;
808
+ } else {
809
+ row.list = null; row.listId = null; row.accountId = null; row.account = null;
810
+ unmapped++;
811
+ }
812
+ }
813
+
814
+ return ok({
815
+ count: count,
816
+ reminders: rows,
817
+ lists: lists,
818
+ unmapped: unmapped,
819
+ membershipVia: member.via
820
+ });
821
+ `);
822
+ /**
823
+ * Full detail for a specific set of reminders, by id.
824
+ *
825
+ * Used after the index narrows things down, and to re-read a reminder after a
826
+ * write so the result reflects what Reminders actually stored rather than what
827
+ * was requested.
828
+ */
829
+ const GET_REMINDERS = script(`
830
+ var out = [];
831
+ for (var i = 0; i < p.ids.length; i++) {
832
+ var id = String(p.ids[i]);
833
+ var r = null;
834
+ try { r = R.reminders.byId(id); } catch (e) { r = null; }
835
+ if (!r) { out.push({ id: id, found: false }); continue; }
836
+ // container() throws on a reminder on macOS 26.6 (60/60 attempts), so this
837
+ // is expected to be null. Kept because it costs nothing when it fails and
838
+ // would start working silently if Apple ever fixes it.
839
+ var container = prop(function () { return r.container(); }, null);
840
+ var containerClass = container === null ? null : prop(function () { return String(container.class()); }, null);
841
+ var dueRaw = prop(function () { return r.dueDate(); }, null);
842
+ var allDayRaw = prop(function () { return r.alldayDueDate(); }, null);
843
+ out.push({
844
+ id: id,
845
+ found: true,
846
+ name: prop(function () { return String(r.name()); }, null),
847
+ body: prop(function () { var b = r.body(); return b === null ? null : String(b); }, null),
848
+ completed: prop(function () { return r.completed(); }, null),
849
+ completionDate: iso(prop(function () { return r.completionDate(); }, null)),
850
+ dueDate: iso(dueRaw),
851
+ alldayDueDate: iso(allDayRaw),
852
+ allDayGuess: isMidnight(allDayRaw || dueRaw),
853
+ dueDay: dayOf(allDayRaw || dueRaw),
854
+ remindMeDate: iso(prop(function () { return r.remindMeDate(); }, null)),
855
+ priority: prop(function () { return r.priority(); }, 0),
856
+ flagged: prop(function () { return r.flagged(); }, false),
857
+ created: iso(prop(function () { return r.creationDate(); }, null)),
858
+ modified: iso(prop(function () { return r.modificationDate(); }, null)),
859
+ containerClass: containerClass,
860
+ containerId: container === null ? null : prop(function () { return String(container.id()); }, null),
861
+ containerName: container === null ? null : prop(function () { return String(container.name()); }, null)
862
+ });
863
+ }
864
+ return ok(out);
865
+ `);
866
+ //#endregion
867
+ //#region src/client/jxa/write.ts
868
+ /**
869
+ * Mutating scripts.
870
+ *
871
+ * These are the only place Reminders is asked to change anything, and every one
872
+ * of them re-reads the affected reminder afterwards: the result a tool returns
873
+ * is what Reminders stored, never what the caller requested. The two differ
874
+ * more often than you would expect — setting `dueDate` on an all-day reminder
875
+ * is a property assignment whose visible effect is decided by the app.
876
+ *
877
+ * Dates arrive as ISO-8601 strings carrying an explicit offset (see
878
+ * `dates.ts`) and are turned back into Date objects here. Passing a bare local
879
+ * string would have Reminders resolve it in whatever zone it feels like.
880
+ */
881
+ /** Read-back shape, shared by every write so their results are uniform. */
882
+ const READBACK = `
883
+ function readback(r) {
884
+ return {
885
+ id: prop(function () { return String(r.id()); }, null),
886
+ name: prop(function () { return String(r.name()); }, null),
887
+ body: prop(function () { var b = r.body(); return b === null ? null : String(b); }, null),
888
+ completed: prop(function () { return r.completed(); }, null),
889
+ completionDate: iso(prop(function () { return r.completionDate(); }, null)),
890
+ dueDate: iso(prop(function () { return r.dueDate(); }, null)),
891
+ alldayDueDate: iso(prop(function () { return r.alldayDueDate(); }, null)),
892
+ remindMeDate: iso(prop(function () { return r.remindMeDate(); }, null)),
893
+ priority: prop(function () { return r.priority(); }, 0),
894
+ flagged: prop(function () { return r.flagged(); }, false),
895
+ created: iso(prop(function () { return r.creationDate(); }, null)),
896
+ modified: iso(prop(function () { return r.modificationDate(); }, null))
897
+ };
898
+ }
899
+
900
+ /** Apply the optional fields a create and an update have in common. */
901
+ function applyFields(target, f) {
902
+ if (f.name !== undefined && f.name !== null) target.name = String(f.name);
903
+ if (f.body !== undefined) target.body = f.body === null ? "" : String(f.body);
904
+ if (f.dueDate !== undefined && f.dueDate !== null) target.dueDate = new Date(f.dueDate);
905
+ if (f.alldayDueDate !== undefined && f.alldayDueDate !== null) target.alldayDueDate = new Date(f.alldayDueDate);
906
+ if (f.remindMeDate !== undefined && f.remindMeDate !== null) target.remindMeDate = new Date(f.remindMeDate);
907
+ if (f.priority !== undefined && f.priority !== null) target.priority = f.priority;
908
+ if (f.flagged !== undefined && f.flagged !== null) target.flagged = f.flagged;
909
+ if (f.completed !== undefined && f.completed !== null) target.completed = f.completed;
910
+ }
911
+ `;
912
+ /**
913
+ * Create a reminder.
914
+ *
915
+ * `listId` is optional: with none, Reminders' own default list wins, which is
916
+ * the same list the app would have used. Guessing "the first list" instead
917
+ * would put things somewhere the person does not look.
918
+ */
919
+ const CREATE_REMINDER = script(`${READBACK}
920
+ var target = null;
921
+ if (p.listId) {
922
+ try { target = R.lists.byId(String(p.listId)); } catch (e) { target = null; }
923
+ if (!target) return err("LIST_NOT_FOUND", "No list with id " + p.listId);
924
+ } else {
925
+ target = prop(function () { return R.defaultList; }, null);
926
+ if (!target) return err("NO_DEFAULT_LIST", "Reminders reports no default list.");
927
+ }
928
+
929
+ var fields = { name: String(p.name) };
930
+ var r = R.Reminder(fields);
931
+ target.reminders.push(r);
932
+ // Set the rest AFTER the push: a Reminder object that is not yet in a
933
+ // container has nowhere to store a date, and the assignment is dropped.
934
+ applyFields(r, p);
935
+ return ok(readback(r));
936
+ `, { allowLaunch: true });
937
+ /** Update whatever fields were supplied, leaving the rest untouched. */
938
+ const UPDATE_REMINDER = script(`${READBACK}
939
+ var r = null;
940
+ try { r = R.reminders.byId(String(p.id)); } catch (e) { r = null; }
941
+ if (!r) return err("REMINDER_NOT_FOUND", "No reminder with id " + p.id);
942
+ applyFields(r, p);
943
+ return ok(readback(r));
944
+ `, { allowLaunch: true });
945
+ /**
946
+ * Complete (or un-complete) reminders in bulk.
947
+ *
948
+ * Separate from update because it is the single most common mutation and is
949
+ * naturally plural — a caller ticking off four things should not have to make
950
+ * four round trips.
951
+ */
952
+ const COMPLETE_REMINDERS = script(`${READBACK}
953
+ var out = [];
954
+ for (var i = 0; i < p.ids.length; i++) {
955
+ var id = String(p.ids[i]);
956
+ var r = null;
957
+ try { r = R.reminders.byId(id); } catch (e) { r = null; }
958
+ if (!r) { out.push({ id: id, found: false }); continue; }
959
+ r.completed = p.completed === false ? false : true;
960
+ var after = readback(r);
961
+ after.found = true;
962
+ out.push(after);
963
+ }
964
+ return ok(out);
965
+ `, { allowLaunch: true });
966
+ /**
967
+ * Move reminders to another list.
968
+ *
969
+ * **This is a copy followed by a delete, and it cannot be anything else.**
970
+ * `reminder.container` is declared `access="r"` in the scripting dictionary, so
971
+ * there is no assignment that relocates a reminder. Two consequences the caller
972
+ * has to know about, and which the tool description repeats:
973
+ *
974
+ * - the reminder gets a **new id**, so any ref held for it stops resolving
975
+ * - the creation date becomes now, because a new object is what was made
976
+ *
977
+ * The original is deleted only after the copy has been created and read back.
978
+ * If the copy fails, nothing is destroyed and the failure is reported per id.
979
+ */
980
+ const MOVE_REMINDERS = script(`${READBACK}
981
+ var target = null;
982
+ try { target = R.lists.byId(String(p.listId)); } catch (e) { target = null; }
983
+ if (!target) return err("LIST_NOT_FOUND", "No list with id " + p.listId);
984
+
985
+ var out = [];
986
+ for (var i = 0; i < p.ids.length; i++) {
987
+ var id = String(p.ids[i]);
988
+ var src = null;
989
+ try { src = R.reminders.byId(id); } catch (e) { src = null; }
990
+ if (!src) { out.push({ id: id, found: false }); continue; }
991
+
992
+ var snapshot = readback(src);
993
+ var copy = R.Reminder({ name: snapshot.name === null ? "" : snapshot.name });
994
+ target.reminders.push(copy);
995
+ applyFields(copy, {
996
+ body: snapshot.body,
997
+ dueDate: snapshot.dueDate,
998
+ alldayDueDate: snapshot.alldayDueDate,
999
+ remindMeDate: snapshot.remindMeDate,
1000
+ priority: snapshot.priority,
1001
+ flagged: snapshot.flagged,
1002
+ completed: snapshot.completed
1003
+ });
1004
+ var made = readback(copy);
1005
+ if (made.id === null) {
1006
+ out.push({ id: id, found: true, moved: false, error: "the copy could not be read back; nothing was deleted" });
1007
+ continue;
1008
+ }
1009
+ // Only now is the original expendable.
1010
+ var deleted = true;
1011
+ try { R.delete(src); } catch (e) { deleted = false; }
1012
+ made.found = true;
1013
+ made.moved = true;
1014
+ made.previousId = id;
1015
+ made.originalDeleted = deleted;
1016
+ out.push(made);
1017
+ }
1018
+ return ok(out);
1019
+ `, { allowLaunch: true });
1020
+ /** Delete reminders. Irreversible: they do not land anywhere recoverable. */
1021
+ const DELETE_REMINDERS = script(`
1022
+ var deleted = 0;
1023
+ var missing = [];
1024
+ for (var i = 0; i < p.ids.length; i++) {
1025
+ var id = String(p.ids[i]);
1026
+ var r = null;
1027
+ try { r = R.reminders.byId(id); } catch (e) { r = null; }
1028
+ if (!r) { missing.push(id); continue; }
1029
+ try { R.delete(r); deleted++; } catch (e) { missing.push(id); }
1030
+ }
1031
+ return ok({ deleted: deleted, missing: missing });
1032
+ `, { allowLaunch: true });
1033
+ //#endregion
1034
+ //#region src/client/store.ts
1035
+ /**
1036
+ * The index lane: Reminders' Core Data store, read-only.
1037
+ *
1038
+ * Every fact encoded here was measured by `scripts/probe-reminders.mjs` against
1039
+ * a real store on macOS 26.6 — see docs/reminders.md. The three that matter:
1040
+ *
1041
+ * 1. **The bridge is `ZREMCDREMINDER.ZCKIDENTIFIER`**, which holds the bare
1042
+ * UUID from the Apple Events id `x-apple-reminder://<uuid>`. Found by
1043
+ * scanning all 139 TEXT columns for a known id rather than by guessing a
1044
+ * name — the guess would have been plausible and wrong, which is how the
1045
+ * Notes body decoder passed at 51% accuracy.
1046
+ *
1047
+ * 2. **The live predicate is `ZMARKEDFORDELETION` falsy.** Verified by
1048
+ * comparing ID SETS against Apple Events, not counts: all rows gave 338 with
1049
+ * 21 extra, the filtered set gave exactly 317 with 0 missing and 0 extra. A
1050
+ * matching count is not a matching set.
1051
+ *
1052
+ * 3. **`ZALLDAY` is the authoritative all-day flag**, and it exists nowhere
1053
+ * else. Apple Events populates both `due date` and `allday due date` for
1054
+ * every dated reminder — 144 of 144 carried both — so presence discriminates
1055
+ * nothing there. This column is the whole reason the index improves
1056
+ * correctness and not merely speed.
1057
+ *
1058
+ * Writes never come here. The Apple Events lane is the authority for mutation,
1059
+ * as in Mail and Notes; this store is opened read-only and `PRAGMA query_only`
1060
+ * is set on top.
1061
+ */
1062
+ /** Tables the lane cannot work without. Anything else degrades to a null field. */
1063
+ const REQUIRED = ["ZREMCDREMINDER", "ZREMCDBASELIST"];
1064
+ /** SQLite hands back unknown; only a real number is a value. */
1065
+ const num = (v) => typeof v === "number" ? v : null;
1066
+ /** Core Data seconds -> ISO, or null. Guards the 31-year offset mistake. */
1067
+ const toIso = (seconds, offset) => {
1068
+ if (seconds === null || seconds === void 0 || !Number.isFinite(seconds)) return null;
1069
+ const d = /* @__PURE__ */ new Date((seconds + offset) * 1e3);
1070
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
1071
+ };
1072
+ var ReminderStore = class {
1073
+ db;
1074
+ mode;
1075
+ caps;
1076
+ constructor(db, mode, caps) {
1077
+ this.db = db;
1078
+ this.mode = mode;
1079
+ this.caps = caps;
1080
+ }
1081
+ /** Only select columns this store actually has, so a rename degrades one field. */
1082
+ #col(table, name, as = name) {
1083
+ return (table === "reminder" ? this.caps.reminderColumns : this.caps.listColumns).has(name) ? `r."${name}" AS ${as}` : `NULL AS ${as}`;
1084
+ }
1085
+ /**
1086
+ * The live-reminder predicate, verified by set comparison against Apple
1087
+ * Events. `ZMARKEDFORDELETION` is a tombstone Reminders leaves behind until
1088
+ * the CloudKit sync settles; without this filter the store reports 21 rows
1089
+ * the user deleted and cannot see.
1090
+ */
1091
+ #live() {
1092
+ return this.caps.reminderColumns.has("ZMARKEDFORDELETION") ? `(r."ZMARKEDFORDELETION" IS NULL OR r."ZMARKEDFORDELETION" = 0)` : "1 = 1";
1093
+ }
1094
+ #selectList() {
1095
+ return this.caps.listColumns.has("ZNAME") ? `l."ZNAME"` : "NULL";
1096
+ }
1097
+ #rowToReminder = (row) => {
1098
+ const o = this.caps.epochOffset;
1099
+ return {
1100
+ primaryKey: row.pk,
1101
+ uuid: row.uuid === null || row.uuid === void 0 ? null : String(row.uuid).toUpperCase(),
1102
+ title: row.title ?? null,
1103
+ notes: row.notes ?? null,
1104
+ completed: Boolean(row.completed),
1105
+ allDay: Boolean(row.allday),
1106
+ due: toIso(num(row.due), o),
1107
+ completionDate: toIso(num(row.completionDate), o),
1108
+ created: toIso(num(row.created), o),
1109
+ modified: toIso(num(row.modified), o),
1110
+ priority: num(row.priority),
1111
+ flagged: Boolean(row.flagged),
1112
+ listPk: num(row.listPk),
1113
+ listName: row.listName ?? null,
1114
+ parentPk: num(row.parentPk),
1115
+ parentUuid: row.parentUuid === null || row.parentUuid === void 0 ? null : String(row.parentUuid).toUpperCase()
1116
+ };
1117
+ };
1118
+ #baseSelect() {
1119
+ return `SELECT r."Z_PK" AS pk,
1120
+ ${this.#col("reminder", "ZCKIDENTIFIER", "uuid")},
1121
+ ${this.#col("reminder", "ZTITLE", "title")},
1122
+ ${this.#col("reminder", "ZNOTES", "notes")},
1123
+ ${this.#col("reminder", "ZCOMPLETED", "completed")},
1124
+ ${this.#col("reminder", "ZALLDAY", "allday")},
1125
+ ${this.#col("reminder", "ZDUEDATE", "due")},
1126
+ ${this.#col("reminder", "ZCOMPLETIONDATE", "completionDate")},
1127
+ ${this.#col("reminder", "ZCREATIONDATE", "created")},
1128
+ ${this.#col("reminder", "ZLASTMODIFIEDDATE", "modified")},
1129
+ ${this.#col("reminder", "ZPRIORITY", "priority")},
1130
+ ${this.#col("reminder", "ZFLAGGED", "flagged")},
1131
+ ${this.#col("reminder", "ZLIST", "listPk")},
1132
+ ${this.#col("reminder", "ZPARENTREMINDER", "parentPk")},
1133
+ ${this.#col("reminder", "ZCKPARENTREMINDERIDENTIFIER", "parentUuid")},
1134
+ ${this.#selectList()} AS listName
1135
+ FROM ZREMCDREMINDER r
1136
+ LEFT JOIN ZREMCDBASELIST l ON l."Z_PK" = r."ZLIST"`;
1137
+ }
1138
+ search(q) {
1139
+ const where = [this.#live()];
1140
+ const params = [];
1141
+ if (!q.includeCompleted && this.caps.reminderColumns.has("ZCOMPLETED")) where.push(`(r."ZCOMPLETED" IS NULL OR r."ZCOMPLETED" = 0)`);
1142
+ if (q.listPk !== void 0) {
1143
+ where.push(`r."ZLIST" = ?`);
1144
+ params.push(q.listPk);
1145
+ }
1146
+ if (q.query) {
1147
+ const needle = `%${escapeLike(q.query)}%`;
1148
+ const full = (q.scope ?? "full") === "full" && this.caps.reminderColumns.has("ZNOTES");
1149
+ where.push(full ? `(r."ZTITLE" LIKE ? ESCAPE '\\' OR r."ZNOTES" LIKE ? ESCAPE '\\')` : `r."ZTITLE" LIKE ? ESCAPE '\\'`);
1150
+ params.push(needle);
1151
+ if (full) params.push(needle);
1152
+ }
1153
+ return this.db.prepare(`${this.#baseSelect()} WHERE ${where.join(" AND ")}
1154
+ ORDER BY (r."ZDUEDATE" IS NULL), r."ZDUEDATE" ASC, r."ZTITLE" ASC
1155
+ LIMIT ? OFFSET ?`).all(...params, q.limit, q.offset ?? 0).map(this.#rowToReminder);
1156
+ }
1157
+ byUuid(uuid) {
1158
+ if (!this.caps.reminderColumns.has("ZCKIDENTIFIER")) return null;
1159
+ const row = this.db.prepare(`${this.#baseSelect()} WHERE ${this.#live()} AND UPPER(r."ZCKIDENTIFIER") = ? LIMIT 1`).get(uuid.toUpperCase());
1160
+ return row ? this.#rowToReminder(row) : null;
1161
+ }
1162
+ /**
1163
+ * Subtasks, which Apple Events cannot reach at all — `container()` throws on
1164
+ * every reminder, so this column is the only way to know a reminder has a
1165
+ * parent.
1166
+ */
1167
+ subtasksOf(parentPk) {
1168
+ if (!this.caps.reminderColumns.has("ZPARENTREMINDER")) return [];
1169
+ return this.db.prepare(`${this.#baseSelect()} WHERE ${this.#live()} AND r."ZPARENTREMINDER" = ?
1170
+ ORDER BY (r."ZDUEDATE" IS NULL), r."ZDUEDATE" ASC, r."ZTITLE" ASC`).all(parentPk).map(this.#rowToReminder);
1171
+ }
1172
+ lists() {
1173
+ const c = this.caps.listColumns;
1174
+ const pick = (n, as) => c.has(n) ? `"${n}" AS ${as}` : `NULL AS ${as}`;
1175
+ const live = c.has("ZMARKEDFORDELETION") ? `WHERE ("ZMARKEDFORDELETION" IS NULL OR "ZMARKEDFORDELETION" = 0)` : "";
1176
+ return this.db.prepare(`SELECT "Z_PK" AS pk, ${pick("ZCKIDENTIFIER", "uuid")}, ${pick("ZNAME", "name")},
1177
+ ${pick("ZISGROUP", "isGroup")}, ${pick("ZPARENTLIST", "parentListPk")},
1178
+ ${pick("ZSMARTLISTTYPE", "smartListType")}
1179
+ FROM ZREMCDBASELIST ${live} ORDER BY "ZNAME"`).all().map((r) => ({
1180
+ primaryKey: r.pk,
1181
+ uuid: r.uuid === null || r.uuid === void 0 ? null : String(r.uuid).toUpperCase(),
1182
+ name: r.name ?? null,
1183
+ isGroup: Boolean(r.isGroup),
1184
+ parentListPk: typeof r.parentListPk === "number" ? r.parentListPk : null,
1185
+ smartListType: r.smartListType ?? null
1186
+ }));
1187
+ }
1188
+ attachmentsOf(reminderPk) {
1189
+ if (!this.caps.hasAttachments) return [];
1190
+ return this.db.prepare(`SELECT "Z_PK" AS pk, "ZCKIDENTIFIER" AS uuid, "ZREMINDER" AS reminderPk,
1191
+ "ZFILENAME" AS filename, "ZUTI" AS uti, "ZSHA512SUM" AS sha512
1192
+ FROM ZREMCDSAVEDATTACHMENT
1193
+ WHERE "ZREMINDER" = ? AND ("ZMARKEDFORDELETION" IS NULL OR "ZMARKEDFORDELETION" = 0)`).all(reminderPk).map((r) => ({
1194
+ primaryKey: r.pk,
1195
+ uuid: r.uuid === null || r.uuid === void 0 ? null : String(r.uuid).toUpperCase(),
1196
+ reminderPk: typeof r.reminderPk === "number" ? r.reminderPk : null,
1197
+ filename: r.filename ?? null,
1198
+ uti: r.uti ?? null,
1199
+ sha512: r.sha512 ?? null
1200
+ }));
1201
+ }
1202
+ /**
1203
+ * Alarms, recurrence and location for one reminder.
1204
+ *
1205
+ * `ZREMCDOBJECT` is polymorphic — alarm rows and recurrence rows share it and
1206
+ * are told apart by which columns are populated, not by a type column we can
1207
+ * rely on. So this reports presence and counts rather than pretending to
1208
+ * reconstruct an RFC 5545 rule from columns nobody has documented.
1209
+ */
1210
+ enrichmentOf(reminderPk) {
1211
+ const empty = {
1212
+ alarmCount: 0,
1213
+ hasRecurrence: false,
1214
+ location: null
1215
+ };
1216
+ if (!this.caps.hasObjects) return empty;
1217
+ const rows = this.db.prepare(`SELECT "ZFREQUENCY" AS frequency, "ZLATITUDE" AS latitude, "ZLONGITUDE" AS longitude,
1218
+ "ZPROXIMITY" AS proximity, "ZALARMUID" AS alarmUid
1219
+ FROM ZREMCDOBJECT WHERE "ZREMINDER" = ?`).all(reminderPk);
1220
+ if (!rows.length) return empty;
1221
+ let alarmCount = 0;
1222
+ let hasRecurrence = false;
1223
+ let location = null;
1224
+ for (const r of rows) {
1225
+ if (r.alarmUid !== null && r.alarmUid !== void 0) alarmCount += 1;
1226
+ if (typeof r.frequency === "number") hasRecurrence = true;
1227
+ if (typeof r.latitude === "number" && typeof r.longitude === "number" && !location) location = {
1228
+ latitude: r.latitude,
1229
+ longitude: r.longitude,
1230
+ proximity: typeof r.proximity === "number" ? r.proximity : null
1231
+ };
1232
+ }
1233
+ return {
1234
+ alarmCount,
1235
+ hasRecurrence,
1236
+ location
1237
+ };
1238
+ }
1239
+ };
1240
+ /** Read the store's shape once, so every query can degrade per column. */
1241
+ const introspect = (db) => {
1242
+ const reminderColumns = new Set(columnsOf(db, "ZREMCDREMINDER"));
1243
+ const listColumns = new Set(columnsOf(db, "ZREMCDBASELIST"));
1244
+ for (const t of REQUIRED) if ((t === "ZREMCDREMINDER" ? reminderColumns : listColumns).size === 0) throw new SchemaDriftError(`This Reminders store has no ${t} table. It was probed on macOS 26.6 with schema fingerprint 278b001e3c55; re-run \`pnpm probe:reminders\` to see what changed.`);
1245
+ return {
1246
+ fingerprint: fingerprintSchema(db),
1247
+ reminderColumns,
1248
+ listColumns,
1249
+ hasAttachments: columnsOf(db, "ZREMCDSAVEDATTACHMENT").length > 0,
1250
+ hasObjects: columnsOf(db, "ZREMCDOBJECT").length > 0,
1251
+ epochOffset: CORE_DATA_EPOCH_OFFSET
1252
+ };
1253
+ };
1254
+ const openStore = (path, mode, logger) => {
1255
+ if (!path) return null;
1256
+ const { db, mode: used, validated } = openReadOnly(path, mode, {
1257
+ label: "Reminders store",
1258
+ envVar: "APPLE_REMINDERS_INDEX_MODE",
1259
+ validate: introspect,
1260
+ fatal: (err) => err instanceof SchemaDriftError,
1261
+ onFallback: () => logger?.debug?.("opened the Reminders store with immutable=1, which skips the write-ahead log — very recent changes may be missing until Reminders checkpoints.")
1262
+ });
1263
+ return new ReminderStore(db, used, validated);
1264
+ };
1265
+ //#endregion
1266
+ //#region src/client/reminders.ts
1267
+ /**
1268
+ * Render a due date for the caller.
1269
+ *
1270
+ * An all-day reminder names a DAY, and reporting it as an instant is wrong
1271
+ * rather than merely ugly — the same value reads as a different date either
1272
+ * side of Greenwich.
1273
+ *
1274
+ * Which day, though, depends on the lane, because the two genuinely disagree.
1275
+ * The same reminder, due 9 November, measured on a real library:
1276
+ *
1277
+ * Apple Events 2025-11-08T23:00:00Z LOCAL midnight (Paris, UTC+1)
1278
+ * ZDUEDATE 2025-11-09T00:00:00Z UTC midnight
1279
+ *
1280
+ * So neither lane's string can be sliced by the other's rule. Each converts on
1281
+ * its own terms — JXA formats from local components, the store from UTC — and
1282
+ * hands the finished day in here.
1283
+ */
1284
+ const renderDue = (instant, allDay, day) => allDay ? day : instant;
1285
+ /** The store keeps all-day dates at UTC midnight, so the UTC date IS the day. */
1286
+ const utcDay = (iso) => iso ? iso.slice(0, 10) : null;
1287
+ /** Sort key for due dates: undated reminders sort last rather than first. */
1288
+ const dueAt = (s) => s.due ? new Date(s.due).getTime() : Number.MAX_SAFE_INTEGER;
1289
+ /**
1290
+ * The Reminders client.
1291
+ *
1292
+ * Two lanes, and which one answers depends on what was granted:
1293
+ *
1294
+ * - **Apple Events** — accounts, lists, every mutation, and the whole core
1295
+ * model. Always the authority: after a write, the result is what Reminders
1296
+ * re-read, never what was requested.
1297
+ * - **Index** — the Core Data store, for the fields the scripting dictionary
1298
+ * has no class for at all: tags, url, recurrence, alarms.
1299
+ *
1300
+ * That split is the opposite way round from Mail, where the file lane exists
1301
+ * because Apple Events search took 74 seconds. Here the dictionary is complete
1302
+ * enough to ship on, and the permission buys capability rather than speed —
1303
+ * which is the rule recorded in docs/distribution.md.
1304
+ */
1305
+ var AppleRemindersClient = class AppleRemindersClient {
1306
+ config;
1307
+ runner;
1308
+ #logger;
1309
+ #now;
1310
+ #cache = null;
1311
+ #store = null;
1312
+ #storeTried = false;
1313
+ constructor(opts) {
1314
+ this.config = opts.config;
1315
+ this.#logger = opts.logger;
1316
+ this.#now = opts.now ?? (() => /* @__PURE__ */ new Date());
1317
+ this.runner = opts.osascript ?? createOsascriptRunner({
1318
+ osascriptPath: opts.config.osascriptPath,
1319
+ timeoutMs: opts.config.osascriptTimeoutMs,
1320
+ surface: REMINDERS_SURFACE,
1321
+ logger: opts.logger
1322
+ });
1323
+ }
1324
+ locate() {
1325
+ return locateStore({ storePath: this.config.storePath });
1326
+ }
1327
+ /** Open the index once and remember the outcome, including the failure. */
1328
+ index() {
1329
+ if (this.#storeTried) return this.#store;
1330
+ this.#storeTried = true;
1331
+ if (this.config.indexMode === "off") return null;
1332
+ try {
1333
+ this.#store = openStore(this.locate().storePath, this.config.indexMode, this.#logger);
1334
+ } catch (err) {
1335
+ this.#logger?.debug?.("index lane unavailable", err);
1336
+ this.#store = null;
1337
+ }
1338
+ return this.#store;
1339
+ }
1340
+ /**
1341
+ * Probe both lanes.
1342
+ *
1343
+ * Apple Events is probed twice with a gap: the first event is what triggers
1344
+ * the Automation prompt, and it can return failure while the user is still
1345
+ * deciding — reporting "denied" then would be wrong.
1346
+ */
1347
+ async lanes() {
1348
+ let applescript = "unavailable";
1349
+ for (let attempt = 0; attempt < 2; attempt += 1) try {
1350
+ await this.runner.run(LIST_ACCOUNTS);
1351
+ applescript = "live";
1352
+ break;
1353
+ } catch (err) {
1354
+ this.#logger?.debug?.("applescript probe failed", err);
1355
+ if (attempt === 0) await new Promise((r) => setTimeout(r, 400));
1356
+ }
1357
+ const located = this.locate();
1358
+ const store = this.index();
1359
+ return {
1360
+ applescript,
1361
+ index: this.config.indexMode === "off" ? "disabled" : store ? "live" : "unavailable",
1362
+ indexMode: store?.mode ?? null,
1363
+ storeFingerprint: store?.caps.fingerprint ?? null,
1364
+ reason: store ? null : located.reason
1365
+ };
1366
+ }
1367
+ #allowedAccount(name) {
1368
+ const list = this.config.accounts;
1369
+ if (!list.length) return true;
1370
+ return Boolean(name && list.some((a) => a.toLowerCase() === name.toLowerCase()));
1371
+ }
1372
+ #allowedList(name) {
1373
+ const list = this.config.lists;
1374
+ if (!list.length) return true;
1375
+ return Boolean(name && list.some((l) => l.toLowerCase() === name.toLowerCase()));
1376
+ }
1377
+ async accounts() {
1378
+ return (await withBusyRetry(() => this.runner.run(LIST_ACCOUNTS))).accounts.filter((a) => this.#allowedAccount(a.name));
1379
+ }
1380
+ async lists() {
1381
+ return (await withBusyRetry(() => this.runner.run(LIST_LISTS))).filter((l) => this.#allowedAccount(l.accountName) && this.#allowedList(l.name));
1382
+ }
1383
+ /**
1384
+ * Every reminder, cached on a TTL.
1385
+ *
1386
+ * Same trade Notes documented: there is no cheap way to ask "has anything
1387
+ * changed" — the freshness check is itself a bulk fetch of ids and
1388
+ * modification dates, which costs about what re-reading everything costs. So
1389
+ * a TTL with bounded staleness is the honest option, and it is configurable
1390
+ * because the right bound depends on whether a person is actively editing.
1391
+ */
1392
+ async #bulk() {
1393
+ const ttl = this.config.searchCacheTtlMs;
1394
+ const now = this.#now().getTime();
1395
+ if (this.#cache && ttl > 0 && now - this.#cache.at < ttl) return this.#cache.data;
1396
+ const data = await withBusyRetry(() => this.runner.run(BULK_REMINDERS, {}));
1397
+ if (data.membershipVia === "per-list") this.#logger?.debug?.(`the chained membership fetch did not work; fell back to one call per list (${data.lists.length} extra Apple Events).`);
1398
+ if (data.unmapped) this.#logger?.debug?.(`${data.unmapped} reminders belong to no list — usually subtasks, whose parentage only the index lane can resolve.`);
1399
+ this.#cache = {
1400
+ at: now,
1401
+ data
1402
+ };
1403
+ return data;
1404
+ }
1405
+ /** Drop the cache after a write, so the next read reflects it. */
1406
+ invalidate() {
1407
+ this.#cache = null;
1408
+ }
1409
+ #summarise(r, source = "apple-events") {
1410
+ const allDay = Boolean(r.allDayGuess);
1411
+ return {
1412
+ ref: encodeRef(r.id),
1413
+ name: r.name,
1414
+ completed: Boolean(r.completed),
1415
+ due: renderDue(r.dueDate ?? r.alldayDueDate, allDay, r.dueDay ?? null),
1416
+ dueAllDay: allDay,
1417
+ dueAllDaySource: "heuristic",
1418
+ remindMe: r.remindMeDate,
1419
+ priority: toPriorityName(r.priority),
1420
+ flagged: Boolean(r.flagged),
1421
+ list: r.list,
1422
+ account: r.account,
1423
+ parentRef: r.parentId ? encodeRef(r.parentId) : null,
1424
+ created: r.created,
1425
+ modified: r.modified,
1426
+ source
1427
+ };
1428
+ }
1429
+ #matches(r, f, now) {
1430
+ if (!this.#allowedAccount(r.account) || !this.#allowedList(r.list)) return false;
1431
+ if (!(f.includeCompleted ?? this.config.includeCompleted) && r.completed) return false;
1432
+ if (f.list) {
1433
+ const want = f.list.toLowerCase();
1434
+ if ((r.list ?? "").toLowerCase() !== want && r.listId !== f.list) return false;
1435
+ }
1436
+ if (f.flagged !== void 0 && Boolean(r.flagged) !== f.flagged) return false;
1437
+ if (f.priority && toPriorityName(r.priority) !== f.priority) return false;
1438
+ const due = r.alldayDueDate ?? r.dueDate;
1439
+ if (f.hasDueDate !== void 0 && Boolean(due) !== f.hasDueDate) return false;
1440
+ if (f.dueBefore || f.dueAfter) {
1441
+ if (!due) return false;
1442
+ const at = new Date(due).getTime();
1443
+ if (f.dueBefore && at > parseBound("dueBefore", f.dueBefore, "end", now).getTime()) return false;
1444
+ if (f.dueAfter && at < parseBound("dueAfter", f.dueAfter, "start", now).getTime()) return false;
1445
+ }
1446
+ return true;
1447
+ }
1448
+ /** Soonest-due first, then by urgency, with undated reminders last. */
1449
+ static #order(a, b) {
1450
+ return dueAt(a) - dueAt(b) || a.name?.localeCompare(b.name ?? "") || 0;
1451
+ }
1452
+ /** An index row wears the same shape as an Apple Events one. */
1453
+ #fromIndex(r, listName) {
1454
+ return {
1455
+ ref: r.uuid ? refFromUuid(r.uuid) : encodeRef(String(r.primaryKey)),
1456
+ name: r.title,
1457
+ completed: r.completed,
1458
+ due: renderDue(r.due, r.allDay, utcDay(r.due)),
1459
+ dueAllDay: r.allDay,
1460
+ dueAllDaySource: "index",
1461
+ remindMe: null,
1462
+ priority: toPriorityName(r.priority),
1463
+ flagged: r.flagged,
1464
+ list: listName ?? r.listName,
1465
+ account: null,
1466
+ parentRef: r.parentUuid ? refFromUuid(r.parentUuid) : null,
1467
+ created: r.created,
1468
+ modified: r.modified,
1469
+ source: "index"
1470
+ };
1471
+ }
1472
+ /** Resolve a list name to its index primary key, for an index-side filter. */
1473
+ #listPk(store, name) {
1474
+ const want = name.toLowerCase();
1475
+ return store.lists().find((l) => l.name?.toLowerCase() === want)?.primaryKey;
1476
+ }
1477
+ /**
1478
+ * Post-filter index rows for the predicates SQL did not apply.
1479
+ *
1480
+ * Dates are compared here rather than in SQL because the bounds accept
1481
+ * relative offsets, which have to be resolved against the same clock the rest
1482
+ * of the request uses.
1483
+ */
1484
+ #matchesIndex(r, f, now) {
1485
+ if (!this.#allowedList(r.list)) return false;
1486
+ if (f.flagged !== void 0 && r.flagged !== f.flagged) return false;
1487
+ if (f.priority && r.priority !== f.priority) return false;
1488
+ if (f.hasDueDate !== void 0 && Boolean(r.due) !== f.hasDueDate) return false;
1489
+ if (f.dueBefore || f.dueAfter) {
1490
+ if (!r.due) return false;
1491
+ const at = new Date(r.due).getTime();
1492
+ if (f.dueBefore && at > parseBound("dueBefore", f.dueBefore, "end", now).getTime()) return false;
1493
+ if (f.dueAfter && at < parseBound("dueAfter", f.dueAfter, "start", now).getTime()) return false;
1494
+ }
1495
+ return true;
1496
+ }
1497
+ /**
1498
+ * The index path for listing and search.
1499
+ *
1500
+ * Preferred whenever the store is readable, and not only for scale: a bulk
1501
+ * Apple Events read costs ~700ms PER PROPERTY on this bridge — about nine
1502
+ * seconds for a full listing, whatever the library size. It is also the only
1503
+ * lane that knows whether a due date is all-day.
1504
+ */
1505
+ #fromStore(store, filters, query, scope, now) {
1506
+ const listPk = filters.list ? this.#listPk(store, filters.list) : void 0;
1507
+ if (filters.list && listPk === void 0) return [];
1508
+ return store.search({
1509
+ ...query ? { query } : {},
1510
+ ...scope ? { scope } : {},
1511
+ ...listPk === void 0 ? {} : { listPk },
1512
+ includeCompleted: filters.includeCompleted ?? this.config.includeCompleted,
1513
+ limit: Math.min(filters.limit * 4 + 50, 2e3)
1514
+ }).map((r) => this.#fromIndex(r)).filter((r) => this.#matchesIndex(r, filters, now)).slice(0, filters.limit);
1515
+ }
1516
+ /**
1517
+ * Whether the index can answer this request faithfully.
1518
+ *
1519
+ * The store has no readable account name — `ZREMCDACCOUNTLISTDATA` is a blob
1520
+ * and nothing else carries one — so an account allowlist cannot be applied on
1521
+ * that lane. Returning index rows anyway would silently ignore the setting
1522
+ * whose entire job is limiting what gets read, and would do so ONLY on
1523
+ * machines with Full Disk Access, which is exactly where it matters. So a
1524
+ * configured allowlist takes the slower Apple Events lane instead.
1525
+ */
1526
+ #indexCanAnswer() {
1527
+ return this.config.accounts.length === 0;
1528
+ }
1529
+ async listReminders(filters) {
1530
+ const now = this.#now();
1531
+ const store = this.#indexCanAnswer() ? this.index() : null;
1532
+ if (store) return this.#fromStore(store, filters, void 0, void 0, now);
1533
+ return (await this.#bulk()).reminders.filter((r) => this.#matches(r, filters, now)).map((r) => this.#summarise(r)).toSorted(AppleRemindersClient.#order).slice(0, Math.min(filters.limit, this.config.degradedMaxReminders));
1534
+ }
1535
+ /**
1536
+ * Text search over name and, optionally, body.
1537
+ *
1538
+ * Filtering happens in JS over the bulk arrays rather than through a `whose`
1539
+ * specifier. `whose` evaluates per item across the Apple Event bridge, which
1540
+ * Notes measured at 6.9x slower for a substring match on a comparable library.
1541
+ */
1542
+ async searchReminders(query, opts) {
1543
+ const now = this.#now();
1544
+ const needle = query.trim().toLowerCase();
1545
+ const full = (opts.scope ?? "full") === "full";
1546
+ const store = this.#indexCanAnswer() ? this.index() : null;
1547
+ if (store) return this.#fromStore(store, opts, query.trim(), opts.scope ?? "full", now);
1548
+ return (await this.#bulk()).reminders.filter((r) => this.#matches(r, opts, now)).filter((r) => {
1549
+ if (!needle) return true;
1550
+ if ((r.name ?? "").toLowerCase().includes(needle)) return true;
1551
+ return full && (r.body ?? "").toLowerCase().includes(needle);
1552
+ }).map((r) => this.#summarise(r)).toSorted(AppleRemindersClient.#order).slice(0, Math.min(opts.limit, this.config.degradedMaxReminders));
1553
+ }
1554
+ /**
1555
+ * One reminder in full.
1556
+ *
1557
+ * Apple Events is the authority for the core model, and the index supplies
1558
+ * what the dictionary has no class for: the authoritative all-day flag,
1559
+ * subtasks (`container()` throws on every reminder, so there is no other
1560
+ * way), attachments, alarms, recurrence and location.
1561
+ *
1562
+ * The two are joined on the UUID inside the Apple Events id — measured, by
1563
+ * scanning every TEXT column in the store for a real id rather than guessing
1564
+ * a column name.
1565
+ */
1566
+ async getReminder(ref) {
1567
+ const { id, uuid } = decodeRef(ref);
1568
+ const row = (await withBusyRetry(() => this.runner.run(GET_REMINDERS, { ids: [id] })))[0];
1569
+ if (!row?.found) throw new ReminderNotFoundError(ref);
1570
+ const summary = this.#summarise(row);
1571
+ const store = this.index();
1572
+ const indexed = store && uuid ? store.byUuid(uuid) : null;
1573
+ let subtasks = [];
1574
+ let attachments = null;
1575
+ let alarms = null;
1576
+ if (store && indexed) {
1577
+ subtasks = store.subtasksOf(indexed.primaryKey).map((r) => this.#fromIndex(r));
1578
+ attachments = store.attachmentsOf(indexed.primaryKey).map((a) => ({
1579
+ id: a.uuid,
1580
+ filename: a.filename,
1581
+ uti: a.uti
1582
+ }));
1583
+ alarms = store.enrichmentOf(indexed.primaryKey);
1584
+ }
1585
+ return {
1586
+ ...summary,
1587
+ ...indexed ? {
1588
+ dueAllDay: indexed.allDay,
1589
+ dueAllDaySource: "index",
1590
+ due: renderDue(indexed.due, indexed.allDay, utcDay(indexed.due))
1591
+ } : {},
1592
+ body: row.body,
1593
+ completionDate: row.completionDate,
1594
+ dueDate: row.dueDate,
1595
+ alldayDueDate: row.alldayDueDate,
1596
+ subtasks,
1597
+ attachments,
1598
+ alarms
1599
+ };
1600
+ }
1601
+ /** Resolve a list by name or id, erroring with what is available. */
1602
+ async resolveList(nameOrId) {
1603
+ const lists = await this.lists();
1604
+ const want = nameOrId.toLowerCase();
1605
+ const hit = lists.find((l) => l.id === nameOrId) ?? lists.find((l) => l.name?.toLowerCase() === want);
1606
+ if (!hit?.id) throw new ListNotFoundError(nameOrId, lists.map((l) => l.name).filter((n) => Boolean(n)));
1607
+ return hit.id;
1608
+ }
1609
+ /**
1610
+ * Turn the caller's field bag into JXA parameters.
1611
+ *
1612
+ * The due date is where the shape of the input picks the property: a bare day
1613
+ * sets `allday due date`, a date-time sets `due date`. See dates.ts.
1614
+ */
1615
+ #toJxaFields(fields) {
1616
+ const now = this.#now();
1617
+ const out = {};
1618
+ if (fields.name !== void 0) out.name = fields.name;
1619
+ if (fields.body !== void 0) out.body = fields.body;
1620
+ if (fields.priority !== void 0) out.priority = toPriorityValue(fields.priority);
1621
+ if (fields.flagged !== void 0) out.flagged = fields.flagged;
1622
+ if (fields.completed !== void 0) out.completed = fields.completed;
1623
+ if (fields.remindMe !== void 0) out.remindMeDate = parseDate("remindMe", fields.remindMe, now).iso;
1624
+ if (fields.due !== void 0) {
1625
+ const parsed = parseDate("due", fields.due, now);
1626
+ if (parsed.kind === "allDay") out.alldayDueDate = parsed.iso;
1627
+ else out.dueDate = parsed.iso;
1628
+ out.resolved = parsed;
1629
+ }
1630
+ return out;
1631
+ }
1632
+ async createReminder(fields) {
1633
+ const target = fields.list ?? this.config.defaultList;
1634
+ const listId = target ? await this.resolveList(target) : void 0;
1635
+ const jxa = this.#toJxaFields(fields);
1636
+ delete jxa.resolved;
1637
+ const made = await withBusyRetry(() => this.runner.run(CREATE_REMINDER, {
1638
+ ...jxa,
1639
+ name: fields.name,
1640
+ ...listId ? { listId } : {}
1641
+ }));
1642
+ this.invalidate();
1643
+ return this.getReminder(encodeRef(made.id));
1644
+ }
1645
+ async updateReminder(ref, fields) {
1646
+ const { id } = decodeRef(ref);
1647
+ const jxa = this.#toJxaFields(fields);
1648
+ delete jxa.resolved;
1649
+ await withBusyRetry(() => this.runner.run(UPDATE_REMINDER, {
1650
+ ...jxa,
1651
+ id
1652
+ }));
1653
+ this.invalidate();
1654
+ return this.getReminder(ref);
1655
+ }
1656
+ async completeReminders(refs, completed = true) {
1657
+ const ids = refs.map((r) => decodeRef(r).id);
1658
+ const rows = await withBusyRetry(() => this.runner.run(COMPLETE_REMINDERS, {
1659
+ ids,
1660
+ completed
1661
+ }));
1662
+ this.invalidate();
1663
+ return rows.map((r) => ({
1664
+ ref: encodeRef(r.id),
1665
+ found: Boolean(r.found),
1666
+ completed: Boolean(r.completed)
1667
+ }));
1668
+ }
1669
+ /**
1670
+ * Move reminders to another list.
1671
+ *
1672
+ * Copy-then-delete, because `reminder.container` is read-only in the scripting
1673
+ * dictionary. The new ref is returned alongside the old one so a caller can
1674
+ * update anything it was holding — the old ref stops resolving.
1675
+ */
1676
+ async moveReminders(refs, list) {
1677
+ const listId = await this.resolveList(list);
1678
+ const ids = refs.map((r) => decodeRef(r).id);
1679
+ const rows = await withBusyRetry(() => this.runner.run(MOVE_REMINDERS, {
1680
+ ids,
1681
+ listId
1682
+ }));
1683
+ this.invalidate();
1684
+ return rows.map((r, i) => ({
1685
+ ref: r.id ? encodeRef(r.id) : null,
1686
+ previousRef: r.previousId ? encodeRef(r.previousId) : refs[i],
1687
+ moved: Boolean(r.moved),
1688
+ ...r.error ? { error: r.error } : {}
1689
+ }));
1690
+ }
1691
+ async deleteReminders(refs) {
1692
+ const ids = refs.map((r) => decodeRef(r).id);
1693
+ const out = await withBusyRetry(() => this.runner.run(DELETE_REMINDERS, { ids }));
1694
+ this.invalidate();
1695
+ return {
1696
+ deleted: out.deleted,
1697
+ missing: out.missing.map((id) => encodeRef(id))
1698
+ };
1699
+ }
1700
+ };
1701
+ //#endregion
1702
+ //#region src/config.ts
1703
+ /**
1704
+ * Configuration is environment-only — this server holds no secret at all, its
1705
+ * access is the macOS permission the user granted.
1706
+ *
1707
+ * `allowWrites`, `debug`, `osascriptPath`, `osascriptTimeoutMs` and `maxResults`
1708
+ * come from `BaseConfigSchema`.
1709
+ */
1710
+ const ConfigSchema = BaseConfigSchema.extend({
1711
+ /** Account allowlist (names or ids). Empty means every account. */
1712
+ accounts: z.array(z.string().min(1)).default([]),
1713
+ /**
1714
+ * List allowlist (names or ids). Empty means every list.
1715
+ *
1716
+ * Finer-grained than the account allowlist and worth having here in a way it
1717
+ * was not for Notes: a shared "Groceries" list and a private one live in the
1718
+ * same account, so the account is often the wrong unit to scope by.
1719
+ */
1720
+ lists: z.array(z.string().min(1)).default([]),
1721
+ /** Explicit store path. Bypasses discovery — for tests and forensic copies. */
1722
+ storePath: z.string().optional(),
1723
+ indexMode: z.enum([
1724
+ "auto",
1725
+ "ro",
1726
+ "immutable",
1727
+ "off"
1728
+ ]).default("auto"),
1729
+ /** List a new reminder goes to when the caller names none. Empty = Reminders' default list. */
1730
+ defaultList: z.string().optional(),
1731
+ /**
1732
+ * Whether completed reminders are included when the caller does not say.
1733
+ *
1734
+ * Off, matching what Reminders itself shows. A long-lived account accumulates
1735
+ * years of completed items that would otherwise dominate every result.
1736
+ */
1737
+ includeCompleted: z.boolean().default(false),
1738
+ /** Cap for the Apple Events listing lane. */
1739
+ degradedMaxReminders: z.number().int().min(1).max(5e3).default(500),
1740
+ /** The only directory save_attachment may write into, enforced after realpath. */
1741
+ attachmentDir: z.string().default(join(homedir(), "Downloads")),
1742
+ /**
1743
+ * How long the Apple Events bulk-property cache stays warm.
1744
+ *
1745
+ * Same trade as Notes: a bulk fetch is one Apple Event per property whatever
1746
+ * the library size, so there is no cheap way to ask "has anything changed"
1747
+ * that costs less than simply asking again. A TTL with bounded staleness is
1748
+ * the honest option.
1749
+ */
1750
+ searchCacheTtlMs: z.number().int().min(0).max(36e5).default(3e4)
1751
+ }).strict();
1752
+ /**
1753
+ * `env` is a parameter with a default so tests are hermetic — they pass their
1754
+ * own object rather than mutating (and having to restore) process.env.
1755
+ */
1756
+ const loadConfig = (env = process.env) => parseConfig(ConfigSchema, {
1757
+ allowWrites: parseBool(env.APPLE_REMINDERS_ALLOW_WRITES),
1758
+ debug: parseBool(env.APPLE_REMINDERS_DEBUG),
1759
+ accounts: parseList(env.APPLE_REMINDERS_ACCOUNTS),
1760
+ lists: parseList(env.APPLE_REMINDERS_LISTS),
1761
+ storePath: trimmed(env.APPLE_REMINDERS_STORE),
1762
+ indexMode: trimmed(env.APPLE_REMINDERS_INDEX_MODE),
1763
+ defaultList: trimmed(env.APPLE_REMINDERS_DEFAULT_LIST),
1764
+ includeCompleted: parseBool(env.APPLE_REMINDERS_INCLUDE_COMPLETED),
1765
+ osascriptPath: trimmed(env.APPLE_REMINDERS_OSASCRIPT_PATH),
1766
+ osascriptTimeoutMs: parseIntOpt(env.APPLE_REMINDERS_OSASCRIPT_TIMEOUT_MS),
1767
+ maxResults: parseIntOpt(env.APPLE_REMINDERS_MAX_RESULTS),
1768
+ degradedMaxReminders: parseIntOpt(env.APPLE_REMINDERS_DEGRADED_MAX_REMINDERS),
1769
+ attachmentDir: trimmed(env.APPLE_REMINDERS_ATTACHMENT_DIR),
1770
+ searchCacheTtlMs: parseIntOpt(env.APPLE_REMINDERS_SEARCH_CACHE_TTL_MS)
1771
+ });
1772
+ //#endregion
1773
+ //#region src/tools/util.ts
1774
+ const reminderRefArg = z.string().min(1).describe("An opaque reminder ref from a search or list result (looks like \"r1:x-apple-reminder://…\"). Do not construct one by hand.");
1775
+ const reminderRefsArg = z.array(z.string().min(1)).min(1).max(200).describe("Reminder refs from a search or list result.");
1776
+ const listArg = z.string().optional().describe("A list name or id, e.g. \"Groceries\". Lists can be nested inside other lists; give the leaf name. Use apple_reminders_list_lists to see what exists.");
1777
+ const priorityArg = z.enum([
1778
+ "none",
1779
+ "low",
1780
+ "medium",
1781
+ "high"
1782
+ ]).optional().describe("Reminders stores priority as 0-9 and shows four buckets; these are the four. A value synced from another CalDAV client is bucketed into the nearest one.");
1783
+ /**
1784
+ * The date grammar, written out in full.
1785
+ *
1786
+ * The description is load-bearing: the caller is usually a model that gets one
1787
+ * retry, and the difference between a bare day and a date-time is the
1788
+ * difference between an all-day reminder and one due at a specific minute.
1789
+ */
1790
+ const dateArg = z.string().describe("ISO-8601 — \"2026-08-20\" for an all-day reminder, \"2026-08-20T09:00\" for a timed one — or a relative offset: \"+2d\", \"+3h\", \"+45m\", \"+1w\", \"today\", \"tomorrow\", \"tomorrow 09:00\", \"next monday\". Resolved in local time. Naming a day gives an all-day reminder; naming a time or a duration gives a timed one. The result echoes back the absolute time it resolved to.");
1791
+ const includeCompletedArg = z.boolean().optional().describe("Include completed reminders. Off by default, matching what Reminders itself shows — a long-lived account holds years of finished items.");
1792
+ //#endregion
1793
+ //#region src/tools/accounts.ts
1794
+ const registerAccountTools = (server, client) => {
1795
+ server.registerTool("apple_reminders_list_accounts", {
1796
+ description: "List the Reminders accounts, with how many lists and reminders each holds. Start here to discover account names for the other tools.",
1797
+ inputSchema: {},
1798
+ annotations: { readOnlyHint: true }
1799
+ }, async () => wrap(() => client.accounts()));
1800
+ server.registerTool("apple_reminders_list_lists", {
1801
+ description: "List every Reminders list, across accounts. Lists nest inside other lists (Reminders calls those groups), so each entry carries its depth. Each also reports its total and incomplete counts, which is the cheapest way to see where the live work is.",
1802
+ inputSchema: {},
1803
+ annotations: { readOnlyHint: true }
1804
+ }, async () => wrap(() => client.lists()));
1805
+ };
1806
+ //#endregion
1807
+ //#region src/tools/actions.ts
1808
+ /**
1809
+ * The mutating tools.
1810
+ *
1811
+ * Registered only when writes are enabled, so with the flag off they are
1812
+ * invisible to the model rather than merely refused.
1813
+ *
1814
+ * Every one of these re-reads the reminder afterwards and returns what
1815
+ * Reminders stored — not what was asked for. That matters most for dates: a
1816
+ * relative offset like "+2d" is resolved here, and the result says what instant
1817
+ * it became.
1818
+ */
1819
+ const registerActionTools = (server, client) => {
1820
+ server.registerTool("apple_reminders_create_reminder", {
1821
+ description: "Create a reminder. With no list, it goes to the list Reminders itself treats as the default — the same one the app would have used.",
1822
+ inputSchema: {
1823
+ name: z.string().min(1).describe("The reminder's title."),
1824
+ body: z.string().optional().describe("Notes attached to the reminder."),
1825
+ list: listArg,
1826
+ due: dateArg.optional(),
1827
+ remindMe: dateArg.optional().describe("When to actually alert, if different from the due date."),
1828
+ priority: priorityArg,
1829
+ flagged: z.boolean().optional().describe("Flag it.")
1830
+ }
1831
+ }, async (args) => wrap(() => client.createReminder(args)));
1832
+ server.registerTool("apple_reminders_update_reminder", {
1833
+ description: "Change fields on one reminder. Anything you omit is left alone. Setting `due` to a bare day converts it to an all-day reminder; setting a date-time makes it timed.",
1834
+ inputSchema: {
1835
+ ref: reminderRefArg,
1836
+ name: z.string().optional(),
1837
+ body: z.string().optional().describe("Replaces the notes body. Pass an empty string to clear it."),
1838
+ due: dateArg.optional(),
1839
+ remindMe: dateArg.optional(),
1840
+ priority: priorityArg,
1841
+ flagged: z.boolean().optional()
1842
+ }
1843
+ }, async ({ ref, ...fields }) => wrap(() => client.updateReminder(ref, fields)));
1844
+ server.registerTool("apple_reminders_complete_reminders", {
1845
+ description: "Tick reminders off, or un-tick them with `completed: false`. Separate from update because it is the common case and takes several at once.",
1846
+ inputSchema: {
1847
+ refs: reminderRefsArg,
1848
+ completed: z.boolean().optional().describe("Defaults to true. Pass false to mark them not done again.")
1849
+ }
1850
+ }, async ({ refs, completed }) => wrap(() => client.completeReminders(refs, completed ?? true)));
1851
+ server.registerTool("apple_reminders_move_reminders", {
1852
+ description: "Move reminders to another list. NOTE: Reminders' scripting interface makes a list read-only on a reminder, so this is a copy followed by a delete. Each moved reminder therefore gets a NEW ref (returned alongside the old one) and a new creation date. The original is deleted only after the copy is confirmed.",
1853
+ inputSchema: {
1854
+ refs: reminderRefsArg,
1855
+ list: z.string().min(1).describe("Target list name or id."),
1856
+ confirm: confirmArg
1857
+ }
1858
+ }, async ({ refs, list }) => wrap(() => client.moveReminders(refs, list)));
1859
+ server.registerTool("apple_reminders_delete_reminders", {
1860
+ description: "Delete reminders. Unlike Notes, Reminders has no Recently Deleted — this is irreversible, so it requires an explicit confirm.",
1861
+ inputSchema: {
1862
+ refs: reminderRefsArg,
1863
+ confirm: confirmArg
1864
+ }
1865
+ }, async ({ refs }) => wrap(() => client.deleteReminders(refs)));
1866
+ };
1867
+ //#endregion
1868
+ //#region src/tools/diagnostics.ts
1869
+ /**
1870
+ * One tool that answers "why is this not working".
1871
+ *
1872
+ * Lanes are probed before anything else is read, because the first Apple Event
1873
+ * is what triggers the Automation prompt: reading accounts first and probing
1874
+ * afterwards makes the two disagree whenever that first event loses the race.
1875
+ */
1876
+ const registerDiagnosticsTools = (server, client, ctx) => {
1877
+ server.registerTool("apple_reminders_diagnostics", {
1878
+ description: "Report which lanes are live, which macOS permissions are granted, and what each missing one is blocking. Start here when a tool returns degraded or fails — it names the exact System Settings pane to open.",
1879
+ inputSchema: {},
1880
+ annotations: { readOnlyHint: true }
1881
+ }, async () => wrap(async () => {
1882
+ const lanes = await client.lanes();
1883
+ const located = client.locate();
1884
+ const accounts = lanes.applescript === "live" ? await client.accounts() : [];
1885
+ /**
1886
+ * Reminders' Full Disk Access signal is not "can I read the file" but
1887
+ * "can I list the directory". The store's filename carries a generated
1888
+ * UUID, so without the grant there is no path to even test.
1889
+ */
1890
+ const fullDiskAccess = located.readable ? "granted" : located.containerListable ? "denied (found the store, cannot read it)" : "denied (cannot list the container, so the store cannot be located)";
1891
+ return {
1892
+ server: { lanes },
1893
+ permissions: {
1894
+ automation: lanes.applescript === "live" ? "granted" : "denied-or-reminders-not-running",
1895
+ fullDiskAccess,
1896
+ ...located.readable ? {} : { howToGrant: [
1897
+ "System Settings > Privacy & Security > Full Disk Access",
1898
+ "Add the app that launches this server (Terminal, iTerm, VS Code, Claude...), then restart it.",
1899
+ "Granting it to Reminders.app does nothing — the reader needs the permission, not Reminders."
1900
+ ] }
1901
+ },
1902
+ store: {
1903
+ containerPath: located.containerPath,
1904
+ path: located.storePath,
1905
+ containerListable: located.containerListable,
1906
+ candidates: located.candidates.length,
1907
+ exists: located.exists,
1908
+ readable: located.readable,
1909
+ sizeBytes: located.size,
1910
+ walPresent: located.walPresent,
1911
+ walSizeBytes: located.walSizeBytes,
1912
+ fingerprint: lanes.storeFingerprint,
1913
+ reason: located.reason
1914
+ },
1915
+ accounts,
1916
+ settings: {
1917
+ allowWrites: ctx.allowWrites,
1918
+ accountAllowlist: client.config.accounts,
1919
+ listAllowlist: client.config.lists,
1920
+ defaultList: client.config.defaultList ?? null,
1921
+ includeCompleted: client.config.includeCompleted,
1922
+ indexMode: client.config.indexMode,
1923
+ maxResults: client.config.maxResults,
1924
+ searchCacheTtlMs: client.config.searchCacheTtlMs
1925
+ },
1926
+ caveats: [
1927
+ "Reminders' scripting dictionary covers the core model read-write, so this server works with Automation alone. But a bulk read costs about 700ms PER PROPERTY on that bridge — roughly nine seconds for a full listing, whatever the library size — so the index lane carries listing and search whenever it is available.",
1928
+ "Without the index, `dueAllDay` is a guess. Reminders populates BOTH `due date` and `allday due date` for every dated reminder, so only the store's ZALLDAY column can actually answer it. Each result says which source it used.",
1929
+ "Subtasks need the index. The scripting dictionary types a reminder's container as \"list or reminder\", but calling container() on a reminder throws every time, so parentage is unreachable over Apple Events.",
1930
+ "Also index-only: attachments, alarms, recurrence and location alerts. There is no URL field in this store despite the folklore — it was looked for and is not there.",
1931
+ "Moving a reminder between lists is a copy-and-delete, because the scripting dictionary makes a reminder's list read-only. Moved reminders get a new ref.",
1932
+ `Apple Events results are cached for ${client.config.searchCacheTtlMs}ms. Checking for changes costs about as much as re-reading everything, so there is no cheaper invalidation to be had.`
1933
+ ]
1934
+ };
1935
+ }).then((r) => r ?? ok({})));
1936
+ };
1937
+ //#endregion
1938
+ //#region src/tools/reminders.ts
1939
+ /** Filters shared by list and search, declared once so the two cannot drift. */
1940
+ const filterSchema = {
1941
+ list: listArg,
1942
+ includeCompleted: includeCompletedArg,
1943
+ dueBefore: z.string().optional().describe("Only reminders due at or before this. A bare day means the WHOLE day, so \"2026-08-20\" includes everything due that evening. Same grammar as the due argument."),
1944
+ dueAfter: z.string().optional().describe("Only reminders due at or after this. A bare day means from that morning. Combine with dueBefore for a range."),
1945
+ flagged: z.boolean().optional().describe("Only flagged, or only unflagged."),
1946
+ priority: priorityArg,
1947
+ hasDueDate: z.boolean().optional().describe("true = only reminders with a due date; false = only those without one."),
1948
+ limit: limitArg
1949
+ };
1950
+ const registerReminderTools = (server, client) => {
1951
+ server.registerTool("apple_reminders_list_reminders", {
1952
+ description: "List reminders, soonest due first, with undated ones last. Returns a `ref` per reminder for the read and action tools. Completed reminders are excluded unless you ask for them. Every filter is optional; with none, this is the whole live list.",
1953
+ inputSchema: filterSchema,
1954
+ annotations: { readOnlyHint: true }
1955
+ }, async (args) => wrap(() => client.listReminders({
1956
+ ...args,
1957
+ limit: args.limit ?? Math.min(50, client.config.maxResults)
1958
+ })));
1959
+ server.registerTool("apple_reminders_search_reminders", {
1960
+ description: "Search reminders by text. `scope: \"full\"` (the default) matches the name and the notes body; `scope: \"title\"` matches only the name. Accepts the same filters as list_reminders, so you can search within one list or one date range.",
1961
+ inputSchema: {
1962
+ query: z.string().min(1).describe("Text to look for. Case-insensitive substring match."),
1963
+ scope: z.enum(["full", "title"]).optional().describe("full = name and notes body (default). title = name only."),
1964
+ ...filterSchema
1965
+ },
1966
+ annotations: { readOnlyHint: true }
1967
+ }, async ({ query, scope, ...rest }) => wrap(() => client.searchReminders(query, {
1968
+ ...rest,
1969
+ ...scope ? { scope } : {},
1970
+ limit: rest.limit ?? Math.min(50, client.config.maxResults)
1971
+ })));
1972
+ server.registerTool("apple_reminders_get_reminder", {
1973
+ description: "Read one reminder in full by ref, including its notes body and any subtasks. `dueDate` and `alldayDueDate` are reported separately from the combined `due` field, so you can see which property actually holds the date.",
1974
+ inputSchema: { ref: reminderRefArg },
1975
+ annotations: { readOnlyHint: true }
1976
+ }, async ({ ref }) => wrap(() => client.getReminder(ref)));
1977
+ };
1978
+ //#endregion
1979
+ //#region src/tools/index.ts
1980
+ /**
1981
+ * Register the Apple Reminders tools.
1982
+ *
1983
+ * The registered set is a pure function of `allowWrites` and nothing else. In
1984
+ * particular it does NOT vary with whether Full Disk Access is granted: that is
1985
+ * a runtime condition which can change while the process lives, and MCP clients
1986
+ * cache the tool list, so a tool that appears and disappears would leave clients
1987
+ * calling names the server no longer has. Tools that need the index instead
1988
+ * report their source, or explain what is missing.
1989
+ */
1990
+ const registerTools = (server, client, ctx) => {
1991
+ registerDiagnosticsTools(server, client, ctx);
1992
+ registerAccountTools(server, client);
1993
+ registerReminderTools(server, client);
1994
+ if (!ctx.allowWrites) return;
1995
+ registerActionTools(server, client);
1996
+ };
1997
+ //#endregion
1998
+ //#region src/server.ts
1999
+ const SERVER_NAME = BUILD_INFO.name;
2000
+ const SERVER_VERSION = BUILD_INFO.version;
2001
+ /**
2002
+ * Build the server. Side-effect free: it opens no connection, spawns no
2003
+ * process and reads no file, so a test can construct it freely and every
2004
+ * external dependency arrives through an option.
2005
+ */
2006
+ const createServer = (opts) => {
2007
+ const { config } = opts;
2008
+ const server = new McpServer({
2009
+ name: SERVER_NAME,
2010
+ version: SERVER_VERSION
2011
+ });
2012
+ const client = new AppleRemindersClient({
2013
+ config,
2014
+ ...opts.logger ? { logger: opts.logger } : {},
2015
+ ...opts.osascript ? { osascript: opts.osascript } : {},
2016
+ ...opts.now ? { now: opts.now } : {}
2017
+ });
2018
+ registerTools(server, client, { allowWrites: config.allowWrites });
2019
+ return {
2020
+ server,
2021
+ client
2022
+ };
2023
+ };
2024
+ //#endregion
2025
+ export { RemindersBusyError as A, parseDate as C, ListNotFoundError as D, InvalidDateError as E, BUILD_INFO as M, REMINDERS_SURFACE as O, parseBound as S, AppleRemindersError as T, toPriorityName as _, loadConfig as a, defaultContainerPath as b, introspect as c, decodeRef as d, encodeRef as f, rank as g, PRIORITY_NAMES as h, registerTools as i, RemindersNotRunningError as j, ReminderNotFoundError as k, openStore as l, uuidOf as m, SERVER_VERSION as n, AppleRemindersClient as o, refFromUuid as p, createServer as r, ReminderStore as s, SERVER_NAME as t, REF_VERSION as u, toPriorityValue as v, toLocalIso as w, locateStore as x, GROUP_CONTAINER as y };
2026
+
2027
+ //# sourceMappingURL=server-pj2yDDQb.js.map