@segmentstream/agent 0.73.2 → 0.75.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/CHANGELOG.md +48 -0
- package/dist/_chunks/{build-metadata-3mxf7v2b.mjs → build-metadata-CLenocka.mjs} +1 -1
- package/dist/_chunks/{chat-archive-BCPLSZeK.mjs → chat-archive-CDk-FPLX.mjs} +11 -4
- package/dist/_chunks/{chat-archive-DK7uCgff.mjs → chat-archive-DHYplDT5.mjs} +1 -1
- package/dist/extension/config.d.ts +12 -0
- package/dist/extension/config.mjs +21 -2
- package/dist/extension/extension.d.ts +1 -1
- package/dist/extension/hooks/chat-context.mjs +1 -1
- package/dist/extension/hooks/chat-recorder.mjs +1 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/chat-archive.d.ts +6 -1
- package/dist/extension/lib/chat-archive.mjs +1 -1
- package/dist/extension/lib/chat-context.mjs +1 -1
- package/dist/extension/lib/chat-messages.d.ts +108 -0
- package/dist/extension/lib/chat-messages.mjs +169 -4
- package/dist/extension/lib/chat-recorder.mjs +44 -13
- package/dist/extension/lib/chat-store.d.ts +23 -1
- package/dist/extension/lib/email/channel.d.ts +3 -0
- package/dist/extension/lib/email/channel.mjs +60 -14
- package/dist/extension/lib/group-routing/routing-context.mjs +1 -1
- package/dist/extension/lib/model-service-alert.mjs +1 -1
- package/dist/extension/lib/review/judge.mjs +1 -1
- package/dist/extension/lib/review/reply.mjs +1 -1
- package/dist/extension/lib/review/revision-channel.mjs +1 -1
- package/dist/extension/lib/slack/adapter.mjs +1 -1
- package/dist/extension/lib/telegram/adapter.mjs +3 -3
- package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
- package/dist/extension/lib/telegram/confirmations.mjs +1 -1
- package/dist/extension/lib/telegram/delivery-diagnostics.mjs +1 -1
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/inbound.mjs +1 -1
- package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
- package/dist/extension/lib/telegram/store-capture.mjs +1 -1
- package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
- package/dist/extension/lib/whatsapp/adapter.d.ts +21 -1
- package/dist/extension/lib/whatsapp/adapter.mjs +82 -13
- package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
- package/dist/extension/lib/whatsapp/changes.d.ts +46 -0
- package/dist/extension/lib/whatsapp/changes.mjs +212 -0
- package/dist/extension/lib/whatsapp/sent.mjs +1 -1
- package/dist/extension/lib/whatsapp/statuses.d.ts +9 -0
- package/dist/extension/lib/whatsapp/statuses.mjs +9 -0
- package/dist/extension/lib/workspace-channel/channel.d.ts +68 -7
- package/dist/extension/lib/workspace-channel/channel.mjs +149 -33
- package/dist/extension/lib/workspace-chat-archive.d.ts +7 -0
- package/dist/extension/lib/workspace-chat-archive.mjs +1 -1
- package/package.json +2 -2
|
@@ -20,12 +20,14 @@ import { MAXIMUM_DOWNLOAD_BYTES, connectionProxy } from "../connection-proxy.mjs
|
|
|
20
20
|
import { appOrigin, channelsEnabled, proxyEnvironment, webhookSecret } from "../environment.mjs";
|
|
21
21
|
import { agentIdentities } from "../identities.mjs";
|
|
22
22
|
import { runtimeToken } from "../runtime-token.mjs";
|
|
23
|
-
import { r as chatArchive } from "../../../_chunks/chat-archive-
|
|
24
|
-
import { recordHandledMessage } from "../chat-messages.mjs";
|
|
23
|
+
import { r as chatArchive } from "../../../_chunks/chat-archive-CDk-FPLX.mjs";
|
|
24
|
+
import { recordHandledMessage, recordReceivedMessage, stagedFiles } from "../chat-messages.mjs";
|
|
25
25
|
import { handleWorkspaceButton } from "./callbacks.mjs";
|
|
26
|
+
import { recordWhatsAppChanges, whatsappChanges, whatsappParts } from "./changes.mjs";
|
|
26
27
|
import { recordEchoes, whatsappEchoes } from "./echoes.mjs";
|
|
27
28
|
import { withPlainLinks } from "./links.mjs";
|
|
28
29
|
import { collectSent, noteSent, recordSent } from "./sent.mjs";
|
|
30
|
+
import { STATUSES_HEADER, STATUSES_RECORDED } from "./statuses.mjs";
|
|
29
31
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
30
32
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
31
33
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
@@ -117,7 +119,9 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
|
|
|
117
119
|
if (!this.#runtime.enabled()) return new Response(null, { status: 404 });
|
|
118
120
|
if (request.method !== "POST") return new Response(null, { status: 405 });
|
|
119
121
|
const record = this.#runtime.echoes;
|
|
120
|
-
|
|
122
|
+
const change = this.#runtime.changes;
|
|
123
|
+
let recorded = false;
|
|
124
|
+
if (record !== void 0 || change !== void 0) {
|
|
121
125
|
const body = await request.clone().text();
|
|
122
126
|
if (this.verifySignature(body, request.headers.get("x-hub-signature-256"))) {
|
|
123
127
|
let payload;
|
|
@@ -126,16 +130,32 @@ var ProxiedWhatsAppAdapter = class extends WhatsAppAdapter {
|
|
|
126
130
|
} catch {
|
|
127
131
|
payload = void 0;
|
|
128
132
|
}
|
|
129
|
-
const echoes = whatsappEchoes(payload);
|
|
133
|
+
const echoes = record === void 0 ? [] : whatsappEchoes(payload);
|
|
134
|
+
const changes = whatsappChanges(payload);
|
|
130
135
|
if (echoes.length > 0) try {
|
|
131
136
|
await record(echoes);
|
|
132
137
|
} catch (cause) {
|
|
133
138
|
report("echo_record_failed", cause);
|
|
134
139
|
return new Response(null, { status: 503 });
|
|
135
140
|
}
|
|
141
|
+
if (change !== void 0 && (changes.changes.length > 0 || changes.contacts.length > 0)) try {
|
|
142
|
+
recorded = await change(changes) && changes.statuses;
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
report("change_record_failed", cause);
|
|
145
|
+
return new Response(null, { status: 503 });
|
|
146
|
+
}
|
|
136
147
|
}
|
|
137
148
|
}
|
|
138
|
-
|
|
149
|
+
const response = await super.handleWebhook(request, options);
|
|
150
|
+
if (recorded && response.ok) {
|
|
151
|
+
const headers = new Headers(response.headers);
|
|
152
|
+
headers.set(STATUSES_HEADER, STATUSES_RECORDED);
|
|
153
|
+
return new Response(response.body, {
|
|
154
|
+
status: response.status,
|
|
155
|
+
headers
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return response;
|
|
139
159
|
}
|
|
140
160
|
verifySignature(body, signature) {
|
|
141
161
|
const secret = this.#runtime.secret();
|
|
@@ -258,6 +278,7 @@ function segmentstreamWhatsApp(options) {
|
|
|
258
278
|
enabled: () => channelsEnabled(environment) && settings() !== null && webhookSecret(environment) !== void 0,
|
|
259
279
|
secret: () => webhookSecret(environment),
|
|
260
280
|
echoes: (echoes) => recordEchoes(chats(), echoes),
|
|
281
|
+
changes: (changes) => recordWhatsAppChanges(chats(), changes),
|
|
261
282
|
proxy: () => {
|
|
262
283
|
const connection = settings()?.connection;
|
|
263
284
|
if (connection === void 0) throw new Error("The WhatsApp channel is not configured in agent/segmentstream.json.");
|
|
@@ -337,11 +358,27 @@ function segmentstreamWhatsApp(options) {
|
|
|
337
358
|
await thread.post(pairingMessage(text, localizedText(admission.replies.pairingButton), `${appOrigin(environment)}/agent/connect?code=${encodeURIComponent(code)}`));
|
|
338
359
|
},
|
|
339
360
|
turn: async (text, auth) => {
|
|
340
|
-
if (thread !== null)
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
361
|
+
if (thread !== null) {
|
|
362
|
+
const delivery = await bridge.send(text, {
|
|
363
|
+
thread: thread.id,
|
|
364
|
+
idempotencyKey: currentKey("whatsapp", `${event.messageId}:button`),
|
|
365
|
+
auth
|
|
366
|
+
});
|
|
367
|
+
const memberId = memberIdOf(auth);
|
|
368
|
+
if (memberId !== void 0) await recordReceivedMessage(chats(), {
|
|
369
|
+
channel: currentChannel("whatsapp"),
|
|
370
|
+
chatId: thread.id,
|
|
371
|
+
memberId,
|
|
372
|
+
senderId: event.user.userId,
|
|
373
|
+
senderName: event.user.fullName,
|
|
374
|
+
messageId: event.messageId,
|
|
375
|
+
text,
|
|
376
|
+
outcome: { turn: {
|
|
377
|
+
sessionId: delivery.sessionId,
|
|
378
|
+
deliveryId: delivery.deliveryId
|
|
379
|
+
} }
|
|
380
|
+
}).catch((cause) => report("message_record_failed", cause));
|
|
381
|
+
}
|
|
345
382
|
},
|
|
346
383
|
report,
|
|
347
384
|
token,
|
|
@@ -388,7 +425,7 @@ function segmentstreamWhatsApp(options) {
|
|
|
388
425
|
sourceRef: (index) => `${thread.id}:${message.id}:${index}`
|
|
389
426
|
}
|
|
390
427
|
});
|
|
391
|
-
await bridge.send(whatsappTurnContent({
|
|
428
|
+
const delivery = await bridge.send(whatsappTurnContent({
|
|
392
429
|
content: messageContentOf(message),
|
|
393
430
|
message,
|
|
394
431
|
media
|
|
@@ -398,6 +435,22 @@ function segmentstreamWhatsApp(options) {
|
|
|
398
435
|
auth,
|
|
399
436
|
...media.context.length === 0 ? {} : { context: media.context }
|
|
400
437
|
});
|
|
438
|
+
const raw = inboundOf(message);
|
|
439
|
+
await recordReceivedMessage(chats(), {
|
|
440
|
+
channel: currentChannel("whatsapp"),
|
|
441
|
+
chatId: thread.id,
|
|
442
|
+
memberId,
|
|
443
|
+
senderId: message.author.userId,
|
|
444
|
+
senderName: message.author.fullName,
|
|
445
|
+
messageId: message.id,
|
|
446
|
+
text: media.text,
|
|
447
|
+
files: stagedFiles(media.files),
|
|
448
|
+
...raw,
|
|
449
|
+
outcome: { turn: {
|
|
450
|
+
sessionId: delivery.sessionId,
|
|
451
|
+
deliveryId: delivery.deliveryId
|
|
452
|
+
} }
|
|
453
|
+
}).catch((cause) => report("message_record_failed", cause));
|
|
401
454
|
});
|
|
402
455
|
const recorded = withRecordedReplies(withDurableTyping(bridge.channel), chats);
|
|
403
456
|
const reviewed = options.review === void 0 ? void 0 : channelReview(options.review, {
|
|
@@ -411,6 +464,21 @@ function segmentstreamWhatsApp(options) {
|
|
|
411
464
|
routes: withNamedRoutes("whatsapp", channel.routes.flatMap((route) => route.transport === "websocket" ? [] : [route]), (name) => options.settings(name) !== null)
|
|
412
465
|
};
|
|
413
466
|
}
|
|
467
|
+
function record(value) {
|
|
468
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
469
|
+
}
|
|
470
|
+
function inboundOf(message) {
|
|
471
|
+
const inbound = record(record(message.raw)?.message);
|
|
472
|
+
if (inbound === void 0) return {};
|
|
473
|
+
const replyTo = record(inbound.context)?.id;
|
|
474
|
+
const parts = whatsappParts(inbound);
|
|
475
|
+
const seconds = typeof inbound.timestamp === "string" && /^\d{1,12}$/u.test(inbound.timestamp) ? Number(inbound.timestamp) : void 0;
|
|
476
|
+
return {
|
|
477
|
+
...typeof replyTo === "string" && replyTo !== "" ? { replyTo } : {},
|
|
478
|
+
...parts.length === 0 ? {} : { parts },
|
|
479
|
+
...seconds === void 0 ? {} : { at: new Date(seconds * 1e3).toISOString() }
|
|
480
|
+
};
|
|
481
|
+
}
|
|
414
482
|
async function receive(input) {
|
|
415
483
|
const { thread, message, admission, identities } = input;
|
|
416
484
|
if (message.author.isMe) return;
|
|
@@ -451,7 +519,8 @@ async function receive(input) {
|
|
|
451
519
|
senderName: display ?? null,
|
|
452
520
|
messageId: message.id,
|
|
453
521
|
text: message.text,
|
|
454
|
-
files: message.attachments
|
|
522
|
+
files: message.attachments,
|
|
523
|
+
...message.raw === void 0 ? {} : inboundOf({ raw: message.raw })
|
|
455
524
|
});
|
|
456
525
|
return;
|
|
457
526
|
}
|
|
@@ -513,4 +582,4 @@ function pairingMessage(text, label, url) {
|
|
|
513
582
|
fallbackText: fallback
|
|
514
583
|
};
|
|
515
584
|
}
|
|
516
|
-
export { ProxiedWhatsAppAdapter, WHATSAPP_AUTHENTICATOR, WHATSAPP_PROXY_ORIGIN, WhatsAppProxyRouteError, pairingMessage, proxyPath, receive, segmentstreamWhatsApp, whatsappPrincipal, withRecordedReplies };
|
|
585
|
+
export { ProxiedWhatsAppAdapter, WHATSAPP_AUTHENTICATOR, WHATSAPP_PROXY_ORIGIN, WhatsAppProxyRouteError, inboundOf, pairingMessage, proxyPath, receive, segmentstreamWhatsApp, whatsappPrincipal, withRecordedReplies };
|
|
@@ -6,7 +6,7 @@ __eveDirname(__filename);
|
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { _ as AttachmentError } from "../../../_chunks/principal-Zf42Yf4r.mjs";
|
|
8
8
|
import { sendStoredAttachments } from "../attachments-send.mjs";
|
|
9
|
-
import { r as chatArchive } from "../../../_chunks/chat-archive-
|
|
9
|
+
import { r as chatArchive } from "../../../_chunks/chat-archive-CDk-FPLX.mjs";
|
|
10
10
|
import { connectionProxy } from "../connection-proxy.mjs";
|
|
11
11
|
import { redactDiagnostic } from "../diagnostics.mjs";
|
|
12
12
|
import { proxyEnvironment } from "../environment.mjs";
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type ChatArchive } from "../chat-archive.js";
|
|
2
|
+
import { type ChatChange, type ChatPart } from "../chat-messages.js";
|
|
3
|
+
/**
|
|
4
|
+
* How long a failure Meta reports waits for its message, between tries: Meta can report a send
|
|
5
|
+
* failed before the agent stored the send's receipt, which names the message.
|
|
6
|
+
*/
|
|
7
|
+
export declare const FAILURE_RETRY_MS: ReadonlyArray<number>;
|
|
8
|
+
/**
|
|
9
|
+
* What a relayed WhatsApp delivery says of messages beside the people's new ones, which the Chat
|
|
10
|
+
* SDK adapter reads (`docs/agent.md`, "Message changes"): the delivery statuses of messages the
|
|
11
|
+
* number sent, people's reactions, and on a number in Coexistence with the WhatsApp Business app,
|
|
12
|
+
* edits and deletions by the person or by the business in the app. Each is a change of a message
|
|
13
|
+
* in the person's chat, found by Meta's id of it, and starts no turn. A contact card a person
|
|
14
|
+
* sends, which the adapter reads as no message, is recorded in their chat with its parts.
|
|
15
|
+
*/
|
|
16
|
+
/** A change one delivery holds, in the person's chat on the channel the delivery runs for. */
|
|
17
|
+
export type WhatsAppChange = ChatChange extends infer Change ? Change extends unknown ? Omit<Change, "channel"> : never : never;
|
|
18
|
+
/** A contact card a person sent, recorded in their chat without a turn. */
|
|
19
|
+
export interface WhatsAppContactCard {
|
|
20
|
+
readonly chatId: string;
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly from: string;
|
|
23
|
+
readonly parts: ReadonlyArray<ChatPart>;
|
|
24
|
+
readonly replyTo?: string;
|
|
25
|
+
readonly at?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface WhatsAppChanges {
|
|
28
|
+
readonly changes: ReadonlyArray<WhatsAppChange>;
|
|
29
|
+
readonly contacts: ReadonlyArray<WhatsAppContactCard>;
|
|
30
|
+
/** Whether the delivery holds delivery statuses, which the channel answers it recorded. */
|
|
31
|
+
readonly statuses: boolean;
|
|
32
|
+
}
|
|
33
|
+
/** A person's location or contact card as the chat's parts. */
|
|
34
|
+
export declare function whatsappParts(message: Readonly<Record<string, unknown>>): ReadonlyArray<ChatPart>;
|
|
35
|
+
/**
|
|
36
|
+
* The changes a verified relayed delivery holds, in order, each in the person's chat as the Chat
|
|
37
|
+
* SDK adapter names it, `whatsapp:<phone number id>:<person>`: the person by their phone number,
|
|
38
|
+
* else by their user id.
|
|
39
|
+
*/
|
|
40
|
+
export declare function whatsappChanges(payload: unknown): WhatsAppChanges;
|
|
41
|
+
/**
|
|
42
|
+
* Applies a delivery's changes, then records its contact cards, on the WhatsApp channel the
|
|
43
|
+
* delivery runs for. Answers whether its statuses were recorded: false on the chat archive in
|
|
44
|
+
* Cloud, which keeps no changes, so the platform keeps a failure Meta reports there itself.
|
|
45
|
+
*/
|
|
46
|
+
export declare function recordWhatsAppChanges(archive: ChatArchive, read: WhatsAppChanges, wait?: (ms: number) => Promise<void>): Promise<boolean>;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { fileURLToPath as __eveFileURLToPath } from "node:url";
|
|
2
|
+
import { dirname as __eveDirname } from "node:path";
|
|
3
|
+
import { createRequire as __eveCreateRequire } from "node:module";
|
|
4
|
+
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
|
+
__eveDirname(__filename);
|
|
6
|
+
__eveCreateRequire(import.meta.url);
|
|
7
|
+
import { currentChannel, currentKey } from "../channel-scope.mjs";
|
|
8
|
+
import { f as storeOf } from "../../../_chunks/chat-archive-CDk-FPLX.mjs";
|
|
9
|
+
import { applyChatChange, chatPart, recordUnreadMessage } from "../chat-messages.mjs";
|
|
10
|
+
import { WHATSAPP_REFUSALS } from "@segmentstream/ontology/whatsapp";
|
|
11
|
+
const FAILURE_RETRY_MS = [
|
|
12
|
+
500,
|
|
13
|
+
1e3,
|
|
14
|
+
2e3
|
|
15
|
+
];
|
|
16
|
+
function record(value) {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
18
|
+
}
|
|
19
|
+
function text(value) {
|
|
20
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
21
|
+
}
|
|
22
|
+
function list(value) {
|
|
23
|
+
return Array.isArray(value) ? value : [];
|
|
24
|
+
}
|
|
25
|
+
function time(value) {
|
|
26
|
+
const seconds = typeof value === "string" && /^\d{1,12}$/u.test(value) ? Number(value) : NaN;
|
|
27
|
+
return Number.isFinite(seconds) ? new Date(seconds * 1e3).toISOString() : void 0;
|
|
28
|
+
}
|
|
29
|
+
const CAPTIONED = [
|
|
30
|
+
"image",
|
|
31
|
+
"video",
|
|
32
|
+
"document",
|
|
33
|
+
"audio",
|
|
34
|
+
"sticker"
|
|
35
|
+
];
|
|
36
|
+
function contentText(content) {
|
|
37
|
+
return text(record(content.text)?.body) ?? CAPTIONED.map((field) => text(record(content[field])?.caption)).find(Boolean) ?? "";
|
|
38
|
+
}
|
|
39
|
+
function failureOf(errors) {
|
|
40
|
+
const codes = list(errors).flatMap((error) => {
|
|
41
|
+
const code = record(error)?.code;
|
|
42
|
+
return typeof code === "number" && Number.isInteger(code) ? [code] : [];
|
|
43
|
+
});
|
|
44
|
+
return codes.map((code) => WHATSAPP_REFUSALS[code]).find(Boolean) ?? (codes[0] === void 0 ? void 0 : `whatsapp_${codes[0]}`);
|
|
45
|
+
}
|
|
46
|
+
function whatsappParts(message) {
|
|
47
|
+
if (message.type === "location") {
|
|
48
|
+
const location = record(message.location);
|
|
49
|
+
const part = chatPart({
|
|
50
|
+
type: "location",
|
|
51
|
+
latitude: location?.latitude,
|
|
52
|
+
longitude: location?.longitude,
|
|
53
|
+
name: location?.name,
|
|
54
|
+
address: location?.address
|
|
55
|
+
});
|
|
56
|
+
return part === void 0 ? [] : [part];
|
|
57
|
+
}
|
|
58
|
+
if (message.type === "contacts") return list(message.contacts).flatMap((item) => {
|
|
59
|
+
const contact = record(item);
|
|
60
|
+
const name = record(contact?.name);
|
|
61
|
+
const part = chatPart({
|
|
62
|
+
type: "contact",
|
|
63
|
+
name: text(name?.formatted_name) ?? [text(name?.first_name), text(name?.last_name)].filter(Boolean).join(" "),
|
|
64
|
+
phones: list(contact?.phones).map((phone) => record(phone)?.phone),
|
|
65
|
+
emails: list(contact?.emails).map((email) => record(email)?.email),
|
|
66
|
+
organization: text(record(contact?.org)?.company)
|
|
67
|
+
});
|
|
68
|
+
return part === void 0 ? [] : [part];
|
|
69
|
+
});
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
function revision(chatId, message) {
|
|
73
|
+
const at = time(message.timestamp);
|
|
74
|
+
if (message.type === "edit") {
|
|
75
|
+
const edit = record(message.edit);
|
|
76
|
+
const target = text(edit?.original_message_id);
|
|
77
|
+
const content = record(edit?.message);
|
|
78
|
+
return target === void 0 || content === void 0 ? void 0 : {
|
|
79
|
+
chatId,
|
|
80
|
+
target,
|
|
81
|
+
change: "edit",
|
|
82
|
+
text: contentText(content),
|
|
83
|
+
...at === void 0 ? {} : { at }
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (message.type === "revoke") {
|
|
87
|
+
const target = text(record(message.revoke)?.original_message_id);
|
|
88
|
+
return target === void 0 ? void 0 : {
|
|
89
|
+
chatId,
|
|
90
|
+
target,
|
|
91
|
+
change: "delete",
|
|
92
|
+
...at === void 0 ? {} : { at }
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function whatsappChanges(payload) {
|
|
97
|
+
const changes = [];
|
|
98
|
+
const contacts = [];
|
|
99
|
+
let statuses = false;
|
|
100
|
+
for (const entry of list(record(payload)?.entry)) for (const item of list(record(entry)?.changes)) {
|
|
101
|
+
const field = record(item)?.field;
|
|
102
|
+
const value = record(record(item)?.value);
|
|
103
|
+
const phoneNumberId = text(record(value?.metadata)?.phone_number_id);
|
|
104
|
+
if (value === void 0 || phoneNumberId === void 0) continue;
|
|
105
|
+
const chat = (person) => `whatsapp:${phoneNumberId}:${person}`;
|
|
106
|
+
if (field === "messages") {
|
|
107
|
+
for (const status of list(value.statuses).map(record)) {
|
|
108
|
+
const target = text(status?.id);
|
|
109
|
+
const person = text(status?.recipient_id) ?? text(status?.recipient_user_id);
|
|
110
|
+
const state = status?.status;
|
|
111
|
+
if (target === void 0 || person === void 0 || state !== "sent" && state !== "delivered" && state !== "read" && state !== "failed") continue;
|
|
112
|
+
const failure = state === "failed" ? failureOf(status?.errors) : void 0;
|
|
113
|
+
statuses = true;
|
|
114
|
+
changes.push({
|
|
115
|
+
chatId: chat(person),
|
|
116
|
+
target,
|
|
117
|
+
change: "status",
|
|
118
|
+
status: state,
|
|
119
|
+
...failure === void 0 ? {} : { failure }
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
for (const message of list(value.messages).map(record)) {
|
|
123
|
+
const person = text(message?.from) ?? text(message?.from_user_id);
|
|
124
|
+
const id = text(message?.id);
|
|
125
|
+
if (message === void 0 || person === void 0 || id === void 0) continue;
|
|
126
|
+
if (message.type === "reaction") {
|
|
127
|
+
const reaction = record(message.reaction);
|
|
128
|
+
const target = text(reaction?.message_id);
|
|
129
|
+
if (target !== void 0) changes.push({
|
|
130
|
+
chatId: chat(person),
|
|
131
|
+
target,
|
|
132
|
+
change: "reaction",
|
|
133
|
+
senderId: person,
|
|
134
|
+
emoji: typeof reaction?.emoji === "string" ? reaction.emoji : ""
|
|
135
|
+
});
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const revised = revision(chat(person), message);
|
|
139
|
+
if (revised !== void 0) {
|
|
140
|
+
changes.push(revised);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (message.type === "contacts") {
|
|
144
|
+
const parts = whatsappParts(message);
|
|
145
|
+
const replyTo = text(record(message.context)?.id);
|
|
146
|
+
const at = time(message.timestamp);
|
|
147
|
+
if (parts.length > 0) contacts.push({
|
|
148
|
+
chatId: chat(person),
|
|
149
|
+
id,
|
|
150
|
+
from: person,
|
|
151
|
+
parts,
|
|
152
|
+
...replyTo === void 0 ? {} : { replyTo },
|
|
153
|
+
...at === void 0 ? {} : { at }
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (field === "smb_message_echoes") for (const echo of list(value.message_echoes).map(record)) {
|
|
159
|
+
const person = text(echo?.to) ?? text(echo?.to_user_id);
|
|
160
|
+
const revised = echo === void 0 || person === void 0 ? void 0 : revision(chat(person), echo);
|
|
161
|
+
if (revised !== void 0) changes.push(revised);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
changes,
|
|
166
|
+
contacts,
|
|
167
|
+
statuses
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
async function recordWhatsAppChanges(archive, read, wait = (ms) => new Promise((done) => setTimeout(done, ms))) {
|
|
171
|
+
const channel = currentChannel("whatsapp");
|
|
172
|
+
let recorded = read.statuses;
|
|
173
|
+
for (const change of read.changes) {
|
|
174
|
+
const outcome = await applyChatChange(archive, {
|
|
175
|
+
...change,
|
|
176
|
+
channel
|
|
177
|
+
});
|
|
178
|
+
if (outcome === "dropped") recorded = false;
|
|
179
|
+
else if (outcome === "unchanged" && change.change === "status" && change.status === "failed" && !await failureKept(archive, {
|
|
180
|
+
...change,
|
|
181
|
+
channel
|
|
182
|
+
}, wait)) recorded = false;
|
|
183
|
+
}
|
|
184
|
+
for (const card of read.contacts) await recordUnreadMessage(archive, {
|
|
185
|
+
provider: channel,
|
|
186
|
+
chatId: card.chatId,
|
|
187
|
+
eventId: currentKey("whatsapp", `whatsapp:contacts:${card.id}`),
|
|
188
|
+
senderId: card.from,
|
|
189
|
+
messageId: card.id,
|
|
190
|
+
text: "",
|
|
191
|
+
parts: card.parts,
|
|
192
|
+
...card.replyTo === void 0 ? {} : { replyTo: card.replyTo },
|
|
193
|
+
...card.at === void 0 ? {} : { at: card.at }
|
|
194
|
+
}, "no_text");
|
|
195
|
+
return recorded;
|
|
196
|
+
}
|
|
197
|
+
async function failureKept(archive, change, wait) {
|
|
198
|
+
const store = await storeOf(archive);
|
|
199
|
+
const held = async () => store !== void 0 && (await store.read({
|
|
200
|
+
channel: change.channel,
|
|
201
|
+
chatId: change.chatId.slice(0, 256),
|
|
202
|
+
messageId: change.target.slice(0, 512),
|
|
203
|
+
limit: 1
|
|
204
|
+
})).messages.length > 0;
|
|
205
|
+
for (const ms of FAILURE_RETRY_MS) {
|
|
206
|
+
if (await held()) return true;
|
|
207
|
+
await wait(ms);
|
|
208
|
+
if (await applyChatChange(archive, change) === "applied") return true;
|
|
209
|
+
}
|
|
210
|
+
return held();
|
|
211
|
+
}
|
|
212
|
+
export { FAILURE_RETRY_MS, recordWhatsAppChanges, whatsappChanges, whatsappParts };
|
|
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
|
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
7
|
import { channelKey } from "../channel-scope.mjs";
|
|
8
|
-
import { a as chatEvent, t as AGENT_SENDER } from "../../../_chunks/chat-archive-
|
|
8
|
+
import { a as chatEvent, t as AGENT_SENDER } from "../../../_chunks/chat-archive-CDk-FPLX.mjs";
|
|
9
9
|
import { stampedChat } from "../chat-recorder.mjs";
|
|
10
10
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
11
|
const collected = new AsyncLocalStorage();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The header the agent's WhatsApp channel answers a relayed delivery with, `recorded`, once it
|
|
3
|
+
* kept the delivery's statuses in the workspace chat store: a failure Meta reports for a message is
|
|
4
|
+
* then the message's own, and the relay records it nowhere else. An agent that keeps its chats in
|
|
5
|
+
* Cloud's archive, or one released before it read statuses, answers none.
|
|
6
|
+
*/
|
|
7
|
+
export declare const STATUSES_HEADER = "x-segmentstream-message-statuses";
|
|
8
|
+
/** The value of {@link STATUSES_HEADER}. */
|
|
9
|
+
export declare const STATUSES_RECORDED = "recorded";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { fileURLToPath as __eveFileURLToPath } from "node:url";
|
|
2
|
+
import { dirname as __eveDirname } from "node:path";
|
|
3
|
+
import { createRequire as __eveCreateRequire } from "node:module";
|
|
4
|
+
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
|
+
__eveDirname(__filename);
|
|
6
|
+
__eveCreateRequire(import.meta.url);
|
|
7
|
+
const STATUSES_HEADER = "x-segmentstream-message-statuses";
|
|
8
|
+
const STATUSES_RECORDED = "recorded";
|
|
9
|
+
export { STATUSES_HEADER, STATUSES_RECORDED };
|
|
@@ -3,6 +3,7 @@ import type { SessionAuthContext } from "eve/context";
|
|
|
3
3
|
import { type SegmentStreamAgentConfigInput } from "../../config.js";
|
|
4
4
|
import { type AgentAttachments } from "../attachments.js";
|
|
5
5
|
import { type ChatArchive } from "../chat-archive.js";
|
|
6
|
+
import { type ChatPart } from "../chat-messages.js";
|
|
6
7
|
import { type Environment } from "../environment.js";
|
|
7
8
|
import { type AgentIdentities, type PairedMember } from "../identities.js";
|
|
8
9
|
import { type CapabilityLookup } from "../inbound-media/plan.js";
|
|
@@ -15,6 +16,7 @@ import { type RuntimeToken } from "../runtime-token.js";
|
|
|
15
16
|
import { type ChannelConnection } from "./connection.js";
|
|
16
17
|
import { type ChannelChecks } from "./secrets.js";
|
|
17
18
|
export type { ChannelChecks } from "./secrets.js";
|
|
19
|
+
export type { ChatPart } from "../chat-messages.js";
|
|
18
20
|
/**
|
|
19
21
|
* A channel the workspace defines in its own code (`docs/agent.md`, "Workspace channels"), for any
|
|
20
22
|
* provider with an API: a CRM inbox, a marketplace's buyer chat, an in-house messenger. The
|
|
@@ -68,6 +70,10 @@ export interface ChannelMessage {
|
|
|
68
70
|
readonly chatId: string;
|
|
69
71
|
/** Who wrote it: the person, or for an `outbound` message the workspace's account. */
|
|
70
72
|
readonly sender: ChannelSender;
|
|
73
|
+
/**
|
|
74
|
+
* What the agent reads. It may be empty when the message carries files or parts: a message with
|
|
75
|
+
* neither text nor files starts no turn.
|
|
76
|
+
*/
|
|
71
77
|
readonly text: string;
|
|
72
78
|
/** Files the message carries; read only when `limits.files` is on. */
|
|
73
79
|
readonly files?: ReadonlyArray<ChannelFile>;
|
|
@@ -82,6 +88,59 @@ export interface ChannelMessage {
|
|
|
82
88
|
/** Who wrote an `outbound` message: `human` (the default), or `bot` for another program. */
|
|
83
89
|
readonly by?: "human" | "bot";
|
|
84
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* A message one provider event holds, with what the provider says of it beside its text, which the
|
|
93
|
+
* chat keeps: the message it quotes, when it was written, and its parts, such as a location or a
|
|
94
|
+
* contact card. The agent reads its text and files; its parts are for the chat, so a message whose
|
|
95
|
+
* only content is a part starts no turn, and the inbox shows it.
|
|
96
|
+
*/
|
|
97
|
+
export type ChannelMessageEvent = ChannelMessage & {
|
|
98
|
+
readonly type?: "message";
|
|
99
|
+
/** The provider's id of the message it quotes. */
|
|
100
|
+
readonly replyTo?: string;
|
|
101
|
+
/** When it was written, ISO 8601; by default when it arrived. */
|
|
102
|
+
readonly at?: string;
|
|
103
|
+
readonly parts?: ReadonlyArray<ChatPart>;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* What one provider event holds, as {@link ChannelDefinition.parse} reads it: messages, and
|
|
107
|
+
* changes to messages of the person's chat, each found by the provider's id of its message, the
|
|
108
|
+
* `target`. No change starts a turn: the chat shows it, and the agent reads an edited or deleted
|
|
109
|
+
* message again, marked, in its next turn. A change to a message the chat does not hold is
|
|
110
|
+
* dropped.
|
|
111
|
+
*
|
|
112
|
+
* - `reaction`: who reacted to a message, with which emoji; an empty emoji removes theirs.
|
|
113
|
+
* - `edit`: the message's new text.
|
|
114
|
+
* - `deletion`: the message is gone; the chat keeps its place, without its content.
|
|
115
|
+
* - `status`: what became of a message the workspace's side sent, the agent's replies among them:
|
|
116
|
+
* `delivered`, `read` (which implies delivered), or `failed`, with the provider's `reason` as a
|
|
117
|
+
* code. A status never moves a message backwards, except to `failed`.
|
|
118
|
+
*/
|
|
119
|
+
export type ChannelEvent = ChannelMessageEvent | {
|
|
120
|
+
readonly type: "reaction";
|
|
121
|
+
readonly chatId: string;
|
|
122
|
+
readonly sender: ChannelSender;
|
|
123
|
+
readonly target: string;
|
|
124
|
+
readonly emoji: string;
|
|
125
|
+
} | {
|
|
126
|
+
readonly type: "edit";
|
|
127
|
+
readonly chatId: string;
|
|
128
|
+
readonly target: string;
|
|
129
|
+
readonly text: string;
|
|
130
|
+
readonly at?: string;
|
|
131
|
+
} | {
|
|
132
|
+
readonly type: "deletion";
|
|
133
|
+
readonly chatId: string;
|
|
134
|
+
readonly target: string;
|
|
135
|
+
readonly at?: string;
|
|
136
|
+
} | {
|
|
137
|
+
readonly type: "status";
|
|
138
|
+
readonly chatId: string;
|
|
139
|
+
readonly target: string;
|
|
140
|
+
readonly status: "delivered" | "read" | "failed";
|
|
141
|
+
/** The provider's refusal of a failed message, as a code such as `recipient_unreachable`. */
|
|
142
|
+
readonly reason?: string;
|
|
143
|
+
};
|
|
85
144
|
/** A file the agent sends, its bytes read. */
|
|
86
145
|
export interface ChannelReplyFile {
|
|
87
146
|
readonly filename: string;
|
|
@@ -109,7 +168,8 @@ export interface ChannelContext {
|
|
|
109
168
|
export interface ChannelRead {
|
|
110
169
|
/**
|
|
111
170
|
* The provider's events, each read as {@link ChannelDefinition.parse} reads a webhook's, holding
|
|
112
|
-
* at most 50 messages together: a larger read is refused whole and
|
|
171
|
+
* at most 50 messages together, whatever changes beside them: a larger read is refused whole and
|
|
172
|
+
* its cursor kept.
|
|
113
173
|
*/
|
|
114
174
|
readonly events: ReadonlyArray<unknown>;
|
|
115
175
|
/** Where the next read starts; the platform keeps it, at most 16,384 characters. */
|
|
@@ -148,11 +208,11 @@ export interface ChannelDefinition {
|
|
|
148
208
|
};
|
|
149
209
|
};
|
|
150
210
|
/**
|
|
151
|
-
* The messages one provider event holds: a webhook's body,
|
|
152
|
-
*
|
|
153
|
-
*
|
|
211
|
+
* The messages and changes one provider event holds ({@link ChannelEvent}): a webhook's body,
|
|
212
|
+
* parsed as JSON when it is JSON, or an event a poll read. What the workspace's side sent is an
|
|
213
|
+
* `outbound` message; a delivery receipt is a `status`. An event that holds nothing holds none.
|
|
154
214
|
*/
|
|
155
|
-
parse(event: unknown, context: ChannelContext): ReadonlyArray<
|
|
215
|
+
parse(event: unknown, context: ChannelContext): ReadonlyArray<ChannelEvent> | Promise<ReadonlyArray<ChannelEvent>>;
|
|
156
216
|
/** Sends one message; answers the provider's id of it, when it gives one. */
|
|
157
217
|
send(reply: ChannelReply, context: ChannelContext): Promise<{
|
|
158
218
|
readonly id?: string;
|
|
@@ -192,8 +252,9 @@ export interface WorkspaceChannelOptions extends ChannelDefinition {
|
|
|
192
252
|
readonly log?: (message: string, detail: unknown) => void;
|
|
193
253
|
}
|
|
194
254
|
/**
|
|
195
|
-
* The most messages one webhook delivery or one read may hold
|
|
196
|
-
* before any of it starts a turn: its cursor stays, and the provider's
|
|
255
|
+
* The most messages one webhook delivery or one read may hold, whatever changes beside them. A
|
|
256
|
+
* larger one is refused whole, before any of it starts a turn: its cursor stays, and the provider's
|
|
257
|
+
* delivery is answered 413.
|
|
197
258
|
*/
|
|
198
259
|
export declare const MAXIMUM_MESSAGES = 50;
|
|
199
260
|
/**
|