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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Your own mail layer for agents. Inboxer stores every email that comes in or goes out, gives agents an MCP server to read, draft and send, and gives you a small web UI to review drafts from your phone before they leave.
4
4
 
5
- Inboxer has no business rules. It does not decide what to answer or when. Each consumer, such as a scheduled agent, a support bot or you in a chat, brings its own rules in its prompt and uses the same tools. Sending goes through a **provider**. Inboxer ships with [Resend](https://resend.com), and the provider interface lets you plug in another service without touching the rest.
5
+ Inboxer has no business rules. It does not decide what to answer or when. Each consumer, such as a scheduled agent, a support bot or you in a chat, brings its own rules in its prompt and uses the same tools. Sending goes through a **provider**. Inboxer ships with [Resend](https://resend.com) for mail and [Kapso](https://kapso.ai) for WhatsApp, and the provider interface lets you plug in another service without touching the rest.
6
6
 
7
7
  - **One process, one SQLite file.** Persistence uses [DeepBase](https://github.com/clasen/DeepBase) on the runtime's built-in `node:sqlite`, so there is nothing to compile and no external database.
8
8
  - **Webhooks plus a backup sync.** Inbound mail and delivery events arrive by webhook. A periodic sync picks up anything a webhook missed.
@@ -46,17 +46,17 @@ const config = {
46
46
  syncIntervalMin: 10,
47
47
  threadWindowDays: 30,
48
48
  mailboxes: {
49
- support: { address: "support@example.com", name: "Example Support",
49
+ support: { address: "support@example.com", name: "Example Support", provider: "resend",
50
50
  signatureText: "-- Example Support", signatureHtml: "<p>-- Example Support</p>" },
51
- feedback: { address: "feedback@example.com", name: "Example" }
51
+ feedback: { address: "feedback@example.com", name: "Example", provider: "resend" }
52
52
  },
53
- provider: { type: "resend", apiKey: "re_...", webhookSecret: "whsec_..." },
53
+ providers: { resend: { type: "resend", apiKey: "re_...", webhookSecret: "whsec_..." } },
54
54
  mcp: { tokens: { "support-schedule": "...", "laptop": "..." }, maxAttachmentMb: 10 },
55
55
  ui: { cookieSecret: "...", loginLinkTtlMin: 10, undoSec: 10, maxUploadMb: 20 }
56
56
  };
57
57
  ```
58
58
 
59
- Load it from wherever your project keeps configuration: a JSON file, environment variables, a secrets manager. `provider.apiKey`, `provider.webhookSecret`, the MCP tokens and `ui.cookieSecret` are secrets, so keep them out of Git. [Configre](https://github.com/clasen/Configre) is one way to do that: it merges a public file and an encrypted secret file into one object.
59
+ Load it from wherever your project keeps configuration: a JSON file, environment variables, a secrets manager. The providers' keys and webhook secrets, the MCP tokens and `ui.cookieSecret` are secrets, so keep them out of Git. [Configre](https://github.com/clasen/Configre) is one way to do that: it merges a public file and an encrypted secret file into one object.
60
60
 
61
61
  Generate each token and the cookie secret with:
62
62
 
@@ -106,7 +106,7 @@ Everything lives under one origin:
106
106
 
107
107
  The function is synchronous, so a host that needs a synchronous factory can call it directly. Requests wait for `ready` before they are handled.
108
108
 
109
- `options.provider` takes a provider instance instead of resolving `cfg.provider.type`. See [Providers](#providers).
109
+ `options.providers` takes provider instances by name instead of resolving `cfg.providers`. See [Providers](#providers).
110
110
 
111
111
  `createLoginLink(cfg, { label?, threadId? })` mints a one-time login link from a script on the server. See [Signing in](#signing-in).
112
112
 
@@ -134,10 +134,10 @@ With roster's default isolation the site runs in its own process, so the databas
134
134
  | --- | --- |
135
135
  | `publicUrl` | Base URL used in login links |
136
136
  | `dataDir` | Absolute directory for `inboxer.db` and the `attachments/` folder |
137
- | `syncIntervalMin` | Minutes between backup syncs with the provider |
137
+ | `syncIntervalMin` | Minutes between backup syncs with each provider |
138
138
  | `threadWindowDays` | How far back a subject match may join an existing thread |
139
- | `mailboxes.<id>` | `address`, `name`, optional `signatureText` and `signatureHtml` |
140
- | `provider` | `type` plus the provider's own options, such as Resend's `apiKey` and `webhookSecret` |
139
+ | `mailboxes.<id>` | `address`, `name`, `provider` (a key of `providers`), optional `signatureText`, `signatureHtml` and `uiReadOnly` |
140
+ | `providers.<name>` | `type` plus the provider's own options, such as Resend's `apiKey` and `webhookSecret`. The name is the webhook route and is stored on every message, so keep it once there is data |
141
141
  | `mcp.tokens.<name>` | Bearer tokens for MCP that reach every mailbox; the name is recorded as the actor in the audit log |
142
142
  | `mailboxes.<id>.tokens.<name>` | Bearer tokens that reach only that mailbox |
143
143
  | `mcp.maxAttachmentMb` | Largest attachment `get_attachment` returns as content |
@@ -148,33 +148,38 @@ With roster's default isolation the site runs in its own process, so the databas
148
148
 
149
149
  `mailboxes` is an object keyed by id rather than an array, so a per-environment override can replace one mailbox without repeating the others. Mail sent to an address that matches no mailbox lands in the reserved `catchall` mailbox, grouped by that address. Replies go out from the address that was written to, with the name and signature of a mailbox on the same domain; the catch-all cannot start new mail.
150
150
 
151
+ `uiReadOnly: true` makes a mailbox an audit view: browser sessions read, label, archive and annotate, but cannot draft or send in it. MCP tokens are not affected.
152
+
151
153
  ## Providers
152
154
 
153
- A provider adapts one email service to the `MailProvider` interface. Nothing outside the provider knows which service is in use: messages store the provider's name and id, and the webhook route is `/webhooks/<name>`.
155
+ A provider adapts one messaging service to the `MailProvider` interface. Nothing outside the provider knows which service is in use: messages store the provider's name and id, and the webhook route is `/webhooks/<name>`. One instance can run several providers; each mailbox names the one it uses.
156
+
157
+ A provider is of one of two kinds. A `mail` provider has subjects, several recipients, HTML and threading by headers. A `chat` provider serves one mailbox, a phone line: addresses are phone numbers (`+5491155550000`), a thread is the whole conversation with one number, and a message is plain text with at most one attachment.
154
158
 
155
159
  ```typescript
156
160
  interface MailProvider {
157
- readonly name: string;
161
+ readonly name: string; // its key in `providers`
162
+ readonly kind: "mail" | "chat";
158
163
  parseWebhook(req: { headers: Headers; body: string }): ProviderEvent[]; // throws WebhookSignatureError
159
- getInbound(providerId: string): Promise<InboundMessage>;
160
- listInbound(since: Date): AsyncIterable<string>;
164
+ getMessage(providerId: string): Promise<ProviderMessage>;
165
+ listMessages(since: Date): AsyncIterable<MessageEvent>;
161
166
  listOutbound(since: Date): AsyncIterable<{ providerId: string; status: DeliveryStatus }>;
162
167
  send(message: OutboundMessage, idempotencyKey: string): Promise<{ providerId: string }>;
163
168
  getAttachment(providerMessageId: string, attachmentId: string): Promise<Uint8Array>;
164
169
  }
165
170
 
166
171
  type ProviderEvent =
167
- | { type: "received"; providerId: string }
172
+ | { type: "message"; providerId: string; message?: ProviderMessage } // MessageEvent
168
173
  | { type: "status"; providerId: string; status: DeliveryStatus; messageId: string | null };
169
174
 
170
- type DeliveryStatus = "sent" | "delivered" | "bounced" | "failed";
175
+ type DeliveryStatus = "sent" | "delivered" | "read" | "bounced" | "failed";
171
176
  ```
172
177
 
173
- `OutboundMessage.attachments` carries the draft's files as `{ filename, contentType, content }`. `InboundMessage.attachments` lists `{ id, filename, content_type, size, inline, content_id }`; `inline` marks an image embedded in the body by `cid:`. `send()` must not deliver twice for the same `idempotencyKey`. Inboxer uses the draft id, so retrying a failed send is safe. Pass your own implementation with `createInboxer(cfg, { provider })`. All the types above are exported from `inboxer`.
178
+ `OutboundMessage.attachments` carries the draft's files as `{ filename, contentType, content }`. `ProviderMessage.attachments` lists `{ id, filename, content_type, size, inline, content_id }`; `inline` marks an image embedded in the body by `cid:`. A `ProviderMessage` has a `direction`: `out` ones were sent on the account by anyone, and Inboxer stores those it did not send itself, so a thread shows the whole conversation. A message event may carry the message; without it Inboxer calls `getMessage`. `send()` must not deliver twice for the same `idempotencyKey`. Inboxer uses the draft id, so retrying a failed send is safe. Pass your own implementations with `createInboxer(cfg, { providers: { <name>: instance } })`. All the types above are exported from `inboxer`.
174
179
 
175
180
  ### Resend
176
181
 
177
- `provider: { type: "resend", apiKey, webhookSecret }`.
182
+ `providers: { resend: { type: "resend", apiKey, webhookSecret } }`.
178
183
 
179
184
  Resend handles sending and receiving. Inboxer talks to it in three ways:
180
185
 
@@ -202,15 +207,29 @@ The app's host name does not have to match the addresses. A name like `inboxer.`
202
207
  4. **MX — receiving.** Name `@` (the domain itself), value `inbound-smtp.us-east-1.amazonaws.com`, priority `10`. From then on every address of the domain is delivered to Resend and no longer to your previous mail host or forwarding rules; mail to addresses you did not configure lands in Inboxer's `catchall` mailbox. To keep the root domain on another host, put Inboxer's addresses on a subdomain such as `help.example.com` and add this MX there.
203
208
 
204
209
  Wait until Resend shows the domain as verified. That usually takes minutes, sometimes hours while DNS propagates.
205
- 5. **Create an API key.** In *API Keys*, create a key with full access: Inboxer reads received and sent emails, not just sends. Put it in `provider.apiKey`.
210
+ 5. **Create an API key.** In *API Keys*, create a key with full access: Inboxer reads received and sent emails, not just sends. Put it in the provider's `apiKey`.
206
211
  6. **Deploy Inboxer.** Point `inboxer.example.com` at your server, serve it over HTTPS (roster-server issues certificates on its own; otherwise use your reverse proxy), and set `publicUrl` to that URL. The webhook and login links depend on it.
207
- 7. **Create the webhook.** In *Webhooks*, add an endpoint at `https://inboxer.example.com/webhooks/resend` with the `email.received`, `email.sent`, `email.delivered`, `email.bounced`, `email.failed` and `email.suppressed` events. Copy its signing secret into `provider.webhookSecret`.
212
+ 7. **Create the webhook.** In *Webhooks*, add an endpoint at `https://inboxer.example.com/webhooks/resend` with the `email.received`, `email.sent`, `email.delivered`, `email.bounced`, `email.failed` and `email.suppressed` events. Copy its signing secret into the provider's `webhookSecret`.
208
213
  8. **Restart and test.** Restart Inboxer so it loads the secrets. Send an email from an outside account to `support@example.com`. Within seconds it should appear in the UI's Inbox and in `list_threads`. Resend's webhook page shows each delivery and Inboxer's response; a `401` means the signing secret is wrong.
209
214
 
210
215
  Inbound webhooks carry no body, so Inboxer fetches each message from the receiving API. The webhook answers `500` when processing fails, so Resend retries; processing is idempotent by Resend id.
211
216
 
212
217
  Inboxer sets its own `Message-ID` (`<uuid@your-domain>`) on outgoing mail. If the provider reports a different one in a delivery event, Inboxer adopts it, so replies still find the thread. When neither header matches, the subject-and-participant rule keeps the conversation together.
213
218
 
219
+ ### Kapso (WhatsApp)
220
+
221
+ ```javascript
222
+ mailboxes: { whatsapp: { address: "+12025550100", name: "Example", provider: "whatsapp" } },
223
+ providers: { whatsapp: { type: "kapso", apiKey, webhookSecret, phoneNumberId } }
224
+ ```
225
+
226
+ A WhatsApp number becomes a mailbox whose contacts are phone numbers. Inboxer mirrors the line: what people write, and what anyone sends on it, such as a bot that talks to Kapso directly. Buttons, links and templates show as Kapso describes them in text; images, documents and voice notes are attachments, a voice note with its transcript.
227
+
228
+ 1. In Kapso, add a webhook of kind `kapso` on the phone number, pointing at `<publicUrl>/webhooks/<name>` (here `/webhooks/whatsapp`), with the events `whatsapp.message.received`, `whatsapp.message.sent`, `whatsapp.message.delivered`, `whatsapp.message.read` and `whatsapp.message.failed`. A number takes several webhooks, so one that already feeds a bot stays as it is. Its secret is `webhookSecret`.
229
+ 2. `apiKey` is a Kapso API key and `phoneNumberId` the number's id.
230
+
231
+ The first sync reads the line's whole history, so conversations that began before Inboxer was attached are there. A reply is plain text, or one file with the text as its caption. WhatsApp only delivers free text within 24 hours of the person's last message; after that the send fails and the message shows as `failed`. Templates and starting a chat from the review UI are not supported. The Cloud API takes no idempotency key, so a send whose response was lost can repeat on retry.
232
+
214
233
  ## MCP
215
234
 
216
235
  The MCP server is at `<publicUrl>/mcp`. It speaks Streamable HTTP without sessions, and every request carries `Authorization: Bearer <token>`.
@@ -359,10 +378,11 @@ DeepBase is a nested key-value store without secondary indexes, so Inboxer maint
359
378
  | `msgid/<sha1(Message-ID)>` | Message lookup for threading |
360
379
  | `ext/<provider>/<sha1(provider id)>` | Idempotent ingest and delivery updates |
361
380
  | `contacts/<sha1(address)>` · `thread_context/<id>` | Context set through MCP |
381
+ | `sync_cursor/<provider>` | When each provider's last sync started |
362
382
  | `audit/<id>` | Sends, edits, discards, labels, context changes, login links and session changes, with the actor |
363
383
  | `login_links/<sha256>` · `sessions/<sha256>` | UI access |
364
384
 
365
- Inbound attachments are copied to `<dataDir>/attachments/<message id>/` when the message arrives, so they outlive the provider's retention. One that fails to download is fetched again the first time it is opened.
385
+ Attachments of messages the provider holds are copied to `<dataDir>/attachments/<message id>/` when the message arrives, so they outlive the provider's retention. One that fails to download is fetched again the first time it is opened.
366
386
 
367
387
  Search scans messages in memory. That is enough for support volumes; a dedicated full-text index can be added later without changing the tools.
368
388
 
package/dist/app.js CHANGED
@@ -30,11 +30,12 @@ export function buildApp(mail, access, cfg, ready) {
30
30
  });
31
31
  // A failure answers 500 so the provider retries; ingest is idempotent.
32
32
  app.post("/webhooks/:provider", async (c) => {
33
- if (c.req.param("provider") !== mail.provider.name)
33
+ const name = c.req.param("provider");
34
+ if (!Object.hasOwn(mail.providers, name))
34
35
  return c.notFound();
35
36
  let events;
36
37
  try {
37
- events = mail.provider.parseWebhook({ headers: c.req.raw.headers, body: await c.req.text() });
38
+ events = mail.providers[name].parseWebhook({ headers: c.req.raw.headers, body: await c.req.text() });
38
39
  }
39
40
  catch (err) {
40
41
  if (err instanceof WebhookSignatureError)
@@ -42,7 +43,7 @@ export function buildApp(mail, access, cfg, ready) {
42
43
  throw err;
43
44
  }
44
45
  for (const event of events)
45
- await mail.applyEvent(event);
46
+ await mail.applyEvent(name, event);
46
47
  return c.json({ ok: true });
47
48
  });
48
49
  app.all("/mcp", async (c) => {
package/dist/config.d.ts CHANGED
@@ -3,10 +3,8 @@ import { type InboxerConfig, type Scope } from "./types.ts";
3
3
  export declare function appUrl(cfg: Pick<InboxerConfig, "publicUrl">, path: string): string;
4
4
  /** UI path of a thread, scrolled to one of its drafts when given. */
5
5
  export declare function threadPath(threadId: string, draftId?: string): string;
6
- /** Asserts the shape `createInboxer` relies on. */
7
- export declare function assertConfig(cfg: InboxerConfig, { requireProvider }: {
8
- requireProvider: boolean;
9
- }): void;
6
+ /** Asserts the shape `createInboxer` relies on. `injectedProviders` names provider instances passed in place of `cfg.providers`. */
7
+ export declare function assertConfig(cfg: InboxerConfig, injectedProviders?: string[]): void;
10
8
  export interface McpToken {
11
9
  name: string;
12
10
  token: string;
package/dist/config.js CHANGED
@@ -19,14 +19,21 @@ function requirePositive(value, path) {
19
19
  if (typeof value !== "number" || !(value > 0))
20
20
  fail(path, "a positive number");
21
21
  }
22
- /** Asserts the shape `createInboxer` relies on. */
23
- export function assertConfig(cfg, { requireProvider }) {
22
+ /** Asserts the shape `createInboxer` relies on. `injectedProviders` names provider instances passed in place of `cfg.providers`. */
23
+ export function assertConfig(cfg, injectedProviders) {
24
24
  requireString(cfg.publicUrl, "publicUrl");
25
25
  requireString(cfg.dataDir, "dataDir");
26
26
  if (!isAbsolute(cfg.dataDir))
27
27
  fail("dataDir", "an absolute path");
28
28
  requirePositive(cfg.syncIntervalMin, "syncIntervalMin");
29
29
  requirePositive(cfg.threadWindowDays, "threadWindowDays");
30
+ if (!injectedProviders) {
31
+ if (!cfg.providers || typeof cfg.providers !== "object")
32
+ fail("providers", "an object keyed by provider name");
33
+ for (const [name, provider] of Object.entries(cfg.providers))
34
+ requireString(provider?.type, `providers.${name}.type`);
35
+ }
36
+ const providers = injectedProviders ?? Object.keys(cfg.providers);
30
37
  if (!cfg.mailboxes || typeof cfg.mailboxes !== "object")
31
38
  fail("mailboxes", "an object keyed by mailbox id");
32
39
  if (CATCHALL in cfg.mailboxes)
@@ -34,11 +41,13 @@ export function assertConfig(cfg, { requireProvider }) {
34
41
  for (const [id, mailbox] of Object.entries(cfg.mailboxes)) {
35
42
  requireString(mailbox.address, `mailboxes.${id}.address`);
36
43
  requireString(mailbox.name, `mailboxes.${id}.name`);
44
+ if (!providers.includes(mailbox.provider))
45
+ fail(`mailboxes.${id}.provider`, `one of: ${providers.join(", ")}`);
46
+ if (mailbox.uiReadOnly !== undefined && mailbox.uiReadOnly !== true)
47
+ fail(`mailboxes.${id}.uiReadOnly`, "true or absent");
37
48
  if (mailbox.tokens !== undefined && (!mailbox.tokens || typeof mailbox.tokens !== "object"))
38
49
  fail(`mailboxes.${id}.tokens`, "an object of named tokens");
39
50
  }
40
- if (requireProvider)
41
- requireString(cfg.provider?.type, "provider.type");
42
51
  if (!cfg.mcp?.tokens || typeof cfg.mcp.tokens !== "object")
43
52
  fail("mcp.tokens", "an object of named tokens");
44
53
  for (const [name, token] of Object.entries(cfg.mcp.tokens))
@@ -1,5 +1,9 @@
1
- /** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. */
1
+ /** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. A chat address is a phone number: `+5491155550000`. */
2
2
  export declare function bareAddress(value: string): string;
3
+ /** Display name from `Name <address>`, or null when there is none. */
4
+ export declare function nameOf(value: string): string | null;
5
+ /** The E.164 address of a phone number written with or without the plus, spaces or dashes; null when it is not one. */
6
+ export declare function phoneAddress(value: string): string | null;
3
7
  export declare function formatAddress(name: string, address: string): string;
4
8
  /** Splits a comma-separated recipient field, keeping commas inside quoted names. */
5
9
  export declare function splitAddresses(value: string): string[];
@@ -1,8 +1,18 @@
1
- /** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. */
1
+ /** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. A chat address is a phone number: `+5491155550000`. */
2
2
  export function bareAddress(value) {
3
3
  const match = /<([^<>]+)>\s*$/.exec(value);
4
4
  return (match ? match[1] : value).trim().toLowerCase();
5
5
  }
6
+ /** Display name from `Name <address>`, or null when there is none. */
7
+ export function nameOf(value) {
8
+ const match = /^\s*"?([^"<]+?)"?\s*</.exec(value);
9
+ return match ? match[1] : null;
10
+ }
11
+ /** The E.164 address of a phone number written with or without the plus, spaces or dashes; null when it is not one. */
12
+ export function phoneAddress(value) {
13
+ const digits = bareAddress(value).replace(/[\s().-]/g, "").replace(/^\+/, "");
14
+ return /^[1-9]\d{6,14}$/.test(digits) ? `+${digits}` : null;
15
+ }
6
16
  export function formatAddress(name, address) {
7
17
  return `"${name.replace(/["\\]/g, "\\$&")}" <${address}>`;
8
18
  }
@@ -1,4 +1,4 @@
1
- import type { DeliveryStatus, MailProvider, ProviderEvent } from "../provider/types.ts";
1
+ import type { DeliveryStatus, MailProvider, ProviderEvent, ProviderKind, ProviderMessage } from "../provider/types.ts";
2
2
  import { type Store } from "../store.ts";
3
3
  import { type Actor, type Contact, type Context, type AttachmentMeta, type InboxerConfig, type Message, type MetaValue, type PendingAction, type Scope, type Thread } from "../types.ts";
4
4
  import { type ContextPatch } from "./context.ts";
@@ -71,7 +71,7 @@ export interface MessageView {
71
71
  /** The mail domain: everything the MCP tools, the UI and the webhook do goes through here. */
72
72
  export declare class Mail {
73
73
  readonly store: Store;
74
- readonly provider: MailProvider;
74
+ readonly providers: Record<string, MailProvider>;
75
75
  readonly cfg: InboxerConfig;
76
76
  private readonly ownAddresses;
77
77
  private readonly domains;
@@ -79,15 +79,22 @@ export declare class Mail {
79
79
  private readonly files;
80
80
  /** Fires "change" after every write, so open pages can refresh. */
81
81
  readonly changes: EventTarget;
82
- constructor(store: Store, provider: MailProvider, cfg: InboxerConfig);
82
+ constructor(store: Store, providers: Record<string, MailProvider>, cfg: InboxerConfig);
83
83
  /** Runs `fn` in the store's write queue, then announces the change. */
84
84
  private write;
85
+ private provider;
86
+ /** The catch-all only collects mail. */
87
+ kindOf(mailbox: string): ProviderKind;
88
+ /** Whether the review UI may draft and send in `mailbox`. */
89
+ uiCanWrite(mailbox: string): boolean;
90
+ private assertCanWrite;
85
91
  listMailboxes(scope: Scope): {
86
92
  id: string;
87
93
  address: string;
88
94
  name: string;
95
+ kind: ProviderKind;
89
96
  }[];
90
- /** A configured mailbox address or any other address on its domains, such as one the catch-all received. */
97
+ /** A configured mailbox address or any other address on a mail domain, such as one the catch-all received. */
91
98
  isOwn(address: string): boolean;
92
99
  /** The first address on our domains that is not a configured mailbox: the one a catch-all message was written to. */
93
100
  private catchAllAddress;
@@ -101,18 +108,21 @@ export declare class Mail {
101
108
  requireThread(id: string, scope: Scope): Promise<Thread>;
102
109
  /** Scoped actors only reach contacts that take part in one of their threads. */
103
110
  private requireContactAccess;
111
+ /** A chat provider serves one mailbox; mail goes to the mailbox it is addressed to, else to the catch-all. */
104
112
  private mailboxFor;
105
113
  /** Who sends for `id`; the catch-all answers as `address`, with the name and signature of a mailbox on that domain. */
106
114
  private sendingMailbox;
107
115
  /**
108
- * Stores an inbound message once per provider id and returns its id. Attachments are copied to
109
- * disk right away; one that fails to download is fetched again the first time it is opened.
116
+ * Stores a message the provider holds once per provider id and returns its id: one received, or
117
+ * one sent on the account by someone else. A message already known only takes the delivery
118
+ * status that came with it. Attachments are copied to disk right away; one that fails to
119
+ * download is fetched again the first time it is opened.
110
120
  */
111
- ingest(providerId: string): Promise<string>;
112
- private storeInbound;
113
- applyEvent(event: ProviderEvent): Promise<void>;
121
+ ingest(providerName: string, providerId: string, given?: ProviderMessage): Promise<string>;
122
+ private storeMessage;
123
+ applyEvent(provider: string, event: ProviderEvent): Promise<void>;
114
124
  /** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
115
- applyStatus(providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void>;
125
+ applyStatus(provider: string, providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void>;
116
126
  /** Matches a thread by its own context or by any participant's contact. */
117
127
  private metaFilter;
118
128
  listThreads(input: ListThreadsInput, scope: Scope): Promise<Thread[]>;
@@ -177,14 +187,15 @@ export declare class Mail {
177
187
  private runPending;
178
188
  sendDraft(id: string, actor: Actor): Promise<Message>;
179
189
  /**
180
- * The draft id is the idempotency key and the Message-ID is stored before the provider call,
181
- * so retrying a failed send repeats the same request instead of sending twice.
190
+ * The draft id is the idempotency key and a mail's Message-ID is stored before the provider call,
191
+ * so retrying a failed send repeats the same request instead of sending twice. A chat message
192
+ * goes out as written: no headers, HTML or signature.
182
193
  */
183
194
  private sendDraftUnlocked;
184
195
  /** Direct send. If the provider fails, the message stays as a pending draft. */
185
196
  send(input: CreateDraftInput, actor: Actor): Promise<Message>;
186
197
  reply(messageId: string, text: string, replyAll: boolean, actor: Actor): Promise<Message>;
187
- /** An inbound attachment's metadata and bytes, from disk or, the first time, from the provider. */
198
+ /** An attachment's metadata and bytes, from disk or, the first time for a message the provider holds, from the provider. */
188
199
  getAttachment(messageId: string, attachmentId: string, scope: Scope): Promise<{
189
200
  meta: AttachmentMeta;
190
201
  body: Uint8Array;