@mgcrea/mcp-apple-mail 1.22.1 → 1.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +113 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{server-DsaFsRg0.js → server-pL69NC1O.js} +717 -82
- package/dist/server-pL69NC1O.js.map +1 -0
- package/package.json +2 -2
- package/dist/server-DsaFsRg0.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-DsaFsRg0.js","names":["#channel","#call","#bodyOf","#relative","#names","#db","#mailboxPredicate","#toEpoch","#FROM","#subjectExpr","#filterPredicate","#toIso","#dateBucket","#groupExpr","#runner","#allowlist","#ttlMs","#now","#cache","#admits","#logger","#ax","#located","#indexError","#withRef","#indexTried","#index","#mailboxLookup","#targetMailboxRowids","#rowToSummary","#lookupMessageFile","#explainMissingFile","#sampleMessage"],"sources":["../src/build-info.ts","../src/client/errors.ts","../src/client/locate.ts","../src/client/ax.ts","../src/client/mime.ts","../src/client/emlx.ts","../src/client/body-scan.ts","../src/client/jxa/core.ts","../src/client/jxa/read.ts","../src/client/jxa/write.ts","../src/client/compose.ts","../src/client/schema.ts","../src/client/envelope.ts","../src/client/mailbox-map.ts","../src/client/ref.ts","../src/client/mail.ts","../src/config.ts","../src/guide.ts","../src/prompts.ts","../src/tools/util.ts","../src/tools/diagnostics.ts","../src/tools/accounts.ts","../src/tools/actions.ts","../src/tools/compose.ts","../src/tools/messages.ts","../src/tools/query.ts","../src/tools/search.ts","../src/tools/index.ts","../src/server.ts"],"sourcesContent":["// Build-time / runtime identity for the running server. `name`/`version` are\n// read from package.json at startup (always accurate); `gitCommit` /\n// `gitCommitDate` are injected by tsdown's `define` substitution at build time\n// and fall back to \"unknown\" when running from source (e.g. vitest).\n\nimport { readPackageIdentity, type BuildInfo } from \"@mgcrea/mcp-apple-core\";\n\n// oxlint-disable no-underscore-dangle -- bundler-injected build-time constants.\ndeclare const __GIT_COMMIT__: string;\ndeclare const __GIT_COMMIT_DATE__: string;\n\nconst pkg = readPackageIdentity(new URL(\"../package.json\", import.meta.url), {\n name: \"@mgcrea/mcp-apple-mail\",\n version: \"0.0.0\",\n});\n\nexport type { BuildInfo };\n\nexport const BUILD_INFO: BuildInfo = {\n name: pkg.name,\n version: pkg.version,\n gitCommit: typeof __GIT_COMMIT__ === \"string\" ? __GIT_COMMIT__ : \"unknown\",\n gitCommitDate: typeof __GIT_COMMIT_DATE__ === \"string\" ? __GIT_COMMIT_DATE__ : \"unknown\",\n};\n","/**\n * Mail's error surface.\n *\n * The taxonomy itself lives in `@mgcrea/mcp-apple-core` — TCC denial, app not\n * running, app busy and the rest are facts about driving any Apple app, not\n * about mail. What belongs here is the identity those messages are written\n * against, and the one error that is genuinely about messages.\n */\n\nimport { AppleAutomationError, type SurfaceContext } from \"@mgcrea/mcp-apple-core\";\n\n/** Named in every user-facing error and in the env vars they mention. */\nexport const MAIL_SURFACE: SurfaceContext = { appName: \"Mail\", envPrefix: \"APPLE_MAIL\" };\n\nexport {\n AppleAutomationError as AppleMailError,\n AppBusyError as MailBusyError,\n AppNotRunningError as MailNotRunningError,\n IndexUnavailableError,\n OsascriptTimeoutError,\n PlatformError,\n PreconditionError,\n ProtocolError,\n SchemaDriftError,\n TccDeniedError,\n WritesDisabledError,\n} from \"@mgcrea/mcp-apple-core\";\n\n/** A MessageRef no longer resolves — the message was moved, deleted, or the index is stale. */\nexport class MessageNotFoundError extends AppleAutomationError {\n override readonly name = \"MessageNotFoundError\";\n\n constructor(ref: string) {\n super(\n `No message for ref \"${ref}\". It was probably moved or deleted since the search ran. ` +\n `Re-run the search to get a current ref.`,\n );\n }\n}\n","import { readdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { inspectFile, type FileFacts } from \"@mgcrea/mcp-apple-core\";\n\n/**\n * Find Mail's data root and its Envelope Index.\n *\n * The obvious approach — glob `~/Library/Mail/V*` — does not work: that\n * directory is TCC-protected, so without Full Disk Access the glob returns\n * nothing even though the path is right there. Mail itself will hand us the\n * answer though: `account.accountDirectory()` returns\n * `~/Library/Mail/V10/<accountUuid>` over Apple Events, which need only the\n * Automation permission. So Mail naming its own directory is the primary\n * strategy and the glob is the fallback, not the other way round.\n *\n * A second subtlety, learned the same way: `statSync` SUCCEEDS on a\n * TCC-protected file — you get the real size and mtime — and only open(2) and\n * access(2) are denied. Existence and readability are therefore different\n * questions here, and only readability tells you whether FDA is granted.\n */\n\nexport type LocateResult = {\n /** e.g. /Users/me/Library/Mail/V10 */\n mailRoot: string | null;\n /** e.g. V10 */\n dataVersion: string | null;\n envelopeIndexPath: string | null;\n /** How mailRoot was decided — reported by diagnostics so a bug report is self-describing. */\n strategy: \"config\" | \"accountDirectory\" | \"glob\" | \"none\";\n exists: boolean;\n readable: boolean;\n sizeBytes: number | null;\n mtime: string | null;\n /** Whether a -wal file is present, i.e. whether `immutable=1` COULD miss recent mail. */\n walPresent: boolean;\n walSizeBytes: number | null;\n reason: string | null;\n};\n\nexport { inspectFile, type FileFacts };\n\nexport type LocateOptions = {\n /** Explicit index path from config — wins outright. */\n envelopeIndexPath?: string | undefined;\n /** Explicit Mail root from config. */\n mailRoot?: string | undefined;\n /** Any account directory reported by Mail, e.g. ~/Library/Mail/V10/<uuid>. */\n accountDirectory?: string | undefined;\n /** Injectable for tests. */\n home?: string | undefined;\n};\n\nconst INDEX_SUFFIX = join(\"MailData\", \"Envelope Index\");\n\nconst highestVersionDir = (mailHome: string): string | null => {\n try {\n const versions = readdirSync(mailHome)\n .filter((d) => /^V\\d+$/.test(d))\n .toSorted((a, b) => Number(b.slice(1)) - Number(a.slice(1)));\n return versions[0] ?? null;\n } catch {\n // Almost always EPERM without Full Disk Access — not \"Mail isn't installed\".\n return null;\n }\n};\n\nexport const locateEnvelopeIndex = (opts: LocateOptions = {}): LocateResult => {\n const home = opts.home ?? homedir();\n\n let mailRoot: string | null = null;\n let indexPath: string | null = null;\n let strategy: LocateResult[\"strategy\"] = \"none\";\n\n if (opts.envelopeIndexPath) {\n indexPath = opts.envelopeIndexPath;\n mailRoot = dirname(dirname(indexPath));\n strategy = \"config\";\n } else if (opts.mailRoot) {\n mailRoot = opts.mailRoot;\n indexPath = join(mailRoot, INDEX_SUFFIX);\n strategy = \"config\";\n } else if (opts.accountDirectory) {\n mailRoot = dirname(opts.accountDirectory);\n indexPath = join(mailRoot, INDEX_SUFFIX);\n strategy = \"accountDirectory\";\n } else {\n const mailHome = join(home, \"Library\", \"Mail\");\n const v = highestVersionDir(mailHome);\n if (v) {\n mailRoot = join(mailHome, v);\n indexPath = join(mailRoot, INDEX_SUFFIX);\n strategy = \"glob\";\n }\n }\n\n if (!indexPath || !mailRoot) {\n return {\n mailRoot: null,\n dataVersion: null,\n envelopeIndexPath: null,\n strategy: \"none\",\n exists: false,\n readable: false,\n sizeBytes: null,\n mtime: null,\n walPresent: false,\n walSizeBytes: null,\n reason:\n \"Could not locate Mail's data directory. Mail did not report an account directory and \" +\n \"~/Library/Mail could not be listed (expected without Full Disk Access).\",\n };\n }\n\n const facts = inspectFile(indexPath);\n const wal = inspectFile(`${indexPath}-wal`);\n\n const reason = facts.exists\n ? facts.readable\n ? null\n : \"The Envelope Index exists but cannot be read. Grant Full Disk Access to the app running \" +\n \"this server (System Settings > Privacy & Security > Full Disk Access) and restart it. \" +\n \"Granting it to Mail.app does nothing — the reader needs the permission.\"\n : `No Envelope Index at ${indexPath}. Has Mail ever been set up on this account?`;\n\n return {\n mailRoot,\n dataVersion: /\\/(V\\d+)$/.exec(mailRoot)?.[1] ?? null,\n envelopeIndexPath: indexPath,\n strategy,\n exists: facts.exists,\n readable: facts.readable,\n sizeBytes: facts.size,\n mtime: facts.mtime,\n walPresent: wal.exists,\n walSizeBytes: wal.size,\n reason,\n };\n};\n","import {\n openAxChannel,\n watchInterference,\n type AxChannel,\n type InterferenceWatch,\n} from \"@mgcrea/mcp-apple-core\";\n\nimport { MAIL_SURFACE } from \"./errors.js\";\n\n/**\n * Mail's composer, driven through Cupertino's native Accessibility driver.\n *\n * ## What this replaces, and why it is worth replacing\n *\n * `jxa/core.ts` reaches the same composer through System Events. That path\n * works, and it costs two things this one does not:\n *\n * * **A second TCC grant.** UI scripting through System Events needs\n * Automation-to-System-Events *on top of* Accessibility — two grants, in two\n * System Settings panes, to reach one window. `composerGrantMessage` is ten\n * lines long because of it.\n * * **47.4 ms per attribute read**, against 0.202 ms called natively. Which is\n * why `findBodyArea` is bounded at depth 6 and `composerBodyText` carries a\n * character budget: both are cost control, not correctness.\n *\n * ## What it deliberately does NOT change\n *\n * **The body is still pasted.** Assigning `content` is dropped by Mail, and so\n * is setting AXValue on the web area, \"which reports itself settable first and\n * then does nothing\" — measured in `jxa/write.ts`, and independently in\n * `docs/desktop.md`, which found the same trap on the first text field of all\n * seven apps it probed. A native driver does not make an app honour a write it\n * ignores. The clipboard is still borrowed and still put back.\n *\n * **Nothing reports a draft ready on the strength of a write being accepted.**\n * That is the failure this whole path is shaped around: a draft correct in every\n * visible respect except the words, reported as a success.\n *\n * ## The fallback is not optional\n *\n * `openAxChannel` returns null when this server was not started by Cupertino —\n * the npm packages are published artifacts and are run by hand. Every function\n * here is reached only after `available()`, and `client/mail.ts` keeps the\n * System Events path for when it is false.\n */\n\nconst MAIL_BUNDLE = \"com.apple.mail\";\n\n/** Mail's composer body is a WebKit view, not a text field. */\nconst BODY_ROLE = \"AXWebArea\";\n\n/**\n * How deep to look for the body.\n *\n * `findBodyArea` uses 6 and says the bound is there to survive the cost. Cost is\n * no longer the reason, so this is only a guard against walking a composer that\n * holds a deeply nested quoted message — the web area itself sits near the top.\n */\nconst BODY_DEPTH = 8;\n\n/**\n * How long to keep asking the composer's body to take the focus.\n *\n * **Readable is not ready, and the gap is not zero.** `findComposer` returns as\n * soon as the window and its web area can be READ; the body cannot take the\n * keyboard for about another 140 ms after that. Measured over three fresh\n * composers, driving the real driver:\n *\n * web area readable at 395 ms focus -> false at 421 ms, true at 560 ms\n * web area readable at 637 ms focus -> false at 671 ms, true at 812 ms\n * web area readable at 640 ms focus -> false at 665 ms, true at 805 ms\n *\n * The first attempt failed on every trial. Without a poll here that is a\n * coin-flip resting on how long the surrounding round trips happen to take —\n * `compose.ts` retries the whole paste once, for an unrelated reason, and that\n * retry was silently carrying this.\n *\n * Which is `docs/desktop.md`'s most expensive lesson arriving in a new place:\n * *the control must be polled for, not waited for*. It was written about a\n * window's chrome appearing before its content; this is the same shape one level\n * down, where the content is there and the focus is not.\n */\nconst FOCUS_TIMEOUT_MS = 2_000;\n\n/** Between focus attempts. Each one is a round trip, so this is not a spin. */\nconst FOCUS_POLL_MS = 100;\n\ntype Element = {\n handle: string;\n role: string;\n name?: string | null;\n value?: string | null;\n depth: number;\n};\n\ntype Tree = { elements?: Element[]; matched?: number; truncated?: string };\ntype Windows = { windows?: { handle: string; index: number; title?: string | null }[] };\n\nexport type ComposerRef = { window: string; body: string; index: number };\n\nexport type ReachReport = {\n ok: boolean;\n /** `accessibility` when Mail's windows cannot be read; null when they can. */\n reason: \"accessibility\" | null;\n windows: string[] | null;\n};\n\nexport class MailAxLane {\n readonly #channel: AxChannel;\n\n private constructor(channel: AxChannel) {\n this.#channel = channel;\n }\n\n /** Null when this server is not hosted by Cupertino — see the note above. */\n static open(env: NodeJS.ProcessEnv = process.env): MailAxLane | null {\n const channel = openAxChannel(MAIL_SURFACE, env);\n return channel ? new MailAxLane(channel) : null;\n }\n\n close(): void {\n this.#channel.close();\n }\n\n /** Start watching for someone using the Mac during a sequence. */\n watch(): InterferenceWatch {\n return watchInterference(this.#channel);\n }\n\n #call(tool: string, args: Record<string, unknown> = {}): Promise<unknown> {\n return this.#channel.call({ tool: `apple_desktop_${tool}`, args });\n }\n\n /**\n * Can this process read Mail's windows, right now?\n *\n * Asked BEFORE a composer is opened, keeping the ordering `jxa/write.ts`\n * established: the old shape opened a window, failed the read, and left an\n * empty reply on screen with an error telling the user to close it by hand.\n *\n * Ground truth is the functional read, never a trusted flag. One bundle\n * identifier can hold several Accessibility entries — one per path and\n * signature it has been granted at — so the flag can answer for a different\n * row from the one the request resolves against. A window list that comes back\n * named is proof regardless of what the flag says.\n *\n * Mail with no windows is legitimate — everything closed to the menu bar — so\n * an empty list is not evidence of anything and must not refuse a reply that\n * would have worked.\n */\n async reach(): Promise<ReachReport> {\n try {\n const result = (await this.#call(\"list_windows\", {\n bundleId: MAIL_BUNDLE,\n includeTitles: true,\n })) as Windows;\n const titles = (result.windows ?? []).map((w) => w.title ?? null);\n return { ok: true, reason: null, windows: titles.filter((t): t is string => t !== null) };\n } catch {\n return { ok: false, reason: \"accessibility\", windows: null };\n }\n }\n\n /**\n * The sentence to say when the composer cannot be reached natively.\n *\n * One grant rather than two, and none of the \"quit Cupertino and open it\n * again\" ritual the System Events path needs — that exists because a node\n * child started before the grant does not inherit it, and this driver runs in\n * the app itself.\n */\n static grantMessage(mode: string): string {\n return (\n `Cupertino cannot read Mail's windows, which is the only route into a ${mode} composer, ` +\n `so it was not started and nothing was written. This needs Accessibility for ` +\n `Cupertino.app in System Settings > Privacy & Security > Accessibility. If the app is ` +\n `already listed, toggle it off and on — the grant goes stale when the bundle is ` +\n `reinstalled. Run apple_mail_diagnostics to check; it names the windows it can see.`\n );\n }\n\n /**\n * Poll for the composer window, and for its body.\n *\n * Polled rather than waited for, which `docs/desktop.md` records as the trap\n * that cost it the most: a window's chrome appearing is not its content being\n * ready, so no fixed settle time is correct. Cheap here — a bounded walk is\n * milliseconds.\n *\n * The subject is the identity, and requiring a body area with it rejects the\n * main window and the drafts list. It is an identity only because `compose.ts`\n * refuses when a composer under the same subject was already open before the\n * call: a leftover from an earlier attempt matches here just as well, and is\n * readable first. Counting windows does not work: Mail closes\n * and reuses windows around a compose, so the count comes back unchanged with\n * a new composer on screen.\n */\n async findComposer(subject: string, timeoutMs: number): Promise<ComposerRef | null> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const listed = (await this.#call(\"list_windows\", {\n bundleId: MAIL_BUNDLE,\n includeTitles: true,\n })) as Windows;\n for (const win of listed.windows ?? []) {\n if ((win.title ?? \"\") !== subject) continue;\n const body = await this.#bodyOf(win.index);\n if (body) return { window: win.handle, body, index: win.index };\n }\n if (Date.now() >= deadline) return null;\n await new Promise((resolve) => setTimeout(resolve, 200));\n }\n }\n\n async #bodyOf(windowIndex: number): Promise<string | null> {\n const tree = (await this.#call(\"ui_tree\", {\n bundleId: MAIL_BUNDLE,\n window: windowIndex,\n detail: \"all\",\n maxDepth: BODY_DEPTH,\n })) as Tree;\n return (tree.elements ?? []).find((el) => el.role === BODY_ROLE)?.handle ?? null;\n }\n\n /** Bring Mail to the front. A synthetic keystroke lands in whatever is frontmost. */\n async activate(): Promise<void> {\n await this.#call(\"activate\", { bundleId: MAIL_BUNDLE });\n }\n\n /**\n * The accessible text under the body, which is what a person would see.\n *\n * One call rather than a bounded walk. The System Events version reads a\n * parent at a time and stops at a character budget because every node costs an\n * Apple Event; here the whole subtree comes back in one answer with each\n * element's value already on it.\n *\n * Returns null when the body cannot be reached at all — a different answer\n * from \"\", and the two must stay apart: one means we are blind, the other\n * means the composer is empty.\n */\n async bodyText(body: string): Promise<string | null> {\n try {\n const tree = (await this.#call(\"expand\", {\n handle: body,\n detail: \"all\",\n maxDepth: BODY_DEPTH,\n })) as Tree;\n return (tree.elements ?? [])\n .map((el) => el.value)\n .filter((v): v is string => typeof v === \"string\" && v.trim() !== \"\")\n .join(\"\\n\");\n } catch {\n return null;\n }\n }\n\n /**\n * How many elements the body holds.\n *\n * A fingerprint, not a reading. Taken before and after a paste it answers \"did\n * anything at all land\", which is what decides whether pasting again is safe:\n * a paste that landed and cannot be read must NOT be repeated, or the reply\n * ends up in the draft twice with no way to undo it from here.\n *\n * `matched` rather than the returned length, because the response is byte\n * capped and a long quoted message will truncate — a fingerprint taken from a\n * truncated list would compare two different bounds rather than two states.\n *\n * **Null when the body cannot be read at all, and that is the whole point.**\n * This returned -1 for a failed read, and the caller compared it as a count.\n * A composer that CLOSES takes its element handle with it — the driver answers\n * `staleHandle` — so a body that had gone in perfectly read back as -1 and\n * compared unequal to the size before, which is the signature of \"something\n * landed that cannot be matched\". A reply sent by hand mid-call was reported\n * as a body that never went in, with a warning against the retry that was in\n * fact the safe move. Blind and different are not the same answer, exactly as\n * `bodyText` above insists, and this is where that was forgotten.\n */\n async bodySize(body: string): Promise<number | null> {\n try {\n const tree = (await this.#call(\"expand\", {\n handle: body,\n detail: \"all\",\n maxDepth: BODY_DEPTH,\n })) as Tree;\n return tree.matched ?? (tree.elements ?? []).length;\n } catch {\n return null;\n }\n }\n\n /**\n * Focus the body and paste, and say whether the focus took.\n *\n * Focus is not a raise: a raise orders a window forward inside Mail while the\n * keystroke goes wherever the focus actually is. Both are needed, and the\n * focus is read back because an element can report itself focusable and not\n * take it.\n *\n * **What \"read back\" has to mean here, learned the hard way.** Mail's composer\n * web area answers `AXFocused: false` while holding the keyboard — measured\n * over 1.2 s without ever flipping, with a command-V landing in it the whole\n * time. `apple_desktop_focus` used to return that flag, so this guard refused\n * to press command-V and every native reply came back \"Nothing landed in it\"\n * for a body that would have gone in. The driver now answers from the\n * APPLICATION's `AXFocusedUIElement`, which is what the window server routes\n * keystrokes by and so cannot disagree with where one will land.\n *\n * The guard itself stays. Posting command-V without knowing where the focus is\n * types into whatever happens to be in front, and that is the user's window.\n *\n * **A composer that has gone answers false rather than throwing.** Both handles\n * die with the window, so raising or focusing one afterwards is a `staleHandle`\n * — and letting that escape turns a describable failure into a bare channel\n * error with no note attached, on the one path whose whole job is to say what\n * happened. False is the honest answer: the focus was not taken, so nothing was\n * typed.\n */\n async paste(ref: ComposerRef, focusTimeoutMs = FOCUS_TIMEOUT_MS): Promise<boolean> {\n try {\n await this.#call(\"raise_window\", { handle: ref.window });\n await this.activate();\n const deadline = Date.now() + focusTimeoutMs;\n for (;;) {\n const focused = (await this.#call(\"focus\", { handle: ref.body })) as { focused?: boolean };\n if (focused.focused === true) break;\n if (Date.now() >= deadline) return false;\n await new Promise((resolve) => setTimeout(resolve, FOCUS_POLL_MS));\n }\n // Named by the body's handle, so the desktop server brings Mail forward\n // before posting and refuses if it does not come. The activate above can\n // be undone by the person at the keyboard in the milliseconds between.\n await this.#call(\"key\", { key: \"v\", modifiers: [\"command\"], handle: ref.body });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Send the composer, or save it as a draft.\n *\n * A keyboard shortcut rather than the Send button, and that is a correctness\n * choice rather than a shortcut in the other sense: the button's name is\n * localised — a French Mail says \"Envoyer\" — while command-shift-D is the same\n * on every Mac. Addressing it by name would have worked on the machine it was\n * written on and nowhere else.\n *\n * This is the step that replaces `draft.send()`, and the reason it had to. A\n * JXA object reference cannot outlive the `osascript` process that made it,\n * and this flow now spans two processes: Apple Events opens the composer, and\n * everything after is native. Re-finding the draft to send it was the\n * alternative and is worse — drafts are discovered by subject, so two with the\n * same one are indistinguishable, on the single path whose named failure is\n * sending the wrong thing.\n *\n * **The window is raised again first, and the answer says whether that took.**\n * The focus is only known to be in the composer at the moment of the paste;\n * between the read that verifies the body and this keystroke the person at the\n * keyboard can move the foreground, and command-shift-D would then be posted\n * into whatever they moved to. Re-raising costs two round trips and closes\n * that window.\n *\n * The keystroke also names the composer's window, which closes the gap that\n * remains between the re-raise and the key: the desktop server brings Mail\n * forward again and refuses rather than posting into something else.\n *\n * Only `\"pressed\"` means anything was pressed. The other two answers are both\n * refusals, and they are kept apart because they mean opposite things to the\n * person reading the result:\n *\n * * `\"gone\"`: the composer could not be raised. Its handle died with the\n * window, so somebody sent or closed it.\n * * `\"refused\"`: raised, but the keystroke was refused because Mail would\n * not come forward. The composer is still on screen, unsent.\n *\n * Posting a send into an unknown foreground is the one outcome worth refusing\n * outright, which is why neither of them throws.\n */\n async finish(sendNow: boolean, ref: ComposerRef): Promise<\"pressed\" | \"gone\" | \"refused\"> {\n try {\n await this.#call(\"raise_window\", { handle: ref.window });\n await this.activate();\n } catch {\n return \"gone\";\n }\n try {\n await this.#call(\n \"key\",\n sendNow\n ? { key: \"d\", modifiers: [\"command\", \"shift\"], handle: ref.window }\n : { key: \"s\", modifiers: [\"command\"], handle: ref.window },\n );\n } catch {\n return \"refused\";\n }\n return \"pressed\";\n }\n\n /**\n * Has the composer for this subject gone?\n *\n * How a send is confirmed. Mail closes the window when it accepts one, so the\n * window still being there means it did not go — which is checked rather than\n * assumed, because nothing in this path may report success on the strength of\n * a keystroke having been delivered.\n */\n async composerGone(subject: string, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const listed = (await this.#call(\"list_windows\", {\n bundleId: MAIL_BUNDLE,\n includeTitles: true,\n })) as Windows;\n if (!(listed.windows ?? []).some((w) => (w.title ?? \"\") === subject)) return true;\n if (Date.now() >= deadline) return false;\n await new Promise((resolve) => setTimeout(resolve, 200));\n }\n }\n\n /** Select everything in the body, for the quote strip. */\n async selectAll(): Promise<void> {\n await this.#call(\"key\", { key: \"a\", modifiers: [\"command\"] });\n }\n\n /**\n * The deepest quote level anywhere in the body; 0 once the citation is gone.\n *\n * `AXBlockQuoteLevel` is not in the tree's field set, which is chosen for\n * addressing controls — so it is read one element at a time. That is\n * affordable only natively: 343 elements at 0.2 ms is well under a tenth of a\n * second, where the same walk through System Events would be sixteen.\n */\n async maxQuoteLevel(body: string): Promise<number> {\n const tree = (await this.#call(\"expand\", {\n handle: body,\n detail: \"all\",\n maxDepth: BODY_DEPTH,\n })) as Tree;\n let worst = 0;\n for (const el of tree.elements ?? []) {\n const read = (await this.#call(\"get_attribute\", {\n handle: el.handle,\n attribute: \"AXBlockQuoteLevel\",\n })) as { value?: unknown };\n const level = typeof read.value === \"number\" ? read.value : 0;\n if (level > worst) worst = level;\n }\n return worst;\n }\n}\n\n/**\n * Does the pasted text appear at the top of what the composer now holds?\n *\n * Whitespace-squashed on both sides: the accessible text of a WebKit view breaks\n * lines where the rendering does, not where the source did.\n */\nconst squash = (s: string) => s.replace(/\\s+/g, \" \").trim();\n\nexport const containsText = (haystack: string, needle: string): boolean => {\n const n = squash(needle);\n if (!n) return true;\n return squash(haystack).includes(n);\n};\n","/**\n * A small MIME reader, hand-rolled to keep the dependency count at two.\n *\n * It does the parts that actually come up when reading real mail — RFC 2047\n * headers, base64 and quoted-printable bodies, multipart walking, charset\n * decoding, and picking the part a human would want to read — and nothing else.\n * It is not a general-purpose MIME library and does not try to be.\n */\n\nexport type Header = { name: string; value: string };\n\nexport type MimePart = {\n headers: Header[];\n contentType: string;\n charset: string | null;\n encoding: string | null;\n disposition: string | null;\n filename: string | null;\n contentId: string | null;\n /** Raw (still-encoded) body for leaf parts. */\n raw: Buffer;\n parts: MimePart[];\n};\n\nexport type Attachment = {\n filename: string | null;\n contentType: string;\n contentId: string | null;\n /**\n * Size in bytes, or null if genuinely unknowable.\n *\n * The DECODED length when the bytes are in this file, otherwise null — the\n * parser cannot know. `readEmlx` fills it in from the sidecar file on disk,\n * which is both exact and the only way to know if it can be fetched. Never 0,\n * which would read as a measurement rather than an absence.\n */\n sizeBytes: number | null;\n /** False when the bytes were stripped into a sidecar file (.partial.emlx). */\n inline: boolean;\n};\n\n// ─── headers ─────────────────────────────────────────────────────────────────\n\nconst decodeBase64 = (s: string): Buffer => Buffer.from(s, \"base64\");\n\nconst decodeQuotedPrintable = (s: string, forHeader = false): Buffer => {\n const bytes: number[] = [];\n for (let i = 0; i < s.length; i += 1) {\n const ch = s[i]!;\n if (ch === \"=\" && i + 1 < s.length) {\n const next = s.slice(i + 1, i + 3);\n if (next === \"\\r\\n\" || next[0] === \"\\n\") {\n // Soft line break: the newline is not part of the content.\n i += next[0] === \"\\n\" ? 1 : 2;\n continue;\n }\n if (/^[0-9A-Fa-f]{2}$/.test(next)) {\n bytes.push(Number.parseInt(next, 16));\n i += 2;\n continue;\n }\n }\n if (forHeader && ch === \"_\") {\n // In encoded words, underscore means space. Only there.\n bytes.push(0x20);\n continue;\n }\n bytes.push(ch.charCodeAt(0));\n }\n return Buffer.from(bytes);\n};\n\nexport const decodeCharset = (buf: Buffer, charset: string | null): string => {\n const label = (charset ?? \"utf-8\").toLowerCase().replaceAll(/[\"']/g, \"\");\n try {\n return new TextDecoder(label).decode(buf);\n } catch {\n // An unknown or misspelled charset should not lose the message.\n return buf.toString(\"utf8\");\n }\n};\n\n/**\n * Decode RFC 2047 encoded words, e.g. `=?UTF-8?Q?Facture_5753?=`.\n *\n * Adjacent encoded words separated only by whitespace are joined without it,\n * which is what the RFC requires and what makes multi-word subjects come out\n * right instead of gaining stray spaces.\n */\nexport const decodeEncodedWords = (input: string): string => {\n const pattern = /=\\?([^?]+)\\?([BbQq])\\?([^?]*)\\?=/g;\n let result = \"\";\n let lastEnd = 0;\n let previousWasEncoded = false;\n\n for (const match of input.matchAll(pattern)) {\n const start = match.index;\n const between = input.slice(lastEnd, start);\n if (!(previousWasEncoded && between.trim() === \"\")) result += between;\n\n const [, charset, kind, payload] = match;\n const decoded =\n kind?.toLowerCase() === \"b\"\n ? decodeCharset(decodeBase64(payload ?? \"\"), charset ?? null)\n : decodeCharset(decodeQuotedPrintable(payload ?? \"\", true), charset ?? null);\n result += decoded;\n\n lastEnd = start + match[0].length;\n previousWasEncoded = true;\n }\n return result + input.slice(lastEnd);\n};\n\n/** Split a header block into unfolded name/value pairs. */\nexport const parseHeaders = (block: string): Header[] => {\n const headers: Header[] = [];\n // Continuation lines start with whitespace and belong to the previous header.\n const lines = block.split(/\\r?\\n/);\n let current: string | null = null;\n\n const flush = () => {\n if (current === null) return;\n const idx = current.indexOf(\":\");\n if (idx > 0) {\n headers.push({ name: current.slice(0, idx).trim(), value: current.slice(idx + 1).trim() });\n }\n current = null;\n };\n\n for (const line of lines) {\n if (/^[ \\t]/.test(line) && current !== null) current += ` ${line.trim()}`;\n else {\n flush();\n current = line;\n }\n }\n flush();\n return headers;\n};\n\nexport const headerValue = (headers: Header[], name: string): string | null =>\n headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? null;\n\n/** Pull a parameter out of a structured header, handling quotes. */\nexport const headerParam = (value: string | null, param: string): string | null => {\n if (!value) return null;\n const match = new RegExp(`${param}\\\\s*=\\\\s*\"([^\"]*)\"|${param}\\\\s*=\\\\s*([^;\\\\s]+)`, \"i\").exec(\n value,\n );\n return match ? (match[1] ?? match[2] ?? null) : null;\n};\n\n/**\n * The filename a part actually carries, through both ways of spelling one.\n *\n * `headerParam` reads `filename=\"x\"` and nothing else, which is fine for\n * `charset` and `boundary` — both plain ASCII tokens by definition — and wrong\n * for a filename, because a filename is the one parameter that routinely is not\n * ASCII. Two encodings exist for it and mail uses both:\n *\n * RFC 2231 `filename*=UTF-8''r%C3%A9sum%C3%A9.pdf`\n * also split across `filename*0*=`, `filename*1*=` for long names\n * RFC 2047 `name=\"=?utf-8?Q?r=C3=A9sum=C3=A9=2Epdf?=\"`\n *\n * Neither was handled. The first returned null, so an attachment with an\n * accented name was reported as having no filename at all — which\n * `list_attachments` shows as unretrievable and `save_attachment` cannot write.\n * The second came back verbatim, so saving it wrote a file literally named\n * `=?utf-8?Q?...?=` on disk.\n *\n * RFC 2231 is tried first because it is the one designed for this; the RFC 2047\n * form in a parameter is technically not allowed and is nonetheless everywhere.\n */\nexport const headerFilename = (\n disposition: string | null,\n contentType: string | null,\n): string | null => {\n for (const [value, param] of [\n [disposition, \"filename\"],\n [contentType, \"name\"],\n ] as const) {\n if (!value) continue;\n const extended = extendedParam(value, param);\n if (extended !== null) return extended;\n const plain = headerParam(value, param);\n if (plain !== null) return decodeEncodedWords(plain);\n }\n return null;\n};\n\n/**\n * The RFC 2231 form, including the numbered continuations long names use.\n *\n * A continuation is only percent-decoded when its own segment is starred —\n * `filename*1=` is literal text and `filename*1*=` is encoded, and treating the\n * two alike turns a legitimate `%` in a filename into mojibake.\n */\nconst extendedParam = (value: string, param: string): string | null => {\n const single = new RegExp(`${param}\\\\*\\\\s*=\\\\s*(?:\"([^\"]*)\"|([^;\\\\s]+))`, \"i\").exec(value);\n if (single) return decodeExtended(single[1] ?? single[2] ?? \"\", true);\n\n const segments: { index: number; text: string; encoded: boolean }[] = [];\n const pattern = new RegExp(`${param}\\\\*(\\\\d+)(\\\\*)?\\\\s*=\\\\s*(?:\"([^\"]*)\"|([^;\\\\s]+))`, \"gi\");\n for (const match of value.matchAll(pattern)) {\n segments.push({\n index: Number(match[1]),\n text: match[3] ?? match[4] ?? \"\",\n encoded: match[2] === \"*\",\n });\n }\n if (segments.length === 0) return null;\n segments.sort((a, b) => a.index - b.index);\n\n // The charset prefix rides on the first segment only.\n let charset: string | null = null;\n let out = \"\";\n for (const [position, segment] of segments.entries()) {\n if (!segment.encoded) {\n out += segment.text;\n continue;\n }\n if (position === 0) {\n const parts = segment.text.split(\"'\");\n if (parts.length >= 3) {\n charset = parts[0] || null;\n out += percentDecode(parts.slice(2).join(\"'\"), charset);\n continue;\n }\n }\n out += percentDecode(segment.text, charset);\n }\n return out;\n};\n\nconst decodeExtended = (raw: string, hasCharsetPrefix: boolean): string => {\n if (!hasCharsetPrefix) return percentDecode(raw, null);\n const parts = raw.split(\"'\");\n // charset'language'text — anything shorter is not the extended form.\n if (parts.length < 3) return percentDecode(raw, null);\n return percentDecode(parts.slice(2).join(\"'\"), parts[0] || null);\n};\n\n/** Percent-decoded as BYTES, then read in the charset the header named. */\nconst percentDecode = (raw: string, charset: string | null): string => {\n const bytes: number[] = [];\n for (let i = 0; i < raw.length; i += 1) {\n if (raw[i] === \"%\" && /^[0-9a-f]{2}$/i.test(raw.slice(i + 1, i + 3))) {\n bytes.push(Number.parseInt(raw.slice(i + 1, i + 3), 16));\n i += 2;\n } else {\n bytes.push(raw.charCodeAt(i) & 0xff);\n }\n }\n return decodeCharset(Buffer.from(bytes), charset);\n};\n\n// ─── body ────────────────────────────────────────────────────────────────────\n\nconst HEADER_BODY_SPLIT = /\\r?\\n\\r?\\n/;\n\nexport const parsePart = (buf: Buffer): MimePart => {\n const text = buf.toString(\"latin1\"); // byte-preserving: real decoding happens per-part\n const split = HEADER_BODY_SPLIT.exec(text);\n const headerBlock = split ? text.slice(0, split.index) : text;\n const bodyStart = split ? split.index + split[0].length : text.length;\n\n const headers = parseHeaders(headerBlock);\n const contentTypeRaw = headerValue(headers, \"content-type\");\n const contentType = (contentTypeRaw?.split(\";\")[0] ?? \"text/plain\").trim().toLowerCase();\n const dispositionRaw = headerValue(headers, \"content-disposition\");\n\n const part: MimePart = {\n headers,\n contentType,\n charset: headerParam(contentTypeRaw, \"charset\"),\n encoding: headerValue(headers, \"content-transfer-encoding\")?.trim().toLowerCase() ?? null,\n disposition: dispositionRaw?.split(\";\")[0]?.trim().toLowerCase() ?? null,\n filename: headerFilename(dispositionRaw, contentTypeRaw),\n contentId: headerValue(headers, \"content-id\")?.replaceAll(/[<>]/g, \"\") ?? null,\n raw: Buffer.from(text.slice(bodyStart), \"latin1\"),\n parts: [],\n };\n\n if (contentType.startsWith(\"multipart/\")) {\n const boundary = headerParam(contentTypeRaw, \"boundary\");\n if (boundary) part.parts = splitMultipart(part.raw, boundary);\n }\n return part;\n};\n\nconst splitMultipart = (body: Buffer, boundary: string): MimePart[] => {\n const text = body.toString(\"latin1\");\n const marker = `--${boundary}`;\n\n /**\n * RFC 2046: a delimiter starts a line, and nothing follows it but the closing\n * `--` or the end of that line. Both halves earn their keep. Without the\n * first, a body that merely quotes the delimiter splits the part it sits in.\n * Without the second, `--B` also matches inside `--B2`, which flattened a\n * nested multipart into its parent's sibling list — harmless while only one\n * part was ever read, and a doubled body the moment the parts are joined.\n */\n const isDelimiter = (at: number): boolean => {\n if (at !== 0 && text[at - 1] !== \"\\n\") return false;\n const after = text[at + marker.length];\n return after === undefined || after === \"\\r\" || after === \"\\n\" || after === \"-\";\n };\n const find = (from: number): number => {\n let at = text.indexOf(marker, from);\n while (at !== -1 && !isDelimiter(at)) at = text.indexOf(marker, at + 1);\n return at;\n };\n\n const segments: string[] = [];\n let index = find(0);\n if (index === -1) return [];\n\n while (index !== -1) {\n const afterMarker = index + marker.length;\n if (text.startsWith(\"--\", afterMarker)) break; // closing delimiter\n const next = find(afterMarker);\n segments.push(text.slice(afterMarker, next === -1 ? undefined : next).replace(/^\\r?\\n/, \"\"));\n if (next === -1) break;\n index = next;\n }\n return segments.map((s) => parsePart(Buffer.from(s, \"latin1\")));\n};\n\n/**\n * Decode one leaf part's body to raw bytes.\n *\n * Shared rather than duplicated: `emlx.ts` needs the same decoding to extract\n * attachment contents, and two copies of a transfer-encoding switch is how the\n * two ends up disagreeing about what a part contains.\n */\nexport const partBytes = (part: MimePart): Buffer => {\n if (part.encoding === \"base64\") return decodeBase64(part.raw.toString(\"latin1\"));\n if (part.encoding === \"quoted-printable\")\n return decodeQuotedPrintable(part.raw.toString(\"latin1\"));\n return part.raw;\n};\n\n/** Decode one leaf part's body into text. */\nexport const partText = (part: MimePart): string => decodeCharset(partBytes(part), part.charset);\n\n/** Very small HTML-to-text pass: enough to read a marketing email, not a renderer. */\nexport const htmlToText = (html: string): string =>\n html\n .replaceAll(/<(script|style)[^>]*>[\\s\\S]*?<\\/\\1>/gi, \"\")\n // The rule above needs a closing tag. The scan lane parses only the first\n // maxBytes of a file, so a style block routinely has none — and the tag\n // stripper then left the CSS behind as prose for a body search to match.\n .replaceAll(/<(script|style)[^>]*>[\\s\\S]*$/gi, \"\")\n .replaceAll(/<br\\s*\\/?>/gi, \"\\n\")\n .replaceAll(/<\\/(p|div|tr|h[1-6]|li)>/gi, \"\\n\")\n .replaceAll(/<li[^>]*>/gi, \"- \")\n .replaceAll(/<[^>]+>/g, \"\")\n // A tag cut off mid-attribute. Anchored on a tag name so that prose using a\n // bare \"<\" as a less-than sign keeps it.\n .replaceAll(/<\\/?[a-zA-Z][^>]*$/g, \"\")\n .replaceAll(\" \", \" \")\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll(\""\", '\"')\n .replaceAll(\"'\", \"'\")\n .replaceAll(/&#(\\d+);/g, (_, d: string) => String.fromCodePoint(Number(d)))\n .replaceAll(/[ \\t]+\\n/g, \"\\n\")\n .replaceAll(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n\nconst walk = (part: MimePart, visit: (p: MimePart) => void): void => {\n visit(part);\n for (const child of part.parts) walk(child, visit);\n};\n\ntype BodyFrom = \"text/plain\" | \"text/html\" | \"none\";\n\n/**\n * Is this part a file rather than something to read?\n *\n * Deliberately shared with `listAttachments`. The two used to disagree — this\n * one excluded only `disposition: attachment`, that one also counted any\n * non-multipart part carrying a filename — and the disagreement was harmless\n * only because a single part was ever chosen as the body. Joining the parts\n * made it visible, as an attached notes.txt landing in the mail it came with.\n */\nconst isAttachmentPart = (p: MimePart): boolean =>\n p.disposition === \"attachment\" ||\n (p.filename !== null && !p.contentType.startsWith(\"multipart/\"));\n\n/**\n * A run of body text, or a note that a file sat between two of them.\n *\n * Markers cannot be resolved to text on the way up: inside a `related` part an\n * image is a trailing marker and would be dropped, while at the root the same\n * image sits between two runs and has to survive. So the tagging lasts until\n * `bestBody` collapses the whole thing, once.\n */\ntype Segment = { kind: \"text\" | \"marker\"; text: string };\ntype Resolved = { segments: Segment[]; from: BodyFrom };\n\nconst NOTHING: Resolved = { segments: [], from: \"none\" };\n\nconst hasText = (r: Resolved): boolean =>\n r.segments.some((s) => s.kind === \"text\" && s.text.trim() !== \"\");\n\n/** `[image: shot.png]` — house style is the truncation marker's: label, colon, fact. */\nconst markerFor = (p: MimePart): Segment => ({\n kind: \"marker\",\n text: `[${p.contentType.startsWith(\"image/\") ? \"image\" : \"attachment\"}: ${\n p.filename ?? p.contentType\n }]`,\n});\n\n/**\n * Resolve one subtree to the runs a person would read, in document order.\n *\n * The container decides. `multipart/alternative` children are competing\n * renderings of one thing, so exactly one is taken; every other multipart holds\n * sequential content, so the children are spliced in order. A flat walk that\n * gathered all the text parts would read the interleaved message correctly and\n * emit a plain+html alternative twice.\n */\nconst resolveBody = (part: MimePart, isFile: (p: MimePart) => boolean): Resolved => {\n if (part.contentType.startsWith(\"multipart/\")) {\n // No children means the boundary never appeared. The whole body is still\n // sitting in `raw`, but it is delimiters and headers, not prose.\n if (part.parts.length === 0) return NOTHING;\n const children = part.parts.map((child) => resolveBody(child, isFile));\n\n if (part.contentType === \"multipart/alternative\") {\n // Only a rendering that actually says something can win. An empty\n // text/plain alternative used to, reporting an empty body with the real\n // content one part away.\n return (\n children.find((c) => c.from === \"text/plain\" && hasText(c)) ??\n children.find((c) => c.from === \"text/html\" && hasText(c)) ??\n NOTHING\n );\n }\n\n // mixed, related, signed, report, anything unknown. `related` is sequential\n // on purpose: Mail emits related{ html, file, html } for a reply carrying\n // one file, so reading it as RFC 2387's root-plus-resources drops half.\n const contributing = children.filter(hasText);\n return {\n segments: children.flatMap((c) => c.segments),\n from: contributing.some((c) => c.from === \"text/html\")\n ? \"text/html\"\n : contributing.some((c) => c.from === \"text/plain\")\n ? \"text/plain\"\n : \"none\",\n };\n }\n\n if (isFile(part)) return { segments: [markerFor(part)], from: \"none\" };\n if (part.contentType === \"text/plain\")\n return { segments: [{ kind: \"text\", text: partText(part).trim() }], from: \"text/plain\" };\n if (part.contentType === \"text/html\")\n return { segments: [{ kind: \"text\", text: htmlToText(partText(part)) }], from: \"text/html\" };\n // Not text and not flagged as a file — a cid image, a forwarded message.\n // Still worth marking: it is a thing the reader saw at this point.\n return { segments: [markerFor(part)], from: \"none\" };\n};\n\n/**\n * The body a person would want to read: every run of it, in order.\n *\n * `from` reports the worst provenance of the runs that contributed, not the\n * first. It is the caller's only warning that the text went through\n * `htmlToText`, and a concatenation that is half derived must not claim to be\n * text/plain just because its first run was.\n */\nexport const bestBody = (root: MimePart): { text: string; from: BodyFrom } => {\n const strict = resolveBody(root, isAttachmentPart);\n // The shared predicate is stricter than the disposition-only test this used\n // to apply, so a message whose ONLY text part carries a filename would go\n // from readable to empty. Losing a whole message to that is worse than the\n // notes.txt it was tightened for, so fall back rather than go silent.\n const resolved = hasText(strict)\n ? strict\n : resolveBody(root, (p) => p.disposition === \"attachment\");\n\n const kept = resolved.segments.filter((s) => s.kind === \"marker\" || s.text.trim() !== \"\");\n // A marker exists to deny an adjacency the message does not have. One at the\n // head or the tail separates nothing, and would append a line to every mail\n // that merely carries a file.\n let first = 0;\n let last = kept.length;\n while (first < last && kept[first]!.kind === \"marker\") first += 1;\n while (last > first && kept[last - 1]!.kind === \"marker\") last -= 1;\n\n const text = kept\n .slice(first, last)\n .map((s) => s.text)\n .join(\"\\n\\n\")\n .trim();\n return { text, from: text === \"\" ? \"none\" : resolved.from };\n};\n\n/**\n * Does a decoded part carry actual content?\n *\n * Stripping an attachment out to the sidecar tree leaves the part's delimiter\n * whitespace behind, so `length > 0` is not the question — \"is any of it not\n * whitespace\" is. A size threshold would work too but would be a magic number,\n * and would misjudge a genuinely tiny attachment.\n */\nconst hasContent = (bytes: Buffer): boolean => {\n for (const byte of bytes) {\n // tab, LF, VT, FF, CR, space\n const isSpace =\n byte === 0x09 ||\n byte === 0x0a ||\n byte === 0x0b ||\n byte === 0x0c ||\n byte === 0x0d ||\n byte === 0x20;\n if (!isSpace) return true;\n }\n return false;\n};\n\nexport const listAttachments = (root: MimePart): Attachment[] => {\n const found: Attachment[] = [];\n walk(root, (p) => {\n if (!isAttachmentPart(p) || p.contentType.startsWith(\"multipart/\")) return;\n // Measure the DECODED payload. `raw` is still transfer-encoded, so a base64\n // part would otherwise report roughly 4/3 of its true size.\n const decoded = partBytes(p);\n\n // Apple strips attachment bodies out into a sidecar tree for .partial.emlx,\n // leaving only delimiter whitespace. Testing `> 0` therefore reported a\n // stripped 250 KB PDF as present with a size of 1 byte — telling callers\n // save_attachment would work when it could not.\n const present = hasContent(decoded);\n\n // Deliberately NOT falling back to X-Apple-Content-Length here: that header\n // records the base64-ENCODED length, so a 164156-byte PDF advertises 224634.\n // The exact size comes from statting the sidecar file, which the emlx layer\n // does because it is the part that knows where the message lives on disk.\n found.push({\n filename: p.filename,\n contentType: p.contentType,\n contentId: p.contentId,\n sizeBytes: present ? decoded.length : null,\n inline: present,\n });\n });\n return found;\n};\n\n/** The headers worth surfacing, decoded. */\nexport const summaryHeaders = (root: MimePart): Record<string, string | null> => {\n const pick = (name: string): string | null => {\n const value = headerValue(root.headers, name);\n return value === null ? null : decodeEncodedWords(value);\n };\n return {\n from: pick(\"from\"),\n to: pick(\"to\"),\n cc: pick(\"cc\"),\n replyTo: pick(\"reply-to\"),\n subject: pick(\"subject\"),\n date: pick(\"date\"),\n messageId: headerValue(root.headers, \"message-id\"),\n };\n};\n","import {\n closeSync,\n existsSync,\n openSync,\n readdirSync,\n readFileSync,\n readSync,\n statSync,\n} from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\n\nimport { PreconditionError } from \"./errors.js\";\nimport {\n bestBody,\n listAttachments,\n parsePart,\n partBytes,\n summaryHeaders,\n type Attachment,\n type MimePart,\n} from \"./mime.js\";\n\n/**\n * Reading Apple's `.emlx` message files.\n *\n * The container is simple:\n *\n * 1255\\n <- byte length of the MIME payload\n * From: ... <- exactly that many bytes of RFC 5322\n * <?xml ...><plist>...</plist> <- Apple's own metadata trailer\n *\n * `.partial.emlx` is the same container with attachment bodies stripped out\n * into a sibling `Attachments/` tree, which is why an attachment can be listed\n * with a name and type but no bytes.\n *\n * The hard part is not the format, it is finding the file. The directory layout\n * is undocumented, so we derive the path, verify it, and fall back to scanning\n * — the derivation is a fast path, not a promise.\n */\n\nexport type ParsedMessage = {\n headers: Record<string, string | null>;\n body: string;\n bodyFrom: \"text/plain\" | \"text/html\" | \"none\";\n /** `retrievable` says whether save_attachment can actually fetch the bytes. */\n attachments: (Attachment & { retrievable: boolean })[];\n truncated: boolean;\n sizeBytes: number;\n path: string;\n partial: boolean;\n};\n\n/** Hard ceiling, independent of the body budget: some mail is enormous. */\nconst MAX_FILE_BYTES = 25 * 1024 * 1024;\n\n/**\n * The undocumented shard rule: take floor(id / 1000), then use its decimal\n * digits in REVERSE order as nested directory names. Message 198577 lands in\n * `Data/8/9/1/Messages/198577.emlx`. Confirmed 5/5 against a live mail store.\n */\nexport const shardPath = (rowid: number): string =>\n String(Math.floor(rowid / 1000))\n .split(\"\")\n .toReversed()\n .join(\"/\");\n\nexport type LocateMessageOptions = {\n accountDirectory: string;\n /** Mailbox name as Mail spells it, e.g. \"INBOX\" or \"All Mail\". */\n mailbox: string;\n rowid: number;\n};\n\n/**\n * Why a lookup failed, so the caller can say something true.\n *\n * `permission` matters because the obvious probe lies: `existsSync` is\n * stat-based and SUCCEEDS on a TCC-protected path, while `readdirSync` and\n * `readFileSync` return EPERM. Without Full Disk Access we therefore get past\n * the directory check and die on the first read — which is a different problem\n * from a path that is simply not there, and needs a different sentence.\n */\nexport type EmlxLookup =\n | { found: true; path: string; partial: boolean }\n | {\n found: false;\n reason: \"no-mailbox-dir\" | \"no-message-file\" | \"permission\";\n /** The `.mbox` directories the mailbox name resolved to. */\n mailboxDirs: string[];\n /** Concrete paths we looked for the message file at. */\n probed: string[];\n };\n\n/**\n * Find a message file. Derive first (a few `existsSync` calls, microseconds),\n * then scan the mailbox's `Messages/` directories, then give up so the caller\n * can fall back to asking Mail directly.\n *\n * The mailbox name is resolved to a directory rather than joined onto the\n * account root, because providers nest: a Gmail account keeps its special\n * mailboxes under `[Gmail].mbox/`, so `All Mail` is not at\n * `<account>/All Mail.mbox` and the flat join found nothing — which took the\n * whole message-file lane out on those accounts without ever saying so.\n */\nexport const lookupEmlx = (opts: LocateMessageOptions): EmlxLookup => {\n const search = new MailboxSearch(opts.rowid);\n\n // Fast path: the mailbox name spells its own directory. A flat `INBOX` costs\n // one stat and no walk at all, exactly as it did before nesting was handled.\n const derived = derivedMailboxDir(opts.accountDirectory, opts.mailbox);\n if (isDirectory(derived)) {\n const hit = search.in(derived);\n if (hit) return hit;\n }\n\n /*\n * Fallback: find the directory by name. A ref carries only a bare leaf, so\n * `All Mail` has to be located inside whatever container holds it, and more\n * than one container may hold that name. Try each; the one holding this rowid\n * is the answer, which settles the ambiguity against the message that\n * actually exists rather than by guessing at the name.\n */\n const mboxDirs = resolveMailboxDirs(opts.accountDirectory, opts.mailbox).filter(\n (d) => d !== derived,\n );\n for (const mboxDir of mboxDirs) {\n const hit = search.in(mboxDir);\n if (hit) return hit;\n }\n\n const searched = [...(isDirectory(derived) ? [derived] : []), ...mboxDirs];\n if (searched.length === 0) {\n // Nothing resolved, but \"not there\" and \"not allowed to look\" are different\n // answers: without Full Disk Access the walk's readdirs all fail silently.\n let reason: \"no-mailbox-dir\" | \"permission\" = \"no-mailbox-dir\";\n try {\n readdirSync(opts.accountDirectory);\n } catch (err) {\n if (isPermissionError(err)) reason = \"permission\";\n }\n return { found: false, reason, mailboxDirs: [], probed: [derived] };\n }\n\n return {\n found: false,\n reason: search.denied ? \"permission\" : \"no-message-file\",\n mailboxDirs: searched,\n probed: search.probed,\n };\n};\n\n/** Looks for one rowid inside a `.mbox` directory, remembering where it looked. */\nclass MailboxSearch {\n readonly probed: string[] = [];\n denied = false;\n readonly #relative: string;\n readonly #names: string[];\n\n constructor(rowid: number) {\n this.#relative = join(\"Data\", shardPath(rowid), \"Messages\");\n this.#names = [`${rowid}.emlx`, `${rowid}.partial.emlx`];\n }\n\n in(mboxDir: string): Extract<EmlxLookup, { found: true }> | null {\n let inner: string[];\n try {\n inner = readdirSync(mboxDir).filter((d) => !d.startsWith(\".\"));\n } catch (err) {\n if (isPermissionError(err)) this.denied = true;\n return null;\n }\n\n // Fast path: the derived shard.\n for (const uuid of inner) {\n for (const name of this.#names) {\n const candidate = join(mboxDir, uuid, this.#relative, name);\n this.probed.push(candidate);\n if (existsSync(candidate)) return foundAt(candidate, name);\n }\n }\n\n // Slow path. Kept even though the derivation hits reliably today, because it\n // is what stops a future layout change from taking the body lane out entirely.\n for (const uuid of inner) {\n const dataRoot = join(mboxDir, uuid, \"Data\");\n for (const dir of findMessagesDirs(dataRoot, 0)) {\n for (const name of this.#names) {\n const candidate = join(dir, name);\n if (existsSync(candidate)) return foundAt(candidate, name);\n }\n }\n }\n return null;\n }\n}\n\nconst foundAt = (path: string, name: string): Extract<EmlxLookup, { found: true }> => ({\n found: true,\n path,\n partial: name.includes(\".partial.\"),\n});\n\n/** The `path | null` shape most callers want. See `lookupEmlx` for the reason. */\nexport const locateEmlx = (\n opts: LocateMessageOptions,\n): { path: string; partial: boolean } | null => {\n const found = lookupEmlx(opts);\n return found.found ? { path: found.path, partial: found.partial } : null;\n};\n\n// ─── mailbox name → on-disk directory ────────────────────────────────────────\n\n/** Depth cap for the `.mbox` walk. Matches `findMessagesDirs`. */\nconst MAX_MBOX_DEPTH = 6;\n\n/** `[Gmail]/All Mail` -> `<account>/[Gmail].mbox/All Mail.mbox`. */\nconst derivedMailboxDir = (accountDirectory: string, mailbox: string): string =>\n join(accountDirectory, ...mailbox.split(\"/\").map((segment) => `${segment}.mbox`));\n\n/**\n * Resolve a mailbox name to every `.mbox` directory that could be it.\n *\n * This is the inverse of the ladder `MailboxMap.resolveMailboxName` and the JXA\n * `resolveMailbox` walk (exact, `[Gmail]/`-stripped, final segment, then\n * case-insensitive): those take a path and find a mailbox Mail knows about,\n * this takes the bare leaf name that survives into a ref and finds the nested\n * container holding it.\n *\n * Deliberately generic rather than special-casing `[Gmail]`: Exchange and other\n * providers nest too, and a Gmail label `Work/Projects` lands two levels deep as\n * `Work.mbox/Projects.mbox`.\n */\nexport const resolveMailboxDirs = (accountDirectory: string, mailbox: string): string[] => {\n // The name may spell its own path: a flat `INBOX.mbox`, or an explicit\n // `[Gmail]/All Mail`. That goes first, but it does not end the search — a flat\n // `Archive.mbox` existing does not prove this message is in it rather than in\n // a nested one of the same name, and the caller settles that by rowid.\n const derived = derivedMailboxDir(accountDirectory, mailbox);\n const first = isDirectory(derived) ? [derived] : [];\n\n const candidates = mailboxNameCandidates(mailbox);\n const exact: string[] = [];\n const insensitive: string[] = [];\n const lowered = candidates.map((c) => c.toLowerCase());\n\n // Breadth-first so shallower matches are offered before deeper ones. Only\n // `.mbox` entries are ever opened, so the walk never descends into `Data/` —\n // that is what keeps this to tens of small readdirs instead of a scan over\n // every message shard in the account.\n let frontier = [accountDirectory];\n for (let depth = 0; depth < MAX_MBOX_DEPTH && frontier.length > 0; depth += 1) {\n const next: string[] = [];\n for (const dir of frontier) {\n for (const entry of safeReaddir(dir)) {\n if (!entry.endsWith(\".mbox\") || entry.startsWith(\".\")) continue;\n const full = join(dir, entry);\n if (!isDirectory(full)) continue;\n const name = basename(entry, \".mbox\");\n if (candidates.includes(name)) exact.push(full);\n else if (lowered.includes(name.toLowerCase())) insensitive.push(full);\n // Recurse regardless: a mailbox can be both a match and a container.\n next.push(full);\n }\n }\n frontier = next;\n }\n\n return [...new Set([...first, ...exact, ...insensitive])];\n};\n\n/** Exact, `[Gmail]/`-stripped, then final segment — the shared ladder's names. */\nconst mailboxNameCandidates = (mailbox: string): string[] => {\n const candidates = [mailbox];\n if (mailbox.startsWith(\"[Gmail]/\")) candidates.push(mailbox.slice(8));\n if (mailbox.includes(\"/\")) {\n const last = mailbox.split(\"/\").pop();\n if (last) candidates.push(last);\n }\n return candidates;\n};\n\nconst isDirectory = (path: string): boolean => {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst isPermissionError = (err: unknown): boolean => {\n const code = (err as { code?: string } | null)?.code;\n return code === \"EPERM\" || code === \"EACCES\";\n};\n\n/** Depth-limited walk for `Messages/` directories under a Data root. */\nconst findMessagesDirs = (root: string, depth: number): string[] => {\n if (depth > 6) return [];\n let entries: string[];\n try {\n entries = readdirSync(root);\n } catch {\n return [];\n }\n const found: string[] = [];\n for (const entry of entries) {\n const full = join(root, entry);\n let isDir = false;\n try {\n isDir = statSync(full).isDirectory();\n } catch {\n continue;\n }\n if (!isDir) continue;\n if (entry === \"Messages\") found.push(full);\n else found.push(...findMessagesDirs(full, depth + 1));\n }\n return found;\n};\n\n/** Split the container into its MIME payload, using the length prefix. */\nexport const splitEmlx = (buf: Buffer): Buffer => {\n const newline = buf.indexOf(0x0a);\n if (newline === -1) return buf;\n const declared = Number.parseInt(buf.subarray(0, newline).toString(\"ascii\").trim(), 10);\n const start = newline + 1;\n if (!Number.isFinite(declared) || declared <= 0) return buf.subarray(start);\n // Trust the prefix, but never read past the end of the file.\n return buf.subarray(start, Math.min(start + declared, buf.length));\n};\n\nexport const readEmlx = (\n path: string,\n opts: { maxBodyBytes: number; partial?: boolean; rowid?: number },\n): ParsedMessage => {\n const stat = statSync(path);\n if (stat.size > MAX_FILE_BYTES) {\n throw new PreconditionError(\n `Message file is ${stat.size} bytes, above the ${MAX_FILE_BYTES}-byte ceiling. ` +\n `Use apple_mail_list_attachments to see what is in it.`,\n { path, sizeBytes: stat.size },\n );\n }\n\n const mime = splitEmlx(readFileSync(path));\n const root: MimePart = parsePart(mime);\n const picked = bestBody(root);\n\n const encoded = Buffer.from(picked.text, \"utf8\");\n const truncated = encoded.length > opts.maxBodyBytes;\n const body = truncated\n ? `${encoded.subarray(0, opts.maxBodyBytes).toString(\"utf8\")}\\n\\n[truncated: ${encoded.length} bytes total]`\n : picked.text;\n\n /*\n * Reconcile the parsed attachment list against the disk.\n *\n * Mail almost always moves attachment bodies out to a sidecar tree — on a\n * real store, none of the sampled attachments were inline — so the parse\n * alone cannot say how big an attachment is or whether it can be fetched.\n * `X-Apple-Content-Length` is not the answer either: it records the\n * BASE64-ENCODED length, so a 164156-byte PDF advertises 224634.\n *\n * Statting the sidecar gives the exact size and, more importantly, tells the\n * caller whether apple_mail_save_attachment will actually succeed.\n */\n const attachments = listAttachments(root).map((a) => {\n if (a.inline || !a.filename) return { ...a, retrievable: a.inline };\n const sidecar = locateSidecar(path, opts.rowid ?? -1, a.filename);\n if (!sidecar) return { ...a, sizeBytes: null, retrievable: false };\n try {\n return { ...a, sizeBytes: statSync(sidecar).size, retrievable: true };\n } catch {\n return { ...a, sizeBytes: null, retrievable: false };\n }\n });\n\n return {\n headers: summaryHeaders(root),\n body,\n bodyFrom: picked.from,\n attachments,\n truncated,\n sizeBytes: stat.size,\n path,\n partial: opts.partial ?? path.includes(\".partial.\"),\n };\n};\n\n/**\n * Body text only, for the scan lane — no attachment reconciliation.\n *\n * `readEmlx` stats every attachment's sidecar to answer `retrievable`, which is\n * exactly right when a caller asked for one message and exactly wrong when the\n * caller is walking two thousand of them looking for a word. Scanning pays the\n * MIME parse, which is what finds the text, and nothing else.\n *\n * Reading is capped at `maxBytes` from the front of the file rather than the\n * whole thing. Measured on a real store the mean message is 52 KB and 79% of\n * those bytes are base64 that no text search would ever match; the text parts\n * of a MIME message sit ahead of its attachments, so the cap trades a tail no\n * scan wants for a per-file cost the scan pays on every candidate.\n *\n * Returns null rather than throwing. A scan over thousands of files will meet\n * an unreadable one, and one bad file must not take out the query — the caller\n * counts these and reports them instead.\n */\nexport const readEmlxBodyText = (path: string, opts: { maxBytes: number }): string | null => {\n try {\n const stat = statSync(path);\n if (stat.size > MAX_FILE_BYTES) return null;\n const fd = openSync(path, \"r\");\n try {\n const want = Math.min(stat.size, opts.maxBytes);\n const buf = Buffer.alloc(want);\n readSync(fd, buf, 0, want, 0);\n const mime = splitEmlx(buf);\n const picked = bestBody(parsePart(mime));\n return picked.text;\n } finally {\n closeSync(fd);\n }\n } catch {\n return null;\n }\n};\n\n/** Raw RFC 5322 source, for header forensics. Capped and offsettable. */\nexport const readEmlxSource = (\n path: string,\n opts: { offset: number; maxBytes: number },\n): { source: string; totalBytes: number; truncated: boolean } => {\n const mime = splitEmlx(readFileSync(path));\n const slice = mime.subarray(opts.offset, opts.offset + opts.maxBytes);\n return {\n source: slice.toString(\"utf8\"),\n totalBytes: mime.length,\n truncated: opts.offset + slice.length < mime.length,\n };\n};\n\n// ─── attachment extraction ───────────────────────────────────────────────────\n\nconst walkParts = (part: MimePart, visit: (p: MimePart) => void): void => {\n visit(part);\n for (const child of part.parts) walkParts(child, visit);\n};\n\n/**\n * Pull one attachment's bytes out of a message.\n *\n * For a normal `.emlx` the bytes are in the MIME part. For a `.partial.emlx`\n * Apple has moved them into a sibling `Attachments/<rowid>/<part>/<filename>`\n * tree, so we go looking there instead — which is why an attachment can be\n * listed with a name and type but report a size of zero.\n */\nexport const extractAttachment = (\n emlxPath: string,\n filename: string,\n rowid: number,\n): { bytes: Buffer; from: \"inline\" | \"sidecar\" } => {\n const root = parsePart(splitEmlx(readFileSync(emlxPath)));\n\n let match: MimePart | null = null;\n walkParts(root, (p) => {\n if (!match && p.filename === filename) match = p;\n });\n if (!match) {\n throw new PreconditionError(\n `No attachment named \"${filename}\" in this message. Use apple_mail_list_attachments to see what is there.`,\n );\n }\n\n const inline = partBytes(match);\n if (inline.length > 0) return { bytes: inline, from: \"inline\" };\n\n // The stripped case — which is the NORMAL one, not an edge case: on a real\n // mail store none of the sampled attachments were inline. Mail moves the\n // bytes to an `Attachments/<rowid>/<part>/<filename>` tree.\n //\n // We search for that tree rather than deriving its path. The message lives at\n // a variable depth (the shard is the digits of rowid/1000, so 5607 nests one\n // level and 198577 nests three), which is precisely what a fixed number of\n // `..` hops got wrong.\n const hit = locateSidecar(emlxPath, rowid, filename);\n if (hit) return { bytes: readFileSync(hit), from: \"sidecar\" };\n\n throw new PreconditionError(\n `The attachment \"${filename}\" is not stored locally. Either it was never downloaded, or ` +\n `this account caches headers only — apple_mail_diagnostics reports the caching policy ` +\n `per account. Opening the message in Mail fetches it.`,\n { emlxPath, rowid },\n );\n};\n\n/**\n * Find an attachment's sidecar file.\n *\n * We search for the `Attachments/<rowid>/` tree rather than deriving its path.\n * The message sits at a variable depth — the shard is the digits of rowid/1000,\n * so 5607 nests one level and 198577 nests three — which is exactly what a\n * fixed number of `..` hops got wrong.\n */\nexport const locateSidecar = (emlxPath: string, rowid: number, filename: string): string | null => {\n let dir = dirname(emlxPath);\n for (let depth = 0; depth < 12; depth += 1) {\n const root = join(dir, \"Attachments\", String(rowid));\n if (existsSync(root)) {\n const found = findNamedFile(root, filename, 0);\n if (found) return found;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n};\n\n/** Find a file by name anywhere under `root`. Depth-limited; the tree is shallow. */\nconst findNamedFile = (root: string, filename: string, depth: number): string | null => {\n if (depth > 4) return null;\n for (const entry of safeReaddir(root)) {\n const full = join(root, entry);\n if (entry === filename) return full;\n try {\n if (statSync(full).isDirectory()) {\n const hit = findNamedFile(full, filename, depth + 1);\n if (hit) return hit;\n }\n } catch {\n // Raced with Mail, or unreadable. Keep looking.\n }\n }\n return null;\n};\n\nconst safeReaddir = (dir: string): string[] => {\n try {\n return readdirSync(dir);\n } catch {\n return [];\n }\n};\n","import { readEmlxBodyText } from \"./emlx.js\";\n\n/**\n * Body search, without an index.\n *\n * There is no index to use. The Envelope Index carries no FTS table, and the\n * Spotlight volume index does not reach `~/Library` at all — the whole tree is\n * excluded, so `mdfind` returns nothing there however the query is phrased.\n * Mail's own body search runs on CoreSpotlight donations, which are queried\n * through `CSSearchQuery` by the app that donated them and are not reachable\n * from here. docs/mail-body.md has the measurements.\n *\n * What is left is the shape this file implements: let the Envelope Index narrow\n * the query — mailbox, account, sender, date range, flags, all of which it\n * answers in milliseconds — then read the bodies of the survivors and match\n * them in memory.\n *\n * THE COST IS LINEAR IN SURVIVORS, AND THAT IS THE WHOLE DESIGN. Measured at\n * 0.48 ms per message warm on a 181,734-message store:\n *\n * 100 candidates 48 ms a tight filter\n * 500 candidates 242 ms\n * 1,932 candidates 933 ms 90 days of the busiest mailbox\n * 6,566 candidates 3.2 s 90 days, every mailbox\n * 182,329 candidates 88 s no filter at all — unusable\n *\n * So a bound is not optional. The one thing this must never do is scan a\n * truncated prefix and return what it found: answering \"not found\" from a\n * partial scan is indistinguishable from a real absence, and the model has no\n * way to tell. Over the bound this refuses and says so, with the numbers, so\n * the caller can narrow the filter or raise the ceiling deliberately.\n */\n\nexport type BodyScanOutcome =\n | {\n status: \"ok\";\n /** Rowids whose body matched, in the order the index returned them. */\n matched: number[];\n candidates: number;\n scanned: number;\n /** Candidates whose file could not be read — no grant, or no message file. */\n unreadable: number;\n elapsedMs: number;\n }\n | {\n status: \"over-bound\";\n candidates: number;\n bound: number;\n };\n\nexport type BodyScanOptions = {\n /** Candidate rowids, already narrowed by the index. */\n candidates: number[];\n term: string;\n bound: number;\n maxBytes: number;\n /** Resolve a rowid to a message file. Returns null when there is no file. */\n locate: (rowid: number) => string | null;\n};\n\n/**\n * Case-insensitive substring, matching what `search_messages` already does for\n * subject and sender via SQL `LIKE`. Not tokenised, not stemmed: a body search\n * that quietly stemmed while the subject search did not would make one tool\n * behave two ways depending on which field matched.\n */\nconst matches = (haystack: string, needle: string): boolean =>\n haystack.toLowerCase().includes(needle);\n\nexport const scanBodies = (opts: BodyScanOptions): BodyScanOutcome => {\n if (opts.candidates.length > opts.bound) {\n return { status: \"over-bound\", candidates: opts.candidates.length, bound: opts.bound };\n }\n\n const started = performance.now();\n const needle = opts.term.toLowerCase();\n const matched: number[] = [];\n let unreadable = 0;\n let scanned = 0;\n\n for (const rowid of opts.candidates) {\n const path = opts.locate(rowid);\n if (!path) {\n unreadable += 1;\n continue;\n }\n const text = readEmlxBodyText(path, { maxBytes: opts.maxBytes });\n if (text === null) {\n unreadable += 1;\n continue;\n }\n scanned += 1;\n if (matches(text, needle)) matched.push(rowid);\n }\n\n return {\n status: \"ok\",\n matched,\n candidates: opts.candidates.length,\n scanned,\n unreadable,\n elapsedMs: Math.round(performance.now() - started),\n };\n};\n","/**\n * JXA script fragments.\n *\n * Every script here is a static constant. None of them may contain a template\n * interpolation — `osascript.assertStaticScript` rejects any script containing\n * `${`, and that includes JavaScript template literals written *inside* the JXA\n * source. Use string concatenation in JXA code.\n *\n * Every script follows the same contract:\n * - it reads its parameters from `JSON.parse(argv[0])`\n * - it returns `JSON.stringify({ok: true, data})` on success\n * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an\n * application-level failure, still exiting 0\n * so that a non-zero exit always means infrastructure rather than \"no such mailbox\".\n */\n\n/**\n * Shared prelude.\n *\n * The liveness gate matters more than it looks. `Application(\"Mail\").accounts`\n * *launches* Mail if it isn't running — which steals focus and kicks off a sync\n * as a side effect of a read. `NSRunningApplication` answers the same question\n * without launching anything and without a second TCC prompt, so read tools can\n * fail cleanly instead of taking over the user's screen.\n */\nexport const PRELUDE = `\nObjC.import(\"AppKit\");\n// For AXIsProcessTrusted, read by composerReach. AppKit does not\n// reliably pull it in, and an unbridged symbol would throw rather than\n// answer.\nObjC.import(\"ApplicationServices\");\n\nfunction isMailRunning() {\n var apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(\"com.apple.mail\");\n return apps.count > 0;\n}\n\nfunction ok(data) { return JSON.stringify({ ok: true, data: data }); }\nfunction err(code, message) { return JSON.stringify({ ok: false, error: { code: code, message: String(message) } }); }\n\nfunction iso(d) {\n try { return d ? d.toISOString() : null; } catch (e) { return null; }\n}\n\n/** Read one property defensively: Mail throws on properties it cannot supply. */\nfunction prop(fn, fallback) {\n try {\n var v = fn();\n return v === undefined ? fallback : v;\n } catch (e) {\n return fallback;\n }\n}\n\n/** Resolve a mailbox by the ladder: exact path, [Gmail]-stripped, final segment, case-insensitive. */\nfunction resolveMailbox(acct, wanted) {\n var boxes = acct.mailboxes();\n var names = boxes.map(function (b) { return b.name(); });\n\n var candidates = [wanted];\n if (wanted.indexOf(\"[Gmail]/\") === 0) candidates.push(wanted.slice(8));\n if (wanted.indexOf(\"/\") !== -1) candidates.push(wanted.split(\"/\").pop());\n\n for (var c = 0; c < candidates.length; c++) {\n var idx = names.indexOf(candidates[c]);\n if (idx !== -1) return boxes[idx];\n }\n for (var c2 = 0; c2 < candidates.length; c2++) {\n var lower = String(candidates[c2]).toLowerCase();\n for (var i = 0; i < names.length; i++) {\n if (String(names[i]).toLowerCase() === lower) return boxes[i];\n }\n }\n return null;\n}\n\nfunction findAccount(M, uuid) {\n var accts = M.accounts();\n for (var i = 0; i < accts.length; i++) {\n if (accts[i].id() === uuid) return accts[i];\n }\n return null;\n}\n\nfunction pause(seconds) { $.NSThread.sleepForTimeInterval(seconds); }\n\n/**\n * Does the haystack contain the needle, ignoring how Mail rewrote whitespace?\n *\n * Used to verify a body we just wrote into a composer. A literal comparison\n * fails on text that was stored correctly: Mail hands back CR or CRLF line\n * endings, re-wraps runs of spaces and drops trailing ones, so an indented,\n * blank-line-separated body never reads back byte-identical. Collapsing every\n * whitespace run on both sides compares what a reader would see, which is the\n * question being asked -- the alternative is a false \"the body was dropped\" on\n * a draft that is in fact fine.\n */\nfunction containsText(haystack, needle) {\n var squash = function (s) { return String(s).replace(/\\\\s+/g, \" \").trim(); };\n var n = squash(needle);\n if (!n) return true;\n return squash(haystack).indexOf(n) !== -1;\n}\n\n/**\n * Read the start of a composer's body, out of the window.\n *\n * Mail's scripting interface reports content as \"\" for every reply and forward\n * composer, and silently discards writes to it — measured on macOS 26, with and\n * without opening window, immediately and six seconds later. So the window is\n * the only place a composed body can be read, and the accessible text under its\n * web area is what a person would see on screen.\n *\n * Bounded on purpose. Every node costs an Apple Event, and a composer holding a\n * quoted newsletter runs to 160 of them — around eight seconds to walk in full,\n * twice over, on a tool whose whole budget is thirty. Reading stops once budget\n * characters are in hand, which is enough to answer the only question being\n * asked: is the text we just pasted at the top of this window. Values are read a\n * parent at a time, one event per level rather than one per node.\n *\n * Returns null when the body cannot be reached at all — a different answer from\n * \"\", and the two have to stay apart: one means we are blind, the other means\n * the composer is empty.\n */\nfunction composerBodyText(body, budget) {\n if (!body) return null;\n var acc = { lines: [], chars: 0 };\n collectText(body, 0, acc, budget);\n return acc.lines.join(\"\\\\n\");\n}\n\nfunction collectText(el, depth, acc, budget) {\n if (depth > 6 || acc.chars >= budget) return;\n var kids = prop(function () { return el.uiElements(); }, []);\n if (!kids.length) return;\n // One event for the whole level. Falls back to one per child if this composer\n // has a level whose values will not marshal as a list.\n var values = prop(function () { return el.uiElements.value(); }, null);\n for (var i = 0; i < kids.length && acc.chars < budget; i++) {\n var kid = kids[i];\n var value = values ? values[i] : prop(function () { return kid.value(); }, null);\n if (value && typeof value === \"string\" && value.trim()) {\n acc.lines.push(value);\n acc.chars += value.length + 1;\n } else {\n collectText(kid, depth + 1, acc, budget);\n }\n }\n}\n\n/**\n * How many elements the composer's body holds, in one Apple Event.\n *\n * A fingerprint, not a reading. Taken before and after a paste it answers \"did\n * anything at all land\", which is what decides whether pasting again is safe:\n * a paste that landed and cannot be read must NOT be repeated, or the reply\n * ends up in the draft twice with no way to undo it from here.\n */\nfunction composerBodySize(body) {\n return prop(function () { return body.entireContents().length; }, null);\n}\n\n/**\n * Did anything at all reach the composer, comparing two fingerprints?\n *\n * Three answers, and the third is the one that was missing. \"unknown\" is a body\n * that cannot be READ -- which is what a composer that has CLOSED looks like\n * from the outside, because its reference dies with the window.\n *\n * This returned -1 for an unreadable body and the caller compared it as a\n * length. Two consequences, both wrong and in opposite directions: -1 against a\n * real count read as \"something landed\", so a reply sent by hand mid-call was\n * reported as a body that never went in; and -1 against -1 read as \"nothing\n * landed\", which is the branch that DISCARDS the composer -- destroying a body\n * that may well have been in it.\n */\nfunction landedVerdict(before, after) {\n if (before === null || after === null) return \"unknown\";\n return after === before ? \"no\" : \"yes\";\n}\n\n/**\n * Can this process actually read Mail's UI, right now?\n *\n * Asked BEFORE a composer is opened, because the alternative is what shipped:\n * M.reply opens a window, the accessibility read fails, and the user is left\n * with an empty reply window on screen and an error telling them to close it by\n * hand. Every retry left another one. Nothing about that failure needed the\n * window to exist first -- the grants it depends on can be read in one event.\n *\n * Ground truth here is the functional read, not AXIsProcessTrusted. The two do\n * disagree. MEASURED, macOS 26.6: Cupertino.app's own process reported trusted\n * while an osascript grandchild of it reported the opposite and could not name\n * a single Mail window -- a green Accessibility row in System Settings beside a\n * reply that failed every time.\n *\n * The cause was not attribution, which was correct throughout (launchctl put\n * the responsible pid of the node server at the app). It was that ONE BUNDLE\n * IDENTIFIER CAN HOLD SEVERAL ACCESSIBILITY ENTRIES AT ONCE, one per path and\n * signature it has been granted at -- an installed copy, a debug build, each\n * earlier reinstall. tccutil reported resetting four of them for\n * io.mgcrea.cupertino. The app's own check matched one and the requests made on\n * its behalf were resolved against another.\n *\n * So the flag is a claim about an identity that may be ambiguous, and this is\n * the thing itself. A window list that comes back named is proof regardless of\n * what the flag says; the flag only breaks the tie when Mail has no windows.\n *\n * Returns { ok, reason, windows }. The reason separates the two grants that fail\n * identically once inside a composer: \"systemEvents\" when System Events cannot\n * be addressed at all, \"accessibility\" when it can but its UI is unreadable.\n */\nfunction composerReach(SE) {\n try {\n SE.processes.name();\n } catch (e) {\n return { ok: false, reason: \"systemEvents\", windows: null };\n }\n\n var names;\n try {\n var proc = SE.processes.byName(\"Mail\");\n names = proc.windows().map(function (w) {\n try { return w.name(); } catch (e2) { return null; }\n });\n } catch (e) {\n return { ok: false, reason: \"accessibility\", windows: null };\n }\n\n if (names.length) return { ok: true, reason: null, windows: names };\n\n // Mail with no windows at all is legitimate -- everything closed down to the\n // menu bar -- so an empty list is not evidence of anything on its own, and\n // refusing on it would break a reply that would have worked.\n var trusted = false;\n try { trusted = $.AXIsProcessTrusted(); } catch (e) { trusted = false; }\n return trusted\n ? { ok: true, reason: null, windows: names }\n : { ok: false, reason: \"accessibility\", windows: names };\n}\n\n/**\n * The sentence to say when a composer cannot be reached.\n *\n * Shared by the pre-flight and by the post-open failure so the two cannot drift\n * apart, and because the advice is identical: the reason a window is unreadable\n * is never anything the caller did.\n */\nfunction composerGrantMessage(mode, reach) {\n var head =\n reach.reason === \"systemEvents\"\n ? \"Cupertino cannot address System Events at all, which is the only route into a Mail \" +\n \"composer, so the \" + mode + \" was not started and nothing was written.\"\n : \"Cupertino cannot read Mail's windows, which is the only route into a \" + mode + \" \" +\n \"composer, so it was not started and nothing was written.\";\n return (\n head +\n \" Reaching a composer needs BOTH Accessibility and Automation to System Events -- the latter \" +\n \"a different grant from Automation to Mail, which is why every other tool still works. Both \" +\n \"belong to /Applications/Cupertino.app, NOT to your terminal and NOT to node: the app is the \" +\n \"process macOS holds responsible and every server inherits its identity. Accessibility is in \" +\n \"System Settings > Privacy & Security > Accessibility; Automation is under Automation. If the \" +\n \"app is already listed, toggle it off and on -- the grant goes stale when the bundle is \" +\n \"reinstalled. Then QUIT CUPERTINO AND OPEN IT AGAIN: the servers are children of the running \" +\n \"app, and a child started before the grant does not see it. Run apple_mail_diagnostics to \" +\n \"check, which reports the two grants separately and names the windows it can see.\"\n );\n}\n\n/**\n * Close a composer this script opened, when nothing of the user's is in it.\n *\n * Only ever called on a window put on screen moments earlier and provably not\n * written to. Without it every failed attempt leaves an empty reply window\n * behind, and the errors below had to end by asking the user to clean up after\n * the tool -- for a window that only exists because the tool opened it.\n *\n * It goes through Mail's own scripting interface, which is working in every\n * state that reaches here: what fails on this path is reading the window, not\n * owning it.\n */\nfunction discardComposer(M, draft) {\n try {\n M.close(draft, { saving: \"no\" });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Find the composer Mail just opened, by the subject Mail gave it.\n *\n * Counting windows before and after does not work: Mail closes and reuses\n * windows around a compose, so the count comes back unchanged with a new\n * composer on screen — measured. The subject is the identity that holds, and\n * requiring a body area with it rejects the main window and the drafts list.\n */\nfunction composerWindow(proc, subject, timeoutMs) {\n var waited = 0;\n while (true) {\n var wins = prop(function () { return proc.windows(); }, []);\n for (var i = 0; i < wins.length; i++) {\n var win = wins[i];\n if (prop(function () { return win.name(); }, \"\") !== subject) continue;\n if (findBodyArea(win, 0)) return win;\n }\n if (waited >= timeoutMs) return null;\n pause(0.2);\n waited += 200;\n }\n}\n\n/**\n * Put text into a composer body, via the pasteboard.\n *\n * No route through the scripting interface works on a reply or a forward:\n * assigning content is dropped, and so is setting AXValue on the web area,\n * which reports itself settable first and then does nothing. Typing the text\n * keystroke by keystroke does land, but a 4 KB body takes minutes and mangles\n * accented characters. A paste is one event, exact, and encoding-safe.\n *\n * The caller must have made Mail frontmost already: a keystroke goes to the\n * active application, and raising a window inside Mail is not that.\n *\n * COST, stated because it is real: this borrows the user's clipboard. The\n * string on it is put back afterwards, but a clipboard holding an image or a\n * file promise comes back as text, because AppKit offers no way to carry an\n * arbitrary item across without knowing its type.\n */\nfunction pasteIntoComposer(win, body, text) {\n if (!body) return false;\n var SE = Application(\"System Events\");\n\n var pb = $.NSPasteboard.generalPasteboard;\n var saved = null;\n try {\n var existing = pb.stringForType($.NSPasteboardTypeString);\n saved = existing.isNil() ? null : ObjC.unwrap(existing);\n } catch (e) {\n saved = null;\n }\n\n var pasted = false;\n try {\n pb.clearContents;\n pb.setStringForType($(text), $.NSPasteboardTypeString);\n try { win.actions.byName(\"AXRaise\").perform(); } catch (e) {}\n body.focused = true;\n pause(0.3);\n SE.keystroke(\"v\", { using: [\"command down\"] });\n pause(0.8);\n pasted = true;\n } catch (e) {\n pasted = false;\n }\n\n if (saved !== null) {\n try {\n pb.clearContents;\n pb.setStringForType($(saved), $.NSPasteboardTypeString);\n } catch (e) {}\n }\n return pasted;\n}\n\n/** Depth-first hunt for the composer's body, which is a web area, not a text field. */\nfunction findBodyArea(el, depth) {\n if (depth > 6) return null;\n var kids;\n try { kids = el.uiElements(); } catch (e) { return null; }\n for (var i = 0; i < kids.length; i++) {\n try { if (kids[i].role() === \"AXWebArea\") return kids[i]; } catch (e) {}\n var found = findBodyArea(kids[i], depth + 1);\n if (found) return found;\n }\n return null;\n}\n\n/** Deepest quote level reported anywhere in the body; 0 once the citation is gone. */\nfunction maxQuoteLevel(el, depth) {\n var worst = 0;\n if (depth > 5) return worst;\n var kids;\n try { kids = el.uiElements(); } catch (e) { return worst; }\n for (var i = 0; i < kids.length; i++) {\n var level = prop(function () { return kids[i].attributes.byName(\"AXBlockQuoteLevel\").value(); }, 0);\n if (level && level > worst) worst = level;\n var deeper = maxQuoteLevel(kids[i], depth + 1);\n if (deeper > worst) worst = deeper;\n }\n return worst;\n}\n\n/**\n * Undo Mail's citation wrapper on a composer window.\n *\n * Mail wraps *any* body set by AppleScript in <blockquote type=\"cite\">, so the\n * message arrives looking like a quoted reply and its text/plain alternative\n * carries \"> \" on every line. This is FB11734014, filed in 2023 and still open.\n * No scriptable property avoids it: the content setter goes through Mail's\n * NSSharingService composer, and constructor-vs-assignment, visible true/false,\n * htmlContent, plain message format and a relaunch all produce the same markup.\n *\n * The composer's own Format > Quote Level > Decrease does remove it, so we drive\n * that menu. AppKit only gives the *active* application a key window, and the\n * menu item validates to disabled without one, so Mail genuinely has to come\n * forward — driving it in the background was measured, not assumed. What we can\n * do is make that as close to invisible as the window server allows: shrink the\n * composer to its minimum and push it off-screen first (macOS clamps it back to\n * leave a 40px sliver — that residue is not removable from outside Mail's\n * process, as the window server ignores alpha changes from a foreign\n * connection), then put the window back exactly where it was found before the\n * user's app is handed back.\n *\n * Restoring is NOT cosmetic. Mail persists the compose window's frame, so a\n * composer left at [1, 1] off-screen is inherited by the next one the user\n * opens by hand -- and on a send that only saves a draft, the window this\n * shrank is the very window the caller is told is \"open in Mail for review\".\n * So a window whose geometry cannot be read back is not moved at all: the flash\n * of a composer coming forward is worth less than a window stuck at [1, 1].\n *\n * Failure is reported, never fatal: a quoted send still beats a lost one.\n */\nfunction stripCitation(windowName) {\n var SE = Application(\"System Events\");\n var proc = SE.processes.byName(\"Mail\");\n\n var wins = prop(function () { return proc.windows(); }, []);\n if (!wins.length) return false;\n\n var win = null;\n for (var i = 0; i < wins.length; i++) {\n if (prop(function () { return wins[i].name(); }, \"\") === windowName) { win = wins[i]; break; }\n }\n // An empty subject names the window something else; the composer is frontmost regardless.\n if (!win) win = wins[0];\n\n // Read the real geometry BEFORE moving: once the window is off-screen the\n // window server answers with what it clamped to, not what the user chose.\n var was = null;\n try { was = { size: win.size(), position: win.position() }; } catch (e) { was = null; }\n var unhide = function () {\n if (!was) return;\n // Position first, so the window grows back from the right top-left corner.\n try { win.position = was.position; } catch (e) {}\n try { win.size = was.size; } catch (e) {}\n };\n\n // Out of sight before Mail comes forward, so the user sees as little as\n // possible -- and only when the geometry came back, because hiding a window\n // we have no way to put back is how it stays hidden.\n if (was) {\n try { win.size = [1, 1]; } catch (e) {}\n try { win.position = [-100000, -100000]; } catch (e) {}\n }\n\n var previous = prop(function () {\n return SE.applicationProcesses.whose({ frontmost: true })[0].name();\n }, null);\n\n var stripped = false;\n try {\n proc.frontmost = true;\n pause(0.6);\n\n var body = findBodyArea(win, 0);\n if (body) {\n body.focused = true;\n pause(0.3);\n SE.keystroke(\"a\", { using: [\"command down\"] });\n pause(0.3);\n\n var decrease = proc.menuBars[0].menuBarItems.byName(\"Format\").menus[0]\n .menuItems.byName(\"Quote Level\").menus[0].menuItems.byName(\"Decrease\");\n var clicks = 0;\n while (clicks < 3 && prop(function () { return decrease.enabled(); }, false)) {\n decrease.click();\n clicks++;\n pause(0.25);\n }\n // Ask the composer itself rather than trusting the click count.\n stripped = maxQuoteLevel(body, 0) === 0;\n }\n } catch (e) {\n stripped = false;\n }\n\n // Before the caller sends, saves, or leaves this window on screen, and on the\n // failure path too: a strip that threw must not cost the user their composer.\n unhide();\n\n if (previous && previous !== \"Mail\") {\n try { SE.processes.byName(previous).frontmost = true; } catch (e) {}\n }\n return stripped;\n}\n\n/** Shape one message into the wire format every tool consumes. */\nfunction messageSummary(m, accountUuid, mailboxName) {\n return {\n id: prop(function () { return m.id(); }, null),\n accountUuid: accountUuid,\n mailbox: mailboxName,\n subject: prop(function () { return m.subject(); }, null),\n sender: prop(function () { return m.sender(); }, null),\n dateReceived: iso(prop(function () { return m.dateReceived(); }, null)),\n dateSent: iso(prop(function () { return m.dateSent(); }, null)),\n messageId: prop(function () { return m.messageId(); }, null),\n read: prop(function () { return m.readStatus(); }, null),\n flagged: prop(function () { return m.flaggedStatus(); }, null),\n junk: prop(function () { return m.junkMailStatus(); }, null),\n size: prop(function () { return m.messageSize(); }, null),\n wasRepliedTo: prop(function () { return m.wasRepliedTo(); }, null),\n wasForwarded: prop(function () { return m.wasForwarded(); }, null)\n };\n}\n`;\n\n/**\n * Wrap a script body in the prelude and the liveness gate.\n *\n * `allowLaunch` is opt-in per script, and only the tools whose whole purpose is\n * to make Mail do something (send, reply, forward, check for new mail) set it.\n * A read that silently launches Mail is a read with a side effect.\n */\nexport const script = (body: string, opts: { allowLaunch?: boolean } = {}): string => `\n${PRELUDE}\nfunction run(argv) {\n var p = JSON.parse(argv[0] || \"{}\");\n if (!isMailRunning() && !${opts.allowLaunch ? \"true\" : \"false\"}) {\n return err(\"MAIL_NOT_RUNNING\", \"Mail is not running.\");\n }\n try {\n var M = Application(\"Mail\");\n ${body}\n } catch (e) {\n var msg = String(e && e.message ? e.message : e);\n if (msg.indexOf(\"-1743\") !== -1) return err(\"NOT_AUTHORIZED\", msg);\n return err(\"SCRIPT_ERROR\", msg);\n }\n}\n`;\n","import { script } from \"./core.js\";\n\n/** Accounts, their UUIDs, on-disk directories and mailbox names. ~0.6s for 4 accounts. */\nexport const LIST_ACCOUNTS = script(`\n var accts = M.accounts();\n var out = [];\n for (var i = 0; i < accts.length; i++) {\n var a = accts[i];\n out.push({\n id: prop(function () { return a.id(); }, null),\n name: prop(function () { return a.name(); }, null),\n enabled: prop(function () { return a.enabled(); }, null),\n accountType: prop(function () { return String(a.accountType()); }, null),\n emailAddresses: prop(function () { return a.emailAddresses(); }, []),\n fullName: prop(function () { return a.fullName(); }, null),\n // Path objects need String(); JSON.stringify renders them as {}.\n directory: prop(function () { return String(a.accountDirectory()); }, null),\n messageCaching: prop(function () { return String(a.messageCaching()); }, null),\n mailboxes: prop(function () { return a.mailboxes().map(function (m) { return m.name(); }); }, [])\n });\n }\n return ok(out);\n`);\n\n/**\n * Mailboxes with counts. Counts come from AppleScript rather than the index\n * because they are cheap here (76ms unread / 295ms total on a 29k mailbox) and\n * therefore never need to degrade when Full Disk Access is missing.\n */\nexport const LIST_MAILBOXES = script(`\n var accts = M.accounts();\n var out = [];\n for (var i = 0; i < accts.length; i++) {\n var a = accts[i];\n var uuid = prop(function () { return a.id(); }, null);\n if (p.accountUuids && p.accountUuids.length && p.accountUuids.indexOf(uuid) === -1) continue;\n var boxes = a.mailboxes();\n for (var j = 0; j < boxes.length; j++) {\n var b = boxes[j];\n var entry = {\n accountUuid: uuid,\n accountName: prop(function () { return a.name(); }, null),\n name: prop(function () { return b.name(); }, null)\n };\n if (p.withCounts) {\n entry.unread = prop(function () { return b.unreadCount(); }, null);\n entry.total = prop(function () { return b.messages.length; }, null);\n }\n out.push(entry);\n }\n }\n return ok(out);\n`);\n\n/** Total and unread for one mailbox. */\nexport const COUNT_MAILBOX = script(`\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n return ok({\n accountUuid: p.accountUuid,\n mailbox: prop(function () { return mb.name(); }, p.mailbox),\n total: prop(function () { return mb.messages.length; }, null),\n unread: prop(function () { return mb.unreadCount(); }, null)\n });\n`);\n\n/**\n * The degraded listing lane: newest N of one mailbox, used when the Envelope\n * Index is unavailable. Costs roughly 130ms + 42ms per message per property,\n * which is why the caller caps N hard (default 50) instead of paginating.\n */\nexport const LIST_RECENT = script(`\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n var mailboxName = prop(function () { return mb.name(); }, p.mailbox);\n\n var total = prop(function () { return mb.messages.length; }, 0);\n var n = Math.min(p.limit || 20, total);\n if (n <= 0) return ok({ mailbox: mailboxName, total: total, messages: [] });\n\n // Batch the property reads: one Apple Event per property beats one per message\n // by roughly 6x. slice() on the message collection keeps it to a range specifier.\n var slice = mb.messages.slice(0, n);\n var subjects = prop(function () { return slice.subject(); }, []);\n var senders = prop(function () { return slice.sender(); }, []);\n var dates = prop(function () { return slice.dateReceived(); }, []);\n var reads = prop(function () { return slice.readStatus(); }, []);\n var flags = prop(function () { return slice.flaggedStatus(); }, []);\n var ids = prop(function () { return slice.id(); }, []);\n\n var out = [];\n for (var i = 0; i < n; i++) {\n out.push({\n id: ids[i] === undefined ? null : ids[i],\n accountUuid: p.accountUuid,\n mailbox: mailboxName,\n subject: subjects[i] === undefined ? null : subjects[i],\n sender: senders[i] === undefined ? null : senders[i],\n dateReceived: iso(dates[i]),\n read: reads[i] === undefined ? null : reads[i],\n flagged: flags[i] === undefined ? null : flags[i]\n });\n }\n return ok({ mailbox: mailboxName, total: total, messages: out });\n`);\n\n/** Resolve a batch of message ids inside one mailbox. ~0.1s even on a 29k mailbox. */\nexport const GET_MESSAGES = script(`\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n var mailboxName = prop(function () { return mb.name(); }, p.mailbox);\n\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = p.ids[i];\n try {\n var m = mb.messages.byId(id);\n var summary = messageSummary(m, p.accountUuid, mailboxName);\n if (p.withContent) {\n summary.content = prop(function () { return m.content(); }, null);\n }\n if (p.withSource) {\n summary.source = prop(function () { return m.source(); }, null);\n }\n if (p.withHeaders) {\n summary.allHeaders = prop(function () { return m.allHeaders(); }, null);\n }\n out.push(summary);\n } catch (e) {\n out.push({ id: id, found: false, error: String(e && e.message ? e.message : e) });\n }\n }\n return ok(out);\n`);\n\n/**\n * Did a message with this subject reach Sent, at or after a given instant?\n *\n * The question a failed compose cannot answer for itself. When the composer\n * window is GONE, nothing in the Accessibility lane can say whether it was sent\n * or discarded — both leave the same empty screen — and getting that wrong in\n * either direction is expensive: calling a sent reply a failure invites a retry\n * that sends it twice, and calling a discarded one sent loses the reply.\n *\n * ## Where it looks\n *\n * The application-level unified mailbox, not the account's. `docs/mail-compose.md`\n * measured `account.draftsMailbox` answering \"Can't get object.\" on all four\n * account types while `application.draftsMailbox` resolves to the unified \"All\n * Drafts\", and there is no reason to expect `sentMailbox` to differ. The\n * documented per-account property is still tried first, so this repairs itself\n * if Apple ever fixes it.\n *\n * Unified is the better target anyway: which account Mail actually sends from is\n * its own decision, and need not be the account the original was read in.\n *\n * ## Why `found: false` is deliberately weak\n *\n * The newest messages are taken as the head of the collection, the way\n * LIST_RECENT does. If a mailbox ever came back oldest-first, the head would be\n * ancient and nothing would match — a FALSE NEGATIVE on a reply that did go,\n * which is the dangerous direction. So `newest` is reported alongside: a caller\n * that sees nothing found AND a newest older than its floor knows the listing\n * never showed it recent mail, and must say \"could not tell\" rather than \"not\n * sent\".\n */\nexport const SENT_SINCE = script(`\n var box = null;\n var acct = p.accountUuid ? findAccount(M, p.accountUuid) : null;\n // name() forces the event: JXA is lazy, so a specifier that will fail does not\n // fail until something reads through it.\n if (acct) box = prop(function () { var b = acct.sentMailbox(); b.name(); return b; }, null);\n if (!box) box = prop(function () { var b = M.sentMailbox(); b.name(); return b; }, null);\n if (!box) return ok({ checked: false, reason: \"NO_SENT_MAILBOX\", found: false, messages: [] });\n\n var mailbox = prop(function () { return box.name(); }, \"Sent\");\n var total = prop(function () { return box.messages.length; }, 0);\n var n = Math.min(p.limit || 25, total);\n if (n <= 0) return ok({ checked: true, mailbox: mailbox, total: total, found: false, newest: null, messages: [] });\n\n // One Apple Event per property rather than one per message, as LIST_RECENT.\n var slice = box.messages.slice(0, n);\n var subjects = prop(function () { return slice.subject(); }, []);\n var sent = prop(function () { return slice.dateSent(); }, []);\n var received = prop(function () { return slice.dateReceived(); }, []);\n\n var floor = p.sinceMs ? Number(p.sinceMs) : 0;\n var wanted = String(p.subject == null ? \"\" : p.subject);\n var hits = [];\n var newest = 0;\n for (var i = 0; i < n; i++) {\n var when = sent[i] || received[i];\n var ms = 0;\n try { ms = when ? when.getTime() : 0; } catch (e) { ms = 0; }\n if (ms > newest) newest = ms;\n if (String(subjects[i] === undefined ? \"\" : subjects[i]) !== wanted) continue;\n if (ms && ms < floor) continue;\n hits.push({\n subject: subjects[i] === undefined ? null : subjects[i],\n dateSent: iso(sent[i]),\n dateReceived: iso(received[i])\n });\n }\n return ok({\n checked: true,\n mailbox: mailbox,\n total: total,\n scanned: n,\n found: hits.length > 0,\n newest: newest ? new Date(newest).toISOString() : null,\n messages: hits\n });\n`);\n","import { script } from \"./core.js\";\n\n/**\n * Mutating scripts.\n *\n * Two rules hold across every one of them:\n *\n * 1. **The post-state is re-read from Mail inside the same script.** Mail\n * updates its Envelope Index eventually, not immediately, so verifying a\n * write by re-querying the index can report the old value and send an agent\n * into a mark-it-again loop. What Mail says right after the mutation is the\n * only trustworthy answer.\n * 2. **Refs are grouped by mailbox by the caller**, so a batch of 50 messages\n * in one mailbox costs one Apple Event, not 50.\n */\n\n/** Set any combination of read / flagged / flagIndex / junk on a batch of ids. */\n/**\n * The two grants a composer needs, probed separately.\n *\n * `composerWindow` reaches Mail's compose window through System Events, and\n * that single call sits behind TWO different permissions: Automation from the\n * responsible process to **System Events** (a distinct TCC row from Automation\n * to Mail, which every other write tool uses), and **Accessibility** for the\n * responsible process, which is what allows reading UI elements once System\n * Events will talk at all.\n *\n * They have to be reported separately because the failure cannot tell them\n * apart. `proc.windows()` is wrapped in `prop()`, which swallows the exception\n * and yields `[]`, so a denied Automation and a denied Accessibility both\n * arrive as \"no window matched\" — indistinguishable from Mail genuinely not\n * having opened one. The old message named Accessibility outright and was read\n * as authoritative; it was a guess with the other two possibilities hidden.\n *\n * The identity being probed is **Cupertino.app**, not the terminal and not\n * node: `scripts/spike-app-tcc` measured that the app is its own responsible\n * process and everything beneath it inherits that. This runs under the same\n * identity as the composer code, so it answers for the process that will\n * actually be refused.\n */\nexport const COMPOSER_ACCESS = `\nObjC.import(\"ApplicationServices\");\nfunction run() {\n // Accessibility: reading UI elements out of another process.\n var accessibility = $.AXIsProcessTrusted() ? \"granted\" : \"denied\";\n\n // Automation -> System Events: being allowed to address it at all. Distinct\n // from Automation -> Mail, and prompted for separately.\n var systemEvents = \"unknown\";\n var detail = null;\n try {\n var SE = Application(\"System Events\");\n SE.processes.name();\n systemEvents = \"granted\";\n } catch (e) {\n var msg = String(e && e.message ? e.message : e);\n detail = msg;\n // Same vocabulary as Permissions.AutomationStatus in the app: -1743 is\n // errAEEventNotPermitted (refused), -1744 is errAEEventWouldRequireUserConsent\n // (never asked). They need different advice — one is a toggle to flip, the\n // other is a prompt nobody has seen yet — so they are not collapsed.\n if (msg.indexOf(\"-1743\") !== -1) systemEvents = \"denied\";\n else if (msg.indexOf(\"-1744\") !== -1) systemEvents = \"notDetermined\";\n else systemEvents = \"error\";\n }\n\n // The functional read, which outranks both flags above.\n //\n // MEASURED, macOS 26.6: Cupertino.app's own process answered\n // AXIsProcessTrusted true while an osascript grandchild of it answered false,\n // because the same bundle identifier held four separate Accessibility entries\n // -- one per path and signature it had been granted at -- and the two checks\n // matched different ones. The flag alone therefore cannot say whether a\n // composer is reachable: it is a claim about an identity that may be\n // ambiguous, and this is the thing itself. Naming a window of Mail's needs\n // exactly the grants a composer needs, and opens nothing.\n var uiRead = \"unknown\";\n var windows = null;\n try {\n var proc = Application(\"System Events\").processes.byName(\"Mail\");\n windows = proc.windows().map(function (w) {\n try { return w.name(); } catch (e) { return null; }\n });\n // No windows is not evidence: Mail closed down to the menu bar reads the\n // same as Mail we are blind to.\n uiRead = windows.length ? \"granted\" : \"inconclusive\";\n } catch (e) {\n uiRead = \"denied\";\n windows = null;\n }\n\n return JSON.stringify({\n ok: true,\n data: {\n accessibility: accessibility,\n systemEvents: systemEvents,\n uiRead: uiRead,\n windows: windows,\n detail: detail,\n },\n });\n}\n`;\n\nexport const SET_FLAGS = script(`\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n var mailboxName = prop(function () { return mb.name(); }, p.mailbox);\n\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = p.ids[i];\n try {\n var m = mb.messages.byId(id);\n if (p.read !== undefined && p.read !== null) m.readStatus = p.read;\n if (p.flagged !== undefined && p.flagged !== null) m.flaggedStatus = p.flagged;\n if (p.flagIndex !== undefined && p.flagIndex !== null) m.flagIndex = p.flagIndex;\n if (p.junk !== undefined && p.junk !== null) m.junkMailStatus = p.junk;\n\n // Re-read from Mail rather than echoing back what we asked for.\n out.push({\n id: id,\n ok: true,\n read: prop(function () { return m.readStatus(); }, null),\n flagged: prop(function () { return m.flaggedStatus(); }, null),\n flagIndex: prop(function () { return m.flagIndex(); }, null),\n junk: prop(function () { return m.junkMailStatus(); }, null)\n });\n } catch (e) {\n out.push({ id: id, ok: false, error: String(e && e.message ? e.message : e) });\n }\n }\n return ok({ mailbox: mailboxName, results: out });\n`);\n\n/**\n * Move messages to another mailbox.\n *\n * The moved message gets a NEW row id, so the refs the caller holds are dead\n * afterwards. We re-resolve each moved message in the destination and hand back\n * fresh ids; anything we cannot re-find is reported rather than silently dropped.\n */\nexport const MOVE_MESSAGES = script(`\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var src = resolveMailbox(acct, p.mailbox);\n if (!src) return err(\"MAILBOX_NOT_FOUND\", \"No source mailbox \" + p.mailbox);\n\n var destAcct = p.destAccountUuid ? findAccount(M, p.destAccountUuid) : acct;\n if (!destAcct) return err(\"ACCOUNT_NOT_FOUND\", \"No destination account \" + p.destAccountUuid);\n var dest = resolveMailbox(destAcct, p.destMailbox);\n if (!dest) return err(\"MAILBOX_NOT_FOUND\", \"No destination mailbox \" + p.destMailbox);\n\n var destName = prop(function () { return dest.name(); }, p.destMailbox);\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = p.ids[i];\n try {\n var m = src.messages.byId(id);\n var messageId = prop(function () { return m.messageId(); }, null);\n M.move(m, { to: dest });\n\n // Find it again by Message-ID: the row id changed, and only the RFC id survives.\n var newId = null;\n if (messageId) {\n try {\n var matches = dest.messages.whose({ messageId: messageId })();\n if (matches.length > 0) newId = matches[0].id();\n } catch (e2) { newId = null; }\n }\n out.push({ id: id, ok: true, newId: newId, messageId: messageId });\n } catch (e) {\n out.push({ id: id, ok: false, error: String(e && e.message ? e.message : e) });\n }\n }\n return ok({ destination: destName, destinationAccountUuid: prop(function () { return destAcct.id(); }, null), results: out });\n`);\n\n/**\n * Create a mailbox, on an account or in \"On My Mac\".\n *\n * ## Idempotent by inspection, not by catching a failure\n *\n * Mail does not refuse a second mailbox with a name one already has — depending\n * on the account it will either no-op or make a duplicate, and a duplicate is\n * not something a caller can undo from here. So this looks first and reports\n * `created: false` for a name that is already taken, which also makes the tool\n * safe to call before a move without a separate existence check.\n *\n * ## Why the result is re-read\n *\n * On an IMAP account the SERVER decides whether the name is acceptable and what\n * it ends up called — a leading dot, a reserved prefix, a namespace the account\n * cannot write to. `push` reports none of that, so the mailbox is looked up\n * again afterwards and its absence is an error rather than a silent success.\n */\nexport const CREATE_MAILBOX = script(`\n var acct = null;\n if (p.accountUuid) {\n acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n }\n\n // Local mailboxes hang off the application, account mailboxes off the account.\n var find = function (name) {\n if (acct) return resolveMailbox(acct, name);\n var tops = M.mailboxes();\n var lower = String(name).toLowerCase();\n for (var i = 0; i < tops.length; i++) {\n var box = tops[i];\n if (String(prop(function () { return box.name(); }, \"\")).toLowerCase() === lower) return box;\n }\n return null;\n };\n\n var describe = function (box, created, note) {\n var out = {\n created: created,\n name: prop(function () { return box.name(); }, p.name),\n account: acct ? prop(function () { return acct.name(); }, null) : null,\n accountUuid: acct ? prop(function () { return acct.id(); }, null) : null\n };\n if (note) out.note = note;\n return out;\n };\n\n var existing = find(p.name);\n if (existing) {\n return ok(describe(existing, false, \"A mailbox with that name already exists; nothing was created.\"));\n }\n\n var mb = M.Mailbox({ name: p.name });\n if (acct) acct.mailboxes.push(mb); else M.mailboxes.push(mb);\n\n var made = find(p.name);\n if (!made) {\n return err(\n \"MAILBOX_NOT_CREATED\",\n \"Mail accepted the request but no mailbox named \" + p.name + \" exists afterwards. On an \" +\n \"IMAP account the server can reject a name without reporting an error to AppleScript.\"\n );\n }\n return ok(describe(made, true, null));\n`);\n\n/**\n * Delete messages.\n *\n * Mail's `delete` honours the account's \"move deleted messages to Trash\"\n * setting, so whether this is recoverable is the account's decision and not\n * ours. We report that setting back so the answer is visible rather than assumed.\n */\nexport const DELETE_MESSAGES = script(`\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n\n var movesToTrash = prop(function () { return acct.moveDeletedMessagesToTrash(); }, null);\n\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = p.ids[i];\n try {\n var m = mb.messages.byId(id);\n var subjectLength = String(prop(function () { return m.subject(); }, \"\")).length;\n M.delete(m);\n out.push({ id: id, ok: true, subjectLength: subjectLength });\n } catch (e) {\n out.push({ id: id, ok: false, error: String(e && e.message ? e.message : e) });\n }\n }\n return ok({ movedToTrash: movesToTrash, results: out });\n`);\n\n/** Trigger a sync. Allowed to launch Mail, because making Mail act is the whole point. */\nexport const CHECK_FOR_NEW_MAIL = script(\n `\n if (p.accountUuid) {\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n M.checkForNewMail({ for: acct });\n return ok({ checked: prop(function () { return acct.name(); }, p.accountUuid) });\n }\n M.checkForNewMail();\n return ok({ checked: \"all accounts\" });\n`,\n { allowLaunch: true },\n);\n\n/**\n * Compose a new message.\n *\n * `sendNow` defaults to false at every layer above this, which leaves the\n * draft on screen for a human to read before it goes anywhere. Sending is the\n * only action in this server that is both irreversible and visible to other\n * people, so it gets two independent gates rather than one.\n */\nexport const SEND_MESSAGE = script(\n `\n var msg = M.OutgoingMessage({\n subject: p.subject || \"\",\n content: p.body || \"\",\n visible: true\n });\n M.outgoingMessages.push(msg);\n\n if (p.senderAddress) msg.sender = p.senderAddress;\n\n var lists = [[\"to\", p.to], [\"cc\", p.cc], [\"bcc\", p.bcc]];\n for (var l = 0; l < lists.length; l++) {\n var kind = lists[l][0];\n var addrs = lists[l][1] || [];\n for (var i = 0; i < addrs.length; i++) {\n if (kind === \"to\") msg.toRecipients.push(M.ToRecipient({ address: addrs[i] }));\n else if (kind === \"cc\") msg.ccRecipients.push(M.CcRecipient({ address: addrs[i] }));\n else msg.bccRecipients.push(M.BccRecipient({ address: addrs[i] }));\n }\n }\n\n pause(1.2);\n var unquoted = false;\n try { unquoted = stripCitation(String(p.subject || \"\")); } catch (e) { unquoted = false; }\n\n if (p.sendNow) {\n msg.send();\n return ok({ sent: true, unquoted: unquoted, subjectLength: String(p.subject || \"\").length,\n recipientCount: (p.to || []).length + (p.cc || []).length + (p.bcc || []).length });\n }\n return ok({ sent: false, draft: true, unquoted: unquoted, subjectLength: String(p.subject || \"\").length,\n recipientCount: (p.to || []).length + (p.cc || []).length + (p.bcc || []).length,\n note: \"Draft window is open in Mail for review.\" });\n`,\n { allowLaunch: true },\n);\n\n/**\n * Replace the body of a saved draft, by recreating it.\n *\n * ## Why recreating, when \"edit the draft\" is the obvious thing\n *\n * Because Mail's dictionary does not offer it, and that is measured rather than\n * assumed — see `docs/mail-compose.md`. A saved draft is a `message`, whose\n * `content` is `access=\"r\"`. There is no `open` command and no `edit` command in\n * the entire suite, so nothing turns a saved draft back into the `outgoing\n * message` whose content IS writable. The only class that ever held a reference\n * from one to the other is `OLD message editor`, marked `hidden` and\n * \"DEPRECATED - DO NOT USE\".\n *\n * So the body is replaced the only way the interface allows: compose a new\n * message carrying the old one's recipients and the new text, and remove the\n * old one.\n *\n * ## The order is the safety property\n *\n * The replacement is created AND CONFIRMED PRESENT before the original is\n * deleted, never the other way round. A delete-then-create that fails halfway\n * has destroyed something the user wrote and cannot get back — this server has\n * no undo and Mail's Trash may not be in play, since `moveDeletedMessagesToTrash`\n * is per-account. If the confirmation does not come back, the original is left\n * exactly where it was and the caller is told there are now two.\n *\n * ## What it refuses\n *\n * Recreating cannot carry everything across, and the two things it drops are\n * both invisible in the result:\n *\n * * **Threading.** `In-Reply-To` and `References` are set by Mail's own\n * `reply` command, which needs the original message. A recreated reply\n * draft looks perfect and starts a new thread.\n * * **Attachments.** Adding one to an outgoing message IS possible:\n * `content.attachments.push(Mail.Attachment({fileName: Path(f)}))`, measured\n * on macOS 26.6. What is missing is a file to point at. The bytes live in the\n * original's sidecar tree, and extracting them first is not done here.\n *\n * Both are refused rather than silently dropped. A draft that is correct in\n * every visible respect except the part nobody checks is the exact failure the\n * compose path already learned once.\n */\nexport const UPDATE_DRAFT = script(\n `\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n\n var original;\n try {\n original = mb.messages.byId(p.id);\n original.subject();\n } catch (e) {\n return err(\"MESSAGE_NOT_FOUND\", \"No message \" + p.id + \" in \" + p.mailbox);\n }\n\n /*\n * Find the account's Drafts mailbox.\n *\n * MEASURED, macOS 26.6: account.draftsMailbox is in the dictionary with\n * access=\"r\" and raises \"Can't get object.\" on EVERY account — iCloud, two\n * IMAP, one Exchange. The application-level draftsMailbox does resolve, but\n * it is the unified \"All Drafts\" smart mailbox and is not what a message\n * reports as its own container.\n *\n * So the name is DISCOVERED rather than guessed: every message in All Drafts\n * reports its real per-account mailbox, which also makes this correct on a\n * localised Mail where a hardcoded \"Drafts\" would not be. The documented\n * property is still tried first, so this repairs itself if Apple fixes it.\n */\n var drafts = prop(function () { return acct.draftsMailbox(); }, null);\n var acctName = String(prop(function () { return acct.name(); }, \"\"));\n if (!drafts) {\n var all = prop(function () { return M.draftsMailbox(); }, null);\n var pool = all ? prop(function () { return all.messages(); }, []) : [];\n for (var d = 0; d < pool.length && d < 200 && !drafts; d++) {\n var box = prop(function () { return pool[d].mailbox(); }, null);\n if (!box) continue;\n var owner = prop(function () { return box.account().name(); }, null);\n if (owner === null || String(owner) !== acctName) continue;\n drafts = box;\n }\n }\n if (!drafts) {\n return err(\n \"DRAFTS_MAILBOX_UNKNOWN\",\n \"The Drafts mailbox for \" + acctName + \" could not be identified: Mail refuses the \" +\n \"account's draftsMailbox property, and no message in All Drafts belongs to this account. \" +\n \"Nothing was changed. If the account genuinely holds no drafts, then neither does the \" +\n \"message you named.\"\n );\n }\n var draftsName = String(prop(function () { return drafts.name(); }, \"\"));\n\n // Only a draft may be rewritten. Editing a SENT or RECEIVED message by\n // deleting it and writing a lookalike is not editing, it is forgery, and the\n // ref for one looks exactly like the ref for the other.\n var here = String(prop(function () { return mb.name(); }, p.mailbox));\n if (here.toLowerCase() !== draftsName.toLowerCase()) {\n return err(\n \"NOT_A_DRAFT\",\n \"That message is in \" + here + \", not in \" + draftsName + \". Only an unsent draft can be \" +\n \"rewritten: doing this to a sent or received message would delete the real one and leave \" +\n \"a lookalike in its place.\"\n );\n }\n\n var attachments = prop(function () { return original.mailAttachments().length; }, 0);\n var headers = String(prop(function () { return original.allHeaders(); }, \"\"));\n var isReply = /^(in-reply-to|references):/im.test(headers);\n\n var readAddresses = function (list) {\n var out = [];\n var items = prop(function () { return list(); }, []);\n for (var i = 0; i < items.length; i++) {\n var box = items[i];\n var addr = prop(function () { return box.address(); }, null);\n if (addr) out.push(String(addr));\n }\n return out;\n };\n var to = readAddresses(function () { return original.toRecipients(); });\n var cc = readAddresses(function () { return original.ccRecipients(); });\n var bcc = readAddresses(function () { return original.bccRecipients(); });\n var oldSubject = String(prop(function () { return original.subject(); }, \"\"));\n var sender = String(prop(function () { return original.sender(); }, \"\"));\n\n // Everything the caller needs to decide what to do instead, reported on the\n // refusals as well as on success.\n var facts = {\n subject: oldSubject,\n isReply: isReply,\n attachments: attachments,\n recipientCount: to.length + cc.length + bcc.length\n };\n\n if (isReply) {\n return ok({\n replaced: false, degraded: true, capability: \"threading\", draft: facts,\n reason:\n \"This draft is a reply or a forward: its headers carry In-Reply-To or References, and \" +\n \"those are written by Mail's own reply command, which needs the original message. \" +\n \"Recreating it would produce a draft that looks right and starts a NEW thread.\",\n hint:\n \"Edit the body in Mail directly, or delete this draft and start again with \" +\n \"apple_mail_reply_to_message, which threads correctly.\"\n });\n }\n if (attachments > 0) {\n return ok({\n replaced: false, degraded: true, capability: \"attachments\", draft: facts,\n reason:\n \"This draft carries \" + attachments + \" attachment(s). Recreating it would silently drop \" +\n \"them: their bytes live inside the original message, not as files this can point at, and \" +\n \"re-attaching means extracting them first, which is not done here.\",\n hint: \"Edit the body in Mail directly, which keeps the attachments.\"\n });\n }\n\n var subject = p.subject === null || p.subject === undefined ? oldSubject : String(p.subject);\n if (!subject) {\n return ok({\n replaced: false, degraded: true, capability: \"confirmation\", draft: facts,\n reason:\n \"This draft has no subject, and the subject is the only handle this server has for \" +\n \"finding the replacement again after Mail saves it. Without that confirmation the \" +\n \"original cannot be deleted safely, so nothing was changed.\",\n hint: 'Pass the subject argument to give it one, or edit the draft in Mail.'\n });\n }\n\n var replacement = M.OutgoingMessage({ subject: subject, content: p.body || \"\", visible: true });\n M.outgoingMessages.push(replacement);\n if (sender) { try { replacement.sender = sender; } catch (e) {} }\n\n var lists = [[\"to\", to], [\"cc\", cc], [\"bcc\", bcc]];\n for (var l = 0; l < lists.length; l++) {\n var kind = lists[l][0];\n var addrs = lists[l][1];\n for (var i = 0; i < addrs.length; i++) {\n if (kind === \"to\") replacement.toRecipients.push(M.ToRecipient({ address: addrs[i] }));\n else if (kind === \"cc\") replacement.ccRecipients.push(M.CcRecipient({ address: addrs[i] }));\n else replacement.bccRecipients.push(M.BccRecipient({ address: addrs[i] }));\n }\n }\n\n pause(1.2);\n var unquoted = false;\n try { unquoted = stripCitation(subject); } catch (e) { unquoted = false; }\n\n var saved = true;\n try { replacement.save(); } catch (e) { saved = false; }\n\n // Ask the Drafts mailbox, not the object we just made: \"save() did not throw\"\n // is precisely the kind of evidence the compose path already learned not to\n // trust. Anything but a new row here means we must not delete the old one.\n var newId = null;\n for (var attempt = 0; attempt < 10 && newId === null; attempt++) {\n pause(0.4);\n var matches = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);\n for (var k = 0; k < matches.length; k++) {\n var mid = prop(function () { return matches[k].id(); }, null);\n if (mid === null || mid === p.id) continue;\n if (newId === null || mid > newId) newId = mid;\n }\n }\n\n if (newId === null) {\n return ok({\n replaced: false, degraded: true, capability: \"confirmation\", draft: facts, saved: saved,\n reason:\n \"The replacement was composed but never appeared in \" + draftsName + \" within four \" +\n \"seconds, so it could not be confirmed. THE ORIGINAL DRAFT WAS NOT DELETED — there are \" +\n \"now two, and the new one may still be an unsaved window on screen.\",\n hint:\n \"Look at Mail: save or discard the open composer, then decide which draft to keep. \" +\n \"Nothing here will delete either of them.\"\n });\n }\n\n var movesToTrash = prop(function () { return acct.moveDeletedMessagesToTrash(); }, null);\n var removed = true;\n var removeError = null;\n /*\n * Re-resolve before deleting, never reuse the original reference.\n *\n * MEASURED: on a syncing account the row id of a just-saved draft is\n * REWRITTEN within seconds — a probe watched a confirmed draft move from\n * 199625 to 199626 while the script was still running, and the reference held\n * across that gap failed with \"Can't get object.\" The reference fetched at the\n * top of this script has been through several seconds of polling and a server\n * round trip by the time we get here, so it is refetched by id.\n */\n try {\n M.delete(mb.messages.byId(p.id));\n } catch (e) {\n removed = false;\n removeError = String(e && e.message ? e.message : e);\n }\n\n // Read the id back once more: the same sync rewrite that invalidates the\n // original can renumber the replacement between confirmation and return.\n pause(0.4);\n var settledId = newId;\n var finals = prop(function () { return drafts.messages.whose({ subject: subject })(); }, []);\n for (var f = 0; f < finals.length; f++) {\n var fid = prop(function () { return finals[f].id(); }, null);\n if (fid !== null && fid !== p.id && (settledId === newId || fid > settledId)) settledId = fid;\n }\n\n return ok({\n replaced: true,\n newId: settledId,\n confirmedId: newId,\n draftsMailbox: draftsName,\n subject: subject,\n recipientCount: facts.recipientCount,\n bodyLength: String(p.body || \"\").length,\n unquoted: unquoted,\n originalDeleted: removed,\n originalMovedToTrash: removed ? movesToTrash : null,\n removeError: removeError\n });\n`,\n { allowLaunch: true },\n);\n\n/**\n * Reply to, or forward, an existing message.\n *\n * The body cannot go through the scripting interface. `reply` and `forward`\n * hand back an outgoing message whose `content` reads as \"\" and swallows every\n * write — not a race, and not fixed by waiting: measured on macOS 26 with and\n * without `opening window`, immediately and six seconds later, and the same for\n * setting AXValue on the composer's web area, which reports itself settable and\n * then does nothing. Recipients, subject and threading DO come through, which\n * is what made the old failure so bad: a draft correct in every visible respect\n * except the words, reported as a success.\n *\n * So the body is pasted into the composer window and then read back out of it.\n * Nothing here reports a draft as ready on the strength of an assignment having\n * been accepted, because that is exactly what lied.\n */\nexport const REPLY_OR_FORWARD = script(\n `\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n\n var original;\n try {\n original = mb.messages.byId(p.id);\n original.subject();\n } catch (e) {\n return err(\"MESSAGE_NOT_FOUND\", \"No message \" + p.id + \" in \" + p.mailbox);\n }\n\n // Asked BEFORE anything is opened, and that ordering is the fix for the\n // failure this tool was best known for. The two grants below fail in exactly\n // the state where a composer is already on screen, so the old shape left an\n // empty reply window behind on every attempt and told the user to close it.\n // Nothing about the check needs the window to exist.\n var SE = Application(\"System Events\");\n var reach = composerReach(SE);\n if (!reach.ok) return err(\"COMPOSER_NOT_FOUND\", composerGrantMessage(p.mode, reach));\n\n // The window is opened even when sending immediately: it is where the body\n // has to be typed, and sending from it sends what was verified rather than\n // whatever the disconnected scripting object thinks it holds.\n var draft;\n if (p.mode === \"forward\") {\n draft = M.forward(original, { openingWindow: true });\n } else {\n draft = M.reply(original, { openingWindow: true, replyToAll: p.replyToAll ? true : false });\n }\n\n var subject = String(prop(function () { return draft.subject(); }, \"\"));\n if (!subject) return err(\"COMPOSER_NOT_FOUND\", \"Mail did not return a composer for the \" + p.mode + \".\");\n\n var proc = SE.processes.byName(\"Mail\");\n var win = composerWindow(proc, subject, 8000);\n if (!win) {\n // The pre-flight passed and this still failed, so the grants are live and\n // the window is the problem. Nothing has been typed yet, so the composer we\n // opened is ours to take back.\n var closedUnreadable = discardComposer(M, draft);\n return err(\n \"COMPOSER_NOT_FOUND\",\n \"Mail was asked to open a \" + p.mode + \" window for \\\\\"\" + subject + \"\\\\\" and no such window \" +\n \"was readable within 8s, although Mail's other windows read fine — so this is not a \" +\n \"permission. Nothing was written. Mail may still have been opening it. The windows visible \" +\n \"at the time were: \" + JSON.stringify(reach.windows) + \". \" +\n (closedUnreadable\n ? \"The composer was closed again without saving, so a retry is safe.\"\n : \"The composer could NOT be closed from here — look for an empty \" + p.mode +\n \" window in Mail and close it, or a retry leaves a second one behind.\")\n );\n }\n\n // Recipients go through the scripting object, which does work for them, but\n // only once the composer exists.\n if (p.mode === \"forward\") {\n var addrs = p.to || [];\n for (var i = 0; i < addrs.length; i++) {\n draft.toRecipients.push(M.ToRecipient({ address: addrs[i] }));\n }\n }\n\n var bodyArea = findBodyArea(win, 0);\n if (!bodyArea) {\n var closedNoBody = discardComposer(M, draft);\n return err(\n \"COMPOSER_NOT_FOUND\",\n \"The \" + p.mode + \" window for \\\\\"\" + subject + \"\\\\\" is open, but its body cannot be reached \" +\n \"through the accessibility interface, which is the only way into it. Nothing was written. \" +\n (closedNoBody\n ? \"The window was closed again without saving.\"\n : \"The window could NOT be closed from here and is still on screen.\")\n );\n }\n\n var previous = prop(function () {\n return SE.applicationProcesses.whose({ frontmost: true })[0].name();\n }, null);\n var restore = function () {\n if (previous && previous !== \"Mail\") {\n try { SE.processes.byName(previous).frontmost = true; } catch (e) {}\n }\n };\n\n var bodyVerified = null;\n var verifiedChars = 0;\n if (p.body) {\n var body = String(p.body);\n // Confirm the opening of the body rather than all of it. Reading the whole\n // of a long reply plus the quote it sits above costs seconds of Apple\n // Events, and buys nothing: a paste either arrives whole or does not arrive,\n // which is what was measured, so the top of it is the tell.\n var expected = body.length > 400 ? body.slice(0, 400) : body;\n var sizeBefore = composerBodySize(bodyArea);\n bodyVerified = false;\n\n try {\n proc.frontmost = true;\n pause(0.4);\n for (var attempt = 0; attempt < 2 && !bodyVerified; attempt++) {\n pasteIntoComposer(win, bodyArea, body);\n var after = composerBodyText(bodyArea, expected.length + 400);\n bodyVerified = after !== null && containsText(after, expected);\n if (bodyVerified) {\n verifiedChars = expected.length;\n } else if (landedVerdict(sizeBefore, composerBodySize(bodyArea)) !== \"no\") {\n // Something went in that we cannot match, or the body can no longer be\n // read at all. Pasting again would put the reply in the draft twice,\n // and nothing here can undo that -- so an UNKNOWN reading stops the\n // retry just as firmly as a changed one.\n break;\n }\n }\n } catch (e) {\n bodyVerified = false;\n }\n\n if (!bodyVerified) {\n restore();\n\n // A composer that has GONE reads exactly like one whose body is\n // unreadable, and only this tells them apart. Nothing here closes a\n // composer before this point, so one that is missing was taken by the\n // person at the keyboard -- and sent and discarded leave the same empty\n // screen. Saying \"the body did not go in\" here named the wrong failure and\n // forbade the wrong retry: the hazard is sending the mail twice, not\n // pasting it twice.\n //\n // The native path (client/compose.ts) goes on to ask Mail whether the\n // message reached Sent. This one only says where to look -- it is the\n // fallback for a server not hosted by Cupertino, and a second mailbox scan\n // inside this script is not worth the surface.\n if (composerWindow(proc, subject, 0) === null) {\n return err(\n \"COMPOSER_GONE\",\n \"The \" + p.mode + \" window for \\\\\"\" + subject + \"\\\\\" is GONE. Nothing here closed it — \" +\n \"this path discards a composer only when it is provably empty — so someone using the \" +\n \"Mac sent it or closed it while this was running. Whether it went cannot be told from \" +\n \"here: LOOK IN SENT for this subject before retrying, because a retry after a send \" +\n \"that did go sends it twice.\"\n );\n }\n\n // Take the window back only when it is provably still empty. A paste that\n // landed and could not be READ is a different thing from one that never\n // landed, and closing that one would destroy the reply with no way to get\n // it back -- so it is left on screen for the user to judge. An UNKNOWN\n // reading counts as \"may have landed\" for exactly the same reason.\n var landed = landedVerdict(sizeBefore, composerBodySize(bodyArea));\n var closedUnverified = landed === \"no\" ? discardComposer(M, draft) : false;\n return err(\n \"DRAFT_BODY_NOT_SET\",\n \"The \" + p.mode + \" window for \\\\\"\" + subject + \"\\\\\" was opened and correctly addressed, but the \" +\n \"body did not go in: reading the composer back does not show the text that was sent. It \" +\n \"MUST NOT be described to the user as ready. \" +\n (closedUnverified\n ? \"Nothing had landed in it, so it was closed again without saving and a retry is safe.\"\n : landed === \"yes\"\n ? \"SOMETHING DID land in it that could not be read back, so it was left open rather \" +\n \"than discarded — look at it in Mail before retrying, because a retry would paste \" +\n \"the reply in twice.\"\n : landed === \"unknown\"\n ? \"The window is still there but its body could not be READ, so whether anything \" +\n \"landed is unknown. It was left open rather than discarded — look at it in Mail \" +\n \"before retrying, because a retry would paste the reply in twice.\"\n : \"It could NOT be closed from here — close it in Mail before retrying, or the retry \" +\n \"leaves a second draft behind.\")\n );\n }\n }\n\n if (p.sendNow) {\n // Sent from the window, so what goes out is what was just verified.\n var clicked = false;\n try {\n proc.frontmost = true;\n pause(0.4);\n try { win.actions.byName(\"AXRaise\").perform(); } catch (e) {}\n pause(0.3);\n var send = proc.menuBars[0].menuBarItems.byName(\"Message\").menus[0].menuItems.byName(\"Send\");\n if (prop(function () { return send.enabled(); }, false)) {\n send.click();\n clicked = true;\n }\n } catch (e) {\n clicked = false;\n }\n // The window closing is the confirmation that it went. Wait for it rather\n // than sampling once: reporting a slow close as a failure would invite a\n // retry, and a retry after a send that DID go sends the mail twice.\n var stillOpen = true;\n var waited = 0;\n while (clicked && waited < 8000) {\n pause(0.5);\n waited += 500;\n if (composerWindow(proc, subject, 0) === null) { stillOpen = false; break; }\n }\n restore();\n if (!clicked) {\n return err(\n \"SEND_FAILED\",\n \"The \" + p.mode + \" was composed and its body verified, but Message > Send would not \" +\n \"activate, so NOTHING WAS SENT. The draft is on screen with the right text in it and can \" +\n \"be sent by hand.\"\n );\n }\n if (stillOpen) {\n return err(\n \"SEND_UNCONFIRMED\",\n \"The \" + p.mode + \" was composed, its body verified, and Send was clicked — but the window \" +\n \"was still open 8s later, so whether it went cannot be confirmed from here. DO NOT send it \" +\n \"again: check Sent in Mail first, because a retry would send it twice.\"\n );\n }\n return ok({ sent: true, mode: p.mode, bodyVerified: bodyVerified,\n verifiedChars: verifiedChars, subject: subject });\n }\n\n restore();\n return ok({\n sent: false,\n draft: true,\n mode: p.mode,\n subject: subject,\n bodyVerified: bodyVerified,\n verifiedChars: verifiedChars,\n note: bodyVerified\n ? \"Draft window is open in Mail for review; its body was read back out of the window and matches.\"\n : \"Draft window is open in Mail for review.\"\n });\n`,\n { allowLaunch: true },\n);\n\n/**\n * Open a reply or forward composer, address it, and stop.\n *\n * The Apple Events half of the NATIVE composer path — see `client/ax.ts` for\n * the other half and `client/compose.ts` for the sequence that joins them.\n *\n * It exists because a JXA object reference cannot outlive the `osascript`\n * process that made it, and `packages/core/src/osascript.ts` spawns one per\n * call by design. The old flow held `draft` from `M.reply(...)` all the way\n * through to `draft.send()`, with every Accessibility step in between; once\n * those steps move out of the script, the reference cannot survive to the end\n * of it. So this script does everything that NEEDS the reference — open,\n * address — and returns the subject, which is the identity the native half\n * addresses the window by.\n *\n * **No System Events here, deliberately.** That is the whole point of the\n * split: this half needs Automation for Mail, which every other write tool\n * already has, and nothing else. The second grant goes with the second half.\n *\n * Recipients go through the scripting object, which does work for them, and\n * only once the composer exists.\n */\nexport const OPEN_COMPOSER = script(\n `\n var acct = findAccount(M, p.accountUuid);\n if (!acct) return err(\"ACCOUNT_NOT_FOUND\", \"No account with id \" + p.accountUuid);\n var mb = resolveMailbox(acct, p.mailbox);\n if (!mb) return err(\"MAILBOX_NOT_FOUND\", \"No mailbox \" + p.mailbox + \" in that account\");\n\n var original;\n try {\n original = mb.messages.byId(p.id);\n original.subject();\n } catch (e) {\n return err(\"MESSAGE_NOT_FOUND\", \"No message \" + p.id + \" in \" + p.mailbox);\n }\n\n var draft;\n if (p.mode === \"forward\") {\n draft = M.forward(original, { openingWindow: true });\n } else {\n draft = M.reply(original, { openingWindow: true, replyToAll: p.replyToAll ? true : false });\n }\n\n var subject = String(prop(function () { return draft.subject(); }, \"\"));\n if (!subject) {\n return err(\"COMPOSER_NOT_FOUND\", \"Mail did not return a composer for the \" + p.mode + \".\");\n }\n\n if (p.mode === \"forward\") {\n var addrs = p.to || [];\n for (var i = 0; i < addrs.length; i++) {\n draft.toRecipients.push(M.ToRecipient({ address: addrs[i] }));\n }\n }\n\n return ok({ subject: subject });\n`,\n { allowLaunch: true },\n);\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport { interferenceNote, type OsascriptRunner } from \"@mgcrea/mcp-apple-core\";\n\nimport { containsText, MailAxLane, type ComposerRef } from \"./ax.js\";\nimport { SENT_SINCE } from \"./jxa/read.js\";\nimport { OPEN_COMPOSER } from \"./jxa/write.js\";\n\nconst run = promisify(execFile);\n\n/**\n * Reply or forward, with the body driven natively.\n *\n * ## Why this is two halves rather than one script\n *\n * A JXA object reference cannot outlive the `osascript` process that made it,\n * and `packages/core/src/osascript.ts` spawns one per call by design. The\n * original flow held `draft` from `M.reply(...)` through to `draft.send()`, with\n * every Accessibility step in between — so moving those steps out of the script\n * necessarily ends the reference before the send.\n *\n * The arrangement that needs no reference: `OPEN_COMPOSER` opens and addresses\n * the composer and returns the SUBJECT, which is an identity the native half can\n * find a window by; everything after is Accessibility, including the send, which\n * becomes command-shift-D rather than `draft.send()`.\n *\n * The alternative — re-finding the draft in a third Apple Events call — was\n * rejected: drafts are discovered by subject, so two with the same one are\n * indistinguishable, and this is the single path whose named failure is sending\n * the wrong thing.\n *\n * ## What is given up, and it is stated rather than hidden\n *\n * The System Events path discards the composer when a paste provably did not\n * land, so a retry is safe. This one cannot: closing an unsaved composer raises\n * a save sheet whose buttons are LOCALISED, and pressing a button by a name that\n * is only right in English is worse than not pressing one. So a failed compose\n * here always leaves the window on screen and says so. Strictly safer — nothing\n * a person wrote is ever destroyed — and strictly less tidy.\n */\n\n/** How long to wait for the composer, matching the System Events path's 8s. */\nconst COMPOSER_TIMEOUT_MS = 8_000;\n\n/** How long to wait for the window to close before calling a send unconfirmed. */\nconst SEND_TIMEOUT_MS = 5_000;\n\n/**\n * Confirm the opening of the body rather than all of it.\n *\n * A paste either arrives whole or does not arrive, which is what was measured,\n * so the top of it is the tell.\n */\nconst VERIFY_CHARS = 400;\n\n/**\n * How far back to accept a message in Sent as this call's.\n *\n * Generous on purpose. `dateSent` and the moment the row appears are not the\n * same instant — a real send measured 16s between them — and the cost of the two\n * errors is lopsided: a window slightly too wide names a message that was\n * already there, which a reader can see and dismiss; one too narrow reports a\n * reply that DID go as missing, and invites sending it again.\n */\nconst SENT_SLACK_MS = 120_000;\n\nexport type ComposeResult = {\n ok: boolean;\n subject: string;\n bodyVerified: boolean | null;\n verifiedChars: number;\n /** Null when it cannot be told — the composer went while nobody was looking. */\n sent: boolean | null;\n note: string;\n};\n\n/**\n * Did anything at all reach the composer?\n *\n * Three answers rather than two, and the third is the bug this path was rebuilt\n * around. \"unknown\" is a body that cannot be READ — which is what a composer\n * that has closed looks like from here, because its element handle dies with it.\n * Folding that into \"different from before\" reported a reply sent by hand as a\n * body that never went in.\n */\ntype Landed = \"yes\" | \"no\" | \"unknown\";\n\nconst compare = (before: number | null, after: number | null): Landed => {\n if (before === null || after === null) return \"unknown\";\n return after === before ? \"no\" : \"yes\";\n};\n\n/**\n * The pasteboard, as a seam.\n *\n * Injectable because the real one is shared machine state: a test that called\n * `pbcopy` would clobber whatever the person running it had copied, which is\n * not a thing a test suite may do.\n */\nexport type Clipboard = { read(): Promise<string | null>; write(text: string): Promise<void> };\n\nexport const systemClipboard: Clipboard = {\n async read() {\n try {\n return (await run(\"/usr/bin/pbpaste\", [])).stdout;\n } catch {\n return null;\n }\n },\n async write(text) {\n const child = execFile(\"/usr/bin/pbcopy\", []);\n child.stdin?.end(text);\n await new Promise((resolve, reject) => {\n child.on(\"close\", resolve);\n child.on(\"error\", reject);\n });\n },\n};\n\n/**\n * Borrow the clipboard, and put it back.\n *\n * The same cost the System Events path documents and for the same reason: this\n * is a paste, so the pasteboard is the mechanism. A clipboard holding an image\n * or a file promise still comes back as text, because there is no way to carry\n * an arbitrary item across without knowing its type.\n */\nconst withClipboard = async <T>(\n clipboard: Clipboard,\n text: string,\n body: () => Promise<T>,\n): Promise<T> => {\n const saved = await clipboard.read();\n await clipboard.write(text);\n try {\n return await body();\n } finally {\n if (saved !== null) {\n try {\n await clipboard.write(saved);\n } catch {\n // The clipboard is a courtesy; failing to restore it must not turn a\n // sent reply into a reported failure.\n }\n }\n }\n};\n\nconst paste = async (\n lane: MailAxLane,\n clipboard: Clipboard,\n ref: ComposerRef,\n text: string,\n focusTimeoutMs: number | undefined,\n): Promise<{ verified: boolean; landed: Landed }> => {\n const expected = text.length > VERIFY_CHARS ? text.slice(0, VERIFY_CHARS) : text;\n const sizeBefore = await lane.bodySize(ref.body);\n\n return withClipboard(clipboard, text, async () => {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const focused = await lane.paste(ref, focusTimeoutMs);\n if (focused) {\n const after = await lane.bodyText(ref.body);\n if (after !== null && containsText(after, expected))\n return { verified: true, landed: \"yes\" as const };\n }\n // Something went in that cannot be matched, or the body can no longer be\n // read at all. Pasting again would put the reply in the draft twice, and\n // nothing here can undo that — so an UNKNOWN reading stops the retry just\n // as firmly as a changed one.\n if (compare(sizeBefore, await lane.bodySize(ref.body)) !== \"no\") break;\n }\n return { verified: false, landed: compare(sizeBefore, await lane.bodySize(ref.body)) };\n });\n};\n\n/**\n * What became of a composer that is no longer on screen.\n *\n * Nothing in this file closes a composer, so one that has gone was taken by the\n * person at the keyboard — and sent and discarded look identical from the\n * Accessibility side. This is the only place that can tell them apart, and it\n * asks Mail rather than guessing.\n *\n * Costs one Apple Event, on a failure path. Deliberately NOT the envelope index:\n * the index is rebuilt on a schedule and was 47 minutes stale when this bug was\n * found, so it cannot see a message sent seconds ago.\n */\nconst sentVerdict = async (\n runner: OsascriptRunner,\n accountUuid: string,\n subject: string,\n since: number,\n): Promise<{ sent: boolean | null; sentence: string }> => {\n let found: {\n checked?: boolean;\n found?: boolean;\n mailbox?: string;\n scanned?: number;\n newest?: string | null;\n messages?: { dateSent?: string | null; dateReceived?: string | null }[];\n };\n try {\n found = (await runner.run(SENT_SINCE, {\n accountUuid,\n subject,\n sinceMs: since - SENT_SLACK_MS,\n })) as typeof found;\n } catch {\n return {\n sent: null,\n sentence:\n \"Whether it was sent could NOT be checked from here — Mail would not answer for its \" +\n \"Sent mailbox. Look there for this subject before retrying: a retry after a send that \" +\n \"did go sends it twice.\",\n };\n }\n\n if (found.checked !== true) {\n return {\n sent: null,\n sentence:\n \"Whether it was sent could NOT be checked from here — no Sent mailbox could be resolved. \" +\n \"Look for this subject in Sent before retrying: a retry after a send that did go sends \" +\n \"it twice.\",\n };\n }\n\n if (found.found === true) {\n const when = found.messages?.[0]?.dateSent ?? found.messages?.[0]?.dateReceived ?? \"just now\";\n return {\n sent: true,\n sentence:\n `It WAS SENT: a message with this subject is in ${found.mailbox ?? \"Sent\"}, dated ` +\n `${when}. Do NOT send it again. Its body was never read back from the window, so what ` +\n `went out is not verified from here — open it in ${found.mailbox ?? \"Sent\"} to see what ` +\n `it actually says.`,\n };\n }\n\n // Nothing matched, which is only evidence if the listing was showing recent\n // mail at all. See SENT_SINCE on why `found: false` is weak on its own.\n const newest = found.newest ? Date.parse(found.newest) : Number.NaN;\n if (!Number.isNaN(newest) && newest < since - SENT_SLACK_MS) {\n return {\n sent: null,\n sentence:\n `Whether it was sent could NOT be told: the ${found.scanned ?? 0} messages read back ` +\n `from ${found.mailbox ?? \"Sent\"} are all older than this call (newest ${found.newest}), ` +\n `so that listing never showed recent mail. Check Sent yourself before retrying.`,\n };\n }\n return {\n sent: false,\n sentence:\n `It does NOT appear to have been sent: no message with this subject is among the ` +\n `${found.scanned ?? 0} most recent in ${found.mailbox ?? \"Sent\"}. So it was most likely ` +\n `closed or discarded rather than sent. Confirm in Sent before retrying.`,\n };\n};\n\nexport const replyOrForwardNatively = async (\n lane: MailAxLane,\n runner: OsascriptRunner,\n params: {\n accountUuid: string;\n mailbox: string;\n id: number;\n mode: \"reply\" | \"forward\";\n body: string | null;\n to: string[];\n replyToAll: boolean;\n sendNow: boolean;\n },\n opts: {\n clipboard?: Clipboard;\n /** Overridable so a test can pin the unconfirmed-send path without waiting for it. */\n composerTimeoutMs?: number;\n sendTimeoutMs?: number;\n /** Same, for the focus poll — see FOCUS_TIMEOUT_MS in `ax.ts`. */\n focusTimeoutMs?: number;\n } = {},\n): Promise<ComposeResult> => {\n const clipboard = opts.clipboard ?? systemClipboard;\n const composerTimeoutMs = opts.composerTimeoutMs ?? COMPOSER_TIMEOUT_MS;\n const sendTimeoutMs = opts.sendTimeoutMs ?? SEND_TIMEOUT_MS;\n // Asked BEFORE anything is opened, keeping the ordering the System Events path\n // established: the failure this tool was best known for left an empty reply\n // window on screen on every attempt, and nothing about the check needs the\n // window to exist.\n // Watched from before anything is opened, so a disturbed run says so instead\n // of blaming Mail. Every refusal below appends the finding when there is one.\n const watch = lane.watch();\n // The floor for the Sent check below, taken before the composer exists so it\n // cannot exclude the very message this call is about.\n const startedAt = Date.now();\n\n const reach = await lane.reach();\n if (!reach.ok) throw new Error(MailAxLane.grantMessage(params.mode));\n\n const opened = (await runner.run(OPEN_COMPOSER, params)) as { subject: string };\n const subject = opened.subject;\n\n /**\n * A composer under this subject was open BEFORE this call opened one.\n *\n * The subject is the only identity the native half has, and it stops being\n * one the moment a composer from an earlier call survives — which is routine,\n * because nothing here ever closes one. The incident, 2026-09-10: Mail keeps\n * composers as tabs, the leftover was readable before the new one was, and\n * the title matched it first. ⌘V went to the composer Mail had in front, the\n * read-back went to the leftover, and a reply that was fine came back as\n * \"SOMETHING DID land in it that could not be read back\". With `sendNow` the\n * send shortcut would have named the leftover too: the wrong message sent,\n * which is the one failure this path is built to refuse.\n *\n * Refused rather than disambiguated. Handles are minted per call, so there is\n * nothing to tell the two apart by, and a guess here is a guess about which\n * message to send. The pre-flight list is the one moment the new composer\n * provably was not on screen.\n */\n if ((reach.windows ?? []).includes(subject)) {\n return {\n ok: false,\n subject,\n bodyVerified: null,\n verifiedChars: 0,\n sent: false,\n note:\n `A ${params.mode} window titled \"${subject}\" was already open in Mail before this call, ` +\n `most likely left by an earlier attempt, and this call has now opened another. With two ` +\n `under one title this path cannot tell which one it opened, so nothing was pasted, ` +\n `pressed or sent. The one just opened has no text above the quoted message. Close it, ` +\n `finish or discard the older one, then retry.` +\n interferenceNote(await watch.check()),\n };\n }\n\n const ref = await lane.findComposer(subject, composerTimeoutMs);\n if (!ref) {\n return {\n ok: false,\n subject,\n bodyVerified: null,\n verifiedChars: 0,\n sent: false,\n note:\n `Mail was asked to open a ${params.mode} window for \"${subject}\" and no such window was ` +\n `readable within ${composerTimeoutMs / 1000}s, although Mail's other windows read ` +\n `fine — so this is not a permission. Nothing was written. The window may still be on ` +\n `screen: look for an empty ${params.mode} in Mail before retrying, because a retry ` +\n `would leave a second one behind. Windows visible at the time: ` +\n `${JSON.stringify(reach.windows)}.` +\n interferenceNote(await watch.check()),\n };\n }\n\n /**\n * The composer is no longer on screen, and nothing here closed it.\n *\n * Which makes this someone else's doing, and the two things they can have done\n * — sent it, discarded it — leave exactly the same empty screen. Saying \"the\n * body did not go in\" here is what shipped, and it was wrong in every part: it\n * named the body as the failure when the body was fine, and forbade the retry\n * on double-paste grounds when the real hazard was sending the mail twice.\n */\n const vanished = async (\n // What was known about the body before the window went. Null from the paste,\n // which is the case that could not read it; true when the vanishing arrived\n // later, after a body had been read back and matched — and that is worth\n // keeping, because it says the message that may have gone out was the right\n // one.\n knownBody: { verified: boolean; chars: number } | null = null,\n ): Promise<ComposeResult> => {\n const verdict = await sentVerdict(runner, params.accountUuid, subject, startedAt);\n return {\n ok: false,\n subject,\n // Unknown, NOT false. Nothing here established that the body was wrong.\n bodyVerified: knownBody?.verified ?? null,\n verifiedChars: knownBody?.chars ?? 0,\n sent: verdict.sent,\n note:\n `The ${params.mode} window for \"${subject}\" is GONE. Nothing here closed it — this path ` +\n `never discards a composer — so someone using the Mac sent it or closed it while this ` +\n `was running. ${verdict.sentence}` +\n interferenceNote(await watch.check()),\n };\n };\n\n let bodyVerified: boolean | null = null;\n let verifiedChars = 0;\n if (params.body) {\n const result = await paste(lane, clipboard, ref, params.body, opts.focusTimeoutMs);\n bodyVerified = result.verified;\n verifiedChars = result.verified ? Math.min(params.body.length, VERIFY_CHARS) : 0;\n if (!result.verified) {\n // Asked before anything is claimed about the body: a composer that has\n // gone reads exactly like one whose body is unreadable, and only this\n // tells them apart.\n if (await lane.composerGone(subject, 0)) return vanished();\n return {\n ok: false,\n subject,\n bodyVerified: false,\n verifiedChars: 0,\n sent: false,\n note:\n `The ${params.mode} window for \"${subject}\" was opened and correctly addressed, but ` +\n `the body did not go in: reading the composer back does not show the text that was ` +\n `sent. It MUST NOT be described to the user as ready. ` +\n (result.landed === \"no\"\n ? \"Nothing landed in it. It was left open rather than discarded, because closing an \" +\n \"unsaved composer raises a save sheet whose buttons are localised. Close it in \" +\n \"Mail, then retry.\"\n : result.landed === \"yes\"\n ? \"SOMETHING DID land in it that could not be read back — look at it in Mail \" +\n \"before retrying, because a retry would paste the reply in twice.\"\n : \"The window is still there but its body could not be READ, so whether anything \" +\n \"landed is unknown — look at it in Mail before retrying, because a retry would \" +\n \"paste the reply in twice.\") +\n interferenceNote(await watch.check()),\n };\n }\n }\n\n // Nothing was pressed unless `finish` says so, and its two refusals must not\n // be reported alike. A composer that could not be raised has gone, the same\n // vanishing as above arriving one step later. A refused keystroke left the\n // composer where it was: the key names it, and the desktop server will not\n // post into somebody else's window when Mail does not come forward.\n const finished = await lane.finish(params.sendNow, ref);\n if (finished === \"gone\")\n return vanished(bodyVerified === true ? { verified: true, chars: verifiedChars } : null);\n if (finished === \"refused\") {\n return {\n ok: false,\n subject,\n bodyVerified,\n verifiedChars,\n sent: false,\n note:\n `The ${params.mode} for \"${subject}\" was composed, but Mail could not be brought to the ` +\n `front, so nothing was pressed and it was not ${params.sendNow ? \"sent\" : \"saved\"}. ` +\n `Its window is still open in Mail. Someone is probably using the Mac; retry once it ` +\n `is free, or finish it in Mail.` +\n interferenceNote(await watch.check()),\n };\n }\n // A send closes the window. Checked rather than assumed: nothing here may\n // report success on the strength of a keystroke having been delivered.\n const sent = params.sendNow ? await lane.composerGone(subject, sendTimeoutMs) : false;\n\n return {\n ok: params.sendNow ? sent : true,\n subject,\n bodyVerified,\n verifiedChars,\n sent,\n note: params.sendNow\n ? sent\n ? \"Sent.\"\n : `The ${params.mode} was composed and verified, but its window is still open ${\n sendTimeoutMs / 1000\n }s after the send, so it may not have gone. Check Mail before retrying.`\n : \"Draft window is open in Mail for review.\",\n };\n};\n","import type { DatabaseSync } from \"node:sqlite\";\n\nimport {\n CORE_DATA_EPOCH_OFFSET,\n detectEpoch,\n fingerprintSchema,\n tableMap,\n} from \"@mgcrea/mcp-apple-core\";\n\nimport { SchemaDriftError } from \"./errors.js\";\n\n/**\n * Introspect the Envelope Index once per connection.\n *\n * Apple owns this schema and can reshape it in any macOS release, so nothing\n * here assumes a column exists. Required columns missing means the lane goes\n * `unavailable` with a message naming them; optional ones simply switch query\n * variants off. The failure mode we are avoiding is a `SELECT *` that starts\n * throwing after a system update and takes the whole server down with it.\n */\n\nexport { CORE_DATA_EPOCH_OFFSET, detectEpoch };\n\nexport type IndexCapabilities = {\n fingerprint: string;\n tables: Record<string, string[]>;\n has: {\n labels: boolean;\n recipients: boolean;\n attachments: boolean;\n subjects: boolean;\n addresses: boolean;\n subjectPrefix: boolean;\n conversationId: boolean;\n flagged: boolean;\n dateSent: boolean;\n messageIdHeader: boolean;\n mailboxCounts: boolean;\n };\n /** Detected, never assumed — prior art disagrees about which epoch this is. */\n epochOffset: number;\n epochReason: string;\n missing: string[];\n};\n\nconst REQUIRED: Record<string, string[]> = {\n messages: [\"mailbox\", \"subject\", \"sender\", \"date_received\", \"read\", \"deleted\"],\n mailboxes: [\"url\"],\n subjects: [\"subject\"],\n addresses: [\"address\"],\n};\n\nexport const introspect = (db: DatabaseSync, now?: number): IndexCapabilities => {\n const fingerprint = fingerprintSchema(db);\n const tables = tableMap(db);\n const tableNames = Object.keys(tables);\n\n const missing: string[] = [];\n for (const [table, cols] of Object.entries(REQUIRED)) {\n if (!tables[table]) {\n missing.push(`${table} (table)`);\n continue;\n }\n for (const c of cols) if (!tables[table]?.includes(c)) missing.push(`${table}.${c}`);\n }\n\n const messageCols = tables.messages ?? [];\n let epoch = { offset: 0, reason: \"not probed\" };\n if (missing.length === 0) {\n const row = db.prepare(\"SELECT MAX(date_received) AS m FROM messages\").get() as {\n m: number | null;\n };\n epoch = detectEpoch(row?.m ?? null, now);\n }\n\n return {\n fingerprint,\n tables,\n has: {\n labels: tableNames.includes(\"labels\"),\n recipients: tableNames.includes(\"recipients\"),\n attachments: tableNames.includes(\"attachments\"),\n subjects: tableNames.includes(\"subjects\"),\n addresses: tableNames.includes(\"addresses\"),\n subjectPrefix: messageCols.includes(\"subject_prefix\"),\n conversationId: messageCols.includes(\"conversation_id\"),\n flagged: messageCols.includes(\"flagged\"),\n dateSent: messageCols.includes(\"date_sent\"),\n messageIdHeader: (tables.message_global_data ?? []).includes(\"message_id_header\"),\n mailboxCounts: (tables.mailboxes ?? []).includes(\"unread_count\"),\n },\n epochOffset: epoch.offset,\n epochReason: epoch.reason,\n missing,\n };\n};\n\nexport const assertUsable = (caps: IndexCapabilities): void => {\n if (caps.missing.length > 0) {\n throw new SchemaDriftError(\n `Mail's search index is not the shape this server knows how to read (missing: ` +\n `${caps.missing.join(\", \")}). This usually means a macOS upgrade changed the schema. ` +\n `The AppleScript lane still works; please report schema fingerprint ${caps.fingerprint}.`,\n { fingerprint: caps.fingerprint, missing: caps.missing },\n );\n }\n};\n","import type { DatabaseSync } from \"node:sqlite\";\n\nimport { escapeLike, openReadOnly, parseBound, toFileUri } from \"@mgcrea/mcp-apple-core\";\n\nimport { SchemaDriftError } from \"./errors.js\";\nimport type { Logger } from \"./osascript.js\";\nimport { assertUsable, introspect, type IndexCapabilities } from \"./schema.js\";\n\n/**\n * Read-only access to Mail's Envelope Index.\n *\n * Two rules, both load-bearing:\n *\n * 1. **Never write.** Mail owns this database, holds it open, and reconciles it\n * against the server. `PRAGMA query_only` makes that structural rather than\n * a matter of everyone remembering.\n * 2. **Prefer `mode=ro` over `immutable=1`.** `immutable=1` tells SQLite the\n * file cannot change and to skip the `-wal` entirely — so a read silently\n * misses anything not yet checkpointed. Measured on a live index: the two\n * modes reported 181427 and 181426 messages minutes after reporting the same\n * number, the difference being one newly-arrived mail. It is a race you lose\n * intermittently and without any error, which is the worst kind.\n */\n\nexport type IndexMode = \"auto\" | \"ro\" | \"immutable\" | \"off\";\n\nexport type MessageRow = {\n rowid: number;\n mailboxUrl: string;\n subject: string | null;\n senderAddress: string | null;\n senderName: string | null;\n dateReceived: string | null;\n dateSent: string | null;\n read: boolean;\n flagged: boolean;\n size: number | null;\n conversationId: number | null;\n hasAttachment: boolean;\n};\n\nexport type SearchFilters = {\n query?: string | undefined;\n sender?: string | undefined;\n recipient?: string | undefined;\n subject?: string | undefined;\n mailboxRowids?: number[] | undefined;\n unreadOnly?: boolean | undefined;\n flaggedOnly?: boolean | undefined;\n hasAttachment?: boolean | undefined;\n dateFrom?: string | undefined;\n dateTo?: string | undefined;\n limit: number;\n offset: number;\n};\n\n/**\n * What a mail query can group on.\n *\n * The single source of truth for both the tool's enum and the SQL expressions\n * in `#groupExpr` — a field can only be asked for if it is listed here, which\n * is what keeps caller strings out of the statement.\n */\nexport const GROUP_FIELDS = [\"sender\", \"mailbox\", \"subject\", \"day\", \"month\"] as const;\n\nexport type GroupField = (typeof GROUP_FIELDS)[number];\n\nexport type GroupRow = {\n /** The grouped value. Null where the underlying column is null. */\n key: string | null;\n /** A display form of `key` where the schema carries one, else null. */\n label: string | null;\n count: number;\n unread: number;\n firstAt: string | null;\n lastAt: string | null;\n};\n\nexport type GroupResult = {\n groups: GroupRow[];\n /** Distinct groups matched, before `limit` cut the list. */\n totalGroups: number;\n /** Messages aggregated. Never capped by `limit`. */\n totalRows: number;\n};\n\nexport { escapeLike, toFileUri };\n\nconst contains = (value: string): string => `%${escapeLike(value)}%`;\n\nexport type OpenResult = {\n db: DatabaseSync;\n /** Which mode actually opened. `immutable` results are WAL-blind — say so. */\n mode: \"ro\" | \"immutable\";\n caps: IndexCapabilities;\n};\n\nexport const openIndex = (path: string, mode: IndexMode, logger?: Logger): OpenResult => {\n const {\n db,\n mode: opened,\n validated: caps,\n } = openReadOnly<IndexCapabilities>(path, mode, {\n envVar: \"APPLE_MAIL_INDEX_MODE\",\n label: \"Mail's search index\",\n hint: \"If this is a permission error, grant Full Disk Access to the app running this server.\",\n // Introspect inside the ladder: an index that opens but is missing required\n // columns should fall through to the next mode, not be handed back.\n validate: (conn) => {\n const found = introspect(conn);\n assertUsable(found);\n return found;\n },\n // Schema drift is not something a different open mode can fix, and its\n // message names the missing columns and the fingerprint — far more useful\n // than the generic \"could not open\" the ladder would otherwise produce.\n fatal: (err) => err instanceof SchemaDriftError,\n onFallback: () =>\n logger?.warn?.(\n \"opened the index with immutable=1; results may omit mail that is still in the -wal\",\n ),\n });\n return { db, mode: opened, caps };\n};\n\nexport class EnvelopeIndex {\n readonly #db: DatabaseSync;\n readonly caps: IndexCapabilities;\n readonly mode: \"ro\" | \"immutable\";\n\n constructor(opened: OpenResult) {\n this.#db = opened.db;\n this.caps = opened.caps;\n this.mode = opened.mode;\n }\n\n close(): void {\n try {\n this.#db.close();\n } catch {\n // Already closed, or the file vanished under us. Nothing useful to do.\n }\n }\n\n /** id -> url for every mailbox, so results can be mapped back to scriptable names. */\n mailboxes(): { rowid: number; url: string; total: number | null; unread: number | null }[] {\n const hasCounts = this.caps.has.mailboxCounts;\n const rows = this.#db\n .prepare(\n hasCounts\n ? \"SELECT ROWID AS rowid, url, total_count AS total, unread_count AS unread FROM mailboxes\"\n : \"SELECT ROWID AS rowid, url, NULL AS total, NULL AS unread FROM mailboxes\",\n )\n .all() as { rowid: number; url: string; total: number | null; unread: number | null }[];\n return rows;\n }\n\n /**\n * Restrict to a set of mailboxes.\n *\n * The `labels` half is not optional for Gmail. Gmail-over-IMAP keeps every\n * message in `[Gmail]/All Mail` and expresses INBOX membership as a label\n * row, so `m.mailbox IN (...)` alone returns an EMPTY inbox — measured here\n * as 0 rows against 51,128 real messages.\n */\n #mailboxPredicate(rowids: number[] | undefined, params: unknown[]): string {\n // `undefined` means \"no mailbox filter was asked for\". An EMPTY ARRAY means\n // one was asked for and matched nothing, which must narrow to nothing —\n // `!rowids?.length` collapsed the two, and a scope that matched no rowid\n // silently became a search of the whole archive.\n if (rowids === undefined) return \"1=1\";\n if (rowids.length === 0) return \"1=0\";\n const placeholders = rowids.map(() => \"?\").join(\",\");\n if (!this.caps.has.labels) {\n params.push(...rowids);\n return `m.mailbox IN (${placeholders})`;\n }\n params.push(...rowids, ...rowids);\n return (\n `(m.mailbox IN (${placeholders}) OR m.ROWID IN ` +\n `(SELECT message_id FROM labels WHERE mailbox_id IN (${placeholders})))`\n );\n }\n\n #toIso(value: number | null): string | null {\n if (value === null || !Number.isFinite(value)) return null;\n return new Date((value + this.caps.epochOffset) * 1000).toISOString();\n }\n\n /**\n * A resolved instant to this store's own units.\n *\n * Takes a Date rather than a string, which is the whole point: it used to do\n * `Date.parse(iso)`, and `Date.parse(\"last week\")` is NaN. node:sqlite binds\n * NaN as NULL, `date_received >= NULL` matches nothing, and the caller got\n * zero results with no error. Parsing now happens once, in core's grammar,\n * which refuses what it cannot read.\n */\n #toEpoch(when: Date): number {\n return Math.floor(when.getTime() / 1000) - this.caps.epochOffset;\n }\n\n /**\n * The WHERE half of a filtered read, appending its bind values to `params`.\n *\n * Shared by `search` and `groupBy` so the two cannot drift: a filter that\n * narrowed a listing but not its aggregate would make \"count per sender in\n * INBOX\" quietly count the whole archive.\n *\n * Call this before adding any other bind value — the placeholders it appends\n * have to come first in the parameter list, which mirrors WHERE preceding\n * ORDER BY and LIMIT in every statement built from it.\n */\n #filterPredicate(filters: Omit<SearchFilters, \"limit\" | \"offset\">, params: unknown[]): string {\n const where: string[] = [\"m.deleted = 0\"];\n\n where.push(this.#mailboxPredicate(filters.mailboxRowids, params));\n\n if (filters.query) {\n // Free text spans subject and sender, which is what \"search my mail for X\"\n // means in practice. Body search is a separate, opt-in scan.\n where.push(\n \"(s.subject LIKE ? ESCAPE '\\\\' OR a.address LIKE ? ESCAPE '\\\\' OR a.comment LIKE ? ESCAPE '\\\\')\",\n );\n params.push(contains(filters.query), contains(filters.query), contains(filters.query));\n }\n if (filters.subject) {\n where.push(\"s.subject LIKE ? ESCAPE '\\\\'\");\n params.push(contains(filters.subject));\n }\n if (filters.sender) {\n where.push(\"(a.address LIKE ? ESCAPE '\\\\' OR a.comment LIKE ? ESCAPE '\\\\')\");\n params.push(contains(filters.sender), contains(filters.sender));\n }\n if (filters.recipient && this.caps.has.recipients) {\n where.push(\n \"EXISTS (SELECT 1 FROM recipients r JOIN addresses ra ON ra.ROWID = r.address \" +\n \"WHERE r.message = m.ROWID AND ra.address LIKE ? ESCAPE '\\\\')\",\n );\n params.push(contains(filters.recipient));\n }\n if (filters.unreadOnly) where.push(\"m.read = 0\");\n if (filters.flaggedOnly && this.caps.has.flagged) where.push(\"m.flagged = 1\");\n if (filters.hasAttachment && this.caps.has.attachments) {\n where.push(\"EXISTS (SELECT 1 FROM attachments at WHERE at.message = m.ROWID)\");\n }\n if (filters.dateFrom) {\n where.push(\"m.date_received >= ?\");\n params.push(this.#toEpoch(parseBound(\"dateFrom\", filters.dateFrom, \"start\")));\n }\n if (filters.dateTo) {\n // Exclusive, because a bare `dateTo` resolves to the NEXT day's midnight.\n // With `<=` and the old same-day midnight, `dateTo: \"2026-08-07\"` excluded\n // every message received on the 7th — the day the caller named.\n where.push(\"m.date_received < ?\");\n params.push(this.#toEpoch(parseBound(\"dateTo\", filters.dateTo, \"end\")));\n }\n\n return where.join(\" AND \");\n }\n\n /**\n * The joins every filtered read needs. `s` and `a` are LEFT joins because a\n * message can legitimately have no subject row and no sender row, and an\n * INNER join here would drop exactly those from counts.\n */\n static readonly #FROM =\n \"FROM messages m \" +\n \"JOIN mailboxes mb ON mb.ROWID = m.mailbox \" +\n \"LEFT JOIN subjects s ON s.ROWID = m.subject \" +\n \"LEFT JOIN addresses a ON a.ROWID = m.sender\";\n\n /**\n * subject_prefix holds \"Re: \" / \"Fwd: \" separately from the deduplicated\n * subject row, so the displayed subject is the concatenation of the two.\n */\n get #subjectExpr(): string {\n return this.caps.has.subjectPrefix\n ? \"COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')\"\n : \"COALESCE(s.subject, '')\";\n }\n\n search(filters: SearchFilters): MessageRow[] {\n const params: unknown[] = [];\n const predicate = this.#filterPredicate(filters, params);\n const subjectExpr = this.#subjectExpr;\n\n const sql =\n `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${subjectExpr} AS subject, ` +\n `a.address AS senderAddress, a.comment AS senderName, ` +\n `m.date_received AS dateReceived, ${this.caps.has.dateSent ? \"m.date_sent\" : \"NULL\"} AS dateSent, ` +\n `m.read AS read, ${this.caps.has.flagged ? \"m.flagged\" : \"0\"} AS flagged, m.size AS size, ` +\n `${this.caps.has.conversationId ? \"m.conversation_id\" : \"NULL\"} AS conversationId, ` +\n (this.caps.has.attachments\n ? \"EXISTS (SELECT 1 FROM attachments at2 WHERE at2.message = m.ROWID) AS hasAttachment \"\n : \"0 AS hasAttachment \") +\n `${EnvelopeIndex.#FROM} ` +\n `WHERE ${predicate} ` +\n `ORDER BY m.date_received DESC LIMIT ? OFFSET ?`;\n\n params.push(filters.limit, filters.offset);\n\n const rows = this.#db.prepare(sql).all(...(params as never[])) as Record<string, unknown>[];\n return rows.map((r) => ({\n rowid: Number(r.rowid),\n mailboxUrl: String(r.mailboxUrl),\n subject: (r.subject as string) || null,\n senderAddress: (r.senderAddress as string) ?? null,\n senderName: (r.senderName as string) || null,\n dateReceived: this.#toIso(r.dateReceived as number | null),\n dateSent: this.#toIso(r.dateSent as number | null),\n read: Boolean(r.read),\n flagged: Boolean(r.flagged),\n size: (r.size as number) ?? null,\n conversationId: (r.conversationId as number) ?? null,\n hasAttachment: Boolean(r.hasAttachment),\n }));\n }\n\n /**\n * The column expression each groupable field aggregates on.\n *\n * A key here is the ONLY thing that reaches the statement — the tool matches\n * the caller's string against `GROUP_FIELDS` and passes the matched literal,\n * so no caller-controlled text is ever interpolated. `label` is a second,\n * human-readable form of the same group where one exists; it goes through\n * MAX() because everything outside GROUP BY has to be aggregated, and the\n * value is constant within a group anyway.\n */\n #groupExpr(field: GroupField): { key: string; label: string } {\n switch (field) {\n case \"sender\":\n return { key: \"a.address\", label: \"MAX(NULLIF(a.comment, ''))\" };\n // Grouped on the rowid rather than the URL so the caller can map it back\n // through the same mailbox lookup every other result uses.\n case \"mailbox\":\n return { key: \"m.mailbox\", label: \"MAX(mb.url)\" };\n case \"subject\":\n return { key: this.#subjectExpr, label: \"NULL\" };\n case \"day\":\n return { key: this.#dateBucket(\"%Y-%m-%d\"), label: \"NULL\" };\n case \"month\":\n return { key: this.#dateBucket(\"%Y-%m\"), label: \"NULL\" };\n }\n }\n\n /**\n * `date_received` is epoch-with-offset, so shift it before formatting.\n *\n * `'localtime'`, matching Messages' buckets and — since the shared grammar\n * landed — matching the bounds. A day bucket is a CALENDAR day, and a person\n * asking \"how much mail per day\" means their own days. In UTC a message that\n * arrived at 23:30 local counted against tomorrow, so a bare `dateTo` naming\n * a local day could return rows the grouping then filed under the day after\n * the one that was asked for.\n */\n #dateBucket(format: string): string {\n return (\n `strftime('${format}', datetime(m.date_received + ${this.caps.epochOffset}, ` +\n `'unixepoch', 'localtime'))`\n );\n }\n\n /**\n * Count matches per group, over every match rather than a page of them.\n *\n * `filters.limit` caps the number of GROUPS returned, not the number of\n * messages considered — that distinction is the whole point of this lane.\n * Aggregating a page instead would answer \"the top senders among the\n * twenty-five rows we happened to return\", which is indistinguishable from a\n * real top-N unless you already knew to doubt it.\n */\n groupBy(filters: Omit<SearchFilters, \"offset\">, field: GroupField): GroupResult {\n const { key, label } = this.#groupExpr(field);\n\n const totalsParams: unknown[] = [];\n const totalsPredicate = this.#filterPredicate(filters, totalsParams);\n // COUNT(DISTINCT) skips NULL, so a \"no sender\" group would go unreported in\n // totalGroups while still appearing in `groups` — and `truncated` is derived\n // from that number. The second term adds the null group back when it exists.\n const totals = this.#db\n .prepare(\n `SELECT COUNT(*) AS totalRows, ` +\n `COUNT(DISTINCT ${key}) + MAX(CASE WHEN ${key} IS NULL THEN 1 ELSE 0 END) AS totalGroups ` +\n `${EnvelopeIndex.#FROM} WHERE ${totalsPredicate}`,\n )\n .get(...(totalsParams as never[])) as { totalRows: number; totalGroups: number | null };\n\n const params: unknown[] = [];\n const predicate = this.#filterPredicate(filters, params);\n params.push(filters.limit);\n\n const rows = this.#db\n .prepare(\n `SELECT ${key} AS key, ${label} AS label, COUNT(*) AS count, ` +\n `SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread, ` +\n `MIN(m.date_received) AS firstAt, MAX(m.date_received) AS lastAt ` +\n `${EnvelopeIndex.#FROM} WHERE ${predicate} ` +\n // Ordered by count so `limit` yields a top-N; the key breaks ties so\n // repeating the same query cannot reshuffle equal-count groups.\n `GROUP BY ${key} ORDER BY count DESC, key ASC LIMIT ?`,\n )\n .all(...(params as never[])) as Record<string, unknown>[];\n\n return {\n groups: rows.map((r) => ({\n key: r.key === null ? null : String(r.key),\n label: (r.label as string) || null,\n count: Number(r.count),\n unread: Number(r.unread ?? 0),\n firstAt: this.#toIso(r.firstAt as number | null),\n lastAt: this.#toIso(r.lastAt as number | null),\n })),\n totalRows: totals.totalRows,\n // MAX() over zero rows is NULL, which is the empty-result case.\n totalGroups: totals.totalGroups ?? 0,\n };\n }\n\n /**\n * Narrowed to the one filter this actually applies.\n *\n * It used to take the whole filter set, which promised a query/sender/date\n * scope it silently dropped. No caller passed one, so the lie was free —\n * until somebody added a caller that did.\n */\n count(filters: Pick<SearchFilters, \"mailboxRowids\">): { total: number; unread: number } {\n const params: unknown[] = [];\n const predicate = this.#mailboxPredicate(filters.mailboxRowids, params);\n const row = this.#db\n .prepare(\n `SELECT COUNT(*) AS total, SUM(CASE WHEN m.read = 0 THEN 1 ELSE 0 END) AS unread ` +\n `FROM messages m WHERE m.deleted = 0 AND ${predicate}`,\n )\n .get(...(params as never[])) as { total: number; unread: number | null };\n return { total: row.total, unread: row.unread ?? 0 };\n }\n\n /** Every message in one conversation, oldest first. */\n thread(conversationId: number, limit: number): MessageRow[] {\n if (!this.caps.has.conversationId) return [];\n const subjectExpr = this.caps.has.subjectPrefix\n ? \"COALESCE(m.subject_prefix, '') || COALESCE(s.subject, '')\"\n : \"COALESCE(s.subject, '')\";\n const rows = this.#db\n .prepare(\n `SELECT m.ROWID AS rowid, mb.url AS mailboxUrl, ${subjectExpr} AS subject, ` +\n `a.address AS senderAddress, a.comment AS senderName, m.date_received AS dateReceived, ` +\n `${this.caps.has.dateSent ? \"m.date_sent\" : \"NULL\"} AS dateSent, m.read AS read, ` +\n `${this.caps.has.flagged ? \"m.flagged\" : \"0\"} AS flagged, m.size AS size, ` +\n `m.conversation_id AS conversationId, 0 AS hasAttachment ` +\n `FROM messages m JOIN mailboxes mb ON mb.ROWID = m.mailbox ` +\n `LEFT JOIN subjects s ON s.ROWID = m.subject ` +\n `LEFT JOIN addresses a ON a.ROWID = m.sender ` +\n `WHERE m.deleted = 0 AND m.conversation_id = ? ORDER BY m.date_received ASC LIMIT ?`,\n )\n .all(conversationId, limit) as Record<string, unknown>[];\n return rows.map((r) => ({\n rowid: Number(r.rowid),\n mailboxUrl: String(r.mailboxUrl),\n subject: (r.subject as string) || null,\n senderAddress: (r.senderAddress as string) ?? null,\n senderName: (r.senderName as string) || null,\n dateReceived: this.#toIso(r.dateReceived as number | null),\n dateSent: this.#toIso(r.dateSent as number | null),\n read: Boolean(r.read),\n flagged: Boolean(r.flagged),\n size: (r.size as number) ?? null,\n conversationId: (r.conversationId as number) ?? null,\n hasAttachment: false,\n }));\n }\n\n /** conversation_id for one message, so get_thread can start from a ref. */\n conversationOf(rowid: number): number | null {\n if (!this.caps.has.conversationId) return null;\n const row = this.#db\n .prepare(\"SELECT conversation_id AS c FROM messages WHERE ROWID = ?\")\n .get(rowid) as { c: number } | undefined;\n return row?.c ?? null;\n }\n}\n","import { PreconditionError } from \"./errors.js\";\nimport { LIST_ACCOUNTS } from \"./jxa/read.js\";\nimport type { OsascriptRunner } from \"./osascript.js\";\n\n/**\n * The account/mailbox join table, and the single choke point for the account\n * allowlist.\n *\n * Everything downstream — search, reads, writes — resolves through here, so\n * filtering the account list once at construction is enough to guarantee that\n * no query path can reach an account the user excluded. Enforcing it in each\n * tool instead would be a list of places to forget.\n */\n\nexport type MailAccount = {\n id: string;\n name: string;\n enabled: boolean;\n accountType: string | null;\n emailAddresses: string[];\n fullName: string | null;\n directory: string | null;\n messageCaching: string | null;\n mailboxes: string[];\n};\n\nexport type MailboxMapOptions = {\n runner: OsascriptRunner;\n /** Names or UUIDs. Empty = every account. */\n allowlist: string[];\n ttlMs: number;\n now?: () => number;\n};\n\nexport class MailboxMap {\n readonly #runner: OsascriptRunner;\n readonly #allowlist: string[];\n readonly #ttlMs: number;\n readonly #now: () => number;\n\n #cache: { at: number; accounts: MailAccount[] } | null = null;\n\n constructor(opts: MailboxMapOptions) {\n this.#runner = opts.runner;\n this.#allowlist = opts.allowlist;\n this.#ttlMs = opts.ttlMs;\n this.#now = opts.now ?? Date.now;\n }\n\n /** True when the allowlist admits this account, by UUID or by display name. */\n #admits(account: MailAccount): boolean {\n if (this.#allowlist.length === 0) return true;\n return this.#allowlist.some(\n (entry) => entry === account.id || entry.toLowerCase() === account.name.toLowerCase(),\n );\n }\n\n async accounts(force = false): Promise<MailAccount[]> {\n const cached = this.#cache;\n if (!force && cached && this.#now() - cached.at < this.#ttlMs) return cached.accounts;\n\n const raw = await this.#runner.run<MailAccount[]>(LIST_ACCOUNTS);\n const accounts = raw.filter((a) => this.#admits(a));\n this.#cache = { at: this.#now(), accounts };\n return accounts;\n }\n\n /** Resolve an account by UUID or display name. Case-insensitive on the name. */\n async resolveAccount(needle: string): Promise<MailAccount> {\n const accounts = await this.accounts();\n const found =\n accounts.find((a) => a.id === needle) ??\n accounts.find((a) => a.name.toLowerCase() === needle.toLowerCase());\n if (!found) {\n throw new PreconditionError(\n `No account \"${needle}\". Known accounts: ${accounts.map((a) => a.name).join(\", \") || \"(none visible)\"}.` +\n (this.#allowlist.length ? \" An allowlist is active (APPLE_MAIL_ACCOUNTS).\" : \"\"),\n );\n }\n return found;\n }\n\n /**\n * Resolve a mailbox name within an account using the same ladder the JXA side\n * uses, so a name that works in one lane works in the other: exact, then\n * `[Gmail]/`-stripped, then final path segment, then case-insensitive.\n */\n resolveMailboxName(account: MailAccount, wanted: string): string {\n const candidates = [wanted];\n if (wanted.startsWith(\"[Gmail]/\")) candidates.push(wanted.slice(8));\n if (wanted.includes(\"/\")) {\n const last = wanted.split(\"/\").pop();\n if (last) candidates.push(last);\n }\n for (const c of candidates) {\n if (account.mailboxes.includes(c)) return c;\n }\n for (const c of candidates) {\n const hit = account.mailboxes.find((m) => m.toLowerCase() === c.toLowerCase());\n if (hit) return hit;\n }\n throw new PreconditionError(\n `No mailbox \"${wanted}\" in account \"${account.name}\". Available: ${account.mailboxes.join(\", \")}.`,\n );\n }\n\n /**\n * Map an Envelope Index `mailboxes.url` onto a scriptable account + mailbox.\n * The URL host is the account UUID (verified against live Mail), so this join\n * is exact rather than a heuristic on display names.\n */\n async resolveIndexUrl(url: string): Promise<{ account: MailAccount; mailbox: string } | null> {\n const m = /^([a-z-]+):\\/\\/([^/]*)\\/?(.*)$/i.exec(url);\n if (!m) return null;\n const host = decodeURIComponent(m[2] ?? \"\");\n const path = decodeURIComponent(m[3] ?? \"\");\n const accounts = await this.accounts();\n const account = accounts.find((a) => a.id === host);\n if (!account) return null;\n try {\n return { account, mailbox: this.resolveMailboxName(account, path) };\n } catch {\n return null;\n }\n }\n\n invalidate(): void {\n this.#cache = null;\n }\n}\n","/**\n * MessageRef — the one identifier any tool accepts or returns.\n *\n * A bare row id is not enough: the same integer means different messages in\n * different mailboxes, and `messages.byId` is only resolvable inside a mailbox\n * (a global `Mail.messages.byId(...)` fails with -1728). Handing the model a\n * naked integer would let it address the wrong message; the ref carries the\n * mailbox with it so that cannot happen.\n *\n * Wire format: m1:<accountUuid>/<mailboxPath>#<id>\n *\n * The `m1:` prefix is deliberate. If the Phase 0 spike ever shows that the\n * SQLite ROWID is not the AppleScript message id, resolution has to fall back\n * to the RFC 5322 Message-ID — and a versioned prefix makes that an additive\n * change instead of a silent reinterpretation of every ref already in a\n * conversation.\n */\n\nimport { PreconditionError } from \"./errors.js\";\n\nexport const REF_VERSION = \"m1\";\n\nexport type MessageRef = {\n accountUuid: string;\n mailbox: string;\n id: number;\n};\n\nconst UUID_RE = /^[0-9A-Fa-f-]{8,64}$/;\n\nexport const encodeRef = (ref: MessageRef): string =>\n `${REF_VERSION}:${ref.accountUuid}/${encodeURIComponent(ref.mailbox)}#${ref.id}`;\n\nexport const decodeRef = (raw: string): MessageRef => {\n const m = /^([a-z0-9]+):([^/]+)\\/(.*)#(\\d+)$/.exec(raw);\n if (!m) {\n throw new PreconditionError(\n `Malformed message ref \"${raw}\". Refs come from the search and list tools — ` +\n `construct them from those results rather than by hand.`,\n { expected: `${REF_VERSION}:<accountUuid>/<mailbox>#<id>` },\n );\n }\n const [, version, accountUuid, mailboxRaw, idRaw] = m;\n if (version !== REF_VERSION) {\n throw new PreconditionError(\n `Unsupported message ref version \"${version}\". This server issues \"${REF_VERSION}\" refs; ` +\n `re-run the search to get current ones.`,\n );\n }\n if (!accountUuid || !UUID_RE.test(accountUuid)) {\n throw new PreconditionError(`Message ref \"${raw}\" does not carry a valid account id.`);\n }\n const id = Number(idRaw);\n if (!Number.isSafeInteger(id) || id <= 0) {\n throw new PreconditionError(`Message ref \"${raw}\" does not carry a valid message id.`);\n }\n return { accountUuid, mailbox: decodeURIComponent(mailboxRaw ?? \"\"), id };\n};\n\n/** Group refs by mailbox so a batch of them costs one Apple Event per mailbox, not per message. */\nexport const groupRefsByMailbox = (refs: MessageRef[]): Map<string, MessageRef[]> => {\n const groups = new Map<string, MessageRef[]>();\n for (const ref of refs) {\n const key = `${ref.accountUuid}/${ref.mailbox}`;\n const existing = groups.get(key);\n if (existing) existing.push(ref);\n else groups.set(key, [ref]);\n }\n return groups;\n};\n","import { closeSync, mkdirSync, openSync, readSync, writeFileSync } from \"node:fs\";\nimport { basename, join, resolve, sep } from \"node:path\";\n\nimport type { Config } from \"../config.js\";\nimport { MailAxLane } from \"./ax.js\";\nimport { scanBodies } from \"./body-scan.js\";\nimport { replyOrForwardNatively } from \"./compose.js\";\nimport {\n extractAttachment,\n lookupEmlx,\n readEmlx,\n readEmlxSource,\n type EmlxLookup,\n type ParsedMessage,\n} from \"./emlx.js\";\nimport {\n EnvelopeIndex,\n openIndex,\n type GroupField,\n type GroupResult,\n type MessageRow,\n type SearchFilters,\n} from \"./envelope.js\";\nimport { MAIL_SURFACE, MessageNotFoundError, PreconditionError } from \"./errors.js\";\nimport { COUNT_MAILBOX, GET_MESSAGES, LIST_MAILBOXES, LIST_RECENT } from \"./jxa/read.js\";\nimport {\n COMPOSER_ACCESS,\n CHECK_FOR_NEW_MAIL,\n CREATE_MAILBOX,\n DELETE_MESSAGES,\n MOVE_MESSAGES,\n REPLY_OR_FORWARD,\n SEND_MESSAGE,\n SET_FLAGS,\n UPDATE_DRAFT,\n} from \"./jxa/write.js\";\nimport { locateEnvelopeIndex, type LocateResult } from \"./locate.js\";\nimport { MailboxMap, type MailAccount } from \"./mailbox-map.js\";\nimport {\n createOsascriptRunner,\n type Logger,\n type OsascriptRunner,\n withBusyRetry,\n} from \"./osascript.js\";\nimport { decodeRef, encodeRef, groupRefsByMailbox, type MessageRef } from \"./ref.js\";\n\n/**\n * The facade every tool talks to. It owns three things the tools should not\n * each re-decide: which lane answers a question, what to say when a lane is\n * unavailable, and the read-after-write rule.\n */\n\n/**\n * The three fields `ref` is built from.\n *\n * Kept off `MessageSummary` deliberately. `ref` is `encodeRef` over exactly\n * these, so emitting them beside it repeats the same identity three more times\n * on every row of every list - measured at 38% of a 25-row reply for something\n * that round-trips through `decodeRef`. Both lanes carry them internally and\n * drop them once the ref exists.\n */\nexport type MessageIdentity = {\n id: number;\n accountUuid: string;\n mailbox: string;\n};\n\nexport type MessageSummary = {\n ref: string;\n subject: string | null;\n sender: string | null;\n dateReceived: string | null;\n dateSent?: string | null;\n messageId?: string | null;\n read: boolean | null;\n flagged?: boolean | null;\n junk?: boolean | null;\n size?: number | null;\n content?: string | null;\n source?: string | null;\n allHeaders?: string | null;\n};\n\nexport type LaneStatus = {\n applescript: \"live\" | \"unavailable\";\n index: \"live\" | \"unavailable\" | \"disabled\";\n indexReason: string | null;\n indexMode?: string;\n schemaFingerprint?: string;\n};\n\n/**\n * What a body search actually did, reported alongside the results.\n *\n * The bound is declared rather than hidden. A scan that silently stopped at the\n * newest N messages would answer \"not found\" for older mail indistinguishably\n * from a real absence, and the model has no way to tell the two apart — so when\n * the candidate set is too wide this says so, with both numbers, and returns\n * nothing rather than a partial answer dressed as a complete one.\n */\nexport type BodyScanReport =\n | {\n status: \"ok\";\n candidates: number;\n scanned: number;\n matched: number;\n /** Candidates with no readable message file. Usually a missing grant. */\n unreadable: number;\n elapsedMs: number;\n bound: number;\n }\n | { status: \"over-bound\"; candidates: number; bound: number };\n\n/** What `#lookupMessageFile` found, and — when it found nothing — why. */\ntype MessageFileLookup =\n | { found: true; path: string; partial: boolean }\n | { found: false; lookup?: Extract<EmlxLookup, { found: false }>; explain: string };\n\n/** The FDA sentence, kept verbatim for the case where FDA really is the problem. */\nconst FDA_HINT =\n \"The message file could not be read. Grant Full Disk Access to the app running this server \" +\n \"and restart it.\";\n\nexport type AppleMailClientOptions = {\n config: Config;\n logger?: Logger | undefined;\n osascript?: OsascriptRunner | undefined;\n /**\n * The composer lane, for tests.\n *\n * A seam of the same shape as `osascript`: passing null pins the System Events\n * path on a machine that IS hosted, and passing a stub drives the native one\n * on a machine that is not. Undefined means \"ask the environment\", which is\n * what the server does.\n */\n ax?: MailAxLane | null | undefined;\n};\n\nexport class AppleMailClient {\n readonly config: Config;\n readonly runner: OsascriptRunner;\n readonly mailboxes: MailboxMap;\n readonly #logger: Logger | undefined;\n\n /**\n * The native Accessibility lane, when this server is hosted by Cupertino.\n *\n * Null when it is not — a package installed from npm and run by hand — and\n * that is the supported case rather than a fault, so every use of it falls\n * back to the System Events path rather than refusing. `diagnostics` reports\n * which one is live.\n */\n readonly #ax: MailAxLane | null;\n\n #located: LocateResult | null = null;\n #index: EnvelopeIndex | null = null;\n #indexError: string | null = null;\n #indexTried = false;\n\n constructor(opts: AppleMailClientOptions) {\n this.config = opts.config;\n this.#logger = opts.logger;\n this.runner =\n opts.osascript ??\n createOsascriptRunner({\n osascriptPath: opts.config.osascriptPath,\n timeoutMs: opts.config.osascriptTimeoutMs,\n surface: MAIL_SURFACE,\n logger: opts.logger,\n });\n this.mailboxes = new MailboxMap({\n runner: this.runner,\n allowlist: opts.config.accounts,\n ttlMs: opts.config.mailboxCacheTtlMs,\n });\n this.#ax = opts.ax !== undefined ? opts.ax : MailAxLane.open();\n }\n\n /** Which composer lane is live, for `diagnostics` to report. */\n get composerLane(): \"accessibility\" | \"system-events\" {\n return this.#ax ? \"accessibility\" : \"system-events\";\n }\n\n accounts(force = false): Promise<MailAccount[]> {\n return this.mailboxes.accounts(force);\n }\n\n /**\n * Where the Envelope Index is and whether we may read it. Resolved lazily and\n * cached: it needs an Apple Event to ask Mail for its own directory, and that\n * answer does not change while the process lives.\n */\n async locate(force = false): Promise<LocateResult> {\n if (this.#located && !force) return this.#located;\n\n let accountDirectory: string | undefined;\n try {\n const accounts = await this.accounts();\n accountDirectory = accounts.find((a) => a.directory)?.directory ?? undefined;\n } catch (err) {\n this.#logger?.debug?.(\"locate: could not ask Mail for its account directory\", err);\n }\n\n this.#located = locateEnvelopeIndex({\n envelopeIndexPath: this.config.envelopeIndexPath,\n mailRoot: this.config.mailRoot,\n accountDirectory,\n });\n return this.#located;\n }\n\n /**\n * Whether the composer can be reached, and which grant is missing if not.\n *\n * Reported by diagnostics rather than only discovered on a failed reply.\n * Automation-to-Mail and Full Disk Access being granted says nothing about\n * either of these, and every read tool works without them — so the only\n * signal used to be a `COMPOSER_NOT_FOUND` on a window that was\n * demonstrably on screen, with no way to tell which permission was at fault.\n *\n * Never throws. A probe that cannot answer must not be the reason\n * diagnostics fails, and \"unknown\" is an honest third state.\n */\n async composerAccess(): Promise<{\n accessibility: \"granted\" | \"denied\" | \"unknown\";\n systemEvents: \"granted\" | \"denied\" | \"notDetermined\" | \"error\" | \"unknown\";\n /**\n * Whether Mail's UI could actually be read, which is the only one of these\n * three that is evidence rather than a claim. The flag above answers for an\n * identity, and an identity can be ambiguous: one bundle id was measured\n * holding four Accessibility entries at once, with the app's own check and\n * its servers' checks matching different ones. `inconclusive` is Mail with\n * no windows open, where nothing can be concluded either way.\n */\n uiRead: \"granted\" | \"denied\" | \"inconclusive\" | \"unknown\";\n windows: (string | null)[] | null;\n }> {\n try {\n return await this.runner.run(COMPOSER_ACCESS);\n } catch {\n return {\n accessibility: \"unknown\",\n systemEvents: \"unknown\",\n uiRead: \"unknown\",\n windows: null,\n };\n }\n }\n\n /**\n * Can the NATIVE lane actually read Mail's windows, right now?\n *\n * The same principle `composerAccess` states for the System Events path, for\n * the same reason: `composerLane` above says which lane is configured, and\n * configured is a claim. This is the functional read, and when the two\n * disagree this is the one to believe.\n *\n * Null when there is no native lane, which is not a failure — see `#ax`.\n */\n async composerAxReach(): Promise<{ ok: boolean; windows: string[] | null } | null> {\n if (!this.#ax) return null;\n const reach = await this.#ax.reach();\n return { ok: reach.ok, windows: reach.windows };\n }\n\n async lanes(): Promise<LaneStatus> {\n /**\n * Probe twice before declaring the lane dead.\n *\n * The FIRST Apple Event a fresh process sends is what triggers the macOS\n * Automation prompt, and osascript can come back failed while the user is\n * still deciding. Reporting \"denied\" off that one attempt produced a\n * diagnostic that said automation was denied in the same breath as listing\n * four accounts it had just read over automation — which sends people to\n * fix a permission that was never the problem.\n */\n let applescript: LaneStatus[\"applescript\"] = \"unavailable\";\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n await this.accounts();\n applescript = \"live\";\n break;\n } catch {\n if (attempt === 0) await new Promise((r) => setTimeout(r, 400));\n }\n }\n\n if (this.config.indexMode === \"off\") {\n return { applescript, index: \"disabled\", indexReason: \"APPLE_MAIL_INDEX_MODE=off\" };\n }\n const index = await this.index();\n return {\n applescript,\n index: index ? \"live\" : \"unavailable\",\n indexReason: index ? null : (this.#indexError ?? (await this.locate()).reason),\n ...(index ? { indexMode: index.mode, schemaFingerprint: index.caps.fingerprint } : {}),\n };\n }\n\n async listMailboxes(opts: {\n accountUuids?: string[];\n withCounts: boolean;\n }): Promise<\n { accountUuid: string; accountName: string; name: string; unread?: number; total?: number }[]\n > {\n const accounts = await this.accounts();\n const allowed = opts.accountUuids?.length\n ? accounts.filter((a) => opts.accountUuids?.includes(a.id)).map((a) => a.id)\n : accounts.map((a) => a.id);\n return withBusyRetry(() =>\n this.runner.run(LIST_MAILBOXES, { accountUuids: allowed, withCounts: opts.withCounts }),\n );\n }\n\n async countMailbox(account: MailAccount, mailbox: string) {\n const name = this.mailboxes.resolveMailboxName(account, mailbox);\n return withBusyRetry(() =>\n this.runner.run<{\n accountUuid: string;\n mailbox: string;\n total: number | null;\n unread: number | null;\n }>(COUNT_MAILBOX, { accountUuid: account.id, mailbox: name }),\n );\n }\n\n /**\n * The degraded listing lane. Capped rather than paginated on purpose: each\n * extra message costs another ~42ms per property, so a \"just fetch 500\" call\n * is a 20-second call, and a limit the model can see beats a timeout it cannot.\n */\n async listRecent(\n account: MailAccount,\n mailbox: string,\n limit: number,\n ): Promise<{ mailbox: string; total: number; messages: MessageSummary[] }> {\n const name = this.mailboxes.resolveMailboxName(account, mailbox);\n const capped = Math.min(limit, this.config.degradedMaxMessages);\n const raw = await withBusyRetry(() =>\n this.runner.run<{\n mailbox: string;\n total: number;\n messages: (Omit<MessageSummary, \"ref\"> & MessageIdentity)[];\n }>(LIST_RECENT, { accountUuid: account.id, mailbox: name, limit: capped }),\n );\n return { ...raw, messages: raw.messages.map((m) => this.#withRef(m)) };\n }\n\n /** Resolve message ids inside one mailbox. This is the search-to-action bridge. */\n async getMessages(\n ref: { accountUuid: string; mailbox: string },\n ids: number[],\n opts: { withContent?: boolean; withSource?: boolean; withHeaders?: boolean } = {},\n ): Promise<MessageSummary[]> {\n const raw = await withBusyRetry(() =>\n this.runner.run<(Omit<MessageSummary, \"ref\"> & MessageIdentity & { found?: boolean })[]>(\n GET_MESSAGES,\n {\n accountUuid: ref.accountUuid,\n mailbox: ref.mailbox,\n ids,\n withContent: opts.withContent ?? false,\n withSource: opts.withSource ?? false,\n withHeaders: opts.withHeaders ?? false,\n },\n ),\n );\n return raw.filter((m) => m.found !== false).map((m) => this.#withRef(m));\n }\n\n // ── index lane ─────────────────────────────────────────────────────────────\n\n /**\n * Open the index on first use, once. A failure is remembered rather than\n * retried on every call: the usual cause is a missing permission, which will\n * not change until the user restarts the host app anyway.\n */\n async index(): Promise<EnvelopeIndex | null> {\n if (this.#indexTried) return this.#index;\n this.#indexTried = true;\n\n if (this.config.indexMode === \"off\") {\n this.#indexError = \"APPLE_MAIL_INDEX_MODE=off\";\n return null;\n }\n const located = await this.locate();\n if (!located.envelopeIndexPath) {\n this.#indexError = located.reason;\n return null;\n }\n try {\n this.#index = new EnvelopeIndex(\n openIndex(located.envelopeIndexPath, this.config.indexMode, this.#logger),\n );\n } catch (err) {\n this.#indexError = err instanceof Error ? err.message : String(err);\n this.#index = null;\n }\n return this.#index;\n }\n\n get indexError(): string | null {\n return this.#indexError;\n }\n\n /** How stale the index file is, so callers can see when they are reading history. */\n async indexAgeSeconds(): Promise<number | null> {\n const located = await this.locate();\n if (!located.mtime) return null;\n return Math.max(0, Math.round((Date.now() - Date.parse(located.mtime)) / 1000));\n }\n\n /**\n * Map index mailbox rows onto scriptable account/mailbox names.\n *\n * Three of the mailbox URLs on a real machine are `local://` (On My Mac) with\n * no account UUID in the host position, so entries that do not resolve are\n * dropped rather than guessed at.\n */\n async #mailboxLookup(): Promise<\n Map<number, { accountUuid: string; mailbox: string; url: string }>\n > {\n const index = await this.index();\n const map = new Map<number, { accountUuid: string; mailbox: string; url: string }>();\n if (!index) return map;\n for (const row of index.mailboxes()) {\n const resolved = await this.mailboxes.resolveIndexUrl(row.url);\n if (!resolved) continue;\n map.set(row.rowid, {\n accountUuid: resolved.account.id,\n mailbox: resolved.mailbox,\n url: row.url,\n });\n }\n return map;\n }\n\n /** Resolve account/mailbox filters down to the index rowids they cover. */\n async #targetMailboxRowids(opts: {\n account?: string | undefined;\n mailbox?: string | undefined;\n }): Promise<number[] | undefined> {\n if (!opts.account && !opts.mailbox) return undefined;\n const lookup = await this.#mailboxLookup();\n const account = opts.account ? await this.mailboxes.resolveAccount(opts.account) : null;\n const wanted = opts.mailbox\n ? account\n ? this.mailboxes.resolveMailboxName(account, opts.mailbox)\n : opts.mailbox\n : null;\n\n const rowids: number[] = [];\n for (const [rowid, entry] of lookup) {\n if (account && entry.accountUuid !== account.id) continue;\n if (wanted && entry.mailbox.toLowerCase() !== wanted.toLowerCase()) continue;\n rowids.push(rowid);\n }\n\n // An empty result is a REFUSAL, never a filter that quietly disappears.\n //\n // `#mailboxPredicate` used to read `[]` the same way it reads `undefined`,\n // so a scope that matched no index rowid widened the query to the whole\n // archive: a search of one mailbox returned other accounts' mail, and\n // count_messages reported the archive total for a single mailbox. The\n // trigger is ordinary — a `local://` mailbox the URL ladder could not\n // resolve, or an account whose rows have not been indexed yet.\n if (rowids.length === 0) {\n const known = [...lookup.values()]\n .filter((e) => !account || e.accountUuid === account.id)\n .map((e) => e.mailbox);\n const unique = [...new Set(known)].toSorted();\n throw new PreconditionError(\n `No mailbox matching ${JSON.stringify(opts.mailbox ?? \"\")}` +\n `${account ? ` in account ${JSON.stringify(account.name)}` : \"\"} is present in ` +\n `Mail's search index.` +\n (unique.length\n ? ` Indexed there: ${unique.slice(0, 20).join(\", \")}.`\n : \" That account has no indexed mailboxes at all.\"),\n );\n }\n return rowids;\n }\n\n /**\n * Aggregate matches instead of listing them.\n *\n * Same filters as `searchMessages`, same index — the difference is that the\n * counting happens in SQLite over the whole match set rather than in the\n * model's head over a page of it. Returns null on the same condition\n * `searchMessages` does, so callers keep one degradation path.\n */\n async groupMessages(\n opts: Omit<SearchFilters, \"mailboxRowids\" | \"offset\"> & {\n account?: string | undefined;\n mailbox?: string | undefined;\n },\n field: GroupField,\n ): Promise<\n | (GroupResult & {\n indexMode: string;\n indexAgeSeconds: number | null;\n walBlind: boolean;\n })\n | null\n > {\n const index = await this.index();\n if (!index) return null;\n\n const mailboxRowids = await this.#targetMailboxRowids(opts);\n const result = index.groupBy({ ...opts, ...(mailboxRowids ? { mailboxRowids } : {}) }, field);\n\n // The mailbox lane groups on a rowid, which is an internal handle. Resolve\n // it to the account/mailbox pair every other result speaks in, and only\n // then — a rowid that no longer resolves keeps its count rather than\n // vanishing from the totals.\n const groups =\n field === \"mailbox\"\n ? await (async () => {\n const lookup = await this.#mailboxLookup();\n return result.groups.map((g) => {\n const entry = g.key === null ? undefined : lookup.get(Number(g.key));\n return entry\n ? { ...g, key: entry.mailbox, label: entry.accountUuid }\n : { ...g, label: g.label ?? null };\n });\n })()\n : result.groups;\n\n return {\n ...result,\n groups,\n indexMode: index.mode,\n indexAgeSeconds: await this.indexAgeSeconds(),\n walBlind: index.mode === \"immutable\",\n };\n }\n\n async searchMessages(\n opts: Omit<SearchFilters, \"mailboxRowids\"> & {\n account?: string | undefined;\n mailbox?: string | undefined;\n /** Free text matched against message BODIES. See body-scan.ts. */\n body?: string | undefined;\n },\n ): Promise<{\n messages: MessageSummary[];\n source: \"index\" | \"index+body-scan\";\n indexMode: string;\n indexAgeSeconds: number | null;\n walBlind: boolean;\n bodyScan?: BodyScanReport;\n } | null> {\n const index = await this.index();\n if (!index) return null;\n\n const mailboxRowids = await this.#targetMailboxRowids(opts);\n const lookup = await this.#mailboxLookup();\n const scoped = { ...opts, ...(mailboxRowids ? { mailboxRowids } : {}) };\n\n const common = {\n indexMode: index.mode,\n indexAgeSeconds: await this.indexAgeSeconds(),\n // immutable=1 cannot see the -wal, so results may lag reality.\n walBlind: index.mode === \"immutable\",\n };\n\n if (!opts.body) {\n const rows = index.search(scoped);\n return {\n messages: rows\n .map((r) => this.#rowToSummary(r, lookup))\n .filter((m): m is MessageSummary => m !== null),\n source: \"index\" as const,\n ...common,\n };\n }\n\n /*\n * The body lane. The index narrows, the scan reads only the survivors.\n *\n * Candidates are fetched WITHOUT the caller's limit and offset, because\n * those bound the answer and this needs to bound the work: paging into\n * results that have not been filtered yet would silently drop matches\n * sitting past the first page. One row over the ceiling is enough to know\n * the set is too wide, so ask for exactly that many.\n */\n const bound = this.config.bodyScanMax;\n const candidateRows = index.search({ ...scoped, limit: bound + 1, offset: 0 });\n\n const byUrl = new Map([...lookup.values()].map((e) => [e.url, e]));\n const accounts = await this.mailboxes.accounts();\n const dirOf = new Map(accounts.map((a) => [a.id, a.directory]));\n const placeOf = new Map<number, { accountUuid: string; mailbox: string }>();\n for (const row of candidateRows) {\n const entry = byUrl.get(row.mailboxUrl);\n if (entry) placeOf.set(row.rowid, entry);\n }\n\n const outcome = scanBodies({\n candidates: candidateRows.map((r) => r.rowid),\n term: opts.body,\n bound,\n maxBytes: this.config.bodyScanBytes,\n locate: (rowid) => {\n const place = placeOf.get(rowid);\n const directory = place ? dirOf.get(place.accountUuid) : null;\n if (!place || !directory) return null;\n try {\n const found = lookupEmlx({\n accountDirectory: directory,\n mailbox: place.mailbox,\n rowid,\n });\n return found.found ? found.path : null;\n } catch {\n // lookupEmlx swallows its own I/O errors; anything reaching here is\n // one bad candidate, and one bad candidate must not take out a query\n // over two thousand of them.\n return null;\n }\n },\n });\n\n if (outcome.status === \"over-bound\") {\n return {\n messages: [],\n source: \"index+body-scan\" as const,\n ...common,\n bodyScan: {\n status: \"over-bound\",\n candidates: outcome.candidates,\n bound: outcome.bound,\n },\n };\n }\n\n const hits = new Set(outcome.matched);\n const matchedRows = candidateRows.filter((r) => hits.has(r.rowid));\n const paged = matchedRows.slice(opts.offset, opts.offset + opts.limit);\n\n return {\n messages: paged\n .map((r) => this.#rowToSummary(r, lookup))\n .filter((m): m is MessageSummary => m !== null),\n source: \"index+body-scan\" as const,\n ...common,\n bodyScan: {\n status: \"ok\",\n candidates: outcome.candidates,\n scanned: outcome.scanned,\n matched: matchedRows.length,\n unreadable: outcome.unreadable,\n elapsedMs: outcome.elapsedMs,\n bound,\n },\n };\n }\n\n async threadOf(ref: string, limit: number): Promise<MessageSummary[] | null> {\n const index = await this.index();\n if (!index) return null;\n const decoded = decodeRef(ref);\n const conversationId = index.conversationOf(decoded.id);\n if (conversationId === null) return [];\n const lookup = await this.#mailboxLookup();\n return index\n .thread(conversationId, limit)\n .map((r) => this.#rowToSummary(r, lookup))\n .filter((m): m is MessageSummary => m !== null);\n }\n\n async countViaIndex(opts: {\n account?: string | undefined;\n mailbox?: string | undefined;\n }): Promise<{ total: number; unread: number } | null> {\n const index = await this.index();\n if (!index) return null;\n const mailboxRowids = await this.#targetMailboxRowids(opts);\n return index.count(mailboxRowids ? { mailboxRowids } : {});\n }\n\n #rowToSummary(\n row: MessageRow,\n lookup: Map<number, { accountUuid: string; mailbox: string; url: string }>,\n ): MessageSummary | null {\n const entry = [...lookup.values()].find((e) => e.url === row.mailboxUrl);\n if (!entry) return null;\n const sender = row.senderName\n ? `${row.senderName} <${row.senderAddress ?? \"\"}>`\n : (row.senderAddress ?? null);\n return {\n ref: encodeRef({ accountUuid: entry.accountUuid, mailbox: entry.mailbox, id: row.rowid }),\n subject: row.subject,\n sender,\n dateReceived: row.dateReceived,\n dateSent: row.dateSent,\n read: row.read,\n flagged: row.flagged,\n size: row.size,\n };\n }\n\n // ── body lane ──────────────────────────────────────────────────────────────\n\n /**\n * Read a message body.\n *\n * Preferred path is the `.emlx` file on disk, which is instant and gives us\n * the real MIME structure. Falls back to asking Mail for `content` (~250ms),\n * which also covers accounts whose message caching keeps headers only — so a\n * missing file is a slow answer, not a failure.\n */\n async getMessageBody(\n ref: string,\n opts: { maxBodyBytes?: number } = {},\n ): Promise<{\n message: MessageSummary;\n parsed: ParsedMessage | null;\n source: \"emlx\" | \"applescript\";\n /** Why the file lane was not used. Present only when it was not. */\n fallbackReason?: string;\n }> {\n const decoded = decodeRef(ref);\n const located = await this.#lookupMessageFile(decoded);\n\n if (located.found) {\n const parsed = readEmlx(located.path, {\n maxBodyBytes: opts.maxBodyBytes ?? this.config.bodyMaxBytes,\n partial: located.partial,\n rowid: decoded.id,\n });\n const [summary] = await this.getMessages(decoded, [decoded.id]);\n if (summary) return { message: summary, parsed, source: \"emlx\" };\n }\n\n const [summary] = await this.getMessages(decoded, [decoded.id], { withContent: true });\n if (!summary) throw new MessageNotFoundError(ref);\n return {\n message: summary,\n parsed: null,\n source: \"applescript\",\n fallbackReason: located.found\n ? \"The message file was read, but Mail did not return a summary for it.\"\n : located.explain,\n };\n }\n\n async getMessageSource(\n ref: string,\n opts: { offset: number; maxBytes: number },\n ): Promise<{\n source: string;\n totalBytes: number | null;\n truncated: boolean;\n via: \"emlx\" | \"applescript\";\n fallbackReason?: string;\n }> {\n const decoded = decodeRef(ref);\n const located = await this.#lookupMessageFile(decoded);\n if (located.found) {\n return { ...readEmlxSource(located.path, opts), via: \"emlx\" };\n }\n const [summary] = await this.getMessages(decoded, [decoded.id], { withSource: true });\n if (!summary) throw new MessageNotFoundError(ref);\n const full = summary.source ?? \"\";\n const slice = full.slice(opts.offset, opts.offset + opts.maxBytes);\n return {\n source: slice,\n totalBytes: full.length,\n truncated: opts.offset + slice.length < full.length,\n via: \"applescript\",\n ...(located.found ? {} : { fallbackReason: located.explain }),\n };\n }\n\n /**\n * Look for a message's `.emlx`, keeping the reason it was not found.\n *\n * The reason is the point. This lane degrades silently by design — the\n * AppleScript fallback answers most questions — so a lookup that fails for\n * the WRONG reason (a mailbox path we derived incorrectly, say) is invisible\n * and stays invisible. Every caller that reports a degraded read now has the\n * evidence to say which of \"no permission\", \"not cached\", and \"no such path\"\n * it actually was.\n */\n async #lookupMessageFile(ref: MessageRef): Promise<MessageFileLookup> {\n const accounts = await this.accounts();\n const account = accounts.find((a) => a.id === ref.accountUuid);\n if (!account) {\n return { found: false, explain: `No account with id ${ref.accountUuid} is visible.` };\n }\n if (!account.directory) {\n return {\n found: false,\n explain: `Mail did not report an on-disk directory for account \"${account.name}\".`,\n };\n }\n let lookup: EmlxLookup;\n try {\n lookup = lookupEmlx({\n accountDirectory: account.directory,\n mailbox: ref.mailbox,\n rowid: ref.id,\n });\n } catch (err) {\n // Unexpected: lookupEmlx swallows its own I/O errors. The AppleScript\n // fallback still works, so this is not worth failing the call over.\n return { found: false, explain: err instanceof Error ? err.message : String(err) };\n }\n if (lookup.found) return { found: true, path: lookup.path, partial: lookup.partial };\n return {\n found: false,\n lookup,\n explain: await this.#explainMissingFile(account, ref, lookup),\n };\n }\n\n /**\n * One truthful sentence about why there is no message file.\n *\n * Written because the old text said \"Grant Full Disk Access and restart the\n * host app\" unconditionally, which sent people to fix a permission that was\n * already granted while the real cause — a mailbox nested under\n * `[Gmail].mbox/` that the flat path join never found — went unmentioned.\n */\n async #explainMissingFile(\n account: MailAccount,\n ref: MessageRef,\n lookup: Extract<EmlxLookup, { found: false }>,\n ): Promise<string> {\n if (lookup.reason === \"permission\") return FDA_HINT;\n\n const probed = lookup.probed.slice(0, 3).join(\", \");\n\n if (lookup.reason === \"no-mailbox-dir\") {\n // Nothing resolved and no EPERM. If we also cannot read the index, a\n // blanket TCC denial is still the likeliest story; otherwise the path is\n // simply wrong, and saying \"grant Full Disk Access\" would be a lie.\n if (!(await this.locate()).readable) return FDA_HINT;\n return (\n `Full Disk Access is granted, but no mailbox directory for \"${ref.mailbox}\" was found ` +\n `under ${account.directory}. Probed: ${probed}.`\n );\n }\n\n /*\n * `no-message-file` means the mailbox directory was listed successfully, so\n * we demonstrably have read access to the mail store. Permission is settled\n * by that evidence and must not be blamed here — not even when the Envelope\n * Index is unreadable for its own reasons.\n */\n const cachesBodies = /all messages/i.test(account.messageCaching ?? \"\");\n if (!cachesBodies) {\n return (\n `The mailbox directory was found, but message ${ref.id} has no file on disk. Account ` +\n `\"${account.name}\" caches \"${account.messageCaching ?? \"unknown\"}\", so bodies may not be ` +\n `stored locally. Opening the message in Mail downloads it.`\n );\n }\n return (\n `The mailbox directory was found and is readable, but no file for message ${ref.id} exists ` +\n `under ${lookup.mailboxDirs.slice(0, 2).join(\", \")}. Probed: ${probed}.`\n );\n }\n\n /**\n * Walk the message-file lane end to end, per account, and report what broke.\n *\n * This exists because the lane fails silently by construction: every reader\n * falls back to AppleScript, so a lane that has been dead for months looks\n * like a lane that is merely slow. Diagnostics reporting\n * `fullDiskAccess: granted` beside a lane where every file read fails is the\n * misleading part, and this is what replaces the guess with a probe.\n *\n * Deliberately per-account: the failure that motivated it was an account-level\n * layout difference (Gmail nesting its mailboxes under `[Gmail].mbox/`), so a\n * single-account probe would have reported a healthy lane.\n */\n async probeMessageFile(): Promise<\n {\n account: string;\n accountUuid: string;\n status: \"ok\" | \"unreachable\" | \"headers-only\" | \"not-probed\";\n mailbox?: string;\n rowid?: number;\n path?: string;\n reason?: string;\n probed?: string[];\n }[]\n > {\n let accounts: MailAccount[];\n try {\n accounts = await this.accounts();\n } catch (err) {\n this.#logger?.debug?.(\"probeMessageFile: no account list\", err);\n return [];\n }\n\n const index = await this.index();\n // No index means no cheap way to name a real message. Firing an Apple Event\n // per account to find one would make diagnostics slower precisely when the\n // index lane is already telling the user what to fix, so we say so instead.\n const noIndex = index\n ? null\n : (this.#indexError ?? (await this.locate()).reason ?? \"the search index is unavailable\");\n\n const results = [];\n for (const account of accounts) {\n const base = { account: account.name, accountUuid: account.id };\n if (!account.directory) {\n results.push({\n ...base,\n status: \"not-probed\" as const,\n reason: \"Mail did not report an on-disk directory for this account.\",\n });\n continue;\n }\n if (!index) {\n results.push({ ...base, status: \"not-probed\" as const, reason: noIndex ?? undefined });\n continue;\n }\n\n const sample = this.#sampleMessage(index, account);\n if (!sample) {\n results.push({\n ...base,\n status: \"not-probed\" as const,\n reason: \"The search index holds no message for this account.\",\n });\n continue;\n }\n\n const lookup = lookupEmlx({\n accountDirectory: account.directory,\n mailbox: sample.mailbox,\n rowid: sample.rowid,\n });\n const located = { ...base, mailbox: sample.mailbox, rowid: sample.rowid };\n\n if (lookup.found) {\n // Stat is not enough: it SUCCEEDS on a TCC-protected file, so a lane\n // with no read permission would report `ok`. Read a byte instead.\n try {\n const fd = openSync(lookup.path, \"r\");\n try {\n readSync(fd, Buffer.alloc(1), 0, 1, 0);\n } finally {\n closeSync(fd);\n }\n results.push({ ...located, status: \"ok\" as const, path: lookup.path });\n } catch (err) {\n results.push({\n ...located,\n status: \"unreachable\" as const,\n path: lookup.path,\n reason: `The message file exists but could not be read: ${\n err instanceof Error ? err.message : String(err)\n }`,\n });\n }\n continue;\n }\n\n const cachesBodies = /all messages/i.test(account.messageCaching ?? \"\");\n results.push({\n ...located,\n status:\n lookup.reason === \"no-message-file\" && !cachesBodies\n ? (\"headers-only\" as const)\n : (\"unreachable\" as const),\n reason: lookup.reason,\n probed: lookup.probed.slice(0, 3),\n });\n }\n return results;\n }\n\n /** Cheapest real (mailbox, rowid) pair for an account, straight from the index. */\n #sampleMessage(\n index: EnvelopeIndex,\n account: MailAccount,\n ): { mailbox: string; rowid: number } | null {\n const owned = index.mailboxes().filter((m) => {\n const host = /^[a-z-]+:\\/\\/([^/]*)/i.exec(m.url)?.[1];\n return host && decodeURIComponent(host) === account.id;\n });\n if (owned.length === 0) return null;\n\n const [row] = index.search({ mailboxRowids: owned.map((m) => m.rowid), limit: 1, offset: 0 });\n if (!row) return null;\n\n const path = decodeURIComponent(/^[a-z-]+:\\/\\/[^/]*\\/?(.*)$/i.exec(row.mailboxUrl)?.[1] ?? \"\");\n if (!path) return null;\n try {\n return { mailbox: this.mailboxes.resolveMailboxName(account, path), rowid: row.rowid };\n } catch {\n // The index knows a mailbox Mail does not list. Probe the raw path — that\n // is exactly the sort of mismatch this probe should surface, not hide.\n return { mailbox: path, rowid: row.rowid };\n }\n }\n\n /**\n * Save one attachment into the configured directory.\n *\n * The destination is resolved and then checked to be inside\n * `APPLE_MAIL_ATTACHMENT_DIR`, so a filename of `../../.ssh/authorized_keys`\n * lands nowhere. Existing files are never overwritten.\n */\n async saveAttachment(\n ref: string,\n filename: string,\n opts: { overwrite?: boolean } = {},\n ): Promise<{ path: string; bytes: number; from: \"inline\" | \"sidecar\" }> {\n const decoded = decodeRef(ref);\n const located = await this.#lookupMessageFile(decoded);\n if (!located.found) {\n throw new PreconditionError(\n `The message file was not found, so its attachments are not reachable. ${located.explain}`,\n { probed: located.lookup?.probed.slice(0, 3) ?? [] },\n );\n }\n\n // The path is settled BEFORE the attachment is extracted. Extraction parses\n // the whole message file and may walk the sidecar tree, and doing that first\n // meant a refusal — a traversal attempt, or a destination already taken —\n // was paid for with all of that work. Order the cheap refusal first.\n const root = resolve(this.config.attachmentDir);\n // basename() first: the filename comes from message content, which is\n // attacker-controlled in exactly the way path traversal needs.\n const target = resolve(join(root, basename(filename)));\n if (target !== join(root, basename(filename)) || !target.startsWith(root + sep)) {\n throw new PreconditionError(\n `Refusing to write outside ${root}. Set APPLE_MAIL_ATTACHMENT_DIR to change the destination.`,\n );\n }\n\n const { bytes, from } = extractAttachment(located.path, filename, decoded.id);\n\n mkdirSync(root, { recursive: true });\n // `wx` rather than existsSync-then-write. The check and the write were two\n // steps with a window between them, so a file appearing in that window was\n // overwritten by a call that had already decided it would not overwrite\n // anything. The flag makes the refusal the file system's job, and atomic.\n try {\n writeFileSync(target, bytes, { mode: 0o600, flag: opts.overwrite ? \"w\" : \"wx\" });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n throw new PreconditionError(`${target} already exists; refusing to overwrite it.`);\n }\n throw err;\n }\n return { path: target, bytes: bytes.length, from };\n }\n\n // ── write lane ─────────────────────────────────────────────────────────────\n // Every mutation reports the state Mail re-read after the change. Verifying a\n // write against the search index instead would race Mail's own update of it.\n\n /** Set flags across refs, one Apple Event per distinct mailbox. */\n async setFlags(\n refs: string[],\n flags: { read?: boolean; flagged?: boolean; flagIndex?: number; junk?: boolean },\n ): Promise<{ changed: number; failed: number; results: unknown[] }> {\n const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));\n const results: unknown[] = [];\n let changed = 0;\n let failed = 0;\n\n for (const [, group] of groups) {\n const first = group[0];\n if (!first) continue;\n const res = await withBusyRetry(() =>\n this.runner.run<{ mailbox: string; results: { id: number; ok: boolean }[] }>(SET_FLAGS, {\n accountUuid: first.accountUuid,\n mailbox: first.mailbox,\n ids: group.map((r) => r.id),\n ...flags,\n }),\n );\n for (const r of res.results) {\n if (r.ok) changed += 1;\n else failed += 1;\n results.push({\n ref: encodeRef({ accountUuid: first.accountUuid, mailbox: first.mailbox, id: r.id }),\n ...r,\n });\n }\n }\n return { changed, failed, results };\n }\n\n async moveMessages(\n refs: string[],\n opts: { destinationMailbox: string; destinationAccount?: string },\n ): Promise<{ moved: number; failed: number; destination: string; results: unknown[] }> {\n const destAccount = opts.destinationAccount\n ? await this.mailboxes.resolveAccount(opts.destinationAccount)\n : null;\n const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));\n const results: unknown[] = [];\n let moved = 0;\n let failed = 0;\n let destination = opts.destinationMailbox;\n\n for (const [, group] of groups) {\n const first = group[0];\n if (!first) continue;\n const res = await withBusyRetry(() =>\n this.runner.run<{\n destination: string;\n destinationAccountUuid: string;\n results: { id: number; ok: boolean; newId: number | null }[];\n }>(MOVE_MESSAGES, {\n accountUuid: first.accountUuid,\n mailbox: first.mailbox,\n ids: group.map((r) => r.id),\n destMailbox: opts.destinationMailbox,\n destAccountUuid: destAccount?.id ?? null,\n }),\n );\n destination = res.destination;\n for (const r of res.results) {\n if (r.ok) moved += 1;\n else failed += 1;\n results.push({\n previousRef: encodeRef({\n accountUuid: first.accountUuid,\n mailbox: first.mailbox,\n id: r.id,\n }),\n // A moved message has a new row id, so the old ref is dead. Null here\n // means Mail moved it but we could not re-locate it by Message-ID.\n ref:\n r.ok && r.newId\n ? encodeRef({\n accountUuid: res.destinationAccountUuid || first.accountUuid,\n mailbox: res.destination,\n id: r.newId,\n })\n : null,\n ...r,\n });\n }\n }\n return { moved, failed, destination, results };\n }\n\n async deleteMessages(refs: string[]): Promise<{\n deleted: number;\n failed: number;\n movedToTrash: boolean | null;\n results: unknown[];\n }> {\n const groups = groupRefsByMailbox(refs.map((r) => decodeRef(r)));\n const results: unknown[] = [];\n let deleted = 0;\n let failed = 0;\n let movedToTrash: boolean | null = null;\n\n for (const [, group] of groups) {\n const first = group[0];\n if (!first) continue;\n const res = await withBusyRetry(() =>\n this.runner.run<{ movedToTrash: boolean | null; results: { id: number; ok: boolean }[] }>(\n DELETE_MESSAGES,\n { accountUuid: first.accountUuid, mailbox: first.mailbox, ids: group.map((r) => r.id) },\n ),\n );\n movedToTrash = res.movedToTrash;\n for (const r of res.results) {\n if (r.ok) deleted += 1;\n else failed += 1;\n results.push(r);\n }\n }\n return { deleted, failed, movedToTrash, results };\n }\n\n /**\n * Create a mailbox.\n *\n * ## Why the cache is dropped afterwards\n *\n * `MailboxMap` caches each account together with its mailbox NAMES, and\n * `resolveMailboxName` answers out of that cache. A mailbox created here and\n * used as a move destination in the next call would resolve against a list\n * taken before it existed, so the move would fail with \"no destination\n * mailbox\" naming a mailbox this server had just made. Invalidating is not an\n * optimisation detail; it is what makes create-then-move work.\n */\n async createMailbox(\n name: string,\n account?: string,\n ): Promise<{\n created: boolean;\n name: string;\n account: string | null;\n accountUuid: string | null;\n note?: string;\n }> {\n const trimmed = name.trim();\n if (!trimmed) {\n throw new PreconditionError(\"A mailbox name cannot be empty or only whitespace.\");\n }\n /*\n * Mail reads \"/\" as the hierarchy separator, so an empty segment asks for a\n * mailbox with no name somewhere in the path. Mail's own answer to that is\n * inconsistent across account types — sometimes a silent no-op, sometimes a\n * mailbox that cannot be selected — and neither is something the caller can\n * clean up from here.\n */\n if (trimmed.split(\"/\").some((segment) => segment.trim() === \"\")) {\n throw new PreconditionError(\n `\"${name}\" has an empty path segment. \"/\" separates levels, so a name may not start or ` +\n 'end with it, e.g. \"Projects/Cupertino\".',\n );\n }\n\n const resolved = account ? await this.mailboxes.resolveAccount(account) : null;\n const result = await withBusyRetry(() =>\n this.runner.run<{\n created: boolean;\n name: string;\n account: string | null;\n accountUuid: string | null;\n note?: string;\n }>(CREATE_MAILBOX, {\n name: trimmed,\n accountUuid: resolved?.id ?? null,\n }),\n );\n this.mailboxes.invalidate();\n return result;\n }\n\n /**\n * Replace a saved draft's body by recreating it.\n *\n * The refusals live in the script, next to the properties they are read from,\n * and come back as ordinary results carrying `replaced: false` rather than as\n * thrown errors — a caller that cannot rewrite this draft still wants to know\n * WHY, and what to do instead, and both travel better as data than as a\n * message string.\n *\n * What is enforced here instead is the shape of the request, before Mail is\n * touched at all: an empty body would silently blank a draft the user wrote,\n * which is the one outcome nothing downstream could distinguish from success.\n */\n async updateDraft(\n ref: string,\n opts: { body: string; subject?: string | undefined },\n ): Promise<Record<string, unknown>> {\n if (!opts.body.trim()) {\n throw new PreconditionError(\n \"A replacement body cannot be empty. Blanking a draft and reporting success is \" +\n \"indistinguishable from having written it, so it is refused here rather than done. \" +\n \"Delete the draft with apple_mail_delete_messages if that is what you meant.\",\n );\n }\n const decoded = decodeRef(ref);\n return withBusyRetry(() =>\n this.runner.run<Record<string, unknown>>(UPDATE_DRAFT, {\n accountUuid: decoded.accountUuid,\n mailbox: decoded.mailbox,\n id: decoded.id,\n body: opts.body,\n subject: opts.subject ?? null,\n }),\n );\n }\n\n async checkForNewMail(account?: string): Promise<unknown> {\n const resolved = account ? await this.mailboxes.resolveAccount(account) : null;\n return this.runner.run(CHECK_FOR_NEW_MAIL, { accountUuid: resolved?.id ?? null });\n }\n\n async sendMessage(opts: {\n account?: string;\n to: string[];\n cc: string[];\n bcc: string[];\n subject: string;\n body: string;\n sendNow: boolean;\n }): Promise<unknown> {\n const account = opts.account ? await this.mailboxes.resolveAccount(opts.account) : null;\n return this.runner.run(SEND_MESSAGE, {\n senderAddress: account?.emailAddresses[0] ?? null,\n to: opts.to,\n cc: opts.cc,\n bcc: opts.bcc,\n subject: opts.subject,\n body: opts.body,\n sendNow: opts.sendNow,\n });\n }\n\n async replyOrForward(\n ref: string,\n opts: {\n mode: \"reply\" | \"forward\";\n body?: string;\n to?: string[];\n replyToAll?: boolean;\n sendNow: boolean;\n },\n ): Promise<unknown> {\n const decoded = decodeRef(ref);\n const params = {\n accountUuid: decoded.accountUuid,\n mailbox: decoded.mailbox,\n id: decoded.id,\n mode: opts.mode,\n body: opts.body ?? null,\n to: opts.to ?? [],\n replyToAll: opts.replyToAll ?? false,\n sendNow: opts.sendNow,\n };\n // The native lane when the app is hosting this server, and the System Events\n // one otherwise. Both are kept because the npm packages are published\n // artifacts that have to work with no Cupertino on the machine — the\n // difference a person sees is that the native path needs ONE grant where\n // the other needs two.\n if (this.#ax) return replyOrForwardNatively(this.#ax, this.runner, params);\n return this.runner.run(REPLY_OR_FORWARD, params);\n }\n\n #withRef(m: Omit<MessageSummary, \"ref\"> & MessageIdentity): MessageSummary {\n const { id, accountUuid, mailbox, ...rest } = m;\n return { ...rest, ref: encodeRef({ accountUuid, mailbox, id }) };\n }\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport {\n BaseConfigSchema,\n parseBool,\n parseConfig,\n parseIntOpt,\n parseList,\n trimmed,\n} from \"@mgcrea/mcp-apple-core\";\nimport { z } from \"zod\";\n\n/**\n * Configuration is environment-only. The sibling servers that also read a\n * `~/.config/<service>/config.json` do so because they hold a private key or an\n * OAuth token; this server holds no secret at all — its access comes from macOS\n * permissions granted to the host process — so a second config source would be\n * machinery without a job.\n */\n/**\n * `allowWrites`, `debug`, `osascriptPath`, `osascriptTimeoutMs` and `maxResults`\n * come from `BaseConfigSchema` — every Apple-app server has them, with the same\n * bounds and the same defaults.\n */\nconst ConfigSchema = BaseConfigSchema.extend({\n /**\n * Account allowlist (names or UUIDs). Empty means every account.\n *\n * `allowWrites` gates mutation, but the larger blast radius here is *reading*\n * a person's entire mail archive. This is the read-side control, and it is\n * enforced in exactly one place (mailbox-map) so no query path can escape it.\n */\n accounts: z.array(z.string().min(1)).default([]),\n /** Override the Mail data root. Normally discovered from Mail itself. */\n mailRoot: z.string().optional(),\n /** Explicit Envelope Index path. Bypasses discovery — used by tests and forensic copies. */\n envelopeIndexPath: z.string().optional(),\n indexMode: z.enum([\"auto\", \"ro\", \"immutable\", \"off\"]).default(\"auto\"),\n /** Cap for the AppleScript listing lane: ~130ms + 42ms per message per property. */\n degradedMaxMessages: z.number().int().min(1).max(200).default(50),\n bodyMaxBytes: z.number().int().min(1_024).max(10_000_000).default(262_144),\n /**\n * The declared bound on a body search, in candidate messages.\n *\n * Body search has no index behind it — the Spotlight volume index does not\n * reach `~/Library` at all, so there is nothing to query. What there is\n * instead is the Envelope Index narrowing a query to its survivors and the\n * scan reading only those. Cost is therefore linear in survivors, measured at\n * 0.48 ms per message warm: 100 candidates is 48 ms, 2,000 is under a second,\n * and the whole 182k store is 88 seconds — the Apple Events wall again.\n *\n * 2,000 is where an interactive answer stops being interactive. Over it the\n * search returns `degraded` naming the count and the bound rather than\n * scanning a truncated prefix, which is the failure this default exists to\n * avoid: a silent cap answers \"not found\" for older mail indistinguishably\n * from a real absence. See docs/mail-body.md.\n */\n bodyScanMax: z.number().int().min(1).max(50_000).default(2_000),\n /**\n * How much of each candidate file the scan reads. 79% of a mail store's bytes\n * are base64 that no text search matches, and MIME puts the text parts first.\n */\n bodyScanBytes: z.number().int().min(1_024).max(1_000_000).default(65_536),\n /**\n * The only directory save_attachment may write into. Enforced lexically with\n * `resolve()` + `basename()`, not `realpath()`: the destination may not exist\n * yet, and the filename — not the directory — is the attacker-controlled part.\n */\n attachmentDir: z.string().default(join(homedir(), \"Downloads\")),\n mailboxCacheTtlMs: z.number().int().min(0).max(3_600_000).default(60_000),\n}).strict();\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/**\n * `env` is a parameter with a default so tests are hermetic — they pass their\n * own object rather than mutating (and having to restore) process.env.\n */\nexport const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => {\n const raw = {\n allowWrites: parseBool(env.APPLE_MAIL_ALLOW_WRITES),\n exposePrompts: parseBool(env.APPLE_MAIL_EXPOSE_PROMPTS),\n lazyTools: parseBool(env.APPLE_MAIL_LAZY_TOOLS),\n debug: parseBool(env.APPLE_MAIL_DEBUG),\n accounts: parseList(env.APPLE_MAIL_ACCOUNTS),\n mailRoot: trimmed(env.APPLE_MAIL_ROOT),\n envelopeIndexPath: trimmed(env.APPLE_MAIL_ENVELOPE_INDEX),\n indexMode: trimmed(env.APPLE_MAIL_INDEX_MODE),\n osascriptPath: trimmed(env.APPLE_MAIL_OSASCRIPT_PATH),\n osascriptTimeoutMs: parseIntOpt(env.APPLE_MAIL_OSASCRIPT_TIMEOUT_MS),\n maxResults: parseIntOpt(env.APPLE_MAIL_MAX_RESULTS),\n degradedMaxMessages: parseIntOpt(env.APPLE_MAIL_DEGRADED_MAX_MESSAGES),\n bodyMaxBytes: parseIntOpt(env.APPLE_MAIL_BODY_MAX_BYTES),\n bodyScanMax: parseIntOpt(env.APPLE_MAIL_BODY_SCAN_MAX),\n bodyScanBytes: parseIntOpt(env.APPLE_MAIL_BODY_SCAN_BYTES),\n attachmentDir: trimmed(env.APPLE_MAIL_ATTACHMENT_DIR),\n mailboxCacheTtlMs: parseIntOpt(env.APPLE_MAIL_MAILBOX_CACHE_TTL_MS),\n };\n\n return parseConfig(ConfigSchema, raw);\n};\n","/**\n * The Mail operating manual, served as `cupertino://mail/guide` and embedded\n * ahead of every Mail prompt.\n *\n * It is deliberately static. Everything else this server exposes depends on a\n * permission, a running Mail or a readable index, and can therefore fail at the\n * exact moment someone needs to understand what is happening. This cannot: it\n * is a string in the bundle, so a completely denied server still explains\n * itself. What it must never contain, in exchange, is anything only a probe\n * could know — no account names, no counts, no permission verdicts. Those live\n * in `cupertino://mail/diagnostics`, which is allowed to fail.\n */\nexport const MAIL_GUIDE = `# Apple Mail — how to drive this server\n\n## Refs are opaque\n\nEvery message comes back with a \\`ref\\` like \\`m1:<accountUuid>/<mailbox>#<id>\\`.\nPass it back verbatim. Do not build one, parse one, or carry one across\nsurfaces — a Mail ref means nothing to Notes or Calendar.\n\n## Which tool, under which constraint\n\n- **Any filter at all** — sender, subject, date bound, unread, attachments —\n is \\`apple_mail_search_messages\\`. It reads Mail's own index, so it stays fast\n across a six-figure archive.\n- **\\`apple_mail_list_messages\\`** is a capped listing of one mailbox in date\n order. It is the fallback when the index is unreadable, not the default.\n- **Body text** is the \\`body\\` argument of the search tool, and it is the one\n expensive path here: macOS has no body index, so it opens the message files\n of whatever the other filters leave. Always combine it with a narrowing\n filter (mailbox, sender, \\`dateFrom\\`).\n- **A conversation** is \\`apple_mail_get_thread\\`, not several \\`get_message\\`\n calls.\n- **Counts** are \\`apple_mail_count_messages\\`. Do not count by paging a search.\n\n## \\`degraded: true\\` is not an empty result\n\nTwo failures look identical from the outside and must never be reported the\nsame way:\n\n- \\`degraded: true\\` with \\`capability: \"search-index\"\\` means the index could not\n be read — usually Full Disk Access. **Nothing was searched.**\n- \\`degraded: true\\` with \\`capability: \"body-scan\"\\` means the other filters left\n more messages than the scan bound allows, so **nothing was scanned**. Narrow\n and retry; do not report it as \"no matches\".\n\nSay \"I could not check\" for both. Reporting either as \"I found nothing\" is the\nworst thing this server can be made to do, because it is indistinguishable from\na real answer and quietly wrong.\n\nMailbox \\`unread\\` from the AppleScript lane is Mail's cached badge value and can\ndisagree with the truth — 0 has been observed for a mailbox holding 1618 unread\nmessages. Prefer the index; results are labelled with their source.\n\n## Writes\n\nMutating tools are registered only when writes are enabled. If you cannot see\n\\`apple_mail_send_message\\`, writes are off — say so rather than describing a\ndraft you could not create.\n\nWhen they are on, \\`sendNow\\` defaults to **false** on all three compose tools:\nthey open a draft in Mail for a human to review. That default is the safety\nproperty, so do not set \\`sendNow: true\\` to be helpful.\n\nOne trap: \\`apple_mail_reply_to_message\\` and \\`apple_mail_forward_message\\` called\nwithout a \\`body\\` leave an **empty** draft with the original quoted beneath.\nThat is a blank page, not a written reply. Fill the body, or tell the user\nplainly that the draft is empty.\n`;\n","import {\n promptArg,\n registerWorkflowPrompt,\n requiredPromptArg,\n type PromptContext,\n} from \"@mgcrea/mcp-apple-core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { MAIL_GUIDE } from \"./guide.js\";\n\nconst CTX: PromptContext = { surface: \"mail\", guide: MAIL_GUIDE };\n\n/**\n * Mail's workflow prompts.\n *\n * Each one exists because the ordering it encodes is not a property of any\n * single tool, so no tool description can hold it: triage is \"search, never\n * page\"; finding a thread is \"cheap filters before the expensive body lane\";\n * replying is \"read the thread first, and a body-less reply tool leaves a blank\n * page\". All three are rebuilt from scratch by every model in every session\n * otherwise.\n */\nexport const registerPrompts = (server: McpServer, allowWrites: boolean): void => {\n registerWorkflowPrompt(server, CTX, {\n name: \"apple_mail_triage\",\n title: \"Triage a mailbox\",\n description:\n \"Work through what arrived and report what needs a human: who is waiting, what is \" +\n \"committed to, what can be ignored. Read-only — it proposes, it does not file or reply.\",\n argsSchema: {\n mailbox: promptArg('Mailbox to triage, e.g. \"INBOX\". Omit for the default inbox.'),\n account: promptArg(\"Account display name or UUID. Omit to span every visible account.\"),\n since: promptArg(\"ISO date lower bound, e.g. 2026-08-18. Omit for the last 7 days.\"),\n },\n build: ({\n mailbox,\n account,\n since,\n }) => `Triage ${mailbox ? `the ${mailbox} mailbox` : \"the inbox\"}${\n account ? ` on the ${account} account` : \"\"\n }, covering ${since ? `everything since ${since}` : \"the last 7 days\"}.\n\n1. Call \\`apple_mail_search_messages\\` with a \\`dateFrom\\` bound${\n mailbox ? ` and \\`mailbox\\`` : \"\"\n }. Do not page \\`apple_mail_list_messages\\` — the index is what makes this fast.\n2. Group by sender and thread. Use \\`apple_mail_get_thread\\` where a subject\n recurs, so a five-message exchange is read once, not five times.\n3. Sort into: **needs a reply from me**, **waiting on someone else**, **for\n information**, **ignorable**. Put anything with a date or a commitment in it\n at the top, and say what the commitment is.\n4. Read bodies only for the messages that reach the first two groups. Subjects\n and senders decide the other two.\n\nReport what you found. Do not flag, move, delete or reply to anything — if an\naction looks obviously right, propose it and let the user say yes.\n\nIf any call comes back \\`degraded: true\\`, stop and say which mailbox you could\nnot read and why. An unread index is not an empty inbox.`,\n });\n\n registerWorkflowPrompt(server, CTX, {\n name: \"apple_mail_find_thread\",\n title: \"Find a thread about something\",\n description:\n \"Track down a conversation from a vague description — a project name, a person, something \" +\n \"half-remembered — spending the cheap search lanes before the expensive body lane.\",\n argsSchema: {\n about: requiredPromptArg(\n 'What the thread is about, in whatever words the user used, e.g. \"the Atlas pricing thread\".',\n ),\n since: promptArg(\"ISO date lower bound, if the user knows roughly when. Omit if not.\"),\n },\n build: ({ about, since }) => `Find the mail thread about: ${about}${\n since ? `\\n\\nThe user thinks it was on or after ${since}.` : \"\"\n }\n\nSpend the cheap lanes first — each of these reads the index, so run them before\ntouching any message body:\n\n1. \\`apple_mail_search_messages\\` with \\`query\\` (subject and sender) for the\n distinctive words. Proper nouns beat common ones.\n2. If that misses, try \\`subject\\` alone, then \\`sender\\` if the description names\n a person${since ? \", always with `dateFrom`\" : \"\"}.\n3. Only if steps 1–2 come up empty, use \\`body\\` — and **only with a narrowing\n filter alongside it**${\n since ? \" (you have a date, so use it)\" : \" (a mailbox, a sender, or a date bound)\"\n }. Without one it will refuse rather than answer from a partial scan, and\n that refusal is not \"no results\".\n\nWhen you have a candidate, call \\`apple_mail_get_thread\\` on it and summarise the\nexchange: who said what, what was decided, what is outstanding.\n\nIf several threads match, list them with dates and participants and ask which\none — do not pick for the user.`,\n });\n\n if (!allowWrites) return;\n\n registerWorkflowPrompt(server, CTX, {\n name: \"apple_mail_draft_reply\",\n title: \"Draft a reply\",\n description:\n \"Read a thread properly, then leave a written draft in Mail for review. Never sends: the \" +\n \"draft waits for a human. Requires writes to be enabled.\",\n argsSchema: {\n ref: promptArg(\"Message ref to reply to, from a search or list result. Omit to find it.\"),\n about: promptArg(\"If no ref: what the thread is about, so it can be found first.\"),\n instruction: promptArg(\n 'What the reply should say or do, e.g. \"accept, propose Thursday instead\".',\n ),\n },\n build: ({ ref, about, instruction }) => `Draft a reply${\n ref ? ` to ${ref}` : about ? ` to the thread about: ${about}` : \"\"\n }.${instruction ? `\\n\\nWhat it should say: ${instruction}` : \"\"}\n\n${\n ref\n ? `1. Read the full exchange with \\`apple_mail_get_thread\\` before writing a word.`\n : `1. Find the thread first — \\`apple_mail_search_messages\\` on subject and sender, body only\n with a narrowing filter — then read it in full with \\`apple_mail_get_thread\\`.\n If more than one thread matches, ask which before drafting.`\n}\n2. Match how this correspondent is actually written to: the greeting, the\n sign-off, the length, whether contractions appear. Read the user's own\n earlier messages in the thread for that, not just the incoming one.\n3. Answer every question that was actually asked. A reply that addresses the\n last paragraph and drops the other three is the common failure here.\n4. Call \\`apple_mail_reply_to_message\\` **with a \\`body\\`**. Calling it without one\n leaves an empty draft with the original quoted underneath — a blank page,\n which must never be reported as a written reply.\n5. Leave \\`sendNow\\` at its default. This produces a draft in Mail; a human\n decides whether it goes.\n\nThen tell the user what you drafted and what you assumed, so they can correct\nit before sending.`,\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Mail's tool helpers.\n *\n * The generic half — result shaping, error rendering and the two args every\n * server has — lives in `@mgcrea/mcp-apple-core`. Re-exported here so tools\n * keep importing from one place.\n */\nexport {\n compact,\n confirmArg,\n describeAggregation,\n fail,\n groupByArg,\n limitArg,\n ok,\n okText,\n project,\n resolveLimit,\n selectArg,\n toFailure,\n wrap,\n wrapResult,\n type ToolResult,\n} from \"@mgcrea/mcp-apple-core\";\n\n// ─── Mail's own args ─────────────────────────────────────────────────────────\n\nexport const accountArg = z\n .string()\n .optional()\n .describe(\n 'Account display name (e.g. \"iCloud\") or its UUID, from apple_mail_list_accounts. ' +\n \"Omit to span every visible account.\",\n );\n\nexport const mailboxArg = z\n .string()\n .optional()\n .describe(\n 'Mailbox name, e.g. \"INBOX\", \"Sent Messages\", or \"[Gmail]/All Mail\". ' +\n \"Gmail-style prefixes are resolved automatically.\",\n );\n\nexport const messageRefArg = z\n .string()\n .min(1)\n .describe(\n \"An opaque message ref from a search or list result (looks like \" +\n '\"m1:<accountUuid>/<mailbox>#<id>\"). Do not construct one by hand.',\n );\n\nexport const messageRefsArg = z\n .array(z.string().min(1))\n .min(1)\n .max(200)\n .describe(\n \"Message refs from a search or list result. Batched by mailbox into one round-trip each.\",\n );\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { BUILD_INFO } from \"../build-info.js\";\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport type { ToolContext } from \"./index.js\";\nimport { wrap } from \"./util.js\";\n\n/**\n * Build the report.\n *\n * Split out of the tool registration so the `cupertino://mail/diagnostics`\n * resource can serve the same bytes. Two renderings of one probe: duplicated,\n * the resource and the tool would drift, and the disagreement would surface as\n * \"the diagnostics lied\" — the one thing this file must never do.\n */\nexport const buildDiagnostics = async (\n client: AppleMailClient,\n ctx: ToolContext,\n): Promise<Record<string, unknown>> => {\n // Probe the lanes FIRST. lanes() is the call that retries past the\n // cold-start Automation prompt, and a successful probe caches the\n // accounts — so the account list below is read from the same evidence\n // the lane status is derived from. Doing it the other way round makes\n // the two disagree whenever the first Apple Event loses the race.\n const lanes = await client.lanes();\n const located = await client.locate();\n // End-to-end probe of the message-file lane: resolve a real message to\n // a path and read a byte of it. Without this the report can say Full\n // Disk Access is granted while every file read on an account fails.\n const messageFile = await client.probeMessageFile();\n // Cheap, and the two permissions nothing else in this report would reveal.\n const composer = await client.composerAccess();\n const axReach = await client.composerAxReach();\n\n let accounts: unknown[] = [];\n let accountsError: string | null = null;\n try {\n accounts = (await client.accounts()).map((a) => ({\n id: a.id,\n name: a.name,\n enabled: a.enabled,\n type: a.accountType,\n emailAddresses: a.emailAddresses,\n mailboxCount: a.mailboxes.length,\n // Headers-only caching means .emlx bodies are not on disk and the\n // body lane has to fall back to a per-message Apple Event.\n messageCaching: a.messageCaching,\n }));\n } catch (err) {\n accountsError = err instanceof Error ? err.message : String(err);\n }\n\n const indexAgeSeconds = located.mtime\n ? Math.max(0, Math.round((Date.now() - Date.parse(located.mtime)) / 1000))\n : null;\n\n return {\n server: {\n name: BUILD_INFO.name,\n version: BUILD_INFO.version,\n gitCommit: BUILD_INFO.gitCommit,\n node: process.version,\n platform: process.platform,\n },\n lanes,\n messageFile,\n /*\n * Body search is its own lane and reports as one, because \"it found\n * nothing\" and \"it could not look\" are the two answers a caller must\n * never confuse. It rides on the message-file lane — no file, no body\n * — so its readiness is that lane's readiness plus a declared bound.\n */\n bodySearch: {\n available: messageFile.some((p) => p.status === \"ok\"),\n via: \"index narrows, message files are scanned\",\n reason: messageFile.some((p) => p.status === \"ok\")\n ? null\n : \"Body search reads .emlx files, and no account produced one. An account cached \" +\n \"headers-only has no bodies on disk at all; otherwise this is the message-file \" +\n \"lane failing, which the messageFile block above explains per account.\",\n scanBound: client.config.bodyScanMax,\n readBytesPerMessage: client.config.bodyScanBytes,\n note:\n \"There is no body index on macOS to use: the Envelope Index has no FTS table, and \" +\n \"the Spotlight volume index excludes ~/Library entirely. Cost is linear in the \" +\n \"messages left by the other filters, so a body search wants a narrowing filter.\",\n },\n permissions: {\n automation: lanes.applescript === \"live\" ? \"granted\" : \"denied-or-mail-not-running\",\n // Only the composer needs this, so it is granted independently of the\n // other two and denied without affecting anything else in this report.\n // Both only matter to the composer, so they are granted independently of\n // the other two and denied without affecting anything else in this report.\n accessibility: composer.accessibility,\n automationSystemEvents: composer.systemEvents,\n // The one line here that is a measurement rather than a claim: whether\n // Mail's windows could actually be named. `accessibility` above answers\n // for an identity, and the two have been seen to disagree — the app's own\n // process reporting trusted while the server it spawned reports the\n // opposite — so when they conflict, this is the one to believe.\n composerUiRead: composer.uiRead,\n ...(composer.windows ? { composerWindowsSeen: composer.windows } : {}),\n // WHICH lane fills a composer, which decides whether the two grants above\n // are both needed. `accessibility` reaches Mail's composer through\n // Cupertino's own native driver and needs Accessibility alone;\n // `system-events` is the fallback for a server nobody is hosting — a\n // package installed from npm and run by hand — and needs both.\n composerLane: client.composerLane,\n // The functional read on the native lane, and the same rule as\n // `composerUiRead`: `composerLane` says which lane is configured, which is\n // a claim about the environment. This is whether it can actually see\n // Mail's windows.\n ...(axReach\n ? {\n composerAxRead: axReach.ok ? \"granted\" : \"denied\",\n ...(axReach.windows ? { composerAxWindowsSeen: axReach.windows } : {}),\n }\n : {}),\n ...(client.composerLane === \"accessibility\"\n ? {\n composerLaneNote:\n \"This server is hosted by Cupertino, so a composer is driven through the app's \" +\n \"own Accessibility driver. Automation to System Events is NOT required for it, \" +\n \"and `automationSystemEvents` above can be denied without affecting a reply.\",\n }\n : {}),\n ...((composer.uiRead === \"granted\" && composer.systemEvents === \"granted\") ||\n client.composerLane === \"accessibility\"\n ? {}\n : {\n composerNote:\n \"Filling a Mail composer goes through System Events, which needs BOTH of the \" +\n \"above: Automation to System Events (a different grant from Automation to Mail) \" +\n \"and Accessibility. Until both are granted, apple_mail_reply_to_message and \" +\n \"apple_mail_forward_message fail with COMPOSER_NOT_FOUND while every other tool \" +\n \"works. Grant them to the Cupertino bundle that is RUNNING — not to your terminal \" +\n \"and not to node: the app is the process macOS holds responsible, and the servers \" +\n \"do inherit its identity. If Cupertino's own Settings shows a GREEN Accessibility \" +\n \"row while `composerUiRead` above says denied, believe this line and not the row: \" +\n \"one bundle identifier can hold several Accessibility entries at once, one per \" +\n \"path and signature it has been granted at (an installed copy, a development \" +\n \"build, each earlier reinstall), and the two checks can match different ones. The \" +\n \"cure is to clear them all and grant once, from the bundle that is running: \" +\n \"`tccutil reset Accessibility io.mgcrea.cupertino`, then Ask… in Cupertino's \" +\n \"Settings — it reported resetting FOUR entries the first time this was hit. \" +\n \"Accessibility is in System Settings > \" +\n \"Privacy & Security > Accessibility; Automation is under Automation. If the app \" +\n \"is already listed, toggle it off and on — the grant goes stale when the bundle \" +\n \"is reinstalled. Then quit Cupertino and open it again: the servers are children \" +\n \"of the running app, and a child started before the grant does not see it — which \" +\n \"is what `accessibility: denied` beside a green Accessibility row in Cupertino's \" +\n \"own Settings means.\",\n }),\n fullDiskAccess: located.readable\n ? \"granted\"\n : located.exists\n ? \"denied\"\n : \"unknown (no index file found)\",\n ...(located.readable\n ? {}\n : {\n howToGrant: [\n \"System Settings > Privacy & Security > Full Disk Access\",\n \"Add the app that launches this server (Terminal, iTerm, VS Code, Claude...), then restart it.\",\n \"Granting it to Mail.app does nothing — the reader needs the permission, not Mail.\",\n ],\n }),\n },\n mailData: {\n root: located.mailRoot,\n dataVersion: located.dataVersion,\n envelopeIndex: located.envelopeIndexPath,\n foundVia: located.strategy,\n exists: located.exists,\n readable: located.readable,\n sizeBytes: located.sizeBytes,\n indexAgeSeconds,\n // A -wal means some mail may live outside the main file. Whether a\n // given read would miss it depends on checkpoint timing, which is\n // exactly why the server opens with mode=ro and does not gamble.\n walPresent: located.walPresent,\n walSizeBytes: located.walSizeBytes,\n reason: located.reason,\n },\n settings: {\n allowWrites: ctx.allowWrites,\n // Off means the prompts and the cupertino:// resources are not registered\n // at all. Reported here because this tool still is, so it stays the one\n // place that explains a capability the client cannot see.\n exposePrompts: client.config.exposePrompts,\n accountAllowlist: client.config.accounts.length ? client.config.accounts : \"(all accounts)\",\n indexMode: client.config.indexMode,\n degradedMaxMessages: client.config.degradedMaxMessages,\n bodyScanMax: client.config.bodyScanMax,\n maxResults: client.config.maxResults,\n attachmentDir: client.config.attachmentDir,\n },\n accounts,\n ...(accountsError ? { accountsError } : {}),\n caveats: [\n \"`messageFile` is per account on purpose: mailbox layout differs by provider, so one \" +\n \"account's lane can be dead while another's works. `unreachable` with \" +\n \"`fullDiskAccess: granted` means the path was wrong, not the permission.\",\n \"Mailbox `unread` from the AppleScript lane is Mail's cached badge value and can \" +\n \"disagree with the real count (observed: 0 reported for a mailbox with 1618 unread \" +\n \"messages). Counts are labelled with their source; prefer the index when it is live.\",\n ],\n };\n};\n\n/**\n * The first tool anyone should call when something looks wrong. Every\n * permission this server depends on is invisible until you ask for it, and the\n * failure modes (a TCC denial, a stale index, a mailbox that reports zero\n * unread) all look like \"the tool is broken\" from the outside.\n */\nexport const registerDiagnosticsTools = (\n server: McpServer,\n client: AppleMailClient,\n ctx: ToolContext,\n): void => {\n server.registerTool(\n \"apple_mail_diagnostics\",\n {\n description:\n \"Report what this server can currently do and why. Shows whether Mail is running, whether \" +\n \"Automation and Full Disk Access are granted, where Mail's data lives, whether the search \" +\n \"index is readable and how stale it is, whether the message file lane actually resolves \" +\n \"and reads a real message per account, per-account message caching, and the active \" +\n \"write/allowlist settings. Call this first whenever a tool returns `degraded: true` or a \" +\n \"permission error — it names the exact System Settings pane to open.\",\n inputSchema: {},\n annotations: { readOnlyHint: true },\n },\n async () => wrap(() => buildDiagnostics(client, ctx)),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport { accountArg, wrap } from \"./util.js\";\n\n/**\n * Account and mailbox listing.\n *\n * Both are AppleScript-primary rather than index-primary, which is the reverse\n * of what \"SQLite is the fast lane\" suggests. Two reasons: it is genuinely fast\n * here (0.6s for every account and mailbox on this machine, because the cost is\n * O(mailboxes) not O(messages)), and the Envelope Index stores no account\n * display names at all — only UUIDs inside `mailboxes.url` — so an index-first\n * implementation has to invent names from URL fragments and gets them wrong.\n */\nexport const registerAccountTools = (server: McpServer, client: AppleMailClient): void => {\n server.registerTool(\n \"apple_mail_list_accounts\",\n {\n description:\n \"List the mail accounts configured in Apple Mail: display name, UUID, type, addresses and \" +\n \"mailbox names. Start here — the account name or UUID is what every other tool takes, and \" +\n \"the mailbox names come back exactly as Mail spells them.\",\n inputSchema: {},\n annotations: { readOnlyHint: true },\n },\n async () =>\n wrap(async () =>\n (await client.accounts()).map((a) => ({\n id: a.id,\n name: a.name,\n enabled: a.enabled,\n type: a.accountType,\n emailAddresses: a.emailAddresses,\n fullName: a.fullName,\n mailboxes: a.mailboxes,\n })),\n ),\n );\n\n server.registerTool(\n \"apple_mail_list_mailboxes\",\n {\n description:\n \"List mailboxes, optionally with message counts. Counts cost one round-trip per mailbox \" +\n \"(~0.3s each), so `withCounts` is off by default — turn it on for one account, not for all \" +\n \"of them. Note that `unread` here is Mail's cached badge value and can be wrong; \" +\n \"apple_mail_count_messages reports both sources.\",\n inputSchema: {\n account: accountArg,\n withCounts: z\n .boolean()\n .optional()\n .describe(\n \"Include total and unread per mailbox. Costs ~0.3s per mailbox. Default false.\",\n ),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ account, withCounts }) =>\n wrap(async () => {\n const accountUuids = account\n ? [(await client.mailboxes.resolveAccount(account)).id]\n : undefined;\n return client.listMailboxes({\n ...(accountUuids ? { accountUuids } : {}),\n withCounts: withCounts ?? false,\n });\n }),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport { confirmArg, messageRefsArg, wrap } from \"./util.js\";\n\n/**\n * Mutating tools.\n *\n * The whole file is behind `allowWrites` in the aggregator: with writes off\n * these are never registered, so the model cannot see them, cannot call them,\n * and is not tempted to explain to the user why it will not.\n */\nexport const registerActionTools = (server: McpServer, client: AppleMailClient): void => {\n server.registerTool(\n \"apple_mail_set_message_flags\",\n {\n description:\n \"Set read / flagged / junk state on one or more messages. Pass only the fields you want to \" +\n \"change; the rest are left alone. This is one tool rather than four because the four are \" +\n \"one Apple Event when batched, and because refs in the same mailbox are grouped into a \" +\n \"single round-trip. The response reports the state Mail re-read after the change, not what \" +\n \"was requested — Mail's search index updates on its own schedule, so a follow-up search may \" +\n \"briefly still show the old value.\",\n inputSchema: {\n refs: messageRefsArg,\n read: z.boolean().optional().describe(\"Mark read (true) or unread (false).\"),\n flagged: z.boolean().optional().describe(\"Set or clear the flag.\"),\n flagIndex: z\n .number()\n .int()\n .min(-1)\n .max(6)\n .optional()\n .describe(\"Flag colour: 0-6, or -1 to clear. Only meaningful when flagged is true.\"),\n junk: z.boolean().optional().describe(\"Mark as junk (true) or not junk (false).\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },\n },\n async ({ refs, read, flagged, flagIndex, junk }) =>\n wrap(async () => {\n if (\n read === undefined &&\n flagged === undefined &&\n flagIndex === undefined &&\n junk === undefined\n ) {\n return { changed: 0, note: \"No flag fields were supplied, so nothing was changed.\" };\n }\n return client.setFlags(refs, {\n ...(read === undefined ? {} : { read }),\n ...(flagged === undefined ? {} : { flagged }),\n ...(flagIndex === undefined ? {} : { flagIndex }),\n ...(junk === undefined ? {} : { junk }),\n });\n }),\n );\n\n server.registerTool(\n \"apple_mail_create_mailbox\",\n {\n description:\n \"Create a mailbox (a folder). Use this before apple_mail_move_messages when the \" +\n \"destination does not exist yet — a move to a mailbox that is not there fails, and this \" +\n 'is the only way to make one from here. Nest with \"/\": \"Projects/Cupertino\" creates ' +\n \"Cupertino inside Projects. Omit `account` to create a local mailbox under On My Mac. \" +\n \"ON A SERVER ACCOUNT (iCloud, Gmail, Exchange, any IMAP) THIS CREATES THE FOLDER ON THE \" +\n \"SERVER: it syncs to the user's phone and every other device within seconds, and there \" +\n \"is no delete tool here to undo it. Calling it for a name that already exists is safe \" +\n \"and does nothing — the result says `created: false`. The name comes back as Mail \" +\n \"re-read it, which is not always the one you asked for: an IMAP server can rename or \" +\n \"reject it.\",\n inputSchema: {\n name: z\n .string()\n .min(1)\n .describe(\n 'The mailbox name, e.g. \"Receipts\" or \"Projects/Cupertino\" for a nested one. Take ' +\n \"the spelling of an existing parent from apple_mail_list_mailboxes.\",\n ),\n account: z\n .string()\n .optional()\n .describe(\n \"Account name or UUID from apple_mail_list_accounts. Omit for a local mailbox in \" +\n \"On My Mac, which stays on this machine.\",\n ),\n confirm: confirmArg,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },\n },\n async ({ name, account }) => wrap(async () => client.createMailbox(name, account)),\n );\n\n server.registerTool(\n \"apple_mail_move_messages\",\n {\n description:\n \"Move messages to another mailbox, optionally in another account. The refs you passed in \" +\n \"are DEAD afterwards: a moved message gets a new row id, so the response returns fresh refs \" +\n \"and reports any message it could not re-locate. Requires confirm: true.\",\n inputSchema: {\n refs: messageRefsArg,\n destinationMailbox: z\n .string()\n .min(1)\n .describe('Target mailbox name, e.g. \"Archive\" or \"[Gmail]/All Mail\".'),\n destinationAccount: z\n .string()\n .optional()\n .describe(\"Target account name or UUID. Defaults to each message's own account.\"),\n confirm: confirmArg,\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },\n },\n async ({ refs, destinationMailbox, destinationAccount }) =>\n wrap(async () =>\n client.moveMessages(refs, {\n destinationMailbox,\n ...(destinationAccount ? { destinationAccount } : {}),\n }),\n ),\n );\n\n server.registerTool(\n \"apple_mail_delete_messages\",\n {\n description:\n \"Delete messages. This follows the account's own 'move deleted messages to Trash' setting, \" +\n \"which this server does not control — for an account with that setting off, deletion is \" +\n \"immediate and NOT recoverable from here. The response reports which behaviour applied. \" +\n \"Requires confirm: true.\",\n inputSchema: {\n refs: messageRefsArg,\n confirm: confirmArg,\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },\n },\n async ({ refs }) => wrap(async () => client.deleteMessages(refs)),\n );\n\n server.registerTool(\n \"apple_mail_check_for_new_mail\",\n {\n description:\n \"Ask Mail to sync now, for one account or all of them. Unlike the read tools this will \" +\n \"launch Mail if it is not running, and it causes real network activity against the mail \" +\n \"servers, which is why it is a write-gated tool.\",\n inputSchema: {\n account: z\n .string()\n .optional()\n .describe(\"Account name or UUID. Omit to check every account.\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },\n },\n async ({ account }) => wrap(async () => client.checkForNewMail(account)),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport { confirmArg, messageRefArg, wrap } from \"./util.js\";\n\n/**\n * Composing and sending.\n *\n * Sending is the only action in this server that is irreversible AND visible to\n * other people, so it carries two independent gates rather than one:\n *\n * 1. `APPLE_MAIL_ALLOW_WRITES` must be on, or these tools do not exist.\n * 2. `sendNow` defaults to FALSE, which leaves the draft open in Mail for a\n * human to read. Setting it to true additionally requires `confirm: true`.\n *\n * The default is the important half. An agent that drafts is useful and safe;\n * an agent that sends is neither by default.\n */\n\nconst sendNowArg = z\n .boolean()\n .optional()\n .describe(\n \"Send immediately instead of leaving a draft. Defaults to FALSE, which opens the message in \" +\n \"Mail for a human to review and send. When true, confirm must also be true.\",\n );\n\nconst bodyArg = z.string().min(1).describe(\"Plain text body.\");\n\nconst recipientsArg = (kind: string) =>\n z.array(z.string().email()).optional().describe(`${kind} email addresses.`);\n\n/** Reject sendNow without confirm before anything reaches Mail. */\nconst assertSendGate = (sendNow: boolean | undefined, confirm: boolean | undefined): void => {\n if (sendNow && confirm !== true) {\n throw new Error(\n \"Refusing to send: sendNow is true but confirm is not. Sending mail is irreversible and \" +\n \"visible to the recipient, so it needs an explicit confirm: true. Omit sendNow to leave a \" +\n \"draft open for review instead.\",\n );\n }\n};\n\nexport const registerComposeTools = (server: McpServer, client: AppleMailClient): void => {\n server.registerTool(\n \"apple_mail_send_message\",\n {\n description:\n \"Compose a new message. By DEFAULT this does not send: it opens a draft in Mail for the \" +\n \"user to review, which is almost always what you want. Only pass sendNow: true (with \" +\n \"confirm: true) when the user has explicitly asked for the mail to go out now.\",\n inputSchema: {\n account: z\n .string()\n .optional()\n .describe(\"Account to send from, by name or UUID. Defaults to Mail's default account.\"),\n to: recipientsArg(\"To\"),\n cc: recipientsArg(\"Cc\"),\n bcc: recipientsArg(\"Bcc\"),\n subject: z.string().describe(\"Subject line.\"),\n body: bodyArg,\n sendNow: sendNowArg,\n confirm: z.literal(true).optional().describe(\"Required when sendNow is true.\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },\n },\n async ({ account, to, cc, bcc, subject, body, sendNow, confirm }) =>\n wrap(async () => {\n assertSendGate(sendNow, confirm);\n if (!to?.length && !cc?.length && !bcc?.length) {\n throw new Error(\"No recipients: pass at least one of to, cc or bcc.\");\n }\n return client.sendMessage({\n ...(account ? { account } : {}),\n to: to ?? [],\n cc: cc ?? [],\n bcc: bcc ?? [],\n subject,\n body,\n sendNow: sendNow ?? false,\n });\n }),\n );\n\n server.registerTool(\n \"apple_mail_reply_to_message\",\n {\n description:\n \"Reply to a message. By default it opens a draft in Mail with the original quoted beneath \" +\n \"your text, for the user to review. Pass replyToAll to include every original recipient. \" +\n \"Only pass sendNow: true (with confirm: true) when explicitly asked to send now. \" +\n \"Success means the body was read back out of the composer window and matched, and only \" +\n \"then may it be described to the user as ready. A failure is NOT automatically an empty \" +\n \"draft: read the note, which says what was actually found — including that the composer \" +\n \"was taken by someone using the Mac, in which case the reply may already have been SENT \" +\n \"and a retry would send it twice. Filling the composer brings Mail to the front for a \" +\n \"moment and borrows the clipboard, both of which are put back.\",\n inputSchema: {\n ref: messageRefArg,\n body: bodyArg,\n replyToAll: z\n .boolean()\n .optional()\n .describe(\"Reply to every recipient, not just the sender.\"),\n sendNow: sendNowArg,\n confirm: z.literal(true).optional().describe(\"Required when sendNow is true.\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },\n },\n async ({ ref, body, replyToAll, sendNow, confirm }) =>\n wrap(async () => {\n assertSendGate(sendNow, confirm);\n return client.replyOrForward(ref, {\n mode: \"reply\",\n body,\n replyToAll: replyToAll ?? false,\n sendNow: sendNow ?? false,\n });\n }),\n );\n\n server.registerTool(\n \"apple_mail_forward_message\",\n {\n description:\n \"Forward a message to new recipients. By default it opens a draft in Mail for review. \" +\n \"Only pass sendNow: true (with confirm: true) when explicitly asked to send now. \" +\n \"When a note is given, success means it was read back out of the composer window and \" +\n \"matched. Filling the composer brings Mail to the front for a moment and borrows the \" +\n \"clipboard, both of which are put back.\",\n inputSchema: {\n ref: messageRefArg,\n to: z.array(z.string().email()).min(1).describe(\"Who to forward to.\"),\n body: z.string().optional().describe(\"Optional note to add above the forwarded message.\"),\n sendNow: sendNowArg,\n confirm: z.literal(true).optional().describe(\"Required when sendNow is true.\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },\n },\n async ({ ref, to, body, sendNow, confirm }) =>\n wrap(async () => {\n assertSendGate(sendNow, confirm);\n return client.replyOrForward(ref, {\n mode: \"forward\",\n to,\n ...(body ? { body } : {}),\n sendNow: sendNow ?? false,\n });\n }),\n );\n\n server.registerTool(\n \"apple_mail_update_draft\",\n {\n description:\n \"Replace the body of an unsent draft. Mail has no way to edit a saved draft — its \" +\n \"`content` is read-only and there is no open or edit command — so this RECREATES it: a \" +\n \"new draft with the same recipients and a new body, and the old one deleted once the \" +\n \"replacement is confirmed present. The ref you passed in is DEAD afterwards and the \" +\n \"result carries the new one. \" +\n \"It REFUSES rather than doing damage, and returns `replaced: false` with a reason when \" +\n \"it does: on a reply or forward draft, because In-Reply-To is set by Mail's reply \" +\n \"command and a recreated one would silently start a new thread; on a draft carrying \" +\n \"attachments, because their bytes are not available as files to re-attach; and on \" +\n \"anything not in the Drafts mailbox, because deleting a sent or received message and \" +\n \"writing a lookalike is \" +\n \"not editing. In every refusal the original is untouched. If the replacement cannot be \" +\n \"confirmed the original is KEPT and you are told there are now two — never assume a \" +\n \"clean swap without reading `replaced`.\",\n inputSchema: {\n ref: messageRefArg,\n body: z\n .string()\n .min(1)\n .describe(\n \"The complete new body. This REPLACES the draft's text rather than appending to it, \" +\n \"so include everything that should remain — read the draft first with \" +\n \"apple_mail_get_message if you are editing rather than rewriting.\",\n ),\n subject: z\n .string()\n .optional()\n .describe(\n \"A new subject. Defaults to the draft's existing one. A draft with no subject at \" +\n \"all is refused unless you pass one, because the subject is how the replacement \" +\n \"is found again before the original is deleted.\",\n ),\n confirm: confirmArg,\n },\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },\n },\n async ({ ref, body, subject }) =>\n wrap(async () => client.updateDraft(ref, { body, ...(subject ? { subject } : {}) })),\n );\n};\n\nexport { assertSendGate };\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport { messageRefArg, wrap } from \"./util.js\";\n\n/**\n * Reading one message.\n *\n * `get_message` and `get_message_source` are deliberately separate tools. A\n * routine read should not drag two megabytes of base64 attachment and forty\n * Received: headers into the conversation; when you actually need those — chasing\n * a spoofed sender, say — you ask for them explicitly.\n */\nexport const registerMessageTools = (\n server: McpServer,\n client: AppleMailClient,\n allowWrites: boolean,\n): void => {\n server.registerTool(\n \"apple_mail_get_message\",\n {\n description:\n \"Read one message: decoded headers, the plain-text body, and a list of its attachments. \" +\n \"HTML-only mail is converted to text. Long bodies are truncated with an explicit marker \" +\n \"rather than silently cut. Reads the message file directly when Full Disk Access allows, \" +\n \"and otherwise asks Mail, which is slower but works — so this tool does not need the \" +\n \"search index.\",\n inputSchema: {\n ref: messageRefArg,\n maxBodyBytes: z\n .number()\n .int()\n .min(256)\n .max(2_000_000)\n .optional()\n .describe(\"Override the body truncation limit for this call.\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ ref, maxBodyBytes }) =>\n wrap(async () => {\n const { message, parsed, source, fallbackReason } = await client.getMessageBody(\n ref,\n maxBodyBytes ? { maxBodyBytes } : {},\n );\n\n if (!parsed) {\n // AppleScript fallback: Mail hands back display text, not MIME, so\n // there is no attachment manifest to report here.\n return {\n ref: message.ref,\n source,\n subject: message.subject,\n sender: message.sender,\n dateReceived: message.dateReceived,\n read: message.read,\n flagged: message.flagged,\n body: message.content ?? \"\",\n // The reason comes from an actual lookup rather than a fixed guess.\n // The old text always blamed Full Disk Access, which sent people to\n // a setting that was already correct whenever the real cause was a\n // mailbox path we failed to resolve.\n note:\n \"Body came from Mail rather than the message file, so attachment details are not \" +\n `available. ${fallbackReason ?? \"\"}`.trimEnd(),\n };\n }\n\n return {\n ref: message.ref,\n source,\n headers: parsed.headers,\n subject: message.subject ?? parsed.headers.subject,\n sender: message.sender ?? parsed.headers.from,\n dateReceived: message.dateReceived,\n read: message.read,\n flagged: message.flagged,\n bodyFrom: parsed.bodyFrom,\n truncated: parsed.truncated,\n body: parsed.body,\n attachments: parsed.attachments,\n // Derive the note from what was actually found, not from the file\n // layout. Keying it on `partial` alone produced a note saying sizes\n // read as 0 beside an attachment reporting 1 byte and inline: true.\n ...(parsed.attachments.some((a) => !a.inline)\n ? {\n note:\n \"Some attachments are stored outside this message file, so their sizes are \" +\n \"unknown and apple_mail_save_attachment cannot retrieve them. Open the message \" +\n \"in Mail to download them first.\",\n }\n : {}),\n };\n }),\n );\n\n server.registerTool(\n \"apple_mail_get_message_source\",\n {\n description:\n \"Get the raw RFC 5322 source of a message — every header and the undecoded body. Use this \" +\n \"for header forensics (Received chains, SPF/DKIM/DMARC results, List-Unsubscribe), not for \" +\n \"reading mail: apple_mail_get_message gives you the readable version without the noise. \" +\n \"Capped and pageable via offset.\",\n inputSchema: {\n ref: messageRefArg,\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Byte offset to start from. Default 0.\"),\n maxBytes: z\n .number()\n .int()\n .min(256)\n .max(1_000_000)\n .optional()\n .describe(\"How many bytes to return. Default 32768.\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ ref, offset, maxBytes }) =>\n wrap(async () =>\n client.getMessageSource(ref, { offset: offset ?? 0, maxBytes: maxBytes ?? 32_768 }),\n ),\n );\n\n server.registerTool(\n \"apple_mail_list_attachments\",\n {\n description:\n \"List a message's attachments: filename, MIME type, size and whether the bytes are present \" +\n \"locally. Metadata only — it never returns file contents. A size of 0 with a filename means \" +\n \"Mail stored the attachment outside the message file, which is normal.\",\n inputSchema: { ref: messageRefArg },\n annotations: { readOnlyHint: true },\n },\n async ({ ref }) =>\n wrap(async () => {\n const { parsed, source, fallbackReason } = await client.getMessageBody(ref, {\n maxBodyBytes: 1024,\n });\n if (!parsed) {\n return {\n degraded: true,\n capability: \"message-file\",\n reason:\n \"The message file was not read, and Mail's scripting interface does not expose a \" +\n `MIME attachment manifest. ${fallbackReason ?? \"\"}`.trimEnd(),\n hint: \"See the `messageFile` section of apple_mail_diagnostics, which probes this lane.\",\n };\n }\n return { ref, source, count: parsed.attachments.length, attachments: parsed.attachments };\n }),\n );\n\n if (!allowWrites) return;\n\n server.registerTool(\n \"apple_mail_save_attachment\",\n {\n description:\n \"Save one attachment to disk. It can only write into APPLE_MAIL_ATTACHMENT_DIR (default \" +\n \"~/Downloads) and will not overwrite an existing file unless you ask it to. Write-gated \" +\n \"because it puts a file on the user's disk, even though it changes nothing in Mail.\",\n inputSchema: {\n ref: messageRefArg,\n filename: z.string().min(1).describe(\"Exact filename from apple_mail_list_attachments.\"),\n overwrite: z.boolean().optional().describe(\"Replace an existing file. Default false.\"),\n },\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },\n },\n async ({ ref, filename, overwrite }) =>\n wrap(async () => client.saveAttachment(ref, filename, overwrite ? { overwrite } : {})),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport { GROUP_FIELDS } from \"../client/envelope.js\";\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport {\n accountArg,\n describeAggregation,\n groupByArg,\n limitArg,\n mailboxArg,\n project,\n resolveLimit,\n selectArg,\n wrap,\n} from \"./util.js\";\n\n/** What a search result actually carries, and therefore what `select` may name. */\nconst SELECTABLE = [\n \"ref\",\n \"subject\",\n \"sender\",\n \"dateReceived\",\n \"dateSent\",\n \"read\",\n \"flagged\",\n \"size\",\n] as const;\n\n/**\n * The cheap-answer lane: same index as `apple_mail_search_messages`, but able to\n * return less than a whole row, or a count instead of the rows.\n *\n * Read-only by construction — it reaches nothing but the index — and registered\n * on every server, write-enabled ones included, since it repays its own listing\n * cost on a single grouped question (see docs/mail-query.md).\n */\nexport const registerQueryTools = (server: McpServer, client: AppleMailClient): void => {\n server.registerTool(\n \"apple_mail_query\",\n {\n description:\n \"Answer a question ABOUT your mail without reading the mail. Takes the same index \" +\n \"filters as apple_mail_search_messages, plus two things it cannot do: `select` to keep \" +\n \"only the fields you need, and `groupBy` to get counts per sender, mailbox, subject, \" +\n \"day or month. Reach for this whenever the question is 'how many', 'who most', 'which \" +\n \"mailbox' or 'when' — one grouped call replaces paging through hundreds of messages \" +\n \"and tallying them by hand. Grouping counts every match, not just the first `limit`. \" +\n \"Body search is not offered here (it is a linear file scan, which does not belong \" +\n \"behind an aggregate) — use apple_mail_search_messages for that. \" +\n \"Requires Full Disk Access; without it this returns degraded:true.\",\n inputSchema: {\n query: z.string().optional().describe(\"Free text matched against subject and sender.\"),\n sender: z.string().optional().describe(\"Match the sender address or display name.\"),\n recipient: z.string().optional().describe(\"Match any recipient address.\"),\n subject: z.string().optional().describe(\"Match the subject only.\"),\n account: accountArg,\n mailbox: mailboxArg,\n unreadOnly: z.boolean().optional().describe(\"Only unread messages.\"),\n flaggedOnly: z.boolean().optional().describe(\"Only flagged messages.\"),\n hasAttachment: z.boolean().optional().describe(\"Only messages carrying an attachment.\"),\n dateFrom: z.string().optional().describe(\"ISO date/time lower bound, e.g. 2026-01-01.\"),\n dateTo: z.string().optional().describe(\"ISO date/time upper bound.\"),\n groupBy: groupByArg(GROUP_FIELDS),\n select: selectArg,\n limit: limitArg,\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Skip this many rows, for paging. Ignored when grouping.\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ groupBy, select, limit, offset, ...filters }) =>\n wrap(async () => {\n const resolved = resolveLimit(limit, client.config.maxResults);\n\n if (groupBy) {\n const result = await client.groupMessages({ ...filters, limit: resolved }, groupBy);\n if (!result) return degraded(client);\n return {\n ...describeAggregation(groupBy, result.groups, result),\n indexAgeSeconds: result.indexAgeSeconds,\n ...walBlindWarning(result.walBlind),\n };\n }\n\n const result = await client.searchMessages({\n ...filters,\n limit: resolved,\n offset: offset ?? 0,\n });\n if (!result) return degraded(client);\n\n const { rows, unknownFields } = project(result.messages, select, SELECTABLE);\n return {\n returned: rows.length,\n indexAgeSeconds: result.indexAgeSeconds,\n ...(unknownFields\n ? {\n unknownFields,\n hint: `Selectable fields are: ${SELECTABLE.join(\", \")}.`,\n }\n : {}),\n ...walBlindWarning(result.walBlind),\n messages: rows,\n };\n }),\n );\n};\n\n/**\n * The same degradation the other index-backed tools report. Kept identical on\n * purpose: a model that has learned what `capability: \"search-index\"` means\n * should not have to learn a second spelling of it here.\n */\nconst degraded = (client: AppleMailClient) => ({\n degraded: true,\n capability: \"search-index\",\n reason: client.indexError ?? \"the search index is unavailable\",\n hint:\n \"Grant Full Disk Access and restart the host app, then retry. \" +\n \"Call apple_mail_diagnostics for details.\",\n});\n\nconst walBlindWarning = (walBlind: boolean) =>\n walBlind\n ? { warning: \"Index opened WAL-blind (immutable); very recent mail may be missing.\" }\n : {};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport { accountArg, limitArg, mailboxArg, messageRefArg, resolveLimit, wrap } from \"./util.js\";\n\n/** Searching, listing and counting. */\nexport const registerSearchTools = (server: McpServer, client: AppleMailClient): void => {\n server.registerTool(\n \"apple_mail_search_messages\",\n {\n description:\n \"Search mail by any combination of text, body text, sender, recipient, subject, mailbox, \" +\n \"account, read/flagged state, attachments and date range. This is the tool to reach for \" +\n \"whenever a filter is involved — it reads Mail's own search index, so it is fast even \" +\n \"across a six-figure archive. Returns a `ref` per message for the read and action tools. \" +\n \"Requires Full Disk Access; without it this returns degraded:true and you should fall back \" +\n \"to apple_mail_list_messages on a specific mailbox.\",\n inputSchema: {\n query: z\n .string()\n .optional()\n .describe(\"Free text matched against subject and sender. For bodies, use `body`.\"),\n body: z\n .string()\n .optional()\n .describe(\n \"Free text matched against message BODIES. There is no body index on macOS, so this \" +\n \"reads the message files of whatever the other filters leave — cost is linear in \" +\n \"that number. COMBINE IT WITH A NARROWING FILTER (mailbox, sender, dateFrom) or it \" +\n \"will exceed the scan bound and refuse rather than answer from a partial scan. The \" +\n \"result's `bodyScan` block reports how many messages were considered and scanned.\",\n ),\n sender: z.string().optional().describe(\"Match the sender address or display name.\"),\n recipient: z.string().optional().describe(\"Match any recipient address.\"),\n subject: z.string().optional().describe(\"Match the subject only.\"),\n account: accountArg,\n mailbox: mailboxArg,\n unreadOnly: z.boolean().optional().describe(\"Only unread messages.\"),\n flaggedOnly: z.boolean().optional().describe(\"Only flagged messages.\"),\n hasAttachment: z.boolean().optional().describe(\"Only messages carrying an attachment.\"),\n dateFrom: z.string().optional().describe(\"ISO date/time lower bound, e.g. 2026-01-01.\"),\n dateTo: z.string().optional().describe(\"ISO date/time upper bound.\"),\n limit: limitArg,\n offset: z.number().int().min(0).optional().describe(\"Skip this many results, for paging.\"),\n },\n annotations: { readOnlyHint: true },\n },\n async (args) =>\n wrap(async () => {\n const result = await client.searchMessages({\n ...args,\n limit: resolveLimit(args.limit, client.config.maxResults),\n offset: args.offset ?? 0,\n });\n if (!result) {\n return {\n degraded: true,\n capability: \"search-index\",\n reason: client.indexError ?? \"the search index is unavailable\",\n hint:\n \"Grant Full Disk Access and restart the host app, or use apple_mail_list_messages \" +\n \"for a capped listing of one mailbox. Call apple_mail_diagnostics for details.\",\n };\n }\n /*\n * A refusal, not an empty result. The distinction is the whole point of\n * the bound: \"no messages matched\" and \"too many messages to check\"\n * look identical to a model unless the second one says so.\n */\n if (result.bodyScan?.status === \"over-bound\") {\n const { candidates, bound } = result.bodyScan;\n return {\n degraded: true,\n capability: \"body-scan\",\n reason:\n `${candidates} messages match the other filters, above the ${bound}-message body ` +\n `scan bound. Nothing was scanned, so this is not \"no results\".`,\n hint:\n \"Narrow with mailbox, account, sender or dateFrom and try again — a body search \" +\n \"over a few hundred candidates is near-instant. Raise APPLE_MAIL_BODY_SCAN_MAX \" +\n \"only if a slow answer is genuinely wanted.\",\n candidates,\n bound,\n };\n }\n\n return {\n returned: result.messages.length,\n source: result.source,\n indexAgeSeconds: result.indexAgeSeconds,\n ...(result.bodyScan ? { bodyScan: result.bodyScan } : {}),\n ...(result.walBlind\n ? { warning: \"Index opened WAL-blind (immutable); very recent mail may be missing.\" }\n : {}),\n messages: result.messages,\n };\n }),\n );\n\n server.registerTool(\n \"apple_mail_get_thread\",\n {\n description:\n \"Get every message in the conversation containing a given message, oldest first, across \" +\n \"mailboxes and accounts. Metadata only — use apple_mail_get_message for bodies. Requires \" +\n \"Full Disk Access.\",\n inputSchema: {\n ref: messageRefArg,\n limit: limitArg,\n },\n annotations: { readOnlyHint: true },\n },\n async ({ ref, limit }) =>\n wrap(async () => {\n const messages = await client.threadOf(\n ref,\n resolveLimit(limit, client.config.maxResults, 50),\n );\n if (!messages) {\n return {\n degraded: true,\n capability: \"search-index\",\n reason: client.indexError ?? \"the search index is unavailable\",\n hint: \"Threading needs Mail's search index. Call apple_mail_diagnostics for details.\",\n };\n }\n return { returned: messages.length, messages };\n }),\n );\n\n server.registerTool(\n \"apple_mail_list_messages\",\n {\n description:\n \"List the newest messages in one mailbox, most recent first. Returns a `ref` per message \" +\n \"that the read and action tools take. Without the search index this runs over Apple Events \" +\n \"and is capped (default 50) because each additional message costs about 40ms per field — \" +\n \"ask for 20 unless you have a reason not to. For anything involving a filter, use \" +\n \"apple_mail_search_messages.\",\n inputSchema: {\n account: accountArg,\n mailbox: mailboxArg,\n limit: limitArg,\n },\n annotations: { readOnlyHint: true },\n },\n async ({ account, mailbox, limit }) =>\n wrap(async () => {\n const accounts = await client.accounts();\n const resolved = account ? await client.mailboxes.resolveAccount(account) : accounts[0];\n if (!resolved) {\n return { messages: [], note: \"No accounts are visible to this server.\" };\n }\n const box = mailbox ?? (resolved.mailboxes.includes(\"INBOX\") ? \"INBOX\" : \"Inbox\");\n const result = await client.listRecent(\n resolved,\n box,\n resolveLimit(limit, client.config.maxResults),\n );\n const lanes = await client.lanes();\n return {\n account: resolved.name,\n mailbox: result.mailbox,\n total: result.total,\n returned: result.messages.length,\n source: \"applescript\",\n ...(lanes.index === \"live\"\n ? {}\n : {\n note:\n `Listing came from Apple Events and is capped at ${client.config.degradedMaxMessages}. ` +\n `The search index is ${lanes.index}: ${lanes.indexReason ?? \"unavailable\"}`,\n }),\n messages: result.messages,\n };\n }),\n );\n\n server.registerTool(\n \"apple_mail_count_messages\",\n {\n description:\n \"Count messages in a mailbox. Cheap in both lanes, so this works with no extra permissions. \" +\n \"The `unread` figure is reported per source: Mail's own cached count is fast but can be \" +\n \"flatly wrong (observed reporting 0 for a mailbox holding 1618 unread messages), so treat \" +\n \"the index figure as authoritative when it is present.\",\n inputSchema: {\n account: accountArg,\n mailbox: mailboxArg,\n },\n annotations: { readOnlyHint: true },\n },\n async ({ account, mailbox }) =>\n wrap(async () => {\n const accounts = await client.accounts();\n const resolved = account ? await client.mailboxes.resolveAccount(account) : accounts[0];\n if (!resolved) return { note: \"No accounts are visible to this server.\" };\n const box = mailbox ?? (resolved.mailboxes.includes(\"INBOX\") ? \"INBOX\" : \"Inbox\");\n const counts = await client.countMailbox(resolved, box);\n const viaIndex = await client.countViaIndex({ account: resolved.name, mailbox: box });\n return {\n account: resolved.name,\n mailbox: counts.mailbox,\n total: viaIndex?.total ?? counts.total,\n unread: { applescript: counts.unread, index: viaIndex?.unread ?? null },\n note: viaIndex\n ? \"Prefer unread.index: unread.applescript is Mail's cached badge value and is \" +\n \"sometimes flatly wrong (observed as 0 for a mailbox with 1618 unread).\"\n : \"unread.applescript is Mail's cached badge value and may be stale or zero. \" +\n \"Grant Full Disk Access for the authoritative count.\",\n };\n }),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport type { AppleMailClient } from \"../client/mail.js\";\nimport { registerAccountTools } from \"./accounts.js\";\nimport { registerActionTools } from \"./actions.js\";\nimport { registerComposeTools } from \"./compose.js\";\nimport { registerDiagnosticsTools } from \"./diagnostics.js\";\nimport { registerMessageTools } from \"./messages.js\";\nimport { registerQueryTools } from \"./query.js\";\nimport { registerSearchTools } from \"./search.js\";\n\nexport type ToolContext = {\n /**\n * Register the mutating tools too. Off by default — with the flag off they are\n * not merely refused, they are invisible and cannot be called at all.\n */\n allowWrites: boolean;\n};\n\n/**\n * Register the Apple Mail tools.\n *\n * The registered set is a pure function of `allowWrites` and nothing else. In\n * particular it does NOT vary with whether Full Disk Access is granted: that is\n * a runtime condition which can change while the process lives, and MCP clients\n * cache the tool list, so a tool that appears and disappears would leave clients\n * calling names the server no longer has. Tools that need the index instead\n * return a structured `degraded` result naming the missing capability.\n */\nexport const registerTools = (\n server: McpServer,\n client: AppleMailClient,\n ctx: ToolContext,\n): void => {\n registerDiagnosticsTools(server, client, ctx);\n registerAccountTools(server, client);\n registerSearchTools(server, client);\n registerMessageTools(server, client, ctx.allowWrites);\n /*\n * On every server, write-enabled ones included. It was held to read-only ones\n * at first — not because it is unsafe with writes on, it reaches nothing but\n * the index, but because every tool costs listing tokens on every connect and\n * this one had to prove it saves more than it costs. It has: one grouped\n * question repays the ~716 tokens it lists for several times over, measured in\n * docs/mail-query.md.\n */\n registerQueryTools(server, client);\n\n if (!ctx.allowWrites) return;\n\n registerActionTools(server, client);\n registerComposeTools(server, client);\n};\n","import { registerSurfaceResources, withLazyTools } from \"@mgcrea/mcp-apple-core\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { BUILD_INFO } from \"./build-info.js\";\nimport { AppleMailClient } from \"./client/mail.js\";\nimport type { Logger, OsascriptRunner } from \"./client/osascript.js\";\nimport type { Config } from \"./config.js\";\nimport { MAIL_GUIDE } from \"./guide.js\";\nimport { registerPrompts } from \"./prompts.js\";\nimport { buildDiagnostics } from \"./tools/diagnostics.js\";\nimport { registerTools } from \"./tools/index.js\";\n\nexport const SERVER_NAME = BUILD_INFO.name;\nexport const SERVER_VERSION = BUILD_INFO.version;\n\nexport type CreateServerOptions = {\n config: Config;\n logger?: Logger;\n /** Injected by tests so nothing spawns a process or touches a real Mail. */\n osascript?: OsascriptRunner;\n};\n\nexport type CreatedServer = {\n server: McpServer;\n client: AppleMailClient;\n};\n\n/**\n * Build the server. Side-effect free: it opens no connection, spawns no\n * process and reads no file, so a test can construct it freely and every\n * external dependency arrives through an option.\n */\nexport const createServer = (opts: CreateServerOptions): CreatedServer => {\n const { config } = opts;\n const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });\n\n const client = new AppleMailClient({\n config,\n ...(opts.logger ? { logger: opts.logger } : {}),\n ...(opts.osascript ? { osascript: opts.osascript } : {}),\n });\n\n withLazyTools(\n server,\n {\n surface: \"mail\",\n displayName: \"Mail\",\n lazy: config.lazyTools,\n allowWrites: config.allowWrites,\n },\n (target, allowWrites) => registerTools(target, client, { allowWrites }),\n );\n /*\n * One flag, both primitives — see `exposePrompts` in core's config. A prompt\n * embeds its surface guide, so registering prompts without the resources\n * would leave every expansion naming a `cupertino://…/guide` that this\n * server does not serve.\n */\n if (config.exposePrompts) {\n registerPrompts(server, config.allowWrites);\n registerSurfaceResources(server, {\n surface: \"mail\",\n displayName: \"Mail\",\n guide: MAIL_GUIDE,\n diagnostics: () => buildDiagnostics(client, { allowWrites: config.allowWrites }),\n inventory: {\n describes: \"accounts and mailboxes\",\n // The AppleScript lane, not the index: the Envelope Index stores no\n // account display names at all, so an index-first inventory would have\n // to invent them out of URL fragments. Cost is O(mailboxes), not\n // O(messages) — measured at 0.6s for every account on this machine.\n read: async () =>\n (await client.accounts()).map((a) => ({\n id: a.id,\n name: a.name,\n enabled: a.enabled,\n type: a.accountType,\n emailAddresses: a.emailAddresses,\n mailboxes: a.mailboxes,\n })),\n },\n });\n }\n\n return { server, client };\n};\n"],"mappings":";;;;;;;;;AAWA,MAAM,MAAM,oBAAoB,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG;CAC3E,MAAM;CACN,SAAS;AACX,CAAC;AAID,MAAa,aAAwB;CACnC,MAAM,IAAI;CACV,SAAS,IAAI;CACb,WAAA;CACA,eAAA;AACF;;;;;;;;;;;;ACXA,MAAa,eAA+B;CAAE,SAAS;CAAQ,WAAW;AAAa;;AAiBvF,IAAa,uBAAb,cAA0C,qBAAqB;CAC7D,OAAyB;CAEzB,YAAY,KAAa;EACvB,MACE,uBAAuB,IAAI,kGAE7B;CACF;AACF;;;ACgBA,MAAM,eAAe,KAAK,YAAY,gBAAgB;AAEtD,MAAM,qBAAqB,aAAoC;CAC7D,IAAI;EAIF,OAHiB,YAAY,QAAQ,CAAC,CACnC,QAAQ,MAAM,SAAS,KAAK,CAAC,CAAC,CAAC,CAC/B,UAAU,GAAG,MAAM,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,OAAO,EAAE,MAAM,CAAC,CAAC,CAC9C,CAAC,CAAC,MAAM;CACxB,QAAQ;EAEN,OAAO;CACT;AACF;AAEA,MAAa,uBAAuB,OAAsB,CAAC,MAAoB;CAC7E,MAAM,OAAO,KAAK,QAAQ,QAAQ;CAElC,IAAI,WAA0B;CAC9B,IAAI,YAA2B;CAC/B,IAAI,WAAqC;CAEzC,IAAI,KAAK,mBAAmB;EAC1B,YAAY,KAAK;EACjB,WA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