langmail-mcp 0.1.0 → 0.2.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.
Files changed (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/tool-logging.js +0 -67
  75. package/dist/observability/errors.js +0 -41
  76. package/dist/rules/apply.js +0 -236
  77. package/dist/rules/rule.js +0 -280
  78. package/dist/rules/store.js +0 -92
  79. package/dist/tools/annotations.js +0 -71
  80. package/dist/tools/archive-emails.js +0 -40
  81. package/dist/tools/calendar-lookup.js +0 -64
  82. package/dist/tools/contact-common.js +0 -146
  83. package/dist/tools/contact-format.js +0 -72
  84. package/dist/tools/contact-write-through.js +0 -37
  85. package/dist/tools/create-calendar-event.js +0 -231
  86. package/dist/tools/create-calendar.js +0 -54
  87. package/dist/tools/create-contact.js +0 -172
  88. package/dist/tools/create-draft.js +0 -369
  89. package/dist/tools/create-mail-rule.js +0 -101
  90. package/dist/tools/delete-calendar-event.js +0 -165
  91. package/dist/tools/delete-contact.js +0 -60
  92. package/dist/tools/delete-draft.js +0 -129
  93. package/dist/tools/delete-mail-rule.js +0 -38
  94. package/dist/tools/download-attachment.js +0 -90
  95. package/dist/tools/download-email.js +0 -112
  96. package/dist/tools/draft-common.js +0 -600
  97. package/dist/tools/email-types.js +0 -58
  98. package/dist/tools/error-detail.js +0 -10
  99. package/dist/tools/file-emails-common.js +0 -75
  100. package/dist/tools/format.js +0 -131
  101. package/dist/tools/forward-message.js +0 -237
  102. package/dist/tools/forward-quote.js +0 -179
  103. package/dist/tools/get-draft.js +0 -61
  104. package/dist/tools/get-email.js +0 -164
  105. package/dist/tools/get-thread.js +0 -67
  106. package/dist/tools/keywords.js +0 -43
  107. package/dist/tools/list-calendar-events.js +0 -180
  108. package/dist/tools/list-calendars.js +0 -44
  109. package/dist/tools/list-drafts.js +0 -134
  110. package/dist/tools/list-mail-rules.js +0 -28
  111. package/dist/tools/list-unsubscribe.js +0 -152
  112. package/dist/tools/list-upcoming-birthdays.js +0 -165
  113. package/dist/tools/mail-rule-common.js +0 -43
  114. package/dist/tools/mail-rule-format.js +0 -79
  115. package/dist/tools/mailbox-lookup.js +0 -13
  116. package/dist/tools/mark-emails.js +0 -78
  117. package/dist/tools/merge-contacts.js +0 -145
  118. package/dist/tools/move-calendar-events.js +0 -340
  119. package/dist/tools/move-emails.js +0 -64
  120. package/dist/tools/one-click-post.js +0 -275
  121. package/dist/tools/preview-email.js +0 -204
  122. package/dist/tools/preview-mail-rule.js +0 -79
  123. package/dist/tools/reply-quote.js +0 -426
  124. package/dist/tools/reply-to-message.js +0 -292
  125. package/dist/tools/respond-to-event.js +0 -110
  126. package/dist/tools/result.js +0 -9
  127. package/dist/tools/search-contacts.js +0 -431
  128. package/dist/tools/search-emails.js +0 -570
  129. package/dist/tools/send-draft.js +0 -308
  130. package/dist/tools/trash-emails.js +0 -36
  131. package/dist/tools/unsubscribe-from-list.js +0 -249
  132. package/dist/tools/update-calendar-event.js +0 -973
  133. package/dist/tools/update-calendar.js +0 -100
  134. package/dist/tools/update-contact.js +0 -382
  135. package/dist/tools/update-draft.js +0 -714
  136. package/dist/tools/update-mail-rule.js +0 -103
  137. package/dist/tools/upload-attachments.js +0 -126
@@ -1,600 +0,0 @@
1
- // Shared plumbing for the composition tools (create_draft, get_draft,
2
- // list_drafts, update_draft, send_draft, delete_draft, reply_to_message).
3
- //
4
- // Three things live here because getting them wrong in one tool and right in
5
- // another is exactly the failure the sending surface can't afford:
6
- //
7
- // - address parsing, so `Name <address>` — the form search_contacts hands
8
- // back — is accepted everywhere a recipient is accepted;
9
- // - identity resolution, so the sending address is always one the account is
10
- // actually allowed to send as;
11
- // - reply derivation (recipients, `Re:` subject, In-Reply-To/References), so
12
- // threading is computed server-side from the message being replied to and
13
- // never assembled by the agent.
14
- import { accountIdForMail, accountIdForSubmission, blobUpload, DRAFT_FORWARD_OF_KEYWORD_PREFIX, DRAFT_ID_KEYWORD_PREFIX, DRAFT_KEYWORD, DRAFT_REPLY_TO_KEYWORD_PREFIX, draftCreate, draftDestroy, draftIdResolve, draftList, emailComposeGet, emailSet, emailSubmissionCreate, identityGet, JmapError, LABEL_KEYWORD_PREFIX, mailboxIdsByRoles, threadMessageFind, } from "../jmap/index.js";
15
- import { formatAddressList, formatSize } from "./format.js";
16
- // The read-back budget for a draft's body values, in *octets* (RFC 8621 §4.2) —
17
- // four times the 100_000-*character* cap the composition tools accept, because a
18
- // character can cost up to four octets in UTF-8.
19
- //
20
- // The multiplier is the whole point. At 1× a perfectly legal draft of 100_000
21
- // characters containing anything non-ASCII — an em dash, an accented name, an
22
- // emoji — reads back truncated, and update_draft would re-stage the truncated
23
- // text and destroy the original: a subject-only edit would silently amputate the
24
- // message. Headroom makes that unreachable for any body this surface accepted;
25
- // `bodyTruncated` catches a body some other client staged.
26
- export const MAX_DRAFT_BODY_VALUE_BYTES = 400_000;
27
- // Enough of the body for a human to recognise what was staged without paying
28
- // for the whole thing twice (the agent wrote it — it already has the text).
29
- const BODY_PREVIEW_CHARS = 500;
30
- // --- addresses -------------------------------------------------------------
31
- // `Display Name <local@domain>`. The name is whatever precedes the bracketed
32
- // address, quotes and all — anchoring on the brackets rather than on a quoting
33
- // convention means a nickname (`Nadia "Nads" Bram <n@example.org>`) parses
34
- // instead of being bounced back at the caller.
35
- const NAMED_ADDRESS_RE = /^\s*(.*?)\s*<([^<>\s]+)>\s*$/u;
36
- // Surrounding quotes on a display name are RFC 5322 syntax, not part of the
37
- // name.
38
- const WRAPPING_QUOTES_RE = /^"(.*)"$/u;
39
- // Deliberately permissive: one `@`, no whitespace or angle brackets, something
40
- // either side. Stalwart is the authority on deliverability, and a stricter
41
- // regex here would reject valid addresses (RFC 5322 local parts are wild)
42
- // without making an invalid one any less rejected downstream.
43
- const BARE_ADDRESS_RE = /^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/u;
44
- // Parse one recipient in either the bare or `Name <address>` form. Returns null
45
- // for anything that isn't an address — the caller reports it by name rather
46
- // than silently dropping a recipient the user asked for.
47
- export const parseAddress = (input) => {
48
- const named = NAMED_ADDRESS_RE.exec(input);
49
- if (named) {
50
- const address = named[2] ?? "";
51
- if (!BARE_ADDRESS_RE.test(address)) {
52
- return null;
53
- }
54
- const raw = (named[1] ?? "").trim();
55
- const name = (WRAPPING_QUOTES_RE.exec(raw)?.[1] ?? raw).trim();
56
- return name ? { email: address, name } : { email: address };
57
- }
58
- const bare = input.trim();
59
- return BARE_ADDRESS_RE.test(bare) ? { email: bare } : null;
60
- };
61
- const parseAddressList = (values) => {
62
- const addresses = [];
63
- const invalid = [];
64
- for (const value of values ?? []) {
65
- const parsed = parseAddress(value);
66
- if (parsed) {
67
- addresses.push(parsed);
68
- }
69
- else {
70
- invalid.push(value);
71
- }
72
- }
73
- return { addresses, invalid };
74
- };
75
- // How many people a message is addressed to, across all three fields. Counting
76
- // beats "was `to` supplied", because `to: []` is present but empty and addresses
77
- // nobody. Deliberately blind to the element type so the staging check (raw
78
- // strings from the caller) and the send check (parsed addresses off the record)
79
- // cannot drift apart — they already did once, which is why this is shared.
80
- export const countRecipients = (fields) => (fields.to?.length ?? 0) +
81
- (fields.cc?.length ?? 0) +
82
- (fields.bcc?.length ?? 0);
83
- export const parseRecipients = (fields) => {
84
- const to = parseAddressList(fields.to);
85
- const cc = parseAddressList(fields.cc);
86
- const bcc = parseAddressList(fields.bcc);
87
- const invalid = [...to.invalid, ...cc.invalid, ...bcc.invalid];
88
- if (invalid.length > 0) {
89
- return {
90
- error: `Not a valid email address: ${invalid.join(", ")}. ` +
91
- 'Pass a bare address (person@example.com) or the "Name <person@example.com>" form.',
92
- };
93
- }
94
- // Deduped for the same reason the derived reply recipients are: the same
95
- // person twice on one line is a visible oddity in the recipient's client, and
96
- // an agent that resolved a contact twice shouldn't produce it.
97
- return {
98
- ...(fields.to ? { to: dedupeAddresses(to.addresses, []) } : {}),
99
- ...(fields.cc ? { cc: dedupeAddresses(cc.addresses, []) } : {}),
100
- ...(fields.bcc ? { bcc: dedupeAddresses(bcc.addresses, []) } : {}),
101
- };
102
- };
103
- const sameAddress = (a, b) => a.toLowerCase() === b.toLowerCase();
104
- // Drop duplicates (case-insensitively on the address) and anything already
105
- // spoken for, keeping first-seen order.
106
- const dedupeAddresses = (addresses, exclude) => {
107
- const seen = new Set(exclude.map((e) => e.toLowerCase()));
108
- const out = [];
109
- for (const address of addresses) {
110
- const key = address.email.toLowerCase();
111
- if (!seen.has(key)) {
112
- seen.add(key);
113
- out.push(address);
114
- }
115
- }
116
- return out;
117
- };
118
- // The account's configured display name wins over one the caller typed: it's
119
- // what the user's other mail goes out as, and a draft that reads differently
120
- // from the rest of their Sent folder is the tell that an agent wrote it.
121
- //
122
- // On Stalwart that name is the account's `description`; an account without
123
- // one gets its address there (Stalwart 1.1.1). An account whose description
124
- // is the user's display name therefore sends under that name, and no tool
125
- // that sends has to patch it up.
126
- const identityAddress = (identity, requestedName) => {
127
- const name = identity.name?.trim() || requestedName;
128
- return name ? { email: identity.email, name } : { email: identity.email };
129
- };
130
- // Pick the Identity a message goes out as. `from` selects among the account's
131
- // aliases and is rejected if it names an address the account may not send as —
132
- // that check has to be server-side, because an agent has no way to know which
133
- // aliases exist and a silently-substituted sender is worse than an error.
134
- export const resolveIdentity = async (deps, p) => {
135
- const identities = await deps.identityGet({
136
- accountId: p.accountId,
137
- apiUrl: "",
138
- authorization: p.authorization,
139
- });
140
- if (identities.length === 0) {
141
- return {
142
- error: "This account has no sending identity configured, so nothing can be composed or sent.",
143
- };
144
- }
145
- const selfAddresses = [
146
- p.principal,
147
- ...identities.map((identity) => identity.email),
148
- ];
149
- let wanted = p.principal;
150
- let requestedName;
151
- if (p.from !== undefined) {
152
- const parsed = parseAddress(p.from);
153
- if (!parsed) {
154
- return { error: `Not a valid sending address: ${p.from}.` };
155
- }
156
- wanted = parsed.email;
157
- requestedName = parsed.name ?? undefined;
158
- }
159
- const hit = identities.find((identity) => sameAddress(identity.email, wanted));
160
- if (!hit) {
161
- if (p.from !== undefined) {
162
- return {
163
- error: `This account cannot send as ${wanted}. Available sending addresses: ` +
164
- `${identities.map((identity) => identity.email).join(", ")}.`,
165
- };
166
- }
167
- // The principal isn't among the identities — an aliased login, say. With a
168
- // single identity there is only one address this account could possibly
169
- // send as, so use it. With several, picking one would be a guess at which
170
- // of the user's addresses they meant, and Identity/get guarantees no
171
- // ordering to make that guess with — so ask instead of silently choosing.
172
- const [only] = identities;
173
- if (identities.length > 1 || !only) {
174
- return {
175
- error: `Could not tell which address to send as: the signed-in address is not one of this account's ` +
176
- `sending identities. Pass \`from\` with one of: ${identities.map((i) => i.email).join(", ")}.`,
177
- };
178
- }
179
- return {
180
- address: identityAddress(only),
181
- identityId: only.id,
182
- selfAddresses,
183
- };
184
- }
185
- return {
186
- address: identityAddress(hit, requestedName),
187
- identityId: hit.id,
188
- selfAddresses,
189
- };
190
- };
191
- // --- replies ---------------------------------------------------------------
192
- // The reply's recipients, derived from the message being answered. `Reply-To`
193
- // wins over `From` when the sender set it (RFC 5322 §3.6.2 — that's what it's
194
- // for); reply-all folds the original To and Cc into Cc.
195
- //
196
- // `self` is every address that is the user (see `ResolvedIdentity.selfAddresses`)
197
- // and all of them are excluded, not just the sending one: a message addressed to
198
- // one of the user's aliases would otherwise put that alias on the reply's Cc,
199
- // delivering the user their own reply — and, once mail rules or an auto-responder
200
- // exist on that alias, doing it in a loop.
201
- export const replyRecipients = (original, self, replyAll) => {
202
- const replyTo = original.replyTo ?? [];
203
- const to = dedupeAddresses(replyTo.length > 0 ? replyTo : (original.from ?? []), self);
204
- if (!replyAll) {
205
- return { cc: [], to };
206
- }
207
- const others = [...(original.to ?? []), ...(original.cc ?? [])];
208
- return {
209
- cc: dedupeAddresses(others, [...self, ...to.map((a) => a.email)]),
210
- to,
211
- };
212
- };
213
- const RE_PREFIX_RE = /^re\s*:/iu;
214
- export const replySubject = (subject) => {
215
- const trimmed = (subject ?? "").trim();
216
- if (!trimmed) {
217
- return "Re:";
218
- }
219
- return RE_PREFIX_RE.test(trimmed) ? trimmed : `Re: ${trimmed}`;
220
- };
221
- // The RFC 5322 threading headers, in RFC 8621's bare-Message-ID form. Built
222
- // from the original's own headers so a reply lands in the same conversation in
223
- // every client, not just in Langmail's own threading.
224
- export const replyThreading = (original) => {
225
- const messageIds = original.messageId ?? [];
226
- const references = [...(original.references ?? []), ...messageIds];
227
- return {
228
- inReplyTo: messageIds,
229
- references: [...new Set(references)],
230
- };
231
- };
232
- // The one rule both reply paths enforce, in one place so they cannot disagree
233
- // about it: `replyAll` and explicit recipients are mutually exclusive.
234
- //
235
- // "Reply to everyone, but only these people" has no defensible reading, and
236
- // resolving it silently is worse than refusing. Per-field precedence looks
237
- // harmless and isn't: with `replyAll` plus an explicit `to`, the derived Cc
238
- // excludes the *derived* To, so the person actually being answered lands in
239
- // neither list and the reply goes only to the bystanders. With `replyAll` plus
240
- // an explicit `cc`, `replyAll` becomes a silent no-op.
241
- export const replyConflictError = (p) => {
242
- if (p.replyAll !== true) {
243
- return null;
244
- }
245
- if (p.to !== undefined || p.cc !== undefined || p.bcc !== undefined) {
246
- return ("replyAll cannot be combined with to/cc/bcc. Either reply to everyone on the original, or name the " +
247
- "recipients explicitly — not both.");
248
- }
249
- return null;
250
- };
251
- // --- draft round-tripping --------------------------------------------------
252
- // Concatenate the fetched values of the body parts of one media type. Filtering
253
- // on `type` matters: RFC 8621's `textBody` falls back to the text/html part on
254
- // an html-only message, and reading that back as `text` would turn a staged
255
- // html draft into a plain-text draft full of markup on the next edit.
256
- const bodyOfType = (record, parts, mediaType) => {
257
- const values = record.bodyValues ?? {};
258
- const matching = (parts ?? []).filter((part) => part.type === mediaType);
259
- if (matching.length === 0) {
260
- return;
261
- }
262
- // Not trimmed: this value is re-staged verbatim by update_draft, and trimming
263
- // would silently edit a body the caller didn't touch.
264
- return matching
265
- .map((part) => (part.partId ? (values[part.partId]?.value ?? "") : ""))
266
- .join("\n");
267
- };
268
- // Whether any body value came back truncated. A truncated read is fine to
269
- // *display* and unsafe to *re-stage*, so this is the signal update_draft refuses
270
- // on rather than quietly shortening the user's message.
271
- // Scoped to the parts that actually make up the body, because `bodyValues` holds
272
- // more than those: the read asks for `fetchAllBodyValues`, and RFC 8621 §4.2.2
273
- // defines that as every text/* part in the structure — a .csv or .txt
274
- // *attachment* included. Those come back truncated at the same budget, and a
275
- // truncated attachment is not a truncated body: its bytes are re-referenced by
276
- // blobId on a rewrite, never re-staged from this text, so nothing is at risk.
277
- // Checking them too refused perfectly lossless edits with a diagnosis about the
278
- // body — including an `attachments: []` that meant to remove the very file
279
- // causing it. Unreachable before this surface could edit an attached draft at
280
- // all, which is why it surfaces now.
281
- export const bodyTruncated = (record) => {
282
- const bodyPartIds = new Set([...(record.textBody ?? []), ...(record.htmlBody ?? [])].flatMap((part) => part.partId ? [part.partId] : []));
283
- return Object.entries(record.bodyValues ?? {}).some(([partId, value]) => value.isTruncated === true && bodyPartIds.has(partId));
284
- };
285
- // The attached files of a stored draft, in the shape a re-create can reference.
286
- //
287
- // Only the blobId is carried, never the bytes: an edit rewrites the message, and
288
- // re-referencing the existing blobs is what lets it do so without downloading
289
- // and re-uploading a 5 MB PDF the caller never even mentioned. Parts with no
290
- // blobId are dropped — an EmailBodyPart without one names nothing that can be
291
- // re-attached — which is why `unreferencableAttachments` exists to stop an edit
292
- // before that drop can become a silent loss.
293
- //
294
- // RFC 8621 lists most files under `attachments`, but an image inline in a
295
- // `multipart/mixed` body — the shape Apple Mail sends, and the one a staged
296
- // forward that carries such an image reads back as — sits in `textBody`/
297
- // `htmlBody` between the text parts. Those are files too, so they are carried
298
- // as well, inline as they were presented; a part listed in both body lists
299
- // counts once.
300
- export const attachmentsFromRecord = (record) => {
301
- const inBody = [...(record.textBody ?? []), ...(record.htmlBody ?? [])]
302
- .filter((part) => part.type && !part.type.startsWith("text/"))
303
- .map((part) => ({ ...part, disposition: part.disposition ?? "inline" }));
304
- const seen = new Set();
305
- return [...(record.attachments ?? []), ...inBody].flatMap((part) => {
306
- const key = part.partId ?? part.blobId;
307
- if (!part.blobId || (key && seen.has(key))) {
308
- return [];
309
- }
310
- if (key) {
311
- seen.add(key);
312
- }
313
- return [
314
- {
315
- blobId: part.blobId,
316
- ...(part.cid ? { cid: part.cid } : {}),
317
- // Preserved, not re-derived — see DraftAttachment.disposition.
318
- ...(part.disposition ? { disposition: part.disposition } : {}),
319
- ...(part.location ? { location: part.location } : {}),
320
- ...(part.name ? { name: part.name } : {}),
321
- ...(typeof part.size === "number" ? { size: part.size } : {}),
322
- ...(part.type ? { type: part.type } : {}),
323
- },
324
- ];
325
- });
326
- };
327
- // The attached files of a stored draft that could *not* be carried onto a
328
- // replacement, named for a refusal message.
329
- //
330
- // RFC 8621 lets an EmailBodyPart's `blobId` be null (it is, for a multipart
331
- // part), and a part without one cannot be re-referenced by the new message. An
332
- // edit that quietly skipped it would destroy the original after writing a
333
- // replacement missing the file — unrecoverable, and reported as a success.
334
- // Refusing costs the caller an edit; the alternative costs them the file.
335
- export const unreferencableAttachments = (record) => (record.attachments ?? [])
336
- .filter((part) => !part.blobId)
337
- .map((part) => part.name ?? "(unnamed)");
338
- // Read a stored draft back into the composable shape, so update_draft can merge
339
- // changes onto it and re-create the message (RFC 8621 makes an Email's content
340
- // immutable — see src/jmap drafts.ts).
341
- export const draftFromRecord = (record) => {
342
- const text = bodyOfType(record, record.textBody, "text/plain");
343
- const html = bodyOfType(record, record.htmlBody, "text/html");
344
- const attachments = attachmentsFromRecord(record);
345
- return {
346
- from: record.from ?? [],
347
- ...(attachments.length > 0 ? { attachments } : {}),
348
- ...(record.to ? { to: record.to } : {}),
349
- ...(record.cc ? { cc: record.cc } : {}),
350
- ...(record.bcc ? { bcc: record.bcc } : {}),
351
- ...(record.replyTo ? { replyTo: record.replyTo } : {}),
352
- ...(record.subject === null || record.subject === undefined
353
- ? {}
354
- : { subject: record.subject }),
355
- ...(record.inReplyTo ? { inReplyTo: record.inReplyTo } : {}),
356
- ...(record.references ? { references: record.references } : {}),
357
- ...(text === undefined ? {} : { text }),
358
- ...(html === undefined ? {} : { html }),
359
- };
360
- };
361
- export const isDraft = (record) => Boolean(record.keywords?.[DRAFT_KEYWORD]);
362
- // A draft moved to Trash still carries `$draft`, so `isDraft` alone would read,
363
- // edit or send one the user has already discarded.
364
- export const isTrashed = (record, mailboxes) => mailboxes.trash !== null && Boolean(record.mailboxIds?.[mailboxes.trash]);
365
- // How to get a discarded draft back, for the refusals that meet one.
366
- export const restoreFromTrashHint = (record) => `To restore it, move it back with move_emails, passing id ${record.id} and mailbox "Drafts".`;
367
- // --- stable draft ids --------------------------------------------------------
368
- const keywordSuffix = (record, prefix) => {
369
- const keyword = Object.keys(record.keywords ?? {}).find((k) => k.startsWith(prefix));
370
- return keyword ? keyword.slice(prefix.length) : null;
371
- };
372
- // The id a draft is known by on this surface: a random token create_draft mints
373
- // and every revision carries as a `$draftid:` keyword (see src/jmap
374
- // drafts.ts). A token, not the first revision's JMAP id: Stalwart may hand a
375
- // freed id out again, and a stale keyword naming it would then resolve another
376
- // draft's id to this one. Null for a draft staged by another client, which gets
377
- // its token on its first edit and until then is known by its JMAP id. This is
378
- // what create_draft, update_draft and get_draft report, so the id an agent
379
- // holds keeps working across any number of edits.
380
- export const stableDraftId = (record) => keywordSuffix(record, DRAFT_ID_KEYWORD_PREFIX);
381
- // The keyword a revision carries so `loadDraft` can find it by its stable id.
382
- export const stableDraftIdKeyword = (draftId) => `${DRAFT_ID_KEYWORD_PREFIX}${draftId}`;
383
- // The keyword create_draft puts on a reply, naming the message it answers — see
384
- // src/jmap drafts.ts for why the In-Reply-To header is not enough.
385
- export const replyOriginalKeyword = (originalId) => `${DRAFT_REPLY_TO_KEYWORD_PREFIX}${originalId}`;
386
- // The JMAP id of the message a reply draft answers, when create_draft recorded it.
387
- export const replyOriginalId = (record) => keywordSuffix(record, DRAFT_REPLY_TO_KEYWORD_PREFIX);
388
- // The keyword a staged forward carries, naming the message it forwards — see
389
- // src/jmap drafts.ts.
390
- export const forwardOriginalKeyword = (originalId) => `${DRAFT_FORWARD_OF_KEYWORD_PREFIX}${originalId}`;
391
- // The JMAP id of the message a forward draft forwards, when it was staged here.
392
- export const forwardOriginalId = (record) => keywordSuffix(record, DRAFT_FORWARD_OF_KEYWORD_PREFIX);
393
- // RFC 5788 / RFC 8621 §4.1.1: the message has been forwarded. Clients show it
394
- // next to the message, the way `$answered` marks a reply.
395
- const FORWARDED_KEYWORD = "$forwarded";
396
- // Mark the original of a forward that has gone out. Run once the send has
397
- // succeeded, and never thrown from: the mail is already delivered, so a failure
398
- // here is a line in the result, not a failed send. Returns that line, or null.
399
- export const markForwarded = async (deps, p) => {
400
- try {
401
- await deps.emailKeywordsSet({
402
- accountId: p.accountId,
403
- apiUrl: "",
404
- authorization: p.authorization,
405
- changes: { keywords: { [FORWARDED_KEYWORD]: true } },
406
- id: p.id,
407
- });
408
- return null;
409
- }
410
- catch {
411
- return `The forward went out, but the original (${p.id}) could not be marked as forwarded.`;
412
- }
413
- };
414
- // RFC 8620 §1.2 Id syntax. Anything else cannot be a draft id, and spliced into
415
- // a keyword it could make the query itself invalid.
416
- const JMAP_ID_RE = /^[\w-]{1,255}$/u;
417
- // Read a draft by the id the caller holds: its stable id, or the JMAP id of
418
- // any message (a draft found through search_emails, say). The keyword lookup
419
- // runs first, because a stable id may still name a message — the first
420
- // revision, when an edit created its replacement but failed to destroy it — and
421
- // that superseded copy must never be what is read, edited, or sent.
422
- export const loadDraft = async (deps, p) => {
423
- const current = JMAP_ID_RE.test(p.draftId)
424
- ? await deps.draftIdResolve({
425
- accountId: p.accountId,
426
- apiUrl: "",
427
- authorization: p.authorization,
428
- draftId: p.draftId,
429
- })
430
- : null;
431
- return deps.emailComposeGet({
432
- accountId: p.accountId,
433
- apiUrl: "",
434
- authorization: p.authorization,
435
- id: current ?? p.draftId,
436
- maxBodyValueBytes: MAX_DRAFT_BODY_VALUE_BYTES,
437
- });
438
- };
439
- // Why the server refused to write a draft, phrased for the agent that has to
440
- // fix it — or null when the failure was not the server saying no, in which case
441
- // the caller rethrows rather than reporting a refusal that never happened.
442
- //
443
- // The attachment hint is the reason this exists. Stalwart answers an
444
- // unresolvable `attachments` blobId with `blobNotFound`, which does not tell
445
- // the agent what to do next — while "re-read the blobId" is very often the
446
- // right move, because a blobId is per-account and does not outlive the message
447
- // it was read from.
448
- export const draftRefusalReason = (error, draft) => {
449
- if (!(error instanceof JmapError) || error.errorType === undefined) {
450
- return null;
451
- }
452
- const hint = (draft.attachments ?? []).length > 0 && error.errorType === "blobNotFound"
453
- ? " The likeliest cause is an attachment blobId the server does not recognise: blobIds belong to one " +
454
- "account and do not outlive the message they were read from, so re-read it with get_email or " +
455
- "get_draft and use the blobId it reports now — or pass the file as base64 `content` instead."
456
- : "";
457
- return `The server refused this draft (${error.errorType}).${hint}`;
458
- };
459
- // The user-facing `$label:` tags on a message. Carried onto the replacement when
460
- // a draft is edited: an edit rewrites the message, so without this a draft the
461
- // user had filed under a label would come back untagged.
462
- export const draftLabelKeywords = (record) => Object.entries(record.keywords ?? {})
463
- .filter(([keyword, set]) => set && keyword.startsWith(LABEL_KEYWORD_PREFIX))
464
- .map(([keyword]) => keyword);
465
- // --- formatting ------------------------------------------------------------
466
- const bodyKind = (draft) => {
467
- if (draft.text !== undefined && draft.html !== undefined) {
468
- return "text + html";
469
- }
470
- if (draft.html !== undefined) {
471
- return "html";
472
- }
473
- return "text";
474
- };
475
- const bodyPreview = (draft) => {
476
- const flat = (draft.text ?? draft.html ?? "").replace(/\s+/gu, " ").trim();
477
- if (!flat) {
478
- return "(empty)";
479
- }
480
- return flat.length > BODY_PREVIEW_CHARS
481
- ? `${flat.slice(0, BODY_PREVIEW_CHARS)}…`
482
- : flat;
483
- };
484
- // The message itself, as a composition tool reports it back: resolved
485
- // recipients and a body preview, so the agent can tell the user exactly what
486
- // was staged (or sent) without a second call.
487
- //
488
- // The id line is the caller's to write, because the id means different things
489
- // on the two paths — a `draftId` to send later, or the `messageId` of mail that
490
- // has already gone — and printing "draftId" under a "Sent." heading would be
491
- // actively misleading.
492
- export const formatDraft = (draft, opts = {}) => {
493
- const lines = [
494
- `from: ${formatAddressList(draft.from)}`,
495
- `to: ${formatAddressList(draft.to) || "(none)"}`,
496
- ];
497
- if (draft.cc && draft.cc.length > 0) {
498
- lines.push(`cc: ${formatAddressList(draft.cc)}`);
499
- }
500
- if (draft.bcc && draft.bcc.length > 0) {
501
- lines.push(`bcc: ${formatAddressList(draft.bcc)}`);
502
- }
503
- lines.push(`subject: ${draft.subject || "(no subject)"}`);
504
- if (opts.threadId) {
505
- lines.push(`threadId: ${opts.threadId}`);
506
- }
507
- if (draft.inReplyTo && draft.inReplyTo.length > 0) {
508
- lines.push("threading: In-Reply-To/References set — this message continues an existing conversation");
509
- }
510
- lines.push(`body (${bodyKind(draft)}): ${bodyPreview(draft)}`);
511
- lines.push(...attachmentLines(draft.attachments ?? [], opts.unreferencable ?? []));
512
- return lines.join("\n");
513
- };
514
- // What is attached, itemised. This is the half of the draft a human reviewing it
515
- // cannot otherwise see — the body they can read back, but "did the invoice
516
- // actually make it on?" is only answerable if the files are listed — so it is
517
- // printed by every composition tool, not just get_draft.
518
- //
519
- // The blobId is on the line because it is the handle the next call needs: an
520
- // update_draft that keeps this file, or a second message that attaches it too,
521
- // both reference it and neither should have to re-upload anything.
522
- const attachmentLines = (attachments, unreferencable) => {
523
- const total = attachments.length + unreferencable.length;
524
- if (total === 0) {
525
- return [];
526
- }
527
- return [
528
- `attachments (${total}):`,
529
- ...attachments.map((attachment, index) => {
530
- const pieces = [
531
- attachment.name ?? "(unnamed)",
532
- attachment.type ?? "application/octet-stream",
533
- ];
534
- if (typeof attachment.size === "number") {
535
- pieces.push(formatSize(attachment.size));
536
- }
537
- return ` ${index + 1}. ${pieces.join(" — ")} — blobId: ${attachment.blobId}`;
538
- }),
539
- ...unreferencable.map((name, index) => ` ${attachments.length + index + 1}. ${name} — no blobId, so this file cannot be re-attached: it will ` +
540
- "be sent with the draft, but an edit here cannot carry it across. Edit the draft in the user's mail client to change it."),
541
- ];
542
- };
543
- // --- live-deps wiring ----------------------------------------------------
544
- // `live` is shared across the JMAP tools (built once in the handler) so a
545
- // bearer's session is resolved once per request cycle, not once per tool.
546
- export const makeLiveDeps = (live) => ({
547
- blobUpload: async (p) => blobUpload({
548
- ...p,
549
- uploadUrl: (await live.getSession(p.authorization)).uploadUrl,
550
- }),
551
- draftCreate: async (p) => draftCreate({
552
- ...p,
553
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
554
- }),
555
- draftDestroy: async (p) => draftDestroy({
556
- ...p,
557
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
558
- }),
559
- draftIdResolve: async (p) => draftIdResolve({
560
- ...p,
561
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
562
- }),
563
- draftList: async (p) => draftList({
564
- ...p,
565
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
566
- }),
567
- emailComposeGet: async (p) => emailComposeGet({
568
- ...p,
569
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
570
- }),
571
- emailKeywordsSet: async (p) => emailSet({ ...p, apiUrl: (await live.getSession(p.authorization)).apiUrl }),
572
- emailSubmissionCreate: async (p) => emailSubmissionCreate({
573
- ...p,
574
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
575
- }),
576
- identityGet: async (p) => identityGet({
577
- ...p,
578
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
579
- }),
580
- resolveAccountId: live.resolveAccountId,
581
- resolveComposeMailboxes: async (authorization) => {
582
- const session = await live.getSession(authorization);
583
- const byRole = await mailboxIdsByRoles({
584
- accountId: accountIdForMail(session),
585
- apiUrl: session.apiUrl,
586
- authorization,
587
- roles: ["drafts", "sent", "trash"],
588
- });
589
- return {
590
- drafts: byRole.drafts ?? null,
591
- sent: byRole.sent ?? null,
592
- trash: byRole.trash ?? null,
593
- };
594
- },
595
- resolveSubmissionAccountId: async (authorization) => accountIdForSubmission(await live.getSession(authorization)),
596
- threadMessageFind: async (p) => threadMessageFind({
597
- ...p,
598
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
599
- }),
600
- });
@@ -1,58 +0,0 @@
1
- // The email-type taxonomy: the exact set of types Langmail's classifier
2
- // assigns, the vocabulary behind the `$type:` JMAP keywords, and the value
3
- // set `search_emails` exposes as a filter. Inlined from Langmail's hosted
4
- // code; keys, glosses and order must stay the same as there.
5
- /**
6
- * The ten classified types, in the order Langmail's classifier prompt lists
7
- * them. Keys are used verbatim as `$type:` keyword suffixes and as
8
- * `search_emails` enum values, so they must stay lowercase, slug-stable, and
9
- * free of RFC 8621's forbidden keyword characters.
10
- */
11
- export const EMAIL_TYPES = {
12
- direct: {
13
- name: "💬 Direct",
14
- search: "Person-to-person mail written by an individual, with no platform in between.",
15
- },
16
- newsletter: {
17
- name: "📧 Newsletter",
18
- search: "Recurring updates, news digests, and curated broadcast content.",
19
- },
20
- promotional: {
21
- name: "🎯 Promotional",
22
- search: "Marketing mail, sales pitches, and discount offers.",
23
- },
24
- notification: {
25
- name: "🔔 Notification",
26
- search: "Platform activity alerts and account notices such as billing or subscription problems.",
27
- },
28
- ticket: {
29
- name: "🎫 Ticket",
30
- search: "Event tickets: theater, cinema, concerts, conferences.",
31
- },
32
- receipt: {
33
- name: "🧾 Receipt",
34
- search: "Transaction receipts and payment confirmations.",
35
- },
36
- order: {
37
- name: "📦 Order",
38
- search: "Order confirmations, shipping updates, delivery tracking, returns and refunds.",
39
- },
40
- scheduling: {
41
- name: "📅 Scheduling",
42
- search: "Calendar invites and booking confirmations — hotels, flights, restaurants, meetings, appointments.",
43
- },
44
- security_alert: {
45
- name: "🔐 Security Alert",
46
- search: "Login alerts, password changes, verification codes, and account recovery notices.",
47
- },
48
- terms: {
49
- name: "📜 Terms",
50
- search: "Terms of service and privacy policy updates, and other legal or compliance notices.",
51
- },
52
- };
53
- /**
54
- * The taxonomy keys as a non-empty tuple — what `z.enum` and the MCP search
55
- * enum both need, and the iteration order for "clear every other type keyword"
56
- * writes.
57
- */
58
- export const EMAIL_TYPE_VALUES = Object.keys(EMAIL_TYPES);
@@ -1,10 +0,0 @@
1
- import { JmapError } from "../jmap/index.js";
2
- // A log-safe description of a failed JMAP call. JmapError messages are
3
- // status-only; anything else is reduced to its name so a fetch-level error
4
- // can't leak a URL that embeds the accountId (no user IDs in logs).
5
- export const errorDetail = (err) => {
6
- if (err instanceof JmapError) {
7
- return err.message;
8
- }
9
- return err instanceof Error ? err.name : "unknown";
10
- };