@mgcrea/mcp-apple-mail 1.36.1 → 1.37.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,7 @@
1
- import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, buildBaseDiagnostics, confirmArg, createOsascriptRunner, createWatches, describeAggregation, detectEpoch, escapeLike, fileIdentity, fileTrigger, fingerprintSchema, groupByArg, inspectFile, interferenceNote, isoMs, limitArg, mapOsaError, normalizeFilter, occurrenceTimestamp, openAxChannel, openReadOnly, parseBool, parseBound, parseConfig, parseIntOpt, parseList, parseSenderArgs, project, promptArg, readPackageIdentity, registerEvents, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, sameFile, selectArg, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, wrap, writeConfinedFile } from "@mgcrea/mcp-apple-core";
2
- import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
1
+ import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, PreconditionError as PreconditionError$1, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, buildBaseDiagnostics, confirmArg, createOsascriptRunner, createWatches, describeAggregation, detectEpoch, escapeLike, fileIdentity, fileTrigger, fingerprintSchema, groupByArg, inspectFile, interferenceNote, isoMs, limitArg, mapOsaError, normalizeFilter, occurrenceTimestamp, openAxChannel, openReadOnly, parseBool, parseBound, parseConfig, parseIntOpt, parseList, parseSenderArgs, project, promptArg, readPackageIdentity, registerEvents, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, sameFile, selectArg, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, wrap, writeConfinedFile } from "@mgcrea/mcp-apple-core";
2
+ import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
- import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
5
5
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
6
6
  import { z } from "zod";
7
7
  import { McpServer } from "@modelcontextprotocol/server";
@@ -14,8 +14,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
14
14
  const BUILD_INFO = {
15
15
  name: pkg.name,
16
16
  version: pkg.version,
17
- gitCommit: "b82ad61",
18
- gitCommitDate: "2026-11-03T12:29:16+01:00"
17
+ gitCommit: "9f3ce2c",
18
+ gitCommitDate: "2026-11-06T12:19:38+01:00"
19
19
  };
20
20
  //#endregion
21
21
  //#region src/client/errors.ts
@@ -39,6 +39,15 @@ var MessageNotFoundError = class extends AppleAutomationError {
39
39
  super(`No message for ref "${ref}". It was probably moved or deleted since the search ran. Re-run the search to get a current ref.`);
40
40
  }
41
41
  };
42
+ /**
43
+ * An attachment whose bytes are in neither the message file nor the sidecar
44
+ * tree: Mail has not downloaded it. Its own class so that save_attachment can
45
+ * tell this case, which Mail can repair by fetching it, from the refusals
46
+ * (no such name, a path outside the confinement) that it must pass on.
47
+ */
48
+ var AttachmentNotStoredError = class extends PreconditionError {
49
+ name = "AttachmentNotStoredError";
50
+ };
42
51
  //#endregion
43
52
  //#region src/client/locate.ts
44
53
  const INDEX_SUFFIX = join("MailData", "Envelope Index");
@@ -1032,7 +1041,7 @@ const splitEmlx = (buf) => {
1032
1041
  };
1033
1042
  const readEmlx = (path, opts) => {
1034
1043
  const stat = statSync(path);
1035
- if (stat.size > MAX_FILE_BYTES) throw new PreconditionError(`Message file is ${stat.size} bytes, above the ${MAX_FILE_BYTES}-byte ceiling. Use apple_mail_list_attachments to see what is in it.`, {
1044
+ if (stat.size > MAX_FILE_BYTES) throw new PreconditionError$1(`Message file is ${stat.size} bytes, above the ${MAX_FILE_BYTES}-byte ceiling. Use apple_mail_list_attachments to see what is in it.`, {
1036
1045
  path,
1037
1046
  sizeBytes: stat.size
1038
1047
  });
@@ -1142,7 +1151,7 @@ const extractAttachment = (emlxPath, filename, rowid) => {
1142
1151
  walkParts(root, (p) => {
1143
1152
  if (!match && p.filename === filename) match = p;
1144
1153
  });
1145
- if (!match) throw new PreconditionError(`No attachment named "${filename}" in this message. Use apple_mail_list_attachments to see what is there.`);
1154
+ if (!match) throw new PreconditionError$1(`No attachment named "${filename}" in this message. Use apple_mail_list_attachments to see what is there.`);
1146
1155
  const inline = partBytes(match);
1147
1156
  if (hasContent(inline)) return {
1148
1157
  bytes: inline,
@@ -1153,7 +1162,7 @@ const extractAttachment = (emlxPath, filename, rowid) => {
1153
1162
  bytes: readFileSync(hit),
1154
1163
  from: "sidecar"
1155
1164
  };
1156
- throw new PreconditionError(`The attachment "${filename}" is not stored locally. Either it was never downloaded, or this account caches headers only — apple_mail_diagnostics reports the caching policy per account. Opening the message in Mail fetches it.`, {
1165
+ throw new AttachmentNotStoredError(`The attachment "${filename}" is not stored locally. Either it was never downloaded, or this account caches headers only — apple_mail_diagnostics reports the caching policy per account.`, {
1157
1166
  emlxPath,
1158
1167
  rowid
1159
1168
  });
@@ -3345,6 +3354,79 @@ const OPEN_COMPOSER = script(`
3345
3354
 
3346
3355
  return ok({ subject: subject });
3347
3356
  `, { allowLaunch: true });
3357
+ /**
3358
+ * Have Mail download one attachment and save it to `p.dest`.
3359
+ *
3360
+ * Mail's `save` on a `mail attachment` that is not downloaded fetches it from
3361
+ * the server first, and the fetch also lands in Mail's own store: measured
3362
+ * 2026-11-06 on a Gmail account caching messages without attachments, a message
3363
+ * whose attachments were not on disk listed them `retrievable: true`, with real
3364
+ * sizes, after Mail had saved them this way. There is no separate download verb
3365
+ * in Mail's dictionary; `downloaded` is read-only.
3366
+ *
3367
+ * `p.dest` is a path in a fresh staging folder the caller made and owns. Mail's
3368
+ * `save` overwrites and follows symlinks, so it must never be pointed at the
3369
+ * user's destination; the caller moves the bytes there through the confinement.
3370
+ *
3371
+ * A name that matches nothing, or matches twice, comes back as data rather than
3372
+ * an error so the caller can say what Mail listed.
3373
+ */
3374
+ const FETCH_ATTACHMENT = script(`
3375
+ var acct = findAccount(M, p.accountUuid);
3376
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3377
+ var mb = resolveMailbox(acct, p.mailbox);
3378
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3379
+
3380
+ var m;
3381
+ try {
3382
+ m = mb.messages.byId(p.id);
3383
+ m.id();
3384
+ } catch (e) {
3385
+ return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
3386
+ }
3387
+
3388
+ var wanted = String(p.filename).normalize("NFC");
3389
+ // Not prop(): a failed read here is not a message without attachments, and
3390
+ // answering "none" would tell the caller the name does not exist.
3391
+ var atts;
3392
+ try {
3393
+ atts = m.mailAttachments();
3394
+ } catch (e) {
3395
+ return ok({
3396
+ saved: false,
3397
+ reason: "save-failed",
3398
+ downloaded: null,
3399
+ error: "Mail could not list the message's attachments: " +
3400
+ String(e && e.message ? e.message : e)
3401
+ });
3402
+ }
3403
+ var names = [];
3404
+ var hits = [];
3405
+ for (var i = 0; i < atts.length; i++) {
3406
+ var a = atts[i];
3407
+ var name = prop(function () { return a.name(); }, null);
3408
+ if (name === null) continue;
3409
+ names.push(String(name));
3410
+ if (String(name).normalize("NFC") === wanted) hits.push(a);
3411
+ }
3412
+ if (hits.length === 0) return ok({ saved: false, reason: "none", names: names });
3413
+ if (hits.length > 1) return ok({ saved: false, reason: "ambiguous", count: hits.length });
3414
+
3415
+ var hit = hits[0];
3416
+ var downloaded = prop(function () { return hit.downloaded(); }, null);
3417
+ var fileSize = prop(function () { return hit.fileSize(); }, null);
3418
+ try {
3419
+ M.save(hit, { in: Path(p.dest) });
3420
+ } catch (e) {
3421
+ return ok({
3422
+ saved: false,
3423
+ reason: "save-failed",
3424
+ downloaded: downloaded,
3425
+ error: String(e && e.message ? e.message : e)
3426
+ });
3427
+ }
3428
+ return ok({ saved: true, downloaded: downloaded, fileSize: fileSize });
3429
+ `);
3348
3430
  //#endregion
3349
3431
  //#region src/client/compose.ts
3350
3432
  /**
@@ -3457,10 +3539,11 @@ const sameHead = (a, b) => {
3457
3539
  const n = Math.min(x.length, y.length, HEAD_CHARS$1);
3458
3540
  return x.slice(0, n) === y.slice(0, n);
3459
3541
  };
3460
- /** A composer taken as the new one, with the own text it was listed with. */
3542
+ /** A composer taken as the new one, with the own text and the title it was listed with. */
3461
3543
  const taken = (c) => ({
3462
3544
  handle: c.composer,
3463
- text: c.text ?? null
3545
+ text: c.text ?? null,
3546
+ subject: c.subject
3464
3547
  });
3465
3548
  /**
3466
3549
  * Wait for a composer that was not there before, and return its handle.
@@ -3473,7 +3556,9 @@ const taken = (c) => ({
3473
3556
  * is the one this call opened, whatever it is titled.
3474
3557
  *
3475
3558
  * A person can open a window by hand during the poll, and an empty composer
3476
- * gives nothing to tell theirs from ours. So the candidates are every fresh
3559
+ * gives nothing to tell theirs from ours. Without a subject that holds for any
3560
+ * new composer they open: theirs, listed before ours, is taken, and our body
3561
+ * goes above its signature. Nothing of theirs is replaced, since it is new. So the candidates are every fresh
3477
3562
  * handle, narrowed to those titled `subject` when it is given (the subject
3478
3563
  * `OPEN_COMPOSER` returned). Exactly one candidate is returned as `{ handle }`;
3479
3564
  * more than one is `{ ambiguous }` and nothing is picked, because filling the
@@ -3520,11 +3605,19 @@ const taken = (c) => ({
3520
3605
  const awaitNewComposer = async (lane, before, timeoutMs, subject) => {
3521
3606
  const known = new Set(before.map((c) => typeof c === "string" ? c : c.composer));
3522
3607
  const counted = before.every((c) => typeof c !== "string");
3523
- const sameSubject = before.filter((c) => typeof c !== "string" && c.subject === subject);
3524
- const had = sameSubject.length;
3525
- const held = sameSubject.map((c) => c.text);
3526
- const unread = held.some((t) => typeof t !== "string");
3527
- const isOld = (text) => typeof text !== "string" || unread || held.some((t) => typeof t === "string" && sameHead(t, text));
3608
+ const under = (title) => {
3609
+ const same = before.filter((c) => typeof c !== "string" && c.subject === title);
3610
+ const held = same.map((c) => c.text);
3611
+ const unread = held.some((t) => typeof t !== "string");
3612
+ const isOld = (text) => typeof text !== "string" || unread || held.some((t) => typeof t === "string" && sameHead(t, text));
3613
+ return {
3614
+ had: same.length,
3615
+ unread,
3616
+ isOld
3617
+ };
3618
+ };
3619
+ const bySubject = under(subject);
3620
+ const { had, unread, isOld } = bySubject;
3528
3621
  const deadline = Date.now() + timeoutMs;
3529
3622
  let waitedOn;
3530
3623
  for (;;) {
@@ -3533,10 +3626,12 @@ const awaitNewComposer = async (lane, before, timeoutMs, subject) => {
3533
3626
  const fresh = listed.filter((c) => !known.has(c.composer));
3534
3627
  const candidates = subject === void 0 ? fresh : fresh.filter((c) => c.subject === subject);
3535
3628
  const only = candidates.length === 1 ? candidates[0] : void 0;
3536
- if (only && had === 0) return taken(only);
3537
- if (only && !isOld(only.text)) return taken(only);
3629
+ if (only && subject === void 0 && !counted) return { ambiguous: [only.composer] };
3630
+ const lone = only && subject === void 0 ? under(only.subject) : bySubject;
3631
+ if (only && lone.had === 0) return taken(only);
3632
+ if (only && !lone.isOld(only.text)) return taken(only);
3538
3633
  if (only) {
3539
- if (!(!unread && typeof only.text !== "string") || Date.now() >= deadline) return { ambiguous: [only.composer] };
3634
+ if (!(!lone.unread && typeof only.text !== "string") || Date.now() >= deadline) return { ambiguous: [only.composer] };
3540
3635
  waitedOn = [only.composer];
3541
3636
  }
3542
3637
  if (candidates.length > 1) {
@@ -3566,19 +3661,31 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3566
3661
  const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
3567
3662
  const watch = lane.watch();
3568
3663
  const startedAt = Date.now();
3664
+ if (!params.subject?.trim() && params.mode === "new") {
3665
+ if (params.sendNow || !params.body && !params.attachments?.length) return {
3666
+ ok: false,
3667
+ subject: params.subject ?? "",
3668
+ bodyVerified: null,
3669
+ verifiedChars: 0,
3670
+ sent: false,
3671
+ note: (params.sendNow ? "A new message with no subject cannot be sent from here: Mail asks before sending one, and its buttons are named in the Mac's language." : "A new message with no subject and nothing to fill cannot be saved from here: the only way to save it is a keystroke aimed by its title, and it has none.") + " Nothing was opened. Give it a subject, or leave out sendNow and give it a body."
3672
+ };
3673
+ }
3569
3674
  const reach = await lane.reach();
3570
3675
  if (!reach.ok) throw new Error(`${MailAxLane.grantMessage(params.mode)} ${MailAxLane.nothingWritten}`);
3571
3676
  const { attachments: files = [], ...toOpen } = params;
3572
3677
  const before = await lane.composers();
3573
3678
  const subject = (await runner.run(OPEN_COMPOSER, toOpen)).subject;
3574
- const found = await awaitNewComposer(lane, before, composerTimeoutMs, subject);
3679
+ const keyed = subject.trim() !== "";
3680
+ const titled = keyed ? `for "${subject}"` : "with no subject";
3681
+ const found = await awaitNewComposer(lane, before, composerTimeoutMs, keyed ? subject : void 0);
3575
3682
  if (found && "ambiguous" in found) return {
3576
3683
  ok: false,
3577
3684
  subject,
3578
3685
  bodyVerified: null,
3579
3686
  verifiedChars: 0,
3580
3687
  sent: false,
3581
- note: `Mail was asked to open a ${params.mode} window for "${subject}", and ` + (found.ambiguous.length === 1 ? `the one new composer under that title (${found.ambiguous[0]}) could not be told from the draft already open under it: its text reads as that draft's, or could not be read. Nothing was filled, pressed or sent, and every window is left open in Mail. Close the extra one, finish the other by hand, then retry.` : `${found.ambiguous.length} new composers titled that appeared (${found.ambiguous.join(", ")}), so this path cannot tell which one it opened. Nothing was filled, pressed or sent, and all of them are left open in Mail. Close the extra one, finish the other by hand, then retry.`) + interferenceNote(await watch.check())
3688
+ note: `Mail was asked to open a ${params.mode} window ${titled}, and ` + (found.ambiguous.length === 1 ? `the one new composer under that title (${found.ambiguous[0]}) could not be told from the draft already open under it: its text reads as that draft's, or could not be read. Nothing was filled, pressed or sent, and every window is left open in Mail. Close the extra one, finish the other by hand, then retry.` : `${found.ambiguous.length} new composers${keyed ? " titled that" : ""} appeared (${found.ambiguous.join(", ")}), so this path cannot tell which one it opened. Nothing was filled, pressed or sent, and all of them are left open in Mail. Close the extra one, finish the other by hand, then retry.`) + interferenceNote(await watch.check())
3582
3689
  };
3583
3690
  const handle = found?.handle ?? null;
3584
3691
  const expectHead = found?.text ? found.text : null;
@@ -3588,7 +3695,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3588
3695
  bodyVerified: null,
3589
3696
  verifiedChars: 0,
3590
3697
  sent: false,
3591
- note: `Mail was asked to open a ${params.mode} window for "${subject}" and no such window was readable within ${composerTimeoutMs / 1e3}s, ` + ((reach.windows ?? []).length > 0 ? `although Mail's other windows read fine — so this is not a permission. ` : "and no Mail window could be read at all, on any desktop. Run apple_mail_diagnostics before retrying. ") + `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())
3698
+ note: `Mail was asked to open a ${params.mode} window ${titled} and no such window was readable within ${composerTimeoutMs / 1e3}s, ` + ((reach.windows ?? []).length > 0 ? `although Mail's other windows read fine — so this is not a permission. ` : "and no Mail window could be read at all, on any desktop. Run apple_mail_diagnostics before retrying. ") + `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())
3592
3699
  };
3593
3700
  /**
3594
3701
  * The composer is no longer on screen, and nothing here closed it.
@@ -3600,16 +3707,21 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3600
3707
  * on double-paste grounds when the real hazard was sending the mail twice.
3601
3708
  */
3602
3709
  const vanished = async (knownBody = null) => {
3603
- const verdict = await sentVerdict(runner, params.accountUuid, subject, startedAt);
3710
+ const verdict = keyed ? await sentVerdict(runner, params.accountUuid, subject, startedAt) : {
3711
+ sent: null,
3712
+ sentence: "Nothing here sends a message with no subject, so it was closed or sent by hand, and Sent cannot tell which from here: look in Drafts and in Sent before retrying."
3713
+ };
3604
3714
  return {
3605
3715
  ok: false,
3606
3716
  subject,
3607
3717
  bodyVerified: knownBody?.verified ?? null,
3608
3718
  verifiedChars: knownBody?.chars ?? 0,
3609
3719
  sent: verdict.sent,
3610
- note: `The ${params.mode} window for "${subject}" is GONE. Nothing here closed it — this path never discards a composer — so someone using the Mac sent it or closed it while this was running. ${verdict.sentence}` + interferenceNote(await watch.check())
3720
+ note: `The ${params.mode} window ${titled} is GONE. Nothing here closed it — this path never discards a composer — so someone using the Mac sent it or closed it while this was running. ${verdict.sentence}` + interferenceNote(await watch.check())
3611
3721
  };
3612
3722
  };
3723
+ const listedTitle = found && "handle" in found ? found.subject : void 0;
3724
+ const gone = () => keyed ? lane.composerGone(subject, 0) : lane.composers().then((listed) => !listed.some((c) => c.composer === handle || listedTitle !== void 0 && c.subject === listedTitle), () => false);
3613
3725
  const body = params.body ?? "";
3614
3726
  const filling = body !== "" || files.length > 0;
3615
3727
  let bodyVerified = null;
@@ -3628,7 +3740,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3628
3740
  save: !params.sendNow
3629
3741
  });
3630
3742
  } catch (error) {
3631
- if (await lane.composerGone(subject, 0)) return vanished();
3743
+ if (await gone()) return vanished();
3632
3744
  return {
3633
3745
  ok: false,
3634
3746
  degraded: true,
@@ -3636,11 +3748,11 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3636
3748
  bodyVerified: null,
3637
3749
  verifiedChars: 0,
3638
3750
  sent: false,
3639
- note: `The ${params.mode} window for "${subject}" was opened and addressed, but filling it failed: ${error instanceof Error ? error.message : String(error)} Its window is still open in Mail: finish it there, or close it without saving and retry.` + interferenceNote(await watch.check())
3751
+ note: `The ${params.mode} window ${titled} was opened and addressed, but filling it failed: ${error instanceof Error ? error.message : String(error)} Its window is still open in Mail: finish it there, or close it without saving and retry.` + interferenceNote(await watch.check())
3640
3752
  };
3641
3753
  }
3642
3754
  if (edit["replaced"] !== true) {
3643
- if (await lane.composerGone(subject, 0)) return vanished();
3755
+ if (await gone()) return vanished();
3644
3756
  return {
3645
3757
  ok: false,
3646
3758
  degraded: true,
@@ -3648,7 +3760,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3648
3760
  bodyVerified: null,
3649
3761
  verifiedChars: 0,
3650
3762
  sent: false,
3651
- note: `${typeof edit["reason"] === "string" ? edit["reason"] : "The edit was refused."}${typeof edit["hint"] === "string" ? ` ${edit["hint"]}` : ""} The ${params.mode} window for "${subject}" is still open in Mail.` + interferenceNote(await watch.check())
3763
+ note: `${typeof edit["reason"] === "string" ? edit["reason"] : "The edit was refused."}${typeof edit["hint"] === "string" ? ` ${edit["hint"]}` : ""} The ${params.mode} window ${titled} is still open in Mail.` + interferenceNote(await watch.check())
3652
3764
  };
3653
3765
  }
3654
3766
  const text = typeof edit["text"] === "string" ? edit["text"] : "";
@@ -3662,7 +3774,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3662
3774
  bodyVerified: false,
3663
3775
  verifiedChars,
3664
3776
  sent: false,
3665
- note: `The ${params.mode} window for "${subject}" was opened and correctly addressed, but reading the composer back does not show the text that was sent. It MUST NOT be described to the user as ready. It was left open rather than discarded, and may already be saved as it stands: look at it in Mail, then fix or close it.` + interferenceNote(await watch.check())
3777
+ note: `The ${params.mode} window ${titled} was opened and correctly addressed, but reading the composer back does not show the text that was sent. It MUST NOT be described to the user as ready. It was left open rather than discarded, and may already be saved as it stands: look at it in Mail, then fix or close it.` + interferenceNote(await watch.check())
3666
3778
  };
3667
3779
  }
3668
3780
  if (!params.sendNow && edit["saved"] === false) return {
@@ -3673,7 +3785,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3673
3785
  verifiedChars,
3674
3786
  sent: false,
3675
3787
  ...files.length > 0 ? { attachments: files.length } : {},
3676
- note: `The ${params.mode} window for "${subject}" was filled` + (bodyVerified ? " and its body verified" : "") + `, but it was NOT saved. Its window is still open in Mail: save it there.` + interferenceNote(await watch.check())
3788
+ note: `The ${params.mode} window ${titled} was filled` + (bodyVerified ? " and its body verified" : "") + `, but it was NOT saved. Its window is still open in Mail: save it there.` + interferenceNote(await watch.check())
3677
3789
  };
3678
3790
  }
3679
3791
  const known = () => bodyVerified === true ? {
@@ -3710,7 +3822,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3710
3822
  verifiedChars,
3711
3823
  sent: false,
3712
3824
  ...files.length > 0 ? { attachments: files.length } : {},
3713
- note: `The ${params.mode} for "${subject}" was ${filling ? "filled" : "opened"}` + (bodyVerified ? " and its body verified" : "") + `, but it was NOT ${action}: ` + (sharing === null ? `Mail's composers could not be listed, so it is not known that the title picks out one.` : moved ? "its handle was re-bound: Mail rebuilt its window's tabs since the draft was filled, so the handle may now name another draft under this title, which the shortcut could reach." : `${sharing.length} composers in Mail carry this title, and the shortcut is aimed by title, so it could reach the wrong one.`) + ` The draft is open in Mail for review: ${params.sendNow ? "send" : "save"} it from there.` + interferenceNote(await watch.check())
3825
+ note: `The ${params.mode} ${titled} was ${filling ? "filled" : "opened"}` + (bodyVerified ? " and its body verified" : "") + `, but it was NOT ${action}: ` + (sharing === null ? `Mail's composers could not be listed, so it is not known that the title picks out one.` : moved ? "its handle was re-bound: Mail rebuilt its window's tabs since the draft was filled, so the handle may now name another draft under this title, which the shortcut could reach." : `${sharing.length} composers in Mail carry this title, and the shortcut is aimed by title, so it could reach the wrong one.`) + ` The draft is open in Mail for review: ${params.sendNow ? "send" : "save"} it from there.` + interferenceNote(await watch.check())
3714
3826
  };
3715
3827
  const ref = await lane.findComposer(subject, composerTimeoutMs);
3716
3828
  if (!ref) {
@@ -3722,7 +3834,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3722
3834
  bodyVerified,
3723
3835
  verifiedChars,
3724
3836
  sent: false,
3725
- note: `The ${params.mode} for "${subject}" was composed, but its window could not be read to press anything, so it was NOT ${action}. It is open in Mail for review.` + interferenceNote(await watch.check())
3837
+ note: `The ${params.mode} ${titled} was composed, but its window could not be read to press anything, so it was NOT ${action}. It is open in Mail for review.` + interferenceNote(await watch.check())
3726
3838
  };
3727
3839
  }
3728
3840
  let rebound = false;
@@ -3742,7 +3854,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3742
3854
  verifiedChars,
3743
3855
  sent: false,
3744
3856
  ...files.length > 0 ? { attachments: files.length } : {},
3745
- note: `The ${params.mode} for "${subject}" was ${filling ? "filled" : "opened"}` + (bodyVerified ? " and its body verified" : "") + `, but it was NOT ${action}: ` + (rebound ? "right before the shortcut its handle read as re-bound: Mail rebuilt its window's tabs since the draft was filled, so the handle may now name another draft under this title, which the shortcut could have reached." : "its window holds several drafts as tabs, and right before the shortcut this draft's tab was not the one shown (or could not be confirmed to be), so the shortcut could have reached another draft.") + ` Nothing was pressed. The draft is open in Mail for review: ${params.sendNow ? "send" : "save"} it from there.` + interferenceNote(await watch.check())
3857
+ note: `The ${params.mode} ${titled} was ${filling ? "filled" : "opened"}` + (bodyVerified ? " and its body verified" : "") + `, but it was NOT ${action}: ` + (rebound ? "right before the shortcut its handle read as re-bound: Mail rebuilt its window's tabs since the draft was filled, so the handle may now name another draft under this title, which the shortcut could have reached." : "its window holds several drafts as tabs, and right before the shortcut this draft's tab was not the one shown (or could not be confirmed to be), so the shortcut could have reached another draft.") + ` Nothing was pressed. The draft is open in Mail for review: ${params.sendNow ? "send" : "save"} it from there.` + interferenceNote(await watch.check())
3746
3858
  };
3747
3859
  }
3748
3860
  if (finished === "refused") return {
@@ -3751,7 +3863,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3751
3863
  bodyVerified,
3752
3864
  verifiedChars,
3753
3865
  sent: false,
3754
- note: `The ${params.mode} for "${subject}" was composed, but Mail could not be brought to the front, so nothing was pressed and it was not ${action}. Its window is still open in Mail. Someone is probably using the Mac; retry once it is free, or finish it in Mail.` + interferenceNote(await watch.check())
3866
+ note: `The ${params.mode} ${titled} was composed, but Mail could not be brought to the front, so nothing was pressed and it was not ${action}. Its window is still open in Mail. Someone is probably using the Mac; retry once it is free, or finish it in Mail.` + interferenceNote(await watch.check())
3755
3867
  };
3756
3868
  const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;
3757
3869
  if (!params.sendNow) await lane.release();
@@ -4289,7 +4401,7 @@ var MailboxMap = class {
4289
4401
  accounts = await this.accounts(true);
4290
4402
  found = find(accounts);
4291
4403
  }
4292
- if (!found) throw new PreconditionError(`No account "${needle}". Known accounts: ${accounts.map((a) => a.name).join(", ") || "(none visible)"}.` + (this.#allowlist.length ? " An allowlist is active (APPLE_MAIL_ACCOUNTS)." : ""));
4404
+ if (!found) throw new PreconditionError$1(`No account "${needle}". Known accounts: ${accounts.map((a) => a.name).join(", ") || "(none visible)"}.` + (this.#allowlist.length ? " An allowlist is active (APPLE_MAIL_ACCOUNTS)." : ""));
4293
4405
  return found;
4294
4406
  }
4295
4407
  /**
@@ -4309,7 +4421,7 @@ var MailboxMap = class {
4309
4421
  const hit = account.mailboxes.find((m) => m.toLowerCase() === c.toLowerCase());
4310
4422
  if (hit) return hit;
4311
4423
  }
4312
- throw new PreconditionError(`No mailbox "${wanted}" in account "${account.name}". Available: ${account.mailboxes.join(", ")}.`);
4424
+ throw new PreconditionError$1(`No mailbox "${wanted}" in account "${account.name}". Available: ${account.mailboxes.join(", ")}.`);
4313
4425
  }
4314
4426
  /**
4315
4427
  * Map an Envelope Index `mailboxes.url` onto a scriptable account + mailbox.
@@ -5048,12 +5160,12 @@ const UUID_RE = /^[0-9A-Fa-f-]{8,64}$/;
5048
5160
  const encodeRef = (ref) => `m1:${ref.accountUuid}/${encodeURIComponent(ref.mailbox)}#${ref.id}`;
5049
5161
  const decodeRef = (raw) => {
5050
5162
  const m = /^([a-z0-9]+):([^/]+)\/(.*)#(\d+)$/.exec(raw);
5051
- if (!m) throw new PreconditionError(`Malformed message ref "${raw}". Refs come from the search and list tools — construct them from those results rather than by hand.`, { expected: `m1:<accountUuid>/<mailbox>#<id>` });
5163
+ if (!m) throw new PreconditionError$1(`Malformed message ref "${raw}". Refs come from the search and list tools — construct them from those results rather than by hand.`, { expected: `m1:<accountUuid>/<mailbox>#<id>` });
5052
5164
  const [, version, accountUuid, mailboxRaw, idRaw] = m;
5053
- if (version !== "m1") throw new PreconditionError(`Unsupported message ref version "${version}". This server issues "m1" refs; re-run the search to get current ones.`);
5054
- if (!accountUuid || !UUID_RE.test(accountUuid)) throw new PreconditionError(`Message ref "${raw}" does not carry a valid account id.`);
5165
+ if (version !== "m1") throw new PreconditionError$1(`Unsupported message ref version "${version}". This server issues "m1" refs; re-run the search to get current ones.`);
5166
+ if (!accountUuid || !UUID_RE.test(accountUuid)) throw new PreconditionError$1(`Message ref "${raw}" does not carry a valid account id.`);
5055
5167
  const id = Number(idRaw);
5056
- if (!Number.isSafeInteger(id) || id <= 0) throw new PreconditionError(`Message ref "${raw}" does not carry a valid message id.`);
5168
+ if (!Number.isSafeInteger(id) || id <= 0) throw new PreconditionError$1(`Message ref "${raw}" does not carry a valid message id.`);
5057
5169
  return {
5058
5170
  accountUuid,
5059
5171
  mailbox: decodeURIComponent(mailboxRaw ?? ""),
@@ -5187,6 +5299,22 @@ const reviseDraftInPlace = async (lane, facts, opts) => {
5187
5299
  };
5188
5300
  //#endregion
5189
5301
  //#region src/client/mail.ts
5302
+ /**
5303
+ * How long the process may take to have Mail download one attachment. A large
5304
+ * Gmail PDF can outlast the ordinary 30 s budget. Mail's own reply deadline is
5305
+ * the default Apple Event timeout, 120 s from when `save` is sent; the margin
5306
+ * lets the script's catch around `save` answer first, with Mail's reason,
5307
+ * rather than the process being killed with none.
5308
+ */
5309
+ const FETCH_TIMEOUT_MS = 135e3;
5310
+ const isFetchAnswer = (value) => {
5311
+ if (typeof value !== "object" || value === null || !("saved" in value)) return false;
5312
+ const a = value;
5313
+ if (a.saved === true) return true;
5314
+ if (a.reason === "none") return Array.isArray(a.names);
5315
+ if (a.reason === "ambiguous") return typeof a.count === "number";
5316
+ return a.reason === "save-failed" && typeof a.error === "string";
5317
+ };
5190
5318
  /** The FDA sentence, kept verbatim for the case where FDA really is the problem. */
5191
5319
  /**
5192
5320
  * A display name, quoted when it holds a comma, and only then.
@@ -5595,7 +5723,7 @@ var AppleMailClient = class {
5595
5723
  if (rowids.length === 0) {
5596
5724
  const known = [...lookup.values()].filter((e) => !account || e.accountUuid === account.id).map((e) => e.mailbox);
5597
5725
  const unique = [...new Set(known)].toSorted();
5598
- 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."));
5726
+ throw new PreconditionError$1(`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."));
5599
5727
  }
5600
5728
  return rowids;
5601
5729
  }
@@ -6022,27 +6150,112 @@ var AppleMailClient = class {
6022
6150
  * The destination is resolved and then checked to be inside
6023
6151
  * `APPLE_MAIL_ATTACHMENT_DIR`, so a filename of `../../.ssh/authorized_keys`
6024
6152
  * lands nowhere. Existing files are never overwritten.
6153
+ *
6154
+ * When the bytes are not on disk, which on a Gmail account caching messages
6155
+ * without their attachments is most older mail, Mail is asked to download
6156
+ * the attachment (see `#fetchFromMail`).
6025
6157
  */
6026
6158
  async saveAttachment(ref, filename, opts = {}) {
6027
6159
  const decoded = decodeRef(ref);
6028
6160
  const located = await this.#lookupMessageFile(decoded);
6029
- 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) ?? [] });
6161
+ if (!located.found) throw new PreconditionError$1(`The message file was not found, so its attachments are not reachable. ${located.explain}`, { probed: located.lookup?.probed.slice(0, 3) ?? [] });
6030
6162
  let from = "inline";
6163
+ try {
6164
+ return {
6165
+ ...writeConfinedFile({
6166
+ root: this.config.attachmentDir,
6167
+ name: filename,
6168
+ bytes: () => {
6169
+ const extracted = extractAttachment(located.path, filename, decoded.id);
6170
+ from = extracted.from;
6171
+ return extracted.bytes;
6172
+ },
6173
+ overwrite: opts.overwrite ?? false,
6174
+ settingName: "APPLE_MAIL_ATTACHMENT_DIR"
6175
+ }),
6176
+ from
6177
+ };
6178
+ } catch (error) {
6179
+ if (!(error instanceof AttachmentNotStoredError)) throw error;
6180
+ }
6181
+ const dest = resolve(this.config.attachmentDir, basename(filename));
6182
+ if (!opts.overwrite && existsSync(dest)) throw new PreconditionError$1(`${dest} already exists; refusing to overwrite it.`);
6183
+ const bytes = await this.#fetchFromMail(decoded, filename);
6031
6184
  return {
6032
6185
  ...writeConfinedFile({
6033
6186
  root: this.config.attachmentDir,
6034
6187
  name: filename,
6035
- bytes: () => {
6036
- const extracted = extractAttachment(located.path, filename, decoded.id);
6037
- from = extracted.from;
6038
- return extracted.bytes;
6039
- },
6188
+ bytes,
6040
6189
  overwrite: opts.overwrite ?? false,
6041
6190
  settingName: "APPLE_MAIL_ATTACHMENT_DIR"
6042
6191
  }),
6043
- from
6192
+ from: "mail"
6044
6193
  };
6045
6194
  }
6195
+ /**
6196
+ * Have Mail download an attachment it has not fetched, and return its bytes.
6197
+ *
6198
+ * Mail's `save` fetches the attachment from the server, and keeps it in its
6199
+ * own store as well, so the next save finds the sidecar on disk.
6200
+ *
6201
+ * Mail writes into a staging folder of ours inside the attachment directory,
6202
+ * never the destination itself: its `save` overwrites and follows symlinks,
6203
+ * which is exactly what `writeConfinedFile` refuses. The staging file gets a
6204
+ * fixed name, keeping only a sanitised extension, so no part of a caller's
6205
+ * filename becomes a path Mail writes to. The folder goes whatever happens.
6206
+ *
6207
+ * Not retried on a busy answer: -1712 is also what a timed-out Apple Event
6208
+ * returns, and retrying a slow download would only double the wait.
6209
+ */
6210
+ async #fetchFromMail(ref, filename) {
6211
+ mkdirSync(this.config.attachmentDir, { recursive: true });
6212
+ const staging = mkdtempSync(join(this.config.attachmentDir, ".cupertino-download-"));
6213
+ try {
6214
+ const ext = extname(basename(filename)).replace(/[^A-Za-z0-9.]/g, "");
6215
+ const target = join(staging, `attachment${ext}`);
6216
+ const notStored = `The attachment "${filename}" is not stored locally, and`;
6217
+ let answer;
6218
+ try {
6219
+ answer = await this.runner.run(FETCH_ATTACHMENT, {
6220
+ accountUuid: ref.accountUuid,
6221
+ mailbox: ref.mailbox,
6222
+ id: ref.id,
6223
+ filename,
6224
+ dest: target
6225
+ }, { timeoutMs: Math.max(FETCH_TIMEOUT_MS, this.config.osascriptTimeoutMs) });
6226
+ } catch (error) {
6227
+ if (error instanceof MailNotRunningError) throw new PreconditionError$1(`${notStored} Mail is not running to download it. Open Mail and try again.`);
6228
+ if (error instanceof OsascriptTimeoutError) throw new PreconditionError$1(`${notStored} Mail did not finish downloading it in time. It may still be downloading: try again in a minute, or open the message in Mail.`);
6229
+ if (error instanceof ProtocolError) throw new ProtocolError(`${notStored} Mail could not download it: ${error.message}`, { ...error.details });
6230
+ throw error;
6231
+ }
6232
+ if (!isFetchAnswer(answer)) throw new ProtocolError(`${notStored} Mail's answer to the download was not one save_attachment can read: ${String(JSON.stringify(answer ?? null)).slice(0, 200)}.`);
6233
+ if (!answer.saved) {
6234
+ if (answer.reason === "ambiguous") throw new PreconditionError$1(`${notStored} this message has ${answer.count} attachments named "${filename}", so there is no telling which one to have Mail download. Save it from Mail.`);
6235
+ if (answer.reason === "none") {
6236
+ const listed = answer.names.length > 0 ? answer.names.join(", ") : "none";
6237
+ throw new PreconditionError$1(`${notStored} Mail lists no attachment by that name on this message, so it cannot download it. Mail lists: ${listed}.`);
6238
+ }
6239
+ throw new PreconditionError$1(`${notStored} Mail could not download "${filename}": ${answer.error}. Check that Mail is online and the account is enabled.`);
6240
+ }
6241
+ const entries = readdirSync(staging);
6242
+ const candidate = existsSync(target) ? target : entries.length === 1 ? join(staging, entries[0]) : null;
6243
+ const written = candidate && lstatSync(candidate).isFile() ? candidate : null;
6244
+ if (!written) throw new PreconditionError$1(`${notStored} Mail reported saving "${filename}" but wrote no file. Opening the message in Mail downloads it.`);
6245
+ const bytes = readFileSync(written);
6246
+ if (bytes.length === 0) throw new PreconditionError$1(`${notStored} Mail saved "${filename}" as an empty file, so it did not download it. Check that Mail is online and the account is enabled.`);
6247
+ return bytes;
6248
+ } finally {
6249
+ try {
6250
+ rmSync(staging, {
6251
+ recursive: true,
6252
+ force: true
6253
+ });
6254
+ } catch {
6255
+ this.#logger?.warn?.(`could not remove the download staging folder ${staging}`);
6256
+ }
6257
+ }
6258
+ }
6046
6259
  /** Set flags across refs, one Apple Event per distinct mailbox. */
6047
6260
  async setFlags(refs, flags) {
6048
6261
  const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));
@@ -6162,8 +6375,8 @@ var AppleMailClient = class {
6162
6375
  */
6163
6376
  async createMailbox(name, account) {
6164
6377
  const trimmed = name.trim();
6165
- if (!trimmed) throw new PreconditionError("A mailbox name cannot be empty or only whitespace.");
6166
- if (trimmed.split("/").some((segment) => segment.trim() === "")) throw new PreconditionError(`"${name}" has an empty path segment. "/" separates levels, so a name may not start or end with it, e.g. "Projects/Cupertino".`);
6378
+ if (!trimmed) throw new PreconditionError$1("A mailbox name cannot be empty or only whitespace.");
6379
+ if (trimmed.split("/").some((segment) => segment.trim() === "")) throw new PreconditionError$1(`"${name}" has an empty path segment. "/" separates levels, so a name may not start or end with it, e.g. "Projects/Cupertino".`);
6167
6380
  const resolved = account ? await this.mailboxes.resolveAccount(account) : null;
6168
6381
  const result = await withBusyRetry(() => this.runner.run(CREATE_MAILBOX, {
6169
6382
  name: trimmed,
@@ -6205,13 +6418,13 @@ var AppleMailClient = class {
6205
6418
  * which is the one outcome nothing downstream could distinguish from success.
6206
6419
  */
6207
6420
  async updateDraft(target, opts) {
6208
- if (target.ref !== void 0 && target.composer !== void 0) throw new PreconditionError("Pass either ref or composer, not both: a ref finds the draft's window by its content, and a composer handle already names the window.");
6209
- if (opts.body !== void 0 && opts.edits !== void 0) throw new PreconditionError("Pass either body or edits, not both: a body replaces the whole text and edits change only what they match.");
6210
- if (opts.body === void 0 && !opts.edits?.length && !opts.attachments?.length) throw new PreconditionError("Nothing to change: pass a body, edits, attachments, or a combination. A new subject alone needs a body.");
6211
- if (opts.body !== void 0 && !opts.body.trim()) throw new PreconditionError("A replacement body cannot be empty. Blanking a draft and reporting success is indistinguishable from having written it, so it is refused here rather than done. Delete the draft with apple_mail_delete_messages if that is what you meant.");
6421
+ if (target.ref !== void 0 && target.composer !== void 0) throw new PreconditionError$1("Pass either ref or composer, not both: a ref finds the draft's window by its content, and a composer handle already names the window.");
6422
+ if (opts.body !== void 0 && opts.edits !== void 0) throw new PreconditionError$1("Pass either body or edits, not both: a body replaces the whole text and edits change only what they match.");
6423
+ if (opts.body === void 0 && !opts.edits?.length && !opts.attachments?.length) throw new PreconditionError$1("Nothing to change: pass a body, edits, attachments, or a combination. A new subject alone needs a body.");
6424
+ if (opts.body !== void 0 && !opts.body.trim()) throw new PreconditionError$1("A replacement body cannot be empty. Blanking a draft and reporting success is indistinguishable from having written it, so it is refused here rather than done. Delete the draft with apple_mail_delete_messages if that is what you meant.");
6212
6425
  const attachments = this.#resolveAttachments(opts.attachments, false);
6213
6426
  if (target.ref === void 0) {
6214
- if (opts.subject !== void 0) throw new PreconditionError("A new subject can only be set by rebuilding a saved draft, which needs its ref. Editing a composer by handle, or the one open, leaves the subject as it is.");
6427
+ if (opts.subject !== void 0) throw new PreconditionError$1("A new subject can only be set by rebuilding a saved draft, which needs its ref. Editing a composer by handle, or the one open, leaves the subject as it is.");
6215
6428
  if (!this.#ax) return nativeOnlyRefusal(target.composer !== void 0 ? "Editing a composer by handle" : "Editing the open composer");
6216
6429
  return released(this.#ax, await this.#editComposerDirectly(this.#ax, target.composer, opts, attachments));
6217
6430
  }
@@ -6443,7 +6656,8 @@ var AppleMailClient = class {
6443
6656
  async sendMessage(opts) {
6444
6657
  const attachments = this.#resolveAttachments(opts.attachments, opts.sendNow);
6445
6658
  const account = opts.account ? await this.mailboxes.resolveAccount(opts.account) : null;
6446
- if (this.#ax && opts.subject.trim()) return composeNatively(this.#ax, this.runner, {
6659
+ const native = opts.subject.trim() !== "" || !opts.sendNow && (opts.body !== "" || attachments.length > 0);
6660
+ if (this.#ax && native) return composeNatively(this.#ax, this.runner, {
6447
6661
  mode: "new",
6448
6662
  accountUuid: account?.id ?? null,
6449
6663
  subject: opts.subject,
@@ -6499,12 +6713,12 @@ var AppleMailClient = class {
6499
6713
  */
6500
6714
  #resolveAttachments(paths, sendNow) {
6501
6715
  if (!paths?.length) return [];
6502
- if (sendNow && !this.config.allowFileSend) throw new PreconditionError("Sending a local file immediately is off. Leave out sendNow to open a draft with the attachments for the user to review and send, or set APPLE_MAIL_ALLOW_FILE_SEND=1 to allow attaching and sending in one call.");
6716
+ if (sendNow && !this.config.allowFileSend) throw new PreconditionError$1("Sending a local file immediately is off. Leave out sendNow to open a draft with the attachments for the user to review and send, or set APPLE_MAIL_ALLOW_FILE_SEND=1 to allow attaching and sending in one call.");
6503
6717
  return paths.map((path) => {
6504
- if (!isAbsolute(path)) throw new PreconditionError(`"${path}" is not an absolute path. This server has no meaningful working directory, so a relative path cannot be resolved to the file you mean.`);
6718
+ if (!isAbsolute(path)) throw new PreconditionError$1(`"${path}" is not an absolute path. This server has no meaningful working directory, so a relative path cannot be resolved to the file you mean.`);
6505
6719
  const source = resolve(path);
6506
- if (!existsSync(source)) throw new PreconditionError(`There is no file at ${source}.`);
6507
- if (!statSync(source).isFile()) throw new PreconditionError(`${source} is not a regular file; Mail can only attach files.`);
6720
+ if (!existsSync(source)) throw new PreconditionError$1(`There is no file at ${source}.`);
6721
+ if (!statSync(source).isFile()) throw new PreconditionError$1(`${source} is not a regular file; Mail can only attach files.`);
6508
6722
  return source;
6509
6723
  });
6510
6724
  }
@@ -6937,7 +7151,7 @@ const buildDiagnostics = async (client, ctx) => {
6937
7151
  composerAxRead: axReach.ok ? "granted" : "denied",
6938
7152
  ...axReach.windows ? { composerAxWindowsSeen: axReach.windows } : {}
6939
7153
  } : {},
6940
- ...client.composerLane === "accessibility" ? { composerLaneNote: "This server is hosted by Cupertino, so a composer is driven through the app's own Accessibility driver, for a new message as for a reply or forward: the body is pasted, never assigned. Automation to System Events is NOT required for it, and `automationSystemEvents` above can be denied. The one exception is a new message with no subject, which still has its body assigned and then needs System Events to take off the quotation Mail wraps an assigned body in; without it, the result says `quoted: true` and the message is not sent." } : {},
7154
+ ...client.composerLane === "accessibility" ? { composerLaneNote: "This server is hosted by Cupertino, so a composer is driven through the app's own Accessibility driver, for a new message as for a reply or forward: the body is pasted, never assigned. Automation to System Events is NOT required for it, and `automationSystemEvents` above can be denied. The one exception is a new message with no subject that is sent at once, or saved with no body or files: it still has its body assigned and then needs System Events to take off the quotation Mail wraps an assigned body in; without it, the result says `quoted: true` and the message is not sent." } : {},
6941
7155
  ...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, and apple_mail_send_message leaves its body wrapped as a QUOTATION that recipients see — reported as `quoted: true`, and never sent that way. 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." },
6942
7156
  fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
6943
7157
  ...located.readable ? {} : { howToGrant: [
@@ -7404,7 +7618,7 @@ const registerMessageTools = (server, client, allowWrites) => {
7404
7618
  truncated: parsed.truncated,
7405
7619
  body: parsed.body,
7406
7620
  attachments: parsed.attachments,
7407
- ...missing.length > 0 ? { note: `Not downloaded by Mail yet: ${missing.join(", ")}. Its bytes are not on disk, so apple_mail_save_attachment cannot retrieve it. Open the message in Mail to download it first.` } : {}
7621
+ ...missing.length > 0 ? { note: `Not downloaded by Mail yet: ${missing.join(", ")}. Its bytes are not on disk; apple_mail_save_attachment asks Mail to download it, which takes a few seconds per file and needs Mail running and online.` } : {}
7408
7622
  };
7409
7623
  }));
7410
7624
  server.registerTool("apple_mail_list_open_drafts", {
@@ -7446,7 +7660,7 @@ const registerMessageTools = (server, client, allowWrites) => {
7446
7660
  }));
7447
7661
  if (!allowWrites) return;
7448
7662
  server.registerTool("apple_mail_save_attachment", {
7449
- description: "Save one attachment to disk. It can only write into APPLE_MAIL_ATTACHMENT_DIR (default ~/Downloads) and will not overwrite an existing file unless you ask it to. Write-gated because it puts a file on the user's disk, even though it changes nothing in Mail.",
7663
+ description: "Save one attachment to disk. It can only write into APPLE_MAIL_ATTACHMENT_DIR (default ~/Downloads) and will not overwrite an existing file unless you ask it to. An attachment Mail has not downloaded (retrievable: false) is fetched by Mail from the server first, which needs Mail running and online and can take a few seconds; `from` says \"mail\" then. Write-gated because it puts a file on the user's disk.",
7450
7664
  inputSchema: z.object({
7451
7665
  ref: messageRefArg,
7452
7666
  filename: z.string().min(1).describe("Exact filename from apple_mail_list_attachments."),
@@ -8003,10 +8217,10 @@ var MailWatchService = class {
8003
8217
  }
8004
8218
  async #setUp() {
8005
8219
  const shared = await this.#client.index();
8006
- if (!shared) throw new PreconditionError(`The Envelope Index cannot be read, so there is nothing to ${this.#noun === "watch" ? "watch" : "read events from"}: ${this.#client.indexError ?? "reason unknown"}`);
8007
- if (shared.mode === "immutable") throw new PreconditionError(immutableReason(this.#noun));
8220
+ if (!shared) throw new PreconditionError$1(`The Envelope Index cannot be read, so there is nothing to ${this.#noun === "watch" ? "watch" : "read events from"}: ${this.#client.indexError ?? "reason unknown"}`);
8221
+ if (shared.mode === "immutable") throw new PreconditionError$1(immutableReason(this.#noun));
8008
8222
  const located = await this.#client.locate();
8009
- if (!located.envelopeIndexPath) throw new PreconditionError(located.reason ?? "The Envelope Index was not located.");
8223
+ if (!located.envelopeIndexPath) throw new PreconditionError$1(located.reason ?? "The Envelope Index was not located.");
8010
8224
  this.#open(located.envelopeIndexPath);
8011
8225
  try {
8012
8226
  await this.#refresh();
@@ -8024,7 +8238,7 @@ var MailWatchService = class {
8024
8238
  const index = new EnvelopeIndex(openIndex(path, this.#client.config.indexMode, this.#logger));
8025
8239
  if (index.mode === "immutable") {
8026
8240
  index.close();
8027
- throw new PreconditionError(immutableReason(this.#noun));
8241
+ throw new PreconditionError$1(immutableReason(this.#noun));
8028
8242
  }
8029
8243
  const old = this.#index;
8030
8244
  this.#index = index;
@@ -8187,10 +8401,10 @@ var MailWatchService = class {
8187
8401
  return [];
8188
8402
  }
8189
8403
  if (!(running ?? await this.#isMailRunning())) throw this.#mailboxesNeedMail();
8190
- for (const name of mailboxes) if (isUnwatchedMailbox(`imap://x/${name}`)) throw new PreconditionError(`"${name}" is never ${noun === "watch" ? "watched" : "followed"}: Sent, Drafts, Junk and Trash are excluded, so a ${noun} on it could never fire.`);
8404
+ for (const name of mailboxes) if (isUnwatchedMailbox(`imap://x/${name}`)) throw new PreconditionError$1(`"${name}" is never ${noun === "watch" ? "watched" : "followed"}: Sent, Drafts, Junk and Trash are excluded, so a ${noun} on it could never fire.`);
8191
8405
  await this.ensure();
8192
8406
  const rowids = await this.#client.mailboxRowidsFor(mailboxes);
8193
- if (rowids.length > MAX_WATCHED_MAILBOXES) throw new PreconditionError(`Those names cover ${rowids.length} mailboxes across the accounts, more than a ${noun} can follow (${MAX_WATCHED_MAILBOXES}). Name fewer mailboxes.`);
8407
+ if (rowids.length > MAX_WATCHED_MAILBOXES) throw new PreconditionError$1(`Those names cover ${rowids.length} mailboxes across the accounts, more than a ${noun} can follow (${MAX_WATCHED_MAILBOXES}). Name fewer mailboxes.`);
8194
8408
  return rowids.map(String);
8195
8409
  }
8196
8410
  /**
@@ -8202,7 +8416,7 @@ var MailWatchService = class {
8202
8416
  if (mailboxes.length > 0 && !await this.#isMailRunning()) throw this.#mailboxesNeedMail();
8203
8417
  }
8204
8418
  #mailboxesNeedMail() {
8205
- return new PreconditionError(`Mailbox names cannot be resolved until Mail is running: Mail is what says which mailboxes an account has. Open Mail and try again, or ${this.#noun === "watch" ? "watch" : "subscribe"} without \`mailboxes\`.`);
8419
+ return new PreconditionError$1(`Mailbox names cannot be resolved until Mail is running: Mail is what says which mailboxes an account has. Open Mail and try again, or ${this.#noun === "watch" ? "watch" : "subscribe"} without \`mailboxes\`.`);
8206
8420
  }
8207
8421
  /** Resolve `mailboxes` to scope keys and register the watch. */
8208
8422
  async add(filter, mailboxes) {
@@ -8380,6 +8594,6 @@ const createServer = (opts) => {
8380
8594
  };
8381
8595
  };
8382
8596
  //#endregion
8383
- 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 };
8597
+ export { WritesDisabledError as A, MessageNotFoundError as C, ProtocolError as D, PreconditionError$1 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 };
8384
8598
 
8385
- //# sourceMappingURL=server-BcVfuC1E.js.map
8599
+ //# sourceMappingURL=server-D5S4dzq6.js.map