langmail-mcp 0.0.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 (138) 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/test-client.js +0 -43
  75. package/dist/mcp/tool-logging.js +0 -67
  76. package/dist/observability/errors.js +0 -41
  77. package/dist/rules/apply.js +0 -236
  78. package/dist/rules/rule.js +0 -280
  79. package/dist/rules/store.js +0 -92
  80. package/dist/tools/annotations.js +0 -71
  81. package/dist/tools/archive-emails.js +0 -40
  82. package/dist/tools/calendar-lookup.js +0 -64
  83. package/dist/tools/contact-common.js +0 -146
  84. package/dist/tools/contact-format.js +0 -72
  85. package/dist/tools/contact-write-through.js +0 -37
  86. package/dist/tools/create-calendar-event.js +0 -231
  87. package/dist/tools/create-calendar.js +0 -54
  88. package/dist/tools/create-contact.js +0 -172
  89. package/dist/tools/create-draft.js +0 -369
  90. package/dist/tools/create-mail-rule.js +0 -101
  91. package/dist/tools/delete-calendar-event.js +0 -165
  92. package/dist/tools/delete-contact.js +0 -60
  93. package/dist/tools/delete-draft.js +0 -129
  94. package/dist/tools/delete-mail-rule.js +0 -38
  95. package/dist/tools/download-attachment.js +0 -90
  96. package/dist/tools/download-email.js +0 -112
  97. package/dist/tools/draft-common.js +0 -600
  98. package/dist/tools/email-types.js +0 -58
  99. package/dist/tools/error-detail.js +0 -10
  100. package/dist/tools/file-emails-common.js +0 -75
  101. package/dist/tools/format.js +0 -131
  102. package/dist/tools/forward-message.js +0 -237
  103. package/dist/tools/forward-quote.js +0 -179
  104. package/dist/tools/get-draft.js +0 -61
  105. package/dist/tools/get-email.js +0 -164
  106. package/dist/tools/get-thread.js +0 -67
  107. package/dist/tools/keywords.js +0 -43
  108. package/dist/tools/list-calendar-events.js +0 -180
  109. package/dist/tools/list-calendars.js +0 -44
  110. package/dist/tools/list-drafts.js +0 -134
  111. package/dist/tools/list-mail-rules.js +0 -28
  112. package/dist/tools/list-unsubscribe.js +0 -152
  113. package/dist/tools/list-upcoming-birthdays.js +0 -165
  114. package/dist/tools/mail-rule-common.js +0 -43
  115. package/dist/tools/mail-rule-format.js +0 -79
  116. package/dist/tools/mailbox-lookup.js +0 -13
  117. package/dist/tools/mark-emails.js +0 -78
  118. package/dist/tools/merge-contacts.js +0 -145
  119. package/dist/tools/move-calendar-events.js +0 -340
  120. package/dist/tools/move-emails.js +0 -64
  121. package/dist/tools/one-click-post.js +0 -275
  122. package/dist/tools/preview-email.js +0 -204
  123. package/dist/tools/preview-mail-rule.js +0 -79
  124. package/dist/tools/reply-quote.js +0 -426
  125. package/dist/tools/reply-to-message.js +0 -292
  126. package/dist/tools/respond-to-event.js +0 -110
  127. package/dist/tools/result.js +0 -9
  128. package/dist/tools/search-contacts.js +0 -431
  129. package/dist/tools/search-emails.js +0 -570
  130. package/dist/tools/send-draft.js +0 -308
  131. package/dist/tools/trash-emails.js +0 -36
  132. package/dist/tools/unsubscribe-from-list.js +0 -249
  133. package/dist/tools/update-calendar-event.js +0 -973
  134. package/dist/tools/update-calendar.js +0 -100
  135. package/dist/tools/update-contact.js +0 -382
  136. package/dist/tools/update-draft.js +0 -714
  137. package/dist/tools/update-mail-rule.js +0 -103
  138. package/dist/tools/upload-attachments.js +0 -126
@@ -1,131 +0,0 @@
1
- // The thin IO layer over the fold: find-or-create the collected book, look
2
- // up candidate cards, fold, apply. Deps are injected so both writers test
3
- // against fakes; `liveCollectionDeps` binds the real `src/jmap`
4
- // wrappers. All calls run under the caller's own credential — the poller's
5
- // Basic authorization or the MCP request bearer — so collection writes into
6
- // each user's own address book under the user's own Stalwart identity.
7
- import { addressBookCreate, addressBookList, ContactUidTakenError, contactCardCreate, contactCardDestroy, contactCardGet, contactCardQuery, contactCardUpdate, } from "../jmap/index.js";
8
- import { normalizeAddress } from "./address-class.js";
9
- import { cardAddresses, collectedUid } from "./card.js";
10
- import { COLLECTED_BOOK_NAME } from "./constants.js";
11
- import { foldObservations } from "./fold.js";
12
- export const liveCollectionDeps = {
13
- addressBookCreate,
14
- addressBookList,
15
- contactCardCreate,
16
- contactCardDestroy,
17
- contactCardGet,
18
- contactCardQuery,
19
- contactCardUpdate,
20
- };
21
- // Page size for the candidate query. The whole candidate set is always
22
- // fetched (paged until exhausted) — truncating it would blind the fold to
23
- // existing cards and re-create people, and a 200-message backfill page can
24
- // legitimately reference more than one page of candidates.
25
- const CANDIDATE_PAGE_SIZE = 100;
26
- // Every card matching any of the conditions, paged until exhausted.
27
- const candidates = async (deps, ctx, conditions) => {
28
- const ids = [];
29
- for (let position = 0;; position += CANDIDATE_PAGE_SIZE) {
30
- const page = await deps.contactCardQuery({
31
- ...ctx,
32
- filter: { conditions, operator: "OR" },
33
- limit: CANDIDATE_PAGE_SIZE,
34
- position,
35
- });
36
- ids.push(...page);
37
- if (page.length < CANDIDATE_PAGE_SIZE) {
38
- break;
39
- }
40
- }
41
- return deps.contactCardGet({ ...ctx, ids });
42
- };
43
- // Collect one batch of observations into the user's address book. Callers
44
- // wrap this in their own failure policy: a collection write must never
45
- // block mail analysis or fail a scheduling action.
46
- //
47
- // Read-modify-write without a compare-and-swap: the fold builds its patch
48
- // from the cards read above, so two writers racing on the same person (the
49
- // poller's batch and a calendar write-through firing together) can have the
50
- // later write replace the extension entry from a stale snapshot, dropping a
51
- // few counter increments or log entries. Accepted MVP gap, in the same
52
- // class as the backfill's re-run double-count: identity data — addresses,
53
- // names, grades — is unaffected, only the volume signals drift slightly,
54
- // and both writers re-observe continuously. A version-checked update
55
- // (`ifInState`) with retry is the fix if that ever shows up in practice.
56
- export const collectContacts = async (deps, ctx, extracted) => {
57
- if (extracted.observations.length === 0) {
58
- return;
59
- }
60
- const books = await deps.addressBookList(ctx);
61
- const collectedBookId = books.find((b) => b.name === COLLECTED_BOOK_NAME)?.id ??
62
- (await deps.addressBookCreate({ ...ctx, name: COLLECTED_BOOK_NAME }));
63
- // Candidates across ALL books: cards holding an observed address (so a
64
- // personal-book contact is updated, never duplicated) plus cards matching
65
- // an observed display name (the merge gate's candidates). The collected
66
- // uid finds our own card even while the search index lags behind a write:
67
- // Stalwart 1.0 answers `uid` from the store but `email` and `name` from
68
- // its asynchronous index, so a card created a moment ago, or any card
69
- // during the post-migration reindex, would otherwise be created again and
70
- // rejected for its duplicate uid. The uid is minted from the card's first
71
- // address only. An address the merge gate added later, or one on a
72
- // personal-book card, is still found through the index alone, so in that
73
- // lag it can be collected onto a second card. The same holds for an
74
- // address a merge moved from a destroyed Collected card onto a personal
75
- // card: until the personal card is reindexed, a sighting of that address
76
- // can mint a fresh Collected card, which the next batch merges again.
77
- // Accepted: the lag is about 100 ms in steady state.
78
- const conditions = [];
79
- for (const address of new Set(extracted.observations.map((o) => o.address))) {
80
- conditions.push({ email: address }, { uid: collectedUid(address) });
81
- }
82
- for (const name of new Set(extracted.observations.flatMap((o) => (o.name ? [o.name] : [])))) {
83
- conditions.push({ name });
84
- }
85
- const cards = await candidates(deps, ctx, conditions);
86
- // A Collected card about to be merged into a personal card may hold more
87
- // addresses than this batch observed. Their owners are fetched too, so the
88
- // fold never copies an address onto a personal card while another card
89
- // already holds it.
90
- const observed = new Set(extracted.observations.map((o) => normalizeAddress(o.address)));
91
- const extra = new Set(cards
92
- .filter((c) => c.addressBookIds[collectedBookId] &&
93
- cardAddresses(c).some((a) => observed.has(a)))
94
- .flatMap(cardAddresses)
95
- .filter((a) => !observed.has(a)));
96
- if (extra.size > 0) {
97
- const known = new Set(cards.map((c) => c.id));
98
- const owners = await candidates(deps, ctx, [...extra].map((email) => ({ email })));
99
- cards.push(...owners.filter((c) => !known.has(c.id)));
100
- }
101
- const { creates, updates } = foldObservations({ cards, collectedBookId }, extracted.observations, extracted.relays);
102
- for (const card of creates) {
103
- try {
104
- await deps.contactCardCreate({ ...ctx, card });
105
- }
106
- catch (error) {
107
- // A concurrent writer created this person's collected card between our
108
- // read and this create, so the person is collected already. Its
109
- // observations from this batch are dropped, the same volume-signal
110
- // drift as the race above; the rest of the batch still applies.
111
- if (!(error instanceof ContactUidTakenError)) {
112
- throw error;
113
- }
114
- }
115
- }
116
- for (const update of updates) {
117
- await deps.contactCardUpdate({
118
- ...ctx,
119
- cardId: update.cardId,
120
- patch: update.patch,
121
- });
122
- // A Collected card goes only once its history is safely on the personal
123
- // card. If this update fails, both cards stay and the next batch merges
124
- // again. A failed destroy is swallowed: the personal card's `absorbed`
125
- // list makes the next merge retry it without summing the history twice,
126
- // so it must not cost the rest of the batch its updates.
127
- for (const cardId of update.absorbs) {
128
- await deps.contactCardDestroy({ ...ctx, cardId }).catch(() => undefined);
129
- }
130
- }
131
- };
@@ -1,254 +0,0 @@
1
- // Attachment resolution for the composition tools: turn what a caller can
2
- // name into the JMAP blobIds `Email/set` wants.
3
- //
4
- // Two ways to name a file, and the order matters because the first one is the
5
- // one we want callers to reach for:
6
- //
7
- // - `blobId` — a blob that is already on the server, which is what
8
- // search_emails/get_email hand back for every attachment they list.
9
- // Forwarding a contract to a lawyer moves no bytes at all: the handle is
10
- // re-referenced by a new message and the blob is never downloaded, never
11
- // re-uploaded, and never enters the conversation.
12
- // - `content` — base64 bytes, for a file the agent has just produced. These
13
- // do pass through the model's context, which is why the cap is small and
14
- // the tool descriptions say to prefer `blobId`.
15
- //
16
- // A file on the agent's own disk reaches the first form too: upload_attachments
17
- // hands out a URL the agent PUTs the file to, and the upload answers with a
18
- // blobId (attachments/upload.ts), so a 10 MB PDF never passes through the model.
19
- //
20
- // There is deliberately no `path`. Over HTTP the agent's filesystem and the
21
- // server's can be different machines, and a path would either name nothing or,
22
- // worse, name one of the server's own files; over stdio they are the same
23
- // machine, but a tool that opened whatever path a model typed would read any
24
- // file the user can. So the server reads no path on either transport.
25
- // `unnamedEntry` says so in as many words rather than letting the call fail as
26
- // a shrug, and names the upload tool as the remedy.
27
- //
28
- // Inline parts (`cid`) are not exposed here yet. src/jmap models them
29
- // (`DraftAttachment.cid`), so an HTML body referencing a generated chart is a
30
- // schema addition rather than a redesign; nothing needs one today.
31
- import { z } from "zod";
32
- // Ceiling on the bytes one call *uploads*, checked before anything is sent.
33
- // 25 MB is what a receiving MTA typically accepts (and what Gmail's own
34
- // attachment API documents), so the refusal lands here — where the message
35
- // names the number and nothing has been staged — rather than at submission
36
- // time, where the draft already exists and the error is Stalwart's.
37
- //
38
- // Deliberately not a whole-message ceiling: a `blobId` entry is not weighed,
39
- // because its size is not in the request and finding it out would cost a
40
- // lookup per attachment on the common, cheap path — forwarding a file that is
41
- // already sitting on the server. Stalwart still enforces its own message size
42
- // at submission, so an enormous forward is refused, just later and by it. The
43
- // cap here exists to stop *this* process buffering and uploading bytes that
44
- // could never be delivered, and for that the upload total is the right meter.
45
- export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
46
- export const MAX_ATTACHMENTS = 10;
47
- const DEFAULT_MIME_TYPE = "application/octet-stream";
48
- // Base64 as RFC 4648 §4 spells it, after whitespace has been stripped. Models
49
- // wrap long base64 across lines, so the whitespace is expected; anything else
50
- // outside the alphabet means the bytes are not what the caller thinks they are,
51
- // and decoding leniently would attach a silently corrupted file.
52
- const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/u;
53
- const WHITESPACE_RE = /\s+/gu;
54
- // The trailing '=' run, which is how many bytes the last quantum does *not*
55
- // carry.
56
- const PADDING_RE = /[=]*$/u;
57
- const EXTENSION_RE = /\.([a-z0-9]+)$/iu;
58
- // Media types for the artifacts an agent actually generates. Guessing from the
59
- // extension is worth the table: `mimeType` is optional, and a PDF that arrives
60
- // as application/octet-stream is one the recipient's client offers as an opaque
61
- // download instead of previewing. Anything not listed falls back to
62
- // octet-stream, which is correct-but-dull rather than wrong.
63
- const MIME_TYPES_BY_EXTENSION = {
64
- csv: "text/csv",
65
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
66
- gif: "image/gif",
67
- html: "text/html",
68
- ics: "text/calendar",
69
- jpeg: "image/jpeg",
70
- jpg: "image/jpeg",
71
- json: "application/json",
72
- md: "text/markdown",
73
- pdf: "application/pdf",
74
- png: "image/png",
75
- svg: "image/svg+xml",
76
- txt: "text/plain",
77
- webp: "image/webp",
78
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
79
- zip: "application/zip",
80
- };
81
- const attachmentEntrySchema = z.object({
82
- blobId: z
83
- .string()
84
- .min(1)
85
- .optional()
86
- .describe("Attach a file already on the server, by the blobId search_emails, get_thread, get_email, or " +
87
- "get_draft listed for it, or the one an upload from upload_attachments returned. Nothing " +
88
- "passes through the conversation — this is how you forward an attachment and how you attach a " +
89
- "file from your disk. Prefer this over `content` whenever you can."),
90
- content: z
91
- .string()
92
- .min(1)
93
- .optional()
94
- .describe("Base64-encoded bytes of a small file you generated. The bytes pass through the conversation, so " +
95
- "for a file on disk use upload_attachments and pass the `blobId` it returns instead."),
96
- filename: z
97
- .string()
98
- .min(1)
99
- .max(255)
100
- .optional()
101
- .describe('Name the recipient sees, e.g. "invoice-2026-006.pdf". Required with `blobId` — pass the filename ' +
102
- "listed beside it (or the one you uploaded it as), or the file arrives unnamed. Always worth " +
103
- "setting with `content` too."),
104
- mimeType: z
105
- .string()
106
- .min(3)
107
- .max(255)
108
- .optional()
109
- .describe('Media type, e.g. "application/pdf". Guessed from the filename extension when omitted.'),
110
- });
111
- export const attachmentsSchema = z
112
- .array(attachmentEntrySchema)
113
- .max(MAX_ATTACHMENTS)
114
- .describe(`Files to attach, at most ${MAX_ATTACHMENTS}. Each entry names its file either by \`blobId\` (already in ` +
115
- "the mailbox, or uploaded with upload_attachments — nothing passes through the conversation) " +
116
- "or by base64 `content` (a small file you just generated); the `content` entries may come to at most " +
117
- `${MAX_ATTACHMENT_BYTES / (1024 * 1024)} MB between them. A file path cannot be used: this server ` +
118
- "cannot read your disk — upload a local file with upload_attachments instead.");
119
- export const mimeTypeFor = (entry) => {
120
- if (entry.mimeType) {
121
- return entry.mimeType;
122
- }
123
- const extension = EXTENSION_RE.exec(entry.filename ?? "")?.[1]?.toLowerCase();
124
- return ((extension ? MIME_TYPES_BY_EXTENSION[extension] : undefined) ??
125
- DEFAULT_MIME_TYPE);
126
- };
127
- // How the caller referred to an entry, for error messages. The index alone
128
- // ("attachment 2") is unhelpfully abstract when the agent passed three files.
129
- const label = (entry, index) => entry.filename ? `"${entry.filename}"` : `attachment ${index + 1}`;
130
- const unnamedEntry = (index) => `Attachment ${index + 1} names no file. Give it either \`blobId\` (for a file already in the mailbox — ` +
131
- "the blobId that search_emails or get_email listed) or `content` (base64 bytes). A file path is not " +
132
- "accepted: this MCP server cannot read your filesystem, so " +
133
- "upload the file with upload_attachments and pass the `blobId` it returns.";
134
- // Decode one base64 payload, or say why it isn't one. Whitespace is stripped
135
- // first because a wrapped payload is the normal case, not a malformed one.
136
- const cleanBase64 = (content, name) => {
137
- const cleaned = content.replaceAll(WHITESPACE_RE, "");
138
- // Whitespace-only content survives the schema's `.min(1)` and then satisfies
139
- // every base64 check, because the empty string is valid base64 for zero bytes.
140
- // Left alone it would upload an empty blob and report a staged attachment, so
141
- // a generated file that came out empty would reach the recipient as an empty
142
- // one — the silent version of the failure the caller most needs told about.
143
- if (cleaned.length === 0) {
144
- return {
145
- error: `The \`content\` of ${name} is empty, so nothing was staged. The file has no bytes — check it was ` +
146
- "actually written before attaching it.",
147
- };
148
- }
149
- if (cleaned.length % 4 !== 0 || !BASE64_RE.test(cleaned)) {
150
- return {
151
- error: `The \`content\` of ${name} is not valid base64, so nothing was staged. Encode the file's raw bytes ` +
152
- "as base64 — not its text, and not a data: URL.",
153
- };
154
- }
155
- return { cleaned };
156
- };
157
- // What a validated base64 payload will weigh once decoded, computed from its
158
- // length rather than by decoding it.
159
- //
160
- // This is what lets the size cap be enforced before `Buffer.from` runs. Every
161
- // 4 characters carry 3 bytes, less one byte per '=' of padding — exact, not an
162
- // estimate — so an oversized payload is refused without ever allocating the
163
- // decoded copy of it. Decoding first to find out how big it is would let a
164
- // caller who ignored the documented cap make us allocate the very thing the cap
165
- // exists to refuse.
166
- export const decodedByteLength = (cleaned) => {
167
- const padding = PADDING_RE.exec(cleaned)?.[0].length ?? 0;
168
- return (cleaned.length / 4) * 3 - padding;
169
- };
170
- // Resolve every entry to a blobId, uploading the ones that arrived as bytes.
171
- //
172
- // The whole list is validated — and the combined size checked — before a single
173
- // upload runs, so a call that names one good file and one 40 MB one leaves no
174
- // orphaned blob behind and no half-attached draft.
175
- export const resolveAttachments = async (deps, p) => {
176
- const uploads = [];
177
- const resolved = [];
178
- let totalBytes = 0;
179
- for (const [index, entry] of p.entries.entries()) {
180
- if (entry.blobId && entry.content) {
181
- return {
182
- error: `${label(entry, index)} gives both \`blobId\` and \`content\`, so it is ambiguous which file was ` +
183
- "meant and nothing was staged. Pass one or the other.",
184
- };
185
- }
186
- const type = mimeTypeFor(entry);
187
- if (entry.blobId) {
188
- // A blobId carries bytes and nothing else — no name, no media type. Those
189
- // live on the *part* of the message the blob was read from, and this call
190
- // has no way back to it, so an entry that omits `filename` would forward
191
- // the file as an unnamed application/octet-stream: the recipient gets an
192
- // opaque download of a document that had a perfectly good name one
193
- // message ago. Refusing costs the caller nothing, because whatever listed
194
- // the blobId (get_email, search_emails, get_draft) printed the filename on
195
- // the very same line — and naming it also settles the media type, which
196
- // `mimeTypeFor` reads off the extension.
197
- if (entry.filename === undefined) {
198
- return {
199
- error: `Attachment ${index + 1} gives a \`blobId\` but no \`filename\`, so nothing was staged. Pass the ` +
200
- "filename listed beside that blobId — without it the file would arrive unnamed, as an " +
201
- "unrecognised download.",
202
- };
203
- }
204
- resolved.push({ blobId: entry.blobId, name: entry.filename, type });
205
- continue;
206
- }
207
- if (!entry.content) {
208
- return { error: unnamedEntry(index) };
209
- }
210
- const base64 = cleanBase64(entry.content, label(entry, index));
211
- if ("error" in base64) {
212
- return base64;
213
- }
214
- // Weighed before it is decoded — see `decodedByteLength`.
215
- totalBytes += decodedByteLength(base64.cleaned);
216
- if (totalBytes > MAX_ATTACHMENT_BYTES) {
217
- return {
218
- error: `These attachments come to more than the ${MAX_ATTACHMENT_BYTES / (1024 * 1024)} MB of new files a ` +
219
- "message can carry, so nothing was staged. Send fewer or smaller files, attach one already in the " +
220
- "mailbox by `blobId` instead of re-uploading it, or link to the large one.",
221
- };
222
- }
223
- // Placeholder: the blobId lands here once the upload runs, so the resolved
224
- // list keeps the caller's ordering rather than putting uploads last.
225
- resolved.push({
226
- blobId: "",
227
- type,
228
- ...(entry.filename === undefined ? {} : { name: entry.filename }),
229
- });
230
- // The Buffer is handed on as-is: it already *is* a Uint8Array, so wrapping
231
- // it in one would allocate and copy the whole payload a second time and
232
- // hold both until the uploads run — up to another 25 MB per request, on top
233
- // of the JSON and the cleaned base64 string already in memory.
234
- uploads.push({
235
- bytes: Buffer.from(base64.cleaned, "base64"),
236
- index: resolved.length - 1,
237
- type,
238
- });
239
- }
240
- for (const upload of uploads) {
241
- const blobId = await deps.blobUpload({
242
- accountId: p.accountId,
243
- authorization: p.authorization,
244
- content: upload.bytes,
245
- type: upload.type,
246
- uploadUrl: "",
247
- });
248
- const target = resolved[upload.index];
249
- if (target) {
250
- target.blobId = blobId;
251
- }
252
- }
253
- return { attachments: resolved };
254
- };
@@ -1,60 +0,0 @@
1
- // In-memory replay cache for the composition tools' `idempotencyKey`.
2
- //
3
- // The failure mode this closes is specific to agents: a client calls
4
- // `send_draft`, the response is lost (timeout, dropped connection, a retry
5
- // wrapper that doesn't know the call had a side effect), and the client calls
6
- // again. Without a key, the second call is indistinguishable from a deliberate
7
- // second send. With one, the first call's answer is replayed and nothing leaves
8
- // the mailbox twice.
9
- //
10
- // The value is the tool's result text, because replaying the exact answer is the
11
- // point — not merely suppressing the write.
12
- //
13
- // Entries are scoped by (tool, principal), and both halves matter:
14
- //
15
- // - by principal, so two accounts can't collide on the same key;
16
- // - by tool, because "one key per user request" is the natural way for an
17
- // agent to use these. Sharing a namespace would make
18
- // `create_draft(key: "k")` followed by `send_draft(key: "k")` look like a
19
- // retry of the create — so the send would be skipped, and the agent would be
20
- // handed the create's "Nothing has been sent" text as though it were the
21
- // send's answer. A retry is the same call again, not the next call in a
22
- // chain.
23
- //
24
- // Single-process state is fine here, for the same reason it is for attachment
25
- // tickets: the server is one container. A restart loses the cache, which
26
- // reopens the retry window rather than corrupting anything — and the
27
- // "is this still a draft?" check in send_draft closes it structurally
28
- // regardless of whether a key was passed.
29
- export const IDEMPOTENCY_TTL_MINUTES = 15;
30
- const IDEMPOTENCY_TTL_MS = IDEMPOTENCY_TTL_MINUTES * 60 * 1000;
31
- // Length-prefixed rather than separator-joined, so no key — whatever bytes an
32
- // agent puts in one — can be split differently and collide with another tool's
33
- // or principal's entry. A separator only works if it cannot occur in the
34
- // operands, and `key` is caller-supplied.
35
- const scopedKey = (tool, principal, key) => `${tool.length}:${tool}${principal.length}:${principal}${key}`;
36
- export const createIdempotencyStore = (now = Date.now) => {
37
- const entries = new Map();
38
- // Lazy sweep on access keeps the map bounded without a timer.
39
- const sweep = () => {
40
- const t = now();
41
- for (const [key, entry] of entries) {
42
- if (entry.expiresAt <= t) {
43
- entries.delete(key);
44
- }
45
- }
46
- };
47
- return {
48
- lookup: (tool, principal, key) => {
49
- sweep();
50
- return entries.get(scopedKey(tool, principal, key))?.value ?? null;
51
- },
52
- record: (tool, principal, key, value) => {
53
- sweep();
54
- entries.set(scopedKey(tool, principal, key), {
55
- expiresAt: now() + IDEMPOTENCY_TTL_MS,
56
- value,
57
- });
58
- },
59
- };
60
- };
@@ -1,184 +0,0 @@
1
- // Reservation around an in-flight send.
2
- //
3
- // `idempotencyKey` and the "is this still a draft?" check both compare state,
4
- // then act on it, and both leave a window between the two. That window is not
5
- // exotic: it is exactly the case the key exists for. A client whose request
6
- // times out fires the retry *while the first call is still running*, so the
7
- // retry's `lookup` finds nothing recorded yet and its `isDraft` read still says
8
- // "draft", because Stalwart hasn't applied the follow-up patch. Both calls
9
- // submit, and the recipient gets two copies.
10
- //
11
- // So a send reserves *first* — in the same synchronous step as its replay
12
- // lookup, before its first await — and holds the reservation until the call
13
- // ends, recording its replay before letting go. Both checks then mean
14
- // something: a retry that gets past `reserve` knows the earlier call has
15
- // finished, so the replay it looked up in that same step is already recorded,
16
- // and its `isDraft` read sees the mailbox after that call's submission.
17
- // Reserving any later reopens the window: the retry reads "still a draft" while
18
- // the first call is in flight, waits on its own I/O, and reserves after the
19
- // first call has released — then submits a message that has already gone.
20
- // Do not move the reservation, an `await` or the replay record relative to
21
- // each other: this ordering is what keeps one request from sending twice.
22
- //
23
- // The reservation is keyed on something that is *the same on a retry* rather
24
- // than on the caller's optional key — which is what makes it cover a client
25
- // retrying blind, the likelier shape, since a client retrying without a key is a
26
- // client not thinking about idempotency.
27
- //
28
- // What that stable thing is differs per tool, which is why the key is a
29
- // parameter and not a draft id:
30
- //
31
- // - send_draft is given a draftId, and a retry passes the same one.
32
- // - reply_to_message is given the id of the message being answered, and mints
33
- // a *fresh* draft on every call. Keying on the draft it just created would
34
- // reserve a different key each time and guard nothing at all, so it reserves
35
- // against the message it is replying to instead — and then also covers the
36
- // draft it staged under send_draft's key, because its result names that draft
37
- // and a send_draft of it must not race, or follow an unknown outcome of, the
38
- // reply's own submission.
39
- //
40
- // The tool name is part of the key: both ids come from the same Email id space,
41
- // so replying to message X and sending draft X must not collide.
42
- //
43
- // What happens when a submission *throws* is the interesting half, because the
44
- // throw does not say whether the mail went out:
45
- //
46
- // - Stalwart answered "no" (a JMAP method error carrying an error type, e.g.
47
- // `forbiddenFrom`): nothing was sent, so the reservation is released and the
48
- // call stays retryable.
49
- // - Anything else — a timeout, a reset, a proxy 502: the request may have been
50
- // accepted and the answer lost. Releasing would invite a retry that delivers
51
- // a second copy, so the reservation is *kept* and a later attempt is told the
52
- // outcome is unknown rather than being allowed to send again. Erring towards
53
- // "you must check" is the only safe direction: an unsent message the user
54
- // re-sends by hand costs a minute, a duplicate cannot be recalled.
55
- //
56
- // Single-process state, like the replay cache next door: one container, and a
57
- // restart merely reopens the window.
58
- export const SEND_RESERVATION_TTL_MINUTES = 10;
59
- const SEND_RESERVATION_TTL_MS = SEND_RESERVATION_TTL_MINUTES * 60 * 1000;
60
- // reply_to_message's tool name. Its subjects are the message being answered,
61
- // which the refusal text has to name differently; the tool keys its replay
62
- // cache under the same name.
63
- export const REPLY_TOOL = "reply_to_message";
64
- // forward_message's tool name. Like a reply, its subjects are the message being
65
- // forwarded, and it keys its replay cache under the same name.
66
- export const FORWARD_TOOL = "forward_message";
67
- const scopedKey = (principal, subject) => `${subject.tool.length}:${subject.tool}${principal.length}:${principal}${subject.key}`;
68
- export const createSendGuard = (now = Date.now) => {
69
- const entries = new Map();
70
- // Another call's live entry is left alone. An unowned settle acts
71
- // unconditionally, and so does one whose entry has already been swept:
72
- // dropping an `unknown` there would let the next call send a second copy.
73
- const ownedBy = (key, owner) => {
74
- const held = entries.get(key);
75
- return owner === undefined || held === undefined || held.owner === owner;
76
- };
77
- const sweep = () => {
78
- const t = now();
79
- for (const [key, entry] of entries) {
80
- if (entry.expiresAt <= t) {
81
- entries.delete(key);
82
- }
83
- }
84
- };
85
- return {
86
- markUnknown: (principal, subject, owner) => {
87
- const key = scopedKey(principal, subject);
88
- if (ownedBy(key, owner)) {
89
- entries.set(key, {
90
- expiresAt: now() + SEND_RESERVATION_TTL_MS,
91
- owner,
92
- state: "unknown",
93
- });
94
- }
95
- },
96
- release: (principal, subject, owner) => {
97
- const key = scopedKey(principal, subject);
98
- if (ownedBy(key, owner)) {
99
- entries.delete(key);
100
- }
101
- },
102
- reserve: (principal, subject, owner) => {
103
- sweep();
104
- const key = scopedKey(principal, subject);
105
- const held = entries.get(key);
106
- if (held) {
107
- return { state: held.state };
108
- }
109
- entries.set(key, {
110
- expiresAt: now() + SEND_RESERVATION_TTL_MS,
111
- owner,
112
- state: "in_flight",
113
- });
114
- return null;
115
- },
116
- };
117
- };
118
- // Why a send was refused because another call holds its subject. Nothing was
119
- // sent by the refused call in either case. A reply's subject is the message
120
- // being answered, and reading that back says nothing about the reply — so a
121
- // reply is pointed at the Sent folder, a draft at the draft itself. delete_draft
122
- // reserves a draft's subject too, so an in-flight draft holder may be a delete.
123
- export const reservationRefusal = (subject, held) => {
124
- if (subject.tool === FORWARD_TOOL) {
125
- return held.state === "in_flight"
126
- ? `A forward of ${subject.key} is already in progress. Nothing was sent by this call. Wait, then check ` +
127
- "the user's Sent folder to see whether it went out."
128
- : `An earlier forward of ${subject.key} failed without saying whether it went out, so it was NOT sent ` +
129
- "again — a second attempt could deliver a duplicate. Check the user's Sent folder before deciding.";
130
- }
131
- if (subject.tool === REPLY_TOOL) {
132
- return held.state === "in_flight"
133
- ? `A reply to ${subject.key} is already in progress. Nothing was sent by this call. Wait, then check ` +
134
- "the user's Sent folder to see whether it went out."
135
- : `An earlier reply to ${subject.key} failed without saying whether it went out, so it was NOT sent ` +
136
- "again — a second attempt could deliver a duplicate. Check the user's Sent folder before deciding.";
137
- }
138
- return held.state === "in_flight"
139
- ? `A send or delete of ${subject.key} is already in progress. Nothing was sent by this call. Wait, ` +
140
- "then read it back with get_draft — or get_email, if it is no longer a draft — to see what happened."
141
- : `An earlier send of ${subject.key} failed without saying whether the message went out, so it was ` +
142
- "NOT sent again — a second attempt could deliver a duplicate. Read it back with get_email, or check " +
143
- "the user's Sent folder, before deciding.";
144
- };
145
- // Take the first reservation of a call. Must run before the call's first read of
146
- // the replay cache or the mailbox — see the header.
147
- export const holdSend = (guard, principal, subject) => {
148
- const owner = Symbol("send");
149
- const refused = guard.reserve(principal, subject, owner);
150
- if (refused) {
151
- return { refused };
152
- }
153
- const subjects = [subject];
154
- let unknown = false;
155
- let ended = false;
156
- return {
157
- hold: {
158
- cover: (next) => {
159
- const held = guard.reserve(principal, next, owner);
160
- if (!held) {
161
- subjects.push(next);
162
- }
163
- return held;
164
- },
165
- end: () => {
166
- if (ended) {
167
- return;
168
- }
169
- ended = true;
170
- for (const s of subjects) {
171
- if (unknown) {
172
- guard.markUnknown(principal, s, owner);
173
- }
174
- else {
175
- guard.release(principal, s, owner);
176
- }
177
- }
178
- },
179
- markUnknown: () => {
180
- unknown = true;
181
- },
182
- },
183
- };
184
- };