@mgcrea/mcp-apple-mail 1.38.0 → 1.40.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,4 +1,4 @@
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";
1
+ import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, AxChannelError, 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, settleGroups, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, wrap, writeConfinedFile } from "@mgcrea/mcp-apple-core";
2
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
4
  import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
@@ -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: "45c3a7e",
18
- gitCommitDate: "2026-11-10T15:30:40+01:00"
17
+ gitCommit: "1e3dc3e",
18
+ gitCommitDate: "2026-11-16T14:52:33+01:00"
19
19
  };
20
20
  //#endregion
21
21
  //#region src/client/errors.ts
@@ -278,25 +278,43 @@ var MailAxLane = class MailAxLane {
278
278
  * Mail with no windows is legitimate — everything closed to the menu bar — so
279
279
  * an empty list is not evidence of anything and must not refuse a reply that
280
280
  * would have worked.
281
+ *
282
+ * A refused HANDSHAKE is kept apart from a failed read. The host turns the
283
+ * lend away before any window is asked for — Mail switched off, no licence,
284
+ * or a connection it does not recognise as this server — and every one of
285
+ * those used to come back here as `accessibility`, so the sentence a person
286
+ * read sent them to grant something already granted.
281
287
  */
282
288
  async reach() {
283
289
  try {
284
290
  return {
285
291
  ok: true,
286
292
  reason: null,
293
+ refusal: null,
287
294
  windows: ((await this.#call("list_windows", {
288
295
  bundleId: MAIL_BUNDLE,
289
296
  includeTitles: true
290
297
  })).windows ?? []).map((w) => w.title ?? null).filter((t) => t !== null)
291
298
  };
292
- } catch {
299
+ } catch (error) {
300
+ if (error instanceof AxChannelError && error.refusal !== null) return {
301
+ ok: false,
302
+ reason: "refused",
303
+ refusal: error.refusal,
304
+ windows: null
305
+ };
293
306
  return {
294
307
  ok: false,
295
308
  reason: "accessibility",
309
+ refusal: null,
296
310
  windows: null
297
311
  };
298
312
  }
299
313
  }
314
+ /** The sentence to say when the host refused to lend its driver at all. */
315
+ static refusalMessage(mode, refusal) {
316
+ return `Cupertino would not lend Mail its Accessibility driver, which is the only route into a ${mode} composer, so it was not started and nothing was written. The app said: ${refusal}`;
317
+ }
300
318
  /**
301
319
  * The sentence to say when the app is there but Mail's windows cannot be read.
302
320
  *
@@ -1132,16 +1150,39 @@ const readEmlxBodyText = (path, opts) => {
1132
1150
  return null;
1133
1151
  }
1134
1152
  };
1135
- /** Raw RFC 5322 source, for header forensics. Capped and offsettable. */
1136
- const readEmlxSource = (path, opts) => {
1137
- const mime = splitEmlx(readFileSync(path));
1138
- const slice = mime.subarray(opts.offset, opts.offset + opts.maxBytes);
1153
+ /**
1154
+ * One page of a UTF-8 message, in bytes, never cut inside a character.
1155
+ *
1156
+ * Both source lanes page through this, so an offset names the same place
1157
+ * whether the bytes came from the `.emlx` file or from Mail. Each page is
1158
+ * decoded on its own, so a boundary inside a multibyte character turned both
1159
+ * halves into U+FFFD and the pages no longer joined back into the message.
1160
+ * Both ends therefore back off to the start of the character they land in
1161
+ * (a UTF-8 character has at most three continuation bytes), and `nextOffset`
1162
+ * carries the adjusted end, so paging by it reassembles the source exactly.
1163
+ * A page can come back up to three bytes short of `maxBytes` for that reason.
1164
+ */
1165
+ const pageUtf8 = (buf, offset, maxBytes) => {
1166
+ const startOf = (at) => {
1167
+ let i = Math.min(at, buf.length);
1168
+ for (let n = 0; n < 3 && i > 0 && i < buf.length; n++) {
1169
+ if (((buf[i] ?? 0) & 192) !== 128) break;
1170
+ i--;
1171
+ }
1172
+ return i;
1173
+ };
1174
+ const start = startOf(offset);
1175
+ let end = startOf(offset + maxBytes);
1176
+ if (end <= start) end = Math.min(buf.length, offset + maxBytes);
1139
1177
  return {
1140
- source: slice.toString("utf8"),
1141
- totalBytes: mime.length,
1142
- truncated: opts.offset + slice.length < mime.length
1178
+ source: buf.subarray(start, end).toString("utf8"),
1179
+ totalBytes: buf.length,
1180
+ truncated: end < buf.length,
1181
+ nextOffset: end
1143
1182
  };
1144
1183
  };
1184
+ /** Raw RFC 5322 source, for header forensics. Capped and offsettable. */
1185
+ const readEmlxSource = (path, opts) => pageUtf8(splitEmlx(readFileSync(path)), opts.offset, opts.maxBytes);
1145
1186
  const walkParts = (part, visit) => {
1146
1187
  visit(part);
1147
1188
  for (const child of part.parts) walkParts(child, visit);
@@ -2671,6 +2712,33 @@ const UPDATE_DRAFT = script(`
2671
2712
  if (bid !== null) before[bid] = true;
2672
2713
  }
2673
2714
 
2715
+
2716
+ var HEAD = 120;
2717
+ var squashed = function (s) {
2718
+ return String(s).replace(/\\uFFFC/g, "").replace(/\\s+/g, " ").trim();
2719
+ };
2720
+ var headOf = function (m) {
2721
+ return squashed(prop(function () { return m.content(); }, "")).slice(0, HEAD);
2722
+ };
2723
+ var originalMessageId = prop(function () { return original.messageId(); }, null);
2724
+ var oldHead = headOf(original);
2725
+ var newHead = squashed(p.body || "").slice(0, HEAD);
2726
+
2727
+ // The row's id when it can be the replacement, else null. A Message-ID or a
2728
+ // head that cannot be read is no evidence either way, so it does not refuse.
2729
+ var replacementId = function (row) {
2730
+ var id = prop(function () { return row.id(); }, null);
2731
+ if (id === null || before[id]) return null;
2732
+ var mid = prop(function () { return row.messageId(); }, null);
2733
+ if (originalMessageId && mid && String(mid) === String(originalMessageId)) return null;
2734
+ // Only telling when the bodies open differently: a revision of the closing
2735
+ // lines leaves both heads alike and the Message-ID to decide. An empty head
2736
+ // is a body Mail has not reported yet, not a different one.
2737
+ var rowHead = headOf(row);
2738
+ if (newHead !== oldHead && rowHead && rowHead.indexOf(newHead) !== 0) return null;
2739
+ return id;
2740
+ };
2741
+
2674
2742
 
2675
2743
  var replacement = M.OutgoingMessage({ subject: subject, content: p.body || "", visible: true });
2676
2744
  M.outgoingMessages.push(replacement);
@@ -2734,8 +2802,8 @@ const UPDATE_DRAFT = script(`
2734
2802
  pause(0.4);
2735
2803
  var matches = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);
2736
2804
  for (var k = 0; k < matches.length; k++) {
2737
- var mid = prop(function () { return matches[k].id(); }, null);
2738
- if (mid === null || before[mid]) continue;
2805
+ var mid = replacementId(matches[k]);
2806
+ if (mid === null) continue;
2739
2807
  if (newId === null || mid > newId) newId = mid;
2740
2808
  }
2741
2809
  }
@@ -2765,6 +2833,10 @@ const UPDATE_DRAFT = script(`
2765
2833
  * across that gap failed with "Can't get object." The reference fetched at the
2766
2834
  * top of this script has been through several seconds of polling and a server
2767
2835
  * round trip by the time we get here, so it is refetched by id.
2836
+ *
2837
+ * The same rewrite can move the original itself, and then its old id finds
2838
+ * nothing. It is left where it is rather than looked for some other way, as
2839
+ * COMMIT_REPLACEMENT does: nothing is deleted on a guess.
2768
2840
  */
2769
2841
  try {
2770
2842
  M.delete(mb.messages.byId(p.id));
@@ -2775,13 +2847,18 @@ const UPDATE_DRAFT = script(`
2775
2847
 
2776
2848
  // Read the id back once more: the same sync rewrite that invalidates the
2777
2849
  // original can renumber the replacement between confirmation and return.
2850
+ // The confirmed id stands while it is still there; otherwise the newest row
2851
+ // that passes the replacement test, which a renumbered original does not.
2778
2852
  pause(0.4);
2779
- var settledId = newId;
2853
+ var settledId = null;
2780
2854
  var finals = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);
2781
2855
  for (var f = 0; f < finals.length; f++) {
2782
- var fid = prop(function () { return finals[f].id(); }, null);
2783
- if (fid !== null && !before[fid] && (settledId === newId || fid > settledId)) settledId = fid;
2856
+ var fid = replacementId(finals[f]);
2857
+ if (fid === null) continue;
2858
+ if (fid === newId) { settledId = newId; break; }
2859
+ if (settledId === null || fid > settledId) settledId = fid;
2784
2860
  }
2861
+ if (settledId === null) settledId = newId;
2785
2862
 
2786
2863
  return ok({
2787
2864
  replaced: true,
@@ -3706,7 +3783,7 @@ const composeNatively = async (lane, runner, params, opts = {}) => {
3706
3783
  };
3707
3784
  }
3708
3785
  const reach = await lane.reach();
3709
- if (!reach.ok) throw new Error(`${MailAxLane.grantMessage(params.mode)} ${MailAxLane.nothingWritten}`);
3786
+ if (!reach.ok) throw new Error(reach.refusal === null ? `${MailAxLane.grantMessage(params.mode)} ${MailAxLane.nothingWritten}` : MailAxLane.refusalMessage(params.mode, reach.refusal));
3710
3787
  const { attachments: files = [], ...toOpen } = params;
3711
3788
  const before = await lane.composers();
3712
3789
  const subject = (await runner.run(OPEN_COMPOSER, toOpen)).subject;
@@ -4378,6 +4455,15 @@ var EnvelopeIndex = class EnvelopeIndex {
4378
4455
  };
4379
4456
  //#endregion
4380
4457
  //#region src/client/mailbox-map.ts
4458
+ /** Split an Envelope Index mailbox URL into its account host and mailbox path. */
4459
+ const parseIndexUrl = (url) => {
4460
+ const m = /^([a-z-]+):\/\/([^/]*)\/?(.*)$/i.exec(url);
4461
+ if (!m) return null;
4462
+ return {
4463
+ host: decodeURIComponent(m[2] ?? ""),
4464
+ path: decodeURIComponent(m[3] ?? "")
4465
+ };
4466
+ };
4381
4467
  var MailboxMap = class {
4382
4468
  #runner;
4383
4469
  #allowlist;
@@ -4392,6 +4478,15 @@ var MailboxMap = class {
4392
4478
  this.#ttlMs = opts.ttlMs;
4393
4479
  this.#now = opts.now ?? Date.now;
4394
4480
  }
4481
+ /**
4482
+ * True when an allowlist is set. A query that names no account then has a
4483
+ * scope of its own, the admitted accounts, rather than none: a SQL lane that
4484
+ * read "no account given" as "no filter" would count, name and page through
4485
+ * mail the user excluded before any row reached this map.
4486
+ */
4487
+ get restricted() {
4488
+ return this.#allowlist.length > 0;
4489
+ }
4395
4490
  /** True when the allowlist admits this account, by UUID or by display name. */
4396
4491
  #admits(account) {
4397
4492
  if (this.#allowlist.length === 0) return true;
@@ -4488,21 +4583,32 @@ var MailboxMap = class {
4488
4583
  * accounts it last asked Mail for.
4489
4584
  */
4490
4585
  resolveIndexUrlIn(accounts, url) {
4491
- const m = /^([a-z-]+):\/\/([^/]*)\/?(.*)$/i.exec(url);
4492
- if (!m) return null;
4493
- const host = decodeURIComponent(m[2] ?? "");
4494
- const path = decodeURIComponent(m[3] ?? "");
4495
- const account = accounts.find((a) => a.id === host);
4586
+ const parsed = parseIndexUrl(url);
4587
+ if (!parsed) return null;
4588
+ const account = accounts.find((a) => a.id === parsed.host);
4496
4589
  if (!account) return null;
4497
4590
  try {
4498
4591
  return {
4499
4592
  account,
4500
- mailbox: this.resolveMailboxName(account, path)
4593
+ mailbox: this.resolveMailboxName(account, parsed.path)
4501
4594
  };
4502
4595
  } catch {
4503
4596
  return null;
4504
4597
  }
4505
4598
  }
4599
+ /**
4600
+ * True when an Envelope Index `mailboxes.url` belongs to an admitted account.
4601
+ *
4602
+ * The host alone decides, on purpose. `resolveIndexUrl` also needs the path
4603
+ * to name a mailbox Mail scripts, and a row whose path does not resolve is
4604
+ * still that account's mail: scoping by the host keeps it in the admitted
4605
+ * set, where the per-row lookup decides what it can show.
4606
+ */
4607
+ async admitsIndexUrl(url) {
4608
+ const parsed = parseIndexUrl(url);
4609
+ if (!parsed) return false;
4610
+ return (await this.accounts()).some((a) => a.id === parsed.host);
4611
+ }
4506
4612
  invalidate() {
4507
4613
  this.#cache = null;
4508
4614
  }
@@ -5005,7 +5111,8 @@ const rebuildDraft = async (deps, target, opts) => {
5005
5111
  ...extra
5006
5112
  });
5007
5113
  const untouched = "Nothing was opened and the draft was not changed.";
5008
- if (!(await lane.reach()).ok) return refuse("accessibility", MailAxLane.grantMessage("replacement"), MailAxLane.nothingWritten);
5114
+ const reach = await lane.reach();
5115
+ if (!reach.ok) return reach.refusal === null ? refuse("accessibility", MailAxLane.grantMessage("replacement"), MailAxLane.nothingWritten) : refuse("accessibility", MailAxLane.refusalMessage("replacement", reach.refusal), "Open Cupertino to see why; this is not an Accessibility grant.");
5009
5116
  const clash = (await lane.composers()).filter((c) => c.subject === facts.subject);
5010
5117
  if (clash.length > 0) {
5011
5118
  const handles = clash.map((c) => c.composer).join(", ");
@@ -5424,6 +5531,8 @@ const displayName = (name) => name.includes(",") ? `"${name.replaceAll(/["\\]/g,
5424
5531
  /** One mailbox of one account, as a single map key. */
5425
5532
  const mailboxKey = (accountUuid, name) => `${accountUuid}\u0000${name}`;
5426
5533
  const FDA_HINT = "The message file could not be read. Grant Full Disk Access to the app running this server and restart it.";
5534
+ /** The refs a mailbox group was given, for the rows of a group whose script threw. */
5535
+ const refsOfGroup = (group) => group.map((r) => encodeRef(r));
5427
5536
  /** What a call that needs the app's composer verb answers when the app is not hosting this server. */
5428
5537
  const nativeOnlyRefusal = (what) => ({
5429
5538
  replaced: false,
@@ -5538,6 +5647,7 @@ var AppleMailClient = class {
5538
5647
  const reach = await this.#ax.reach();
5539
5648
  return {
5540
5649
  ok: reach.ok,
5650
+ refusal: reach.refusal,
5541
5651
  windows: reach.windows
5542
5652
  };
5543
5653
  }
@@ -5813,7 +5923,13 @@ var AppleMailClient = class {
5813
5923
  }
5814
5924
  /** Resolve account/mailbox filters down to the index rowids they cover. */
5815
5925
  async #targetMailboxRowids(opts) {
5816
- if (!opts.account && !opts.mailbox) return void 0;
5926
+ if (!opts.account && !opts.mailbox) {
5927
+ if (!this.mailboxes.restricted) return void 0;
5928
+ const index = await this.index();
5929
+ const rowids = [];
5930
+ for (const row of index?.mailboxes() ?? []) if (await this.mailboxes.admitsIndexUrl(row.url)) rowids.push(row.rowid);
5931
+ return rowids;
5932
+ }
5817
5933
  const lookup = await this.mailboxLookup();
5818
5934
  const account = opts.account ? await this.mailboxes.resolveAccount(opts.account) : null;
5819
5935
  const wanted = opts.mailbox ? account ? await this.mailboxes.resolveMailbox(account, opts.mailbox) : opts.mailbox : null;
@@ -6062,12 +6178,9 @@ var AppleMailClient = class {
6062
6178
  };
6063
6179
  const [summary] = await this.getMessages(decoded, [decoded.id], { withSource: true });
6064
6180
  if (!summary) throw new MessageNotFoundError(ref);
6065
- const full = summary.source ?? "";
6066
- const slice = full.slice(opts.offset, opts.offset + opts.maxBytes);
6181
+ const full = Buffer.from(summary.source ?? "", "utf8");
6067
6182
  return {
6068
- source: slice,
6069
- totalBytes: full.length,
6070
- truncated: opts.offset + slice.length < full.length,
6183
+ ...pageUtf8(full, opts.offset, opts.maxBytes),
6071
6184
  via: "applescript",
6072
6185
  ...located.found ? {} : { fallbackReason: located.explain }
6073
6186
  };
@@ -6384,50 +6497,47 @@ var AppleMailClient = class {
6384
6497
  }
6385
6498
  }
6386
6499
  }
6387
- /** Set flags across refs, one Apple Event per distinct mailbox. */
6500
+ /**
6501
+ * Set flags across refs, one Apple Event per distinct mailbox.
6502
+ *
6503
+ * This and the move and delete below settle each mailbox on its own (see
6504
+ * core's `settleGroups`): a mailbox whose script throws gets a failed row
6505
+ * per ref while the mailboxes already changed keep theirs, and `unknown`
6506
+ * counts refs whose script timed out mid-change.
6507
+ */
6388
6508
  async setFlags(refs, flags) {
6389
6509
  const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));
6390
- const results = [];
6391
- let changed = 0;
6392
- let failed = 0;
6393
- for (const [, group] of groups) {
6510
+ const { rows, unknown } = await settleGroups(groups.values(), refsOfGroup, async (group) => {
6394
6511
  const first = group[0];
6395
- if (!first) continue;
6396
- const res = await withBusyRetry(() => this.runner.run(SET_FLAGS, {
6512
+ if (!first) return [];
6513
+ return (await withBusyRetry(() => this.runner.run(SET_FLAGS, {
6397
6514
  accountUuid: first.accountUuid,
6398
6515
  mailbox: first.mailbox,
6399
6516
  ids: group.map((r) => r.id),
6400
6517
  ...flags
6518
+ }))).results.map((r) => ({
6519
+ ref: encodeRef({
6520
+ accountUuid: first.accountUuid,
6521
+ mailbox: first.mailbox,
6522
+ id: r.id
6523
+ }),
6524
+ ...r
6401
6525
  }));
6402
- for (const r of res.results) {
6403
- if (r.ok) changed += 1;
6404
- else failed += 1;
6405
- results.push({
6406
- ref: encodeRef({
6407
- accountUuid: first.accountUuid,
6408
- mailbox: first.mailbox,
6409
- id: r.id
6410
- }),
6411
- ...r
6412
- });
6413
- }
6414
- }
6526
+ });
6415
6527
  return {
6416
- changed,
6417
- failed,
6418
- results
6528
+ changed: rows.filter((r) => r.ok === true).length,
6529
+ failed: rows.filter((r) => r.ok === false).length,
6530
+ ...unknown ? { unknown } : {},
6531
+ results: rows
6419
6532
  };
6420
6533
  }
6421
6534
  async moveMessages(refs, opts) {
6422
6535
  const destAccount = opts.destinationAccount ? await this.mailboxes.resolveAccount(opts.destinationAccount) : null;
6423
6536
  const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));
6424
- const results = [];
6425
- let moved = 0;
6426
- let failed = 0;
6427
6537
  let destination = opts.destinationMailbox;
6428
- for (const [, group] of groups) {
6538
+ const { rows, unknown } = await settleGroups(groups.values(), refsOfGroup, async (group) => {
6429
6539
  const first = group[0];
6430
- if (!first) continue;
6540
+ if (!first) return [];
6431
6541
  const res = await withBusyRetry(() => this.runner.run(MOVE_MESSAGES, {
6432
6542
  accountUuid: first.accountUuid,
6433
6543
  mailbox: first.mailbox,
@@ -6436,57 +6546,60 @@ var AppleMailClient = class {
6436
6546
  destAccountUuid: destAccount?.id ?? null
6437
6547
  }));
6438
6548
  destination = res.destination;
6439
- for (const r of res.results) {
6440
- if (r.ok) moved += 1;
6441
- else failed += 1;
6442
- results.push({
6443
- previousRef: encodeRef({
6444
- accountUuid: first.accountUuid,
6445
- mailbox: first.mailbox,
6446
- id: r.id
6447
- }),
6448
- ref: r.ok && r.newId ? encodeRef({
6449
- accountUuid: res.destinationAccountUuid || first.accountUuid,
6450
- mailbox: res.destination,
6451
- id: r.newId
6452
- }) : null,
6453
- ...r
6454
- });
6455
- }
6456
- }
6549
+ return res.results.map((r) => ({
6550
+ previousRef: encodeRef({
6551
+ accountUuid: first.accountUuid,
6552
+ mailbox: first.mailbox,
6553
+ id: r.id
6554
+ }),
6555
+ ref: r.ok && r.newId ? encodeRef({
6556
+ accountUuid: res.destinationAccountUuid || first.accountUuid,
6557
+ mailbox: res.destination,
6558
+ id: r.newId
6559
+ }) : null,
6560
+ ...r
6561
+ }));
6562
+ });
6563
+ const results = rows.map((r) => "previousRef" in r ? r : {
6564
+ ...r,
6565
+ previousRef: r.ref,
6566
+ ref: null
6567
+ });
6457
6568
  return {
6458
- moved,
6459
- failed,
6569
+ moved: rows.filter((r) => r.ok === true).length,
6570
+ failed: rows.filter((r) => r.ok === false).length,
6571
+ ...unknown ? { unknown } : {},
6460
6572
  destination,
6461
6573
  results
6462
6574
  };
6463
6575
  }
6464
6576
  async deleteMessages(refs) {
6465
6577
  const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));
6466
- const results = [];
6467
- let deleted = 0;
6468
- let failed = 0;
6469
6578
  let movedToTrash = null;
6470
- for (const [, group] of groups) {
6579
+ const { rows, unknown } = await settleGroups(groups.values(), refsOfGroup, async (group) => {
6471
6580
  const first = group[0];
6472
- if (!first) continue;
6581
+ if (!first) return [];
6473
6582
  const res = await withBusyRetry(() => this.runner.run(DELETE_MESSAGES, {
6474
6583
  accountUuid: first.accountUuid,
6475
6584
  mailbox: first.mailbox,
6476
6585
  ids: group.map((r) => r.id)
6477
6586
  }));
6478
6587
  movedToTrash = res.movedToTrash;
6479
- for (const r of res.results) {
6480
- if (r.ok) deleted += 1;
6481
- else failed += 1;
6482
- results.push(r);
6483
- }
6484
- }
6588
+ return res.results.map((r) => ({
6589
+ ref: encodeRef({
6590
+ accountUuid: first.accountUuid,
6591
+ mailbox: first.mailbox,
6592
+ id: r.id
6593
+ }),
6594
+ ...r
6595
+ }));
6596
+ });
6485
6597
  return {
6486
- deleted,
6487
- failed,
6598
+ deleted: rows.filter((r) => r.ok === true).length,
6599
+ failed: rows.filter((r) => r.ok === false).length,
6600
+ ...unknown ? { unknown } : {},
6488
6601
  movedToTrash,
6489
- results
6602
+ results: rows
6490
6603
  };
6491
6604
  }
6492
6605
  /**
@@ -6660,7 +6773,16 @@ var AppleMailClient = class {
6660
6773
  * else is refused with the choices listed, and the refusal touches nothing.
6661
6774
  */
6662
6775
  async #editComposerDirectly(lane, handle, opts, attachments) {
6663
- if (!(await lane.reach()).ok) return {
6776
+ const reach = await lane.reach();
6777
+ if (!reach.ok && reach.refusal !== null) return {
6778
+ replaced: false,
6779
+ degraded: true,
6780
+ method: "inPlace",
6781
+ capability: "accessibility",
6782
+ reason: `Cupertino would not lend Mail its Accessibility driver, which is the only route into an open composer, so nothing was edited. The app said: ${reach.refusal}`,
6783
+ hint: "Open Cupertino to see why; this is not an Accessibility grant."
6784
+ };
6785
+ if (!reach.ok) return {
6664
6786
  replaced: false,
6665
6787
  degraded: true,
6666
6788
  method: "inPlace",
@@ -6740,7 +6862,15 @@ var AppleMailClient = class {
6740
6862
  reason: "Open compose windows can only be read through Cupertino's Accessibility lane, and this server was not started by Cupertino. Nothing was read, so this does NOT mean no draft is open.",
6741
6863
  hint: "Run the Mail server from Cupertino.app to use this tool."
6742
6864
  };
6743
- if (!(await this.#ax.reach()).ok) return {
6865
+ const reach = await this.#ax.reach();
6866
+ if (!reach.ok && reach.refusal !== null) return {
6867
+ degraded: true,
6868
+ capability: "accessibility",
6869
+ drafts: [],
6870
+ reason: `Cupertino would not lend its Accessibility driver, so nothing was checked — this does NOT mean no draft is open. The app said: ${reach.refusal}`,
6871
+ hint: "Open Cupertino to see why; this is not an Accessibility grant."
6872
+ };
6873
+ if (!reach.ok) return {
6744
6874
  degraded: true,
6745
6875
  capability: "accessibility",
6746
6876
  drafts: [],
@@ -7276,7 +7406,8 @@ const buildDiagnostics = async (client, ctx) => {
7276
7406
  ...composer.windows ? { composerWindowsSeen: composer.windows } : {},
7277
7407
  composerLane: client.composerLane,
7278
7408
  ...axReach ? {
7279
- composerAxRead: axReach.ok ? "granted" : "denied",
7409
+ composerAxRead: axReach.ok ? "granted" : axReach.refusal === null ? "denied" : "refused",
7410
+ ...axReach.refusal === null ? {} : { composerAxRefusal: axReach.refusal },
7280
7411
  ...axReach.windows ? { composerAxWindowsSeen: axReach.windows } : {}
7281
7412
  } : {},
7282
7413
  ...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." } : {},
@@ -7755,7 +7886,7 @@ const registerMessageTools = (server, client, allowWrites) => {
7755
7886
  annotations: { readOnlyHint: true }
7756
7887
  }, async ({ quoteChars }) => wrap(async () => client.listOpenDrafts({ quoteChars })));
7757
7888
  server.registerTool("apple_mail_get_message_source", {
7758
- description: "Get the raw RFC 5322 source of a message — every header and the undecoded body. Use this for header forensics (Received chains, SPF/DKIM/DMARC results, List-Unsubscribe), not for reading mail: apple_mail_get_message gives you the readable version without the noise. Capped and pageable via offset.",
7889
+ description: "Get the raw RFC 5322 source of a message — every header and the undecoded body. Use this for header forensics (Received chains, SPF/DKIM/DMARC results, List-Unsubscribe), not for reading mail: apple_mail_get_message gives you the readable version without the noise. Capped and pageable in UTF-8 bytes: while truncated is true, pass the returned nextOffset as offset for the next page. Pages never split a character.",
7759
7890
  inputSchema: z.object({
7760
7891
  ref: messageRefArg,
7761
7892
  offset: z.number().int().min(0).optional().describe("Byte offset to start from. Default 0."),
@@ -8750,4 +8881,4 @@ const createServer = (opts) => {
8750
8881
  //#endregion
8751
8882
  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 };
8752
8883
 
8753
- //# sourceMappingURL=server-D-UcpTRv.js.map
8884
+ //# sourceMappingURL=server-CITqE3QO.js.map