@mgcrea/mcp-apple-mail 0.0.0-bootstrap → 1.3.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.
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +37 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{server-OoiI7t3N.js → server-CYFxflV5.js} +700 -91
- package/dist/server-CYFxflV5.js.map +1 -0
- package/package.json +2 -2
- package/dist/server-OoiI7t3N.js.map +0 -1
|
@@ -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: "
|
|
16
|
-
gitCommitDate: "2026-08-
|
|
15
|
+
gitCommit: "8248fc3",
|
|
16
|
+
gitCommitDate: "2026-08-26T11:35:39+02:00"
|
|
17
17
|
};
|
|
18
18
|
//#endregion
|
|
19
19
|
//#region src/client/errors.ts
|
|
@@ -1552,6 +1552,72 @@ const MOVE_MESSAGES = script(`
|
|
|
1552
1552
|
return ok({ destination: destName, destinationAccountUuid: prop(function () { return destAcct.id(); }, null), results: out });
|
|
1553
1553
|
`);
|
|
1554
1554
|
/**
|
|
1555
|
+
* Create a mailbox, on an account or in "On My Mac".
|
|
1556
|
+
*
|
|
1557
|
+
* ## Idempotent by inspection, not by catching a failure
|
|
1558
|
+
*
|
|
1559
|
+
* Mail does not refuse a second mailbox with a name one already has — depending
|
|
1560
|
+
* on the account it will either no-op or make a duplicate, and a duplicate is
|
|
1561
|
+
* not something a caller can undo from here. So this looks first and reports
|
|
1562
|
+
* `created: false` for a name that is already taken, which also makes the tool
|
|
1563
|
+
* safe to call before a move without a separate existence check.
|
|
1564
|
+
*
|
|
1565
|
+
* ## Why the result is re-read
|
|
1566
|
+
*
|
|
1567
|
+
* On an IMAP account the SERVER decides whether the name is acceptable and what
|
|
1568
|
+
* it ends up called — a leading dot, a reserved prefix, a namespace the account
|
|
1569
|
+
* cannot write to. `push` reports none of that, so the mailbox is looked up
|
|
1570
|
+
* again afterwards and its absence is an error rather than a silent success.
|
|
1571
|
+
*/
|
|
1572
|
+
const CREATE_MAILBOX = script(`
|
|
1573
|
+
var acct = null;
|
|
1574
|
+
if (p.accountUuid) {
|
|
1575
|
+
acct = findAccount(M, p.accountUuid);
|
|
1576
|
+
if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
// Local mailboxes hang off the application, account mailboxes off the account.
|
|
1580
|
+
var find = function (name) {
|
|
1581
|
+
if (acct) return resolveMailbox(acct, name);
|
|
1582
|
+
var tops = M.mailboxes();
|
|
1583
|
+
var lower = String(name).toLowerCase();
|
|
1584
|
+
for (var i = 0; i < tops.length; i++) {
|
|
1585
|
+
var box = tops[i];
|
|
1586
|
+
if (String(prop(function () { return box.name(); }, "")).toLowerCase() === lower) return box;
|
|
1587
|
+
}
|
|
1588
|
+
return null;
|
|
1589
|
+
};
|
|
1590
|
+
|
|
1591
|
+
var describe = function (box, created, note) {
|
|
1592
|
+
var out = {
|
|
1593
|
+
created: created,
|
|
1594
|
+
name: prop(function () { return box.name(); }, p.name),
|
|
1595
|
+
account: acct ? prop(function () { return acct.name(); }, null) : null,
|
|
1596
|
+
accountUuid: acct ? prop(function () { return acct.id(); }, null) : null
|
|
1597
|
+
};
|
|
1598
|
+
if (note) out.note = note;
|
|
1599
|
+
return out;
|
|
1600
|
+
};
|
|
1601
|
+
|
|
1602
|
+
var existing = find(p.name);
|
|
1603
|
+
if (existing) {
|
|
1604
|
+
return ok(describe(existing, false, "A mailbox with that name already exists; nothing was created."));
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
var mb = M.Mailbox({ name: p.name });
|
|
1608
|
+
if (acct) acct.mailboxes.push(mb); else M.mailboxes.push(mb);
|
|
1609
|
+
|
|
1610
|
+
var made = find(p.name);
|
|
1611
|
+
if (!made) {
|
|
1612
|
+
return err(
|
|
1613
|
+
"MAILBOX_NOT_CREATED",
|
|
1614
|
+
"Mail accepted the request but no mailbox named " + p.name + " exists afterwards. On an " +
|
|
1615
|
+
"IMAP account the server can reject a name without reporting an error to AppleScript."
|
|
1616
|
+
);
|
|
1617
|
+
}
|
|
1618
|
+
return ok(describe(made, true, null));
|
|
1619
|
+
`);
|
|
1620
|
+
/**
|
|
1555
1621
|
* Delete messages.
|
|
1556
1622
|
*
|
|
1557
1623
|
* Mail's `delete` honours the account's "move deleted messages to Trash"
|
|
@@ -1634,6 +1700,269 @@ const SEND_MESSAGE = script(`
|
|
|
1634
1700
|
note: "Draft window is open in Mail for review." });
|
|
1635
1701
|
`, { allowLaunch: true });
|
|
1636
1702
|
/**
|
|
1703
|
+
* Replace the body of a saved draft, by recreating it.
|
|
1704
|
+
*
|
|
1705
|
+
* ## Why recreating, when "edit the draft" is the obvious thing
|
|
1706
|
+
*
|
|
1707
|
+
* Because Mail's dictionary does not offer it, and that is measured rather than
|
|
1708
|
+
* assumed — see `docs/mail-compose.md`. A saved draft is a `message`, whose
|
|
1709
|
+
* `content` is `access="r"`. There is no `open` command and no `edit` command in
|
|
1710
|
+
* the entire suite, so nothing turns a saved draft back into the `outgoing
|
|
1711
|
+
* message` whose content IS writable. The only class that ever held a reference
|
|
1712
|
+
* from one to the other is `OLD message editor`, marked `hidden` and
|
|
1713
|
+
* "DEPRECATED - DO NOT USE".
|
|
1714
|
+
*
|
|
1715
|
+
* So the body is replaced the only way the interface allows: compose a new
|
|
1716
|
+
* message carrying the old one's recipients and the new text, and remove the
|
|
1717
|
+
* old one.
|
|
1718
|
+
*
|
|
1719
|
+
* ## The order is the safety property
|
|
1720
|
+
*
|
|
1721
|
+
* The replacement is created AND CONFIRMED PRESENT before the original is
|
|
1722
|
+
* deleted, never the other way round. A delete-then-create that fails halfway
|
|
1723
|
+
* has destroyed something the user wrote and cannot get back — this server has
|
|
1724
|
+
* no undo and Mail's Trash may not be in play, since `moveDeletedMessagesToTrash`
|
|
1725
|
+
* is per-account. If the confirmation does not come back, the original is left
|
|
1726
|
+
* exactly where it was and the caller is told there are now two.
|
|
1727
|
+
*
|
|
1728
|
+
* ## What it refuses
|
|
1729
|
+
*
|
|
1730
|
+
* Recreating cannot carry everything across, and the two things it drops are
|
|
1731
|
+
* both invisible in the result:
|
|
1732
|
+
*
|
|
1733
|
+
* * **Threading.** `In-Reply-To` and `References` are set by Mail's own
|
|
1734
|
+
* `reply` command, which needs the original message. A recreated reply
|
|
1735
|
+
* draft looks perfect and starts a new thread.
|
|
1736
|
+
* * **Attachments.** They can be read but not re-attached; the dictionary has
|
|
1737
|
+
* no verb for adding one to an outgoing message.
|
|
1738
|
+
*
|
|
1739
|
+
* Both are refused rather than silently dropped. A draft that is correct in
|
|
1740
|
+
* every visible respect except the part nobody checks is the exact failure the
|
|
1741
|
+
* compose path already learned once.
|
|
1742
|
+
*/
|
|
1743
|
+
const UPDATE_DRAFT = script(`
|
|
1744
|
+
var acct = findAccount(M, p.accountUuid);
|
|
1745
|
+
if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
|
|
1746
|
+
var mb = resolveMailbox(acct, p.mailbox);
|
|
1747
|
+
if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
|
|
1748
|
+
|
|
1749
|
+
var original;
|
|
1750
|
+
try {
|
|
1751
|
+
original = mb.messages.byId(p.id);
|
|
1752
|
+
original.subject();
|
|
1753
|
+
} catch (e) {
|
|
1754
|
+
return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/*
|
|
1758
|
+
* Find the account's Drafts mailbox.
|
|
1759
|
+
*
|
|
1760
|
+
* MEASURED, macOS 26.6: account.draftsMailbox is in the dictionary with
|
|
1761
|
+
* access="r" and raises "Can't get object." on EVERY account — iCloud, two
|
|
1762
|
+
* IMAP, one Exchange. The application-level draftsMailbox does resolve, but
|
|
1763
|
+
* it is the unified "All Drafts" smart mailbox and is not what a message
|
|
1764
|
+
* reports as its own container.
|
|
1765
|
+
*
|
|
1766
|
+
* So the name is DISCOVERED rather than guessed: every message in All Drafts
|
|
1767
|
+
* reports its real per-account mailbox, which also makes this correct on a
|
|
1768
|
+
* localised Mail where a hardcoded "Drafts" would not be. The documented
|
|
1769
|
+
* property is still tried first, so this repairs itself if Apple fixes it.
|
|
1770
|
+
*/
|
|
1771
|
+
var drafts = prop(function () { return acct.draftsMailbox(); }, null);
|
|
1772
|
+
var acctName = String(prop(function () { return acct.name(); }, ""));
|
|
1773
|
+
if (!drafts) {
|
|
1774
|
+
var all = prop(function () { return M.draftsMailbox(); }, null);
|
|
1775
|
+
var pool = all ? prop(function () { return all.messages(); }, []) : [];
|
|
1776
|
+
for (var d = 0; d < pool.length && d < 200 && !drafts; d++) {
|
|
1777
|
+
var box = prop(function () { return pool[d].mailbox(); }, null);
|
|
1778
|
+
if (!box) continue;
|
|
1779
|
+
var owner = prop(function () { return box.account().name(); }, null);
|
|
1780
|
+
if (owner === null || String(owner) !== acctName) continue;
|
|
1781
|
+
drafts = box;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
if (!drafts) {
|
|
1785
|
+
return err(
|
|
1786
|
+
"DRAFTS_MAILBOX_UNKNOWN",
|
|
1787
|
+
"The Drafts mailbox for " + acctName + " could not be identified: Mail refuses the " +
|
|
1788
|
+
"account's draftsMailbox property, and no message in All Drafts belongs to this account. " +
|
|
1789
|
+
"Nothing was changed. If the account genuinely holds no drafts, then neither does the " +
|
|
1790
|
+
"message you named."
|
|
1791
|
+
);
|
|
1792
|
+
}
|
|
1793
|
+
var draftsName = String(prop(function () { return drafts.name(); }, ""));
|
|
1794
|
+
|
|
1795
|
+
// Only a draft may be rewritten. Editing a SENT or RECEIVED message by
|
|
1796
|
+
// deleting it and writing a lookalike is not editing, it is forgery, and the
|
|
1797
|
+
// ref for one looks exactly like the ref for the other.
|
|
1798
|
+
var here = String(prop(function () { return mb.name(); }, p.mailbox));
|
|
1799
|
+
if (here.toLowerCase() !== draftsName.toLowerCase()) {
|
|
1800
|
+
return err(
|
|
1801
|
+
"NOT_A_DRAFT",
|
|
1802
|
+
"That message is in " + here + ", not in " + draftsName + ". Only an unsent draft can be " +
|
|
1803
|
+
"rewritten: doing this to a sent or received message would delete the real one and leave " +
|
|
1804
|
+
"a lookalike in its place."
|
|
1805
|
+
);
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
var attachments = prop(function () { return original.mailAttachments().length; }, 0);
|
|
1809
|
+
var headers = String(prop(function () { return original.allHeaders(); }, ""));
|
|
1810
|
+
var isReply = /^(in-reply-to|references):/im.test(headers);
|
|
1811
|
+
|
|
1812
|
+
var readAddresses = function (list) {
|
|
1813
|
+
var out = [];
|
|
1814
|
+
var items = prop(function () { return list(); }, []);
|
|
1815
|
+
for (var i = 0; i < items.length; i++) {
|
|
1816
|
+
var box = items[i];
|
|
1817
|
+
var addr = prop(function () { return box.address(); }, null);
|
|
1818
|
+
if (addr) out.push(String(addr));
|
|
1819
|
+
}
|
|
1820
|
+
return out;
|
|
1821
|
+
};
|
|
1822
|
+
var to = readAddresses(function () { return original.toRecipients(); });
|
|
1823
|
+
var cc = readAddresses(function () { return original.ccRecipients(); });
|
|
1824
|
+
var bcc = readAddresses(function () { return original.bccRecipients(); });
|
|
1825
|
+
var oldSubject = String(prop(function () { return original.subject(); }, ""));
|
|
1826
|
+
var sender = String(prop(function () { return original.sender(); }, ""));
|
|
1827
|
+
|
|
1828
|
+
// Everything the caller needs to decide what to do instead, reported on the
|
|
1829
|
+
// refusals as well as on success.
|
|
1830
|
+
var facts = {
|
|
1831
|
+
subject: oldSubject,
|
|
1832
|
+
isReply: isReply,
|
|
1833
|
+
attachments: attachments,
|
|
1834
|
+
recipientCount: to.length + cc.length + bcc.length
|
|
1835
|
+
};
|
|
1836
|
+
|
|
1837
|
+
if (isReply) {
|
|
1838
|
+
return ok({
|
|
1839
|
+
replaced: false, degraded: true, capability: "threading", draft: facts,
|
|
1840
|
+
reason:
|
|
1841
|
+
"This draft is a reply or a forward: its headers carry In-Reply-To or References, and " +
|
|
1842
|
+
"those are written by Mail's own reply command, which needs the original message. " +
|
|
1843
|
+
"Recreating it would produce a draft that looks right and starts a NEW thread.",
|
|
1844
|
+
hint:
|
|
1845
|
+
"Edit the body in Mail directly, or delete this draft and start again with " +
|
|
1846
|
+
"apple_mail_reply_to_message, which threads correctly."
|
|
1847
|
+
});
|
|
1848
|
+
}
|
|
1849
|
+
if (attachments > 0) {
|
|
1850
|
+
return ok({
|
|
1851
|
+
replaced: false, degraded: true, capability: "attachments", draft: facts,
|
|
1852
|
+
reason:
|
|
1853
|
+
"This draft carries " + attachments + " attachment(s). Mail's scripting interface can " +
|
|
1854
|
+
"read an attachment but has no verb for adding one to an outgoing message, so " +
|
|
1855
|
+
"recreating the draft would silently drop them.",
|
|
1856
|
+
hint: "Edit the body in Mail directly, which keeps the attachments."
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
var subject = p.subject === null || p.subject === undefined ? oldSubject : String(p.subject);
|
|
1861
|
+
if (!subject) {
|
|
1862
|
+
return ok({
|
|
1863
|
+
replaced: false, degraded: true, capability: "confirmation", draft: facts,
|
|
1864
|
+
reason:
|
|
1865
|
+
"This draft has no subject, and the subject is the only handle this server has for " +
|
|
1866
|
+
"finding the replacement again after Mail saves it. Without that confirmation the " +
|
|
1867
|
+
"original cannot be deleted safely, so nothing was changed.",
|
|
1868
|
+
hint: 'Pass the subject argument to give it one, or edit the draft in Mail.'
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
var replacement = M.OutgoingMessage({ subject: subject, content: p.body || "", visible: true });
|
|
1873
|
+
M.outgoingMessages.push(replacement);
|
|
1874
|
+
if (sender) { try { replacement.sender = sender; } catch (e) {} }
|
|
1875
|
+
|
|
1876
|
+
var lists = [["to", to], ["cc", cc], ["bcc", bcc]];
|
|
1877
|
+
for (var l = 0; l < lists.length; l++) {
|
|
1878
|
+
var kind = lists[l][0];
|
|
1879
|
+
var addrs = lists[l][1];
|
|
1880
|
+
for (var i = 0; i < addrs.length; i++) {
|
|
1881
|
+
if (kind === "to") replacement.toRecipients.push(M.ToRecipient({ address: addrs[i] }));
|
|
1882
|
+
else if (kind === "cc") replacement.ccRecipients.push(M.CcRecipient({ address: addrs[i] }));
|
|
1883
|
+
else replacement.bccRecipients.push(M.BccRecipient({ address: addrs[i] }));
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
pause(1.2);
|
|
1888
|
+
var unquoted = false;
|
|
1889
|
+
try { unquoted = stripCitation(subject); } catch (e) { unquoted = false; }
|
|
1890
|
+
|
|
1891
|
+
var saved = true;
|
|
1892
|
+
try { replacement.save(); } catch (e) { saved = false; }
|
|
1893
|
+
|
|
1894
|
+
// Ask the Drafts mailbox, not the object we just made: "save() did not throw"
|
|
1895
|
+
// is precisely the kind of evidence the compose path already learned not to
|
|
1896
|
+
// trust. Anything but a new row here means we must not delete the old one.
|
|
1897
|
+
var newId = null;
|
|
1898
|
+
for (var attempt = 0; attempt < 10 && newId === null; attempt++) {
|
|
1899
|
+
pause(0.4);
|
|
1900
|
+
var matches = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);
|
|
1901
|
+
for (var k = 0; k < matches.length; k++) {
|
|
1902
|
+
var mid = prop(function () { return matches[k].id(); }, null);
|
|
1903
|
+
if (mid === null || mid === p.id) continue;
|
|
1904
|
+
if (newId === null || mid > newId) newId = mid;
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
if (newId === null) {
|
|
1909
|
+
return ok({
|
|
1910
|
+
replaced: false, degraded: true, capability: "confirmation", draft: facts, saved: saved,
|
|
1911
|
+
reason:
|
|
1912
|
+
"The replacement was composed but never appeared in " + draftsName + " within four " +
|
|
1913
|
+
"seconds, so it could not be confirmed. THE ORIGINAL DRAFT WAS NOT DELETED — there are " +
|
|
1914
|
+
"now two, and the new one may still be an unsaved window on screen.",
|
|
1915
|
+
hint:
|
|
1916
|
+
"Look at Mail: save or discard the open composer, then decide which draft to keep. " +
|
|
1917
|
+
"Nothing here will delete either of them."
|
|
1918
|
+
});
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
var movesToTrash = prop(function () { return acct.moveDeletedMessagesToTrash(); }, null);
|
|
1922
|
+
var removed = true;
|
|
1923
|
+
var removeError = null;
|
|
1924
|
+
/*
|
|
1925
|
+
* Re-resolve before deleting, never reuse the original reference.
|
|
1926
|
+
*
|
|
1927
|
+
* MEASURED: on a syncing account the row id of a just-saved draft is
|
|
1928
|
+
* REWRITTEN within seconds — a probe watched a confirmed draft move from
|
|
1929
|
+
* 199625 to 199626 while the script was still running, and the reference held
|
|
1930
|
+
* across that gap failed with "Can't get object." The reference fetched at the
|
|
1931
|
+
* top of this script has been through several seconds of polling and a server
|
|
1932
|
+
* round trip by the time we get here, so it is refetched by id.
|
|
1933
|
+
*/
|
|
1934
|
+
try {
|
|
1935
|
+
M.delete(mb.messages.byId(p.id));
|
|
1936
|
+
} catch (e) {
|
|
1937
|
+
removed = false;
|
|
1938
|
+
removeError = String(e && e.message ? e.message : e);
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
// Read the id back once more: the same sync rewrite that invalidates the
|
|
1942
|
+
// original can renumber the replacement between confirmation and return.
|
|
1943
|
+
pause(0.4);
|
|
1944
|
+
var settledId = newId;
|
|
1945
|
+
var finals = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);
|
|
1946
|
+
for (var f = 0; f < finals.length; f++) {
|
|
1947
|
+
var fid = prop(function () { return finals[f].id(); }, null);
|
|
1948
|
+
if (fid !== null && fid !== p.id && (settledId === newId || fid > settledId)) settledId = fid;
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
return ok({
|
|
1952
|
+
replaced: true,
|
|
1953
|
+
newId: settledId,
|
|
1954
|
+
confirmedId: newId,
|
|
1955
|
+
draftsMailbox: draftsName,
|
|
1956
|
+
subject: subject,
|
|
1957
|
+
recipientCount: facts.recipientCount,
|
|
1958
|
+
bodyLength: String(p.body || "").length,
|
|
1959
|
+
unquoted: unquoted,
|
|
1960
|
+
originalDeleted: removed,
|
|
1961
|
+
originalMovedToTrash: removed ? movesToTrash : null,
|
|
1962
|
+
removeError: removeError
|
|
1963
|
+
});
|
|
1964
|
+
`, { allowLaunch: true });
|
|
1965
|
+
/**
|
|
1637
1966
|
* Reply to, or forward, an existing message.
|
|
1638
1967
|
*
|
|
1639
1968
|
* The body cannot go through the scripting interface. `reply` and `forward`
|
|
@@ -2631,6 +2960,54 @@ var AppleMailClient = class {
|
|
|
2631
2960
|
results
|
|
2632
2961
|
};
|
|
2633
2962
|
}
|
|
2963
|
+
/**
|
|
2964
|
+
* Create a mailbox.
|
|
2965
|
+
*
|
|
2966
|
+
* ## Why the cache is dropped afterwards
|
|
2967
|
+
*
|
|
2968
|
+
* `MailboxMap` caches each account together with its mailbox NAMES, and
|
|
2969
|
+
* `resolveMailboxName` answers out of that cache. A mailbox created here and
|
|
2970
|
+
* used as a move destination in the next call would resolve against a list
|
|
2971
|
+
* taken before it existed, so the move would fail with "no destination
|
|
2972
|
+
* mailbox" naming a mailbox this server had just made. Invalidating is not an
|
|
2973
|
+
* optimisation detail; it is what makes create-then-move work.
|
|
2974
|
+
*/
|
|
2975
|
+
async createMailbox(name, account) {
|
|
2976
|
+
const trimmed = name.trim();
|
|
2977
|
+
if (!trimmed) throw new PreconditionError("A mailbox name cannot be empty or only whitespace.");
|
|
2978
|
+
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".`);
|
|
2979
|
+
const resolved = account ? await this.mailboxes.resolveAccount(account) : null;
|
|
2980
|
+
const result = await withBusyRetry(() => this.runner.run(CREATE_MAILBOX, {
|
|
2981
|
+
name: trimmed,
|
|
2982
|
+
accountUuid: resolved?.id ?? null
|
|
2983
|
+
}));
|
|
2984
|
+
this.mailboxes.invalidate();
|
|
2985
|
+
return result;
|
|
2986
|
+
}
|
|
2987
|
+
/**
|
|
2988
|
+
* Replace a saved draft's body by recreating it.
|
|
2989
|
+
*
|
|
2990
|
+
* The refusals live in the script, next to the properties they are read from,
|
|
2991
|
+
* and come back as ordinary results carrying `replaced: false` rather than as
|
|
2992
|
+
* thrown errors — a caller that cannot rewrite this draft still wants to know
|
|
2993
|
+
* WHY, and what to do instead, and both travel better as data than as a
|
|
2994
|
+
* message string.
|
|
2995
|
+
*
|
|
2996
|
+
* What is enforced here instead is the shape of the request, before Mail is
|
|
2997
|
+
* touched at all: an empty body would silently blank a draft the user wrote,
|
|
2998
|
+
* which is the one outcome nothing downstream could distinguish from success.
|
|
2999
|
+
*/
|
|
3000
|
+
async updateDraft(ref, opts) {
|
|
3001
|
+
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.");
|
|
3002
|
+
const decoded = decodeRef(ref);
|
|
3003
|
+
return withBusyRetry(() => this.runner.run(UPDATE_DRAFT, {
|
|
3004
|
+
accountUuid: decoded.accountUuid,
|
|
3005
|
+
mailbox: decoded.mailbox,
|
|
3006
|
+
id: decoded.id,
|
|
3007
|
+
body: opts.body,
|
|
3008
|
+
subject: opts.subject ?? null
|
|
3009
|
+
}));
|
|
3010
|
+
}
|
|
2634
3011
|
async checkForNewMail(account) {
|
|
2635
3012
|
const resolved = account ? await this.mailboxes.resolveAccount(account) : null;
|
|
2636
3013
|
return this.runner.run(CHECK_FOR_NEW_MAIL, { accountUuid: resolved?.id ?? null });
|
|
@@ -2745,6 +3122,7 @@ const ConfigSchema = BaseConfigSchema.extend({
|
|
|
2745
3122
|
const loadConfig = (env = process.env) => {
|
|
2746
3123
|
const raw = {
|
|
2747
3124
|
allowWrites: parseBool(env.APPLE_MAIL_ALLOW_WRITES),
|
|
3125
|
+
exposePrompts: parseBool(env.APPLE_MAIL_EXPOSE_PROMPTS),
|
|
2748
3126
|
debug: parseBool(env.APPLE_MAIL_DEBUG),
|
|
2749
3127
|
accounts: parseList(env.APPLE_MAIL_ACCOUNTS),
|
|
2750
3128
|
mailRoot: trimmed(env.APPLE_MAIL_ROOT),
|
|
@@ -2763,12 +3141,281 @@ const loadConfig = (env = process.env) => {
|
|
|
2763
3141
|
return parseConfig(ConfigSchema, raw);
|
|
2764
3142
|
};
|
|
2765
3143
|
//#endregion
|
|
3144
|
+
//#region src/guide.ts
|
|
3145
|
+
/**
|
|
3146
|
+
* The Mail operating manual, served as `cupertino://mail/guide` and embedded
|
|
3147
|
+
* ahead of every Mail prompt.
|
|
3148
|
+
*
|
|
3149
|
+
* It is deliberately static. Everything else this server exposes depends on a
|
|
3150
|
+
* permission, a running Mail or a readable index, and can therefore fail at the
|
|
3151
|
+
* exact moment someone needs to understand what is happening. This cannot: it
|
|
3152
|
+
* is a string in the bundle, so a completely denied server still explains
|
|
3153
|
+
* itself. What it must never contain, in exchange, is anything only a probe
|
|
3154
|
+
* could know — no account names, no counts, no permission verdicts. Those live
|
|
3155
|
+
* in `cupertino://mail/diagnostics`, which is allowed to fail.
|
|
3156
|
+
*/
|
|
3157
|
+
const MAIL_GUIDE = `# Apple Mail — how to drive this server
|
|
3158
|
+
|
|
3159
|
+
## Refs are opaque
|
|
3160
|
+
|
|
3161
|
+
Every message comes back with a \`ref\` like \`m1:<accountUuid>/<mailbox>#<id>\`.
|
|
3162
|
+
Pass it back verbatim. Do not build one, parse one, or carry one across
|
|
3163
|
+
surfaces — a Mail ref means nothing to Notes or Calendar.
|
|
3164
|
+
|
|
3165
|
+
## Which tool, under which constraint
|
|
3166
|
+
|
|
3167
|
+
- **Any filter at all** — sender, subject, date bound, unread, attachments —
|
|
3168
|
+
is \`apple_mail_search_messages\`. It reads Mail's own index, so it stays fast
|
|
3169
|
+
across a six-figure archive.
|
|
3170
|
+
- **\`apple_mail_list_messages\`** is a capped listing of one mailbox in date
|
|
3171
|
+
order. It is the fallback when the index is unreadable, not the default.
|
|
3172
|
+
- **Body text** is the \`body\` argument of the search tool, and it is the one
|
|
3173
|
+
expensive path here: macOS has no body index, so it opens the message files
|
|
3174
|
+
of whatever the other filters leave. Always combine it with a narrowing
|
|
3175
|
+
filter (mailbox, sender, \`dateFrom\`).
|
|
3176
|
+
- **A conversation** is \`apple_mail_get_thread\`, not several \`get_message\`
|
|
3177
|
+
calls.
|
|
3178
|
+
- **Counts** are \`apple_mail_count_messages\`. Do not count by paging a search.
|
|
3179
|
+
|
|
3180
|
+
## \`degraded: true\` is not an empty result
|
|
3181
|
+
|
|
3182
|
+
Two failures look identical from the outside and must never be reported the
|
|
3183
|
+
same way:
|
|
3184
|
+
|
|
3185
|
+
- \`degraded: true\` with \`capability: "search-index"\` means the index could not
|
|
3186
|
+
be read — usually Full Disk Access. **Nothing was searched.**
|
|
3187
|
+
- \`degraded: true\` with \`capability: "body-scan"\` means the other filters left
|
|
3188
|
+
more messages than the scan bound allows, so **nothing was scanned**. Narrow
|
|
3189
|
+
and retry; do not report it as "no matches".
|
|
3190
|
+
|
|
3191
|
+
Say "I could not check" for both. Reporting either as "I found nothing" is the
|
|
3192
|
+
worst thing this server can be made to do, because it is indistinguishable from
|
|
3193
|
+
a real answer and quietly wrong.
|
|
3194
|
+
|
|
3195
|
+
Mailbox \`unread\` from the AppleScript lane is Mail's cached badge value and can
|
|
3196
|
+
disagree with the truth — 0 has been observed for a mailbox holding 1618 unread
|
|
3197
|
+
messages. Prefer the index; results are labelled with their source.
|
|
3198
|
+
|
|
3199
|
+
## Writes
|
|
3200
|
+
|
|
3201
|
+
Mutating tools are registered only when writes are enabled. If you cannot see
|
|
3202
|
+
\`apple_mail_send_message\`, writes are off — say so rather than describing a
|
|
3203
|
+
draft you could not create.
|
|
3204
|
+
|
|
3205
|
+
When they are on, \`sendNow\` defaults to **false** on all three compose tools:
|
|
3206
|
+
they open a draft in Mail for a human to review. That default is the safety
|
|
3207
|
+
property, so do not set \`sendNow: true\` to be helpful.
|
|
3208
|
+
|
|
3209
|
+
One trap: \`apple_mail_reply_to_message\` and \`apple_mail_forward_message\` called
|
|
3210
|
+
without a \`body\` leave an **empty** draft with the original quoted beneath.
|
|
3211
|
+
That is a blank page, not a written reply. Fill the body, or tell the user
|
|
3212
|
+
plainly that the draft is empty.
|
|
3213
|
+
`;
|
|
3214
|
+
//#endregion
|
|
3215
|
+
//#region src/prompts.ts
|
|
3216
|
+
const CTX = {
|
|
3217
|
+
surface: "mail",
|
|
3218
|
+
guide: MAIL_GUIDE
|
|
3219
|
+
};
|
|
3220
|
+
/**
|
|
3221
|
+
* Mail's workflow prompts.
|
|
3222
|
+
*
|
|
3223
|
+
* Each one exists because the ordering it encodes is not a property of any
|
|
3224
|
+
* single tool, so no tool description can hold it: triage is "search, never
|
|
3225
|
+
* page"; finding a thread is "cheap filters before the expensive body lane";
|
|
3226
|
+
* replying is "read the thread first, and a body-less reply tool leaves a blank
|
|
3227
|
+
* page". All three are rebuilt from scratch by every model in every session
|
|
3228
|
+
* otherwise.
|
|
3229
|
+
*/
|
|
3230
|
+
const registerPrompts = (server, allowWrites) => {
|
|
3231
|
+
registerWorkflowPrompt(server, CTX, {
|
|
3232
|
+
name: "apple_mail_triage",
|
|
3233
|
+
title: "Triage a mailbox",
|
|
3234
|
+
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.",
|
|
3235
|
+
argsSchema: {
|
|
3236
|
+
mailbox: promptArg("Mailbox to triage, e.g. \"INBOX\". Omit for the default inbox."),
|
|
3237
|
+
account: promptArg("Account display name or UUID. Omit to span every visible account."),
|
|
3238
|
+
since: promptArg("ISO date lower bound, e.g. 2026-08-18. Omit for the last 7 days.")
|
|
3239
|
+
},
|
|
3240
|
+
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"}.
|
|
3241
|
+
|
|
3242
|
+
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.
|
|
3243
|
+
2. Group by sender and thread. Use \`apple_mail_get_thread\` where a subject
|
|
3244
|
+
recurs, so a five-message exchange is read once, not five times.
|
|
3245
|
+
3. Sort into: **needs a reply from me**, **waiting on someone else**, **for
|
|
3246
|
+
information**, **ignorable**. Put anything with a date or a commitment in it
|
|
3247
|
+
at the top, and say what the commitment is.
|
|
3248
|
+
4. Read bodies only for the messages that reach the first two groups. Subjects
|
|
3249
|
+
and senders decide the other two.
|
|
3250
|
+
|
|
3251
|
+
Report what you found. Do not flag, move, delete or reply to anything — if an
|
|
3252
|
+
action looks obviously right, propose it and let the user say yes.
|
|
3253
|
+
|
|
3254
|
+
If any call comes back \`degraded: true\`, stop and say which mailbox you could
|
|
3255
|
+
not read and why. An unread index is not an empty inbox.`
|
|
3256
|
+
});
|
|
3257
|
+
registerWorkflowPrompt(server, CTX, {
|
|
3258
|
+
name: "apple_mail_find_thread",
|
|
3259
|
+
title: "Find a thread about something",
|
|
3260
|
+
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.",
|
|
3261
|
+
argsSchema: {
|
|
3262
|
+
about: requiredPromptArg("What the thread is about, in whatever words the user used, e.g. \"the Atlas pricing thread\"."),
|
|
3263
|
+
since: promptArg("ISO date lower bound, if the user knows roughly when. Omit if not.")
|
|
3264
|
+
},
|
|
3265
|
+
build: ({ about, since }) => `Find the mail thread about: ${about}${since ? `\n\nThe user thinks it was on or after ${since}.` : ""}
|
|
3266
|
+
|
|
3267
|
+
Spend the cheap lanes first — each of these reads the index, so run them before
|
|
3268
|
+
touching any message body:
|
|
3269
|
+
|
|
3270
|
+
1. \`apple_mail_search_messages\` with \`query\` (subject and sender) for the
|
|
3271
|
+
distinctive words. Proper nouns beat common ones.
|
|
3272
|
+
2. If that misses, try \`subject\` alone, then \`sender\` if the description names
|
|
3273
|
+
a person${since ? ", always with `dateFrom`" : ""}.
|
|
3274
|
+
3. Only if steps 1–2 come up empty, use \`body\` — and **only with a narrowing
|
|
3275
|
+
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
|
|
3276
|
+
that refusal is not "no results".
|
|
3277
|
+
|
|
3278
|
+
When you have a candidate, call \`apple_mail_get_thread\` on it and summarise the
|
|
3279
|
+
exchange: who said what, what was decided, what is outstanding.
|
|
3280
|
+
|
|
3281
|
+
If several threads match, list them with dates and participants and ask which
|
|
3282
|
+
one — do not pick for the user.`
|
|
3283
|
+
});
|
|
3284
|
+
if (!allowWrites) return;
|
|
3285
|
+
registerWorkflowPrompt(server, CTX, {
|
|
3286
|
+
name: "apple_mail_draft_reply",
|
|
3287
|
+
title: "Draft a reply",
|
|
3288
|
+
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.",
|
|
3289
|
+
argsSchema: {
|
|
3290
|
+
ref: promptArg("Message ref to reply to, from a search or list result. Omit to find it."),
|
|
3291
|
+
about: promptArg("If no ref: what the thread is about, so it can be found first."),
|
|
3292
|
+
instruction: promptArg("What the reply should say or do, e.g. \"accept, propose Thursday instead\".")
|
|
3293
|
+
},
|
|
3294
|
+
build: ({ ref, about, instruction }) => `Draft a reply${ref ? ` to ${ref}` : about ? ` to the thread about: ${about}` : ""}.${instruction ? `\n\nWhat it should say: ${instruction}` : ""}
|
|
3295
|
+
|
|
3296
|
+
${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
|
|
3297
|
+
with a narrowing filter — then read it in full with \`apple_mail_get_thread\`.
|
|
3298
|
+
If more than one thread matches, ask which before drafting.`}
|
|
3299
|
+
2. Match how this correspondent is actually written to: the greeting, the
|
|
3300
|
+
sign-off, the length, whether contractions appear. Read the user's own
|
|
3301
|
+
earlier messages in the thread for that, not just the incoming one.
|
|
3302
|
+
3. Answer every question that was actually asked. A reply that addresses the
|
|
3303
|
+
last paragraph and drops the other three is the common failure here.
|
|
3304
|
+
4. Call \`apple_mail_reply_to_message\` **with a \`body\`**. Calling it without one
|
|
3305
|
+
leaves an empty draft with the original quoted underneath — a blank page,
|
|
3306
|
+
which must never be reported as a written reply.
|
|
3307
|
+
5. Leave \`sendNow\` at its default. This produces a draft in Mail; a human
|
|
3308
|
+
decides whether it goes.
|
|
3309
|
+
|
|
3310
|
+
Then tell the user what you drafted and what you assumed, so they can correct
|
|
3311
|
+
it before sending.`
|
|
3312
|
+
});
|
|
3313
|
+
};
|
|
3314
|
+
//#endregion
|
|
2766
3315
|
//#region src/tools/util.ts
|
|
2767
3316
|
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
3317
|
const mailboxArg = z.string().optional().describe("Mailbox name, e.g. \"INBOX\", \"Sent Messages\", or \"[Gmail]/All Mail\". Gmail-style prefixes are resolved automatically.");
|
|
2769
3318
|
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
3319
|
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
3320
|
//#endregion
|
|
3321
|
+
//#region src/tools/diagnostics.ts
|
|
3322
|
+
/**
|
|
3323
|
+
* Build the report.
|
|
3324
|
+
*
|
|
3325
|
+
* Split out of the tool registration so the `cupertino://mail/diagnostics`
|
|
3326
|
+
* resource can serve the same bytes. Two renderings of one probe: duplicated,
|
|
3327
|
+
* the resource and the tool would drift, and the disagreement would surface as
|
|
3328
|
+
* "the diagnostics lied" — the one thing this file must never do.
|
|
3329
|
+
*/
|
|
3330
|
+
const buildDiagnostics = async (client, ctx) => {
|
|
3331
|
+
const lanes = await client.lanes();
|
|
3332
|
+
const located = await client.locate();
|
|
3333
|
+
const messageFile = await client.probeMessageFile();
|
|
3334
|
+
let accounts = [];
|
|
3335
|
+
let accountsError = null;
|
|
3336
|
+
try {
|
|
3337
|
+
accounts = (await client.accounts()).map((a) => ({
|
|
3338
|
+
id: a.id,
|
|
3339
|
+
name: a.name,
|
|
3340
|
+
enabled: a.enabled,
|
|
3341
|
+
type: a.accountType,
|
|
3342
|
+
emailAddresses: a.emailAddresses,
|
|
3343
|
+
mailboxCount: a.mailboxes.length,
|
|
3344
|
+
messageCaching: a.messageCaching
|
|
3345
|
+
}));
|
|
3346
|
+
} catch (err) {
|
|
3347
|
+
accountsError = err instanceof Error ? err.message : String(err);
|
|
3348
|
+
}
|
|
3349
|
+
const indexAgeSeconds = located.mtime ? Math.max(0, Math.round((Date.now() - Date.parse(located.mtime)) / 1e3)) : null;
|
|
3350
|
+
return {
|
|
3351
|
+
server: {
|
|
3352
|
+
name: BUILD_INFO.name,
|
|
3353
|
+
version: BUILD_INFO.version,
|
|
3354
|
+
gitCommit: BUILD_INFO.gitCommit,
|
|
3355
|
+
node: process.version,
|
|
3356
|
+
platform: process.platform
|
|
3357
|
+
},
|
|
3358
|
+
lanes,
|
|
3359
|
+
messageFile,
|
|
3360
|
+
bodySearch: {
|
|
3361
|
+
available: messageFile.some((p) => p.status === "ok"),
|
|
3362
|
+
via: "index narrows, message files are scanned",
|
|
3363
|
+
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.",
|
|
3364
|
+
scanBound: client.config.bodyScanMax,
|
|
3365
|
+
readBytesPerMessage: client.config.bodyScanBytes,
|
|
3366
|
+
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."
|
|
3367
|
+
},
|
|
3368
|
+
permissions: {
|
|
3369
|
+
automation: lanes.applescript === "live" ? "granted" : "denied-or-mail-not-running",
|
|
3370
|
+
fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
|
|
3371
|
+
...located.readable ? {} : { howToGrant: [
|
|
3372
|
+
"System Settings > Privacy & Security > Full Disk Access",
|
|
3373
|
+
"Add the app that launches this server (Terminal, iTerm, VS Code, Claude...), then restart it.",
|
|
3374
|
+
"Granting it to Mail.app does nothing — the reader needs the permission, not Mail."
|
|
3375
|
+
] }
|
|
3376
|
+
},
|
|
3377
|
+
mailData: {
|
|
3378
|
+
root: located.mailRoot,
|
|
3379
|
+
dataVersion: located.dataVersion,
|
|
3380
|
+
envelopeIndex: located.envelopeIndexPath,
|
|
3381
|
+
foundVia: located.strategy,
|
|
3382
|
+
exists: located.exists,
|
|
3383
|
+
readable: located.readable,
|
|
3384
|
+
sizeBytes: located.sizeBytes,
|
|
3385
|
+
indexAgeSeconds,
|
|
3386
|
+
walPresent: located.walPresent,
|
|
3387
|
+
walSizeBytes: located.walSizeBytes,
|
|
3388
|
+
reason: located.reason
|
|
3389
|
+
},
|
|
3390
|
+
settings: {
|
|
3391
|
+
allowWrites: ctx.allowWrites,
|
|
3392
|
+
exposePrompts: client.config.exposePrompts,
|
|
3393
|
+
accountAllowlist: client.config.accounts.length ? client.config.accounts : "(all accounts)",
|
|
3394
|
+
indexMode: client.config.indexMode,
|
|
3395
|
+
degradedMaxMessages: client.config.degradedMaxMessages,
|
|
3396
|
+
bodyScanMax: client.config.bodyScanMax,
|
|
3397
|
+
maxResults: client.config.maxResults,
|
|
3398
|
+
attachmentDir: client.config.attachmentDir
|
|
3399
|
+
},
|
|
3400
|
+
accounts,
|
|
3401
|
+
...accountsError ? { accountsError } : {},
|
|
3402
|
+
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."]
|
|
3403
|
+
};
|
|
3404
|
+
};
|
|
3405
|
+
/**
|
|
3406
|
+
* The first tool anyone should call when something looks wrong. Every
|
|
3407
|
+
* permission this server depends on is invisible until you ask for it, and the
|
|
3408
|
+
* failure modes (a TCC denial, a stale index, a mailbox that reports zero
|
|
3409
|
+
* unread) all look like "the tool is broken" from the outside.
|
|
3410
|
+
*/
|
|
3411
|
+
const registerDiagnosticsTools = (server, client, ctx) => {
|
|
3412
|
+
server.registerTool("apple_mail_diagnostics", {
|
|
3413
|
+
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.",
|
|
3414
|
+
inputSchema: {},
|
|
3415
|
+
annotations: { readOnlyHint: true }
|
|
3416
|
+
}, async () => wrap(() => buildDiagnostics(client, ctx)));
|
|
3417
|
+
};
|
|
3418
|
+
//#endregion
|
|
2772
3419
|
//#region src/tools/accounts.ts
|
|
2773
3420
|
/**
|
|
2774
3421
|
* Account and mailbox listing.
|
|
@@ -2845,6 +3492,19 @@ const registerActionTools = (server, client) => {
|
|
|
2845
3492
|
...junk === void 0 ? {} : { junk }
|
|
2846
3493
|
});
|
|
2847
3494
|
}));
|
|
3495
|
+
server.registerTool("apple_mail_create_mailbox", {
|
|
3496
|
+
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.",
|
|
3497
|
+
inputSchema: {
|
|
3498
|
+
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."),
|
|
3499
|
+
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."),
|
|
3500
|
+
confirm: confirmArg
|
|
3501
|
+
},
|
|
3502
|
+
annotations: {
|
|
3503
|
+
readOnlyHint: false,
|
|
3504
|
+
destructiveHint: false,
|
|
3505
|
+
idempotentHint: true
|
|
3506
|
+
}
|
|
3507
|
+
}, async ({ name, account }) => wrap(async () => client.createMailbox(name, account)));
|
|
2848
3508
|
server.registerTool("apple_mail_move_messages", {
|
|
2849
3509
|
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
3510
|
inputSchema: {
|
|
@@ -2983,94 +3643,23 @@ const registerComposeTools = (server, client) => {
|
|
|
2983
3643
|
sendNow: sendNow ?? false
|
|
2984
3644
|
});
|
|
2985
3645
|
}));
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
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);
|
|
3646
|
+
server.registerTool("apple_mail_update_draft", {
|
|
3647
|
+
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`.",
|
|
3648
|
+
inputSchema: {
|
|
3649
|
+
ref: messageRefArg,
|
|
3650
|
+
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."),
|
|
3651
|
+
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."),
|
|
3652
|
+
confirm: confirmArg
|
|
3653
|
+
},
|
|
3654
|
+
annotations: {
|
|
3655
|
+
readOnlyHint: false,
|
|
3656
|
+
destructiveHint: true,
|
|
3657
|
+
idempotentHint: false
|
|
3018
3658
|
}
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
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
|
-
}));
|
|
3659
|
+
}, async ({ ref, body, subject }) => wrap(async () => client.updateDraft(ref, {
|
|
3660
|
+
body,
|
|
3661
|
+
...subject ? { subject } : {}
|
|
3662
|
+
})));
|
|
3074
3663
|
};
|
|
3075
3664
|
//#endregion
|
|
3076
3665
|
//#region src/tools/messages.ts
|
|
@@ -3339,6 +3928,26 @@ const createServer = (opts) => {
|
|
|
3339
3928
|
...opts.osascript ? { osascript: opts.osascript } : {}
|
|
3340
3929
|
});
|
|
3341
3930
|
registerTools(server, client, { allowWrites: config.allowWrites });
|
|
3931
|
+
if (config.exposePrompts) {
|
|
3932
|
+
registerPrompts(server, config.allowWrites);
|
|
3933
|
+
registerSurfaceResources(server, {
|
|
3934
|
+
surface: "mail",
|
|
3935
|
+
displayName: "Mail",
|
|
3936
|
+
guide: MAIL_GUIDE,
|
|
3937
|
+
diagnostics: () => buildDiagnostics(client, { allowWrites: config.allowWrites }),
|
|
3938
|
+
inventory: {
|
|
3939
|
+
describes: "accounts and mailboxes",
|
|
3940
|
+
read: async () => (await client.accounts()).map((a) => ({
|
|
3941
|
+
id: a.id,
|
|
3942
|
+
name: a.name,
|
|
3943
|
+
enabled: a.enabled,
|
|
3944
|
+
type: a.accountType,
|
|
3945
|
+
emailAddresses: a.emailAddresses,
|
|
3946
|
+
mailboxes: a.mailboxes
|
|
3947
|
+
}))
|
|
3948
|
+
}
|
|
3949
|
+
});
|
|
3950
|
+
}
|
|
3342
3951
|
return {
|
|
3343
3952
|
server,
|
|
3344
3953
|
client
|
|
@@ -3347,4 +3956,4 @@ const createServer = (opts) => {
|
|
|
3347
3956
|
//#endregion
|
|
3348
3957
|
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
3958
|
|
|
3350
|
-
//# sourceMappingURL=server-
|
|
3959
|
+
//# sourceMappingURL=server-CYFxflV5.js.map
|