@12-apps/messaging 1.0.0 → 1.1.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 CHANGED
@@ -38,6 +38,7 @@ messaging.process-delivery (a job)
38
38
  ├─ parse the stored bytes through the channel's adapter
39
39
  ├─ per event, resolve the tenant: the event's account against the connections
40
40
  │ unknown, revoked or in error ............. dropped (the edge already said 200)
41
+ │ unknown only, with hooks.onUnclaimedEvents handed to the host (see below)
41
42
  ├─ message → create or re-open the conversation, update lastInboundAt,
42
43
  │ store the message (a known channel id is a no-op),
43
44
  │ then the host's onInboundMessage({ conversation, message })
@@ -50,6 +51,29 @@ messaging.process-delivery (a job)
50
51
  The tenant is never taken from the URL: a channel like WhatsApp posts every
51
52
  connected account's events to the one callback configured on the app.
52
53
 
54
+ **A number nobody connected.** A host whose OWN number lives on the same app
55
+ (a platform notification number: its confirmation replies, its opt-outs, its
56
+ delivery receipts) passes `hooks.onUnclaimedEvents(channel, events)`. It is
57
+ handed, once per processed delivery, the parsed events of every account no
58
+ connection row names: already signature-checked and persisted, and stored
59
+ nowhere here. A revoked or errored account is a tenant's and is never handed
60
+ over. A throw settles the delivery `FAILED` and the reconciliation sweep runs
61
+ it again, so the handler is idempotent on the provider's message id. Without
62
+ the hook those events are dropped, as before.
63
+
64
+ **Filter on your OWN account id.** The hook is handed every account the app
65
+ posts for that no connection names — not only the platform's number. A host
66
+ that wants its own number's events keeps `event.accountId === <its phone
67
+ number id>` and drops the rest; anything else would act on a stranger's
68
+ messages.
69
+
70
+ **Meta's `wa_id` is not always the stored number.** For many Brazilian mobiles
71
+ Meta reports the sender WITHOUT the 9th digit (`55 11 8765-4321` for
72
+ `+55 11 98765-4321`). A host matching a reply to a stored number (a consent
73
+ reply, `@12-apps/notifications`' `applyInbound`) normalises `from` first: for a
74
+ `55` number with a 2-digit area code and an 8-digit subscriber starting 6–9,
75
+ insert the `9` — or the reply misses the account that sent it.
76
+
53
77
  **Opt-out.** On WhatsApp, a message that is exactly `PARAR`, `SAIR`, `STOP` or
54
78
  `CANCELAR` — case- and accent-insensitive, ignoring punctuation and emoji
55
79
  around it ("PARAR.", "Parar!") — opts the contact out, as does Meta's own
@@ -1,4 +1,4 @@
1
- import { g as ConversationState, h as ConversationSummary, f as ConnectionView, i as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, e as ConnectionStatus, C as ConversationView, M as MessageView, l as MessageDirection, m as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, o as OutboundContent } from './channel-Cs_vLGl_.js';
1
+ import { g as ConversationState, h as ConversationSummary, f as ConnectionView, i as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, e as ConnectionStatus, C as ConversationView, M as MessageView, l as MessageDirection, m as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, o as OutboundContent } from './channel-Cs_vLGl_.js';
2
2
 
3
3
  /**
4
4
  * THE STORE PORT: every read and write the engine makes, as named operations.
@@ -249,6 +249,23 @@ interface MessagingHooks {
249
249
  * it, and an answer that slips through anyway is read as `AGENT`.
250
250
  */
251
251
  reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;
252
+ /**
253
+ * Events of a channel account NOBODY connected: a message, an opt-out or a
254
+ * delivery receipt of a number the host itself owns on the same app (its
255
+ * platform notification number, typically), which no tenant row resolves.
256
+ *
257
+ * Without this hook they are dropped, exactly as before. With it, the host is
258
+ * handed them once per processed delivery: already signature-checked,
259
+ * persisted and parsed, and still stored nowhere here (no conversation, no
260
+ * message). An event of a CONNECTED, revoked or errored tenant account is
261
+ * never handed over: a tenant's traffic is the tenant's, and the host's
262
+ * platform path must not see it.
263
+ *
264
+ * A throw settles the delivery FAILED, so the reconciliation sweep runs it
265
+ * again: the host's handler must be idempotent on the provider's message id.
266
+ * Default: nothing.
267
+ */
268
+ onUnclaimedEvents?(channel: string, events: NormalizedEvent[]): Promise<void> | void;
252
269
  }
253
270
  /** Everything a host hands `createMessagingEngine`. */
254
271
  interface MessagingEngineConfig {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as StoredConnection, M as MessagingStore } from './engine-B5EPo66m.js';
2
- export { C as ConnectInput, a as ConversationPatch, D as DeliveryOutcome, E as EventOutcome, I as InboundMessageNotice, b as MESSAGING_DEFAULTS, c as MessagePatch, d as MessagingClockPort, e as MessagingEngine, f as MessagingEngineConfig, g as MessagingEnqueuePort, h as MessagingHooks, i as MessagingLogger, j as MessagingSecretsPort, N as NewConnection, k as NewConversation, l as NewMessage, P as PROCESS_DELIVERY_JOB, m as SendAuthor, n as SendInput, o as createMessagingEngine } from './engine-B5EPo66m.js';
1
+ import { S as StoredConnection, M as MessagingStore } from './engine-DTnp2zUL.js';
2
+ export { C as ConnectInput, a as ConversationPatch, D as DeliveryOutcome, E as EventOutcome, I as InboundMessageNotice, b as MESSAGING_DEFAULTS, c as MessagePatch, d as MessagingClockPort, e as MessagingEngine, f as MessagingEngineConfig, g as MessagingEnqueuePort, h as MessagingHooks, i as MessagingLogger, j as MessagingSecretsPort, N as NewConnection, k as NewConversation, l as NewMessage, P as PROCESS_DELIVERY_JOB, m as SendAuthor, n as SendInput, o as createMessagingEngine } from './engine-DTnp2zUL.js';
3
3
  import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-Cs_vLGl_.js';
4
4
  export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelSendFailure, d as ChannelSendInput, e as ConnectionStatus, f as ConnectionView, g as ConversationState, h as ConversationSummary, D as DeliveryState, i as DeliveryStatus, H as HandshakeAnswer, j as InboundContent, k as InboundMessageEvent, l as MessageDirection, m as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, n as OptOutEvent, o as OutboundContent, R as ReceiptStatus, S as SendPolicy, p as SendPolicyContext, q as SendPolicyVerdict, r as StatusEvent, s as isWindowOpen, t as serviceWindowPolicy } from './channel-Cs_vLGl_.js';
5
5
 
package/dist/index.js CHANGED
@@ -285,6 +285,7 @@ async function processDelivery(ctx, deliveryId) {
285
285
  try {
286
286
  const outcomes = [];
287
287
  for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));
288
+ await handOverUnclaimed(ctx, row.channel, events, outcomes);
288
289
  const unapplied = outcomes.filter((outcome) => outcome.kind === "receipt" && !outcome.applied).length;
289
290
  if (unapplied > 0) {
290
291
  const error = `${unapplied} receipt(s) for a message not stored yet`;
@@ -300,6 +301,16 @@ async function processDelivery(ctx, deliveryId) {
300
301
  }
301
302
  }
302
303
  __name(processDelivery, "processDelivery");
304
+ async function handOverUnclaimed(ctx, channel, events, outcomes) {
305
+ const hook = ctx.config.hooks?.onUnclaimedEvents;
306
+ if (!hook) return;
307
+ const unclaimed = events.filter((_, index) => {
308
+ const outcome = outcomes[index];
309
+ return outcome?.kind === "dropped" && outcome.reason === "unknown-account";
310
+ });
311
+ if (unclaimed.length > 0) await hook(channel, unclaimed);
312
+ }
313
+ __name(handOverUnclaimed, "handOverUnclaimed");
303
314
  async function reconcileInbox(ctx) {
304
315
  const { store, clock, logger, reconcileAfterMs, maxDeliveryAttempts, reconcileBatchSize } = ctx.config;
305
316
  const due = await store.listRetryableDeliveries({
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/connections.ts","../src/core/ports.ts","../src/core/context.ts","../src/core/hash.ts","../src/core/inbound.ts","../src/core/inbox.ts","../src/core/retention.ts","../src/core/sender.ts","../src/core/engine.ts","../src/core/memory-store.ts","../src/core/store.ts","../src/core/prisma-store.ts"],"sourcesContent":["import type { EngineContext } from \"./context\";\nimport { MessagingConnectError } from \"./errors\";\nimport type { ConnectionView } from \"./types\";\n\nexport interface ConnectInput {\n tenantId: string;\n channel: string;\n /** The channel's id for the account (WhatsApp's phone_number_id). */\n externalAccountId: string;\n /** The channel's parent account (WhatsApp's WABA id), when it has one. */\n externalParentId?: string | null;\n displayAddress: string;\n /** The credential in clear (a business token). Sealed here; never stored, returned or logged in clear. */\n credential: string;\n}\n\n/**\n * Connect an account to a tenant. The account is UNIQUE across tenants: one\n * held by another tenant (connected, or in error) is refused\n * (`ACCOUNT_TAKEN`); only one that tenant revoked may be connected by another,\n * who proves it through the channel's own signup. Re-connecting one's own\n * account replaces its credential and clears its error.\n */\nexport async function connect(ctx: EngineContext, input: ConnectInput): Promise<ConnectionView> {\n const { store, secrets, clock } = ctx.config;\n if (!ctx.adapters.has(input.channel)) {\n throw new MessagingConnectError(\"UNKNOWN_CHANNEL\", `no adapter for channel \"${input.channel}\"`);\n }\n const existing = await store.findConnectionByAccount(input.channel, input.externalAccountId);\n if (existing && existing.tenantId !== input.tenantId && existing.status !== \"REVOKED\") {\n throw new MessagingConnectError(\"ACCOUNT_TAKEN\", `account ${input.externalAccountId} is held by another tenant`);\n }\n const saved = await store.saveConnection({\n tenantId: input.tenantId,\n channel: input.channel,\n externalAccountId: input.externalAccountId,\n externalParentId: input.externalParentId ?? null,\n displayAddress: input.displayAddress,\n credentialSealed: await secrets.seal(input.credential),\n connectedAt: clock.now(),\n });\n // The store's write is conditional, so a connect that lost a race for the account is refused here too.\n if (!saved) throw new MessagingConnectError(\"ACCOUNT_TAKEN\", `account ${input.externalAccountId} is held by another tenant`);\n return saved;\n}\n\n/**\n * Revoke a tenant's connection: inbound traffic for it is dropped, sends are\n * refused, and the sealed credential is cleared — disconnecting removes the token.\n */\nexport async function revoke(ctx: EngineContext, tenantId: string, connectionId: string, reason: string | null = null) {\n return ctx.config.store.setConnectionStatus(tenantId, connectionId, {\n status: \"REVOKED\",\n statusReason: reason,\n revokedAt: ctx.config.clock.now(),\n credentialSealed: null,\n });\n}\n\n/** Mark a connection in error (a token the channel rejects): treated as revoked until re-connected. */\nexport async function markError(ctx: EngineContext, tenantId: string, connectionId: string, reason: string) {\n return ctx.config.store.setConnectionStatus(tenantId, connectionId, {\n status: \"ERROR\",\n statusReason: reason.slice(0, 500),\n revokedAt: null,\n });\n}\n","import type { ChannelAdapter } from \"./channel\";\nimport type { MessagingStore } from \"./store\";\nimport type { ConversationState, ConversationView, MessageView } from \"./types\";\n\n/**\n * What the engine needs FROM its host. The mechanism (the inbox, the tenant\n * resolution, the conversation states, the outbound bookkeeping, the\n * retention) is the engine's and appears nowhere here.\n */\n\n/**\n * Sealing and opening a stored credential. The KEY is the host's: the package\n * never sees it. `open` THROWS on a ciphertext that will not open — a row\n * sealed under a rotated key must fail a send loudly, never read as \"no\n * credential\".\n */\nexport interface MessagingSecretsPort {\n seal(plaintext: string): string | Promise<string>;\n open(sealed: string): string | Promise<string>;\n}\n\n/**\n * Defer one job run by wire name — the shape of `@12-apps/wiring/ports`'\n * `JobsEnqueuePort`. Never throws. The engine enqueues only its own\n * namespaced job (`messaging.process-delivery`).\n */\nexport interface MessagingEnqueuePort {\n enqueue(\n name: string,\n payload: unknown,\n options?: { dedupeKey?: string },\n ): Promise<{ enqueued: boolean; reason?: string }>;\n}\n\n/** The clock, so a test or a replay decides what \"now\" is. */\nexport interface MessagingClockPort {\n now(): Date;\n}\n\n/** Where the engine says what it did — the wiring `LoggerPort` shape. Never handed a credential. */\nexport interface MessagingLogger {\n info(message: string, ...meta: unknown[]): void;\n warn(message: string, ...meta: unknown[]): void;\n error(message: string, ...meta: unknown[]): void;\n}\n\n/** What `onInboundMessage` is told: the conversation as it now stands, and the stored message. */\nexport interface InboundMessageNotice {\n conversation: ConversationView;\n message: MessageView;\n}\n\n/** What a re-opened conversation may become. */\nexport type ReopenState = Exclude<ConversationState, \"OPTED_OUT\">;\n\n/** The host's answers to what only it knows about a conversation. All optional. */\nexport interface MessagingHooks {\n /**\n * A contact's message was stored. The host's agent (or a person's inbox)\n * picks it up here. Called once per stored message, never for a redelivery,\n * and NOT for a message that opted the contact out — nothing may be said to\n * them. Keep it short (enqueue the host's own job): a throw is logged, never\n * retried, because the message is already stored. Default: nothing.\n */\n onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;\n /**\n * The state a CLOSED or OPTED_OUT conversation re-opens into when its\n * contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`\n * (only the contact's own words put a conversation there): the type refuses\n * it, and an answer that slips through anyway is read as `AGENT`.\n */\n reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;\n}\n\n/** Everything a host hands `createMessagingEngine`. */\nexport interface MessagingEngineConfig {\n store: MessagingStore;\n /** One per channel — `createWhatsAppAdapter(...)` and, later, its siblings. */\n adapters: readonly ChannelAdapter[];\n secrets: MessagingSecretsPort;\n enqueue: MessagingEnqueuePort;\n clock: MessagingClockPort;\n logger: MessagingLogger;\n hooks?: MessagingHooks;\n /**\n * How long a conversation's text is kept after its LAST message, in\n * milliseconds. Default 12 hours: the conversation lives in the contact's\n * own app, not with the tenant.\n */\n retentionMs?: number;\n /** How many conversations one retention pass purges. Default 500. */\n retentionBatchSize?: number;\n /** How many stored deliveries one reconciliation pass re-runs. Default 50. */\n reconcileBatchSize?: number;\n /** How many times a stored delivery may be processed before it is left for a person. Default 5. */\n maxDeliveryAttempts?: number;\n /**\n * How old an unprocessed delivery must be before the reconciliation sweep\n * re-runs it, so the sweep never races the job the webhook just queued.\n * Default 2 minutes.\n */\n reconcileAfterMs?: number;\n}\n\n/** The defaults the config's optional numbers take. */\nexport const MESSAGING_DEFAULTS = {\n retentionMs: 12 * 60 * 60 * 1000,\n retentionBatchSize: 500,\n reconcileBatchSize: 50,\n maxDeliveryAttempts: 5,\n reconcileAfterMs: 2 * 60 * 1000,\n} as const;\n","import type { ChannelAdapter } from \"./channel\";\nimport { MESSAGING_DEFAULTS, type MessagingEngineConfig } from \"./ports\";\n\n/** The config with every default applied, and the adapters keyed by channel. */\nexport interface EngineContext {\n config: MessagingEngineConfig & Required<Pick<MessagingEngineConfig, keyof typeof MESSAGING_DEFAULTS>>;\n adapters: ReadonlyMap<string, ChannelAdapter>;\n}\n\n/** Build the context; a channel mounted twice is a configuration error. */\nexport function engineContext(config: MessagingEngineConfig): EngineContext {\n const adapters = new Map<string, ChannelAdapter>();\n for (const adapter of config.adapters) {\n if (adapters.has(adapter.kind)) throw new Error(`messaging: channel \"${adapter.kind}\" is mounted twice`);\n adapters.set(adapter.kind, adapter);\n }\n return {\n config: {\n ...config,\n retentionMs: config.retentionMs ?? MESSAGING_DEFAULTS.retentionMs,\n retentionBatchSize: config.retentionBatchSize ?? MESSAGING_DEFAULTS.retentionBatchSize,\n reconcileBatchSize: config.reconcileBatchSize ?? MESSAGING_DEFAULTS.reconcileBatchSize,\n maxDeliveryAttempts: config.maxDeliveryAttempts ?? MESSAGING_DEFAULTS.maxDeliveryAttempts,\n reconcileAfterMs: config.reconcileAfterMs ?? MESSAGING_DEFAULTS.reconcileAfterMs,\n },\n adapters,\n };\n}\n","import { createHash } from \"node:crypto\";\n\n/** The inbox key of a raw body: its SHA-256, hex. A redelivery is the same bytes, so the same key. */\nexport function bodyHash(rawBody: string): string {\n return createHash(\"sha256\").update(rawBody, \"utf8\").digest(\"hex\");\n}\n","import type { EngineContext } from \"./context\";\nimport { errorText } from \"./errors\";\nimport type { StoredConnection } from \"./store\";\nimport type {\n ConversationState,\n ConversationView,\n InboundContent,\n InboundMessageEvent,\n MessageView,\n NormalizedEvent,\n OptOutEvent,\n} from \"./types\";\n\n/**\n * One normalized event, applied. The tenant is resolved HERE, from the\n * event's channel account against the connections — never from the URL, which\n * for a channel like WhatsApp is one callback shared by every tenant. An\n * account nobody connected, or one revoked or in error, resolves to nobody:\n * the event is dropped (the edge already answered 200, so the channel stops\n * redelivering) and a tenant can never receive another tenant's traffic.\n */\n\nexport type EventOutcome =\n | { kind: \"dropped\"; reason: \"unknown-account\" | \"not-connected\" }\n | { kind: \"duplicate\" }\n | { kind: \"message\"; conversationId: string; messageId: string }\n | { kind: \"opted-out\"; conversationId: string }\n | { kind: \"receipt\"; applied: boolean };\n\nexport async function handleEvent(ctx: EngineContext, channel: string, event: NormalizedEvent): Promise<EventOutcome> {\n const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);\n if (!connection) return { kind: \"dropped\", reason: \"unknown-account\" };\n if (connection.status !== \"CONNECTED\") return { kind: \"dropped\", reason: \"not-connected\" };\n\n if (event.type === \"message\") return handleMessage(ctx, connection, event);\n if (event.type === \"opt_out\") return handleOptOut(ctx, connection, event);\n const applied = await ctx.config.store.applyReceipt({\n tenantId: connection.tenantId,\n channel,\n externalId: event.externalId,\n status: event.status,\n at: event.at,\n error: event.error,\n });\n return { kind: \"receipt\", applied };\n}\n\n/** The text a message row keeps, and the channel reference beside it. */\nfunction columnsOf(content: InboundContent): { kind: InboundContent[\"kind\"]; body: string | null; attachmentRef: string | null } {\n switch (content.kind) {\n case \"TEXT\":\n return { kind: \"TEXT\", body: content.text, attachmentRef: null };\n case \"INTERACTIVE\":\n return { kind: \"INTERACTIVE\", body: content.title, attachmentRef: content.replyId };\n case \"AUDIO\":\n return { kind: \"AUDIO\", body: null, attachmentRef: content.mediaId };\n default:\n return { kind: \"OTHER\", body: null, attachmentRef: null };\n }\n}\n\nconst later = (a: Date | null, b: Date): Date => (a && a > b ? a : b);\n\n/** How many times a conversation write is re-decided after losing a compare-and-set. */\nconst MAX_WRITE_ATTEMPTS = 6;\n\nasync function handleMessage(\n ctx: EngineContext,\n connection: StoredConnection,\n event: InboundMessageEvent,\n): Promise<EventOutcome> {\n const { store } = ctx.config;\n if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: \"duplicate\" };\n\n const columns = columnsOf(event.content);\n const conversation = await openConversation(ctx, connection, event, columns.body !== null);\n const inserted = await store.insertMessage({\n conversationId: conversation.id,\n tenantId: connection.tenantId,\n channel: connection.channel,\n direction: \"INBOUND\",\n ...columns,\n options: null,\n externalId: event.externalId,\n deliveryStatus: \"RECEIVED\",\n authorKind: \"CONTACT\",\n staffUserId: null,\n createdAt: event.sentAt,\n });\n if (!inserted.created) return { kind: \"duplicate\" };\n // Stored, but nothing may be said: the contact opted out with this message,\n // or this one was sent BEFORE their opt-out and only now got processed.\n if (event.optOut || conversation.state === \"OPTED_OUT\") return { kind: \"opted-out\", conversationId: conversation.id };\n\n await notifyHost(ctx, conversation, inserted.message);\n return { kind: \"message\", conversationId: conversation.id, messageId: inserted.message.id };\n}\n\n/**\n * Create the conversation, or bring an existing one up to this message.\n *\n * Every write to an existing row is a compare-and-set on what was read (its\n * state and its two timestamps): a worker that lost the race re-reads and\n * decides again, so a stale read can never put back a state another worker\n * just changed — an opt-out above all.\n */\nasync function openConversation(\n ctx: EngineContext,\n connection: StoredConnection,\n event: InboundMessageEvent,\n carriesText: boolean,\n): Promise<ConversationView> {\n const { store } = ctx.config;\n for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {\n const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);\n // A lost insert race answers a null: go again, and the winner's row is `existing`.\n const result = existing\n ? await updateExisting(ctx, connection, existing, event, carriesText)\n : await createFirst(ctx, connection, event, carriesText);\n if (result) return result;\n }\n throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);\n}\n\n/** The first message of a contact opens the conversation; null when another worker's insert won. */\nasync function createFirst(\n ctx: EngineContext,\n connection: StoredConnection,\n event: InboundMessageEvent,\n carriesText: boolean,\n): Promise<ConversationView | null> {\n const state = event.optOut ? \"OPTED_OUT\" : \"AGENT\";\n const created = await ctx.config.store.createConversation({\n tenantId: connection.tenantId,\n channel: connection.channel,\n contactId: event.contactId,\n contactName: event.contactName,\n connectionId: connection.id,\n state,\n lastInboundAt: event.sentAt,\n lastMessageAt: event.sentAt,\n optedOutAt: event.optOut ? event.sentAt : null,\n hasText: carriesText,\n });\n return created.state === state && created.lastInboundAt?.getTime() === event.sentAt.getTime() ? created : null;\n}\n\n/** Bring an existing conversation up to this message; null when the compare-and-set lost. */\nasync function updateExisting(\n ctx: EngineContext,\n connection: StoredConnection,\n existing: ConversationView,\n event: InboundMessageEvent,\n carriesText: boolean,\n): Promise<ConversationView | null> {\n const state = await nextState(ctx, existing, event);\n return ctx.config.store.updateConversation(\n connection.tenantId,\n existing.id,\n {\n // Left out when unchanged: the write never carries a state it did not decide.\n ...(state !== existing.state ? { state } : {}),\n ...(event.optOut ? { optedOutAt: later(existing.optedOutAt, event.sentAt) } : {}),\n ...(connection.id !== existing.connectionId ? { connectionId: connection.id } : {}),\n lastInboundAt: later(existing.lastInboundAt, event.sentAt),\n lastMessageAt: later(existing.lastMessageAt, event.sentAt),\n ...(event.contactName ? { contactName: event.contactName } : {}),\n ...(carriesText ? { hasText: true } : {}),\n },\n { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },\n );\n}\n\n/**\n * An opt-out wins. A message re-opens a CLOSED conversation, and an OPTED_OUT\n * one only when it was sent AFTER the opt-out (the message's own time, so a\n * delivery processed late, out of order, never undoes it).\n */\nasync function nextState(ctx: EngineContext, conversation: ConversationView, event: InboundMessageEvent): Promise<ConversationState> {\n if (event.optOut) return \"OPTED_OUT\";\n if (conversation.state === \"OPTED_OUT\") {\n if (conversation.optedOutAt && event.sentAt <= conversation.optedOutAt) return \"OPTED_OUT\";\n } else if (conversation.state !== \"CLOSED\") {\n return conversation.state;\n }\n // The type refuses OPTED_OUT; a JavaScript host that returns it anyway is read as the default.\n const chosen = (await ctx.config.hooks?.reopenState?.(conversation)) as ConversationState | undefined;\n return chosen && chosen !== \"OPTED_OUT\" ? chosen : \"AGENT\";\n}\n\nasync function notifyHost(\n ctx: EngineContext,\n conversation: ConversationView,\n message: MessageView,\n): Promise<void> {\n const hook = ctx.config.hooks?.onInboundMessage;\n if (!hook) return;\n try {\n await hook({ conversation, message });\n } catch (error) {\n // The message is stored; a retry of the delivery would be a no-op, so the\n // hook's failure is the host's to log and recover from, never a re-run.\n ctx.config.logger.error(`messaging.inbound: onInboundMessage failed for ${conversation.id}: ${errorText(error)}`, { error });\n }\n}\n\nasync function handleOptOut(ctx: EngineContext, connection: StoredConnection, event: OptOutEvent): Promise<EventOutcome> {\n const { store } = ctx.config;\n for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {\n const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);\n if (!existing) {\n // No conversation yet: one is opened in OPTED_OUT, so a later send is refused.\n const created = await store.createConversation({\n tenantId: connection.tenantId,\n channel: connection.channel,\n contactId: event.contactId,\n contactName: null,\n connectionId: connection.id,\n state: \"OPTED_OUT\",\n lastInboundAt: null,\n lastMessageAt: null,\n optedOutAt: event.at,\n hasText: false,\n });\n if (created.state === \"OPTED_OUT\") return { kind: \"opted-out\", conversationId: created.id };\n continue;\n }\n const updated = await store.updateConversation(\n connection.tenantId,\n existing.id,\n {\n ...(existing.state !== \"OPTED_OUT\" ? { state: \"OPTED_OUT\" as const } : {}),\n optedOutAt: later(existing.optedOutAt, event.at),\n },\n { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },\n );\n if (updated) return { kind: \"opted-out\", conversationId: existing.id };\n }\n throw new Error(`conversation ${event.contactId} kept changing under this opt-out; retry`);\n}\n","import type { EngineContext } from \"./context\";\nimport { errorText } from \"./errors\";\nimport { bodyHash } from \"./hash\";\nimport { handleEvent, type EventOutcome } from \"./inbound\";\nimport type { NormalizedEvent } from \"./types\";\n\n/**\n * The durable inbox: persist the raw delivery, ACK, then process in a job.\n *\n * Nothing is resolved before the row is written — not the tenant, not even\n * whether the body parses — because the one thing a webhook must never do is\n * lose a delivery to a bug in the code that reads it. The raw bytes are kept\n * so a mapping bug can be replayed once fixed — until the retention sweep\n * deletes them, with the conversation's text, past the retention window.\n */\n\n/** The job the engine enqueues per fresh delivery, by wire name. */\nexport const PROCESS_DELIVERY_JOB = \"messaging.process-delivery\";\n\n/** Store one verified delivery and queue its processing. Redeliveries are stored once. */\nexport async function receiveDelivery(\n ctx: EngineContext,\n channel: string,\n rawBody: string,\n): Promise<{ deliveryId: string; fresh: boolean }> {\n const { store, clock, enqueue, logger } = ctx.config;\n const recorded = await store.recordDelivery({ channel, bodyHash: bodyHash(rawBody), rawBody, receivedAt: clock.now() });\n if (recorded.fresh) {\n const queued = await enqueue.enqueue(\n PROCESS_DELIVERY_JOB,\n { deliveryId: recorded.id },\n { dedupeKey: `${PROCESS_DELIVERY_JOB}:${recorded.id}` },\n );\n // Never fatal: the row is stored, and the reconciliation sweep runs it.\n if (!queued.enqueued) logger.warn(`messaging.inbox: delivery ${recorded.id} not queued (${queued.reason ?? \"no reason\"})`);\n }\n return { deliveryId: recorded.id, fresh: recorded.fresh };\n}\n\n/** What processing one stored delivery did. */\nexport type DeliveryOutcome =\n | { kind: \"missing\" }\n | { kind: \"already-processed\" }\n | { kind: \"processed\"; events: EventOutcome[] }\n | { kind: \"unreadable\"; reason: string };\n\n/**\n * Process one stored delivery. Every event handler is idempotent (messages\n * dedupe on their channel id, receipts on their column), so a retry after a\n * partial failure redoes nothing. A throw settles the row FAILED and is\n * rethrown, so the job's own retry runs it again; a receipt that found no\n * message to land on settles it FAILED too, left to the reconciliation sweep.\n */\nexport async function processDelivery(ctx: EngineContext, deliveryId: string): Promise<DeliveryOutcome> {\n const { store, clock, logger } = ctx.config;\n const row = await store.getDelivery(deliveryId);\n if (!row) return { kind: \"missing\" };\n if (row.state === \"PROCESSED\") return { kind: \"already-processed\" };\n\n const adapter = ctx.adapters.get(row.channel);\n let events: NormalizedEvent[];\n try {\n if (!adapter) throw new Error(`no adapter mounted for channel \"${row.channel}\"`);\n events = adapter.parse(row.rawBody);\n } catch (error) {\n // The same bytes will never read differently: settle it, with the reason,\n // rather than retry. The raw body stays for a replay until retention deletes it.\n const reason = errorText(error);\n logger.warn(`messaging.inbox: delivery ${deliveryId} unreadable: ${reason}`);\n await store.settleDelivery(deliveryId, { state: \"PROCESSED\", error: `unreadable: ${reason}`, at: clock.now() });\n return { kind: \"unreadable\", reason };\n }\n\n try {\n const outcomes: EventOutcome[] = [];\n for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));\n // A receipt for a message nobody stored yet (it raced the sender's own\n // write of the channel id) changed nothing: settle FAILED, not PROCESSED,\n // so the reconciliation sweep applies it once the id exists.\n const unapplied = outcomes.filter((outcome) => outcome.kind === \"receipt\" && !outcome.applied).length;\n if (unapplied > 0) {\n const error = `${unapplied} receipt(s) for a message not stored yet`;\n logger.warn(`messaging.inbox: delivery ${deliveryId}: ${error}`);\n await store.settleDelivery(deliveryId, { state: \"FAILED\", error, at: clock.now() });\n } else {\n await store.settleDelivery(deliveryId, { state: \"PROCESSED\", error: null, at: clock.now() });\n }\n return { kind: \"processed\", events: outcomes };\n } catch (error) {\n await store.settleDelivery(deliveryId, { state: \"FAILED\", error: errorText(error), at: clock.now() });\n throw error;\n }\n}\n\n/**\n * Re-run deliveries left unprocessed (a dead worker, a refused enqueue, a\n * failure) once they are older than the job's own retry span. One delivery's\n * failure never stops the batch.\n */\nexport async function reconcileInbox(ctx: EngineContext): Promise<{ retried: number; failed: number }> {\n const { store, clock, logger, reconcileAfterMs, maxDeliveryAttempts, reconcileBatchSize } = ctx.config;\n const due = await store.listRetryableDeliveries({\n receivedBefore: new Date(clock.now().getTime() - reconcileAfterMs),\n maxAttempts: maxDeliveryAttempts,\n take: reconcileBatchSize,\n });\n let failed = 0;\n for (const row of due) {\n try {\n await processDelivery(ctx, row.id);\n } catch (error) {\n failed += 1;\n logger.warn(`messaging.inbox: delivery ${row.id} failed again: ${errorText(error)}`);\n }\n }\n return { retried: due.length, failed };\n}\n","import type { EngineContext } from \"./context\";\n\n/**\n * The retention sweep. A conversation's TEXT lives only while the\n * conversation does: `retentionMs` (default 12 h) after its LAST message,\n * every message's body, choices and transcript are deleted. The conversation\n * row, its state and its structured summary stay — they are what the next\n * conversation with the same contact starts from.\n *\n * The same cutoff deletes the raw inbox rows (Meta's whole payload: the text,\n * the phone number, the profile name): the PROCESSED ones, and the FAILED ones\n * nothing will retry any more. What stays of a delivery is nothing; dedupe\n * lives on the message row's `(channel, external_id)`, which outlives the text.\n *\n * One indexed query finds the due conversations across every tenant (never a\n * walk over tenants); a pass that fills its batch says so, and the next tick\n * takes the rest.\n */\nexport async function sweepRetention(\n ctx: EngineContext,\n): Promise<{ conversations: number; messages: number; deliveries: number; more: boolean }> {\n const { store, clock, retentionMs, retentionBatchSize, maxDeliveryAttempts } = ctx.config;\n const cutoff = new Date(clock.now().getTime() - retentionMs);\n const text = await store.purgeExpiredText({ cutoff, take: retentionBatchSize });\n const deliveries = await store.purgeExpiredDeliveries({ cutoff, maxAttempts: maxDeliveryAttempts, take: retentionBatchSize });\n return { ...text, deliveries, more: text.conversations === retentionBatchSize || deliveries >= retentionBatchSize };\n}\n","import { ChannelSendFailure } from \"./channel\";\nimport type { EngineContext } from \"./context\";\nimport { errorText, MessagingSendError } from \"./errors\";\nimport type { StoredConnection } from \"./store\";\nimport type { ConversationView, MessageView, OutboundContent } from \"./types\";\n\n/** Who is sending: the host's agent, or a person on the tenant's staff. */\nexport type SendAuthor = { kind: \"AGENT\" } | { kind: \"STAFF\"; staffUserId?: string | null };\n\nexport interface SendInput {\n tenantId: string;\n conversationId: string;\n content: OutboundContent;\n author: SendAuthor;\n}\n\n/**\n * Send one message into a conversation.\n *\n * Refused, with nothing recorded, when the contact opted out, when the\n * channel's policy says the window is closed, or when the conversation's\n * connection is not connected. Otherwise the outbound row is recorded\n * PENDING BEFORE the channel is called — a crash mid-call leaves evidence, not\n * silence — then stamped ACCEPTED with the channel's id, or FAILED with the\n * channel's error (and the error is thrown).\n */\nexport async function sendMessage(ctx: EngineContext, input: SendInput): Promise<MessageView> {\n const { store, clock } = ctx.config;\n const conversation = await store.getConversation(input.tenantId, input.conversationId);\n if (!conversation) throw new MessagingSendError(\"NOT_FOUND\", `no conversation ${input.conversationId}`);\n const { adapter, connection } = await admit(ctx, conversation);\n\n const now = clock.now();\n const recorded = await store.insertMessage({\n conversationId: conversation.id,\n tenantId: conversation.tenantId,\n channel: conversation.channel,\n direction: \"OUTBOUND\",\n kind: input.content.kind === \"TEXT\" ? \"TEXT\" : \"INTERACTIVE\",\n body: input.content.text,\n options: optionsOf(input.content),\n attachmentRef: null,\n externalId: null,\n deliveryStatus: \"PENDING\",\n authorKind: input.author.kind,\n staffUserId: input.author.kind === \"STAFF\" ? (input.author.staffUserId ?? null) : null,\n createdAt: now,\n });\n await store.updateConversation(conversation.tenantId, conversation.id, {\n lastMessageAt: now,\n hasText: true,\n });\n\n let externalId: string;\n try {\n if (connection.credentialSealed === null) throw new Error(\"the connection holds no credential\");\n const credential = await ctx.config.secrets.open(connection.credentialSealed);\n ({ externalId } = await adapter.send({\n credential,\n accountId: connection.externalAccountId,\n to: conversation.contactId,\n content: input.content,\n }));\n } catch (error) {\n const reason = error instanceof ChannelSendFailure ? `${error.code}: ${error.message}` : errorText(error);\n await store.updateMessage(conversation.tenantId, recorded.message.id, {\n deliveryStatus: \"FAILED\",\n error: reason.slice(0, 500),\n failedAt: clock.now(),\n });\n throw new MessagingSendError(\"CHANNEL_FAILED\", reason, recorded.message.id);\n }\n const accepted = await store.updateMessage(conversation.tenantId, recorded.message.id, {\n externalId,\n deliveryStatus: \"ACCEPTED\",\n });\n return accepted ?? recorded.message;\n}\n\n/** The checks a send must pass before anything is written. */\nasync function admit(ctx: EngineContext, conversation: ConversationView) {\n if (conversation.state === \"OPTED_OUT\") {\n throw new MessagingSendError(\"OPTED_OUT\", `conversation ${conversation.id} opted out`);\n }\n const adapter = ctx.adapters.get(conversation.channel);\n if (!adapter) throw new MessagingSendError(\"UNKNOWN_CHANNEL\", `no adapter for channel \"${conversation.channel}\"`);\n const verdict = adapter.policy.check({ lastInboundAt: conversation.lastInboundAt, now: ctx.config.clock.now() });\n if (!verdict.allowed) {\n throw new MessagingSendError(verdict.reason, `conversation ${conversation.id}: the channel's window is closed`);\n }\n const connection: StoredConnection | null = await ctx.config.store.getConnection(\n conversation.tenantId,\n conversation.connectionId,\n );\n if (!connection || connection.status !== \"CONNECTED\") {\n throw new MessagingSendError(\"NOT_CONNECTED\", `conversation ${conversation.id}: its connection is not connected`);\n }\n return { adapter, connection };\n}\n\n/** An interactive message's choices, kept as JSON text beside its prompt. */\nfunction optionsOf(content: OutboundContent): string | null {\n if (content.kind === \"BUTTONS\") return JSON.stringify({ buttons: content.buttons });\n if (content.kind === \"LIST\") return JSON.stringify({ buttonLabel: content.buttonLabel, sections: content.sections });\n return null;\n}\n","import { connect, markError, revoke, type ConnectInput } from \"./connections\";\nimport { engineContext } from \"./context\";\nimport { processDelivery, receiveDelivery, reconcileInbox } from \"./inbox\";\nimport type { MessagingEngineConfig } from \"./ports\";\nimport { sweepRetention } from \"./retention\";\nimport { sendMessage, type SendInput } from \"./sender\";\nimport type { ConversationState, ConversationSummary } from \"./types\";\n\n/**\n * Mount the connector: one engine per process, over the host's store and\n * ports, with one adapter per channel.\n */\nexport function createMessagingEngine(config: MessagingEngineConfig) {\n const ctx = engineContext(config);\n const { store, clock } = ctx.config;\n return {\n /** The adapter mounted for a channel, or undefined. */\n adapter: (channel: string) => ctx.adapters.get(channel),\n /** The channels this engine serves. */\n channels: () => [...ctx.adapters.keys()],\n\n // ── The pipeline ─────────────────────────────────────────────────────────\n /** Store a VERIFIED raw delivery and queue its processing. The edge answers 200 after this. */\n receive: (channel: string, rawBody: string) => receiveDelivery(ctx, channel, rawBody),\n /** The `process-delivery` job's body. */\n processDelivery: (deliveryId: string) => processDelivery(ctx, deliveryId),\n /** The `reconcile-inbox` sweep's body. */\n reconcile: () => reconcileInbox(ctx),\n /** The `retention` sweep's body. */\n sweepRetention: () => sweepRetention(ctx),\n\n // ── Sending ──────────────────────────────────────────────────────────────\n send: (input: SendInput) => sendMessage(ctx, input),\n\n // ── Connections ──────────────────────────────────────────────────────────\n connect: (input: ConnectInput) => connect(ctx, input),\n revoke: (tenantId: string, connectionId: string, reason?: string | null) => revoke(ctx, tenantId, connectionId, reason),\n markError: (tenantId: string, connectionId: string, reason: string) => markError(ctx, tenantId, connectionId, reason),\n listConnections: (tenantId: string) => store.listConnections(tenantId),\n\n // ── Conversations, for the host's own surfaces ───────────────────────────\n getConversation: (tenantId: string, conversationId: string) => store.getConversation(tenantId, conversationId),\n listMessages: (tenantId: string, conversationId: string) => store.listMessages(tenantId, conversationId),\n /**\n * Move a conversation between AGENT, HUMAN and CLOSED (a hand-off). OPTED_OUT\n * is the contact's alone, both ways: an opted-out conversation is not\n * moved (null), and only the contact's next message re-opens it.\n */\n setState: (tenantId: string, conversationId: string, state: Exclude<ConversationState, \"OPTED_OUT\">) =>\n // ONE guarded write: an opt-out landing between a read and this write cannot be overwritten.\n store.updateConversation(tenantId, conversationId, { state }, { stateNot: \"OPTED_OUT\" }),\n /** Replace the structured summary that outlives the text. */\n setSummary: (tenantId: string, conversationId: string, summary: ConversationSummary) =>\n store.updateConversation(tenantId, conversationId, { summary, summaryUpdatedAt: clock.now() }),\n /** Store an audio message's transcript (deleted with the text). */\n setTranscript: async (tenantId: string, messageId: string, transcript: string) => {\n const message = await store.updateMessage(tenantId, messageId, { transcript });\n if (message) await store.updateConversation(tenantId, message.conversationId, { hasText: true });\n return message;\n },\n };\n}\n\nexport type MessagingEngine = ReturnType<typeof createMessagingEngine>;\n","import { randomUUID } from \"node:crypto\";\n\nimport { DELIVERY_RANK, RECEIPT_COLUMN, type ConversationGuard, type MessagingStore, type StoredConnection } from \"./store\";\nimport type { ConnectionView, ConversationView, InboxDeliveryView, MessageView } from \"./types\";\n\n/**\n * An in-memory {@link MessagingStore}, for a host's tests and this package's\n * own. It enforces the migration's unique keys the way Postgres does, so a\n * test that passes here exercises the same dedupe a database would.\n *\n * Not for production: it lives in one process and forgets on restart.\n */\nexport function createMemoryMessagingStore(): MessagingStore & { readonly dump: () => MemoryStoreDump } {\n const tables: MemoryTables = {\n deliveries: new Map(),\n connections: new Map(),\n conversations: new Map(),\n messages: new Map(),\n };\n return {\n ...memoryInbox(tables),\n ...memoryConnections(tables),\n ...memoryConversations(tables),\n ...memoryMessages(tables),\n purgeExpiredText: async (input) => purge(tables, input),\n purgeExpiredDeliveries: async (input) => purgeDeliveries(tables, input),\n dump: () => ({\n deliveries: [...tables.deliveries.values()].map(copy),\n connections: [...tables.connections.values()].map(copy),\n conversations: [...tables.conversations.values()].map(copy),\n messages: [...tables.messages.values()].map(copy),\n }),\n };\n}\n\n/** Everything the memory store holds, for a test to assert on. */\nexport interface MemoryStoreDump {\n deliveries: StoredDelivery[];\n connections: StoredConnection[];\n conversations: ConversationView[];\n messages: MessageView[];\n}\n\ntype StoredDelivery = InboxDeliveryView & { bodyHash: string };\n\ninterface MemoryTables {\n deliveries: Map<string, StoredDelivery>;\n connections: Map<string, StoredConnection>;\n conversations: Map<string, ConversationView>;\n messages: Map<string, MessageView>;\n}\n\nconst copy = <T extends object>(row: T): T => ({ ...row });\n/** A copy of `row` without `key`: what a real select would not return. */\nfunction without<T extends object, K extends keyof T>(row: T, key: K): Omit<T, K> {\n return Object.fromEntries(Object.entries(row).filter(([name]) => name !== key)) as Omit<T, K>;\n}\nconst deliveryView = (row: StoredDelivery): InboxDeliveryView => without(row, \"bodyHash\");\nconst connectionView = (row: StoredConnection): ConnectionView => without(row, \"credentialSealed\");\n\nfunction memoryInbox({ deliveries }: MemoryTables) {\n return {\n async recordDelivery({ channel, bodyHash, rawBody, receivedAt }) {\n const existing = [...deliveries.values()].find((row) => row.channel === channel && row.bodyHash === bodyHash);\n if (existing) return { id: existing.id, fresh: false };\n const id = randomUUID();\n deliveries.set(id, { id, channel, bodyHash, rawBody, state: \"PENDING\", attempts: 0, error: null, receivedAt, processedAt: null });\n return { id, fresh: true };\n },\n async getDelivery(id) {\n const row = deliveries.get(id);\n return row ? deliveryView(row) : null;\n },\n async settleDelivery(id, { state, error, at }) {\n const row = deliveries.get(id);\n if (row) deliveries.set(id, { ...row, state, error, processedAt: at, attempts: row.attempts + 1 });\n },\n async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {\n return [...deliveries.values()]\n .filter((row) => row.state !== \"PROCESSED\" && row.attempts < maxAttempts && row.receivedAt < receivedBefore)\n .sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime())\n .slice(0, take)\n .map(deliveryView);\n },\n } satisfies Partial<MessagingStore>;\n}\n\nfunction memoryConnections({ connections }: MemoryTables) {\n const findConnectionByAccount = async (channel: string, externalAccountId: string) => {\n const row = [...connections.values()].find(\n (candidate) => candidate.channel === channel && candidate.externalAccountId === externalAccountId,\n );\n return row ? copy(row) : null;\n };\n return {\n findConnectionByAccount,\n async getConnection(tenantId, id) {\n const row = connections.get(id);\n return row && row.tenantId === tenantId ? copy(row) : null;\n },\n async listConnections(tenantId) {\n return [...connections.values()].filter((row) => row.tenantId === tenantId).map(connectionView);\n },\n async saveConnection(input) {\n // Read and write with no await between them: the check-and-set is atomic, as the database's unique key makes it.\n const existing = [...connections.values()].find(\n (candidate) => candidate.channel === input.channel && candidate.externalAccountId === input.externalAccountId,\n );\n if (existing && existing.tenantId !== input.tenantId && existing.status !== \"REVOKED\") return null;\n const row: StoredConnection = {\n id: existing?.id ?? randomUUID(),\n ...input,\n status: \"CONNECTED\",\n statusReason: null,\n revokedAt: null,\n };\n connections.set(row.id, row);\n return connectionView(row);\n },\n async setConnectionStatus(tenantId, id, patch) {\n const row = connections.get(id);\n if (!row || row.tenantId !== tenantId) return false;\n connections.set(id, { ...row, ...patch });\n return true;\n },\n } satisfies Partial<MessagingStore>;\n}\n\nfunction memoryConversations({ conversations }: MemoryTables) {\n const findConversation = async (tenantId: string, channel: string, contactId: string) => {\n const row = [...conversations.values()].find(\n (candidate) => candidate.tenantId === tenantId && candidate.channel === channel && candidate.contactId === contactId,\n );\n return row ? copy(row) : null;\n };\n return {\n findConversation,\n async getConversation(tenantId, id) {\n const row = conversations.get(id);\n return row && row.tenantId === tenantId ? copy(row) : null;\n },\n async createConversation(input) {\n const existing = await findConversation(input.tenantId, input.channel, input.contactId);\n if (existing) return existing;\n const row: ConversationView = {\n id: randomUUID(),\n ...input,\n optedOutAt: input.optedOutAt ?? null,\n summary: null,\n summaryUpdatedAt: null,\n createdAt: new Date(),\n };\n conversations.set(row.id, row);\n return copy(row);\n },\n async updateConversation(tenantId, id, patch, guard) {\n const row = conversations.get(id);\n if (!row || row.tenantId !== tenantId) return null;\n // No await between this check and the write below: the compare-and-set is atomic.\n if (guard && !matchesGuard(row, guard)) return null;\n const next = { ...row, ...patch };\n conversations.set(id, next);\n return copy(next);\n },\n } satisfies Partial<MessagingStore>;\n}\n\nconst sameTime = (a: Date | null, b: Date | null): boolean => (a === null || b === null ? a === b : a.getTime() === b.getTime());\n\nconst GUARDED_TIMES = [\"lastInboundAt\", \"lastMessageAt\", \"optedOutAt\"] as const;\n\nfunction matchesGuard(row: ConversationView, guard: ConversationGuard): boolean {\n if (guard.state !== undefined && row.state !== guard.state) return false;\n if (guard.stateNot !== undefined && row.state === guard.stateNot) return false;\n return GUARDED_TIMES.every((key) => {\n const wanted = guard[key];\n return wanted === undefined || sameTime(row[key], wanted);\n });\n}\n\nfunction memoryMessages({ messages }: MemoryTables) {\n const findMessageByExternalId = async (channel: string, externalId: string) => {\n const row = [...messages.values()].find((candidate) => candidate.channel === channel && candidate.externalId === externalId);\n return row ? copy(row) : null;\n };\n return {\n findMessageByExternalId,\n async insertMessage(input) {\n const existing = input.externalId === null ? null : await findMessageByExternalId(input.channel, input.externalId);\n if (existing) return { created: false, message: existing };\n const row: MessageView = {\n id: randomUUID(),\n ...input,\n transcript: null,\n error: null,\n sentAt: null,\n deliveredAt: null,\n readAt: null,\n failedAt: null,\n };\n messages.set(row.id, row);\n return { created: true, message: copy(row) };\n },\n async updateMessage(tenantId, id, patch) {\n const row = messages.get(id);\n if (!row || row.tenantId !== tenantId) return null;\n const taken = patch.externalId === undefined ? null : await findMessageByExternalId(row.channel, patch.externalId);\n if (taken && taken.id !== id) throw Object.assign(new Error(\"unique\"), { code: \"P2002\" });\n const next = { ...row, ...patch };\n messages.set(id, next);\n return copy(next);\n },\n async listMessages(tenantId, conversationId) {\n return [...messages.values()]\n .filter((row) => row.tenantId === tenantId && row.conversationId === conversationId)\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())\n .map(copy);\n },\n async applyReceipt({ tenantId, channel, externalId, status, at, error }) {\n const row = [...messages.values()].find(\n (candidate) =>\n candidate.tenantId === tenantId &&\n candidate.channel === channel &&\n candidate.externalId === externalId &&\n candidate.direction === \"OUTBOUND\",\n );\n if (!row) return false;\n const column = RECEIPT_COLUMN[status];\n const stamp = row[column] === null;\n const forward = DELIVERY_RANK[status] > DELIVERY_RANK[row.deliveryStatus];\n messages.set(row.id, {\n ...row,\n ...(stamp ? { [column]: at, ...(error !== null ? { error } : {}) } : {}),\n ...(forward ? { deliveryStatus: status } : {}),\n });\n return true;\n },\n } satisfies Partial<MessagingStore>;\n}\n\nfunction purgeDeliveries(\n { deliveries }: MemoryTables,\n { cutoff, maxAttempts, take }: { cutoff: Date; maxAttempts: number; take: number },\n): number {\n const due = (match: (row: StoredDelivery) => boolean) =>\n [...deliveries.values()]\n .filter((row) => row.receivedAt < cutoff && match(row))\n .sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime())\n .slice(0, take);\n const rows = [...due((row) => row.state === \"PROCESSED\"), ...due((row) => row.state === \"FAILED\" && row.attempts >= maxAttempts)];\n for (const row of rows) deliveries.delete(row.id);\n return rows.length;\n}\n\nfunction purge({ conversations, messages }: MemoryTables, { cutoff, take }: { cutoff: Date; take: number }) {\n const expired = (row: ConversationView) => row.lastMessageAt !== null && row.lastMessageAt < cutoff;\n const due = [...conversations.values()]\n .filter((row) => row.hasText && expired(row))\n .sort((a, b) => a.lastMessageAt!.getTime() - b.lastMessageAt!.getTime())\n .slice(0, take);\n const ids = new Set(due.map((row) => row.id));\n let purged = 0;\n for (const row of messages.values()) {\n if (!ids.has(row.conversationId) || row.createdAt > cutoff) continue;\n messages.set(row.id, { ...row, body: null, options: null, transcript: null });\n purged += 1;\n }\n for (const row of due) {\n const current = conversations.get(row.id)!;\n if (expired(current)) conversations.set(row.id, { ...current, hasText: false });\n }\n return { conversations: due.length, messages: purged };\n}\n","import type {\n AuthorKind,\n ChannelKind,\n ConnectionStatus,\n ConnectionView,\n ConversationState,\n ConversationSummary,\n ConversationView,\n DeliveryStatus,\n InboxDeliveryView,\n MessageDirection,\n MessageKind,\n MessageView,\n ReceiptStatus,\n} from \"./types\";\n\n/**\n * THE STORE PORT: every read and write the engine makes, as named operations.\n *\n * The engine never builds a query. Two implementations ship:\n * `createPrismaMessagingStore` over the Prisma delegates generated from the\n * shipped partial (what a host mounts), and `createMemoryMessagingStore` (what\n * a test mounts). The same contract suite runs over both — the Prisma one on\n * real Postgres with the shipped migration — so the two cannot drift.\n *\n * Every operation is tenant-scoped where a tenant is known, and every unique\n * key the migration enforces is enforced by both implementations, with the\n * race answered the same way (the existing row wins).\n */\nexport interface MessagingStore {\n // ── The inbox ──────────────────────────────────────────────────────────────\n /** Store one raw delivery, deduped on `(channel, bodyHash)`. `fresh: false` for a redelivery. */\n recordDelivery(input: {\n channel: ChannelKind;\n bodyHash: string;\n rawBody: string;\n receivedAt: Date;\n }): Promise<{ id: string; fresh: boolean }>;\n getDelivery(id: string): Promise<InboxDeliveryView | null>;\n /** Close a delivery out, counting the attempt. */\n settleDelivery(id: string, outcome: { state: \"PROCESSED\" | \"FAILED\"; error: string | null; at: Date }): Promise<void>;\n /** Deliveries not yet processed, received before `receivedBefore`, under the attempt bound, oldest first. */\n listRetryableDeliveries(input: { receivedBefore: Date; maxAttempts: number; take: number }): Promise<InboxDeliveryView[]>;\n\n // ── Connections ────────────────────────────────────────────────────────────\n findConnectionByAccount(channel: ChannelKind, externalAccountId: string): Promise<StoredConnection | null>;\n getConnection(tenantId: string, id: string): Promise<StoredConnection | null>;\n listConnections(tenantId: string): Promise<ConnectionView[]>;\n /**\n * Insert, or overwrite the row keyed by `(channel, externalAccountId)` — but\n * only the same tenant's, or one that is REVOKED: the write itself is\n * conditional, so two connects racing for one account cannot both win.\n * `null` when the account is held by another tenant (the engine answers\n * `ACCOUNT_TAKEN`).\n */\n saveConnection(input: NewConnection): Promise<ConnectionView | null>;\n setConnectionStatus(\n tenantId: string,\n id: string,\n patch: { status: ConnectionStatus; statusReason: string | null; revokedAt: Date | null; credentialSealed?: null },\n ): Promise<boolean>;\n\n // ── Conversations ──────────────────────────────────────────────────────────\n findConversation(tenantId: string, channel: ChannelKind, contactId: string): Promise<ConversationView | null>;\n getConversation(tenantId: string, id: string): Promise<ConversationView | null>;\n /** Create one; on a lost race for `(tenant, channel, contact)` the existing row is returned. */\n createConversation(input: NewConversation): Promise<ConversationView>;\n /**\n * Apply `patch` to the tenant's conversation. With a `guard` it is a\n * COMPARE-AND-SET: the write happens only while the row still matches every\n * guarded field (one `updateMany`), and `null` comes back when it does not —\n * the caller re-reads and decides again. Without a guard, `null` only means\n * \"no such conversation\".\n */\n updateConversation(\n tenantId: string,\n id: string,\n patch: ConversationPatch,\n guard?: ConversationGuard,\n ): Promise<ConversationView | null>;\n\n // ── Messages ───────────────────────────────────────────────────────────────\n findMessageByExternalId(channel: ChannelKind, externalId: string): Promise<MessageView | null>;\n /** Insert one; a duplicate `(channel, externalId)` is `created: false` and the existing row. */\n insertMessage(input: NewMessage): Promise<{ created: boolean; message: MessageView }>;\n updateMessage(tenantId: string, id: string, patch: MessagePatch): Promise<MessageView | null>;\n listMessages(tenantId: string, conversationId: string): Promise<MessageView[]>;\n /**\n * Stamp a receipt on the tenant's outbound message: the receipt's timestamp\n * column is written only while still null (so `(externalId, status)` is\n * deduped by the row itself), and the delivery status only moves forward.\n * False when no outbound message of that tenant has that id.\n */\n applyReceipt(input: {\n tenantId: string;\n channel: ChannelKind;\n externalId: string;\n status: ReceiptStatus;\n at: Date;\n error: string | null;\n }): Promise<boolean>;\n\n // ── Retention ──────────────────────────────────────────────────────────────\n /**\n * Delete raw inbox rows past `cutoff`: the PROCESSED ones, and the FAILED\n * ones that reached `maxAttempts` (nothing will retry them). One batch of up\n * to `take` per state, found through the `(state, received_at)` index.\n * Returns how many were deleted. Dedupe survives: a redelivered message\n * still meets `(channel, external_id)` on its message row.\n */\n purgeExpiredDeliveries(input: { cutoff: Date; maxAttempts: number; take: number }): Promise<number>;\n /**\n * Delete the text of conversations whose last message is older than\n * `cutoff`: ONE indexed query finds up to `take` of them across every tenant\n * (`has_text`, `last_message_at`), then their messages created at or before\n * the cutoff lose `body`, `options` and `transcript`. Conversation rows,\n * states and summaries stay.\n */\n purgeExpiredText(input: { cutoff: Date; take: number }): Promise<{ conversations: number; messages: number }>;\n}\n\n/** A connection with its sealed credential: only the engine sees this shape. */\nexport interface StoredConnection extends ConnectionView {\n /** Null once the connection was revoked: disconnecting removes the token. */\n credentialSealed: string | null;\n}\n\nexport interface NewConnection {\n tenantId: string;\n channel: ChannelKind;\n externalAccountId: string;\n externalParentId: string | null;\n displayAddress: string;\n credentialSealed: string;\n connectedAt: Date;\n}\n\nexport interface NewConversation {\n tenantId: string;\n channel: ChannelKind;\n contactId: string;\n contactName: string | null;\n connectionId: string;\n state: ConversationState;\n lastInboundAt: Date | null;\n lastMessageAt: Date | null;\n optedOutAt?: Date | null;\n hasText: boolean;\n}\n\n/**\n * What a compare-and-set update requires of the row it writes: every field\n * given must equal the row's current value (`null` matches a null column),\n * and `stateNot` that the state differs.\n */\nexport interface ConversationGuard {\n state?: ConversationState;\n stateNot?: ConversationState;\n lastInboundAt?: Date | null;\n lastMessageAt?: Date | null;\n optedOutAt?: Date | null;\n}\n\nexport interface ConversationPatch {\n contactName?: string | null;\n connectionId?: string;\n state?: ConversationState;\n lastInboundAt?: Date | null;\n lastMessageAt?: Date | null;\n optedOutAt?: Date | null;\n hasText?: boolean;\n summary?: ConversationSummary;\n summaryUpdatedAt?: Date;\n}\n\nexport interface NewMessage {\n conversationId: string;\n tenantId: string;\n channel: ChannelKind;\n direction: MessageDirection;\n kind: MessageKind;\n body: string | null;\n options: string | null;\n attachmentRef: string | null;\n externalId: string | null;\n deliveryStatus: DeliveryStatus;\n authorKind: AuthorKind;\n staffUserId: string | null;\n createdAt: Date;\n}\n\nexport interface MessagePatch {\n externalId?: string;\n deliveryStatus?: DeliveryStatus;\n error?: string | null;\n transcript?: string;\n failedAt?: Date;\n}\n\n/** The forward order of delivery statuses; FAILED outranks them all. */\nexport const DELIVERY_RANK: Readonly<Record<DeliveryStatus, number>> = {\n RECEIVED: 0,\n PENDING: 1,\n ACCEPTED: 2,\n SENT: 3,\n DELIVERED: 4,\n READ: 5,\n FAILED: 6,\n};\n\n/** The receipt's timestamp column. */\nexport const RECEIPT_COLUMN = {\n SENT: \"sentAt\",\n DELIVERED: \"deliveredAt\",\n READ: \"readAt\",\n FAILED: \"failedAt\",\n} as const satisfies Record<ReceiptStatus, keyof MessageView>;\n","import { DELIVERY_RANK, RECEIPT_COLUMN, type ConversationGuard, type MessagingStore, type StoredConnection } from \"./store\";\nimport type {\n ConnectionView,\n ConversationView,\n DeliveryStatus,\n InboxDeliveryView,\n MessageView,\n ReceiptStatus,\n} from \"./types\";\n\n/**\n * The Prisma delegates the store reads and writes.\n *\n * Structural rather than a `PrismaClient` import: the package must not depend\n * on the host's generated client, and this shape is what any client generated\n * from the shipped partial satisfies. Only the query subset below is used —\n * equality, `in`, `lt`, `lte`, `gte`, `not`, compound unique keys, `increment`,\n * `orderBy`, `take` — which is also what the package's Postgres suite\n * translates, so the suite runs the exact queries a host runs.\n */\nexport interface MessagingPrismaDb {\n messagingConnection: Delegate;\n messagingInboxDelivery: Delegate;\n messagingConversation: Delegate;\n messagingMessage: Delegate;\n}\n\ninterface Delegate {\n findUnique(args: unknown): Promise<unknown>;\n findFirst(args: unknown): Promise<unknown>;\n findMany(args: unknown): Promise<unknown[]>;\n create(args: unknown): Promise<unknown>;\n update(args: unknown): Promise<unknown>;\n updateMany(args: unknown): Promise<{ count: number }>;\n deleteMany(args: unknown): Promise<{ count: number }>;\n}\n\n/** Prisma's unique-violation code. */\nconst UNIQUE_VIOLATION = \"P2002\";\nconst isUniqueViolation = (error: unknown): boolean => (error as { code?: string } | null)?.code === UNIQUE_VIOLATION;\n\nconst CONNECTION_VIEW = {\n id: true,\n tenantId: true,\n channel: true,\n externalAccountId: true,\n externalParentId: true,\n displayAddress: true,\n status: true,\n statusReason: true,\n connectedAt: true,\n revokedAt: true,\n} as const;\n\nconst DELIVERY_VIEW = {\n id: true,\n channel: true,\n rawBody: true,\n state: true,\n attempts: true,\n error: true,\n receivedAt: true,\n processedAt: true,\n} as const;\n\nconst pickConversation = (row: ConversationView): ConversationView => ({\n id: row.id,\n tenantId: row.tenantId,\n channel: row.channel,\n contactId: row.contactId,\n contactName: row.contactName,\n connectionId: row.connectionId,\n state: row.state,\n lastInboundAt: row.lastInboundAt,\n lastMessageAt: row.lastMessageAt,\n optedOutAt: row.optedOutAt,\n hasText: row.hasText,\n summary: row.summary,\n summaryUpdatedAt: row.summaryUpdatedAt,\n createdAt: row.createdAt,\n});\n\ntype Client = () => Promise<MessagingPrismaDb>;\n\n/** A {@link MessagingStore} over a Prisma client generated from the shipped partial. */\nexport function createPrismaMessagingStore(db: MessagingPrismaDb | (() => Promise<MessagingPrismaDb>)): MessagingStore {\n const client: Client = typeof db === \"function\" ? db : async () => db;\n return {\n ...inboxOperations(client),\n ...connectionOperations(client),\n ...conversationOperations(client),\n ...messageOperations(client),\n purgeExpiredText: (input) => purgeExpiredText(client, input),\n purgeExpiredDeliveries: (input) => purgeExpiredDeliveries(client, input),\n };\n}\n\ntype InboxOperations = Pick<\n MessagingStore,\n \"recordDelivery\" | \"getDelivery\" | \"settleDelivery\" | \"listRetryableDeliveries\"\n>;\n\nfunction inboxOperations(client: Client): InboxOperations {\n return {\n async recordDelivery({ channel, bodyHash, rawBody, receivedAt }) {\n const delegate = (await client()).messagingInboxDelivery;\n const key = { channel_bodyHash: { channel, bodyHash } };\n const existing = (await delegate.findUnique({ where: key, select: { id: true } })) as { id: string } | null;\n if (existing) return { id: existing.id, fresh: false };\n try {\n const row = (await delegate.create({\n data: { channel, bodyHash, rawBody, receivedAt },\n select: { id: true },\n })) as { id: string };\n return { id: row.id, fresh: true };\n } catch (error) {\n // Two simultaneous redeliveries lose the check-then-insert race; the\n // unique index is the real guard, and losing it is a redelivery.\n if (!isUniqueViolation(error)) throw error;\n const raced = (await delegate.findUnique({ where: key, select: { id: true } })) as { id: string };\n return { id: raced.id, fresh: false };\n }\n },\n async getDelivery(id) {\n return ((await (await client()).messagingInboxDelivery.findUnique({\n where: { id },\n select: DELIVERY_VIEW,\n })) as InboxDeliveryView | null) ?? null;\n },\n async settleDelivery(id, { state, error, at }) {\n await (await client()).messagingInboxDelivery.updateMany({\n where: { id },\n data: { state, error, processedAt: at, attempts: { increment: 1 } },\n });\n },\n async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {\n return (await (await client()).messagingInboxDelivery.findMany({\n where: { state: { in: [\"PENDING\", \"FAILED\"] }, attempts: { lt: maxAttempts }, receivedAt: { lt: receivedBefore } },\n orderBy: { receivedAt: \"asc\" },\n take,\n select: DELIVERY_VIEW,\n })) as InboxDeliveryView[];\n },\n };\n}\n\ntype ConnectionOperations = Pick<\n MessagingStore,\n \"findConnectionByAccount\" | \"getConnection\" | \"listConnections\" | \"saveConnection\" | \"setConnectionStatus\"\n>;\n\nfunction connectionOperations(client: Client): ConnectionOperations {\n const findConnectionByAccount = async (channel: string, externalAccountId: string) =>\n ((await (await client()).messagingConnection.findUnique({\n where: { channel_externalAccountId: { channel, externalAccountId } },\n })) as StoredConnection | null) ?? null;\n return {\n findConnectionByAccount,\n async getConnection(tenantId, id) {\n return ((await (await client()).messagingConnection.findFirst({ where: { id, tenantId } })) as StoredConnection | null) ?? null;\n },\n async listConnections(tenantId) {\n return (await (await client()).messagingConnection.findMany({\n where: { tenantId },\n orderBy: { connectedAt: \"asc\" },\n select: CONNECTION_VIEW,\n })) as ConnectionView[];\n },\n async saveConnection(input) {\n const delegate = (await client()).messagingConnection;\n const data = { ...input, status: \"CONNECTED\", statusReason: null, revokedAt: null };\n // Twice at most: a lost insert race turns into an update of the winner's row.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const existing = await findConnectionByAccount(input.channel, input.externalAccountId);\n if (!existing) {\n try {\n return (await delegate.create({ data, select: CONNECTION_VIEW })) as ConnectionView;\n } catch (error) {\n if (!isUniqueViolation(error)) throw error;\n continue;\n }\n }\n // The takeover is conditional in the write itself: the tenant's own row, or a REVOKED one.\n const where = existing.tenantId === input.tenantId ? { id: existing.id, tenantId: input.tenantId } : { id: existing.id, status: \"REVOKED\" };\n const updated = await delegate.updateMany({ where, data });\n if (updated.count === 0) return null;\n return (await delegate.findUnique({ where: { id: existing.id }, select: CONNECTION_VIEW })) as ConnectionView;\n }\n return null;\n },\n async setConnectionStatus(tenantId, id, patch) {\n const result = await (await client()).messagingConnection.updateMany({ where: { id, tenantId }, data: patch });\n return result.count > 0;\n },\n };\n}\n\ntype ConversationOperations = Pick<\n MessagingStore,\n \"findConversation\" | \"getConversation\" | \"createConversation\" | \"updateConversation\"\n>;\n\nfunction conversationOperations(client: Client): ConversationOperations {\n const findConversation = async (tenantId: string, channel: string, contactId: string) => {\n const row = (await (await client()).messagingConversation.findUnique({\n where: { tenantId_channel_contactId: { tenantId, channel, contactId } },\n })) as ConversationView | null;\n return row ? pickConversation(row) : null;\n };\n return {\n findConversation,\n async getConversation(tenantId, id) {\n const row = (await (await client()).messagingConversation.findFirst({ where: { id, tenantId } })) as ConversationView | null;\n return row ? pickConversation(row) : null;\n },\n async createConversation(input) {\n try {\n return pickConversation((await (await client()).messagingConversation.create({ data: input })) as ConversationView);\n } catch (error) {\n if (!isUniqueViolation(error)) throw error;\n const raced = await findConversation(input.tenantId, input.channel, input.contactId);\n if (!raced) throw error;\n return raced;\n }\n },\n async updateConversation(tenantId, id, patch, guard) {\n const delegate = (await client()).messagingConversation;\n const result = await delegate.updateMany({ where: { id, tenantId, ...guardWhere(guard) }, data: patch });\n if (result.count === 0) return null;\n return pickConversation((await delegate.findUnique({ where: { id } })) as ConversationView);\n },\n };\n}\n\n/** A guard as the `where` clause of the one `updateMany` that makes the write a compare-and-set. */\nfunction guardWhere(guard: ConversationGuard | undefined): Record<string, unknown> {\n if (!guard) return {};\n const { state, stateNot, lastInboundAt, lastMessageAt, optedOutAt } = guard;\n return {\n ...(state !== undefined ? { state } : {}),\n ...(stateNot !== undefined ? { state: { not: stateNot } } : {}),\n ...(lastInboundAt !== undefined ? { lastInboundAt } : {}),\n ...(lastMessageAt !== undefined ? { lastMessageAt } : {}),\n ...(optedOutAt !== undefined ? { optedOutAt } : {}),\n };\n}\n\ntype MessageOperations = Pick<\n MessagingStore,\n \"findMessageByExternalId\" | \"insertMessage\" | \"updateMessage\" | \"listMessages\" | \"applyReceipt\"\n>;\n\nfunction messageOperations(client: Client): MessageOperations {\n const findMessageByExternalId = async (channel: string, externalId: string) =>\n ((await (await client()).messagingMessage.findUnique({\n where: { channel_externalId: { channel, externalId } },\n })) as MessageView | null) ?? null;\n return {\n findMessageByExternalId,\n async insertMessage(input) {\n try {\n return { created: true, message: (await (await client()).messagingMessage.create({ data: input })) as MessageView };\n } catch (error) {\n if (!isUniqueViolation(error) || input.externalId === null) throw error;\n const existing = await findMessageByExternalId(input.channel, input.externalId);\n if (!existing) throw error;\n return { created: false, message: existing };\n }\n },\n async updateMessage(tenantId, id, patch) {\n const delegate = (await client()).messagingMessage;\n const result = await delegate.updateMany({ where: { id, tenantId }, data: patch });\n if (result.count === 0) return null;\n return (await delegate.findUnique({ where: { id } })) as MessageView;\n },\n async listMessages(tenantId, conversationId) {\n return (await (await client()).messagingMessage.findMany({\n where: { tenantId, conversationId },\n orderBy: { createdAt: \"asc\" },\n })) as MessageView[];\n },\n applyReceipt: (input) => applyReceipt(client, input),\n };\n}\n\nasync function applyReceipt(client: Client, input: Parameters<MessagingStore[\"applyReceipt\"]>[0]): Promise<boolean> {\n const { tenantId, channel, externalId, status, at, error } = input;\n const delegate = (await client()).messagingMessage;\n const scope = { tenantId, channel, externalId, direction: \"OUTBOUND\" };\n const found = (await delegate.findFirst({ where: scope, select: { id: true } })) as { id: string } | null;\n if (!found) return false;\n const column = RECEIPT_COLUMN[status];\n // The timestamp column is written once: a second identical receipt matches\n // nothing. Then the status moves only forward, in a second guarded write,\n // so a late SENT never overwrites a READ.\n await delegate.updateMany({\n where: { id: found.id, [column]: null },\n data: { [column]: at, ...(error !== null ? { error } : {}) },\n });\n await delegate.updateMany({\n where: { id: found.id, deliveryStatus: { in: statusesBelow(status) } },\n data: { deliveryStatus: status },\n });\n return true;\n}\n\nasync function purgeExpiredText(\n client: Client,\n { cutoff, take }: { cutoff: Date; take: number },\n): Promise<{ conversations: number; messages: number }> {\n const db = await client();\n const due = (await db.messagingConversation.findMany({\n where: { hasText: true, lastMessageAt: { lt: cutoff } },\n orderBy: { lastMessageAt: \"asc\" },\n take,\n select: { id: true },\n })) as { id: string }[];\n if (due.length === 0) return { conversations: 0, messages: 0 };\n const ids = due.map((row) => row.id);\n const purged = await db.messagingMessage.updateMany({\n where: { conversationId: { in: ids }, createdAt: { lte: cutoff } },\n data: { body: null, options: null, transcript: null },\n });\n // Guarded on the same predicate: a conversation that took a message since\n // the read above keeps its flag, and its new text.\n await db.messagingConversation.updateMany({\n where: { id: { in: ids }, lastMessageAt: { lt: cutoff } },\n data: { hasText: false },\n });\n return { conversations: due.length, messages: purged.count };\n}\n\nasync function purgeExpiredDeliveries(\n client: Client,\n { cutoff, maxAttempts, take }: { cutoff: Date; maxAttempts: number; take: number },\n): Promise<number> {\n const delegate = (await client()).messagingInboxDelivery;\n const batches = [\n { state: \"PROCESSED\", receivedAt: { lt: cutoff } },\n { state: \"FAILED\", receivedAt: { lt: cutoff }, attempts: { gte: maxAttempts } },\n ];\n let deleted = 0;\n for (const where of batches) {\n const due = (await delegate.findMany({ where, orderBy: { receivedAt: \"asc\" }, take, select: { id: true } })) as { id: string }[];\n if (due.length === 0) continue;\n deleted += (await delegate.deleteMany({ where: { id: { in: due.map((row) => row.id) } } })).count;\n }\n return deleted;\n}\n\n/** Every status a receipt may move a message forward from. */\nfunction statusesBelow(status: ReceiptStatus): DeliveryStatus[] {\n return (Object.keys(DELIVERY_RANK) as DeliveryStatus[]).filter((candidate) => DELIVERY_RANK[candidate] < DELIVER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AAA,EACzB,CAAC;AACD,SAAO,EAAE,eAAe,IAAI,QAAQ,UAAU,OAAO,MAAM;AAC7D;AAxBe;AA0Bf,eAAe,uBACb,QACA,EAAE,QAAQ,aAAa,KAAK,GACX;AACjB,QAAM,YAAY,MAAM,OAAO,GAAG;AAClC,QAAM,UAAU;AAAA,IACd,EAAE,OAAO,aAAa,YAAY,EAAE,IAAI,OAAO,EAAE;AAAA,IACjD,EAAE,OAAO,UAAU,YAAY,EAAE,IAAI,OAAO,GAAG,UAAU,EAAE,KAAK,YAAY,EAAE;AAAA,EAChF;AACA,MAAI,UAAU;AACd,aAAW,SAAS,SAAS;AAC3B,UAAM,MAAO,MAAM,SAAS,SAAS,EAAE,OAAO,SAAS,EAAE,YAAY,MAAM,GAAG,MAAM,QAAQ,EAAE,IAAI,KAAK,EAAE,CAAC;AAC1G,QAAI,IAAI,WAAW,EAAG;AACtB,gBAAY,MAAM,SAAS,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,IAAI,IAAI,CAAC,QAAQ,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG;AAAA,EAC9F;AACA,SAAO;AACT;AAhBe;AAmBf,SAAS,cAAc,QAAyC;AAC9D,SAAQ,OAAO,KAAK,aAAa,EAAuB,OAAO,CAAC,cAAc,cAAc,SAAS,IAAI,cAAc,MAAM,CAAC;AAChI;AAFS;","names":["bodyHash","bodyHash"]}
1
+ {"version":3,"sources":["../src/core/connections.ts","../src/core/ports.ts","../src/core/context.ts","../src/core/hash.ts","../src/core/inbound.ts","../src/core/inbox.ts","../src/core/retention.ts","../src/core/sender.ts","../src/core/engine.ts","../src/core/memory-store.ts","../src/core/store.ts","../src/core/prisma-store.ts"],"sourcesContent":["import type { EngineContext } from \"./context\";\nimport { MessagingConnectError } from \"./errors\";\nimport type { ConnectionView } from \"./types\";\n\nexport interface ConnectInput {\n tenantId: string;\n channel: string;\n /** The channel's id for the account (WhatsApp's phone_number_id). */\n externalAccountId: string;\n /** The channel's parent account (WhatsApp's WABA id), when it has one. */\n externalParentId?: string | null;\n displayAddress: string;\n /** The credential in clear (a business token). Sealed here; never stored, returned or logged in clear. */\n credential: string;\n}\n\n/**\n * Connect an account to a tenant. The account is UNIQUE across tenants: one\n * held by another tenant (connected, or in error) is refused\n * (`ACCOUNT_TAKEN`); only one that tenant revoked may be connected by another,\n * who proves it through the channel's own signup. Re-connecting one's own\n * account replaces its credential and clears its error.\n */\nexport async function connect(ctx: EngineContext, input: ConnectInput): Promise<ConnectionView> {\n const { store, secrets, clock } = ctx.config;\n if (!ctx.adapters.has(input.channel)) {\n throw new MessagingConnectError(\"UNKNOWN_CHANNEL\", `no adapter for channel \"${input.channel}\"`);\n }\n const existing = await store.findConnectionByAccount(input.channel, input.externalAccountId);\n if (existing && existing.tenantId !== input.tenantId && existing.status !== \"REVOKED\") {\n throw new MessagingConnectError(\"ACCOUNT_TAKEN\", `account ${input.externalAccountId} is held by another tenant`);\n }\n const saved = await store.saveConnection({\n tenantId: input.tenantId,\n channel: input.channel,\n externalAccountId: input.externalAccountId,\n externalParentId: input.externalParentId ?? null,\n displayAddress: input.displayAddress,\n credentialSealed: await secrets.seal(input.credential),\n connectedAt: clock.now(),\n });\n // The store's write is conditional, so a connect that lost a race for the account is refused here too.\n if (!saved) throw new MessagingConnectError(\"ACCOUNT_TAKEN\", `account ${input.externalAccountId} is held by another tenant`);\n return saved;\n}\n\n/**\n * Revoke a tenant's connection: inbound traffic for it is dropped, sends are\n * refused, and the sealed credential is cleared — disconnecting removes the token.\n */\nexport async function revoke(ctx: EngineContext, tenantId: string, connectionId: string, reason: string | null = null) {\n return ctx.config.store.setConnectionStatus(tenantId, connectionId, {\n status: \"REVOKED\",\n statusReason: reason,\n revokedAt: ctx.config.clock.now(),\n credentialSealed: null,\n });\n}\n\n/** Mark a connection in error (a token the channel rejects): treated as revoked until re-connected. */\nexport async function markError(ctx: EngineContext, tenantId: string, connectionId: string, reason: string) {\n return ctx.config.store.setConnectionStatus(tenantId, connectionId, {\n status: \"ERROR\",\n statusReason: reason.slice(0, 500),\n revokedAt: null,\n });\n}\n","import type { ChannelAdapter } from \"./channel\";\nimport type { MessagingStore } from \"./store\";\nimport type { ConversationState, ConversationView, MessageView, NormalizedEvent } from \"./types\";\n\n/**\n * What the engine needs FROM its host. The mechanism (the inbox, the tenant\n * resolution, the conversation states, the outbound bookkeeping, the\n * retention) is the engine's and appears nowhere here.\n */\n\n/**\n * Sealing and opening a stored credential. The KEY is the host's: the package\n * never sees it. `open` THROWS on a ciphertext that will not open — a row\n * sealed under a rotated key must fail a send loudly, never read as \"no\n * credential\".\n */\nexport interface MessagingSecretsPort {\n seal(plaintext: string): string | Promise<string>;\n open(sealed: string): string | Promise<string>;\n}\n\n/**\n * Defer one job run by wire name — the shape of `@12-apps/wiring/ports`'\n * `JobsEnqueuePort`. Never throws. The engine enqueues only its own\n * namespaced job (`messaging.process-delivery`).\n */\nexport interface MessagingEnqueuePort {\n enqueue(\n name: string,\n payload: unknown,\n options?: { dedupeKey?: string },\n ): Promise<{ enqueued: boolean; reason?: string }>;\n}\n\n/** The clock, so a test or a replay decides what \"now\" is. */\nexport interface MessagingClockPort {\n now(): Date;\n}\n\n/** Where the engine says what it did — the wiring `LoggerPort` shape. Never handed a credential. */\nexport interface MessagingLogger {\n info(message: string, ...meta: unknown[]): void;\n warn(message: string, ...meta: unknown[]): void;\n error(message: string, ...meta: unknown[]): void;\n}\n\n/** What `onInboundMessage` is told: the conversation as it now stands, and the stored message. */\nexport interface InboundMessageNotice {\n conversation: ConversationView;\n message: MessageView;\n}\n\n/** What a re-opened conversation may become. */\nexport type ReopenState = Exclude<ConversationState, \"OPTED_OUT\">;\n\n/** The host's answers to what only it knows about a conversation. All optional. */\nexport interface MessagingHooks {\n /**\n * A contact's message was stored. The host's agent (or a person's inbox)\n * picks it up here. Called once per stored message, never for a redelivery,\n * and NOT for a message that opted the contact out — nothing may be said to\n * them. Keep it short (enqueue the host's own job): a throw is logged, never\n * retried, because the message is already stored. Default: nothing.\n */\n onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;\n /**\n * The state a CLOSED or OPTED_OUT conversation re-opens into when its\n * contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`\n * (only the contact's own words put a conversation there): the type refuses\n * it, and an answer that slips through anyway is read as `AGENT`.\n */\n reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;\n /**\n * Events of a channel account NOBODY connected: a message, an opt-out or a\n * delivery receipt of a number the host itself owns on the same app (its\n * platform notification number, typically), which no tenant row resolves.\n *\n * Without this hook they are dropped, exactly as before. With it, the host is\n * handed them once per processed delivery: already signature-checked,\n * persisted and parsed, and still stored nowhere here (no conversation, no\n * message). An event of a CONNECTED, revoked or errored tenant account is\n * never handed over: a tenant's traffic is the tenant's, and the host's\n * platform path must not see it.\n *\n * A throw settles the delivery FAILED, so the reconciliation sweep runs it\n * again: the host's handler must be idempotent on the provider's message id.\n * Default: nothing.\n */\n onUnclaimedEvents?(channel: string, events: NormalizedEvent[]): Promise<void> | void;\n}\n\n/** Everything a host hands `createMessagingEngine`. */\nexport interface MessagingEngineConfig {\n store: MessagingStore;\n /** One per channel — `createWhatsAppAdapter(...)` and, later, its siblings. */\n adapters: readonly ChannelAdapter[];\n secrets: MessagingSecretsPort;\n enqueue: MessagingEnqueuePort;\n clock: MessagingClockPort;\n logger: MessagingLogger;\n hooks?: MessagingHooks;\n /**\n * How long a conversation's text is kept after its LAST message, in\n * milliseconds. Default 12 hours: the conversation lives in the contact's\n * own app, not with the tenant.\n */\n retentionMs?: number;\n /** How many conversations one retention pass purges. Default 500. */\n retentionBatchSize?: number;\n /** How many stored deliveries one reconciliation pass re-runs. Default 50. */\n reconcileBatchSize?: number;\n /** How many times a stored delivery may be processed before it is left for a person. Default 5. */\n maxDeliveryAttempts?: number;\n /**\n * How old an unprocessed delivery must be before the reconciliation sweep\n * re-runs it, so the sweep never races the job the webhook just queued.\n * Default 2 minutes.\n */\n reconcileAfterMs?: number;\n}\n\n/** The defaults the config's optional numbers take. */\nexport const MESSAGING_DEFAULTS = {\n retentionMs: 12 * 60 * 60 * 1000,\n retentionBatchSize: 500,\n reconcileBatchSize: 50,\n maxDeliveryAttempts: 5,\n reconcileAfterMs: 2 * 60 * 1000,\n} as const;\n","import type { ChannelAdapter } from \"./channel\";\nimport { MESSAGING_DEFAULTS, type MessagingEngineConfig } from \"./ports\";\n\n/** The config with every default applied, and the adapters keyed by channel. */\nexport interface EngineContext {\n config: MessagingEngineConfig & Required<Pick<MessagingEngineConfig, keyof typeof MESSAGING_DEFAULTS>>;\n adapters: ReadonlyMap<string, ChannelAdapter>;\n}\n\n/** Build the context; a channel mounted twice is a configuration error. */\nexport function engineContext(config: MessagingEngineConfig): EngineContext {\n const adapters = new Map<string, ChannelAdapter>();\n for (const adapter of config.adapters) {\n if (adapters.has(adapter.kind)) throw new Error(`messaging: channel \"${adapter.kind}\" is mounted twice`);\n adapters.set(adapter.kind, adapter);\n }\n return {\n config: {\n ...config,\n retentionMs: config.retentionMs ?? MESSAGING_DEFAULTS.retentionMs,\n retentionBatchSize: config.retentionBatchSize ?? MESSAGING_DEFAULTS.retentionBatchSize,\n reconcileBatchSize: config.reconcileBatchSize ?? MESSAGING_DEFAULTS.reconcileBatchSize,\n maxDeliveryAttempts: config.maxDeliveryAttempts ?? MESSAGING_DEFAULTS.maxDeliveryAttempts,\n reconcileAfterMs: config.reconcileAfterMs ?? MESSAGING_DEFAULTS.reconcileAfterMs,\n },\n adapters,\n };\n}\n","import { createHash } from \"node:crypto\";\n\n/** The inbox key of a raw body: its SHA-256, hex. A redelivery is the same bytes, so the same key. */\nexport function bodyHash(rawBody: string): string {\n return createHash(\"sha256\").update(rawBody, \"utf8\").digest(\"hex\");\n}\n","import type { EngineContext } from \"./context\";\nimport { errorText } from \"./errors\";\nimport type { StoredConnection } from \"./store\";\nimport type {\n ConversationState,\n ConversationView,\n InboundContent,\n InboundMessageEvent,\n MessageView,\n NormalizedEvent,\n OptOutEvent,\n} from \"./types\";\n\n/**\n * One normalized event, applied. The tenant is resolved HERE, from the\n * event's channel account against the connections — never from the URL, which\n * for a channel like WhatsApp is one callback shared by every tenant. An\n * account nobody connected, or one revoked or in error, resolves to nobody:\n * the event is dropped (the edge already answered 200, so the channel stops\n * redelivering) and a tenant can never receive another tenant's traffic.\n */\n\nexport type EventOutcome =\n | { kind: \"dropped\"; reason: \"unknown-account\" | \"not-connected\" }\n | { kind: \"duplicate\" }\n | { kind: \"message\"; conversationId: string; messageId: string }\n | { kind: \"opted-out\"; conversationId: string }\n | { kind: \"receipt\"; applied: boolean };\n\nexport async function handleEvent(ctx: EngineContext, channel: string, event: NormalizedEvent): Promise<EventOutcome> {\n const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);\n if (!connection) return { kind: \"dropped\", reason: \"unknown-account\" };\n if (connection.status !== \"CONNECTED\") return { kind: \"dropped\", reason: \"not-connected\" };\n\n if (event.type === \"message\") return handleMessage(ctx, connection, event);\n if (event.type === \"opt_out\") return handleOptOut(ctx, connection, event);\n const applied = await ctx.config.store.applyReceipt({\n tenantId: connection.tenantId,\n channel,\n externalId: event.externalId,\n status: event.status,\n at: event.at,\n error: event.error,\n });\n return { kind: \"receipt\", applied };\n}\n\n/** The text a message row keeps, and the channel reference beside it. */\nfunction columnsOf(content: InboundContent): { kind: InboundContent[\"kind\"]; body: string | null; attachmentRef: string | null } {\n switch (content.kind) {\n case \"TEXT\":\n return { kind: \"TEXT\", body: content.text, attachmentRef: null };\n case \"INTERACTIVE\":\n return { kind: \"INTERACTIVE\", body: content.title, attachmentRef: content.replyId };\n case \"AUDIO\":\n return { kind: \"AUDIO\", body: null, attachmentRef: content.mediaId };\n default:\n return { kind: \"OTHER\", body: null, attachmentRef: null };\n }\n}\n\nconst later = (a: Date | null, b: Date): Date => (a && a > b ? a : b);\n\n/** How many times a conversation write is re-decided after losing a compare-and-set. */\nconst MAX_WRITE_ATTEMPTS = 6;\n\nasync function handleMessage(\n ctx: EngineContext,\n connection: StoredConnection,\n event: InboundMessageEvent,\n): Promise<EventOutcome> {\n const { store } = ctx.config;\n if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: \"duplicate\" };\n\n const columns = columnsOf(event.content);\n const conversation = await openConversation(ctx, connection, event, columns.body !== null);\n const inserted = await store.insertMessage({\n conversationId: conversation.id,\n tenantId: connection.tenantId,\n channel: connection.channel,\n direction: \"INBOUND\",\n ...columns,\n options: null,\n externalId: event.externalId,\n deliveryStatus: \"RECEIVED\",\n authorKind: \"CONTACT\",\n staffUserId: null,\n createdAt: event.sentAt,\n });\n if (!inserted.created) return { kind: \"duplicate\" };\n // Stored, but nothing may be said: the contact opted out with this message,\n // or this one was sent BEFORE their opt-out and only now got processed.\n if (event.optOut || conversation.state === \"OPTED_OUT\") return { kind: \"opted-out\", conversationId: conversation.id };\n\n await notifyHost(ctx, conversation, inserted.message);\n return { kind: \"message\", conversationId: conversation.id, messageId: inserted.message.id };\n}\n\n/**\n * Create the conversation, or bring an existing one up to this message.\n *\n * Every write to an existing row is a compare-and-set on what was read (its\n * state and its two timestamps): a worker that lost the race re-reads and\n * decides again, so a stale read can never put back a state another worker\n * just changed — an opt-out above all.\n */\nasync function openConversation(\n ctx: EngineContext,\n connection: StoredConnection,\n event: InboundMessageEvent,\n carriesText: boolean,\n): Promise<ConversationView> {\n const { store } = ctx.config;\n for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {\n const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);\n // A lost insert race answers a null: go again, and the winner's row is `existing`.\n const result = existing\n ? await updateExisting(ctx, connection, existing, event, carriesText)\n : await createFirst(ctx, connection, event, carriesText);\n if (result) return result;\n }\n throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);\n}\n\n/** The first message of a contact opens the conversation; null when another worker's insert won. */\nasync function createFirst(\n ctx: EngineContext,\n connection: StoredConnection,\n event: InboundMessageEvent,\n carriesText: boolean,\n): Promise<ConversationView | null> {\n const state = event.optOut ? \"OPTED_OUT\" : \"AGENT\";\n const created = await ctx.config.store.createConversation({\n tenantId: connection.tenantId,\n channel: connection.channel,\n contactId: event.contactId,\n contactName: event.contactName,\n connectionId: connection.id,\n state,\n lastInboundAt: event.sentAt,\n lastMessageAt: event.sentAt,\n optedOutAt: event.optOut ? event.sentAt : null,\n hasText: carriesText,\n });\n return created.state === state && created.lastInboundAt?.getTime() === event.sentAt.getTime() ? created : null;\n}\n\n/** Bring an existing conversation up to this message; null when the compare-and-set lost. */\nasync function updateExisting(\n ctx: EngineContext,\n connection: StoredConnection,\n existing: ConversationView,\n event: InboundMessageEvent,\n carriesText: boolean,\n): Promise<ConversationView | null> {\n const state = await nextState(ctx, existing, event);\n return ctx.config.store.updateConversation(\n connection.tenantId,\n existing.id,\n {\n // Left out when unchanged: the write never carries a state it did not decide.\n ...(state !== existing.state ? { state } : {}),\n ...(event.optOut ? { optedOutAt: later(existing.optedOutAt, event.sentAt) } : {}),\n ...(connection.id !== existing.connectionId ? { connectionId: connection.id } : {}),\n lastInboundAt: later(existing.lastInboundAt, event.sentAt),\n lastMessageAt: later(existing.lastMessageAt, event.sentAt),\n ...(event.contactName ? { contactName: event.contactName } : {}),\n ...(carriesText ? { hasText: true } : {}),\n },\n { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },\n );\n}\n\n/**\n * An opt-out wins. A message re-opens a CLOSED conversation, and an OPTED_OUT\n * one only when it was sent AFTER the opt-out (the message's own time, so a\n * delivery processed late, out of order, never undoes it).\n */\nasync function nextState(ctx: EngineContext, conversation: ConversationView, event: InboundMessageEvent): Promise<ConversationState> {\n if (event.optOut) return \"OPTED_OUT\";\n if (conversation.state === \"OPTED_OUT\") {\n if (conversation.optedOutAt && event.sentAt <= conversation.optedOutAt) return \"OPTED_OUT\";\n } else if (conversation.state !== \"CLOSED\") {\n return conversation.state;\n }\n // The type refuses OPTED_OUT; a JavaScript host that returns it anyway is read as the default.\n const chosen = (await ctx.config.hooks?.reopenState?.(conversation)) as ConversationState | undefined;\n return chosen && chosen !== \"OPTED_OUT\" ? chosen : \"AGENT\";\n}\n\nasync function notifyHost(\n ctx: EngineContext,\n conversation: ConversationView,\n message: MessageView,\n): Promise<void> {\n const hook = ctx.config.hooks?.onInboundMessage;\n if (!hook) return;\n try {\n await hook({ conversation, message });\n } catch (error) {\n // The message is stored; a retry of the delivery would be a no-op, so the\n // hook's failure is the host's to log and recover from, never a re-run.\n ctx.config.logger.error(`messaging.inbound: onInboundMessage failed for ${conversation.id}: ${errorText(error)}`, { error });\n }\n}\n\nasync function handleOptOut(ctx: EngineContext, connection: StoredConnection, event: OptOutEvent): Promise<EventOutcome> {\n const { store } = ctx.config;\n for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {\n const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);\n if (!existing) {\n // No conversation yet: one is opened in OPTED_OUT, so a later send is refused.\n const created = await store.createConversation({\n tenantId: connection.tenantId,\n channel: connection.channel,\n contactId: event.contactId,\n contactName: null,\n connectionId: connection.id,\n state: \"OPTED_OUT\",\n lastInboundAt: null,\n lastMessageAt: null,\n optedOutAt: event.at,\n hasText: false,\n });\n if (created.state === \"OPTED_OUT\") return { kind: \"opted-out\", conversationId: created.id };\n continue;\n }\n const updated = await store.updateConversation(\n connection.tenantId,\n existing.id,\n {\n ...(existing.state !== \"OPTED_OUT\" ? { state: \"OPTED_OUT\" as const } : {}),\n optedOutAt: later(existing.optedOutAt, event.at),\n },\n { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt },\n );\n if (updated) return { kind: \"opted-out\", conversationId: existing.id };\n }\n throw new Error(`conversation ${event.contactId} kept changing under this opt-out; retry`);\n}\n","import type { EngineContext } from \"./context\";\nimport { errorText } from \"./errors\";\nimport { bodyHash } from \"./hash\";\nimport { handleEvent, type EventOutcome } from \"./inbound\";\nimport type { NormalizedEvent } from \"./types\";\n\n/**\n * The durable inbox: persist the raw delivery, ACK, then process in a job.\n *\n * Nothing is resolved before the row is written — not the tenant, not even\n * whether the body parses — because the one thing a webhook must never do is\n * lose a delivery to a bug in the code that reads it. The raw bytes are kept\n * so a mapping bug can be replayed once fixed — until the retention sweep\n * deletes them, with the conversation's text, past the retention window.\n */\n\n/** The job the engine enqueues per fresh delivery, by wire name. */\nexport const PROCESS_DELIVERY_JOB = \"messaging.process-delivery\";\n\n/** Store one verified delivery and queue its processing. Redeliveries are stored once. */\nexport async function receiveDelivery(\n ctx: EngineContext,\n channel: string,\n rawBody: string,\n): Promise<{ deliveryId: string; fresh: boolean }> {\n const { store, clock, enqueue, logger } = ctx.config;\n const recorded = await store.recordDelivery({ channel, bodyHash: bodyHash(rawBody), rawBody, receivedAt: clock.now() });\n if (recorded.fresh) {\n const queued = await enqueue.enqueue(\n PROCESS_DELIVERY_JOB,\n { deliveryId: recorded.id },\n { dedupeKey: `${PROCESS_DELIVERY_JOB}:${recorded.id}` },\n );\n // Never fatal: the row is stored, and the reconciliation sweep runs it.\n if (!queued.enqueued) logger.warn(`messaging.inbox: delivery ${recorded.id} not queued (${queued.reason ?? \"no reason\"})`);\n }\n return { deliveryId: recorded.id, fresh: recorded.fresh };\n}\n\n/** What processing one stored delivery did. */\nexport type DeliveryOutcome =\n | { kind: \"missing\" }\n | { kind: \"already-processed\" }\n | { kind: \"processed\"; events: EventOutcome[] }\n | { kind: \"unreadable\"; reason: string };\n\n/**\n * Process one stored delivery. Every event handler is idempotent (messages\n * dedupe on their channel id, receipts on their column), so a retry after a\n * partial failure redoes nothing. A throw settles the row FAILED and is\n * rethrown, so the job's own retry runs it again; a receipt that found no\n * message to land on settles it FAILED too, left to the reconciliation sweep.\n */\nexport async function processDelivery(ctx: EngineContext, deliveryId: string): Promise<DeliveryOutcome> {\n const { store, clock, logger } = ctx.config;\n const row = await store.getDelivery(deliveryId);\n if (!row) return { kind: \"missing\" };\n if (row.state === \"PROCESSED\") return { kind: \"already-processed\" };\n\n const adapter = ctx.adapters.get(row.channel);\n let events: NormalizedEvent[];\n try {\n if (!adapter) throw new Error(`no adapter mounted for channel \"${row.channel}\"`);\n events = adapter.parse(row.rawBody);\n } catch (error) {\n // The same bytes will never read differently: settle it, with the reason,\n // rather than retry. The raw body stays for a replay until retention deletes it.\n const reason = errorText(error);\n logger.warn(`messaging.inbox: delivery ${deliveryId} unreadable: ${reason}`);\n await store.settleDelivery(deliveryId, { state: \"PROCESSED\", error: `unreadable: ${reason}`, at: clock.now() });\n return { kind: \"unreadable\", reason };\n }\n\n try {\n const outcomes: EventOutcome[] = [];\n for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));\n // Inside the try: a throwing hook settles the row FAILED for the sweep.\n await handOverUnclaimed(ctx, row.channel, events, outcomes);\n // A receipt for a message nobody stored yet (it raced the sender's own\n // write of the channel id) changed nothing: settle FAILED, not PROCESSED,\n // so the reconciliation sweep applies it once the id exists.\n const unapplied = outcomes.filter((outcome) => outcome.kind === \"receipt\" && !outcome.applied).length;\n if (unapplied > 0) {\n const error = `${unapplied} receipt(s) for a message not stored yet`;\n logger.warn(`messaging.inbox: delivery ${deliveryId}: ${error}`);\n await store.settleDelivery(deliveryId, { state: \"FAILED\", error, at: clock.now() });\n } else {\n await store.settleDelivery(deliveryId, { state: \"PROCESSED\", error: null, at: clock.now() });\n }\n return { kind: \"processed\", events: outcomes };\n } catch (error) {\n await store.settleDelivery(deliveryId, { state: \"FAILED\", error: errorText(error), at: clock.now() });\n throw error;\n }\n}\n\n/**\n * The events whose account nobody connected, handed to the host's\n * `onUnclaimedEvents` (its own number on the shared app). Only `unknown-account`\n * drops: a revoked or errored account is a tenant's, never the host's.\n */\nasync function handOverUnclaimed(\n ctx: EngineContext,\n channel: string,\n events: readonly NormalizedEvent[],\n outcomes: readonly EventOutcome[],\n): Promise<void> {\n const hook = ctx.config.hooks?.onUnclaimedEvents;\n if (!hook) return;\n const unclaimed = events.filter((_, index) => {\n const outcome = outcomes[index];\n return outcome?.kind === \"dropped\" && outcome.reason === \"unknown-account\";\n });\n if (unclaimed.length > 0) await hook(channel, unclaimed);\n}\n\n/**\n * Re-run deliveries left unprocessed (a dead worker, a refused enqueue, a\n * failure) once they are older than the job's own retry span. One delivery's\n * failure never stops the batch.\n */\nexport async function reconcileInbox(ctx: EngineContext): Promise<{ retried: number; failed: number }> {\n const { store, clock, logger, reconcileAfterMs, maxDeliveryAttempts, reconcileBatchSize } = ctx.config;\n const due = await store.listRetryableDeliveries({\n receivedBefore: new Date(clock.now().getTime() - reconcileAfterMs),\n maxAttempts: maxDeliveryAttempts,\n take: reconcileBatchSize,\n });\n let failed = 0;\n for (const row of due) {\n try {\n await processDelivery(ctx, row.id);\n } catch (error) {\n failed += 1;\n logger.warn(`messaging.inbox: delivery ${row.id} failed again: ${errorText(error)}`);\n }\n }\n return { retried: due.length, failed };\n}\n","import type { EngineContext } from \"./context\";\n\n/**\n * The retention sweep. A conversation's TEXT lives only while the\n * conversation does: `retentionMs` (default 12 h) after its LAST message,\n * every message's body, choices and transcript are deleted. The conversation\n * row, its state and its structured summary stay — they are what the next\n * conversation with the same contact starts from.\n *\n * The same cutoff deletes the raw inbox rows (Meta's whole payload: the text,\n * the phone number, the profile name): the PROCESSED ones, and the FAILED ones\n * nothing will retry any more. What stays of a delivery is nothing; dedupe\n * lives on the message row's `(channel, external_id)`, which outlives the text.\n *\n * One indexed query finds the due conversations across every tenant (never a\n * walk over tenants); a pass that fills its batch says so, and the next tick\n * takes the rest.\n */\nexport async function sweepRetention(\n ctx: EngineContext,\n): Promise<{ conversations: number; messages: number; deliveries: number; more: boolean }> {\n const { store, clock, retentionMs, retentionBatchSize, maxDeliveryAttempts } = ctx.config;\n const cutoff = new Date(clock.now().getTime() - retentionMs);\n const text = await store.purgeExpiredText({ cutoff, take: retentionBatchSize });\n const deliveries = await store.purgeExpiredDeliveries({ cutoff, maxAttempts: maxDeliveryAttempts, take: retentionBatchSize });\n return { ...text, deliveries, more: text.conversations === retentionBatchSize || deliveries >= retentionBatchSize };\n}\n","import { ChannelSendFailure } from \"./channel\";\nimport type { EngineContext } from \"./context\";\nimport { errorText, MessagingSendError } from \"./errors\";\nimport type { StoredConnection } from \"./store\";\nimport type { ConversationView, MessageView, OutboundContent } from \"./types\";\n\n/** Who is sending: the host's agent, or a person on the tenant's staff. */\nexport type SendAuthor = { kind: \"AGENT\" } | { kind: \"STAFF\"; staffUserId?: string | null };\n\nexport interface SendInput {\n tenantId: string;\n conversationId: string;\n content: OutboundContent;\n author: SendAuthor;\n}\n\n/**\n * Send one message into a conversation.\n *\n * Refused, with nothing recorded, when the contact opted out, when the\n * channel's policy says the window is closed, or when the conversation's\n * connection is not connected. Otherwise the outbound row is recorded\n * PENDING BEFORE the channel is called — a crash mid-call leaves evidence, not\n * silence — then stamped ACCEPTED with the channel's id, or FAILED with the\n * channel's error (and the error is thrown).\n */\nexport async function sendMessage(ctx: EngineContext, input: SendInput): Promise<MessageView> {\n const { store, clock } = ctx.config;\n const conversation = await store.getConversation(input.tenantId, input.conversationId);\n if (!conversation) throw new MessagingSendError(\"NOT_FOUND\", `no conversation ${input.conversationId}`);\n const { adapter, connection } = await admit(ctx, conversation);\n\n const now = clock.now();\n const recorded = await store.insertMessage({\n conversationId: conversation.id,\n tenantId: conversation.tenantId,\n channel: conversation.channel,\n direction: \"OUTBOUND\",\n kind: input.content.kind === \"TEXT\" ? \"TEXT\" : \"INTERACTIVE\",\n body: input.content.text,\n options: optionsOf(input.content),\n attachmentRef: null,\n externalId: null,\n deliveryStatus: \"PENDING\",\n authorKind: input.author.kind,\n staffUserId: input.author.kind === \"STAFF\" ? (input.author.staffUserId ?? null) : null,\n createdAt: now,\n });\n await store.updateConversation(conversation.tenantId, conversation.id, {\n lastMessageAt: now,\n hasText: true,\n });\n\n let externalId: string;\n try {\n if (connection.credentialSealed === null) throw new Error(\"the connection holds no credential\");\n const credential = await ctx.config.secrets.open(connection.credentialSealed);\n ({ externalId } = await adapter.send({\n credential,\n accountId: connection.externalAccountId,\n to: conversation.contactId,\n content: input.content,\n }));\n } catch (error) {\n const reason = error instanceof ChannelSendFailure ? `${error.code}: ${error.message}` : errorText(error);\n await store.updateMessage(conversation.tenantId, recorded.message.id, {\n deliveryStatus: \"FAILED\",\n error: reason.slice(0, 500),\n failedAt: clock.now(),\n });\n throw new MessagingSendError(\"CHANNEL_FAILED\", reason, recorded.message.id);\n }\n const accepted = await store.updateMessage(conversation.tenantId, recorded.message.id, {\n externalId,\n deliveryStatus: \"ACCEPTED\",\n });\n return accepted ?? recorded.message;\n}\n\n/** The checks a send must pass before anything is written. */\nasync function admit(ctx: EngineContext, conversation: ConversationView) {\n if (conversation.state === \"OPTED_OUT\") {\n throw new MessagingSendError(\"OPTED_OUT\", `conversation ${conversation.id} opted out`);\n }\n const adapter = ctx.adapters.get(conversation.channel);\n if (!adapter) throw new MessagingSendError(\"UNKNOWN_CHANNEL\", `no adapter for channel \"${conversation.channel}\"`);\n const verdict = adapter.policy.check({ lastInboundAt: conversation.lastInboundAt, now: ctx.config.clock.now() });\n if (!verdict.allowed) {\n throw new MessagingSendError(verdict.reason, `conversation ${conversation.id}: the channel's window is closed`);\n }\n const connection: StoredConnection | null = await ctx.config.store.getConnection(\n conversation.tenantId,\n conversation.connectionId,\n );\n if (!connection || connection.status !== \"CONNECTED\") {\n throw new MessagingSendError(\"NOT_CONNECTED\", `conversation ${conversation.id}: its connection is not connected`);\n }\n return { adapter, connection };\n}\n\n/** An interactive message's choices, kept as JSON text beside its prompt. */\nfunction optionsOf(content: OutboundContent): string | null {\n if (content.kind === \"BUTTONS\") return JSON.stringify({ buttons: content.buttons });\n if (content.kind === \"LIST\") return JSON.stringify({ buttonLabel: content.buttonLabel, sections: content.sections });\n return null;\n}\n","import { connect, markError, revoke, type ConnectInput } from \"./connections\";\nimport { engineContext } from \"./context\";\nimport { processDelivery, receiveDelivery, reconcileInbox } from \"./inbox\";\nimport type { MessagingEngineConfig } from \"./ports\";\nimport { sweepRetention } from \"./retention\";\nimport { sendMessage, type SendInput } from \"./sender\";\nimport type { ConversationState, ConversationSummary } from \"./types\";\n\n/**\n * Mount the connector: one engine per process, over the host's store and\n * ports, with one adapter per channel.\n */\nexport function createMessagingEngine(config: MessagingEngineConfig) {\n const ctx = engineContext(config);\n const { store, clock } = ctx.config;\n return {\n /** The adapter mounted for a channel, or undefined. */\n adapter: (channel: string) => ctx.adapters.get(channel),\n /** The channels this engine serves. */\n channels: () => [...ctx.adapters.keys()],\n\n // ── The pipeline ─────────────────────────────────────────────────────────\n /** Store a VERIFIED raw delivery and queue its processing. The edge answers 200 after this. */\n receive: (channel: string, rawBody: string) => receiveDelivery(ctx, channel, rawBody),\n /** The `process-delivery` job's body. */\n processDelivery: (deliveryId: string) => processDelivery(ctx, deliveryId),\n /** The `reconcile-inbox` sweep's body. */\n reconcile: () => reconcileInbox(ctx),\n /** The `retention` sweep's body. */\n sweepRetention: () => sweepRetention(ctx),\n\n // ── Sending ──────────────────────────────────────────────────────────────\n send: (input: SendInput) => sendMessage(ctx, input),\n\n // ── Connections ──────────────────────────────────────────────────────────\n connect: (input: ConnectInput) => connect(ctx, input),\n revoke: (tenantId: string, connectionId: string, reason?: string | null) => revoke(ctx, tenantId, connectionId, reason),\n markError: (tenantId: string, connectionId: string, reason: string) => markError(ctx, tenantId, connectionId, reason),\n listConnections: (tenantId: string) => store.listConnections(tenantId),\n\n // ── Conversations, for the host's own surfaces ───────────────────────────\n getConversation: (tenantId: string, conversationId: string) => store.getConversation(tenantId, conversationId),\n listMessages: (tenantId: string, conversationId: string) => store.listMessages(tenantId, conversationId),\n /**\n * Move a conversation between AGENT, HUMAN and CLOSED (a hand-off). OPTED_OUT\n * is the contact's alone, both ways: an opted-out conversation is not\n * moved (null), and only the contact's next message re-opens it.\n */\n setState: (tenantId: string, conversationId: string, state: Exclude<ConversationState, \"OPTED_OUT\">) =>\n // ONE guarded write: an opt-out landing between a read and this write cannot be overwritten.\n store.updateConversation(tenantId, conversationId, { state }, { stateNot: \"OPTED_OUT\" }),\n /** Replace the structured summary that outlives the text. */\n setSummary: (tenantId: string, conversationId: string, summary: ConversationSummary) =>\n store.updateConversation(tenantId, conversationId, { summary, summaryUpdatedAt: clock.now() }),\n /** Store an audio message's transcript (deleted with the text). */\n setTranscript: async (tenantId: string, messageId: string, transcript: string) => {\n const message = await store.updateMessage(tenantId, messageId, { transcript });\n if (message) await store.updateConversation(tenantId, message.conversationId, { hasText: true });\n return message;\n },\n };\n}\n\nexport type MessagingEngine = ReturnType<typeof createMessagingEngine>;\n","import { randomUUID } from \"node:crypto\";\n\nimport { DELIVERY_RANK, RECEIPT_COLUMN, type ConversationGuard, type MessagingStore, type StoredConnection } from \"./store\";\nimport type { ConnectionView, ConversationView, InboxDeliveryView, MessageView } from \"./types\";\n\n/**\n * An in-memory {@link MessagingStore}, for a host's tests and this package's\n * own. It enforces the migration's unique keys the way Postgres does, so a\n * test that passes here exercises the same dedupe a database would.\n *\n * Not for production: it lives in one process and forgets on restart.\n */\nexport function createMemoryMessagingStore(): MessagingStore & { readonly dump: () => MemoryStoreDump } {\n const tables: MemoryTables = {\n deliveries: new Map(),\n connections: new Map(),\n conversations: new Map(),\n messages: new Map(),\n };\n return {\n ...memoryInbox(tables),\n ...memoryConnections(tables),\n ...memoryConversations(tables),\n ...memoryMessages(tables),\n purgeExpiredText: async (input) => purge(tables, input),\n purgeExpiredDeliveries: async (input) => purgeDeliveries(tables, input),\n dump: () => ({\n deliveries: [...tables.deliveries.values()].map(copy),\n connections: [...tables.connections.values()].map(copy),\n conversations: [...tables.conversations.values()].map(copy),\n messages: [...tables.messages.values()].map(copy),\n }),\n };\n}\n\n/** Everything the memory store holds, for a test to assert on. */\nexport interface MemoryStoreDump {\n deliveries: StoredDelivery[];\n connections: StoredConnection[];\n conversations: ConversationView[];\n messages: MessageView[];\n}\n\ntype StoredDelivery = InboxDeliveryView & { bodyHash: string };\n\ninterface MemoryTables {\n deliveries: Map<string, StoredDelivery>;\n connections: Map<string, StoredConnection>;\n conversations: Map<string, ConversationView>;\n messages: Map<string, MessageView>;\n}\n\nconst copy = <T extends object>(row: T): T => ({ ...row });\n/** A copy of `row` without `key`: what a real select would not return. */\nfunction without<T extends object, K extends keyof T>(row: T, key: K): Omit<T, K> {\n return Object.fromEntries(Object.entries(row).filter(([name]) => name !== key)) as Omit<T, K>;\n}\nconst deliveryView = (row: StoredDelivery): InboxDeliveryView => without(row, \"bodyHash\");\nconst connectionView = (row: StoredConnection): ConnectionView => without(row, \"credentialSealed\");\n\nfunction memoryInbox({ deliveries }: MemoryTables) {\n return {\n async recordDelivery({ channel, bodyHash, rawBody, receivedAt }) {\n const existing = [...deliveries.values()].find((row) => row.channel === channel && row.bodyHash === bodyHash);\n if (existing) return { id: existing.id, fresh: false };\n const id = randomUUID();\n deliveries.set(id, { id, channel, bodyHash, rawBody, state: \"PENDING\", attempts: 0, error: null, receivedAt, processedAt: null });\n return { id, fresh: true };\n },\n async getDelivery(id) {\n const row = deliveries.get(id);\n return row ? deliveryView(row) : null;\n },\n async settleDelivery(id, { state, error, at }) {\n const row = deliveries.get(id);\n if (row) deliveries.set(id, { ...row, state, error, processedAt: at, attempts: row.attempts + 1 });\n },\n async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {\n return [...deliveries.values()]\n .filter((row) => row.state !== \"PROCESSED\" && row.attempts < maxAttempts && row.receivedAt < receivedBefore)\n .sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime())\n .slice(0, take)\n .map(deliveryView);\n },\n } satisfies Partial<MessagingStore>;\n}\n\nfunction memoryConnections({ connections }: MemoryTables) {\n const findConnectionByAccount = async (channel: string, externalAccountId: string) => {\n const row = [...connections.values()].find(\n (candidate) => candidate.channel === channel && candidate.externalAccountId === externalAccountId,\n );\n return row ? copy(row) : null;\n };\n return {\n findConnectionByAccount,\n async getConnection(tenantId, id) {\n const row = connections.get(id);\n return row && row.tenantId === tenantId ? copy(row) : null;\n },\n async listConnections(tenantId) {\n return [...connections.values()].filter((row) => row.tenantId === tenantId).map(connectionView);\n },\n async saveConnection(input) {\n // Read and write with no await between them: the check-and-set is atomic, as the database's unique key makes it.\n const existing = [...connections.values()].find(\n (candidate) => candidate.channel === input.channel && candidate.externalAccountId === input.externalAccountId,\n );\n if (existing && existing.tenantId !== input.tenantId && existing.status !== \"REVOKED\") return null;\n const row: StoredConnection = {\n id: existing?.id ?? randomUUID(),\n ...input,\n status: \"CONNECTED\",\n statusReason: null,\n revokedAt: null,\n };\n connections.set(row.id, row);\n return connectionView(row);\n },\n async setConnectionStatus(tenantId, id, patch) {\n const row = connections.get(id);\n if (!row || row.tenantId !== tenantId) return false;\n connections.set(id, { ...row, ...patch });\n return true;\n },\n } satisfies Partial<MessagingStore>;\n}\n\nfunction memoryConversations({ conversations }: MemoryTables) {\n const findConversation = async (tenantId: string, channel: string, contactId: string) => {\n const row = [...conversations.values()].find(\n (candidate) => candidate.tenantId === tenantId && candidate.channel === channel && candidate.contactId === contactId,\n );\n return row ? copy(row) : null;\n };\n return {\n findConversation,\n async getConversation(tenantId, id) {\n const row = conversations.get(id);\n return row && row.tenantId === tenantId ? copy(row) : null;\n },\n async createConversation(input) {\n const existing = await findConversation(input.tenantId, input.channel, input.contactId);\n if (existing) return existing;\n const row: ConversationView = {\n id: randomUUID(),\n ...input,\n optedOutAt: input.optedOutAt ?? null,\n summary: null,\n summaryUpdatedAt: null,\n createdAt: new Date(),\n };\n conversations.set(row.id, row);\n return copy(row);\n },\n async updateConversation(tenantId, id, patch, guard) {\n const row = conversations.get(id);\n if (!row || row.tenantId !== tenantId) return null;\n // No await between this check and the write below: the compare-and-set is atomic.\n if (guard && !matchesGuard(row, guard)) return null;\n const next = { ...row, ...patch };\n conversations.set(id, next);\n return copy(next);\n },\n } satisfies Partial<MessagingStore>;\n}\n\nconst sameTime = (a: Date | null, b: Date | null): boolean => (a === null || b === null ? a === b : a.getTime() === b.getTime());\n\nconst GUARDED_TIMES = [\"lastInboundAt\", \"lastMessageAt\", \"optedOutAt\"] as const;\n\nfunction matchesGuard(row: ConversationView, guard: ConversationGuard): boolean {\n if (guard.state !== undefined && row.state !== guard.state) return false;\n if (guard.stateNot !== undefined && row.state === guard.stateNot) return false;\n return GUARDED_TIMES.every((key) => {\n const wanted = guard[key];\n return wanted === undefined || sameTime(row[key], wanted);\n });\n}\n\nfunction memoryMessages({ messages }: MemoryTables) {\n const findMessageByExternalId = async (channel: string, externalId: string) => {\n const row = [...messages.values()].find((candidate) => candidate.channel === channel && candidate.externalId === externalId);\n return row ? copy(row) : null;\n };\n return {\n findMessageByExternalId,\n async insertMessage(input) {\n const existing = input.externalId === null ? null : await findMessageByExternalId(input.channel, input.externalId);\n if (existing) return { created: false, message: existing };\n const row: MessageView = {\n id: randomUUID(),\n ...input,\n transcript: null,\n error: null,\n sentAt: null,\n deliveredAt: null,\n readAt: null,\n failedAt: null,\n };\n messages.set(row.id, row);\n return { created: true, message: copy(row) };\n },\n async updateMessage(tenantId, id, patch) {\n const row = messages.get(id);\n if (!row || row.tenantId !== tenantId) return null;\n const taken = patch.externalId === undefined ? null : await findMessageByExternalId(row.channel, patch.externalId);\n if (taken && taken.id !== id) throw Object.assign(new Error(\"unique\"), { code: \"P2002\" });\n const next = { ...row, ...patch };\n messages.set(id, next);\n return copy(next);\n },\n async listMessages(tenantId, conversationId) {\n return [...messages.values()]\n .filter((row) => row.tenantId === tenantId && row.conversationId === conversationId)\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())\n .map(copy);\n },\n async applyReceipt({ tenantId, channel, externalId, status, at, error }) {\n const row = [...messages.values()].find(\n (candidate) =>\n candidate.tenantId === tenantId &&\n candidate.channel === channel &&\n candidate.externalId === externalId &&\n candidate.direction === \"OUTBOUND\",\n );\n if (!row) return false;\n const column = RECEIPT_COLUMN[status];\n const stamp = row[column] === null;\n const forward = DELIVERY_RANK[status] > DELIVERY_RANK[row.deliveryStatus];\n messages.set(row.id, {\n ...row,\n ...(stamp ? { [column]: at, ...(error !== null ? { error } : {}) } : {}),\n ...(forward ? { deliveryStatus: status } : {}),\n });\n return true;\n },\n } satisfies Partial<MessagingStore>;\n}\n\nfunction purgeDeliveries(\n { deliveries }: MemoryTables,\n { cutoff, maxAttempts, take }: { cutoff: Date; maxAttempts: number; take: number },\n): number {\n const due = (match: (row: StoredDelivery) => boolean) =>\n [...deliveries.values()]\n .filter((row) => row.receivedAt < cutoff && match(row))\n .sort((a, b) => a.receivedAt.getTime() - b.receivedAt.getTime())\n .slice(0, take);\n const rows = [...due((row) => row.state === \"PROCESSED\"), ...due((row) => row.state === \"FAILED\" && row.attempts >= maxAttempts)];\n for (const row of rows) deliveries.delete(row.id);\n return rows.length;\n}\n\nfunction purge({ conversations, messages }: MemoryTables, { cutoff, take }: { cutoff: Date; take: number }) {\n const expired = (row: ConversationView) => row.lastMessageAt !== null && row.lastMessageAt < cutoff;\n const due = [...conversations.values()]\n .filter((row) => row.hasText && expired(row))\n .sort((a, b) => a.lastMessageAt!.getTime() - b.lastMessageAt!.getTime())\n .slice(0, take);\n const ids = new Set(due.map((row) => row.id));\n let purged = 0;\n for (const row of messages.values()) {\n if (!ids.has(row.conversationId) || row.createdAt > cutoff) continue;\n messages.set(row.id, { ...row, body: null, options: null, transcript: null });\n purged += 1;\n }\n for (const row of due) {\n const current = conversations.get(row.id)!;\n if (expired(current)) conversations.set(row.id, { ...current, hasText: false });\n }\n return { conversations: due.length, messages: purged };\n}\n","import type {\n AuthorKind,\n ChannelKind,\n ConnectionStatus,\n ConnectionView,\n ConversationState,\n ConversationSummary,\n ConversationView,\n DeliveryStatus,\n InboxDeliveryView,\n MessageDirection,\n MessageKind,\n MessageView,\n ReceiptStatus,\n} from \"./types\";\n\n/**\n * THE STORE PORT: every read and write the engine makes, as named operations.\n *\n * The engine never builds a query. Two implementations ship:\n * `createPrismaMessagingStore` over the Prisma delegates generated from the\n * shipped partial (what a host mounts), and `createMemoryMessagingStore` (what\n * a test mounts). The same contract suite runs over both — the Prisma one on\n * real Postgres with the shipped migration — so the two cannot drift.\n *\n * Every operation is tenant-scoped where a tenant is known, and every unique\n * key the migration enforces is enforced by both implementations, with the\n * race answered the same way (the existing row wins).\n */\nexport interface MessagingStore {\n // ── The inbox ──────────────────────────────────────────────────────────────\n /** Store one raw delivery, deduped on `(channel, bodyHash)`. `fresh: false` for a redelivery. */\n recordDelivery(input: {\n channel: ChannelKind;\n bodyHash: string;\n rawBody: string;\n receivedAt: Date;\n }): Promise<{ id: string; fresh: boolean }>;\n getDelivery(id: string): Promise<InboxDeliveryView | null>;\n /** Close a delivery out, counting the attempt. */\n settleDelivery(id: string, outcome: { state: \"PROCESSED\" | \"FAILED\"; error: string | null; at: Date }): Promise<void>;\n /** Deliveries not yet processed, received before `receivedBefore`, under the attempt bound, oldest first. */\n listRetryableDeliveries(input: { receivedBefore: Date; maxAttempts: number; take: number }): Promise<InboxDeliveryView[]>;\n\n // ── Connections ────────────────────────────────────────────────────────────\n findConnectionByAccount(channel: ChannelKind, externalAccountId: string): Promise<StoredConnection | null>;\n getConnection(tenantId: string, id: string): Promise<StoredConnection | null>;\n listConnections(tenantId: string): Promise<ConnectionView[]>;\n /**\n * Insert, or overwrite the row keyed by `(channel, externalAccountId)` — but\n * only the same tenant's, or one that is REVOKED: the write itself is\n * conditional, so two connects racing for one account cannot both win.\n * `null` when the account is held by another tenant (the engine answers\n * `ACCOUNT_TAKEN`).\n */\n saveConnection(input: NewConnection): Promise<ConnectionView | null>;\n setConnectionStatus(\n tenantId: string,\n id: string,\n patch: { status: ConnectionStatus; statusReason: string | null; revokedAt: Date | null; credentialSealed?: null },\n ): Promise<boolean>;\n\n // ── Conversations ──────────────────────────────────────────────────────────\n findConversation(tenantId: string, channel: ChannelKind, contactId: string): Promise<ConversationView | null>;\n getConversation(tenantId: string, id: string): Promise<ConversationView | null>;\n /** Create one; on a lost race for `(tenant, channel, contact)` the existing row is returned. */\n createConversation(input: NewConversation): Promise<ConversationView>;\n /**\n * Apply `patch` to the tenant's conversation. With a `guard` it is a\n * COMPARE-AND-SET: the write happens only while the row still matches every\n * guarded field (one `updateMany`), and `null` comes back when it does not —\n * the caller re-reads and decides again. Without a guard, `null` only means\n * \"no such conversation\".\n */\n updateConversation(\n tenantId: string,\n id: string,\n patch: ConversationPatch,\n guard?: ConversationGuard,\n ): Promise<ConversationView | null>;\n\n // ── Messages ───────────────────────────────────────────────────────────────\n findMessageByExternalId(channel: ChannelKind, externalId: string): Promise<MessageView | null>;\n /** Insert one; a duplicate `(channel, externalId)` is `created: false` and the existing row. */\n insertMessage(input: NewMessage): Promise<{ created: boolean; message: MessageView }>;\n updateMessage(tenantId: string, id: string, patch: MessagePatch): Promise<MessageView | null>;\n listMessages(tenantId: string, conversationId: string): Promise<MessageView[]>;\n /**\n * Stamp a receipt on the tenant's outbound message: the receipt's timestamp\n * column is written only while still null (so `(externalId, status)` is\n * deduped by the row itself), and the delivery status only moves forward.\n * False when no outbound message of that tenant has that id.\n */\n applyReceipt(input: {\n tenantId: string;\n channel: ChannelKind;\n externalId: string;\n status: ReceiptStatus;\n at: Date;\n error: string | null;\n }): Promise<boolean>;\n\n // ── Retention ──────────────────────────────────────────────────────────────\n /**\n * Delete raw inbox rows past `cutoff`: the PROCESSED ones, and the FAILED\n * ones that reached `maxAttempts` (nothing will retry them). One batch of up\n * to `take` per state, found through the `(state, received_at)` index.\n * Returns how many were deleted. Dedupe survives: a redelivered message\n * still meets `(channel, external_id)` on its message row.\n */\n purgeExpiredDeliveries(input: { cutoff: Date; maxAttempts: number; take: number }): Promise<number>;\n /**\n * Delete the text of conversations whose last message is older than\n * `cutoff`: ONE indexed query finds up to `take` of them across every tenant\n * (`has_text`, `last_message_at`), then their messages created at or before\n * the cutoff lose `body`, `options` and `transcript`. Conversation rows,\n * states and summaries stay.\n */\n purgeExpiredText(input: { cutoff: Date; take: number }): Promise<{ conversations: number; messages: number }>;\n}\n\n/** A connection with its sealed credential: only the engine sees this shape. */\nexport interface StoredConnection extends ConnectionView {\n /** Null once the connection was revoked: disconnecting removes the token. */\n credentialSealed: string | null;\n}\n\nexport interface NewConnection {\n tenantId: string;\n channel: ChannelKind;\n externalAccountId: string;\n externalParentId: string | null;\n displayAddress: string;\n credentialSealed: string;\n connectedAt: Date;\n}\n\nexport interface NewConversation {\n tenantId: string;\n channel: ChannelKind;\n contactId: string;\n contactName: string | null;\n connectionId: string;\n state: ConversationState;\n lastInboundAt: Date | null;\n lastMessageAt: Date | null;\n optedOutAt?: Date | null;\n hasText: boolean;\n}\n\n/**\n * What a compare-and-set update requires of the row it writes: every field\n * given must equal the row's current value (`null` matches a null column),\n * and `stateNot` that the state differs.\n */\nexport interface ConversationGuard {\n state?: ConversationState;\n stateNot?: ConversationState;\n lastInboundAt?: Date | null;\n lastMessageAt?: Date | null;\n optedOutAt?: Date | null;\n}\n\nexport interface ConversationPatch {\n contactName?: string | null;\n connectionId?: string;\n state?: ConversationState;\n lastInboundAt?: Date | null;\n lastMessageAt?: Date | null;\n optedOutAt?: Date | null;\n hasText?: boolean;\n summary?: ConversationSummary;\n summaryUpdatedAt?: Date;\n}\n\nexport interface NewMessage {\n conversationId: string;\n tenantId: string;\n channel: ChannelKind;\n direction: MessageDirection;\n kind: MessageKind;\n body: string | null;\n options: string | null;\n attachmentRef: string | null;\n externalId: string | null;\n deliveryStatus: DeliveryStatus;\n authorKind: AuthorKind;\n staffUserId: string | null;\n createdAt: Date;\n}\n\nexport interface MessagePatch {\n externalId?: string;\n deliveryStatus?: DeliveryStatus;\n error?: string | null;\n transcript?: string;\n failedAt?: Date;\n}\n\n/** The forward order of delivery statuses; FAILED outranks them all. */\nexport const DELIVERY_RANK: Readonly<Record<DeliveryStatus, number>> = {\n RECEIVED: 0,\n PENDING: 1,\n ACCEPTED: 2,\n SENT: 3,\n DELIVERED: 4,\n READ: 5,\n FAILED: 6,\n};\n\n/** The receipt's timestamp column. */\nexport const RECEIPT_COLUMN = {\n SENT: \"sentAt\",\n DELIVERED: \"deliveredAt\",\n READ: \"readAt\",\n FAILED: \"failedAt\",\n} as const satisfies Record<ReceiptStatus, keyof MessageView>;\n","import { DELIVERY_RANK, RECEIPT_COLUMN, type ConversationGuard, type MessagingStore, type StoredConnection } from \"./store\";\nimport type {\n ConnectionView,\n ConversationView,\n DeliveryStatus,\n InboxDeliveryView,\n MessageView,\n ReceiptStatus,\n} from \"./types\";\n\n/**\n * The Prisma delegates the store reads and writes.\n *\n * Structural rather than a `PrismaClient` import: the package must not depend\n * on the host's generated client, and this shape is what any client generated\n * from the shipped partial satisfies. Only the query subset below is used —\n * equality, `in`, `lt`, `lte`, `gte`, `not`, compound unique keys, `increment`,\n * `orderBy`, `take` — which is also what the package's Postgres suite\n * translates, so the suite runs the exact queries a host runs.\n */\nexport interface MessagingPrismaDb {\n messagingConnection: Delegate;\n messagingInboxDelivery: Delegate;\n messagingConversation: Delegate;\n messagingMessage: Delegate;\n}\n\ninterface Delegate {\n findUnique(args: unknown): Promise<unknown>;\n findFirst(args: unknown): Promise<unknown>;\n findMany(args: unknown): Promise<unknown[]>;\n create(args: unknown): Promise<unknown>;\n update(args: unknown): Promise<unknown>;\n updateMany(args: unknown): Promise<{ count: number }>;\n deleteMany(args: unknown): Promise<{ count: number }>;\n}\n\n/** Prisma's unique-violation code. */\nconst UNIQUE_VIOLATION = \"P2002\";\nconst isUniqueViolation = (error: unknown): boolean => (error as { code?: string } | null)?.code === UNIQUE_VIOLATION;\n\nconst CONNECTION_VIEW = {\n id: true,\n tenantId: true,\n channel: true,\n externalAccountId: true,\n externalParentId: true,\n displayAddress: true,\n status: true,\n statusReason: true,\n connectedAt: true,\n revokedAt: true,\n} as const;\n\nconst DELIVERY_VIEW = {\n id: true,\n channel: true,\n rawBody: true,\n state: true,\n attempts: true,\n error: true,\n receivedAt: true,\n processedAt: true,\n} as const;\n\nconst pickConversation = (row: ConversationView): ConversationView => ({\n id: row.id,\n tenantId: row.tenantId,\n channel: row.channel,\n contactId: row.contactId,\n contactName: row.contactName,\n connectionId: row.connectionId,\n state: row.state,\n lastInboundAt: row.lastInboundAt,\n lastMessageAt: row.lastMessageAt,\n optedOutAt: row.optedOutAt,\n hasText: row.hasText,\n summary: row.summary,\n summaryUpdatedAt: row.summaryUpdatedAt,\n createdAt: row.createdAt,\n});\n\ntype Client = () => Promise<MessagingPrismaDb>;\n\n/** A {@link MessagingStore} over a Prisma client generated from the shipped partial. */\nexport function createPrismaMessagingStore(db: MessagingPrismaDb | (() => Promise<MessagingPrismaDb>)): MessagingStore {\n const client: Client = typeof db === \"function\" ? db : async () => db;\n return {\n ...inboxOperations(client),\n ...connectionOperations(client),\n ...conversationOperations(client),\n ...messageOperations(client),\n purgeExpiredText: (input) => purgeExpiredText(client, input),\n purgeExpiredDeliveries: (input) => purgeExpiredDeliveries(client, input),\n };\n}\n\ntype InboxOperations = Pick<\n MessagingStore,\n \"recordDelivery\" | \"getDelivery\" | \"settleDelivery\" | \"listRetryableDeliveries\"\n>;\n\nfunction inboxOperations(client: Client): InboxOperations {\n return {\n async recordDelivery({ channel, bodyHash, rawBody, receivedAt }) {\n const delegate = (await client()).messagingInboxDelivery;\n const key = { channel_bodyHash: { channel, bodyHash } };\n const existing = (await delegate.findUnique({ where: key, select: { id: true } })) as { id: string } | null;\n if (existing) return { id: existing.id, fresh: false };\n try {\n const row = (await delegate.create({\n data: { channel, bodyHash, rawBody, receivedAt },\n select: { id: true },\n })) as { id: string };\n return { id: row.id, fresh: true };\n } catch (error) {\n // Two simultaneous redeliveries lose the check-then-insert race; the\n // unique index is the real guard, and losing it is a redelivery.\n if (!isUniqueViolation(error)) throw error;\n const raced = (await delegate.findUnique({ where: key, select: { id: true } })) as { id: string };\n return { id: raced.id, fresh: false };\n }\n },\n async getDelivery(id) {\n return ((await (await client()).messagingInboxDelivery.findUnique({\n where: { id },\n select: DELIVERY_VIEW,\n })) as InboxDeliveryView | null) ?? null;\n },\n async settleDelivery(id, { state, error, at }) {\n await (await client()).messagingInboxDelivery.updateMany({\n where: { id },\n data: { state, error, processedAt: at, attempts: { increment: 1 } },\n });\n },\n async listRetryableDeliveries({ receivedBefore, maxAttempts, take }) {\n return (await (await client()).messagingInboxDelivery.findMany({\n where: { state: { in: [\"PENDING\", \"FAILED\"] }, attempts: { lt: maxAttempts }, receivedAt: { lt: receivedBefore } },\n orderBy: { receivedAt: \"asc\" },\n take,\n select: DELIVERY_VIEW,\n })) as InboxDeliveryView[];\n },\n };\n}\n\ntype ConnectionOperations = Pick<\n MessagingStore,\n \"findConnectionByAccount\" | \"getConnection\" | \"listConnections\" | \"saveConnection\" | \"setConnectionStatus\"\n>;\n\nfunction connectionOperations(client: Client): ConnectionOperations {\n const findConnectionByAccount = async (channel: string, externalAccountId: string) =>\n ((await (await client()).messagingConnection.findUnique({\n where: { channel_externalAccountId: { channel, externalAccountId } },\n })) as StoredConnection | null) ?? null;\n return {\n findConnectionByAccount,\n async getConnection(tenantId, id) {\n return ((await (await client()).messagingConnection.findFirst({ where: { id, tenantId } })) as StoredConnection | null) ?? null;\n },\n async listConnections(tenantId) {\n return (await (await client()).messagingConnection.findMany({\n where: { tenantId },\n orderBy: { connectedAt: \"asc\" },\n select: CONNECTION_VIEW,\n })) as ConnectionView[];\n },\n async saveConnection(input) {\n const delegate = (await client()).messagingConnection;\n const data = { ...input, status: \"CONNECTED\", statusReason: null, revokedAt: null };\n // Twice at most: a lost insert race turns into an update of the winner's row.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const existing = await findConnectionByAccount(input.channel, input.externalAccountId);\n if (!existing) {\n try {\n return (await delegate.create({ data, select: CONNECTION_VIEW })) as ConnectionView;\n } catch (error) {\n if (!isUniqueViolation(error)) throw error;\n continue;\n }\n }\n // The takeover is conditional in the write itself: the tenant's own row, or a REVOKED one.\n const where = existing.tenantId === input.tenantId ? { id: existing.id, tenantId: input.tenantId } : { id: existing.id, status: \"REVOKED\" };\n const updated = await delegate.updateMany({ where, data });\n if (updated.count === 0) return null;\n return (await delegate.findUnique({ where: { id: existing.id }, select: CONNECTION_VIEW })) as ConnectionView;\n }\n return null;\n },\n async setConnectionStatus(tenantId, id, patch) {\n const result = await (await client()).messagingConnection.updateMany({ where: { id, tenantId }, data: patch });\n return result.count > 0;\n },\n };\n}\n\ntype ConversationOperations = Pick<\n MessagingStore,\n \"findConversation\" | \"getConversation\" | \"createConversation\" | \"updateConversation\"\n>;\n\nfunction conversationOperations(client: Client): ConversationOperations {\n const findConversation = async (tenantId: string, channel: string, contactId: string) => {\n const row = (await (await client()).messagingConversation.findUnique({\n where: { tenantId_channel_contactId: { tenantId, channel, contactId } },\n })) as ConversationView | null;\n return row ? pickConversation(row) : null;\n };\n return {\n findConversation,\n async getConversation(tenantId, id) {\n const row = (await (await client()).messagingConversation.findFirst({ where: { id, tenantId } })) as ConversationView | null;\n return row ? pickConversation(row) : null;\n },\n async createConversation(input) {\n try {\n return pickConversation((await (await client()).messagingConversation.create({ data: input })) as ConversationView);\n } catch (error) {\n if (!isUniqueViolation(error)) throw error;\n const raced = await findConversation(input.tenantId, input.channel, input.contactId);\n if (!raced) throw error;\n return raced;\n }\n },\n async updateConversation(tenantId, id, patch, guard) {\n const delegate = (await client()).messagingConversation;\n const result = await delegate.updateMany({ where: { id, tenantId, ...guardWhere(guard) }, data: patch });\n if (result.count === 0) return null;\n return pickConversation((await delegate.findUnique({ where: { id } })) as ConversationView);\n },\n };\n}\n\n/** A guard as the `where` clause of the one `updateMany` that makes the write a compare-and-set. */\nfunction guardWhere(guard: ConversationGuard | undefined): Record<string, unknown> {\n if (!guard) return {};\n const { state, stateNot, lastInboundAt, lastMessageAt, optedOutAt } = guard;\n return {\n ...(state !== undefined ? { state } : {}),\n ...(stateNot !== undefined ? { state: { not: stateNot } } : {}),\n ...(lastInboundAt !== undefined ? { lastInboundAt } : {}),\n ...(lastMessageAt !== undefined ? { lastMessageAt } : {}),\n ...(optedOutAt !== undefined ? { optedOutAt } : {}),\n };\n}\n\ntype MessageOperations = Pick<\n MessagingStore,\n \"findMessageByExternalId\" | \"insertMessage\" | \"updateMessage\" | \"listMessages\" | \"applyReceipt\"\n>;\n\nfunction messageOperations(client: Client): MessageOperations {\n const findMessageByExternalId = async (channel: string, externalId: string) =>\n ((await (await client()).messagingMessage.findUnique({\n where: { channel_externalId: { channel, externalId } },\n })) as MessageView | null) ?? null;\n return {\n findMessageByExternalId,\n async insertMessage(input) {\n try {\n return { created: true, message: (await (await client()).messagingMessage.create({ data: input })) as MessageView };\n } catch (error) {\n if (!isUniqueViolation(error) || input.externalId === null) throw error;\n const existing = await findMessageByExternalId(input.channel, input.externalId);\n if (!existing) throw error;\n return { created: false, message: existing };\n }\n },\n async updateMessage(tenantId, id, patch) {\n const delegate = (await client()).messagingMessage;\n const result = await delegate.updateMany({ where: { id, tenantId }, data: patch });\n if (result.count === 0) return null;\n return (await delegate.findUnique({ where: { id } })) as MessageView;\n },\n async listMessages(tenantId, conversationId) {\n return (await (await client()).messagingMessage.findMany({\n where: { tenantId, conversationId },\n orderBy: { createdAt: \"asc\" },\n })) as MessageView[];\n },\n applyReceipt: (input) => applyReceipt(client, input),\n };\n}\n\nasync function applyReceipt(client: Client, input: Parameters<MessagingStore[\"applyReceipt\"]>[0]): Promise<boolean> {\n const { tenantId, channel, externalId, status, at, error } = input;\n const delegate = (await client()).messagingMessage;\n const scope = { tenantId, channel, externalId, direction: \"OUTBOUND\" };\n const found = (await delegate.findFirst({ where: scope, select: { id: true } })) as { id: string } | null;\n if (!found) return false;\n const column = RECEIPT_COLUMN[status];\n // The timestamp column is written once: a second identical receipt matches\n // nothing. Then the status moves only forward, in a second guarded write,\n // so a late SENT never overwrites a READ.\n await delegate.updateMany({\n where: { id: found.id, [column]: null },\n data: { [column]: at, ...(error !== null ? { error } : {}) },\n });\n await delegate.updateMany({\n where: { id: found.id, deliveryStatus: { in: statusesBelow(status) } },\n data: { deliveryStatus: status },\n });\n return true;\n}\n\nasync function purgeExpiredText(\n client: Client,\n { cutoff, take }: { cutoff: Date; take: number },\n): Promise<{ conversations: number; messages: number }> {\n const db = await client();\n const due = (await db.messagingConversation.findMany({\n where: { hasText: true, lastMessageAt: { lt: cutoff } },\n orderBy: { lastMessageAt: \"asc\" },\n take,\n select: { id: true },\n })) as { id: string }[];\n if (due.length === 0) return { conversations: 0, messages: 0 };\n const ids = due.map((row) => row.id);\n const purged = await db.messagingMessage.updateMany({\n where: { conversationId: { in: ids }, createdAt: { lte: cutoff } },\n data: { body: null, options: null, transcript: null },\n });\n // Guarded on the same predicate: a conversation that took a message since\n // the read above keeps its flag, and its new text.\n await db.messagingConversation.updateMany({\n where: { id: { in: ids }, lastMessageAt: { lt: cutoff } },\n data: { hasText: false },\n });\n return { conversations: due.length, messages: purged.count };\n}\n\nasync function purgeExpiredDeliveries(\n client: Client,\n { cutoff, maxAttempts, take }: { cutoff: Date; maxAttempts: number; take: number },\n): Promise<number> {\n const delegate = (await client()).messagingInboxDelivery;\n const batches = [\n { state: \"PROCESSED\", receivedAt: { lt: cutoff } },\n { state: \"FAILED\", receivedAt: { lt: cutoff }, attempts: { gte: maxAttempts } },\n ];\n let deleted = 0;\n for (const where of batches) {\n const due = (await delegate.findMany({ where, orderBy: { receivedAt: \"asc\" }, take, select: { id: true } })) as { id: string }[];\n if (due.length === 0) continue;\n deleted += (await delegate.deleteMany({ where: { id: { in: due.map((row) => row.id) } } })).count;\n }\n return deleted;\n}\n\n/** Every status a receipt may move a message forward from. */\nfunction statusesBelow(status: ReceiptStatus): DeliveryStatus[] {\n return (Object.keys(DELIVERY_RANK) as DeliveryStatus[]).filter((candidate) => DELIVERY_RANK[candidate] < DELIVERY_RANK[status]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,eAAsB,QAAQ,KAAoB,OAA8C;AAC9F,QAAM,EAAE,OAAO,SAAS,MAAM,IAAI,IAAI;AACtC,MAAI,CAAC,IAAI,SAAS,IAAI,MAAM,OAAO,GAAG;AACpC,UAAM,IAAI,sBAAsB,mBAAmB,2BAA2B,MAAM,OAAO,GAAG;AAAA,EAChG;AACA,QAAM,WAAW,MAAM,MAAM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GAAG,eAAe,EAAE,IAAI,OAAO,EAAE;AAAA,IACxD,MAAM,EAAE,SAAS,MAAM;AAAA,EACzB,CAAC;AACD,SAAO,EAAE,eAAe,IAAI,QAAQ,UAAU,OAAO,MAAM;AAC7D;AAxBe;AA0Bf,eAAe,uBACb,QACA,EAAE,QAAQ,aAAa,KAAK,GACX;AACjB,QAAM,YAAY,MAAM,OAAO,GAAG;AAClC,QAAM,UAAU;AAAA,IACd,EAAE,OAAO,aAAa,YAAY,EAAE,IAAI,OAAO,EAAE;AAAA,IACjD,EAAE,OAAO,UAAU,YAAY,EAAE,IAAI,OAAO,GAAG,UAAU,EAAE,KAAK,YAAY,EAAE;AAAA,EAChF;AACA,MAAI,UAAU;AACd,aAAW,SAAS,SAAS;AAC3B,UAAM,MAAO,MAAM,SAAS,SAAS,EAAE,OAAO,SAAS,EAAE,YAAY,MAAM,GAAG,MAAM,QAAQ,EAAE,IAAI,KAAK,EAAE,CAAC;AAC1G,QAAI,IAAI,WAAW,EAAG;AACtB,gBAAY,MAAM,SAAS,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,IAAI,IAAI,CAAC,QAAQ,IAAI,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG;AAAA,EAC9F;AACA,SAAO;AACT;AAhBe;AAmBf,SAAS,cAAc,QAAyC;AAC9D,SAAQ,OAAO,KAAK,aAAa,EAAuB,OAAO,CAAC,cAAc,cAAc,SAAS,IAAI,cAAc,MAAM,CAAC;AAChI;AAFS;","names":["bodyHash","bodyHash"]}
@@ -1,6 +1,6 @@
1
1
  import * as _12_apps_wiring from '@12-apps/wiring';
2
2
  import { createApiMessaging, ProcessDeliveryPayload, MessagingJobDeps } from '../server/index.js';
3
- import '../engine-B5EPo66m.js';
3
+ import '../engine-DTnp2zUL.js';
4
4
  import '../channel-Cs_vLGl_.js';
5
5
 
6
6
  declare const messagingServerManifest: {
@@ -1,5 +1,5 @@
1
1
  import { WireJobBlueprint, WireRoute, WireRouteAnswer } from '@12-apps/wiring';
2
- import { e as MessagingEngine, i as MessagingLogger } from '../engine-B5EPo66m.js';
2
+ import { e as MessagingEngine, i as MessagingLogger } from '../engine-DTnp2zUL.js';
3
3
  import '../channel-Cs_vLGl_.js';
4
4
 
5
5
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/messaging",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "A channel-agnostic conversational messaging connector: channel connections with sealed credentials, a durable inbox of raw webhook deliveries, conversations with an owner state and a structured summary, messages with delivery statuses, an opt-out, a per-channel send policy and a text-retention sweep, behind a channel adapter port. WhatsApp Cloud is the first adapter (./whatsapp), with its signature check, payload parser, Graph sender and Embedded Signup helpers. Framework-neutral webhook routes (./server), dep-free job blueprints and the package-owned Prisma partial + migrations.",
package/src/core/inbox.ts CHANGED
@@ -74,6 +74,8 @@ export async function processDelivery(ctx: EngineContext, deliveryId: string): P
74
74
  try {
75
75
  const outcomes: EventOutcome[] = [];
76
76
  for (const event of events) outcomes.push(await handleEvent(ctx, row.channel, event));
77
+ // Inside the try: a throwing hook settles the row FAILED for the sweep.
78
+ await handOverUnclaimed(ctx, row.channel, events, outcomes);
77
79
  // A receipt for a message nobody stored yet (it raced the sender's own
78
80
  // write of the channel id) changed nothing: settle FAILED, not PROCESSED,
79
81
  // so the reconciliation sweep applies it once the id exists.
@@ -92,6 +94,26 @@ export async function processDelivery(ctx: EngineContext, deliveryId: string): P
92
94
  }
93
95
  }
94
96
 
97
+ /**
98
+ * The events whose account nobody connected, handed to the host's
99
+ * `onUnclaimedEvents` (its own number on the shared app). Only `unknown-account`
100
+ * drops: a revoked or errored account is a tenant's, never the host's.
101
+ */
102
+ async function handOverUnclaimed(
103
+ ctx: EngineContext,
104
+ channel: string,
105
+ events: readonly NormalizedEvent[],
106
+ outcomes: readonly EventOutcome[],
107
+ ): Promise<void> {
108
+ const hook = ctx.config.hooks?.onUnclaimedEvents;
109
+ if (!hook) return;
110
+ const unclaimed = events.filter((_, index) => {
111
+ const outcome = outcomes[index];
112
+ return outcome?.kind === "dropped" && outcome.reason === "unknown-account";
113
+ });
114
+ if (unclaimed.length > 0) await hook(channel, unclaimed);
115
+ }
116
+
95
117
  /**
96
118
  * Re-run deliveries left unprocessed (a dead worker, a refused enqueue, a
97
119
  * failure) once they are older than the job's own retry span. One delivery's
package/src/core/ports.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ChannelAdapter } from "./channel";
2
2
  import type { MessagingStore } from "./store";
3
- import type { ConversationState, ConversationView, MessageView } from "./types";
3
+ import type { ConversationState, ConversationView, MessageView, NormalizedEvent } from "./types";
4
4
 
5
5
  /**
6
6
  * What the engine needs FROM its host. The mechanism (the inbox, the tenant
@@ -70,6 +70,23 @@ export interface MessagingHooks {
70
70
  * it, and an answer that slips through anyway is read as `AGENT`.
71
71
  */
72
72
  reopenState?(conversation: ConversationView): ReopenState | Promise<ReopenState>;
73
+ /**
74
+ * Events of a channel account NOBODY connected: a message, an opt-out or a
75
+ * delivery receipt of a number the host itself owns on the same app (its
76
+ * platform notification number, typically), which no tenant row resolves.
77
+ *
78
+ * Without this hook they are dropped, exactly as before. With it, the host is
79
+ * handed them once per processed delivery: already signature-checked,
80
+ * persisted and parsed, and still stored nowhere here (no conversation, no
81
+ * message). An event of a CONNECTED, revoked or errored tenant account is
82
+ * never handed over: a tenant's traffic is the tenant's, and the host's
83
+ * platform path must not see it.
84
+ *
85
+ * A throw settles the delivery FAILED, so the reconciliation sweep runs it
86
+ * again: the host's handler must be idempotent on the provider's message id.
87
+ * Default: nothing.
88
+ */
89
+ onUnclaimedEvents?(channel: string, events: NormalizedEvent[]): Promise<void> | void;
73
90
  }
74
91
 
75
92
  /** Everything a host hands `createMessagingEngine`. */