@mgcrea/mcp-apple-mail 1.36.2 → 1.38.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/README.md +13 -3
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +27 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{server-ynr059Dx.js → server-D-UcpTRv.js} +417 -80
- package/dist/server-D-UcpTRv.js.map +1 -0
- package/package.json +2 -2
- package/dist/server-ynr059Dx.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, buildBaseDiagnostics, confirmArg, createOsascriptRunner, createWatches, describeAggregation, detectEpoch, escapeLike, fileIdentity, fileTrigger, fingerprintSchema, groupByArg, inspectFile, interferenceNote, isoMs, limitArg, mapOsaError, normalizeFilter, occurrenceTimestamp, openAxChannel, openReadOnly, parseBool, parseBound, parseConfig, parseIntOpt, parseList, parseSenderArgs, project, promptArg, readPackageIdentity, registerEvents, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, sameFile, selectArg, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, wrap, writeConfinedFile } from "@mgcrea/mcp-apple-core";
|
|
2
|
-
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
|
|
1
|
+
import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, PreconditionError as PreconditionError$1, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, buildBaseDiagnostics, confirmArg, createOsascriptRunner, createWatches, describeAggregation, detectEpoch, escapeLike, fileIdentity, fileTrigger, fingerprintSchema, groupByArg, inspectFile, interferenceNote, isoMs, limitArg, mapOsaError, normalizeFilter, occurrenceTimestamp, openAxChannel, openReadOnly, parseBool, parseBound, parseConfig, parseIntOpt, parseList, parseSenderArgs, project, promptArg, readPackageIdentity, registerEvents, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, sameFile, selectArg, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, wrap, writeConfinedFile } from "@mgcrea/mcp-apple-core";
|
|
2
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
3
3
|
import { homedir, tmpdir } from "node:os";
|
|
4
|
-
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
5
5
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
@@ -14,8 +14,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
|
|
|
14
14
|
const BUILD_INFO = {
|
|
15
15
|
name: pkg.name,
|
|
16
16
|
version: pkg.version,
|
|
17
|
-
gitCommit: "
|
|
18
|
-
gitCommitDate: "2026-11-
|
|
17
|
+
gitCommit: "45c3a7e",
|
|
18
|
+
gitCommitDate: "2026-11-10T15:30:40+01:00"
|
|
19
19
|
};
|
|
20
20
|
//#endregion
|
|
21
21
|
//#region src/client/errors.ts
|
|
@@ -39,6 +39,15 @@ var MessageNotFoundError = class extends AppleAutomationError {
|
|
|
39
39
|
super(`No message for ref "${ref}". It was probably moved or deleted since the search ran. Re-run the search to get a current ref.`);
|
|
40
40
|
}
|
|
41
41
|
};
|
|
42
|
+
/**
|
|
43
|
+
* An attachment whose bytes are in neither the message file nor the sidecar
|
|
44
|
+
* tree: Mail has not downloaded it. Its own class so that save_attachment can
|
|
45
|
+
* tell this case, which Mail can repair by fetching it, from the refusals
|
|
46
|
+
* (no such name, a path outside the confinement) that it must pass on.
|
|
47
|
+
*/
|
|
48
|
+
var AttachmentNotStoredError = class extends PreconditionError {
|
|
49
|
+
name = "AttachmentNotStoredError";
|
|
50
|
+
};
|
|
42
51
|
//#endregion
|
|
43
52
|
//#region src/client/locate.ts
|
|
44
53
|
const INDEX_SUFFIX = join("MailData", "Envelope Index");
|
|
@@ -577,6 +586,14 @@ const headerFilename = (disposition, contentType) => {
|
|
|
577
586
|
return null;
|
|
578
587
|
};
|
|
579
588
|
/**
|
|
589
|
+
* Whether two spellings name the same attachment.
|
|
590
|
+
*
|
|
591
|
+
* The message file, the sidecar tree on disk and Mail can each hold an accented
|
|
592
|
+
* name in NFC or NFD, so a byte comparison sends a name the list tools gave out
|
|
593
|
+
* back as "no attachment named". Mail's own download script compares NFC too.
|
|
594
|
+
*/
|
|
595
|
+
const sameAttachmentName = (a, b) => a.normalize("NFC") === b.normalize("NFC");
|
|
596
|
+
/**
|
|
580
597
|
* The RFC 2231 form, including the numbered continuations long names use.
|
|
581
598
|
*
|
|
582
599
|
* A continuation is only percent-decoded when its own segment is starred —
|
|
@@ -595,6 +612,7 @@ const extendedParam = (value, param) => {
|
|
|
595
612
|
});
|
|
596
613
|
if (segments.length === 0) return null;
|
|
597
614
|
segments.sort((a, b) => a.index - b.index);
|
|
615
|
+
if (segments.every((s) => !s.encoded)) return decodeEncodedWords(segments.map((s) => s.text).join(""));
|
|
598
616
|
let charset = null;
|
|
599
617
|
let out = "";
|
|
600
618
|
for (const [position, segment] of segments.entries()) {
|
|
@@ -1032,7 +1050,7 @@ const splitEmlx = (buf) => {
|
|
|
1032
1050
|
};
|
|
1033
1051
|
const readEmlx = (path, opts) => {
|
|
1034
1052
|
const stat = statSync(path);
|
|
1035
|
-
if (stat.size > MAX_FILE_BYTES) throw new PreconditionError(`Message file is ${stat.size} bytes, above the ${MAX_FILE_BYTES}-byte ceiling. Use apple_mail_list_attachments to see what is in it.`, {
|
|
1053
|
+
if (stat.size > MAX_FILE_BYTES) throw new PreconditionError$1(`Message file is ${stat.size} bytes, above the ${MAX_FILE_BYTES}-byte ceiling. Use apple_mail_list_attachments to see what is in it.`, {
|
|
1036
1054
|
path,
|
|
1037
1055
|
sizeBytes: stat.size
|
|
1038
1056
|
});
|
|
@@ -1139,10 +1157,16 @@ const walkParts = (part, visit) => {
|
|
|
1139
1157
|
const extractAttachment = (emlxPath, filename, rowid) => {
|
|
1140
1158
|
const root = parsePart(splitEmlx(readFileSync(emlxPath)));
|
|
1141
1159
|
let match = null;
|
|
1160
|
+
const names = [];
|
|
1142
1161
|
walkParts(root, (p) => {
|
|
1143
|
-
if (
|
|
1162
|
+
if (p.filename === null) return;
|
|
1163
|
+
names.push(p.filename);
|
|
1164
|
+
if (!match && sameAttachmentName(p.filename, filename)) match = p;
|
|
1144
1165
|
});
|
|
1145
|
-
if (!match)
|
|
1166
|
+
if (!match) {
|
|
1167
|
+
const listed = names.length > 0 ? `It lists: ${names.join(", ")}.` : "It lists none.";
|
|
1168
|
+
throw new PreconditionError$1(`No attachment named "${filename}" in this message. ${listed}`);
|
|
1169
|
+
}
|
|
1146
1170
|
const inline = partBytes(match);
|
|
1147
1171
|
if (hasContent(inline)) return {
|
|
1148
1172
|
bytes: inline,
|
|
@@ -1153,7 +1177,7 @@ const extractAttachment = (emlxPath, filename, rowid) => {
|
|
|
1153
1177
|
bytes: readFileSync(hit),
|
|
1154
1178
|
from: "sidecar"
|
|
1155
1179
|
};
|
|
1156
|
-
throw new
|
|
1180
|
+
throw new AttachmentNotStoredError(`The attachment "${filename}" is not stored locally. Either it was never downloaded, or this account caches headers only — apple_mail_diagnostics reports the caching policy per account.`, {
|
|
1157
1181
|
emlxPath,
|
|
1158
1182
|
rowid
|
|
1159
1183
|
});
|
|
@@ -1185,7 +1209,7 @@ const findNamedFile = (root, filename, depth) => {
|
|
|
1185
1209
|
if (depth > 4) return null;
|
|
1186
1210
|
for (const entry of safeReaddir(root)) {
|
|
1187
1211
|
const full = join(root, entry);
|
|
1188
|
-
if (entry
|
|
1212
|
+
if (sameAttachmentName(entry, filename)) return full;
|
|
1189
1213
|
try {
|
|
1190
1214
|
if (statSync(full).isDirectory()) {
|
|
1191
1215
|
const hit = findNamedFile(full, filename, depth + 1);
|
|
@@ -2417,6 +2441,23 @@ const SEND_MESSAGE = script(`
|
|
|
2417
2441
|
}
|
|
2418
2442
|
|
|
2419
2443
|
if (p.sendNow) {
|
|
2444
|
+
// Read back right before the send, after everything that touched the
|
|
2445
|
+
// window: a file Mail took without throwing and never attached would
|
|
2446
|
+
// otherwise go out missing. A count Mail will not give is not a shortfall.
|
|
2447
|
+
var wanted = (p.attachments || []).length;
|
|
2448
|
+
var held = wanted ? prop(function () { return msg.content.attachments.length; }, null) : 0;
|
|
2449
|
+
if (held !== null && held < wanted) {
|
|
2450
|
+
return ok({
|
|
2451
|
+
sent: false, draft: true, degraded: true, capability: "attachments",
|
|
2452
|
+
subjectLength: String(p.subject || "").length,
|
|
2453
|
+
recipientCount: (p.to || []).length + (p.cc || []).length + (p.bcc || []).length,
|
|
2454
|
+
attachments: held, attachmentsRequested: wanted,
|
|
2455
|
+
note:
|
|
2456
|
+
"Mail holds " + held + " of the " + wanted + " files asked for, so the message was " +
|
|
2457
|
+
"NOT sent. It is open in Mail as a draft: attach the missing files there and send " +
|
|
2458
|
+
"it, or close it without saving and try again."
|
|
2459
|
+
});
|
|
2460
|
+
}
|
|
2420
2461
|
msg.send();
|
|
2421
2462
|
return ok({ sent: true, unquoted: unquoted, subjectLength: String(p.subject || "").length,
|
|
2422
2463
|
recipientCount: (p.to || []).length + (p.cc || []).length + (p.bcc || []).length,
|
|
@@ -2587,10 +2628,11 @@ const UPDATE_DRAFT = script(`
|
|
|
2587
2628
|
"those are written by Mail's own reply command, which needs the original message. " +
|
|
2588
2629
|
"Recreating it would produce a draft that looks right and starts a NEW thread.",
|
|
2589
2630
|
hint:
|
|
2590
|
-
"
|
|
2591
|
-
"
|
|
2592
|
-
"
|
|
2593
|
-
"which threads correctly and leaves the composer open for
|
|
2631
|
+
"Editing a reply in its open composer window takes the Mail server run from " +
|
|
2632
|
+
"Cupertino.app, and this one is not, so no window was looked for. Run it from " +
|
|
2633
|
+
"Cupertino.app, or edit the draft in Mail directly, or delete it and start again with " +
|
|
2634
|
+
"apple_mail_reply_to_message, which threads correctly and leaves the composer open for " +
|
|
2635
|
+
"further revisions."
|
|
2594
2636
|
});
|
|
2595
2637
|
}
|
|
2596
2638
|
if (attachments > 0) {
|
|
@@ -3184,7 +3226,7 @@ const REPLY_OR_FORWARD = script(`
|
|
|
3184
3226
|
);
|
|
3185
3227
|
}
|
|
3186
3228
|
return ok({ sent: true, mode: p.mode, bodyVerified: bodyVerified,
|
|
3187
|
-
verifiedChars: verifiedChars, subject: subject });
|
|
3229
|
+
verifiedChars: verifiedChars, subject: subject, attachments: attached.count });
|
|
3188
3230
|
}
|
|
3189
3231
|
|
|
3190
3232
|
// A draft is left for the person to read, unless the setting asks otherwise.
|
|
@@ -3196,6 +3238,7 @@ const REPLY_OR_FORWARD = script(`
|
|
|
3196
3238
|
subject: subject,
|
|
3197
3239
|
bodyVerified: bodyVerified,
|
|
3198
3240
|
verifiedChars: verifiedChars,
|
|
3241
|
+
attachments: attached.count,
|
|
3199
3242
|
note: bodyVerified
|
|
3200
3243
|
? "Draft window is open in Mail for review; its body was read back out of the window and matches."
|
|
3201
3244
|
: "Draft window is open in Mail for review."
|
|
@@ -3345,6 +3388,79 @@ const OPEN_COMPOSER = script(`
|
|
|
3345
3388
|
|
|
3346
3389
|
return ok({ subject: subject });
|
|
3347
3390
|
`, { allowLaunch: true });
|
|
3391
|
+
/**
|
|
3392
|
+
* Have Mail download one attachment and save it to `p.dest`.
|
|
3393
|
+
*
|
|
3394
|
+
* Mail's `save` on a `mail attachment` that is not downloaded fetches it from
|
|
3395
|
+
* the server first, and the fetch also lands in Mail's own store: measured
|
|
3396
|
+
* 2026-11-06 on a Gmail account caching messages without attachments, a message
|
|
3397
|
+
* whose attachments were not on disk listed them `retrievable: true`, with real
|
|
3398
|
+
* sizes, after Mail had saved them this way. There is no separate download verb
|
|
3399
|
+
* in Mail's dictionary; `downloaded` is read-only.
|
|
3400
|
+
*
|
|
3401
|
+
* `p.dest` is a path in a fresh staging folder the caller made and owns. Mail's
|
|
3402
|
+
* `save` overwrites and follows symlinks, so it must never be pointed at the
|
|
3403
|
+
* user's destination; the caller moves the bytes there through the confinement.
|
|
3404
|
+
*
|
|
3405
|
+
* A name that matches nothing, or matches twice, comes back as data rather than
|
|
3406
|
+
* an error so the caller can say what Mail listed.
|
|
3407
|
+
*/
|
|
3408
|
+
const FETCH_ATTACHMENT = script(`
|
|
3409
|
+
var acct = findAccount(M, p.accountUuid);
|
|
3410
|
+
if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
|
|
3411
|
+
var mb = resolveMailbox(acct, p.mailbox);
|
|
3412
|
+
if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
|
|
3413
|
+
|
|
3414
|
+
var m;
|
|
3415
|
+
try {
|
|
3416
|
+
m = mb.messages.byId(p.id);
|
|
3417
|
+
m.id();
|
|
3418
|
+
} catch (e) {
|
|
3419
|
+
return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
|
|
3420
|
+
}
|
|
3421
|
+
|
|
3422
|
+
var wanted = String(p.filename).normalize("NFC");
|
|
3423
|
+
// Not prop(): a failed read here is not a message without attachments, and
|
|
3424
|
+
// answering "none" would tell the caller the name does not exist.
|
|
3425
|
+
var atts;
|
|
3426
|
+
try {
|
|
3427
|
+
atts = m.mailAttachments();
|
|
3428
|
+
} catch (e) {
|
|
3429
|
+
return ok({
|
|
3430
|
+
saved: false,
|
|
3431
|
+
reason: "save-failed",
|
|
3432
|
+
downloaded: null,
|
|
3433
|
+
error: "Mail could not list the message's attachments: " +
|
|
3434
|
+
String(e && e.message ? e.message : e)
|
|
3435
|
+
});
|
|
3436
|
+
}
|
|
3437
|
+
var names = [];
|
|
3438
|
+
var hits = [];
|
|
3439
|
+
for (var i = 0; i < atts.length; i++) {
|
|
3440
|
+
var a = atts[i];
|
|
3441
|
+
var name = prop(function () { return a.name(); }, null);
|
|
3442
|
+
if (name === null) continue;
|
|
3443
|
+
names.push(String(name));
|
|
3444
|
+
if (String(name).normalize("NFC") === wanted) hits.push(a);
|
|
3445
|
+
}
|
|
3446
|
+
if (hits.length === 0) return ok({ saved: false, reason: "none", names: names });
|
|
3447
|
+
if (hits.length > 1) return ok({ saved: false, reason: "ambiguous", count: hits.length });
|
|
3448
|
+
|
|
3449
|
+
var hit = hits[0];
|
|
3450
|
+
var downloaded = prop(function () { return hit.downloaded(); }, null);
|
|
3451
|
+
var fileSize = prop(function () { return hit.fileSize(); }, null);
|
|
3452
|
+
try {
|
|
3453
|
+
M.save(hit, { in: Path(p.dest) });
|
|
3454
|
+
} catch (e) {
|
|
3455
|
+
return ok({
|
|
3456
|
+
saved: false,
|
|
3457
|
+
reason: "save-failed",
|
|
3458
|
+
downloaded: downloaded,
|
|
3459
|
+
error: String(e && e.message ? e.message : e)
|
|
3460
|
+
});
|
|
3461
|
+
}
|
|
3462
|
+
return ok({ saved: true, downloaded: downloaded, fileSize: fileSize });
|
|
3463
|
+
`);
|
|
3348
3464
|
//#endregion
|
|
3349
3465
|
//#region src/client/compose.ts
|
|
3350
3466
|
/**
|
|
@@ -4319,7 +4435,7 @@ var MailboxMap = class {
|
|
|
4319
4435
|
accounts = await this.accounts(true);
|
|
4320
4436
|
found = find(accounts);
|
|
4321
4437
|
}
|
|
4322
|
-
if (!found) throw new PreconditionError(`No account "${needle}". Known accounts: ${accounts.map((a) => a.name).join(", ") || "(none visible)"}.` + (this.#allowlist.length ? " An allowlist is active (APPLE_MAIL_ACCOUNTS)." : ""));
|
|
4438
|
+
if (!found) throw new PreconditionError$1(`No account "${needle}". Known accounts: ${accounts.map((a) => a.name).join(", ") || "(none visible)"}.` + (this.#allowlist.length ? " An allowlist is active (APPLE_MAIL_ACCOUNTS)." : ""));
|
|
4323
4439
|
return found;
|
|
4324
4440
|
}
|
|
4325
4441
|
/**
|
|
@@ -4339,7 +4455,24 @@ var MailboxMap = class {
|
|
|
4339
4455
|
const hit = account.mailboxes.find((m) => m.toLowerCase() === c.toLowerCase());
|
|
4340
4456
|
if (hit) return hit;
|
|
4341
4457
|
}
|
|
4342
|
-
throw new PreconditionError(`No mailbox "${wanted}" in account "${account.name}". Available: ${account.mailboxes.join(", ")}.`);
|
|
4458
|
+
throw new PreconditionError$1(`No mailbox "${wanted}" in account "${account.name}". Available: ${account.mailboxes.join(", ")}.`);
|
|
4459
|
+
}
|
|
4460
|
+
/**
|
|
4461
|
+
* `resolveMailboxName` for a name a caller asked for, with `resolveAccount`'s
|
|
4462
|
+
* second chance: the account came out of a list that can be stale by design,
|
|
4463
|
+
* so a name it lacks earns one fresh read before it is refused. A mailbox
|
|
4464
|
+
* created in Mail, or synced from another device, since that list was taken
|
|
4465
|
+
* is then found on the first call rather than the one after.
|
|
4466
|
+
*/
|
|
4467
|
+
async resolveMailbox(account, wanted) {
|
|
4468
|
+
try {
|
|
4469
|
+
return this.resolveMailboxName(account, wanted);
|
|
4470
|
+
} catch (error) {
|
|
4471
|
+
if (!(error instanceof PreconditionError$1)) throw error;
|
|
4472
|
+
const fresh = (await this.accounts(true)).find((a) => a.id === account.id);
|
|
4473
|
+
if (!fresh) throw error;
|
|
4474
|
+
return this.resolveMailboxName(fresh, wanted);
|
|
4475
|
+
}
|
|
4343
4476
|
}
|
|
4344
4477
|
/**
|
|
4345
4478
|
* Map an Envelope Index `mailboxes.url` onto a scriptable account + mailbox.
|
|
@@ -4503,13 +4636,46 @@ const NAMED = {
|
|
|
4503
4636
|
apos: "'",
|
|
4504
4637
|
nbsp: "\xA0"
|
|
4505
4638
|
};
|
|
4506
|
-
const
|
|
4639
|
+
const decodeEntity = (whole, name) => {
|
|
4507
4640
|
if (name[0] === "#") {
|
|
4508
4641
|
const code = name[1] === "x" || name[1] === "X" ? Number.parseInt(name.slice(2), 16) : Number.parseInt(name.slice(1), 10);
|
|
4509
4642
|
return Number.isFinite(code) && code > 0 && code <= 1114111 ? String.fromCodePoint(code) : whole;
|
|
4510
4643
|
}
|
|
4511
4644
|
return NAMED[name.toLowerCase()] ?? whole;
|
|
4512
|
-
}
|
|
4645
|
+
};
|
|
4646
|
+
/**
|
|
4647
|
+
* A run's text with its entities decoded, and where each of its UTF-16 units came from in the
|
|
4648
|
+
* run, so an edit can be spliced into the source and the rest of the run kept as it was.
|
|
4649
|
+
*/
|
|
4650
|
+
const decodeEntities = (raw) => {
|
|
4651
|
+
let text = "";
|
|
4652
|
+
const at = [];
|
|
4653
|
+
let cursor = 0;
|
|
4654
|
+
const copy = (end) => {
|
|
4655
|
+
for (; cursor < end; cursor += 1) {
|
|
4656
|
+
text += raw[cursor];
|
|
4657
|
+
at.push(cursor);
|
|
4658
|
+
}
|
|
4659
|
+
};
|
|
4660
|
+
for (const entity of raw.matchAll(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi)) {
|
|
4661
|
+
const whole = entity[0];
|
|
4662
|
+
const decoded = decodeEntity(whole, entity[1]);
|
|
4663
|
+
copy(entity.index);
|
|
4664
|
+
if (decoded === whole) {
|
|
4665
|
+
copy(entity.index + whole.length);
|
|
4666
|
+
continue;
|
|
4667
|
+
}
|
|
4668
|
+
for (let unit = 0; unit < decoded.length; unit += 1) at.push(entity.index);
|
|
4669
|
+
text += decoded;
|
|
4670
|
+
cursor = entity.index + whole.length;
|
|
4671
|
+
}
|
|
4672
|
+
copy(raw.length);
|
|
4673
|
+
at.push(raw.length);
|
|
4674
|
+
return {
|
|
4675
|
+
text,
|
|
4676
|
+
at
|
|
4677
|
+
};
|
|
4678
|
+
};
|
|
4513
4679
|
const encodeText = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\xA0", " ");
|
|
4514
4680
|
/**
|
|
4515
4681
|
* A replacement's text as HTML: encoded, and each line break it carries a
|
|
@@ -4530,7 +4696,7 @@ const tokenize = (html) => {
|
|
|
4530
4696
|
if (text) tokens.push({
|
|
4531
4697
|
kind: "text",
|
|
4532
4698
|
raw: text,
|
|
4533
|
-
|
|
4699
|
+
...decodeEntities(text)
|
|
4534
4700
|
});
|
|
4535
4701
|
text = "";
|
|
4536
4702
|
};
|
|
@@ -4622,15 +4788,15 @@ const applyHtmlEdits = (edits, html) => {
|
|
|
4622
4788
|
});
|
|
4623
4789
|
}
|
|
4624
4790
|
const edited = /* @__PURE__ */ new Map();
|
|
4625
|
-
for (const
|
|
4626
|
-
const
|
|
4627
|
-
let
|
|
4791
|
+
for (const index of new Set(placed.map((p) => p.token))) {
|
|
4792
|
+
const { raw, at } = tokens[index];
|
|
4793
|
+
let spliced = "";
|
|
4628
4794
|
let cursor = 0;
|
|
4629
|
-
for (const p of placed.filter((q) => q.token ===
|
|
4630
|
-
|
|
4795
|
+
for (const p of placed.filter((q) => q.token === index).toSorted((a, b) => a.start - b.start)) {
|
|
4796
|
+
spliced += raw.slice(at[cursor], at[p.start]) + encodeReplacement(p.replace);
|
|
4631
4797
|
cursor = p.end;
|
|
4632
4798
|
}
|
|
4633
|
-
edited.set(
|
|
4799
|
+
edited.set(index, spliced + raw.slice(at[cursor]));
|
|
4634
4800
|
}
|
|
4635
4801
|
const out = tokens.map((token, at) => edited.get(at) ?? token.raw).join("");
|
|
4636
4802
|
return {
|
|
@@ -4974,6 +5140,7 @@ const rebuildDraft = async (deps, target, opts) => {
|
|
|
4974
5140
|
const found = await awaitNewComposer(lane, before, deps.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS, opened.subject);
|
|
4975
5141
|
if (found === null || "ambiguous" in found) return refuse("composer", found === null ? `Mail was asked to open a ${kind} for "${opened.subject}", and no new window under that title was readable in time. Nothing was filled. The original draft was not changed.` : `Mail was asked to open a ${kind} for "${opened.subject}", and ` + (found.ambiguous.length === 1 ? `the one new window under that title (${found.ambiguous[0]}) could not be told from the composer already open under it. ` : `${found.ambiguous.length} new windows under that title appeared (${found.ambiguous.join(", ")}), so which one is it cannot be told. `) + "Nothing was filled. The original draft was not changed.", `Look for an empty ${kind} window in Mail and close it without saving.`);
|
|
4976
5142
|
handle = found.handle;
|
|
5143
|
+
if (squash(opened.subject) !== squash(subject)) return refuse("subject", `Mail did not take the subject: it was given "${subject}" and the new ${kind} holds "${opened.subject}". Nothing was filled. ${leftOpen(handle)}`, closeIt, { composer: handle });
|
|
4977
5144
|
const wanted = recipients;
|
|
4978
5145
|
const got = opened.recipients;
|
|
4979
5146
|
if (!got || !sameAddresses(got.to, wanted.to) || !sameAddresses(got.cc, wanted.cc) || !sameAddresses(got.bcc, wanted.bcc)) return refuse("recipients", `Mail did not take the draft's recipients: it was given ${JSON.stringify(wanted)} and holds ${JSON.stringify(got ?? null)}. Nothing was filled. ${leftOpen(handle)}`, closeIt, { composer: handle });
|
|
@@ -5078,12 +5245,12 @@ const UUID_RE = /^[0-9A-Fa-f-]{8,64}$/;
|
|
|
5078
5245
|
const encodeRef = (ref) => `m1:${ref.accountUuid}/${encodeURIComponent(ref.mailbox)}#${ref.id}`;
|
|
5079
5246
|
const decodeRef = (raw) => {
|
|
5080
5247
|
const m = /^([a-z0-9]+):([^/]+)\/(.*)#(\d+)$/.exec(raw);
|
|
5081
|
-
if (!m) throw new PreconditionError(`Malformed message ref "${raw}". Refs come from the search and list tools — construct them from those results rather than by hand.`, { expected: `m1:<accountUuid>/<mailbox>#<id>` });
|
|
5248
|
+
if (!m) throw new PreconditionError$1(`Malformed message ref "${raw}". Refs come from the search and list tools — construct them from those results rather than by hand.`, { expected: `m1:<accountUuid>/<mailbox>#<id>` });
|
|
5082
5249
|
const [, version, accountUuid, mailboxRaw, idRaw] = m;
|
|
5083
|
-
if (version !== "m1") throw new PreconditionError(`Unsupported message ref version "${version}". This server issues "m1" refs; re-run the search to get current ones.`);
|
|
5084
|
-
if (!accountUuid || !UUID_RE.test(accountUuid)) throw new PreconditionError(`Message ref "${raw}" does not carry a valid account id.`);
|
|
5250
|
+
if (version !== "m1") throw new PreconditionError$1(`Unsupported message ref version "${version}". This server issues "m1" refs; re-run the search to get current ones.`);
|
|
5251
|
+
if (!accountUuid || !UUID_RE.test(accountUuid)) throw new PreconditionError$1(`Message ref "${raw}" does not carry a valid account id.`);
|
|
5085
5252
|
const id = Number(idRaw);
|
|
5086
|
-
if (!Number.isSafeInteger(id) || id <= 0) throw new PreconditionError(`Message ref "${raw}" does not carry a valid message id.`);
|
|
5253
|
+
if (!Number.isSafeInteger(id) || id <= 0) throw new PreconditionError$1(`Message ref "${raw}" does not carry a valid message id.`);
|
|
5087
5254
|
return {
|
|
5088
5255
|
accountUuid,
|
|
5089
5256
|
mailbox: decodeURIComponent(mailboxRaw ?? ""),
|
|
@@ -5119,8 +5286,11 @@ const groupRefsByMailbox = (refs) => {
|
|
|
5119
5286
|
*
|
|
5120
5287
|
* * The window is matched to the draft by CONTENT, not only by subject. Two
|
|
5121
5288
|
* replies in one thread carry the same title.
|
|
5122
|
-
* * The
|
|
5123
|
-
* the
|
|
5289
|
+
* * The stored text's opening goes along as `expectHead`, so the app checks
|
|
5290
|
+
* the same thing again against the window it actually edits: the first 120
|
|
5291
|
+
* characters for a reply, and for any other draft its stored text whole (up
|
|
5292
|
+
* to 400 characters) with `expectWhole`, since below the cap its window must
|
|
5293
|
+
* hold exactly that text.
|
|
5124
5294
|
* * Every refusal the app makes is returned exactly as it answered.
|
|
5125
5295
|
*/
|
|
5126
5296
|
/**
|
|
@@ -5157,12 +5327,13 @@ const refuse = (capability, facts, reason, hint, extra = {}) => ({
|
|
|
5157
5327
|
* the other is what an accessibility client sees a WebKit view display — and
|
|
5158
5328
|
* they agree on the words while disagreeing about every line break.
|
|
5159
5329
|
*/
|
|
5160
|
-
const sameDraft = (stored, shown) => {
|
|
5330
|
+
const sameDraft = (stored, shown, whole) => {
|
|
5161
5331
|
const a = squash(stored.replaceAll(FILE_CHAR, ""));
|
|
5162
5332
|
const b = squash(shown.replaceAll(FILE_CHAR, ""));
|
|
5163
5333
|
if (a.length === 0 || b.length === 0) return a.length === b.length;
|
|
5164
5334
|
const chars = Math.min(a.length, b.length, IDENTITY_CHARS);
|
|
5165
|
-
|
|
5335
|
+
if (a.slice(0, chars) !== b.slice(0, chars)) return false;
|
|
5336
|
+
return !whole || chars === IDENTITY_CHARS || a.length === b.length;
|
|
5166
5337
|
};
|
|
5167
5338
|
/** A composer whose text the listing could not read: a background tab, or a body not loaded. */
|
|
5168
5339
|
const isHidden = (c) => c.tab === "background" || c.text === null;
|
|
@@ -5182,7 +5353,7 @@ const reviseDraftInPlace = async (lane, facts, opts) => {
|
|
|
5182
5353
|
if (sameSubject.length === 0) return null;
|
|
5183
5354
|
const hidden = sameSubject.filter(isHidden);
|
|
5184
5355
|
const read = sameSubject.filter((c) => !isHidden(c));
|
|
5185
|
-
const matches = read.filter((c) => sameDraft(facts.contentHead, c.text ?? ""));
|
|
5356
|
+
const matches = read.filter((c) => sameDraft(facts.contentHead, c.text ?? "", !facts.isReply));
|
|
5186
5357
|
if (matches.length === 0 && hidden.length === 0) return refuse("identity", facts, `A composer titled "${facts.subject}" is open, but what it holds is not what this draft holds — most likely a different message under the same subject, such as another reply in the thread. Rewriting it would destroy text belonging to something else, so nothing was touched.`, "Check which windows are open in Mail, or edit the draft there directly.", {
|
|
5187
5358
|
composerText: (read[0]?.text ?? "").slice(0, 200),
|
|
5188
5359
|
draftText: facts.contentHead.slice(0, 200)
|
|
@@ -5195,13 +5366,17 @@ const reviseDraftInPlace = async (lane, facts, opts) => {
|
|
|
5195
5366
|
handle = (matches[0] ?? hidden[0]).composer;
|
|
5196
5367
|
}
|
|
5197
5368
|
const files = opts.attachments ?? [];
|
|
5198
|
-
const
|
|
5369
|
+
const whole = !facts.isReply;
|
|
5370
|
+
const head = whole ? facts.contentHead : facts.contentHead.slice(0, IDENTITY_CHARS);
|
|
5199
5371
|
const answer = await lane.editComposer({
|
|
5200
5372
|
composer: handle,
|
|
5201
5373
|
...opts.edits !== void 0 ? { edits: opts.edits } : {},
|
|
5202
5374
|
...opts.body !== void 0 ? { body: opts.body } : {},
|
|
5203
5375
|
...files.length > 0 ? { attachments: files } : {},
|
|
5204
|
-
...matched || head.length > 0 ? {
|
|
5376
|
+
...matched || head.length > 0 ? {
|
|
5377
|
+
expectHead: head,
|
|
5378
|
+
...whole ? { expectWhole: true } : {}
|
|
5379
|
+
} : {}
|
|
5205
5380
|
});
|
|
5206
5381
|
if (answer.replaced !== true) return answer;
|
|
5207
5382
|
return {
|
|
@@ -5217,6 +5392,22 @@ const reviseDraftInPlace = async (lane, facts, opts) => {
|
|
|
5217
5392
|
};
|
|
5218
5393
|
//#endregion
|
|
5219
5394
|
//#region src/client/mail.ts
|
|
5395
|
+
/**
|
|
5396
|
+
* How long the process may take to have Mail download one attachment. A large
|
|
5397
|
+
* Gmail PDF can outlast the ordinary 30 s budget. Mail's own reply deadline is
|
|
5398
|
+
* the default Apple Event timeout, 120 s from when `save` is sent; the margin
|
|
5399
|
+
* lets the script's catch around `save` answer first, with Mail's reason,
|
|
5400
|
+
* rather than the process being killed with none.
|
|
5401
|
+
*/
|
|
5402
|
+
const FETCH_TIMEOUT_MS = 135e3;
|
|
5403
|
+
const isFetchAnswer = (value) => {
|
|
5404
|
+
if (typeof value !== "object" || value === null || !("saved" in value)) return false;
|
|
5405
|
+
const a = value;
|
|
5406
|
+
if (a.saved === true) return true;
|
|
5407
|
+
if (a.reason === "none") return Array.isArray(a.names);
|
|
5408
|
+
if (a.reason === "ambiguous") return typeof a.count === "number";
|
|
5409
|
+
return a.reason === "save-failed" && typeof a.error === "string";
|
|
5410
|
+
};
|
|
5220
5411
|
/** The FDA sentence, kept verbatim for the case where FDA really is the problem. */
|
|
5221
5412
|
/**
|
|
5222
5413
|
* A display name, quoted when it holds a comma, and only then.
|
|
@@ -5457,7 +5648,7 @@ var AppleMailClient = class {
|
|
|
5457
5648
|
* Events otherwise, which measured 8.4 s for twenty and is capped.
|
|
5458
5649
|
*/
|
|
5459
5650
|
async listMessages(account, mailbox, limit) {
|
|
5460
|
-
const name = this.mailboxes.
|
|
5651
|
+
const name = await this.mailboxes.resolveMailbox(account, mailbox);
|
|
5461
5652
|
const scope = await this.#indexScope(account, name);
|
|
5462
5653
|
if ("reason" in scope) return {
|
|
5463
5654
|
...await this.listRecent(account, name, limit),
|
|
@@ -5469,7 +5660,17 @@ var AppleMailClient = class {
|
|
|
5469
5660
|
mailboxRowids: scope.rowids,
|
|
5470
5661
|
limit,
|
|
5471
5662
|
offset: 0
|
|
5472
|
-
}).map((r) =>
|
|
5663
|
+
}).map((r) => {
|
|
5664
|
+
const summary = this.#rowToSummary(r, lookup);
|
|
5665
|
+
return summary ? {
|
|
5666
|
+
...summary,
|
|
5667
|
+
ref: encodeRef({
|
|
5668
|
+
accountUuid: account.id,
|
|
5669
|
+
mailbox: name,
|
|
5670
|
+
id: r.rowid
|
|
5671
|
+
})
|
|
5672
|
+
} : null;
|
|
5673
|
+
}).filter((m) => m !== null);
|
|
5473
5674
|
const { total } = scope.index.count({ mailboxRowids: scope.rowids });
|
|
5474
5675
|
return {
|
|
5475
5676
|
mailbox: name,
|
|
@@ -5484,7 +5685,7 @@ var AppleMailClient = class {
|
|
|
5484
5685
|
* that figure is the cached badge value and the Apple Event cost 0.77 s.
|
|
5485
5686
|
*/
|
|
5486
5687
|
async countMessages(account, mailbox) {
|
|
5487
|
-
const name = this.mailboxes.
|
|
5688
|
+
const name = await this.mailboxes.resolveMailbox(account, mailbox);
|
|
5488
5689
|
const scope = await this.#indexScope(account, name);
|
|
5489
5690
|
if ("reason" in scope) {
|
|
5490
5691
|
const counts = await this.countMailbox(account, name);
|
|
@@ -5615,7 +5816,7 @@ var AppleMailClient = class {
|
|
|
5615
5816
|
if (!opts.account && !opts.mailbox) return void 0;
|
|
5616
5817
|
const lookup = await this.mailboxLookup();
|
|
5617
5818
|
const account = opts.account ? await this.mailboxes.resolveAccount(opts.account) : null;
|
|
5618
|
-
const wanted = opts.mailbox ? account ? this.mailboxes.
|
|
5819
|
+
const wanted = opts.mailbox ? account ? await this.mailboxes.resolveMailbox(account, opts.mailbox) : opts.mailbox : null;
|
|
5619
5820
|
const rowids = [];
|
|
5620
5821
|
for (const [rowid, entry] of lookup) {
|
|
5621
5822
|
if (account && entry.accountUuid !== account.id) continue;
|
|
@@ -5625,7 +5826,7 @@ var AppleMailClient = class {
|
|
|
5625
5826
|
if (rowids.length === 0) {
|
|
5626
5827
|
const known = [...lookup.values()].filter((e) => !account || e.accountUuid === account.id).map((e) => e.mailbox);
|
|
5627
5828
|
const unique = [...new Set(known)].toSorted();
|
|
5628
|
-
throw new PreconditionError(`No mailbox matching ${JSON.stringify(opts.mailbox ?? "")}${account ? ` in account ${JSON.stringify(account.name)}` : ""} is present in Mail's search index.` + (unique.length ? ` Indexed there: ${unique.slice(0, 20).join(", ")}.` : " That account has no indexed mailboxes at all."));
|
|
5829
|
+
throw new PreconditionError$1(`No mailbox matching ${JSON.stringify(opts.mailbox ?? "")}${account ? ` in account ${JSON.stringify(account.name)}` : ""} is present in Mail's search index.` + (unique.length ? ` Indexed there: ${unique.slice(0, 20).join(", ")}.` : " That account has no indexed mailboxes at all."));
|
|
5629
5830
|
}
|
|
5630
5831
|
return rowids;
|
|
5631
5832
|
}
|
|
@@ -5832,6 +6033,17 @@ var AppleMailClient = class {
|
|
|
5832
6033
|
source: "emlx"
|
|
5833
6034
|
};
|
|
5834
6035
|
}
|
|
6036
|
+
/**
|
|
6037
|
+
* The mailbox the index says a ref's row lives in, when it is in the ref's
|
|
6038
|
+
* account, or null: no index, no such row, or a mailbox the account list
|
|
6039
|
+
* cannot name.
|
|
6040
|
+
*/
|
|
6041
|
+
async #rowMailbox(ref) {
|
|
6042
|
+
const row = (await this.index())?.byRowid(ref.id);
|
|
6043
|
+
if (!row?.mailboxUrl) return null;
|
|
6044
|
+
const where = await this.mailboxes.resolveIndexUrl(row.mailboxUrl);
|
|
6045
|
+
return where && where.account.id === ref.accountUuid ? where.mailbox : null;
|
|
6046
|
+
}
|
|
5835
6047
|
/** A ref's envelope fields from the index, keeping the ref the caller passed. */
|
|
5836
6048
|
async #indexSummary(ref) {
|
|
5837
6049
|
const row = (await this.index())?.byRowid(ref.id);
|
|
@@ -5898,6 +6110,19 @@ var AppleMailClient = class {
|
|
|
5898
6110
|
path: lookup.path,
|
|
5899
6111
|
partial: lookup.partial
|
|
5900
6112
|
};
|
|
6113
|
+
const home = await this.#rowMailbox(ref);
|
|
6114
|
+
if (home !== null && home !== ref.mailbox) try {
|
|
6115
|
+
const there = lookupEmlx({
|
|
6116
|
+
accountDirectory: account.directory,
|
|
6117
|
+
mailbox: home,
|
|
6118
|
+
rowid: ref.id
|
|
6119
|
+
});
|
|
6120
|
+
if (there.found) return {
|
|
6121
|
+
found: true,
|
|
6122
|
+
path: there.path,
|
|
6123
|
+
partial: there.partial
|
|
6124
|
+
};
|
|
6125
|
+
} catch {}
|
|
5901
6126
|
return {
|
|
5902
6127
|
found: false,
|
|
5903
6128
|
lookup,
|
|
@@ -6052,27 +6277,113 @@ var AppleMailClient = class {
|
|
|
6052
6277
|
* The destination is resolved and then checked to be inside
|
|
6053
6278
|
* `APPLE_MAIL_ATTACHMENT_DIR`, so a filename of `../../.ssh/authorized_keys`
|
|
6054
6279
|
* lands nowhere. Existing files are never overwritten.
|
|
6280
|
+
*
|
|
6281
|
+
* When the bytes are not on disk, which on a Gmail account caching messages
|
|
6282
|
+
* without their attachments is most older mail, Mail is asked to download
|
|
6283
|
+
* the attachment (see `#fetchFromMail`).
|
|
6055
6284
|
*/
|
|
6056
|
-
async saveAttachment(ref,
|
|
6285
|
+
async saveAttachment(ref, requested, opts = {}) {
|
|
6286
|
+
const filename = decodeEncodedWords(requested);
|
|
6057
6287
|
const decoded = decodeRef(ref);
|
|
6058
6288
|
const located = await this.#lookupMessageFile(decoded);
|
|
6059
|
-
if (!located.found) throw new PreconditionError(`The message file was not found, so its attachments are not reachable. ${located.explain}`, { probed: located.lookup?.probed.slice(0, 3) ?? [] });
|
|
6289
|
+
if (!located.found) throw new PreconditionError$1(`The message file was not found, so its attachments are not reachable. ${located.explain}`, { probed: located.lookup?.probed.slice(0, 3) ?? [] });
|
|
6060
6290
|
let from = "inline";
|
|
6291
|
+
try {
|
|
6292
|
+
return {
|
|
6293
|
+
...writeConfinedFile({
|
|
6294
|
+
root: this.config.attachmentDir,
|
|
6295
|
+
name: filename,
|
|
6296
|
+
bytes: () => {
|
|
6297
|
+
const extracted = extractAttachment(located.path, filename, decoded.id);
|
|
6298
|
+
from = extracted.from;
|
|
6299
|
+
return extracted.bytes;
|
|
6300
|
+
},
|
|
6301
|
+
overwrite: opts.overwrite ?? false,
|
|
6302
|
+
settingName: "APPLE_MAIL_ATTACHMENT_DIR"
|
|
6303
|
+
}),
|
|
6304
|
+
from
|
|
6305
|
+
};
|
|
6306
|
+
} catch (error) {
|
|
6307
|
+
if (!(error instanceof AttachmentNotStoredError)) throw error;
|
|
6308
|
+
}
|
|
6309
|
+
const dest = resolve(this.config.attachmentDir, basename(filename));
|
|
6310
|
+
if (!opts.overwrite && existsSync(dest)) throw new PreconditionError$1(`${dest} already exists; refusing to overwrite it.`);
|
|
6311
|
+
const bytes = await this.#fetchFromMail(decoded, filename);
|
|
6061
6312
|
return {
|
|
6062
6313
|
...writeConfinedFile({
|
|
6063
6314
|
root: this.config.attachmentDir,
|
|
6064
6315
|
name: filename,
|
|
6065
|
-
bytes
|
|
6066
|
-
const extracted = extractAttachment(located.path, filename, decoded.id);
|
|
6067
|
-
from = extracted.from;
|
|
6068
|
-
return extracted.bytes;
|
|
6069
|
-
},
|
|
6316
|
+
bytes,
|
|
6070
6317
|
overwrite: opts.overwrite ?? false,
|
|
6071
6318
|
settingName: "APPLE_MAIL_ATTACHMENT_DIR"
|
|
6072
6319
|
}),
|
|
6073
|
-
from
|
|
6320
|
+
from: "mail"
|
|
6074
6321
|
};
|
|
6075
6322
|
}
|
|
6323
|
+
/**
|
|
6324
|
+
* Have Mail download an attachment it has not fetched, and return its bytes.
|
|
6325
|
+
*
|
|
6326
|
+
* Mail's `save` fetches the attachment from the server, and keeps it in its
|
|
6327
|
+
* own store as well, so the next save finds the sidecar on disk.
|
|
6328
|
+
*
|
|
6329
|
+
* Mail writes into a staging folder of ours inside the attachment directory,
|
|
6330
|
+
* never the destination itself: its `save` overwrites and follows symlinks,
|
|
6331
|
+
* which is exactly what `writeConfinedFile` refuses. The staging file gets a
|
|
6332
|
+
* fixed name, keeping only a sanitised extension, so no part of a caller's
|
|
6333
|
+
* filename becomes a path Mail writes to. The folder goes whatever happens.
|
|
6334
|
+
*
|
|
6335
|
+
* Not retried on a busy answer: -1712 is also what a timed-out Apple Event
|
|
6336
|
+
* returns, and retrying a slow download would only double the wait.
|
|
6337
|
+
*/
|
|
6338
|
+
async #fetchFromMail(ref, filename) {
|
|
6339
|
+
mkdirSync(this.config.attachmentDir, { recursive: true });
|
|
6340
|
+
const staging = mkdtempSync(join(this.config.attachmentDir, ".cupertino-download-"));
|
|
6341
|
+
try {
|
|
6342
|
+
const ext = extname(basename(filename)).replace(/[^A-Za-z0-9.]/g, "");
|
|
6343
|
+
const target = join(staging, `attachment${ext}`);
|
|
6344
|
+
const notStored = `The attachment "${filename}" is not stored locally, and`;
|
|
6345
|
+
let answer;
|
|
6346
|
+
try {
|
|
6347
|
+
answer = await this.runner.run(FETCH_ATTACHMENT, {
|
|
6348
|
+
accountUuid: ref.accountUuid,
|
|
6349
|
+
mailbox: ref.mailbox,
|
|
6350
|
+
id: ref.id,
|
|
6351
|
+
filename,
|
|
6352
|
+
dest: target
|
|
6353
|
+
}, { timeoutMs: Math.max(FETCH_TIMEOUT_MS, this.config.osascriptTimeoutMs) });
|
|
6354
|
+
} catch (error) {
|
|
6355
|
+
if (error instanceof MailNotRunningError) throw new PreconditionError$1(`${notStored} Mail is not running to download it. Open Mail and try again.`);
|
|
6356
|
+
if (error instanceof OsascriptTimeoutError) throw new PreconditionError$1(`${notStored} Mail did not finish downloading it in time. It may still be downloading: try again in a minute, or open the message in Mail.`);
|
|
6357
|
+
if (error instanceof ProtocolError) throw new ProtocolError(`${notStored} Mail could not download it: ${error.message}`, { ...error.details });
|
|
6358
|
+
throw error;
|
|
6359
|
+
}
|
|
6360
|
+
if (!isFetchAnswer(answer)) throw new ProtocolError(`${notStored} Mail's answer to the download was not one save_attachment can read: ${String(JSON.stringify(answer ?? null)).slice(0, 200)}.`);
|
|
6361
|
+
if (!answer.saved) {
|
|
6362
|
+
if (answer.reason === "ambiguous") throw new PreconditionError$1(`${notStored} this message has ${answer.count} attachments named "${filename}", so there is no telling which one to have Mail download. Save it from Mail.`);
|
|
6363
|
+
if (answer.reason === "none") {
|
|
6364
|
+
const listed = answer.names.length > 0 ? answer.names.join(", ") : "none";
|
|
6365
|
+
throw new PreconditionError$1(`${notStored} Mail lists no attachment by that name on this message, so it cannot download it. Mail lists: ${listed}.`);
|
|
6366
|
+
}
|
|
6367
|
+
throw new PreconditionError$1(`${notStored} Mail could not download "${filename}": ${answer.error}. Check that Mail is online and the account is enabled.`);
|
|
6368
|
+
}
|
|
6369
|
+
const entries = readdirSync(staging);
|
|
6370
|
+
const candidate = existsSync(target) ? target : entries.length === 1 ? join(staging, entries[0]) : null;
|
|
6371
|
+
const written = candidate && lstatSync(candidate).isFile() ? candidate : null;
|
|
6372
|
+
if (!written) throw new PreconditionError$1(`${notStored} Mail reported saving "${filename}" but wrote no file. Opening the message in Mail downloads it.`);
|
|
6373
|
+
const bytes = readFileSync(written);
|
|
6374
|
+
if (bytes.length === 0) throw new PreconditionError$1(`${notStored} Mail saved "${filename}" as an empty file, so it did not download it. Check that Mail is online and the account is enabled.`);
|
|
6375
|
+
return bytes;
|
|
6376
|
+
} finally {
|
|
6377
|
+
try {
|
|
6378
|
+
rmSync(staging, {
|
|
6379
|
+
recursive: true,
|
|
6380
|
+
force: true
|
|
6381
|
+
});
|
|
6382
|
+
} catch {
|
|
6383
|
+
this.#logger?.warn?.(`could not remove the download staging folder ${staging}`);
|
|
6384
|
+
}
|
|
6385
|
+
}
|
|
6386
|
+
}
|
|
6076
6387
|
/** Set flags across refs, one Apple Event per distinct mailbox. */
|
|
6077
6388
|
async setFlags(refs, flags) {
|
|
6078
6389
|
const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));
|
|
@@ -6192,8 +6503,8 @@ var AppleMailClient = class {
|
|
|
6192
6503
|
*/
|
|
6193
6504
|
async createMailbox(name, account) {
|
|
6194
6505
|
const trimmed = name.trim();
|
|
6195
|
-
if (!trimmed) throw new PreconditionError("A mailbox name cannot be empty or only whitespace.");
|
|
6196
|
-
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".`);
|
|
6506
|
+
if (!trimmed) throw new PreconditionError$1("A mailbox name cannot be empty or only whitespace.");
|
|
6507
|
+
if (trimmed.split("/").some((segment) => segment.trim() === "")) throw new PreconditionError$1(`"${name}" has an empty path segment. "/" separates levels, so a name may not start or end with it, e.g. "Projects/Cupertino".`);
|
|
6197
6508
|
const resolved = account ? await this.mailboxes.resolveAccount(account) : null;
|
|
6198
6509
|
const result = await withBusyRetry(() => this.runner.run(CREATE_MAILBOX, {
|
|
6199
6510
|
name: trimmed,
|
|
@@ -6235,13 +6546,13 @@ var AppleMailClient = class {
|
|
|
6235
6546
|
* which is the one outcome nothing downstream could distinguish from success.
|
|
6236
6547
|
*/
|
|
6237
6548
|
async updateDraft(target, opts) {
|
|
6238
|
-
if (target.ref !== void 0 && target.composer !== void 0) throw new PreconditionError("Pass either ref or composer, not both: a ref finds the draft's window by its content, and a composer handle already names the window.");
|
|
6239
|
-
if (opts.body !== void 0 && opts.edits !== void 0) throw new PreconditionError("Pass either body or edits, not both: a body replaces the whole text and edits change only what they match.");
|
|
6240
|
-
if (opts.body === void 0 && !opts.edits?.length && !opts.attachments?.length) throw new PreconditionError("Nothing to change: pass a body, edits, attachments, or a combination. A new subject alone needs a body.");
|
|
6241
|
-
if (opts.body !== void 0 && !opts.body.trim()) throw new PreconditionError("A replacement body cannot be empty. Blanking a draft and reporting success is indistinguishable from having written it, so it is refused here rather than done. Delete the draft with apple_mail_delete_messages if that is what you meant.");
|
|
6549
|
+
if (target.ref !== void 0 && target.composer !== void 0) throw new PreconditionError$1("Pass either ref or composer, not both: a ref finds the draft's window by its content, and a composer handle already names the window.");
|
|
6550
|
+
if (opts.body !== void 0 && opts.edits !== void 0) throw new PreconditionError$1("Pass either body or edits, not both: a body replaces the whole text and edits change only what they match.");
|
|
6551
|
+
if (opts.body === void 0 && !opts.edits?.length && !opts.attachments?.length) throw new PreconditionError$1("Nothing to change: pass a body, edits, attachments, or a combination. A new subject alone needs a body.");
|
|
6552
|
+
if (opts.body !== void 0 && !opts.body.trim()) throw new PreconditionError$1("A replacement body cannot be empty. Blanking a draft and reporting success is indistinguishable from having written it, so it is refused here rather than done. Delete the draft with apple_mail_delete_messages if that is what you meant.");
|
|
6242
6553
|
const attachments = this.#resolveAttachments(opts.attachments, false);
|
|
6243
6554
|
if (target.ref === void 0) {
|
|
6244
|
-
if (opts.subject !== void 0) throw new PreconditionError("A new subject can only be set by rebuilding a saved draft, which needs its ref. Editing a composer by handle, or the one open, leaves the subject as it is.");
|
|
6555
|
+
if (opts.subject !== void 0) throw new PreconditionError$1("A new subject can only be set by rebuilding a saved draft, which needs its ref. Editing a composer by handle, or the one open, leaves the subject as it is.");
|
|
6245
6556
|
if (!this.#ax) return nativeOnlyRefusal(target.composer !== void 0 ? "Editing a composer by handle" : "Editing the open composer");
|
|
6246
6557
|
return released(this.#ax, await this.#editComposerDirectly(this.#ax, target.composer, opts, attachments));
|
|
6247
6558
|
}
|
|
@@ -6530,12 +6841,12 @@ var AppleMailClient = class {
|
|
|
6530
6841
|
*/
|
|
6531
6842
|
#resolveAttachments(paths, sendNow) {
|
|
6532
6843
|
if (!paths?.length) return [];
|
|
6533
|
-
if (sendNow && !this.config.allowFileSend) throw new PreconditionError("Sending a local file immediately is off. Leave out sendNow to open a draft with the attachments for the user to review and send, or set APPLE_MAIL_ALLOW_FILE_SEND=1 to allow attaching and sending in one call.");
|
|
6844
|
+
if (sendNow && !this.config.allowFileSend) throw new PreconditionError$1("Sending a local file immediately is off. Leave out sendNow to open a draft with the attachments for the user to review and send, or set APPLE_MAIL_ALLOW_FILE_SEND=1 to allow attaching and sending in one call.");
|
|
6534
6845
|
return paths.map((path) => {
|
|
6535
|
-
if (!isAbsolute(path)) throw new PreconditionError(`"${path}" is not an absolute path. This server has no meaningful working directory, so a relative path cannot be resolved to the file you mean.`);
|
|
6846
|
+
if (!isAbsolute(path)) throw new PreconditionError$1(`"${path}" is not an absolute path. This server has no meaningful working directory, so a relative path cannot be resolved to the file you mean.`);
|
|
6536
6847
|
const source = resolve(path);
|
|
6537
|
-
if (!existsSync(source)) throw new PreconditionError(`There is no file at ${source}.`);
|
|
6538
|
-
if (!statSync(source).isFile()) throw new PreconditionError(`${source} is not a regular file; Mail can only attach files.`);
|
|
6848
|
+
if (!existsSync(source)) throw new PreconditionError$1(`There is no file at ${source}.`);
|
|
6849
|
+
if (!statSync(source).isFile()) throw new PreconditionError$1(`${source} is not a regular file; Mail can only attach files.`);
|
|
6539
6850
|
return source;
|
|
6540
6851
|
});
|
|
6541
6852
|
}
|
|
@@ -7435,7 +7746,7 @@ const registerMessageTools = (server, client, allowWrites) => {
|
|
|
7435
7746
|
truncated: parsed.truncated,
|
|
7436
7747
|
body: parsed.body,
|
|
7437
7748
|
attachments: parsed.attachments,
|
|
7438
|
-
...missing.length > 0 ? { note: `Not downloaded by Mail yet: ${missing.join(", ")}. Its bytes are not on disk
|
|
7749
|
+
...missing.length > 0 ? { note: `Not downloaded by Mail yet: ${missing.join(", ")}. Its bytes are not on disk; apple_mail_save_attachment asks Mail to download it, which takes a few seconds per file and needs Mail running and online.` } : {}
|
|
7439
7750
|
};
|
|
7440
7751
|
}));
|
|
7441
7752
|
server.registerTool("apple_mail_list_open_drafts", {
|
|
@@ -7477,7 +7788,7 @@ const registerMessageTools = (server, client, allowWrites) => {
|
|
|
7477
7788
|
}));
|
|
7478
7789
|
if (!allowWrites) return;
|
|
7479
7790
|
server.registerTool("apple_mail_save_attachment", {
|
|
7480
|
-
description: "Save one attachment to disk. It can only write into APPLE_MAIL_ATTACHMENT_DIR (default ~/Downloads) and will not overwrite an existing file unless you ask it to. Write-gated because it puts a file on the user's disk
|
|
7791
|
+
description: "Save one attachment to disk. It can only write into APPLE_MAIL_ATTACHMENT_DIR (default ~/Downloads) and will not overwrite an existing file unless you ask it to. An attachment Mail has not downloaded (retrievable: false) is fetched by Mail from the server first, which needs Mail running and online and can take a few seconds; `from` says \"mail\" then. Write-gated because it puts a file on the user's disk.",
|
|
7481
7792
|
inputSchema: z.object({
|
|
7482
7793
|
ref: messageRefArg,
|
|
7483
7794
|
filename: z.string().min(1).describe("Exact filename from apple_mail_list_attachments."),
|
|
@@ -7744,8 +8055,10 @@ var MailArrivalSource = class {
|
|
|
7744
8055
|
* While set, `since` stops before the first row whose mailbox is not among
|
|
7745
8056
|
* `knownMailboxes`, so the cursor stays below a row the lookup cannot judge
|
|
7746
8057
|
* yet. The watch service sets it around a tick, refreshes when `takeHeld()`
|
|
7747
|
-
* says it stopped, and ticks again;
|
|
7748
|
-
*
|
|
8058
|
+
* says it stopped, and ticks again; it sets it around a read too, and drops
|
|
8059
|
+
* what the read held, so the cursor a client gets never passes such a row.
|
|
8060
|
+
* The events service keeps it set, and refreshes before the next poll or
|
|
8061
|
+
* tick.
|
|
7749
8062
|
*/
|
|
7750
8063
|
holdNewMailboxes = false;
|
|
7751
8064
|
constructor(opts) {
|
|
@@ -7865,8 +8178,9 @@ const isMailRunning = async (run = defaultRun) => {
|
|
|
7865
8178
|
* that writes a new `Envelope Index` and renames it over the old one leaves that
|
|
7866
8179
|
* connection reading the deleted file: nothing new arrives there and nothing
|
|
7867
8180
|
* errors. So the service records the file's inode when it opens it, compares on
|
|
7868
|
-
* every trigger, and reopens before the tick when it changed
|
|
7869
|
-
*
|
|
8181
|
+
* every trigger, and reopens before the tick when it changed, then restarts the
|
|
8182
|
+
* registry at the new file's head, so nothing it already holds is reported,
|
|
8183
|
+
* whether its renumbered head is below the old mark or past it. The
|
|
7870
8184
|
* mailbox rowids may be renumbered too, so the lookup is rebuilt from the new
|
|
7871
8185
|
* file's `mailboxes` table with the accounts already in hand.
|
|
7872
8186
|
*
|
|
@@ -7961,10 +8275,23 @@ var MailWatchService = class {
|
|
|
7961
8275
|
get #loaded() {
|
|
7962
8276
|
return this.#accounts !== void 0;
|
|
7963
8277
|
}
|
|
8278
|
+
/** True while `onTrigger` ticks, so `source.since` can tell a tick from a read. */
|
|
8279
|
+
#ticking = false;
|
|
7964
8280
|
/** What `createWatches` is given. Delegates to the source `ensure()` builds. */
|
|
7965
8281
|
source = {
|
|
7966
8282
|
head: () => this.#ready().head(),
|
|
7967
|
-
since: (after, limit) =>
|
|
8283
|
+
since: (after, limit) => {
|
|
8284
|
+
if (!this.#loaded) return [];
|
|
8285
|
+
const inner = this.#ready();
|
|
8286
|
+
if (this.#ticking || this.#events) return inner.since(after, limit);
|
|
8287
|
+
inner.holdNewMailboxes = true;
|
|
8288
|
+
try {
|
|
8289
|
+
return inner.since(after, limit);
|
|
8290
|
+
} finally {
|
|
8291
|
+
inner.holdNewMailboxes = false;
|
|
8292
|
+
inner.takeHeld();
|
|
8293
|
+
}
|
|
8294
|
+
}
|
|
7968
8295
|
};
|
|
7969
8296
|
constructor(opts) {
|
|
7970
8297
|
this.#client = opts.client;
|
|
@@ -8034,10 +8361,10 @@ var MailWatchService = class {
|
|
|
8034
8361
|
}
|
|
8035
8362
|
async #setUp() {
|
|
8036
8363
|
const shared = await this.#client.index();
|
|
8037
|
-
if (!shared) throw new PreconditionError(`The Envelope Index cannot be read, so there is nothing to ${this.#noun === "watch" ? "watch" : "read events from"}: ${this.#client.indexError ?? "reason unknown"}`);
|
|
8038
|
-
if (shared.mode === "immutable") throw new PreconditionError(immutableReason(this.#noun));
|
|
8364
|
+
if (!shared) throw new PreconditionError$1(`The Envelope Index cannot be read, so there is nothing to ${this.#noun === "watch" ? "watch" : "read events from"}: ${this.#client.indexError ?? "reason unknown"}`);
|
|
8365
|
+
if (shared.mode === "immutable") throw new PreconditionError$1(immutableReason(this.#noun));
|
|
8039
8366
|
const located = await this.#client.locate();
|
|
8040
|
-
if (!located.envelopeIndexPath) throw new PreconditionError(located.reason ?? "The Envelope Index was not located.");
|
|
8367
|
+
if (!located.envelopeIndexPath) throw new PreconditionError$1(located.reason ?? "The Envelope Index was not located.");
|
|
8041
8368
|
this.#open(located.envelopeIndexPath);
|
|
8042
8369
|
try {
|
|
8043
8370
|
await this.#refresh();
|
|
@@ -8055,7 +8382,7 @@ var MailWatchService = class {
|
|
|
8055
8382
|
const index = new EnvelopeIndex(openIndex(path, this.#client.config.indexMode, this.#logger));
|
|
8056
8383
|
if (index.mode === "immutable") {
|
|
8057
8384
|
index.close();
|
|
8058
|
-
throw new PreconditionError(immutableReason(this.#noun));
|
|
8385
|
+
throw new PreconditionError$1(immutableReason(this.#noun));
|
|
8059
8386
|
}
|
|
8060
8387
|
const old = this.#index;
|
|
8061
8388
|
this.#index = index;
|
|
@@ -8077,6 +8404,7 @@ var MailWatchService = class {
|
|
|
8077
8404
|
try {
|
|
8078
8405
|
this.#open(this.#path);
|
|
8079
8406
|
this.#reopenFailing = false;
|
|
8407
|
+
this.#registry?.restart();
|
|
8080
8408
|
} catch (err) {
|
|
8081
8409
|
if (!this.#reopenFailing) this.#logger?.warn?.("watch: the Envelope Index was replaced and could not be reopened", err);
|
|
8082
8410
|
this.#reopenFailing = true;
|
|
@@ -8152,14 +8480,23 @@ var MailWatchService = class {
|
|
|
8152
8480
|
if (this.#ready().head() > (this.#registry?.mark ?? 0) && this.#stale() && !await this.#refreshSoftly() && !this.#loaded) return;
|
|
8153
8481
|
const inner = this.#ready();
|
|
8154
8482
|
inner.holdNewMailboxes = true;
|
|
8483
|
+
this.#ticking = true;
|
|
8155
8484
|
try {
|
|
8156
8485
|
tick();
|
|
8157
8486
|
} finally {
|
|
8158
8487
|
inner.holdNewMailboxes = false;
|
|
8488
|
+
this.#ticking = false;
|
|
8489
|
+
}
|
|
8490
|
+
const held = inner.takeHeld();
|
|
8491
|
+
if (held === null) return;
|
|
8492
|
+
this.#heldThrough.set(held.mailbox, Math.max(held.rowid, this.#heldThrough.get(held.mailbox) ?? 0));
|
|
8493
|
+
if (!await this.#refreshSoftly()) this.#rebuild();
|
|
8494
|
+
this.#ticking = true;
|
|
8495
|
+
try {
|
|
8496
|
+
tick();
|
|
8497
|
+
} finally {
|
|
8498
|
+
this.#ticking = false;
|
|
8159
8499
|
}
|
|
8160
|
-
if (inner.takeHeld() === null) return;
|
|
8161
|
-
await this.#refreshSoftly();
|
|
8162
|
-
tick();
|
|
8163
8500
|
}
|
|
8164
8501
|
/**
|
|
8165
8502
|
* What the file trigger runs. `onTrigger` is async and the trigger's own
|
|
@@ -8218,10 +8555,10 @@ var MailWatchService = class {
|
|
|
8218
8555
|
return [];
|
|
8219
8556
|
}
|
|
8220
8557
|
if (!(running ?? await this.#isMailRunning())) throw this.#mailboxesNeedMail();
|
|
8221
|
-
for (const name of mailboxes) if (isUnwatchedMailbox(`imap://x/${name}`)) throw new PreconditionError(`"${name}" is never ${noun === "watch" ? "watched" : "followed"}: Sent, Drafts, Junk and Trash are excluded, so a ${noun} on it could never fire.`);
|
|
8558
|
+
for (const name of mailboxes) if (isUnwatchedMailbox(`imap://x/${name}`)) throw new PreconditionError$1(`"${name}" is never ${noun === "watch" ? "watched" : "followed"}: Sent, Drafts, Junk and Trash are excluded, so a ${noun} on it could never fire.`);
|
|
8222
8559
|
await this.ensure();
|
|
8223
8560
|
const rowids = await this.#client.mailboxRowidsFor(mailboxes);
|
|
8224
|
-
if (rowids.length > MAX_WATCHED_MAILBOXES) throw new PreconditionError(`Those names cover ${rowids.length} mailboxes across the accounts, more than a ${noun} can follow (${MAX_WATCHED_MAILBOXES}). Name fewer mailboxes.`);
|
|
8561
|
+
if (rowids.length > MAX_WATCHED_MAILBOXES) throw new PreconditionError$1(`Those names cover ${rowids.length} mailboxes across the accounts, more than a ${noun} can follow (${MAX_WATCHED_MAILBOXES}). Name fewer mailboxes.`);
|
|
8225
8562
|
return rowids.map(String);
|
|
8226
8563
|
}
|
|
8227
8564
|
/**
|
|
@@ -8233,7 +8570,7 @@ var MailWatchService = class {
|
|
|
8233
8570
|
if (mailboxes.length > 0 && !await this.#isMailRunning()) throw this.#mailboxesNeedMail();
|
|
8234
8571
|
}
|
|
8235
8572
|
#mailboxesNeedMail() {
|
|
8236
|
-
return new PreconditionError(`Mailbox names cannot be resolved until Mail is running: Mail is what says which mailboxes an account has. Open Mail and try again, or ${this.#noun === "watch" ? "watch" : "subscribe"} without \`mailboxes\`.`);
|
|
8573
|
+
return new PreconditionError$1(`Mailbox names cannot be resolved until Mail is running: Mail is what says which mailboxes an account has. Open Mail and try again, or ${this.#noun === "watch" ? "watch" : "subscribe"} without \`mailboxes\`.`);
|
|
8237
8574
|
}
|
|
8238
8575
|
/** Resolve `mailboxes` to scope keys and register the watch. */
|
|
8239
8576
|
async add(filter, mailboxes) {
|
|
@@ -8411,6 +8748,6 @@ const createServer = (opts) => {
|
|
|
8411
8748
|
};
|
|
8412
8749
|
};
|
|
8413
8750
|
//#endregion
|
|
8414
|
-
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 };
|
|
8751
|
+
export { WritesDisabledError as A, MessageNotFoundError as C, ProtocolError as D, PreconditionError$1 as E, SchemaDriftError as O, MailNotRunningError as S, PlatformError as T, locateEnvelopeIndex as _, loadConfig as a, MAIL_SURFACE as b, decodeRef as c, assertStaticScript as d, createOsascriptRunner as f, inspectFile as g, MailboxMap as h, registerTools as i, BUILD_INFO as j, TccDeniedError as k, encodeRef as l, withBusyRetry as m, SERVER_VERSION as n, AppleMailClient as o, mapOsaError as p, createServer as r, REF_VERSION as s, SERVER_NAME as t, groupRefsByMailbox as u, AppleMailError as v, OsascriptTimeoutError as w, MailBusyError as x, IndexUnavailableError as y };
|
|
8415
8752
|
|
|
8416
|
-
//# sourceMappingURL=server-
|
|
8753
|
+
//# sourceMappingURL=server-D-UcpTRv.js.map
|