@12-apps/messaging 0.0.0-stage → 1.0.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 (57) hide show
  1. package/ADOPTING.md +119 -0
  2. package/README.md +133 -2
  3. package/dist/channel-Cs_vLGl_.d.ts +293 -0
  4. package/dist/chunk-72TDAQUW.js +136 -0
  5. package/dist/chunk-72TDAQUW.js.map +1 -0
  6. package/dist/chunk-7QVYU63E.js +7 -0
  7. package/dist/chunk-7QVYU63E.js.map +1 -0
  8. package/dist/chunk-R3DKM2IV.js +42 -0
  9. package/dist/chunk-R3DKM2IV.js.map +1 -0
  10. package/dist/chunk-Y7MG2UDQ.js +36 -0
  11. package/dist/chunk-Y7MG2UDQ.js.map +1 -0
  12. package/dist/engine-B5EPo66m.d.ts +414 -0
  13. package/dist/index.d.ts +97 -0
  14. package/dist/index.js +988 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/manifest/index.d.ts +36 -0
  17. package/dist/manifest/index.js +14 -0
  18. package/dist/manifest/index.js.map +1 -0
  19. package/dist/manifest/server.d.ts +21 -0
  20. package/dist/manifest/server.js +17 -0
  21. package/dist/manifest/server.js.map +1 -0
  22. package/dist/server/index.d.ts +78 -0
  23. package/dist/server/index.js +15 -0
  24. package/dist/server/index.js.map +1 -0
  25. package/dist/whatsapp/index.d.ts +180 -0
  26. package/dist/whatsapp/index.js +385 -0
  27. package/dist/whatsapp/index.js.map +1 -0
  28. package/package.json +90 -4
  29. package/prisma/messaging.prisma +140 -0
  30. package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
  31. package/src/core/channel.ts +106 -0
  32. package/src/core/connections.ts +67 -0
  33. package/src/core/context.ts +28 -0
  34. package/src/core/engine.ts +64 -0
  35. package/src/core/errors.ts +53 -0
  36. package/src/core/hash.ts +6 -0
  37. package/src/core/inbound.ts +240 -0
  38. package/src/core/inbox.ts +117 -0
  39. package/src/core/memory-store.ts +273 -0
  40. package/src/core/ports.ts +112 -0
  41. package/src/core/prisma-store.ts +354 -0
  42. package/src/core/retention.ts +27 -0
  43. package/src/core/sender.ts +106 -0
  44. package/src/core/store.ts +217 -0
  45. package/src/core/types.ts +189 -0
  46. package/src/index.ts +54 -0
  47. package/src/manifest/index.ts +32 -0
  48. package/src/manifest/server.ts +18 -0
  49. package/src/server/index.ts +22 -0
  50. package/src/server/jobs.ts +99 -0
  51. package/src/server/webhook.ts +92 -0
  52. package/src/whatsapp/graph.ts +136 -0
  53. package/src/whatsapp/index.ts +64 -0
  54. package/src/whatsapp/opt-out.ts +26 -0
  55. package/src/whatsapp/parse.ts +200 -0
  56. package/src/whatsapp/signature.ts +52 -0
  57. package/src/whatsapp/signup.ts +115 -0
@@ -0,0 +1,112 @@
1
+ import type { ChannelAdapter } from "./channel";
2
+ import type { MessagingStore } from "./store";
3
+ import type { ConversationState, ConversationView, MessageView } from "./types";
4
+
5
+ /**
6
+ * What the engine needs FROM its host. The mechanism (the inbox, the tenant
7
+ * resolution, the conversation states, the outbound bookkeeping, the
8
+ * retention) is the engine's and appears nowhere here.
9
+ */
10
+
11
+ /**
12
+ * Sealing and opening a stored credential. The KEY is the host's: the package
13
+ * never sees it. `open` THROWS on a ciphertext that will not open — a row
14
+ * sealed under a rotated key must fail a send loudly, never read as "no
15
+ * credential".
16
+ */
17
+ export interface MessagingSecretsPort {
18
+ seal(plaintext: string): string | Promise<string>;
19
+ open(sealed: string): string | Promise<string>;
20
+ }
21
+
22
+ /**
23
+ * Defer one job run by wire name — the shape of `@12-apps/wiring/ports`'
24
+ * `JobsEnqueuePort`. Never throws. The engine enqueues only its own
25
+ * namespaced job (`messaging.process-delivery`).
26
+ */
27
+ export interface MessagingEnqueuePort {
28
+ enqueue(
29
+ name: string,
30
+ payload: unknown,
31
+ options?: { dedupeKey?: string },
32
+ ): Promise<{ enqueued: boolean; reason?: string }>;
33
+ }
34
+
35
+ /** The clock, so a test or a replay decides what "now" is. */
36
+ export interface MessagingClockPort {
37
+ now(): Date;
38
+ }
39
+
40
+ /** Where the engine says what it did — the wiring `LoggerPort` shape. Never handed a credential. */
41
+ export interface MessagingLogger {
42
+ info(message: string, ...meta: unknown[]): void;
43
+ warn(message: string, ...meta: unknown[]): void;
44
+ error(message: string, ...meta: unknown[]): void;
45
+ }
46
+
47
+ /** What `onInboundMessage` is told: the conversation as it now stands, and the stored message. */
48
+ export interface InboundMessageNotice {
49
+ conversation: ConversationView;
50
+ message: MessageView;
51
+ }
52
+
53
+ /** What a re-opened conversation may become. */
54
+ export type ReopenState = Exclude<ConversationState, "OPTED_OUT">;
55
+
56
+ /** The host's answers to what only it knows about a conversation. All optional. */
57
+ export interface MessagingHooks {
58
+ /**
59
+ * A contact's message was stored. The host's agent (or a person's inbox)
60
+ * picks it up here. Called once per stored message, never for a redelivery,
61
+ * and NOT for a message that opted the contact out — nothing may be said to
62
+ * them. Keep it short (enqueue the host's own job): a throw is logged, never
63
+ * retried, because the message is already stored. Default: nothing.
64
+ */
65
+ onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;
66
+ /**
67
+ * The state a CLOSED or OPTED_OUT conversation re-opens into when its
68
+ * contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`
69
+ * (only the contact's own words put a conversation there): the type refuses
70
+ * it, and an answer that slips through anyway is read as `AGENT`.
71
+ */
72
+ reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;
73
+ }
74
+
75
+ /** Everything a host hands `createMessagingEngine`. */
76
+ export interface MessagingEngineConfig {
77
+ store: MessagingStore;
78
+ /** One per channel — `createWhatsAppAdapter(...)` and, later, its siblings. */
79
+ adapters: readonly ChannelAdapter[];
80
+ secrets: MessagingSecretsPort;
81
+ enqueue: MessagingEnqueuePort;
82
+ clock: MessagingClockPort;
83
+ logger: MessagingLogger;
84
+ hooks?: MessagingHooks;
85
+ /**
86
+ * How long a conversation's text is kept after its LAST message, in
87
+ * milliseconds. Default 12 hours: the conversation lives in the contact's
88
+ * own app, not with the tenant.
89
+ */
90
+ retentionMs?: number;
91
+ /** How many conversations one retention pass purges. Default 500. */
92
+ retentionBatchSize?: number;
93
+ /** How many stored deliveries one reconciliation pass re-runs. Default 50. */
94
+ reconcileBatchSize?: number;
95
+ /** How many times a stored delivery may be processed before it is left for a person. Default 5. */
96
+ maxDeliveryAttempts?: number;
97
+ /**
98
+ * How old an unprocessed delivery must be before the reconciliation sweep
99
+ * re-runs it, so the sweep never races the job the webhook just queued.
100
+ * Default 2 minutes.
101
+ */
102
+ reconcileAfterMs?: number;
103
+ }
104
+
105
+ /** The defaults the config's optional numbers take. */
106
+ export const MESSAGING_DEFAULTS = {
107
+ retentionMs: 12 * 60 * 60 * 1000,
108
+ retentionBatchSize: 500,
109
+ reconcileBatchSize: 50,
110
+ maxDeliveryAttempts: 5,
111
+ reconcileAfterMs: 2 * 60 * 1000,
112
+ } as const;
@@ -0,0 +1,354 @@
1
+ import { DELIVERY_RANK, RECEIPT_COLUMN, type ConversationGuard, type MessagingStore, type StoredConnection } from "./store";
2
+ import type {
3
+ ConnectionView,
4
+ ConversationView,
5
+ DeliveryStatus,
6
+ InboxDeliveryView,
7
+ MessageView,
8
+ ReceiptStatus,
9
+ } from "./types";
10
+
11
+ /**
12
+ * The Prisma delegates the store reads and writes.
13
+ *
14
+ * Structural rather than a `PrismaClient` import: the package must not depend
15
+ * on the host's generated client, and this shape is what any client generated
16
+ * from the shipped partial satisfies. Only the query subset below is used —
17
+ * equality, `in`, `lt`, `lte`, `gte`, `not`, compound unique keys, `increment`,
18
+ * `orderBy`, `take` — which is also what the package's Postgres suite
19
+ * translates, so the suite runs the exact queries a host runs.
20
+ */
21
+ export interface MessagingPrismaDb {
22
+ messagingConnection: Delegate;
23
+ messagingInboxDelivery: Delegate;
24
+ messagingConversation: Delegate;
25
+ messagingMessage: Delegate;
26
+ }
27
+
28
+ interface Delegate {
29
+ findUnique(args: unknown): Promise<unknown>;
30
+ findFirst(args: unknown): Promise<unknown>;
31
+ findMany(args: unknown): Promise<unknown[]>;
32
+ create(args: unknown): Promise<unknown>;
33
+ update(args: unknown): Promise<unknown>;
34
+ updateMany(args: unknown): Promise<{ count: number }>;
35
+ deleteMany(args: unknown): Promise<{ count: number }>;
36
+ }
37
+
38
+ /** Prisma's unique-violation code. */
39
+ const UNIQUE_VIOLATION = "P2002";
40
+ const isUniqueViolation = (error: unknown): boolean => (error as { code?: string } | null)?.code === UNIQUE_VIOLATION;
41
+
42
+ const CONNECTION_VIEW = {
43
+ id: true,
44
+ tenantId: true,
45
+ channel: true,
46
+ externalAccountId: true,
47
+ externalParentId: true,
48
+ displayAddress: true,
49
+ status: true,
50
+ statusReason: true,
51
+ connectedAt: true,
52
+ revokedAt: true,
53
+ } as const;
54
+
55
+ const DELIVERY_VIEW = {
56
+ id: true,
57
+ channel: true,
58
+ rawBody: true,
59
+ state: true,
60
+ attempts: true,
61
+ error: true,
62
+ receivedAt: true,
63
+ processedAt: true,
64
+ } as const;
65
+
66
+ const pickConversation = (row: ConversationView): ConversationView => ({
67
+ id: row.id,
68
+ tenantId: row.tenantId,
69
+ channel: row.channel,
70
+ contactId: row.contactId,
71
+ contactName: row.contactName,
72
+ connectionId: row.connectionId,
73
+ state: row.state,
74
+ lastInboundAt: row.lastInboundAt,
75
+ lastMessageAt: row.lastMessageAt,
76
+ optedOutAt: row.optedOutAt,
77
+ hasText: row.hasText,
78
+ summary: row.summary,
79
+ summaryUpdatedAt: row.summaryUpdatedAt,
80
+ createdAt: row.createdAt,
81
+ });
82
+
83
+ type Client = () => Promise<MessagingPrismaDb>;
84
+
85
+ /** A {@link MessagingStore} over a Prisma client generated from the shipped partial. */
86
+ export function createPrismaMessagingStore(db: MessagingPrismaDb | (() => Promise<MessagingPrismaDb>)): MessagingStore {
87
+ const client: Client = typeof db === "function" ? db : async () => db;
88
+ return {
89
+ ...inboxOperations(client),
90
+ ...connectionOperations(client),
91
+ ...conversationOperations(client),
92
+ ...messageOperations(client),
93
+ purgeExpiredText: (input) => purgeExpiredText(client, input),
94
+ purgeExpiredDeliveries: (input) => purgeExpiredDeliveries(client, input),
95
+ };
96
+ }
97
+
98
+ type InboxOperations = Pick<
99
+ MessagingStore,
100
+ "recordDelivery" | "getDelivery" | "settleDelivery" | "listRetryableDeliveries"
101
+ >;
102
+
103
+ function inboxOperations(client: Client): InboxOperations {
104
+ return {
105
+ async recordDelivery({ channel, bodyHash, rawBody, receivedAt }) {
106
+ const delegate = (await client()).messagingInboxDelivery;
107
+ const key = { channel_bodyHash: { channel, bodyHash } };
108
+ const existing = (await delegate.findUnique({ where: key, select: { id: true } })) as { id: string } | null;
109
+ if (existing) return { id: existing.id, fresh: false };
110
+ try {
111
+ const row = (await delegate.create({
112
+ data: { channel, bodyHash, rawBody, receivedAt },
113
+ select: { id: true },
114
+ })) as { id: string };
115
+ return { id: row.id, fresh: true };
116
+ } catch (error) {
117
+ // Two simultaneous redeliveries lose the check-then-insert race; the
118
+ // unique index is the real guard, and losing it is a redelivery.
119
+ if (!isUniqueViolation(error)) throw error;
120
+ const raced = (await delegate.findUnique({ where: key, select: { id: true } })) as { id: string };
121
+ return { id: raced.id, fresh: false };
122
+ }
123
+ },
124
+ async getDelivery(id) {
125
+ return ((await (await client()).messagingInboxDelivery.findUnique({
126
+ where: { id },
127
+ select: DELIVERY_VIEW,
128
+ })) as InboxDeliveryView | null) ?? null;
129
+ },
130
+ async settleDelivery(id, { state, error, at }) {
131
+ await (await client()).messagingInboxDelivery.updateMany({
132
+ where: { id },
133
+ data: { state, error, processedAt: at, attempts: { increment: 1 } },
134
+ });
135
+ },
136
+ async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {
137
+ return (await (await client()).messagingInboxDelivery.findMany({
138
+ where: { state: { in: ["PENDING", "FAILED"] }, attempts: { lt: maxAttempts }, receivedAt: { lt: receivedBefore } },
139
+ orderBy: { receivedAt: "asc" },
140
+ take,
141
+ select: DELIVERY_VIEW,
142
+ })) as InboxDeliveryView[];
143
+ },
144
+ };
145
+ }
146
+
147
+ type ConnectionOperations = Pick<
148
+ MessagingStore,
149
+ "findConnectionByAccount" | "getConnection" | "listConnections" | "saveConnection" | "setConnectionStatus"
150
+ >;
151
+
152
+ function connectionOperations(client: Client): ConnectionOperations {
153
+ const findConnectionByAccount = async (channel: string, externalAccountId: string) =>
154
+ ((await (await client()).messagingConnection.findUnique({
155
+ where: { channel_externalAccountId: { channel, externalAccountId } },
156
+ })) as StoredConnection | null) ?? null;
157
+ return {
158
+ findConnectionByAccount,
159
+ async getConnection(tenantId, id) {
160
+ return ((await (await client()).messagingConnection.findFirst({ where: { id, tenantId } })) as StoredConnection | null) ?? null;
161
+ },
162
+ async listConnections(tenantId) {
163
+ return (await (await client()).messagingConnection.findMany({
164
+ where: { tenantId },
165
+ orderBy: { connectedAt: "asc" },
166
+ select: CONNECTION_VIEW,
167
+ })) as ConnectionView[];
168
+ },
169
+ async saveConnection(input) {
170
+ const delegate = (await client()).messagingConnection;
171
+ const data = { ...input, status: "CONNECTED", statusReason: null, revokedAt: null };
172
+ // Twice at most: a lost insert race turns into an update of the winner's row.
173
+ for (let attempt = 0; attempt < 2; attempt += 1) {
174
+ const existing = await findConnectionByAccount(input.channel, input.externalAccountId);
175
+ if (!existing) {
176
+ try {
177
+ return (await delegate.create({ data, select: CONNECTION_VIEW })) as ConnectionView;
178
+ } catch (error) {
179
+ if (!isUniqueViolation(error)) throw error;
180
+ continue;
181
+ }
182
+ }
183
+ // The takeover is conditional in the write itself: the tenant's own row, or a REVOKED one.
184
+ const where = existing.tenantId === input.tenantId ? { id: existing.id, tenantId: input.tenantId } : { id: existing.id, status: "REVOKED" };
185
+ const updated = await delegate.updateMany({ where, data });
186
+ if (updated.count === 0) return null;
187
+ return (await delegate.findUnique({ where: { id: existing.id }, select: CONNECTION_VIEW })) as ConnectionView;
188
+ }
189
+ return null;
190
+ },
191
+ async setConnectionStatus(tenantId, id, patch) {
192
+ const result = await (await client()).messagingConnection.updateMany({ where: { id, tenantId }, data: patch });
193
+ return result.count > 0;
194
+ },
195
+ };
196
+ }
197
+
198
+ type ConversationOperations = Pick<
199
+ MessagingStore,
200
+ "findConversation" | "getConversation" | "createConversation" | "updateConversation"
201
+ >;
202
+
203
+ function conversationOperations(client: Client): ConversationOperations {
204
+ const findConversation = async (tenantId: string, channel: string, contactId: string) => {
205
+ const row = (await (await client()).messagingConversation.findUnique({
206
+ where: { tenantId_channel_contactId: { tenantId, channel, contactId } },
207
+ })) as ConversationView | null;
208
+ return row ? pickConversation(row) : null;
209
+ };
210
+ return {
211
+ findConversation,
212
+ async getConversation(tenantId, id) {
213
+ const row = (await (await client()).messagingConversation.findFirst({ where: { id, tenantId } })) as ConversationView | null;
214
+ return row ? pickConversation(row) : null;
215
+ },
216
+ async createConversation(input) {
217
+ try {
218
+ return pickConversation((await (await client()).messagingConversation.create({ data: input })) as ConversationView);
219
+ } catch (error) {
220
+ if (!isUniqueViolation(error)) throw error;
221
+ const raced = await findConversation(input.tenantId, input.channel, input.contactId);
222
+ if (!raced) throw error;
223
+ return raced;
224
+ }
225
+ },
226
+ async updateConversation(tenantId, id, patch, guard) {
227
+ const delegate = (await client()).messagingConversation;
228
+ const result = await delegate.updateMany({ where: { id, tenantId, ...guardWhere(guard) }, data: patch });
229
+ if (result.count === 0) return null;
230
+ return pickConversation((await delegate.findUnique({ where: { id } })) as ConversationView);
231
+ },
232
+ };
233
+ }
234
+
235
+ /** A guard as the `where` clause of the one `updateMany` that makes the write a compare-and-set. */
236
+ function guardWhere(guard: ConversationGuard | undefined): Record<string, unknown> {
237
+ if (!guard) return {};
238
+ const { state, stateNot, lastInboundAt, lastMessageAt, optedOutAt } = guard;
239
+ return {
240
+ ...(state !== undefined ? { state } : {}),
241
+ ...(stateNot !== undefined ? { state: { not: stateNot } } : {}),
242
+ ...(lastInboundAt !== undefined ? { lastInboundAt } : {}),
243
+ ...(lastMessageAt !== undefined ? { lastMessageAt } : {}),
244
+ ...(optedOutAt !== undefined ? { optedOutAt } : {}),
245
+ };
246
+ }
247
+
248
+ type MessageOperations = Pick<
249
+ MessagingStore,
250
+ "findMessageByExternalId" | "insertMessage" | "updateMessage" | "listMessages" | "applyReceipt"
251
+ >;
252
+
253
+ function messageOperations(client: Client): MessageOperations {
254
+ const findMessageByExternalId = async (channel: string, externalId: string) =>
255
+ ((await (await client()).messagingMessage.findUnique({
256
+ where: { channel_externalId: { channel, externalId } },
257
+ })) as MessageView | null) ?? null;
258
+ return {
259
+ findMessageByExternalId,
260
+ async insertMessage(input) {
261
+ try {
262
+ return { created: true, message: (await (await client()).messagingMessage.create({ data: input })) as MessageView };
263
+ } catch (error) {
264
+ if (!isUniqueViolation(error) || input.externalId === null) throw error;
265
+ const existing = await findMessageByExternalId(input.channel, input.externalId);
266
+ if (!existing) throw error;
267
+ return { created: false, message: existing };
268
+ }
269
+ },
270
+ async updateMessage(tenantId, id, patch) {
271
+ const delegate = (await client()).messagingMessage;
272
+ const result = await delegate.updateMany({ where: { id, tenantId }, data: patch });
273
+ if (result.count === 0) return null;
274
+ return (await delegate.findUnique({ where: { id } })) as MessageView;
275
+ },
276
+ async listMessages(tenantId, conversationId) {
277
+ return (await (await client()).messagingMessage.findMany({
278
+ where: { tenantId, conversationId },
279
+ orderBy: { createdAt: "asc" },
280
+ })) as MessageView[];
281
+ },
282
+ applyReceipt: (input) => applyReceipt(client, input),
283
+ };
284
+ }
285
+
286
+ async function applyReceipt(client: Client, input: Parameters<MessagingStore["applyReceipt"]>[0]): Promise<boolean> {
287
+ const { tenantId, channel, externalId, status, at, error } = input;
288
+ const delegate = (await client()).messagingMessage;
289
+ const scope = { tenantId, channel, externalId, direction: "OUTBOUND" };
290
+ const found = (await delegate.findFirst({ where: scope, select: { id: true } })) as { id: string } | null;
291
+ if (!found) return false;
292
+ const column = RECEIPT_COLUMN[status];
293
+ // The timestamp column is written once: a second identical receipt matches
294
+ // nothing. Then the status moves only forward, in a second guarded write,
295
+ // so a late SENT never overwrites a READ.
296
+ await delegate.updateMany({
297
+ where: { id: found.id, [column]: null },
298
+ data: { [column]: at, ...(error !== null ? { error } : {}) },
299
+ });
300
+ await delegate.updateMany({
301
+ where: { id: found.id, deliveryStatus: { in: statusesBelow(status) } },
302
+ data: { deliveryStatus: status },
303
+ });
304
+ return true;
305
+ }
306
+
307
+ async function purgeExpiredText(
308
+ client: Client,
309
+ { cutoff, take }: { cutoff: Date; take: number },
310
+ ): Promise<{ conversations: number; messages: number }> {
311
+ const db = await client();
312
+ const due = (await db.messagingConversation.findMany({
313
+ where: { hasText: true, lastMessageAt: { lt: cutoff } },
314
+ orderBy: { lastMessageAt: "asc" },
315
+ take,
316
+ select: { id: true },
317
+ })) as { id: string }[];
318
+ if (due.length === 0) return { conversations: 0, messages: 0 };
319
+ const ids = due.map((row) => row.id);
320
+ const purged = await db.messagingMessage.updateMany({
321
+ where: { conversationId: { in: ids }, createdAt: { lte: cutoff } },
322
+ data: { body: null, options: null, transcript: null },
323
+ });
324
+ // Guarded on the same predicate: a conversation that took a message since
325
+ // the read above keeps its flag, and its new text.
326
+ await db.messagingConversation.updateMany({
327
+ where: { id: { in: ids }, lastMessageAt: { lt: cutoff } },
328
+ data: { hasText: false },
329
+ });
330
+ return { conversations: due.length, messages: purged.count };
331
+ }
332
+
333
+ async function purgeExpiredDeliveries(
334
+ client: Client,
335
+ { cutoff, maxAttempts, take }: { cutoff: Date; maxAttempts: number; take: number },
336
+ ): Promise<number> {
337
+ const delegate = (await client()).messagingInboxDelivery;
338
+ const batches = [
339
+ { state: "PROCESSED", receivedAt: { lt: cutoff } },
340
+ { state: "FAILED", receivedAt: { lt: cutoff }, attempts: { gte: maxAttempts } },
341
+ ];
342
+ let deleted = 0;
343
+ for (const where of batches) {
344
+ const due = (await delegate.findMany({ where, orderBy: { receivedAt: "asc" }, take, select: { id: true } })) as { id: string }[];
345
+ if (due.length === 0) continue;
346
+ deleted += (await delegate.deleteMany({ where: { id: { in: due.map((row) => row.id) } } })).count;
347
+ }
348
+ return deleted;
349
+ }
350
+
351
+ /** Every status a receipt may move a message forward from. */
352
+ function statusesBelow(status: ReceiptStatus): DeliveryStatus[] {
353
+ return (Object.keys(DELIVERY_RANK) as DeliveryStatus[]).filter((candidate) => DELIVERY_RANK[candidate] < DELIVERY_RANK[status]);
354
+ }
@@ -0,0 +1,27 @@
1
+ import type { EngineContext } from "./context";
2
+
3
+ /**
4
+ * The retention sweep. A conversation's TEXT lives only while the
5
+ * conversation does: `retentionMs` (default 12 h) after its LAST message,
6
+ * every message's body, choices and transcript are deleted. The conversation
7
+ * row, its state and its structured summary stay — they are what the next
8
+ * conversation with the same contact starts from.
9
+ *
10
+ * The same cutoff deletes the raw inbox rows (Meta's whole payload: the text,
11
+ * the phone number, the profile name): the PROCESSED ones, and the FAILED ones
12
+ * nothing will retry any more. What stays of a delivery is nothing; dedupe
13
+ * lives on the message row's `(channel, external_id)`, which outlives the text.
14
+ *
15
+ * One indexed query finds the due conversations across every tenant (never a
16
+ * walk over tenants); a pass that fills its batch says so, and the next tick
17
+ * takes the rest.
18
+ */
19
+ export async function sweepRetention(
20
+ ctx: EngineContext,
21
+ ): Promise<{ conversations: number; messages: number; deliveries: number; more: boolean }> {
22
+ const { store, clock, retentionMs, retentionBatchSize, maxDeliveryAttempts } = ctx.config;
23
+ const cutoff = new Date(clock.now().getTime() - retentionMs);
24
+ const text = await store.purgeExpiredText({ cutoff, take: retentionBatchSize });
25
+ const deliveries = await store.purgeExpiredDeliveries({ cutoff, maxAttempts: maxDeliveryAttempts, take: retentionBatchSize });
26
+ return { ...text, deliveries, more: text.conversations === retentionBatchSize || deliveries >= retentionBatchSize };
27
+ }
@@ -0,0 +1,106 @@
1
+ import { ChannelSendFailure } from "./channel";
2
+ import type { EngineContext } from "./context";
3
+ import { errorText, MessagingSendError } from "./errors";
4
+ import type { StoredConnection } from "./store";
5
+ import type { ConversationView, MessageView, OutboundContent } from "./types";
6
+
7
+ /** Who is sending: the host's agent, or a person on the tenant's staff. */
8
+ export type SendAuthor = { kind: "AGENT" } | { kind: "STAFF"; staffUserId?: string | null };
9
+
10
+ export interface SendInput {
11
+ tenantId: string;
12
+ conversationId: string;
13
+ content: OutboundContent;
14
+ author: SendAuthor;
15
+ }
16
+
17
+ /**
18
+ * Send one message into a conversation.
19
+ *
20
+ * Refused, with nothing recorded, when the contact opted out, when the
21
+ * channel's policy says the window is closed, or when the conversation's
22
+ * connection is not connected. Otherwise the outbound row is recorded
23
+ * PENDING BEFORE the channel is called — a crash mid-call leaves evidence, not
24
+ * silence — then stamped ACCEPTED with the channel's id, or FAILED with the
25
+ * channel's error (and the error is thrown).
26
+ */
27
+ export async function sendMessage(ctx: EngineContext, input: SendInput): Promise<MessageView> {
28
+ const { store, clock } = ctx.config;
29
+ const conversation = await store.getConversation(input.tenantId, input.conversationId);
30
+ if (!conversation) throw new MessagingSendError("NOT_FOUND", `no conversation ${input.conversationId}`);
31
+ const { adapter, connection } = await admit(ctx, conversation);
32
+
33
+ const now = clock.now();
34
+ const recorded = await store.insertMessage({
35
+ conversationId: conversation.id,
36
+ tenantId: conversation.tenantId,
37
+ channel: conversation.channel,
38
+ direction: "OUTBOUND",
39
+ kind: input.content.kind === "TEXT" ? "TEXT" : "INTERACTIVE",
40
+ body: input.content.text,
41
+ options: optionsOf(input.content),
42
+ attachmentRef: null,
43
+ externalId: null,
44
+ deliveryStatus: "PENDING",
45
+ authorKind: input.author.kind,
46
+ staffUserId: input.author.kind === "STAFF" ? (input.author.staffUserId ?? null) : null,
47
+ createdAt: now,
48
+ });
49
+ await store.updateConversation(conversation.tenantId, conversation.id, {
50
+ lastMessageAt: now,
51
+ hasText: true,
52
+ });
53
+
54
+ let externalId: string;
55
+ try {
56
+ if (connection.credentialSealed === null) throw new Error("the connection holds no credential");
57
+ const credential = await ctx.config.secrets.open(connection.credentialSealed);
58
+ ({ externalId } = await adapter.send({
59
+ credential,
60
+ accountId: connection.externalAccountId,
61
+ to: conversation.contactId,
62
+ content: input.content,
63
+ }));
64
+ } catch (error) {
65
+ const reason = error instanceof ChannelSendFailure ? `${error.code}: ${error.message}` : errorText(error);
66
+ await store.updateMessage(conversation.tenantId, recorded.message.id, {
67
+ deliveryStatus: "FAILED",
68
+ error: reason.slice(0, 500),
69
+ failedAt: clock.now(),
70
+ });
71
+ throw new MessagingSendError("CHANNEL_FAILED", reason, recorded.message.id);
72
+ }
73
+ const accepted = await store.updateMessage(conversation.tenantId, recorded.message.id, {
74
+ externalId,
75
+ deliveryStatus: "ACCEPTED",
76
+ });
77
+ return accepted ?? recorded.message;
78
+ }
79
+
80
+ /** The checks a send must pass before anything is written. */
81
+ async function admit(ctx: EngineContext, conversation: ConversationView) {
82
+ if (conversation.state === "OPTED_OUT") {
83
+ throw new MessagingSendError("OPTED_OUT", `conversation ${conversation.id} opted out`);
84
+ }
85
+ const adapter = ctx.adapters.get(conversation.channel);
86
+ if (!adapter) throw new MessagingSendError("UNKNOWN_CHANNEL", `no adapter for channel "${conversation.channel}"`);
87
+ const verdict = adapter.policy.check({ lastInboundAt: conversation.lastInboundAt, now: ctx.config.clock.now() });
88
+ if (!verdict.allowed) {
89
+ throw new MessagingSendError(verdict.reason, `conversation ${conversation.id}: the channel's window is closed`);
90
+ }
91
+ const connection: StoredConnection | null = await ctx.config.store.getConnection(
92
+ conversation.tenantId,
93
+ conversation.connectionId,
94
+ );
95
+ if (!connection || connection.status !== "CONNECTED") {
96
+ throw new MessagingSendError("NOT_CONNECTED", `conversation ${conversation.id}: its connection is not connected`);
97
+ }
98
+ return { adapter, connection };
99
+ }
100
+
101
+ /** An interactive message's choices, kept as JSON text beside its prompt. */
102
+ function optionsOf(content: OutboundContent): string | null {
103
+ if (content.kind === "BUTTONS") return JSON.stringify({ buttons: content.buttons });
104
+ if (content.kind === "LIST") return JSON.stringify({ buttonLabel: content.buttonLabel, sections: content.sections });
105
+ return null;
106
+ }