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.
- package/README.md +40 -20
- package/dist/app.js +4 -3
- package/dist/config.d.ts +2 -4
- package/dist/config.js +13 -4
- package/dist/core/address.d.ts +5 -1
- package/dist/core/address.js +11 -1
- package/dist/core/mail.d.ts +24 -13
- package/dist/core/mail.js +158 -85
- package/dist/core/sync.d.ts +6 -0
- package/dist/core/sync.js +22 -7
- package/dist/core/threads.d.ts +2 -0
- package/dist/core/threads.js +12 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -5
- package/dist/mcp.js +8 -8
- package/dist/provider/index.d.ts +2 -1
- package/dist/provider/index.js +10 -6
- package/dist/provider/kapso.d.ts +8 -0
- package/dist/provider/kapso.js +198 -0
- package/dist/provider/resend.d.ts +1 -1
- package/dist/provider/resend.js +14 -10
- package/dist/provider/types.d.ts +35 -16
- package/dist/store.d.ts +2 -2
- package/dist/store.js +4 -4
- package/dist/types.d.ts +10 -2
- package/dist/ui/routes.js +15 -11
- package/dist/ui/views.d.ts +7 -5
- package/dist/ui/views.js +18 -16
- package/package.json +1 -1
- package/skills/inboxer/SKILL.md +15 -8
- package/src/app.ts +4 -3
- package/src/config.ts +10 -3
- package/src/core/address.ts +13 -1
- package/src/core/mail.ts +162 -89
- package/src/core/sync.ts +23 -7
- package/src/core/threads.ts +12 -1
- package/src/index.ts +10 -8
- package/src/mcp.ts +8 -8
- package/src/provider/index.ts +9 -5
- package/src/provider/kapso.ts +251 -0
- package/src/provider/resend.ts +15 -11
- package/src/provider/types.ts +38 -14
- package/src/store.ts +4 -4
- package/src/types.ts +10 -2
- package/src/ui/routes.ts +16 -11
- package/src/ui/views.ts +20 -17
package/src/mcp.ts
CHANGED
|
@@ -51,7 +51,7 @@ function attachmentContent(cfg: Cfg, messageId: string, meta: AttachmentMeta, bo
|
|
|
51
51
|
return { type: "resource" as const, resource: { uri, mimeType: meta.content_type, blob: data } };
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
const addresses = z.array(z.string()).describe("Addresses, e.g. \"Ana <ana@example.com>\" or \"ana@example.com\"");
|
|
54
|
+
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\"");
|
|
55
55
|
const isoDate = z.string().describe("ISO 8601 timestamp");
|
|
56
56
|
const metaFilter = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
|
|
57
57
|
.describe("Every pair must match the thread's context or a participant's contact; values compare as text");
|
|
@@ -63,7 +63,7 @@ function buildServer(mail: Mail, access: Access, actor: Actor): McpServer {
|
|
|
63
63
|
const server = new McpServer({ name: "inboxer", version: VERSION });
|
|
64
64
|
const cfg = mail.cfg;
|
|
65
65
|
|
|
66
|
-
server.registerTool("list_mailboxes", { description: "Mailboxes this token reaches; tokens for every mailbox also see the catch-all for unknown recipients." },
|
|
66
|
+
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." },
|
|
67
67
|
wrap(cfg, async () => mail.listMailboxes(actor.scope)));
|
|
68
68
|
|
|
69
69
|
server.registerTool("list_threads", {
|
|
@@ -100,12 +100,12 @@ function buildServer(mail: Mail, access: Access, actor: Actor): McpServer {
|
|
|
100
100
|
}));
|
|
101
101
|
|
|
102
102
|
server.registerTool("get_contact", {
|
|
103
|
-
description: "Context stored for an email address: meta (e.g. ids in other systems) and a note. null when there is none.",
|
|
103
|
+
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.",
|
|
104
104
|
inputSchema: { address: z.string() },
|
|
105
105
|
}, wrap(cfg, async ({ address }) => mail.getContact(address, actor.scope)));
|
|
106
106
|
|
|
107
107
|
server.registerTool("set_contact", {
|
|
108
|
-
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.",
|
|
108
|
+
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.",
|
|
109
109
|
inputSchema: { address: z.string(), meta: metaPatch.optional(), note: notePatch.optional() },
|
|
110
110
|
}, wrap(cfg, async ({ address, meta, note }) => mail.setContact(address, { meta, note }, actor)));
|
|
111
111
|
|
|
@@ -125,7 +125,7 @@ function buildServer(mail: Mail, access: Access, actor: Actor): McpServer {
|
|
|
125
125
|
}, wrap(cfg, async ({ ids, read, archived }) => ({ updated: await mail.mark(ids, { read, archived }, actor) })));
|
|
126
126
|
|
|
127
127
|
server.registerTool("create_draft", {
|
|
128
|
-
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.",
|
|
128
|
+
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.",
|
|
129
129
|
inputSchema: {
|
|
130
130
|
mailbox: z.string().optional(),
|
|
131
131
|
reply_to_id: z.string().optional().describe("Message id to reply to"),
|
|
@@ -171,13 +171,13 @@ function buildServer(mail: Mail, access: Access, actor: Actor): McpServer {
|
|
|
171
171
|
wrap(cfg, async ({ id }) => messageView(cfg, toView(await mail.sendDraft(id, actor)))));
|
|
172
172
|
|
|
173
173
|
server.registerTool("send", {
|
|
174
|
-
description: "Send a new message directly, without review. Use only when your rules allow it.",
|
|
174
|
+
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.",
|
|
175
175
|
inputSchema: {
|
|
176
176
|
mailbox: z.string(),
|
|
177
177
|
to: addresses,
|
|
178
178
|
cc: addresses.optional(),
|
|
179
179
|
bcc: addresses.optional(),
|
|
180
|
-
subject: z.string(),
|
|
180
|
+
subject: z.string().optional(),
|
|
181
181
|
text: z.string(),
|
|
182
182
|
html: z.string().optional(),
|
|
183
183
|
},
|
|
@@ -189,7 +189,7 @@ function buildServer(mail: Mail, access: Access, actor: Actor): McpServer {
|
|
|
189
189
|
}, wrap(cfg, async ({ message_id, text, reply_all }) => messageView(cfg, toView(await mail.reply(message_id, text, reply_all ?? false, actor)))));
|
|
190
190
|
|
|
191
191
|
server.registerTool("get_attachment", {
|
|
192
|
-
description: "Content of an
|
|
192
|
+
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.",
|
|
193
193
|
inputSchema: { message_id: z.string(), attachment_id: z.string() },
|
|
194
194
|
}, async ({ message_id, attachment_id }) => {
|
|
195
195
|
try {
|
package/src/provider/index.ts
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import type { ProviderConfig } from "../types.ts";
|
|
2
|
+
import { createKapsoProvider } from "./kapso.ts";
|
|
2
3
|
import { createResendProvider } from "./resend.ts";
|
|
3
4
|
import type { MailProvider, ProviderFactory } from "./types.ts";
|
|
4
5
|
|
|
5
6
|
const PROVIDERS: Record<string, ProviderFactory> = {
|
|
6
7
|
resend: createResendProvider,
|
|
8
|
+
kapso: createKapsoProvider,
|
|
7
9
|
};
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
/** One provider per entry of `providers`, named by its key. */
|
|
12
|
+
export function resolveProviders(configs: Record<string, ProviderConfig>): Record<string, MailProvider> {
|
|
13
|
+
return Object.fromEntries(Object.entries(configs).map(([name, { type, ...options }]) => {
|
|
14
|
+
const factory = PROVIDERS[type];
|
|
15
|
+
if (!factory) throw new Error(`Unknown provider type "${type}" in providers.${name}. Available: ${Object.keys(PROVIDERS).join(", ")}`);
|
|
16
|
+
return [name, factory(name, options)];
|
|
17
|
+
}));
|
|
14
18
|
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { bareAddress, formatAddress, phoneAddress } from "../core/address.ts";
|
|
3
|
+
import type { AttachmentMeta } from "../types.ts";
|
|
4
|
+
import {
|
|
5
|
+
WebhookSignatureError,
|
|
6
|
+
type DeliveryStatus,
|
|
7
|
+
type MailProvider,
|
|
8
|
+
type MessageEvent,
|
|
9
|
+
type OutboundAttachment,
|
|
10
|
+
type OutboundMessage,
|
|
11
|
+
type OutboundStatus,
|
|
12
|
+
type ProviderEvent,
|
|
13
|
+
type ProviderMessage,
|
|
14
|
+
type WebhookRequest,
|
|
15
|
+
} from "./types.ts";
|
|
16
|
+
|
|
17
|
+
const PLATFORM_API = "https://api.kapso.ai/platform/v1/whatsapp";
|
|
18
|
+
const META_API = "https://api.kapso.ai/meta/whatsapp/v24.0";
|
|
19
|
+
const PAGE_LIMIT = 100;
|
|
20
|
+
const TEXT_LIMIT = 4096;
|
|
21
|
+
const CAPTION_LIMIT = 1024;
|
|
22
|
+
|
|
23
|
+
const MEDIA_TYPES = new Set(["image", "video", "audio", "document", "sticker"]);
|
|
24
|
+
|
|
25
|
+
const STATUS: Record<string, DeliveryStatus> = { sent: "sent", delivered: "delivered", read: "read", failed: "failed" };
|
|
26
|
+
|
|
27
|
+
const WEBHOOK_STATUS: Record<string, DeliveryStatus> = {
|
|
28
|
+
"whatsapp.message.delivered": "delivered",
|
|
29
|
+
"whatsapp.message.read": "read",
|
|
30
|
+
"whatsapp.message.failed": "failed",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
interface KapsoMedia {
|
|
34
|
+
id?: string;
|
|
35
|
+
caption?: string | null;
|
|
36
|
+
filename?: string | null;
|
|
37
|
+
mime_type?: string | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A WhatsApp Cloud API message with Kapso's `kapso` block. The media payload sits under the key named by `type`. */
|
|
41
|
+
interface KapsoMessage {
|
|
42
|
+
id: string;
|
|
43
|
+
timestamp: string;
|
|
44
|
+
type: string;
|
|
45
|
+
from?: string | null;
|
|
46
|
+
to?: string | null;
|
|
47
|
+
text?: { body: string };
|
|
48
|
+
interactive?: { button_reply?: { title: string } };
|
|
49
|
+
kapso?: {
|
|
50
|
+
direction: string;
|
|
51
|
+
status?: string;
|
|
52
|
+
content?: string | null;
|
|
53
|
+
contact_name?: string | null;
|
|
54
|
+
phone_number?: string | null;
|
|
55
|
+
transcript?: { text: string } | null;
|
|
56
|
+
media_data?: { filename?: string | null; content_type?: string | null; byte_size?: number | null } | null;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface KapsoWebhookItem {
|
|
61
|
+
message: KapsoMessage;
|
|
62
|
+
conversation?: { contact_name?: string | null; phone_number?: string | null };
|
|
63
|
+
phone_number_id: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface KapsoPage {
|
|
67
|
+
data: KapsoMessage[];
|
|
68
|
+
paging?: { cursors?: { after?: string | null }; next?: string | null };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface KapsoProviderConfig {
|
|
72
|
+
apiKey: string;
|
|
73
|
+
webhookSecret: string;
|
|
74
|
+
phoneNumberId: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** One WhatsApp number through Kapso's proxy of the WhatsApp Cloud API. */
|
|
78
|
+
export function createKapsoProvider(name: string, config: Record<string, unknown>): MailProvider {
|
|
79
|
+
const { apiKey, webhookSecret, phoneNumberId } = config as unknown as KapsoProviderConfig;
|
|
80
|
+
for (const [key, value] of Object.entries({ apiKey, webhookSecret, phoneNumberId })) {
|
|
81
|
+
if (typeof value !== "string" || !value) throw new Error(`providers.${name}.${key} is required for the kapso provider`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function request<T>(method: string, url: string, body?: BodyInit, headers: Record<string, string> = {}): Promise<T> {
|
|
85
|
+
const res = await fetch(url, { method, headers: { "X-API-Key": apiKey, "User-Agent": "inboxer", ...headers }, body });
|
|
86
|
+
if (!res.ok) throw new Error(`Kapso ${method} ${url} failed: ${res.status} ${await res.text()}`);
|
|
87
|
+
return (await res.json()) as T;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function upload(file: OutboundAttachment): Promise<string> {
|
|
91
|
+
const form = new FormData();
|
|
92
|
+
form.set("messaging_product", "whatsapp");
|
|
93
|
+
form.set("file", new Blob([file.content as Uint8Array<ArrayBuffer>], { type: file.contentType }), file.filename);
|
|
94
|
+
return (await request<{ id: string }>("POST", `${META_API}/${phoneNumberId}/media`, form)).id;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
name,
|
|
99
|
+
kind: "chat",
|
|
100
|
+
|
|
101
|
+
parseWebhook({ headers, body }: WebhookRequest): ProviderEvent[] {
|
|
102
|
+
const expected = createHmac("sha256", webhookSecret).update(body).digest();
|
|
103
|
+
const given = Buffer.from(headers.get("x-webhook-signature") ?? "", "hex");
|
|
104
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) throw new WebhookSignatureError("Invalid Kapso webhook signature");
|
|
105
|
+
|
|
106
|
+
const event = headers.get("x-webhook-event") ?? "";
|
|
107
|
+
const payload = JSON.parse(body) as KapsoWebhookItem | { batch: true; data: KapsoWebhookItem[] };
|
|
108
|
+
const items = "batch" in payload ? payload.data : [payload];
|
|
109
|
+
const events: ProviderEvent[] = [];
|
|
110
|
+
for (const item of items) {
|
|
111
|
+
if (item.phone_number_id !== phoneNumberId) continue;
|
|
112
|
+
const status = WEBHOOK_STATUS[event];
|
|
113
|
+
if (status) {
|
|
114
|
+
events.push({ type: "status", providerId: item.message.id, status, messageId: null });
|
|
115
|
+
} else if (event === "whatsapp.message.received" || event === "whatsapp.message.sent") {
|
|
116
|
+
const message = normalize(item.message, item.conversation);
|
|
117
|
+
if (message) events.push({ type: "message", providerId: message.providerId, message });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return events;
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
async getMessage(providerId: string): Promise<ProviderMessage> {
|
|
124
|
+
const { data } = await request<{ data: KapsoMessage }>("GET", `${PLATFORM_API}/messages/${encodeURIComponent(providerId)}`);
|
|
125
|
+
const message = normalize(data);
|
|
126
|
+
if (!message) throw new Error(`Kapso message ${providerId} has no phone number`);
|
|
127
|
+
return message;
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
/** The history is listed newest first, with no date filter. */
|
|
131
|
+
async *listMessages(since: Date): AsyncIterable<MessageEvent> {
|
|
132
|
+
let after: string | null = null;
|
|
133
|
+
while (true) {
|
|
134
|
+
const query = new URLSearchParams({ phone_number_id: phoneNumberId, limit: String(PAGE_LIMIT), ...(after ? { after } : {}) });
|
|
135
|
+
const page: KapsoPage = await request<KapsoPage>("GET", `${PLATFORM_API}/messages?${query}`);
|
|
136
|
+
for (const item of page.data) {
|
|
137
|
+
if (timeOf(item) < since) return;
|
|
138
|
+
const message = normalize(item);
|
|
139
|
+
if (message) yield { type: "message", providerId: message.providerId, message };
|
|
140
|
+
}
|
|
141
|
+
after = page.paging?.cursors?.after ?? null;
|
|
142
|
+
if (!page.paging?.next || !after || page.data.length === 0) return;
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
|
|
146
|
+
/** `listMessages` already carries the status of every outbound message. */
|
|
147
|
+
async *listOutbound(): AsyncIterable<OutboundStatus> {},
|
|
148
|
+
|
|
149
|
+
/** The Cloud API takes no idempotency key: a send whose response was lost can repeat on retry. */
|
|
150
|
+
async send(message: OutboundMessage): Promise<{ providerId: string }> {
|
|
151
|
+
const body: Record<string, unknown> = { messaging_product: "whatsapp", recipient_type: "individual", to: bareAddress(message.to[0]!).slice(1) };
|
|
152
|
+
const [file] = message.attachments;
|
|
153
|
+
if (!file) {
|
|
154
|
+
if (message.text.length > TEXT_LIMIT) throw new Error(`A WhatsApp text takes up to ${TEXT_LIMIT} characters`);
|
|
155
|
+
Object.assign(body, { type: "text", text: { body: message.text } });
|
|
156
|
+
} else {
|
|
157
|
+
const type = mediaType(file.contentType);
|
|
158
|
+
if (message.text && type === "audio") throw new Error("A WhatsApp audio message takes no text");
|
|
159
|
+
if (message.text.length > CAPTION_LIMIT) throw new Error(`A WhatsApp caption takes up to ${CAPTION_LIMIT} characters`);
|
|
160
|
+
const media: Record<string, string> = { id: await upload(file) };
|
|
161
|
+
if (message.text) media.caption = message.text;
|
|
162
|
+
if (type === "document") media.filename = file.filename;
|
|
163
|
+
Object.assign(body, { type, [type]: media });
|
|
164
|
+
}
|
|
165
|
+
const res = await request<{ messages: { id: string }[] }>(
|
|
166
|
+
"POST", `${META_API}/${phoneNumberId}/messages`, JSON.stringify(body), { "Content-Type": "application/json" });
|
|
167
|
+
return { providerId: res.messages[0]!.id };
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
/** The attachment id is the media id; its download link is short-lived, so it is asked for each time. */
|
|
171
|
+
async getAttachment(_providerMessageId: string, attachmentId: string): Promise<Uint8Array> {
|
|
172
|
+
const { download_url } = await request<{ download_url: string }>(
|
|
173
|
+
"GET", `${META_API}/${encodeURIComponent(attachmentId)}?${new URLSearchParams({ phone_number_id: phoneNumberId })}`);
|
|
174
|
+
const res = await fetch(download_url);
|
|
175
|
+
if (!res.ok) throw new Error(`Kapso media ${attachmentId} download failed: ${res.status}`);
|
|
176
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function timeOf(message: KapsoMessage): Date {
|
|
182
|
+
const date = new Date(Number(message.timestamp) * 1000);
|
|
183
|
+
if (Number.isNaN(date.getTime())) throw new Error(`Unparseable Kapso timestamp: ${message.timestamp}`);
|
|
184
|
+
return date;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function mediaOf(message: KapsoMessage): KapsoMedia | null {
|
|
188
|
+
if (!MEDIA_TYPES.has(message.type)) return null;
|
|
189
|
+
return (message as unknown as Record<string, KapsoMedia | undefined>)[message.type] ?? null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Media shows its caption (a voice note, its transcript); anything else without a body shows Kapso's description of it. */
|
|
193
|
+
function textOf(message: KapsoMessage): string {
|
|
194
|
+
if (message.type === "text") return message.text?.body ?? "";
|
|
195
|
+
if (MEDIA_TYPES.has(message.type)) return mediaOf(message)?.caption ?? message.kapso?.transcript?.text ?? "";
|
|
196
|
+
return message.interactive?.button_reply?.title ?? message.kapso?.content ?? `[${message.type}]`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function attachmentsOf(message: KapsoMessage): AttachmentMeta[] {
|
|
200
|
+
const media = mediaOf(message);
|
|
201
|
+
if (!media?.id) return [];
|
|
202
|
+
const data = message.kapso?.media_data;
|
|
203
|
+
return [{
|
|
204
|
+
id: media.id,
|
|
205
|
+
filename: data?.filename ?? media.filename ?? message.type,
|
|
206
|
+
content_type: data?.content_type ?? media.mime_type ?? "application/octet-stream",
|
|
207
|
+
size: data?.byte_size ?? null,
|
|
208
|
+
inline: false,
|
|
209
|
+
content_id: null,
|
|
210
|
+
}];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** null for a message that carries no phone number (a contact known only by a business-scoped user id). */
|
|
214
|
+
function normalize(message: KapsoMessage, conversation?: KapsoWebhookItem["conversation"]): ProviderMessage | null {
|
|
215
|
+
if (!message.kapso) throw new Error(`Kapso message ${message.id} has no kapso block`);
|
|
216
|
+
const direction = message.kapso.direction === "outbound" ? "out" : "in";
|
|
217
|
+
const number = (direction === "in" ? message.from : message.to) ?? message.kapso.phone_number ?? conversation?.phone_number;
|
|
218
|
+
const phone = number ? phoneAddress(number) : null;
|
|
219
|
+
if (!phone) {
|
|
220
|
+
console.warn(`inboxer: Kapso message ${message.id} skipped, it has no phone number`);
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
const name = conversation?.contact_name ?? message.kapso.contact_name;
|
|
224
|
+
return {
|
|
225
|
+
providerId: message.id,
|
|
226
|
+
direction,
|
|
227
|
+
status: direction === "out" ? STATUS[message.kapso.status ?? ""] ?? null : null,
|
|
228
|
+
messageId: null,
|
|
229
|
+
inReplyTo: null,
|
|
230
|
+
references: [],
|
|
231
|
+
from: direction === "in" ? (name ? formatAddress(name, phone) : phone) : "",
|
|
232
|
+
to: direction === "in" ? [] : [phone],
|
|
233
|
+
cc: [],
|
|
234
|
+
bcc: [],
|
|
235
|
+
replyTo: [],
|
|
236
|
+
deliveredTo: [],
|
|
237
|
+
subject: "",
|
|
238
|
+
text: textOf(message),
|
|
239
|
+
html: null,
|
|
240
|
+
headers: {},
|
|
241
|
+
attachments: attachmentsOf(message),
|
|
242
|
+
at: timeOf(message).toISOString(),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function mediaType(contentType: string): "image" | "video" | "audio" | "document" {
|
|
247
|
+
if (contentType === "image/jpeg" || contentType === "image/png") return "image";
|
|
248
|
+
if (contentType === "video/mp4" || contentType === "video/3gpp") return "video";
|
|
249
|
+
if (contentType.startsWith("audio/")) return "audio";
|
|
250
|
+
return "document";
|
|
251
|
+
}
|
package/src/provider/resend.ts
CHANGED
|
@@ -3,11 +3,12 @@ import type { AttachmentMeta } from "../types.ts";
|
|
|
3
3
|
import {
|
|
4
4
|
WebhookSignatureError,
|
|
5
5
|
type DeliveryStatus,
|
|
6
|
-
type InboundMessage,
|
|
7
6
|
type MailProvider,
|
|
7
|
+
type MessageEvent,
|
|
8
8
|
type OutboundMessage,
|
|
9
9
|
type OutboundStatus,
|
|
10
10
|
type ProviderEvent,
|
|
11
|
+
type ProviderMessage,
|
|
11
12
|
type WebhookRequest,
|
|
12
13
|
} from "./types.ts";
|
|
13
14
|
|
|
@@ -74,11 +75,11 @@ export interface ResendProviderConfig {
|
|
|
74
75
|
webhookSecret: string;
|
|
75
76
|
}
|
|
76
77
|
|
|
77
|
-
export function createResendProvider(config: Record<string, unknown>): MailProvider {
|
|
78
|
+
export function createResendProvider(name: string, config: Record<string, unknown>): MailProvider {
|
|
78
79
|
const { apiKey, webhookSecret } = config as unknown as ResendProviderConfig;
|
|
79
|
-
if (typeof apiKey !== "string" || !apiKey) throw new Error(
|
|
80
|
+
if (typeof apiKey !== "string" || !apiKey) throw new Error(`providers.${name}.apiKey is required for the resend provider`);
|
|
80
81
|
if (typeof webhookSecret !== "string" || !webhookSecret) {
|
|
81
|
-
throw new Error(
|
|
82
|
+
throw new Error(`providers.${name}.webhookSecret is required for the resend provider`);
|
|
82
83
|
}
|
|
83
84
|
const webhook = new Webhook(webhookSecret);
|
|
84
85
|
|
|
@@ -114,7 +115,8 @@ export function createResendProvider(config: Record<string, unknown>): MailProvi
|
|
|
114
115
|
}
|
|
115
116
|
|
|
116
117
|
return {
|
|
117
|
-
name
|
|
118
|
+
name,
|
|
119
|
+
kind: "mail",
|
|
118
120
|
|
|
119
121
|
parseWebhook({ headers, body }: WebhookRequest): ProviderEvent[] {
|
|
120
122
|
try {
|
|
@@ -128,17 +130,19 @@ export function createResendProvider(config: Record<string, unknown>): MailProvi
|
|
|
128
130
|
throw err;
|
|
129
131
|
}
|
|
130
132
|
const payload = JSON.parse(body) as { type: string; data: { email_id: string; message_id?: string | null } };
|
|
131
|
-
if (payload.type === "email.received") return [{ type: "
|
|
133
|
+
if (payload.type === "email.received") return [{ type: "message", providerId: payload.data.email_id }];
|
|
132
134
|
const status = WEBHOOK_STATUS[payload.type];
|
|
133
135
|
if (!status) return [];
|
|
134
136
|
return [{ type: "status", providerId: payload.data.email_id, status, messageId: payload.data.message_id ?? null }];
|
|
135
137
|
},
|
|
136
138
|
|
|
137
|
-
async
|
|
139
|
+
async getMessage(providerId: string): Promise<ProviderMessage> {
|
|
138
140
|
const email = await request<ResendReceivedEmail>("GET", `/emails/receiving/${encodeURIComponent(providerId)}`);
|
|
139
141
|
const headers = normalizeHeaders(email.headers ?? {});
|
|
140
142
|
return {
|
|
141
143
|
providerId: email.id,
|
|
144
|
+
direction: "in",
|
|
145
|
+
status: null,
|
|
142
146
|
messageId: email.message_id ?? headers["message-id"] ?? null,
|
|
143
147
|
inReplyTo: headers["in-reply-to"]?.trim() || null,
|
|
144
148
|
references: (headers["references"] ?? "").split(/\s+/).filter(Boolean),
|
|
@@ -153,13 +157,13 @@ export function createResendProvider(config: Record<string, unknown>): MailProvi
|
|
|
153
157
|
html: email.html,
|
|
154
158
|
headers,
|
|
155
159
|
attachments: (email.attachments ?? []).map(toAttachmentMeta),
|
|
156
|
-
|
|
160
|
+
at: parseResendDate(email.created_at).toISOString(),
|
|
157
161
|
};
|
|
158
162
|
},
|
|
159
163
|
|
|
160
|
-
async *
|
|
164
|
+
async *listMessages(since: Date): AsyncIterable<MessageEvent> {
|
|
161
165
|
for await (const item of paginate<{ id: string; created_at: string }>("/emails/receiving", since)) {
|
|
162
|
-
yield item.id;
|
|
166
|
+
yield { type: "message", providerId: item.id };
|
|
163
167
|
}
|
|
164
168
|
},
|
|
165
169
|
|
|
@@ -177,9 +181,9 @@ export function createResendProvider(config: Record<string, unknown>): MailProvi
|
|
|
177
181
|
to: message.to,
|
|
178
182
|
subject: message.subject,
|
|
179
183
|
text: message.text,
|
|
180
|
-
html: message.html,
|
|
181
184
|
headers: message.headers,
|
|
182
185
|
};
|
|
186
|
+
if (message.html !== null) body.html = message.html;
|
|
183
187
|
if (message.cc.length) body.cc = message.cc;
|
|
184
188
|
if (message.bcc.length) body.bcc = message.bcc;
|
|
185
189
|
if (message.replyTo.length) body.reply_to = message.replyTo;
|
package/src/provider/types.ts
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
1
|
-
import type { AttachmentMeta } from "../types.ts";
|
|
1
|
+
import type { AttachmentMeta, Direction } from "../types.ts";
|
|
2
2
|
|
|
3
|
-
export type DeliveryStatus = "sent" | "delivered" | "bounced" | "failed";
|
|
3
|
+
export type DeliveryStatus = "sent" | "delivered" | "read" | "bounced" | "failed";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `mail`: subjects, several recipients, HTML, threading by headers.
|
|
7
|
+
* `chat`: one counterpart per thread, plain text, at most one attachment per message.
|
|
8
|
+
*/
|
|
9
|
+
export type ProviderKind = "mail" | "chat";
|
|
10
|
+
|
|
11
|
+
export interface MessageEvent {
|
|
12
|
+
type: "message";
|
|
13
|
+
providerId: string;
|
|
14
|
+
/** The message itself, when the provider already has it; otherwise Inboxer calls `getMessage`. */
|
|
15
|
+
message?: ProviderMessage;
|
|
16
|
+
}
|
|
4
17
|
|
|
5
18
|
export type ProviderEvent =
|
|
6
|
-
|
|
|
19
|
+
| MessageEvent
|
|
7
20
|
| { type: "status"; providerId: string; status: DeliveryStatus; messageId: string | null };
|
|
8
21
|
|
|
9
|
-
|
|
22
|
+
/**
|
|
23
|
+
* A message as the provider holds it. `out` ones were sent by anyone on the account, Inboxer included.
|
|
24
|
+
* A chat provider only knows the counterpart: it leaves `to` empty on `in` and `from` empty on `out`,
|
|
25
|
+
* and Inboxer fills in the mailbox's own address.
|
|
26
|
+
*/
|
|
27
|
+
export interface ProviderMessage {
|
|
10
28
|
providerId: string;
|
|
29
|
+
direction: Direction;
|
|
30
|
+
/** Delivery status of an `out` message, when the provider reports it with the message. */
|
|
31
|
+
status: DeliveryStatus | null;
|
|
11
32
|
messageId: string | null;
|
|
12
33
|
inReplyTo: string | null;
|
|
13
34
|
references: string[];
|
|
@@ -23,7 +44,8 @@ export interface InboundMessage {
|
|
|
23
44
|
html: string | null;
|
|
24
45
|
headers: Record<string, string>;
|
|
25
46
|
attachments: AttachmentMeta[];
|
|
26
|
-
|
|
47
|
+
/** When it was received or sent. */
|
|
48
|
+
at: string;
|
|
27
49
|
}
|
|
28
50
|
|
|
29
51
|
export interface OutboundMessage {
|
|
@@ -34,7 +56,8 @@ export interface OutboundMessage {
|
|
|
34
56
|
replyTo: string[];
|
|
35
57
|
subject: string;
|
|
36
58
|
text: string;
|
|
37
|
-
|
|
59
|
+
/** null in a chat. */
|
|
60
|
+
html: string | null;
|
|
38
61
|
headers: Record<string, string>;
|
|
39
62
|
attachments: OutboundAttachment[];
|
|
40
63
|
}
|
|
@@ -55,24 +78,25 @@ export interface WebhookRequest {
|
|
|
55
78
|
body: string;
|
|
56
79
|
}
|
|
57
80
|
|
|
58
|
-
/** Everything Inboxer needs from
|
|
81
|
+
/** Everything Inboxer needs from a messaging service. Implementations normalize the service's shapes. */
|
|
59
82
|
export interface MailProvider {
|
|
60
|
-
/**
|
|
83
|
+
/** Its key in `providers`, stored on every message and used as the webhook route: `/webhooks/<name>`. */
|
|
61
84
|
readonly name: string;
|
|
85
|
+
readonly kind: ProviderKind;
|
|
62
86
|
/** Verifies the signature and returns the events Inboxer cares about. Throws `WebhookSignatureError`. */
|
|
63
87
|
parseWebhook(req: WebhookRequest): ProviderEvent[];
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
|
|
67
|
-
/** Delivery status of outbound messages created at or after `since
|
|
88
|
+
getMessage(providerId: string): Promise<ProviderMessage>;
|
|
89
|
+
/** Messages received or sent at or after `since`. */
|
|
90
|
+
listMessages(since: Date): AsyncIterable<MessageEvent>;
|
|
91
|
+
/** Delivery status of outbound messages created at or after `since`, when `listMessages` does not carry it. */
|
|
68
92
|
listOutbound(since: Date): AsyncIterable<OutboundStatus>;
|
|
69
93
|
/** Sends once per `idempotencyKey`; a retry with the same key must not send again. */
|
|
70
94
|
send(message: OutboundMessage, idempotencyKey: string): Promise<{ providerId: string }>;
|
|
71
|
-
/** The bytes of an
|
|
95
|
+
/** The bytes of an attachment of a message the provider holds. */
|
|
72
96
|
getAttachment(providerMessageId: string, attachmentId: string): Promise<Uint8Array>;
|
|
73
97
|
}
|
|
74
98
|
|
|
75
|
-
export type ProviderFactory = (config: Record<string, unknown>) => MailProvider;
|
|
99
|
+
export type ProviderFactory = (name: string, config: Record<string, unknown>) => MailProvider;
|
|
76
100
|
|
|
77
101
|
export class WebhookSignatureError extends Error {
|
|
78
102
|
constructor(message: string) {
|
package/src/store.ts
CHANGED
|
@@ -170,12 +170,12 @@ export class Store {
|
|
|
170
170
|
return Object.values((await this.db.get("sessions")) ?? {});
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
-
getSyncCursor(): Promise<string | null> {
|
|
174
|
-
return this.db.get("
|
|
173
|
+
getSyncCursor(provider: string): Promise<string | null> {
|
|
174
|
+
return this.db.get("sync_cursor", provider);
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
-
setSyncCursor(at: string): Promise<unknown> {
|
|
178
|
-
return this.db.set("
|
|
177
|
+
setSyncCursor(provider: string, at: string): Promise<unknown> {
|
|
178
|
+
return this.db.set("sync_cursor", provider, at);
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
181
|
|
package/src/types.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
|
}
|
|
@@ -18,7 +23,8 @@ export interface InboxerConfig {
|
|
|
18
23
|
syncIntervalMin: number;
|
|
19
24
|
threadWindowDays: number;
|
|
20
25
|
mailboxes: Record<string, MailboxConfig>;
|
|
21
|
-
|
|
26
|
+
/** Messaging services by name; the name is the webhook route, `/webhooks/<name>`. */
|
|
27
|
+
providers: Record<string, ProviderConfig>;
|
|
22
28
|
mcp: { tokens: Record<string, string>; maxAttachmentMb: number };
|
|
23
29
|
ui: { cookieSecret: string; loginLinkTtlMin: number; undoSec: number; maxUploadMb: number };
|
|
24
30
|
}
|
|
@@ -26,7 +32,7 @@ export interface InboxerConfig {
|
|
|
26
32
|
export const CATCHALL = "catchall";
|
|
27
33
|
|
|
28
34
|
export type Direction = "in" | "out";
|
|
29
|
-
export type MessageStatus = "received" | "draft" | "sent" | "delivered" | "bounced" | "failed" | "discarded";
|
|
35
|
+
export type MessageStatus = "received" | "draft" | "sent" | "delivered" | "read" | "bounced" | "failed" | "discarded";
|
|
30
36
|
/** Mailbox ids an actor may reach; null reaches every mailbox, the catch-all included. */
|
|
31
37
|
export type Scope = string[] | null;
|
|
32
38
|
export type Actor = { kind: "agent" | "ui" | "cli"; name: string; scope: Scope };
|
|
@@ -87,6 +93,8 @@ export interface Thread {
|
|
|
87
93
|
subject: string;
|
|
88
94
|
norm_subject: string;
|
|
89
95
|
participants: string[];
|
|
96
|
+
/** Display names seen in the From of received messages, by bare address. */
|
|
97
|
+
names: Record<string, string>;
|
|
90
98
|
last_at: string;
|
|
91
99
|
last_direction: Direction;
|
|
92
100
|
has_draft: boolean;
|