@mgcrea/mcp-apple-mail 1.14.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
- import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BaseConfigSchema, IndexUnavailableError, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, confirmArg, createOsascriptRunner, describeAggregation, detectEpoch, escapeLike, fingerprintSchema, groupByArg, inspectFile, limitArg, mapOsaError, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, project, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, selectArg, 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, describeAggregation, detectEpoch, escapeLike, fingerprintSchema, groupByArg, inspectFile, interferenceNote, limitArg, mapOsaError, openAxChannel, openReadOnly, parseBool, parseConfig, parseIntOpt, parseList, project, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, requiredPromptArg, resolveLimit, selectArg, tableMap, trimmed, watchInterference, withBusyRetry, withLazyTools, 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";
5
+ import { execFile } from "node:child_process";
6
+ import { promisify } from "node:util";
5
7
  import { z } from "zod";
6
8
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
9
  //#region src/build-info.ts
@@ -12,8 +14,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
12
14
  const BUILD_INFO = {
13
15
  name: pkg.name,
14
16
  version: pkg.version,
15
- gitCommit: "e006496",
16
- gitCommitDate: "2026-09-04T23:14:11+02:00"
17
+ gitCommit: "d70b8e4",
18
+ gitCommitDate: "2026-09-06T12:13:21+02:00"
17
19
  };
18
20
  //#endregion
19
21
  //#region src/client/errors.ts
@@ -104,6 +106,324 @@ const locateEnvelopeIndex = (opts = {}) => {
104
106
  };
105
107
  };
106
108
  //#endregion
109
+ //#region src/client/ax.ts
110
+ /**
111
+ * Mail's composer, driven through Cupertino's native Accessibility driver.
112
+ *
113
+ * ## What this replaces, and why it is worth replacing
114
+ *
115
+ * `jxa/core.ts` reaches the same composer through System Events. That path
116
+ * works, and it costs two things this one does not:
117
+ *
118
+ * * **A second TCC grant.** UI scripting through System Events needs
119
+ * Automation-to-System-Events *on top of* Accessibility — two grants, in two
120
+ * System Settings panes, to reach one window. `composerGrantMessage` is ten
121
+ * lines long because of it.
122
+ * * **47.4 ms per attribute read**, against 0.202 ms called natively. Which is
123
+ * why `findBodyArea` is bounded at depth 6 and `composerBodyText` carries a
124
+ * character budget: both are cost control, not correctness.
125
+ *
126
+ * ## What it deliberately does NOT change
127
+ *
128
+ * **The body is still pasted.** Assigning `content` is dropped by Mail, and so
129
+ * is setting AXValue on the web area, "which reports itself settable first and
130
+ * then does nothing" — measured in `jxa/write.ts`, and independently in
131
+ * `docs/desktop.md`, which found the same trap on the first text field of all
132
+ * seven apps it probed. A native driver does not make an app honour a write it
133
+ * ignores. The clipboard is still borrowed and still put back.
134
+ *
135
+ * **Nothing reports a draft ready on the strength of a write being accepted.**
136
+ * That is the failure this whole path is shaped around: a draft correct in every
137
+ * visible respect except the words, reported as a success.
138
+ *
139
+ * ## The fallback is not optional
140
+ *
141
+ * `openAxChannel` returns null when this server was not started by Cupertino —
142
+ * the npm packages are published artifacts and are run by hand. Every function
143
+ * here is reached only after `available()`, and `client/mail.ts` keeps the
144
+ * System Events path for when it is false.
145
+ */
146
+ const MAIL_BUNDLE = "com.apple.mail";
147
+ /** Mail's composer body is a WebKit view, not a text field. */
148
+ const BODY_ROLE = "AXWebArea";
149
+ /**
150
+ * How deep to look for the body.
151
+ *
152
+ * `findBodyArea` uses 6 and says the bound is there to survive the cost. Cost is
153
+ * no longer the reason, so this is only a guard against walking a composer that
154
+ * holds a deeply nested quoted message — the web area itself sits near the top.
155
+ */
156
+ const BODY_DEPTH = 8;
157
+ var MailAxLane = class MailAxLane {
158
+ #channel;
159
+ constructor(channel) {
160
+ this.#channel = channel;
161
+ }
162
+ /** Null when this server is not hosted by Cupertino — see the note above. */
163
+ static open(env = process.env) {
164
+ const channel = openAxChannel(MAIL_SURFACE, env);
165
+ return channel ? new MailAxLane(channel) : null;
166
+ }
167
+ close() {
168
+ this.#channel.close();
169
+ }
170
+ /** Start watching for someone using the Mac during a sequence. */
171
+ watch() {
172
+ return watchInterference(this.#channel);
173
+ }
174
+ #call(tool, args = {}) {
175
+ return this.#channel.call({
176
+ tool: `apple_desktop_${tool}`,
177
+ args
178
+ });
179
+ }
180
+ /**
181
+ * Can this process read Mail's windows, right now?
182
+ *
183
+ * Asked BEFORE a composer is opened, keeping the ordering `jxa/write.ts`
184
+ * established: the old shape opened a window, failed the read, and left an
185
+ * empty reply on screen with an error telling the user to close it by hand.
186
+ *
187
+ * Ground truth is the functional read, never a trusted flag. One bundle
188
+ * identifier can hold several Accessibility entries — one per path and
189
+ * signature it has been granted at — so the flag can answer for a different
190
+ * row from the one the request resolves against. A window list that comes back
191
+ * named is proof regardless of what the flag says.
192
+ *
193
+ * Mail with no windows is legitimate — everything closed to the menu bar — so
194
+ * an empty list is not evidence of anything and must not refuse a reply that
195
+ * would have worked.
196
+ */
197
+ async reach() {
198
+ try {
199
+ return {
200
+ ok: true,
201
+ reason: null,
202
+ windows: ((await this.#call("list_windows", {
203
+ bundleId: MAIL_BUNDLE,
204
+ includeTitles: true
205
+ })).windows ?? []).map((w) => w.title ?? null).filter((t) => t !== null)
206
+ };
207
+ } catch {
208
+ return {
209
+ ok: false,
210
+ reason: "accessibility",
211
+ windows: null
212
+ };
213
+ }
214
+ }
215
+ /**
216
+ * The sentence to say when the composer cannot be reached natively.
217
+ *
218
+ * One grant rather than two, and none of the "quit Cupertino and open it
219
+ * again" ritual the System Events path needs — that exists because a node
220
+ * child started before the grant does not inherit it, and this driver runs in
221
+ * the app itself.
222
+ */
223
+ static grantMessage(mode) {
224
+ return `Cupertino cannot read Mail's windows, which is the only route into a ${mode} composer, so it was not started and nothing was written. This needs Accessibility for Cupertino.app in System Settings > Privacy & Security > Accessibility. If the app is already listed, toggle it off and on — the grant goes stale when the bundle is reinstalled. Run apple_mail_diagnostics to check; it names the windows it can see.`;
225
+ }
226
+ /**
227
+ * Poll for the composer window, and for its body.
228
+ *
229
+ * Polled rather than waited for, which `docs/desktop.md` records as the trap
230
+ * that cost it the most: a window's chrome appearing is not its content being
231
+ * ready, so no fixed settle time is correct. Cheap here — a bounded walk is
232
+ * milliseconds.
233
+ *
234
+ * The subject is the identity, and requiring a body area with it rejects the
235
+ * main window and the drafts list. Counting windows does not work: Mail closes
236
+ * and reuses windows around a compose, so the count comes back unchanged with
237
+ * a new composer on screen.
238
+ */
239
+ async findComposer(subject, timeoutMs) {
240
+ const deadline = Date.now() + timeoutMs;
241
+ for (;;) {
242
+ const listed = await this.#call("list_windows", {
243
+ bundleId: MAIL_BUNDLE,
244
+ includeTitles: true
245
+ });
246
+ for (const win of listed.windows ?? []) {
247
+ if ((win.title ?? "") !== subject) continue;
248
+ const body = await this.#bodyOf(win.index);
249
+ if (body) return {
250
+ window: win.handle,
251
+ body,
252
+ index: win.index
253
+ };
254
+ }
255
+ if (Date.now() >= deadline) return null;
256
+ await new Promise((resolve) => setTimeout(resolve, 200));
257
+ }
258
+ }
259
+ async #bodyOf(windowIndex) {
260
+ return ((await this.#call("ui_tree", {
261
+ bundleId: MAIL_BUNDLE,
262
+ window: windowIndex,
263
+ detail: "all",
264
+ maxDepth: BODY_DEPTH
265
+ })).elements ?? []).find((el) => el.role === BODY_ROLE)?.handle ?? null;
266
+ }
267
+ /** Bring Mail to the front. A synthetic keystroke lands in whatever is frontmost. */
268
+ async activate() {
269
+ await this.#call("activate", { bundleId: MAIL_BUNDLE });
270
+ }
271
+ /**
272
+ * The accessible text under the body, which is what a person would see.
273
+ *
274
+ * One call rather than a bounded walk. The System Events version reads a
275
+ * parent at a time and stops at a character budget because every node costs an
276
+ * Apple Event; here the whole subtree comes back in one answer with each
277
+ * element's value already on it.
278
+ *
279
+ * Returns null when the body cannot be reached at all — a different answer
280
+ * from "", and the two must stay apart: one means we are blind, the other
281
+ * means the composer is empty.
282
+ */
283
+ async bodyText(body) {
284
+ try {
285
+ return ((await this.#call("expand", {
286
+ handle: body,
287
+ detail: "all",
288
+ maxDepth: BODY_DEPTH
289
+ })).elements ?? []).map((el) => el.value).filter((v) => typeof v === "string" && v.trim() !== "").join("\n");
290
+ } catch {
291
+ return null;
292
+ }
293
+ }
294
+ /**
295
+ * How many elements the body holds.
296
+ *
297
+ * A fingerprint, not a reading. Taken before and after a paste it answers "did
298
+ * anything at all land", which is what decides whether pasting again is safe:
299
+ * a paste that landed and cannot be read must NOT be repeated, or the reply
300
+ * ends up in the draft twice with no way to undo it from here.
301
+ *
302
+ * `matched` rather than the returned length, because the response is byte
303
+ * capped and a long quoted message will truncate — a fingerprint taken from a
304
+ * truncated list would compare two different bounds rather than two states.
305
+ */
306
+ async bodySize(body) {
307
+ try {
308
+ const tree = await this.#call("expand", {
309
+ handle: body,
310
+ detail: "all",
311
+ maxDepth: BODY_DEPTH
312
+ });
313
+ return tree.matched ?? (tree.elements ?? []).length;
314
+ } catch {
315
+ return -1;
316
+ }
317
+ }
318
+ /**
319
+ * Focus the body and paste, and say whether the focus took.
320
+ *
321
+ * Focus is not a raise: a raise orders a window forward inside Mail while the
322
+ * keystroke goes wherever the focus actually is. Both are needed, and the
323
+ * focus is read back because an element can report itself focusable and not
324
+ * take it.
325
+ */
326
+ async paste(ref) {
327
+ await this.#call("raise_window", { handle: ref.window });
328
+ await this.activate();
329
+ if ((await this.#call("focus", { handle: ref.body })).focused !== true) return false;
330
+ await this.#call("key", {
331
+ key: "v",
332
+ modifiers: ["command"]
333
+ });
334
+ return true;
335
+ }
336
+ /**
337
+ * Send the composer, or save it as a draft.
338
+ *
339
+ * A keyboard shortcut rather than the Send button, and that is a correctness
340
+ * choice rather than a shortcut in the other sense: the button's name is
341
+ * localised — a French Mail says "Envoyer" — while command-shift-D is the same
342
+ * on every Mac. Addressing it by name would have worked on the machine it was
343
+ * written on and nowhere else.
344
+ *
345
+ * This is the step that replaces `draft.send()`, and the reason it had to. A
346
+ * JXA object reference cannot outlive the `osascript` process that made it,
347
+ * and this flow now spans two processes: Apple Events opens the composer, and
348
+ * everything after is native. Re-finding the draft to send it was the
349
+ * alternative and is worse — drafts are discovered by subject, so two with the
350
+ * same one are indistinguishable, on the single path whose named failure is
351
+ * sending the wrong thing.
352
+ */
353
+ async finish(sendNow) {
354
+ await this.#call("key", sendNow ? {
355
+ key: "d",
356
+ modifiers: ["command", "shift"]
357
+ } : {
358
+ key: "s",
359
+ modifiers: ["command"]
360
+ });
361
+ }
362
+ /**
363
+ * Has the composer for this subject gone?
364
+ *
365
+ * How a send is confirmed. Mail closes the window when it accepts one, so the
366
+ * window still being there means it did not go — which is checked rather than
367
+ * assumed, because nothing in this path may report success on the strength of
368
+ * a keystroke having been delivered.
369
+ */
370
+ async composerGone(subject, timeoutMs) {
371
+ const deadline = Date.now() + timeoutMs;
372
+ for (;;) {
373
+ if (!((await this.#call("list_windows", {
374
+ bundleId: MAIL_BUNDLE,
375
+ includeTitles: true
376
+ })).windows ?? []).some((w) => (w.title ?? "") === subject)) return true;
377
+ if (Date.now() >= deadline) return false;
378
+ await new Promise((resolve) => setTimeout(resolve, 200));
379
+ }
380
+ }
381
+ /** Select everything in the body, for the quote strip. */
382
+ async selectAll() {
383
+ await this.#call("key", {
384
+ key: "a",
385
+ modifiers: ["command"]
386
+ });
387
+ }
388
+ /**
389
+ * The deepest quote level anywhere in the body; 0 once the citation is gone.
390
+ *
391
+ * `AXBlockQuoteLevel` is not in the tree's field set, which is chosen for
392
+ * addressing controls — so it is read one element at a time. That is
393
+ * affordable only natively: 343 elements at 0.2 ms is well under a tenth of a
394
+ * second, where the same walk through System Events would be sixteen.
395
+ */
396
+ async maxQuoteLevel(body) {
397
+ const tree = await this.#call("expand", {
398
+ handle: body,
399
+ detail: "all",
400
+ maxDepth: BODY_DEPTH
401
+ });
402
+ let worst = 0;
403
+ for (const el of tree.elements ?? []) {
404
+ const read = await this.#call("get_attribute", {
405
+ handle: el.handle,
406
+ attribute: "AXBlockQuoteLevel"
407
+ });
408
+ const level = typeof read.value === "number" ? read.value : 0;
409
+ if (level > worst) worst = level;
410
+ }
411
+ return worst;
412
+ }
413
+ };
414
+ /**
415
+ * Does the pasted text appear at the top of what the composer now holds?
416
+ *
417
+ * Whitespace-squashed on both sides: the accessible text of a WebKit view breaks
418
+ * lines where the rendering does, not where the source did.
419
+ */
420
+ const squash = (s) => s.replace(/\s+/g, " ").trim();
421
+ const containsText = (haystack, needle) => {
422
+ const n = squash(needle);
423
+ if (!n) return true;
424
+ return squash(haystack).includes(n);
425
+ };
426
+ //#endregion
107
427
  //#region src/client/mime.ts
108
428
  const decodeBase64 = (s) => Buffer.from(s, "base64");
109
429
  const decodeQuotedPrintable = (s, forHeader = false) => {
@@ -731,342 +1051,21 @@ const scanBodies = (opts) => {
731
1051
  };
732
1052
  };
733
1053
  //#endregion
734
- //#region src/client/schema.ts
735
- const REQUIRED = {
736
- messages: [
737
- "mailbox",
738
- "subject",
739
- "sender",
740
- "date_received",
741
- "read",
742
- "deleted"
743
- ],
744
- mailboxes: ["url"],
745
- subjects: ["subject"],
746
- addresses: ["address"]
747
- };
748
- const introspect = (db, now) => {
749
- const fingerprint = fingerprintSchema(db);
750
- const tables = tableMap(db);
751
- const tableNames = Object.keys(tables);
752
- const missing = [];
753
- for (const [table, cols] of Object.entries(REQUIRED)) {
754
- if (!tables[table]) {
755
- missing.push(`${table} (table)`);
756
- continue;
757
- }
758
- for (const c of cols) if (!tables[table]?.includes(c)) missing.push(`${table}.${c}`);
759
- }
760
- const messageCols = tables.messages ?? [];
761
- let epoch = {
762
- offset: 0,
763
- reason: "not probed"
764
- };
765
- if (missing.length === 0) {
766
- const row = db.prepare("SELECT MAX(date_received) AS m FROM messages").get();
767
- epoch = detectEpoch(row?.m ?? null, now);
768
- }
769
- return {
770
- fingerprint,
771
- tables,
772
- has: {
773
- labels: tableNames.includes("labels"),
774
- recipients: tableNames.includes("recipients"),
775
- attachments: tableNames.includes("attachments"),
776
- subjects: tableNames.includes("subjects"),
777
- addresses: tableNames.includes("addresses"),
778
- subjectPrefix: messageCols.includes("subject_prefix"),
779
- conversationId: messageCols.includes("conversation_id"),
780
- flagged: messageCols.includes("flagged"),
781
- dateSent: messageCols.includes("date_sent"),
782
- messageIdHeader: (tables.message_global_data ?? []).includes("message_id_header"),
783
- mailboxCounts: (tables.mailboxes ?? []).includes("unread_count")
784
- },
785
- epochOffset: epoch.offset,
786
- epochReason: epoch.reason,
787
- missing
788
- };
789
- };
790
- const assertUsable = (caps) => {
791
- if (caps.missing.length > 0) throw new SchemaDriftError(`Mail's search index is not the shape this server knows how to read (missing: ${caps.missing.join(", ")}). This usually means a macOS upgrade changed the schema. The AppleScript lane still works; please report schema fingerprint ${caps.fingerprint}.`, {
792
- fingerprint: caps.fingerprint,
793
- missing: caps.missing
794
- });
795
- };
796
- //#endregion
797
- //#region src/client/envelope.ts
1054
+ //#region src/client/jxa/core.ts
798
1055
  /**
799
- * What a mail query can group on.
1056
+ * JXA script fragments.
800
1057
  *
801
- * The single source of truth for both the tool's enum and the SQL expressions
802
- * in `#groupExpr` — a field can only be asked for if it is listed here, which
803
- * is what keeps caller strings out of the statement.
804
- */
805
- const GROUP_FIELDS = [
806
- "sender",
807
- "mailbox",
808
- "subject",
809
- "day",
810
- "month"
811
- ];
812
- const contains = (value) => `%${escapeLike(value)}%`;
813
- const openIndex = (path, mode, logger) => {
814
- const { db, mode: opened, validated: caps } = openReadOnly(path, mode, {
815
- envVar: "APPLE_MAIL_INDEX_MODE",
816
- label: "Mail's search index",
817
- hint: "If this is a permission error, grant Full Disk Access to the app running this server.",
818
- validate: (conn) => {
819
- const found = introspect(conn);
820
- assertUsable(found);
821
- return found;
822
- },
823
- fatal: (err) => err instanceof SchemaDriftError,
824
- onFallback: () => logger?.warn?.("opened the index with immutable=1; results may omit mail that is still in the -wal")
825
- });
826
- return {
827
- db,
828
- mode: opened,
829
- caps
830
- };
831
- };
832
- var EnvelopeIndex = class EnvelopeIndex {
833
- #db;
834
- caps;
835
- mode;
836
- constructor(opened) {
837
- this.#db = opened.db;
838
- this.caps = opened.caps;
839
- this.mode = opened.mode;
840
- }
841
- close() {
842
- try {
843
- this.#db.close();
844
- } catch {}
845
- }
846
- /** id -> url for every mailbox, so results can be mapped back to scriptable names. */
847
- mailboxes() {
848
- const hasCounts = this.caps.has.mailboxCounts;
849
- return this.#db.prepare(hasCounts ? "SELECT ROWID AS rowid, url, total_count AS total, unread_count AS unread FROM mailboxes" : "SELECT ROWID AS rowid, url, NULL AS total, NULL AS unread FROM mailboxes").all();
850
- }
851
- /**
852
- * Restrict to a set of mailboxes.
853
- *
854
- * The `labels` half is not optional for Gmail. Gmail-over-IMAP keeps every
855
- * message in `[Gmail]/All Mail` and expresses INBOX membership as a label
856
- * row, so `m.mailbox IN (...)` alone returns an EMPTY inbox — measured here
857
- * as 0 rows against 51,128 real messages.
858
- */
859
- #mailboxPredicate(rowids, params) {
860
- if (!rowids?.length) return "1=1";
861
- const placeholders = rowids.map(() => "?").join(",");
862
- if (!this.caps.has.labels) {
863
- params.push(...rowids);
864
- return `m.mailbox IN (${placeholders})`;
865
- }
866
- params.push(...rowids, ...rowids);
867
- return `(m.mailbox IN (${placeholders}) OR m.ROWID IN (SELECT message_id FROM labels WHERE mailbox_id IN (${placeholders})))`;
868
- }
869
- #toIso(value) {
870
- if (value === null || !Number.isFinite(value)) return null;
871
- return (/* @__PURE__ */ new Date((value + this.caps.epochOffset) * 1e3)).toISOString();
872
- }
873
- #toEpoch(iso) {
874
- return Math.floor(Date.parse(iso) / 1e3) - this.caps.epochOffset;
875
- }
876
- /**
877
- * The WHERE half of a filtered read, appending its bind values to `params`.
878
- *
879
- * Shared by `search` and `groupBy` so the two cannot drift: a filter that
880
- * narrowed a listing but not its aggregate would make "count per sender in
881
- * INBOX" quietly count the whole archive.
882
- *
883
- * Call this before adding any other bind value — the placeholders it appends
884
- * have to come first in the parameter list, which mirrors WHERE preceding
885
- * ORDER BY and LIMIT in every statement built from it.
886
- */
887
- #filterPredicate(filters, params) {
888
- const where = ["m.deleted = 0"];
889
- where.push(this.#mailboxPredicate(filters.mailboxRowids, params));
890
- if (filters.query) {
891
- where.push("(s.subject LIKE ? ESCAPE '\\' OR a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
892
- params.push(contains(filters.query), contains(filters.query), contains(filters.query));
893
- }
894
- if (filters.subject) {
895
- where.push("s.subject LIKE ? ESCAPE '\\'");
896
- params.push(contains(filters.subject));
897
- }
898
- if (filters.sender) {
899
- where.push("(a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
900
- params.push(contains(filters.sender), contains(filters.sender));
901
- }
902
- if (filters.recipient && this.caps.has.recipients) {
903
- where.push("EXISTS (SELECT 1 FROM recipients r JOIN addresses ra ON ra.ROWID = r.address WHERE r.message = m.ROWID AND ra.address LIKE ? ESCAPE '\\')");
904
- params.push(contains(filters.recipient));
905
- }
906
- if (filters.unreadOnly) where.push("m.read = 0");
907
- if (filters.flaggedOnly && this.caps.has.flagged) where.push("m.flagged = 1");
908
- if (filters.hasAttachment && this.caps.has.attachments) where.push("EXISTS (SELECT 1 FROM attachments at WHERE at.message = m.ROWID)");
909
- if (filters.dateFrom) {
910
- where.push("m.date_received >= ?");
911
- params.push(this.#toEpoch(filters.dateFrom));
912
- }
913
- if (filters.dateTo) {
914
- where.push("m.date_received <= ?");
915
- params.push(this.#toEpoch(filters.dateTo));
916
- }
917
- return where.join(" AND ");
918
- }
919
- /**
920
- * The joins every filtered read needs. `s` and `a` are LEFT joins because a
921
- * message can legitimately have no subject row and no sender row, and an
922
- * INNER join here would drop exactly those from counts.
923
- */
924
- static #FROM = "FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender";
925
- /**
926
- * subject_prefix holds "Re: " / "Fwd: " separately from the deduplicated
927
- * subject row, so the displayed subject is the concatenation of the two.
928
- */
929
- get #subjectExpr() {
930
- return this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
931
- }
932
- search(filters) {
933
- const params = [];
934
- const predicate = this.#filterPredicate(filters, params);
935
- const sql = `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${this.#subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, ${this.caps.has.conversationId ? "m.conversation_id" : "NULL"} AS conversationId, ` + (this.caps.has.attachments ? "EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment " : "0 AS hasAttachment ") + `${EnvelopeIndex.#FROM} WHERE ${predicate} ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;
936
- params.push(filters.limit, filters.offset);
937
- return this.#db.prepare(sql).all(...params).map((r) => ({
938
- rowid: Number(r.rowid),
939
- mailboxUrl: String(r.mailboxUrl),
940
- subject: r.subject || null,
941
- senderAddress: r.senderAddress ?? null,
942
- senderName: r.senderName || null,
943
- dateReceived: this.#toIso(r.dateReceived),
944
- dateSent: this.#toIso(r.dateSent),
945
- read: Boolean(r.read),
946
- flagged: Boolean(r.flagged),
947
- size: r.size ?? null,
948
- conversationId: r.conversationId ?? null,
949
- hasAttachment: Boolean(r.hasAttachment)
950
- }));
951
- }
952
- /**
953
- * The column expression each groupable field aggregates on.
954
- *
955
- * A key here is the ONLY thing that reaches the statement — the tool matches
956
- * the caller's string against `GROUP_FIELDS` and passes the matched literal,
957
- * so no caller-controlled text is ever interpolated. `label` is a second,
958
- * human-readable form of the same group where one exists; it goes through
959
- * MAX() because everything outside GROUP BY has to be aggregated, and the
960
- * value is constant within a group anyway.
961
- */
962
- #groupExpr(field) {
963
- switch (field) {
964
- case "sender": return {
965
- key: "a.address",
966
- label: "MAX(NULLIF(a.comment, ''))"
967
- };
968
- case "mailbox": return {
969
- key: "m.mailbox",
970
- label: "MAX(mb.url)"
971
- };
972
- case "subject": return {
973
- key: this.#subjectExpr,
974
- label: "NULL"
975
- };
976
- case "day": return {
977
- key: this.#dateBucket("%Y-%m-%d"),
978
- label: "NULL"
979
- };
980
- case "month": return {
981
- key: this.#dateBucket("%Y-%m"),
982
- label: "NULL"
983
- };
984
- }
985
- }
986
- /** `date_received` is epoch-with-offset, so shift it before formatting. */
987
- #dateBucket(format) {
988
- return `strftime('${format}', datetime(m.date_received + ${this.caps.epochOffset}, 'unixepoch'))`;
989
- }
990
- /**
991
- * Count matches per group, over every match rather than a page of them.
992
- *
993
- * `filters.limit` caps the number of GROUPS returned, not the number of
994
- * messages considered — that distinction is the whole point of this lane.
995
- * Aggregating a page instead would answer "the top senders among the
996
- * twenty-five rows we happened to return", which is indistinguishable from a
997
- * real top-N unless you already knew to doubt it.
998
- */
999
- groupBy(filters, field) {
1000
- const { key, label } = this.#groupExpr(field);
1001
- const totalsParams = [];
1002
- const totalsPredicate = this.#filterPredicate(filters, totalsParams);
1003
- const totals = this.#db.prepare(`SELECT COUNT(*) AS totalRows, COUNT(DISTINCT ${key}) + MAX(CASE WHEN ${key} IS NULL THEN 1 ELSE 0 END) AS totalGroups ${EnvelopeIndex.#FROM} WHERE ${totalsPredicate}`).get(...totalsParams);
1004
- const params = [];
1005
- const predicate = this.#filterPredicate(filters, params);
1006
- params.push(filters.limit);
1007
- return {
1008
- groups: this.#db.prepare(`SELECT ${key} AS key, ${label} AS label, COUNT(*) AS count, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread, MIN(m.date_received) AS firstAt, MAX(m.date_received) AS lastAt ${EnvelopeIndex.#FROM} WHERE ${predicate} GROUP BY ${key} ORDER BY count DESC, key ASC LIMIT ?`).all(...params).map((r) => ({
1009
- key: r.key === null ? null : String(r.key),
1010
- label: r.label || null,
1011
- count: Number(r.count),
1012
- unread: Number(r.unread ?? 0),
1013
- firstAt: this.#toIso(r.firstAt),
1014
- lastAt: this.#toIso(r.lastAt)
1015
- })),
1016
- totalRows: totals.totalRows,
1017
- totalGroups: totals.totalGroups ?? 0
1018
- };
1019
- }
1020
- count(filters) {
1021
- const params = [];
1022
- const predicate = this.#mailboxPredicate(filters.mailboxRowids, params);
1023
- const row = this.#db.prepare(`SELECT COUNT(*) AS total, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread FROM messages m WHERE m.deleted = 0 AND ${predicate}`).get(...params);
1024
- return {
1025
- total: row.total,
1026
- unread: row.unread ?? 0
1027
- };
1028
- }
1029
- /** Every message in one conversation, oldest first. */
1030
- thread(conversationId, limit) {
1031
- if (!this.caps.has.conversationId) return [];
1032
- const subjectExpr = this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
1033
- return this.#db.prepare(`SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, m.conversation_id AS conversationId, 0 AS hasAttachment FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender WHERE m.deleted = 0 AND m.conversation_id = ? ORDER BY m.date_received ASC LIMIT ?`).all(conversationId, limit).map((r) => ({
1034
- rowid: Number(r.rowid),
1035
- mailboxUrl: String(r.mailboxUrl),
1036
- subject: r.subject || null,
1037
- senderAddress: r.senderAddress ?? null,
1038
- senderName: r.senderName || null,
1039
- dateReceived: this.#toIso(r.dateReceived),
1040
- dateSent: this.#toIso(r.dateSent),
1041
- read: Boolean(r.read),
1042
- flagged: Boolean(r.flagged),
1043
- size: r.size ?? null,
1044
- conversationId: r.conversationId ?? null,
1045
- hasAttachment: false
1046
- }));
1047
- }
1048
- /** conversation_id for one message, so get_thread can start from a ref. */
1049
- conversationOf(rowid) {
1050
- if (!this.caps.has.conversationId) return null;
1051
- return this.#db.prepare("SELECT conversation_id AS c FROM messages WHERE ROWID = ?").get(rowid)?.c ?? null;
1052
- }
1053
- };
1054
- //#endregion
1055
- //#region src/client/jxa/core.ts
1056
- /**
1057
- * JXA script fragments.
1058
- *
1059
- * Every script here is a static constant. None of them may contain a template
1060
- * interpolation — `osascript.assertStaticScript` rejects any script containing
1061
- * `${`, and that includes JavaScript template literals written *inside* the JXA
1062
- * source. Use string concatenation in JXA code.
1063
- *
1064
- * Every script follows the same contract:
1065
- * - it reads its parameters from `JSON.parse(argv[0])`
1066
- * - it returns `JSON.stringify({ok: true, data})` on success
1067
- * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an
1068
- * application-level failure, still exiting 0
1069
- * so that a non-zero exit always means infrastructure rather than "no such mailbox".
1058
+ * Every script here is a static constant. None of them may contain a template
1059
+ * interpolation — `osascript.assertStaticScript` rejects any script containing
1060
+ * `${`, and that includes JavaScript template literals written *inside* the JXA
1061
+ * source. Use string concatenation in JXA code.
1062
+ *
1063
+ * Every script follows the same contract:
1064
+ * - it reads its parameters from `JSON.parse(argv[0])`
1065
+ * - it returns `JSON.stringify({ok: true, data})` on success
1066
+ * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an
1067
+ * application-level failure, still exiting 0
1068
+ * so that a non-zero exit always means infrastructure rather than "no such mailbox".
1070
1069
  */
1071
1070
  /**
1072
1071
  * Shared prelude.
@@ -1576,155 +1575,19 @@ function run(argv) {
1576
1575
  }
1577
1576
  `;
1578
1577
  //#endregion
1579
- //#region src/client/jxa/read.ts
1580
- /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
1581
- const LIST_ACCOUNTS = script(`
1582
- var accts = M.accounts();
1583
- var out = [];
1584
- for (var i = 0; i < accts.length; i++) {
1585
- var a = accts[i];
1586
- out.push({
1587
- id: prop(function () { return a.id(); }, null),
1588
- name: prop(function () { return a.name(); }, null),
1589
- enabled: prop(function () { return a.enabled(); }, null),
1590
- accountType: prop(function () { return String(a.accountType()); }, null),
1591
- emailAddresses: prop(function () { return a.emailAddresses(); }, []),
1592
- fullName: prop(function () { return a.fullName(); }, null),
1593
- // Path objects need String(); JSON.stringify renders them as {}.
1594
- directory: prop(function () { return String(a.accountDirectory()); }, null),
1595
- messageCaching: prop(function () { return String(a.messageCaching()); }, null),
1596
- mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
1597
- });
1598
- }
1599
- return ok(out);
1600
- `);
1578
+ //#region src/client/jxa/write.ts
1601
1579
  /**
1602
- * Mailboxes with counts. Counts come from AppleScript rather than the index
1603
- * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
1604
- * therefore never need to degrade when Full Disk Access is missing.
1605
- */
1606
- const LIST_MAILBOXES = script(`
1607
- var accts = M.accounts();
1608
- var out = [];
1609
- for (var i = 0; i < accts.length; i++) {
1610
- var a = accts[i];
1611
- var uuid = prop(function () { return a.id(); }, null);
1612
- if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
1613
- var boxes = a.mailboxes();
1614
- for (var j = 0; j < boxes.length; j++) {
1615
- var b = boxes[j];
1616
- var entry = {
1617
- accountUuid: uuid,
1618
- accountName: prop(function () { return a.name(); }, null),
1619
- name: prop(function () { return b.name(); }, null)
1620
- };
1621
- if (p.withCounts) {
1622
- entry.unread = prop(function () { return b.unreadCount(); }, null);
1623
- entry.total = prop(function () { return b.messages.length; }, null);
1624
- }
1625
- out.push(entry);
1626
- }
1627
- }
1628
- return ok(out);
1629
- `);
1630
- /** Total and unread for one mailbox. */
1631
- const COUNT_MAILBOX = script(`
1632
- var acct = findAccount(M, p.accountUuid);
1633
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1634
- var mb = resolveMailbox(acct, p.mailbox);
1635
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1636
- return ok({
1637
- accountUuid: p.accountUuid,
1638
- mailbox: prop(function () { return mb.name(); }, p.mailbox),
1639
- total: prop(function () { return mb.messages.length; }, null),
1640
- unread: prop(function () { return mb.unreadCount(); }, null)
1641
- });
1642
- `);
1643
- /**
1644
- * The degraded listing lane: newest N of one mailbox, used when the Envelope
1645
- * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
1646
- * which is why the caller caps N hard (default 50) instead of paginating.
1647
- */
1648
- const LIST_RECENT = script(`
1649
- var acct = findAccount(M, p.accountUuid);
1650
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1651
- var mb = resolveMailbox(acct, p.mailbox);
1652
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1653
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1654
-
1655
- var total = prop(function () { return mb.messages.length; }, 0);
1656
- var n = Math.min(p.limit || 20, total);
1657
- if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
1658
-
1659
- // Batch the property reads: one Apple Event per property beats one per message
1660
- // by roughly 6x. slice() on the message collection keeps it to a range specifier.
1661
- var slice = mb.messages.slice(0, n);
1662
- var subjects = prop(function () { return slice.subject(); }, []);
1663
- var senders = prop(function () { return slice.sender(); }, []);
1664
- var dates = prop(function () { return slice.dateReceived(); }, []);
1665
- var reads = prop(function () { return slice.readStatus(); }, []);
1666
- var flags = prop(function () { return slice.flaggedStatus(); }, []);
1667
- var ids = prop(function () { return slice.id(); }, []);
1668
-
1669
- var out = [];
1670
- for (var i = 0; i < n; i++) {
1671
- out.push({
1672
- id: ids[i] === undefined ? null : ids[i],
1673
- accountUuid: p.accountUuid,
1674
- mailbox: mailboxName,
1675
- subject: subjects[i] === undefined ? null : subjects[i],
1676
- sender: senders[i] === undefined ? null : senders[i],
1677
- dateReceived: iso(dates[i]),
1678
- read: reads[i] === undefined ? null : reads[i],
1679
- flagged: flags[i] === undefined ? null : flags[i]
1680
- });
1681
- }
1682
- return ok({ mailbox: mailboxName, total: total, messages: out });
1683
- `);
1684
- /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
1685
- const GET_MESSAGES = script(`
1686
- var acct = findAccount(M, p.accountUuid);
1687
- if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
1688
- var mb = resolveMailbox(acct, p.mailbox);
1689
- if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
1690
- var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
1691
-
1692
- var out = [];
1693
- for (var i = 0; i < p.ids.length; i++) {
1694
- var id = p.ids[i];
1695
- try {
1696
- var m = mb.messages.byId(id);
1697
- var summary = messageSummary(m, p.accountUuid, mailboxName);
1698
- if (p.withContent) {
1699
- summary.content = prop(function () { return m.content(); }, null);
1700
- }
1701
- if (p.withSource) {
1702
- summary.source = prop(function () { return m.source(); }, null);
1703
- }
1704
- if (p.withHeaders) {
1705
- summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
1706
- }
1707
- out.push(summary);
1708
- } catch (e) {
1709
- out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
1710
- }
1711
- }
1712
- return ok(out);
1713
- `);
1714
- //#endregion
1715
- //#region src/client/jxa/write.ts
1716
- /**
1717
- * Mutating scripts.
1718
- *
1719
- * Two rules hold across every one of them:
1720
- *
1721
- * 1. **The post-state is re-read from Mail inside the same script.** Mail
1722
- * updates its Envelope Index eventually, not immediately, so verifying a
1723
- * write by re-querying the index can report the old value and send an agent
1724
- * into a mark-it-again loop. What Mail says right after the mutation is the
1725
- * only trustworthy answer.
1726
- * 2. **Refs are grouped by mailbox by the caller**, so a batch of 50 messages
1727
- * in one mailbox costs one Apple Event, not 50.
1580
+ * Mutating scripts.
1581
+ *
1582
+ * Two rules hold across every one of them:
1583
+ *
1584
+ * 1. **The post-state is re-read from Mail inside the same script.** Mail
1585
+ * updates its Envelope Index eventually, not immediately, so verifying a
1586
+ * write by re-querying the index can report the old value and send an agent
1587
+ * into a mark-it-again loop. What Mail says right after the mutation is the
1588
+ * only trustworthy answer.
1589
+ * 2. **Refs are grouped by mailbox by the caller**, so a batch of 50 messages
1590
+ * in one mailbox costs one Apple Event, not 50.
1728
1591
  */
1729
1592
  /** Set any combination of read / flagged / flagIndex / junk on a batch of ids. */
1730
1593
  /**
@@ -2316,209 +2179,866 @@ const UPDATE_DRAFT = script(`
2316
2179
  * Nothing here reports a draft as ready on the strength of an assignment having
2317
2180
  * been accepted, because that is exactly what lied.
2318
2181
  */
2319
- const REPLY_OR_FORWARD = script(`
2182
+ const REPLY_OR_FORWARD = script(`
2183
+ var acct = findAccount(M, p.accountUuid);
2184
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
2185
+ var mb = resolveMailbox(acct, p.mailbox);
2186
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
2187
+
2188
+ var original;
2189
+ try {
2190
+ original = mb.messages.byId(p.id);
2191
+ original.subject();
2192
+ } catch (e) {
2193
+ return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
2194
+ }
2195
+
2196
+ // Asked BEFORE anything is opened, and that ordering is the fix for the
2197
+ // failure this tool was best known for. The two grants below fail in exactly
2198
+ // the state where a composer is already on screen, so the old shape left an
2199
+ // empty reply window behind on every attempt and told the user to close it.
2200
+ // Nothing about the check needs the window to exist.
2201
+ var SE = Application("System Events");
2202
+ var reach = composerReach(SE);
2203
+ if (!reach.ok) return err("COMPOSER_NOT_FOUND", composerGrantMessage(p.mode, reach));
2204
+
2205
+ // The window is opened even when sending immediately: it is where the body
2206
+ // has to be typed, and sending from it sends what was verified rather than
2207
+ // whatever the disconnected scripting object thinks it holds.
2208
+ var draft;
2209
+ if (p.mode === "forward") {
2210
+ draft = M.forward(original, { openingWindow: true });
2211
+ } else {
2212
+ draft = M.reply(original, { openingWindow: true, replyToAll: p.replyToAll ? true : false });
2213
+ }
2214
+
2215
+ var subject = String(prop(function () { return draft.subject(); }, ""));
2216
+ if (!subject) return err("COMPOSER_NOT_FOUND", "Mail did not return a composer for the " + p.mode + ".");
2217
+
2218
+ var proc = SE.processes.byName("Mail");
2219
+ var win = composerWindow(proc, subject, 8000);
2220
+ if (!win) {
2221
+ // The pre-flight passed and this still failed, so the grants are live and
2222
+ // the window is the problem. Nothing has been typed yet, so the composer we
2223
+ // opened is ours to take back.
2224
+ var closedUnreadable = discardComposer(M, draft);
2225
+ return err(
2226
+ "COMPOSER_NOT_FOUND",
2227
+ "Mail was asked to open a " + p.mode + " window for \\"" + subject + "\\" and no such window " +
2228
+ "was readable within 8s, although Mail's other windows read fine — so this is not a " +
2229
+ "permission. Nothing was written. Mail may still have been opening it. The windows visible " +
2230
+ "at the time were: " + JSON.stringify(reach.windows) + ". " +
2231
+ (closedUnreadable
2232
+ ? "The composer was closed again without saving, so a retry is safe."
2233
+ : "The composer could NOT be closed from here — look for an empty " + p.mode +
2234
+ " window in Mail and close it, or a retry leaves a second one behind.")
2235
+ );
2236
+ }
2237
+
2238
+ // Recipients go through the scripting object, which does work for them, but
2239
+ // only once the composer exists.
2240
+ if (p.mode === "forward") {
2241
+ var addrs = p.to || [];
2242
+ for (var i = 0; i < addrs.length; i++) {
2243
+ draft.toRecipients.push(M.ToRecipient({ address: addrs[i] }));
2244
+ }
2245
+ }
2246
+
2247
+ var bodyArea = findBodyArea(win, 0);
2248
+ if (!bodyArea) {
2249
+ var closedNoBody = discardComposer(M, draft);
2250
+ return err(
2251
+ "COMPOSER_NOT_FOUND",
2252
+ "The " + p.mode + " window for \\"" + subject + "\\" is open, but its body cannot be reached " +
2253
+ "through the accessibility interface, which is the only way into it. Nothing was written. " +
2254
+ (closedNoBody
2255
+ ? "The window was closed again without saving."
2256
+ : "The window could NOT be closed from here and is still on screen.")
2257
+ );
2258
+ }
2259
+
2260
+ var previous = prop(function () {
2261
+ return SE.applicationProcesses.whose({ frontmost: true })[0].name();
2262
+ }, null);
2263
+ var restore = function () {
2264
+ if (previous && previous !== "Mail") {
2265
+ try { SE.processes.byName(previous).frontmost = true; } catch (e) {}
2266
+ }
2267
+ };
2268
+
2269
+ var bodyVerified = null;
2270
+ var verifiedChars = 0;
2271
+ if (p.body) {
2272
+ var body = String(p.body);
2273
+ // Confirm the opening of the body rather than all of it. Reading the whole
2274
+ // of a long reply plus the quote it sits above costs seconds of Apple
2275
+ // Events, and buys nothing: a paste either arrives whole or does not arrive,
2276
+ // which is what was measured, so the top of it is the tell.
2277
+ var expected = body.length > 400 ? body.slice(0, 400) : body;
2278
+ var sizeBefore = composerBodySize(bodyArea);
2279
+ bodyVerified = false;
2280
+
2281
+ try {
2282
+ proc.frontmost = true;
2283
+ pause(0.4);
2284
+ for (var attempt = 0; attempt < 2 && !bodyVerified; attempt++) {
2285
+ pasteIntoComposer(win, bodyArea, body);
2286
+ var after = composerBodyText(bodyArea, expected.length + 400);
2287
+ bodyVerified = after !== null && containsText(after, expected);
2288
+ if (bodyVerified) {
2289
+ verifiedChars = expected.length;
2290
+ } else if (composerBodySize(bodyArea) !== sizeBefore) {
2291
+ // Something went in that we cannot match. Pasting again would put the
2292
+ // reply in the draft twice, and nothing here can undo that.
2293
+ break;
2294
+ }
2295
+ }
2296
+ } catch (e) {
2297
+ bodyVerified = false;
2298
+ }
2299
+
2300
+ if (!bodyVerified) {
2301
+ restore();
2302
+ // Take the window back only when it is provably still empty. A paste that
2303
+ // landed and could not be READ is a different thing from one that never
2304
+ // landed, and closing that one would destroy the reply with no way to get
2305
+ // it back -- so it is left on screen for the user to judge.
2306
+ var landed = composerBodySize(bodyArea) !== sizeBefore;
2307
+ var closedUnverified = landed ? false : discardComposer(M, draft);
2308
+ return err(
2309
+ "DRAFT_BODY_NOT_SET",
2310
+ "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
2311
+ "body did not go in: reading the composer back does not show the text that was sent. It " +
2312
+ "MUST NOT be described to the user as ready. " +
2313
+ (closedUnverified
2314
+ ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2315
+ : landed
2316
+ ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2317
+ "than discarded — look at it in Mail before retrying, because a retry would paste " +
2318
+ "the reply in twice."
2319
+ : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2320
+ "leaves a second draft behind.")
2321
+ );
2322
+ }
2323
+ }
2324
+
2325
+ if (p.sendNow) {
2326
+ // Sent from the window, so what goes out is what was just verified.
2327
+ var clicked = false;
2328
+ try {
2329
+ proc.frontmost = true;
2330
+ pause(0.4);
2331
+ try { win.actions.byName("AXRaise").perform(); } catch (e) {}
2332
+ pause(0.3);
2333
+ var send = proc.menuBars[0].menuBarItems.byName("Message").menus[0].menuItems.byName("Send");
2334
+ if (prop(function () { return send.enabled(); }, false)) {
2335
+ send.click();
2336
+ clicked = true;
2337
+ }
2338
+ } catch (e) {
2339
+ clicked = false;
2340
+ }
2341
+ // The window closing is the confirmation that it went. Wait for it rather
2342
+ // than sampling once: reporting a slow close as a failure would invite a
2343
+ // retry, and a retry after a send that DID go sends the mail twice.
2344
+ var stillOpen = true;
2345
+ var waited = 0;
2346
+ while (clicked && waited < 8000) {
2347
+ pause(0.5);
2348
+ waited += 500;
2349
+ if (composerWindow(proc, subject, 0) === null) { stillOpen = false; break; }
2350
+ }
2351
+ restore();
2352
+ if (!clicked) {
2353
+ return err(
2354
+ "SEND_FAILED",
2355
+ "The " + p.mode + " was composed and its body verified, but Message > Send would not " +
2356
+ "activate, so NOTHING WAS SENT. The draft is on screen with the right text in it and can " +
2357
+ "be sent by hand."
2358
+ );
2359
+ }
2360
+ if (stillOpen) {
2361
+ return err(
2362
+ "SEND_UNCONFIRMED",
2363
+ "The " + p.mode + " was composed, its body verified, and Send was clicked — but the window " +
2364
+ "was still open 8s later, so whether it went cannot be confirmed from here. DO NOT send it " +
2365
+ "again: check Sent in Mail first, because a retry would send it twice."
2366
+ );
2367
+ }
2368
+ return ok({ sent: true, mode: p.mode, bodyVerified: bodyVerified,
2369
+ verifiedChars: verifiedChars, subject: subject });
2370
+ }
2371
+
2372
+ restore();
2373
+ return ok({
2374
+ sent: false,
2375
+ draft: true,
2376
+ mode: p.mode,
2377
+ subject: subject,
2378
+ bodyVerified: bodyVerified,
2379
+ verifiedChars: verifiedChars,
2380
+ note: bodyVerified
2381
+ ? "Draft window is open in Mail for review; its body was read back out of the window and matches."
2382
+ : "Draft window is open in Mail for review."
2383
+ });
2384
+ `, { allowLaunch: true });
2385
+ /**
2386
+ * Open a reply or forward composer, address it, and stop.
2387
+ *
2388
+ * The Apple Events half of the NATIVE composer path — see `client/ax.ts` for
2389
+ * the other half and `client/compose.ts` for the sequence that joins them.
2390
+ *
2391
+ * It exists because a JXA object reference cannot outlive the `osascript`
2392
+ * process that made it, and `packages/core/src/osascript.ts` spawns one per
2393
+ * call by design. The old flow held `draft` from `M.reply(...)` all the way
2394
+ * through to `draft.send()`, with every Accessibility step in between; once
2395
+ * those steps move out of the script, the reference cannot survive to the end
2396
+ * of it. So this script does everything that NEEDS the reference — open,
2397
+ * address — and returns the subject, which is the identity the native half
2398
+ * addresses the window by.
2399
+ *
2400
+ * **No System Events here, deliberately.** That is the whole point of the
2401
+ * split: this half needs Automation for Mail, which every other write tool
2402
+ * already has, and nothing else. The second grant goes with the second half.
2403
+ *
2404
+ * Recipients go through the scripting object, which does work for them, and
2405
+ * only once the composer exists.
2406
+ */
2407
+ const OPEN_COMPOSER = script(`
2408
+ var acct = findAccount(M, p.accountUuid);
2409
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
2410
+ var mb = resolveMailbox(acct, p.mailbox);
2411
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
2412
+
2413
+ var original;
2414
+ try {
2415
+ original = mb.messages.byId(p.id);
2416
+ original.subject();
2417
+ } catch (e) {
2418
+ return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
2419
+ }
2420
+
2421
+ var draft;
2422
+ if (p.mode === "forward") {
2423
+ draft = M.forward(original, { openingWindow: true });
2424
+ } else {
2425
+ draft = M.reply(original, { openingWindow: true, replyToAll: p.replyToAll ? true : false });
2426
+ }
2427
+
2428
+ var subject = String(prop(function () { return draft.subject(); }, ""));
2429
+ if (!subject) {
2430
+ return err("COMPOSER_NOT_FOUND", "Mail did not return a composer for the " + p.mode + ".");
2431
+ }
2432
+
2433
+ if (p.mode === "forward") {
2434
+ var addrs = p.to || [];
2435
+ for (var i = 0; i < addrs.length; i++) {
2436
+ draft.toRecipients.push(M.ToRecipient({ address: addrs[i] }));
2437
+ }
2438
+ }
2439
+
2440
+ return ok({ subject: subject });
2441
+ `, { allowLaunch: true });
2442
+ //#endregion
2443
+ //#region src/client/compose.ts
2444
+ const run = promisify(execFile);
2445
+ /**
2446
+ * Reply or forward, with the body driven natively.
2447
+ *
2448
+ * ## Why this is two halves rather than one script
2449
+ *
2450
+ * A JXA object reference cannot outlive the `osascript` process that made it,
2451
+ * and `packages/core/src/osascript.ts` spawns one per call by design. The
2452
+ * original flow held `draft` from `M.reply(...)` through to `draft.send()`, with
2453
+ * every Accessibility step in between — so moving those steps out of the script
2454
+ * necessarily ends the reference before the send.
2455
+ *
2456
+ * The arrangement that needs no reference: `OPEN_COMPOSER` opens and addresses
2457
+ * the composer and returns the SUBJECT, which is an identity the native half can
2458
+ * find a window by; everything after is Accessibility, including the send, which
2459
+ * becomes command-shift-D rather than `draft.send()`.
2460
+ *
2461
+ * The alternative — re-finding the draft in a third Apple Events call — was
2462
+ * rejected: drafts are discovered by subject, so two with the same one are
2463
+ * indistinguishable, and this is the single path whose named failure is sending
2464
+ * the wrong thing.
2465
+ *
2466
+ * ## What is given up, and it is stated rather than hidden
2467
+ *
2468
+ * The System Events path discards the composer when a paste provably did not
2469
+ * land, so a retry is safe. This one cannot: closing an unsaved composer raises
2470
+ * a save sheet whose buttons are LOCALISED, and pressing a button by a name that
2471
+ * is only right in English is worse than not pressing one. So a failed compose
2472
+ * here always leaves the window on screen and says so. Strictly safer — nothing
2473
+ * a person wrote is ever destroyed — and strictly less tidy.
2474
+ */
2475
+ /** How long to wait for the composer, matching the System Events path's 8s. */
2476
+ const COMPOSER_TIMEOUT_MS = 8e3;
2477
+ /** How long to wait for the window to close before calling a send unconfirmed. */
2478
+ const SEND_TIMEOUT_MS = 5e3;
2479
+ /**
2480
+ * Confirm the opening of the body rather than all of it.
2481
+ *
2482
+ * A paste either arrives whole or does not arrive, which is what was measured,
2483
+ * so the top of it is the tell.
2484
+ */
2485
+ const VERIFY_CHARS = 400;
2486
+ const systemClipboard = {
2487
+ async read() {
2488
+ try {
2489
+ return (await run("/usr/bin/pbpaste", [])).stdout;
2490
+ } catch {
2491
+ return null;
2492
+ }
2493
+ },
2494
+ async write(text) {
2495
+ const child = execFile("/usr/bin/pbcopy", []);
2496
+ child.stdin?.end(text);
2497
+ await new Promise((resolve, reject) => {
2498
+ child.on("close", resolve);
2499
+ child.on("error", reject);
2500
+ });
2501
+ }
2502
+ };
2503
+ /**
2504
+ * Borrow the clipboard, and put it back.
2505
+ *
2506
+ * The same cost the System Events path documents and for the same reason: this
2507
+ * is a paste, so the pasteboard is the mechanism. A clipboard holding an image
2508
+ * or a file promise still comes back as text, because there is no way to carry
2509
+ * an arbitrary item across without knowing its type.
2510
+ */
2511
+ const withClipboard = async (clipboard, text, body) => {
2512
+ const saved = await clipboard.read();
2513
+ await clipboard.write(text);
2514
+ try {
2515
+ return await body();
2516
+ } finally {
2517
+ if (saved !== null) try {
2518
+ await clipboard.write(saved);
2519
+ } catch {}
2520
+ }
2521
+ };
2522
+ const paste = async (lane, clipboard, ref, text) => {
2523
+ const expected = text.length > VERIFY_CHARS ? text.slice(0, VERIFY_CHARS) : text;
2524
+ const sizeBefore = await lane.bodySize(ref.body);
2525
+ return withClipboard(clipboard, text, async () => {
2526
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2527
+ if (await lane.paste(ref)) {
2528
+ const after = await lane.bodyText(ref.body);
2529
+ if (after !== null && containsText(after, expected)) return {
2530
+ verified: true,
2531
+ landed: true
2532
+ };
2533
+ }
2534
+ if (await lane.bodySize(ref.body) !== sizeBefore) break;
2535
+ }
2536
+ return {
2537
+ verified: false,
2538
+ landed: await lane.bodySize(ref.body) !== sizeBefore
2539
+ };
2540
+ });
2541
+ };
2542
+ const replyOrForwardNatively = async (lane, runner, params, opts = {}) => {
2543
+ const clipboard = opts.clipboard ?? systemClipboard;
2544
+ const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;
2545
+ const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;
2546
+ const watch = lane.watch();
2547
+ const reach = await lane.reach();
2548
+ if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));
2549
+ const subject = (await runner.run(OPEN_COMPOSER, params)).subject;
2550
+ const ref = await lane.findComposer(subject, composerTimeoutMs);
2551
+ if (!ref) return {
2552
+ ok: false,
2553
+ subject,
2554
+ bodyVerified: null,
2555
+ verifiedChars: 0,
2556
+ sent: false,
2557
+ note: `Mail was asked to open a ${params.mode} window for "${subject}" and no such window was readable within ${composerTimeoutMs / 1e3}s, although Mail's other windows read fine — so this is not a permission. Nothing was written. The window may still be on screen: look for an empty ${params.mode} in Mail before retrying, because a retry would leave a second one behind. Windows visible at the time: ${JSON.stringify(reach.windows)}.` + interferenceNote(await watch.check())
2558
+ };
2559
+ let bodyVerified = null;
2560
+ let verifiedChars = 0;
2561
+ if (params.body) {
2562
+ const result = await paste(lane, clipboard, ref, params.body);
2563
+ bodyVerified = result.verified;
2564
+ verifiedChars = result.verified ? Math.min(params.body.length, VERIFY_CHARS) : 0;
2565
+ if (!result.verified) return {
2566
+ ok: false,
2567
+ subject,
2568
+ bodyVerified: false,
2569
+ verifiedChars: 0,
2570
+ sent: false,
2571
+ note: `The ${params.mode} window for "${subject}" was opened and correctly addressed, but the body did not go in: reading the composer back does not show the text that was sent. It MUST NOT be described to the user as ready. ` + (result.landed ? "SOMETHING DID land in it that could not be read back — look at it in Mail before retrying, because a retry would paste the reply in twice." : "Nothing landed in it. It was left open rather than discarded, because closing an unsaved composer raises a save sheet whose buttons are localised. Close it in Mail, then retry.") + interferenceNote(await watch.check())
2572
+ };
2573
+ }
2574
+ await lane.finish(params.sendNow);
2575
+ const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;
2576
+ return {
2577
+ ok: params.sendNow ? sent : true,
2578
+ subject,
2579
+ bodyVerified,
2580
+ verifiedChars,
2581
+ sent,
2582
+ note: params.sendNow ? sent ? "Sent." : `The ${params.mode} was composed and verified, but its window is still open ${sendTimeoutMs / 1e3}s after the send, so it may not have gone. Check Mail before retrying.` : "Draft window is open in Mail for review."
2583
+ };
2584
+ };
2585
+ //#endregion
2586
+ //#region src/client/schema.ts
2587
+ const REQUIRED = {
2588
+ messages: [
2589
+ "mailbox",
2590
+ "subject",
2591
+ "sender",
2592
+ "date_received",
2593
+ "read",
2594
+ "deleted"
2595
+ ],
2596
+ mailboxes: ["url"],
2597
+ subjects: ["subject"],
2598
+ addresses: ["address"]
2599
+ };
2600
+ const introspect = (db, now) => {
2601
+ const fingerprint = fingerprintSchema(db);
2602
+ const tables = tableMap(db);
2603
+ const tableNames = Object.keys(tables);
2604
+ const missing = [];
2605
+ for (const [table, cols] of Object.entries(REQUIRED)) {
2606
+ if (!tables[table]) {
2607
+ missing.push(`${table} (table)`);
2608
+ continue;
2609
+ }
2610
+ for (const c of cols) if (!tables[table]?.includes(c)) missing.push(`${table}.${c}`);
2611
+ }
2612
+ const messageCols = tables.messages ?? [];
2613
+ let epoch = {
2614
+ offset: 0,
2615
+ reason: "not probed"
2616
+ };
2617
+ if (missing.length === 0) {
2618
+ const row = db.prepare("SELECT MAX(date_received) AS m FROM messages").get();
2619
+ epoch = detectEpoch(row?.m ?? null, now);
2620
+ }
2621
+ return {
2622
+ fingerprint,
2623
+ tables,
2624
+ has: {
2625
+ labels: tableNames.includes("labels"),
2626
+ recipients: tableNames.includes("recipients"),
2627
+ attachments: tableNames.includes("attachments"),
2628
+ subjects: tableNames.includes("subjects"),
2629
+ addresses: tableNames.includes("addresses"),
2630
+ subjectPrefix: messageCols.includes("subject_prefix"),
2631
+ conversationId: messageCols.includes("conversation_id"),
2632
+ flagged: messageCols.includes("flagged"),
2633
+ dateSent: messageCols.includes("date_sent"),
2634
+ messageIdHeader: (tables.message_global_data ?? []).includes("message_id_header"),
2635
+ mailboxCounts: (tables.mailboxes ?? []).includes("unread_count")
2636
+ },
2637
+ epochOffset: epoch.offset,
2638
+ epochReason: epoch.reason,
2639
+ missing
2640
+ };
2641
+ };
2642
+ const assertUsable = (caps) => {
2643
+ if (caps.missing.length > 0) throw new SchemaDriftError(`Mail's search index is not the shape this server knows how to read (missing: ${caps.missing.join(", ")}). This usually means a macOS upgrade changed the schema. The AppleScript lane still works; please report schema fingerprint ${caps.fingerprint}.`, {
2644
+ fingerprint: caps.fingerprint,
2645
+ missing: caps.missing
2646
+ });
2647
+ };
2648
+ //#endregion
2649
+ //#region src/client/envelope.ts
2650
+ /**
2651
+ * What a mail query can group on.
2652
+ *
2653
+ * The single source of truth for both the tool's enum and the SQL expressions
2654
+ * in `#groupExpr` — a field can only be asked for if it is listed here, which
2655
+ * is what keeps caller strings out of the statement.
2656
+ */
2657
+ const GROUP_FIELDS = [
2658
+ "sender",
2659
+ "mailbox",
2660
+ "subject",
2661
+ "day",
2662
+ "month"
2663
+ ];
2664
+ const contains = (value) => `%${escapeLike(value)}%`;
2665
+ const openIndex = (path, mode, logger) => {
2666
+ const { db, mode: opened, validated: caps } = openReadOnly(path, mode, {
2667
+ envVar: "APPLE_MAIL_INDEX_MODE",
2668
+ label: "Mail's search index",
2669
+ hint: "If this is a permission error, grant Full Disk Access to the app running this server.",
2670
+ validate: (conn) => {
2671
+ const found = introspect(conn);
2672
+ assertUsable(found);
2673
+ return found;
2674
+ },
2675
+ fatal: (err) => err instanceof SchemaDriftError,
2676
+ onFallback: () => logger?.warn?.("opened the index with immutable=1; results may omit mail that is still in the -wal")
2677
+ });
2678
+ return {
2679
+ db,
2680
+ mode: opened,
2681
+ caps
2682
+ };
2683
+ };
2684
+ var EnvelopeIndex = class EnvelopeIndex {
2685
+ #db;
2686
+ caps;
2687
+ mode;
2688
+ constructor(opened) {
2689
+ this.#db = opened.db;
2690
+ this.caps = opened.caps;
2691
+ this.mode = opened.mode;
2692
+ }
2693
+ close() {
2694
+ try {
2695
+ this.#db.close();
2696
+ } catch {}
2697
+ }
2698
+ /** id -> url for every mailbox, so results can be mapped back to scriptable names. */
2699
+ mailboxes() {
2700
+ const hasCounts = this.caps.has.mailboxCounts;
2701
+ return this.#db.prepare(hasCounts ? "SELECT ROWID AS rowid, url, total_count AS total, unread_count AS unread FROM mailboxes" : "SELECT ROWID AS rowid, url, NULL AS total, NULL AS unread FROM mailboxes").all();
2702
+ }
2703
+ /**
2704
+ * Restrict to a set of mailboxes.
2705
+ *
2706
+ * The `labels` half is not optional for Gmail. Gmail-over-IMAP keeps every
2707
+ * message in `[Gmail]/All Mail` and expresses INBOX membership as a label
2708
+ * row, so `m.mailbox IN (...)` alone returns an EMPTY inbox — measured here
2709
+ * as 0 rows against 51,128 real messages.
2710
+ */
2711
+ #mailboxPredicate(rowids, params) {
2712
+ if (!rowids?.length) return "1=1";
2713
+ const placeholders = rowids.map(() => "?").join(",");
2714
+ if (!this.caps.has.labels) {
2715
+ params.push(...rowids);
2716
+ return `m.mailbox IN (${placeholders})`;
2717
+ }
2718
+ params.push(...rowids, ...rowids);
2719
+ return `(m.mailbox IN (${placeholders}) OR m.ROWID IN (SELECT message_id FROM labels WHERE mailbox_id IN (${placeholders})))`;
2720
+ }
2721
+ #toIso(value) {
2722
+ if (value === null || !Number.isFinite(value)) return null;
2723
+ return (/* @__PURE__ */ new Date((value + this.caps.epochOffset) * 1e3)).toISOString();
2724
+ }
2725
+ #toEpoch(iso) {
2726
+ return Math.floor(Date.parse(iso) / 1e3) - this.caps.epochOffset;
2727
+ }
2728
+ /**
2729
+ * The WHERE half of a filtered read, appending its bind values to `params`.
2730
+ *
2731
+ * Shared by `search` and `groupBy` so the two cannot drift: a filter that
2732
+ * narrowed a listing but not its aggregate would make "count per sender in
2733
+ * INBOX" quietly count the whole archive.
2734
+ *
2735
+ * Call this before adding any other bind value — the placeholders it appends
2736
+ * have to come first in the parameter list, which mirrors WHERE preceding
2737
+ * ORDER BY and LIMIT in every statement built from it.
2738
+ */
2739
+ #filterPredicate(filters, params) {
2740
+ const where = ["m.deleted = 0"];
2741
+ where.push(this.#mailboxPredicate(filters.mailboxRowids, params));
2742
+ if (filters.query) {
2743
+ where.push("(s.subject LIKE ? ESCAPE '\\' OR a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
2744
+ params.push(contains(filters.query), contains(filters.query), contains(filters.query));
2745
+ }
2746
+ if (filters.subject) {
2747
+ where.push("s.subject LIKE ? ESCAPE '\\'");
2748
+ params.push(contains(filters.subject));
2749
+ }
2750
+ if (filters.sender) {
2751
+ where.push("(a.address LIKE ? ESCAPE '\\' OR a.comment LIKE ? ESCAPE '\\')");
2752
+ params.push(contains(filters.sender), contains(filters.sender));
2753
+ }
2754
+ if (filters.recipient && this.caps.has.recipients) {
2755
+ where.push("EXISTS (SELECT 1 FROM recipients r JOIN addresses ra ON ra.ROWID = r.address WHERE r.message = m.ROWID AND ra.address LIKE ? ESCAPE '\\')");
2756
+ params.push(contains(filters.recipient));
2757
+ }
2758
+ if (filters.unreadOnly) where.push("m.read = 0");
2759
+ if (filters.flaggedOnly && this.caps.has.flagged) where.push("m.flagged = 1");
2760
+ if (filters.hasAttachment && this.caps.has.attachments) where.push("EXISTS (SELECT 1 FROM attachments at WHERE at.message = m.ROWID)");
2761
+ if (filters.dateFrom) {
2762
+ where.push("m.date_received >= ?");
2763
+ params.push(this.#toEpoch(filters.dateFrom));
2764
+ }
2765
+ if (filters.dateTo) {
2766
+ where.push("m.date_received <= ?");
2767
+ params.push(this.#toEpoch(filters.dateTo));
2768
+ }
2769
+ return where.join(" AND ");
2770
+ }
2771
+ /**
2772
+ * The joins every filtered read needs. `s` and `a` are LEFT joins because a
2773
+ * message can legitimately have no subject row and no sender row, and an
2774
+ * INNER join here would drop exactly those from counts.
2775
+ */
2776
+ static #FROM = "FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender";
2777
+ /**
2778
+ * subject_prefix holds "Re: " / "Fwd: " separately from the deduplicated
2779
+ * subject row, so the displayed subject is the concatenation of the two.
2780
+ */
2781
+ get #subjectExpr() {
2782
+ return this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
2783
+ }
2784
+ search(filters) {
2785
+ const params = [];
2786
+ const predicate = this.#filterPredicate(filters, params);
2787
+ const sql = `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${this.#subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, ${this.caps.has.conversationId ? "m.conversation_id" : "NULL"} AS conversationId, ` + (this.caps.has.attachments ? "EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment " : "0 AS hasAttachment ") + `${EnvelopeIndex.#FROM} WHERE ${predicate} ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;
2788
+ params.push(filters.limit, filters.offset);
2789
+ return this.#db.prepare(sql).all(...params).map((r) => ({
2790
+ rowid: Number(r.rowid),
2791
+ mailboxUrl: String(r.mailboxUrl),
2792
+ subject: r.subject || null,
2793
+ senderAddress: r.senderAddress ?? null,
2794
+ senderName: r.senderName || null,
2795
+ dateReceived: this.#toIso(r.dateReceived),
2796
+ dateSent: this.#toIso(r.dateSent),
2797
+ read: Boolean(r.read),
2798
+ flagged: Boolean(r.flagged),
2799
+ size: r.size ?? null,
2800
+ conversationId: r.conversationId ?? null,
2801
+ hasAttachment: Boolean(r.hasAttachment)
2802
+ }));
2803
+ }
2804
+ /**
2805
+ * The column expression each groupable field aggregates on.
2806
+ *
2807
+ * A key here is the ONLY thing that reaches the statement — the tool matches
2808
+ * the caller's string against `GROUP_FIELDS` and passes the matched literal,
2809
+ * so no caller-controlled text is ever interpolated. `label` is a second,
2810
+ * human-readable form of the same group where one exists; it goes through
2811
+ * MAX() because everything outside GROUP BY has to be aggregated, and the
2812
+ * value is constant within a group anyway.
2813
+ */
2814
+ #groupExpr(field) {
2815
+ switch (field) {
2816
+ case "sender": return {
2817
+ key: "a.address",
2818
+ label: "MAX(NULLIF(a.comment, ''))"
2819
+ };
2820
+ case "mailbox": return {
2821
+ key: "m.mailbox",
2822
+ label: "MAX(mb.url)"
2823
+ };
2824
+ case "subject": return {
2825
+ key: this.#subjectExpr,
2826
+ label: "NULL"
2827
+ };
2828
+ case "day": return {
2829
+ key: this.#dateBucket("%Y-%m-%d"),
2830
+ label: "NULL"
2831
+ };
2832
+ case "month": return {
2833
+ key: this.#dateBucket("%Y-%m"),
2834
+ label: "NULL"
2835
+ };
2836
+ }
2837
+ }
2838
+ /** `date_received` is epoch-with-offset, so shift it before formatting. */
2839
+ #dateBucket(format) {
2840
+ return `strftime('${format}', datetime(m.date_received + ${this.caps.epochOffset}, 'unixepoch'))`;
2841
+ }
2842
+ /**
2843
+ * Count matches per group, over every match rather than a page of them.
2844
+ *
2845
+ * `filters.limit` caps the number of GROUPS returned, not the number of
2846
+ * messages considered — that distinction is the whole point of this lane.
2847
+ * Aggregating a page instead would answer "the top senders among the
2848
+ * twenty-five rows we happened to return", which is indistinguishable from a
2849
+ * real top-N unless you already knew to doubt it.
2850
+ */
2851
+ groupBy(filters, field) {
2852
+ const { key, label } = this.#groupExpr(field);
2853
+ const totalsParams = [];
2854
+ const totalsPredicate = this.#filterPredicate(filters, totalsParams);
2855
+ const totals = this.#db.prepare(`SELECT COUNT(*) AS totalRows, COUNT(DISTINCT ${key}) + MAX(CASE WHEN ${key} IS NULL THEN 1 ELSE 0 END) AS totalGroups ${EnvelopeIndex.#FROM} WHERE ${totalsPredicate}`).get(...totalsParams);
2856
+ const params = [];
2857
+ const predicate = this.#filterPredicate(filters, params);
2858
+ params.push(filters.limit);
2859
+ return {
2860
+ groups: this.#db.prepare(`SELECT ${key} AS key, ${label} AS label, COUNT(*) AS count, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread, MIN(m.date_received) AS firstAt, MAX(m.date_received) AS lastAt ${EnvelopeIndex.#FROM} WHERE ${predicate} GROUP BY ${key} ORDER BY count DESC, key ASC LIMIT ?`).all(...params).map((r) => ({
2861
+ key: r.key === null ? null : String(r.key),
2862
+ label: r.label || null,
2863
+ count: Number(r.count),
2864
+ unread: Number(r.unread ?? 0),
2865
+ firstAt: this.#toIso(r.firstAt),
2866
+ lastAt: this.#toIso(r.lastAt)
2867
+ })),
2868
+ totalRows: totals.totalRows,
2869
+ totalGroups: totals.totalGroups ?? 0
2870
+ };
2871
+ }
2872
+ count(filters) {
2873
+ const params = [];
2874
+ const predicate = this.#mailboxPredicate(filters.mailboxRowids, params);
2875
+ const row = this.#db.prepare(`SELECT COUNT(*) AS total, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread FROM messages m WHERE m.deleted = 0 AND ${predicate}`).get(...params);
2876
+ return {
2877
+ total: row.total,
2878
+ unread: row.unread ?? 0
2879
+ };
2880
+ }
2881
+ /** Every message in one conversation, oldest first. */
2882
+ thread(conversationId, limit) {
2883
+ if (!this.caps.has.conversationId) return [];
2884
+ const subjectExpr = this.caps.has.subjectPrefix ? "COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')" : "COALESCE(s.subject, '')";
2885
+ return this.#db.prepare(`SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${subjectExpr} AS subject, a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ${this.caps.has.dateSent ? "m.date_sent" : "NULL"} AS dateSent, m.read AS read, ${this.caps.has.flagged ? "m.flagged" : "0"} AS flagged, m.size AS size, m.conversation_id AS conversationId, 0 AS hasAttachment FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox LEFT JOIN subjects s ON s.ROWID = m.subject LEFT JOIN addresses a ON a.ROWID = m.sender WHERE m.deleted = 0 AND m.conversation_id = ? ORDER BY m.date_received ASC LIMIT ?`).all(conversationId, limit).map((r) => ({
2886
+ rowid: Number(r.rowid),
2887
+ mailboxUrl: String(r.mailboxUrl),
2888
+ subject: r.subject || null,
2889
+ senderAddress: r.senderAddress ?? null,
2890
+ senderName: r.senderName || null,
2891
+ dateReceived: this.#toIso(r.dateReceived),
2892
+ dateSent: this.#toIso(r.dateSent),
2893
+ read: Boolean(r.read),
2894
+ flagged: Boolean(r.flagged),
2895
+ size: r.size ?? null,
2896
+ conversationId: r.conversationId ?? null,
2897
+ hasAttachment: false
2898
+ }));
2899
+ }
2900
+ /** conversation_id for one message, so get_thread can start from a ref. */
2901
+ conversationOf(rowid) {
2902
+ if (!this.caps.has.conversationId) return null;
2903
+ return this.#db.prepare("SELECT conversation_id AS c FROM messages WHERE ROWID = ?").get(rowid)?.c ?? null;
2904
+ }
2905
+ };
2906
+ //#endregion
2907
+ //#region src/client/jxa/read.ts
2908
+ /** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */
2909
+ const LIST_ACCOUNTS = script(`
2910
+ var accts = M.accounts();
2911
+ var out = [];
2912
+ for (var i = 0; i < accts.length; i++) {
2913
+ var a = accts[i];
2914
+ out.push({
2915
+ id: prop(function () { return a.id(); }, null),
2916
+ name: prop(function () { return a.name(); }, null),
2917
+ enabled: prop(function () { return a.enabled(); }, null),
2918
+ accountType: prop(function () { return String(a.accountType()); }, null),
2919
+ emailAddresses: prop(function () { return a.emailAddresses(); }, []),
2920
+ fullName: prop(function () { return a.fullName(); }, null),
2921
+ // Path objects need String(); JSON.stringify renders them as {}.
2922
+ directory: prop(function () { return String(a.accountDirectory()); }, null),
2923
+ messageCaching: prop(function () { return String(a.messageCaching()); }, null),
2924
+ mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])
2925
+ });
2926
+ }
2927
+ return ok(out);
2928
+ `);
2929
+ /**
2930
+ * Mailboxes with counts. Counts come from AppleScript rather than the index
2931
+ * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and
2932
+ * therefore never need to degrade when Full Disk Access is missing.
2933
+ */
2934
+ const LIST_MAILBOXES = script(`
2935
+ var accts = M.accounts();
2936
+ var out = [];
2937
+ for (var i = 0; i < accts.length; i++) {
2938
+ var a = accts[i];
2939
+ var uuid = prop(function () { return a.id(); }, null);
2940
+ if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;
2941
+ var boxes = a.mailboxes();
2942
+ for (var j = 0; j < boxes.length; j++) {
2943
+ var b = boxes[j];
2944
+ var entry = {
2945
+ accountUuid: uuid,
2946
+ accountName: prop(function () { return a.name(); }, null),
2947
+ name: prop(function () { return b.name(); }, null)
2948
+ };
2949
+ if (p.withCounts) {
2950
+ entry.unread = prop(function () { return b.unreadCount(); }, null);
2951
+ entry.total = prop(function () { return b.messages.length; }, null);
2952
+ }
2953
+ out.push(entry);
2954
+ }
2955
+ }
2956
+ return ok(out);
2957
+ `);
2958
+ /** Total and unread for one mailbox. */
2959
+ const COUNT_MAILBOX = script(`
2960
+ var acct = findAccount(M, p.accountUuid);
2961
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
2962
+ var mb = resolveMailbox(acct, p.mailbox);
2963
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
2964
+ return ok({
2965
+ accountUuid: p.accountUuid,
2966
+ mailbox: prop(function () { return mb.name(); }, p.mailbox),
2967
+ total: prop(function () { return mb.messages.length; }, null),
2968
+ unread: prop(function () { return mb.unreadCount(); }, null)
2969
+ });
2970
+ `);
2971
+ /**
2972
+ * The degraded listing lane: newest N of one mailbox, used when the Envelope
2973
+ * Index is unavailable. Costs roughly 130ms + 42ms per message per property,
2974
+ * which is why the caller caps N hard (default 50) instead of paginating.
2975
+ */
2976
+ const LIST_RECENT = script(`
2320
2977
  var acct = findAccount(M, p.accountUuid);
2321
2978
  if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
2322
2979
  var mb = resolveMailbox(acct, p.mailbox);
2323
2980
  if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
2981
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
2324
2982
 
2325
- var original;
2326
- try {
2327
- original = mb.messages.byId(p.id);
2328
- original.subject();
2329
- } catch (e) {
2330
- return err("MESSAGE_NOT_FOUND", "No message " + p.id + " in " + p.mailbox);
2331
- }
2332
-
2333
- // Asked BEFORE anything is opened, and that ordering is the fix for the
2334
- // failure this tool was best known for. The two grants below fail in exactly
2335
- // the state where a composer is already on screen, so the old shape left an
2336
- // empty reply window behind on every attempt and told the user to close it.
2337
- // Nothing about the check needs the window to exist.
2338
- var SE = Application("System Events");
2339
- var reach = composerReach(SE);
2340
- if (!reach.ok) return err("COMPOSER_NOT_FOUND", composerGrantMessage(p.mode, reach));
2341
-
2342
- // The window is opened even when sending immediately: it is where the body
2343
- // has to be typed, and sending from it sends what was verified rather than
2344
- // whatever the disconnected scripting object thinks it holds.
2345
- var draft;
2346
- if (p.mode === "forward") {
2347
- draft = M.forward(original, { openingWindow: true });
2348
- } else {
2349
- draft = M.reply(original, { openingWindow: true, replyToAll: p.replyToAll ? true : false });
2350
- }
2351
-
2352
- var subject = String(prop(function () { return draft.subject(); }, ""));
2353
- if (!subject) return err("COMPOSER_NOT_FOUND", "Mail did not return a composer for the " + p.mode + ".");
2354
-
2355
- var proc = SE.processes.byName("Mail");
2356
- var win = composerWindow(proc, subject, 8000);
2357
- if (!win) {
2358
- // The pre-flight passed and this still failed, so the grants are live and
2359
- // the window is the problem. Nothing has been typed yet, so the composer we
2360
- // opened is ours to take back.
2361
- var closedUnreadable = discardComposer(M, draft);
2362
- return err(
2363
- "COMPOSER_NOT_FOUND",
2364
- "Mail was asked to open a " + p.mode + " window for \\"" + subject + "\\" and no such window " +
2365
- "was readable within 8s, although Mail's other windows read fine — so this is not a " +
2366
- "permission. Nothing was written. Mail may still have been opening it. The windows visible " +
2367
- "at the time were: " + JSON.stringify(reach.windows) + ". " +
2368
- (closedUnreadable
2369
- ? "The composer was closed again without saving, so a retry is safe."
2370
- : "The composer could NOT be closed from here — look for an empty " + p.mode +
2371
- " window in Mail and close it, or a retry leaves a second one behind.")
2372
- );
2373
- }
2983
+ var total = prop(function () { return mb.messages.length; }, 0);
2984
+ var n = Math.min(p.limit || 20, total);
2985
+ if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });
2374
2986
 
2375
- // Recipients go through the scripting object, which does work for them, but
2376
- // only once the composer exists.
2377
- if (p.mode === "forward") {
2378
- var addrs = p.to || [];
2379
- for (var i = 0; i < addrs.length; i++) {
2380
- draft.toRecipients.push(M.ToRecipient({ address: addrs[i] }));
2381
- }
2382
- }
2987
+ // Batch the property reads: one Apple Event per property beats one per message
2988
+ // by roughly 6x. slice() on the message collection keeps it to a range specifier.
2989
+ var slice = mb.messages.slice(0, n);
2990
+ var subjects = prop(function () { return slice.subject(); }, []);
2991
+ var senders = prop(function () { return slice.sender(); }, []);
2992
+ var dates = prop(function () { return slice.dateReceived(); }, []);
2993
+ var reads = prop(function () { return slice.readStatus(); }, []);
2994
+ var flags = prop(function () { return slice.flaggedStatus(); }, []);
2995
+ var ids = prop(function () { return slice.id(); }, []);
2383
2996
 
2384
- var bodyArea = findBodyArea(win, 0);
2385
- if (!bodyArea) {
2386
- var closedNoBody = discardComposer(M, draft);
2387
- return err(
2388
- "COMPOSER_NOT_FOUND",
2389
- "The " + p.mode + " window for \\"" + subject + "\\" is open, but its body cannot be reached " +
2390
- "through the accessibility interface, which is the only way into it. Nothing was written. " +
2391
- (closedNoBody
2392
- ? "The window was closed again without saving."
2393
- : "The window could NOT be closed from here and is still on screen.")
2394
- );
2997
+ var out = [];
2998
+ for (var i = 0; i < n; i++) {
2999
+ out.push({
3000
+ id: ids[i] === undefined ? null : ids[i],
3001
+ accountUuid: p.accountUuid,
3002
+ mailbox: mailboxName,
3003
+ subject: subjects[i] === undefined ? null : subjects[i],
3004
+ sender: senders[i] === undefined ? null : senders[i],
3005
+ dateReceived: iso(dates[i]),
3006
+ read: reads[i] === undefined ? null : reads[i],
3007
+ flagged: flags[i] === undefined ? null : flags[i]
3008
+ });
2395
3009
  }
3010
+ return ok({ mailbox: mailboxName, total: total, messages: out });
3011
+ `);
3012
+ /** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */
3013
+ const GET_MESSAGES = script(`
3014
+ var acct = findAccount(M, p.accountUuid);
3015
+ if (!acct) return err("ACCOUNT_NOT_FOUND", "No account with id " + p.accountUuid);
3016
+ var mb = resolveMailbox(acct, p.mailbox);
3017
+ if (!mb) return err("MAILBOX_NOT_FOUND", "No mailbox " + p.mailbox + " in that account");
3018
+ var mailboxName = prop(function () { return mb.name(); }, p.mailbox);
2396
3019
 
2397
- var previous = prop(function () {
2398
- return SE.applicationProcesses.whose({ frontmost: true })[0].name();
2399
- }, null);
2400
- var restore = function () {
2401
- if (previous && previous !== "Mail") {
2402
- try { SE.processes.byName(previous).frontmost = true; } catch (e) {}
2403
- }
2404
- };
2405
-
2406
- var bodyVerified = null;
2407
- var verifiedChars = 0;
2408
- if (p.body) {
2409
- var body = String(p.body);
2410
- // Confirm the opening of the body rather than all of it. Reading the whole
2411
- // of a long reply plus the quote it sits above costs seconds of Apple
2412
- // Events, and buys nothing: a paste either arrives whole or does not arrive,
2413
- // which is what was measured, so the top of it is the tell.
2414
- var expected = body.length > 400 ? body.slice(0, 400) : body;
2415
- var sizeBefore = composerBodySize(bodyArea);
2416
- bodyVerified = false;
2417
-
3020
+ var out = [];
3021
+ for (var i = 0; i < p.ids.length; i++) {
3022
+ var id = p.ids[i];
2418
3023
  try {
2419
- proc.frontmost = true;
2420
- pause(0.4);
2421
- for (var attempt = 0; attempt < 2 && !bodyVerified; attempt++) {
2422
- pasteIntoComposer(win, bodyArea, body);
2423
- var after = composerBodyText(bodyArea, expected.length + 400);
2424
- bodyVerified = after !== null && containsText(after, expected);
2425
- if (bodyVerified) {
2426
- verifiedChars = expected.length;
2427
- } else if (composerBodySize(bodyArea) !== sizeBefore) {
2428
- // Something went in that we cannot match. Pasting again would put the
2429
- // reply in the draft twice, and nothing here can undo that.
2430
- break;
2431
- }
3024
+ var m = mb.messages.byId(id);
3025
+ var summary = messageSummary(m, p.accountUuid, mailboxName);
3026
+ if (p.withContent) {
3027
+ summary.content = prop(function () { return m.content(); }, null);
2432
3028
  }
2433
- } catch (e) {
2434
- bodyVerified = false;
2435
- }
2436
-
2437
- if (!bodyVerified) {
2438
- restore();
2439
- // Take the window back only when it is provably still empty. A paste that
2440
- // landed and could not be READ is a different thing from one that never
2441
- // landed, and closing that one would destroy the reply with no way to get
2442
- // it back -- so it is left on screen for the user to judge.
2443
- var landed = composerBodySize(bodyArea) !== sizeBefore;
2444
- var closedUnverified = landed ? false : discardComposer(M, draft);
2445
- return err(
2446
- "DRAFT_BODY_NOT_SET",
2447
- "The " + p.mode + " window for \\"" + subject + "\\" was opened and correctly addressed, but the " +
2448
- "body did not go in: reading the composer back does not show the text that was sent. It " +
2449
- "MUST NOT be described to the user as ready. " +
2450
- (closedUnverified
2451
- ? "Nothing had landed in it, so it was closed again without saving and a retry is safe."
2452
- : landed
2453
- ? "SOMETHING DID land in it that could not be read back, so it was left open rather " +
2454
- "than discarded — look at it in Mail before retrying, because a retry would paste " +
2455
- "the reply in twice."
2456
- : "It could NOT be closed from here — close it in Mail before retrying, or the retry " +
2457
- "leaves a second draft behind.")
2458
- );
2459
- }
2460
- }
2461
-
2462
- if (p.sendNow) {
2463
- // Sent from the window, so what goes out is what was just verified.
2464
- var clicked = false;
2465
- try {
2466
- proc.frontmost = true;
2467
- pause(0.4);
2468
- try { win.actions.byName("AXRaise").perform(); } catch (e) {}
2469
- pause(0.3);
2470
- var send = proc.menuBars[0].menuBarItems.byName("Message").menus[0].menuItems.byName("Send");
2471
- if (prop(function () { return send.enabled(); }, false)) {
2472
- send.click();
2473
- clicked = true;
3029
+ if (p.withSource) {
3030
+ summary.source = prop(function () { return m.source(); }, null);
3031
+ }
3032
+ if (p.withHeaders) {
3033
+ summary.allHeaders = prop(function () { return m.allHeaders(); }, null);
2474
3034
  }
3035
+ out.push(summary);
2475
3036
  } catch (e) {
2476
- clicked = false;
2477
- }
2478
- // The window closing is the confirmation that it went. Wait for it rather
2479
- // than sampling once: reporting a slow close as a failure would invite a
2480
- // retry, and a retry after a send that DID go sends the mail twice.
2481
- var stillOpen = true;
2482
- var waited = 0;
2483
- while (clicked && waited < 8000) {
2484
- pause(0.5);
2485
- waited += 500;
2486
- if (composerWindow(proc, subject, 0) === null) { stillOpen = false; break; }
2487
- }
2488
- restore();
2489
- if (!clicked) {
2490
- return err(
2491
- "SEND_FAILED",
2492
- "The " + p.mode + " was composed and its body verified, but Message > Send would not " +
2493
- "activate, so NOTHING WAS SENT. The draft is on screen with the right text in it and can " +
2494
- "be sent by hand."
2495
- );
2496
- }
2497
- if (stillOpen) {
2498
- return err(
2499
- "SEND_UNCONFIRMED",
2500
- "The " + p.mode + " was composed, its body verified, and Send was clicked — but the window " +
2501
- "was still open 8s later, so whether it went cannot be confirmed from here. DO NOT send it " +
2502
- "again: check Sent in Mail first, because a retry would send it twice."
2503
- );
3037
+ out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });
2504
3038
  }
2505
- return ok({ sent: true, mode: p.mode, bodyVerified: bodyVerified,
2506
- verifiedChars: verifiedChars, subject: subject });
2507
3039
  }
2508
-
2509
- restore();
2510
- return ok({
2511
- sent: false,
2512
- draft: true,
2513
- mode: p.mode,
2514
- subject: subject,
2515
- bodyVerified: bodyVerified,
2516
- verifiedChars: verifiedChars,
2517
- note: bodyVerified
2518
- ? "Draft window is open in Mail for review; its body was read back out of the window and matches."
2519
- : "Draft window is open in Mail for review."
2520
- });
2521
- `, { allowLaunch: true });
3040
+ return ok(out);
3041
+ `);
2522
3042
  //#endregion
2523
3043
  //#region src/client/mailbox-map.ts
2524
3044
  var MailboxMap = class {
@@ -2655,6 +3175,15 @@ var AppleMailClient = class {
2655
3175
  runner;
2656
3176
  mailboxes;
2657
3177
  #logger;
3178
+ /**
3179
+ * The native Accessibility lane, when this server is hosted by Cupertino.
3180
+ *
3181
+ * Null when it is not — a package installed from npm and run by hand — and
3182
+ * that is the supported case rather than a fault, so every use of it falls
3183
+ * back to the System Events path rather than refusing. `diagnostics` reports
3184
+ * which one is live.
3185
+ */
3186
+ #ax;
2658
3187
  #located = null;
2659
3188
  #index = null;
2660
3189
  #indexError = null;
@@ -2673,6 +3202,11 @@ var AppleMailClient = class {
2673
3202
  allowlist: opts.config.accounts,
2674
3203
  ttlMs: opts.config.mailboxCacheTtlMs
2675
3204
  });
3205
+ this.#ax = opts.ax !== void 0 ? opts.ax : MailAxLane.open();
3206
+ }
3207
+ /** Which composer lane is live, for `diagnostics` to report. */
3208
+ get composerLane() {
3209
+ return this.#ax ? "accessibility" : "system-events";
2676
3210
  }
2677
3211
  accounts(force = false) {
2678
3212
  return this.mailboxes.accounts(force);
@@ -2721,6 +3255,24 @@ var AppleMailClient = class {
2721
3255
  };
2722
3256
  }
2723
3257
  }
3258
+ /**
3259
+ * Can the NATIVE lane actually read Mail's windows, right now?
3260
+ *
3261
+ * The same principle `composerAccess` states for the System Events path, for
3262
+ * the same reason: `composerLane` above says which lane is configured, and
3263
+ * configured is a claim. This is the functional read, and when the two
3264
+ * disagree this is the one to believe.
3265
+ *
3266
+ * Null when there is no native lane, which is not a failure — see `#ax`.
3267
+ */
3268
+ async composerAxReach() {
3269
+ if (!this.#ax) return null;
3270
+ const reach = await this.#ax.reach();
3271
+ return {
3272
+ ok: reach.ok,
3273
+ windows: reach.windows
3274
+ };
3275
+ }
2724
3276
  async lanes() {
2725
3277
  /**
2726
3278
  * Probe twice before declaring the lane dead.
@@ -3456,7 +4008,7 @@ var AppleMailClient = class {
3456
4008
  }
3457
4009
  async replyOrForward(ref, opts) {
3458
4010
  const decoded = decodeRef(ref);
3459
- return this.runner.run(REPLY_OR_FORWARD, {
4011
+ const params = {
3460
4012
  accountUuid: decoded.accountUuid,
3461
4013
  mailbox: decoded.mailbox,
3462
4014
  id: decoded.id,
@@ -3465,7 +4017,9 @@ var AppleMailClient = class {
3465
4017
  to: opts.to ?? [],
3466
4018
  replyToAll: opts.replyToAll ?? false,
3467
4019
  sendNow: opts.sendNow
3468
- });
4020
+ };
4021
+ if (this.#ax) return replyOrForwardNatively(this.#ax, this.runner, params);
4022
+ return this.runner.run(REPLY_OR_FORWARD, params);
3469
4023
  }
3470
4024
  #withRef(m) {
3471
4025
  const { id, accountUuid, mailbox, ...rest } = m;
@@ -3553,6 +4107,7 @@ const loadConfig = (env = process.env) => {
3553
4107
  const raw = {
3554
4108
  allowWrites: parseBool(env.APPLE_MAIL_ALLOW_WRITES),
3555
4109
  exposePrompts: parseBool(env.APPLE_MAIL_EXPOSE_PROMPTS),
4110
+ lazyTools: parseBool(env.APPLE_MAIL_LAZY_TOOLS),
3556
4111
  debug: parseBool(env.APPLE_MAIL_DEBUG),
3557
4112
  accounts: parseList(env.APPLE_MAIL_ACCOUNTS),
3558
4113
  mailRoot: trimmed(env.APPLE_MAIL_ROOT),
@@ -3762,6 +4317,7 @@ const buildDiagnostics = async (client, ctx) => {
3762
4317
  const located = await client.locate();
3763
4318
  const messageFile = await client.probeMessageFile();
3764
4319
  const composer = await client.composerAccess();
4320
+ const axReach = await client.composerAxReach();
3765
4321
  let accounts = [];
3766
4322
  let accountsError = null;
3767
4323
  try {
@@ -3802,7 +4358,13 @@ const buildDiagnostics = async (client, ctx) => {
3802
4358
  automationSystemEvents: composer.systemEvents,
3803
4359
  composerUiRead: composer.uiRead,
3804
4360
  ...composer.windows ? { composerWindowsSeen: composer.windows } : {},
3805
- ...composer.uiRead === "granted" && composer.systemEvents === "granted" ? {} : { composerNote: "Filling a Mail composer goes through System Events, which needs BOTH of the above: Automation to System Events (a different grant from Automation to Mail) and Accessibility. Until both are granted, apple_mail_reply_to_message and apple_mail_forward_message fail with COMPOSER_NOT_FOUND while every other tool works. Grant them to the Cupertino bundle that is RUNNING — not to your terminal and not to node: the app is the process macOS holds responsible, and the servers do inherit its identity. If Cupertino's own Settings shows a GREEN Accessibility row while `composerUiRead` above says denied, believe this line and not the row: one bundle identifier can hold several Accessibility entries at once, one per path and signature it has been granted at (an installed copy, a development build, each earlier reinstall), and the two checks can match different ones. The cure is to clear them all and grant once, from the bundle that is running: `tccutil reset Accessibility io.mgcrea.cupertino`, then Ask… in Cupertino's Settings — it reported resetting FOUR entries the first time this was hit. Accessibility is in System Settings > Privacy & Security > Accessibility; Automation is under Automation. If the app is already listed, toggle it off and on — the grant goes stale when the bundle is reinstalled. Then quit Cupertino and open it again: the servers are children of the running app, and a child started before the grant does not see it — which is what `accessibility: denied` beside a green Accessibility row in Cupertino's own Settings means." },
4361
+ composerLane: client.composerLane,
4362
+ ...axReach ? {
4363
+ composerAxRead: axReach.ok ? "granted" : "denied",
4364
+ ...axReach.windows ? { composerAxWindowsSeen: axReach.windows } : {}
4365
+ } : {},
4366
+ ...client.composerLane === "accessibility" ? { composerLaneNote: "This server is hosted by Cupertino, so a composer is driven through the app's own Accessibility driver. Automation to System Events is NOT required for it, and `automationSystemEvents` above can be denied without affecting a reply." } : {},
4367
+ ...composer.uiRead === "granted" && composer.systemEvents === "granted" || client.composerLane === "accessibility" ? {} : { composerNote: "Filling a Mail composer goes through System Events, which needs BOTH of the above: Automation to System Events (a different grant from Automation to Mail) and Accessibility. Until both are granted, apple_mail_reply_to_message and apple_mail_forward_message fail with COMPOSER_NOT_FOUND while every other tool works. Grant them to the Cupertino bundle that is RUNNING — not to your terminal and not to node: the app is the process macOS holds responsible, and the servers do inherit its identity. If Cupertino's own Settings shows a GREEN Accessibility row while `composerUiRead` above says denied, believe this line and not the row: one bundle identifier can hold several Accessibility entries at once, one per path and signature it has been granted at (an installed copy, a development build, each earlier reinstall), and the two checks can match different ones. The cure is to clear them all and grant once, from the bundle that is running: `tccutil reset Accessibility io.mgcrea.cupertino`, then Ask… in Cupertino's Settings — it reported resetting FOUR entries the first time this was hit. Accessibility is in System Settings > Privacy & Security > Accessibility; Automation is under Automation. If the app is already listed, toggle it off and on — the grant goes stale when the bundle is reinstalled. Then quit Cupertino and open it again: the servers are children of the running app, and a child started before the grant does not see it — which is what `accessibility: denied` beside a green Accessibility row in Cupertino's own Settings means." },
3806
4368
  fullDiskAccess: located.readable ? "granted" : located.exists ? "denied" : "unknown (no index file found)",
3807
4369
  ...located.readable ? {} : { howToGrant: [
3808
4370
  "System Settings > Privacy & Security > Full Disk Access",
@@ -4451,7 +5013,12 @@ const createServer = (opts) => {
4451
5013
  ...opts.logger ? { logger: opts.logger } : {},
4452
5014
  ...opts.osascript ? { osascript: opts.osascript } : {}
4453
5015
  });
4454
- registerTools(server, client, { allowWrites: config.allowWrites });
5016
+ withLazyTools(server, {
5017
+ surface: "mail",
5018
+ displayName: "Mail",
5019
+ lazy: config.lazyTools,
5020
+ allowWrites: config.allowWrites
5021
+ }, (target, allowWrites) => registerTools(target, client, { allowWrites }));
4455
5022
  if (config.exposePrompts) {
4456
5023
  registerPrompts(server, config.allowWrites);
4457
5024
  registerSurfaceResources(server, {
@@ -4480,4 +5047,4 @@ const createServer = (opts) => {
4480
5047
  //#endregion
4481
5048
  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 };
4482
5049
 
4483
- //# sourceMappingURL=server-CTA6m12j.js.map
5050
+ //# sourceMappingURL=server-D7Aj2CJS.js.map