@12-apps/messaging 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +119 -0
- package/README.md +133 -2
- package/dist/channel-Cs_vLGl_.d.ts +293 -0
- package/dist/chunk-72TDAQUW.js +136 -0
- package/dist/chunk-72TDAQUW.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-R3DKM2IV.js +42 -0
- package/dist/chunk-R3DKM2IV.js.map +1 -0
- package/dist/chunk-Y7MG2UDQ.js +36 -0
- package/dist/chunk-Y7MG2UDQ.js.map +1 -0
- package/dist/engine-B5EPo66m.d.ts +414 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +988 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest/index.d.ts +36 -0
- package/dist/manifest/index.js +14 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +21 -0
- package/dist/manifest/server.js +17 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/server/index.d.ts +78 -0
- package/dist/server/index.js +15 -0
- package/dist/server/index.js.map +1 -0
- package/dist/whatsapp/index.d.ts +180 -0
- package/dist/whatsapp/index.js +385 -0
- package/dist/whatsapp/index.js.map +1 -0
- package/package.json +90 -4
- package/prisma/messaging.prisma +140 -0
- package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
- package/src/core/channel.ts +106 -0
- package/src/core/connections.ts +67 -0
- package/src/core/context.ts +28 -0
- package/src/core/engine.ts +64 -0
- package/src/core/errors.ts +53 -0
- package/src/core/hash.ts +6 -0
- package/src/core/inbound.ts +240 -0
- package/src/core/inbox.ts +117 -0
- package/src/core/memory-store.ts +273 -0
- package/src/core/ports.ts +112 -0
- package/src/core/prisma-store.ts +354 -0
- package/src/core/retention.ts +27 -0
- package/src/core/sender.ts +106 -0
- package/src/core/store.ts +217 -0
- package/src/core/types.ts +189 -0
- package/src/index.ts +54 -0
- package/src/manifest/index.ts +32 -0
- package/src/manifest/server.ts +18 -0
- package/src/server/index.ts +22 -0
- package/src/server/jobs.ts +99 -0
- package/src/server/webhook.ts +92 -0
- package/src/whatsapp/graph.ts +136 -0
- package/src/whatsapp/index.ts +64 -0
- package/src/whatsapp/opt-out.ts +26 -0
- package/src/whatsapp/parse.ts +200 -0
- package/src/whatsapp/signature.ts +52 -0
- package/src/whatsapp/signup.ts +115 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AuthorKind,
|
|
3
|
+
ChannelKind,
|
|
4
|
+
ConnectionStatus,
|
|
5
|
+
ConnectionView,
|
|
6
|
+
ConversationState,
|
|
7
|
+
ConversationSummary,
|
|
8
|
+
ConversationView,
|
|
9
|
+
DeliveryStatus,
|
|
10
|
+
InboxDeliveryView,
|
|
11
|
+
MessageDirection,
|
|
12
|
+
MessageKind,
|
|
13
|
+
MessageView,
|
|
14
|
+
ReceiptStatus,
|
|
15
|
+
} from "./types";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* THE STORE PORT: every read and write the engine makes, as named operations.
|
|
19
|
+
*
|
|
20
|
+
* The engine never builds a query. Two implementations ship:
|
|
21
|
+
* `createPrismaMessagingStore` over the Prisma delegates generated from the
|
|
22
|
+
* shipped partial (what a host mounts), and `createMemoryMessagingStore` (what
|
|
23
|
+
* a test mounts). The same contract suite runs over both — the Prisma one on
|
|
24
|
+
* real Postgres with the shipped migration — so the two cannot drift.
|
|
25
|
+
*
|
|
26
|
+
* Every operation is tenant-scoped where a tenant is known, and every unique
|
|
27
|
+
* key the migration enforces is enforced by both implementations, with the
|
|
28
|
+
* race answered the same way (the existing row wins).
|
|
29
|
+
*/
|
|
30
|
+
export interface MessagingStore {
|
|
31
|
+
// ── The inbox ──────────────────────────────────────────────────────────────
|
|
32
|
+
/** Store one raw delivery, deduped on `(channel, bodyHash)`. `fresh: false` for a redelivery. */
|
|
33
|
+
recordDelivery(input: {
|
|
34
|
+
channel: ChannelKind;
|
|
35
|
+
bodyHash: string;
|
|
36
|
+
rawBody: string;
|
|
37
|
+
receivedAt: Date;
|
|
38
|
+
}): Promise<{ id: string; fresh: boolean }>;
|
|
39
|
+
getDelivery(id: string): Promise<InboxDeliveryView | null>;
|
|
40
|
+
/** Close a delivery out, counting the attempt. */
|
|
41
|
+
settleDelivery(id: string, outcome: { state: "PROCESSED" | "FAILED"; error: string | null; at: Date }): Promise<void>;
|
|
42
|
+
/** Deliveries not yet processed, received before `receivedBefore`, under the attempt bound, oldest first. */
|
|
43
|
+
listRetryableDeliveries(input: { receivedBefore: Date; maxAttempts: number; take: number }): Promise<InboxDeliveryView[]>;
|
|
44
|
+
|
|
45
|
+
// ── Connections ────────────────────────────────────────────────────────────
|
|
46
|
+
findConnectionByAccount(channel: ChannelKind, externalAccountId: string): Promise<StoredConnection | null>;
|
|
47
|
+
getConnection(tenantId: string, id: string): Promise<StoredConnection | null>;
|
|
48
|
+
listConnections(tenantId: string): Promise<ConnectionView[]>;
|
|
49
|
+
/**
|
|
50
|
+
* Insert, or overwrite the row keyed by `(channel, externalAccountId)` — but
|
|
51
|
+
* only the same tenant's, or one that is REVOKED: the write itself is
|
|
52
|
+
* conditional, so two connects racing for one account cannot both win.
|
|
53
|
+
* `null` when the account is held by another tenant (the engine answers
|
|
54
|
+
* `ACCOUNT_TAKEN`).
|
|
55
|
+
*/
|
|
56
|
+
saveConnection(input: NewConnection): Promise<ConnectionView | null>;
|
|
57
|
+
setConnectionStatus(
|
|
58
|
+
tenantId: string,
|
|
59
|
+
id: string,
|
|
60
|
+
patch: { status: ConnectionStatus; statusReason: string | null; revokedAt: Date | null; credentialSealed?: null },
|
|
61
|
+
): Promise<boolean>;
|
|
62
|
+
|
|
63
|
+
// ── Conversations ──────────────────────────────────────────────────────────
|
|
64
|
+
findConversation(tenantId: string, channel: ChannelKind, contactId: string): Promise<ConversationView | null>;
|
|
65
|
+
getConversation(tenantId: string, id: string): Promise<ConversationView | null>;
|
|
66
|
+
/** Create one; on a lost race for `(tenant, channel, contact)` the existing row is returned. */
|
|
67
|
+
createConversation(input: NewConversation): Promise<ConversationView>;
|
|
68
|
+
/**
|
|
69
|
+
* Apply `patch` to the tenant's conversation. With a `guard` it is a
|
|
70
|
+
* COMPARE-AND-SET: the write happens only while the row still matches every
|
|
71
|
+
* guarded field (one `updateMany`), and `null` comes back when it does not —
|
|
72
|
+
* the caller re-reads and decides again. Without a guard, `null` only means
|
|
73
|
+
* "no such conversation".
|
|
74
|
+
*/
|
|
75
|
+
updateConversation(
|
|
76
|
+
tenantId: string,
|
|
77
|
+
id: string,
|
|
78
|
+
patch: ConversationPatch,
|
|
79
|
+
guard?: ConversationGuard,
|
|
80
|
+
): Promise<ConversationView | null>;
|
|
81
|
+
|
|
82
|
+
// ── Messages ───────────────────────────────────────────────────────────────
|
|
83
|
+
findMessageByExternalId(channel: ChannelKind, externalId: string): Promise<MessageView | null>;
|
|
84
|
+
/** Insert one; a duplicate `(channel, externalId)` is `created: false` and the existing row. */
|
|
85
|
+
insertMessage(input: NewMessage): Promise<{ created: boolean; message: MessageView }>;
|
|
86
|
+
updateMessage(tenantId: string, id: string, patch: MessagePatch): Promise<MessageView | null>;
|
|
87
|
+
listMessages(tenantId: string, conversationId: string): Promise<MessageView[]>;
|
|
88
|
+
/**
|
|
89
|
+
* Stamp a receipt on the tenant's outbound message: the receipt's timestamp
|
|
90
|
+
* column is written only while still null (so `(externalId, status)` is
|
|
91
|
+
* deduped by the row itself), and the delivery status only moves forward.
|
|
92
|
+
* False when no outbound message of that tenant has that id.
|
|
93
|
+
*/
|
|
94
|
+
applyReceipt(input: {
|
|
95
|
+
tenantId: string;
|
|
96
|
+
channel: ChannelKind;
|
|
97
|
+
externalId: string;
|
|
98
|
+
status: ReceiptStatus;
|
|
99
|
+
at: Date;
|
|
100
|
+
error: string | null;
|
|
101
|
+
}): Promise<boolean>;
|
|
102
|
+
|
|
103
|
+
// ── Retention ──────────────────────────────────────────────────────────────
|
|
104
|
+
/**
|
|
105
|
+
* Delete raw inbox rows past `cutoff`: the PROCESSED ones, and the FAILED
|
|
106
|
+
* ones that reached `maxAttempts` (nothing will retry them). One batch of up
|
|
107
|
+
* to `take` per state, found through the `(state, received_at)` index.
|
|
108
|
+
* Returns how many were deleted. Dedupe survives: a redelivered message
|
|
109
|
+
* still meets `(channel, external_id)` on its message row.
|
|
110
|
+
*/
|
|
111
|
+
purgeExpiredDeliveries(input: { cutoff: Date; maxAttempts: number; take: number }): Promise<number>;
|
|
112
|
+
/**
|
|
113
|
+
* Delete the text of conversations whose last message is older than
|
|
114
|
+
* `cutoff`: ONE indexed query finds up to `take` of them across every tenant
|
|
115
|
+
* (`has_text`, `last_message_at`), then their messages created at or before
|
|
116
|
+
* the cutoff lose `body`, `options` and `transcript`. Conversation rows,
|
|
117
|
+
* states and summaries stay.
|
|
118
|
+
*/
|
|
119
|
+
purgeExpiredText(input: { cutoff: Date; take: number }): Promise<{ conversations: number; messages: number }>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A connection with its sealed credential: only the engine sees this shape. */
|
|
123
|
+
export interface StoredConnection extends ConnectionView {
|
|
124
|
+
/** Null once the connection was revoked: disconnecting removes the token. */
|
|
125
|
+
credentialSealed: string | null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface NewConnection {
|
|
129
|
+
tenantId: string;
|
|
130
|
+
channel: ChannelKind;
|
|
131
|
+
externalAccountId: string;
|
|
132
|
+
externalParentId: string | null;
|
|
133
|
+
displayAddress: string;
|
|
134
|
+
credentialSealed: string;
|
|
135
|
+
connectedAt: Date;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface NewConversation {
|
|
139
|
+
tenantId: string;
|
|
140
|
+
channel: ChannelKind;
|
|
141
|
+
contactId: string;
|
|
142
|
+
contactName: string | null;
|
|
143
|
+
connectionId: string;
|
|
144
|
+
state: ConversationState;
|
|
145
|
+
lastInboundAt: Date | null;
|
|
146
|
+
lastMessageAt: Date | null;
|
|
147
|
+
optedOutAt?: Date | null;
|
|
148
|
+
hasText: boolean;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* What a compare-and-set update requires of the row it writes: every field
|
|
153
|
+
* given must equal the row's current value (`null` matches a null column),
|
|
154
|
+
* and `stateNot` that the state differs.
|
|
155
|
+
*/
|
|
156
|
+
export interface ConversationGuard {
|
|
157
|
+
state?: ConversationState;
|
|
158
|
+
stateNot?: ConversationState;
|
|
159
|
+
lastInboundAt?: Date | null;
|
|
160
|
+
lastMessageAt?: Date | null;
|
|
161
|
+
optedOutAt?: Date | null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export interface ConversationPatch {
|
|
165
|
+
contactName?: string | null;
|
|
166
|
+
connectionId?: string;
|
|
167
|
+
state?: ConversationState;
|
|
168
|
+
lastInboundAt?: Date | null;
|
|
169
|
+
lastMessageAt?: Date | null;
|
|
170
|
+
optedOutAt?: Date | null;
|
|
171
|
+
hasText?: boolean;
|
|
172
|
+
summary?: ConversationSummary;
|
|
173
|
+
summaryUpdatedAt?: Date;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface NewMessage {
|
|
177
|
+
conversationId: string;
|
|
178
|
+
tenantId: string;
|
|
179
|
+
channel: ChannelKind;
|
|
180
|
+
direction: MessageDirection;
|
|
181
|
+
kind: MessageKind;
|
|
182
|
+
body: string | null;
|
|
183
|
+
options: string | null;
|
|
184
|
+
attachmentRef: string | null;
|
|
185
|
+
externalId: string | null;
|
|
186
|
+
deliveryStatus: DeliveryStatus;
|
|
187
|
+
authorKind: AuthorKind;
|
|
188
|
+
staffUserId: string | null;
|
|
189
|
+
createdAt: Date;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface MessagePatch {
|
|
193
|
+
externalId?: string;
|
|
194
|
+
deliveryStatus?: DeliveryStatus;
|
|
195
|
+
error?: string | null;
|
|
196
|
+
transcript?: string;
|
|
197
|
+
failedAt?: Date;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The forward order of delivery statuses; FAILED outranks them all. */
|
|
201
|
+
export const DELIVERY_RANK: Readonly<Record<DeliveryStatus, number>> = {
|
|
202
|
+
RECEIVED: 0,
|
|
203
|
+
PENDING: 1,
|
|
204
|
+
ACCEPTED: 2,
|
|
205
|
+
SENT: 3,
|
|
206
|
+
DELIVERED: 4,
|
|
207
|
+
READ: 5,
|
|
208
|
+
FAILED: 6,
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
/** The receipt's timestamp column. */
|
|
212
|
+
export const RECEIPT_COLUMN = {
|
|
213
|
+
SENT: "sentAt",
|
|
214
|
+
DELIVERED: "deliveredAt",
|
|
215
|
+
READ: "readAt",
|
|
216
|
+
FAILED: "failedAt",
|
|
217
|
+
} as const satisfies Record<ReceiptStatus, keyof MessageView>;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connector's vocabulary: what every channel adapter normalizes into and
|
|
3
|
+
* what every store reads and writes. Machine words, never copy — a sentence a
|
|
4
|
+
* person reads is the host's.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A channel's key: `whatsapp` today; `email`, `slack` when their adapters land. Lowercase, dash-separated. */
|
|
8
|
+
export type ChannelKind = string;
|
|
9
|
+
|
|
10
|
+
/** Whether a connected account can be used. */
|
|
11
|
+
export type ConnectionStatus = "CONNECTED" | "REVOKED" | "ERROR";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Who answers a conversation:
|
|
15
|
+
* - `AGENT` — the host's automated agent (the `onInboundMessage` hook);
|
|
16
|
+
* - `HUMAN` — a person on the tenant's staff took it over;
|
|
17
|
+
* - `CLOSED` — nobody, until the contact writes again;
|
|
18
|
+
* - `OPTED_OUT` — the contact asked to stop. Nothing is sent until they write again.
|
|
19
|
+
*/
|
|
20
|
+
export type ConversationState = "AGENT" | "HUMAN" | "CLOSED" | "OPTED_OUT";
|
|
21
|
+
|
|
22
|
+
export type MessageDirection = "INBOUND" | "OUTBOUND";
|
|
23
|
+
|
|
24
|
+
/** What a message carries. Templates join when the template story lands. */
|
|
25
|
+
export type MessageKind = "TEXT" | "INTERACTIVE" | "AUDIO" | "OTHER";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Where a message stands:
|
|
29
|
+
* - `RECEIVED` — an inbound message;
|
|
30
|
+
* - `PENDING` — an outbound row recorded, the channel not yet called;
|
|
31
|
+
* - `ACCEPTED` — the channel took it and returned its id;
|
|
32
|
+
* - `SENT` / `DELIVERED` / `READ` — the channel's own receipts;
|
|
33
|
+
* - `FAILED` — the call failed, or the channel reported a failure.
|
|
34
|
+
*/
|
|
35
|
+
export type DeliveryStatus = "RECEIVED" | "PENDING" | "ACCEPTED" | "SENT" | "DELIVERED" | "READ" | "FAILED";
|
|
36
|
+
|
|
37
|
+
/** A receipt a channel reports for an outbound message. */
|
|
38
|
+
export type ReceiptStatus = "SENT" | "DELIVERED" | "READ" | "FAILED";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Who wrote a message. `CONTACT` is the person on the other end of the
|
|
42
|
+
* channel — a buyer, a supplier, a support requester: the host decides what
|
|
43
|
+
* that person is to it.
|
|
44
|
+
*/
|
|
45
|
+
export type AuthorKind = "CONTACT" | "AGENT" | "STAFF";
|
|
46
|
+
|
|
47
|
+
/** The structured summary a host keeps beside a conversation. JSON, never free text by convention. */
|
|
48
|
+
export type ConversationSummary = { readonly [key: string]: unknown };
|
|
49
|
+
|
|
50
|
+
/** What an inbound message carried, normalized across channels. */
|
|
51
|
+
export type InboundContent =
|
|
52
|
+
| { kind: "TEXT"; text: string }
|
|
53
|
+
/** A tap on a button or a list row the conversation offered. */
|
|
54
|
+
| { kind: "INTERACTIVE"; replyId: string; title: string }
|
|
55
|
+
/** A voice note or an audio file: only the channel's media id, never the bytes. */
|
|
56
|
+
| { kind: "AUDIO"; mediaId: string; mimeType: string | null }
|
|
57
|
+
/** Anything else (an image, a location, a sticker): kept as its channel type, not read. */
|
|
58
|
+
| { kind: "OTHER"; channelType: string };
|
|
59
|
+
|
|
60
|
+
/** One message a contact sent. */
|
|
61
|
+
export interface InboundMessageEvent {
|
|
62
|
+
type: "message";
|
|
63
|
+
/** The channel account it was sent TO (WhatsApp's phone_number_id). */
|
|
64
|
+
accountId: string;
|
|
65
|
+
/** The sender's address on the channel. */
|
|
66
|
+
contactId: string;
|
|
67
|
+
/** The name the channel shows for the sender, when it sends one. */
|
|
68
|
+
contactName: string | null;
|
|
69
|
+
/** The channel's id for the message. */
|
|
70
|
+
externalId: string;
|
|
71
|
+
sentAt: Date;
|
|
72
|
+
content: InboundContent;
|
|
73
|
+
/** The text asked to stop (an opt-out keyword). The message is still stored. */
|
|
74
|
+
optOut: boolean;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A receipt for a message the tenant sent. */
|
|
78
|
+
export interface StatusEvent {
|
|
79
|
+
type: "status";
|
|
80
|
+
accountId: string;
|
|
81
|
+
/** The channel's id of the outbound message. */
|
|
82
|
+
externalId: string;
|
|
83
|
+
status: ReceiptStatus;
|
|
84
|
+
at: Date;
|
|
85
|
+
/** The recipient's address, when the channel says. */
|
|
86
|
+
contactId: string | null;
|
|
87
|
+
/** The channel's error code and title, for a failure. */
|
|
88
|
+
error: string | null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The channel's own signal that a contact stopped messages (not a keyword in a text). */
|
|
92
|
+
export interface OptOutEvent {
|
|
93
|
+
type: "opt_out";
|
|
94
|
+
accountId: string;
|
|
95
|
+
contactId: string;
|
|
96
|
+
at: Date;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export type NormalizedEvent = InboundMessageEvent | StatusEvent | OptOutEvent;
|
|
100
|
+
|
|
101
|
+
/** A message the tenant sends, normalized across channels. */
|
|
102
|
+
export type OutboundContent =
|
|
103
|
+
| { kind: "TEXT"; text: string }
|
|
104
|
+
/** Up to the channel's number of reply buttons under a text. */
|
|
105
|
+
| { kind: "BUTTONS"; text: string; buttons: readonly { id: string; title: string }[] }
|
|
106
|
+
/** A text with one button that opens a list of rows in sections. */
|
|
107
|
+
| {
|
|
108
|
+
kind: "LIST";
|
|
109
|
+
text: string;
|
|
110
|
+
/** The words on the button that opens the list — the host's copy. */
|
|
111
|
+
buttonLabel: string;
|
|
112
|
+
sections: readonly {
|
|
113
|
+
title?: string;
|
|
114
|
+
rows: readonly { id: string; title: string; description?: string }[];
|
|
115
|
+
}[];
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** A connection as the package returns it: never the credential. */
|
|
119
|
+
export interface ConnectionView {
|
|
120
|
+
id: string;
|
|
121
|
+
tenantId: string;
|
|
122
|
+
channel: ChannelKind;
|
|
123
|
+
externalAccountId: string;
|
|
124
|
+
externalParentId: string | null;
|
|
125
|
+
displayAddress: string;
|
|
126
|
+
status: ConnectionStatus;
|
|
127
|
+
statusReason: string | null;
|
|
128
|
+
connectedAt: Date;
|
|
129
|
+
revokedAt: Date | null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface ConversationView {
|
|
133
|
+
id: string;
|
|
134
|
+
tenantId: string;
|
|
135
|
+
channel: ChannelKind;
|
|
136
|
+
contactId: string;
|
|
137
|
+
contactName: string | null;
|
|
138
|
+
connectionId: string;
|
|
139
|
+
state: ConversationState;
|
|
140
|
+
lastInboundAt: Date | null;
|
|
141
|
+
lastMessageAt: Date | null;
|
|
142
|
+
/** When the contact last opted out (the message's own time, not the processing time). Kept after a re-open. */
|
|
143
|
+
optedOutAt: Date | null;
|
|
144
|
+
hasText: boolean;
|
|
145
|
+
summary: ConversationSummary | null;
|
|
146
|
+
summaryUpdatedAt: Date | null;
|
|
147
|
+
createdAt: Date;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface MessageView {
|
|
151
|
+
id: string;
|
|
152
|
+
conversationId: string;
|
|
153
|
+
tenantId: string;
|
|
154
|
+
channel: ChannelKind;
|
|
155
|
+
direction: MessageDirection;
|
|
156
|
+
kind: MessageKind;
|
|
157
|
+
/** The text, the tapped choice's title, or an outbound prompt. Null once retention ran. */
|
|
158
|
+
body: string | null;
|
|
159
|
+
/** An outbound interactive message's choices, as JSON text. Null once retention ran. */
|
|
160
|
+
options: string | null;
|
|
161
|
+
/** An audio message's transcript, written by the host. Null once retention ran. */
|
|
162
|
+
transcript: string | null;
|
|
163
|
+
/** An attachment's (or a tapped choice's) id on the channel. */
|
|
164
|
+
attachmentRef: string | null;
|
|
165
|
+
externalId: string | null;
|
|
166
|
+
deliveryStatus: DeliveryStatus;
|
|
167
|
+
authorKind: AuthorKind;
|
|
168
|
+
staffUserId: string | null;
|
|
169
|
+
error: string | null;
|
|
170
|
+
createdAt: Date;
|
|
171
|
+
sentAt: Date | null;
|
|
172
|
+
deliveredAt: Date | null;
|
|
173
|
+
readAt: Date | null;
|
|
174
|
+
failedAt: Date | null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The inbox's processing state. */
|
|
178
|
+
export type DeliveryState = "PENDING" | "PROCESSED" | "FAILED";
|
|
179
|
+
|
|
180
|
+
export interface InboxDeliveryView {
|
|
181
|
+
id: string;
|
|
182
|
+
channel: ChannelKind;
|
|
183
|
+
rawBody: string;
|
|
184
|
+
state: DeliveryState;
|
|
185
|
+
attempts: number;
|
|
186
|
+
error: string | null;
|
|
187
|
+
receivedAt: Date;
|
|
188
|
+
processedAt: Date | null;
|
|
189
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging` — a channel-agnostic conversational messaging
|
|
3
|
+
* connector. The engine, its ports, the store port with its two
|
|
4
|
+
* implementations, and the channel adapter interface. Each channel is an
|
|
5
|
+
* adapter at its own subpath (`./whatsapp`); the webhook routes and job
|
|
6
|
+
* blueprints are at `./server`; the wiring manifests at `./manifest`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { createMessagingEngine, type MessagingEngine } from "./core/engine";
|
|
10
|
+
export {
|
|
11
|
+
ChannelSendFailure,
|
|
12
|
+
isWindowOpen,
|
|
13
|
+
OPEN_SEND_POLICY,
|
|
14
|
+
serviceWindowPolicy,
|
|
15
|
+
type ChannelAdapter,
|
|
16
|
+
type ChannelSendInput,
|
|
17
|
+
type HandshakeAnswer,
|
|
18
|
+
type SendPolicy,
|
|
19
|
+
type SendPolicyContext,
|
|
20
|
+
type SendPolicyVerdict,
|
|
21
|
+
} from "./core/channel";
|
|
22
|
+
export {
|
|
23
|
+
MESSAGING_DEFAULTS,
|
|
24
|
+
type InboundMessageNotice,
|
|
25
|
+
type MessagingClockPort,
|
|
26
|
+
type MessagingEngineConfig,
|
|
27
|
+
type MessagingEnqueuePort,
|
|
28
|
+
type MessagingHooks,
|
|
29
|
+
type MessagingLogger,
|
|
30
|
+
type MessagingSecretsPort,
|
|
31
|
+
} from "./core/ports";
|
|
32
|
+
export {
|
|
33
|
+
MessagingConnectError,
|
|
34
|
+
MessagingSendError,
|
|
35
|
+
type MessagingConnectErrorCode,
|
|
36
|
+
type MessagingSendErrorCode,
|
|
37
|
+
} from "./core/errors";
|
|
38
|
+
export { PROCESS_DELIVERY_JOB, type DeliveryOutcome } from "./core/inbox";
|
|
39
|
+
export type { EventOutcome } from "./core/inbound";
|
|
40
|
+
export type { SendAuthor, SendInput } from "./core/sender";
|
|
41
|
+
export type { ConnectInput } from "./core/connections";
|
|
42
|
+
export type {
|
|
43
|
+
ConversationPatch,
|
|
44
|
+
MessagePatch,
|
|
45
|
+
MessagingStore,
|
|
46
|
+
NewConnection,
|
|
47
|
+
NewConversation,
|
|
48
|
+
NewMessage,
|
|
49
|
+
StoredConnection,
|
|
50
|
+
} from "./core/store";
|
|
51
|
+
export { createMemoryMessagingStore, type MemoryStoreDump } from "./core/memory-store";
|
|
52
|
+
export { createPrismaMessagingStore, type MessagingPrismaDb } from "./core/prisma-store";
|
|
53
|
+
export { bodyHash } from "./core/hash";
|
|
54
|
+
export type * from "./core/types";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging/manifest` — the SHARED wiring manifest.
|
|
3
|
+
*
|
|
4
|
+
* - `db` — `composed`: the partial names no host table (tenant and staff ids
|
|
5
|
+
* are by-value strings), so it composes into any host's schema folder.
|
|
6
|
+
* Composed rather than isolated because a host keeps its own links (a cart,
|
|
7
|
+
* a customer, a sale) keyed by the conversation id, in the same database.
|
|
8
|
+
* - `observability` — failures file under `messaging`.
|
|
9
|
+
* - `server` — `http` (the webhook pair) and `jobs` (process, reconcile,
|
|
10
|
+
* retention).
|
|
11
|
+
*
|
|
12
|
+
* Declined, each with its argument in `.wiring-conformance.json`:
|
|
13
|
+
* `permissions` (no authenticated route ships yet), `notifications` (an
|
|
14
|
+
* arriving message is the host's news, through `onInboundMessage`), `mcp`
|
|
15
|
+
* (conversations and contacts' addresses are off the agent surface by
|
|
16
|
+
* design), `email`, the environment (every secret arrives as config), `e2e`,
|
|
17
|
+
* and the web capabilities (the screens are the host's).
|
|
18
|
+
*
|
|
19
|
+
* `@12-apps/wiring` is a TYPE-ONLY dependency here: the manifest is a plain
|
|
20
|
+
* `satisfies`-checked value, and the producer's assertions run in this
|
|
21
|
+
* package's own test suite.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { PackageManifest } from "@12-apps/wiring";
|
|
25
|
+
|
|
26
|
+
export const messagingManifest = {
|
|
27
|
+
name: "@12-apps/messaging",
|
|
28
|
+
contract: 1,
|
|
29
|
+
db: { partial: "prisma/messaging.prisma", migrations: "prisma/migrations" },
|
|
30
|
+
observability: { namespace: "messaging" },
|
|
31
|
+
server: ["http", "jobs"],
|
|
32
|
+
} as const satisfies PackageManifest;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging/manifest/server` — the server capabilities.
|
|
3
|
+
*
|
|
4
|
+
* `http.create` IS `createApiMessaging`: its descriptors already satisfy the
|
|
5
|
+
* wiring contract's `WireRoute`, both marked `webhook`. `jobs` is the
|
|
6
|
+
* connector's own cadence; a host binds `{ engine }`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { AnyServerManifest } from "@12-apps/wiring";
|
|
10
|
+
|
|
11
|
+
import { createApiMessaging } from "../server";
|
|
12
|
+
import { MESSAGING_JOBS } from "../server/jobs";
|
|
13
|
+
|
|
14
|
+
export const messagingServerManifest = {
|
|
15
|
+
name: "@12-apps/messaging",
|
|
16
|
+
http: { create: createApiMessaging },
|
|
17
|
+
jobs: MESSAGING_JOBS,
|
|
18
|
+
} as const satisfies AnyServerManifest;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging/server` — framework-neutral route descriptors and job
|
|
3
|
+
* blueprints, in the `@12-apps/wiring` contract's shapes.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { WireRoute, WireRouteAnswer } from "@12-apps/wiring";
|
|
7
|
+
|
|
8
|
+
import { webhookRoutes, type MessagingApiConfig } from "./webhook";
|
|
9
|
+
|
|
10
|
+
/** The connector's HTTP surface: the webhook pair. Mount it where the host keeps webhooks (`/api`). */
|
|
11
|
+
export function createApiMessaging(config: MessagingApiConfig): { routes: readonly WireRoute<unknown, WireRouteAnswer>[] } {
|
|
12
|
+
return { routes: webhookRoutes(config) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type { MessagingApiConfig } from "./webhook";
|
|
16
|
+
export {
|
|
17
|
+
MESSAGING_JOBS,
|
|
18
|
+
MESSAGING_PROCESS_ATTEMPTS,
|
|
19
|
+
MESSAGING_SWEEP_QUEUE,
|
|
20
|
+
type MessagingJobDeps,
|
|
21
|
+
type ProcessDeliveryPayload,
|
|
22
|
+
} from "./jobs";
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { JobsContribution, WireJobBlueprint } from "@12-apps/wiring";
|
|
2
|
+
|
|
3
|
+
import type { MessagingEngine } from "../core/engine";
|
|
4
|
+
import { errorText } from "../core/errors";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The connector's three jobs, declared here because every number in them is
|
|
8
|
+
* the connector's knowledge, not a host's:
|
|
9
|
+
*
|
|
10
|
+
* - `process-delivery`, on demand: one stored delivery, parsed and applied.
|
|
11
|
+
* Five attempts with backoff; every handler is idempotent, so a retry
|
|
12
|
+
* redoes nothing already done.
|
|
13
|
+
* - `reconcile-inbox`, every five minutes: re-runs deliveries a dead worker or
|
|
14
|
+
* a refused enqueue left behind, up to the engine's attempt bound.
|
|
15
|
+
* - `retention`, every ten minutes: deletes the text of conversations whose
|
|
16
|
+
* last message is past the retention window, through ONE indexed query
|
|
17
|
+
* across every tenant. Ten minutes against a twelve-hour window keeps text
|
|
18
|
+
* at most a few minutes past its deadline.
|
|
19
|
+
*
|
|
20
|
+
* Bound with `{ engine }`, these arrive at a runner as
|
|
21
|
+
* `messaging.process-delivery`, `messaging.reconcile-inbox` and
|
|
22
|
+
* `messaging.retention`. A host with no worker declines `jobs` in writing —
|
|
23
|
+
* and then nothing is processed, so it should not adopt the connector.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export interface MessagingJobDeps {
|
|
27
|
+
engine: Pick<MessagingEngine, "processDelivery" | "reconcile" | "sweepRetention">;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ProcessDeliveryPayload {
|
|
31
|
+
deliveryId: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
|
|
35
|
+
export const MESSAGING_SWEEP_QUEUE = "sweeps";
|
|
36
|
+
|
|
37
|
+
const SWEEP_LEASE_MS = 5 * 60_000;
|
|
38
|
+
|
|
39
|
+
export const MESSAGING_PROCESS_ATTEMPTS = 5;
|
|
40
|
+
|
|
41
|
+
const processDelivery: WireJobBlueprint<ProcessDeliveryPayload, MessagingJobDeps> = {
|
|
42
|
+
name: "process-delivery",
|
|
43
|
+
attempts: MESSAGING_PROCESS_ATTEMPTS,
|
|
44
|
+
// Short: a contact is waiting for the reply this processing leads to.
|
|
45
|
+
backoff: { type: "exponential", delayMs: 2_000 },
|
|
46
|
+
handle: async (payload, deps, context) => {
|
|
47
|
+
try {
|
|
48
|
+
const outcome = await deps.engine.processDelivery(payload.deliveryId);
|
|
49
|
+
if (outcome.kind === "unreadable") {
|
|
50
|
+
context.logger.warn(`messaging.process-delivery: ${payload.deliveryId} unreadable: ${outcome.reason}`);
|
|
51
|
+
}
|
|
52
|
+
} catch (error) {
|
|
53
|
+
context.logger.warn(`messaging.process-delivery: ${payload.deliveryId} failed: ${errorText(error)}`);
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const reconcileInbox: WireJobBlueprint<void, MessagingJobDeps> = {
|
|
60
|
+
name: "reconcile-inbox",
|
|
61
|
+
queue: MESSAGING_SWEEP_QUEUE,
|
|
62
|
+
concurrency: 1,
|
|
63
|
+
schedule: { pattern: "*/5 * * * *", timezone: "UTC" },
|
|
64
|
+
// Never retried by the queue: the next tick re-finds everything from the rows.
|
|
65
|
+
attempts: 1,
|
|
66
|
+
lease: { ttlMs: SWEEP_LEASE_MS },
|
|
67
|
+
handle: async (_payload, deps, context) => {
|
|
68
|
+
const result = await deps.engine.reconcile();
|
|
69
|
+
if (result.retried === 0) return;
|
|
70
|
+
context.logger.info(`messaging.reconcile-inbox: re-ran ${result.retried} delivery(ies), ${result.failed} failed again.`);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const retention: WireJobBlueprint<void, MessagingJobDeps> = {
|
|
75
|
+
name: "retention",
|
|
76
|
+
queue: MESSAGING_SWEEP_QUEUE,
|
|
77
|
+
concurrency: 1,
|
|
78
|
+
schedule: { pattern: "*/10 * * * *", timezone: "UTC" },
|
|
79
|
+
attempts: 1,
|
|
80
|
+
lease: { ttlMs: SWEEP_LEASE_MS },
|
|
81
|
+
handle: async (_payload, deps, context) => {
|
|
82
|
+
const result = await deps.engine.sweepRetention();
|
|
83
|
+
if (result.conversations === 0) return;
|
|
84
|
+
context.logger.info(
|
|
85
|
+
`messaging.retention: deleted the text of ${result.messages} message(s) in ${result.conversations} conversation(s)` +
|
|
86
|
+
(result.more ? "; more are due." : "."),
|
|
87
|
+
);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** The jobs contribution. */
|
|
92
|
+
export const MESSAGING_JOBS = {
|
|
93
|
+
namespace: "messaging",
|
|
94
|
+
blueprints: {
|
|
95
|
+
"process-delivery": processDelivery,
|
|
96
|
+
"reconcile-inbox": reconcileInbox,
|
|
97
|
+
retention,
|
|
98
|
+
},
|
|
99
|
+
} as const satisfies JobsContribution<MessagingJobDeps>;
|