@mgcrea/mcp-apple-mail 1.30.0 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, BuildInfo, IndexUnavailableError, InterferenceWatch, JxaEnvelope, Logger, OsascriptRunner, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, WritesDisabledError, assertStaticScript, createOsascriptRunner, inspectFile, mapOsaError, withBusyRetry } from "@mgcrea/mcp-apple-core";
1
+ import { AppBusyError as MailBusyError, AppNotRunningError as MailNotRunningError, AppleAutomationError, AppleAutomationError as AppleMailError, ArrivalRow, ArrivalSource, BuildInfo, Era, FileIdentity, IndexUnavailableError, InterferenceWatch, JxaEnvelope, Logger, OsascriptRunner, OsascriptTimeoutError, PlatformError, PreconditionError, ProtocolError, SchemaDriftError, TccDeniedError, Watch, WatchRegistry, WritesDisabledError, assertStaticScript, createOsascriptRunner, inspectFile, mapOsaError, normalizeFilter, withBusyRetry } from "@mgcrea/mcp-apple-core";
2
2
  import { z } from "zod";
3
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { McpServer } from "@modelcontextprotocol/server";
4
4
  import { DatabaseSync } from "node:sqlite";
5
5
  //#region src/build-info.d.ts
6
6
  declare const BUILD_INFO: BuildInfo;
@@ -93,6 +93,8 @@ declare const ConfigSchema: z.ZodObject<{
93
93
  bodyScanBytes: z.ZodDefault<z.ZodNumber>;
94
94
  attachmentDir: z.ZodDefault<z.ZodString>;
95
95
  allowFileSend: z.ZodDefault<z.ZodBoolean>;
96
+ allowWatches: z.ZodDefault<z.ZodBoolean>;
97
+ allowEvents: z.ZodDefault<z.ZodBoolean>;
96
98
  mailboxCacheTtlMs: z.ZodDefault<z.ZodNumber>;
97
99
  }, z.core.$strict>;
98
100
  type Config = z.infer<typeof ConfigSchema>;
@@ -103,76 +105,85 @@ type Config = z.infer<typeof ConfigSchema>;
103
105
  declare const loadConfig: (env?: NodeJS.ProcessEnv) => Config;
104
106
  //#endregion
105
107
  //#region src/client/ax.d.ts
106
- /** One keystroke, as `apple_desktop_key` takes it. */
107
- type Keystroke = {
108
- key: string;
109
- modifiers?: string[];
110
- };
111
108
  type ComposerRef = {
112
109
  window: string;
113
110
  body: string;
114
111
  index: number;
115
112
  };
116
- /**
117
- * A composer's own text, told apart from the original it quotes.
118
- *
119
- * MEASURED, macOS 27.0 (build 26A428), on a reply composer: `AXBlockQuoteLevel`
120
- * reads 0 on every block the sender wrote and 1 on every block from the
121
- * attribution line — `On <date>, <who> wrote:` — down, including the quoted
122
- * message's images and links. The split is exact, which is what makes replacing
123
- * a reply's text without touching its quote possible at all.
124
- *
125
- * **A FORWARD is quoted too**, and that was worth measuring rather than assuming:
126
- * a forward reads as prose with a `Begin forwarded message:` header and nothing
127
- * about it looks like a quotation, but that line and everything under it read
128
- * level 1 on the same build. Had they read 0 the whole forwarded message would
129
- * have counted as the sender's own text and been offered up for replacement.
130
- *
131
- * `blocks` counts the top-level elements above that boundary, NOT rendered
132
- * lines: a paragraph that wraps is one block and two lines. So it is a floor for
133
- * how many times the selection has to be extended, never a target — see
134
- * `selectOwnText` in `revise.ts`, which converges upwards from it and verifies
135
- * the answer before anything is replaced.
136
- */
137
- type ComposerBody = {
138
- /** What the sender wrote, blocks joined by newlines. "" when they wrote nothing. */
139
- text: string;
140
- /** Top-level elements above the quote. */
141
- blocks: number;
142
- /** Whether a quoted original follows. */
143
- quoted: boolean;
113
+ /** One open composer, as the app's `mail_composers` verb reports it. */
114
+ type NativeComposer = {
144
115
  /**
145
- * The names of the files sitting in the sender's own text, in order. See
146
- * `FILE_ROLES`. They carry no value, so `text` never includes them.
116
+ * The handle, `mc-<n>`. It names this composer, tab or window, for as long
117
+ * as it lives, and its number is never reused. One thing moves it: Mail
118
+ * re-mints every tab button when a tab opens or closes, and a tab's handle
119
+ * is then re-bound to the live tab of its window carrying its title, when
120
+ * that title was unique both before and after. That tab may be another
121
+ * draft, which `rebound` says.
147
122
  */
148
- files: string[];
149
- };
150
- /**
151
- * One compose window as a person would read it, for reviewing what they wrote.
152
- *
153
- * Recipients are display names, never addresses — see `TOKEN_CHAR`. A name
154
- * still being typed, not yet turned into a token, is returned as typed.
155
- */
156
- type OpenComposer = {
123
+ composer: string;
124
+ /**
125
+ * True while the handle was re-bound to a tab that may be another draft
126
+ * (the person closed the first and opened, or retitled, another under its
127
+ * title). An edit by the handle alone is refused; one by ref, which sends
128
+ * the draft's text as `expectHead`, goes through when the text matches. A
129
+ * moved handle stays reference-only until its text is proved: a verified
130
+ * edit by ref clears the mark, and so does a listing that reads the tab's
131
+ * own text, not empty, as what the handle was last seen with. Absent from
132
+ * an app that predates it.
133
+ */
134
+ rebound?: boolean;
135
+ /** A tab's subject is its title. */
157
136
  subject: string;
158
- /** The window Mail considers main — the one in front, when Mail is. */
159
- main: boolean;
160
- /** The account picker's value, `Name – address`. */
161
- from: string | null;
162
- to: string[];
163
- cc: string[];
137
+ /**
138
+ * Null (or absent) for a window of its own. With "Prefer tabs: Always" Mail
139
+ * opens every composer as a tab of one window, and Accessibility shows only
140
+ * the selected tab's content: `"selected"` reads as a window does,
141
+ * `"background"` carries its subject and nothing else, because reading the
142
+ * rest would mean switching tabs and a listing never does.
143
+ */
144
+ tab?: "selected" | "background" | null;
145
+ /** To and Cc names together. Null for a background tab. */
146
+ recipients: string[] | null;
147
+ /** The window Mail considers main: the one in front, when Mail is. */
148
+ main?: boolean;
149
+ /** The account picker's value, `Name – address`; null when there is none. */
150
+ from?: string | null;
151
+ to?: string[] | null;
152
+ cc?: string[] | null;
164
153
  /** Null when the Bcc field is not shown, which is not the same as empty. */
165
- bcc: string[] | null;
154
+ bcc?: string[] | null;
155
+ /** The opening of the quoted original; null when none, or none was asked for. */
156
+ quote?: string | null;
157
+ quoteTruncated?: boolean;
166
158
  /**
167
- * What the sender wrote. When `quoted` is null the boundary could not be
168
- * found, and this is the readable text of the whole body instead.
159
+ * The sender's own text, blocks joined by newlines. Null for a background
160
+ * tab, and for a body the app could not read (Mail still loading it, or not
161
+ * answering): never "" for one, which would read as an empty draft.
169
162
  */
170
163
  text: string | null;
171
- /** Whether a quoted original follows; null when that could not be established. */
164
+ /** Null when a quote level was unreadable, and for a background tab. */
172
165
  quoted: boolean | null;
173
- /** The opening of the quoted original, up to the requested length. */
174
- quote: string | null;
175
- quoteTruncated: boolean;
166
+ /** Named files in the own text. Empty for a background tab, which is not read. */
167
+ files: string[];
168
+ };
169
+ type EditComposerArgs = {
170
+ composer: string;
171
+ body?: string;
172
+ /**
173
+ * Put `body` in ABOVE the own text instead of over it: for a new composer,
174
+ * whose own text is the account's signature. The answer then carries
175
+ * `kept`, the own text it went in above. An app that predates it ignores
176
+ * it and replaces, which the caller's read-back still catches.
177
+ */
178
+ insert?: boolean;
179
+ html?: string;
180
+ edits?: {
181
+ find: string;
182
+ replace: string;
183
+ }[];
184
+ attachments?: string[];
185
+ save?: boolean;
186
+ expectHead?: string;
176
187
  };
177
188
  type ReachReport = {
178
189
  ok: boolean;
@@ -188,6 +199,14 @@ declare class MailAxLane {
188
199
  close(): void;
189
200
  /** Start watching for someone using the Mac during a sequence. */
190
201
  watch(): InterferenceWatch;
202
+ /** Every open composer, with its handle and own text. */
203
+ composers(quoteChars?: number): Promise<NativeComposer[]>;
204
+ /**
205
+ * Edit a composer in one verified native step. The verb's JSON comes back
206
+ * verbatim: a refusal is an answer, not an error. A failure of the call itself
207
+ * (bad arguments, Accessibility not trusted) throws, as every `#call` does.
208
+ */
209
+ editComposer(args: EditComposerArgs): Promise<Record<string, unknown>>;
191
210
  /**
192
211
  * Can this process read Mail's windows, right now?
193
212
  *
@@ -207,14 +226,22 @@ declare class MailAxLane {
207
226
  */
208
227
  reach(): Promise<ReachReport>;
209
228
  /**
210
- * The sentence to say when the composer cannot be reached natively.
229
+ * The sentence to say when the app is there but Mail's windows cannot be read.
230
+ *
231
+ * Said once, in one wording, by every draft entry point (compose, edit,
232
+ * rebuild, list open drafts), so whoever meets it from any of them is led to
233
+ * the same switch. `mode` is accepted so callers can keep naming what they
234
+ * were doing, and is deliberately not part of the text.
211
235
  *
212
236
  * One grant rather than two, and none of the "quit Cupertino and open it
213
- * again" ritual the System Events path needs — that exists because a node
237
+ * again" ritual the System Events path needs: that exists because a node
214
238
  * child started before the grant does not inherit it, and this driver runs in
215
- * the app itself.
239
+ * the app itself. A server Cupertino did not start has no lane to be refused
240
+ * on, and says so in its own words.
216
241
  */
217
- static grantMessage(mode: string): string;
242
+ static grantMessage(_mode?: string): string;
243
+ /** What a WRITE refusal adds to `grantMessage`; a read has no use for it. */
244
+ static readonly nothingWritten = "Nothing was written.";
218
245
  /**
219
246
  * Poll for the composer window, and for its body.
220
247
  *
@@ -232,123 +259,8 @@ declare class MailAxLane {
232
259
  * a new composer on screen.
233
260
  */
234
261
  findComposer(subject: string, timeoutMs: number): Promise<ComposerRef | null>;
235
- /**
236
- * Every composer currently under this subject, in window order.
237
- *
238
- * `findComposer` takes the first match because it is looking for a window it
239
- * just opened. Rewriting one that was already there is the opposite problem:
240
- * the caller has to know whether the subject picks out ONE composer, because
241
- * two under one title cannot be told apart — handles are minted per call —
242
- * and replacing the body of the wrong one destroys what somebody wrote. So
243
- * this returns the list and lets `revise.ts` refuse on its length.
244
- *
245
- * Does not poll. Nothing here opened a window, so there is nothing to wait
246
- * for: the composer either is on screen or is not.
247
- */
248
- findComposers(subject: string): Promise<ComposerRef[]>;
249
262
  /** Bring Mail to the front. A synthetic keystroke lands in whatever is frontmost. */
250
263
  activate(): Promise<void>;
251
- /**
252
- * The accessible text under the body, which is what a person would see.
253
- *
254
- * One call rather than a bounded walk. The System Events version reads a
255
- * parent at a time and stops at a character budget because every node costs an
256
- * Apple Event; here the whole subtree comes back in one answer with each
257
- * element's value already on it.
258
- *
259
- * Returns null when the body cannot be reached at all — a different answer
260
- * from "", and the two must stay apart: one means we are blind, the other
261
- * means the composer is empty.
262
- */
263
- bodyText(body: string): Promise<string | null>;
264
- /**
265
- * How many elements the body holds.
266
- *
267
- * A fingerprint, not a reading. Taken before and after a paste it answers "did
268
- * anything at all land", which is what decides whether pasting again is safe:
269
- * a paste that landed and cannot be read must NOT be repeated, or the reply
270
- * ends up in the draft twice with no way to undo it from here.
271
- *
272
- * `matched` rather than the returned length, because the response is byte
273
- * capped and a long quoted message will truncate — a fingerprint taken from a
274
- * truncated list would compare two different bounds rather than two states.
275
- *
276
- * **Null when the body cannot be read at all, and that is the whole point.**
277
- * This returned -1 for a failed read, and the caller compared it as a count.
278
- * A composer that CLOSES takes its element handle with it — the driver answers
279
- * `staleHandle` — so a body that had gone in perfectly read back as -1 and
280
- * compared unequal to the size before, which is the signature of "something
281
- * landed that cannot be matched". A reply sent by hand mid-call was reported
282
- * as a body that never went in, with a warning against the retry that was in
283
- * fact the safe move. Blind and different are not the same answer, exactly as
284
- * `bodyText` above insists, and this is where that was forgotten.
285
- */
286
- bodySize(body: string): Promise<number | null>;
287
- /**
288
- * Focus the body and paste, and say whether the focus took.
289
- *
290
- * Focus is not a raise: a raise orders a window forward inside Mail while the
291
- * keystroke goes wherever the focus actually is. Both are needed, and the
292
- * focus is read back because an element can report itself focusable and not
293
- * take it.
294
- *
295
- * **What "read back" has to mean here, learned the hard way.** Mail's composer
296
- * web area answers `AXFocused: false` while holding the keyboard — measured
297
- * over 1.2 s without ever flipping, with a command-V landing in it the whole
298
- * time. `apple_desktop_focus` used to return that flag, so this guard refused
299
- * to press command-V and every native reply came back "Nothing landed in it"
300
- * for a body that would have gone in. The driver now answers from the
301
- * APPLICATION's `AXFocusedUIElement`, which is what the window server routes
302
- * keystrokes by and so cannot disagree with where one will land.
303
- *
304
- * The guard itself stays. Posting command-V without knowing where the focus is
305
- * types into whatever happens to be in front, and that is the user's window.
306
- *
307
- * **A composer that has gone answers false rather than throwing.** Both handles
308
- * die with the window, so raising or focusing one afterwards is a `staleHandle`
309
- * — and letting that escape turns a describable failure into a bare channel
310
- * error with no note attached, on the one path whose whole job is to say what
311
- * happened. False is the honest answer: the focus was not taken, so nothing was
312
- * typed.
313
- */
314
- paste(ref: ComposerRef, focusTimeoutMs?: number): Promise<boolean>;
315
- /**
316
- * Focus the composer's body and send a burst of keystrokes to it.
317
- *
318
- * What `paste` was, generalised, because replacing a reply's text without
319
- * touching its quote is a sequence rather than one key: the caret goes to the
320
- * top of the document, the selection is walked down to the end of the
321
- * sender's own text, and only then is anything pasted over it.
322
- *
323
- * Sent through `apple_desktop_run` so a burst is ONE round trip. That is not
324
- * only speed: every stroke in a run is checked before the first one is posted,
325
- * and the run stops at the first failure, so a selection cannot be left
326
- * half-extended by a refusal partway through.
327
- *
328
- * Each stroke names the body's handle, so the desktop server brings Mail
329
- * forward before posting and refuses rather than typing into whatever the
330
- * person at the keyboard just switched to.
331
- */
332
- keys(ref: ComposerRef, strokes: Keystroke[], focusTimeoutMs?: number): Promise<boolean>;
333
- composerBody(body: string): Promise<ComposerBody | null>;
334
- /**
335
- * Every compose window open in Mail, read the way a person reviewing it would.
336
- *
337
- * **Why this reads windows rather than asking Mail.** `outgoing messages` —
338
- * the scripting class for a composer — came back EMPTY with a reply composer
339
- * on screen that the person had opened by hand (measured 2026-10-06, macOS
340
- * 27.0). It lists only the composers a script made. The window is the one
341
- * place every draft being written can be seen.
342
- *
343
- * A composer is recognised by its subject FIELD, not its title: the title is
344
- * the subject, so it cannot tell a composer from a viewer showing a message
345
- * with the same one. The shallow walk that finds the field is cheap on Mail's
346
- * main window, which is the one with thousands of rows under it.
347
- *
348
- * Pure reads. Nothing is raised, focused or typed, so it can run while
349
- * someone is using the Mac.
350
- */
351
- listComposers(quoteChars?: number): Promise<OpenComposer[]>;
352
264
  /**
353
265
  * Send the composer, or save it as a draft.
354
266
  *
@@ -388,8 +300,14 @@ declare class MailAxLane {
388
300
  *
389
301
  * Posting a send into an unknown foreground is the one outcome worth refusing
390
302
  * outright, which is why neither of them throws.
303
+ *
304
+ * `ready`, when given, is asked once Mail is in front, right before the key,
305
+ * and the key is pressed only on a yes: `"unready"` means nothing was
306
+ * pressed. A window holding several drafts as tabs sends or saves the one it
307
+ * SHOWS, so the caller checks that is still its draft. A check that throws
308
+ * is a no.
391
309
  */
392
- finish(sendNow: boolean, ref: ComposerRef): Promise<"pressed" | "gone" | "refused">;
310
+ finish(sendNow: boolean, ref: ComposerRef, ready?: () => Promise<boolean>): Promise<"pressed" | "gone" | "refused" | "unready">;
393
311
  /**
394
312
  * Has the composer for this subject gone?
395
313
  *
@@ -397,36 +315,14 @@ declare class MailAxLane {
397
315
  * window still being there means it did not go — which is checked rather than
398
316
  * assumed, because nothing in this path may report success on the strength of
399
317
  * a keystroke having been delivered.
400
- */
401
- composerGone(subject: string, timeoutMs: number): Promise<boolean>;
402
- /** Select everything in the body, for the quote strip. */
403
- selectAll(): Promise<void>;
404
- /**
405
- * The deepest quote level anywhere in the body; 0 once the citation is gone.
406
318
  *
407
- * `AXBlockQuoteLevel` is not in the tree's field set, which is chosen for
408
- * addressing controls — so it is read one element at a time. That is
409
- * affordable only natively: 343 elements at 0.2 ms is well under a tenth of a
410
- * second, where the same walk through System Events would be sixteen.
319
+ * A tab Mail is not showing is no window's title, so the composers listed as
320
+ * tabs are asked too: a draft in a background tab is still there. When they
321
+ * cannot be listed, the window titles decide alone, as they always did.
411
322
  */
412
- maxQuoteLevel(body: string): Promise<number>;
323
+ composerGone(subject: string, timeoutMs: number): Promise<boolean>;
413
324
  }
414
325
  //#endregion
415
- //#region src/client/compose.d.ts
416
- /**
417
- * The pasteboard, as a seam.
418
- *
419
- * Injectable because the real one is shared machine state: a test that called
420
- * `pbcopy` would clobber whatever the person running it had copied, which is
421
- * not a thing a test suite may do.
422
- */
423
- type Clipboard = {
424
- read(): Promise<string | null>;
425
- write(text: string): Promise<void>;
426
- /** Put these files on the pasteboard, the way Finder's Copy does. */
427
- writeFiles(paths: string[]): Promise<void>;
428
- };
429
- //#endregion
430
326
  //#region src/client/mime.d.ts
431
327
  type Attachment = {
432
328
  filename: string | null;
@@ -555,6 +451,21 @@ type GroupResult = {
555
451
  /** Messages aggregated. Never capped by `limit`. */
556
452
  totalRows: number;
557
453
  };
454
+ /** One message as the arrival scan sees it: envelope fields only, `dateReceived` in store units. */
455
+ type ArrivalScanRow = {
456
+ rowid: number;
457
+ /** `global_message_id` as a string. Row identity, not a dedup key. */
458
+ key: string;
459
+ mailboxRowid: number;
460
+ /** Null when the row's mailbox has no `mailboxes` row. */
461
+ mailboxUrl: string | null;
462
+ /** Mailboxes this row is in by label (Gmail INBOX membership); empty without a `labels` table. */
463
+ labelMailboxIds: number[];
464
+ subject: string | null;
465
+ senderAddress: string | null;
466
+ senderName: string | null;
467
+ dateReceived: number | null;
468
+ };
558
469
  type OpenResult = {
559
470
  db: DatabaseSync;
560
471
  /** Which mode actually opened. `immutable` results are WAL-blind — say so. */
@@ -596,8 +507,72 @@ declare class EnvelopeIndex {
596
507
  total: number;
597
508
  unread: number;
598
509
  };
510
+ /**
511
+ * `count` for many mailbox groups at once.
512
+ *
513
+ * Each group is what `count` would be handed for one mailbox name — every
514
+ * index rowid that name resolves to — and gets exactly the answer `count`
515
+ * gives it. Called once per mailbox, `count` scans `messages` each time,
516
+ * because nothing in Mail's schema indexes it on `mailbox` first.
517
+ *
518
+ * A group of one rowid, nearly every group, comes from a single GROUP BY over
519
+ * each mailbox's own messages plus its labels. That cannot count a message
520
+ * twice: `labels` is keyed on (message, mailbox), and a label naming the
521
+ * message's own mailbox is skipped. A group of several rowids can — one
522
+ * message living in one and labelled into another — so each of those goes
523
+ * through `count`, which matches per message.
524
+ *
525
+ * The single pass measured 68 ms on 189k messages and 204k labels. Deduping
526
+ * every group with a UNION instead returned the same counts in 1,060 ms,
527
+ * almost all of it sorting the union.
528
+ */
529
+ countGroups(groups: {
530
+ key: string;
531
+ rowids: number[];
532
+ }[]): Map<string, {
533
+ total: number;
534
+ unread: number;
535
+ }>;
536
+ /**
537
+ * One message by rowid, in the shape `search` returns, or null.
538
+ *
539
+ * Deleted rows are included on purpose. This answers "what are this
540
+ * message's envelope fields", for a ref the caller already holds, and the
541
+ * Apple Events read it replaces did not refuse a message on that flag either.
542
+ */
543
+ byRowid(rowid: number): MessageRow | null;
599
544
  /** Every message in one conversation, oldest first. */
600
545
  thread(conversationId: number, limit: number): MessageRow[];
546
+ /** Highest message ROWID now, or 0 for an empty index. */
547
+ headRowid(): number;
548
+ /**
549
+ * Messages with ROWID above `after`, ascending, at most `limit`.
550
+ *
551
+ * Nothing is filtered out: a watch cursor advances over every ROWID, and the
552
+ * caller decides what is excluded. That is why `mailboxes` is a LEFT JOIN here
553
+ * where listings use an inner one: a row with no mailbox row must still come
554
+ * back. Otherwise it uses the listings' joins and subject expression.
555
+ *
556
+ * Label mailbox ids come back too, because Gmail INBOX membership is a
557
+ * `labels` row on an All Mail message (see `#mailboxPredicate`).
558
+ */
559
+ arrivalsAfter(after: number, limit: number): ArrivalScanRow[];
560
+ /** A stored `date_received` rendered exactly as search results render theirs. */
561
+ renderDate(value: number | null): string | null;
562
+ /**
563
+ * The messages carrying one RFC 5322 Message-ID, newest first, or null when
564
+ * this index has no `message_global_data.message_id_header` to ask.
565
+ *
566
+ * How a reply draft finds what it answers: its `In-Reply-To` names the
567
+ * original by Message-ID, and the ref to reply to is built from the row this
568
+ * returns. Several rows are normal, one per mailbox a message sits in. The
569
+ * header is matched with and without its angle brackets, because which form
570
+ * the column keeps is not something this code should bet on.
571
+ */
572
+ findByMessageIdHeader(header: string): {
573
+ rowid: number;
574
+ mailbox: number;
575
+ }[] | null;
601
576
  /** conversation_id for one message, so get_thread can start from a ref. */
602
577
  conversationOf(rowid: number): number | null;
603
578
  }
@@ -633,8 +608,18 @@ type MailboxMapOptions = {
633
608
  declare class MailboxMap {
634
609
  #private;
635
610
  constructor(opts: MailboxMapOptions);
611
+ /**
612
+ * The account list. An expired one is served at once and refreshed behind
613
+ * the call: LIST_ACCOUNTS measured ~1 s, and with a plain TTL that second
614
+ * came back on the first call after every minute-long pause. Only a list
615
+ * nobody has yet, an invalidated one or a forced read is waited for.
616
+ */
636
617
  accounts(force?: boolean): Promise<MailAccount[]>;
637
- /** Resolve an account by UUID or display name. Case-insensitive on the name. */
618
+ /**
619
+ * Resolve an account by UUID or display name. Case-insensitive on the name.
620
+ * A name the cached list lacks earns one fresh read before it is refused,
621
+ * since that list can be stale by design.
622
+ */
638
623
  resolveAccount(needle: string): Promise<MailAccount>;
639
624
  /**
640
625
  * Resolve a mailbox name within an account using the same ladder the JXA side
@@ -651,6 +636,15 @@ declare class MailboxMap {
651
636
  account: MailAccount;
652
637
  mailbox: string;
653
638
  } | null>;
639
+ /**
640
+ * `resolveIndexUrl` against accounts the caller already holds, with no Apple
641
+ * Event: a watch rebuilds its lookup after reopening the index, from the
642
+ * accounts it last asked Mail for.
643
+ */
644
+ resolveIndexUrlIn(accounts: readonly MailAccount[], url: string): {
645
+ account: MailAccount;
646
+ mailbox: string;
647
+ } | null;
654
648
  invalidate(): void;
655
649
  }
656
650
  //#endregion
@@ -713,15 +707,6 @@ type AppleMailClientOptions = {
713
707
  * what the server does.
714
708
  */
715
709
  ax?: MailAxLane | null | undefined;
716
- /**
717
- * The pasteboard, for tests.
718
- *
719
- * The same seam `compose.ts` already documents, hoisted to the client because
720
- * `updateDraft` reaches the composer through it too. The real pasteboard is
721
- * shared machine state and a test that wrote to it would clobber whatever the
722
- * person running it had copied.
723
- */
724
- clipboard?: Clipboard | undefined;
725
710
  };
726
711
  declare class AppleMailClient {
727
712
  #private;
@@ -779,6 +764,16 @@ declare class AppleMailClient {
779
764
  windows: string[] | null;
780
765
  } | null>;
781
766
  lanes(): Promise<LaneStatus>;
767
+ /**
768
+ * Mailbox names, and counts when asked for.
769
+ *
770
+ * Names come from the account list, which already carries every mailbox name
771
+ * Mail scripts (LIST_ACCOUNTS reads the same `a.mailboxes()` LIST_MAILBOXES
772
+ * did), so listing them sends no Apple Event of its own. Counts come from the
773
+ * index in one pass when it is live — the same count `count_messages` gives,
774
+ * Gmail labels included — and from Mail otherwise, which measured 1.2 s for
775
+ * every mailbox on a live machine.
776
+ */
782
777
  listMailboxes(opts: {
783
778
  accountUuids?: string[];
784
779
  withCounts: boolean;
@@ -786,9 +781,47 @@ declare class AppleMailClient {
786
781
  accountUuid: string;
787
782
  accountName: string;
788
783
  name: string;
789
- unread?: number;
790
- total?: number;
784
+ unread?: number | null;
785
+ total?: number | null;
786
+ countsSource?: "index";
791
787
  }[]>;
788
+ /**
789
+ * The newest messages in one mailbox: from the index when it holds the
790
+ * mailbox, which takes milliseconds and is held only to `limit`; over Apple
791
+ * Events otherwise, which measured 8.4 s for twenty and is capped.
792
+ */
793
+ listMessages(account: MailAccount, mailbox: string, limit: number): Promise<{
794
+ mailbox: string;
795
+ total: number;
796
+ messages: MessageSummary[];
797
+ } & ({
798
+ source: "index";
799
+ } | {
800
+ source: "applescript";
801
+ fallbackReason: string;
802
+ })>;
803
+ /**
804
+ * Total and unread for one mailbox. The index answers alone when it holds
805
+ * the mailbox; Mail's own figure is asked for only when it cannot, since
806
+ * that figure is the cached badge value and the Apple Event cost 0.77 s.
807
+ */
808
+ countMessages(account: MailAccount, mailbox: string): Promise<{
809
+ mailbox: string;
810
+ total: number;
811
+ unread: {
812
+ index: number;
813
+ };
814
+ source: "index";
815
+ } | {
816
+ mailbox: string;
817
+ total: number | null;
818
+ unread: {
819
+ applescript: number | null;
820
+ index: null;
821
+ };
822
+ source: "applescript";
823
+ fallbackReason: string;
824
+ }>;
792
825
  countMailbox(account: MailAccount, mailbox: string): Promise<{
793
826
  accountUuid: string;
794
827
  mailbox: string;
@@ -823,6 +856,25 @@ declare class AppleMailClient {
823
856
  get indexError(): string | null;
824
857
  /** How stale the index file is, so callers can see when they are reading history. */
825
858
  indexAgeSeconds(): Promise<number | null>;
859
+ /**
860
+ * Map index mailbox rows onto scriptable account/mailbox names.
861
+ *
862
+ * Three of the mailbox URLs on a real machine are `local://` (On My Mac) with
863
+ * no account UUID in the host position, so entries that do not resolve are
864
+ * dropped rather than guessed at.
865
+ */
866
+ mailboxLookup(): Promise<Map<number, {
867
+ accountUuid: string;
868
+ mailbox: string;
869
+ url: string;
870
+ }>>;
871
+ /**
872
+ * Index rowids for mailbox names, each resolved exactly as `searchMessages`
873
+ * resolves its `mailbox` filter (same lookup, same refusal naming an unknown
874
+ * one), then united. A watch scopes itself with this so "Archive" means the
875
+ * same mailboxes in both places.
876
+ */
877
+ mailboxRowidsFor(names: string[]): Promise<number[]>;
826
878
  /**
827
879
  * Aggregate matches instead of listing them.
828
880
  *
@@ -853,13 +905,6 @@ declare class AppleMailClient {
853
905
  bodyScan?: BodyScanReport;
854
906
  } | null>;
855
907
  threadOf(ref: string, limit: number): Promise<MessageSummary[] | null>;
856
- countViaIndex(opts: {
857
- account?: string | undefined;
858
- mailbox?: string | undefined;
859
- }): Promise<{
860
- total: number;
861
- unread: number;
862
- } | null>;
863
908
  /**
864
909
  * Read a message body.
865
910
  *
@@ -877,6 +922,22 @@ declare class AppleMailClient {
877
922
  /** Why the file lane was not used. Present only when it was not. */
878
923
  fallbackReason?: string;
879
924
  }>;
925
+ /**
926
+ * The message file alone, parsed, with no Apple Event.
927
+ *
928
+ * For a caller that needs only what the file holds — the attachment manifest
929
+ * — and for whom Mail's scripting interface has no fallback worth waiting
930
+ * for. `fallbackReason` says why there is no file, from an actual lookup.
931
+ */
932
+ readMessageFile(ref: string, opts?: {
933
+ maxBodyBytes?: number;
934
+ }): Promise<{
935
+ parsed: ParsedMessage;
936
+ source: "emlx";
937
+ } | {
938
+ parsed: null;
939
+ fallbackReason: string;
940
+ }>;
880
941
  getMessageSource(ref: string, opts: {
881
942
  offset: number;
882
943
  maxBytes: number;
@@ -970,8 +1031,8 @@ declare class AppleMailClient {
970
1031
  note?: string;
971
1032
  }>;
972
1033
  /**
973
- * Replace a saved draft's body, editing it where that is possible and
974
- * recreating it where it is not.
1034
+ * Change a saved draft, editing it where its window is open and rebuilding
1035
+ * it where it is not.
975
1036
  *
976
1037
  * ## Two lanes, and the order between them is the whole point
977
1038
  *
@@ -981,15 +1042,16 @@ declare class AppleMailClient {
981
1042
  * the save lands on the same draft. Threading, attachments and the quoted
982
1043
  * original survive because nothing is remade. See `revise.ts`.
983
1044
  *
984
- * **Recreating is the fallback.** It composes a replacement and deletes the
985
- * original, which is the only thing Mail's scripting interface allows, and it
986
- * is why `UPDATE_DRAFT` refuses a reply or a draft carrying attachments.
987
- * Those refusals are costs of recreating, not of editing, so they must never
988
- * be reached while a window that could simply be edited is open.
1045
+ * **Rebuilding is the fallback**, for a draft whose window is closed. A reply
1046
+ * is reopened as a reply to its original and filled with the draft's own
1047
+ * HTML and files; the old draft is deleted only once the new one is confirmed
1048
+ * in Drafts. See `rebuild.ts`. A new subject can only be set this way, so it
1049
+ * is refused while the draft's window is open, rather than closing it.
989
1050
  *
990
- * The preflight that decides is only paid when there is a lane to decide for:
991
- * with no accessibility lane — a package installed from npm and run by hand —
992
- * this goes straight to recreation and costs exactly what it always did.
1051
+ * With no accessibility lane — a package installed from npm and run by hand —
1052
+ * there is no window to fill, and a body rewrite goes to `UPDATE_DRAFT`,
1053
+ * which recreates the draft by assigning it and costs exactly what it always
1054
+ * did, refusing a reply or a draft carrying attachments.
993
1055
  *
994
1056
  * The refusals on both lanes come back as ordinary results carrying
995
1057
  * `replaced: false` rather than as thrown errors: a caller that cannot rewrite
@@ -1000,8 +1062,15 @@ declare class AppleMailClient {
1000
1062
  * touched at all: an empty body would silently blank a draft the user wrote,
1001
1063
  * which is the one outcome nothing downstream could distinguish from success.
1002
1064
  */
1003
- updateDraft(ref: string, opts: {
1065
+ updateDraft(target: {
1066
+ ref?: string | undefined;
1067
+ composer?: string | undefined;
1068
+ }, opts: {
1004
1069
  body?: string | undefined;
1070
+ edits?: {
1071
+ find: string;
1072
+ replace: string;
1073
+ }[] | undefined;
1005
1074
  subject?: string | undefined;
1006
1075
  attachments?: string[] | undefined;
1007
1076
  }): Promise<Record<string, unknown>>;
@@ -1009,10 +1078,10 @@ declare class AppleMailClient {
1009
1078
  * The drafts being written right now: every compose window open in Mail.
1010
1079
  *
1011
1080
  * Read from the windows, because nothing else sees them all — see
1012
- * `MailAxLane.listComposers`. Each one is paired with the saved copies Mail
1081
+ * `MailAxLane.composers`. Each one is paired with the saved copies Mail
1013
1082
  * has autosaved under the same subject in a Drafts mailbox, which is where
1014
1083
  * the recipients' ADDRESSES are (the window only shows names) and what
1015
- * `updateDraft` takes. The pairing is by subject, so it is offered as
1084
+ * `updateDraft` takes by ref (the window's own handle is `composer`). The pairing is by subject, so it is offered as
1016
1085
  * candidates rather than asserted; `updateDraft` matches content before it
1017
1086
  * touches anything, so a wrong candidate is refused rather than edited.
1018
1087
  */
@@ -1069,6 +1138,121 @@ declare const decodeRef: (raw: string) => MessageRef;
1069
1138
  /** Group refs by mailbox so a batch of them costs one Apple Event per mailbox, not per message. */
1070
1139
  declare const groupRefsByMailbox: (refs: MessageRef[]) => Map<string, MessageRef[]>;
1071
1140
  //#endregion
1141
+ //#region src/client/watch.d.ts
1142
+ /**
1143
+ * Mail's arrival source over the Envelope Index.
1144
+ *
1145
+ * Envelope metadata only: a `MailArrival` carries no body and no snippet.
1146
+ * The `messages` table is AUTOINCREMENT, so the ROWID is the cursor and never
1147
+ * repeats; `key` is row identity only.
1148
+ *
1149
+ * What the source drops for every watch (`excluded`): Sent, Drafts, Junk and
1150
+ * Trash, the account's own addresses, and rows whose mailbox the lookup does not
1151
+ * know. What only some watches want, the mailbox, is `scope`.
1152
+ */
1153
+ type MailArrival = ArrivalRow & {
1154
+ /** Empty on an excluded row whose mailbox does not resolve; such a row is never delivered. */
1155
+ ref: string;
1156
+ mailbox: string;
1157
+ senderAddress: string | null;
1158
+ senderName: string | null;
1159
+ subject: string | null;
1160
+ dateReceived: string | null;
1161
+ };
1162
+ //#endregion
1163
+ //#region src/tools/watch.d.ts
1164
+ type MailWatchServiceOptions = {
1165
+ client: AppleMailClient;
1166
+ config: Pick<Config, "mailboxCacheTtlMs">;
1167
+ logger?: Logger | undefined;
1168
+ /** Injected by tests; the default asks `pgrep`. */
1169
+ isMailRunning?: (() => Promise<boolean>) | undefined;
1170
+ now?: (() => number) | undefined;
1171
+ /**
1172
+ * Who reads through the service: watches (the default), or the Events
1173
+ * extension (see "Serving events instead"). A refusal names what the client
1174
+ * asked for, a watch or a subscription, so an events client never reads about
1175
+ * watches.
1176
+ */
1177
+ mode?: "watch" | "events" | undefined;
1178
+ };
1179
+ declare class MailWatchService {
1180
+ #private;
1181
+ /** What `createWatches` is given. Delegates to the source `ensure()` builds. */
1182
+ readonly source: ArrivalSource<MailArrival>;
1183
+ constructor(opts: MailWatchServiceOptions);
1184
+ /** How many watches this connection holds. */
1185
+ get count(): number;
1186
+ /** Called once, by `createServer`, after `createWatches` returns. */
1187
+ bind(registry: WatchRegistry<MailArrival>): void;
1188
+ /**
1189
+ * Open the index and build the source, once. Idempotent and concurrency-safe:
1190
+ * two simultaneous `watch` calls share the promise.
1191
+ *
1192
+ * A failure is not kept, so a later call runs setup again. What that recovers
1193
+ * is a failed refresh; an index that would not open stays unopenable, because
1194
+ * `client.index()` memoizes its own failure and answers the same thing again.
1195
+ *
1196
+ * A stale lookup is refreshed on the way out, since a `watch` call is not an
1197
+ * idle poll, and a refresh that fails is tolerated exactly as `onTrigger`
1198
+ * tolerates it: the watch is still usable on the last lookup, so a later
1199
+ * `watch` call must not fail for want of one.
1200
+ *
1201
+ * In events mode the refresh follows the events rule instead (see "Serving
1202
+ * events instead"), since core runs this before every poll and every tick.
1203
+ */
1204
+ ensure(): Promise<void>;
1205
+ /**
1206
+ * The trigger's callback: reopen a replaced index, refresh if rows are waiting
1207
+ * and the lookup is stale, then tick, and refresh once more and tick again if
1208
+ * the scan held back at a mailbox it has never seen.
1209
+ *
1210
+ * Before any lookup has loaded there is none to fall back on (Mail may be
1211
+ * launching, and has written the index before it can answer for its
1212
+ * accounts), so a failed first refresh skips the tick and the next trigger or
1213
+ * the poll tries again.
1214
+ */
1215
+ onTrigger(tick: () => void): Promise<void>;
1216
+ /**
1217
+ * What the file trigger runs. `onTrigger` is async and the trigger's own
1218
+ * log-once guard only sees what throws synchronously, so this one applies the
1219
+ * same rule: a failing tick is logged once until a tick succeeds.
1220
+ */
1221
+ runTrigger(tick: () => void): Promise<void>;
1222
+ /**
1223
+ * What `createWatches` is given as `startTrigger`. Reads the directory now, not
1224
+ * at construction. In events mode `onChange` is core's, whose tick runs
1225
+ * `ensure` itself, so it is called as it is.
1226
+ */
1227
+ startTrigger: (onChange: () => void) => {
1228
+ stop(): void;
1229
+ };
1230
+ /** Close the watch's own handle. Called when the connection ends. */
1231
+ close(): void;
1232
+ remove(id: string): boolean;
1233
+ /** The file identity of the index the watch reads now, or null when it is unknown or unreadable. */
1234
+ identity(): FileIdentity | null;
1235
+ /**
1236
+ * Resolve mailbox names to scope keys (Envelope Index rowids, as strings).
1237
+ * Empty for no names. Refuses with a `PreconditionError` for a name that can
1238
+ * never fire, for names when Mail is not running, for a name that matches no
1239
+ * mailbox, and for more mailboxes than a watch can follow. `running` is for a
1240
+ * caller that has already asked. A refusal says "subscription" in events mode.
1241
+ */
1242
+ resolveMailboxScope(mailboxes: string[], running?: boolean): Promise<string[]>;
1243
+ /**
1244
+ * The refusal `resolveMailboxScope` makes for mailbox names while Mail is not
1245
+ * running, made on its own: for a caller that has to tell it (the server's
1246
+ * state) from the client's own mistakes, and then passes `running: true` on.
1247
+ */
1248
+ requireRunningFor(mailboxes: string[]): Promise<void>;
1249
+ /** Resolve `mailboxes` to scope keys and register the watch. */
1250
+ add(filter: ReturnType<typeof normalizeFilter>, mailboxes: string[] | undefined): Promise<{
1251
+ watch: Watch;
1252
+ running: boolean;
1253
+ }>;
1254
+ }
1255
+ //#endregion
1072
1256
  //#region src/server.d.ts
1073
1257
  declare const SERVER_NAME: string;
1074
1258
  declare const SERVER_VERSION: string;
@@ -1077,10 +1261,18 @@ type CreateServerOptions = {
1077
1261
  logger?: Logger;
1078
1262
  /** Injected by tests so nothing spawns a process or touches a real Mail. */
1079
1263
  osascript?: OsascriptRunner;
1264
+ /** Which protocol era this instance serves. Only watches care. Default `legacy`. */
1265
+ era?: Era;
1266
+ /** Injected by tests so a watch never runs `pgrep`. */
1267
+ isMailRunning?: () => Promise<boolean>;
1080
1268
  };
1081
1269
  type CreatedServer = {
1082
1270
  server: McpServer;
1083
1271
  client: AppleMailClient;
1272
+ /** Present only with `allowWatches` on. */
1273
+ watches?: MailWatchService | undefined;
1274
+ /** Present only with `allowEvents` on. Its own service, never the watches'. */
1275
+ events?: MailWatchService | undefined;
1084
1276
  };
1085
1277
  /**
1086
1278
  * Build the server. Side-effect free: it opens no connection, spawns no
@@ -1096,11 +1288,17 @@ type ToolContext = {
1096
1288
  * not merely refused, they are invisible and cannot be called at all.
1097
1289
  */
1098
1290
  allowWrites: boolean;
1291
+ /**
1292
+ * Present only when `allowWatches` is on. Independent of `allowWrites`: both
1293
+ * watch tools are reads, so they register on read-only servers too.
1294
+ */
1295
+ watches?: MailWatchService | undefined;
1099
1296
  };
1100
1297
  /**
1101
1298
  * Register the Apple Mail tools.
1102
1299
  *
1103
- * The registered set is a pure function of `allowWrites` and nothing else. In
1300
+ * The registered set is a pure function of `allowWrites` and the `allowWatches` gate
1301
+ * (`ctx.watches`), and nothing else. In
1104
1302
  * particular it does NOT vary with whether Full Disk Access is granted: that is
1105
1303
  * a runtime condition which can change while the process lives, and MCP clients
1106
1304
  * cache the tool list, so a tool that appears and disappears would leave clients