@mgcrea/mcp-apple-mail 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
- import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, describeAggregation, detectEpoch, escapeLike, fingerprintSchema, groupByArg, inspectFile, limitArg, mapOsaError, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, project, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, selectArg, tableMap, trimmed, withBusyRetry, withLazyTools, wrap } from "@mgcrea/mcp-apple-core";
1
+ import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, describeAggregation, detectEpoch, escapeLike, fingerprintSchema, groupByArg, inspectFile, interferenceNote, limitArg, mapOsaError, openAxChannel, openReadOnly, parseBool, parseBound, parseConfig, parseIntOpt, parseList, project, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, selectArg, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, wrap } from "@mgcrea/mcp-apple-core";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { basename, dirname, join, resolve, sep } from "node:path";
5
+ import { execFile } from "node:child_process";
6
+ import { promisify } from "node:util";
5
7
  import { z } from "zod";
6
8
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
9
  //#region src/build-info.ts
@@ -12,8 +14,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
12
14
  const BUILD_INFO = {
13
15
  name: pkg.name,
14
16
  version: pkg.version,
15
- gitCommit: "dfc8616",
16
- gitCommitDate: "2026-09-06T00:04:53+02:00"
17
+ gitCommit: "d05a45c",
18
+ gitCommitDate: "2026-09-07T16:21:19+02:00"
17
19
  };
18
20
  //#endregion
19
21
  //#region src/client/errors.ts
@@ -104,6 +106,366 @@ const locateEnvelopeIndex = (opts = {}) => {
104
106
  };
105
107
  };
106
108
  //#endregion
109
+ //#region src/client/ax.ts
110
+ /**
111
+ * Mail's composer, driven through Cupertino's native Accessibility driver.
112
+ *
113
+ * ## What this replaces, and why it is worth replacing
114
+ *
115
+ * `jxa/core.ts` reaches the same composer through System Events. That path
116
+ * works, and it costs two things this one does not:
117
+ *
118
+ * * **A second TCC grant.** UI scripting through System Events needs
119
+ * Automation-to-System-Events *on top of* Accessibility — two grants, in two
120
+ * System Settings panes, to reach one window. `composerGrantMessage` is ten
121
+ * lines long because of it.
122
+ * * **47.4 ms per attribute read**, against 0.202 ms called natively. Which is
123
+ * why `findBodyArea` is bounded at depth 6 and `composerBodyText` carries a
124
+ * character budget: both are cost control, not correctness.
125
+ *
126
+ * ## What it deliberately does NOT change
127
+ *
128
+ * **The body is still pasted.** Assigning `content` is dropped by Mail, and so
129
+ * is setting AXValue on the web area, "which reports itself settable first and
130
+ * then does nothing" — measured in `jxa/write.ts`, and independently in
131
+ * `docs/desktop.md`, which found the same trap on the first text field of all
132
+ * seven apps it probed. A native driver does not make an app honour a write it
133
+ * ignores. The clipboard is still borrowed and still put back.
134
+ *
135
+ * **Nothing reports a draft ready on the strength of a write being accepted.**
136
+ * That is the failure this whole path is shaped around: a draft correct in every
137
+ * visible respect except the words, reported as a success.
138
+ *
139
+ * ## The fallback is not optional
140
+ *
141
+ * `openAxChannel` returns null when this server was not started by Cupertino —
142
+ * the npm packages are published artifacts and are run by hand. Every function
143
+ * here is reached only after `available()`, and `client/mail.ts` keeps the
144
+ * System Events path for when it is false.
145
+ */
146
+ const MAIL_BUNDLE = "com.apple.mail";
147
+ /** Mail's composer body is a WebKit view, not a text field. */
148
+ const BODY_ROLE = "AXWebArea";
149
+ /**
150
+ * How deep to look for the body.
151
+ *
152
+ * `findBodyArea` uses 6 and says the bound is there to survive the cost. Cost is
153
+ * no longer the reason, so this is only a guard against walking a composer that
154
+ * holds a deeply nested quoted message — the web area itself sits near the top.
155
+ */
156
+ const BODY_DEPTH = 8;
157
+ /**
158
+ * How long to keep asking the composer's body to take the focus.
159
+ *
160
+ * **Readable is not ready, and the gap is not zero.** `findComposer` returns as
161
+ * soon as the window and its web area can be READ; the body cannot take the
162
+ * keyboard for about another 140 ms after that. Measured over three fresh
163
+ * composers, driving the real driver:
164
+ *
165
+ * web area readable at 395 ms focus -> false at 421 ms, true at 560 ms
166
+ * web area readable at 637 ms focus -> false at 671 ms, true at 812 ms
167
+ * web area readable at 640 ms focus -> false at 665 ms, true at 805 ms
168
+ *
169
+ * The first attempt failed on every trial. Without a poll here that is a
170
+ * coin-flip resting on how long the surrounding round trips happen to take —
171
+ * `compose.ts` retries the whole paste once, for an unrelated reason, and that
172
+ * retry was silently carrying this.
173
+ *
174
+ * Which is `docs/desktop.md`'s most expensive lesson arriving in a new place:
175
+ * *the control must be polled for, not waited for*. It was written about a
176
+ * window's chrome appearing before its content; this is the same shape one level
177
+ * down, where the content is there and the focus is not.
178
+ */
179
+ const FOCUS_TIMEOUT_MS = 2e3;
180
+ /** Between focus attempts. Each one is a round trip, so this is not a spin. */
181
+ const FOCUS_POLL_MS = 100;
182
+ var MailAxLane = class MailAxLane {
183
+ #channel;
184
+ constructor(channel) {
185
+ this.#channel = channel;
186
+ }
187
+ /** Null when this server is not hosted by Cupertino — see the note above. */
188
+ static open(env = process.env) {
189
+ const channel = openAxChannel(MAIL_SURFACE, env);
190
+ return channel ? new MailAxLane(channel) : null;
191
+ }
192
+ close() {
193
+ this.#channel.close();
194
+ }
195
+ /** Start watching for someone using the Mac during a sequence. */
196
+ watch() {
197
+ return watchInterference(this.#channel);
198
+ }
199
+ #call(tool, args = {}) {
200
+ return this.#channel.call({
201
+ tool: `apple_desktop_${tool}`,
202
+ args
203
+ });
204
+ }
205
+ /**
206
+ * Can this process read Mail's windows, right now?
207
+ *
208
+ * Asked BEFORE a composer is opened, keeping the ordering `jxa/write.ts`
209
+ * established: the old shape opened a window, failed the read, and left an
210
+ * empty reply on screen with an error telling the user to close it by hand.
211
+ *
212
+ * Ground truth is the functional read, never a trusted flag. One bundle
213
+ * identifier can hold several Accessibility entries — one per path and
214
+ * signature it has been granted at — so the flag can answer for a different
215
+ * row from the one the request resolves against. A window list that comes back
216
+ * named is proof regardless of what the flag says.
217
+ *
218
+ * Mail with no windows is legitimate — everything closed to the menu bar — so
219
+ * an empty list is not evidence of anything and must not refuse a reply that
220
+ * would have worked.
221
+ */
222
+ async reach() {
223
+ try {
224
+ return {
225
+ ok: true,
226
+ reason: null,
227
+ windows: ((await this.#call("list_windows", {
228
+ bundleId: MAIL_BUNDLE,
229
+ includeTitles: true
230
+ })).windows ?? []).map((w) => w.title ?? null).filter((t) => t !== null)
231
+ };
232
+ } catch {
233
+ return {
234
+ ok: false,
235
+ reason: "accessibility",
236
+ windows: null
237
+ };
238
+ }
239
+ }
240
+ /**
241
+ * The sentence to say when the composer cannot be reached natively.
242
+ *
243
+ * One grant rather than two, and none of the "quit Cupertino and open it
244
+ * again" ritual the System Events path needs — that exists because a node
245
+ * child started before the grant does not inherit it, and this driver runs in
246
+ * the app itself.
247
+ */
248
+ static grantMessage(mode) {
249
+ return `Cupertino cannot read Mail's windows, which is the only route into a ${mode} composer, so it was not started and nothing was written. This needs Accessibility for Cupertino.app in System Settings > Privacy & Security > Accessibility. If the app is already listed, toggle it off and on — the grant goes stale when the bundle is reinstalled. Run apple_mail_diagnostics to check; it names the windows it can see.`;
250
+ }
251
+ /**
252
+ * Poll for the composer window, and for its body.
253
+ *
254
+ * Polled rather than waited for, which `docs/desktop.md` records as the trap
255
+ * that cost it the most: a window's chrome appearing is not its content being
256
+ * ready, so no fixed settle time is correct. Cheap here — a bounded walk is
257
+ * milliseconds.
258
+ *
259
+ * The subject is the identity, and requiring a body area with it rejects the
260
+ * main window and the drafts list. Counting windows does not work: Mail closes
261
+ * and reuses windows around a compose, so the count comes back unchanged with
262
+ * a new composer on screen.
263
+ */
264
+ async findComposer(subject, timeoutMs) {
265
+ const deadline = Date.now() + timeoutMs;
266
+ for (;;) {
267
+ const listed = await this.#call("list_windows", {
268
+ bundleId: MAIL_BUNDLE,
269
+ includeTitles: true
270
+ });
271
+ for (const win of listed.windows ?? []) {
272
+ if ((win.title ?? "") !== subject) continue;
273
+ const body = await this.#bodyOf(win.index);
274
+ if (body) return {
275
+ window: win.handle,
276
+ body,
277
+ index: win.index
278
+ };
279
+ }
280
+ if (Date.now() >= deadline) return null;
281
+ await new Promise((resolve) => setTimeout(resolve, 200));
282
+ }
283
+ }
284
+ async #bodyOf(windowIndex) {
285
+ return ((await this.#call("ui_tree", {
286
+ bundleId: MAIL_BUNDLE,
287
+ window: windowIndex,
288
+ detail: "all",
289
+ maxDepth: BODY_DEPTH
290
+ })).elements ?? []).find((el) => el.role === BODY_ROLE)?.handle ?? null;
291
+ }
292
+ /** Bring Mail to the front. A synthetic keystroke lands in whatever is frontmost. */
293
+ async activate() {
294
+ await this.#call("activate", { bundleId: MAIL_BUNDLE });
295
+ }
296
+ /**
297
+ * The accessible text under the body, which is what a person would see.
298
+ *
299
+ * One call rather than a bounded walk. The System Events version reads a
300
+ * parent at a time and stops at a character budget because every node costs an
301
+ * Apple Event; here the whole subtree comes back in one answer with each
302
+ * element's value already on it.
303
+ *
304
+ * Returns null when the body cannot be reached at all — a different answer
305
+ * from "", and the two must stay apart: one means we are blind, the other
306
+ * means the composer is empty.
307
+ */
308
+ async bodyText(body) {
309
+ try {
310
+ return ((await this.#call("expand", {
311
+ handle: body,
312
+ detail: "all",
313
+ maxDepth: BODY_DEPTH
314
+ })).elements ?? []).map((el) => el.value).filter((v) => typeof v === "string" && v.trim() !== "").join("\n");
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+ /**
320
+ * How many elements the body holds.
321
+ *
322
+ * A fingerprint, not a reading. Taken before and after a paste it answers "did
323
+ * anything at all land", which is what decides whether pasting again is safe:
324
+ * a paste that landed and cannot be read must NOT be repeated, or the reply
325
+ * ends up in the draft twice with no way to undo it from here.
326
+ *
327
+ * `matched` rather than the returned length, because the response is byte
328
+ * capped and a long quoted message will truncate — a fingerprint taken from a
329
+ * truncated list would compare two different bounds rather than two states.
330
+ */
331
+ async bodySize(body) {
332
+ try {
333
+ const tree = await this.#call("expand", {
334
+ handle: body,
335
+ detail: "all",
336
+ maxDepth: BODY_DEPTH
337
+ });
338
+ return tree.matched ?? (tree.elements ?? []).length;
339
+ } catch {
340
+ return -1;
341
+ }
342
+ }
343
+ /**
344
+ * Focus the body and paste, and say whether the focus took.
345
+ *
346
+ * Focus is not a raise: a raise orders a window forward inside Mail while the
347
+ * keystroke goes wherever the focus actually is. Both are needed, and the
348
+ * focus is read back because an element can report itself focusable and not
349
+ * take it.
350
+ *
351
+ * **What "read back" has to mean here, learned the hard way.** Mail's composer
352
+ * web area answers `AXFocused: false` while holding the keyboard — measured
353
+ * over 1.2 s without ever flipping, with a command-V landing in it the whole
354
+ * time. `apple_desktop_focus` used to return that flag, so this guard refused
355
+ * to press command-V and every native reply came back "Nothing landed in it"
356
+ * for a body that would have gone in. The driver now answers from the
357
+ * APPLICATION's `AXFocusedUIElement`, which is what the window server routes
358
+ * keystrokes by and so cannot disagree with where one will land.
359
+ *
360
+ * The guard itself stays. Posting command-V without knowing where the focus is
361
+ * types into whatever happens to be in front, and that is the user's window.
362
+ */
363
+ async paste(ref, focusTimeoutMs = FOCUS_TIMEOUT_MS) {
364
+ await this.#call("raise_window", { handle: ref.window });
365
+ await this.activate();
366
+ const deadline = Date.now() + focusTimeoutMs;
367
+ for (;;) {
368
+ if ((await this.#call("focus", { handle: ref.body })).focused === true) break;
369
+ if (Date.now() >= deadline) return false;
370
+ await new Promise((resolve) => setTimeout(resolve, FOCUS_POLL_MS));
371
+ }
372
+ await this.#call("key", {
373
+ key: "v",
374
+ modifiers: ["command"]
375
+ });
376
+ return true;
377
+ }
378
+ /**
379
+ * Send the composer, or save it as a draft.
380
+ *
381
+ * A keyboard shortcut rather than the Send button, and that is a correctness
382
+ * choice rather than a shortcut in the other sense: the button's name is
383
+ * localised — a French Mail says "Envoyer" — while command-shift-D is the same
384
+ * on every Mac. Addressing it by name would have worked on the machine it was
385
+ * written on and nowhere else.
386
+ *
387
+ * This is the step that replaces `draft.send()`, and the reason it had to. A
388
+ * JXA object reference cannot outlive the `osascript` process that made it,
389
+ * and this flow now spans two processes: Apple Events opens the composer, and
390
+ * everything after is native. Re-finding the draft to send it was the
391
+ * alternative and is worse — drafts are discovered by subject, so two with the
392
+ * same one are indistinguishable, on the single path whose named failure is
393
+ * sending the wrong thing.
394
+ */
395
+ async finish(sendNow) {
396
+ await this.#call("key", sendNow ? {
397
+ key: "d",
398
+ modifiers: ["command", "shift"]
399
+ } : {
400
+ key: "s",
401
+ modifiers: ["command"]
402
+ });
403
+ }
404
+ /**
405
+ * Has the composer for this subject gone?
406
+ *
407
+ * How a send is confirmed. Mail closes the window when it accepts one, so the
408
+ * window still being there means it did not go — which is checked rather than
409
+ * assumed, because nothing in this path may report success on the strength of
410
+ * a keystroke having been delivered.
411
+ */
412
+ async composerGone(subject, timeoutMs) {
413
+ const deadline = Date.now() + timeoutMs;
414
+ for (;;) {
415
+ if (!((await this.#call("list_windows", {
416
+ bundleId: MAIL_BUNDLE,
417
+ includeTitles: true
418
+ })).windows ?? []).some((w) => (w.title ?? "") === subject)) return true;
419
+ if (Date.now() >= deadline) return false;
420
+ await new Promise((resolve) => setTimeout(resolve, 200));
421
+ }
422
+ }
423
+ /** Select everything in the body, for the quote strip. */
424
+ async selectAll() {
425
+ await this.#call("key", {
426
+ key: "a",
427
+ modifiers: ["command"]
428
+ });
429
+ }
430
+ /**
431
+ * The deepest quote level anywhere in the body; 0 once the citation is gone.
432
+ *
433
+ * `AXBlockQuoteLevel` is not in the tree's field set, which is chosen for
434
+ * addressing controls — so it is read one element at a time. That is
435
+ * affordable only natively: 343 elements at 0.2 ms is well under a tenth of a
436
+ * second, where the same walk through System Events would be sixteen.
437
+ */
438
+ async maxQuoteLevel(body) {
439
+ const tree = await this.#call("expand", {
440
+ handle: body,
441
+ detail: "all",
442
+ maxDepth: BODY_DEPTH
443
+ });
444
+ let worst = 0;
445
+ for (const el of tree.elements ?? []) {
446
+ const read = await this.#call("get_attribute", {
447
+ handle: el.handle,
448
+ attribute: "AXBlockQuoteLevel"
449
+ });
450
+ const level = typeof read.value === "number" ? read.value : 0;
451
+ if (level > worst) worst = level;
452
+ }
453
+ return worst;
454
+ }
455
+ };
456
+ /**
457
+ * Does the pasted text appear at the top of what the composer now holds?
458
+ *
459
+ * Whitespace-squashed on both sides: the accessible text of a WebKit view breaks
460
+ * lines where the rendering does, not where the source did.
461
+ */
462
+ const squash = (s) => s.replace(/\s+/g, " ").trim();
463
+ const containsText = (haystack, needle) => {
464
+ const n = squash(needle);
465
+ if (!n) return true;
466
+ return squash(haystack).includes(n);
467
+ };
468
+ //#endregion
107
469
  //#region src/client/mime.ts
108
470
  const decodeBase64 = (s) => Buffer.from(s, "base64");
109
471
  const decodeQuotedPrintable = (s, forHeader = false) => {
@@ -191,6 +553,90 @@ const headerParam = (value, param) => {
191
553
  const match = new RegExp(`${param}\\s*=\\s*"([^"]*)"|${param}\\s*=\\s*([^;\\s]+)`, "i").exec(value);
192
554
  return match ? match[1] ?? match[2] ?? null : null;
193
555
  };
556
+ /**
557
+ * The filename a part actually carries, through both ways of spelling one.
558
+ *
559
+ * `headerParam` reads `filename="x"` and nothing else, which is fine for
560
+ * `charset` and `boundary` — both plain ASCII tokens by definition — and wrong
561
+ * for a filename, because a filename is the one parameter that routinely is not
562
+ * ASCII. Two encodings exist for it and mail uses both:
563
+ *
564
+ * RFC 2231 `filename*=UTF-8''r%C3%A9sum%C3%A9.pdf`
565
+ * also split across `filename*0*=`, `filename*1*=` for long names
566
+ * RFC 2047 `name="=?utf-8?Q?r=C3=A9sum=C3=A9=2Epdf?="`
567
+ *
568
+ * Neither was handled. The first returned null, so an attachment with an
569
+ * accented name was reported as having no filename at all — which
570
+ * `list_attachments` shows as unretrievable and `save_attachment` cannot write.
571
+ * The second came back verbatim, so saving it wrote a file literally named
572
+ * `=?utf-8?Q?...?=` on disk.
573
+ *
574
+ * RFC 2231 is tried first because it is the one designed for this; the RFC 2047
575
+ * form in a parameter is technically not allowed and is nonetheless everywhere.
576
+ */
577
+ const headerFilename = (disposition, contentType) => {
578
+ for (const [value, param] of [[disposition, "filename"], [contentType, "name"]]) {
579
+ if (!value) continue;
580
+ const extended = extendedParam(value, param);
581
+ if (extended !== null) return extended;
582
+ const plain = headerParam(value, param);
583
+ if (plain !== null) return decodeEncodedWords(plain);
584
+ }
585
+ return null;
586
+ };
587
+ /**
588
+ * The RFC 2231 form, including the numbered continuations long names use.
589
+ *
590
+ * A continuation is only percent-decoded when its own segment is starred —
591
+ * `filename*1=` is literal text and `filename*1*=` is encoded, and treating the
592
+ * two alike turns a legitimate `%` in a filename into mojibake.
593
+ */
594
+ const extendedParam = (value, param) => {
595
+ const single = new RegExp(`${param}\\*\\s*=\\s*(?:"([^"]*)"|([^;\\s]+))`, "i").exec(value);
596
+ if (single) return decodeExtended(single[1] ?? single[2] ?? "", true);
597
+ const segments = [];
598
+ const pattern = new RegExp(`${param}\\*(\\d+)(\\*)?\\s*=\\s*(?:"([^"]*)"|([^;\\s]+))`, "gi");
599
+ for (const match of value.matchAll(pattern)) segments.push({
600
+ index: Number(match[1]),
601
+ text: match[3] ?? match[4] ?? "",
602
+ encoded: match[2] === "*"
603
+ });
604
+ if (segments.length === 0) return null;
605
+ segments.sort((a, b) => a.index - b.index);
606
+ let charset = null;
607
+ let out = "";
608
+ for (const [position, segment] of segments.entries()) {
609
+ if (!segment.encoded) {
610
+ out += segment.text;
611
+ continue;
612
+ }
613
+ if (position === 0) {
614
+ const parts = segment.text.split("'");
615
+ if (parts.length >= 3) {
616
+ charset = parts[0] || null;
617
+ out += percentDecode(parts.slice(2).join("'"), charset);
618
+ continue;
619
+ }
620
+ }
621
+ out += percentDecode(segment.text, charset);
622
+ }
623
+ return out;
624
+ };
625
+ const decodeExtended = (raw, hasCharsetPrefix) => {
626
+ if (!hasCharsetPrefix) return percentDecode(raw, null);
627
+ const parts = raw.split("'");
628
+ if (parts.length < 3) return percentDecode(raw, null);
629
+ return percentDecode(parts.slice(2).join("'"), parts[0] || null);
630
+ };
631
+ /** Percent-decoded as BYTES, then read in the charset the header named. */
632
+ const percentDecode = (raw, charset) => {
633
+ const bytes = [];
634
+ for (let i = 0; i < raw.length; i += 1) if (raw[i] === "%" && /^[0-9a-f]{2}$/i.test(raw.slice(i + 1, i + 3))) {
635
+ bytes.push(Number.parseInt(raw.slice(i + 1, i + 3), 16));
636
+ i += 2;
637
+ } else bytes.push(raw.charCodeAt(i) & 255);
638
+ return decodeCharset(Buffer.from(bytes), charset);
639
+ };
194
640
  const HEADER_BODY_SPLIT = /\r?\n\r?\n/;
195
641
  const parsePart = (buf) => {
196
642
  const text = buf.toString("latin1");
@@ -207,7 +653,7 @@ const parsePart = (buf) => {
207
653
  charset: headerParam(contentTypeRaw, "charset"),
208
654
  encoding: headerValue(headers, "content-transfer-encoding")?.trim().toLowerCase() ?? null,
209
655
  disposition: dispositionRaw?.split(";")[0]?.trim().toLowerCase() ?? null,
210
- filename: headerParam(dispositionRaw, "filename") ?? headerParam(contentTypeRaw, "name") ?? null,
656
+ filename: headerFilename(dispositionRaw, contentTypeRaw),
211
657
  contentId: headerValue(headers, "content-id")?.replaceAll(/[<>]/g, "") ?? null,
212
658
  raw: Buffer.from(text.slice(bodyStart), "latin1"),
213
659
  parts: []
@@ -731,342 +1177,21 @@ const scanBodies = (opts) => {
731
1177
  };
732
1178
  };
733
1179
  //#endregion
734
- //#region src/client/schema.ts
735
- const REQUIRED = {
736
- messages: [
737
- "mailbox",
738
- "subject",
739
- "sender",
740
- "date_received",
741
- "read",
742
- "deleted"
743
- ],
744
- mailboxes: ["url"],
745
- subjects: ["subject"],
746
- addresses: ["address"]
747
- };
748
- const introspect = (db, now) => {
749
- const fingerprint = fingerprintSchema(db);
750
- const tables = tableMap(db);
751
- const tableNames = Object.keys(tables);
752
- const missing = [];
753
- for (const [table, cols] of Object.entries(REQUIRED)) {
754
- if (!tables[table]) {
755
- missing.push(`${table} (table)`);
756
- continue;
757
- }
758
- for (const c of cols) if (!tables[table]?.includes(c)) missing.push(`${table}.${c}`);
759
- }
760
- const messageCols = tables.messages ?? [];
761
- let epoch = {
762
- offset: 0,
763
- reason: "not probed"
764
- };
765
- if (missing.length === 0) {
766
- const row = db.prepare("SELECT MAX(date_received) AS m FROM messages").get();
767
- epoch = detectEpoch(row?.m ?? null, now);
768
- }
769
- return {
770
- fingerprint,
771
- tables,
772
- has: {
773
- labels: tableNames.includes("labels"),
774
- recipients: tableNames.includes("recipients"),
775
- attachments: tableNames.includes("attachments"),
776
- subjects: tableNames.includes("subjects"),
777
- addresses: tableNames.includes("addresses"),
778
- subjectPrefix: messageCols.includes("subject_prefix"),
779
- conversationId: messageCols.includes("conversation_id"),
780
- flagged: messageCols.includes("flagged"),
781
- dateSent: messageCols.includes("date_sent"),
782
- messageIdHeader: (tables.message_global_data ?? []).includes("message_id_header"),
783
- mailboxCounts: (tables.mailboxes ?? []).includes("unread_count")
784
- },
785
- epochOffset: epoch.offset,
786
- epochReason: epoch.reason,
787
- missing
788
- };
789
- };
790
- const assertUsable = (caps) => {
791
- if (caps.missing.length > 0) throw new SchemaDriftError(`Mail's search index is not the shape this server knows how to read (missing: ${caps.missing.join(", ")}). This usually means a macOS upgrade changed the schema. The AppleScript lane still works; please report schema fingerprint ${caps.fingerprint}.`, {
792
- fingerprint: caps.fingerprint,
793
- missing: caps.missing
794
- });
795
- };
796
- //#endregion
797
- //#region src/client/envelope.ts
1180
+ //#region src/client/jxa/core.ts
798
1181
  /**
799
- * What a mail query can group on.
1182
+ * JXA script fragments.
800
1183
  *
801
- * The single source of truth for both the tool's enum and the SQL expressions
802
- * in `#groupExpr` — a field can only be asked for if it is listed here, which
803
- * is what keeps caller strings out of the statement.
804
- */
805
- const GROUP_FIELDS = [
806
- "sender",
807
- "mailbox",
808
- "subject",
809
- "day",
810
- "month"
811
- ];
812
- const contains = (value) => `%${escapeLike(value)}%`;
813
- const openIndex = (path, mode, logger) => {
814
- const { db, mode: opened, validated: caps } = openReadOnly(path, mode, {
815
- envVar: "APPLE_MAIL_INDEX_MODE",
816
- label: "Mail's search index",
817
- hint: "If this is a permission error, grant Full Disk Access to the app running this server.",
818
- validate: (conn) => {
819
- const found = introspect(conn);
820
- assertUsable(found);
821
- return found;
822
- },
823
- fatal: (err) => err instanceof SchemaDriftError,
824
- onFallback: () => logger?.warn?.("opened the index with immutable=1; results may omit mail that is still in the -wal")
825
- });
826
- return {
827
- db,
828
- mode: opened,
829
- caps
830
- };
831
- };
832
- var EnvelopeIndex = class EnvelopeIndex {
833
- #db;
834
- caps;
835
- mode;
836
- constructor(opened) {
837
- this.#db = opened.db;
838
- this.caps = opened.caps;
839
- this.mode = opened.mode;
840
- }
841
- close() {
842
- try {
843
- this.#db.close();
844
- } catch {}
845
- }
846
- /** id -> url for every mailbox, so results can be mapped back to scriptable names. */
847
- mailboxes() {
848
- const hasCounts = this.caps.has.mailboxCounts;
849
- return this.#db.prepare(hasCounts ? "SELECT ROWID AS rowid, url, total_count AS total, unread_count AS unread FROM mailboxes" : "SELECT ROWID AS rowid, url, NULL AS total, NULL AS unread FROM mailboxes").all();
850
- }
851
- /**
852
- * Restrict to a set of mailboxes.
853
- *
854
- * The `labels` half is not optional for Gmail. Gmail-over-IMAP keeps every
855
- * message in `[Gmail]/All Mail` and expresses INBOX membership as a label
856
- * row, so `m.mailbox IN (...)` alone returns an EMPTY inbox — measured here
857
- * as 0 rows against 51,128 real messages.
858
- */
859
- #mailboxPredicate(rowids, params) {
860
- if (!rowids?.length) return "1=1";
861
- const placeholders = rowids.map(() => "?").join(",");
862
- if (!this.caps.has.labels) {
863
- params.push(...rowids);
864
- return `m.mailbox IN (${placeholders})`;
865
- }
866
- params.push(...rowids, ...rowids);
867
- return `(m.mailbox IN (${placeholders}) OR m.ROWID IN (SELECT message_id FROM labels WHERE mailbox_id IN (${placeholders})))`;
868
- }
869
- #toIso(value) {
870
- if (value === null || !Number.isFinite(value)) return null;
871
- return (/* @__PURE__ */ new Date((value + this.caps.epochOffset) * 1e3)).toISOString();
872
- }
873
- #toEpoch(iso) {
874
- return Math.floor(Date.parse(iso) / 1e3) - this.caps.epochOffset;
875
- }
876
- /**
877
- * The WHERE half of a filtered read, appending its bind values to `params`.
878
- *
879
- * Shared by `search` and `groupBy` so the two cannot drift: a filter that
880
- * narrowed a listing but not its aggregate would make "count per sender in
881
- * INBOX" quietly count the whole archive.
882
- *
883
- * Call this before adding any other bind value — the placeholders it appends
884
- * have to come first in the parameter list, which mirrors WHERE preceding
885
- * ORDER BY and LIMIT in every statement built from it.
886
- */
887
- #filterPredicate(filters, params) {
888
- const where = ["m.deleted = 0"];
889
- where.push(this.#mailboxPredicate(filters.mailboxRowids, params));
890
- if (filters.query) {
891
- where.push("(s.subject LIKE ? ESCAPE '\\' OR a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
892
- params.push(contains(filters.query), contains(filters.query), contains(filters.query));
893
- }
894
- if (filters.subject) {
895
- where.push("s.subject LIKE ? ESCAPE '\\'");
896
- params.push(contains(filters.subject));
897
- }
898
- if (filters.sender) {
899
- where.push("(a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
900
- params.push(contains(filters.sender), contains(filters.sender));
901
- }
902
- if (filters.recipient && this.caps.has.recipients) {
903
- where.push("EXISTS (SELECT 1 FROM recipients r JOIN addresses ra ON ra.ROWID = r.address WHERE r.message = m.ROWID AND ra.address LIKE ? ESCAPE '\\')");
904
- params.push(contains(filters.recipient));
905
- }
906
- if (filters.unreadOnly) where.push("m.read = 0");
907
- if (filters.flaggedOnly && this.caps.has.flagged) where.push("m.flagged = 1");
908
- if (filters.hasAttachment && this.caps.has.attachments) where.push("EXISTS (SELECT 1 FROM attachments at WHERE at.message = m.ROWID)");
909
- if (filters.dateFrom) {
910
- where.push("m.date_received >= ?");
911
- params.push(this.#toEpoch(filters.dateFrom));
912
- }
913
- if (filters.dateTo) {
914
- where.push("m.date_received <= ?");
915
- params.push(this.#toEpoch(filters.dateTo));
916
- }
917
- return where.join(" AND ");
918
- }
919
- /**
920
- * The joins every filtered read needs. `s` and `a` are LEFT joins because a
921
- * message can legitimately have no subject row and no sender row, and an
922
- * INNER join here would drop exactly those from counts.
923
- */
924
- static #FROM = "FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender";
925
- /**
926
- * subject_prefix holds "Re: " / "Fwd: " separately from the deduplicated
927
- * subject row, so the displayed subject is the concatenation of the two.
928
- */
929
- get #subjectExpr() {
930
- return this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
931
- }
932
- search(filters) {
933
- const params = [];
934
- const predicate = this.#filterPredicate(filters, params);
935
- const sql = `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${this.#subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, ${this.caps.has.conversationId ? "m.conversation_id" : "NULL"} AS conversationId, ` + (this.caps.has.attachments ? "EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment " : "0 AS hasAttachment ") + `${EnvelopeIndex.#FROM} WHERE ${predicate} ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;
936
- params.push(filters.limit, filters.offset);
937
- return this.#db.prepare(sql).all(...params).map((r) => ({
938
- rowid: Number(r.rowid),
939
- mailboxUrl: String(r.mailboxUrl),
940
- subject: r.subject || null,
941
- senderAddress: r.senderAddress ?? null,
942
- senderName: r.senderName || null,
943
- dateReceived: this.#toIso(r.dateReceived),
944
- dateSent: this.#toIso(r.dateSent),
945
- read: Boolean(r.read),
946
- flagged: Boolean(r.flagged),
947
- size: r.size ?? null,
948
- conversationId: r.conversationId ?? null,
949
- hasAttachment: Boolean(r.hasAttachment)
950
- }));
951
- }
952
- /**
953
- * The column expression each groupable field aggregates on.
954
- *
955
- * A key here is the ONLY thing that reaches the statement — the tool matches
956
- * the caller's string against `GROUP_FIELDS` and passes the matched literal,
957
- * so no caller-controlled text is ever interpolated. `label` is a second,
958
- * human-readable form of the same group where one exists; it goes through
959
- * MAX() because everything outside GROUP BY has to be aggregated, and the
960
- * value is constant within a group anyway.
961
- */
962
- #groupExpr(field) {
963
- switch (field) {
964
- case "sender": return {
965
- key: "a.address",
966
- label: "MAX(NULLIF(a.comment, ''))"
967
- };
968
- case "mailbox": return {
969
- key: "m.mailbox",
970
- label: "MAX(mb.url)"
971
- };
972
- case "subject": return {
973
- key: this.#subjectExpr,
974
- label: "NULL"
975
- };
976
- case "day": return {
977
- key: this.#dateBucket("%Y-%m-%d"),
978
- label: "NULL"
979
- };
980
- case "month": return {
981
- key: this.#dateBucket("%Y-%m"),
982
- label: "NULL"
983
- };
984
- }
985
- }
986
- /** `date_received` is epoch-with-offset, so shift it before formatting. */
987
- #dateBucket(format) {
988
- return `strftime('${format}', datetime(m.date_received + ${this.caps.epochOffset}, 'unixepoch'))`;
989
- }
990
- /**
991
- * Count matches per group, over every match rather than a page of them.
992
- *
993
- * `filters.limit` caps the number of GROUPS returned, not the number of
994
- * messages considered — that distinction is the whole point of this lane.
995
- * Aggregating a page instead would answer "the top senders among the
996
- * twenty-five rows we happened to return", which is indistinguishable from a
997
- * real top-N unless you already knew to doubt it.
998
- */
999
- groupBy(filters, field) {
1000
- const { key, label } = this.#groupExpr(field);
1001
- const totalsParams = [];
1002
- const totalsPredicate = this.#filterPredicate(filters, totalsParams);
1003
- const totals = this.#db.prepare(`SELECT COUNT(*) AS totalRows, COUNT(DISTINCT ${key}) + MAX(CASE WHEN ${key} IS NULL THEN 1 ELSE 0 END) AS totalGroups ${EnvelopeIndex.#FROM} WHERE ${totalsPredicate}`).get(...totalsParams);
1004
- const params = [];
1005
- const predicate = this.#filterPredicate(filters, params);
1006
- params.push(filters.limit);
1007
- return {
1008
- groups: this.#db.prepare(`SELECT ${key} AS key, ${label} AS label, COUNT(*) AS count, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread, MIN(m.date_received) AS firstAt, MAX(m.date_received) AS lastAt ${EnvelopeIndex.#FROM} WHERE ${predicate} GROUP BY ${key} ORDER BY count DESC, key ASC LIMIT ?`).all(...params).map((r) => ({
1009
- key: r.key === null ? null : String(r.key),
1010
- label: r.label || null,
1011
- count: Number(r.count),
1012
- unread: Number(r.unread ?? 0),
1013
- firstAt: this.#toIso(r.firstAt),
1014
- lastAt: this.#toIso(r.lastAt)
1015
- })),
1016
- totalRows: totals.totalRows,
1017
- totalGroups: totals.totalGroups ?? 0
1018
- };
1019
- }
1020
- count(filters) {
1021
- const params = [];
1022
- const predicate = this.#mailboxPredicate(filters.mailboxRowids, params);
1023
- const row = this.#db.prepare(`SELECT COUNT(*) AS total, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread FROM messages m WHERE m.deleted = 0 AND ${predicate}`).get(...params);
1024
- return {
1025
- total: row.total,
1026
- unread: row.unread ?? 0
1027
- };
1028
- }
1029
- /** Every message in one conversation, oldest first. */
1030
- thread(conversationId, limit) {
1031
- if (!this.caps.has.conversationId) return [];
1032
- const subjectExpr = this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
1033
- return this.#db.prepare(`SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, m.conversation_id AS conversationId, 0 AS hasAttachment FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender WHERE m.deleted = 0 AND m.conversation_id = ? ORDER BY m.date_received ASC LIMIT ?`).all(conversationId, limit).map((r) => ({
1034
- rowid: Number(r.rowid),
1035
- mailboxUrl: String(r.mailboxUrl),
1036
- subject: r.subject || null,
1037
- senderAddress: r.senderAddress ?? null,
1038
- senderName: r.senderName || null,
1039
- dateReceived: this.#toIso(r.dateReceived),
1040
- dateSent: this.#toIso(r.dateSent),
1041
- read: Boolean(r.read),
1042
- flagged: Boolean(r.flagged),
1043
- size: r.size ?? null,
1044
- conversationId: r.conversationId ?? null,
1045
- hasAttachment: false
1046
- }));
1047
- }
1048
- /** conversation_id for one message, so get_thread can start from a ref. */
1049
- conversationOf(rowid) {
1050
- if (!this.caps.has.conversationId) return null;
1051
- return this.#db.prepare("SELECT conversation_id AS c FROM messages WHERE ROWID = ?").get(rowid)?.c ?? null;
1052
- }
1053
- };
1054
- //#endregion
1055
- //#region src/client/jxa/core.ts
1056
- /**
1057
- * JXA script fragments.
1058
- *
1059
- * Every script here is a static constant. None of them may contain a template
1060
- * interpolation — `osascript.assertStaticScript` rejects any script containing
1061
- * `${`, and that includes JavaScript template literals written *inside* the JXA
1062
- * source. Use string concatenation in JXA code.
1063
- *
1064
- * Every script follows the same contract:
1065
- * - it reads its parameters from `JSON.parse(argv[0])`
1066
- * - it returns `JSON.stringify({ok: true, data})` on success
1067
- * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an
1068
- * application-level failure, still exiting 0
1069
- * so that a non-zero exit always means infrastructure rather than "no such mailbox".
1184
+ * Every script here is a static constant. None of them may contain a template
1185
+ * interpolation — `osascript.assertStaticScript` rejects any script containing
1186
+ * `${`, and that includes JavaScript template literals written *inside* the JXA
1187
+ * source. Use string concatenation in JXA code.
1188
+ *
1189
+ * Every script follows the same contract:
1190
+ * - it reads its parameters from `JSON.parse(argv[0])`
1191
+ * - it returns `JSON.stringify({ok: true, data})` on success
1192
+ * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an
1193
+ * application-level failure, still exiting 0
1194
+ * so that a non-zero exit always means infrastructure rather than "no such mailbox".
1070
1195
  */
1071
1196
  /**
1072
1197
  * Shared prelude.
@@ -1576,155 +1701,19 @@ function run(argv) {
1576
1701
  }
1577
1702
  `;
1578
1703
  //#endregion
1579
- //#region src/client/jxa/read.ts
1580
- /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
1581
- const LIST_ACCOUNTS = script(`
1582
- var accts = M.accounts();
1583
- var out = [];
1584
- for (var i = 0; i < accts.length; i++) {
1585
- var a = accts[i];
1586
- out.push({
1587
- id: prop(function () { return a.id(); }, null),
1588
- name: prop(function () { return a.name(); }, null),
1589
- enabled: prop(function () { return a.enabled(); }, null),
1590
- accountType: prop(function () { return String(a.accountType()); }, null),
1591
- emailAddresses: prop(function () { return a.emailAddresses(); }, []),
1592
- fullName: prop(function () { return a.fullName(); }, null),
1593
- // Path objects need String(); JSON.stringify renders them as {}.
1594
- directory: prop(function () { return String(a.accountDirectory()); }, null),
1595
- messageCaching: prop(function () { return String(a.messageCaching()); }, null),
1596
- mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
1597
- });
1598
- }
1599
- return ok(out);
1600
- `);
1704
+ //#region src/client/jxa/write.ts
1601
1705
  /**
1602
- * Mailboxes with counts. Counts come from AppleScript rather than the index
1603
- * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
1604
- * therefore never need to degrade when Full Disk Access is missing.
1605
- */
1606
- const LIST_MAILBOXES = script(`
1607
- var accts = M.accounts();
1608
- var out = [];
1609
- for (var i = 0; i < accts.length; i++) {
1610
- var a = accts[i];
1611
- var uuid = prop(function () { return a.id(); }, null);
1612
- if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
1613
- var boxes = a.mailboxes();
1614
- for (var j = 0; j < boxes.length; j++) {
1615
- var b = boxes[j];
1616
- var entry = {
1617
- accountUuid: uuid,
1618
- accountName: prop(function () { return a.name(); }, null),
1619
- name: prop(function () { return b.name(); }, null)
1620
- };
1621
- if (p.withCounts) {
1622
- entry.unread = prop(function () { return b.unreadCount(); }, null);
1623
- entry.total = prop(function () { return b.messages.length; }, null);
1624
- }
1625
- out.push(entry);
1626
- }
1627
- }
1628
- return ok(out);
1629
- `);
1630
- /** Total and unread for one mailbox. */
1631
- const COUNT_MAILBOX = script(`
1632
- var acct = findAccount(M, p.accountUuid);
1633
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1634
- var mb = resolveMailbox(acct, p.mailbox);
1635
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1636
- return ok({
1637
- accountUuid: p.accountUuid,
1638
- mailbox: prop(function () { return mb.name(); }, p.mailbox),
1639
- total: prop(function () { return mb.messages.length; }, null),
1640
- unread: prop(function () { return mb.unreadCount(); }, null)
1641
- });
1642
- `);
1643
- /**
1644
- * The degraded listing lane: newest N of one mailbox, used when the Envelope
1645
- * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
1646
- * which is why the caller caps N hard (default 50) instead of paginating.
1647
- */
1648
- const LIST_RECENT = script(`
1649
- var acct = findAccount(M, p.accountUuid);
1650
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1651
- var mb = resolveMailbox(acct, p.mailbox);
1652
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1653
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1654
-
1655
- var total = prop(function () { return mb.messages.length; }, 0);
1656
- var n = Math.min(p.limit || 20, total);
1657
- if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
1658
-
1659
- // Batch the property reads: one Apple Event per property beats one per message
1660
- // by roughly 6x. slice() on the message collection keeps it to a range specifier.
1661
- var slice = mb.messages.slice(0, n);
1662
- var subjects = prop(function () { return slice.subject(); }, []);
1663
- var senders = prop(function () { return slice.sender(); }, []);
1664
- var dates = prop(function () { return slice.dateReceived(); }, []);
1665
- var reads = prop(function () { return slice.readStatus(); }, []);
1666
- var flags = prop(function () { return slice.flaggedStatus(); }, []);
1667
- var ids = prop(function () { return slice.id(); }, []);
1668
-
1669
- var out = [];
1670
- for (var i = 0; i < n; i++) {
1671
- out.push({
1672
- id: ids[i] === undefined ? null : ids[i],
1673
- accountUuid: p.accountUuid,
1674
- mailbox: mailboxName,
1675
- subject: subjects[i] === undefined ? null : subjects[i],
1676
- sender: senders[i] === undefined ? null : senders[i],
1677
- dateReceived: iso(dates[i]),
1678
- read: reads[i] === undefined ? null : reads[i],
1679
- flagged: flags[i] === undefined ? null : flags[i]
1680
- });
1681
- }
1682
- return ok({ mailbox: mailboxName, total: total, messages: out });
1683
- `);
1684
- /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
1685
- const GET_MESSAGES = script(`
1686
- var acct = findAccount(M, p.accountUuid);
1687
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1688
- var mb = resolveMailbox(acct, p.mailbox);
1689
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1690
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1691
-
1692
- var out = [];
1693
- for (var i = 0; i < p.ids.length; i++) {
1694
- var id = p.ids[i];
1695
- try {
1696
- var m = mb.messages.byId(id);
1697
- var summary = messageSummary(m, p.accountUuid, mailboxName);
1698
- if (p.withContent) {
1699
- summary.content = prop(function () { return m.content(); }, null);
1700
- }
1701
- if (p.withSource) {
1702
- summary.source = prop(function () { return m.source(); }, null);
1703
- }
1704
- if (p.withHeaders) {
1705
- summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
1706
- }
1707
- out.push(summary);
1708
- } catch (e) {
1709
- out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
1710
- }
1711
- }
1712
- return ok(out);
1713
- `);
1714
- //#endregion
1715
- //#region src/client/jxa/write.ts
1716
- /**
1717
- * Mutating scripts.
1718
- *
1719
- * Two rules hold across every one of them:
1720
- *
1721
- * 1. **The post-state is re-read from Mail inside the same script.** Mail
1722
- * updates its Envelope Index eventually, not immediately, so verifying a
1723
- * write by re-querying the index can report the old value and send an agent
1724
- * into a mark-it-again loop. What Mail says right after the mutation is the
1725
- * only trustworthy answer.
1726
- * 2. **Refs are grouped by mailbox by the caller**, so a batch of 50 messages
1727
- * in one mailbox costs one Apple Event, not 50.
1706
+ * Mutating scripts.
1707
+ *
1708
+ * Two rules hold across every one of them:
1709
+ *
1710
+ * 1. **The post-state is re-read from Mail inside the same script.** Mail
1711
+ * updates its Envelope Index eventually, not immediately, so verifying a
1712
+ * write by re-querying the index can report the old value and send an agent
1713
+ * into a mark-it-again loop. What Mail says right after the mutation is the
1714
+ * only trustworthy answer.
1715
+ * 2. **Refs are grouped by mailbox by the caller**, so a batch of 50 messages
1716
+ * in one mailbox costs one Apple Event, not 50.
1728
1717
  */
1729
1718
  /** Set any combination of read / flagged / flagIndex / junk on a batch of ids. */
1730
1719
  /**
@@ -2393,132 +2382,815 @@ const REPLY_OR_FORWARD = script(`
2393
2382
  : "The window could NOT be closed from here and is still on screen.")
2394
2383
  );
2395
2384
  }
2396
-
2397
- var previous = prop(function () {
2398
- return SE.applicationProcesses.whose({ frontmost: true })[0].name();
2399
- }, null);
2400
- var restore = function () {
2401
- if (previous && previous !== "Mail") {
2402
- try { SE.processes.byName(previous).frontmost = true; } catch (e) {}
2385
+
2386
+ var previous = prop(function () {
2387
+ return SE.applicationProcesses.whose({ frontmost: true })[0].name();
2388
+ }, null);
2389
+ var restore = function () {
2390
+ if (previous && previous !== "Mail") {
2391
+ try { SE.processes.byName(previous).frontmost = true; } catch (e) {}
2392
+ }
2393
+ };
2394
+
2395
+ var bodyVerified = null;
2396
+ var verifiedChars = 0;
2397
+ if (p.body) {
2398
+ var body = String(p.body);
2399
+ // Confirm the opening of the body rather than all of it. Reading the whole
2400
+ // of a long reply plus the quote it sits above costs seconds of Apple
2401
+ // Events, and buys nothing: a paste either arrives whole or does not arrive,
2402
+ // which is what was measured, so the top of it is the tell.
2403
+ var expected = body.length > 400 ? body.slice(0, 400) : body;
2404
+ var sizeBefore = composerBodySize(bodyArea);
2405
+ bodyVerified = false;
2406
+
2407
+ try {
2408
+ proc.frontmost = true;
2409
+ pause(0.4);
2410
+ for (var attempt = 0; attempt < 2 && !bodyVerified; attempt++) {
2411
+ pasteIntoComposer(win, bodyArea, body);
2412
+ var after = composerBodyText(bodyArea, expected.length + 400);
2413
+ bodyVerified = after !== null && containsText(after, expected);
2414
+ if (bodyVerified) {
2415
+ verifiedChars = expected.length;
2416
+ } else if (composerBodySize(bodyArea) !== sizeBefore) {
2417
+ // Something went in that we cannot match. Pasting again would put the
2418
+ // reply in the draft twice, and nothing here can undo that.
2419
+ break;
2420
+ }
2421
+ }
2422
+ } catch (e) {
2423
+ bodyVerified = false;
2424
+ }
2425
+
2426
+ if (!bodyVerified) {
2427
+ restore();
2428
+ // Take the window back only when it is provably still empty. A paste that
2429
+ // landed and could not be READ is a different thing from one that never
2430
+ // landed, and closing that one would destroy the reply with no way to get
2431
+ // it back -- so it is left on screen for the user to judge.
2432
+ var landed = composerBodySize(bodyArea) !== sizeBefore;
2433
+ var closedUnverified = landed ? false : discardComposer(M, draft);
2434
+ return err(
2435
+ "DRAFT_BODY_NOT_SET",
2436
+ "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
2437
+ "body did not go in: reading the composer back does not show the text that was sent. It " +
2438
+ "MUST NOT be described to the user as ready. " +
2439
+ (closedUnverified
2440
+ ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2441
+ : landed
2442
+ ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2443
+ "than discarded — look at it in Mail before retrying, because a retry would paste " +
2444
+ "the reply in twice."
2445
+ : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2446
+ "leaves a second draft behind.")
2447
+ );
2448
+ }
2449
+ }
2450
+
2451
+ if (p.sendNow) {
2452
+ // Sent from the window, so what goes out is what was just verified.
2453
+ var clicked = false;
2454
+ try {
2455
+ proc.frontmost = true;
2456
+ pause(0.4);
2457
+ try { win.actions.byName("AXRaise").perform(); } catch (e) {}
2458
+ pause(0.3);
2459
+ var send = proc.menuBars[0].menuBarItems.byName("Message").menus[0].menuItems.byName("Send");
2460
+ if (prop(function () { return send.enabled(); }, false)) {
2461
+ send.click();
2462
+ clicked = true;
2463
+ }
2464
+ } catch (e) {
2465
+ clicked = false;
2466
+ }
2467
+ // The window closing is the confirmation that it went. Wait for it rather
2468
+ // than sampling once: reporting a slow close as a failure would invite a
2469
+ // retry, and a retry after a send that DID go sends the mail twice.
2470
+ var stillOpen = true;
2471
+ var waited = 0;
2472
+ while (clicked && waited < 8000) {
2473
+ pause(0.5);
2474
+ waited += 500;
2475
+ if (composerWindow(proc, subject, 0) === null) { stillOpen = false; break; }
2476
+ }
2477
+ restore();
2478
+ if (!clicked) {
2479
+ return err(
2480
+ "SEND_FAILED",
2481
+ "The " + p.mode + " was composed and its body verified, but Message > Send would not " +
2482
+ "activate, so NOTHING WAS SENT. The draft is on screen with the right text in it and can " +
2483
+ "be sent by hand."
2484
+ );
2485
+ }
2486
+ if (stillOpen) {
2487
+ return err(
2488
+ "SEND_UNCONFIRMED",
2489
+ "The " + p.mode + " was composed, its body verified, and Send was clicked — but the window " +
2490
+ "was still open 8s later, so whether it went cannot be confirmed from here. DO NOT send it " +
2491
+ "again: check Sent in Mail first, because a retry would send it twice."
2492
+ );
2493
+ }
2494
+ return ok({ sent: true, mode: p.mode, bodyVerified: bodyVerified,
2495
+ verifiedChars: verifiedChars, subject: subject });
2496
+ }
2497
+
2498
+ restore();
2499
+ return ok({
2500
+ sent: false,
2501
+ draft: true,
2502
+ mode: p.mode,
2503
+ subject: subject,
2504
+ bodyVerified: bodyVerified,
2505
+ verifiedChars: verifiedChars,
2506
+ note: bodyVerified
2507
+ ? "Draft window is open in Mail for review; its body was read back out of the window and matches."
2508
+ : "Draft window is open in Mail for review."
2509
+ });
2510
+ `, { allowLaunch: true });
2511
+ /**
2512
+ * Open a reply or forward composer, address it, and stop.
2513
+ *
2514
+ * The Apple Events half of the NATIVE composer path — see `client/ax.ts` for
2515
+ * the other half and `client/compose.ts` for the sequence that joins them.
2516
+ *
2517
+ * It exists because a JXA object reference cannot outlive the `osascript`
2518
+ * process that made it, and `packages/core/src/osascript.ts` spawns one per
2519
+ * call by design. The old flow held `draft` from `M.reply(...)` all the way
2520
+ * through to `draft.send()`, with every Accessibility step in between; once
2521
+ * those steps move out of the script, the reference cannot survive to the end
2522
+ * of it. So this script does everything that NEEDS the reference — open,
2523
+ * address — and returns the subject, which is the identity the native half
2524
+ * addresses the window by.
2525
+ *
2526
+ * **No System Events here, deliberately.** That is the whole point of the
2527
+ * split: this half needs Automation for Mail, which every other write tool
2528
+ * already has, and nothing else. The second grant goes with the second half.
2529
+ *
2530
+ * Recipients go through the scripting object, which does work for them, and
2531
+ * only once the composer exists.
2532
+ */
2533
+ const OPEN_COMPOSER = script(`
2534
+ var acct = findAccount(M, p.accountUuid);
2535
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
2536
+ var mb = resolveMailbox(acct, p.mailbox);
2537
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
2538
+
2539
+ var original;
2540
+ try {
2541
+ original = mb.messages.byId(p.id);
2542
+ original.subject();
2543
+ } catch (e) {
2544
+ return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
2545
+ }
2546
+
2547
+ var draft;
2548
+ if (p.mode === "forward") {
2549
+ draft = M.forward(original, { openingWindow: true });
2550
+ } else {
2551
+ draft = M.reply(original, { openingWindow: true, replyToAll: p.replyToAll ? true : false });
2552
+ }
2553
+
2554
+ var subject = String(prop(function () { return draft.subject(); }, ""));
2555
+ if (!subject) {
2556
+ return err("COMPOSER_NOT_FOUND", "Mail did not return a composer for the " + p.mode + ".");
2557
+ }
2558
+
2559
+ if (p.mode === "forward") {
2560
+ var addrs = p.to || [];
2561
+ for (var i = 0; i < addrs.length; i++) {
2562
+ draft.toRecipients.push(M.ToRecipient({ address: addrs[i] }));
2563
+ }
2564
+ }
2565
+
2566
+ return ok({ subject: subject });
2567
+ `, { allowLaunch: true });
2568
+ //#endregion
2569
+ //#region src/client/compose.ts
2570
+ const run = promisify(execFile);
2571
+ /**
2572
+ * Reply or forward, with the body driven natively.
2573
+ *
2574
+ * ## Why this is two halves rather than one script
2575
+ *
2576
+ * A JXA object reference cannot outlive the `osascript` process that made it,
2577
+ * and `packages/core/src/osascript.ts` spawns one per call by design. The
2578
+ * original flow held `draft` from `M.reply(...)` through to `draft.send()`, with
2579
+ * every Accessibility step in between — so moving those steps out of the script
2580
+ * necessarily ends the reference before the send.
2581
+ *
2582
+ * The arrangement that needs no reference: `OPEN_COMPOSER` opens and addresses
2583
+ * the composer and returns the SUBJECT, which is an identity the native half can
2584
+ * find a window by; everything after is Accessibility, including the send, which
2585
+ * becomes command-shift-D rather than `draft.send()`.
2586
+ *
2587
+ * The alternative — re-finding the draft in a third Apple Events call — was
2588
+ * rejected: drafts are discovered by subject, so two with the same one are
2589
+ * indistinguishable, and this is the single path whose named failure is sending
2590
+ * the wrong thing.
2591
+ *
2592
+ * ## What is given up, and it is stated rather than hidden
2593
+ *
2594
+ * The System Events path discards the composer when a paste provably did not
2595
+ * land, so a retry is safe. This one cannot: closing an unsaved composer raises
2596
+ * a save sheet whose buttons are LOCALISED, and pressing a button by a name that
2597
+ * is only right in English is worse than not pressing one. So a failed compose
2598
+ * here always leaves the window on screen and says so. Strictly safer — nothing
2599
+ * a person wrote is ever destroyed — and strictly less tidy.
2600
+ */
2601
+ /** How long to wait for the composer, matching the System Events path's 8s. */
2602
+ const COMPOSER_TIMEOUT_MS = 8e3;
2603
+ /** How long to wait for the window to close before calling a send unconfirmed. */
2604
+ const SEND_TIMEOUT_MS = 5e3;
2605
+ /**
2606
+ * Confirm the opening of the body rather than all of it.
2607
+ *
2608
+ * A paste either arrives whole or does not arrive, which is what was measured,
2609
+ * so the top of it is the tell.
2610
+ */
2611
+ const VERIFY_CHARS = 400;
2612
+ const systemClipboard = {
2613
+ async read() {
2614
+ try {
2615
+ return (await run("/usr/bin/pbpaste", [])).stdout;
2616
+ } catch {
2617
+ return null;
2618
+ }
2619
+ },
2620
+ async write(text) {
2621
+ const child = execFile("/usr/bin/pbcopy", []);
2622
+ child.stdin?.end(text);
2623
+ await new Promise((resolve, reject) => {
2624
+ child.on("close", resolve);
2625
+ child.on("error", reject);
2626
+ });
2627
+ }
2628
+ };
2629
+ /**
2630
+ * Borrow the clipboard, and put it back.
2631
+ *
2632
+ * The same cost the System Events path documents and for the same reason: this
2633
+ * is a paste, so the pasteboard is the mechanism. A clipboard holding an image
2634
+ * or a file promise still comes back as text, because there is no way to carry
2635
+ * an arbitrary item across without knowing its type.
2636
+ */
2637
+ const withClipboard = async (clipboard, text, body) => {
2638
+ const saved = await clipboard.read();
2639
+ await clipboard.write(text);
2640
+ try {
2641
+ return await body();
2642
+ } finally {
2643
+ if (saved !== null) try {
2644
+ await clipboard.write(saved);
2645
+ } catch {}
2646
+ }
2647
+ };
2648
+ const paste = async (lane, clipboard, ref, text, focusTimeoutMs) => {
2649
+ const expected = text.length > VERIFY_CHARS ? text.slice(0, VERIFY_CHARS) : text;
2650
+ const sizeBefore = await lane.bodySize(ref.body);
2651
+ return withClipboard(clipboard, text, async () => {
2652
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2653
+ if (await lane.paste(ref, focusTimeoutMs)) {
2654
+ const after = await lane.bodyText(ref.body);
2655
+ if (after !== null && containsText(after, expected)) return {
2656
+ verified: true,
2657
+ landed: true
2658
+ };
2659
+ }
2660
+ if (await lane.bodySize(ref.body) !== sizeBefore) break;
2661
+ }
2662
+ return {
2663
+ verified: false,
2664
+ landed: await lane.bodySize(ref.body) !== sizeBefore
2665
+ };
2666
+ });
2667
+ };
2668
+ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2669
+ const clipboard = opts.clipboard ?? systemClipboard;
2670
+ const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;
2671
+ const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
2672
+ const watch = lane.watch();
2673
+ const reach = await lane.reach();
2674
+ if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));
2675
+ const subject = (await runner.run(OPEN_COMPOSER, params)).subject;
2676
+ const ref = await lane.findComposer(subject, composerTimeoutMs);
2677
+ if (!ref) return {
2678
+ ok: false,
2679
+ subject,
2680
+ bodyVerified: null,
2681
+ verifiedChars: 0,
2682
+ sent: false,
2683
+ note: `Mail was asked to open a ${params.mode} window for "${subject}" and no such window was readable within ${composerTimeoutMs / 1e3}s, although Mail's other windows read fine — so this is not a permission. Nothing was written. The window may still be on screen: look for an empty ${params.mode} in Mail before retrying, because a retry would leave a second one behind. Windows visible at the time: ${JSON.stringify(reach.windows)}.` + interferenceNote(await watch.check())
2684
+ };
2685
+ let bodyVerified = null;
2686
+ let verifiedChars = 0;
2687
+ if (params.body) {
2688
+ const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs);
2689
+ bodyVerified = result.verified;
2690
+ verifiedChars = result.verified ? Math.min(params.body.length, VERIFY_CHARS) : 0;
2691
+ if (!result.verified) return {
2692
+ ok: false,
2693
+ subject,
2694
+ bodyVerified: false,
2695
+ verifiedChars: 0,
2696
+ sent: false,
2697
+ note: `The ${params.mode} window for "${subject}" was opened and correctly addressed, but the body did not go in: reading the composer back does not show the text that was sent. It MUST NOT be described to the user as ready. ` + (result.landed ? "SOMETHING DID land in it that could not be read back — look at it in Mail before retrying, because a retry would paste the reply in twice." : "Nothing landed in it. It was left open rather than discarded, because closing an unsaved composer raises a save sheet whose buttons are localised. Close it in Mail, then retry.") + interferenceNote(await watch.check())
2698
+ };
2699
+ }
2700
+ await lane.finish(params.sendNow);
2701
+ const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;
2702
+ return {
2703
+ ok: params.sendNow ? sent : true,
2704
+ subject,
2705
+ bodyVerified,
2706
+ verifiedChars,
2707
+ sent,
2708
+ note: params.sendNow ? sent ? "Sent." : `The ${params.mode} was composed and verified, but its window is still open ${sendTimeoutMs / 1e3}s after the send, so it may not have gone. Check Mail before retrying.` : "Draft window is open in Mail for review."
2709
+ };
2710
+ };
2711
+ //#endregion
2712
+ //#region src/client/schema.ts
2713
+ const REQUIRED = {
2714
+ messages: [
2715
+ "mailbox",
2716
+ "subject",
2717
+ "sender",
2718
+ "date_received",
2719
+ "read",
2720
+ "deleted"
2721
+ ],
2722
+ mailboxes: ["url"],
2723
+ subjects: ["subject"],
2724
+ addresses: ["address"]
2725
+ };
2726
+ const introspect = (db, now) => {
2727
+ const fingerprint = fingerprintSchema(db);
2728
+ const tables = tableMap(db);
2729
+ const tableNames = Object.keys(tables);
2730
+ const missing = [];
2731
+ for (const [table, cols] of Object.entries(REQUIRED)) {
2732
+ if (!tables[table]) {
2733
+ missing.push(`${table} (table)`);
2734
+ continue;
2735
+ }
2736
+ for (const c of cols) if (!tables[table]?.includes(c)) missing.push(`${table}.${c}`);
2737
+ }
2738
+ const messageCols = tables.messages ?? [];
2739
+ let epoch = {
2740
+ offset: 0,
2741
+ reason: "not probed"
2742
+ };
2743
+ if (missing.length === 0) {
2744
+ const row = db.prepare("SELECT MAX(date_received) AS m FROM messages").get();
2745
+ epoch = detectEpoch(row?.m ?? null, now);
2746
+ }
2747
+ return {
2748
+ fingerprint,
2749
+ tables,
2750
+ has: {
2751
+ labels: tableNames.includes("labels"),
2752
+ recipients: tableNames.includes("recipients"),
2753
+ attachments: tableNames.includes("attachments"),
2754
+ subjects: tableNames.includes("subjects"),
2755
+ addresses: tableNames.includes("addresses"),
2756
+ subjectPrefix: messageCols.includes("subject_prefix"),
2757
+ conversationId: messageCols.includes("conversation_id"),
2758
+ flagged: messageCols.includes("flagged"),
2759
+ dateSent: messageCols.includes("date_sent"),
2760
+ messageIdHeader: (tables.message_global_data ?? []).includes("message_id_header"),
2761
+ mailboxCounts: (tables.mailboxes ?? []).includes("unread_count")
2762
+ },
2763
+ epochOffset: epoch.offset,
2764
+ epochReason: epoch.reason,
2765
+ missing
2766
+ };
2767
+ };
2768
+ const assertUsable = (caps) => {
2769
+ if (caps.missing.length > 0) throw new SchemaDriftError(`Mail's search index is not the shape this server knows how to read (missing: ${caps.missing.join(", ")}). This usually means a macOS upgrade changed the schema. The AppleScript lane still works; please report schema fingerprint ${caps.fingerprint}.`, {
2770
+ fingerprint: caps.fingerprint,
2771
+ missing: caps.missing
2772
+ });
2773
+ };
2774
+ //#endregion
2775
+ //#region src/client/envelope.ts
2776
+ /**
2777
+ * What a mail query can group on.
2778
+ *
2779
+ * The single source of truth for both the tool's enum and the SQL expressions
2780
+ * in `#groupExpr` — a field can only be asked for if it is listed here, which
2781
+ * is what keeps caller strings out of the statement.
2782
+ */
2783
+ const GROUP_FIELDS = [
2784
+ "sender",
2785
+ "mailbox",
2786
+ "subject",
2787
+ "day",
2788
+ "month"
2789
+ ];
2790
+ const contains = (value) => `%${escapeLike(value)}%`;
2791
+ const openIndex = (path, mode, logger) => {
2792
+ const { db, mode: opened, validated: caps } = openReadOnly(path, mode, {
2793
+ envVar: "APPLE_MAIL_INDEX_MODE",
2794
+ label: "Mail's search index",
2795
+ hint: "If this is a permission error, grant Full Disk Access to the app running this server.",
2796
+ validate: (conn) => {
2797
+ const found = introspect(conn);
2798
+ assertUsable(found);
2799
+ return found;
2800
+ },
2801
+ fatal: (err) => err instanceof SchemaDriftError,
2802
+ onFallback: () => logger?.warn?.("opened the index with immutable=1; results may omit mail that is still in the -wal")
2803
+ });
2804
+ return {
2805
+ db,
2806
+ mode: opened,
2807
+ caps
2808
+ };
2809
+ };
2810
+ var EnvelopeIndex = class EnvelopeIndex {
2811
+ #db;
2812
+ caps;
2813
+ mode;
2814
+ constructor(opened) {
2815
+ this.#db = opened.db;
2816
+ this.caps = opened.caps;
2817
+ this.mode = opened.mode;
2818
+ }
2819
+ close() {
2820
+ try {
2821
+ this.#db.close();
2822
+ } catch {}
2823
+ }
2824
+ /** id -> url for every mailbox, so results can be mapped back to scriptable names. */
2825
+ mailboxes() {
2826
+ const hasCounts = this.caps.has.mailboxCounts;
2827
+ return this.#db.prepare(hasCounts ? "SELECT ROWID AS rowid, url, total_count AS total, unread_count AS unread FROM mailboxes" : "SELECT ROWID AS rowid, url, NULL AS total, NULL AS unread FROM mailboxes").all();
2828
+ }
2829
+ /**
2830
+ * Restrict to a set of mailboxes.
2831
+ *
2832
+ * The `labels` half is not optional for Gmail. Gmail-over-IMAP keeps every
2833
+ * message in `[Gmail]/All Mail` and expresses INBOX membership as a label
2834
+ * row, so `m.mailbox IN (...)` alone returns an EMPTY inbox — measured here
2835
+ * as 0 rows against 51,128 real messages.
2836
+ */
2837
+ #mailboxPredicate(rowids, params) {
2838
+ if (rowids === void 0) return "1=1";
2839
+ if (rowids.length === 0) return "1=0";
2840
+ const placeholders = rowids.map(() => "?").join(",");
2841
+ if (!this.caps.has.labels) {
2842
+ params.push(...rowids);
2843
+ return `m.mailbox IN (${placeholders})`;
2844
+ }
2845
+ params.push(...rowids, ...rowids);
2846
+ return `(m.mailbox IN (${placeholders}) OR m.ROWID IN (SELECT message_id FROM labels WHERE mailbox_id IN (${placeholders})))`;
2847
+ }
2848
+ #toIso(value) {
2849
+ if (value === null || !Number.isFinite(value)) return null;
2850
+ return (/* @__PURE__ */ new Date((value + this.caps.epochOffset) * 1e3)).toISOString();
2851
+ }
2852
+ /**
2853
+ * A resolved instant to this store's own units.
2854
+ *
2855
+ * Takes a Date rather than a string, which is the whole point: it used to do
2856
+ * `Date.parse(iso)`, and `Date.parse("last week")` is NaN. node:sqlite binds
2857
+ * NaN as NULL, `date_received >= NULL` matches nothing, and the caller got
2858
+ * zero results with no error. Parsing now happens once, in core's grammar,
2859
+ * which refuses what it cannot read.
2860
+ */
2861
+ #toEpoch(when) {
2862
+ return Math.floor(when.getTime() / 1e3) - this.caps.epochOffset;
2863
+ }
2864
+ /**
2865
+ * The WHERE half of a filtered read, appending its bind values to `params`.
2866
+ *
2867
+ * Shared by `search` and `groupBy` so the two cannot drift: a filter that
2868
+ * narrowed a listing but not its aggregate would make "count per sender in
2869
+ * INBOX" quietly count the whole archive.
2870
+ *
2871
+ * Call this before adding any other bind value — the placeholders it appends
2872
+ * have to come first in the parameter list, which mirrors WHERE preceding
2873
+ * ORDER BY and LIMIT in every statement built from it.
2874
+ */
2875
+ #filterPredicate(filters, params) {
2876
+ const where = ["m.deleted = 0"];
2877
+ where.push(this.#mailboxPredicate(filters.mailboxRowids, params));
2878
+ if (filters.query) {
2879
+ where.push("(s.subject LIKE ? ESCAPE '\\' OR a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
2880
+ params.push(contains(filters.query), contains(filters.query), contains(filters.query));
2881
+ }
2882
+ if (filters.subject) {
2883
+ where.push("s.subject LIKE ? ESCAPE '\\'");
2884
+ params.push(contains(filters.subject));
2885
+ }
2886
+ if (filters.sender) {
2887
+ where.push("(a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
2888
+ params.push(contains(filters.sender), contains(filters.sender));
2889
+ }
2890
+ if (filters.recipient && this.caps.has.recipients) {
2891
+ where.push("EXISTS (SELECT 1 FROM recipients r JOIN addresses ra ON ra.ROWID = r.address WHERE r.message = m.ROWID AND ra.address LIKE ? ESCAPE '\\')");
2892
+ params.push(contains(filters.recipient));
2893
+ }
2894
+ if (filters.unreadOnly) where.push("m.read = 0");
2895
+ if (filters.flaggedOnly && this.caps.has.flagged) where.push("m.flagged = 1");
2896
+ if (filters.hasAttachment && this.caps.has.attachments) where.push("EXISTS (SELECT 1 FROM attachments at WHERE at.message = m.ROWID)");
2897
+ if (filters.dateFrom) {
2898
+ where.push("m.date_received >= ?");
2899
+ params.push(this.#toEpoch(parseBound("dateFrom", filters.dateFrom, "start")));
2900
+ }
2901
+ if (filters.dateTo) {
2902
+ where.push("m.date_received < ?");
2903
+ params.push(this.#toEpoch(parseBound("dateTo", filters.dateTo, "end")));
2904
+ }
2905
+ return where.join(" AND ");
2906
+ }
2907
+ /**
2908
+ * The joins every filtered read needs. `s` and `a` are LEFT joins because a
2909
+ * message can legitimately have no subject row and no sender row, and an
2910
+ * INNER join here would drop exactly those from counts.
2911
+ */
2912
+ static #FROM = "FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender";
2913
+ /**
2914
+ * subject_prefix holds "Re: " / "Fwd: " separately from the deduplicated
2915
+ * subject row, so the displayed subject is the concatenation of the two.
2916
+ */
2917
+ get #subjectExpr() {
2918
+ return this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
2919
+ }
2920
+ search(filters) {
2921
+ const params = [];
2922
+ const predicate = this.#filterPredicate(filters, params);
2923
+ const sql = `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${this.#subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, ${this.caps.has.conversationId ? "m.conversation_id" : "NULL"} AS conversationId, ` + (this.caps.has.attachments ? "EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment " : "0 AS hasAttachment ") + `${EnvelopeIndex.#FROM} WHERE ${predicate} ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;
2924
+ params.push(filters.limit, filters.offset);
2925
+ return this.#db.prepare(sql).all(...params).map((r) => ({
2926
+ rowid: Number(r.rowid),
2927
+ mailboxUrl: String(r.mailboxUrl),
2928
+ subject: r.subject || null,
2929
+ senderAddress: r.senderAddress ?? null,
2930
+ senderName: r.senderName || null,
2931
+ dateReceived: this.#toIso(r.dateReceived),
2932
+ dateSent: this.#toIso(r.dateSent),
2933
+ read: Boolean(r.read),
2934
+ flagged: Boolean(r.flagged),
2935
+ size: r.size ?? null,
2936
+ conversationId: r.conversationId ?? null,
2937
+ hasAttachment: Boolean(r.hasAttachment)
2938
+ }));
2939
+ }
2940
+ /**
2941
+ * The column expression each groupable field aggregates on.
2942
+ *
2943
+ * A key here is the ONLY thing that reaches the statement — the tool matches
2944
+ * the caller's string against `GROUP_FIELDS` and passes the matched literal,
2945
+ * so no caller-controlled text is ever interpolated. `label` is a second,
2946
+ * human-readable form of the same group where one exists; it goes through
2947
+ * MAX() because everything outside GROUP BY has to be aggregated, and the
2948
+ * value is constant within a group anyway.
2949
+ */
2950
+ #groupExpr(field) {
2951
+ switch (field) {
2952
+ case "sender": return {
2953
+ key: "a.address",
2954
+ label: "MAX(NULLIF(a.comment, ''))"
2955
+ };
2956
+ case "mailbox": return {
2957
+ key: "m.mailbox",
2958
+ label: "MAX(mb.url)"
2959
+ };
2960
+ case "subject": return {
2961
+ key: this.#subjectExpr,
2962
+ label: "NULL"
2963
+ };
2964
+ case "day": return {
2965
+ key: this.#dateBucket("%Y-%m-%d"),
2966
+ label: "NULL"
2967
+ };
2968
+ case "month": return {
2969
+ key: this.#dateBucket("%Y-%m"),
2970
+ label: "NULL"
2971
+ };
2972
+ }
2973
+ }
2974
+ /**
2975
+ * `date_received` is epoch-with-offset, so shift it before formatting.
2976
+ *
2977
+ * `'localtime'`, matching Messages' buckets and — since the shared grammar
2978
+ * landed — matching the bounds. A day bucket is a CALENDAR day, and a person
2979
+ * asking "how much mail per day" means their own days. In UTC a message that
2980
+ * arrived at 23:30 local counted against tomorrow, so a bare `dateTo` naming
2981
+ * a local day could return rows the grouping then filed under the day after
2982
+ * the one that was asked for.
2983
+ */
2984
+ #dateBucket(format) {
2985
+ return `strftime('${format}', datetime(m.date_received + ${this.caps.epochOffset}, 'unixepoch', 'localtime'))`;
2986
+ }
2987
+ /**
2988
+ * Count matches per group, over every match rather than a page of them.
2989
+ *
2990
+ * `filters.limit` caps the number of GROUPS returned, not the number of
2991
+ * messages considered — that distinction is the whole point of this lane.
2992
+ * Aggregating a page instead would answer "the top senders among the
2993
+ * twenty-five rows we happened to return", which is indistinguishable from a
2994
+ * real top-N unless you already knew to doubt it.
2995
+ */
2996
+ groupBy(filters, field) {
2997
+ const { key, label } = this.#groupExpr(field);
2998
+ const totalsParams = [];
2999
+ const totalsPredicate = this.#filterPredicate(filters, totalsParams);
3000
+ const totals = this.#db.prepare(`SELECT COUNT(*) AS totalRows, COUNT(DISTINCT ${key}) + MAX(CASE WHEN ${key} IS NULL THEN 1 ELSE 0 END) AS totalGroups ${EnvelopeIndex.#FROM} WHERE ${totalsPredicate}`).get(...totalsParams);
3001
+ const params = [];
3002
+ const predicate = this.#filterPredicate(filters, params);
3003
+ params.push(filters.limit);
3004
+ return {
3005
+ groups: this.#db.prepare(`SELECT ${key} AS key, ${label} AS label, COUNT(*) AS count, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread, MIN(m.date_received) AS firstAt, MAX(m.date_received) AS lastAt ${EnvelopeIndex.#FROM} WHERE ${predicate} GROUP BY ${key} ORDER BY count DESC, key ASC LIMIT ?`).all(...params).map((r) => ({
3006
+ key: r.key === null ? null : String(r.key),
3007
+ label: r.label || null,
3008
+ count: Number(r.count),
3009
+ unread: Number(r.unread ?? 0),
3010
+ firstAt: this.#toIso(r.firstAt),
3011
+ lastAt: this.#toIso(r.lastAt)
3012
+ })),
3013
+ totalRows: totals.totalRows,
3014
+ totalGroups: totals.totalGroups ?? 0
3015
+ };
3016
+ }
3017
+ /**
3018
+ * Narrowed to the one filter this actually applies.
3019
+ *
3020
+ * It used to take the whole filter set, which promised a query/sender/date
3021
+ * scope it silently dropped. No caller passed one, so the lie was free —
3022
+ * until somebody added a caller that did.
3023
+ */
3024
+ count(filters) {
3025
+ const params = [];
3026
+ const predicate = this.#mailboxPredicate(filters.mailboxRowids, params);
3027
+ const row = this.#db.prepare(`SELECT COUNT(*) AS total, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread FROM messages m WHERE m.deleted = 0 AND ${predicate}`).get(...params);
3028
+ return {
3029
+ total: row.total,
3030
+ unread: row.unread ?? 0
3031
+ };
3032
+ }
3033
+ /** Every message in one conversation, oldest first. */
3034
+ thread(conversationId, limit) {
3035
+ if (!this.caps.has.conversationId) return [];
3036
+ const subjectExpr = this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
3037
+ return this.#db.prepare(`SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, m.conversation_id AS conversationId, 0 AS hasAttachment FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender WHERE m.deleted = 0 AND m.conversation_id = ? ORDER BY m.date_received ASC LIMIT ?`).all(conversationId, limit).map((r) => ({
3038
+ rowid: Number(r.rowid),
3039
+ mailboxUrl: String(r.mailboxUrl),
3040
+ subject: r.subject || null,
3041
+ senderAddress: r.senderAddress ?? null,
3042
+ senderName: r.senderName || null,
3043
+ dateReceived: this.#toIso(r.dateReceived),
3044
+ dateSent: this.#toIso(r.dateSent),
3045
+ read: Boolean(r.read),
3046
+ flagged: Boolean(r.flagged),
3047
+ size: r.size ?? null,
3048
+ conversationId: r.conversationId ?? null,
3049
+ hasAttachment: false
3050
+ }));
3051
+ }
3052
+ /** conversation_id for one message, so get_thread can start from a ref. */
3053
+ conversationOf(rowid) {
3054
+ if (!this.caps.has.conversationId) return null;
3055
+ return this.#db.prepare("SELECT conversation_id AS c FROM messages WHERE ROWID = ?").get(rowid)?.c ?? null;
3056
+ }
3057
+ };
3058
+ //#endregion
3059
+ //#region src/client/jxa/read.ts
3060
+ /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
3061
+ const LIST_ACCOUNTS = script(`
3062
+ var accts = M.accounts();
3063
+ var out = [];
3064
+ for (var i = 0; i < accts.length; i++) {
3065
+ var a = accts[i];
3066
+ out.push({
3067
+ id: prop(function () { return a.id(); }, null),
3068
+ name: prop(function () { return a.name(); }, null),
3069
+ enabled: prop(function () { return a.enabled(); }, null),
3070
+ accountType: prop(function () { return String(a.accountType()); }, null),
3071
+ emailAddresses: prop(function () { return a.emailAddresses(); }, []),
3072
+ fullName: prop(function () { return a.fullName(); }, null),
3073
+ // Path objects need String(); JSON.stringify renders them as {}.
3074
+ directory: prop(function () { return String(a.accountDirectory()); }, null),
3075
+ messageCaching: prop(function () { return String(a.messageCaching()); }, null),
3076
+ mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
3077
+ });
3078
+ }
3079
+ return ok(out);
3080
+ `);
3081
+ /**
3082
+ * Mailboxes with counts. Counts come from AppleScript rather than the index
3083
+ * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
3084
+ * therefore never need to degrade when Full Disk Access is missing.
3085
+ */
3086
+ const LIST_MAILBOXES = script(`
3087
+ var accts = M.accounts();
3088
+ var out = [];
3089
+ for (var i = 0; i < accts.length; i++) {
3090
+ var a = accts[i];
3091
+ var uuid = prop(function () { return a.id(); }, null);
3092
+ if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
3093
+ var boxes = a.mailboxes();
3094
+ for (var j = 0; j < boxes.length; j++) {
3095
+ var b = boxes[j];
3096
+ var entry = {
3097
+ accountUuid: uuid,
3098
+ accountName: prop(function () { return a.name(); }, null),
3099
+ name: prop(function () { return b.name(); }, null)
3100
+ };
3101
+ if (p.withCounts) {
3102
+ entry.unread = prop(function () { return b.unreadCount(); }, null);
3103
+ entry.total = prop(function () { return b.messages.length; }, null);
3104
+ }
3105
+ out.push(entry);
2403
3106
  }
2404
- };
3107
+ }
3108
+ return ok(out);
3109
+ `);
3110
+ /** Total and unread for one mailbox. */
3111
+ const COUNT_MAILBOX = script(`
3112
+ var acct = findAccount(M, p.accountUuid);
3113
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3114
+ var mb = resolveMailbox(acct, p.mailbox);
3115
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3116
+ return ok({
3117
+ accountUuid: p.accountUuid,
3118
+ mailbox: prop(function () { return mb.name(); }, p.mailbox),
3119
+ total: prop(function () { return mb.messages.length; }, null),
3120
+ unread: prop(function () { return mb.unreadCount(); }, null)
3121
+ });
3122
+ `);
3123
+ /**
3124
+ * The degraded listing lane: newest N of one mailbox, used when the Envelope
3125
+ * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
3126
+ * which is why the caller caps N hard (default 50) instead of paginating.
3127
+ */
3128
+ const LIST_RECENT = script(`
3129
+ var acct = findAccount(M, p.accountUuid);
3130
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3131
+ var mb = resolveMailbox(acct, p.mailbox);
3132
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3133
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
2405
3134
 
2406
- var bodyVerified = null;
2407
- var verifiedChars = 0;
2408
- if (p.body) {
2409
- var body = String(p.body);
2410
- // Confirm the opening of the body rather than all of it. Reading the whole
2411
- // of a long reply plus the quote it sits above costs seconds of Apple
2412
- // Events, and buys nothing: a paste either arrives whole or does not arrive,
2413
- // which is what was measured, so the top of it is the tell.
2414
- var expected = body.length > 400 ? body.slice(0, 400) : body;
2415
- var sizeBefore = composerBodySize(bodyArea);
2416
- bodyVerified = false;
3135
+ var total = prop(function () { return mb.messages.length; }, 0);
3136
+ var n = Math.min(p.limit || 20, total);
3137
+ if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
2417
3138
 
2418
- try {
2419
- proc.frontmost = true;
2420
- pause(0.4);
2421
- for (var attempt = 0; attempt < 2 && !bodyVerified; attempt++) {
2422
- pasteIntoComposer(win, bodyArea, body);
2423
- var after = composerBodyText(bodyArea, expected.length + 400);
2424
- bodyVerified = after !== null && containsText(after, expected);
2425
- if (bodyVerified) {
2426
- verifiedChars = expected.length;
2427
- } else if (composerBodySize(bodyArea) !== sizeBefore) {
2428
- // Something went in that we cannot match. Pasting again would put the
2429
- // reply in the draft twice, and nothing here can undo that.
2430
- break;
2431
- }
2432
- }
2433
- } catch (e) {
2434
- bodyVerified = false;
2435
- }
3139
+ // Batch the property reads: one Apple Event per property beats one per message
3140
+ // by roughly 6x. slice() on the message collection keeps it to a range specifier.
3141
+ var slice = mb.messages.slice(0, n);
3142
+ var subjects = prop(function () { return slice.subject(); }, []);
3143
+ var senders = prop(function () { return slice.sender(); }, []);
3144
+ var dates = prop(function () { return slice.dateReceived(); }, []);
3145
+ var reads = prop(function () { return slice.readStatus(); }, []);
3146
+ var flags = prop(function () { return slice.flaggedStatus(); }, []);
3147
+ var ids = prop(function () { return slice.id(); }, []);
2436
3148
 
2437
- if (!bodyVerified) {
2438
- restore();
2439
- // Take the window back only when it is provably still empty. A paste that
2440
- // landed and could not be READ is a different thing from one that never
2441
- // landed, and closing that one would destroy the reply with no way to get
2442
- // it back -- so it is left on screen for the user to judge.
2443
- var landed = composerBodySize(bodyArea) !== sizeBefore;
2444
- var closedUnverified = landed ? false : discardComposer(M, draft);
2445
- return err(
2446
- "DRAFT_BODY_NOT_SET",
2447
- "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
2448
- "body did not go in: reading the composer back does not show the text that was sent. It " +
2449
- "MUST NOT be described to the user as ready. " +
2450
- (closedUnverified
2451
- ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2452
- : landed
2453
- ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2454
- "than discarded — look at it in Mail before retrying, because a retry would paste " +
2455
- "the reply in twice."
2456
- : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2457
- "leaves a second draft behind.")
2458
- );
2459
- }
3149
+ var out = [];
3150
+ for (var i = 0; i < n; i++) {
3151
+ out.push({
3152
+ id: ids[i] === undefined ? null : ids[i],
3153
+ accountUuid: p.accountUuid,
3154
+ mailbox: mailboxName,
3155
+ subject: subjects[i] === undefined ? null : subjects[i],
3156
+ sender: senders[i] === undefined ? null : senders[i],
3157
+ dateReceived: iso(dates[i]),
3158
+ read: reads[i] === undefined ? null : reads[i],
3159
+ flagged: flags[i] === undefined ? null : flags[i]
3160
+ });
2460
3161
  }
3162
+ return ok({ mailbox: mailboxName, total: total, messages: out });
3163
+ `);
3164
+ /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
3165
+ const GET_MESSAGES = script(`
3166
+ var acct = findAccount(M, p.accountUuid);
3167
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3168
+ var mb = resolveMailbox(acct, p.mailbox);
3169
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3170
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
2461
3171
 
2462
- if (p.sendNow) {
2463
- // Sent from the window, so what goes out is what was just verified.
2464
- var clicked = false;
3172
+ var out = [];
3173
+ for (var i = 0; i < p.ids.length; i++) {
3174
+ var id = p.ids[i];
2465
3175
  try {
2466
- proc.frontmost = true;
2467
- pause(0.4);
2468
- try { win.actions.byName("AXRaise").perform(); } catch (e) {}
2469
- pause(0.3);
2470
- var send = proc.menuBars[0].menuBarItems.byName("Message").menus[0].menuItems.byName("Send");
2471
- if (prop(function () { return send.enabled(); }, false)) {
2472
- send.click();
2473
- clicked = true;
3176
+ var m = mb.messages.byId(id);
3177
+ var summary = messageSummary(m, p.accountUuid, mailboxName);
3178
+ if (p.withContent) {
3179
+ summary.content = prop(function () { return m.content(); }, null);
3180
+ }
3181
+ if (p.withSource) {
3182
+ summary.source = prop(function () { return m.source(); }, null);
2474
3183
  }
3184
+ if (p.withHeaders) {
3185
+ summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
3186
+ }
3187
+ out.push(summary);
2475
3188
  } catch (e) {
2476
- clicked = false;
2477
- }
2478
- // The window closing is the confirmation that it went. Wait for it rather
2479
- // than sampling once: reporting a slow close as a failure would invite a
2480
- // retry, and a retry after a send that DID go sends the mail twice.
2481
- var stillOpen = true;
2482
- var waited = 0;
2483
- while (clicked && waited < 8000) {
2484
- pause(0.5);
2485
- waited += 500;
2486
- if (composerWindow(proc, subject, 0) === null) { stillOpen = false; break; }
2487
- }
2488
- restore();
2489
- if (!clicked) {
2490
- return err(
2491
- "SEND_FAILED",
2492
- "The " + p.mode + " was composed and its body verified, but Message > Send would not " +
2493
- "activate, so NOTHING WAS SENT. The draft is on screen with the right text in it and can " +
2494
- "be sent by hand."
2495
- );
2496
- }
2497
- if (stillOpen) {
2498
- return err(
2499
- "SEND_UNCONFIRMED",
2500
- "The " + p.mode + " was composed, its body verified, and Send was clicked — but the window " +
2501
- "was still open 8s later, so whether it went cannot be confirmed from here. DO NOT send it " +
2502
- "again: check Sent in Mail first, because a retry would send it twice."
2503
- );
3189
+ out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
2504
3190
  }
2505
- return ok({ sent: true, mode: p.mode, bodyVerified: bodyVerified,
2506
- verifiedChars: verifiedChars, subject: subject });
2507
3191
  }
2508
-
2509
- restore();
2510
- return ok({
2511
- sent: false,
2512
- draft: true,
2513
- mode: p.mode,
2514
- subject: subject,
2515
- bodyVerified: bodyVerified,
2516
- verifiedChars: verifiedChars,
2517
- note: bodyVerified
2518
- ? "Draft window is open in Mail for review; its body was read back out of the window and matches."
2519
- : "Draft window is open in Mail for review."
2520
- });
2521
- `, { allowLaunch: true });
3192
+ return ok(out);
3193
+ `);
2522
3194
  //#endregion
2523
3195
  //#region src/client/mailbox-map.ts
2524
3196
  var MailboxMap = class {
@@ -2655,6 +3327,15 @@ var AppleMailClient = class {
2655
3327
  runner;
2656
3328
  mailboxes;
2657
3329
  #logger;
3330
+ /**
3331
+ * The native Accessibility lane, when this server is hosted by Cupertino.
3332
+ *
3333
+ * Null when it is not — a package installed from npm and run by hand — and
3334
+ * that is the supported case rather than a fault, so every use of it falls
3335
+ * back to the System Events path rather than refusing. `diagnostics` reports
3336
+ * which one is live.
3337
+ */
3338
+ #ax;
2658
3339
  #located = null;
2659
3340
  #index = null;
2660
3341
  #indexError = null;
@@ -2673,6 +3354,11 @@ var AppleMailClient = class {
2673
3354
  allowlist: opts.config.accounts,
2674
3355
  ttlMs: opts.config.mailboxCacheTtlMs
2675
3356
  });
3357
+ this.#ax = opts.ax !== void 0 ? opts.ax : MailAxLane.open();
3358
+ }
3359
+ /** Which composer lane is live, for `diagnostics` to report. */
3360
+ get composerLane() {
3361
+ return this.#ax ? "accessibility" : "system-events";
2676
3362
  }
2677
3363
  accounts(force = false) {
2678
3364
  return this.mailboxes.accounts(force);
@@ -2721,6 +3407,24 @@ var AppleMailClient = class {
2721
3407
  };
2722
3408
  }
2723
3409
  }
3410
+ /**
3411
+ * Can the NATIVE lane actually read Mail's windows, right now?
3412
+ *
3413
+ * The same principle `composerAccess` states for the System Events path, for
3414
+ * the same reason: `composerLane` above says which lane is configured, and
3415
+ * configured is a claim. This is the functional read, and when the two
3416
+ * disagree this is the one to believe.
3417
+ *
3418
+ * Null when there is no native lane, which is not a failure — see `#ax`.
3419
+ */
3420
+ async composerAxReach() {
3421
+ if (!this.#ax) return null;
3422
+ const reach = await this.#ax.reach();
3423
+ return {
3424
+ ok: reach.ok,
3425
+ windows: reach.windows
3426
+ };
3427
+ }
2724
3428
  async lanes() {
2725
3429
  /**
2726
3430
  * Probe twice before declaring the lane dead.
@@ -2868,6 +3572,11 @@ var AppleMailClient = class {
2868
3572
  if (wanted && entry.mailbox.toLowerCase() !== wanted.toLowerCase()) continue;
2869
3573
  rowids.push(rowid);
2870
3574
  }
3575
+ if (rowids.length === 0) {
3576
+ const known = [...lookup.values()].filter((e) => !account || e.accountUuid === account.id).map((e) => e.mailbox);
3577
+ const unique = [...new Set(known)].toSorted();
3578
+ throw new PreconditionError(`No mailbox matching ${JSON.stringify(opts.mailbox ?? "")}${account ? ` in account ${JSON.stringify(account.name)}` : ""} is present in Mail's search index.` + (unique.length ? ` Indexed there: ${unique.slice(0, 20).join(", ")}.` : " That account has no indexed mailboxes at all."));
3579
+ }
2871
3580
  return rowids;
2872
3581
  }
2873
3582
  /**
@@ -3272,13 +3981,20 @@ var AppleMailClient = class {
3272
3981
  const decoded = decodeRef(ref);
3273
3982
  const located = await this.#lookupMessageFile(decoded);
3274
3983
  if (!located.found) throw new PreconditionError(`The message file was not found, so its attachments are not reachable. ${located.explain}`, { probed: located.lookup?.probed.slice(0, 3) ?? [] });
3275
- const { bytes, from } = extractAttachment(located.path, filename, decoded.id);
3276
3984
  const root = resolve(this.config.attachmentDir);
3277
3985
  const target = resolve(join(root, basename(filename)));
3278
3986
  if (target !== join(root, basename(filename)) || !target.startsWith(root + sep)) throw new PreconditionError(`Refusing to write outside ${root}. Set APPLE_MAIL_ATTACHMENT_DIR to change the destination.`);
3279
- if (existsSync(target) && !opts.overwrite) throw new PreconditionError(`${target} already exists; refusing to overwrite it.`);
3987
+ const { bytes, from } = extractAttachment(located.path, filename, decoded.id);
3280
3988
  mkdirSync(root, { recursive: true });
3281
- writeFileSync(target, bytes, { mode: 384 });
3989
+ try {
3990
+ writeFileSync(target, bytes, {
3991
+ mode: 384,
3992
+ flag: opts.overwrite ? "w" : "wx"
3993
+ });
3994
+ } catch (err) {
3995
+ if (err.code === "EEXIST") throw new PreconditionError(`${target} already exists; refusing to overwrite it.`);
3996
+ throw err;
3997
+ }
3282
3998
  return {
3283
3999
  path: target,
3284
4000
  bytes: bytes.length,
@@ -3456,7 +4172,7 @@ var AppleMailClient = class {
3456
4172
  }
3457
4173
  async replyOrForward(ref, opts) {
3458
4174
  const decoded = decodeRef(ref);
3459
- return this.runner.run(REPLY_OR_FORWARD, {
4175
+ const params = {
3460
4176
  accountUuid: decoded.accountUuid,
3461
4177
  mailbox: decoded.mailbox,
3462
4178
  id: decoded.id,
@@ -3465,7 +4181,9 @@ var AppleMailClient = class {
3465
4181
  to: opts.to ?? [],
3466
4182
  replyToAll: opts.replyToAll ?? false,
3467
4183
  sendNow: opts.sendNow
3468
- });
4184
+ };
4185
+ if (this.#ax) return replyOrForwardNatively(this.#ax, this.runner, params);
4186
+ return this.runner.run(REPLY_OR_FORWARD, params);
3469
4187
  }
3470
4188
  #withRef(m) {
3471
4189
  const { id, accountUuid, mailbox, ...rest } = m;
@@ -3763,6 +4481,7 @@ const buildDiagnostics = async (client, ctx) => {
3763
4481
  const located = await client.locate();
3764
4482
  const messageFile = await client.probeMessageFile();
3765
4483
  const composer = await client.composerAccess();
4484
+ const axReach = await client.composerAxReach();
3766
4485
  let accounts = [];
3767
4486
  let accountsError = null;
3768
4487
  try {
@@ -3803,7 +4522,13 @@ const buildDiagnostics = async (client, ctx) => {
3803
4522
  automationSystemEvents: composer.systemEvents,
3804
4523
  composerUiRead: composer.uiRead,
3805
4524
  ...composer.windows ? { composerWindowsSeen: composer.windows } : {},
3806
- ...composer.uiRead === "granted" && composer.systemEvents === "granted" ? {} : { composerNote: "Filling a Mail composer goes through System Events, which needs BOTH of the above: Automation to System Events (a different grant from Automation to Mail) and Accessibility. Until both are granted, apple_mail_reply_to_message and apple_mail_forward_message fail with COMPOSER_NOT_FOUND while every other tool works. Grant them to the Cupertino bundle that is RUNNING — not to your terminal and not to node: the app is the process macOS holds responsible, and the servers do inherit its identity. If Cupertino's own Settings shows a GREEN Accessibility row while `composerUiRead` above says denied, believe this line and not the row: one bundle identifier can hold several Accessibility entries at once, one per path and signature it has been granted at (an installed copy, a development build, each earlier reinstall), and the two checks can match different ones. The cure is to clear them all and grant once, from the bundle that is running: `tccutil reset Accessibility io.mgcrea.cupertino`, then Ask… in Cupertino's Settings — it reported resetting FOUR entries the first time this was hit. Accessibility is in System Settings > Privacy & Security > Accessibility; Automation is under Automation. If the app is already listed, toggle it off and on — the grant goes stale when the bundle is reinstalled. Then quit Cupertino and open it again: the servers are children of the running app, and a child started before the grant does not see it — which is what `accessibility: denied` beside a green Accessibility row in Cupertino's own Settings means." },
4525
+ composerLane: client.composerLane,
4526
+ ...axReach ? {
4527
+ composerAxRead: axReach.ok ? "granted" : "denied",
4528
+ ...axReach.windows ? { composerAxWindowsSeen: axReach.windows } : {}
4529
+ } : {},
4530
+ ...client.composerLane === "accessibility" ? { composerLaneNote: "This server is hosted by Cupertino, so a composer is driven through the app's own Accessibility driver. Automation to System Events is NOT required for it, and `automationSystemEvents` above can be denied without affecting a reply." } : {},
4531
+ ...composer.uiRead === "granted" && composer.systemEvents === "granted" || client.composerLane === "accessibility" ? {} : { composerNote: "Filling a Mail composer goes through System Events, which needs BOTH of the above: Automation to System Events (a different grant from Automation to Mail) and Accessibility. Until both are granted, apple_mail_reply_to_message and apple_mail_forward_message fail with COMPOSER_NOT_FOUND while every other tool works. Grant them to the Cupertino bundle that is RUNNING — not to your terminal and not to node: the app is the process macOS holds responsible, and the servers do inherit its identity. If Cupertino's own Settings shows a GREEN Accessibility row while `composerUiRead` above says denied, believe this line and not the row: one bundle identifier can hold several Accessibility entries at once, one per path and signature it has been granted at (an installed copy, a development build, each earlier reinstall), and the two checks can match different ones. The cure is to clear them all and grant once, from the bundle that is running: `tccutil reset Accessibility io.mgcrea.cupertino`, then Ask… in Cupertino's Settings — it reported resetting FOUR entries the first time this was hit. Accessibility is in System Settings > Privacy & Security > Accessibility; Automation is under Automation. If the app is already listed, toggle it off and on — the grant goes stale when the bundle is reinstalled. Then quit Cupertino and open it again: the servers are children of the running app, and a child started before the grant does not see it — which is what `accessibility: denied` beside a green Accessibility row in Cupertino's own Settings means." },
3807
4532
  fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
3808
4533
  ...located.readable ? {} : { howToGrant: [
3809
4534
  "System Settings > Privacy & Security > Full Disk Access",
@@ -4486,4 +5211,4 @@ const createServer = (opts) => {
4486
5211
  //#endregion
4487
5212
  export { WritesDisabledError as A, MessageNotFoundError as C, ProtocolError as D, PreconditionError as E, SchemaDriftError as O, MailNotRunningError as S, PlatformError as T, locateEnvelopeIndex as _, loadConfig as a, MAIL_SURFACE as b, decodeRef as c, assertStaticScript as d, createOsascriptRunner as f, inspectFile as g, MailboxMap as h, registerTools as i, BUILD_INFO as j, TccDeniedError as k, encodeRef as l, withBusyRetry as m, SERVER_VERSION as n, AppleMailClient as o, mapOsaError as p, createServer as r, REF_VERSION as s, SERVER_NAME as t, groupRefsByMailbox as u, AppleMailError as v, OsascriptTimeoutError as w, MailBusyError as x, IndexUnavailableError as y };
4488
5213
 
4489
- //# sourceMappingURL=server-DK4F_-So.js.map
5214
+ //# sourceMappingURL=server-D62cuBVz.js.map