@mgcrea/mcp-apple-mail 0.0.0-bootstrap → 1.3.1

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, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, detectEpoch, escapeLike, fingerprintSchema, inspectFile, limitArg, mapOsaError, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, readPackageIdentity, tableMap, trimmed, withBusyRetry, wrap } from "@mgcrea/mcp-apple-core";
1
+ import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, detectEpoch, escapeLike, fingerprintSchema, inspectFile, limitArg, mapOsaError, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, tableMap, trimmed, withBusyRetry, wrap } from "@mgcrea/mcp-apple-core";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -12,8 +12,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
12
12
  const BUILD_INFO = {
13
13
  name: pkg.name,
14
14
  version: pkg.version,
15
- gitCommit: "df06e7f",
16
- gitCommitDate: "2026-08-22T16:20:23+02:00"
15
+ gitCommit: "312147f",
16
+ gitCommitDate: "2026-08-27T16:06:37+02:00"
17
17
  };
18
18
  //#endregion
19
19
  //#region src/client/errors.ts
@@ -969,6 +969,10 @@ var EnvelopeIndex = class {
969
969
  */
970
970
  const PRELUDE = `
971
971
  ObjC.import("AppKit");
972
+ // For AXIsProcessTrusted, read by composerReach. AppKit does not
973
+ // reliably pull it in, and an unbridged symbol would throw rather than
974
+ // answer.
975
+ ObjC.import("ApplicationServices");
972
976
 
973
977
  function isMailRunning() {
974
978
  var apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier("com.apple.mail");
@@ -1100,6 +1104,104 @@ function composerBodySize(body) {
1100
1104
  return prop(function () { return body.entireContents().length; }, -1);
1101
1105
  }
1102
1106
 
1107
+ /**
1108
+ * Can this process actually read Mail's UI, right now?
1109
+ *
1110
+ * Asked BEFORE a composer is opened, because the alternative is what shipped:
1111
+ * M.reply opens a window, the accessibility read fails, and the user is left
1112
+ * with an empty reply window on screen and an error telling them to close it by
1113
+ * hand. Every retry left another one. Nothing about that failure needed the
1114
+ * window to exist first -- the grants it depends on can be read in one event.
1115
+ *
1116
+ * Ground truth here is the functional read, not AXIsProcessTrusted. The two
1117
+ * disagree: MEASURED on macOS 26.6, Cupertino.app's own process reports trusted
1118
+ * while an osascript grandchild of it reports the opposite, so a gate that
1119
+ * believed the flag alone would refuse replies on a Mac where the mechanism
1120
+ * works. A window list that comes back named is proof regardless of what the
1121
+ * flag says; the flag only breaks the tie when Mail has no windows at all.
1122
+ *
1123
+ * Returns { ok, reason, windows }. The reason separates the two grants that fail
1124
+ * identically once inside a composer: "systemEvents" when System Events cannot
1125
+ * be addressed at all, "accessibility" when it can but its UI is unreadable.
1126
+ */
1127
+ function composerReach(SE) {
1128
+ try {
1129
+ SE.processes.name();
1130
+ } catch (e) {
1131
+ return { ok: false, reason: "systemEvents", windows: null };
1132
+ }
1133
+
1134
+ var names;
1135
+ try {
1136
+ var proc = SE.processes.byName("Mail");
1137
+ names = proc.windows().map(function (w) {
1138
+ try { return w.name(); } catch (e2) { return null; }
1139
+ });
1140
+ } catch (e) {
1141
+ return { ok: false, reason: "accessibility", windows: null };
1142
+ }
1143
+
1144
+ if (names.length) return { ok: true, reason: null, windows: names };
1145
+
1146
+ // Mail with no windows at all is legitimate -- everything closed down to the
1147
+ // menu bar -- so an empty list is not evidence of anything on its own, and
1148
+ // refusing on it would break a reply that would have worked.
1149
+ var trusted = false;
1150
+ try { trusted = $.AXIsProcessTrusted(); } catch (e) { trusted = false; }
1151
+ return trusted
1152
+ ? { ok: true, reason: null, windows: names }
1153
+ : { ok: false, reason: "accessibility", windows: names };
1154
+ }
1155
+
1156
+ /**
1157
+ * The sentence to say when a composer cannot be reached.
1158
+ *
1159
+ * Shared by the pre-flight and by the post-open failure so the two cannot drift
1160
+ * apart, and because the advice is identical: the reason a window is unreadable
1161
+ * is never anything the caller did.
1162
+ */
1163
+ function composerGrantMessage(mode, reach) {
1164
+ var head =
1165
+ reach.reason === "systemEvents"
1166
+ ? "Cupertino cannot address System Events at all, which is the only route into a Mail " +
1167
+ "composer, so the " + mode + " was not started and nothing was written."
1168
+ : "Cupertino cannot read Mail's windows, which is the only route into a " + mode + " " +
1169
+ "composer, so it was not started and nothing was written.";
1170
+ return (
1171
+ head +
1172
+ " Reaching a composer needs BOTH Accessibility and Automation to System Events -- the latter " +
1173
+ "a different grant from Automation to Mail, which is why every other tool still works. Both " +
1174
+ "belong to /Applications/Cupertino.app, NOT to your terminal and NOT to node: the app is the " +
1175
+ "process macOS holds responsible and every server inherits its identity. Accessibility is in " +
1176
+ "System Settings > Privacy & Security > Accessibility; Automation is under Automation. If the " +
1177
+ "app is already listed, toggle it off and on -- the grant goes stale when the bundle is " +
1178
+ "reinstalled. Then QUIT CUPERTINO AND OPEN IT AGAIN: the servers are children of the running " +
1179
+ "app, and a child started before the grant does not see it. Run apple_mail_diagnostics to " +
1180
+ "check, which reports the two grants separately and names the windows it can see."
1181
+ );
1182
+ }
1183
+
1184
+ /**
1185
+ * Close a composer this script opened, when nothing of the user's is in it.
1186
+ *
1187
+ * Only ever called on a window put on screen moments earlier and provably not
1188
+ * written to. Without it every failed attempt leaves an empty reply window
1189
+ * behind, and the errors below had to end by asking the user to clean up after
1190
+ * the tool -- for a window that only exists because the tool opened it.
1191
+ *
1192
+ * It goes through Mail's own scripting interface, which is working in every
1193
+ * state that reaches here: what fails on this path is reading the window, not
1194
+ * owning it.
1195
+ */
1196
+ function discardComposer(M, draft) {
1197
+ try {
1198
+ M.close(draft, { saving: "no" });
1199
+ return true;
1200
+ } catch (e) {
1201
+ return false;
1202
+ }
1203
+ }
1204
+
1103
1205
  /**
1104
1206
  * Find the composer Mail just opened, by the subject Mail gave it.
1105
1207
  *
@@ -1477,6 +1579,89 @@ const GET_MESSAGES = script(`
1477
1579
  * in one mailbox costs one Apple Event, not 50.
1478
1580
  */
1479
1581
  /** Set any combination of read / flagged / flagIndex / junk on a batch of ids. */
1582
+ /**
1583
+ * The two grants a composer needs, probed separately.
1584
+ *
1585
+ * `composerWindow` reaches Mail's compose window through System Events, and
1586
+ * that single call sits behind TWO different permissions: Automation from the
1587
+ * responsible process to **System Events** (a distinct TCC row from Automation
1588
+ * to Mail, which every other write tool uses), and **Accessibility** for the
1589
+ * responsible process, which is what allows reading UI elements once System
1590
+ * Events will talk at all.
1591
+ *
1592
+ * They have to be reported separately because the failure cannot tell them
1593
+ * apart. `proc.windows()` is wrapped in `prop()`, which swallows the exception
1594
+ * and yields `[]`, so a denied Automation and a denied Accessibility both
1595
+ * arrive as "no window matched" — indistinguishable from Mail genuinely not
1596
+ * having opened one. The old message named Accessibility outright and was read
1597
+ * as authoritative; it was a guess with the other two possibilities hidden.
1598
+ *
1599
+ * The identity being probed is **Cupertino.app**, not the terminal and not
1600
+ * node: `scripts/spike-app-tcc` measured that the app is its own responsible
1601
+ * process and everything beneath it inherits that. This runs under the same
1602
+ * identity as the composer code, so it answers for the process that will
1603
+ * actually be refused.
1604
+ */
1605
+ const COMPOSER_ACCESS = `
1606
+ ObjC.import("ApplicationServices");
1607
+ function run() {
1608
+ // Accessibility: reading UI elements out of another process.
1609
+ var accessibility = $.AXIsProcessTrusted() ? "granted" : "denied";
1610
+
1611
+ // Automation -> System Events: being allowed to address it at all. Distinct
1612
+ // from Automation -> Mail, and prompted for separately.
1613
+ var systemEvents = "unknown";
1614
+ var detail = null;
1615
+ try {
1616
+ var SE = Application("System Events");
1617
+ SE.processes.name();
1618
+ systemEvents = "granted";
1619
+ } catch (e) {
1620
+ var msg = String(e && e.message ? e.message : e);
1621
+ detail = msg;
1622
+ // Same vocabulary as Permissions.AutomationStatus in the app: -1743 is
1623
+ // errAEEventNotPermitted (refused), -1744 is errAEEventWouldRequireUserConsent
1624
+ // (never asked). They need different advice — one is a toggle to flip, the
1625
+ // other is a prompt nobody has seen yet — so they are not collapsed.
1626
+ if (msg.indexOf("-1743") !== -1) systemEvents = "denied";
1627
+ else if (msg.indexOf("-1744") !== -1) systemEvents = "notDetermined";
1628
+ else systemEvents = "error";
1629
+ }
1630
+
1631
+ // The functional read, which outranks both flags above.
1632
+ //
1633
+ // MEASURED, macOS 26.6: Cupertino.app's own process answers AXIsProcessTrusted
1634
+ // true while an osascript grandchild of it answers false, so the flag
1635
+ // alone cannot say whether a composer is reachable -- it is a claim about an
1636
+ // identity, and this is the thing itself. Naming a window of Mail's needs
1637
+ // exactly the grants a composer needs, and opens nothing.
1638
+ var uiRead = "unknown";
1639
+ var windows = null;
1640
+ try {
1641
+ var proc = Application("System Events").processes.byName("Mail");
1642
+ windows = proc.windows().map(function (w) {
1643
+ try { return w.name(); } catch (e) { return null; }
1644
+ });
1645
+ // No windows is not evidence: Mail closed down to the menu bar reads the
1646
+ // same as Mail we are blind to.
1647
+ uiRead = windows.length ? "granted" : "inconclusive";
1648
+ } catch (e) {
1649
+ uiRead = "denied";
1650
+ windows = null;
1651
+ }
1652
+
1653
+ return JSON.stringify({
1654
+ ok: true,
1655
+ data: {
1656
+ accessibility: accessibility,
1657
+ systemEvents: systemEvents,
1658
+ uiRead: uiRead,
1659
+ windows: windows,
1660
+ detail: detail,
1661
+ },
1662
+ });
1663
+ }
1664
+ `;
1480
1665
  const SET_FLAGS = script(`
1481
1666
  var acct = findAccount(M, p.accountUuid);
1482
1667
  if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
@@ -1552,6 +1737,72 @@ const MOVE_MESSAGES = script(`
1552
1737
  return ok({ destination: destName, destinationAccountUuid: prop(function () { return destAcct.id(); }, null), results: out });
1553
1738
  `);
1554
1739
  /**
1740
+ * Create a mailbox, on an account or in "On My Mac".
1741
+ *
1742
+ * ## Idempotent by inspection, not by catching a failure
1743
+ *
1744
+ * Mail does not refuse a second mailbox with a name one already has — depending
1745
+ * on the account it will either no-op or make a duplicate, and a duplicate is
1746
+ * not something a caller can undo from here. So this looks first and reports
1747
+ * `created: false` for a name that is already taken, which also makes the tool
1748
+ * safe to call before a move without a separate existence check.
1749
+ *
1750
+ * ## Why the result is re-read
1751
+ *
1752
+ * On an IMAP account the SERVER decides whether the name is acceptable and what
1753
+ * it ends up called — a leading dot, a reserved prefix, a namespace the account
1754
+ * cannot write to. `push` reports none of that, so the mailbox is looked up
1755
+ * again afterwards and its absence is an error rather than a silent success.
1756
+ */
1757
+ const CREATE_MAILBOX = script(`
1758
+ var acct = null;
1759
+ if (p.accountUuid) {
1760
+ acct = findAccount(M, p.accountUuid);
1761
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1762
+ }
1763
+
1764
+ // Local mailboxes hang off the application, account mailboxes off the account.
1765
+ var find = function (name) {
1766
+ if (acct) return resolveMailbox(acct, name);
1767
+ var tops = M.mailboxes();
1768
+ var lower = String(name).toLowerCase();
1769
+ for (var i = 0; i < tops.length; i++) {
1770
+ var box = tops[i];
1771
+ if (String(prop(function () { return box.name(); }, "")).toLowerCase() === lower) return box;
1772
+ }
1773
+ return null;
1774
+ };
1775
+
1776
+ var describe = function (box, created, note) {
1777
+ var out = {
1778
+ created: created,
1779
+ name: prop(function () { return box.name(); }, p.name),
1780
+ account: acct ? prop(function () { return acct.name(); }, null) : null,
1781
+ accountUuid: acct ? prop(function () { return acct.id(); }, null) : null
1782
+ };
1783
+ if (note) out.note = note;
1784
+ return out;
1785
+ };
1786
+
1787
+ var existing = find(p.name);
1788
+ if (existing) {
1789
+ return ok(describe(existing, false, "A mailbox with that name already exists; nothing was created."));
1790
+ }
1791
+
1792
+ var mb = M.Mailbox({ name: p.name });
1793
+ if (acct) acct.mailboxes.push(mb); else M.mailboxes.push(mb);
1794
+
1795
+ var made = find(p.name);
1796
+ if (!made) {
1797
+ return err(
1798
+ "MAILBOX_NOT_CREATED",
1799
+ "Mail accepted the request but no mailbox named " + p.name + " exists afterwards. On an " +
1800
+ "IMAP account the server can reject a name without reporting an error to AppleScript."
1801
+ );
1802
+ }
1803
+ return ok(describe(made, true, null));
1804
+ `);
1805
+ /**
1555
1806
  * Delete messages.
1556
1807
  *
1557
1808
  * Mail's `delete` honours the account's "move deleted messages to Trash"
@@ -1634,6 +1885,269 @@ const SEND_MESSAGE = script(`
1634
1885
  note: "Draft window is open in Mail for review." });
1635
1886
  `, { allowLaunch: true });
1636
1887
  /**
1888
+ * Replace the body of a saved draft, by recreating it.
1889
+ *
1890
+ * ## Why recreating, when "edit the draft" is the obvious thing
1891
+ *
1892
+ * Because Mail's dictionary does not offer it, and that is measured rather than
1893
+ * assumed — see `docs/mail-compose.md`. A saved draft is a `message`, whose
1894
+ * `content` is `access="r"`. There is no `open` command and no `edit` command in
1895
+ * the entire suite, so nothing turns a saved draft back into the `outgoing
1896
+ * message` whose content IS writable. The only class that ever held a reference
1897
+ * from one to the other is `OLD message editor`, marked `hidden` and
1898
+ * "DEPRECATED - DO NOT USE".
1899
+ *
1900
+ * So the body is replaced the only way the interface allows: compose a new
1901
+ * message carrying the old one's recipients and the new text, and remove the
1902
+ * old one.
1903
+ *
1904
+ * ## The order is the safety property
1905
+ *
1906
+ * The replacement is created AND CONFIRMED PRESENT before the original is
1907
+ * deleted, never the other way round. A delete-then-create that fails halfway
1908
+ * has destroyed something the user wrote and cannot get back — this server has
1909
+ * no undo and Mail's Trash may not be in play, since `moveDeletedMessagesToTrash`
1910
+ * is per-account. If the confirmation does not come back, the original is left
1911
+ * exactly where it was and the caller is told there are now two.
1912
+ *
1913
+ * ## What it refuses
1914
+ *
1915
+ * Recreating cannot carry everything across, and the two things it drops are
1916
+ * both invisible in the result:
1917
+ *
1918
+ * * **Threading.** `In-Reply-To` and `References` are set by Mail's own
1919
+ * `reply` command, which needs the original message. A recreated reply
1920
+ * draft looks perfect and starts a new thread.
1921
+ * * **Attachments.** They can be read but not re-attached; the dictionary has
1922
+ * no verb for adding one to an outgoing message.
1923
+ *
1924
+ * Both are refused rather than silently dropped. A draft that is correct in
1925
+ * every visible respect except the part nobody checks is the exact failure the
1926
+ * compose path already learned once.
1927
+ */
1928
+ const UPDATE_DRAFT = script(`
1929
+ var acct = findAccount(M, p.accountUuid);
1930
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1931
+ var mb = resolveMailbox(acct, p.mailbox);
1932
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1933
+
1934
+ var original;
1935
+ try {
1936
+ original = mb.messages.byId(p.id);
1937
+ original.subject();
1938
+ } catch (e) {
1939
+ return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
1940
+ }
1941
+
1942
+ /*
1943
+ * Find the account's Drafts mailbox.
1944
+ *
1945
+ * MEASURED, macOS 26.6: account.draftsMailbox is in the dictionary with
1946
+ * access="r" and raises "Can't get object." on EVERY account — iCloud, two
1947
+ * IMAP, one Exchange. The application-level draftsMailbox does resolve, but
1948
+ * it is the unified "All Drafts" smart mailbox and is not what a message
1949
+ * reports as its own container.
1950
+ *
1951
+ * So the name is DISCOVERED rather than guessed: every message in All Drafts
1952
+ * reports its real per-account mailbox, which also makes this correct on a
1953
+ * localised Mail where a hardcoded "Drafts" would not be. The documented
1954
+ * property is still tried first, so this repairs itself if Apple fixes it.
1955
+ */
1956
+ var drafts = prop(function () { return acct.draftsMailbox(); }, null);
1957
+ var acctName = String(prop(function () { return acct.name(); }, ""));
1958
+ if (!drafts) {
1959
+ var all = prop(function () { return M.draftsMailbox(); }, null);
1960
+ var pool = all ? prop(function () { return all.messages(); }, []) : [];
1961
+ for (var d = 0; d < pool.length && d < 200 && !drafts; d++) {
1962
+ var box = prop(function () { return pool[d].mailbox(); }, null);
1963
+ if (!box) continue;
1964
+ var owner = prop(function () { return box.account().name(); }, null);
1965
+ if (owner === null || String(owner) !== acctName) continue;
1966
+ drafts = box;
1967
+ }
1968
+ }
1969
+ if (!drafts) {
1970
+ return err(
1971
+ "DRAFTS_MAILBOX_UNKNOWN",
1972
+ "The Drafts mailbox for " + acctName + " could not be identified: Mail refuses the " +
1973
+ "account's draftsMailbox property, and no message in All Drafts belongs to this account. " +
1974
+ "Nothing was changed. If the account genuinely holds no drafts, then neither does the " +
1975
+ "message you named."
1976
+ );
1977
+ }
1978
+ var draftsName = String(prop(function () { return drafts.name(); }, ""));
1979
+
1980
+ // Only a draft may be rewritten. Editing a SENT or RECEIVED message by
1981
+ // deleting it and writing a lookalike is not editing, it is forgery, and the
1982
+ // ref for one looks exactly like the ref for the other.
1983
+ var here = String(prop(function () { return mb.name(); }, p.mailbox));
1984
+ if (here.toLowerCase() !== draftsName.toLowerCase()) {
1985
+ return err(
1986
+ "NOT_A_DRAFT",
1987
+ "That message is in " + here + ", not in " + draftsName + ". Only an unsent draft can be " +
1988
+ "rewritten: doing this to a sent or received message would delete the real one and leave " +
1989
+ "a lookalike in its place."
1990
+ );
1991
+ }
1992
+
1993
+ var attachments = prop(function () { return original.mailAttachments().length; }, 0);
1994
+ var headers = String(prop(function () { return original.allHeaders(); }, ""));
1995
+ var isReply = /^(in-reply-to|references):/im.test(headers);
1996
+
1997
+ var readAddresses = function (list) {
1998
+ var out = [];
1999
+ var items = prop(function () { return list(); }, []);
2000
+ for (var i = 0; i < items.length; i++) {
2001
+ var box = items[i];
2002
+ var addr = prop(function () { return box.address(); }, null);
2003
+ if (addr) out.push(String(addr));
2004
+ }
2005
+ return out;
2006
+ };
2007
+ var to = readAddresses(function () { return original.toRecipients(); });
2008
+ var cc = readAddresses(function () { return original.ccRecipients(); });
2009
+ var bcc = readAddresses(function () { return original.bccRecipients(); });
2010
+ var oldSubject = String(prop(function () { return original.subject(); }, ""));
2011
+ var sender = String(prop(function () { return original.sender(); }, ""));
2012
+
2013
+ // Everything the caller needs to decide what to do instead, reported on the
2014
+ // refusals as well as on success.
2015
+ var facts = {
2016
+ subject: oldSubject,
2017
+ isReply: isReply,
2018
+ attachments: attachments,
2019
+ recipientCount: to.length + cc.length + bcc.length
2020
+ };
2021
+
2022
+ if (isReply) {
2023
+ return ok({
2024
+ replaced: false, degraded: true, capability: "threading", draft: facts,
2025
+ reason:
2026
+ "This draft is a reply or a forward: its headers carry In-Reply-To or References, and " +
2027
+ "those are written by Mail's own reply command, which needs the original message. " +
2028
+ "Recreating it would produce a draft that looks right and starts a NEW thread.",
2029
+ hint:
2030
+ "Edit the body in Mail directly, or delete this draft and start again with " +
2031
+ "apple_mail_reply_to_message, which threads correctly."
2032
+ });
2033
+ }
2034
+ if (attachments > 0) {
2035
+ return ok({
2036
+ replaced: false, degraded: true, capability: "attachments", draft: facts,
2037
+ reason:
2038
+ "This draft carries " + attachments + " attachment(s). Mail's scripting interface can " +
2039
+ "read an attachment but has no verb for adding one to an outgoing message, so " +
2040
+ "recreating the draft would silently drop them.",
2041
+ hint: "Edit the body in Mail directly, which keeps the attachments."
2042
+ });
2043
+ }
2044
+
2045
+ var subject = p.subject === null || p.subject === undefined ? oldSubject : String(p.subject);
2046
+ if (!subject) {
2047
+ return ok({
2048
+ replaced: false, degraded: true, capability: "confirmation", draft: facts,
2049
+ reason:
2050
+ "This draft has no subject, and the subject is the only handle this server has for " +
2051
+ "finding the replacement again after Mail saves it. Without that confirmation the " +
2052
+ "original cannot be deleted safely, so nothing was changed.",
2053
+ hint: 'Pass the subject argument to give it one, or edit the draft in Mail.'
2054
+ });
2055
+ }
2056
+
2057
+ var replacement = M.OutgoingMessage({ subject: subject, content: p.body || "", visible: true });
2058
+ M.outgoingMessages.push(replacement);
2059
+ if (sender) { try { replacement.sender = sender; } catch (e) {} }
2060
+
2061
+ var lists = [["to", to], ["cc", cc], ["bcc", bcc]];
2062
+ for (var l = 0; l < lists.length; l++) {
2063
+ var kind = lists[l][0];
2064
+ var addrs = lists[l][1];
2065
+ for (var i = 0; i < addrs.length; i++) {
2066
+ if (kind === "to") replacement.toRecipients.push(M.ToRecipient({ address: addrs[i] }));
2067
+ else if (kind === "cc") replacement.ccRecipients.push(M.CcRecipient({ address: addrs[i] }));
2068
+ else replacement.bccRecipients.push(M.BccRecipient({ address: addrs[i] }));
2069
+ }
2070
+ }
2071
+
2072
+ pause(1.2);
2073
+ var unquoted = false;
2074
+ try { unquoted = stripCitation(subject); } catch (e) { unquoted = false; }
2075
+
2076
+ var saved = true;
2077
+ try { replacement.save(); } catch (e) { saved = false; }
2078
+
2079
+ // Ask the Drafts mailbox, not the object we just made: "save() did not throw"
2080
+ // is precisely the kind of evidence the compose path already learned not to
2081
+ // trust. Anything but a new row here means we must not delete the old one.
2082
+ var newId = null;
2083
+ for (var attempt = 0; attempt < 10 && newId === null; attempt++) {
2084
+ pause(0.4);
2085
+ var matches = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);
2086
+ for (var k = 0; k < matches.length; k++) {
2087
+ var mid = prop(function () { return matches[k].id(); }, null);
2088
+ if (mid === null || mid === p.id) continue;
2089
+ if (newId === null || mid > newId) newId = mid;
2090
+ }
2091
+ }
2092
+
2093
+ if (newId === null) {
2094
+ return ok({
2095
+ replaced: false, degraded: true, capability: "confirmation", draft: facts, saved: saved,
2096
+ reason:
2097
+ "The replacement was composed but never appeared in " + draftsName + " within four " +
2098
+ "seconds, so it could not be confirmed. THE ORIGINAL DRAFT WAS NOT DELETED — there are " +
2099
+ "now two, and the new one may still be an unsaved window on screen.",
2100
+ hint:
2101
+ "Look at Mail: save or discard the open composer, then decide which draft to keep. " +
2102
+ "Nothing here will delete either of them."
2103
+ });
2104
+ }
2105
+
2106
+ var movesToTrash = prop(function () { return acct.moveDeletedMessagesToTrash(); }, null);
2107
+ var removed = true;
2108
+ var removeError = null;
2109
+ /*
2110
+ * Re-resolve before deleting, never reuse the original reference.
2111
+ *
2112
+ * MEASURED: on a syncing account the row id of a just-saved draft is
2113
+ * REWRITTEN within seconds — a probe watched a confirmed draft move from
2114
+ * 199625 to 199626 while the script was still running, and the reference held
2115
+ * across that gap failed with "Can't get object." The reference fetched at the
2116
+ * top of this script has been through several seconds of polling and a server
2117
+ * round trip by the time we get here, so it is refetched by id.
2118
+ */
2119
+ try {
2120
+ M.delete(mb.messages.byId(p.id));
2121
+ } catch (e) {
2122
+ removed = false;
2123
+ removeError = String(e && e.message ? e.message : e);
2124
+ }
2125
+
2126
+ // Read the id back once more: the same sync rewrite that invalidates the
2127
+ // original can renumber the replacement between confirmation and return.
2128
+ pause(0.4);
2129
+ var settledId = newId;
2130
+ var finals = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);
2131
+ for (var f = 0; f < finals.length; f++) {
2132
+ var fid = prop(function () { return finals[f].id(); }, null);
2133
+ if (fid !== null && fid !== p.id && (settledId === newId || fid > settledId)) settledId = fid;
2134
+ }
2135
+
2136
+ return ok({
2137
+ replaced: true,
2138
+ newId: settledId,
2139
+ confirmedId: newId,
2140
+ draftsMailbox: draftsName,
2141
+ subject: subject,
2142
+ recipientCount: facts.recipientCount,
2143
+ bodyLength: String(p.body || "").length,
2144
+ unquoted: unquoted,
2145
+ originalDeleted: removed,
2146
+ originalMovedToTrash: removed ? movesToTrash : null,
2147
+ removeError: removeError
2148
+ });
2149
+ `, { allowLaunch: true });
2150
+ /**
1637
2151
  * Reply to, or forward, an existing message.
1638
2152
  *
1639
2153
  * The body cannot go through the scripting interface. `reply` and `forward`
@@ -1663,6 +2177,15 @@ const REPLY_OR_FORWARD = script(`
1663
2177
  return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
1664
2178
  }
1665
2179
 
2180
+ // Asked BEFORE anything is opened, and that ordering is the fix for the
2181
+ // failure this tool was best known for. The two grants below fail in exactly
2182
+ // the state where a composer is already on screen, so the old shape left an
2183
+ // empty reply window behind on every attempt and told the user to close it.
2184
+ // Nothing about the check needs the window to exist.
2185
+ var SE = Application("System Events");
2186
+ var reach = composerReach(SE);
2187
+ if (!reach.ok) return err("COMPOSER_NOT_FOUND", composerGrantMessage(p.mode, reach));
2188
+
1666
2189
  // The window is opened even when sending immediately: it is where the body
1667
2190
  // has to be typed, and sending from it sends what was verified rather than
1668
2191
  // whatever the disconnected scripting object thinks it holds.
@@ -1676,16 +2199,23 @@ const REPLY_OR_FORWARD = script(`
1676
2199
  var subject = String(prop(function () { return draft.subject(); }, ""));
1677
2200
  if (!subject) return err("COMPOSER_NOT_FOUND", "Mail did not return a composer for the " + p.mode + ".");
1678
2201
 
1679
- var SE = Application("System Events");
1680
2202
  var proc = SE.processes.byName("Mail");
1681
2203
  var win = composerWindow(proc, subject, 8000);
1682
2204
  if (!win) {
2205
+ // The pre-flight passed and this still failed, so the grants are live and
2206
+ // the window is the problem. Nothing has been typed yet, so the composer we
2207
+ // opened is ours to take back.
2208
+ var closedUnreadable = discardComposer(M, draft);
1683
2209
  return err(
1684
2210
  "COMPOSER_NOT_FOUND",
1685
2211
  "Mail was asked to open a " + p.mode + " window for \\"" + subject + "\\" and no such window " +
1686
- "appeared within 8s. If a compose window IS on screen, this Mac has not granted Accessibility " +
1687
- "to whatever runs this server, which is what reading and filling a composer needs. Nothing " +
1688
- "was written; check System Settings > Privacy & Security > Accessibility."
2212
+ "was readable within 8s, although Mail's other windows read fine — so this is not a " +
2213
+ "permission. Nothing was written. Mail may still have been opening it. The windows visible " +
2214
+ "at the time were: " + JSON.stringify(reach.windows) + ". " +
2215
+ (closedUnreadable
2216
+ ? "The composer was closed again without saving, so a retry is safe."
2217
+ : "The composer could NOT be closed from here — look for an empty " + p.mode +
2218
+ " window in Mail and close it, or a retry leaves a second one behind.")
1689
2219
  );
1690
2220
  }
1691
2221
 
@@ -1700,10 +2230,14 @@ const REPLY_OR_FORWARD = script(`
1700
2230
 
1701
2231
  var bodyArea = findBodyArea(win, 0);
1702
2232
  if (!bodyArea) {
2233
+ var closedNoBody = discardComposer(M, draft);
1703
2234
  return err(
1704
2235
  "COMPOSER_NOT_FOUND",
1705
2236
  "The " + p.mode + " window for \\"" + subject + "\\" is open, but its body cannot be reached " +
1706
- "through the accessibility interface, which is the only way into it. Nothing was written."
2237
+ "through the accessibility interface, which is the only way into it. Nothing was written. " +
2238
+ (closedNoBody
2239
+ ? "The window was closed again without saving."
2240
+ : "The window could NOT be closed from here and is still on screen.")
1707
2241
  );
1708
2242
  }
1709
2243
 
@@ -1749,12 +2283,25 @@ const REPLY_OR_FORWARD = script(`
1749
2283
 
1750
2284
  if (!bodyVerified) {
1751
2285
  restore();
2286
+ // Take the window back only when it is provably still empty. A paste that
2287
+ // landed and could not be READ is a different thing from one that never
2288
+ // landed, and closing that one would destroy the reply with no way to get
2289
+ // it back -- so it is left on screen for the user to judge.
2290
+ var landed = composerBodySize(bodyArea) !== sizeBefore;
2291
+ var closedUnverified = landed ? false : discardComposer(M, draft);
1752
2292
  return err(
1753
2293
  "DRAFT_BODY_NOT_SET",
1754
- "The " + p.mode + " window for \\"" + subject + "\\" is open and correctly addressed, but the " +
1755
- "body did not go in: reading the composer back does not show the text that was sent. The " +
1756
- "draft is EMPTY or wrong and MUST NOT be described to the user as ready. Close it in Mail " +
1757
- "before retrying, or the retry leaves a second draft behind."
2294
+ "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
2295
+ "body did not go in: reading the composer back does not show the text that was sent. It " +
2296
+ "MUST NOT be described to the user as ready. " +
2297
+ (closedUnverified
2298
+ ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2299
+ : landed
2300
+ ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2301
+ "than discarded — look at it in Mail before retrying, because a retry would paste " +
2302
+ "the reply in twice."
2303
+ : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2304
+ "leaves a second draft behind.")
1758
2305
  );
1759
2306
  }
1760
2307
  }
@@ -1997,6 +2544,30 @@ var AppleMailClient = class {
1997
2544
  });
1998
2545
  return this.#located;
1999
2546
  }
2547
+ /**
2548
+ * Whether the composer can be reached, and which grant is missing if not.
2549
+ *
2550
+ * Reported by diagnostics rather than only discovered on a failed reply.
2551
+ * Automation-to-Mail and Full Disk Access being granted says nothing about
2552
+ * either of these, and every read tool works without them — so the only
2553
+ * signal used to be a `COMPOSER_NOT_FOUND` on a window that was
2554
+ * demonstrably on screen, with no way to tell which permission was at fault.
2555
+ *
2556
+ * Never throws. A probe that cannot answer must not be the reason
2557
+ * diagnostics fails, and "unknown" is an honest third state.
2558
+ */
2559
+ async composerAccess() {
2560
+ try {
2561
+ return await this.runner.run(COMPOSER_ACCESS);
2562
+ } catch {
2563
+ return {
2564
+ accessibility: "unknown",
2565
+ systemEvents: "unknown",
2566
+ uiRead: "unknown",
2567
+ windows: null
2568
+ };
2569
+ }
2570
+ }
2000
2571
  async lanes() {
2001
2572
  /**
2002
2573
  * Probe twice before declaring the lane dead.
@@ -2631,6 +3202,54 @@ var AppleMailClient = class {
2631
3202
  results
2632
3203
  };
2633
3204
  }
3205
+ /**
3206
+ * Create a mailbox.
3207
+ *
3208
+ * ## Why the cache is dropped afterwards
3209
+ *
3210
+ * `MailboxMap` caches each account together with its mailbox NAMES, and
3211
+ * `resolveMailboxName` answers out of that cache. A mailbox created here and
3212
+ * used as a move destination in the next call would resolve against a list
3213
+ * taken before it existed, so the move would fail with "no destination
3214
+ * mailbox" naming a mailbox this server had just made. Invalidating is not an
3215
+ * optimisation detail; it is what makes create-then-move work.
3216
+ */
3217
+ async createMailbox(name, account) {
3218
+ const trimmed = name.trim();
3219
+ if (!trimmed) throw new PreconditionError("A mailbox name cannot be empty or only whitespace.");
3220
+ 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".`);
3221
+ const resolved = account ? await this.mailboxes.resolveAccount(account) : null;
3222
+ const result = await withBusyRetry(() => this.runner.run(CREATE_MAILBOX, {
3223
+ name: trimmed,
3224
+ accountUuid: resolved?.id ?? null
3225
+ }));
3226
+ this.mailboxes.invalidate();
3227
+ return result;
3228
+ }
3229
+ /**
3230
+ * Replace a saved draft's body by recreating it.
3231
+ *
3232
+ * The refusals live in the script, next to the properties they are read from,
3233
+ * and come back as ordinary results carrying `replaced: false` rather than as
3234
+ * thrown errors — a caller that cannot rewrite this draft still wants to know
3235
+ * WHY, and what to do instead, and both travel better as data than as a
3236
+ * message string.
3237
+ *
3238
+ * What is enforced here instead is the shape of the request, before Mail is
3239
+ * touched at all: an empty body would silently blank a draft the user wrote,
3240
+ * which is the one outcome nothing downstream could distinguish from success.
3241
+ */
3242
+ async updateDraft(ref, opts) {
3243
+ 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.");
3244
+ const decoded = decodeRef(ref);
3245
+ return withBusyRetry(() => this.runner.run(UPDATE_DRAFT, {
3246
+ accountUuid: decoded.accountUuid,
3247
+ mailbox: decoded.mailbox,
3248
+ id: decoded.id,
3249
+ body: opts.body,
3250
+ subject: opts.subject ?? null
3251
+ }));
3252
+ }
2634
3253
  async checkForNewMail(account) {
2635
3254
  const resolved = account ? await this.mailboxes.resolveAccount(account) : null;
2636
3255
  return this.runner.run(CHECK_FOR_NEW_MAIL, { accountUuid: resolved?.id ?? null });
@@ -2745,6 +3364,7 @@ const ConfigSchema = BaseConfigSchema.extend({
2745
3364
  const loadConfig = (env = process.env) => {
2746
3365
  const raw = {
2747
3366
  allowWrites: parseBool(env.APPLE_MAIL_ALLOW_WRITES),
3367
+ exposePrompts: parseBool(env.APPLE_MAIL_EXPOSE_PROMPTS),
2748
3368
  debug: parseBool(env.APPLE_MAIL_DEBUG),
2749
3369
  accounts: parseList(env.APPLE_MAIL_ACCOUNTS),
2750
3370
  mailRoot: trimmed(env.APPLE_MAIL_ROOT),
@@ -2763,12 +3383,287 @@ const loadConfig = (env = process.env) => {
2763
3383
  return parseConfig(ConfigSchema, raw);
2764
3384
  };
2765
3385
  //#endregion
3386
+ //#region src/guide.ts
3387
+ /**
3388
+ * The Mail operating manual, served as `cupertino://mail/guide` and embedded
3389
+ * ahead of every Mail prompt.
3390
+ *
3391
+ * It is deliberately static. Everything else this server exposes depends on a
3392
+ * permission, a running Mail or a readable index, and can therefore fail at the
3393
+ * exact moment someone needs to understand what is happening. This cannot: it
3394
+ * is a string in the bundle, so a completely denied server still explains
3395
+ * itself. What it must never contain, in exchange, is anything only a probe
3396
+ * could know — no account names, no counts, no permission verdicts. Those live
3397
+ * in `cupertino://mail/diagnostics`, which is allowed to fail.
3398
+ */
3399
+ const MAIL_GUIDE = `# Apple Mail — how to drive this server
3400
+
3401
+ ## Refs are opaque
3402
+
3403
+ Every message comes back with a \`ref\` like \`m1:<accountUuid>/<mailbox>#<id>\`.
3404
+ Pass it back verbatim. Do not build one, parse one, or carry one across
3405
+ surfaces — a Mail ref means nothing to Notes or Calendar.
3406
+
3407
+ ## Which tool, under which constraint
3408
+
3409
+ - **Any filter at all** — sender, subject, date bound, unread, attachments —
3410
+ is \`apple_mail_search_messages\`. It reads Mail's own index, so it stays fast
3411
+ across a six-figure archive.
3412
+ - **\`apple_mail_list_messages\`** is a capped listing of one mailbox in date
3413
+ order. It is the fallback when the index is unreadable, not the default.
3414
+ - **Body text** is the \`body\` argument of the search tool, and it is the one
3415
+ expensive path here: macOS has no body index, so it opens the message files
3416
+ of whatever the other filters leave. Always combine it with a narrowing
3417
+ filter (mailbox, sender, \`dateFrom\`).
3418
+ - **A conversation** is \`apple_mail_get_thread\`, not several \`get_message\`
3419
+ calls.
3420
+ - **Counts** are \`apple_mail_count_messages\`. Do not count by paging a search.
3421
+
3422
+ ## \`degraded: true\` is not an empty result
3423
+
3424
+ Two failures look identical from the outside and must never be reported the
3425
+ same way:
3426
+
3427
+ - \`degraded: true\` with \`capability: "search-index"\` means the index could not
3428
+ be read — usually Full Disk Access. **Nothing was searched.**
3429
+ - \`degraded: true\` with \`capability: "body-scan"\` means the other filters left
3430
+ more messages than the scan bound allows, so **nothing was scanned**. Narrow
3431
+ and retry; do not report it as "no matches".
3432
+
3433
+ Say "I could not check" for both. Reporting either as "I found nothing" is the
3434
+ worst thing this server can be made to do, because it is indistinguishable from
3435
+ a real answer and quietly wrong.
3436
+
3437
+ Mailbox \`unread\` from the AppleScript lane is Mail's cached badge value and can
3438
+ disagree with the truth — 0 has been observed for a mailbox holding 1618 unread
3439
+ messages. Prefer the index; results are labelled with their source.
3440
+
3441
+ ## Writes
3442
+
3443
+ Mutating tools are registered only when writes are enabled. If you cannot see
3444
+ \`apple_mail_send_message\`, writes are off — say so rather than describing a
3445
+ draft you could not create.
3446
+
3447
+ When they are on, \`sendNow\` defaults to **false** on all three compose tools:
3448
+ they open a draft in Mail for a human to review. That default is the safety
3449
+ property, so do not set \`sendNow: true\` to be helpful.
3450
+
3451
+ One trap: \`apple_mail_reply_to_message\` and \`apple_mail_forward_message\` called
3452
+ without a \`body\` leave an **empty** draft with the original quoted beneath.
3453
+ That is a blank page, not a written reply. Fill the body, or tell the user
3454
+ plainly that the draft is empty.
3455
+ `;
3456
+ //#endregion
3457
+ //#region src/prompts.ts
3458
+ const CTX = {
3459
+ surface: "mail",
3460
+ guide: MAIL_GUIDE
3461
+ };
3462
+ /**
3463
+ * Mail's workflow prompts.
3464
+ *
3465
+ * Each one exists because the ordering it encodes is not a property of any
3466
+ * single tool, so no tool description can hold it: triage is "search, never
3467
+ * page"; finding a thread is "cheap filters before the expensive body lane";
3468
+ * replying is "read the thread first, and a body-less reply tool leaves a blank
3469
+ * page". All three are rebuilt from scratch by every model in every session
3470
+ * otherwise.
3471
+ */
3472
+ const registerPrompts = (server, allowWrites) => {
3473
+ registerWorkflowPrompt(server, CTX, {
3474
+ name: "apple_mail_triage",
3475
+ title: "Triage a mailbox",
3476
+ description: "Work through what arrived and report what needs a human: who is waiting, what is committed to, what can be ignored. Read-only — it proposes, it does not file or reply.",
3477
+ argsSchema: {
3478
+ mailbox: promptArg("Mailbox to triage, e.g. \"INBOX\". Omit for the default inbox."),
3479
+ account: promptArg("Account display name or UUID. Omit to span every visible account."),
3480
+ since: promptArg("ISO date lower bound, e.g. 2026-08-18. Omit for the last 7 days.")
3481
+ },
3482
+ build: ({ mailbox, account, since }) => `Triage ${mailbox ? `the ${mailbox} mailbox` : "the inbox"}${account ? ` on the ${account} account` : ""}, covering ${since ? `everything since ${since}` : "the last 7 days"}.
3483
+
3484
+ 1. Call \`apple_mail_search_messages\` with a \`dateFrom\` bound${mailbox ? ` and \`mailbox\`` : ""}. Do not page \`apple_mail_list_messages\` — the index is what makes this fast.
3485
+ 2. Group by sender and thread. Use \`apple_mail_get_thread\` where a subject
3486
+ recurs, so a five-message exchange is read once, not five times.
3487
+ 3. Sort into: **needs a reply from me**, **waiting on someone else**, **for
3488
+ information**, **ignorable**. Put anything with a date or a commitment in it
3489
+ at the top, and say what the commitment is.
3490
+ 4. Read bodies only for the messages that reach the first two groups. Subjects
3491
+ and senders decide the other two.
3492
+
3493
+ Report what you found. Do not flag, move, delete or reply to anything — if an
3494
+ action looks obviously right, propose it and let the user say yes.
3495
+
3496
+ If any call comes back \`degraded: true\`, stop and say which mailbox you could
3497
+ not read and why. An unread index is not an empty inbox.`
3498
+ });
3499
+ registerWorkflowPrompt(server, CTX, {
3500
+ name: "apple_mail_find_thread",
3501
+ title: "Find a thread about something",
3502
+ description: "Track down a conversation from a vague description — a project name, a person, something half-remembered — spending the cheap search lanes before the expensive body lane.",
3503
+ argsSchema: {
3504
+ about: requiredPromptArg("What the thread is about, in whatever words the user used, e.g. \"the Atlas pricing thread\"."),
3505
+ since: promptArg("ISO date lower bound, if the user knows roughly when. Omit if not.")
3506
+ },
3507
+ build: ({ about, since }) => `Find the mail thread about: ${about}${since ? `\n\nThe user thinks it was on or after ${since}.` : ""}
3508
+
3509
+ Spend the cheap lanes first — each of these reads the index, so run them before
3510
+ touching any message body:
3511
+
3512
+ 1. \`apple_mail_search_messages\` with \`query\` (subject and sender) for the
3513
+ distinctive words. Proper nouns beat common ones.
3514
+ 2. If that misses, try \`subject\` alone, then \`sender\` if the description names
3515
+ a person${since ? ", always with `dateFrom`" : ""}.
3516
+ 3. Only if steps 1–2 come up empty, use \`body\` — and **only with a narrowing
3517
+ filter alongside it**${since ? " (you have a date, so use it)" : " (a mailbox, a sender, or a date bound)"}. Without one it will refuse rather than answer from a partial scan, and
3518
+ that refusal is not "no results".
3519
+
3520
+ When you have a candidate, call \`apple_mail_get_thread\` on it and summarise the
3521
+ exchange: who said what, what was decided, what is outstanding.
3522
+
3523
+ If several threads match, list them with dates and participants and ask which
3524
+ one — do not pick for the user.`
3525
+ });
3526
+ if (!allowWrites) return;
3527
+ registerWorkflowPrompt(server, CTX, {
3528
+ name: "apple_mail_draft_reply",
3529
+ title: "Draft a reply",
3530
+ description: "Read a thread properly, then leave a written draft in Mail for review. Never sends: the draft waits for a human. Requires writes to be enabled.",
3531
+ argsSchema: {
3532
+ ref: promptArg("Message ref to reply to, from a search or list result. Omit to find it."),
3533
+ about: promptArg("If no ref: what the thread is about, so it can be found first."),
3534
+ instruction: promptArg("What the reply should say or do, e.g. \"accept, propose Thursday instead\".")
3535
+ },
3536
+ build: ({ ref, about, instruction }) => `Draft a reply${ref ? ` to ${ref}` : about ? ` to the thread about: ${about}` : ""}.${instruction ? `\n\nWhat it should say: ${instruction}` : ""}
3537
+
3538
+ ${ref ? `1. Read the full exchange with \`apple_mail_get_thread\` before writing a word.` : `1. Find the thread first — \`apple_mail_search_messages\` on subject and sender, body only
3539
+ with a narrowing filter — then read it in full with \`apple_mail_get_thread\`.
3540
+ If more than one thread matches, ask which before drafting.`}
3541
+ 2. Match how this correspondent is actually written to: the greeting, the
3542
+ sign-off, the length, whether contractions appear. Read the user's own
3543
+ earlier messages in the thread for that, not just the incoming one.
3544
+ 3. Answer every question that was actually asked. A reply that addresses the
3545
+ last paragraph and drops the other three is the common failure here.
3546
+ 4. Call \`apple_mail_reply_to_message\` **with a \`body\`**. Calling it without one
3547
+ leaves an empty draft with the original quoted underneath — a blank page,
3548
+ which must never be reported as a written reply.
3549
+ 5. Leave \`sendNow\` at its default. This produces a draft in Mail; a human
3550
+ decides whether it goes.
3551
+
3552
+ Then tell the user what you drafted and what you assumed, so they can correct
3553
+ it before sending.`
3554
+ });
3555
+ };
3556
+ //#endregion
2766
3557
  //#region src/tools/util.ts
2767
3558
  const accountArg = z.string().optional().describe("Account display name (e.g. \"iCloud\") or its UUID, from apple_mail_list_accounts. Omit to span every visible account.");
2768
3559
  const mailboxArg = z.string().optional().describe("Mailbox name, e.g. \"INBOX\", \"Sent Messages\", or \"[Gmail]/All Mail\". Gmail-style prefixes are resolved automatically.");
2769
3560
  const messageRefArg = z.string().min(1).describe("An opaque message ref from a search or list result (looks like \"m1:<accountUuid>/<mailbox>#<id>\"). Do not construct one by hand.");
2770
3561
  const messageRefsArg = z.array(z.string().min(1)).min(1).max(200).describe("Message refs from a search or list result. Batched by mailbox into one round-trip each.");
2771
3562
  //#endregion
3563
+ //#region src/tools/diagnostics.ts
3564
+ /**
3565
+ * Build the report.
3566
+ *
3567
+ * Split out of the tool registration so the `cupertino://mail/diagnostics`
3568
+ * resource can serve the same bytes. Two renderings of one probe: duplicated,
3569
+ * the resource and the tool would drift, and the disagreement would surface as
3570
+ * "the diagnostics lied" — the one thing this file must never do.
3571
+ */
3572
+ const buildDiagnostics = async (client, ctx) => {
3573
+ const lanes = await client.lanes();
3574
+ const located = await client.locate();
3575
+ const messageFile = await client.probeMessageFile();
3576
+ const composer = await client.composerAccess();
3577
+ let accounts = [];
3578
+ let accountsError = null;
3579
+ try {
3580
+ accounts = (await client.accounts()).map((a) => ({
3581
+ id: a.id,
3582
+ name: a.name,
3583
+ enabled: a.enabled,
3584
+ type: a.accountType,
3585
+ emailAddresses: a.emailAddresses,
3586
+ mailboxCount: a.mailboxes.length,
3587
+ messageCaching: a.messageCaching
3588
+ }));
3589
+ } catch (err) {
3590
+ accountsError = err instanceof Error ? err.message : String(err);
3591
+ }
3592
+ const indexAgeSeconds = located.mtime ? Math.max(0, Math.round((Date.now() - Date.parse(located.mtime)) / 1e3)) : null;
3593
+ return {
3594
+ server: {
3595
+ name: BUILD_INFO.name,
3596
+ version: BUILD_INFO.version,
3597
+ gitCommit: BUILD_INFO.gitCommit,
3598
+ node: process.version,
3599
+ platform: process.platform
3600
+ },
3601
+ lanes,
3602
+ messageFile,
3603
+ bodySearch: {
3604
+ available: messageFile.some((p) => p.status === "ok"),
3605
+ via: "index narrows, message files are scanned",
3606
+ reason: messageFile.some((p) => p.status === "ok") ? null : "Body search reads .emlx files, and no account produced one. An account cached headers-only has no bodies on disk at all; otherwise this is the message-file lane failing, which the messageFile block above explains per account.",
3607
+ scanBound: client.config.bodyScanMax,
3608
+ readBytesPerMessage: client.config.bodyScanBytes,
3609
+ note: "There is no body index on macOS to use: the Envelope Index has no FTS table, and the Spotlight volume index excludes ~/Library entirely. Cost is linear in the messages left by the other filters, so a body search wants a narrowing filter."
3610
+ },
3611
+ permissions: {
3612
+ automation: lanes.applescript === "live" ? "granted" : "denied-or-mail-not-running",
3613
+ accessibility: composer.accessibility,
3614
+ automationSystemEvents: composer.systemEvents,
3615
+ composerUiRead: composer.uiRead,
3616
+ ...composer.windows ? { composerWindowsSeen: composer.windows } : {},
3617
+ ...composer.uiRead === "granted" && composer.systemEvents === "granted" ? {} : { composerNote: "Filling a Mail composer goes through System Events, which needs BOTH of the above: Automation to System Events (a different grant from Automation to Mail) and Accessibility. Until both are granted, apple_mail_reply_to_message and apple_mail_forward_message fail with COMPOSER_NOT_FOUND while every other tool works. Grant them to the Cupertino bundle that is RUNNING — not to your terminal and not to node. Automation and Full Disk Access are inherited by the servers from it; Accessibility has been measured NOT to be, so a green row is necessary and not sufficient, and `composerUiRead` above is the only line that settles it. A development build at another path does not stand in for the installed one even though they share a bundle identifier — measured. 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." },
3618
+ fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
3619
+ ...located.readable ? {} : { howToGrant: [
3620
+ "System Settings > Privacy & Security > Full Disk Access",
3621
+ "Add the app that launches this server (Terminal, iTerm, VS Code, Claude...), then restart it.",
3622
+ "Granting it to Mail.app does nothing — the reader needs the permission, not Mail."
3623
+ ] }
3624
+ },
3625
+ mailData: {
3626
+ root: located.mailRoot,
3627
+ dataVersion: located.dataVersion,
3628
+ envelopeIndex: located.envelopeIndexPath,
3629
+ foundVia: located.strategy,
3630
+ exists: located.exists,
3631
+ readable: located.readable,
3632
+ sizeBytes: located.sizeBytes,
3633
+ indexAgeSeconds,
3634
+ walPresent: located.walPresent,
3635
+ walSizeBytes: located.walSizeBytes,
3636
+ reason: located.reason
3637
+ },
3638
+ settings: {
3639
+ allowWrites: ctx.allowWrites,
3640
+ exposePrompts: client.config.exposePrompts,
3641
+ accountAllowlist: client.config.accounts.length ? client.config.accounts : "(all accounts)",
3642
+ indexMode: client.config.indexMode,
3643
+ degradedMaxMessages: client.config.degradedMaxMessages,
3644
+ bodyScanMax: client.config.bodyScanMax,
3645
+ maxResults: client.config.maxResults,
3646
+ attachmentDir: client.config.attachmentDir
3647
+ },
3648
+ accounts,
3649
+ ...accountsError ? { accountsError } : {},
3650
+ caveats: ["`messageFile` is per account on purpose: mailbox layout differs by provider, so one account's lane can be dead while another's works. `unreachable` with `fullDiskAccess: granted` means the path was wrong, not the permission.", "Mailbox `unread` from the AppleScript lane is Mail's cached badge value and can disagree with the real count (observed: 0 reported for a mailbox with 1618 unread messages). Counts are labelled with their source; prefer the index when it is live."]
3651
+ };
3652
+ };
3653
+ /**
3654
+ * The first tool anyone should call when something looks wrong. Every
3655
+ * permission this server depends on is invisible until you ask for it, and the
3656
+ * failure modes (a TCC denial, a stale index, a mailbox that reports zero
3657
+ * unread) all look like "the tool is broken" from the outside.
3658
+ */
3659
+ const registerDiagnosticsTools = (server, client, ctx) => {
3660
+ server.registerTool("apple_mail_diagnostics", {
3661
+ description: "Report what this server can currently do and why. Shows whether Mail is running, whether Automation and Full Disk Access are granted, where Mail's data lives, whether the search index is readable and how stale it is, whether the message file lane actually resolves and reads a real message per account, per-account message caching, and the active write/allowlist settings. Call this first whenever a tool returns `degraded: true` or a permission error — it names the exact System Settings pane to open.",
3662
+ inputSchema: {},
3663
+ annotations: { readOnlyHint: true }
3664
+ }, async () => wrap(() => buildDiagnostics(client, ctx)));
3665
+ };
3666
+ //#endregion
2772
3667
  //#region src/tools/accounts.ts
2773
3668
  /**
2774
3669
  * Account and mailbox listing.
@@ -2845,6 +3740,19 @@ const registerActionTools = (server, client) => {
2845
3740
  ...junk === void 0 ? {} : { junk }
2846
3741
  });
2847
3742
  }));
3743
+ server.registerTool("apple_mail_create_mailbox", {
3744
+ description: "Create a mailbox (a folder). Use this before apple_mail_move_messages when the destination does not exist yet — a move to a mailbox that is not there fails, and this is the only way to make one from here. Nest with \"/\": \"Projects/Cupertino\" creates Cupertino inside Projects. Omit `account` to create a local mailbox under On My Mac. ON A SERVER ACCOUNT (iCloud, Gmail, Exchange, any IMAP) THIS CREATES THE FOLDER ON THE SERVER: it syncs to the user's phone and every other device within seconds, and there is no delete tool here to undo it. Calling it for a name that already exists is safe and does nothing — the result says `created: false`. The name comes back as Mail re-read it, which is not always the one you asked for: an IMAP server can rename or reject it.",
3745
+ inputSchema: {
3746
+ name: z.string().min(1).describe("The mailbox name, e.g. \"Receipts\" or \"Projects/Cupertino\" for a nested one. Take the spelling of an existing parent from apple_mail_list_mailboxes."),
3747
+ account: z.string().optional().describe("Account name or UUID from apple_mail_list_accounts. Omit for a local mailbox in On My Mac, which stays on this machine."),
3748
+ confirm: confirmArg
3749
+ },
3750
+ annotations: {
3751
+ readOnlyHint: false,
3752
+ destructiveHint: false,
3753
+ idempotentHint: true
3754
+ }
3755
+ }, async ({ name, account }) => wrap(async () => client.createMailbox(name, account)));
2848
3756
  server.registerTool("apple_mail_move_messages", {
2849
3757
  description: "Move messages to another mailbox, optionally in another account. The refs you passed in are DEAD afterwards: a moved message gets a new row id, so the response returns fresh refs and reports any message it could not re-locate. Requires confirm: true.",
2850
3758
  inputSchema: {
@@ -2983,94 +3891,23 @@ const registerComposeTools = (server, client) => {
2983
3891
  sendNow: sendNow ?? false
2984
3892
  });
2985
3893
  }));
2986
- };
2987
- //#endregion
2988
- //#region src/tools/diagnostics.ts
2989
- /**
2990
- * The first tool anyone should call when something looks wrong. Every
2991
- * permission this server depends on is invisible until you ask for it, and the
2992
- * failure modes (a TCC denial, a stale index, a mailbox that reports zero
2993
- * unread) all look like "the tool is broken" from the outside.
2994
- */
2995
- const registerDiagnosticsTools = (server, client, ctx) => {
2996
- server.registerTool("apple_mail_diagnostics", {
2997
- description: "Report what this server can currently do and why. Shows whether Mail is running, whether Automation and Full Disk Access are granted, where Mail's data lives, whether the search index is readable and how stale it is, whether the message file lane actually resolves and reads a real message per account, per-account message caching, and the active write/allowlist settings. Call this first whenever a tool returns `degraded: true` or a permission error — it names the exact System Settings pane to open.",
2998
- inputSchema: {},
2999
- annotations: { readOnlyHint: true }
3000
- }, async () => wrap(async () => {
3001
- const lanes = await client.lanes();
3002
- const located = await client.locate();
3003
- const messageFile = await client.probeMessageFile();
3004
- let accounts = [];
3005
- let accountsError = null;
3006
- try {
3007
- accounts = (await client.accounts()).map((a) => ({
3008
- id: a.id,
3009
- name: a.name,
3010
- enabled: a.enabled,
3011
- type: a.accountType,
3012
- emailAddresses: a.emailAddresses,
3013
- mailboxCount: a.mailboxes.length,
3014
- messageCaching: a.messageCaching
3015
- }));
3016
- } catch (err) {
3017
- accountsError = err instanceof Error ? err.message : String(err);
3894
+ server.registerTool("apple_mail_update_draft", {
3895
+ description: "Replace the body of an unsent draft. Mail has no way to edit a saved draft — its `content` is read-only and there is no open or edit command — so this RECREATES it: a new draft with the same recipients and a new body, 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: 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 they cannot be re-attached; and on anything that is 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 the replacement cannot be confirmed the original is KEPT and you are told there are now two — never assume a clean swap without reading `replaced`.",
3896
+ inputSchema: {
3897
+ ref: messageRefArg,
3898
+ 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."),
3899
+ subject: z.string().optional().describe("A new subject. Defaults to the draft's existing one. 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."),
3900
+ confirm: confirmArg
3901
+ },
3902
+ annotations: {
3903
+ readOnlyHint: false,
3904
+ destructiveHint: true,
3905
+ idempotentHint: false
3018
3906
  }
3019
- const indexAgeSeconds = located.mtime ? Math.max(0, Math.round((Date.now() - Date.parse(located.mtime)) / 1e3)) : null;
3020
- return {
3021
- server: {
3022
- name: BUILD_INFO.name,
3023
- version: BUILD_INFO.version,
3024
- gitCommit: BUILD_INFO.gitCommit,
3025
- node: process.version,
3026
- platform: process.platform
3027
- },
3028
- lanes,
3029
- messageFile,
3030
- bodySearch: {
3031
- available: messageFile.some((p) => p.status === "ok"),
3032
- via: "index narrows, message files are scanned",
3033
- reason: messageFile.some((p) => p.status === "ok") ? null : "Body search reads .emlx files, and no account produced one. An account cached headers-only has no bodies on disk at all; otherwise this is the message-file lane failing, which the messageFile block above explains per account.",
3034
- scanBound: client.config.bodyScanMax,
3035
- readBytesPerMessage: client.config.bodyScanBytes,
3036
- note: "There is no body index on macOS to use: the Envelope Index has no FTS table, and the Spotlight volume index excludes ~/Library entirely. Cost is linear in the messages left by the other filters, so a body search wants a narrowing filter."
3037
- },
3038
- permissions: {
3039
- automation: lanes.applescript === "live" ? "granted" : "denied-or-mail-not-running",
3040
- fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
3041
- ...located.readable ? {} : { howToGrant: [
3042
- "System Settings > Privacy & Security > Full Disk Access",
3043
- "Add the app that launches this server (Terminal, iTerm, VS Code, Claude...), then restart it.",
3044
- "Granting it to Mail.app does nothing — the reader needs the permission, not Mail."
3045
- ] }
3046
- },
3047
- mailData: {
3048
- root: located.mailRoot,
3049
- dataVersion: located.dataVersion,
3050
- envelopeIndex: located.envelopeIndexPath,
3051
- foundVia: located.strategy,
3052
- exists: located.exists,
3053
- readable: located.readable,
3054
- sizeBytes: located.sizeBytes,
3055
- indexAgeSeconds,
3056
- walPresent: located.walPresent,
3057
- walSizeBytes: located.walSizeBytes,
3058
- reason: located.reason
3059
- },
3060
- settings: {
3061
- allowWrites: ctx.allowWrites,
3062
- accountAllowlist: client.config.accounts.length ? client.config.accounts : "(all accounts)",
3063
- indexMode: client.config.indexMode,
3064
- degradedMaxMessages: client.config.degradedMaxMessages,
3065
- bodyScanMax: client.config.bodyScanMax,
3066
- maxResults: client.config.maxResults,
3067
- attachmentDir: client.config.attachmentDir
3068
- },
3069
- accounts,
3070
- ...accountsError ? { accountsError } : {},
3071
- caveats: ["`messageFile` is per account on purpose: mailbox layout differs by provider, so one account's lane can be dead while another's works. `unreachable` with `fullDiskAccess: granted` means the path was wrong, not the permission.", "Mailbox `unread` from the AppleScript lane is Mail's cached badge value and can disagree with the real count (observed: 0 reported for a mailbox with 1618 unread messages). Counts are labelled with their source; prefer the index when it is live."]
3072
- };
3073
- }));
3907
+ }, async ({ ref, body, subject }) => wrap(async () => client.updateDraft(ref, {
3908
+ body,
3909
+ ...subject ? { subject } : {}
3910
+ })));
3074
3911
  };
3075
3912
  //#endregion
3076
3913
  //#region src/tools/messages.ts
@@ -3339,6 +4176,26 @@ const createServer = (opts) => {
3339
4176
  ...opts.osascript ? { osascript: opts.osascript } : {}
3340
4177
  });
3341
4178
  registerTools(server, client, { allowWrites: config.allowWrites });
4179
+ if (config.exposePrompts) {
4180
+ registerPrompts(server, config.allowWrites);
4181
+ registerSurfaceResources(server, {
4182
+ surface: "mail",
4183
+ displayName: "Mail",
4184
+ guide: MAIL_GUIDE,
4185
+ diagnostics: () => buildDiagnostics(client, { allowWrites: config.allowWrites }),
4186
+ inventory: {
4187
+ describes: "accounts and mailboxes",
4188
+ read: async () => (await client.accounts()).map((a) => ({
4189
+ id: a.id,
4190
+ name: a.name,
4191
+ enabled: a.enabled,
4192
+ type: a.accountType,
4193
+ emailAddresses: a.emailAddresses,
4194
+ mailboxes: a.mailboxes
4195
+ }))
4196
+ }
4197
+ });
4198
+ }
3342
4199
  return {
3343
4200
  server,
3344
4201
  client
@@ -3347,4 +4204,4 @@ const createServer = (opts) => {
3347
4204
  //#endregion
3348
4205
  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 };
3349
4206
 
3350
- //# sourceMappingURL=server-OoiI7t3N.js.map
4207
+ //# sourceMappingURL=server-Cs0iy6g6.js.map