@mgcrea/mcp-apple-mail 1.29.0 → 1.30.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.
@@ -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: "3557ee5",
18
- gitCommitDate: "2026-10-21T20:44:56+02:00"
17
+ gitCommit: "9c493e1",
18
+ gitCommitDate: "2026-10-22T12:13:02+02:00"
19
19
  };
20
20
  //#endregion
21
21
  //#region src/client/errors.ts
@@ -234,6 +234,20 @@ const TOKEN_CHAR = "";
234
234
  const TOKEN_SUBROLE = "AXTextAttachment";
235
235
  /** How much of the quoted original to return by default. */
236
236
  const QUOTE_CHARS = 2e3;
237
+ /**
238
+ * What a file in a composer's body reads as.
239
+ *
240
+ * MEASURED, macOS 27.0, pasting file URLs into a new message's body: an image
241
+ * is an `AXImage` NAMED with its filename (`attach-probe.png`), and anything
242
+ * else an `AXButton` named with the filename and its size (`attach-probe.txt,
243
+ * 23 bytes`). The size is localised and the filename is not, so a file is
244
+ * matched by the name or by the name followed by a comma — see `isFileNamed`.
245
+ * Neither has a value, so neither disturbs the text read beside it. The image's
246
+ * own child button is unnamed, and is not counted.
247
+ */
248
+ const FILE_ROLES = /* @__PURE__ */ new Set(["AXImage", "AXButton"]);
249
+ /** Does this element name read as the file called `name`? */
250
+ const isFileNamed = (element, name) => element === name || element.startsWith(`${name}, `);
237
251
  var MailAxLane = class MailAxLane {
238
252
  #channel;
239
253
  constructor(channel) {
@@ -603,11 +617,13 @@ var MailAxLane = class MailAxLane {
603
617
  for (let block = 0; block < boundary; block += 1) lines.push(blockText(block));
604
618
  const quoteBlocks = [];
605
619
  for (let block = boundary; block < starts.length; block += 1) quoteBlocks.push(blockText(block));
620
+ const files = elements.slice(0, starts[boundary] ?? elements.length).flatMap((el) => FILE_ROLES.has(el.role) && el.name ? [el.name] : []);
606
621
  return {
607
622
  own: {
608
623
  text: lines.join("\n"),
609
624
  blocks: boundary,
610
- quoted: boundary < starts.length
625
+ quoted: boundary < starts.length,
626
+ files
611
627
  },
612
628
  tree,
613
629
  quoteBlocks
@@ -1942,10 +1958,11 @@ function attachFiles(M, msg, list) {
1942
1958
  return { ok: true, count: prop(function () { return msg.content.attachments.length; }, null) };
1943
1959
  }
1944
1960
 
1945
- function attachmentFailure(failure, closed) {
1961
+ function attachmentFailure(failure, closed, also) {
1946
1962
  return err(
1947
1963
  "ATTACHMENT_FAILED",
1948
1964
  "Mail would not attach " + failure.path + ": " + failure.message + ". Nothing was sent. " +
1965
+ (also ? also + " " : "") +
1949
1966
  (closed
1950
1967
  ? "The composer this opened was closed again without saving, so a retry is safe."
1951
1968
  : "The composer could NOT be closed from here and is still open in Mail; close it before " +
@@ -2766,6 +2783,30 @@ const SEND_MESSAGE = script(`
2766
2783
  var unquoted = false;
2767
2784
  try { unquoted = stripCitation(String(p.subject || "")); } catch (e) { unquoted = false; }
2768
2785
 
2786
+ /*
2787
+ * Assigning content made Mail wrap the body in a quotation that Mail itself
2788
+ * hides and every other client shows — the 2026-10-21 mail that reached its
2789
+ * recipient as one long quote. When it cannot be taken off, the message is
2790
+ * NOT sent, and a draft says so rather than reporting a flag nobody reads.
2791
+ */
2792
+ if (!unquoted) {
2793
+ return ok({
2794
+ sent: false, draft: true, quoted: true, degraded: true, capability: "quoting",
2795
+ subjectLength: String(p.subject || "").length,
2796
+ recipientCount: (p.to || []).length + (p.cc || []).length + (p.bcc || []).length,
2797
+ attachments: attached.count,
2798
+ note:
2799
+ "The draft is open in Mail, but its whole body is wrapped as a QUOTATION: Mail does " +
2800
+ "this to a body set through AppleScript and hides it on screen, while the recipient " +
2801
+ "sees every line quoted. Taking it off needs Automation for System Events, which this " +
2802
+ "process does not have or which failed." +
2803
+ (p.sendNow ? " So it was NOT sent." : "") +
2804
+ " Tell the user before they send it: in Mail, select the whole body and choose " +
2805
+ "Format > Quote Level > Decrease, or run this server from Cupertino, which pastes the " +
2806
+ "body instead."
2807
+ });
2808
+ }
2809
+
2769
2810
  if (p.sendNow) {
2770
2811
  msg.send();
2771
2812
  return ok({ sent: true, unquoted: unquoted, subjectLength: String(p.subject || "").length,
@@ -2955,9 +2996,14 @@ const DRAFT_FACTS = script(`
2955
2996
  * remade. `client/mail.ts` tries that first and arrives here only when there is
2956
2997
  * no window to edit.
2957
2998
  */
2958
- const UPDATE_DRAFT = script(`
2959
- ${RESOLVE_DRAFT}
2960
-
2999
+ /**
3000
+ * Everything both recreate routes check before a replacement exists.
3001
+ *
3002
+ * Shared, like `RESOLVE_DRAFT`, so the route that pastes the body and the one
3003
+ * that assigns it refuse exactly the same drafts. Leaves `facts`, `subject` and
3004
+ * `before` in scope.
3005
+ */
3006
+ const DRAFT_PREFLIGHT = `
2961
3007
  // Everything the caller needs to decide what to do instead, reported on the
2962
3008
  // refusals as well as on success.
2963
3009
  var facts = {
@@ -3016,9 +3062,9 @@ const UPDATE_DRAFT = script(`
3016
3062
  var bid = prop(function () { return existing[b].id(); }, null);
3017
3063
  if (bid !== null) before[bid] = true;
3018
3064
  }
3019
-
3020
- var replacement = M.OutgoingMessage({ subject: subject, content: p.body || "", visible: true });
3021
- M.outgoingMessages.push(replacement);
3065
+ `;
3066
+ /** The original's sender and recipients, onto `replacement`. */
3067
+ const ADDRESS_REPLACEMENT = `
3022
3068
  if (sender) { try { replacement.sender = sender; } catch (e) {} }
3023
3069
 
3024
3070
  var lists = [["to", to], ["cc", cc], ["bcc", bcc]];
@@ -3031,14 +3077,15 @@ const UPDATE_DRAFT = script(`
3031
3077
  else replacement.bccRecipients.push(M.BccRecipient({ address: addrs[i] }));
3032
3078
  }
3033
3079
  }
3034
-
3035
- pause(1.2);
3036
- var unquoted = false;
3037
- try { unquoted = stripCitation(subject); } catch (e) { unquoted = false; }
3038
-
3039
- var saved = true;
3040
- try { replacement.save(); } catch (e) { saved = false; }
3041
-
3080
+ `;
3081
+ /**
3082
+ * Confirm the replacement is in Drafts, and only then delete the original.
3083
+ *
3084
+ * Needs `subject`, `before`, `facts`, `saved`, `unquoted` and `attached` in
3085
+ * scope; the route that pastes its body supplies them as parameters, because
3086
+ * by the time it confirms, the script that composed the replacement is gone.
3087
+ */
3088
+ const CONFIRM_AND_DELETE = `
3042
3089
  // Ask the Drafts mailbox, not the object we just made: "save() did not throw"
3043
3090
  // is precisely the kind of evidence the compose path already learned not to
3044
3091
  // trust. Anything but a new row here means we must not delete the old one.
@@ -3105,11 +3152,110 @@ const UPDATE_DRAFT = script(`
3105
3152
  subject: subject,
3106
3153
  recipientCount: facts.recipientCount,
3107
3154
  bodyLength: String(p.body || "").length,
3155
+ attachmentsAdded: attached.count,
3108
3156
  unquoted: unquoted,
3109
3157
  originalDeleted: removed,
3110
3158
  originalMovedToTrash: removed ? movesToTrash : null,
3111
3159
  removeError: removeError
3112
3160
  });
3161
+ `;
3162
+ const UPDATE_DRAFT = script(`
3163
+ ${RESOLVE_DRAFT}
3164
+ ${DRAFT_PREFLIGHT}
3165
+
3166
+ var replacement = M.OutgoingMessage({ subject: subject, content: p.body || "", visible: true });
3167
+ M.outgoingMessages.push(replacement);
3168
+ ${ADDRESS_REPLACEMENT}
3169
+
3170
+ // Before the save: a refused file takes the replacement back, and the
3171
+ // original has not been touched yet.
3172
+ var attached = attachFiles(M, replacement, p.attachments);
3173
+ if (!attached.ok) {
3174
+ return attachmentFailure(attached, discardComposer(M, replacement),
3175
+ "The original draft was not changed.");
3176
+ }
3177
+
3178
+ pause(1.2);
3179
+ var unquoted = false;
3180
+ try { unquoted = stripCitation(subject); } catch (e) { unquoted = false; }
3181
+
3182
+ /*
3183
+ * Assigning content made Mail wrap the whole body in a hidden quotation, and
3184
+ * it could not be taken off: what would be saved reads as a QUOTE to
3185
+ * whoever gets it, in Outlook most visibly. Saving that and deleting the
3186
+ * original is replacing a good draft with a broken one, so neither happens.
3187
+ */
3188
+ if (!unquoted) {
3189
+ return ok({
3190
+ replaced: false, method: "recreate", degraded: true, capability: "quoting", draft: facts,
3191
+ closed: discardComposer(M, replacement),
3192
+ reason:
3193
+ "Mail wraps a body set through AppleScript in a quotation, hidden in Mail itself but " +
3194
+ "shown to recipients, and taking it off needs Automation for System Events, which this " +
3195
+ "process does not have or which failed. The replacement was not saved and the original " +
3196
+ "draft was not changed.",
3197
+ hint:
3198
+ "Run this server from Cupertino, which pastes the body instead, or grant this process " +
3199
+ "Automation for System Events, or edit the draft in Mail."
3200
+ });
3201
+ }
3202
+
3203
+ var saved = true;
3204
+ try { replacement.save(); } catch (e) { saved = false; }
3205
+
3206
+ ${CONFIRM_AND_DELETE}
3207
+ `, { allowLaunch: true });
3208
+ /**
3209
+ * The first half of recreating a draft without assigning its body.
3210
+ *
3211
+ * MEASURED, macOS 27.0: assigning `content` in any form, "" included and an
3212
+ * attachment pushed onto it included, makes Mail wrap the body in
3213
+ * `<blockquote type="cite">` inside an `Apple-Mail-URLShareWrapperClass`
3214
+ * div, styled with no border. Mail shows nothing; Outlook shows a quotation,
3215
+ * and the text/plain part carries "> " on every line. A message created with
3216
+ * no `content` at all has none of it. So this composes the replacement with
3217
+ * no body, the client pastes the body and any files into its window and
3218
+ * presses save, and `COMMIT_REPLACEMENT` finishes the job.
3219
+ *
3220
+ * Every refusal `UPDATE_DRAFT` makes, it makes here, before anything opens.
3221
+ */
3222
+ const STAGE_REPLACEMENT = script(`
3223
+ ${RESOLVE_DRAFT}
3224
+ ${DRAFT_PREFLIGHT}
3225
+
3226
+ var replacement = M.OutgoingMessage({ subject: subject, visible: true });
3227
+ M.outgoingMessages.push(replacement);
3228
+ ${ADDRESS_REPLACEMENT}
3229
+
3230
+ var ids = [];
3231
+ for (var key in before) ids.push(Number(key));
3232
+ return ok({ staged: true, subject: subject, before: ids, draftsMailbox: draftsName });
3233
+ `, { allowLaunch: true });
3234
+ /**
3235
+ * The second half: the replacement was pasted into and saved by the client.
3236
+ *
3237
+ * The same confirmation and the same order as `UPDATE_DRAFT`, which is the
3238
+ * point of sharing it: nothing is deleted until a row that was not there
3239
+ * before is in Drafts under the subject.
3240
+ */
3241
+ const COMMIT_REPLACEMENT = script(`
3242
+ ${RESOLVE_DRAFT}
3243
+
3244
+ var facts = {
3245
+ subject: oldSubject,
3246
+ isReply: isReply,
3247
+ attachments: attachments,
3248
+ recipientCount: to.length + cc.length + bcc.length
3249
+ };
3250
+ var subject = String(p.subject);
3251
+ var before = {};
3252
+ before[p.id] = true;
3253
+ for (var b = 0; b < p.before.length; b++) before[p.before[b]] = true;
3254
+ var saved = true;
3255
+ var unquoted = null;
3256
+ var attached = { count: p.attachmentsAdded || 0 };
3257
+
3258
+ ${CONFIRM_AND_DELETE}
3113
3259
  `, { allowLaunch: true });
3114
3260
  /**
3115
3261
  * Reply to, or forward, an existing message.
@@ -3365,7 +3511,7 @@ const REPLY_OR_FORWARD = script(`
3365
3511
  });
3366
3512
  `, { allowLaunch: true });
3367
3513
  /**
3368
- * Open a reply or forward composer, address it, and stop.
3514
+ * Open a composer — new, reply or forward — address it, and stop.
3369
3515
  *
3370
3516
  * The Apple Events half of the NATIVE composer path — see `client/ax.ts` for
3371
3517
  * the other half and `client/compose.ts` for the sequence that joins them.
@@ -3385,8 +3531,32 @@ const REPLY_OR_FORWARD = script(`
3385
3531
  *
3386
3532
  * Recipients go through the scripting object, which does work for them, and
3387
3533
  * only once the composer exists.
3534
+ *
3535
+ * **`content` is never touched, and that includes attaching files.** MEASURED,
3536
+ * macOS 27.0: any write to it — assigning "" or pushing an attachment onto it —
3537
+ * makes Mail wrap the body in a hidden quotation that every other client shows
3538
+ * (`STAGE_REPLACEMENT` has the detail). The native half pastes the body and the
3539
+ * files into the window instead.
3388
3540
  */
3389
3541
  const OPEN_COMPOSER = script(`
3542
+ var draft;
3543
+ if (p.mode === "new") {
3544
+ draft = M.OutgoingMessage({ subject: p.subject || "", visible: true });
3545
+ M.outgoingMessages.push(draft);
3546
+ if (p.senderAddress) draft.sender = p.senderAddress;
3547
+ var lists = [["to", p.to], ["cc", p.cc], ["bcc", p.bcc]];
3548
+ for (var l = 0; l < lists.length; l++) {
3549
+ var kind = lists[l][0];
3550
+ var each = lists[l][1] || [];
3551
+ for (var r = 0; r < each.length; r++) {
3552
+ if (kind === "to") draft.toRecipients.push(M.ToRecipient({ address: each[r] }));
3553
+ else if (kind === "cc") draft.ccRecipients.push(M.CcRecipient({ address: each[r] }));
3554
+ else draft.bccRecipients.push(M.BccRecipient({ address: each[r] }));
3555
+ }
3556
+ }
3557
+ return ok({ subject: String(p.subject || "") });
3558
+ }
3559
+
3390
3560
  var acct = findAccount(M, p.accountUuid);
3391
3561
  if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3392
3562
  var mb = resolveMailbox(acct, p.mailbox);
@@ -3400,7 +3570,6 @@ const OPEN_COMPOSER = script(`
3400
3570
  return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
3401
3571
  }
3402
3572
 
3403
- var draft;
3404
3573
  if (p.mode === "forward") {
3405
3574
  draft = M.forward(original, { openingWindow: true });
3406
3575
  } else {
@@ -3419,14 +3588,7 @@ const OPEN_COMPOSER = script(`
3419
3588
  }
3420
3589
  }
3421
3590
 
3422
- // Here or nowhere: the reference dies with this process, and nothing has
3423
- // been typed yet, so a refusal can take the composer back.
3424
- var attached = attachFiles(M, draft, p.attachments);
3425
- if (!attached.ok) return attachmentFailure(attached, discardComposer(M, draft));
3426
-
3427
- // Not a count on a reply or forward: content reads back as the attachment
3428
- // characters alone there (docs/mail-compose.md), so it is the number pushed.
3429
- return ok({ subject: subject, attachments: (p.attachments || []).length });
3591
+ return ok({ subject: subject });
3430
3592
  `, { allowLaunch: true });
3431
3593
  //#endregion
3432
3594
  //#region src/client/compose.ts
@@ -3510,6 +3672,34 @@ const compare = (before, after) => {
3510
3672
  return after === before ? "no" : "yes";
3511
3673
  };
3512
3674
  /**
3675
+ * File URLs onto the pasteboard, as `public.file-url` and `NSFilenamesPboardType`.
3676
+ *
3677
+ * `pbcopy` only carries text, so this goes through the ObjC bridge. The paths
3678
+ * arrive as arguments and are never spliced into the source, so a filename
3679
+ * holding a quote is a filename and not code. Throws when the pasteboard
3680
+ * refuses, rather than leaving whatever was there to be pasted in their place.
3681
+ *
3682
+ * The array is built as an NSMutableArray on purpose. MEASURED, macOS 27.0:
3683
+ * `$(jsArray)` of two NSURLs wrote ONE pasteboard item and `writeObjects`
3684
+ * still answered true, so the second file would have gone missing without a
3685
+ * word. Hence the count check as well.
3686
+ */
3687
+ const WRITE_FILES = `
3688
+ function run(argv) {
3689
+ ObjC.import("AppKit");
3690
+ var pb = $.NSPasteboard.generalPasteboard;
3691
+ pb.clearContents;
3692
+ var urls = $.NSMutableArray.array;
3693
+ argv.forEach(function (path) { urls.addObject($.NSURL.fileURLWithPath(path)); });
3694
+ if (!pb.writeObjects(urls)) throw new Error("the pasteboard refused the files");
3695
+ // Bridged, not a JS number: compared as one, it never equals argv.length.
3696
+ var held = Number(pb.pasteboardItems.count);
3697
+ if (held !== argv.length) {
3698
+ throw new Error("the pasteboard holds " + held + " of " + argv.length + " files");
3699
+ }
3700
+ return "ok";
3701
+ }`;
3702
+ /**
3513
3703
  * `pbcopy` and `pbpaste` speak the locale's encoding, NOT UTF-8.
3514
3704
  *
3515
3705
  * With no `LANG` or `LC_CTYPE` in the environment they fall back to MacRoman,
@@ -3552,6 +3742,15 @@ const systemClipboard = {
3552
3742
  child.on("close", resolve);
3553
3743
  child.on("error", reject);
3554
3744
  });
3745
+ },
3746
+ async writeFiles(paths) {
3747
+ await run("/usr/bin/osascript", [
3748
+ "-l",
3749
+ "JavaScript",
3750
+ "-e",
3751
+ WRITE_FILES,
3752
+ ...paths
3753
+ ]);
3555
3754
  }
3556
3755
  };
3557
3756
  /**
@@ -3608,6 +3807,48 @@ const paste = async (lane, clipboard, ref, text, focusTimeoutMs, renderTimeoutMs
3608
3807
  };
3609
3808
  });
3610
3809
  };
3810
+ /** How many of these element names read as the file called `name`. */
3811
+ const countFiles = (files, name) => files.filter((file) => isFileNamed(file, name)).length;
3812
+ /**
3813
+ * Wait for the files just pasted to read back in the sender's own text.
3814
+ *
3815
+ * Each requested name has to appear once more than it did before the paste, so
3816
+ * a draft already carrying a file of the same name is not taken as proof. The
3817
+ * sender's text must also read exactly as it did: a paste that replaced a
3818
+ * selection instead of landing at a caret would show the files and lose words.
3819
+ */
3820
+ const awaitFiles = async (lane, ref, before, names, timeoutMs) => {
3821
+ const wanted = squash(before.text);
3822
+ const deadline = Date.now() + timeoutMs;
3823
+ for (;;) {
3824
+ const shown = await lane.composerBody(ref.body);
3825
+ if (shown && squash(shown.text) === wanted && names.every((name) => countFiles(shown.files, name) >= countFiles(before.files, name) + names.filter((n) => n === name).length)) return shown;
3826
+ if (Date.now() >= deadline) return null;
3827
+ await new Promise((resolve) => setTimeout(resolve, RENDER_POLL_MS$1));
3828
+ }
3829
+ };
3830
+ /**
3831
+ * Paste files at the composer's caret, and prove they arrived.
3832
+ *
3833
+ * File URLs on the pasteboard, then command-V, which is what pasting a file
3834
+ * copied in Finder does — MEASURED, macOS 27.0, and the only way to attach one
3835
+ * that leaves `content` alone (see OPEN_COMPOSER). The caller owns the caret
3836
+ * and the clipboard borrow; `before` is the composer as read just before.
3837
+ */
3838
+ const pasteFiles = async (lane, clipboard, ref, before, paths, focusTimeoutMs, timeoutMs) => {
3839
+ await clipboard.writeFiles(paths);
3840
+ if (!await lane.keys(ref, [{
3841
+ key: "v",
3842
+ modifiers: ["command"]
3843
+ }], focusTimeoutMs)) return { kind: "unfocused" };
3844
+ const shown = await awaitFiles(lane, ref, before, paths.map((path) => basename(path)), timeoutMs);
3845
+ return shown ? {
3846
+ kind: "done",
3847
+ shown
3848
+ } : { kind: "unconfirmed" };
3849
+ };
3850
+ /** How long files get to show up in a composer, which may be reading them in. */
3851
+ const FILES_TIMEOUT_MS = 12e3;
3611
3852
  /**
3612
3853
  * What became of a composer that is no longer on screen.
3613
3854
  *
@@ -3655,16 +3896,34 @@ const sentVerdict = async (runner, accountUuid, subject, since) => {
3655
3896
  sentence: `It does NOT appear to have been sent: no message with this subject is among the ${found.scanned ?? 0} most recent in ${found.mailbox ?? "Sent"}. So it was most likely closed or discarded rather than sent. Confirm in Sent before retrying.`
3656
3897
  };
3657
3898
  };
3658
- const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
3899
+ /**
3900
+ * Compose natively: open and address over Apple Events, then paste the body
3901
+ * and any files into the window and read both back before saving or sending.
3902
+ *
3903
+ * Nothing here assigns `content`, which is what keeps a NEW message from going
3904
+ * out as one long quotation — see OPEN_COMPOSER.
3905
+ */
3906
+ const composeNatively = async (lane, runner, params, opts = {}) => {
3659
3907
  const clipboard = opts.clipboard ?? systemClipboard;
3660
3908
  const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;
3661
3909
  const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
3662
3910
  const watch = lane.watch();
3663
3911
  const startedAt = Date.now();
3664
- const reach = await lane.reach();
3912
+ const reach = opts.opened ? {
3913
+ ok: true,
3914
+ windows: opts.opened.windowsBefore
3915
+ } : await lane.reach();
3665
3916
  if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));
3666
- const opened = await runner.run(OPEN_COMPOSER, params);
3667
- const subject = opened.subject;
3917
+ if (!opts.opened && params.mode === "new" && (reach.windows ?? []).includes(params.subject ?? "")) return {
3918
+ ok: false,
3919
+ subject: params.subject ?? "",
3920
+ bodyVerified: null,
3921
+ verifiedChars: 0,
3922
+ sent: false,
3923
+ note: `A window titled "${params.subject}" is already open in Mail, and the new message would carry the same title, so this path could not tell the two apart. Nothing was opened. Finish or close that window, or use another subject, then retry.`
3924
+ };
3925
+ const { attachments: files = [], ...toOpen } = params;
3926
+ const subject = opts.opened ? opts.opened.subject : (await runner.run(OPEN_COMPOSER, toOpen)).subject;
3668
3927
  /**
3669
3928
  * A composer under this subject was open BEFORE this call opened one.
3670
3929
  *
@@ -3738,6 +3997,25 @@ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
3738
3997
  };
3739
3998
  }
3740
3999
  }
4000
+ if (files.length > 0) {
4001
+ const before = await lane.composerBody(ref.body);
4002
+ const pasted = before ? await borrowClipboard(clipboard, () => pasteFiles(lane, clipboard, ref, before, files, opts.focusTimeoutMs, opts.renderTimeoutMs ?? FILES_TIMEOUT_MS)) : null;
4003
+ if (pasted?.kind !== "done") {
4004
+ if (await lane.composerGone(subject, 0)) return vanished(bodyVerified === true ? {
4005
+ verified: true,
4006
+ chars: verifiedChars
4007
+ } : null);
4008
+ return {
4009
+ ok: false,
4010
+ degraded: true,
4011
+ subject,
4012
+ bodyVerified,
4013
+ verifiedChars,
4014
+ sent: false,
4015
+ note: `The ${params.mode} window for "${subject}" was composed` + (bodyVerified ? " and its body verified" : "") + `, but ` + (pasted === null ? `where its own text ends could not be read, so the files were not pasted. ` : pasted.kind === "unfocused" ? `it would not take the keyboard for the files, so they were not pasted. ` : `the files did not read back in it, with the text around them unchanged. `) + `It was NOT ${params.sendNow ? "sent" : "saved"}, and its window is still open in Mail: attach the files there, or close it without saving and retry.` + interferenceNote(await watch.check())
4016
+ };
4017
+ }
4018
+ }
3741
4019
  const finished = await lane.finish(params.sendNow, ref);
3742
4020
  if (finished === "gone") return vanished(bodyVerified === true ? {
3743
4021
  verified: true,
@@ -3758,7 +4036,7 @@ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
3758
4036
  bodyVerified,
3759
4037
  verifiedChars,
3760
4038
  sent,
3761
- ...opened.attachments ? { attachments: opened.attachments } : {},
4039
+ ...files.length > 0 ? { attachments: files.length } : {},
3762
4040
  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."
3763
4041
  };
3764
4042
  };
@@ -4330,6 +4608,8 @@ const RENDER_POLL_MS = 250;
4330
4608
  */
4331
4609
  const COPY_TIMEOUT_MS = 1500;
4332
4610
  const COPY_POLL_MS = 50;
4611
+ /** What a text reading puts where a file is. */
4612
+ const FILE_CHAR = "";
4333
4613
  /** A refusal, shaped like `UPDATE_DRAFT`'s so a caller reads one thing. */
4334
4614
  const refuse = (capability, facts, reason, hint, extra = {}) => ({
4335
4615
  replaced: false,
@@ -4355,8 +4635,8 @@ const refuse = (capability, facts, reason, hint, extra = {}) => ({
4355
4635
  * they agree on the words while disagreeing about every line break.
4356
4636
  */
4357
4637
  const sameDraft = (stored, shown) => {
4358
- const a = squash(stored);
4359
- const b = squash(shown);
4638
+ const a = squash(stored.replaceAll(FILE_CHAR, ""));
4639
+ const b = squash(shown.replaceAll(FILE_CHAR, ""));
4360
4640
  if (a.length === 0 || b.length === 0) return a.length === b.length;
4361
4641
  const chars = Math.min(a.length, b.length, IDENTITY_CHARS);
4362
4642
  return a.slice(0, chars) === b.slice(0, chars);
@@ -4443,7 +4723,7 @@ const awaitOwnText = async (lane, ref, expected, timeoutMs) => {
4443
4723
  }
4444
4724
  };
4445
4725
  /**
4446
- * Replace a draft's body in its open composer.
4726
+ * Replace a draft's body in its open composer, add files to it, or both.
4447
4727
  *
4448
4728
  * Null — and only null — means there is no composer to edit, which is the
4449
4729
  * caller's signal to fall back to recreating the draft. Every other outcome,
@@ -4464,53 +4744,84 @@ const reviseDraftInPlace = async (lane, facts, opts) => {
4464
4744
  composerText: shown.text.slice(0, 200),
4465
4745
  draftText: facts.contentHead.slice(0, 200)
4466
4746
  });
4747
+ const files = opts.attachments ?? [];
4748
+ const names = files.map((path) => basename(path));
4467
4749
  const outcome = await borrowClipboard(clipboard, async () => {
4468
4750
  const selection = shown.blocks === 0 ? await lane.keys(ref, [{
4469
4751
  key: "up",
4470
4752
  modifiers: ["command"]
4471
4753
  }], opts.focusTimeoutMs).then((ok) => ok ? "selected" : "unfocused") : await selectOwnText(lane, clipboard, ref, shown, opts.focusTimeoutMs);
4472
4754
  if (selection !== "selected") return {
4473
- selection,
4474
- shown: null
4755
+ kind: "selection",
4756
+ selection
4475
4757
  };
4476
- await clipboard.write(opts.body);
4477
- if (!await lane.keys(ref, [{
4478
- key: "v",
4479
- modifiers: ["command"]
4480
- }], opts.focusTimeoutMs)) return {
4481
- selection: "unfocused",
4482
- shown: null
4758
+ let now = shown;
4759
+ if (opts.body !== void 0) {
4760
+ await clipboard.write(opts.body);
4761
+ if (!await lane.keys(ref, [{
4762
+ key: "v",
4763
+ modifiers: ["command"]
4764
+ }], opts.focusTimeoutMs)) return {
4765
+ kind: "selection",
4766
+ selection: "unfocused"
4767
+ };
4768
+ const pasted = await awaitOwnText(lane, ref, opts.body, renderTimeoutMs);
4769
+ if (!pasted) return {
4770
+ kind: "unconfirmed",
4771
+ what: "body"
4772
+ };
4773
+ now = pasted;
4774
+ } else if (shown.blocks > 0 && !await lane.keys(ref, [{ key: "right" }], opts.focusTimeoutMs)) return {
4775
+ kind: "selection",
4776
+ selection: "unfocused"
4483
4777
  };
4484
- return {
4485
- selection,
4486
- shown: await awaitOwnText(lane, ref, opts.body, renderTimeoutMs)
4778
+ if (files.length === 0) return {
4779
+ kind: "done",
4780
+ shown: now
4781
+ };
4782
+ const attached = await pasteFiles(lane, clipboard, ref, now, files, opts.focusTimeoutMs, renderTimeoutMs);
4783
+ if (attached.kind === "unfocused") return opts.body === void 0 ? {
4784
+ kind: "selection",
4785
+ selection: "unfocused"
4786
+ } : { kind: "interrupted" };
4787
+ return attached.kind === "done" ? {
4788
+ kind: "done",
4789
+ shown: attached.shown
4790
+ } : {
4791
+ kind: "unconfirmed",
4792
+ what: "files"
4487
4793
  };
4488
4794
  });
4489
- if (outcome.selection === "unfocused") return refuse("composer", facts, `The composer for "${facts.subject}" would not take the keyboard, so nothing was typed into it and the draft is unchanged. Someone is probably using the Mac: a keystroke is refused rather than posted into whichever window they moved to.` + interferenceNote(await watch.check()), "Try again once the Mac is free, or edit the draft in Mail.");
4490
- if (outcome.selection === "blind") return refuse("selection", facts, "The draft's own text could not be selected in its composer: copying the selection back returned nothing, so there is no way to know what a paste would replace. Nothing was changed — selecting and copying do not alter a draft.", "Edit the body in Mail directly.");
4491
- if (outcome.selection === "overshot") return refuse("selection", facts, "The draft's own text could not be selected exactly: the selection read back does not match what the composer shows above its quoted original, so a paste could not be guaranteed to leave the quote alone. Nothing was changed — selecting and copying do not alter a draft.", "Edit the body in Mail directly, or delete this draft and write it again.");
4492
- if (!outcome.shown) return refuse("confirmation", facts, `The new body was pasted into the composer for "${facts.subject}" but did not read back as what was sent within ${renderTimeoutMs / 1e3}s, so IT WAS NOT SAVED. The draft still holds its old text; the composer window on screen holds something this could not verify.` + interferenceNote(await watch.check()), "Look at the composer in Mail and either fix it there or close it without saving.");
4493
- if (shown.quoted && !outcome.shown.quoted) return refuse("confirmation", facts, `The new body went into the composer for "${facts.subject}", but the quoted original that was below it is GONE from the window — so the replacement reached further than the draft's own text. IT WAS NOT SAVED: the draft on disk still holds its old text, quote and all.`, "Close the composer in Mail WITHOUT saving, or undo inside it with command-Z. The draft itself is untouched.");
4795
+ if (outcome.kind === "selection" && outcome.selection === "unfocused") return refuse("composer", facts, `The composer for "${facts.subject}" would not take the keyboard, so nothing was typed into it and the draft is unchanged. Someone is probably using the Mac: a keystroke is refused rather than posted into whichever window they moved to.` + interferenceNote(await watch.check()), "Try again once the Mac is free, or edit the draft in Mail.");
4796
+ if (outcome.kind === "selection" && outcome.selection === "blind") return refuse("selection", facts, "The draft's own text could not be selected in its composer: copying the selection back returned nothing, so there is no way to know what a paste would replace. Nothing was changed — selecting and copying do not alter a draft.", "Edit the body in Mail directly.");
4797
+ if (outcome.kind === "selection") return refuse("selection", facts, "The draft's own text could not be selected exactly: the selection read back does not match what the composer shows above its quoted original, so a paste could not be guaranteed to leave the quote alone. Nothing was changed — selecting and copying do not alter a draft.", "Edit the body in Mail directly, or delete this draft and write it again.");
4798
+ if (outcome.kind === "interrupted") return refuse("composer", facts, `The new body went into the composer for "${facts.subject}" and was verified, but the window then would not take the keyboard, so the files were not pasted and IT WAS NOT SAVED. The draft still holds its old text; the window holds the new text without the files.` + interferenceNote(await watch.check()), "Look at the composer in Mail: save it there and attach the files by hand, or close it without saving and try again.");
4799
+ if (outcome.kind === "unconfirmed" && outcome.what === "body") return refuse("confirmation", facts, `The new body was pasted into the composer for "${facts.subject}" but did not read back as what was sent within ${renderTimeoutMs / 1e3}s, so IT WAS NOT SAVED. The draft still holds its old text; the composer window on screen holds something this could not verify.` + interferenceNote(await watch.check()), "Look at the composer in Mail and either fix it there or close it without saving.");
4800
+ if (outcome.kind === "unconfirmed") return refuse("confirmation", facts, `${names.join(", ")} ${names.length > 1 ? "were" : "was"} pasted into the composer for "${facts.subject}" but did not read back in the draft's own text within ${renderTimeoutMs / 1e3}s, with that text unchanged, so IT WAS NOT SAVED. The draft on disk is as it was; the window may hold some of the files, or none.` + interferenceNote(await watch.check()), "Look at the composer in Mail and either fix it there or close it without saving.");
4801
+ if (shown.quoted && !outcome.shown.quoted) return refuse("confirmation", facts, `The paste went into the composer for "${facts.subject}", but the quoted original that was below it is GONE from the window — so it reached further than the draft's own text. IT WAS NOT SAVED: the draft on disk still holds its old text, quote and all.`, "Close the composer in Mail WITHOUT saving, or undo inside it with command-Z. The draft itself is untouched.");
4494
4802
  const saved = await lane.finish(false, ref);
4495
4803
  const disturbed = interferenceNote(await watch.check());
4496
4804
  const survivors = [
4497
4805
  ...facts.isReply ? ["its threading"] : [],
4498
4806
  ...outcome.shown.quoted ? ["the original it quotes"] : [],
4499
- ...facts.attachments > 0 ? [`its ${facts.attachments} attachment(s)`] : []
4807
+ ...facts.attachments > 0 ? [`its ${facts.attachments} earlier attachment(s)`] : []
4500
4808
  ];
4501
4809
  const kept = survivors.length === 0 ? "it is" : `${survivors.slice(0, -1).join(", ")}${survivors.length > 1 ? " and " : ""}${survivors.at(-1)} ${survivors.length > 1 ? "are" : "is"}`;
4810
+ const changed = opts.body === void 0 ? `${names.join(", ")} ${names.length > 1 ? "were" : "was"} added` : files.length > 0 ? `The body was replaced and ${names.join(", ")} added` : "The draft was edited";
4811
+ const what = opts.body === void 0 ? "files" : files.length > 0 ? "new body and files" : "new body";
4502
4812
  return {
4503
4813
  replaced: true,
4504
4814
  method: "inPlace",
4505
4815
  subject: facts.subject,
4506
- bodyLength: opts.body.length,
4816
+ ...opts.body !== void 0 ? { bodyLength: opts.body.length } : {},
4817
+ ...files.length > 0 ? { attachmentsAdded: names } : {},
4507
4818
  threadingKept: facts.isReply,
4508
4819
  quoteKept: outcome.shown.quoted,
4509
4820
  attachmentsKept: facts.attachments,
4510
4821
  recipientCount: facts.recipientCount,
4511
4822
  draftsMailbox: facts.draftsMailbox,
4512
4823
  saved: saved === "pressed",
4513
- note: saved === "pressed" ? `The draft was edited in its own composer window — nothing was recreated, so ${kept} untouched, and no second draft was made. The window is still open in Mail for review. Mail may renumber a saved draft's row within seconds, so re-find it by subject rather than reusing the ref across turns.` + disturbed : saved === "refused" ? "The new body is in the composer and verified, but Mail would not come forward, so command-S was not pressed and the draft on disk still holds the OLD text. The window is open with the new text in it. Press save in Mail, or try again once the Mac is free." + disturbed : "The new body was pasted and verified, and then the composer window went — nothing here closes one, so someone using the Mac closed or sent it. Look in Mail before doing anything else." + disturbed
4824
+ note: saved === "pressed" ? `${changed} in the draft's own composer window — nothing was recreated, so ${kept} untouched, and no second draft was made. The window is still open in Mail for review. Mail may renumber a saved draft's row within seconds, so re-find it by subject rather than reusing the ref across turns.` + disturbed : saved === "refused" ? `The ${what} ${what === "files" ? "are" : "is"} in the composer and verified, but Mail would not come forward, so command-S was not pressed and the draft on disk does NOT have them yet. The window is open with the change in it. Press save in Mail, or try again once the Mac is free.` + disturbed : `The ${what} went in and ${what === "files" ? "were" : "was"} verified, and then the composer window went — nothing here closes one, so someone using the Mac closed or sent it. Look in Mail before doing anything else.` + disturbed
4514
4825
  };
4515
4826
  };
4516
4827
  //#endregion
@@ -5357,30 +5668,115 @@ var AppleMailClient = class {
5357
5668
  * which is the one outcome nothing downstream could distinguish from success.
5358
5669
  */
5359
5670
  async updateDraft(ref, opts) {
5360
- if (!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.");
5671
+ if (opts.body === void 0 && !opts.attachments?.length) throw new PreconditionError("Nothing to change: pass a body, attachments, or both. A new subject alone needs a body.");
5672
+ 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.");
5673
+ const attachments = this.#resolveAttachments(opts.attachments, false);
5361
5674
  const decoded = decodeRef(ref);
5362
5675
  const target = {
5363
5676
  accountUuid: decoded.accountUuid,
5364
5677
  mailbox: decoded.mailbox,
5365
5678
  id: decoded.id
5366
5679
  };
5680
+ let subjectChanging = opts.subject !== void 0;
5367
5681
  if (this.#ax) {
5368
5682
  const facts = await withBusyRetry(() => this.runner.run(DRAFT_FACTS, target));
5369
- if (opts.subject === void 0 || opts.subject === facts.subject) {
5683
+ subjectChanging = opts.subject !== void 0 && opts.subject !== facts.subject;
5684
+ if (!subjectChanging) {
5370
5685
  const edited = await reviseDraftInPlace(this.#ax, facts, {
5371
5686
  body: opts.body,
5687
+ attachments,
5372
5688
  clipboard: this.#clipboard
5373
5689
  });
5374
5690
  if (edited) return edited;
5375
5691
  }
5376
5692
  }
5693
+ if (opts.body === void 0) return {
5694
+ replaced: false,
5695
+ degraded: true,
5696
+ method: "recreate",
5697
+ capability: "composer",
5698
+ reason: subjectChanging ? "A new subject can only be set by recreating the draft, and recreating it needs a body to write. Nothing was changed." : "Files can only be added to a draft through its composer window, and none is open for this one" + (this.#ax ? "" : " that this server can reach: it was not started by Cupertino") + ". Nothing was changed.",
5699
+ hint: subjectChanging ? "Pass the body as well, or leave the subject out to add the files in place." : "Open the draft in Mail and try again, or pass a body too: recreating a draft that is not a reply and carries no files of its own attaches them to the replacement."
5700
+ };
5701
+ if (this.#ax) return this.#recreateNatively(this.#ax, target, opts.body, opts.subject, attachments);
5377
5702
  return withBusyRetry(() => this.runner.run(UPDATE_DRAFT, {
5378
5703
  ...target,
5379
5704
  body: opts.body,
5380
- subject: opts.subject ?? null
5705
+ subject: opts.subject ?? null,
5706
+ attachments
5381
5707
  }));
5382
5708
  }
5383
5709
  /**
5710
+ * Recreate a draft with its body PASTED, never assigned.
5711
+ *
5712
+ * `UPDATE_DRAFT` assigns `content`, and Mail wraps any body set that way in a
5713
+ * quotation that it hides and every other client shows. So the replacement is
5714
+ * staged with no body, filled through its window the way a reply is, saved,
5715
+ * and only then is the original deleted — by `COMMIT_REPLACEMENT`, which
5716
+ * shares `UPDATE_DRAFT`'s confirmation, so the order that protects the
5717
+ * original is the same on both routes.
5718
+ */
5719
+ async #recreateNatively(lane, target, body, subject, attachments) {
5720
+ const reach = await lane.reach();
5721
+ if (!reach.ok) return {
5722
+ replaced: false,
5723
+ degraded: true,
5724
+ method: "recreate",
5725
+ capability: "accessibility",
5726
+ reason: MailAxLane.grantMessage("replacement"),
5727
+ hint: "Run apple_mail_diagnostics."
5728
+ };
5729
+ const staged = await withBusyRetry(() => this.runner.run(STAGE_REPLACEMENT, {
5730
+ ...target,
5731
+ subject: subject ?? null
5732
+ }));
5733
+ if (staged.staged !== true) return staged;
5734
+ const newSubject = String(staged.subject);
5735
+ const composed = await composeNatively(lane, this.runner, {
5736
+ mode: "new",
5737
+ accountUuid: target.accountUuid,
5738
+ subject: newSubject,
5739
+ body,
5740
+ to: [],
5741
+ attachments,
5742
+ sendNow: false
5743
+ }, {
5744
+ opened: {
5745
+ subject: newSubject,
5746
+ windowsBefore: reach.windows ?? []
5747
+ },
5748
+ ...this.#clipboard ? { clipboard: this.#clipboard } : {}
5749
+ });
5750
+ if (!composed.ok) return {
5751
+ replaced: false,
5752
+ degraded: true,
5753
+ method: "recreate",
5754
+ capability: "composer",
5755
+ reason: `${composed.note} The original draft was not changed.`,
5756
+ hint: "Look at the replacement's window in Mail: finish and save it there and delete the original yourself, or close it without saving."
5757
+ };
5758
+ try {
5759
+ return {
5760
+ ...await withBusyRetry(() => this.runner.run(COMMIT_REPLACEMENT, {
5761
+ ...target,
5762
+ subject: newSubject,
5763
+ before: staged.before,
5764
+ attachmentsAdded: composed.attachments ?? 0
5765
+ })),
5766
+ bodyVerified: composed.bodyVerified
5767
+ };
5768
+ } catch (err) {
5769
+ return {
5770
+ replaced: false,
5771
+ degraded: true,
5772
+ method: "recreate",
5773
+ capability: "confirmation",
5774
+ reason: `The replacement was pasted, verified and saved, but the original could not be reached again to confirm it and delete it (${err instanceof Error ? err.message : err}). THE ORIGINAL WAS NOT DELETED — there may now be two drafts under "${newSubject}".`,
5775
+ hint: "Look in Drafts and delete the one you do not want. Nothing here will."
5776
+ };
5777
+ }
5778
+ }
5779
+ /**
5384
5780
  * The drafts being written right now: every compose window open in Mail.
5385
5781
  *
5386
5782
  * Read from the windows, because nothing else sees them all — see
@@ -5443,6 +5839,18 @@ var AppleMailClient = class {
5443
5839
  async sendMessage(opts) {
5444
5840
  const attachments = this.#resolveAttachments(opts.attachments, opts.sendNow);
5445
5841
  const account = opts.account ? await this.mailboxes.resolveAccount(opts.account) : null;
5842
+ if (this.#ax && opts.subject.trim()) return composeNatively(this.#ax, this.runner, {
5843
+ mode: "new",
5844
+ accountUuid: account?.id ?? null,
5845
+ subject: opts.subject,
5846
+ senderAddress: account?.emailAddresses[0] ?? null,
5847
+ body: opts.body,
5848
+ to: opts.to,
5849
+ cc: opts.cc,
5850
+ bcc: opts.bcc,
5851
+ attachments,
5852
+ sendNow: opts.sendNow
5853
+ }, this.#clipboard ? { clipboard: this.#clipboard } : {});
5446
5854
  return this.runner.run(SEND_MESSAGE, {
5447
5855
  senderAddress: account?.emailAddresses[0] ?? null,
5448
5856
  to: opts.to,
@@ -5468,7 +5876,7 @@ var AppleMailClient = class {
5468
5876
  attachments,
5469
5877
  sendNow: opts.sendNow
5470
5878
  };
5471
- if (this.#ax) return replyOrForwardNatively(this.#ax, this.runner, params, this.#clipboard ? { clipboard: this.#clipboard } : {});
5879
+ if (this.#ax) return composeNatively(this.#ax, this.runner, params, this.#clipboard ? { clipboard: this.#clipboard } : {});
5472
5880
  return this.runner.run(REPLY_OR_FORWARD, params);
5473
5881
  }
5474
5882
  /**
@@ -5853,8 +6261,8 @@ const buildDiagnostics = async (client, ctx) => {
5853
6261
  composerAxRead: axReach.ok ? "granted" : "denied",
5854
6262
  ...axReach.windows ? { composerAxWindowsSeen: axReach.windows } : {}
5855
6263
  } : {},
5856
- ...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." } : {},
5857
- ...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." },
6264
+ ...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." } : {},
6265
+ ...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." },
5858
6266
  fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
5859
6267
  ...located.readable ? {} : { howToGrant: [
5860
6268
  "System Settings > Privacy & Security > Full Disk Access",
@@ -6138,10 +6546,11 @@ const registerComposeTools = (server, client) => {
6138
6546
  });
6139
6547
  }));
6140
6548
  server.registerTool("apple_mail_update_draft", {
6141
- description: "Replace the body of an unsent draft — including a REPLY draft you have just written and been asked to revise, which is the usual reason to reach for this. For a draft the user has open, apple_mail_list_open_drafts gives its ref under `savedDrafts`. It takes one of two routes and the result says which in `method`. `inPlace`: the draft's own composer window is still open in Mail, so the body is edited in that window. Nothing is recreated, so threading, attachments and the quoted original all survive, no second draft appears, and your ref stays valid — though Mail may renumber a saved draft within seconds, so re-find it by subject rather than reusing a ref across turns. `recreate`: no composer is open, so a new draft is composed with the same recipients and the old one deleted once the replacement is confirmed present; the ref you passed in is DEAD afterwards and the result carries the new one. It REFUSES rather than doing damage, and returns `replaced: false` with a reason when it does. Editing in place refuses when two composers share the subject, when the open window turns out to hold a different message, or when the draft's own text cannot be selected exactly — it will not risk swallowing the quoted original. Recreating refuses on a reply or forward draft, because In-Reply-To is set by Mail's reply command and a recreated one would silently start a new thread; on a draft carrying attachments, because their bytes are not available as files to re-attach; and on anything not in the Drafts mailbox, because deleting a sent or received message and writing a lookalike is not editing. In every refusal the original is untouched. If a recreated replacement cannot be confirmed the original is KEPT and you are told there are now two — never assume a clean swap without reading `replaced`. Editing in place brings Mail to the front for a moment and borrows the clipboard, both of which are put back.",
6549
+ description: "Replace the body of an unsent draft, add files to it, or both — including a REPLY draft you have just written and been asked to revise or attach something to, which is the usual reason to reach for this. For a draft the user has open, apple_mail_list_open_drafts gives its ref under `savedDrafts`. It takes one of two routes and the result says which in `method`. `inPlace`: the draft's own composer window is still open in Mail, so the body is edited in that window and files are pasted in after the text, above any quoted original; each file must read back in the window before anything is saved. Nothing is recreated, so threading, earlier attachments and the quoted original all survive, no second draft appears, and your ref stays valid — though Mail may renumber a saved draft within seconds, so re-find it by subject rather than reusing a ref across turns. `recreate`: no composer is open, so a new draft is composed with the same recipients and the old one deleted once the replacement is confirmed present; the ref you passed in is DEAD afterwards and the result carries the new one; files go on the replacement, and adding files with no body is refused on this route. It REFUSES rather than doing damage, and returns `replaced: false` with a reason when it does. Editing in place refuses when two composers share the subject, when the open window turns out to hold a different message, or when the draft's own text cannot be selected exactly — it will not risk swallowing the quoted original. Recreating refuses on a reply or forward draft, because In-Reply-To is set by Mail's reply command and a recreated one would silently start a new thread; on a draft carrying attachments, because their bytes are not available as files to re-attach; and on anything not in the Drafts mailbox, because deleting a sent or received message and writing a lookalike is not editing. In every refusal the original is untouched. If a recreated replacement cannot be confirmed the original is KEPT and you are told there are now two — never assume a clean swap without reading `replaced`. Editing in place brings Mail to the front for a moment and borrows the clipboard, both of which are put back.",
6142
6550
  inputSchema: {
6143
6551
  ref: messageRefArg,
6144
- body: z.string().min(1).describe("The complete new body. This REPLACES the draft's text rather than appending to it, so include everything that should remain — read the draft first with apple_mail_get_message if you are editing rather than rewriting."),
6552
+ body: z.string().min(1).optional().describe("The complete new body. This REPLACES the draft's text rather than appending to it, so include everything that should remain — read the draft first with apple_mail_get_message if you are editing rather than rewriting. Omit it to only add attachments, which leaves the text exactly as it is."),
6553
+ attachments: attachmentsArg,
6145
6554
  subject: z.string().optional().describe("A new subject. Defaults to the draft's existing one — OMIT IT unless the subject really is changing, because changing it forces the recreate route (a composer's subject field cannot be retyped from here), which in turn refuses a reply. On that route a draft with no subject at all is refused unless you pass one, because the subject is how the replacement is found again before the original is deleted."),
6146
6555
  confirm: confirmArg
6147
6556
  },
@@ -6150,9 +6559,10 @@ const registerComposeTools = (server, client) => {
6150
6559
  destructiveHint: true,
6151
6560
  idempotentHint: false
6152
6561
  }
6153
- }, async ({ ref, body, subject }) => wrap(async () => client.updateDraft(ref, {
6154
- body,
6155
- ...subject ? { subject } : {}
6562
+ }, async ({ ref, body, subject, attachments }) => wrap(async () => client.updateDraft(ref, {
6563
+ ...body !== void 0 ? { body } : {},
6564
+ ...subject ? { subject } : {},
6565
+ ...attachments?.length ? { attachments } : {}
6156
6566
  })));
6157
6567
  };
6158
6568
  //#endregion
@@ -6204,7 +6614,7 @@ const registerMessageTools = (server, client, allowWrites) => {
6204
6614
  };
6205
6615
  }));
6206
6616
  server.registerTool("apple_mail_list_open_drafts", {
6207
- description: "Read the drafts the user has open in Mail right now — every compose window, with its subject, From, the recipients' names as shown, the text they wrote separated from the quoted message below it, and the opening of that quote. Reach for this when the user says 'review my draft', 'check this email before I send it' or 'what do you think of my reply' without naming a message: the draft in front of them may never have been saved where a search finds it, and the window is the current text either way. `main: true` marks the window in front. Each draft carries `savedDrafts`, the refs Mail autosaved under the same subject: read one with apple_mail_get_message for recipient ADDRESSES, or pass it to apple_mail_update_draft to rewrite the body in place. Read-only: nothing is focused, typed or brought to the front. `degraded: true` means the windows could not be read, which is NOT the same as no draft being open.",
6617
+ description: "Read the drafts the user has open in Mail right now — every compose window, with its subject, From, the recipients' names as shown, the text they wrote separated from the quoted message below it, and the opening of that quote. Reach for this when the user says 'review my draft', 'check this email before I send it' or 'what do you think of my reply' without naming a message: the draft in front of them may never have been saved where a search finds it, and the window is the current text either way. `main: true` marks the window in front. Each draft carries `savedDrafts`, the refs Mail autosaved under the same subject: read one with apple_mail_get_message for recipient ADDRESSES, or pass it to apple_mail_update_draft to rewrite the body or add files in place. Read-only: nothing is focused, typed or brought to the front. `degraded: true` means the windows could not be read, which is NOT the same as no draft being open.",
6208
6618
  inputSchema: { quoteChars: z.number().int().min(0).max(2e4).optional().describe("How much of the quoted original to return per draft. Default 2000; 0 for none.") },
6209
6619
  annotations: { readOnlyHint: true }
6210
6620
  }, async ({ quoteChars }) => wrap(async () => client.listOpenDrafts({ quoteChars })));
@@ -6549,4 +6959,4 @@ const createServer = (opts) => {
6549
6959
  //#endregion
6550
6960
  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 };
6551
6961
 
6552
- //# sourceMappingURL=server-cBMUU2jH.js.map
6962
+ //# sourceMappingURL=server-DSeINDvw.js.map