@open-workspace/email 0.4.1 → 0.5.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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -5,7 +5,10 @@ import type {
5
5
  import { apiPath, runTool } from "@open-workspace/core/module";
6
6
  import { z } from "zod";
7
7
 
8
+ import { autoReplyAudiences } from "../../shared/mail";
8
9
  import { MAIL_ORGANIZE_SCOPE, MAIL_READ_SCOPE } from "../../shared/permissions";
10
+ import { ruleInputSchema, ruleTestSchema } from "../mail/rules";
11
+ import { retentionFolderSchema } from "../mail/schemas";
9
12
  import {
10
13
  conversationIdsSchema,
11
14
  entityIdSchema,
@@ -130,6 +133,97 @@ export function registerMailActionTools(
130
133
  )
131
134
  );
132
135
 
136
+ tool(MAIL_ORGANIZE_SCOPE)(
137
+ "empty_folder",
138
+ {
139
+ title: "Empty Trash or Spam",
140
+ description:
141
+ "Permanently delete up to 100 of the oldest conversations in Trash or Spam. Returns { deleted, remaining }; call again while remaining is above 0. Requires send access.",
142
+ inputSchema: z.object({
143
+ mailboxId: mailboxIdSchema,
144
+ folder: retentionFolderSchema,
145
+ }),
146
+ annotations: { ...write, destructiveHint: true, idempotentHint: false },
147
+ },
148
+ ({ mailboxId, folder }) =>
149
+ runTool(() =>
150
+ api.json(
151
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/folders/${folder}/empty`,
152
+ { method: "POST" }
153
+ )
154
+ )
155
+ );
156
+
157
+ tool(MAIL_READ_SCOPE)(
158
+ "get_auto_reply",
159
+ {
160
+ title: "Get auto-reply",
161
+ description:
162
+ "Read a mailbox's automatic reply: its schedule, its status now (off, scheduled, active, ended), and its two messages, for people inside the workspace and for everyone else. Your own mailboxes; anyone's with Manage people, and team inboxes with Manage teams.",
163
+ inputSchema: z.object({ mailboxId: mailboxIdSchema }),
164
+ annotations: { ...write, readOnlyHint: true },
165
+ },
166
+ ({ mailboxId }) =>
167
+ runTool(() =>
168
+ api.json(
169
+ apiPath(`/mail/mailboxes/${encodeURIComponent(mailboxId)}/auto-reply`)
170
+ )
171
+ )
172
+ );
173
+
174
+ const autoReplyMessage = z.object({
175
+ enabled: z.boolean(),
176
+ subject: z
177
+ .string()
178
+ .max(998)
179
+ .nullable()
180
+ .optional()
181
+ .describe('Defaults to "Auto: <original subject>".'),
182
+ html: z.string().max(20_000).describe("The reply as HTML."),
183
+ text: z.string().max(10_000).describe("The same reply as plain text."),
184
+ });
185
+
186
+ tool(MAIL_ORGANIZE_SCOPE)(
187
+ "set_auto_reply",
188
+ {
189
+ title: "Set auto-reply",
190
+ description:
191
+ "Turn a mailbox's automatic reply on or off, with an optional schedule and one message for people inside the workspace and one for everyone else (or only people the mailbox has written to). Replaces both messages and drops their images. Mailing lists, bounces, other auto-responders, Spam and Trash are never answered, and each sender gets at most one reply per interval.",
192
+ inputSchema: z.object({
193
+ mailboxId: mailboxIdSchema,
194
+ enabled: z.boolean(),
195
+ startsAt: z.iso
196
+ .datetime({ offset: true })
197
+ .nullable()
198
+ .optional()
199
+ .describe("When replies start; omit or null to start now."),
200
+ endsAt: z.iso
201
+ .datetime({ offset: true })
202
+ .nullable()
203
+ .optional()
204
+ .describe("When replies stop; omit or null for no end."),
205
+ replyIntervalDays: z.number().int().min(1).max(30).optional(),
206
+ inside: autoReplyMessage,
207
+ outside: autoReplyMessage.extend({
208
+ audience: z.enum(autoReplyAudiences).optional(),
209
+ }),
210
+ }),
211
+ annotations: write,
212
+ },
213
+ ({ mailboxId, ...settings }) =>
214
+ runTool(() =>
215
+ api.json(
216
+ apiPath(
217
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/auto-reply`
218
+ ),
219
+ {
220
+ method: "PUT",
221
+ json: settings,
222
+ }
223
+ )
224
+ )
225
+ );
226
+
133
227
  tool(MAIL_ORGANIZE_SCOPE)(
134
228
  "create_folder",
135
229
  {
@@ -248,4 +342,66 @@ export function registerMailActionTools(
248
342
  })
249
343
  )
250
344
  );
345
+
346
+ const rulesPath = (mailboxId: string) =>
347
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules`;
348
+
349
+ tool(MAIL_READ_SCOPE)(
350
+ "list_rules",
351
+ {
352
+ title: "List mailbox rules",
353
+ description: "List a mailbox's rules in the order they run on new mail.",
354
+ inputSchema: z.object({ mailboxId: mailboxIdSchema }),
355
+ annotations: { ...write, readOnlyHint: true },
356
+ },
357
+ ({ mailboxId }) => runTool(() => api.json(rulesPath(mailboxId)))
358
+ );
359
+
360
+ tool(MAIL_READ_SCOPE)(
361
+ "test_rule",
362
+ {
363
+ title: "Test a mailbox rule",
364
+ description:
365
+ "Count how many of the latest 500 incoming messages the conditions match, without changing anything.",
366
+ inputSchema: ruleTestSchema.extend({ mailboxId: mailboxIdSchema }),
367
+ annotations: { ...write, readOnlyHint: true },
368
+ },
369
+ ({ mailboxId, ...rule }) =>
370
+ runTool(() =>
371
+ api.json(`${rulesPath(mailboxId)}/test`, { method: "POST", json: rule })
372
+ )
373
+ );
374
+
375
+ tool(MAIL_ORGANIZE_SCOPE)(
376
+ "create_rule",
377
+ {
378
+ title: "Create a mailbox rule",
379
+ description:
380
+ "Add a rule that runs on new mail. Conditions: from (contains/equals/domain), recipient, subject, listId, hasAttachment. Actions: moveToFolder, archive, trash, spam, notSpam, markRead. recipient matches To, Cc and the address the mail was delivered to. A matching moveToFolder or archive replaces AI sorting's folder; blocked senders always go to Spam.",
381
+ inputSchema: ruleInputSchema.extend({ mailboxId: mailboxIdSchema }),
382
+ annotations: { ...write, idempotentHint: false },
383
+ },
384
+ ({ mailboxId, ...rule }) =>
385
+ runTool(() =>
386
+ api.json(rulesPath(mailboxId), { method: "POST", json: rule })
387
+ )
388
+ );
389
+
390
+ tool(MAIL_ORGANIZE_SCOPE)(
391
+ "delete_rule",
392
+ {
393
+ title: "Delete a mailbox rule",
394
+ inputSchema: z.object({
395
+ mailboxId: mailboxIdSchema,
396
+ ruleId: entityIdSchema,
397
+ }),
398
+ annotations: { ...write, destructiveHint: true },
399
+ },
400
+ ({ mailboxId, ruleId }) =>
401
+ runTool(() =>
402
+ api.json(`${rulesPath(mailboxId)}/${encodeURIComponent(ruleId)}`, {
403
+ method: "DELETE",
404
+ })
405
+ )
406
+ );
251
407
  }
@@ -11,6 +11,7 @@ import {
11
11
  } from "../../shared/mail";
12
12
  import { MAIL_SEND_SCOPE } from "../../shared/permissions";
13
13
  import { dedupeRecipientFields, recipientCount } from "../mail/recipients";
14
+ import { forwardedAttachmentIdsSchema } from "../mail/schemas";
14
15
  import {
15
16
  entityIdSchema,
16
17
  mailboxIdSchema,
@@ -49,6 +50,11 @@ const forwardInputSchema = z
49
50
  .object({
50
51
  mailboxId: mailboxIdSchema,
51
52
  sourceMessageId: entityIdSchema,
53
+ forwardedAttachmentIds: forwardedAttachmentIdsSchema
54
+ .optional()
55
+ .describe(
56
+ "Original attachment IDs to include. Omit for all, or pass [] for none."
57
+ ),
52
58
  ...recipientFields,
53
59
  replyTo: emailSchema.optional(),
54
60
  ...messageContentFields,
@@ -72,7 +78,7 @@ export function registerMailComposeTools(
72
78
  {
73
79
  title: "Create attachment upload",
74
80
  description:
75
- "Create a 15-minute presigned R2 PUT URL. Upload exactly the declared number of bytes to upload.uploadUrl using upload.headers, then call complete_attachment_upload with upload.id.",
81
+ "Create a 15-minute presigned R2 PUT URL. PUT exactly the declared size to upload.uploadUrl with upload.headers and a Content-Length header (the URL signs it; a chunked body without a length is refused with 403), then call complete_attachment_upload with upload.id.",
76
82
  inputSchema: z.object({
77
83
  mailboxId: mailboxIdSchema,
78
84
  filename: z.string().trim().min(1).max(255),
@@ -183,7 +189,7 @@ export function registerMailComposeTools(
183
189
  sourceMessageId: entityIdSchema,
184
190
  mode: replyModeSchema.default("reply"),
185
191
  cc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).optional(),
186
- bcc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).default([]),
192
+ bcc: z.array(emailSchema).max(MAX_MAIL_RECIPIENTS).optional(),
187
193
  ...messageContentFields,
188
194
  }),
189
195
  annotations: sendAnnotations,
@@ -297,7 +297,7 @@ export function registerMailSafetyTools(
297
297
  {
298
298
  title: "Unsubscribe from mailing list",
299
299
  description:
300
- 'OUTBOUND ACTION: unsubscribe this mailbox from the mailing list that sent an incoming message. With method "auto" the server tries, in order: an RFC 8058 one-click POST to the sender\'s URL (outcome "done"); an unsubscribe email sent from this mailbox, which requires send access (outcome "requested"); otherwise it returns the sender\'s unsubscribe page URL for the user to open themselves (outcome "link"). Method "link" only records that the user is opening the page and returns its URL; it contacts no one. Confirm with the user before calling. Rate-limited to 20 requests per minute. Check get_message_security\'s unsubscribe field first.',
300
+ 'OUTBOUND ACTION: unsubscribe this mailbox from the mailing list that sent an incoming message. With method "auto" the server tries, in order: an RFC 8058 one-click POST to the sender\'s URL (outcome "done"); an email saying only "unsubscribe" sent from this mailbox, never to an address of this workspace, which requires send access (outcome "requested"); otherwise it returns the sender\'s unsubscribe page URL for the user to open themselves (outcome "link"). Method "link" only records that the user is opening the page and returns its URL; it contacts no one. Confirm with the user before calling. Rate-limited to 20 requests per minute. Check get_message_security\'s unsubscribe field first.',
301
301
  inputSchema: messageInputSchema.extend({
302
302
  method: z.enum(["auto", "link"]).default("auto"),
303
303
  }),
@@ -325,7 +325,7 @@ export function registerMailSafetyTools(
325
325
  {
326
326
  title: "Report spam",
327
327
  description:
328
- "Report an incoming message as spam: labels it, trains the sender's reputation here and across the workspace, and moves its conversation to Spam. Nothing is sent outside the workspace. Confirm with the user before reporting.",
328
+ "Report an incoming message as spam: it and its sender's other messages in the thread go to Spam (the rest of the thread stays), are labelled, and train the sender's reputation here and across the workspace. Nothing is sent outside the workspace. Returns places: for each conversation, where its spam is now and whether the conversation left its folder (left). Confirm with the user before reporting.",
329
329
  inputSchema: messageInputSchema,
330
330
  annotations: { ...write, idempotentHint: false },
331
331
  },
@@ -345,7 +345,7 @@ export function registerMailSafetyTools(
345
345
  {
346
346
  title: "Report conversations as spam",
347
347
  description:
348
- "Report the newest incoming message of up to 100 conversations as spam and move them to Spam. Confirm with the user first.",
348
+ "Report the received mail of up to 100 conversations as spam and move it to Spam (your own replies stay). Returns places, as report_message does. Confirm with the user first.",
349
349
  inputSchema: z.object({
350
350
  mailboxId: mailboxIdSchema,
351
351
  conversationIds: z
@@ -370,7 +370,7 @@ export function registerMailSafetyTools(
370
370
  {
371
371
  title: "Mark message not spam",
372
372
  description:
373
- "Move an incoming message's conversation from Spam back to Inbox, clear its spam label, record the feedback, and mark the sender as trusted in this mailbox.",
373
+ "Move an incoming message's conversation from Spam back to Inbox, clear its spam label, record the feedback, and mark its senders as trusted in this mailbox. Returns places: from, the conversation it was in; conversationId, the one it is in now (a reply kept out of its conversation as spam rejoins it); folder, where that is (inbox, archive or a custom folder id). Empty when it wasn't in Spam.",
374
374
  inputSchema: messageInputSchema,
375
375
  annotations: write,
376
376
  },
package/worker/module.ts CHANGED
@@ -10,16 +10,24 @@ import type { EmailQueueRole } from "../shared/module";
10
10
  import { emailPermissions, mailOauthScopes } from "../shared/permissions";
11
11
  import { EMAIL_WEBHOOK_SOURCE, emailWebhookEvents } from "../shared/webhooks";
12
12
  import { blockedSenderAdminRoutes } from "./admin/blocked-sender-routes";
13
+ import { forgetBackupHashes, mailBackup } from "./backups/mail-backup";
13
14
  import { jmapRoutes } from "./jmap/routes";
15
+ import { runArchiveTick } from "./mail/archive";
16
+ import { mailArchiveRoutes } from "./mail/archive-routes";
14
17
  import { mailBootstrap } from "./mail/bootstrap";
15
18
  import { consumeDeliveryEvents } from "./mail/delivery-events";
16
19
  import { demoRoutes } from "./mail/demo-routes";
17
20
  import { mailDownloadRoutes } from "./mail/downloads";
21
+ import {
22
+ addForwardDestinations,
23
+ forwardDestinationRoutes,
24
+ } from "./mail/forward-destinations";
18
25
  import { mailImportRoutes } from "./mail/import-routes";
19
26
  import { deleteMailboxStorage } from "./mail/mailbox-deletion";
20
27
  import { consumeOfficePreviews } from "./mail/office-preview-queue";
21
28
  import {
22
29
  consumePushNotifications,
30
+ deleteEndedSessionPushSubscriptions,
23
31
  deleteUserPushSubscriptions,
24
32
  pushNotificationRoutes,
25
33
  } from "./mail/push-notifications";
@@ -35,6 +43,8 @@ export const mailAccountApi = new Hono<AppEnv>()
35
43
  // first, so that middleware never runs for it).
36
44
  .route("/mail/remote", mailRemoteRoutes)
37
45
  .route("/mail/import", mailImportRoutes)
46
+ .route("/mail/forward-destinations", forwardDestinationRoutes)
47
+ .route("/mail/archive", mailArchiveRoutes)
38
48
  .route("/mail", mailRoutes)
39
49
  .route("/admin", blockedSenderAdminRoutes);
40
50
 
@@ -56,7 +66,7 @@ export type MailAppType = typeof mailBrowserApi;
56
66
  * and push. `Email()` in alchemy.run.ts puts it in the generated Worker
57
67
  * entry, which also exports `MailboxDO` and `OfficePreviewContainer`.
58
68
  */
59
- export function email(): WorkspaceModule {
69
+ export function email() {
60
70
  return {
61
71
  name: EMAIL_MODULE,
62
72
  accountApi: mailAccountApi,
@@ -73,14 +83,25 @@ export function email(): WorkspaceModule {
73
83
  [emailQueueRoles.deliveryEvents]: (batch, env) =>
74
84
  consumeDeliveryEvents(batch, env),
75
85
  } satisfies Record<EmailQueueRole, QueueConsumer>,
86
+ // Hourly: the mail archive's retries (a no-op without its bucket).
87
+ scheduled: (controller, env) =>
88
+ runArchiveTick(env, new Date(controller.scheduledTime)),
76
89
  mcpTools: () =>
77
90
  import("./mcp/tools").then((tools) => tools.registerMailTools),
78
91
  webhookEvents: emailWebhookEvents,
79
92
  webhookSources: { [EMAIL_WEBHOOK_SOURCE]: emailWebhookData },
93
+ backup: mailBackup,
80
94
  hooks: {
95
+ mailboxSaved: async (env, mailboxId) => {
96
+ await Promise.all([
97
+ addForwardDestinations(env, mailboxId),
98
+ forgetBackupHashes(env, mailboxId),
99
+ ]);
100
+ },
81
101
  mailboxDeleted: deleteMailboxStorage,
102
+ sessionsEnded: deleteEndedSessionPushSubscriptions,
82
103
  sessionsRevoked: deleteUserPushSubscriptions,
83
104
  seedDemo: (env) => seedEmailDemo(env),
84
105
  },
85
- };
106
+ } satisfies WorkspaceModule;
86
107
  }
@@ -1,208 +0,0 @@
1
- import type { FormEvent, RefObject } from "react";
2
-
3
- import type { ComposerContent, ComposerEditorHandle } from "./composer-editor";
4
- import type { ValidatedComposerRecipients } from "./composer-recipients";
5
- import { isUploadedAsset } from "./composer-session";
6
- import type {
7
- ComposerAsset,
8
- ComposerSession,
9
- ComposerSessionPhase,
10
- } from "./composer-session";
11
- import { notifyOutboundResult } from "./outbound-notification";
12
- import type { Mailbox, MessageDetail } from "./types";
13
- import { resolveComposerAttachmentPlan } from "./use-composer-attachment-preflight";
14
- import type { PreflightContext } from "./use-composer-attachment-preflight";
15
- import { useComposerSubmission } from "./use-composer-submission";
16
- import type { PreparedComposerSubmission } from "./use-composer-submission";
17
- import type { MailSendDraft } from "./use-mail-send";
18
-
19
- type ForwardedComposeMessage = Pick<MessageDetail, "id">;
20
-
21
- type ComposeSubmissionInput = {
22
- session: ComposerSession;
23
- phase: ComposerSessionPhase;
24
- mailbox: Mailbox;
25
- forwardedMessage?: ForwardedComposeMessage;
26
- recipients: ValidatedComposerRecipients;
27
- subject: string;
28
- content: ComposerContent;
29
- editor: RefObject<ComposerEditorHandle | null>;
30
- activeAssets: readonly ComposerAsset[];
31
- uploadLimitError: string | null;
32
- uploadsPending: boolean;
33
- uploadsFailed: boolean;
34
- onClose: () => void;
35
- };
36
-
37
- export function useComposeSubmission(input: ComposeSubmissionInput) {
38
- const submission = useComposerSubmission({
39
- session: input.session,
40
- phase: input.phase,
41
- validate: () => submissionValidationError(input),
42
- prepare: (signal) => prepareComposeSubmission(input, signal),
43
- failureLabel: "Could not send message",
44
- onSuccess: (result) => {
45
- notifyOutboundResult(result, "message");
46
- input.onClose();
47
- },
48
- });
49
-
50
- return {
51
- busy: submission.busy,
52
- submit: (event: FormEvent) => {
53
- event.preventDefault();
54
- void submission.submit();
55
- },
56
- };
57
- }
58
-
59
- async function prepareComposeSubmission(
60
- input: ComposeSubmissionInput,
61
- signal: AbortSignal
62
- ): Promise<PreparedComposerSubmission> {
63
- let content = input.editor.current?.content() ?? input.content;
64
-
65
- if (!input.forwardedMessage && !hasAuthoredContent(content)) {
66
- throw new Error("Add text to the message before sending");
67
- }
68
-
69
- const activeIds = new Set(
70
- input.editor.current?.assetIds() ??
71
- input.activeAssets.map((asset) => asset.id)
72
- );
73
-
74
- const assets = input.session
75
- .getSnapshot()
76
- .assets.filter((asset) => activeIds.has(asset.id));
77
-
78
- if (assets.length) {
79
- await resolveComposerAttachmentPlan(
80
- input.session,
81
- preflightContext(input, content),
82
- assets,
83
- signal
84
- );
85
- // Freeze exactly the same link-card projection that final preflight chose.
86
- input.editor.current?.reconcileAssets();
87
- content = input.editor.current?.content() ?? content;
88
- }
89
-
90
- if (!input.forwardedMessage && !hasAuthoredContent(content)) {
91
- throw new Error("Add text to the message before sending");
92
- }
93
-
94
- const finalActiveIds = new Set(
95
- input.editor.current?.assetIds() ?? [...activeIds]
96
- );
97
-
98
- const linkedDocumentAssetIds = new Set(content.linkedAssetIds);
99
-
100
- const submittedAssets = input.session
101
- .getSnapshot()
102
- .assets.filter(isUploadedAsset)
103
- .filter((asset) => finalActiveIds.has(asset.id));
104
-
105
- const uploadedAttachments = submittedAssets.map((asset) => {
106
- const linkedInline =
107
- asset.intent === "inline" && linkedDocumentAssetIds.has(asset.id);
108
-
109
- return {
110
- uploadId: asset.uploadId,
111
- disposition: linkedInline ? ("attachment" as const) : asset.intent,
112
- // A linked inline image goes as a plain attachment, without its content
113
- // ID; JSON leaves an undefined one out.
114
- contentId: (!linkedInline && asset.contentId) || undefined,
115
- };
116
- });
117
-
118
- const common = {
119
- mailboxId: input.mailbox.id,
120
- bodyText: content.bodyText,
121
- bodyHtml:
122
- content.bodyText.trim() ||
123
- content.inlineAssetIds.length ||
124
- content.linkedAssetIds.length
125
- ? content.bodyHtml
126
- : undefined,
127
- uploadedAttachments,
128
- };
129
-
130
- const command: MailSendDraft = input.forwardedMessage
131
- ? {
132
- ...common,
133
- kind: "forward",
134
- sourceEmailId: input.forwardedMessage.id,
135
- to: input.recipients.to,
136
- cc: input.recipients.cc,
137
- bcc: input.recipients.bcc,
138
- replyTo: input.recipients.replyTo,
139
- }
140
- : {
141
- ...common,
142
- kind: "compose",
143
- to: input.recipients.to,
144
- cc: input.recipients.cc,
145
- bcc: input.recipients.bcc,
146
- replyTo: input.recipients.replyTo,
147
- subject: input.subject,
148
- };
149
-
150
- return {
151
- assetIds: submittedAssets.map((asset) => asset.id),
152
- command,
153
- submissionKey: JSON.stringify(command),
154
- };
155
- }
156
-
157
- function submissionValidationError(input: ComposeSubmissionInput) {
158
- if (input.recipients.error) return input.recipients.error;
159
-
160
- if (input.recipients.count === 0) {
161
- return "Add at least one recipient in To, Cc, or Bcc";
162
- }
163
-
164
- if (input.uploadLimitError) return input.uploadLimitError;
165
-
166
- if (input.uploadsPending) {
167
- return "Wait for attachments to finish uploading";
168
- }
169
-
170
- if (input.uploadsFailed) return "Retry or remove failed attachments";
171
-
172
- if (!input.mailbox.canSend) return "This mailbox is read-only";
173
- const content = input.editor.current?.content() ?? input.content;
174
-
175
- if (!input.forwardedMessage && !hasAuthoredContent(content)) {
176
- return "Add text to the message before sending";
177
- }
178
-
179
- return null;
180
- }
181
-
182
- function hasAuthoredContent(content: ComposerContent) {
183
- return Boolean(content.bodyText.trim() || content.inlineAssetIds.length);
184
- }
185
-
186
- function preflightContext(
187
- input: Pick<
188
- ComposeSubmissionInput,
189
- "forwardedMessage" | "mailbox" | "subject"
190
- >,
191
- content: ComposerContent
192
- ): PreflightContext {
193
- return input.forwardedMessage
194
- ? {
195
- kind: "forward",
196
- mailboxId: input.mailbox.id,
197
- sourceEmailId: input.forwardedMessage.id,
198
- bodyText: content.bodyText,
199
- bodyHtml: content.bodyHtml || undefined,
200
- }
201
- : {
202
- kind: "compose",
203
- mailboxId: input.mailbox.id,
204
- subject: input.subject,
205
- bodyText: content.bodyText,
206
- bodyHtml: content.bodyHtml || undefined,
207
- };
208
- }
@@ -1,114 +0,0 @@
1
- import type { ValidatedComposerRecipients } from "./composer-recipients";
2
- import { isUploadedAsset } from "./composer-session";
3
- import type { ComposerSession, ComposerSessionPhase } from "./composer-session";
4
- import { notifyOutboundResult } from "./outbound-notification";
5
- import type { Mailbox, MessageDetail, ReplyAction } from "./types";
6
- import { resolveComposerAttachmentPlan } from "./use-composer-attachment-preflight";
7
- import { useComposerSubmission } from "./use-composer-submission";
8
- import type { PreparedComposerSubmission } from "./use-composer-submission";
9
- import type { MailSendDraft, SubmittedMessage } from "./use-mail-send";
10
-
11
- export type SentReply = Pick<SubmittedMessage, "conversationId" | "detached">;
12
-
13
- type ReplySubmissionInput = {
14
- session: ComposerSession;
15
- phase: ComposerSessionPhase;
16
- mailbox?: Mailbox;
17
- parent: MessageDetail;
18
- action?: ReplyAction;
19
- recipients: ValidatedComposerRecipients;
20
- body: string;
21
- uploadLimitError: string | null;
22
- uploadsPending: boolean;
23
- uploadsFailed: boolean;
24
- onSuccess: (result: SentReply) => void;
25
- };
26
-
27
- export function useReplySubmission(input: ReplySubmissionInput) {
28
- return useComposerSubmission({
29
- session: input.session,
30
- phase: input.phase,
31
- validate: () => replySubmissionValidationError(input),
32
- prepare: (signal) => prepareReplySubmission(input, signal),
33
- failureLabel: "Could not send reply",
34
- onSuccess: (result) => {
35
- notifyOutboundResult(result, "reply");
36
- input.onSuccess({
37
- conversationId: result.conversationId,
38
- detached: result.detached,
39
- });
40
- },
41
- });
42
- }
43
-
44
- function replySubmissionValidationError(input: ReplySubmissionInput) {
45
- if (!input.mailbox?.canSend || !input.action) {
46
- return "Reply is no longer available";
47
- }
48
-
49
- if (input.recipients.error) return input.recipients.error;
50
-
51
- if (input.uploadLimitError) return input.uploadLimitError;
52
-
53
- if (input.uploadsPending) {
54
- return "Wait for attachments to finish uploading";
55
- }
56
-
57
- if (input.uploadsFailed) return "Retry or remove failed attachments";
58
-
59
- if (!input.body.trim()) return "Add text to the reply before sending";
60
-
61
- return null;
62
- }
63
-
64
- async function prepareReplySubmission(
65
- input: ReplySubmissionInput,
66
- signal: AbortSignal
67
- ): Promise<PreparedComposerSubmission> {
68
- if (!input.mailbox || !input.action) {
69
- throw new Error("Reply is no longer available");
70
- }
71
-
72
- const submittedAssets = input.session
73
- .getSnapshot()
74
- .assets.filter(isUploadedAsset);
75
-
76
- if (submittedAssets.length) {
77
- await resolveComposerAttachmentPlan(
78
- input.session,
79
- {
80
- kind: "reply",
81
- mailboxId: input.mailbox.id,
82
- sourceEmailId: input.parent.id,
83
- mode: input.action.mode,
84
- cc: input.recipients.cc,
85
- bcc: input.recipients.bcc,
86
- bodyText: input.body,
87
- },
88
- submittedAssets,
89
- signal
90
- );
91
- }
92
-
93
- const uploadedAttachments = submittedAssets.map((asset) => ({
94
- uploadId: asset.uploadId,
95
- disposition: "attachment" as const,
96
- }));
97
-
98
- const command: MailSendDraft = {
99
- kind: "reply",
100
- mailboxId: input.mailbox.id,
101
- cc: input.recipients.cc,
102
- bcc: input.recipients.bcc,
103
- bodyText: input.body,
104
- uploadedAttachments,
105
- parentEmailId: input.parent.id,
106
- mode: input.action.mode,
107
- };
108
-
109
- return {
110
- assetIds: submittedAssets.map((asset) => asset.id),
111
- command,
112
- submissionKey: JSON.stringify(command),
113
- };
114
- }
@@ -1,36 +0,0 @@
1
- /**
2
- * Reads a body stream to the end, or gives up (cancelling the stream) as soon
3
- * as it grows past `limit` bytes: a remote server or a client cannot make the
4
- * Worker buffer more than it allows.
5
- */
6
- export async function readCappedBody(
7
- body: ReadableStream<Uint8Array>,
8
- limit: number
9
- ): Promise<Uint8Array | null> {
10
- let total = 0;
11
- let exceeded = false;
12
-
13
- const capped = body.pipeThrough(
14
- new TransformStream<Uint8Array, Uint8Array>({
15
- transform(chunk, controller) {
16
- total += chunk.byteLength;
17
-
18
- if (total > limit) {
19
- exceeded = true;
20
- controller.error(new Error("The body is over the size limit"));
21
-
22
- return;
23
- }
24
-
25
- controller.enqueue(chunk);
26
- },
27
- })
28
- );
29
-
30
- try {
31
- return new Uint8Array(await new Response(capped).arrayBuffer());
32
- } catch (error) {
33
- if (exceeded) return null;
34
- throw error;
35
- }
36
- }