inboxer 0.4.11 → 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 (48) 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/style.css +5 -0
  28. package/dist/ui/views.d.ts +7 -5
  29. package/dist/ui/views.js +18 -16
  30. package/package.json +1 -1
  31. package/skills/inboxer/SKILL.md +15 -8
  32. package/src/app.ts +4 -3
  33. package/src/config.ts +10 -3
  34. package/src/core/address.ts +13 -1
  35. package/src/core/mail.ts +162 -89
  36. package/src/core/sync.ts +23 -7
  37. package/src/core/threads.ts +12 -1
  38. package/src/index.ts +10 -8
  39. package/src/mcp.ts +8 -8
  40. package/src/provider/index.ts +9 -5
  41. package/src/provider/kapso.ts +251 -0
  42. package/src/provider/resend.ts +15 -11
  43. package/src/provider/types.ts +38 -14
  44. package/src/store.ts +4 -4
  45. package/src/types.ts +10 -2
  46. package/src/ui/routes.ts +16 -11
  47. package/src/ui/static/style.css +5 -0
  48. package/src/ui/views.ts +20 -17
package/dist/core/mail.js CHANGED
@@ -3,11 +3,11 @@ import { reaches } from "../config.js";
3
3
  import { NotFoundError, nid } from "../store.js";
4
4
  import { CATCHALL } from "../types.js";
5
5
  import { AttachmentFiles } from "./attachments.js";
6
- import { bareAddress, domainOf, formatAddress } from "./address.js";
6
+ import { bareAddress, domainOf, formatAddress, phoneAddress } from "./address.js";
7
7
  import { mergeContext, metaMatches } from "./context.js";
8
8
  import { htmlToText, replySubject, textToHtml, tokenize } from "./text.js";
9
- import { messageTime, participantsOf, refreshThread, resolveThreadId, threadMessages } from "./threads.js";
10
- const STATUS_RANK = { sent: 1, delivered: 2, bounced: 3, failed: 3 };
9
+ import { chatThreadId, messageTime, participantsOf, refreshThread, resolveThreadId, threadMessages } from "./threads.js";
10
+ const STATUS_RANK = { sent: 1, delivered: 2, read: 3, bounced: 4, failed: 4 };
11
11
  export class ConflictError extends Error {
12
12
  current;
13
13
  constructor(current) {
@@ -22,10 +22,19 @@ export class InvalidRequestError extends Error {
22
22
  this.name = "InvalidRequestError";
23
23
  }
24
24
  }
25
+ /** The one phone number a chat message goes to. */
26
+ function chatRecipient(to) {
27
+ if (to.length !== 1)
28
+ throw new InvalidRequestError("a chat message takes exactly one recipient");
29
+ const phone = phoneAddress(to[0]);
30
+ if (!phone)
31
+ throw new InvalidRequestError(`"${to[0]}" is not a phone number`);
32
+ return [phone];
33
+ }
25
34
  /** The mail domain: everything the MCP tools, the UI and the webhook do goes through here. */
26
35
  export class Mail {
27
36
  store;
28
- provider;
37
+ providers;
29
38
  cfg;
30
39
  ownAddresses;
31
40
  domains;
@@ -33,12 +42,20 @@ export class Mail {
33
42
  files;
34
43
  /** Fires "change" after every write, so open pages can refresh. */
35
44
  changes = new EventTarget();
36
- constructor(store, provider, cfg) {
45
+ constructor(store, providers, cfg) {
37
46
  this.store = store;
38
- this.provider = provider;
47
+ this.providers = providers;
39
48
  this.cfg = cfg;
40
- this.ownAddresses = new Set(Object.values(cfg.mailboxes).map(m => bareAddress(m.address)));
41
- this.domains = new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)));
49
+ const mailboxes = Object.values(cfg.mailboxes);
50
+ for (const [name, provider] of Object.entries(providers)) {
51
+ if (provider.name !== name)
52
+ throw new Error(`Provider "${provider.name}" is registered as "${name}"`);
53
+ if (provider.kind === "chat" && mailboxes.filter(m => m.provider === name).length !== 1) {
54
+ throw new Error(`Invalid inboxer config: chat provider "${name}" must serve exactly one mailbox`);
55
+ }
56
+ }
57
+ this.ownAddresses = new Set(mailboxes.map(m => bareAddress(m.address)));
58
+ this.domains = new Set(mailboxes.filter(m => this.provider(m.provider).kind === "mail").map(m => domainOf(m.address)));
42
59
  this.files = new AttachmentFiles(cfg.dataDir);
43
60
  }
44
61
  /** Runs `fn` in the store's write queue, then announces the change. */
@@ -47,13 +64,32 @@ export class Mail {
47
64
  this.changes.dispatchEvent(new Event("change"));
48
65
  return result;
49
66
  }
67
+ provider(name) {
68
+ const provider = this.providers[name];
69
+ if (!provider)
70
+ throw new Error(`Unknown provider "${name}"`);
71
+ return provider;
72
+ }
73
+ /** The catch-all only collects mail. */
74
+ kindOf(mailbox) {
75
+ const configured = this.cfg.mailboxes[mailbox];
76
+ return configured ? this.provider(configured.provider).kind : "mail";
77
+ }
78
+ /** Whether the review UI may draft and send in `mailbox`. */
79
+ uiCanWrite(mailbox) {
80
+ return !this.cfg.mailboxes[mailbox]?.uiReadOnly;
81
+ }
82
+ assertCanWrite(mailbox, actor) {
83
+ if (actor.kind === "ui" && !this.uiCanWrite(mailbox))
84
+ throw new InvalidRequestError(`Mailbox "${mailbox}" is read-only in the review UI`);
85
+ }
50
86
  listMailboxes(scope) {
51
87
  return [
52
- ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name })),
53
- { id: CATCHALL, address: "*", name: "Catch-all" },
88
+ ...Object.entries(this.cfg.mailboxes).map(([id, m]) => ({ id, address: m.address, name: m.name, kind: this.kindOf(id) })),
89
+ { id: CATCHALL, address: "*", name: "Catch-all", kind: "mail" },
54
90
  ].filter(m => reaches(scope, m.id));
55
91
  }
56
- /** A configured mailbox address or any other address on its domains, such as one the catch-all received. */
92
+ /** A configured mailbox address or any other address on a mail domain, such as one the catch-all received. */
57
93
  isOwn(address) {
58
94
  const bare = bareAddress(address);
59
95
  return this.ownAddresses.has(bare) || this.domains.has(domainOf(bare));
@@ -101,19 +137,19 @@ export class Mail {
101
137
  throw new NotFoundError(`Contact ${address} not found`);
102
138
  }
103
139
  }
104
- mailboxFor(addresses) {
140
+ /** A chat provider serves one mailbox; mail goes to the mailbox it is addressed to, else to the catch-all. */
141
+ mailboxFor(provider, addresses) {
142
+ const served = Object.entries(this.cfg.mailboxes).filter(([, m]) => m.provider === provider.name);
143
+ if (provider.kind === "chat")
144
+ return served[0][0];
105
145
  const bare = addresses.map(bareAddress);
106
- for (const [id, mailbox] of Object.entries(this.cfg.mailboxes)) {
107
- if (bare.includes(bareAddress(mailbox.address)))
108
- return id;
109
- }
110
- return CATCHALL;
146
+ return served.find(([, m]) => bare.includes(bareAddress(m.address)))?.[0] ?? CATCHALL;
111
147
  }
112
148
  /** Who sends for `id`; the catch-all answers as `address`, with the name and signature of a mailbox on that domain. */
113
149
  sendingMailbox(id, address) {
114
150
  const peer = id === CATCHALL && address ? Object.values(this.cfg.mailboxes).find(m => domainOf(m.address) === domainOf(address)) : undefined;
115
151
  if (peer && address)
116
- return { name: peer.name, address: bareAddress(address), signatureText: peer.signatureText, signatureHtml: peer.signatureHtml };
152
+ return { name: peer.name, address: bareAddress(address), provider: peer.provider, signatureText: peer.signatureText, signatureHtml: peer.signatureHtml };
117
153
  const mailbox = this.cfg.mailboxes[id];
118
154
  if (!mailbox)
119
155
  throw new InvalidRequestError(`Mailbox "${id}" cannot send (configured: ${Object.keys(this.cfg.mailboxes).join(", ")})`);
@@ -121,43 +157,54 @@ export class Mail {
121
157
  }
122
158
  // Inbound
123
159
  /**
124
- * Stores an inbound message once per provider id and returns its id. Attachments are copied to
125
- * disk right away; one that fails to download is fetched again the first time it is opened.
160
+ * Stores a message the provider holds once per provider id and returns its id: one received, or
161
+ * one sent on the account by someone else. A message already known only takes the delivery
162
+ * status that came with it. Attachments are copied to disk right away; one that fails to
163
+ * download is fetched again the first time it is opened.
126
164
  */
127
- async ingest(providerId) {
128
- const known = await this.store.lookupProviderId(this.provider.name, providerId);
129
- if (known)
165
+ async ingest(providerName, providerId, given) {
166
+ const provider = this.provider(providerName);
167
+ const known = await this.store.lookupProviderId(provider.name, providerId);
168
+ if (known) {
169
+ if (given?.status)
170
+ await this.applyStatus(provider.name, providerId, given.status, null);
130
171
  return known;
131
- const inbound = await this.provider.getInbound(providerId);
132
- const id = await this.storeInbound(providerId, inbound);
172
+ }
173
+ const id = await this.storeMessage(provider, given ?? await provider.getMessage(providerId));
133
174
  const message = await this.store.requireMessage(id);
134
175
  for (const meta of message.attachments) {
135
176
  await this.attachmentBody(message, meta).catch(err => console.error(`inboxer: attachment ${meta.id} of message ${id} not stored`, err));
136
177
  }
137
178
  return id;
138
179
  }
139
- storeInbound(providerId, inbound) {
180
+ storeMessage(provider, given) {
140
181
  return this.write(async () => {
141
- const existing = await this.store.lookupProviderId(this.provider.name, providerId);
182
+ const existing = await this.store.lookupProviderId(provider.name, given.providerId);
142
183
  if (existing)
143
184
  return existing;
144
- const mailbox = this.mailboxFor([...inbound.deliveredTo, ...inbound.to, ...inbound.cc]);
145
- const participants = participantsOf(inbound);
146
- const threadId = await resolveThreadId(this.store, {
147
- mailbox,
148
- inReplyTo: inbound.inReplyTo,
149
- references: inbound.references,
150
- subject: inbound.subject,
151
- participants,
152
- at: inbound.receivedAt,
153
- }, address => this.isOwn(address), this.cfg.threadWindowDays);
185
+ const incoming = given.direction === "in";
186
+ const mailbox = this.mailboxFor(provider, incoming ? [...given.deliveredTo, ...given.to, ...given.cc] : [given.from]);
187
+ const line = provider.kind === "chat" ? this.cfg.mailboxes[mailbox] : null;
188
+ const inbound = line
189
+ ? { ...given, ...(incoming ? { to: [bareAddress(line.address)] } : { from: formatAddress(line.name, line.address) }) }
190
+ : given;
191
+ const threadId = line
192
+ ? await chatThreadId(this.store, mailbox, bareAddress(incoming ? inbound.from : inbound.to[0]))
193
+ : await resolveThreadId(this.store, {
194
+ mailbox,
195
+ inReplyTo: inbound.inReplyTo,
196
+ references: inbound.references,
197
+ subject: inbound.subject,
198
+ participants: participantsOf(inbound),
199
+ at: inbound.at,
200
+ }, address => this.isOwn(address), this.cfg.threadWindowDays);
154
201
  const message = {
155
202
  id: nid(),
156
- provider: this.provider.name,
203
+ provider: provider.name,
157
204
  provider_id: inbound.providerId,
158
205
  mailbox,
159
- direction: "in",
160
- status: "received",
206
+ direction: inbound.direction,
207
+ status: incoming ? "received" : inbound.status ?? "sent",
161
208
  message_id: inbound.messageId,
162
209
  in_reply_to: inbound.inReplyTo,
163
210
  references: inbound.references,
@@ -175,33 +222,33 @@ export class Mail {
175
222
  labels: {},
176
223
  note: null,
177
224
  created_by: null,
178
- read: false,
225
+ read: !incoming,
179
226
  archived: false,
180
- created_at: inbound.receivedAt,
181
- sent_at: null,
227
+ created_at: inbound.at,
228
+ sent_at: incoming ? null : inbound.at,
182
229
  version: 1,
183
230
  edited_by_human: false,
184
231
  pending: null,
185
232
  };
186
233
  await this.store.putMessage(message);
187
- await this.store.indexProviderId(this.provider.name, inbound.providerId, message.id);
234
+ await this.store.indexProviderId(provider.name, inbound.providerId, message.id);
188
235
  if (message.message_id)
189
236
  await this.store.indexMessageId(message.message_id, message.id);
190
237
  await refreshThread(this.store, threadId, message.id);
191
238
  return message.id;
192
239
  });
193
240
  }
194
- async applyEvent(event) {
195
- if (event.type === "received") {
196
- await this.ingest(event.providerId);
241
+ async applyEvent(provider, event) {
242
+ if (event.type === "message") {
243
+ await this.ingest(provider, event.providerId, event.message);
197
244
  return;
198
245
  }
199
- await this.applyStatus(event.providerId, event.status, event.messageId);
246
+ await this.applyStatus(provider, event.providerId, event.status, event.messageId);
200
247
  }
201
248
  /** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
202
- applyStatus(providerId, status, messageId) {
249
+ applyStatus(provider, providerId, status, messageId) {
203
250
  return this.write(async () => {
204
- const id = await this.store.lookupProviderId(this.provider.name, providerId);
251
+ const id = await this.store.lookupProviderId(provider, providerId);
205
252
  if (!id)
206
253
  return;
207
254
  const message = await this.store.requireMessage(id);
@@ -288,14 +335,14 @@ export class Mail {
288
335
  }
289
336
  // Context
290
337
  async getContact(address, scope) {
291
- const bare = bareAddress(address);
338
+ const bare = phoneAddress(address) ?? bareAddress(address);
292
339
  await this.requireContactAccess(bare, scope);
293
340
  return this.store.getContact(bare);
294
341
  }
295
342
  async setContact(address, patch, actor) {
296
- const bare = bareAddress(address);
297
- if (!bare.includes("@"))
298
- throw new InvalidRequestError(`"${address}" is not an email address`);
343
+ const bare = phoneAddress(address) ?? bareAddress(address);
344
+ if (!bare.includes("@") && !bare.startsWith("+"))
345
+ throw new InvalidRequestError(`"${address}" is not an email address or a phone number`);
299
346
  await this.requireContactAccess(bare, actor.scope);
300
347
  return this.write(async () => {
301
348
  const contact = { address: bare, ...this.merge(await this.store.getContact(bare), patch, actor) };
@@ -414,19 +461,28 @@ export class Mail {
414
461
  throw new InvalidRequestError("mailbox is required when not replying");
415
462
  if (!input.to?.length)
416
463
  throw new InvalidRequestError("to is required when not replying");
417
- if (input.subject === undefined)
418
- throw new InvalidRequestError("subject is required when not replying");
419
464
  mailbox = input.mailbox;
420
465
  sender = this.sendingMailbox(mailbox, null);
421
466
  to = input.to;
422
467
  subject = input.subject;
423
- threadId = nid();
424
468
  }
425
469
  if (!reaches(actor.scope, mailbox))
426
470
  throw new InvalidRequestError(`Mailbox "${mailbox}" is not available to ${actor.name}`);
471
+ this.assertCanWrite(mailbox, actor);
472
+ if (this.provider(sender.provider).kind === "chat") {
473
+ if (cc.length || input.bcc?.length || input.html !== undefined || input.subject) {
474
+ throw new InvalidRequestError(`Mailbox "${mailbox}" is a chat: a message is plain text to one phone number`);
475
+ }
476
+ to = chatRecipient(to);
477
+ subject = "";
478
+ threadId ??= await chatThreadId(this.store, mailbox, to[0]);
479
+ }
480
+ if (subject === undefined)
481
+ throw new InvalidRequestError("subject is required when not replying");
482
+ threadId ??= nid();
427
483
  const draft = {
428
484
  id: nid(),
429
- provider: this.provider.name,
485
+ provider: sender.provider,
430
486
  provider_id: null,
431
487
  mailbox,
432
488
  direction: "out",
@@ -462,10 +518,11 @@ export class Mail {
462
518
  await this.store.audit("draft.create", actor, draft.id);
463
519
  return draft;
464
520
  }
465
- async requireDraft(id, scope) {
466
- const draft = await this.requireMessage(id, scope);
521
+ async requireDraft(id, actor) {
522
+ const draft = await this.requireMessage(id, actor.scope);
467
523
  if (draft.status !== "draft")
468
524
  throw new InvalidRequestError(`Message ${id} is not a pending draft (status: ${draft.status})`);
525
+ this.assertCanWrite(draft.mailbox, actor);
469
526
  return draft;
470
527
  }
471
528
  /**
@@ -474,7 +531,7 @@ export class Mail {
474
531
  */
475
532
  updateDraft(id, version, patch, actor, force = false) {
476
533
  return this.write(async () => {
477
- const draft = await this.requireDraft(id, actor.scope);
534
+ const draft = await this.requireDraft(id, actor);
478
535
  if (draft.version !== version)
479
536
  throw new ConflictError(draft);
480
537
  if (draft.pending)
@@ -484,6 +541,12 @@ export class Mail {
484
541
  }
485
542
  const changed = Object.keys(patch).filter(k => patch[k] !== undefined);
486
543
  Object.assign(draft, Object.fromEntries(changed.map(k => [k, patch[k]])));
544
+ if (this.provider(draft.provider).kind === "chat") {
545
+ if (draft.cc.length || draft.bcc.length || draft.html || draft.subject) {
546
+ throw new InvalidRequestError(`Draft ${id} is a chat message: plain text to one phone number`);
547
+ }
548
+ draft.to = chatRecipient(draft.to);
549
+ }
487
550
  if (actor.kind === "ui") {
488
551
  draft.edited_by_human = true;
489
552
  if (patch.text !== undefined && patch.html === undefined)
@@ -500,7 +563,7 @@ export class Mail {
500
563
  return this.write(() => this.discardDraftUnlocked(id, actor));
501
564
  }
502
565
  async discardDraftUnlocked(id, actor) {
503
- const draft = await this.requireDraft(id, actor.scope);
566
+ const draft = await this.requireDraft(id, actor);
504
567
  draft.status = "discarded";
505
568
  draft.pending = null;
506
569
  await this.store.putMessage(draft);
@@ -511,9 +574,12 @@ export class Mail {
511
574
  /** Attaching does not change `version`: it never conflicts with text edits in flight. */
512
575
  attach(id, file, actor) {
513
576
  return this.write(async () => {
514
- const draft = await this.requireDraft(id, actor.scope);
577
+ const draft = await this.requireDraft(id, actor);
515
578
  if (draft.pending)
516
579
  throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
580
+ if (draft.attachments.length && this.provider(draft.provider).kind === "chat") {
581
+ throw new InvalidRequestError(`Draft ${id} is a chat message: it carries one attachment`);
582
+ }
517
583
  const meta = {
518
584
  id: nid(),
519
585
  filename: file.filename,
@@ -531,7 +597,7 @@ export class Mail {
531
597
  }
532
598
  detach(id, attachmentId, actor) {
533
599
  return this.write(async () => {
534
- const draft = await this.requireDraft(id, actor.scope);
600
+ const draft = await this.requireDraft(id, actor);
535
601
  if (draft.pending)
536
602
  throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
537
603
  const index = draft.attachments.findIndex(a => a.id === attachmentId);
@@ -547,7 +613,7 @@ export class Mail {
547
613
  /** Starts the undo window for a send or discard. Calling it again keeps the first one. */
548
614
  schedule(id, action, actor) {
549
615
  return this.write(async () => {
550
- const draft = await this.requireDraft(id, actor.scope);
616
+ const draft = await this.requireDraft(id, actor);
551
617
  if (!draft.pending) {
552
618
  draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
553
619
  await this.store.putMessage(draft);
@@ -559,7 +625,7 @@ export class Mail {
559
625
  }
560
626
  undo(id, actor) {
561
627
  return this.write(async () => {
562
- const draft = await this.requireDraft(id, actor.scope);
628
+ const draft = await this.requireDraft(id, actor);
563
629
  clearTimeout(this.timers.get(id));
564
630
  this.timers.delete(id);
565
631
  if (draft.pending) {
@@ -612,35 +678,41 @@ export class Mail {
612
678
  return this.write(() => this.sendDraftUnlocked(id, actor));
613
679
  }
614
680
  /**
615
- * The draft id is the idempotency key and the Message-ID is stored before the provider call,
616
- * so retrying a failed send repeats the same request instead of sending twice.
681
+ * The draft id is the idempotency key and a mail's Message-ID is stored before the provider call,
682
+ * so retrying a failed send repeats the same request instead of sending twice. A chat message
683
+ * goes out as written: no headers, HTML or signature.
617
684
  */
618
685
  async sendDraftUnlocked(id, actor) {
619
- const draft = await this.requireDraft(id, actor.scope);
686
+ const draft = await this.requireDraft(id, actor);
687
+ const provider = this.provider(draft.provider);
688
+ const chat = provider.kind === "chat";
620
689
  const sender = this.sendingMailbox(draft.mailbox, draft.from);
621
- if (!draft.message_id) {
622
- draft.message_id = `<${randomUUID()}@${domainOf(sender.address)}>`;
623
- await this.store.putMessage(draft);
690
+ const headers = {};
691
+ if (!chat) {
692
+ if (!draft.message_id) {
693
+ draft.message_id = `<${randomUUID()}@${domainOf(sender.address)}>`;
694
+ await this.store.putMessage(draft);
695
+ }
696
+ headers["Message-ID"] = draft.message_id;
697
+ if (draft.in_reply_to)
698
+ headers["In-Reply-To"] = draft.in_reply_to;
699
+ if (draft.references.length)
700
+ headers["References"] = draft.references.join(" ");
624
701
  }
625
- const headers = { "Message-ID": draft.message_id };
626
- if (draft.in_reply_to)
627
- headers["In-Reply-To"] = draft.in_reply_to;
628
- if (draft.references.length)
629
- headers["References"] = draft.references.join(" ");
630
702
  const attachments = await Promise.all(draft.attachments.map(async (a) => ({
631
703
  filename: a.filename,
632
704
  contentType: a.content_type,
633
705
  content: await this.attachmentBody(draft, a),
634
706
  })));
635
- const { providerId } = await this.provider.send({
707
+ const { providerId } = await provider.send({
636
708
  from: draft.from,
637
709
  to: draft.to,
638
710
  cc: draft.cc,
639
711
  bcc: draft.bcc,
640
712
  replyTo: draft.reply_to,
641
713
  subject: draft.subject,
642
- text: sender.signatureText ? `${draft.text}\n\n${sender.signatureText}` : draft.text,
643
- html: (draft.html ?? textToHtml(draft.text)) + (sender.signatureHtml ? `\n${sender.signatureHtml}` : ""),
714
+ text: !chat && sender.signatureText ? `${draft.text}\n\n${sender.signatureText}` : draft.text,
715
+ html: chat ? null : (draft.html ?? textToHtml(draft.text)) + (sender.signatureHtml ? `\n${sender.signatureHtml}` : ""),
644
716
  headers,
645
717
  attachments,
646
718
  }, draft.id);
@@ -650,8 +722,9 @@ export class Mail {
650
722
  draft.sent_at = new Date().toISOString();
651
723
  draft.headers = headers;
652
724
  await this.store.putMessage(draft);
653
- await this.store.indexProviderId(this.provider.name, providerId, draft.id);
654
- await this.store.indexMessageId(draft.message_id, draft.id);
725
+ await this.store.indexProviderId(provider.name, providerId, draft.id);
726
+ if (draft.message_id)
727
+ await this.store.indexMessageId(draft.message_id, draft.id);
655
728
  await this.store.setDraft(draft.id, false);
656
729
  await refreshThread(this.store, draft.thread_id);
657
730
  await this.store.audit("send", actor, draft.id, { provider_id: providerId });
@@ -667,7 +740,7 @@ export class Mail {
667
740
  reply(messageId, text, replyAll, actor) {
668
741
  return this.send({ replyToId: messageId, replyAll, text }, actor);
669
742
  }
670
- /** An inbound attachment's metadata and bytes, from disk or, the first time, from the provider. */
743
+ /** An attachment's metadata and bytes, from disk or, the first time for a message the provider holds, from the provider. */
671
744
  async getAttachment(messageId, attachmentId, scope) {
672
745
  const message = await this.requireMessage(messageId, scope);
673
746
  const meta = message.attachments.find(a => a.id === attachmentId);
@@ -679,9 +752,9 @@ export class Mail {
679
752
  const stored = await this.files.read(message.id, meta.id);
680
753
  if (stored)
681
754
  return stored;
682
- if (!message.provider_id || message.direction !== "in")
755
+ if (!message.provider_id || message.created_by)
683
756
  throw new NotFoundError(`Attachment ${meta.id} not found`);
684
- const body = await this.provider.getAttachment(message.provider_id, meta.id);
757
+ const body = await this.provider(message.provider).getAttachment(message.provider_id, meta.id);
685
758
  await this.files.write(message.id, meta.id, body);
686
759
  return body;
687
760
  }
@@ -12,5 +12,11 @@ export declare class Sync {
12
12
  start(): void;
13
13
  stop(): Promise<void>;
14
14
  run(): Promise<void>;
15
+ /** Providers sync one after another; one that fails does not hold back the rest. */
15
16
  private runOnce;
17
+ /**
18
+ * A chat mailbox mirrors conversations that began before Inboxer was attached to the line,
19
+ * so its first run reads the whole history.
20
+ */
21
+ private syncProvider;
16
22
  }
package/dist/core/sync.js CHANGED
@@ -29,16 +29,31 @@ export class Sync {
29
29
  });
30
30
  return this.running;
31
31
  }
32
+ /** Providers sync one after another; one that fails does not hold back the rest. */
32
33
  async runOnce() {
34
+ const failures = [];
35
+ for (const provider of Object.values(this.mail.providers)) {
36
+ await this.syncProvider(provider).catch(err => failures.push(err));
37
+ }
38
+ if (failures.length)
39
+ throw failures.length === 1 ? failures[0] : new AggregateError(failures, "several providers failed to sync");
40
+ }
41
+ /**
42
+ * A chat mailbox mirrors conversations that began before Inboxer was attached to the line,
43
+ * so its first run reads the whole history.
44
+ */
45
+ async syncProvider(provider) {
33
46
  const startedAt = new Date();
34
- const cursor = await this.mail.store.getSyncCursor();
35
- const since = new Date((cursor ? new Date(cursor).getTime() : startedAt.getTime()) - this.intervalMs);
36
- for await (const providerId of this.mail.provider.listInbound(since)) {
37
- await this.mail.ingest(providerId);
47
+ const cursor = await this.mail.store.getSyncCursor(provider.name);
48
+ const since = cursor
49
+ ? new Date(new Date(cursor).getTime() - this.intervalMs)
50
+ : provider.kind === "chat" ? new Date(0) : new Date(startedAt.getTime() - this.intervalMs);
51
+ for await (const event of provider.listMessages(since)) {
52
+ await this.mail.applyEvent(provider.name, event);
38
53
  }
39
- for await (const { providerId, status } of this.mail.provider.listOutbound(since)) {
40
- await this.mail.applyStatus(providerId, status, null);
54
+ for await (const { providerId, status } of provider.listOutbound(since)) {
55
+ await this.mail.applyStatus(provider.name, providerId, status, null);
41
56
  }
42
- await this.mail.store.setSyncCursor(startedAt.toISOString());
57
+ await this.mail.store.setSyncCursor(provider.name, startedAt.toISOString());
43
58
  }
44
59
  }
@@ -16,6 +16,8 @@ export interface ThreadLookup {
16
16
  * 3. A new thread.
17
17
  */
18
18
  export declare function resolveThreadId(store: Store, lookup: ThreadLookup, isOwn: (address: string) => boolean, windowDays: number): Promise<string>;
19
+ /** A chat mailbox keeps one thread per counterpart. */
20
+ export declare function chatThreadId(store: Store, mailbox: string, counterpart: string): Promise<string>;
19
21
  export declare function threadMessages(store: Store, thread: Thread): Promise<Message[]>;
20
22
  /** Recomputes the thread summary, adding `newMessageId` when given. A thread left with only discarded drafts is removed. */
21
23
  export declare function refreshThread(store: Store, threadId: string, newMessageId?: string): Promise<Thread | null>;
@@ -1,5 +1,5 @@
1
1
  import { nid } from "../store.js";
2
- import { bareAddress } from "./address.js";
2
+ import { bareAddress, nameOf } from "./address.js";
3
3
  import { normalizeSubject } from "./text.js";
4
4
  const DAY_MS = 24 * 60 * 60 * 1000;
5
5
  export function messageTime(message) {
@@ -35,6 +35,11 @@ export async function resolveThreadId(store, lookup, isOwn, windowDays) {
35
35
  }
36
36
  return nid();
37
37
  }
38
+ /** A chat mailbox keeps one thread per counterpart. */
39
+ export async function chatThreadId(store, mailbox, counterpart) {
40
+ const thread = (await store.allThreads()).find(t => t.mailbox === mailbox && t.participants.includes(counterpart));
41
+ return thread?.id ?? nid();
42
+ }
38
43
  export async function threadMessages(store, thread) {
39
44
  const messages = await Promise.all(thread.message_ids.map(id => store.requireMessage(id)));
40
45
  return messages.filter(m => m.status !== "discarded").sort((a, b) => messageTime(a).localeCompare(messageTime(b)));
@@ -49,6 +54,7 @@ export async function refreshThread(store, threadId, newMessageId) {
49
54
  subject: "",
50
55
  norm_subject: "",
51
56
  participants: [],
57
+ names: {},
52
58
  last_at: "",
53
59
  last_direction: "in",
54
60
  has_draft: false,
@@ -69,6 +75,11 @@ export async function refreshThread(store, threadId, newMessageId) {
69
75
  thread.subject = first.subject;
70
76
  thread.norm_subject = normalizeSubject(first.subject);
71
77
  thread.participants = [...new Set(messages.flatMap(participantsOf))];
78
+ for (const m of messages) {
79
+ const name = m.direction === "in" ? nameOf(m.from) : null;
80
+ if (name)
81
+ thread.names[bareAddress(m.from)] = name;
82
+ }
72
83
  thread.last_at = messageTime(last);
73
84
  thread.last_direction = last.direction;
74
85
  thread.has_draft = messages.some(m => m.status === "draft");
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import type { MailProvider } from "./provider/types.ts";
3
3
  import type { InboxerConfig } from "./types.ts";
4
4
  export interface InboxerOptions {
5
- /** A provider instance to use instead of resolving `cfg.provider.type`. */
6
- provider?: MailProvider;
5
+ /** Provider instances by name, to use instead of resolving `cfg.providers`. */
6
+ providers?: Record<string, MailProvider>;
7
7
  }
8
8
  export interface Inboxer {
9
9
  /** Web-standard handler for `Bun.serve`, Hono, Deno or any fetch-based server. */
@@ -31,5 +31,5 @@ export declare function createLoginLink(cfg: InboxerConfig, options?: LoginLinkO
31
31
  expires_at: string;
32
32
  }>;
33
33
  export { WebhookSignatureError } from "./provider/types.ts";
34
- export type { DeliveryStatus, InboundMessage, MailProvider, OutboundAttachment, OutboundMessage, OutboundStatus, ProviderEvent, WebhookRequest, } from "./provider/types.ts";
34
+ export type { DeliveryStatus, MailProvider, MessageEvent, OutboundAttachment, OutboundMessage, OutboundStatus, ProviderEvent, ProviderKind, ProviderMessage, WebhookRequest, } from "./provider/types.ts";
35
35
  export type { InboxerConfig, MailboxConfig, ProviderConfig } from "./types.ts";
package/dist/index.js CHANGED
@@ -4,13 +4,13 @@ import { Access } from "./auth.js";
4
4
  import { assertConfig } from "./config.js";
5
5
  import { Mail } from "./core/mail.js";
6
6
  import { Sync } from "./core/sync.js";
7
- import { resolveProvider } from "./provider/index.js";
7
+ import { resolveProviders } from "./provider/index.js";
8
8
  import { Store } from "./store.js";
9
9
  export function createInboxer(cfg, options = {}) {
10
- assertConfig(cfg, { requireProvider: !options.provider });
11
- const provider = options.provider ?? resolveProvider(cfg.provider);
10
+ assertConfig(cfg, options.providers && Object.keys(options.providers));
11
+ const providers = options.providers ?? resolveProviders(cfg.providers);
12
12
  const store = new Store(cfg.dataDir);
13
- const mail = new Mail(store, provider, cfg);
13
+ const mail = new Mail(store, providers, cfg);
14
14
  const access = new Access(store, cfg);
15
15
  const sync = new Sync(mail, cfg.syncIntervalMin);
16
16
  const ready = (async () => {
@@ -38,7 +38,7 @@ export function createInboxer(cfg, options = {}) {
38
38
  * Opens the database, stores the link and closes it; the session it creates reaches every mailbox.
39
39
  */
40
40
  export async function createLoginLink(cfg, options = {}) {
41
- assertConfig(cfg, { requireProvider: false });
41
+ assertConfig(cfg);
42
42
  const store = new Store(cfg.dataDir);
43
43
  await store.connect();
44
44
  try {