@12-apps/messaging 1.5.0 → 1.7.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/ADOPTING.md CHANGED
@@ -30,6 +30,7 @@ never in these.
30
30
  | `logger` | `{ info, warn, error }` | The wiring `LoggerPort`; bind the `messaging` namespace's logger. Never handed a credential. |
31
31
  | `hooks.onInboundMessage` | OPTIONAL. `({ conversation, message }) => Promise<void>` | A contact's message was stored: hand it to the host's agent or a person's inbox. Once per message, never for a redelivery, never for an opt-out. Keep it short (enqueue the host's own job): a throw is logged and not retried. Default: nothing. |
32
32
  | `hooks.reopenState` | OPTIONAL. `(conversation) => "AGENT" \| "HUMAN" \| "CLOSED"` | The state a `CLOSED` or `OPTED_OUT` conversation re-opens into when its contact writes again (for `OPTED_OUT`, only a message sent AFTER the opt-out re-opens it). Default `AGENT`. The type refuses `OPTED_OUT`: only the contact's own words put a conversation there, and an answer of `OPTED_OUT` from a JavaScript host is read as `AGENT`. |
33
+ | `hooks.opensOnStaffReply` | OPTIONAL. `({ tenantId, channel, connectionId, contactId }) => boolean \| Promise<boolean>` | Whether a message the account sent from another device (`sent_elsewhere`) may OPEN a conversation with a contact who has none on that connection. True: the conversation is created in `HUMAN` (no inbound time), the message is stored in it and `onStaffReply` runs. Default, false or a throw (logged): the message is dropped as `no-conversation`, since the store's phone also carries the owner's family and friends. |
33
34
  | `retentionMs` | OPTIONAL, default 12 h | How long text is kept after a conversation's last message. |
34
35
  | `retentionBatchSize`, `reconcileBatchSize`, `maxDeliveryAttempts`, `reconcileAfterMs` | OPTIONAL | 500, 50, 5, 2 minutes. |
35
36
 
package/README.md CHANGED
@@ -177,7 +177,7 @@ with `setTranscript` (it is deleted with the text), and drop the buffer.
177
177
  |---|---|
178
178
  | `@12-apps/messaging` | `createMessagingEngine`, the ports, the store port with `createPrismaMessagingStore` and `createMemoryMessagingStore`, the adapter interface, the errors, the types. |
179
179
  | `@12-apps/messaging/whatsapp` | `createWhatsAppAdapter`, and standalone: `verifyMetaSignature`, `verifyMetaSubscription`, `parseWhatsAppPayload`, `parseWhatsAppStatuses`, `isOptOutText`, the Graph sender, `downloadWhatsAppMedia`, and the Embedded Signup helpers `exchangeSignupCode`, `readSignupAccounts`, `subscribeAppToWaba`. |
180
- | `@12-apps/messaging/whatsapp-web` | UNOFFICIAL. `createWhatsAppWebSession` (a linked device over Baileys), `createWhatsAppWebAdapter` (the same `ChannelAdapter`), `createMemoryAuthStateStore`, and the pure `normalizeUpsert`, `normalizeUpdates`, `encodeEnvelope`, `parseEnvelope`. See below. |
180
+ | `@12-apps/messaging/whatsapp-web` | UNOFFICIAL. `createWhatsAppWebSession` (a linked device over Baileys), `createWhatsAppWebAdapter` (the same `ChannelAdapter`), `createMemoryAuthStateStore`, and the pure `normalizeUpsert`, `normalizeSentElsewhere`, `normalizeUpdates`, `encodeEnvelope`, `parseEnvelope`, and `ChoiceMemory` (the offered-choices memory the session uses, for a host that renders choices outside the session). The session also offers `sendPresence`, `markRead` and `fetchHistory`. See below. |
181
181
  | `@12-apps/messaging/inbound-guard` | `normalizeInbound`, `screenInbound`, `DEFAULT_INBOUND_RULES`, `wrapForAgent`, `parseClassification`: the screen a host runs on untrusted inbound text before a model reads it. Pure, no I/O, no channel. |
182
182
  | `@12-apps/messaging/server` | `createApiMessaging` (the webhook route pair, in `@12-apps/wiring`'s `WireRoute` shape) and `MESSAGING_JOBS`. |
183
183
  | `@12-apps/messaging/manifest`, `/manifest/server` | The wiring manifests. |
@@ -214,15 +214,18 @@ const engine = createMessagingEngine({ adapters: [createWhatsAppWebAdapter({ ses
214
214
  | | |
215
215
  |---|---|
216
216
  | **Pairing** | `onStatus` reports `qr`: show it on the phone under *Linked devices › Link a device*. With `pairingPhoneNumber`, the session asks ONCE for a code instead (`pairing-code`). After pairing, `creds.update` is saved on every change, and the next `start()` resumes without pairing. |
217
- | **Inbound** | Each live socket event is normalized into the SAME `NormalizedEvent`s the Cloud parser produces, then handed to `deliver` as a small JSON envelope, in socket order. The envelope holds no Baileys objects and no media keys. The inbox, dedupe, processing job and retention are the engine's, unchanged. A failed `deliver` is reported through `onError`, because a socket does not redeliver. |
218
- | **What is skipped** | Groups, broadcasts, Status, channels, the account's own messages (`fromMe`), history sync (`append`) and protocol messages. The engine's conversation is one contact. |
219
- | **Outbound** | `send` goes through the session's socket. Personal accounts have no buttons or lists, so `BUTTONS` and `LIST` become numbered lines under the text, and the answer arrives as `TEXT`. Failures are `ChannelSendFailure`: `NOT_CONNECTED`, the socket's code, or `NO_MESSAGE_ID`. |
217
+ | **Inbound** | Each live socket event is normalized into the SAME `NormalizedEvent`s the Cloud parser produces, then handed to `deliver` as a small JSON envelope, one at a time and in socket order, except a phone-sent message held while a send was in flight (see *Sent from another device*), which is handed on when it is judged, after events that arrived later. The envelope holds no Baileys objects and no media keys. The inbox, dedupe, processing job and retention are the engine's, unchanged. A failed `deliver` is reported through `onError`, because a socket does not redeliver. |
218
+ | **What is skipped** | Groups, broadcasts, Status, channels, history sync (`append`, `messaging-history.set`) and protocol messages. The engine's conversation is one contact. The account's own messages are not inbound, but see *Sent from another device*. |
219
+ | **Outbound** | `send` goes through the session's socket. Personal accounts have no buttons or lists, so `BUTTONS` and `LIST` become numbered lines under the text. The session remembers the last choices offered to each contact (500 contacts, 2 h; `choiceMemorySize`, `choiceTtlMs`), keyed by the address the reply will carry (`+55 11 98765-4321`, `5511987654321:12@s.whatsapp.net` and a LID with its phone number all match the inbound contact), and a TEXT answer that is exactly a listed number (`1`, `1.`, ` 2 `) or exactly a choice's title (case and accents ignored) arrives as `INTERACTIVE { replyId, title }`, as a tap would on the Cloud adapter. Any other answer stays `TEXT` and clears nothing; a match uses the offer up. An offer maps only the first reply after it: any later message to that contact, a plain text from the session or a message from the phone, clears it. Failures are `ChannelSendFailure`: `NOT_CONNECTED`, the socket's code, or `NO_MESSAGE_ID`. |
220
220
  | **Receipts** | `messages.update` on our own messages maps to `SENT` / `DELIVERED` / `READ` / `FAILED`. |
221
221
  | **Media** | The last `mediaCacheSize` (200) audio messages stay in memory. `fetchMedia` downloads by message id, with the size cap and the deadline. After a restart an older audio is `NOT_FOUND`. |
222
222
  | **Reconnects** | An unexpected close reconnects with exponential backoff (5 attempts from 2 s), and 515 (restart after pairing) reconnects at once. 401 (logged out) clears the keys and stops. 440 (replaced) and 403 stop. |
223
223
  | **Webhook** | None. `verify` fails closed, so the webhook route answers 401 to any POST for the channel. |
224
224
  | **Policy** | No service window by default (`OPEN_SEND_POLICY`); the 24 h window is a Business API rule. |
225
225
  | **Channel key** | `whatsapp` by default, so the switch keeps the connections and conversations. Pass `kind: "whatsapp-web"` to run both side by side. The connection's credential is unused: the keys live in the auth store. |
226
+ | **Sent from another device** | A message the account sent from its OTHER device (`fromMe` on a live `notify`) becomes a `sent_elsewhere` event: `contactId`, `externalId`, `sentAt`, and `content` (the text; anything else is `OTHER`, never media keys). The engine stores it ONLY when the contact already has a conversation on that connection, as an `OUTBOUND` message of it, `authorKind: "STAFF"`, `SENT`, once (deduped on its id), and calls `hooks.onStaffReply({ conversation, message })`. A message to anyone else (the owner's family and friends on the store's phone) is dropped (`no-conversation`): never stored, and it never opens a conversation, unless the host vouches for that contact through `hooks.opensOnStaffReply` (a known customer): then the conversation is opened in `HUMAN`, with no inbound time, and the message is stored and announced as above. It changes no state: a host that steps its agent aside does it there. It is never emitted for the echo of a send the session itself made: the session remembers the ids it sent, and holds a `fromMe` event that arrives while sends are in flight (Baileys can emit the echo before `sendMessage` resolves), judging it once THOSE sends settle. A held event waits at most 30 s and at most 200 are held (the oldest is judged first); a close or `stop` releases them all, judged against the ids known then. Accepted edge: a send that throws AFTER its message left (the socket failed before returning the id) has no id to remember, so its echo is reported as a staff reply. |
227
+ | **Presence and read marks** | `session.sendPresence(contactId, "composing" \| "paused")` and `session.markRead(contactId, externalIds)` call the socket's `sendPresenceUpdate` and `readMessages`. They never reject: a failure, or a session that is not open (`ChannelSendFailure` `NOT_CONNECTED`), goes to `onError` with `presence` or `mark-read`. |
228
+ | **History on demand** | `session.fetchHistory(contactId, { externalId, sentAt, fromMe }, count, timeoutMs)` asks the phone (`fetchMessageHistory`) for up to `count` messages before the anchor and resolves with that chat's messages from the `messaging-history.set` answer: `{ externalId, fromMe, sentAt, text, kind }`, oldest first, both sides. Text only: media is a placeholder `kind` (`image`, `audio`, …) with `text: null`, never keys. It resolves `[]` when the session is not open, on timeout, or on failure (`history` in `onError`); a late answer is dropped. Nothing reaches the inbox or the engine, and the session keeps no message after the request settles: what the host does with them (not storing them) is its decision. |
226
229
 
227
230
  ## Screening inbound text before a model reads it
228
231
 
@@ -103,7 +103,27 @@ interface OptOutEvent {
103
103
  contactId: string;
104
104
  at: Date;
105
105
  }
106
- type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent;
106
+ /**
107
+ * A message the account itself sent from ANOTHER device (the owner's phone,
108
+ * typed in the app), seen on a linked-device channel. The engine stores it as
109
+ * an OUTBOUND message of the conversation authored by `STAFF` and tells the
110
+ * host (`hooks.onStaffReply`), so the host can step its agent aside.
111
+ *
112
+ * Never the echo of a send the engine made: the channel adapter dedupes those
113
+ * before they become events. `content` is the text, or `OTHER` for media.
114
+ */
115
+ interface SentElsewhereEvent {
116
+ type: "sent_elsewhere";
117
+ /** The channel account that sent it. */
118
+ accountId: string;
119
+ /** The recipient's address on the channel. */
120
+ contactId: string;
121
+ /** The channel's id for the message. */
122
+ externalId: string;
123
+ sentAt: Date;
124
+ content: InboundContent;
125
+ }
126
+ type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent | SentElsewhereEvent;
107
127
  /** A message the tenant sends, normalized across channels. */
108
128
  type OutboundContent = {
109
129
  kind: "TEXT";
@@ -340,4 +360,4 @@ declare function serviceWindowPolicy(windowMs: number): SendPolicy;
340
360
  /** A policy for a channel with no window (e-mail): every send is allowed. */
341
361
  declare const OPEN_SEND_POLICY: SendPolicy;
342
362
 
343
- export { type AuthorKind as A, type ConversationView as C, DEFAULT_MEDIA_TIMEOUT_MS as D, type HandshakeAnswer as H, type InboxDeliveryView as I, type MessageView as M, type NormalizedEvent as N, OPEN_SEND_POLICY as O, type ReceiptStatus as R, type SendPolicy as S, type ChannelAdapter as a, type ChannelKind as b, type ChannelMedia as c, ChannelMediaFailure as d, type ChannelMediaInput as e, ChannelSendFailure as f, type ChannelSendInput as g, type ConnectionStatus as h, type ConnectionView as i, type ConversationState as j, type ConversationSummary as k, type DeliveryState as l, type DeliveryStatus as m, type InboundContent as n, type InboundMessageEvent as o, type MessageDirection as p, type MessageKind as q, type OptOutEvent as r, type OutboundContent as s, type SendPolicyContext as t, type SendPolicyVerdict as u, type StatusEvent as v, isWindowOpen as w, serviceWindowPolicy as x };
363
+ export { type AuthorKind as A, type ConversationView as C, DEFAULT_MEDIA_TIMEOUT_MS as D, type HandshakeAnswer as H, type InboxDeliveryView as I, type MessageView as M, type NormalizedEvent as N, OPEN_SEND_POLICY as O, type ReceiptStatus as R, type SendPolicy as S, type ChannelAdapter as a, type ChannelKind as b, type ChannelMedia as c, ChannelMediaFailure as d, type ChannelMediaInput as e, ChannelSendFailure as f, type ChannelSendInput as g, type ConnectionStatus as h, type ConnectionView as i, type ConversationState as j, type ConversationSummary as k, type DeliveryState as l, type DeliveryStatus as m, type InboundContent as n, type InboundMessageEvent as o, type MessageDirection as p, type MessageKind as q, type OptOutEvent as r, type OutboundContent as s, type SendPolicyContext as t, type SendPolicyVerdict as u, type SentElsewhereEvent as v, type StatusEvent as w, isWindowOpen as x, serviceWindowPolicy as y };
@@ -1,4 +1,4 @@
1
- import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-CZjNEBLC.js';
1
+ import { j as ConversationState, k as ConversationSummary, i as ConnectionView, m as DeliveryStatus, b as ChannelKind, I as InboxDeliveryView, h as ConnectionStatus, C as ConversationView, M as MessageView, p as MessageDirection, q as MessageKind, A as AuthorKind, R as ReceiptStatus, a as ChannelAdapter, N as NormalizedEvent, s as OutboundContent, c as ChannelMedia } from './channel-BWhnnuip.js';
2
2
 
3
3
  /**
4
4
  * THE STORE PORT: every read and write the engine makes, as named operations.
@@ -236,6 +236,18 @@ interface InboundMessageNotice {
236
236
  conversation: ConversationView;
237
237
  message: MessageView;
238
238
  }
239
+ /** What `onStaffReply` is told: the conversation, and the stored message the owner sent from another device. */
240
+ interface StaffReplyNotice {
241
+ conversation: ConversationView;
242
+ message: MessageView;
243
+ }
244
+ /** What `opensOnStaffReply` is asked: the tenant's connection and the contact the owner wrote to. */
245
+ interface StaffReplyContact {
246
+ tenantId: string;
247
+ channel: string;
248
+ connectionId: string;
249
+ contactId: string;
250
+ }
239
251
  /** What a re-opened conversation may become. */
240
252
  type ReopenState = Exclude<ConversationState, "OPTED_OUT">;
241
253
  /** The host's answers to what only it knows about a conversation. All optional. */
@@ -248,6 +260,28 @@ interface MessagingHooks {
248
260
  * retried, because the message is already stored. Default: nothing.
249
261
  */
250
262
  onInboundMessage?(notice: InboundMessageNotice): Promise<void> | void;
263
+ /**
264
+ * The account's owner answered a contact from ANOTHER device (their phone),
265
+ * on a channel that shows it (WhatsApp Web's `sent_elsewhere` event). The
266
+ * message is stored first, as an outbound `STAFF` message, and this runs once
267
+ * per stored message, never for a redelivery and never for the echo of a send
268
+ * the engine made. The engine changes no state itself: a host that wants its
269
+ * agent to step aside does it here (`setState(..., "HUMAN")`, a timer).
270
+ * A throw is logged, never retried. Default: nothing.
271
+ */
272
+ onStaffReply?(notice: StaffReplyNotice): Promise<void> | void;
273
+ /**
274
+ * Whether a message the owner sent from another device may OPEN a
275
+ * conversation with a contact who has none on this connection yet. The
276
+ * store's phone also carries the owner's family and friends, so only the
277
+ * host can tell a customer from them (a known customer's number, a
278
+ * conversation on another of its channels). When it answers true, the
279
+ * conversation is created in `HUMAN` (a person is answering), the message is
280
+ * stored in it and `onStaffReply` runs as for any other. Default: never
281
+ * (the message is dropped as `no-conversation`). A throw is logged and read
282
+ * as false.
283
+ */
284
+ opensOnStaffReply?(contact: StaffReplyContact): boolean | Promise<boolean>;
251
285
  /**
252
286
  * The state a CLOSED or OPTED_OUT conversation re-opens into when its
253
287
  * contact writes again. Default: `AGENT`. A host never returns `OPTED_OUT`
@@ -319,9 +353,11 @@ declare const MESSAGING_DEFAULTS: {
319
353
  * the event is dropped (the edge already answered 200, so the channel stops
320
354
  * redelivering) and a tenant can never receive another tenant's traffic.
321
355
  */
322
- type EventOutcome = {
356
+ type EventOutcome =
357
+ /** `no-conversation`: a message the owner sent from their phone to a contact the store has no conversation with here. */
358
+ {
323
359
  kind: "dropped";
324
- reason: "unknown-account" | "not-connected";
360
+ reason: "unknown-account" | "not-connected" | "no-conversation";
325
361
  } | {
326
362
  kind: "duplicate";
327
363
  } | {
@@ -331,6 +367,12 @@ type EventOutcome = {
331
367
  } | {
332
368
  kind: "opted-out";
333
369
  conversationId: string;
370
+ }
371
+ /** A message the owner sent from another device, stored as the store's own. */
372
+ | {
373
+ kind: "staff-message";
374
+ conversationId: string;
375
+ messageId: string;
334
376
  } | {
335
377
  kind: "receipt";
336
378
  applied: boolean;
@@ -448,4 +490,4 @@ declare function createMessagingEngine(config: MessagingEngineConfig): {
448
490
  };
449
491
  type MessagingEngine = ReturnType<typeof createMessagingEngine>;
450
492
 
451
- export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES as D, type EventOutcome as E, type InboundMessageNotice as I, type MessagingStore as M, type NewConnection as N, PROCESS_DELIVERY_JOB as P, type StoredConnection as S, type ConversationPatch as a, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p, createMessagingEngine as q };
493
+ export { type ConnectInput as C, DEFAULT_MEDIA_MAX_BYTES as D, type EventOutcome as E, type InboundMessageNotice as I, type MessagingStore as M, type NewConnection as N, PROCESS_DELIVERY_JOB as P, type StoredConnection as S, type ConversationPatch as a, type DeliveryOutcome as b, type DownloadMediaOptions as c, MESSAGING_DEFAULTS as d, type MessagePatch as e, type MessagingClockPort as f, type MessagingEngine as g, type MessagingEngineConfig as h, type MessagingEnqueuePort as i, type MessagingHooks as j, type MessagingLogger as k, type MessagingSecretsPort as l, type NewConversation as m, type NewMessage as n, type SendAuthor as o, type SendInput as p, type StaffReplyContact as q, type StaffReplyNotice as r, createMessagingEngine as s };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { S as StoredConnection, M as MessagingStore } from './engine-BJse1HAX.js';
2
- export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as createMessagingEngine } from './engine-BJse1HAX.js';
3
- import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-CZjNEBLC.js';
4
- export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as StatusEvent, w as isWindowOpen, x as serviceWindowPolicy } from './channel-CZjNEBLC.js';
1
+ import { S as StoredConnection, M as MessagingStore } from './engine-D63T3vk8.js';
2
+ export { C as ConnectInput, a as ConversationPatch, D as DEFAULT_MEDIA_MAX_BYTES, b as DeliveryOutcome, c as DownloadMediaOptions, E as EventOutcome, I as InboundMessageNotice, d as MESSAGING_DEFAULTS, e as MessagePatch, f as MessagingClockPort, g as MessagingEngine, h as MessagingEngineConfig, i as MessagingEnqueuePort, j as MessagingHooks, k as MessagingLogger, l as MessagingSecretsPort, N as NewConnection, m as NewConversation, n as NewMessage, P as PROCESS_DELIVERY_JOB, o as SendAuthor, p as SendInput, q as StaffReplyContact, r as StaffReplyNotice, s as createMessagingEngine } from './engine-D63T3vk8.js';
3
+ import { I as InboxDeliveryView, C as ConversationView, M as MessageView } from './channel-BWhnnuip.js';
4
+ export { A as AuthorKind, a as ChannelAdapter, b as ChannelKind, c as ChannelMedia, d as ChannelMediaFailure, e as ChannelMediaInput, f as ChannelSendFailure, g as ChannelSendInput, h as ConnectionStatus, i as ConnectionView, j as ConversationState, k as ConversationSummary, D as DEFAULT_MEDIA_TIMEOUT_MS, l as DeliveryState, m as DeliveryStatus, H as HandshakeAnswer, n as InboundContent, o as InboundMessageEvent, p as MessageDirection, q as MessageKind, N as NormalizedEvent, O as OPEN_SEND_POLICY, r as OptOutEvent, s as OutboundContent, R as ReceiptStatus, S as SendPolicy, t as SendPolicyContext, u as SendPolicyVerdict, v as SentElsewhereEvent, w as StatusEvent, x as isWindowOpen, y as serviceWindowPolicy } from './channel-BWhnnuip.js';
5
5
 
6
6
  /**
7
7
  * The engine's refusals, as typed errors with machine codes. The sentence a
package/dist/index.js CHANGED
@@ -95,6 +95,95 @@ function bodyHash(rawBody) {
95
95
  }
96
96
  __name(bodyHash, "bodyHash");
97
97
 
98
+ // src/core/sent-elsewhere.ts
99
+ var later = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
100
+ var MAX_WRITE_ATTEMPTS = 6;
101
+ async function handleSentElsewhere(ctx, connection, event) {
102
+ const { store } = ctx.config;
103
+ if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
104
+ const body = event.content.kind === "TEXT" ? event.content.text : null;
105
+ const conversation = await touchConversation(ctx, connection, event, body !== null);
106
+ if (!conversation) return { kind: "dropped", reason: "no-conversation" };
107
+ const inserted = await store.insertMessage({
108
+ conversationId: conversation.id,
109
+ tenantId: connection.tenantId,
110
+ channel: connection.channel,
111
+ direction: "OUTBOUND",
112
+ kind: body === null ? "OTHER" : "TEXT",
113
+ body,
114
+ options: null,
115
+ attachmentRef: null,
116
+ externalId: event.externalId,
117
+ deliveryStatus: "SENT",
118
+ authorKind: "STAFF",
119
+ staffUserId: null,
120
+ createdAt: event.sentAt
121
+ });
122
+ if (!inserted.created) return { kind: "duplicate" };
123
+ await notifyStaffReply(ctx, conversation, inserted.message);
124
+ return { kind: "staff-message", conversationId: conversation.id, messageId: inserted.message.id };
125
+ }
126
+ __name(handleSentElsewhere, "handleSentElsewhere");
127
+ async function touchConversation(ctx, connection, event, carriesText) {
128
+ const { store } = ctx.config;
129
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
130
+ const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
131
+ if (!existing) {
132
+ if (!await hostOpens(ctx, connection, event)) return null;
133
+ const opened = await openForStaff(ctx, connection, event, carriesText);
134
+ if (opened) return opened;
135
+ continue;
136
+ }
137
+ if (existing.connectionId !== connection.id) return null;
138
+ const updated = await store.updateConversation(
139
+ connection.tenantId,
140
+ existing.id,
141
+ { lastMessageAt: later(existing.lastMessageAt, event.sentAt), ...carriesText ? { hasText: true } : {} },
142
+ { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
143
+ );
144
+ if (updated) return updated;
145
+ }
146
+ throw new Error(`conversation ${event.contactId} kept changing under this message; retry`);
147
+ }
148
+ __name(touchConversation, "touchConversation");
149
+ async function hostOpens(ctx, connection, event) {
150
+ const hook = ctx.config.hooks?.opensOnStaffReply;
151
+ if (!hook) return false;
152
+ try {
153
+ return await hook({ tenantId: connection.tenantId, channel: connection.channel, connectionId: connection.id, contactId: event.contactId }) === true;
154
+ } catch (error) {
155
+ ctx.config.logger.error(`messaging.inbound: opensOnStaffReply failed: ${errorText(error)}`, { error });
156
+ return false;
157
+ }
158
+ }
159
+ __name(hostOpens, "hostOpens");
160
+ async function openForStaff(ctx, connection, event, carriesText) {
161
+ const created = await ctx.config.store.createConversation({
162
+ tenantId: connection.tenantId,
163
+ channel: connection.channel,
164
+ contactId: event.contactId,
165
+ contactName: null,
166
+ connectionId: connection.id,
167
+ state: "HUMAN",
168
+ lastInboundAt: null,
169
+ lastMessageAt: event.sentAt,
170
+ hasText: carriesText
171
+ });
172
+ const ours = created.state === "HUMAN" && created.lastInboundAt === null && created.lastMessageAt?.getTime() === event.sentAt.getTime();
173
+ return ours ? created : null;
174
+ }
175
+ __name(openForStaff, "openForStaff");
176
+ async function notifyStaffReply(ctx, conversation, message) {
177
+ const hook = ctx.config.hooks?.onStaffReply;
178
+ if (!hook) return;
179
+ try {
180
+ await hook({ conversation, message });
181
+ } catch (error) {
182
+ ctx.config.logger.error(`messaging.inbound: onStaffReply failed for ${conversation.id}: ${errorText(error)}`, { error });
183
+ }
184
+ }
185
+ __name(notifyStaffReply, "notifyStaffReply");
186
+
98
187
  // src/core/inbound.ts
99
188
  async function handleEvent(ctx, channel, event) {
100
189
  const connection = await ctx.config.store.findConnectionByAccount(channel, event.accountId);
@@ -102,6 +191,7 @@ async function handleEvent(ctx, channel, event) {
102
191
  if (connection.status !== "CONNECTED") return { kind: "dropped", reason: "not-connected" };
103
192
  if (event.type === "message") return handleMessage(ctx, connection, event);
104
193
  if (event.type === "opt_out") return handleOptOut(ctx, connection, event);
194
+ if (event.type === "sent_elsewhere") return handleSentElsewhere(ctx, connection, event);
105
195
  const applied = await ctx.config.store.applyReceipt({
106
196
  tenantId: connection.tenantId,
107
197
  channel,
@@ -126,8 +216,8 @@ function columnsOf(content) {
126
216
  }
127
217
  }
128
218
  __name(columnsOf, "columnsOf");
129
- var later = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
130
- var MAX_WRITE_ATTEMPTS = 6;
219
+ var later2 = /* @__PURE__ */ __name((a, b) => a && a > b ? a : b, "later");
220
+ var MAX_WRITE_ATTEMPTS2 = 6;
131
221
  async function handleMessage(ctx, connection, event) {
132
222
  const { store } = ctx.config;
133
223
  if (await store.findMessageByExternalId(connection.channel, event.externalId)) return { kind: "duplicate" };
@@ -154,7 +244,7 @@ async function handleMessage(ctx, connection, event) {
154
244
  __name(handleMessage, "handleMessage");
155
245
  async function openConversation(ctx, connection, event, carriesText) {
156
246
  const { store } = ctx.config;
157
- for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
247
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS2; attempt += 1) {
158
248
  const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
159
249
  const result = existing ? await updateExisting(ctx, connection, existing, event, carriesText) : await createFirst(ctx, connection, event, carriesText);
160
250
  if (result) return result;
@@ -187,10 +277,10 @@ async function updateExisting(ctx, connection, existing, event, carriesText) {
187
277
  {
188
278
  // Left out when unchanged: the write never carries a state it did not decide.
189
279
  ...state !== existing.state ? { state } : {},
190
- ...event.optOut ? { optedOutAt: later(existing.optedOutAt, event.sentAt) } : {},
280
+ ...event.optOut ? { optedOutAt: later2(existing.optedOutAt, event.sentAt) } : {},
191
281
  ...connection.id !== existing.connectionId ? { connectionId: connection.id } : {},
192
- lastInboundAt: later(existing.lastInboundAt, event.sentAt),
193
- lastMessageAt: later(existing.lastMessageAt, event.sentAt),
282
+ lastInboundAt: later2(existing.lastInboundAt, event.sentAt),
283
+ lastMessageAt: later2(existing.lastMessageAt, event.sentAt),
194
284
  ...event.contactName ? { contactName: event.contactName } : {},
195
285
  ...carriesText ? { hasText: true } : {}
196
286
  },
@@ -221,7 +311,7 @@ async function notifyHost(ctx, conversation, message) {
221
311
  __name(notifyHost, "notifyHost");
222
312
  async function handleOptOut(ctx, connection, event) {
223
313
  const { store } = ctx.config;
224
- for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
314
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS2; attempt += 1) {
225
315
  const existing = await store.findConversation(connection.tenantId, connection.channel, event.contactId);
226
316
  if (!existing) {
227
317
  const created = await store.createConversation({
@@ -244,7 +334,7 @@ async function handleOptOut(ctx, connection, event) {
244
334
  existing.id,
245
335
  {
246
336
  ...existing.state !== "OPTED_OUT" ? { state: "OPTED_OUT" } : {},
247
- optedOutAt: later(existing.optedOutAt, event.at)
337
+ optedOutAt: later2(existing.optedOutAt, event.at)
248
338
  },
249
339
  { state: existing.state, lastInboundAt: existing.lastInboundAt, lastMessageAt: existing.lastMessageAt, optedOutAt: existing.optedOutAt }
250
340
  );