inboxer 0.4.12 → 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 (46) 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/views.d.ts +7 -5
  28. package/dist/ui/views.js +18 -16
  29. package/package.json +1 -1
  30. package/skills/inboxer/SKILL.md +15 -8
  31. package/src/app.ts +4 -3
  32. package/src/config.ts +10 -3
  33. package/src/core/address.ts +13 -1
  34. package/src/core/mail.ts +162 -89
  35. package/src/core/sync.ts +23 -7
  36. package/src/core/threads.ts +12 -1
  37. package/src/index.ts +10 -8
  38. package/src/mcp.ts +8 -8
  39. package/src/provider/index.ts +9 -5
  40. package/src/provider/kapso.ts +251 -0
  41. package/src/provider/resend.ts +15 -11
  42. package/src/provider/types.ts +38 -14
  43. package/src/store.ts +4 -4
  44. package/src/types.ts +10 -2
  45. package/src/ui/routes.ts +16 -11
  46. package/src/ui/views.ts +20 -17
package/dist/mcp.js CHANGED
@@ -42,7 +42,7 @@ function attachmentContent(cfg, messageId, meta, body) {
42
42
  const uri = appUrl(cfg, `/attachments/${encodeURIComponent(messageId)}/${encodeURIComponent(meta.id)}`);
43
43
  return { type: "resource", resource: { uri, mimeType: meta.content_type, blob: data } };
44
44
  }
45
- const addresses = z.array(z.string()).describe("Addresses, e.g. \"Ana <ana@example.com>\" or \"ana@example.com\"");
45
+ const addresses = z.array(z.string()).describe("Addresses, e.g. \"Ana <ana@example.com>\" or \"ana@example.com\"; in a chat mailbox, one phone number, e.g. \"+5491155550000\"");
46
46
  const isoDate = z.string().describe("ISO 8601 timestamp");
47
47
  const metaFilter = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
48
48
  .describe("Every pair must match the thread's context or a participant's contact; values compare as text");
@@ -52,7 +52,7 @@ const notePatch = z.string().nullable().describe("Replaces the note; null clears
52
52
  function buildServer(mail, access, actor) {
53
53
  const server = new McpServer({ name: "inboxer", version: VERSION });
54
54
  const cfg = mail.cfg;
55
- server.registerTool("list_mailboxes", { description: "Mailboxes this token reaches; tokens for every mailbox also see the catch-all for unknown recipients." }, wrap(cfg, async () => mail.listMailboxes(actor.scope)));
55
+ server.registerTool("list_mailboxes", { description: "Mailboxes this token reaches, each of kind mail or chat (a phone line, e.g. WhatsApp, where addresses are phone numbers and a thread is the whole conversation with one number); tokens for every mailbox also see the catch-all for unknown recipients." }, wrap(cfg, async () => mail.listMailboxes(actor.scope)));
56
56
  server.registerTool("list_threads", {
57
57
  description: "Threads, newest first. status: unanswered (last message inbound and no pending draft), all (not archived), archived.",
58
58
  inputSchema: {
@@ -84,11 +84,11 @@ function buildServer(mail, access, actor) {
84
84
  return { thread: threadView(cfg, thread), ...context, messages: messages.map(m => messageView(cfg, m)) };
85
85
  }));
86
86
  server.registerTool("get_contact", {
87
- description: "Context stored for an email address: meta (e.g. ids in other systems) and a note. null when there is none.",
87
+ description: "Context stored for an email address or phone number: meta (e.g. ids in other systems) and a note. null when there is none.",
88
88
  inputSchema: { address: z.string() },
89
89
  }, wrap(cfg, async ({ address }) => mail.getContact(address, actor.scope)));
90
90
  server.registerTool("set_contact", {
91
- description: "Attach context to an email address, e.g. meta { license_id: \"BL-2231\" } or a note. Merges with what is stored. Shown in get_thread and in the review UI, and searchable with meta filters.",
91
+ description: "Attach context to an email address or phone number, e.g. meta { license_id: \"BL-2231\" } or a note. Merges with what is stored. Shown in get_thread and in the review UI, and searchable with meta filters.",
92
92
  inputSchema: { address: z.string(), meta: metaPatch.optional(), note: notePatch.optional() },
93
93
  }, wrap(cfg, async ({ address, meta, note }) => mail.setContact(address, { meta, note }, actor)));
94
94
  server.registerTool("set_thread_meta", {
@@ -104,7 +104,7 @@ function buildServer(mail, access, actor) {
104
104
  inputSchema: { ids: z.array(z.string()), read: z.boolean().optional(), archived: z.boolean().optional() },
105
105
  }, wrap(cfg, async ({ ids, read, archived }) => ({ updated: await mail.mark(ids, { read, archived }, actor) })));
106
106
  server.registerTool("create_draft", {
107
- description: "Create a draft for a human to review. Pass reply_to_id to reply (recipients, subject and threading are derived), or mailbox + to + subject for a new conversation. note is shown to the reviewer. The result's url opens the draft in the review UI; share it with the user.",
107
+ description: "Create a draft for a human to review. Pass reply_to_id to reply (recipients, subject and threading are derived), or mailbox + to + subject for a new conversation (a chat mailbox takes one phone number and no subject, cc, bcc or html). note is shown to the reviewer. The result's url opens the draft in the review UI; share it with the user.",
108
108
  inputSchema: {
109
109
  mailbox: z.string().optional(),
110
110
  reply_to_id: z.string().optional().describe("Message id to reply to"),
@@ -143,13 +143,13 @@ function buildServer(mail, access, actor) {
143
143
  server.registerTool("discard_draft", { description: "Discard a pending draft.", inputSchema: { id: z.string() } }, wrap(cfg, async ({ id }) => { await mail.discardDraft(id, actor); return { discarded: id }; }));
144
144
  server.registerTool("send_draft", { description: "Send the last saved version of a draft.", inputSchema: { id: z.string() } }, wrap(cfg, async ({ id }) => messageView(cfg, toView(await mail.sendDraft(id, actor)))));
145
145
  server.registerTool("send", {
146
- description: "Send a new message directly, without review. Use only when your rules allow it.",
146
+ description: "Send a new message directly, without review. Use only when your rules allow it. subject is required in a mail mailbox; a chat mailbox takes one phone number and text only, and the message joins the conversation with that number.",
147
147
  inputSchema: {
148
148
  mailbox: z.string(),
149
149
  to: addresses,
150
150
  cc: addresses.optional(),
151
151
  bcc: addresses.optional(),
152
- subject: z.string(),
152
+ subject: z.string().optional(),
153
153
  text: z.string(),
154
154
  html: z.string().optional(),
155
155
  },
@@ -159,7 +159,7 @@ function buildServer(mail, access, actor) {
159
159
  inputSchema: { message_id: z.string().describe("Inboxer message id"), text: z.string(), reply_all: z.boolean().optional() },
160
160
  }, wrap(cfg, async ({ message_id, text, reply_all }) => messageView(cfg, toView(await mail.reply(message_id, text, reply_all ?? false, actor)))));
161
161
  server.registerTool("get_attachment", {
162
- description: "Content of an inbound attachment: images as images, text as text, anything else (e.g. PDF) as an embedded resource. Larger than the server's limit returns an error.",
162
+ description: "Content of an attachment: images as images, text as text, anything else (e.g. PDF) as an embedded resource. Larger than the server's limit returns an error.",
163
163
  inputSchema: { message_id: z.string(), attachment_id: z.string() },
164
164
  }, async ({ message_id, attachment_id }) => {
165
165
  try {
@@ -1,3 +1,4 @@
1
1
  import type { ProviderConfig } from "../types.ts";
2
2
  import type { MailProvider } from "./types.ts";
3
- export declare function resolveProvider(config: ProviderConfig): MailProvider;
3
+ /** One provider per entry of `providers`, named by its key. */
4
+ export declare function resolveProviders(configs: Record<string, ProviderConfig>): Record<string, MailProvider>;
@@ -1,11 +1,15 @@
1
+ import { createKapsoProvider } from "./kapso.js";
1
2
  import { createResendProvider } from "./resend.js";
2
3
  const PROVIDERS = {
3
4
  resend: createResendProvider,
5
+ kapso: createKapsoProvider,
4
6
  };
5
- export function resolveProvider(config) {
6
- const { type, ...options } = config;
7
- const factory = PROVIDERS[type];
8
- if (!factory)
9
- throw new Error(`Unknown provider type "${type}". Available: ${Object.keys(PROVIDERS).join(", ")}`);
10
- return factory(options);
7
+ /** One provider per entry of `providers`, named by its key. */
8
+ export function resolveProviders(configs) {
9
+ return Object.fromEntries(Object.entries(configs).map(([name, { type, ...options }]) => {
10
+ const factory = PROVIDERS[type];
11
+ if (!factory)
12
+ throw new Error(`Unknown provider type "${type}" in providers.${name}. Available: ${Object.keys(PROVIDERS).join(", ")}`);
13
+ return [name, factory(name, options)];
14
+ }));
11
15
  }
@@ -0,0 +1,8 @@
1
+ import { type MailProvider } from "./types.ts";
2
+ export interface KapsoProviderConfig {
3
+ apiKey: string;
4
+ webhookSecret: string;
5
+ phoneNumberId: string;
6
+ }
7
+ /** One WhatsApp number through Kapso's proxy of the WhatsApp Cloud API. */
8
+ export declare function createKapsoProvider(name: string, config: Record<string, unknown>): MailProvider;
@@ -0,0 +1,198 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { bareAddress, formatAddress, phoneAddress } from "../core/address.js";
3
+ import { WebhookSignatureError, } from "./types.js";
4
+ const PLATFORM_API = "https://api.kapso.ai/platform/v1/whatsapp";
5
+ const META_API = "https://api.kapso.ai/meta/whatsapp/v24.0";
6
+ const PAGE_LIMIT = 100;
7
+ const TEXT_LIMIT = 4096;
8
+ const CAPTION_LIMIT = 1024;
9
+ const MEDIA_TYPES = new Set(["image", "video", "audio", "document", "sticker"]);
10
+ const STATUS = { sent: "sent", delivered: "delivered", read: "read", failed: "failed" };
11
+ const WEBHOOK_STATUS = {
12
+ "whatsapp.message.delivered": "delivered",
13
+ "whatsapp.message.read": "read",
14
+ "whatsapp.message.failed": "failed",
15
+ };
16
+ /** One WhatsApp number through Kapso's proxy of the WhatsApp Cloud API. */
17
+ export function createKapsoProvider(name, config) {
18
+ const { apiKey, webhookSecret, phoneNumberId } = config;
19
+ for (const [key, value] of Object.entries({ apiKey, webhookSecret, phoneNumberId })) {
20
+ if (typeof value !== "string" || !value)
21
+ throw new Error(`providers.${name}.${key} is required for the kapso provider`);
22
+ }
23
+ async function request(method, url, body, headers = {}) {
24
+ const res = await fetch(url, { method, headers: { "X-API-Key": apiKey, "User-Agent": "inboxer", ...headers }, body });
25
+ if (!res.ok)
26
+ throw new Error(`Kapso ${method} ${url} failed: ${res.status} ${await res.text()}`);
27
+ return (await res.json());
28
+ }
29
+ async function upload(file) {
30
+ const form = new FormData();
31
+ form.set("messaging_product", "whatsapp");
32
+ form.set("file", new Blob([file.content], { type: file.contentType }), file.filename);
33
+ return (await request("POST", `${META_API}/${phoneNumberId}/media`, form)).id;
34
+ }
35
+ return {
36
+ name,
37
+ kind: "chat",
38
+ parseWebhook({ headers, body }) {
39
+ const expected = createHmac("sha256", webhookSecret).update(body).digest();
40
+ const given = Buffer.from(headers.get("x-webhook-signature") ?? "", "hex");
41
+ if (given.length !== expected.length || !timingSafeEqual(given, expected))
42
+ throw new WebhookSignatureError("Invalid Kapso webhook signature");
43
+ const event = headers.get("x-webhook-event") ?? "";
44
+ const payload = JSON.parse(body);
45
+ const items = "batch" in payload ? payload.data : [payload];
46
+ const events = [];
47
+ for (const item of items) {
48
+ if (item.phone_number_id !== phoneNumberId)
49
+ continue;
50
+ const status = WEBHOOK_STATUS[event];
51
+ if (status) {
52
+ events.push({ type: "status", providerId: item.message.id, status, messageId: null });
53
+ }
54
+ else if (event === "whatsapp.message.received" || event === "whatsapp.message.sent") {
55
+ const message = normalize(item.message, item.conversation);
56
+ if (message)
57
+ events.push({ type: "message", providerId: message.providerId, message });
58
+ }
59
+ }
60
+ return events;
61
+ },
62
+ async getMessage(providerId) {
63
+ const { data } = await request("GET", `${PLATFORM_API}/messages/${encodeURIComponent(providerId)}`);
64
+ const message = normalize(data);
65
+ if (!message)
66
+ throw new Error(`Kapso message ${providerId} has no phone number`);
67
+ return message;
68
+ },
69
+ /** The history is listed newest first, with no date filter. */
70
+ async *listMessages(since) {
71
+ let after = null;
72
+ while (true) {
73
+ const query = new URLSearchParams({ phone_number_id: phoneNumberId, limit: String(PAGE_LIMIT), ...(after ? { after } : {}) });
74
+ const page = await request("GET", `${PLATFORM_API}/messages?${query}`);
75
+ for (const item of page.data) {
76
+ if (timeOf(item) < since)
77
+ return;
78
+ const message = normalize(item);
79
+ if (message)
80
+ yield { type: "message", providerId: message.providerId, message };
81
+ }
82
+ after = page.paging?.cursors?.after ?? null;
83
+ if (!page.paging?.next || !after || page.data.length === 0)
84
+ return;
85
+ }
86
+ },
87
+ /** `listMessages` already carries the status of every outbound message. */
88
+ async *listOutbound() { },
89
+ /** The Cloud API takes no idempotency key: a send whose response was lost can repeat on retry. */
90
+ async send(message) {
91
+ const body = { messaging_product: "whatsapp", recipient_type: "individual", to: bareAddress(message.to[0]).slice(1) };
92
+ const [file] = message.attachments;
93
+ if (!file) {
94
+ if (message.text.length > TEXT_LIMIT)
95
+ throw new Error(`A WhatsApp text takes up to ${TEXT_LIMIT} characters`);
96
+ Object.assign(body, { type: "text", text: { body: message.text } });
97
+ }
98
+ else {
99
+ const type = mediaType(file.contentType);
100
+ if (message.text && type === "audio")
101
+ throw new Error("A WhatsApp audio message takes no text");
102
+ if (message.text.length > CAPTION_LIMIT)
103
+ throw new Error(`A WhatsApp caption takes up to ${CAPTION_LIMIT} characters`);
104
+ const media = { id: await upload(file) };
105
+ if (message.text)
106
+ media.caption = message.text;
107
+ if (type === "document")
108
+ media.filename = file.filename;
109
+ Object.assign(body, { type, [type]: media });
110
+ }
111
+ const res = await request("POST", `${META_API}/${phoneNumberId}/messages`, JSON.stringify(body), { "Content-Type": "application/json" });
112
+ return { providerId: res.messages[0].id };
113
+ },
114
+ /** The attachment id is the media id; its download link is short-lived, so it is asked for each time. */
115
+ async getAttachment(_providerMessageId, attachmentId) {
116
+ const { download_url } = await request("GET", `${META_API}/${encodeURIComponent(attachmentId)}?${new URLSearchParams({ phone_number_id: phoneNumberId })}`);
117
+ const res = await fetch(download_url);
118
+ if (!res.ok)
119
+ throw new Error(`Kapso media ${attachmentId} download failed: ${res.status}`);
120
+ return new Uint8Array(await res.arrayBuffer());
121
+ },
122
+ };
123
+ }
124
+ function timeOf(message) {
125
+ const date = new Date(Number(message.timestamp) * 1000);
126
+ if (Number.isNaN(date.getTime()))
127
+ throw new Error(`Unparseable Kapso timestamp: ${message.timestamp}`);
128
+ return date;
129
+ }
130
+ function mediaOf(message) {
131
+ if (!MEDIA_TYPES.has(message.type))
132
+ return null;
133
+ return message[message.type] ?? null;
134
+ }
135
+ /** Media shows its caption (a voice note, its transcript); anything else without a body shows Kapso's description of it. */
136
+ function textOf(message) {
137
+ if (message.type === "text")
138
+ return message.text?.body ?? "";
139
+ if (MEDIA_TYPES.has(message.type))
140
+ return mediaOf(message)?.caption ?? message.kapso?.transcript?.text ?? "";
141
+ return message.interactive?.button_reply?.title ?? message.kapso?.content ?? `[${message.type}]`;
142
+ }
143
+ function attachmentsOf(message) {
144
+ const media = mediaOf(message);
145
+ if (!media?.id)
146
+ return [];
147
+ const data = message.kapso?.media_data;
148
+ return [{
149
+ id: media.id,
150
+ filename: data?.filename ?? media.filename ?? message.type,
151
+ content_type: data?.content_type ?? media.mime_type ?? "application/octet-stream",
152
+ size: data?.byte_size ?? null,
153
+ inline: false,
154
+ content_id: null,
155
+ }];
156
+ }
157
+ /** null for a message that carries no phone number (a contact known only by a business-scoped user id). */
158
+ function normalize(message, conversation) {
159
+ if (!message.kapso)
160
+ throw new Error(`Kapso message ${message.id} has no kapso block`);
161
+ const direction = message.kapso.direction === "outbound" ? "out" : "in";
162
+ const number = (direction === "in" ? message.from : message.to) ?? message.kapso.phone_number ?? conversation?.phone_number;
163
+ const phone = number ? phoneAddress(number) : null;
164
+ if (!phone) {
165
+ console.warn(`inboxer: Kapso message ${message.id} skipped, it has no phone number`);
166
+ return null;
167
+ }
168
+ const name = conversation?.contact_name ?? message.kapso.contact_name;
169
+ return {
170
+ providerId: message.id,
171
+ direction,
172
+ status: direction === "out" ? STATUS[message.kapso.status ?? ""] ?? null : null,
173
+ messageId: null,
174
+ inReplyTo: null,
175
+ references: [],
176
+ from: direction === "in" ? (name ? formatAddress(name, phone) : phone) : "",
177
+ to: direction === "in" ? [] : [phone],
178
+ cc: [],
179
+ bcc: [],
180
+ replyTo: [],
181
+ deliveredTo: [],
182
+ subject: "",
183
+ text: textOf(message),
184
+ html: null,
185
+ headers: {},
186
+ attachments: attachmentsOf(message),
187
+ at: timeOf(message).toISOString(),
188
+ };
189
+ }
190
+ function mediaType(contentType) {
191
+ if (contentType === "image/jpeg" || contentType === "image/png")
192
+ return "image";
193
+ if (contentType === "video/mp4" || contentType === "video/3gpp")
194
+ return "video";
195
+ if (contentType.startsWith("audio/"))
196
+ return "audio";
197
+ return "document";
198
+ }
@@ -3,6 +3,6 @@ export interface ResendProviderConfig {
3
3
  apiKey: string;
4
4
  webhookSecret: string;
5
5
  }
6
- export declare function createResendProvider(config: Record<string, unknown>): MailProvider;
6
+ export declare function createResendProvider(name: string, config: Record<string, unknown>): MailProvider;
7
7
  /** The sent-email list uses `YYYY-MM-DD HH:MM:SS.ffffff+00`; the receiving API uses ISO 8601. */
8
8
  export declare function parseResendDate(value: string): Date;
@@ -24,12 +24,12 @@ const LAST_EVENT_STATUS = {
24
24
  suppressed: "failed",
25
25
  canceled: "failed",
26
26
  };
27
- export function createResendProvider(config) {
27
+ export function createResendProvider(name, config) {
28
28
  const { apiKey, webhookSecret } = config;
29
29
  if (typeof apiKey !== "string" || !apiKey)
30
- throw new Error("provider.apiKey is required for the resend provider");
30
+ throw new Error(`providers.${name}.apiKey is required for the resend provider`);
31
31
  if (typeof webhookSecret !== "string" || !webhookSecret) {
32
- throw new Error("provider.webhookSecret is required for the resend provider");
32
+ throw new Error(`providers.${name}.webhookSecret is required for the resend provider`);
33
33
  }
34
34
  const webhook = new Webhook(webhookSecret);
35
35
  async function request(method, path, body, headers = {}) {
@@ -64,7 +64,8 @@ export function createResendProvider(config) {
64
64
  }
65
65
  }
66
66
  return {
67
- name: "resend",
67
+ name,
68
+ kind: "mail",
68
69
  parseWebhook({ headers, body }) {
69
70
  try {
70
71
  webhook.verify(body, {
@@ -80,17 +81,19 @@ export function createResendProvider(config) {
80
81
  }
81
82
  const payload = JSON.parse(body);
82
83
  if (payload.type === "email.received")
83
- return [{ type: "received", providerId: payload.data.email_id }];
84
+ return [{ type: "message", providerId: payload.data.email_id }];
84
85
  const status = WEBHOOK_STATUS[payload.type];
85
86
  if (!status)
86
87
  return [];
87
88
  return [{ type: "status", providerId: payload.data.email_id, status, messageId: payload.data.message_id ?? null }];
88
89
  },
89
- async getInbound(providerId) {
90
+ async getMessage(providerId) {
90
91
  const email = await request("GET", `/emails/receiving/${encodeURIComponent(providerId)}`);
91
92
  const headers = normalizeHeaders(email.headers ?? {});
92
93
  return {
93
94
  providerId: email.id,
95
+ direction: "in",
96
+ status: null,
94
97
  messageId: email.message_id ?? headers["message-id"] ?? null,
95
98
  inReplyTo: headers["in-reply-to"]?.trim() || null,
96
99
  references: (headers["references"] ?? "").split(/\s+/).filter(Boolean),
@@ -105,12 +108,12 @@ export function createResendProvider(config) {
105
108
  html: email.html,
106
109
  headers,
107
110
  attachments: (email.attachments ?? []).map(toAttachmentMeta),
108
- receivedAt: parseResendDate(email.created_at).toISOString(),
111
+ at: parseResendDate(email.created_at).toISOString(),
109
112
  };
110
113
  },
111
- async *listInbound(since) {
114
+ async *listMessages(since) {
112
115
  for await (const item of paginate("/emails/receiving", since)) {
113
- yield item.id;
116
+ yield { type: "message", providerId: item.id };
114
117
  }
115
118
  },
116
119
  async *listOutbound(since) {
@@ -128,9 +131,10 @@ export function createResendProvider(config) {
128
131
  to: message.to,
129
132
  subject: message.subject,
130
133
  text: message.text,
131
- html: message.html,
132
134
  headers: message.headers,
133
135
  };
136
+ if (message.html !== null)
137
+ body.html = message.html;
134
138
  if (message.cc.length)
135
139
  body.cc = message.cc;
136
140
  if (message.bcc.length)
@@ -1,16 +1,32 @@
1
- import type { AttachmentMeta } from "../types.ts";
2
- export type DeliveryStatus = "sent" | "delivered" | "bounced" | "failed";
3
- export type ProviderEvent = {
4
- type: "received";
1
+ import type { AttachmentMeta, Direction } from "../types.ts";
2
+ export type DeliveryStatus = "sent" | "delivered" | "read" | "bounced" | "failed";
3
+ /**
4
+ * `mail`: subjects, several recipients, HTML, threading by headers.
5
+ * `chat`: one counterpart per thread, plain text, at most one attachment per message.
6
+ */
7
+ export type ProviderKind = "mail" | "chat";
8
+ export interface MessageEvent {
9
+ type: "message";
5
10
  providerId: string;
6
- } | {
11
+ /** The message itself, when the provider already has it; otherwise Inboxer calls `getMessage`. */
12
+ message?: ProviderMessage;
13
+ }
14
+ export type ProviderEvent = MessageEvent | {
7
15
  type: "status";
8
16
  providerId: string;
9
17
  status: DeliveryStatus;
10
18
  messageId: string | null;
11
19
  };
12
- export interface InboundMessage {
20
+ /**
21
+ * A message as the provider holds it. `out` ones were sent by anyone on the account, Inboxer included.
22
+ * A chat provider only knows the counterpart: it leaves `to` empty on `in` and `from` empty on `out`,
23
+ * and Inboxer fills in the mailbox's own address.
24
+ */
25
+ export interface ProviderMessage {
13
26
  providerId: string;
27
+ direction: Direction;
28
+ /** Delivery status of an `out` message, when the provider reports it with the message. */
29
+ status: DeliveryStatus | null;
14
30
  messageId: string | null;
15
31
  inReplyTo: string | null;
16
32
  references: string[];
@@ -26,7 +42,8 @@ export interface InboundMessage {
26
42
  html: string | null;
27
43
  headers: Record<string, string>;
28
44
  attachments: AttachmentMeta[];
29
- receivedAt: string;
45
+ /** When it was received or sent. */
46
+ at: string;
30
47
  }
31
48
  export interface OutboundMessage {
32
49
  from: string;
@@ -36,7 +53,8 @@ export interface OutboundMessage {
36
53
  replyTo: string[];
37
54
  subject: string;
38
55
  text: string;
39
- html: string;
56
+ /** null in a chat. */
57
+ html: string | null;
40
58
  headers: Record<string, string>;
41
59
  attachments: OutboundAttachment[];
42
60
  }
@@ -53,25 +71,26 @@ export interface WebhookRequest {
53
71
  headers: Headers;
54
72
  body: string;
55
73
  }
56
- /** Everything Inboxer needs from an email service. Implementations normalize the service's shapes. */
74
+ /** Everything Inboxer needs from a messaging service. Implementations normalize the service's shapes. */
57
75
  export interface MailProvider {
58
- /** Stable identifier, stored on every message and used as the webhook route: `/webhooks/<name>`. */
76
+ /** Its key in `providers`, stored on every message and used as the webhook route: `/webhooks/<name>`. */
59
77
  readonly name: string;
78
+ readonly kind: ProviderKind;
60
79
  /** Verifies the signature and returns the events Inboxer cares about. Throws `WebhookSignatureError`. */
61
80
  parseWebhook(req: WebhookRequest): ProviderEvent[];
62
- getInbound(providerId: string): Promise<InboundMessage>;
63
- /** Ids of inbound messages received at or after `since`. */
64
- listInbound(since: Date): AsyncIterable<string>;
65
- /** Delivery status of outbound messages created at or after `since`. */
81
+ getMessage(providerId: string): Promise<ProviderMessage>;
82
+ /** Messages received or sent at or after `since`. */
83
+ listMessages(since: Date): AsyncIterable<MessageEvent>;
84
+ /** Delivery status of outbound messages created at or after `since`, when `listMessages` does not carry it. */
66
85
  listOutbound(since: Date): AsyncIterable<OutboundStatus>;
67
86
  /** Sends once per `idempotencyKey`; a retry with the same key must not send again. */
68
87
  send(message: OutboundMessage, idempotencyKey: string): Promise<{
69
88
  providerId: string;
70
89
  }>;
71
- /** The bytes of an inbound attachment. */
90
+ /** The bytes of an attachment of a message the provider holds. */
72
91
  getAttachment(providerMessageId: string, attachmentId: string): Promise<Uint8Array>;
73
92
  }
74
- export type ProviderFactory = (config: Record<string, unknown>) => MailProvider;
93
+ export type ProviderFactory = (name: string, config: Record<string, unknown>) => MailProvider;
75
94
  export declare class WebhookSignatureError extends Error {
76
95
  constructor(message: string);
77
96
  }
package/dist/store.d.ts CHANGED
@@ -46,8 +46,8 @@ export declare class Store {
46
46
  putSession(session: Session): Promise<unknown>;
47
47
  deleteSession(id: string): Promise<unknown>;
48
48
  allSessions(): Promise<Session[]>;
49
- getSyncCursor(): Promise<string | null>;
50
- setSyncCursor(at: string): Promise<unknown>;
49
+ getSyncCursor(provider: string): Promise<string | null>;
50
+ setSyncCursor(provider: string, at: string): Promise<unknown>;
51
51
  }
52
52
  export declare class NotFoundError extends Error {
53
53
  constructor(message: string);
package/dist/store.js CHANGED
@@ -133,11 +133,11 @@ export class Store {
133
133
  async allSessions() {
134
134
  return Object.values((await this.db.get("sessions")) ?? {});
135
135
  }
136
- getSyncCursor() {
137
- return this.db.get("sync", "last_started_at");
136
+ getSyncCursor(provider) {
137
+ return this.db.get("sync_cursor", provider);
138
138
  }
139
- setSyncCursor(at) {
140
- return this.db.set("sync", "last_started_at", at);
139
+ setSyncCursor(provider, at) {
140
+ return this.db.set("sync_cursor", provider, at);
141
141
  }
142
142
  }
143
143
  export class NotFoundError extends Error {
package/dist/types.d.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  export interface MailboxConfig {
2
+ /** An email address, or the phone number of a chat provider's line. */
2
3
  address: string;
3
4
  name: string;
5
+ /** The entry of `providers` this mailbox receives and sends through. */
6
+ provider: string;
4
7
  signatureHtml?: string;
5
8
  signatureText?: string;
9
+ /** Review UI sessions can read and organize this mailbox, but not draft or send in it. */
10
+ uiReadOnly?: true;
6
11
  /** MCP tokens that only reach this mailbox, by name. */
7
12
  tokens?: Record<string, string>;
8
13
  }
@@ -16,7 +21,8 @@ export interface InboxerConfig {
16
21
  syncIntervalMin: number;
17
22
  threadWindowDays: number;
18
23
  mailboxes: Record<string, MailboxConfig>;
19
- provider: ProviderConfig;
24
+ /** Messaging services by name; the name is the webhook route, `/webhooks/<name>`. */
25
+ providers: Record<string, ProviderConfig>;
20
26
  mcp: {
21
27
  tokens: Record<string, string>;
22
28
  maxAttachmentMb: number;
@@ -30,7 +36,7 @@ export interface InboxerConfig {
30
36
  }
31
37
  export declare const CATCHALL = "catchall";
32
38
  export type Direction = "in" | "out";
33
- export type MessageStatus = "received" | "draft" | "sent" | "delivered" | "bounced" | "failed" | "discarded";
39
+ export type MessageStatus = "received" | "draft" | "sent" | "delivered" | "read" | "bounced" | "failed" | "discarded";
34
40
  /** Mailbox ids an actor may reach; null reaches every mailbox, the catch-all included. */
35
41
  export type Scope = string[] | null;
36
42
  export type Actor = {
@@ -91,6 +97,8 @@ export interface Thread {
91
97
  subject: string;
92
98
  norm_subject: string;
93
99
  participants: string[];
100
+ /** Display names seen in the From of received messages, by bare address. */
101
+ names: Record<string, string>;
94
102
  last_at: string;
95
103
  last_direction: Direction;
96
104
  has_draft: boolean;
package/dist/ui/routes.js CHANGED
@@ -24,7 +24,10 @@ function uiActor(session) {
24
24
  export function registerUi(app, mail, access, cfg) {
25
25
  const secret = cfg.ui.cookieSecret;
26
26
  const cookieOptions = { httpOnly: true, secure: true, sameSite: "Lax", path: "/", maxAge: COOKIE_MAX_AGE };
27
- const hue = V.accentHue([...new Set(Object.values(cfg.mailboxes).map(m => domainOf(m.address)))]);
27
+ const mailDomains = (mailboxes) => [...new Set(mailboxes.filter(m => m.kind === "mail").map(m => domainOf(m.address)))];
28
+ const mailboxesOf = (session) => mail.listMailboxes(session.scope).filter(m => m.id !== CATCHALL);
29
+ const hue = V.accentHue(mailDomains(mail.listMailboxes(null).filter(m => m.id !== CATCHALL)));
30
+ const isChat = (mailbox) => mail.kindOf(mailbox) === "chat";
28
31
  const own = (address) => mail.isOwn(address);
29
32
  /** Recipients that are our own addresses are implied by the mailbox badge. */
30
33
  const shown = (m) => ({
@@ -32,9 +35,9 @@ export function registerUi(app, mail, access, cfg) {
32
35
  to: m.to.filter(a => !own(a)),
33
36
  cc: m.cc.filter(a => !own(a)),
34
37
  });
35
- /** Mailboxes a session can send from: every one in its scope but the catch-all. */
36
- const senders = (session) => mail.listMailboxes(session.scope).filter(m => m.id !== CATCHALL);
37
- const domainsOf = (session) => [...new Set(senders(session).map(m => domainOf(m.address)))];
38
+ /** Mailboxes a session can start new mail from: the mail ones in its scope it may write in, but the catch-all. */
39
+ const senders = (session) => mailboxesOf(session).filter(m => m.kind === "mail" && mail.uiCanWrite(m.id));
40
+ const domainsOf = (session) => mailDomains(mailboxesOf(session));
38
41
  const page = async (c, title, body, current, status = 200, fullScreen = false) => {
39
42
  const session = c.get("session");
40
43
  const shell = session
@@ -95,7 +98,7 @@ export function registerUi(app, mail, access, cfg) {
95
98
  return V.draftDone(id, S.discarded);
96
99
  if (draft.status !== "draft")
97
100
  return V.messageBubble(shown(toView(draft)), false);
98
- return V.draftCard(draft);
101
+ return V.draftCard(draft, mail.uiCanWrite(draft.mailbox));
99
102
  };
100
103
  app.get("/", async (c) => {
101
104
  const session = c.get("session");
@@ -119,7 +122,7 @@ export function registerUi(app, mail, access, cfg) {
119
122
  return c.body(null, 204);
120
123
  }
121
124
  const form = { to: draft.to.join(", "), cc: draft.cc.join(", "), subject: draft.subject, text: draft.text };
122
- return c.html(V.draftEditor(draft, form, null));
125
+ return c.html(V.draftEditor(draft, form, null, isChat(draft.mailbox)));
123
126
  });
124
127
  app.post("/drafts/:id/save", async (c) => {
125
128
  const id = c.req.param("id");
@@ -140,7 +143,7 @@ export function registerUi(app, mail, access, cfg) {
140
143
  }
141
144
  catch (err) {
142
145
  if (err instanceof ConflictError)
143
- return c.html(V.draftEditor(err.current, form, err.current));
146
+ return c.html(V.draftEditor(err.current, form, err.current, isChat(err.current.mailbox)));
144
147
  if (err instanceof InvalidRequestError)
145
148
  return c.html(V.draftDone(id, err.message));
146
149
  throw err;
@@ -198,7 +201,7 @@ export function registerUi(app, mail, access, cfg) {
198
201
  const filter = inboxFilter(c);
199
202
  const threads = await mail.listThreads({ mailbox: filter.mailbox || undefined, status: filter.status, limit: 200 }, session.scope);
200
203
  const accounts = await mail.listAccounts(session.scope);
201
- return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), addressOf: a => mail.addressOf(a), domains: domainsOf(session), filter, own, current });
204
+ return V.threadList(threads, { accounts, accountOf: t => mail.accountOf(t), addressOf: a => mail.addressOf(a), domains: domainsOf(session), filter, own, isChat, current });
202
205
  };
203
206
  app.get("/inbox", async (c) => page(c, S.navInbox, V.inboxPage(await threadList(c, null), null), "inbox"));
204
207
  /** A thread with its drafts in place; opening it marks it read. */
@@ -213,11 +216,12 @@ export function registerUi(app, mail, access, cfg) {
213
216
  const people = thread.participants.filter(p => !own(p));
214
217
  const entries = await Promise.all(messages.map(async (m) => ({
215
218
  at: m.date,
216
- view: m.status === "draft" ? V.draftCard(await mail.store.requireMessage(m.id)) : V.messageBubble(shown(m), people.length > 1),
219
+ view: m.status === "draft" ? V.draftCard(await mail.store.requireMessage(m.id), mail.uiCanWrite(m.mailbox)) : V.messageBubble(shown(m), people.length > 1),
217
220
  })));
218
221
  const account = mail.accountOf(thread);
219
- const reply = { allowed: account !== CATCHALL && (thread.mailbox === CATCHALL || senders(session).some(m => m.id === thread.mailbox)), replyAll: people.length > 1 };
220
- return { thread, view: V.threadView(thread, entries, { context, contacts }, { back, filter: inboxFilter(c), own, account, reply }) };
222
+ const chat = isChat(thread.mailbox);
223
+ const reply = { allowed: account !== CATCHALL && mail.uiCanWrite(thread.mailbox), replyAll: people.length > 1 && !chat };
224
+ return { thread, view: V.threadView(thread, entries, { context, contacts }, { back, filter: inboxFilter(c), own, account, chat, reply }) };
221
225
  };
222
226
  app.get("/threads/:id", async (c) => {
223
227
  const id = c.req.param("id");