inboxer 0.4.12 → 0.5.1

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 (50) hide show
  1. package/README.md +40 -20
  2. package/dist/app.js +4 -3
  3. package/dist/config.d.ts +2 -4
  4. package/dist/config.js +13 -4
  5. package/dist/core/address.d.ts +5 -1
  6. package/dist/core/address.js +11 -1
  7. package/dist/core/mail.d.ts +24 -13
  8. package/dist/core/mail.js +158 -85
  9. package/dist/core/sync.d.ts +6 -0
  10. package/dist/core/sync.js +22 -7
  11. package/dist/core/threads.d.ts +2 -0
  12. package/dist/core/threads.js +12 -1
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.js +5 -5
  15. package/dist/mcp.js +8 -8
  16. package/dist/provider/index.d.ts +2 -1
  17. package/dist/provider/index.js +10 -6
  18. package/dist/provider/kapso.d.ts +8 -0
  19. package/dist/provider/kapso.js +198 -0
  20. package/dist/provider/resend.d.ts +1 -1
  21. package/dist/provider/resend.js +14 -10
  22. package/dist/provider/types.d.ts +35 -16
  23. package/dist/store.d.ts +2 -2
  24. package/dist/store.js +4 -4
  25. package/dist/types.d.ts +10 -2
  26. package/dist/ui/routes.js +15 -11
  27. package/dist/ui/static/app.js +19 -3
  28. package/dist/ui/static/style.css +21 -5
  29. package/dist/ui/views.d.ts +7 -5
  30. package/dist/ui/views.js +39 -23
  31. package/package.json +1 -1
  32. package/skills/inboxer/SKILL.md +15 -8
  33. package/src/app.ts +4 -3
  34. package/src/config.ts +10 -3
  35. package/src/core/address.ts +13 -1
  36. package/src/core/mail.ts +162 -89
  37. package/src/core/sync.ts +23 -7
  38. package/src/core/threads.ts +12 -1
  39. package/src/index.ts +10 -8
  40. package/src/mcp.ts +8 -8
  41. package/src/provider/index.ts +9 -5
  42. package/src/provider/kapso.ts +251 -0
  43. package/src/provider/resend.ts +15 -11
  44. package/src/provider/types.ts +38 -14
  45. package/src/store.ts +4 -4
  46. package/src/types.ts +10 -2
  47. package/src/ui/routes.ts +16 -11
  48. package/src/ui/static/app.js +19 -3
  49. package/src/ui/static/style.css +21 -5
  50. package/src/ui/views.ts +41 -24
package/src/core/mail.ts CHANGED
@@ -1,15 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import type { DeliveryStatus, MailProvider, ProviderEvent } from "../provider/types.ts";
2
+ import type { DeliveryStatus, MailProvider, ProviderEvent, ProviderKind, ProviderMessage } from "../provider/types.ts";
3
3
  import { reaches } from "../config.ts";
4
4
  import { NotFoundError, nid, type Store } from "../store.ts";
5
5
  import { CATCHALL, type Actor, type Contact, type Context, type AttachmentMeta, type InboxerConfig, type MailboxConfig, type Message, type MetaValue, type PendingAction, type Scope, type Thread } from "../types.ts";
6
6
  import { AttachmentFiles } from "./attachments.ts";
7
- import { bareAddress, domainOf, formatAddress } from "./address.ts";
7
+ import { bareAddress, domainOf, formatAddress, phoneAddress } from "./address.ts";
8
8
  import { mergeContext, metaMatches, type ContextPatch } from "./context.ts";
9
9
  import { htmlToText, replySubject, textToHtml, tokenize } from "./text.ts";
10
- import { messageTime, participantsOf, refreshThread, resolveThreadId, threadMessages } from "./threads.ts";
10
+ import { chatThreadId, messageTime, participantsOf, refreshThread, resolveThreadId, threadMessages } from "./threads.ts";
11
11
 
12
- const STATUS_RANK: Record<DeliveryStatus, number> = { sent: 1, delivered: 2, bounced: 3, failed: 3 };
12
+ const STATUS_RANK: Record<DeliveryStatus, number> = { sent: 1, delivered: 2, read: 3, bounced: 4, failed: 4 };
13
13
 
14
14
  export class ConflictError extends Error {
15
15
  readonly current: Message;
@@ -27,6 +27,14 @@ export class InvalidRequestError extends Error {
27
27
  }
28
28
  }
29
29
 
30
+ /** The one phone number a chat message goes to. */
31
+ function chatRecipient(to: string[]): string[] {
32
+ if (to.length !== 1) throw new InvalidRequestError("a chat message takes exactly one recipient");
33
+ const phone = phoneAddress(to[0]!);
34
+ if (!phone) throw new InvalidRequestError(`"${to[0]}" is not a phone number`);
35
+ return [phone];
36
+ }
37
+
30
38
  export type ThreadStatus = "unanswered" | "all" | "archived";
31
39
 
32
40
  export interface ListThreadsInput {
@@ -95,7 +103,7 @@ export interface MessageView {
95
103
  /** The mail domain: everything the MCP tools, the UI and the webhook do goes through here. */
96
104
  export class Mail {
97
105
  readonly store: Store;
98
- readonly provider: MailProvider;
106
+ readonly providers: Record<string, MailProvider>;
99
107
  readonly cfg: InboxerConfig;
100
108
  private readonly ownAddresses: Set<string>;
101
109
  private readonly domains: Set<string>;
@@ -104,12 +112,19 @@ export class Mail {
104
112
  /** Fires "change" after every write, so open pages can refresh. */
105
113
  readonly changes = new EventTarget();
106
114
 
107
- constructor(store: Store, provider: MailProvider, cfg: InboxerConfig) {
115
+ constructor(store: Store, providers: Record<string, MailProvider>, cfg: InboxerConfig) {
108
116
  this.store = store;
109
- this.provider = provider;
117
+ this.providers = providers;
110
118
  this.cfg = cfg;
111
- this.ownAddresses = new Set(Object.values(cfg.mailboxes).map(m => bareAddress(m.address)));
112
- this.domains = new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)));
119
+ const mailboxes = Object.values(cfg.mailboxes);
120
+ for (const [name, provider] of Object.entries(providers)) {
121
+ if (provider.name !== name) throw new Error(`Provider "${provider.name}" is registered as "${name}"`);
122
+ if (provider.kind === "chat" && mailboxes.filter(m => m.provider === name).length !== 1) {
123
+ throw new Error(`Invalid inboxer config: chat provider "${name}" must serve exactly one mailbox`);
124
+ }
125
+ }
126
+ this.ownAddresses = new Set(mailboxes.map(m => bareAddress(m.address)));
127
+ this.domains = new Set(mailboxes.filter(m => this.provider(m.provider).kind === "mail").map(m => domainOf(m.address)));
113
128
  this.files = new AttachmentFiles(cfg.dataDir);
114
129
  }
115
130
 
@@ -120,14 +135,35 @@ export class Mail {
120
135
  return result;
121
136
  }
122
137
 
123
- listMailboxes(scope: Scope): { id: string; address: string; name: string }[] {
138
+ private provider(name: string): MailProvider {
139
+ const provider = this.providers[name];
140
+ if (!provider) throw new Error(`Unknown provider "${name}"`);
141
+ return provider;
142
+ }
143
+
144
+ /** The catch-all only collects mail. */
145
+ kindOf(mailbox: string): ProviderKind {
146
+ const configured = this.cfg.mailboxes[mailbox];
147
+ return configured ? this.provider(configured.provider).kind : "mail";
148
+ }
149
+
150
+ /** Whether the review UI may draft and send in `mailbox`. */
151
+ uiCanWrite(mailbox: string): boolean {
152
+ return !this.cfg.mailboxes[mailbox]?.uiReadOnly;
153
+ }
154
+
155
+ private assertCanWrite(mailbox: string, actor: Actor): void {
156
+ if (actor.kind === "ui" && !this.uiCanWrite(mailbox)) throw new InvalidRequestError(`Mailbox "${mailbox}" is read-only in the review UI`);
157
+ }
158
+
159
+ listMailboxes(scope: Scope): { id: string; address: string; name: string; kind: ProviderKind }[] {
124
160
  return [
125
- ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name })),
126
- { id: CATCHALL, address: "*", name: "Catch-all" },
161
+ ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name, kind: this.kindOf(id) })),
162
+ { id: CATCHALL, address: "*", name: "Catch-all", kind: "mail" as const },
127
163
  ].filter(m => reaches(scope, m.id));
128
164
  }
129
165
 
130
- /** A configured mailbox address or any other address on its domains, such as one the catch-all received. */
166
+ /** A configured mailbox address or any other address on a mail domain, such as one the catch-all received. */
131
167
  isOwn(address: string): boolean {
132
168
  const bare = bareAddress(address);
133
169
  return this.ownAddresses.has(bare) || this.domains.has(domainOf(bare));
@@ -180,18 +216,18 @@ export class Mail {
180
216
  }
181
217
  }
182
218
 
183
- private mailboxFor(addresses: string[]): string {
219
+ /** A chat provider serves one mailbox; mail goes to the mailbox it is addressed to, else to the catch-all. */
220
+ private mailboxFor(provider: MailProvider, addresses: string[]): string {
221
+ const served = Object.entries(this.cfg.mailboxes).filter(([, m]) => m.provider === provider.name);
222
+ if (provider.kind === "chat") return served[0]![0];
184
223
  const bare = addresses.map(bareAddress);
185
- for (const [id, mailbox] of Object.entries(this.cfg.mailboxes)) {
186
- if (bare.includes(bareAddress(mailbox.address))) return id;
187
- }
188
- return CATCHALL;
224
+ return served.find(([, m]) => bare.includes(bareAddress(m.address)))?.[0] ?? CATCHALL;
189
225
  }
190
226
 
191
227
  /** Who sends for `id`; the catch-all answers as `address`, with the name and signature of a mailbox on that domain. */
192
228
  private sendingMailbox(id: string, address: string | null): MailboxConfig {
193
229
  const peer = id === CATCHALL && address ? Object.values(this.cfg.mailboxes).find(m => domainOf(m.address) === domainOf(address)) : undefined;
194
- if (peer && address) return { name: peer.name, address: bareAddress(address), signatureText: peer.signatureText, signatureHtml: peer.signatureHtml };
230
+ if (peer && address) return { name: peer.name, address: bareAddress(address), provider: peer.provider, signatureText: peer.signatureText, signatureHtml: peer.signatureHtml };
195
231
  const mailbox = this.cfg.mailboxes[id];
196
232
  if (!mailbox) throw new InvalidRequestError(`Mailbox "${id}" cannot send (configured: ${Object.keys(this.cfg.mailboxes).join(", ")})`);
197
233
  return mailbox;
@@ -200,14 +236,19 @@ export class Mail {
200
236
  // Inbound
201
237
 
202
238
  /**
203
- * Stores an inbound message once per provider id and returns its id. Attachments are copied to
204
- * disk right away; one that fails to download is fetched again the first time it is opened.
239
+ * Stores a message the provider holds once per provider id and returns its id: one received, or
240
+ * one sent on the account by someone else. A message already known only takes the delivery
241
+ * status that came with it. Attachments are copied to disk right away; one that fails to
242
+ * download is fetched again the first time it is opened.
205
243
  */
206
- async ingest(providerId: string): Promise<string> {
207
- const known = await this.store.lookupProviderId(this.provider.name, providerId);
208
- if (known) return known;
209
- const inbound = await this.provider.getInbound(providerId);
210
- const id = await this.storeInbound(providerId, inbound);
244
+ async ingest(providerName: string, providerId: string, given?: ProviderMessage): Promise<string> {
245
+ const provider = this.provider(providerName);
246
+ const known = await this.store.lookupProviderId(provider.name, providerId);
247
+ if (known) {
248
+ if (given?.status) await this.applyStatus(provider.name, providerId, given.status, null);
249
+ return known;
250
+ }
251
+ const id = await this.storeMessage(provider, given ?? await provider.getMessage(providerId));
211
252
  const message = await this.store.requireMessage(id);
212
253
  for (const meta of message.attachments) {
213
254
  await this.attachmentBody(message, meta).catch(err =>
@@ -216,33 +257,39 @@ export class Mail {
216
257
  return id;
217
258
  }
218
259
 
219
- private storeInbound(providerId: string, inbound: Awaited<ReturnType<MailProvider["getInbound"]>>): Promise<string> {
260
+ private storeMessage(provider: MailProvider, given: ProviderMessage): Promise<string> {
220
261
  return this.write(async () => {
221
- const existing = await this.store.lookupProviderId(this.provider.name, providerId);
262
+ const existing = await this.store.lookupProviderId(provider.name, given.providerId);
222
263
  if (existing) return existing;
223
264
 
224
- const mailbox = this.mailboxFor([...inbound.deliveredTo, ...inbound.to, ...inbound.cc]);
225
- const participants = participantsOf(inbound);
226
- const threadId = await resolveThreadId(
227
- this.store,
228
- {
229
- mailbox,
230
- inReplyTo: inbound.inReplyTo,
231
- references: inbound.references,
232
- subject: inbound.subject,
233
- participants,
234
- at: inbound.receivedAt,
235
- },
236
- address => this.isOwn(address),
237
- this.cfg.threadWindowDays,
238
- );
265
+ const incoming = given.direction === "in";
266
+ const mailbox = this.mailboxFor(provider, incoming ? [...given.deliveredTo, ...given.to, ...given.cc] : [given.from]);
267
+ const line = provider.kind === "chat" ? this.cfg.mailboxes[mailbox]! : null;
268
+ const inbound: ProviderMessage = line
269
+ ? { ...given, ...(incoming ? { to: [bareAddress(line.address)] } : { from: formatAddress(line.name, line.address) }) }
270
+ : given;
271
+ const threadId = line
272
+ ? await chatThreadId(this.store, mailbox, bareAddress(incoming ? inbound.from : inbound.to[0]!))
273
+ : await resolveThreadId(
274
+ this.store,
275
+ {
276
+ mailbox,
277
+ inReplyTo: inbound.inReplyTo,
278
+ references: inbound.references,
279
+ subject: inbound.subject,
280
+ participants: participantsOf(inbound),
281
+ at: inbound.at,
282
+ },
283
+ address => this.isOwn(address),
284
+ this.cfg.threadWindowDays,
285
+ );
239
286
  const message: Message = {
240
287
  id: nid(),
241
- provider: this.provider.name,
288
+ provider: provider.name,
242
289
  provider_id: inbound.providerId,
243
290
  mailbox,
244
- direction: "in",
245
- status: "received",
291
+ direction: inbound.direction,
292
+ status: incoming ? "received" : inbound.status ?? "sent",
246
293
  message_id: inbound.messageId,
247
294
  in_reply_to: inbound.inReplyTo,
248
295
  references: inbound.references,
@@ -260,34 +307,34 @@ export class Mail {
260
307
  labels: {},
261
308
  note: null,
262
309
  created_by: null,
263
- read: false,
310
+ read: !incoming,
264
311
  archived: false,
265
- created_at: inbound.receivedAt,
266
- sent_at: null,
312
+ created_at: inbound.at,
313
+ sent_at: incoming ? null : inbound.at,
267
314
  version: 1,
268
315
  edited_by_human: false,
269
316
  pending: null,
270
317
  };
271
318
  await this.store.putMessage(message);
272
- await this.store.indexProviderId(this.provider.name, inbound.providerId, message.id);
319
+ await this.store.indexProviderId(provider.name, inbound.providerId, message.id);
273
320
  if (message.message_id) await this.store.indexMessageId(message.message_id, message.id);
274
321
  await refreshThread(this.store, threadId, message.id);
275
322
  return message.id;
276
323
  });
277
324
  }
278
325
 
279
- async applyEvent(event: ProviderEvent): Promise<void> {
280
- if (event.type === "received") {
281
- await this.ingest(event.providerId);
326
+ async applyEvent(provider: string, event: ProviderEvent): Promise<void> {
327
+ if (event.type === "message") {
328
+ await this.ingest(provider, event.providerId, event.message);
282
329
  return;
283
330
  }
284
- await this.applyStatus(event.providerId, event.status, event.messageId);
331
+ await this.applyStatus(provider, event.providerId, event.status, event.messageId);
285
332
  }
286
333
 
287
334
  /** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
288
- applyStatus(providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void> {
335
+ applyStatus(provider: string, providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void> {
289
336
  return this.write(async () => {
290
- const id = await this.store.lookupProviderId(this.provider.name, providerId);
337
+ const id = await this.store.lookupProviderId(provider, providerId);
291
338
  if (!id) return;
292
339
  const message = await this.store.requireMessage(id);
293
340
  if (message.direction !== "out") return;
@@ -365,14 +412,14 @@ export class Mail {
365
412
  // Context
366
413
 
367
414
  async getContact(address: string, scope: Scope): Promise<Contact | null> {
368
- const bare = bareAddress(address);
415
+ const bare = phoneAddress(address) ?? bareAddress(address);
369
416
  await this.requireContactAccess(bare, scope);
370
417
  return this.store.getContact(bare);
371
418
  }
372
419
 
373
420
  async setContact(address: string, patch: ContextPatch, actor: Actor): Promise<Contact> {
374
- const bare = bareAddress(address);
375
- if (!bare.includes("@")) throw new InvalidRequestError(`"${address}" is not an email address`);
421
+ const bare = phoneAddress(address) ?? bareAddress(address);
422
+ if (!bare.includes("@") && !bare.startsWith("+")) throw new InvalidRequestError(`"${address}" is not an email address or a phone number`);
376
423
  await this.requireContactAccess(bare, actor.scope);
377
424
  return this.write(async () => {
378
425
  const contact: Contact = { address: bare, ...this.merge(await this.store.getContact(bare), patch, actor) };
@@ -474,10 +521,10 @@ export class Mail {
474
521
  let sender: MailboxConfig;
475
522
  let to: string[];
476
523
  let cc = input.cc ?? [];
477
- let subject: string;
524
+ let subject: string | undefined;
478
525
  let inReplyTo: string | null = null;
479
526
  let references: string[] = [];
480
- let threadId: string;
527
+ let threadId: string | undefined;
481
528
 
482
529
  if (input.replyToId) {
483
530
  const original = await this.requireMessage(input.replyToId, actor.scope);
@@ -493,18 +540,28 @@ export class Mail {
493
540
  } else {
494
541
  if (!input.mailbox) throw new InvalidRequestError("mailbox is required when not replying");
495
542
  if (!input.to?.length) throw new InvalidRequestError("to is required when not replying");
496
- if (input.subject === undefined) throw new InvalidRequestError("subject is required when not replying");
497
543
  mailbox = input.mailbox;
498
544
  sender = this.sendingMailbox(mailbox, null);
499
545
  to = input.to;
500
546
  subject = input.subject;
501
- threadId = nid();
502
547
  }
503
548
  if (!reaches(actor.scope, mailbox)) throw new InvalidRequestError(`Mailbox "${mailbox}" is not available to ${actor.name}`);
549
+ this.assertCanWrite(mailbox, actor);
550
+
551
+ if (this.provider(sender.provider).kind === "chat") {
552
+ if (cc.length || input.bcc?.length || input.html !== undefined || input.subject) {
553
+ throw new InvalidRequestError(`Mailbox "${mailbox}" is a chat: a message is plain text to one phone number`);
554
+ }
555
+ to = chatRecipient(to);
556
+ subject = "";
557
+ threadId ??= await chatThreadId(this.store, mailbox, to[0]!);
558
+ }
559
+ if (subject === undefined) throw new InvalidRequestError("subject is required when not replying");
560
+ threadId ??= nid();
504
561
 
505
562
  const draft: Message = {
506
563
  id: nid(),
507
- provider: this.provider.name,
564
+ provider: sender.provider,
508
565
  provider_id: null,
509
566
  mailbox,
510
567
  direction: "out",
@@ -541,9 +598,10 @@ export class Mail {
541
598
  return draft;
542
599
  }
543
600
 
544
- private async requireDraft(id: string, scope: Scope): Promise<Message> {
545
- const draft = await this.requireMessage(id, scope);
601
+ private async requireDraft(id: string, actor: Actor): Promise<Message> {
602
+ const draft = await this.requireMessage(id, actor.scope);
546
603
  if (draft.status !== "draft") throw new InvalidRequestError(`Message ${id} is not a pending draft (status: ${draft.status})`);
604
+ this.assertCanWrite(draft.mailbox, actor);
547
605
  return draft;
548
606
  }
549
607
 
@@ -553,7 +611,7 @@ export class Mail {
553
611
  */
554
612
  updateDraft(id: string, version: number, patch: DraftPatch, actor: Actor, force = false): Promise<Message> {
555
613
  return this.write(async () => {
556
- const draft = await this.requireDraft(id, actor.scope);
614
+ const draft = await this.requireDraft(id, actor);
557
615
  if (draft.version !== version) throw new ConflictError(draft);
558
616
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
559
617
  if (actor.kind !== "ui" && draft.edited_by_human && !force) {
@@ -561,6 +619,12 @@ export class Mail {
561
619
  }
562
620
  const changed = Object.keys(patch).filter(k => patch[k as keyof DraftPatch] !== undefined);
563
621
  Object.assign(draft, Object.fromEntries(changed.map(k => [k, patch[k as keyof DraftPatch]])));
622
+ if (this.provider(draft.provider).kind === "chat") {
623
+ if (draft.cc.length || draft.bcc.length || draft.html || draft.subject) {
624
+ throw new InvalidRequestError(`Draft ${id} is a chat message: plain text to one phone number`);
625
+ }
626
+ draft.to = chatRecipient(draft.to);
627
+ }
564
628
  if (actor.kind === "ui") {
565
629
  draft.edited_by_human = true;
566
630
  if (patch.text !== undefined && patch.html === undefined) draft.html = null;
@@ -578,7 +642,7 @@ export class Mail {
578
642
  }
579
643
 
580
644
  private async discardDraftUnlocked(id: string, actor: Actor): Promise<void> {
581
- const draft = await this.requireDraft(id, actor.scope);
645
+ const draft = await this.requireDraft(id, actor);
582
646
  draft.status = "discarded";
583
647
  draft.pending = null;
584
648
  await this.store.putMessage(draft);
@@ -590,8 +654,11 @@ export class Mail {
590
654
  /** Attaching does not change `version`: it never conflicts with text edits in flight. */
591
655
  attach(id: string, file: { filename: string; contentType: string; body: Uint8Array }, actor: Actor): Promise<Message> {
592
656
  return this.write(async () => {
593
- const draft = await this.requireDraft(id, actor.scope);
657
+ const draft = await this.requireDraft(id, actor);
594
658
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
659
+ if (draft.attachments.length && this.provider(draft.provider).kind === "chat") {
660
+ throw new InvalidRequestError(`Draft ${id} is a chat message: it carries one attachment`);
661
+ }
595
662
  const meta: AttachmentMeta = {
596
663
  id: nid(),
597
664
  filename: file.filename,
@@ -610,7 +677,7 @@ export class Mail {
610
677
 
611
678
  detach(id: string, attachmentId: string, actor: Actor): Promise<Message> {
612
679
  return this.write(async () => {
613
- const draft = await this.requireDraft(id, actor.scope);
680
+ const draft = await this.requireDraft(id, actor);
614
681
  if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
615
682
  const index = draft.attachments.findIndex(a => a.id === attachmentId);
616
683
  if (index < 0) throw new NotFoundError(`Attachment ${attachmentId} not found in draft ${id}`);
@@ -626,7 +693,7 @@ export class Mail {
626
693
  /** Starts the undo window for a send or discard. Calling it again keeps the first one. */
627
694
  schedule(id: string, action: PendingAction["action"], actor: Actor): Promise<Message> {
628
695
  return this.write(async () => {
629
- const draft = await this.requireDraft(id, actor.scope);
696
+ const draft = await this.requireDraft(id, actor);
630
697
  if (!draft.pending) {
631
698
  draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
632
699
  await this.store.putMessage(draft);
@@ -639,7 +706,7 @@ export class Mail {
639
706
 
640
707
  undo(id: string, actor: Actor): Promise<Message> {
641
708
  return this.write(async () => {
642
- const draft = await this.requireDraft(id, actor.scope);
709
+ const draft = await this.requireDraft(id, actor);
643
710
  clearTimeout(this.timers.get(id));
644
711
  this.timers.delete(id);
645
712
  if (draft.pending) {
@@ -693,26 +760,32 @@ export class Mail {
693
760
  }
694
761
 
695
762
  /**
696
- * The draft id is the idempotency key and the Message-ID is stored before the provider call,
697
- * so retrying a failed send repeats the same request instead of sending twice.
763
+ * The draft id is the idempotency key and a mail's Message-ID is stored before the provider call,
764
+ * so retrying a failed send repeats the same request instead of sending twice. A chat message
765
+ * goes out as written: no headers, HTML or signature.
698
766
  */
699
767
  private async sendDraftUnlocked(id: string, actor: Actor): Promise<Message> {
700
- const draft = await this.requireDraft(id, actor.scope);
768
+ const draft = await this.requireDraft(id, actor);
769
+ const provider = this.provider(draft.provider);
770
+ const chat = provider.kind === "chat";
701
771
  const sender = this.sendingMailbox(draft.mailbox, draft.from);
702
- if (!draft.message_id) {
703
- draft.message_id = `<${randomUUID()}@${domainOf(sender.address)}>`;
704
- await this.store.putMessage(draft);
772
+ const headers: Record<string, string> = {};
773
+ if (!chat) {
774
+ if (!draft.message_id) {
775
+ draft.message_id = `<${randomUUID()}@${domainOf(sender.address)}>`;
776
+ await this.store.putMessage(draft);
777
+ }
778
+ headers["Message-ID"] = draft.message_id;
779
+ if (draft.in_reply_to) headers["In-Reply-To"] = draft.in_reply_to;
780
+ if (draft.references.length) headers["References"] = draft.references.join(" ");
705
781
  }
706
- const headers: Record<string, string> = { "Message-ID": draft.message_id };
707
- if (draft.in_reply_to) headers["In-Reply-To"] = draft.in_reply_to;
708
- if (draft.references.length) headers["References"] = draft.references.join(" ");
709
782
 
710
783
  const attachments = await Promise.all(draft.attachments.map(async a => ({
711
784
  filename: a.filename,
712
785
  contentType: a.content_type,
713
786
  content: await this.attachmentBody(draft, a),
714
787
  })));
715
- const { providerId } = await this.provider.send(
788
+ const { providerId } = await provider.send(
716
789
  {
717
790
  from: draft.from,
718
791
  to: draft.to,
@@ -720,8 +793,8 @@ export class Mail {
720
793
  bcc: draft.bcc,
721
794
  replyTo: draft.reply_to,
722
795
  subject: draft.subject,
723
- text: sender.signatureText ? `${draft.text}\n\n${sender.signatureText}` : draft.text,
724
- html: (draft.html ?? textToHtml(draft.text)) + (sender.signatureHtml ? `\n${sender.signatureHtml}` : ""),
796
+ text: !chat && sender.signatureText ? `${draft.text}\n\n${sender.signatureText}` : draft.text,
797
+ html: chat ? null : (draft.html ?? textToHtml(draft.text)) + (sender.signatureHtml ? `\n${sender.signatureHtml}` : ""),
725
798
  headers,
726
799
  attachments,
727
800
  },
@@ -734,8 +807,8 @@ export class Mail {
734
807
  draft.sent_at = new Date().toISOString();
735
808
  draft.headers = headers;
736
809
  await this.store.putMessage(draft);
737
- await this.store.indexProviderId(this.provider.name, providerId, draft.id);
738
- await this.store.indexMessageId(draft.message_id, draft.id);
810
+ await this.store.indexProviderId(provider.name, providerId, draft.id);
811
+ if (draft.message_id) await this.store.indexMessageId(draft.message_id, draft.id);
739
812
  await this.store.setDraft(draft.id, false);
740
813
  await refreshThread(this.store, draft.thread_id);
741
814
  await this.store.audit("send", actor, draft.id, { provider_id: providerId });
@@ -754,7 +827,7 @@ export class Mail {
754
827
  return this.send({ replyToId: messageId, replyAll, text }, actor);
755
828
  }
756
829
 
757
- /** An inbound attachment's metadata and bytes, from disk or, the first time, from the provider. */
830
+ /** An attachment's metadata and bytes, from disk or, the first time for a message the provider holds, from the provider. */
758
831
  async getAttachment(messageId: string, attachmentId: string, scope: Scope): Promise<{ meta: AttachmentMeta; body: Uint8Array }> {
759
832
  const message = await this.requireMessage(messageId, scope);
760
833
  const meta = message.attachments.find(a => a.id === attachmentId);
@@ -765,8 +838,8 @@ export class Mail {
765
838
  private async attachmentBody(message: Message, meta: AttachmentMeta): Promise<Uint8Array> {
766
839
  const stored = await this.files.read(message.id, meta.id);
767
840
  if (stored) return stored;
768
- if (!message.provider_id || message.direction !== "in") throw new NotFoundError(`Attachment ${meta.id} not found`);
769
- const body = await this.provider.getAttachment(message.provider_id, meta.id);
841
+ if (!message.provider_id || message.created_by) throw new NotFoundError(`Attachment ${meta.id} not found`);
842
+ const body = await this.provider(message.provider).getAttachment(message.provider_id, meta.id);
770
843
  await this.files.write(message.id, meta.id, body);
771
844
  return body;
772
845
  }
package/src/core/sync.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { MailProvider } from "../provider/types.ts";
1
2
  import type { Mail } from "./mail.ts";
2
3
 
3
4
  /**
@@ -35,17 +36,32 @@ export class Sync {
35
36
  return this.running;
36
37
  }
37
38
 
39
+ /** Providers sync one after another; one that fails does not hold back the rest. */
38
40
  private async runOnce(): Promise<void> {
41
+ const failures: unknown[] = [];
42
+ for (const provider of Object.values(this.mail.providers)) {
43
+ await this.syncProvider(provider).catch(err => failures.push(err));
44
+ }
45
+ if (failures.length) throw failures.length === 1 ? failures[0] : new AggregateError(failures, "several providers failed to sync");
46
+ }
47
+
48
+ /**
49
+ * A chat mailbox mirrors conversations that began before Inboxer was attached to the line,
50
+ * so its first run reads the whole history.
51
+ */
52
+ private async syncProvider(provider: MailProvider): Promise<void> {
39
53
  const startedAt = new Date();
40
- const cursor = await this.mail.store.getSyncCursor();
41
- const since = new Date((cursor ? new Date(cursor).getTime() : startedAt.getTime()) - this.intervalMs);
54
+ const cursor = await this.mail.store.getSyncCursor(provider.name);
55
+ const since = cursor
56
+ ? new Date(new Date(cursor).getTime() - this.intervalMs)
57
+ : provider.kind === "chat" ? new Date(0) : new Date(startedAt.getTime() - this.intervalMs);
42
58
 
43
- for await (const providerId of this.mail.provider.listInbound(since)) {
44
- await this.mail.ingest(providerId);
59
+ for await (const event of provider.listMessages(since)) {
60
+ await this.mail.applyEvent(provider.name, event);
45
61
  }
46
- for await (const { providerId, status } of this.mail.provider.listOutbound(since)) {
47
- await this.mail.applyStatus(providerId, status, null);
62
+ for await (const { providerId, status } of provider.listOutbound(since)) {
63
+ await this.mail.applyStatus(provider.name, providerId, status, null);
48
64
  }
49
- await this.mail.store.setSyncCursor(startedAt.toISOString());
65
+ await this.mail.store.setSyncCursor(provider.name, startedAt.toISOString());
50
66
  }
51
67
  }
@@ -1,6 +1,6 @@
1
1
  import { nid, type Store } from "../store.ts";
2
2
  import type { Message, Thread } from "../types.ts";
3
- import { bareAddress } from "./address.ts";
3
+ import { bareAddress, nameOf } from "./address.ts";
4
4
  import { normalizeSubject } from "./text.ts";
5
5
 
6
6
  const DAY_MS = 24 * 60 * 60 * 1000;
@@ -54,6 +54,12 @@ export async function resolveThreadId(
54
54
  return nid();
55
55
  }
56
56
 
57
+ /** A chat mailbox keeps one thread per counterpart. */
58
+ export async function chatThreadId(store: Store, mailbox: string, counterpart: string): Promise<string> {
59
+ const thread = (await store.allThreads()).find(t => t.mailbox === mailbox && t.participants.includes(counterpart));
60
+ return thread?.id ?? nid();
61
+ }
62
+
57
63
  export async function threadMessages(store: Store, thread: Thread): Promise<Message[]> {
58
64
  const messages = await Promise.all(thread.message_ids.map(id => store.requireMessage(id)));
59
65
  return messages.filter(m => m.status !== "discarded").sort((a, b) => messageTime(a).localeCompare(messageTime(b)));
@@ -69,6 +75,7 @@ export async function refreshThread(store: Store, threadId: string, newMessageId
69
75
  subject: "",
70
76
  norm_subject: "",
71
77
  participants: [],
78
+ names: {},
72
79
  last_at: "",
73
80
  last_direction: "in",
74
81
  has_draft: false,
@@ -90,6 +97,10 @@ export async function refreshThread(store: Store, threadId: string, newMessageId
90
97
  thread.subject = first.subject;
91
98
  thread.norm_subject = normalizeSubject(first.subject);
92
99
  thread.participants = [...new Set(messages.flatMap(participantsOf))];
100
+ for (const m of messages) {
101
+ const name = m.direction === "in" ? nameOf(m.from) : null;
102
+ if (name) thread.names[bareAddress(m.from)] = name;
103
+ }
93
104
  thread.last_at = messageTime(last);
94
105
  thread.last_direction = last.direction;
95
106
  thread.has_draft = messages.some(m => m.status === "draft");
package/src/index.ts CHANGED
@@ -5,14 +5,14 @@ import { Access } from "./auth.ts";
5
5
  import { assertConfig } from "./config.ts";
6
6
  import { Mail } from "./core/mail.ts";
7
7
  import { Sync } from "./core/sync.ts";
8
- import { resolveProvider } from "./provider/index.ts";
8
+ import { resolveProviders } from "./provider/index.ts";
9
9
  import type { MailProvider } from "./provider/types.ts";
10
10
  import { Store } from "./store.ts";
11
11
  import type { InboxerConfig } from "./types.ts";
12
12
 
13
13
  export interface InboxerOptions {
14
- /** A provider instance to use instead of resolving `cfg.provider.type`. */
15
- provider?: MailProvider;
14
+ /** Provider instances by name, to use instead of resolving `cfg.providers`. */
15
+ providers?: Record<string, MailProvider>;
16
16
  }
17
17
 
18
18
  export interface Inboxer {
@@ -27,10 +27,10 @@ export interface Inboxer {
27
27
  }
28
28
 
29
29
  export function createInboxer(cfg: InboxerConfig, options: InboxerOptions = {}): Inboxer {
30
- assertConfig(cfg, { requireProvider: !options.provider });
31
- const provider = options.provider ?? resolveProvider(cfg.provider);
30
+ assertConfig(cfg, options.providers && Object.keys(options.providers));
31
+ const providers = options.providers ?? resolveProviders(cfg.providers);
32
32
  const store = new Store(cfg.dataDir);
33
- const mail = new Mail(store, provider, cfg);
33
+ const mail = new Mail(store, providers, cfg);
34
34
  const access = new Access(store, cfg);
35
35
  const sync = new Sync(mail, cfg.syncIntervalMin);
36
36
 
@@ -69,7 +69,7 @@ export interface LoginLinkOptions {
69
69
  * Opens the database, stores the link and closes it; the session it creates reaches every mailbox.
70
70
  */
71
71
  export async function createLoginLink(cfg: InboxerConfig, options: LoginLinkOptions = {}): Promise<{ url: string; expires_at: string }> {
72
- assertConfig(cfg, { requireProvider: false });
72
+ assertConfig(cfg);
73
73
  const store = new Store(cfg.dataDir);
74
74
  await store.connect();
75
75
  try {
@@ -82,12 +82,14 @@ export async function createLoginLink(cfg: InboxerConfig, options: LoginLinkOpti
82
82
  export { WebhookSignatureError } from "./provider/types.ts";
83
83
  export type {
84
84
  DeliveryStatus,
85
- InboundMessage,
86
85
  MailProvider,
86
+ MessageEvent,
87
87
  OutboundAttachment,
88
88
  OutboundMessage,
89
89
  OutboundStatus,
90
90
  ProviderEvent,
91
+ ProviderKind,
92
+ ProviderMessage,
91
93
  WebhookRequest,
92
94
  } from "./provider/types.ts";
93
95
  export type { InboxerConfig, MailboxConfig, ProviderConfig } from "./types.ts";