@wednesdayai/whatsapp 0.4.10

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/dist/index.js ADDED
@@ -0,0 +1,3678 @@
1
+ import { C as listWhatsAppAccountIds, E as resolveWhatsAppAuthDir, S as stopActiveWebListener, T as resolveWhatsAppAccount$1, _ as webAuthExists, a as waitForWebLogin, b as getActiveWebListener, c as formatError, d as getBaileys, f as getWebAuthAgeMs, g as waitForWebCredsSaveQueue, h as readWebSelfId, i as tryCanonicalWhatsAppAuthDir, l as getStatusCode, m as logoutWeb, o as closeWaSocket, p as logWebSelfId, r as startWebLoginWithQr, s as createWaSocket, t as closeActiveWebLoginsForAuthDir, u as waitForWaConnection, v as getWhatsAppRuntime, w as resolveDefaultWhatsAppAccountId, x as setActiveWebListener, y as setWhatsAppRuntime } from "./login-qr-B5goEXCP.js";
2
+ import { DEFAULT_ACCOUNT_ID, DEFAULT_GROUP_HISTORY_LIMIT, DEFAULT_MAIN_KEY, ToolAuthorizationError, Type, WhatsAppConfigSchema, applyAccountNameToChannelSection, buildAgentMainSessionKey, buildAgentSessionKey, buildChannelConfigSchema, buildGroupHistoryKey, buildHistoryContextFromEntries, buildMentionRegexes, buildPairingReply, chunkMarkdownTextWithMode, computeBackoff, convertMarkdownTables, createActionGate, createDedupeCache, createInboundDebouncer, createReplyPrefixOptions, createSubsystemLogger, danger, defaultRuntime, dispatchReplyWithBufferedBlockDispatcher, emptyPluginConfigSchema, enqueueSystemEvent, escapeRegExp, finalizeInboundContext, formatCliCommand, formatDocsLink, formatDurationPrecise, formatInboundEnvelope, formatLocationText, formatPairingApproveHint, getAgentScopedMediaLocalRoots, getChildLogger, getReplyFromConfig, hasControlCommand, info, isSelfChatMode, jidToE164, jsonResult, loadConfig, loadSessionStore, loadWebMedia, logInfo, logVerbose, markdownToWhatsApp, mergeWhatsAppConfig, migrateBaseNameToDefaultAccount, missingTargetError, normalizeAccountId, normalizeAgentId, normalizeAllowFromEntries, normalizeE164, normalizeGroupActivation, normalizeMentionText, parseActivationCommand, pathExists, readChannelAllowFromStoreSync, readReactionParams, readStoreAllowFromForDmPolicy, readStringParam, recordChannelActivity, recordPendingHistoryEntryIfEnabled, recordSessionMetaFromInbound, registerUnhandledRejectionHandler, resolveAccountIdForConfigure, resolveAgentRoute, resolveAllowlistProviderRuntimeGroupPolicy, resolveChannelGroupPolicy, resolveChannelGroupRequireMention, resolveChunkMode, resolveChunkNewlinePacking, resolveDefaultGroupPolicy, resolveDmGroupAccessWithCommandGate, resolveDmGroupAccessWithLists, resolveGroupSessionKey, resolveIdentityNamePrefix, resolveInboundDebounceMs, resolveInboundSessionEnvelopeContext, resolveJidToE164, resolveMarkdownTableMode, resolveMentionGating, resolveMessagePrefix, resolveOnboardingAccountId, resolveOpenProviderRuntimeGroupPolicy, resolvePinnedMainDmOwnerFromAllowlist, resolveStorePath, resolveTextChunkLimit, resolveWhatsAppAccount, resolveWhatsAppGroupRequireMention, resolveWhatsAppGroupToolPolicy, saveMediaBuffer, shouldAckReactionForWhatsApp, shouldComputeCommandAuthorized, shouldLogVerbose, sleep, sleepWithAbort, splitOnboardingEntries, success, toLocationContext, toWhatsappJid, transcribeFirstAudio, updateLastRoute, upsertChannelPairingRequest, waitForever, warnMissingProviderGroupPolicyFallbackOnce } from "openclaw/plugin-sdk";
3
+ import path from "node:path";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { escapeRegExp as escapeRegExp$1 } from "openclaw/plugin-sdk/escape-regexp";
6
+
7
+ //#region src/outbound.ts
8
+ function redactIdentifier(value, len = 12) {
9
+ const trimmed = value?.trim();
10
+ if (!trimmed) return "-";
11
+ return `sha256:${createHash("sha256").update(trimmed).digest("hex").slice(0, len)}`;
12
+ }
13
+ const FENCE_PLACEHOLDER = "\0FENCE";
14
+ const INLINE_CODE_PLACEHOLDER = "\0CODE";
15
+ function markdownToWhatsApp$1(text) {
16
+ if (!text) return text;
17
+ const fences = [];
18
+ let result = text.replace(/```[\s\S]*?```/g, (match) => {
19
+ fences.push(match);
20
+ return `${FENCE_PLACEHOLDER}${fences.length - 1}`;
21
+ });
22
+ const inlineCodes = [];
23
+ result = result.replace(/`[^`\n]+`/g, (match) => {
24
+ inlineCodes.push(match);
25
+ return `${INLINE_CODE_PLACEHOLDER}${inlineCodes.length - 1}`;
26
+ });
27
+ result = result.replace(/\*\*(.+?)\*\*/g, "*$1*");
28
+ result = result.replace(/__(.+?)__/g, "*$1*");
29
+ result = result.replace(/~~(.+?)~~/g, "~$1~");
30
+ result = result.replace(new RegExp(`${escapeRegExp(INLINE_CODE_PLACEHOLDER)}(\\d+)`, "g"), (_, idx) => inlineCodes[Number(idx)] ?? "");
31
+ return result.replace(new RegExp(`${escapeRegExp(FENCE_PLACEHOLDER)}(\\d+)`, "g"), (_, idx) => fences[Number(idx)] ?? "");
32
+ }
33
+ function toWhatsappJid$1(number) {
34
+ const withoutPrefix = number.replace(/^whatsapp:/, "").trim();
35
+ if (withoutPrefix.includes("@")) return withoutPrefix;
36
+ return `${normalizeE164(withoutPrefix).replace(/\D/g, "")}@s.whatsapp.net`;
37
+ }
38
+ function normalizePollInput(input, options = {}) {
39
+ const question = input.question.trim();
40
+ if (!question) throw new Error("Poll question is required");
41
+ const cleaned = input.options.map((option) => option.trim()).filter(Boolean);
42
+ if (cleaned.length < 2) throw new Error("Poll requires at least 2 options");
43
+ if (options.maxOptions !== void 0 && cleaned.length > options.maxOptions) throw new Error(`Poll supports at most ${options.maxOptions} options`);
44
+ const maxSelections = typeof input.maxSelections === "number" && Number.isFinite(input.maxSelections) ? Math.floor(input.maxSelections) : 1;
45
+ if (maxSelections < 1) throw new Error("maxSelections must be at least 1");
46
+ if (maxSelections > cleaned.length) throw new Error("maxSelections cannot exceed option count");
47
+ const durationSeconds = typeof input.durationSeconds === "number" && Number.isFinite(input.durationSeconds) ? Math.floor(input.durationSeconds) : void 0;
48
+ if (durationSeconds !== void 0 && durationSeconds < 1) throw new Error("durationSeconds must be at least 1");
49
+ const durationHours = typeof input.durationHours === "number" && Number.isFinite(input.durationHours) ? Math.floor(input.durationHours) : void 0;
50
+ if (durationHours !== void 0 && durationHours < 1) throw new Error("durationHours must be at least 1");
51
+ if (durationSeconds !== void 0 && durationHours !== void 0) throw new Error("durationSeconds and durationHours are mutually exclusive");
52
+ return {
53
+ question,
54
+ options: cleaned,
55
+ maxSelections,
56
+ durationSeconds,
57
+ durationHours
58
+ };
59
+ }
60
+ function resolveWebAccountId(accountId) {
61
+ return (accountId ?? "").trim() || DEFAULT_ACCOUNT_ID;
62
+ }
63
+ function requireActiveWebListener(accountId) {
64
+ const id = resolveWebAccountId(accountId);
65
+ const listener = getActiveWebListener(id);
66
+ if (!listener) throw new Error(`No active WhatsApp Web listener (account: ${id}). Start the gateway, then link WhatsApp with: ${formatCliCommand(`openclaw channels login --channel whatsapp --account ${id}`)}.`);
67
+ return {
68
+ accountId: id,
69
+ listener
70
+ };
71
+ }
72
+ async function sendMessageWhatsApp(to, body, options) {
73
+ let text = body;
74
+ const correlationId = randomUUID();
75
+ const startedAt = Date.now();
76
+ const { listener: active, accountId: resolvedAccountId } = requireActiveWebListener(options.accountId);
77
+ const cfg = getWhatsAppRuntime().config.loadConfig();
78
+ const tableMode = getWhatsAppRuntime().channel.text.resolveMarkdownTableMode({
79
+ cfg,
80
+ channel: "whatsapp",
81
+ accountId: resolvedAccountId ?? options.accountId
82
+ });
83
+ text = getWhatsAppRuntime().channel.text.convertMarkdownTables(text ?? "", tableMode);
84
+ text = markdownToWhatsApp$1(text);
85
+ const redactedTo = redactIdentifier(to);
86
+ const logger = getChildLogger({
87
+ module: "whatsapp-outbound",
88
+ correlationId,
89
+ to: redactedTo
90
+ });
91
+ try {
92
+ const jid = toWhatsappJid$1(to);
93
+ const redactedJid = redactIdentifier(jid);
94
+ let mediaBuffer;
95
+ let mediaType;
96
+ let documentFileName;
97
+ if (options.mediaUrl) {
98
+ const media = await loadWebMedia(options.mediaUrl, { localRoots: options.mediaLocalRoots });
99
+ const caption = text || void 0;
100
+ mediaBuffer = media.buffer;
101
+ mediaType = media.contentType;
102
+ if (media.kind === "audio") mediaType = media.contentType === "audio/ogg" ? "audio/ogg; codecs=opus" : media.contentType ?? "application/octet-stream";
103
+ else if (media.kind === "video" || media.kind === "image") text = caption ?? "";
104
+ else {
105
+ text = caption ?? "";
106
+ documentFileName = media.fileName;
107
+ }
108
+ }
109
+ logger.info({
110
+ jid: redactedJid,
111
+ hasMedia: Boolean(options.mediaUrl)
112
+ }, "sending message");
113
+ active.sendComposingTo(to).catch((err) => {
114
+ logger.warn({
115
+ err: String(err),
116
+ jid: redactedJid
117
+ }, "failed to send composing presence");
118
+ });
119
+ const accountId = Boolean(options.accountId?.trim()) ? resolvedAccountId : void 0;
120
+ const sendOptions = options.gifPlayback || accountId || documentFileName ? {
121
+ ...options.gifPlayback ? { gifPlayback: true } : {},
122
+ ...documentFileName ? { fileName: documentFileName } : {},
123
+ accountId
124
+ } : void 0;
125
+ const messageId = (sendOptions ? await active.sendMessage(to, text, mediaBuffer, mediaType, sendOptions) : await active.sendMessage(to, text, mediaBuffer, mediaType))?.messageId ?? "unknown";
126
+ logger.info({
127
+ jid: redactedJid,
128
+ messageId,
129
+ durationMs: Date.now() - startedAt
130
+ }, "sent message");
131
+ return {
132
+ messageId,
133
+ toJid: jid
134
+ };
135
+ } catch (err) {
136
+ logger.error({
137
+ err: String(err),
138
+ to: redactedTo,
139
+ hasMedia: Boolean(options.mediaUrl)
140
+ }, "failed to send via WhatsApp session");
141
+ throw err;
142
+ }
143
+ }
144
+ async function sendReactionWhatsApp(chatJid, messageId, emoji, options) {
145
+ const correlationId = randomUUID();
146
+ const { listener: active } = requireActiveWebListener(options.accountId);
147
+ const redactedChatJid = redactIdentifier(chatJid);
148
+ const logger = getChildLogger({
149
+ module: "whatsapp-outbound",
150
+ correlationId,
151
+ chatJid: redactedChatJid,
152
+ messageId
153
+ });
154
+ try {
155
+ const jid = toWhatsappJid$1(chatJid);
156
+ logger.info({
157
+ chatJid: redactIdentifier(jid),
158
+ messageId,
159
+ emoji
160
+ }, "sending reaction");
161
+ await active.sendReaction(chatJid, messageId, emoji, options.fromMe ?? false, options.participant);
162
+ logger.info({
163
+ chatJid: redactIdentifier(jid),
164
+ messageId,
165
+ emoji
166
+ }, "sent reaction");
167
+ } catch (err) {
168
+ logger.error({
169
+ err: String(err),
170
+ chatJid: redactedChatJid,
171
+ messageId,
172
+ emoji
173
+ }, "failed to send reaction via WhatsApp session");
174
+ throw err;
175
+ }
176
+ }
177
+ async function sendPollWhatsApp(to, poll, options) {
178
+ const correlationId = randomUUID();
179
+ const startedAt = Date.now();
180
+ const { listener: active } = requireActiveWebListener(options.accountId);
181
+ const redactedTo = redactIdentifier(to);
182
+ const logger = getChildLogger({
183
+ module: "whatsapp-outbound",
184
+ correlationId,
185
+ to: redactedTo
186
+ });
187
+ try {
188
+ const jid = toWhatsappJid$1(to);
189
+ const normalized = normalizePollInput(poll, { maxOptions: 12 });
190
+ logger.info({
191
+ jid: redactIdentifier(jid),
192
+ optionCount: normalized.options.length,
193
+ maxSelections: normalized.maxSelections
194
+ }, "sending poll");
195
+ const messageId = (await active.sendPoll(to, normalized))?.messageId ?? "unknown";
196
+ logger.info({
197
+ jid: redactIdentifier(jid),
198
+ messageId,
199
+ durationMs: Date.now() - startedAt
200
+ }, "sent poll");
201
+ return {
202
+ messageId,
203
+ toJid: jid
204
+ };
205
+ } catch (err) {
206
+ logger.error({
207
+ err: String(err),
208
+ to: redactedTo
209
+ }, "failed to send poll via WhatsApp session");
210
+ throw err;
211
+ }
212
+ }
213
+
214
+ //#endregion
215
+ //#region src/normalize.ts
216
+ const WHATSAPP_USER_JID_RE = /^(\d+)(?::\d+)?@s\.whatsapp\.net$/i;
217
+ const WHATSAPP_LID_RE = /^(\d+)@lid$/i;
218
+ function stripWhatsAppTargetPrefixes(value) {
219
+ let candidate = value.trim();
220
+ for (;;) {
221
+ const before = candidate;
222
+ candidate = candidate.replace(/^whatsapp:/i, "").trim();
223
+ if (candidate === before) return candidate;
224
+ }
225
+ }
226
+ function isWhatsAppGroupJid(value) {
227
+ const candidate = stripWhatsAppTargetPrefixes(value);
228
+ if (!candidate.toLowerCase().endsWith("@g.us")) return false;
229
+ const localPart = candidate.slice(0, candidate.length - 5);
230
+ if (!localPart || localPart.includes("@")) return false;
231
+ return /^(?=.*\d)[0-9a-z]+(?:-[0-9a-z]+)*$/i.test(localPart);
232
+ }
233
+ function isWhatsAppUserTarget(value) {
234
+ const candidate = stripWhatsAppTargetPrefixes(value);
235
+ return WHATSAPP_USER_JID_RE.test(candidate) || WHATSAPP_LID_RE.test(candidate);
236
+ }
237
+ function extractUserJidPhone(jid) {
238
+ const userMatch = jid.match(WHATSAPP_USER_JID_RE);
239
+ if (userMatch) return userMatch[1];
240
+ const lidMatch = jid.match(WHATSAPP_LID_RE);
241
+ if (lidMatch) return lidMatch[1];
242
+ return null;
243
+ }
244
+ function normalizeWhatsAppTarget(value) {
245
+ const candidate = stripWhatsAppTargetPrefixes(value);
246
+ if (!candidate) return null;
247
+ if (isWhatsAppGroupJid(candidate)) return `${candidate.slice(0, candidate.length - 5)}@g.us`;
248
+ if (isWhatsAppUserTarget(candidate)) {
249
+ const phone = extractUserJidPhone(candidate);
250
+ if (!phone) return null;
251
+ const normalized = normalizeE164(phone);
252
+ return normalized.length > 1 ? normalized : null;
253
+ }
254
+ if (candidate.includes("@")) return null;
255
+ const normalized = normalizeE164(candidate);
256
+ return normalized.length > 1 ? normalized : null;
257
+ }
258
+
259
+ //#endregion
260
+ //#region src/resolve-outbound-target.ts
261
+ function resolveWhatsAppOutboundTarget(params) {
262
+ const trimmed = params.to?.trim() ?? "";
263
+ const allowListRaw = (params.allowFrom ?? []).map((entry) => String(entry).trim()).filter(Boolean);
264
+ const hasWildcard = allowListRaw.includes("*");
265
+ const allowList = allowListRaw.filter((entry) => entry !== "*").map((entry) => normalizeWhatsAppTarget(entry)).filter((entry) => Boolean(entry));
266
+ if (trimmed) {
267
+ const normalizedTo = normalizeWhatsAppTarget(trimmed);
268
+ if (!normalizedTo) return {
269
+ ok: false,
270
+ error: missingTargetError("WhatsApp", "<E.164|group JID>")
271
+ };
272
+ if (isWhatsAppGroupJid(normalizedTo)) return {
273
+ ok: true,
274
+ to: normalizedTo
275
+ };
276
+ if (hasWildcard || allowList.length === 0) return {
277
+ ok: true,
278
+ to: normalizedTo
279
+ };
280
+ if (allowList.includes(normalizedTo)) return {
281
+ ok: true,
282
+ to: normalizedTo
283
+ };
284
+ return {
285
+ ok: false,
286
+ error: missingTargetError("WhatsApp", "<E.164|group JID>")
287
+ };
288
+ }
289
+ return {
290
+ ok: false,
291
+ error: missingTargetError("WhatsApp", "<E.164|group JID>")
292
+ };
293
+ }
294
+
295
+ //#endregion
296
+ //#region src/actions.ts
297
+ function resolveAuthorizedWhatsAppOutboundTarget(params) {
298
+ const account = resolveWhatsAppAccount$1({
299
+ cfg: params.cfg,
300
+ accountId: params.accountId
301
+ });
302
+ const resolution = resolveWhatsAppOutboundTarget({
303
+ to: params.chatJid,
304
+ allowFrom: account.allowFrom ?? [],
305
+ mode: "implicit"
306
+ });
307
+ if (!resolution.ok) throw new ToolAuthorizationError(`WhatsApp ${params.actionLabel} blocked: chatJid "${params.chatJid}" is not in the configured allowFrom list for account "${account.accountId}".`);
308
+ return {
309
+ to: resolution.to,
310
+ accountId: account.accountId
311
+ };
312
+ }
313
+ async function handleWhatsAppAction(params, cfg) {
314
+ const action = readStringParam(params, "action", { required: true });
315
+ const isActionEnabled = createActionGate(cfg.channels?.whatsapp?.actions);
316
+ if (action === "react") {
317
+ if (!isActionEnabled("reactions")) throw new Error("WhatsApp reactions are disabled.");
318
+ const chatJid = readStringParam(params, "chatJid", { required: true });
319
+ const messageId = readStringParam(params, "messageId", { required: true });
320
+ const { emoji, remove, isEmpty } = readReactionParams(params, { removeErrorMessage: "Emoji is required to remove a WhatsApp reaction." });
321
+ const participant = readStringParam(params, "participant");
322
+ const accountId = readStringParam(params, "accountId");
323
+ const fromMeRaw = params.fromMe;
324
+ const fromMe = typeof fromMeRaw === "boolean" ? fromMeRaw : void 0;
325
+ const resolved = resolveAuthorizedWhatsAppOutboundTarget({
326
+ cfg,
327
+ chatJid,
328
+ accountId,
329
+ actionLabel: "reaction"
330
+ });
331
+ const resolvedEmoji = remove ? "" : emoji;
332
+ await sendReactionWhatsApp(resolved.to, messageId, resolvedEmoji, {
333
+ verbose: false,
334
+ fromMe,
335
+ participant: participant ?? void 0,
336
+ accountId: resolved.accountId
337
+ });
338
+ if (!remove && !isEmpty) return jsonResult({
339
+ ok: true,
340
+ added: emoji
341
+ });
342
+ return jsonResult({
343
+ ok: true,
344
+ removed: true
345
+ });
346
+ }
347
+ throw new Error(`Unsupported WhatsApp action: ${action}`);
348
+ }
349
+
350
+ //#endregion
351
+ //#region src/agent-tools-login.ts
352
+ function createWhatsAppLoginTool() {
353
+ return {
354
+ label: "WhatsApp Login",
355
+ name: "whatsapp_login",
356
+ ownerOnly: true,
357
+ description: "Generate a WhatsApp QR code for linking, or wait for the scan to complete.",
358
+ parameters: Type.Object({
359
+ action: Type.Unsafe({
360
+ type: "string",
361
+ enum: ["start", "wait"]
362
+ }),
363
+ timeoutMs: Type.Optional(Type.Number()),
364
+ force: Type.Optional(Type.Boolean())
365
+ }),
366
+ execute: async (_toolCallId, args) => {
367
+ const { startWebLoginWithQr, waitForWebLogin } = await import("./login-qr-B5goEXCP.js").then((n) => n.n);
368
+ if ((args?.action ?? "start") === "wait") {
369
+ const result = await waitForWebLogin({ timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : void 0 });
370
+ return {
371
+ content: [{
372
+ type: "text",
373
+ text: result.message
374
+ }],
375
+ details: { connected: result.connected }
376
+ };
377
+ }
378
+ const result = await startWebLoginWithQr({
379
+ timeoutMs: typeof args.timeoutMs === "number" ? args.timeoutMs : void 0,
380
+ force: typeof args.force === "boolean" ? args.force : false
381
+ });
382
+ if (!result.qrDataUrl) return {
383
+ content: [{
384
+ type: "text",
385
+ text: result.message
386
+ }],
387
+ details: { qr: false }
388
+ };
389
+ return {
390
+ content: [{
391
+ type: "text",
392
+ text: [
393
+ result.message,
394
+ "",
395
+ "Open WhatsApp -> Linked Devices and scan:",
396
+ "",
397
+ `![whatsapp-qr](${result.qrDataUrl})`
398
+ ].join("\n")
399
+ }],
400
+ details: { qr: true }
401
+ };
402
+ }
403
+ };
404
+ }
405
+
406
+ //#endregion
407
+ //#region src/targets.ts
408
+ function trimMessagingTarget(raw) {
409
+ return raw.trim() || void 0;
410
+ }
411
+ function looksLikeHandleOrPhoneTarget(params) {
412
+ const trimmed = params.raw.trim();
413
+ if (!trimmed) return false;
414
+ if (params.prefixPattern.test(trimmed)) return true;
415
+ if (trimmed.includes("@")) return true;
416
+ return (params.phonePattern ?? /^\+?\d{3,}$/).test(trimmed);
417
+ }
418
+ function normalizeWhatsAppMessagingTarget(raw) {
419
+ const trimmed = trimMessagingTarget(raw);
420
+ if (!trimmed) return;
421
+ return normalizeWhatsAppTarget(trimmed) ?? void 0;
422
+ }
423
+ function normalizeWhatsAppAllowFromEntries(allowFrom) {
424
+ return allowFrom.map((entry) => String(entry).trim()).filter((entry) => Boolean(entry)).map((entry) => entry === "*" ? entry : normalizeWhatsAppTarget(entry)).filter((entry) => Boolean(entry));
425
+ }
426
+ function looksLikeWhatsAppTargetId(raw) {
427
+ return looksLikeHandleOrPhoneTarget({
428
+ raw,
429
+ prefixPattern: /^whatsapp:/i
430
+ });
431
+ }
432
+
433
+ //#endregion
434
+ //#region src/config.ts
435
+ function resolveWhatsAppConfigAllowFrom(params) {
436
+ return resolveWhatsAppAccount$1(params).allowFrom ?? [];
437
+ }
438
+ function formatWhatsAppConfigAllowFromEntries(allowFrom) {
439
+ return normalizeWhatsAppAllowFromEntries(allowFrom);
440
+ }
441
+ function resolveWhatsAppConfigDefaultTo(params) {
442
+ const root = params.cfg.channels?.whatsapp;
443
+ const normalized = normalizeAccountId(params.accountId);
444
+ return ((root?.accounts?.[normalized])?.defaultTo ?? root?.defaultTo)?.trim() || void 0;
445
+ }
446
+
447
+ //#endregion
448
+ //#region src/directory.ts
449
+ function resolveDirectoryQuery(query) {
450
+ return query?.trim().toLowerCase() || "";
451
+ }
452
+ function resolveDirectoryLimit(limit) {
453
+ return typeof limit === "number" && limit > 0 ? limit : void 0;
454
+ }
455
+ function applyDirectoryQueryAndLimit(ids, params) {
456
+ const q = resolveDirectoryQuery(params.query);
457
+ const limit = resolveDirectoryLimit(params.limit);
458
+ const filtered = ids.filter((id) => q ? id.toLowerCase().includes(q) : true);
459
+ return typeof limit === "number" ? filtered.slice(0, limit) : filtered;
460
+ }
461
+ function toDirectoryEntries(kind, ids) {
462
+ return ids.map((id) => ({
463
+ kind,
464
+ id
465
+ }));
466
+ }
467
+ async function listWhatsAppDirectoryPeersFromConfig(params) {
468
+ return toDirectoryEntries("user", applyDirectoryQueryAndLimit((resolveWhatsAppAccount$1({
469
+ cfg: params.cfg,
470
+ accountId: params.accountId
471
+ }).allowFrom ?? []).map((entry) => String(entry).trim()).filter((entry) => Boolean(entry) && entry !== "*").map((entry) => normalizeWhatsAppTarget(entry) ?? "").filter(Boolean).filter((id) => !isWhatsAppGroupJid(id)), params));
472
+ }
473
+ async function listWhatsAppDirectoryGroupsFromConfig(params) {
474
+ const account = resolveWhatsAppAccount$1({
475
+ cfg: params.cfg,
476
+ accountId: params.accountId
477
+ });
478
+ return toDirectoryEntries("group", applyDirectoryQueryAndLimit(Object.keys(account.groups ?? {}).map((id) => id.trim()).filter((id) => Boolean(id) && id !== "*"), params));
479
+ }
480
+
481
+ //#endregion
482
+ //#region src/loggers.ts
483
+ function makeLoggers() {
484
+ const whatsappLog = createSubsystemLogger("gateway/channels/whatsapp");
485
+ return {
486
+ whatsappLog,
487
+ whatsappInboundLog: whatsappLog.child("inbound"),
488
+ whatsappOutboundLog: whatsappLog.child("outbound"),
489
+ whatsappHeartbeatLog: whatsappLog.child("heartbeat")
490
+ };
491
+ }
492
+ let _loggers;
493
+ function getLoggers() {
494
+ _loggers ??= makeLoggers();
495
+ return _loggers;
496
+ }
497
+ const whatsappLog = new Proxy({}, { get(_t, prop) {
498
+ return Reflect.get(getLoggers().whatsappLog, prop);
499
+ } });
500
+ const whatsappInboundLog = new Proxy({}, { get(_t, prop) {
501
+ return Reflect.get(getLoggers().whatsappInboundLog, prop);
502
+ } });
503
+ const whatsappOutboundLog = new Proxy({}, { get(_t, prop) {
504
+ return Reflect.get(getLoggers().whatsappOutboundLog, prop);
505
+ } });
506
+ const whatsappHeartbeatLog = new Proxy({}, { get(_t, prop) {
507
+ return Reflect.get(getLoggers().whatsappHeartbeatLog, prop);
508
+ } });
509
+
510
+ //#endregion
511
+ //#region src/heartbeat.ts
512
+ function isWhatsAppChannel(raw) {
513
+ return (raw ?? "").trim().toLowerCase() === "whatsapp";
514
+ }
515
+ function getSessionRecipients(cfg, loadSessionStore, resolveStorePath) {
516
+ if ((cfg.session?.scope ?? "per-sender") === "global") return [];
517
+ const store = loadSessionStore(resolveStorePath(cfg.session?.store));
518
+ const isGroupKey = (key) => key.includes(":group:") || key.includes(":channel:") || key.includes("@g.us");
519
+ const isCronKey = (key) => key.startsWith("cron:");
520
+ const recipients = Object.entries(store).filter(([key]) => key !== "global" && key !== "unknown").filter(([key]) => !isGroupKey(key) && !isCronKey(key)).map(([_, entry]) => ({
521
+ to: isWhatsAppChannel(entry?.lastChannel) && entry?.lastTo ? normalizeE164(entry.lastTo) : "",
522
+ updatedAt: entry?.updatedAt ?? 0
523
+ })).filter(({ to }) => to.length > 1).toSorted((a, b) => b.updatedAt - a.updatedAt);
524
+ const seen = /* @__PURE__ */ new Set();
525
+ return recipients.filter((r) => {
526
+ if (seen.has(r.to)) return false;
527
+ seen.add(r.to);
528
+ return true;
529
+ });
530
+ }
531
+ function resolveWhatsAppHeartbeatRecipients(cfg, opts = {}, deps = {}) {
532
+ const loadSessionStore$1 = deps.loadSessionStore ?? loadSessionStore;
533
+ const resolveStorePath$1 = deps.resolveStorePath ?? resolveStorePath;
534
+ const readChannelAllowFromStoreSync$1 = deps.readChannelAllowFromStoreSync ?? readChannelAllowFromStoreSync;
535
+ if (opts.to) return {
536
+ recipients: [normalizeE164(opts.to)],
537
+ source: "flag"
538
+ };
539
+ const sessionRecipients = getSessionRecipients(cfg, loadSessionStore$1, resolveStorePath$1);
540
+ const configuredAllowFromRaw = Array.isArray(cfg.channels?.whatsapp?.allowFrom) && cfg.channels.whatsapp.allowFrom.length > 0 ? cfg.channels.whatsapp.allowFrom : [];
541
+ if (configuredAllowFromRaw.includes("*")) whatsappHeartbeatLog.warn("whatsapp heartbeat allowFrom contains wildcard '*' — wildcard is NOT supported for broadcast heartbeat delivery and will be ignored; list specific JIDs to deliver to those recipients");
542
+ const configuredAllowFrom = configuredAllowFromRaw.filter((v) => v !== "*").map(normalizeE164);
543
+ const storeAllowFrom = readChannelAllowFromStoreSync$1("whatsapp", process.env, DEFAULT_ACCOUNT_ID).map(normalizeE164);
544
+ const unique = (list) => [...new Set(list.filter(Boolean))];
545
+ const allowFrom = unique([...configuredAllowFrom, ...storeAllowFrom]);
546
+ if (opts.all) return {
547
+ recipients: unique([...sessionRecipients.map((s) => s.to), ...allowFrom]),
548
+ source: "all"
549
+ };
550
+ if (allowFrom.length > 0) {
551
+ const allowSet = new Set(allowFrom);
552
+ const authorizedSessionRecipients = sessionRecipients.map((entry) => entry.to).filter((recipient) => allowSet.has(recipient));
553
+ if (authorizedSessionRecipients.length === 1) return {
554
+ recipients: [authorizedSessionRecipients[0]],
555
+ source: "session-single"
556
+ };
557
+ if (authorizedSessionRecipients.length > 1) return {
558
+ recipients: authorizedSessionRecipients,
559
+ source: "session-ambiguous"
560
+ };
561
+ return {
562
+ recipients: allowFrom,
563
+ source: "allowFrom"
564
+ };
565
+ }
566
+ if (sessionRecipients.length === 1) return {
567
+ recipients: [sessionRecipients[0].to],
568
+ source: "session-single"
569
+ };
570
+ if (sessionRecipients.length > 1) return {
571
+ recipients: sessionRecipients.map((s) => s.to),
572
+ source: "session-ambiguous"
573
+ };
574
+ return {
575
+ recipients: allowFrom,
576
+ source: "allowFrom"
577
+ };
578
+ }
579
+
580
+ //#endregion
581
+ //#region src/login.ts
582
+ async function closeSocketWithRetry(socket) {
583
+ try {
584
+ await closeWaSocket(socket);
585
+ } catch {
586
+ await closeWaSocket(socket);
587
+ }
588
+ }
589
+ async function loginWeb(verbose, waitForConnection, runtime = defaultRuntime, accountId, cfg) {
590
+ const { DisconnectReason } = await getBaileys();
591
+ const wait = waitForConnection ?? waitForWaConnection;
592
+ const account = resolveWhatsAppAccount$1({
593
+ cfg: cfg ?? getWhatsAppRuntime().config.loadConfig(),
594
+ accountId
595
+ });
596
+ const sock = await createWaSocket(true, verbose, { authDir: account.authDir });
597
+ const clearLoggedOutSession = async (socket, cause) => {
598
+ await closeSocketWithRetry(socket);
599
+ await logoutWeb({
600
+ authDir: account.authDir,
601
+ isLegacyAuthDir: account.isLegacyAuthDir,
602
+ runtime
603
+ });
604
+ runtime.log(danger(`WhatsApp reported the session is logged out. Cleared cached web session; please rerun ${formatCliCommand("openclaw channels login")} and scan the QR again.`));
605
+ throw new Error("Session logged out; cache cleared. Re-run login.", { cause });
606
+ };
607
+ logInfo("Waiting for WhatsApp connection...", runtime);
608
+ try {
609
+ await wait(sock);
610
+ await waitForWebCredsSaveQueue(account.authDir);
611
+ runtime.log(success("Linked! Credentials saved for future sends."));
612
+ } catch (err) {
613
+ const code = getStatusCode(err);
614
+ if (code === 515) {
615
+ runtime.log(info("WhatsApp asked for a restart after pairing (code 515); creds are saved. Restarting connection once..."));
616
+ try {
617
+ await closeSocketWithRetry(sock);
618
+ } catch {}
619
+ const retry = await createWaSocket(false, verbose, { authDir: account.authDir });
620
+ try {
621
+ await wait(retry);
622
+ await waitForWebCredsSaveQueue(account.authDir);
623
+ runtime.log(success("Linked after restart; web session ready."));
624
+ return;
625
+ } catch (retryErr) {
626
+ if (getStatusCode(retryErr) === DisconnectReason.loggedOut) await clearLoggedOutSession(retry, retryErr);
627
+ throw retryErr;
628
+ } finally {
629
+ await closeSocketWithRetry(retry);
630
+ }
631
+ }
632
+ if (code === DisconnectReason.loggedOut) await clearLoggedOutSession(sock, err);
633
+ const formatted = formatError(err);
634
+ runtime.log(danger(`WhatsApp Web connection ended before fully opening. ${formatted}`));
635
+ throw new Error(formatted, { cause: err });
636
+ } finally {
637
+ await closeSocketWithRetry(sock);
638
+ }
639
+ }
640
+
641
+ //#endregion
642
+ //#region src/constants.ts
643
+ const DEFAULT_WEB_MEDIA_BYTES = 5 * 1024 * 1024;
644
+
645
+ //#endregion
646
+ //#region src/inbound/access-control.ts
647
+ let _log;
648
+ function getLog() {
649
+ _log ??= createSubsystemLogger("whatsapp/inbound/access-control");
650
+ return _log;
651
+ }
652
+ const PAIRING_REPLY_HISTORY_GRACE_MS = 3e4;
653
+ const MIN_E164_DIGITS = 7;
654
+ function isValidE164(normalized) {
655
+ if (!normalized) return false;
656
+ return normalized.replace(/\D/g, "").length >= MIN_E164_DIGITS;
657
+ }
658
+ function resolveWhatsAppRuntimeGroupPolicy(params) {
659
+ return resolveOpenProviderRuntimeGroupPolicy({
660
+ providerConfigPresent: params.providerConfigPresent,
661
+ groupPolicy: params.groupPolicy,
662
+ defaultGroupPolicy: params.defaultGroupPolicy
663
+ });
664
+ }
665
+ async function checkInboundAccessControl(params) {
666
+ const cfg = loadConfig();
667
+ const account = resolveWhatsAppAccount({
668
+ cfg,
669
+ accountId: params.accountId
670
+ });
671
+ const dmPolicy = account.dmPolicy ?? "pairing";
672
+ const configuredAllowFrom = account.allowFrom ?? [];
673
+ const storeAllowFrom = await readStoreAllowFromForDmPolicy({
674
+ provider: "whatsapp",
675
+ accountId: account.accountId,
676
+ dmPolicy
677
+ });
678
+ const defaultAllowFrom = configuredAllowFrom.length === 0 && params.selfE164 ? [params.selfE164] : [];
679
+ const dmAllowFrom = configuredAllowFrom.length > 0 ? configuredAllowFrom : defaultAllowFrom;
680
+ const groupAllowFrom = account.groupAllowFrom ?? (configuredAllowFrom.length > 0 ? configuredAllowFrom : void 0);
681
+ const isSamePhone = params.from === params.selfE164;
682
+ const isSelfChat = account.selfChatMode ?? isSelfChatMode(params.selfE164, configuredAllowFrom);
683
+ const pairingGraceMs = typeof params.pairingGraceMs === "number" && params.pairingGraceMs > 0 ? params.pairingGraceMs : PAIRING_REPLY_HISTORY_GRACE_MS;
684
+ const suppressPairingReply = typeof params.connectedAtMs === "number" && typeof params.messageTimestampMs === "number" && params.messageTimestampMs < params.connectedAtMs - pairingGraceMs;
685
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
686
+ const { groupPolicy, providerMissingFallbackApplied } = resolveWhatsAppRuntimeGroupPolicy({
687
+ providerConfigPresent: cfg.channels?.whatsapp !== void 0,
688
+ groupPolicy: account.groupPolicy,
689
+ defaultGroupPolicy
690
+ });
691
+ warnMissingProviderGroupPolicyFallbackOnce({
692
+ providerMissingFallbackApplied,
693
+ providerKey: "whatsapp",
694
+ accountId: account.accountId,
695
+ log: (message) => logVerbose(message)
696
+ });
697
+ const rawNormalizedDmSender = normalizeE164(params.from);
698
+ if (!isValidE164(rawNormalizedDmSender)) {
699
+ getLog().warn("jid.resolution.failed", { rawJid: params.from });
700
+ return {
701
+ allowed: false,
702
+ shouldMarkRead: false,
703
+ isSelfChat,
704
+ resolvedAccountId: account.accountId
705
+ };
706
+ }
707
+ const normalizedDmSender = rawNormalizedDmSender;
708
+ const rawNormalizedGroupSender = typeof params.senderE164 === "string" ? normalizeE164(params.senderE164) : null;
709
+ if (params.group && params.senderE164 && !isValidE164(rawNormalizedGroupSender)) getLog().warn("jid.resolution.failed", { rawJid: params.senderE164 });
710
+ const normalizedGroupSender = isValidE164(rawNormalizedGroupSender) ? rawNormalizedGroupSender : null;
711
+ const access = resolveDmGroupAccessWithLists({
712
+ isGroup: params.group,
713
+ dmPolicy,
714
+ groupPolicy,
715
+ allowFrom: params.group ? configuredAllowFrom : dmAllowFrom,
716
+ groupAllowFrom,
717
+ storeAllowFrom,
718
+ isSenderAllowed: (allowEntries) => {
719
+ if (allowEntries.includes("*")) return true;
720
+ const normalizedEntrySet = new Set(allowEntries.map((entry) => normalizeE164(String(entry))).filter((entry) => isValidE164(entry)));
721
+ if (!params.group && isSamePhone) return true;
722
+ return params.group ? Boolean(normalizedGroupSender && normalizedEntrySet.has(normalizedGroupSender)) : normalizedEntrySet.has(normalizedDmSender);
723
+ }
724
+ });
725
+ if (params.group && access.decision !== "allow") {
726
+ if (access.reason === "groupPolicy=disabled") logVerbose("Blocked group message (groupPolicy: disabled)");
727
+ else if (access.reason === "groupPolicy=allowlist (empty allowlist)") logVerbose("Blocked group message (groupPolicy: allowlist, no groupAllowFrom)");
728
+ else logVerbose(`Blocked group message from ${params.senderE164 ?? "unknown sender"} (groupPolicy: allowlist)`);
729
+ return {
730
+ allowed: false,
731
+ shouldMarkRead: false,
732
+ isSelfChat,
733
+ resolvedAccountId: account.accountId
734
+ };
735
+ }
736
+ if (!params.group) {
737
+ if (params.isFromMe && !isSamePhone) {
738
+ logVerbose("Skipping outbound DM (fromMe); no pairing reply needed.");
739
+ return {
740
+ allowed: false,
741
+ shouldMarkRead: false,
742
+ isSelfChat,
743
+ resolvedAccountId: account.accountId
744
+ };
745
+ }
746
+ if (access.decision === "block" && access.reason === "dmPolicy=disabled") {
747
+ logVerbose("Blocked dm (dmPolicy: disabled)");
748
+ return {
749
+ allowed: false,
750
+ shouldMarkRead: false,
751
+ isSelfChat,
752
+ resolvedAccountId: account.accountId
753
+ };
754
+ }
755
+ if (access.decision === "pairing" && !isSamePhone) {
756
+ const candidate = params.from;
757
+ if (suppressPairingReply) logVerbose(`Skipping pairing reply for historical DM from ${candidate}.`);
758
+ else {
759
+ const { code, created } = await upsertChannelPairingRequest({
760
+ channel: "whatsapp",
761
+ id: candidate,
762
+ accountId: account.accountId,
763
+ meta: { name: (params.pushName ?? "").trim() || void 0 }
764
+ });
765
+ if (created) {
766
+ logVerbose(`whatsapp pairing request sender=${candidate} name=${params.pushName ?? "unknown"}`);
767
+ try {
768
+ await params.sock.sendMessage(params.remoteJid, { text: buildPairingReply({
769
+ channel: "whatsapp",
770
+ idLine: `Your WhatsApp phone number: ${candidate}`,
771
+ code
772
+ }) });
773
+ } catch (err) {
774
+ logVerbose(`whatsapp pairing reply failed for ${candidate}: ${String(err)}`);
775
+ }
776
+ }
777
+ }
778
+ return {
779
+ allowed: false,
780
+ shouldMarkRead: false,
781
+ isSelfChat,
782
+ resolvedAccountId: account.accountId
783
+ };
784
+ }
785
+ if (access.decision !== "allow") {
786
+ logVerbose(`Blocked unauthorized sender ${params.from} (dmPolicy=${dmPolicy})`);
787
+ return {
788
+ allowed: false,
789
+ shouldMarkRead: false,
790
+ isSelfChat,
791
+ resolvedAccountId: account.accountId
792
+ };
793
+ }
794
+ }
795
+ return {
796
+ allowed: true,
797
+ shouldMarkRead: true,
798
+ isSelfChat,
799
+ resolvedAccountId: account.accountId
800
+ };
801
+ }
802
+
803
+ //#endregion
804
+ //#region src/inbound/dedupe.ts
805
+ const RECENT_WEB_MESSAGE_TTL_MS = 20 * 6e4;
806
+ const RECENT_WEB_MESSAGE_MAX = 5e3;
807
+ function createInboundDedupeCache() {
808
+ const cache = createDedupeCache({
809
+ ttlMs: RECENT_WEB_MESSAGE_TTL_MS,
810
+ maxSize: RECENT_WEB_MESSAGE_MAX
811
+ });
812
+ return { isRecent: (key) => cache.check(key) };
813
+ }
814
+
815
+ //#endregion
816
+ //#region src/vcard.ts
817
+ const ALLOWED_VCARD_KEYS = new Set([
818
+ "FN",
819
+ "N",
820
+ "TEL"
821
+ ]);
822
+ function parseVcard(vcard) {
823
+ if (!vcard) return { phones: [] };
824
+ const lines = vcard.split(/\r?\n/);
825
+ let nameFromN;
826
+ let nameFromFn;
827
+ const phones = [];
828
+ for (const rawLine of lines) {
829
+ const line = rawLine.trim();
830
+ if (!line) continue;
831
+ const colonIndex = line.indexOf(":");
832
+ if (colonIndex === -1) continue;
833
+ const key = line.slice(0, colonIndex).toUpperCase();
834
+ const rawValue = line.slice(colonIndex + 1).trim();
835
+ if (!rawValue) continue;
836
+ const baseKey = normalizeVcardKey(key);
837
+ if (!baseKey || !ALLOWED_VCARD_KEYS.has(baseKey)) continue;
838
+ const value = cleanVcardValue(rawValue);
839
+ if (!value) continue;
840
+ if (baseKey === "FN" && !nameFromFn) {
841
+ nameFromFn = normalizeVcardName(value);
842
+ continue;
843
+ }
844
+ if (baseKey === "N" && !nameFromN) {
845
+ nameFromN = normalizeVcardName(value);
846
+ continue;
847
+ }
848
+ if (baseKey === "TEL") {
849
+ const phone = normalizeVcardPhone(value);
850
+ if (phone) phones.push(phone);
851
+ }
852
+ }
853
+ return {
854
+ name: nameFromFn ?? nameFromN,
855
+ phones
856
+ };
857
+ }
858
+ function normalizeVcardKey(key) {
859
+ const [primary] = key.split(";");
860
+ if (!primary) return;
861
+ const segments = primary.split(".");
862
+ return segments[segments.length - 1] || void 0;
863
+ }
864
+ function cleanVcardValue(value) {
865
+ return value.replace(/\\n/gi, " ").replace(/\\,/g, ",").replace(/\\;/g, ";").trim();
866
+ }
867
+ function normalizeVcardName(value) {
868
+ return value.replace(/;/g, " ").replace(/\s+/g, " ").trim();
869
+ }
870
+ function normalizeVcardPhone(value) {
871
+ const trimmed = value.trim();
872
+ if (!trimmed) return "";
873
+ if (trimmed.toLowerCase().startsWith("tel:")) return trimmed.slice(4).trim();
874
+ return trimmed;
875
+ }
876
+
877
+ //#endregion
878
+ //#region src/inbound/extract.ts
879
+ function unwrapMessage$1(message, utils) {
880
+ return utils.normalizeMessageContent(message);
881
+ }
882
+ function extractContextInfo(message, utils) {
883
+ if (!message) return;
884
+ const contentType = utils.getContentType(message);
885
+ const candidate = contentType ? message[contentType] : void 0;
886
+ const contextInfo = candidate && typeof candidate === "object" && "contextInfo" in candidate ? candidate.contextInfo : void 0;
887
+ if (contextInfo) return contextInfo;
888
+ const fallback = message.extendedTextMessage?.contextInfo ?? message.imageMessage?.contextInfo ?? message.videoMessage?.contextInfo ?? message.documentMessage?.contextInfo ?? message.audioMessage?.contextInfo ?? message.stickerMessage?.contextInfo ?? message.buttonsResponseMessage?.contextInfo ?? message.listResponseMessage?.contextInfo ?? message.templateButtonReplyMessage?.contextInfo ?? message.interactiveResponseMessage?.contextInfo ?? message.buttonsMessage?.contextInfo ?? message.listMessage?.contextInfo;
889
+ if (fallback) return fallback;
890
+ for (const value of Object.values(message)) {
891
+ if (!value || typeof value !== "object") continue;
892
+ if (!("contextInfo" in value)) continue;
893
+ const candidateContext = value.contextInfo;
894
+ if (candidateContext) return candidateContext;
895
+ }
896
+ }
897
+ function extractMentionedJids(utils, rawMessage) {
898
+ const message = unwrapMessage$1(rawMessage, utils);
899
+ if (!message) return;
900
+ const flattened = [
901
+ message.extendedTextMessage?.contextInfo?.mentionedJid,
902
+ message.extendedTextMessage?.contextInfo?.quotedMessage?.extendedTextMessage?.contextInfo?.mentionedJid,
903
+ message.imageMessage?.contextInfo?.mentionedJid,
904
+ message.videoMessage?.contextInfo?.mentionedJid,
905
+ message.documentMessage?.contextInfo?.mentionedJid,
906
+ message.audioMessage?.contextInfo?.mentionedJid,
907
+ message.stickerMessage?.contextInfo?.mentionedJid,
908
+ message.buttonsResponseMessage?.contextInfo?.mentionedJid,
909
+ message.listResponseMessage?.contextInfo?.mentionedJid
910
+ ].flatMap((arr) => arr ?? []).filter(Boolean);
911
+ if (flattened.length === 0) return;
912
+ return Array.from(new Set(flattened));
913
+ }
914
+ function extractText(utils, rawMessage) {
915
+ const message = unwrapMessage$1(rawMessage, utils);
916
+ if (!message) return;
917
+ const extracted = utils.extractMessageContent(message);
918
+ const candidates = [message, extracted && extracted !== message ? extracted : void 0];
919
+ for (const candidate of candidates) {
920
+ if (!candidate) continue;
921
+ if (typeof candidate.conversation === "string" && candidate.conversation.trim()) return candidate.conversation.trim();
922
+ const extended = candidate.extendedTextMessage?.text;
923
+ if (extended?.trim()) return extended.trim();
924
+ const caption = candidate.imageMessage?.caption ?? candidate.videoMessage?.caption ?? candidate.documentMessage?.caption;
925
+ if (caption?.trim()) return caption.trim();
926
+ }
927
+ const contactPlaceholder = extractContactPlaceholder(utils, message) ?? (extracted && extracted !== message ? extractContactPlaceholder(utils, extracted) : void 0);
928
+ if (contactPlaceholder) return contactPlaceholder;
929
+ }
930
+ function extractMediaPlaceholder(utils, rawMessage) {
931
+ const message = unwrapMessage$1(rawMessage, utils);
932
+ if (!message) return;
933
+ if (message.imageMessage) return "<media:image>";
934
+ if (message.videoMessage) return "<media:video>";
935
+ if (message.audioMessage) return "<media:audio>";
936
+ if (message.documentMessage) return "<media:document>";
937
+ if (message.stickerMessage) return "<media:sticker>";
938
+ }
939
+ function extractContactPlaceholder(utils, rawMessage) {
940
+ const message = unwrapMessage$1(rawMessage, utils);
941
+ if (!message) return;
942
+ const contact = message.contactMessage ?? void 0;
943
+ if (contact) {
944
+ const { name, phones } = describeContact({
945
+ displayName: contact.displayName,
946
+ vcard: contact.vcard
947
+ });
948
+ return formatContactPlaceholder(name, phones);
949
+ }
950
+ const contactsArray = message.contactsArrayMessage?.contacts ?? void 0;
951
+ if (!contactsArray || contactsArray.length === 0) return;
952
+ return formatContactsPlaceholder(contactsArray.map((entry) => describeContact({
953
+ displayName: entry.displayName,
954
+ vcard: entry.vcard
955
+ })).map((entry) => formatContactLabel(entry.name, entry.phones)).filter((value) => Boolean(value)), contactsArray.length);
956
+ }
957
+ function describeContact(input) {
958
+ const displayName = (input.displayName ?? "").trim();
959
+ const parsed = parseVcard(input.vcard ?? void 0);
960
+ return {
961
+ name: displayName || parsed.name,
962
+ phones: parsed.phones
963
+ };
964
+ }
965
+ function formatContactPlaceholder(name, phones) {
966
+ const label = formatContactLabel(name, phones);
967
+ if (!label) return "<contact>";
968
+ return `<contact: ${label}>`;
969
+ }
970
+ function formatContactsPlaceholder(labels, total) {
971
+ const cleaned = labels.map((label) => label.trim()).filter(Boolean);
972
+ if (cleaned.length === 0) return `<contacts: ${total} ${total === 1 ? "contact" : "contacts"}>`;
973
+ const remaining = Math.max(total - cleaned.length, 0);
974
+ const suffix = remaining > 0 ? ` +${remaining} more` : "";
975
+ return `<contacts: ${cleaned.join(", ")}${suffix}>`;
976
+ }
977
+ function formatContactLabel(name, phones) {
978
+ const parts = [name, formatPhoneList(phones)].filter((value) => Boolean(value));
979
+ if (parts.length === 0) return;
980
+ return parts.join(", ");
981
+ }
982
+ function formatPhoneList(phones) {
983
+ const cleaned = phones?.map((phone) => phone.trim()).filter(Boolean) ?? [];
984
+ if (cleaned.length === 0) return;
985
+ const { shown, remaining } = summarizeList(cleaned, cleaned.length, 1);
986
+ const [primary] = shown;
987
+ if (!primary) return;
988
+ if (remaining === 0) return primary;
989
+ return `${primary} (+${remaining} more)`;
990
+ }
991
+ function summarizeList(values, total, maxShown) {
992
+ const shown = values.slice(0, maxShown);
993
+ return {
994
+ shown,
995
+ remaining: Math.max(total - shown.length, 0)
996
+ };
997
+ }
998
+ function extractLocationData(utils, rawMessage) {
999
+ const message = unwrapMessage$1(rawMessage, utils);
1000
+ if (!message) return null;
1001
+ const live = message.liveLocationMessage ?? void 0;
1002
+ if (live) {
1003
+ const latitudeRaw = live.degreesLatitude;
1004
+ const longitudeRaw = live.degreesLongitude;
1005
+ if (latitudeRaw != null && longitudeRaw != null) {
1006
+ const latitude = Number(latitudeRaw);
1007
+ const longitude = Number(longitudeRaw);
1008
+ if (Number.isFinite(latitude) && Number.isFinite(longitude)) return {
1009
+ latitude,
1010
+ longitude,
1011
+ accuracy: live.accuracyInMeters ?? void 0,
1012
+ caption: live.caption ?? void 0,
1013
+ source: "live",
1014
+ isLive: true
1015
+ };
1016
+ }
1017
+ }
1018
+ const location = message.locationMessage ?? void 0;
1019
+ if (location) {
1020
+ const latitudeRaw = location.degreesLatitude;
1021
+ const longitudeRaw = location.degreesLongitude;
1022
+ if (latitudeRaw != null && longitudeRaw != null) {
1023
+ const latitude = Number(latitudeRaw);
1024
+ const longitude = Number(longitudeRaw);
1025
+ if (Number.isFinite(latitude) && Number.isFinite(longitude)) {
1026
+ const isLive = Boolean(location.isLive);
1027
+ return {
1028
+ latitude,
1029
+ longitude,
1030
+ accuracy: location.accuracyInMeters ?? void 0,
1031
+ name: location.name ?? void 0,
1032
+ address: location.address ?? void 0,
1033
+ caption: location.comment ?? void 0,
1034
+ source: isLive ? "live" : location.name || location.address ? "place" : "pin",
1035
+ isLive
1036
+ };
1037
+ }
1038
+ }
1039
+ }
1040
+ return null;
1041
+ }
1042
+ function describeReplyContext(utils, rawMessage) {
1043
+ const message = unwrapMessage$1(rawMessage, utils);
1044
+ if (!message) return null;
1045
+ const contextInfo = extractContextInfo(message, utils);
1046
+ const quoted = utils.normalizeMessageContent(contextInfo?.quotedMessage);
1047
+ if (!quoted) return null;
1048
+ const location = extractLocationData(utils, quoted);
1049
+ const locationText = location ? formatLocationText(location) : void 0;
1050
+ let body = [extractText(utils, quoted), locationText].filter(Boolean).join("\n").trim();
1051
+ if (!body) body = extractMediaPlaceholder(utils, quoted);
1052
+ if (!body) {
1053
+ const quotedType = quoted ? utils.getContentType(quoted) : void 0;
1054
+ logVerbose(`Quoted message missing extractable body${quotedType ? ` (type ${quotedType})` : ""}`);
1055
+ return null;
1056
+ }
1057
+ const senderJid = contextInfo?.participant ?? void 0;
1058
+ const senderE164 = senderJid ? jidToE164(senderJid) ?? senderJid : void 0;
1059
+ const sender = senderE164 ?? "unknown sender";
1060
+ return {
1061
+ id: contextInfo?.stanzaId ? String(contextInfo.stanzaId) : void 0,
1062
+ body,
1063
+ sender,
1064
+ senderJid,
1065
+ senderE164
1066
+ };
1067
+ }
1068
+
1069
+ //#endregion
1070
+ //#region src/inbound/media.ts
1071
+ function unwrapMessage(message, normalizeMessageContent) {
1072
+ return normalizeMessageContent(message);
1073
+ }
1074
+ function resolveMediaMimetype(message) {
1075
+ const explicit = message.imageMessage?.mimetype ?? message.videoMessage?.mimetype ?? message.documentMessage?.mimetype ?? message.audioMessage?.mimetype ?? message.stickerMessage?.mimetype ?? void 0;
1076
+ if (explicit) return explicit;
1077
+ if (message.audioMessage) return "audio/ogg; codecs=opus";
1078
+ if (message.imageMessage) return "image/jpeg";
1079
+ if (message.videoMessage) return "video/mp4";
1080
+ if (message.stickerMessage) return "image/webp";
1081
+ }
1082
+ async function downloadInboundMedia(msg, sock) {
1083
+ const { downloadMediaMessage, normalizeMessageContent } = await getBaileys();
1084
+ const message = unwrapMessage(msg.message, normalizeMessageContent);
1085
+ if (!message) return;
1086
+ const mimetype = resolveMediaMimetype(message);
1087
+ const fileName = message.documentMessage?.fileName ?? void 0;
1088
+ if (!message.imageMessage && !message.videoMessage && !message.documentMessage && !message.audioMessage && !message.stickerMessage) return;
1089
+ try {
1090
+ return {
1091
+ buffer: await downloadMediaMessage(msg, "buffer", {}, {
1092
+ reuploadRequest: sock.updateMediaMessage,
1093
+ logger: sock.logger
1094
+ }),
1095
+ mimetype,
1096
+ fileName
1097
+ };
1098
+ } catch (err) {
1099
+ logVerbose(`downloadMediaMessage failed: ${String(err)}`);
1100
+ return;
1101
+ }
1102
+ }
1103
+
1104
+ //#endregion
1105
+ //#region src/inbound/send-api.ts
1106
+ function recordWhatsAppOutbound(accountId) {
1107
+ recordChannelActivity({
1108
+ channel: "whatsapp",
1109
+ accountId,
1110
+ direction: "outbound"
1111
+ });
1112
+ }
1113
+ function resolveOutboundMessageId(result) {
1114
+ return typeof result === "object" && result && "key" in result ? String(result.key?.id ?? "unknown") : "unknown";
1115
+ }
1116
+ function createWebSendApi(params) {
1117
+ return {
1118
+ sendMessage: async (to, text, mediaBuffer, mediaType, sendOptions) => {
1119
+ const jid = toWhatsappJid(to);
1120
+ let payload;
1121
+ if (mediaBuffer && mediaType) if (mediaType.startsWith("image/")) payload = {
1122
+ image: mediaBuffer,
1123
+ caption: text || void 0,
1124
+ mimetype: mediaType
1125
+ };
1126
+ else if (mediaType.startsWith("audio/")) payload = {
1127
+ audio: mediaBuffer,
1128
+ ptt: true,
1129
+ mimetype: mediaType
1130
+ };
1131
+ else if (mediaType.startsWith("video/")) {
1132
+ const gifPlayback = sendOptions?.gifPlayback;
1133
+ payload = {
1134
+ video: mediaBuffer,
1135
+ caption: text || void 0,
1136
+ mimetype: mediaType,
1137
+ ...gifPlayback ? { gifPlayback: true } : {}
1138
+ };
1139
+ } else payload = {
1140
+ document: mediaBuffer,
1141
+ fileName: sendOptions?.fileName?.trim() || "file",
1142
+ caption: text || void 0,
1143
+ mimetype: mediaType
1144
+ };
1145
+ else payload = { text };
1146
+ const result = await params.sock.sendMessage(jid, payload);
1147
+ recordWhatsAppOutbound(sendOptions?.accountId ?? params.defaultAccountId);
1148
+ if (mediaBuffer && mediaType?.startsWith("audio/") && text) await params.sock.sendMessage(jid, { text });
1149
+ return { messageId: resolveOutboundMessageId(result) };
1150
+ },
1151
+ sendPoll: async (to, poll) => {
1152
+ const jid = toWhatsappJid(to);
1153
+ const result = await params.sock.sendMessage(jid, { poll: {
1154
+ name: poll.question,
1155
+ values: poll.options,
1156
+ selectableCount: poll.maxSelections ?? 1
1157
+ } });
1158
+ recordWhatsAppOutbound(params.defaultAccountId);
1159
+ return { messageId: resolveOutboundMessageId(result) };
1160
+ },
1161
+ sendReaction: async (chatJid, messageId, emoji, fromMe, participant) => {
1162
+ const jid = toWhatsappJid(chatJid);
1163
+ await params.sock.sendMessage(jid, { react: {
1164
+ text: emoji,
1165
+ key: {
1166
+ remoteJid: jid,
1167
+ id: messageId,
1168
+ fromMe,
1169
+ participant: participant ? toWhatsappJid(participant) : void 0
1170
+ }
1171
+ } });
1172
+ },
1173
+ sendComposingTo: async (to) => {
1174
+ const jid = toWhatsappJid(to);
1175
+ await params.sock.sendPresenceUpdate("composing", jid);
1176
+ }
1177
+ };
1178
+ }
1179
+
1180
+ //#endregion
1181
+ //#region src/inbound/monitor.ts
1182
+ async function monitorWebInbox(options) {
1183
+ const { isJidGroup, DisconnectReason, extractMessageContent, getContentType, normalizeMessageContent } = await getBaileys();
1184
+ const messageUtils = {
1185
+ extractMessageContent,
1186
+ getContentType,
1187
+ normalizeMessageContent
1188
+ };
1189
+ const inboundLogger = getChildLogger({ module: "web-inbound" });
1190
+ const inboundConsoleLog = createSubsystemLogger("gateway/channels/whatsapp").child("inbound");
1191
+ const sock = await createWaSocket(false, options.verbose, { authDir: options.authDir });
1192
+ try {
1193
+ await waitForWaConnection(sock);
1194
+ } catch (err) {
1195
+ try {
1196
+ await closeWaSocket(sock);
1197
+ } catch (closeErr) {
1198
+ logVerbose(`Socket close failed after connection error: ${String(closeErr)}`);
1199
+ }
1200
+ throw err;
1201
+ }
1202
+ const connectedAtMs = Date.now();
1203
+ const dedupeCache = createInboundDedupeCache();
1204
+ let onCloseResolve = null;
1205
+ const onClose = new Promise((resolve) => {
1206
+ onCloseResolve = resolve;
1207
+ });
1208
+ const resolveClose = (reason) => {
1209
+ if (!onCloseResolve) return;
1210
+ const resolver = onCloseResolve;
1211
+ onCloseResolve = null;
1212
+ resolver(reason);
1213
+ };
1214
+ try {
1215
+ await sock.sendPresenceUpdate("available");
1216
+ if (shouldLogVerbose()) logVerbose("Sent global 'available' presence on connect");
1217
+ } catch (err) {
1218
+ logVerbose(`Failed to send 'available' presence on connect: ${String(err)}`);
1219
+ }
1220
+ const selfJid = sock.user?.id;
1221
+ const selfE164 = selfJid ? await resolveJidToE164(selfJid, { authDir: options.authDir }) ?? null : null;
1222
+ const debouncer = createInboundDebouncer({
1223
+ debounceMs: options.debounceMs ?? 0,
1224
+ buildKey: (msg) => {
1225
+ const senderKey = msg.chatType === "group" ? msg.senderJid ?? msg.senderE164 ?? msg.senderName ?? msg.from : msg.from;
1226
+ if (!senderKey) return null;
1227
+ const conversationKey = msg.chatType === "group" ? msg.chatId : msg.from;
1228
+ return `${msg.accountId}:${conversationKey}:${senderKey}`;
1229
+ },
1230
+ shouldDebounce: options.shouldDebounce,
1231
+ onFlush: async (entries) => {
1232
+ const last = entries.at(-1);
1233
+ if (!last) return;
1234
+ if (entries.length === 1) {
1235
+ await options.onMessage(last);
1236
+ return;
1237
+ }
1238
+ const mentioned = /* @__PURE__ */ new Set();
1239
+ for (const entry of entries) for (const jid of entry.mentionedJids ?? []) mentioned.add(jid);
1240
+ const combinedBody = entries.map((entry) => entry.body).filter(Boolean).join("\n");
1241
+ const combinedMessage = {
1242
+ ...last,
1243
+ body: combinedBody,
1244
+ mentionedJids: mentioned.size > 0 ? Array.from(mentioned) : void 0
1245
+ };
1246
+ await options.onMessage(combinedMessage);
1247
+ },
1248
+ onError: (err) => {
1249
+ inboundLogger.error("failed handling inbound web message", { error: String(err) });
1250
+ inboundConsoleLog.error(`Failed handling inbound web message: ${String(err)}`);
1251
+ }
1252
+ });
1253
+ const groupMetaCache = /* @__PURE__ */ new Map();
1254
+ const GROUP_META_TTL_MS = 300 * 1e3;
1255
+ const lidLookup = sock.signalRepository?.lidMapping;
1256
+ const resolveInboundJid = async (jid) => resolveJidToE164(jid, {
1257
+ authDir: options.authDir,
1258
+ lidLookup
1259
+ }) ?? null;
1260
+ const getGroupMeta = async (jid) => {
1261
+ const cached = groupMetaCache.get(jid);
1262
+ if (cached && cached.expires > Date.now()) return cached;
1263
+ try {
1264
+ const meta = await sock.groupMetadata(jid);
1265
+ const participants = (await Promise.all(meta.participants?.map(async (p) => {
1266
+ return await resolveInboundJid(p.id) ?? p.id;
1267
+ }) ?? [])).filter(Boolean) ?? [];
1268
+ const entry = {
1269
+ subject: meta.subject,
1270
+ participants,
1271
+ expires: Date.now() + GROUP_META_TTL_MS
1272
+ };
1273
+ groupMetaCache.set(jid, entry);
1274
+ return entry;
1275
+ } catch (err) {
1276
+ logVerbose(`Failed to fetch group metadata for ${jid}: ${String(err)}`);
1277
+ return { expires: Date.now() + GROUP_META_TTL_MS };
1278
+ }
1279
+ };
1280
+ const normalizeInboundMessage = async (msg) => {
1281
+ const id = msg.key?.id ?? void 0;
1282
+ const remoteJid = msg.key?.remoteJid;
1283
+ if (!remoteJid) return null;
1284
+ if (remoteJid.endsWith("@status") || remoteJid.endsWith("@broadcast")) return null;
1285
+ const group = isJidGroup(remoteJid) === true;
1286
+ if (id) {
1287
+ const dedupeKey = `${options.accountId}:${remoteJid}:${id}`;
1288
+ if (dedupeCache.isRecent(dedupeKey)) return null;
1289
+ }
1290
+ const participantJid = msg.key?.participant ?? void 0;
1291
+ const from = group ? remoteJid : await resolveInboundJid(remoteJid);
1292
+ if (!from) return null;
1293
+ const senderE164 = group ? participantJid ? await resolveInboundJid(participantJid) : null : from;
1294
+ let groupSubject;
1295
+ let groupParticipants;
1296
+ if (group) {
1297
+ const meta = await getGroupMeta(remoteJid);
1298
+ groupSubject = meta.subject;
1299
+ groupParticipants = meta.participants;
1300
+ }
1301
+ const messageTimestampMs = msg.messageTimestamp ? Number(msg.messageTimestamp) * 1e3 : void 0;
1302
+ const access = await checkInboundAccessControl({
1303
+ accountId: options.accountId,
1304
+ from,
1305
+ selfE164,
1306
+ senderE164,
1307
+ group,
1308
+ pushName: msg.pushName ?? void 0,
1309
+ isFromMe: Boolean(msg.key?.fromMe),
1310
+ messageTimestampMs,
1311
+ connectedAtMs,
1312
+ sock: { sendMessage: (jid, content) => sock.sendMessage(jid, content) },
1313
+ remoteJid
1314
+ });
1315
+ if (!access.allowed) return null;
1316
+ return {
1317
+ id,
1318
+ remoteJid,
1319
+ group,
1320
+ participantJid,
1321
+ from,
1322
+ senderE164,
1323
+ groupSubject,
1324
+ groupParticipants,
1325
+ messageTimestampMs,
1326
+ access
1327
+ };
1328
+ };
1329
+ const maybeMarkInboundAsRead = async (inbound) => {
1330
+ const { id, remoteJid, participantJid, access } = inbound;
1331
+ if (id && !access.isSelfChat && options.sendReadReceipts !== false) try {
1332
+ await sock.readMessages([{
1333
+ remoteJid,
1334
+ id,
1335
+ participant: participantJid,
1336
+ fromMe: false
1337
+ }]);
1338
+ if (shouldLogVerbose()) logVerbose(`Marked message ${id} as read for ${remoteJid}${participantJid ? ` (participant ${participantJid})` : ""}`);
1339
+ } catch (err) {
1340
+ logVerbose(`Failed to mark message ${id} read: ${String(err)}`);
1341
+ }
1342
+ else if (id && access.isSelfChat && shouldLogVerbose()) logVerbose(`Self-chat mode: skipping read receipt for ${id}`);
1343
+ };
1344
+ const enrichInboundMessage = async (msg) => {
1345
+ const location = extractLocationData(messageUtils, msg.message ?? void 0);
1346
+ const locationText = location ? formatLocationText(location) : void 0;
1347
+ let body = extractText(messageUtils, msg.message ?? void 0);
1348
+ if (locationText) body = [body, locationText].filter(Boolean).join("\n").trim();
1349
+ if (!body) {
1350
+ body = extractMediaPlaceholder(messageUtils, msg.message ?? void 0);
1351
+ if (!body) return null;
1352
+ }
1353
+ const replyContext = describeReplyContext(messageUtils, msg.message);
1354
+ let mediaPath;
1355
+ let mediaType;
1356
+ let mediaFileName;
1357
+ try {
1358
+ const inboundMedia = await downloadInboundMedia(msg, sock);
1359
+ if (inboundMedia) {
1360
+ const maxBytes = (typeof options.mediaMaxMb === "number" && options.mediaMaxMb > 0 ? options.mediaMaxMb : 50) * 1024 * 1024;
1361
+ const saved = await saveMediaBuffer(inboundMedia.buffer, inboundMedia.mimetype, "inbound", maxBytes, inboundMedia.fileName);
1362
+ mediaPath = saved.path;
1363
+ mediaType = saved.contentType ?? inboundMedia.mimetype;
1364
+ mediaFileName = inboundMedia.fileName;
1365
+ }
1366
+ } catch (err) {
1367
+ logVerbose(`Inbound media download failed: ${String(err)}`);
1368
+ }
1369
+ return {
1370
+ body,
1371
+ location: location ?? void 0,
1372
+ replyContext,
1373
+ mediaPath,
1374
+ mediaType,
1375
+ mediaFileName
1376
+ };
1377
+ };
1378
+ const enqueueInboundMessage = async (msg, inbound, enriched) => {
1379
+ const chatJid = inbound.remoteJid;
1380
+ const sendComposing = async () => {
1381
+ try {
1382
+ await sock.sendPresenceUpdate("composing", chatJid);
1383
+ } catch (err) {
1384
+ logVerbose(`Presence update failed: ${String(err)}`);
1385
+ }
1386
+ };
1387
+ const reply = async (text) => {
1388
+ await sock.sendMessage(chatJid, { text });
1389
+ };
1390
+ const sendMedia = async (payload) => {
1391
+ await sock.sendMessage(chatJid, payload);
1392
+ };
1393
+ const timestamp = inbound.messageTimestampMs;
1394
+ const mentionedJids = extractMentionedJids(messageUtils, msg.message);
1395
+ const senderName = msg.pushName ?? void 0;
1396
+ inboundLogger.info("inbound message", {
1397
+ from: inbound.from,
1398
+ to: selfE164 ?? "me",
1399
+ body: enriched.body,
1400
+ mediaPath: enriched.mediaPath,
1401
+ mediaType: enriched.mediaType,
1402
+ mediaFileName: enriched.mediaFileName,
1403
+ timestamp
1404
+ });
1405
+ const inboundMessage = {
1406
+ id: inbound.id,
1407
+ from: inbound.from,
1408
+ conversationId: inbound.from,
1409
+ to: selfE164 ?? "me",
1410
+ accountId: inbound.access.resolvedAccountId,
1411
+ body: enriched.body,
1412
+ pushName: senderName,
1413
+ timestamp,
1414
+ chatType: inbound.group ? "group" : "direct",
1415
+ chatId: inbound.remoteJid,
1416
+ senderJid: inbound.participantJid,
1417
+ senderE164: inbound.senderE164 ?? void 0,
1418
+ senderName,
1419
+ replyToId: enriched.replyContext?.id,
1420
+ replyToBody: enriched.replyContext?.body,
1421
+ replyToSender: enriched.replyContext?.sender,
1422
+ replyToSenderJid: enriched.replyContext?.senderJid,
1423
+ replyToSenderE164: enriched.replyContext?.senderE164,
1424
+ groupSubject: inbound.groupSubject,
1425
+ groupParticipants: inbound.groupParticipants,
1426
+ mentionedJids: mentionedJids ?? void 0,
1427
+ selfJid,
1428
+ selfE164,
1429
+ fromMe: Boolean(msg.key?.fromMe),
1430
+ location: enriched.location ?? void 0,
1431
+ sendComposing,
1432
+ reply,
1433
+ sendMedia,
1434
+ mediaPath: enriched.mediaPath,
1435
+ mediaType: enriched.mediaType,
1436
+ mediaFileName: enriched.mediaFileName
1437
+ };
1438
+ try {
1439
+ Promise.resolve(debouncer.enqueue(inboundMessage)).catch((err) => {
1440
+ inboundLogger.error("failed handling inbound web message", { error: String(err) });
1441
+ inboundConsoleLog.error(`Failed handling inbound web message: ${String(err)}`);
1442
+ });
1443
+ } catch (err) {
1444
+ inboundLogger.error("failed handling inbound web message", { error: String(err) });
1445
+ inboundConsoleLog.error(`Failed handling inbound web message: ${String(err)}`);
1446
+ }
1447
+ };
1448
+ const handleMessagesUpsert = async (upsert) => {
1449
+ if (upsert.type !== "notify" && upsert.type !== "append") return;
1450
+ for (const msg of upsert.messages ?? []) {
1451
+ recordChannelActivity({
1452
+ channel: "whatsapp",
1453
+ accountId: options.accountId,
1454
+ direction: "inbound"
1455
+ });
1456
+ const inbound = await normalizeInboundMessage(msg);
1457
+ if (!inbound) continue;
1458
+ await maybeMarkInboundAsRead(inbound);
1459
+ if (upsert.type === "append") continue;
1460
+ const enriched = await enrichInboundMessage(msg);
1461
+ if (!enriched) continue;
1462
+ if (enriched.body === "<media:audio>" && enriched.mediaPath && enriched.mediaType?.startsWith("audio/")) try {
1463
+ const cfg = loadConfig();
1464
+ const audioConfig = cfg.tools?.media?.audio;
1465
+ if (audioConfig && audioConfig.enabled !== false) {
1466
+ const transcript = await transcribeFirstAudio({
1467
+ ctx: {
1468
+ MediaPaths: [enriched.mediaPath],
1469
+ MediaTypes: enriched.mediaType ? [enriched.mediaType] : void 0
1470
+ },
1471
+ cfg,
1472
+ agentDir: void 0
1473
+ });
1474
+ if (transcript) {
1475
+ enriched.body = transcript;
1476
+ enriched.mediaPath = void 0;
1477
+ logVerbose(`whatsapp: transcribed voice note (${transcript.length} chars)`);
1478
+ }
1479
+ }
1480
+ } catch (err) {
1481
+ logVerbose(`whatsapp: voice note transcription failed: ${String(err)}`);
1482
+ }
1483
+ await enqueueInboundMessage(msg, inbound, enriched);
1484
+ }
1485
+ };
1486
+ sock.ev.on("messages.upsert", handleMessagesUpsert);
1487
+ const handleConnectionUpdate = (update) => {
1488
+ try {
1489
+ if (update.connection === "close") {
1490
+ const status = getStatusCode(update.lastDisconnect?.error);
1491
+ resolveClose({
1492
+ status,
1493
+ isLoggedOut: status === DisconnectReason.loggedOut,
1494
+ error: update.lastDisconnect?.error
1495
+ });
1496
+ }
1497
+ } catch (err) {
1498
+ inboundLogger.error("connection.update handler error", { error: String(err) });
1499
+ resolveClose({
1500
+ status: void 0,
1501
+ isLoggedOut: false,
1502
+ error: err
1503
+ });
1504
+ }
1505
+ };
1506
+ sock.ev.on("connection.update", handleConnectionUpdate);
1507
+ return {
1508
+ close: async () => {
1509
+ try {
1510
+ const ev = sock.ev;
1511
+ const messagesUpsertHandler = handleMessagesUpsert;
1512
+ const connectionUpdateHandler = handleConnectionUpdate;
1513
+ if (typeof ev.off === "function") {
1514
+ ev.off("messages.upsert", messagesUpsertHandler);
1515
+ ev.off("connection.update", connectionUpdateHandler);
1516
+ } else if (typeof ev.removeListener === "function") {
1517
+ ev.removeListener("messages.upsert", messagesUpsertHandler);
1518
+ ev.removeListener("connection.update", connectionUpdateHandler);
1519
+ }
1520
+ try {
1521
+ await closeWaSocket(sock);
1522
+ } catch (err) {
1523
+ logVerbose(`Socket close failed: ${String(err)}; retrying once`);
1524
+ await closeWaSocket(sock);
1525
+ }
1526
+ } catch (err) {
1527
+ logVerbose(`Socket close failed: ${String(err)}`);
1528
+ throw err;
1529
+ }
1530
+ },
1531
+ onClose,
1532
+ signalClose: (reason) => {
1533
+ resolveClose(reason ?? {
1534
+ status: void 0,
1535
+ isLoggedOut: false,
1536
+ error: "closed"
1537
+ });
1538
+ },
1539
+ ...createWebSendApi({
1540
+ sock: {
1541
+ sendMessage: (jid, content) => sock.sendMessage(jid, content),
1542
+ sendPresenceUpdate: (presence, jid) => sock.sendPresenceUpdate(presence, jid)
1543
+ },
1544
+ defaultAccountId: options.accountId
1545
+ })
1546
+ };
1547
+ }
1548
+
1549
+ //#endregion
1550
+ //#region src/mentions.ts
1551
+ function buildMentionConfig(cfg, agentId) {
1552
+ return {
1553
+ mentionRegexes: buildMentionRegexes(cfg, agentId),
1554
+ allowFrom: cfg.channels?.whatsapp?.allowFrom
1555
+ };
1556
+ }
1557
+ function resolveMentionTargets(msg, authDir) {
1558
+ const jidOptions = authDir ? { authDir } : void 0;
1559
+ return {
1560
+ normalizedMentions: msg.mentionedJids?.length ? msg.mentionedJids.map((jid) => jidToE164(jid, jidOptions) ?? jid).filter(Boolean) : [],
1561
+ selfE164: msg.selfE164 ?? (msg.selfJid ? jidToE164(msg.selfJid, jidOptions) : null),
1562
+ selfJid: msg.selfJid ? msg.selfJid.replace(/:\\d+/, "") : null
1563
+ };
1564
+ }
1565
+ function isBotMentionedFromTargets(msg, mentionCfg, targets) {
1566
+ const clean = (text) => normalizeMentionText(text);
1567
+ const isSelfChat = isSelfChatMode(targets.selfE164, mentionCfg.allowFrom);
1568
+ const hasMentions = (msg.mentionedJids?.length ?? 0) > 0;
1569
+ if (hasMentions && !isSelfChat) {
1570
+ if (targets.selfE164 && targets.normalizedMentions.includes(targets.selfE164)) return true;
1571
+ if (targets.selfJid) {
1572
+ if (targets.normalizedMentions.includes(targets.selfJid)) return true;
1573
+ }
1574
+ return false;
1575
+ } else if (hasMentions && isSelfChat) {}
1576
+ const bodyClean = clean(msg.body);
1577
+ if (mentionCfg.mentionRegexes.some((re) => re.test(bodyClean))) return true;
1578
+ if (targets.selfE164) {
1579
+ const selfDigits = targets.selfE164.replace(/\D/g, "");
1580
+ if (selfDigits) {
1581
+ if (bodyClean.replace(/[^\d]/g, "").includes(selfDigits)) return true;
1582
+ const bodyNoSpace = msg.body.replace(/[\s-]/g, "");
1583
+ if (new RegExp(`\\+?${selfDigits}`, "i").test(bodyNoSpace)) return true;
1584
+ }
1585
+ }
1586
+ return false;
1587
+ }
1588
+ function debugMention(msg, mentionCfg, authDir) {
1589
+ const mentionTargets = resolveMentionTargets(msg, authDir);
1590
+ return {
1591
+ wasMentioned: isBotMentionedFromTargets(msg, mentionCfg, mentionTargets),
1592
+ details: {
1593
+ from: msg.from,
1594
+ body: msg.body,
1595
+ bodyClean: normalizeMentionText(msg.body),
1596
+ mentionedJids: msg.mentionedJids ?? null,
1597
+ normalizedMentionedJids: mentionTargets.normalizedMentions.length ? mentionTargets.normalizedMentions : null,
1598
+ selfJid: msg.selfJid ?? null,
1599
+ selfJidBare: mentionTargets.selfJid,
1600
+ selfE164: msg.selfE164 ?? null,
1601
+ resolvedSelfE164: mentionTargets.selfE164
1602
+ }
1603
+ };
1604
+ }
1605
+ function resolveOwnerList(mentionCfg, selfE164) {
1606
+ const allowFrom = mentionCfg.allowFrom;
1607
+ return (Array.isArray(allowFrom) && allowFrom.length > 0 ? allowFrom : selfE164 ? [selfE164] : []).filter((entry) => Boolean(entry && entry !== "*")).map((entry) => normalizeE164(entry)).filter((entry) => Boolean(entry));
1608
+ }
1609
+
1610
+ //#endregion
1611
+ //#region src/monitor/echo.ts
1612
+ function createEchoTracker(params) {
1613
+ const recentlySent = /* @__PURE__ */ new Set();
1614
+ const maxItems = Math.max(1, params.maxItems ?? 100);
1615
+ const buildCombinedKey = (p) => `combined:${p.sessionKey}:${p.combinedBody}`;
1616
+ const trim = () => {
1617
+ while (recentlySent.size > maxItems) {
1618
+ const firstKey = recentlySent.values().next().value;
1619
+ if (!firstKey) break;
1620
+ recentlySent.delete(firstKey);
1621
+ }
1622
+ };
1623
+ const rememberText = (text, opts) => {
1624
+ if (!text) return;
1625
+ recentlySent.add(text);
1626
+ if (opts.combinedBody && opts.combinedBodySessionKey) recentlySent.add(buildCombinedKey({
1627
+ sessionKey: opts.combinedBodySessionKey,
1628
+ combinedBody: opts.combinedBody
1629
+ }));
1630
+ if (opts.logVerboseMessage) params.logVerbose?.(`Added to echo detection set (size now: ${recentlySent.size}): ${text.substring(0, 50)}...`);
1631
+ trim();
1632
+ };
1633
+ return {
1634
+ rememberText,
1635
+ has: (key) => recentlySent.has(key),
1636
+ forget: (key) => {
1637
+ recentlySent.delete(key);
1638
+ },
1639
+ buildCombinedKey
1640
+ };
1641
+ }
1642
+
1643
+ //#endregion
1644
+ //#region src/monitor/broadcast.ts
1645
+ let _whatsappInboundLog$1;
1646
+ function getInboundLog$1() {
1647
+ _whatsappInboundLog$1 ??= createSubsystemLogger("gateway/channels/whatsapp").child("inbound");
1648
+ return _whatsappInboundLog$1;
1649
+ }
1650
+ async function maybeBroadcastMessage(params) {
1651
+ const broadcastAgents = params.cfg.broadcast?.[params.peerId];
1652
+ if (!broadcastAgents || !Array.isArray(broadcastAgents)) return false;
1653
+ if (broadcastAgents.length === 0) return false;
1654
+ const strategy = params.cfg.broadcast?.strategy || "parallel";
1655
+ getInboundLog$1().info(`Broadcasting message to ${broadcastAgents.length} agents (${strategy})`);
1656
+ const agentIds = params.cfg.agents?.list?.map((agent) => normalizeAgentId(agent.id));
1657
+ const hasKnownAgents = (agentIds?.length ?? 0) > 0;
1658
+ const groupHistorySnapshot = params.msg.chatType === "group" ? params.groupHistories.get(params.groupHistoryKey) ?? [] : void 0;
1659
+ const processForAgent = async (agentId) => {
1660
+ const normalizedAgentId = normalizeAgentId(agentId);
1661
+ if (hasKnownAgents && !agentIds?.includes(normalizedAgentId)) {
1662
+ getInboundLog$1().warn(`Broadcast agent ${agentId} not found in agents.list; skipping`);
1663
+ return false;
1664
+ }
1665
+ const agentRoute = {
1666
+ ...params.route,
1667
+ agentId: normalizedAgentId,
1668
+ sessionKey: buildAgentSessionKey({
1669
+ agentId: normalizedAgentId,
1670
+ channel: "whatsapp",
1671
+ accountId: params.route.accountId,
1672
+ peer: {
1673
+ kind: params.msg.chatType === "group" ? "group" : "direct",
1674
+ id: params.peerId
1675
+ },
1676
+ dmScope: params.cfg.session?.dmScope,
1677
+ identityLinks: params.cfg.session?.identityLinks
1678
+ }),
1679
+ mainSessionKey: buildAgentMainSessionKey({
1680
+ agentId: normalizedAgentId,
1681
+ mainKey: DEFAULT_MAIN_KEY
1682
+ })
1683
+ };
1684
+ try {
1685
+ return await params.processMessage(params.msg, agentRoute, params.groupHistoryKey, {
1686
+ groupHistory: groupHistorySnapshot,
1687
+ suppressGroupHistoryClear: true
1688
+ });
1689
+ } catch (err) {
1690
+ getInboundLog$1().error(`Broadcast agent ${agentId} failed: ${formatError(err)}`);
1691
+ return false;
1692
+ }
1693
+ };
1694
+ if (strategy === "sequential") for (const agentId of broadcastAgents) await processForAgent(agentId);
1695
+ else await Promise.allSettled(broadcastAgents.map(processForAgent));
1696
+ if (params.msg.chatType === "group") params.groupHistories.set(params.groupHistoryKey, []);
1697
+ return true;
1698
+ }
1699
+
1700
+ //#endregion
1701
+ //#region src/monitor/commands.ts
1702
+ function stripMentionsForCommand(text, mentionRegexes, selfE164) {
1703
+ let result = text;
1704
+ for (const re of mentionRegexes) result = result.replace(re, " ");
1705
+ if (selfE164) {
1706
+ const digits = selfE164.replace(/\D/g, "");
1707
+ if (digits) {
1708
+ const pattern = new RegExp(`\\+?${digits}`, "g");
1709
+ result = result.replace(pattern, " ");
1710
+ }
1711
+ }
1712
+ return result.replace(/\s+/g, " ").trim();
1713
+ }
1714
+
1715
+ //#endregion
1716
+ //#region src/monitor/group-activation.ts
1717
+ function resolveGroupPolicyFor(cfg, conversationId) {
1718
+ const groupId = resolveGroupSessionKey({
1719
+ From: conversationId,
1720
+ ChatType: "group",
1721
+ Provider: "whatsapp"
1722
+ })?.id;
1723
+ const whatsappCfg = cfg.channels?.whatsapp;
1724
+ const hasGroupAllowFrom = Boolean(whatsappCfg?.groupAllowFrom?.length || whatsappCfg?.allowFrom?.length);
1725
+ return resolveChannelGroupPolicy({
1726
+ cfg,
1727
+ channel: "whatsapp",
1728
+ groupId: groupId ?? conversationId,
1729
+ hasGroupAllowFrom
1730
+ });
1731
+ }
1732
+ function resolveGroupRequireMentionFor(cfg, conversationId) {
1733
+ const groupId = resolveGroupSessionKey({
1734
+ From: conversationId,
1735
+ ChatType: "group",
1736
+ Provider: "whatsapp"
1737
+ })?.id;
1738
+ return resolveChannelGroupRequireMention({
1739
+ cfg,
1740
+ channel: "whatsapp",
1741
+ groupId: groupId ?? conversationId
1742
+ });
1743
+ }
1744
+ function resolveGroupActivationFor(params) {
1745
+ const entry = loadSessionStore(resolveStorePath(params.cfg.session?.store, { agentId: params.agentId }))[params.sessionKey];
1746
+ const defaultActivation = !resolveGroupRequireMentionFor(params.cfg, params.conversationId) ? "always" : "mention";
1747
+ return normalizeGroupActivation(entry?.groupActivation) ?? defaultActivation;
1748
+ }
1749
+
1750
+ //#endregion
1751
+ //#region src/monitor/group-members.ts
1752
+ function appendNormalizedUnique(entries, seen, ordered) {
1753
+ for (const entry of entries) {
1754
+ const normalized = normalizeE164(entry) ?? entry;
1755
+ if (!normalized || seen.has(normalized)) continue;
1756
+ seen.add(normalized);
1757
+ ordered.push(normalized);
1758
+ }
1759
+ }
1760
+ function noteGroupMember(groupMemberNames, conversationId, e164, name) {
1761
+ if (!e164 || !name) return;
1762
+ const key = normalizeE164(e164) ?? e164;
1763
+ if (!key) return;
1764
+ let roster = groupMemberNames.get(conversationId);
1765
+ if (!roster) {
1766
+ roster = /* @__PURE__ */ new Map();
1767
+ groupMemberNames.set(conversationId, roster);
1768
+ }
1769
+ roster.set(key, name);
1770
+ }
1771
+ function formatGroupMembers(params) {
1772
+ const { participants, roster, fallbackE164 } = params;
1773
+ const seen = /* @__PURE__ */ new Set();
1774
+ const ordered = [];
1775
+ if (participants?.length) appendNormalizedUnique(participants, seen, ordered);
1776
+ if (roster) appendNormalizedUnique(roster.keys(), seen, ordered);
1777
+ if (ordered.length === 0 && fallbackE164) {
1778
+ const normalized = normalizeE164(fallbackE164) ?? fallbackE164;
1779
+ if (normalized) ordered.push(normalized);
1780
+ }
1781
+ if (ordered.length === 0) return;
1782
+ return ordered.map((entry) => {
1783
+ const name = roster?.get(entry);
1784
+ return name ? `${name} (${entry})` : entry;
1785
+ }).join(", ");
1786
+ }
1787
+
1788
+ //#endregion
1789
+ //#region src/monitor/group-gating.ts
1790
+ function isOwnerSender(baseMentionConfig, msg) {
1791
+ const sender = normalizeE164(msg.senderE164 ?? "");
1792
+ if (!sender) return false;
1793
+ return resolveOwnerList(baseMentionConfig, msg.selfE164 ?? void 0).includes(sender);
1794
+ }
1795
+ function recordPendingGroupHistoryEntry(params) {
1796
+ const sender = params.msg.senderName && params.msg.senderE164 ? `${params.msg.senderName} (${params.msg.senderE164})` : params.msg.senderName ?? params.msg.senderE164 ?? "Unknown";
1797
+ recordPendingHistoryEntryIfEnabled({
1798
+ historyMap: params.groupHistories,
1799
+ historyKey: params.groupHistoryKey,
1800
+ limit: params.groupHistoryLimit,
1801
+ entry: {
1802
+ sender,
1803
+ body: params.msg.body,
1804
+ timestamp: params.msg.timestamp,
1805
+ id: params.msg.id,
1806
+ senderJid: params.msg.senderJid
1807
+ }
1808
+ });
1809
+ }
1810
+ function skipGroupMessageAndStoreHistory(params, verboseMessage) {
1811
+ params.logVerbose(verboseMessage);
1812
+ recordPendingGroupHistoryEntry({
1813
+ msg: params.msg,
1814
+ groupHistories: params.groupHistories,
1815
+ groupHistoryKey: params.groupHistoryKey,
1816
+ groupHistoryLimit: params.groupHistoryLimit
1817
+ });
1818
+ return { shouldProcess: false };
1819
+ }
1820
+ function applyGroupGating(params) {
1821
+ const groupPolicy = resolveGroupPolicyFor(params.cfg, params.conversationId);
1822
+ if (groupPolicy.allowlistEnabled && !groupPolicy.allowed) {
1823
+ params.logVerbose(`Skipping group message ${params.conversationId} (not in allowlist)`);
1824
+ return { shouldProcess: false };
1825
+ }
1826
+ noteGroupMember(params.groupMemberNames, params.groupHistoryKey, params.msg.senderE164, params.msg.senderName);
1827
+ const mentionConfig = buildMentionConfig(params.cfg, params.agentId);
1828
+ const commandBody = stripMentionsForCommand(params.msg.body, mentionConfig.mentionRegexes, params.msg.selfE164);
1829
+ const activationCommand = parseActivationCommand(commandBody);
1830
+ const owner = isOwnerSender(params.baseMentionConfig, params.msg);
1831
+ const shouldBypassMention = owner && hasControlCommand(commandBody, params.cfg);
1832
+ if (activationCommand.hasCommand && !owner) return skipGroupMessageAndStoreHistory(params, `Ignoring /activation from non-owner in group ${params.conversationId}`);
1833
+ const mentionDebug = debugMention(params.msg, mentionConfig, params.authDir);
1834
+ params.replyLogger.debug({
1835
+ conversationId: params.conversationId,
1836
+ wasMentioned: mentionDebug.wasMentioned,
1837
+ ...mentionDebug.details
1838
+ }, "group mention debug");
1839
+ const wasMentioned = mentionDebug.wasMentioned;
1840
+ const requireMention = resolveGroupActivationFor({
1841
+ cfg: params.cfg,
1842
+ agentId: params.agentId,
1843
+ sessionKey: params.sessionKey,
1844
+ conversationId: params.conversationId
1845
+ }) !== "always";
1846
+ const selfJid = params.msg.selfJid?.replace(/:\d+/, "");
1847
+ const replySenderJid = params.msg.replyToSenderJid?.replace(/:\d+/, "");
1848
+ const selfE164 = params.msg.selfE164 ? normalizeE164(params.msg.selfE164) : null;
1849
+ const replySenderE164 = params.msg.replyToSenderE164 ? normalizeE164(params.msg.replyToSenderE164) : null;
1850
+ const mentionGate = resolveMentionGating({
1851
+ requireMention,
1852
+ canDetectMention: true,
1853
+ wasMentioned,
1854
+ implicitMention: Boolean(selfJid && replySenderJid && selfJid === replySenderJid || selfE164 && replySenderE164 && selfE164 === replySenderE164),
1855
+ shouldBypassMention
1856
+ });
1857
+ params.msg.wasMentioned = mentionGate.effectiveWasMentioned;
1858
+ if (!shouldBypassMention && requireMention && mentionGate.shouldSkip) return skipGroupMessageAndStoreHistory(params, `Group message stored for context (no mention detected) in ${params.conversationId}: ${params.msg.body}`);
1859
+ return { shouldProcess: true };
1860
+ }
1861
+
1862
+ //#endregion
1863
+ //#region src/monitor/last-route.ts
1864
+ function trackBackgroundTask(backgroundTasks, task) {
1865
+ backgroundTasks.add(task);
1866
+ task.finally(() => {
1867
+ backgroundTasks.delete(task);
1868
+ });
1869
+ }
1870
+ function updateLastRouteInBackground(params) {
1871
+ const storePath = resolveStorePath(params.cfg.session?.store, { agentId: params.storeAgentId });
1872
+ const task = updateLastRoute({
1873
+ storePath,
1874
+ sessionKey: params.sessionKey,
1875
+ deliveryContext: {
1876
+ channel: params.channel,
1877
+ to: params.to,
1878
+ accountId: params.accountId
1879
+ },
1880
+ ctx: params.ctx
1881
+ }).catch((err) => {
1882
+ params.warn({
1883
+ error: formatError(err),
1884
+ storePath,
1885
+ sessionKey: params.sessionKey,
1886
+ to: params.to
1887
+ }, "failed updating last route");
1888
+ });
1889
+ trackBackgroundTask(params.backgroundTasks, task);
1890
+ }
1891
+
1892
+ //#endregion
1893
+ //#region src/monitor/peer.ts
1894
+ function resolvePeerId(msg) {
1895
+ if (msg.chatType === "group") return msg.conversationId ?? msg.from;
1896
+ if (msg.senderE164) return normalizeE164(msg.senderE164) ?? msg.senderE164;
1897
+ if (msg.from.includes("@")) return jidToE164(msg.from) ?? msg.from;
1898
+ return normalizeE164(msg.from) ?? msg.from;
1899
+ }
1900
+
1901
+ //#endregion
1902
+ //#region src/reconnect.ts
1903
+ const DEFAULT_HEARTBEAT_SECONDS = 60;
1904
+ const DEFAULT_RECONNECT_POLICY = {
1905
+ initialMs: 2e3,
1906
+ maxMs: 6e4,
1907
+ factor: 1.8,
1908
+ jitter: .25,
1909
+ maxAttempts: 0
1910
+ };
1911
+ function clamp(value, min, max) {
1912
+ return Math.min(Math.max(value, min), max);
1913
+ }
1914
+ function resolveHeartbeatSeconds(cfg, overrideSeconds) {
1915
+ const cfgAny = cfg;
1916
+ const candidate = overrideSeconds ?? (cfgAny.channels?.whatsapp)?.heartbeatSeconds ?? cfgAny.web?.heartbeatSeconds;
1917
+ if (typeof candidate === "number" && candidate > 0) return candidate;
1918
+ return DEFAULT_HEARTBEAT_SECONDS;
1919
+ }
1920
+ function resolveReconnectPolicy(cfg, overrides) {
1921
+ const cfgAny = cfg;
1922
+ const reconnectOverrides = (cfgAny.channels?.whatsapp)?.reconnect ?? cfgAny.web?.reconnect ?? {};
1923
+ const merged = {
1924
+ ...DEFAULT_RECONNECT_POLICY,
1925
+ ...reconnectOverrides,
1926
+ ...overrides ?? {}
1927
+ };
1928
+ merged.initialMs = Math.max(250, merged.initialMs);
1929
+ merged.maxMs = Math.max(merged.initialMs, merged.maxMs);
1930
+ merged.factor = clamp(merged.factor, 1.1, 10);
1931
+ merged.jitter = clamp(merged.jitter, 0, 1);
1932
+ merged.maxAttempts = Math.max(0, Math.floor(merged.maxAttempts));
1933
+ return merged;
1934
+ }
1935
+ function newConnectionId() {
1936
+ return randomUUID();
1937
+ }
1938
+
1939
+ //#endregion
1940
+ //#region src/util.ts
1941
+ function elide(text, limit = 400) {
1942
+ if (!text) return text;
1943
+ if (text.length <= limit) return text;
1944
+ return `${text.slice(0, limit)}… (truncated ${text.length - limit} chars)`;
1945
+ }
1946
+ function isLikelyWhatsAppCryptoError(reason) {
1947
+ const formatReason = (value) => {
1948
+ if (value == null) return "";
1949
+ if (typeof value === "string") return value;
1950
+ if (value instanceof Error) return `${value.message}\n${value.stack ?? ""}`;
1951
+ if (typeof value === "object") try {
1952
+ return JSON.stringify(value);
1953
+ } catch {
1954
+ return Object.prototype.toString.call(value);
1955
+ }
1956
+ if (typeof value === "number") return String(value);
1957
+ if (typeof value === "boolean") return String(value);
1958
+ if (typeof value === "bigint") return String(value);
1959
+ if (typeof value === "symbol") return value.description ?? value.toString();
1960
+ if (typeof value === "function") return value.name ? `[function ${value.name}]` : "[function]";
1961
+ return Object.prototype.toString.call(value);
1962
+ };
1963
+ const haystack = (reason instanceof Error ? `${reason.message}\n${reason.stack ?? ""}` : formatReason(reason)).toLowerCase();
1964
+ if (!(haystack.includes("unsupported state or unable to authenticate data") || haystack.includes("bad mac"))) return false;
1965
+ return haystack.includes("@whiskeysockets/baileys") || haystack.includes("baileys") || haystack.includes("noise-handler") || haystack.includes("aesdecryptgcm");
1966
+ }
1967
+
1968
+ //#endregion
1969
+ //#region src/deliver-reply.ts
1970
+ let _whatsappOutboundLog$1;
1971
+ function getOutboundLog$1() {
1972
+ _whatsappOutboundLog$1 ??= createSubsystemLogger("gateway/channels/whatsapp").child("outbound");
1973
+ return _whatsappOutboundLog$1;
1974
+ }
1975
+ const REASONING_PREFIX = "reasoning:";
1976
+ function shouldSuppressReasoningReply(payload) {
1977
+ if (payload.isReasoning === true) return true;
1978
+ const text = payload.text;
1979
+ if (typeof text !== "string") return false;
1980
+ return text.trimStart().toLowerCase().startsWith(REASONING_PREFIX);
1981
+ }
1982
+ async function deliverWebReply(params) {
1983
+ const { replyResult, msg, maxMediaBytes, textLimit, replyLogger, connectionId, skipLog } = params;
1984
+ const replyStarted = Date.now();
1985
+ if (shouldSuppressReasoningReply(replyResult)) {
1986
+ getOutboundLog$1().debug(`Suppressed reasoning payload to ${msg.from}`);
1987
+ return;
1988
+ }
1989
+ const tableMode = params.tableMode ?? "code";
1990
+ const chunkMode = params.chunkMode ?? "length";
1991
+ const pack = params.pack;
1992
+ const textChunks = chunkMarkdownTextWithMode(markdownToWhatsApp(convertMarkdownTables(replyResult.text || "", tableMode)), textLimit, chunkMode, { pack });
1993
+ const mediaList = replyResult.mediaUrls?.length ? replyResult.mediaUrls : replyResult.mediaUrl ? [replyResult.mediaUrl] : [];
1994
+ const sendWithRetry = async (fn, label, maxAttempts = 3) => {
1995
+ let lastErr;
1996
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
1997
+ return await fn();
1998
+ } catch (err) {
1999
+ lastErr = err;
2000
+ const errText = formatError(err);
2001
+ const isLast = attempt === maxAttempts;
2002
+ if (!/closed|reset|timed\s*out|disconnect/i.test(errText) || isLast) throw err;
2003
+ const backoffMs = 500 * attempt;
2004
+ logVerbose(`Retrying ${label} to ${msg.from} after failure (${attempt}/${maxAttempts - 1}) in ${backoffMs}ms: ${errText}`);
2005
+ await sleep(backoffMs);
2006
+ }
2007
+ throw lastErr;
2008
+ };
2009
+ if (mediaList.length === 0 && textChunks.length) {
2010
+ const totalChunks = textChunks.length;
2011
+ for (const [index, chunk] of textChunks.entries()) {
2012
+ const chunkStarted = Date.now();
2013
+ await sendWithRetry(() => msg.reply(chunk), "text");
2014
+ if (!skipLog) {
2015
+ const durationMs = Date.now() - chunkStarted;
2016
+ getOutboundLog$1().debug(`Sent chunk ${index + 1}/${totalChunks} to ${msg.from} (${durationMs.toFixed(0)}ms)`);
2017
+ }
2018
+ }
2019
+ replyLogger.info({
2020
+ correlationId: msg.id ?? newConnectionId(),
2021
+ connectionId: connectionId ?? null,
2022
+ to: msg.from,
2023
+ from: msg.to,
2024
+ text: elide(replyResult.text, 240),
2025
+ mediaUrl: null,
2026
+ mediaSizeBytes: null,
2027
+ mediaKind: null,
2028
+ durationMs: Date.now() - replyStarted
2029
+ }, "auto-reply sent (text)");
2030
+ return;
2031
+ }
2032
+ const remainingText = [...textChunks];
2033
+ for (const [index, mediaUrl] of mediaList.entries()) {
2034
+ const caption = index === 0 ? remainingText.shift() || void 0 : void 0;
2035
+ try {
2036
+ const media = await loadWebMedia(mediaUrl, {
2037
+ maxBytes: maxMediaBytes,
2038
+ localRoots: params.mediaLocalRoots
2039
+ });
2040
+ if (shouldLogVerbose()) {
2041
+ logVerbose(`Web auto-reply media size: ${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB`);
2042
+ logVerbose(`Web auto-reply media source: ${mediaUrl} (kind ${media.kind})`);
2043
+ }
2044
+ if (media.kind === "image") await sendWithRetry(() => msg.sendMedia({
2045
+ image: media.buffer,
2046
+ caption,
2047
+ mimetype: media.contentType
2048
+ }), "media:image");
2049
+ else if (media.kind === "audio") {
2050
+ await sendWithRetry(() => msg.sendMedia({
2051
+ audio: media.buffer,
2052
+ ptt: true,
2053
+ mimetype: media.contentType
2054
+ }), "media:audio");
2055
+ if (caption) await sendWithRetry(() => msg.reply(caption), "text");
2056
+ } else if (media.kind === "video") await sendWithRetry(() => msg.sendMedia({
2057
+ video: media.buffer,
2058
+ caption,
2059
+ mimetype: media.contentType
2060
+ }), "media:video");
2061
+ else {
2062
+ const fileName = media.fileName ?? mediaUrl.split("/").pop() ?? "file";
2063
+ const mimetype = media.contentType ?? "application/octet-stream";
2064
+ await sendWithRetry(() => msg.sendMedia({
2065
+ document: media.buffer,
2066
+ fileName,
2067
+ caption,
2068
+ mimetype
2069
+ }), "media:document");
2070
+ }
2071
+ getOutboundLog$1().info(`Sent media reply to ${msg.from} (${(media.buffer.length / (1024 * 1024)).toFixed(2)}MB)`);
2072
+ replyLogger.info({
2073
+ correlationId: msg.id ?? newConnectionId(),
2074
+ connectionId: connectionId ?? null,
2075
+ to: msg.from,
2076
+ from: msg.to,
2077
+ text: caption ?? null,
2078
+ mediaUrl,
2079
+ mediaSizeBytes: media.buffer.length,
2080
+ mediaKind: media.kind,
2081
+ durationMs: Date.now() - replyStarted
2082
+ }, "auto-reply sent (media)");
2083
+ } catch (err) {
2084
+ getOutboundLog$1().error(`Failed sending web media to ${msg.from}: ${formatError(err)}`);
2085
+ replyLogger.warn({
2086
+ err,
2087
+ mediaUrl
2088
+ }, "failed to send web media reply");
2089
+ if (index === 0) {
2090
+ const warning = err instanceof Error ? `⚠️ Media failed: ${err.message}` : "⚠️ Media failed.";
2091
+ const fallbackText = [remainingText.shift() ?? caption ?? "", warning].filter(Boolean).join("\n");
2092
+ if (fallbackText) {
2093
+ getOutboundLog$1().warn(`Media skipped; sent text-only to ${msg.from}`);
2094
+ await msg.reply(fallbackText);
2095
+ }
2096
+ }
2097
+ }
2098
+ }
2099
+ for (const chunk of remainingText) await msg.reply(chunk);
2100
+ }
2101
+
2102
+ //#endregion
2103
+ //#region src/monitor/ack-reaction.ts
2104
+ function maybeSendAckReaction(params) {
2105
+ if (!params.msg.id) return;
2106
+ const ackConfig = params.cfg.channels?.whatsapp?.ackReaction;
2107
+ const emoji = (ackConfig?.emoji ?? "").trim();
2108
+ const directEnabled = ackConfig?.direct ?? true;
2109
+ const groupMode = ackConfig?.group ?? "mentions";
2110
+ const conversationIdForCheck = params.msg.conversationId ?? params.msg.from;
2111
+ const activation = params.msg.chatType === "group" ? resolveGroupActivationFor({
2112
+ cfg: params.cfg,
2113
+ agentId: params.agentId,
2114
+ sessionKey: params.sessionKey,
2115
+ conversationId: conversationIdForCheck
2116
+ }) : null;
2117
+ const shouldSendReaction = () => shouldAckReactionForWhatsApp({
2118
+ emoji,
2119
+ isDirect: params.msg.chatType === "direct",
2120
+ isGroup: params.msg.chatType === "group",
2121
+ directEnabled,
2122
+ groupMode,
2123
+ wasMentioned: params.msg.wasMentioned === true,
2124
+ groupActivated: activation === "always"
2125
+ });
2126
+ if (!shouldSendReaction()) return;
2127
+ params.info({
2128
+ chatId: params.msg.chatId,
2129
+ messageId: params.msg.id,
2130
+ emoji
2131
+ }, "sending ack reaction");
2132
+ sendReactionWhatsApp(params.msg.chatId, params.msg.id, emoji, {
2133
+ verbose: params.verbose,
2134
+ fromMe: false,
2135
+ participant: params.msg.senderJid,
2136
+ accountId: params.accountId
2137
+ }).catch((err) => {
2138
+ params.warn({
2139
+ error: formatError(err),
2140
+ chatId: params.msg.chatId,
2141
+ messageId: params.msg.id
2142
+ }, "failed to send ack reaction");
2143
+ logVerbose(`WhatsApp ack reaction failed for chat ${params.msg.chatId}: ${formatError(err)}`);
2144
+ });
2145
+ }
2146
+
2147
+ //#endregion
2148
+ //#region src/monitor/message-line.ts
2149
+ function formatReplyContext(msg) {
2150
+ if (!msg.replyToBody) return null;
2151
+ return `[Replying to ${msg.replyToSender ?? "unknown sender"}${msg.replyToId ? ` id:${msg.replyToId}` : ""}]\n${msg.replyToBody}\n[/Replying]`;
2152
+ }
2153
+ function buildInboundLine(params) {
2154
+ const { cfg, msg, agentId, previousTimestamp, envelope } = params;
2155
+ const messagePrefix = resolveMessagePrefix(cfg, agentId, {
2156
+ configured: cfg.channels?.whatsapp?.messagePrefix,
2157
+ hasAllowFrom: (cfg.channels?.whatsapp?.allowFrom?.length ?? 0) > 0
2158
+ });
2159
+ const prefixStr = messagePrefix ? `${messagePrefix} ` : "";
2160
+ const replyContext = formatReplyContext(msg);
2161
+ const baseLine = `${prefixStr}${msg.body}${replyContext ? `\n\n${replyContext}` : ""}`;
2162
+ return formatInboundEnvelope({
2163
+ channel: "WhatsApp",
2164
+ from: msg.chatType === "group" ? msg.from : msg.from?.replace(/^whatsapp:/, ""),
2165
+ timestamp: msg.timestamp,
2166
+ body: baseLine,
2167
+ chatType: msg.chatType,
2168
+ sender: {
2169
+ name: msg.senderName,
2170
+ e164: msg.senderE164,
2171
+ id: msg.senderJid
2172
+ },
2173
+ previousTimestamp,
2174
+ envelope,
2175
+ fromMe: msg.fromMe
2176
+ });
2177
+ }
2178
+
2179
+ //#endregion
2180
+ //#region src/monitor/process-message.ts
2181
+ let _whatsappInboundLog;
2182
+ let _whatsappOutboundLog;
2183
+ function getInboundLog() {
2184
+ _whatsappInboundLog ??= createSubsystemLogger("gateway/channels/whatsapp").child("inbound");
2185
+ return _whatsappInboundLog;
2186
+ }
2187
+ function getOutboundLog() {
2188
+ _whatsappOutboundLog ??= createSubsystemLogger("gateway/channels/whatsapp").child("outbound");
2189
+ return _whatsappOutboundLog;
2190
+ }
2191
+ async function resolveWhatsAppCommandAuthorized(params) {
2192
+ const useAccessGroups = params.cfg.commands?.useAccessGroups !== false;
2193
+ if (!useAccessGroups) return true;
2194
+ const isGroup = params.msg.chatType === "group";
2195
+ const senderE164 = normalizeE164(isGroup ? params.msg.senderE164 ?? "" : params.msg.senderE164 ?? params.msg.from ?? "");
2196
+ if (!senderE164) return false;
2197
+ const account = resolveWhatsAppAccount$1({
2198
+ cfg: params.cfg,
2199
+ accountId: params.msg.accountId
2200
+ });
2201
+ const dmPolicy = account.dmPolicy ?? "pairing";
2202
+ const groupPolicy = account.groupPolicy ?? "allowlist";
2203
+ const configuredAllowFrom = account.allowFrom ?? [];
2204
+ const configuredGroupAllowFrom = account.groupAllowFrom ?? (configuredAllowFrom.length > 0 ? configuredAllowFrom : void 0);
2205
+ const storeAllowFrom = isGroup ? [] : await readStoreAllowFromForDmPolicy({
2206
+ provider: "whatsapp",
2207
+ accountId: params.msg.accountId,
2208
+ dmPolicy
2209
+ });
2210
+ return resolveDmGroupAccessWithCommandGate({
2211
+ isGroup,
2212
+ dmPolicy,
2213
+ groupPolicy,
2214
+ allowFrom: configuredAllowFrom.length > 0 ? configuredAllowFrom : params.msg.selfE164 ? [params.msg.selfE164] : [],
2215
+ groupAllowFrom: configuredGroupAllowFrom,
2216
+ storeAllowFrom,
2217
+ isSenderAllowed: (allowEntries) => {
2218
+ if (allowEntries.includes("*")) return true;
2219
+ return allowEntries.map((entry) => normalizeE164(String(entry))).filter((entry) => Boolean(entry)).includes(senderE164);
2220
+ },
2221
+ command: {
2222
+ useAccessGroups,
2223
+ allowTextCommands: true,
2224
+ hasControlCommand: true
2225
+ }
2226
+ }).commandAuthorized;
2227
+ }
2228
+ function resolvePinnedMainDmRecipient(params) {
2229
+ const account = resolveWhatsAppAccount$1({
2230
+ cfg: params.cfg,
2231
+ accountId: params.msg.accountId
2232
+ });
2233
+ return resolvePinnedMainDmOwnerFromAllowlist({
2234
+ dmScope: params.cfg.session?.dmScope,
2235
+ allowFrom: account.allowFrom,
2236
+ normalizeEntry: (entry) => normalizeE164(entry)
2237
+ });
2238
+ }
2239
+ async function processMessage(params) {
2240
+ const conversationId = params.msg.conversationId ?? params.msg.from;
2241
+ const { storePath, envelopeOptions, previousTimestamp } = resolveInboundSessionEnvelopeContext({
2242
+ cfg: params.cfg,
2243
+ agentId: params.route.agentId,
2244
+ sessionKey: params.route.sessionKey
2245
+ });
2246
+ let combinedBody = buildInboundLine({
2247
+ cfg: params.cfg,
2248
+ msg: params.msg,
2249
+ agentId: params.route.agentId,
2250
+ previousTimestamp,
2251
+ envelope: envelopeOptions
2252
+ });
2253
+ let shouldClearGroupHistory = false;
2254
+ if (params.msg.chatType === "group") {
2255
+ const history = params.groupHistory ?? params.groupHistories.get(params.groupHistoryKey) ?? [];
2256
+ if (history.length > 0) combinedBody = buildHistoryContextFromEntries({
2257
+ entries: history.map((m) => ({
2258
+ sender: m.sender,
2259
+ body: m.body,
2260
+ timestamp: m.timestamp
2261
+ })),
2262
+ currentMessage: combinedBody,
2263
+ excludeLast: false,
2264
+ formatEntry: (entry) => {
2265
+ return formatInboundEnvelope({
2266
+ channel: "WhatsApp",
2267
+ from: conversationId,
2268
+ timestamp: entry.timestamp,
2269
+ body: entry.body,
2270
+ chatType: "group",
2271
+ senderLabel: entry.sender,
2272
+ envelope: envelopeOptions
2273
+ });
2274
+ }
2275
+ });
2276
+ shouldClearGroupHistory = !(params.suppressGroupHistoryClear ?? false);
2277
+ }
2278
+ const combinedEchoKey = params.buildCombinedEchoKey({
2279
+ sessionKey: params.route.sessionKey,
2280
+ combinedBody
2281
+ });
2282
+ if (params.echoHas(combinedEchoKey)) {
2283
+ logVerbose("Skipping auto-reply: detected echo for combined message");
2284
+ params.echoForget(combinedEchoKey);
2285
+ return false;
2286
+ }
2287
+ maybeSendAckReaction({
2288
+ cfg: params.cfg,
2289
+ msg: params.msg,
2290
+ agentId: params.route.agentId,
2291
+ sessionKey: params.route.sessionKey,
2292
+ conversationId,
2293
+ verbose: params.verbose,
2294
+ accountId: params.route.accountId,
2295
+ info: params.replyLogger.info.bind(params.replyLogger),
2296
+ warn: params.replyLogger.warn.bind(params.replyLogger)
2297
+ });
2298
+ const correlationId = params.msg.id ?? newConnectionId();
2299
+ params.replyLogger.info({
2300
+ connectionId: params.connectionId,
2301
+ correlationId,
2302
+ from: params.msg.chatType === "group" ? conversationId : params.msg.from,
2303
+ to: params.msg.to,
2304
+ body: elide(combinedBody, 240),
2305
+ mediaType: params.msg.mediaType ?? null,
2306
+ mediaPath: params.msg.mediaPath ?? null
2307
+ }, "inbound web message");
2308
+ const fromDisplay = params.msg.chatType === "group" ? conversationId : params.msg.from;
2309
+ const kindLabel = params.msg.mediaType ? `, ${params.msg.mediaType}` : "";
2310
+ getInboundLog().info(`Inbound message ${fromDisplay} -> ${params.msg.to} (${params.msg.chatType}${kindLabel}, ${combinedBody.length} chars)`);
2311
+ if (shouldLogVerbose()) getInboundLog().debug(`Inbound body: ${elide(combinedBody, 400)}`);
2312
+ const dmRouteTarget = params.msg.chatType !== "group" ? (() => {
2313
+ if (params.msg.senderE164) return normalizeE164(params.msg.senderE164);
2314
+ if (params.msg.from.includes("@")) return jidToE164(params.msg.from);
2315
+ return normalizeE164(params.msg.from);
2316
+ })() : void 0;
2317
+ const textLimit = params.maxMediaTextChunkLimit ?? resolveTextChunkLimit(params.cfg, "whatsapp");
2318
+ const chunkMode = resolveChunkMode(params.cfg, "whatsapp", params.route.accountId);
2319
+ const pack = resolveChunkNewlinePacking(params.cfg, "whatsapp", params.route.accountId);
2320
+ const tableMode = resolveMarkdownTableMode({
2321
+ cfg: params.cfg,
2322
+ channel: "whatsapp",
2323
+ accountId: params.route.accountId
2324
+ });
2325
+ const mediaLocalRoots = getAgentScopedMediaLocalRoots(params.cfg, params.route.agentId);
2326
+ let didLogHeartbeatStrip = false;
2327
+ let didSendReply = false;
2328
+ const commandAuthorized = shouldComputeCommandAuthorized(params.msg.body, params.cfg) ? await resolveWhatsAppCommandAuthorized({
2329
+ cfg: params.cfg,
2330
+ msg: params.msg
2331
+ }) : void 0;
2332
+ const configuredResponsePrefix = params.cfg.messages?.responsePrefix;
2333
+ const { onModelSelected, ...prefixOptions } = createReplyPrefixOptions({
2334
+ cfg: params.cfg,
2335
+ agentId: params.route.agentId,
2336
+ channel: "whatsapp",
2337
+ accountId: params.route.accountId
2338
+ });
2339
+ const isSelfChat = params.msg.chatType !== "group" && Boolean(params.msg.selfE164) && normalizeE164(params.msg.from) === normalizeE164(params.msg.selfE164 ?? "");
2340
+ const responsePrefix = prefixOptions.responsePrefix ?? (configuredResponsePrefix === void 0 && isSelfChat ? resolveIdentityNamePrefix(params.cfg, params.route.agentId) ?? "[openclaw]" : void 0);
2341
+ const inboundHistory = params.msg.chatType === "group" ? (params.groupHistory ?? params.groupHistories.get(params.groupHistoryKey) ?? []).map((entry) => ({
2342
+ sender: entry.sender,
2343
+ body: entry.body,
2344
+ timestamp: entry.timestamp
2345
+ })) : void 0;
2346
+ const ctxPayload = finalizeInboundContext({
2347
+ Body: combinedBody,
2348
+ BodyForAgent: params.msg.body,
2349
+ InboundHistory: inboundHistory,
2350
+ RawBody: params.msg.body,
2351
+ CommandBody: params.msg.body,
2352
+ From: params.msg.from,
2353
+ To: params.msg.to,
2354
+ SessionKey: params.route.sessionKey,
2355
+ AccountId: params.route.accountId,
2356
+ MessageSid: params.msg.id,
2357
+ ReplyToId: params.msg.replyToId,
2358
+ ReplyToBody: params.msg.replyToBody,
2359
+ ReplyToSender: params.msg.replyToSender,
2360
+ MediaPath: params.msg.mediaPath,
2361
+ MediaUrl: params.msg.mediaUrl,
2362
+ MediaType: params.msg.mediaType,
2363
+ ChatType: params.msg.chatType,
2364
+ ConversationLabel: params.msg.chatType === "group" ? conversationId : params.msg.from,
2365
+ GroupSubject: params.msg.groupSubject,
2366
+ GroupMembers: formatGroupMembers({
2367
+ participants: params.msg.groupParticipants,
2368
+ roster: params.groupMemberNames.get(params.groupHistoryKey),
2369
+ fallbackE164: params.msg.senderE164
2370
+ }),
2371
+ SenderName: params.msg.senderName,
2372
+ SenderId: params.msg.senderJid?.trim() || params.msg.senderE164,
2373
+ SenderE164: params.msg.senderE164,
2374
+ CommandAuthorized: commandAuthorized,
2375
+ WasMentioned: params.msg.wasMentioned,
2376
+ ...params.msg.location ? toLocationContext(params.msg.location) : {},
2377
+ Provider: "whatsapp",
2378
+ Surface: "whatsapp",
2379
+ OriginatingChannel: "whatsapp",
2380
+ OriginatingTo: params.msg.from
2381
+ });
2382
+ const pinnedMainDmRecipient = resolvePinnedMainDmRecipient({
2383
+ cfg: params.cfg,
2384
+ msg: params.msg
2385
+ });
2386
+ const shouldUpdateMainLastRoute = !pinnedMainDmRecipient || pinnedMainDmRecipient === dmRouteTarget;
2387
+ if (dmRouteTarget && params.route.sessionKey === params.route.mainSessionKey && shouldUpdateMainLastRoute) updateLastRouteInBackground({
2388
+ cfg: params.cfg,
2389
+ backgroundTasks: params.backgroundTasks,
2390
+ storeAgentId: params.route.agentId,
2391
+ sessionKey: params.route.mainSessionKey,
2392
+ channel: "whatsapp",
2393
+ to: dmRouteTarget,
2394
+ accountId: params.route.accountId,
2395
+ ctx: ctxPayload,
2396
+ warn: params.replyLogger.warn.bind(params.replyLogger)
2397
+ });
2398
+ else if (dmRouteTarget && params.route.sessionKey === params.route.mainSessionKey && pinnedMainDmRecipient) logVerbose(`Skipping main-session last route update for ${dmRouteTarget} (pinned owner ${pinnedMainDmRecipient})`);
2399
+ const metaTask = recordSessionMetaFromInbound({
2400
+ storePath,
2401
+ sessionKey: params.route.sessionKey,
2402
+ ctx: ctxPayload
2403
+ }).catch((err) => {
2404
+ params.replyLogger.warn({
2405
+ error: formatError(err),
2406
+ storePath,
2407
+ sessionKey: params.route.sessionKey
2408
+ }, "failed updating session meta");
2409
+ });
2410
+ trackBackgroundTask(params.backgroundTasks, metaTask);
2411
+ const { queuedFinal } = await dispatchReplyWithBufferedBlockDispatcher({
2412
+ ctx: ctxPayload,
2413
+ cfg: params.cfg,
2414
+ replyResolver: params.replyResolver,
2415
+ dispatcherOptions: {
2416
+ ...prefixOptions,
2417
+ responsePrefix,
2418
+ onHeartbeatStrip: () => {
2419
+ if (!didLogHeartbeatStrip) {
2420
+ didLogHeartbeatStrip = true;
2421
+ logVerbose("Stripped stray HEARTBEAT_OK token from web reply");
2422
+ }
2423
+ },
2424
+ deliver: async (payload, info) => {
2425
+ if (info.kind !== "final") return;
2426
+ await deliverWebReply({
2427
+ replyResult: payload,
2428
+ msg: params.msg,
2429
+ mediaLocalRoots,
2430
+ maxMediaBytes: params.maxMediaBytes,
2431
+ textLimit,
2432
+ chunkMode,
2433
+ pack,
2434
+ replyLogger: params.replyLogger,
2435
+ connectionId: params.connectionId,
2436
+ skipLog: false,
2437
+ tableMode
2438
+ });
2439
+ didSendReply = true;
2440
+ const shouldLog = payload.text ? true : void 0;
2441
+ params.rememberSentText(payload.text, {
2442
+ combinedBody,
2443
+ combinedBodySessionKey: params.route.sessionKey,
2444
+ logVerboseMessage: shouldLog
2445
+ });
2446
+ const fromDisplay = params.msg.chatType === "group" ? conversationId : params.msg.from ?? "unknown";
2447
+ const hasMedia = Boolean(payload.mediaUrl || payload.mediaUrls?.length);
2448
+ getOutboundLog().info(`Auto-replied to ${fromDisplay}${hasMedia ? " (media)" : ""}`);
2449
+ if (shouldLogVerbose()) {
2450
+ const preview = payload.text != null ? elide(payload.text, 400) : "<media>";
2451
+ getOutboundLog().debug(`Reply body: ${preview}${hasMedia ? " (media)" : ""}`);
2452
+ }
2453
+ },
2454
+ onError: (err, info) => {
2455
+ const label = info.kind === "tool" ? "tool update" : info.kind === "block" ? "block update" : "auto-reply";
2456
+ getOutboundLog().error(`Failed sending web ${label} to ${params.msg.from ?? conversationId}: ${formatError(err)}`);
2457
+ },
2458
+ onReplyStart: params.msg.sendComposing
2459
+ },
2460
+ replyOptions: {
2461
+ disableBlockStreaming: true,
2462
+ onModelSelected
2463
+ }
2464
+ });
2465
+ if (!queuedFinal) {
2466
+ if (shouldClearGroupHistory) params.groupHistories.set(params.groupHistoryKey, []);
2467
+ logVerbose("Skipping auto-reply: silent token or no text/media returned from resolver");
2468
+ return false;
2469
+ }
2470
+ if (shouldClearGroupHistory) params.groupHistories.set(params.groupHistoryKey, []);
2471
+ return didSendReply;
2472
+ }
2473
+
2474
+ //#endregion
2475
+ //#region src/monitor/on-message.ts
2476
+ function createWebOnMessageHandler(params) {
2477
+ const processForRoute = async (msg, route, groupHistoryKey, opts) => processMessage({
2478
+ cfg: params.cfg,
2479
+ msg,
2480
+ route,
2481
+ groupHistoryKey,
2482
+ groupHistories: params.groupHistories,
2483
+ groupMemberNames: params.groupMemberNames,
2484
+ connectionId: params.connectionId,
2485
+ verbose: params.verbose,
2486
+ maxMediaBytes: params.maxMediaBytes,
2487
+ replyResolver: params.replyResolver,
2488
+ replyLogger: params.replyLogger,
2489
+ backgroundTasks: params.backgroundTasks,
2490
+ rememberSentText: params.echoTracker.rememberText,
2491
+ echoHas: params.echoTracker.has,
2492
+ echoForget: params.echoTracker.forget,
2493
+ buildCombinedEchoKey: params.echoTracker.buildCombinedKey,
2494
+ groupHistory: opts?.groupHistory,
2495
+ suppressGroupHistoryClear: opts?.suppressGroupHistoryClear
2496
+ });
2497
+ return async (msg) => {
2498
+ const conversationId = msg.conversationId ?? msg.from;
2499
+ const peerId = resolvePeerId(msg);
2500
+ const route = resolveAgentRoute({
2501
+ cfg: loadConfig(),
2502
+ channel: "whatsapp",
2503
+ accountId: msg.accountId,
2504
+ peer: {
2505
+ kind: msg.chatType === "group" ? "group" : "direct",
2506
+ id: peerId
2507
+ }
2508
+ });
2509
+ const groupHistoryKey = msg.chatType === "group" ? buildGroupHistoryKey({
2510
+ channel: "whatsapp",
2511
+ accountId: route.accountId,
2512
+ peerKind: "group",
2513
+ peerId
2514
+ }) : route.sessionKey;
2515
+ if (msg.from === msg.to) logVerbose(`\u{1F4F1} Same-phone mode detected (from === to: ${msg.from})`);
2516
+ if (params.echoTracker.has(msg.body)) {
2517
+ logVerbose("Skipping auto-reply: detected echo (message matches recently sent text)");
2518
+ params.echoTracker.forget(msg.body);
2519
+ return;
2520
+ }
2521
+ if (msg.chatType === "group") {
2522
+ const metaCtx = {
2523
+ From: msg.from,
2524
+ To: msg.to,
2525
+ SessionKey: route.sessionKey,
2526
+ AccountId: route.accountId,
2527
+ ChatType: msg.chatType,
2528
+ ConversationLabel: conversationId,
2529
+ GroupSubject: msg.groupSubject,
2530
+ SenderName: msg.senderName,
2531
+ SenderId: msg.senderJid?.trim() || msg.senderE164,
2532
+ SenderE164: msg.senderE164,
2533
+ Provider: "whatsapp",
2534
+ Surface: "whatsapp",
2535
+ OriginatingChannel: "whatsapp",
2536
+ OriginatingTo: conversationId
2537
+ };
2538
+ updateLastRouteInBackground({
2539
+ cfg: params.cfg,
2540
+ backgroundTasks: params.backgroundTasks,
2541
+ storeAgentId: route.agentId,
2542
+ sessionKey: route.sessionKey,
2543
+ channel: "whatsapp",
2544
+ to: conversationId,
2545
+ accountId: route.accountId,
2546
+ ctx: metaCtx,
2547
+ warn: params.replyLogger.warn.bind(params.replyLogger)
2548
+ });
2549
+ if (!applyGroupGating({
2550
+ cfg: params.cfg,
2551
+ msg,
2552
+ conversationId,
2553
+ groupHistoryKey,
2554
+ agentId: route.agentId,
2555
+ sessionKey: route.sessionKey,
2556
+ baseMentionConfig: params.baseMentionConfig,
2557
+ authDir: params.account.authDir,
2558
+ groupHistories: params.groupHistories,
2559
+ groupHistoryLimit: params.groupHistoryLimit,
2560
+ groupMemberNames: params.groupMemberNames,
2561
+ logVerbose,
2562
+ replyLogger: params.replyLogger
2563
+ }).shouldProcess) return;
2564
+ } else if (!msg.senderE164 && peerId && peerId.startsWith("+")) msg.senderE164 = normalizeE164(peerId) ?? msg.senderE164;
2565
+ if (await maybeBroadcastMessage({
2566
+ cfg: params.cfg,
2567
+ msg,
2568
+ peerId,
2569
+ route,
2570
+ groupHistoryKey,
2571
+ groupHistories: params.groupHistories,
2572
+ processMessage: processForRoute
2573
+ })) return;
2574
+ await processForRoute(msg, route, groupHistoryKey);
2575
+ };
2576
+ }
2577
+
2578
+ //#endregion
2579
+ //#region src/monitor.ts
2580
+ function isNonRetryableWebCloseStatus(statusCode) {
2581
+ return statusCode === 440;
2582
+ }
2583
+ async function monitorWebChannel(verbose, listenerFactory = monitorWebInbox, keepAlive = true, replyResolver = getReplyFromConfig, runtime = defaultRuntime, abortSignal, tuning = {}) {
2584
+ const runId = newConnectionId();
2585
+ const replyLogger = getChildLogger({
2586
+ module: "web-auto-reply",
2587
+ runId
2588
+ });
2589
+ const heartbeatLogger = getChildLogger({
2590
+ module: "web-heartbeat",
2591
+ runId
2592
+ });
2593
+ const reconnectLogger = getChildLogger({
2594
+ module: "web-reconnect",
2595
+ runId
2596
+ });
2597
+ const status = {
2598
+ running: true,
2599
+ connected: false,
2600
+ reconnectAttempts: 0,
2601
+ lastConnectedAt: null,
2602
+ lastDisconnect: null,
2603
+ lastMessageAt: null,
2604
+ lastEventAt: null,
2605
+ lastError: null
2606
+ };
2607
+ const emitStatus = () => {
2608
+ tuning.statusSink?.({
2609
+ ...status,
2610
+ lastDisconnect: status.lastDisconnect ? { ...status.lastDisconnect } : null
2611
+ });
2612
+ };
2613
+ emitStatus();
2614
+ const baseCfg = loadConfig();
2615
+ const account = resolveWhatsAppAccount({
2616
+ cfg: baseCfg,
2617
+ accountId: tuning.accountId
2618
+ });
2619
+ const cfg = {
2620
+ ...baseCfg,
2621
+ channels: {
2622
+ ...baseCfg.channels,
2623
+ whatsapp: {
2624
+ ...baseCfg.channels?.whatsapp,
2625
+ ackReaction: account.ackReaction,
2626
+ messagePrefix: account.messagePrefix,
2627
+ allowFrom: account.allowFrom,
2628
+ groupAllowFrom: account.groupAllowFrom,
2629
+ groupPolicy: account.groupPolicy,
2630
+ textChunkLimit: account.textChunkLimit,
2631
+ chunkMode: account.chunkMode,
2632
+ mediaMaxMb: account.mediaMaxMb,
2633
+ blockStreaming: account.blockStreaming,
2634
+ groups: account.groups
2635
+ }
2636
+ }
2637
+ };
2638
+ const configuredMaxMb = cfg.agents?.defaults?.mediaMaxMb;
2639
+ const maxMediaBytes = typeof configuredMaxMb === "number" && configuredMaxMb > 0 ? configuredMaxMb * 1024 * 1024 : DEFAULT_WEB_MEDIA_BYTES;
2640
+ const heartbeatSeconds = resolveHeartbeatSeconds(cfg, tuning.heartbeatSeconds);
2641
+ const reconnectPolicy = resolveReconnectPolicy(cfg, tuning.reconnect);
2642
+ const baseMentionConfig = buildMentionConfig(cfg);
2643
+ const groupHistoryLimit = cfg.channels?.whatsapp?.accounts?.[tuning.accountId ?? ""]?.historyLimit ?? cfg.channels?.whatsapp?.historyLimit ?? cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT ?? 20;
2644
+ const groupHistories = /* @__PURE__ */ new Map();
2645
+ const groupMemberNames = /* @__PURE__ */ new Map();
2646
+ const echoTracker = createEchoTracker({
2647
+ maxItems: 100,
2648
+ logVerbose
2649
+ });
2650
+ const sleep = tuning.sleep ?? ((ms, signal) => sleepWithAbort(ms, signal ?? abortSignal));
2651
+ const stopRequested = () => abortSignal?.aborted === true;
2652
+ const abortPromise = abortSignal && new Promise((resolve) => abortSignal.addEventListener("abort", () => resolve("aborted"), { once: true }));
2653
+ const currentMaxListeners = process.getMaxListeners?.() ?? 10;
2654
+ if (process.setMaxListeners && currentMaxListeners < 50) process.setMaxListeners(50);
2655
+ let sigintStop = false;
2656
+ const handleSigint = () => {
2657
+ sigintStop = true;
2658
+ };
2659
+ process.once("SIGINT", handleSigint);
2660
+ let reconnectAttempts = 0;
2661
+ try {
2662
+ while (true) {
2663
+ if (stopRequested()) break;
2664
+ const connectionId = newConnectionId();
2665
+ const startedAt = Date.now();
2666
+ let heartbeat = null;
2667
+ let watchdogTimer = null;
2668
+ let lastMessageAt = null;
2669
+ let handledMessages = 0;
2670
+ let unregisterUnhandled = null;
2671
+ let isClosing = false;
2672
+ const MESSAGE_TIMEOUT_MS = tuning.messageTimeoutMs ?? 1800 * 1e3;
2673
+ const WATCHDOG_CHECK_MS = tuning.watchdogCheckMs ?? 60 * 1e3;
2674
+ const backgroundTasks = /* @__PURE__ */ new Set();
2675
+ const onMessage = createWebOnMessageHandler({
2676
+ cfg,
2677
+ verbose,
2678
+ connectionId,
2679
+ maxMediaBytes,
2680
+ groupHistoryLimit,
2681
+ groupHistories,
2682
+ groupMemberNames,
2683
+ echoTracker,
2684
+ backgroundTasks,
2685
+ replyResolver: replyResolver ?? getReplyFromConfig,
2686
+ replyLogger,
2687
+ baseMentionConfig,
2688
+ account
2689
+ });
2690
+ const inboundDebounceMs = resolveInboundDebounceMs({
2691
+ cfg,
2692
+ channel: "whatsapp"
2693
+ });
2694
+ const shouldDebounce = (msg) => {
2695
+ if (msg.mediaPath || msg.mediaType) return false;
2696
+ if (msg.location) return false;
2697
+ if (msg.replyToId || msg.replyToBody) return false;
2698
+ return !hasControlCommand(msg.body, cfg);
2699
+ };
2700
+ const listener = await (listenerFactory ?? monitorWebInbox)({
2701
+ verbose,
2702
+ accountId: account.accountId,
2703
+ authDir: account.authDir,
2704
+ mediaMaxMb: account.mediaMaxMb,
2705
+ sendReadReceipts: account.sendReadReceipts,
2706
+ debounceMs: inboundDebounceMs,
2707
+ shouldDebounce,
2708
+ onMessage: async (msg) => {
2709
+ handledMessages += 1;
2710
+ lastMessageAt = Date.now();
2711
+ status.lastMessageAt = lastMessageAt;
2712
+ status.lastEventAt = lastMessageAt;
2713
+ emitStatus();
2714
+ await onMessage(msg);
2715
+ }
2716
+ });
2717
+ status.connected = true;
2718
+ status.lastConnectedAt = Date.now();
2719
+ status.lastEventAt = status.lastConnectedAt;
2720
+ status.lastError = null;
2721
+ emitStatus();
2722
+ const { e164: selfE164 } = readWebSelfId(account.authDir);
2723
+ const connectRoute = resolveAgentRoute({
2724
+ cfg,
2725
+ channel: "whatsapp",
2726
+ accountId: account.accountId
2727
+ });
2728
+ enqueueSystemEvent(`WhatsApp gateway connected${selfE164 ? ` as ${selfE164}` : ""}.`, { sessionKey: connectRoute.sessionKey });
2729
+ setActiveWebListener(account.accountId, listener);
2730
+ unregisterUnhandled = registerUnhandledRejectionHandler((reason) => {
2731
+ if (!isLikelyWhatsAppCryptoError(reason)) return false;
2732
+ const errorStr = formatError(reason);
2733
+ reconnectLogger.warn("web reconnect: unhandled rejection from WhatsApp socket; forcing reconnect", {
2734
+ connectionId,
2735
+ error: errorStr
2736
+ });
2737
+ listener.signalClose?.({
2738
+ status: 499,
2739
+ isLoggedOut: false,
2740
+ error: reason
2741
+ });
2742
+ return true;
2743
+ });
2744
+ const closeListener = async () => {
2745
+ isClosing = true;
2746
+ if (unregisterUnhandled) {
2747
+ unregisterUnhandled();
2748
+ unregisterUnhandled = null;
2749
+ }
2750
+ if (heartbeat) clearInterval(heartbeat);
2751
+ if (watchdogTimer) clearInterval(watchdogTimer);
2752
+ if (backgroundTasks.size > 0) {
2753
+ const drainTimeout = new Promise((r) => setTimeout(r, 1e4).unref());
2754
+ await Promise.race([Promise.allSettled(backgroundTasks), drainTimeout]);
2755
+ backgroundTasks.clear();
2756
+ }
2757
+ setActiveWebListener(account.accountId, null);
2758
+ try {
2759
+ await listener.close();
2760
+ } catch (err) {
2761
+ if (getActiveWebListener(account.accountId) === null) setActiveWebListener(account.accountId, listener);
2762
+ logVerbose(`Socket close failed: ${formatError(err)}`);
2763
+ throw err;
2764
+ }
2765
+ };
2766
+ if (keepAlive) {
2767
+ heartbeat = setInterval(() => {
2768
+ const authAgeMs = getWebAuthAgeMs(account.authDir);
2769
+ const minutesSinceLastMessage = lastMessageAt ? Math.floor((Date.now() - lastMessageAt) / 6e4) : null;
2770
+ const logData = {
2771
+ connectionId,
2772
+ reconnectAttempts,
2773
+ messagesHandled: handledMessages,
2774
+ lastMessageAt,
2775
+ authAgeMs,
2776
+ uptimeMs: Date.now() - startedAt,
2777
+ ...minutesSinceLastMessage !== null && minutesSinceLastMessage > 30 ? { minutesSinceLastMessage } : {}
2778
+ };
2779
+ if (minutesSinceLastMessage && minutesSinceLastMessage > 30) heartbeatLogger.warn("⚠️ web gateway heartbeat - no messages in 30+ minutes", logData);
2780
+ else heartbeatLogger.info("web gateway heartbeat", logData);
2781
+ }, heartbeatSeconds * 1e3);
2782
+ watchdogTimer = setInterval(() => {
2783
+ if (isClosing) return;
2784
+ if (!lastMessageAt) return;
2785
+ const timeSinceLastMessage = Date.now() - lastMessageAt;
2786
+ if (timeSinceLastMessage <= MESSAGE_TIMEOUT_MS) return;
2787
+ const minutesSinceLastMessage = Math.floor(timeSinceLastMessage / 6e4);
2788
+ heartbeatLogger.warn("Message timeout detected - forcing reconnect", {
2789
+ connectionId,
2790
+ minutesSinceLastMessage,
2791
+ lastMessageAt: new Date(lastMessageAt),
2792
+ messagesHandled: handledMessages
2793
+ });
2794
+ whatsappHeartbeatLog.warn(`No messages received in ${minutesSinceLastMessage}m - restarting connection`);
2795
+ closeListener().catch((err) => {
2796
+ logVerbose(`Close listener failed: ${formatError(err)}`);
2797
+ });
2798
+ }, WATCHDOG_CHECK_MS);
2799
+ }
2800
+ whatsappLog.info("Listening for personal WhatsApp inbound messages.");
2801
+ if (process.stdout.isTTY || process.stderr.isTTY) whatsappLog.raw("Ctrl+C to stop.");
2802
+ if (!keepAlive) {
2803
+ await closeListener();
2804
+ process.removeListener("SIGINT", handleSigint);
2805
+ return;
2806
+ }
2807
+ const reason = await Promise.race([listener.onClose?.catch((err) => {
2808
+ reconnectLogger.error("listener.onClose rejected", { error: formatError(err) });
2809
+ return {
2810
+ status: 500,
2811
+ isLoggedOut: false,
2812
+ error: err
2813
+ };
2814
+ }) ?? waitForever(), abortPromise ?? waitForever()]);
2815
+ if (Date.now() - startedAt > Math.max(heartbeatSeconds * 1e3, 300 * 1e3)) reconnectAttempts = 0;
2816
+ status.reconnectAttempts = reconnectAttempts;
2817
+ emitStatus();
2818
+ if (stopRequested() || sigintStop || reason === "aborted") {
2819
+ await closeListener();
2820
+ break;
2821
+ }
2822
+ const statusCode = (typeof reason === "object" && reason && "status" in reason ? reason.status : void 0) ?? "unknown";
2823
+ const loggedOut = typeof reason === "object" && reason && "isLoggedOut" in reason && reason.isLoggedOut;
2824
+ const errorStr = formatError(reason);
2825
+ status.connected = false;
2826
+ status.lastEventAt = Date.now();
2827
+ status.lastDisconnect = {
2828
+ at: status.lastEventAt,
2829
+ status: typeof statusCode === "number" ? statusCode : void 0,
2830
+ error: errorStr,
2831
+ loggedOut: Boolean(loggedOut)
2832
+ };
2833
+ status.lastError = errorStr;
2834
+ status.reconnectAttempts = reconnectAttempts;
2835
+ emitStatus();
2836
+ reconnectLogger.info("web reconnect: connection closed", {
2837
+ connectionId,
2838
+ status: statusCode,
2839
+ loggedOut,
2840
+ reconnectAttempts,
2841
+ error: errorStr
2842
+ });
2843
+ enqueueSystemEvent(`WhatsApp gateway disconnected (status ${statusCode ?? "unknown"})`, { sessionKey: connectRoute.sessionKey });
2844
+ if (loggedOut) {
2845
+ runtime.error(`WhatsApp session logged out. Run \`${formatCliCommand("openclaw channels login --channel web")}\` to relink.`);
2846
+ await closeListener();
2847
+ break;
2848
+ }
2849
+ if (isNonRetryableWebCloseStatus(statusCode)) {
2850
+ reconnectLogger.warn("web reconnect: non-retryable close status; stopping monitor", {
2851
+ connectionId,
2852
+ status: statusCode,
2853
+ error: errorStr
2854
+ });
2855
+ runtime.error(`WhatsApp Web connection closed (status ${statusCode}: session conflict). Resolve conflicting WhatsApp Web sessions, then relink with \`${formatCliCommand("openclaw channels login --channel web")}\`. Stopping web monitoring.`);
2856
+ await closeListener();
2857
+ break;
2858
+ }
2859
+ reconnectAttempts += 1;
2860
+ status.reconnectAttempts = reconnectAttempts;
2861
+ emitStatus();
2862
+ if (reconnectPolicy.maxAttempts > 0 && reconnectAttempts >= reconnectPolicy.maxAttempts) {
2863
+ reconnectLogger.warn("web reconnect: max attempts reached; continuing in degraded mode", {
2864
+ connectionId,
2865
+ status: statusCode,
2866
+ reconnectAttempts,
2867
+ maxAttempts: reconnectPolicy.maxAttempts
2868
+ });
2869
+ runtime.error(`WhatsApp Web reconnect: max attempts reached (${reconnectAttempts}/${reconnectPolicy.maxAttempts}). Stopping web monitoring.`);
2870
+ await closeListener();
2871
+ break;
2872
+ }
2873
+ const delay = computeBackoff(reconnectPolicy, reconnectAttempts);
2874
+ reconnectLogger.info("web reconnect: scheduling retry", {
2875
+ connectionId,
2876
+ status: statusCode,
2877
+ reconnectAttempts,
2878
+ maxAttempts: reconnectPolicy.maxAttempts || "unlimited",
2879
+ delayMs: delay
2880
+ });
2881
+ runtime.error(`WhatsApp Web connection closed (status ${statusCode}). Retry ${reconnectAttempts}/${reconnectPolicy.maxAttempts || "∞"} in ${formatDurationPrecise(delay)}… (${errorStr})`);
2882
+ try {
2883
+ await closeListener();
2884
+ } catch (closeErr) {
2885
+ logVerbose(`Socket close failed on reconnect: ${formatError(closeErr)}`);
2886
+ }
2887
+ try {
2888
+ await sleep(delay, abortSignal);
2889
+ } catch {
2890
+ break;
2891
+ }
2892
+ }
2893
+ } finally {
2894
+ status.running = false;
2895
+ status.connected = false;
2896
+ status.lastEventAt = Date.now();
2897
+ emitStatus();
2898
+ process.removeListener("SIGINT", handleSigint);
2899
+ }
2900
+ }
2901
+
2902
+ //#endregion
2903
+ //#region src/onboarding.ts
2904
+ const channel = "whatsapp";
2905
+ function setWhatsAppDmPolicy(cfg, dmPolicy) {
2906
+ return mergeWhatsAppConfig(cfg, { dmPolicy });
2907
+ }
2908
+ function setWhatsAppAllowFrom(cfg, allowFrom) {
2909
+ return mergeWhatsAppConfig(cfg, { allowFrom }, { unsetOnUndefined: ["allowFrom"] });
2910
+ }
2911
+ function setWhatsAppSelfChatMode(cfg, selfChatMode) {
2912
+ return mergeWhatsAppConfig(cfg, { selfChatMode });
2913
+ }
2914
+ async function detectWhatsAppLinked(cfg, accountId) {
2915
+ const { authDir } = resolveWhatsAppAuthDir({
2916
+ cfg,
2917
+ accountId
2918
+ });
2919
+ return await pathExists(path.join(authDir, "creds.json"));
2920
+ }
2921
+ async function promptWhatsAppOwnerAllowFrom(params) {
2922
+ const { prompter, existingAllowFrom } = params;
2923
+ await prompter.note("We need the sender/owner number so WednesdayAI can allowlist you.", "WhatsApp number");
2924
+ const entry = await prompter.text({
2925
+ message: "Your personal WhatsApp number (the phone you will message from)",
2926
+ placeholder: "+15555550123",
2927
+ initialValue: existingAllowFrom[0],
2928
+ validate: (value) => {
2929
+ const raw = String(value ?? "").trim();
2930
+ if (!raw) return "Required";
2931
+ if (!normalizeE164(raw)) return `Invalid number: ${raw}`;
2932
+ }
2933
+ });
2934
+ const normalized = normalizeE164(String(entry).trim());
2935
+ if (!normalized) throw new Error("Invalid WhatsApp owner number (expected E.164 after validation).");
2936
+ return {
2937
+ normalized,
2938
+ allowFrom: normalizeAllowFromEntries([...existingAllowFrom.filter((item) => item !== "*"), normalized], normalizeE164)
2939
+ };
2940
+ }
2941
+ async function applyWhatsAppOwnerAllowlist(params) {
2942
+ const { normalized, allowFrom } = await promptWhatsAppOwnerAllowFrom({
2943
+ prompter: params.prompter,
2944
+ existingAllowFrom: params.existingAllowFrom
2945
+ });
2946
+ let next = setWhatsAppSelfChatMode(params.cfg, true);
2947
+ next = setWhatsAppDmPolicy(next, "allowlist");
2948
+ next = setWhatsAppAllowFrom(next, allowFrom);
2949
+ await params.prompter.note([...params.messageLines, `- allowFrom includes ${normalized}`].join("\n"), params.title);
2950
+ return next;
2951
+ }
2952
+ function parseWhatsAppAllowFromEntries(raw) {
2953
+ const parts = splitOnboardingEntries(raw);
2954
+ if (parts.length === 0) return { entries: [] };
2955
+ const entries = [];
2956
+ for (const part of parts) {
2957
+ if (part === "*") {
2958
+ entries.push("*");
2959
+ continue;
2960
+ }
2961
+ const normalized = normalizeE164(part);
2962
+ if (!normalized) return {
2963
+ entries: [],
2964
+ invalidEntry: part
2965
+ };
2966
+ entries.push(normalized);
2967
+ }
2968
+ return { entries: normalizeAllowFromEntries(entries, normalizeE164) };
2969
+ }
2970
+ async function promptWhatsAppAllowFrom(cfg, _runtime, prompter, options) {
2971
+ const existingPolicy = cfg.channels?.whatsapp?.dmPolicy ?? "pairing";
2972
+ const existingAllowFrom = cfg.channels?.whatsapp?.allowFrom ?? [];
2973
+ const existingLabel = existingAllowFrom.length > 0 ? existingAllowFrom.join(", ") : "unset";
2974
+ if (options?.forceAllowlist) return await applyWhatsAppOwnerAllowlist({
2975
+ cfg,
2976
+ prompter,
2977
+ existingAllowFrom,
2978
+ title: "WhatsApp allowlist",
2979
+ messageLines: ["Allowlist mode enabled."]
2980
+ });
2981
+ await prompter.note([
2982
+ "WhatsApp direct chats are gated by `channels.whatsapp.dmPolicy` + `channels.whatsapp.allowFrom`.",
2983
+ "- pairing (default): unknown senders get a pairing code; owner approves",
2984
+ "- allowlist: unknown senders are blocked",
2985
+ "- open: public inbound DMs (requires allowFrom to include \"*\")",
2986
+ "- disabled: ignore WhatsApp DMs",
2987
+ "",
2988
+ `Current: dmPolicy=${existingPolicy}, allowFrom=${existingLabel}`,
2989
+ `Docs: ${formatDocsLink("/whatsapp", "whatsapp")}`
2990
+ ].join("\n"), "WhatsApp DM access");
2991
+ if (await prompter.select({
2992
+ message: "WhatsApp phone setup",
2993
+ options: [{
2994
+ value: "personal",
2995
+ label: "This is my personal phone number"
2996
+ }, {
2997
+ value: "separate",
2998
+ label: "Separate phone just for WednesdayAI"
2999
+ }]
3000
+ }) === "personal") return await applyWhatsAppOwnerAllowlist({
3001
+ cfg,
3002
+ prompter,
3003
+ existingAllowFrom,
3004
+ title: "WhatsApp personal phone",
3005
+ messageLines: ["Personal phone mode enabled.", "- dmPolicy set to allowlist (pairing skipped)"]
3006
+ });
3007
+ const policy = await prompter.select({
3008
+ message: "WhatsApp DM policy",
3009
+ options: [
3010
+ {
3011
+ value: "pairing",
3012
+ label: "Pairing (recommended)"
3013
+ },
3014
+ {
3015
+ value: "allowlist",
3016
+ label: "Allowlist only (block unknown senders)"
3017
+ },
3018
+ {
3019
+ value: "open",
3020
+ label: "Open (public inbound DMs)"
3021
+ },
3022
+ {
3023
+ value: "disabled",
3024
+ label: "Disabled (ignore WhatsApp DMs)"
3025
+ }
3026
+ ]
3027
+ });
3028
+ let next = setWhatsAppSelfChatMode(cfg, false);
3029
+ next = setWhatsAppDmPolicy(next, policy);
3030
+ if (policy === "open") {
3031
+ const allowFrom = normalizeAllowFromEntries(["*", ...existingAllowFrom], normalizeE164);
3032
+ next = setWhatsAppAllowFrom(next, allowFrom.length > 0 ? allowFrom : ["*"]);
3033
+ return next;
3034
+ }
3035
+ if (policy === "disabled") return next;
3036
+ const allowOptions = existingAllowFrom.length > 0 ? [
3037
+ {
3038
+ value: "keep",
3039
+ label: "Keep current allowFrom"
3040
+ },
3041
+ {
3042
+ value: "unset",
3043
+ label: "Unset allowFrom (use pairing approvals only)"
3044
+ },
3045
+ {
3046
+ value: "list",
3047
+ label: "Set allowFrom to specific numbers"
3048
+ }
3049
+ ] : [{
3050
+ value: "unset",
3051
+ label: "Unset allowFrom (default)"
3052
+ }, {
3053
+ value: "list",
3054
+ label: "Set allowFrom to specific numbers"
3055
+ }];
3056
+ const mode = await prompter.select({
3057
+ message: "WhatsApp allowFrom (optional pre-allowlist)",
3058
+ options: allowOptions.map((opt) => ({
3059
+ value: opt.value,
3060
+ label: opt.label
3061
+ }))
3062
+ });
3063
+ if (mode === "keep") {} else if (mode === "unset") next = setWhatsAppAllowFrom(next, void 0);
3064
+ else {
3065
+ const allowRaw = await prompter.text({
3066
+ message: "Allowed sender numbers (comma-separated, E.164)",
3067
+ placeholder: "+15555550123, +447700900123",
3068
+ validate: (value) => {
3069
+ const raw = String(value ?? "").trim();
3070
+ if (!raw) return "Required";
3071
+ const parsed = parseWhatsAppAllowFromEntries(raw);
3072
+ if (parsed.entries.length === 0 && !parsed.invalidEntry) return "Required";
3073
+ if (parsed.invalidEntry) return `Invalid number: ${parsed.invalidEntry}`;
3074
+ }
3075
+ });
3076
+ const parsed = parseWhatsAppAllowFromEntries(String(allowRaw));
3077
+ next = setWhatsAppAllowFrom(next, parsed.entries);
3078
+ }
3079
+ return next;
3080
+ }
3081
+ const whatsappOnboardingAdapter = {
3082
+ channel,
3083
+ getStatus: async ({ cfg, accountOverrides }) => {
3084
+ const defaultAccountId = resolveDefaultWhatsAppAccountId(cfg);
3085
+ const accountId = resolveOnboardingAccountId({
3086
+ accountId: accountOverrides.whatsapp,
3087
+ defaultAccountId
3088
+ });
3089
+ const linked = await detectWhatsAppLinked(cfg, accountId);
3090
+ return {
3091
+ channel,
3092
+ configured: linked,
3093
+ statusLines: [`WhatsApp (${accountId === DEFAULT_ACCOUNT_ID ? "default" : accountId}): ${linked ? "linked" : "not linked"}`],
3094
+ selectionHint: linked ? "linked" : "not linked",
3095
+ quickstartScore: linked ? 5 : 4
3096
+ };
3097
+ },
3098
+ configure: async ({ cfg, runtime, prompter, options, accountOverrides, shouldPromptAccountIds, forceAllowFrom }) => {
3099
+ const accountId = await resolveAccountIdForConfigure({
3100
+ cfg,
3101
+ prompter,
3102
+ label: "WhatsApp",
3103
+ accountOverride: accountOverrides.whatsapp,
3104
+ shouldPromptAccountIds: Boolean(shouldPromptAccountIds || options?.promptWhatsAppAccountId),
3105
+ listAccountIds: listWhatsAppAccountIds,
3106
+ defaultAccountId: resolveDefaultWhatsAppAccountId(cfg)
3107
+ });
3108
+ let next = cfg;
3109
+ if (accountId !== DEFAULT_ACCOUNT_ID) next = {
3110
+ ...next,
3111
+ channels: {
3112
+ ...next.channels,
3113
+ whatsapp: {
3114
+ ...next.channels?.whatsapp,
3115
+ accounts: {
3116
+ ...next.channels?.whatsapp?.accounts,
3117
+ [accountId]: {
3118
+ ...next.channels?.whatsapp?.accounts?.[accountId],
3119
+ enabled: next.channels?.whatsapp?.accounts?.[accountId]?.enabled ?? true
3120
+ }
3121
+ }
3122
+ }
3123
+ }
3124
+ };
3125
+ const linked = await detectWhatsAppLinked(next, accountId);
3126
+ const { authDir } = resolveWhatsAppAuthDir({
3127
+ cfg: next,
3128
+ accountId
3129
+ });
3130
+ if (!linked) await prompter.note([
3131
+ "Scan the QR with WhatsApp on your phone.",
3132
+ `Credentials are stored under ${authDir}/ for future runs.`,
3133
+ `Docs: ${formatDocsLink("/whatsapp", "whatsapp")}`
3134
+ ].join("\n"), "WhatsApp linking");
3135
+ if (await prompter.confirm({
3136
+ message: linked ? "WhatsApp already linked. Re-link now?" : "Link WhatsApp now (QR)?",
3137
+ initialValue: !linked
3138
+ })) try {
3139
+ await loginWeb(false, void 0, runtime, accountId);
3140
+ } catch (err) {
3141
+ runtime.error(`WhatsApp login failed: ${String(err)}`);
3142
+ await prompter.note(`Docs: ${formatDocsLink("/whatsapp", "whatsapp")}`, "WhatsApp help");
3143
+ }
3144
+ else if (!linked) await prompter.note(`Run \`${formatCliCommand("openclaw channels login")}\` later to link WhatsApp.`, "WhatsApp");
3145
+ next = await promptWhatsAppAllowFrom(next, runtime, prompter, { forceAllowlist: forceAllowFrom });
3146
+ return {
3147
+ cfg: next,
3148
+ accountId
3149
+ };
3150
+ },
3151
+ onAccountRecorded: (accountId, options) => {
3152
+ options?.onWhatsAppAccountId?.(accountId);
3153
+ }
3154
+ };
3155
+
3156
+ //#endregion
3157
+ //#region src/outbound-adapter.ts
3158
+ function stripWhatsAppLeadingBlankLines(text) {
3159
+ return text.replace(/^(?:[ \t]*\r?\n)+/, "");
3160
+ }
3161
+ function createWhatsAppOutboundBase(deps) {
3162
+ return {
3163
+ deliveryMode: "gateway",
3164
+ chunker: deps.chunker,
3165
+ chunkerMode: "text",
3166
+ textChunkLimit: 4e3,
3167
+ pollMaxOptions: 12,
3168
+ resolveTarget: deps.resolveTarget,
3169
+ sendText: async ({ to, text, accountId, deps: callDeps, gifPlayback }) => {
3170
+ return {
3171
+ channel: "whatsapp",
3172
+ ...await (callDeps?.sendWhatsApp ?? deps.sendMessageWhatsApp)(to, text, {
3173
+ verbose: false,
3174
+ accountId: accountId ?? void 0,
3175
+ gifPlayback
3176
+ })
3177
+ };
3178
+ },
3179
+ sendMedia: async ({ to, text, mediaUrl, mediaLocalRoots, accountId, deps: callDeps, gifPlayback }) => {
3180
+ return {
3181
+ channel: "whatsapp",
3182
+ ...await (callDeps?.sendWhatsApp ?? deps.sendMessageWhatsApp)(to, text, {
3183
+ verbose: false,
3184
+ mediaUrl,
3185
+ mediaLocalRoots,
3186
+ accountId: accountId ?? void 0,
3187
+ gifPlayback
3188
+ })
3189
+ };
3190
+ },
3191
+ sendPoll: async ({ to, poll, accountId }) => await deps.sendPollWhatsApp(to, poll, {
3192
+ verbose: deps.shouldLogVerbose(),
3193
+ accountId: accountId ?? void 0
3194
+ }),
3195
+ normalizePayload: ({ payload }) => ({
3196
+ ...payload,
3197
+ text: stripWhatsAppLeadingBlankLines(payload.text ?? "")
3198
+ })
3199
+ };
3200
+ }
3201
+ const whatsappOutbound = createWhatsAppOutboundBase({
3202
+ chunker: (text, limit) => getWhatsAppRuntime().channel.text.chunkText(text, limit),
3203
+ sendMessageWhatsApp,
3204
+ sendPollWhatsApp,
3205
+ shouldLogVerbose: () => getWhatsAppRuntime().logging.shouldLogVerbose(),
3206
+ resolveTarget: ({ to, allowFrom, mode }) => resolveWhatsAppOutboundTarget({
3207
+ to,
3208
+ allowFrom,
3209
+ mode
3210
+ })
3211
+ });
3212
+
3213
+ //#endregion
3214
+ //#region src/shared.ts
3215
+ const WHATSAPP_GROUP_INTRO_HINT = "WhatsApp IDs: SenderId is the participant JID (group participant id).";
3216
+ function resolveWhatsAppGroupIntroHint() {
3217
+ return WHATSAPP_GROUP_INTRO_HINT;
3218
+ }
3219
+ function resolveWhatsAppMentionStripPatterns(ctx) {
3220
+ const selfE164 = (ctx.To ?? "").replace(/^whatsapp:/, "");
3221
+ if (!selfE164) return [];
3222
+ const escaped = escapeRegExp$1(selfE164);
3223
+ return [escaped, `@${escaped}`];
3224
+ }
3225
+
3226
+ //#endregion
3227
+ //#region src/status.ts
3228
+ function isRecord(value) {
3229
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3230
+ }
3231
+ function asString(value) {
3232
+ return typeof value === "string" ? value.trim() : "";
3233
+ }
3234
+ function readWhatsAppAccountStatus(value) {
3235
+ if (!isRecord(value)) return null;
3236
+ return {
3237
+ accountId: value.accountId,
3238
+ enabled: value.enabled,
3239
+ linked: value.linked,
3240
+ connected: value.connected,
3241
+ running: value.running,
3242
+ reconnectAttempts: value.reconnectAttempts,
3243
+ lastError: value.lastError
3244
+ };
3245
+ }
3246
+ function resolveAccountId(account) {
3247
+ return typeof account.accountId === "string" && account.accountId.trim() ? account.accountId.trim() : "default";
3248
+ }
3249
+ function collectWhatsAppStatusIssues(accounts) {
3250
+ const issues = [];
3251
+ for (const rawAccount of accounts) {
3252
+ const account = readWhatsAppAccountStatus(rawAccount);
3253
+ if (!account || account.enabled === false) continue;
3254
+ const accountId = resolveAccountId(account);
3255
+ const linked = account.linked === true;
3256
+ const running = account.running === true;
3257
+ const connected = account.connected === true;
3258
+ const reconnectAttempts = typeof account.reconnectAttempts === "number" ? account.reconnectAttempts : null;
3259
+ const lastError = asString(account.lastError);
3260
+ if (!linked) {
3261
+ issues.push({
3262
+ channel: "whatsapp",
3263
+ accountId,
3264
+ kind: "auth",
3265
+ message: "Not linked (no WhatsApp Web session).",
3266
+ fix: `Run: ${formatCliCommand("openclaw channels login")} (scan QR on the gateway host).`
3267
+ });
3268
+ continue;
3269
+ }
3270
+ if (running && !connected) issues.push({
3271
+ channel: "whatsapp",
3272
+ accountId,
3273
+ kind: "runtime",
3274
+ message: `Linked but disconnected${reconnectAttempts != null ? ` (reconnectAttempts=${reconnectAttempts})` : ""}${lastError ? `: ${lastError}` : "."}`,
3275
+ fix: `Run: ${formatCliCommand("openclaw doctor")} (or restart the gateway). If it persists, relink via channels login and check logs.`
3276
+ });
3277
+ }
3278
+ return issues;
3279
+ }
3280
+
3281
+ //#endregion
3282
+ //#region src/channel.ts
3283
+ const meta = {
3284
+ id: "whatsapp",
3285
+ label: "WhatsApp",
3286
+ selectionLabel: "WhatsApp (QR link)",
3287
+ detailLabel: "WhatsApp Web",
3288
+ docsPath: "/channels/whatsapp",
3289
+ docsLabel: "whatsapp",
3290
+ blurb: "works with your own number; recommend a separate phone + eSIM.",
3291
+ systemImage: "message"
3292
+ };
3293
+ const whatsappPlugin = {
3294
+ id: "whatsapp",
3295
+ meta: {
3296
+ ...meta,
3297
+ showConfigured: false,
3298
+ quickstartAllowFrom: true,
3299
+ forceAccountBinding: true,
3300
+ preferSessionLookupForAnnounceTarget: true
3301
+ },
3302
+ onboarding: whatsappOnboardingAdapter,
3303
+ agentTools: () => [createWhatsAppLoginTool()],
3304
+ pairing: { idLabel: "whatsappSenderId" },
3305
+ capabilities: {
3306
+ chatTypes: ["direct", "group"],
3307
+ polls: true,
3308
+ reactions: true,
3309
+ media: true
3310
+ },
3311
+ reload: {
3312
+ configPrefixes: ["web"],
3313
+ noopPrefixes: ["channels.whatsapp"]
3314
+ },
3315
+ gatewayMethods: ["web.login.start", "web.login.wait"],
3316
+ configSchema: buildChannelConfigSchema(WhatsAppConfigSchema),
3317
+ config: {
3318
+ listAccountIds: (cfg) => listWhatsAppAccountIds(cfg),
3319
+ resolveAccount: (cfg, accountId) => resolveWhatsAppAccount$1({
3320
+ cfg,
3321
+ accountId
3322
+ }),
3323
+ defaultAccountId: (cfg) => resolveDefaultWhatsAppAccountId(cfg),
3324
+ setAccountEnabled: ({ cfg, accountId, enabled }) => {
3325
+ const accountKey = accountId || DEFAULT_ACCOUNT_ID;
3326
+ const accounts = { ...cfg.channels?.whatsapp?.accounts };
3327
+ const existing = accounts[accountKey] ?? {};
3328
+ return {
3329
+ ...cfg,
3330
+ channels: {
3331
+ ...cfg.channels,
3332
+ whatsapp: {
3333
+ ...cfg.channels?.whatsapp,
3334
+ accounts: {
3335
+ ...accounts,
3336
+ [accountKey]: {
3337
+ ...existing,
3338
+ enabled
3339
+ }
3340
+ }
3341
+ }
3342
+ }
3343
+ };
3344
+ },
3345
+ deleteAccount: ({ cfg, accountId }) => {
3346
+ const accountKey = accountId || DEFAULT_ACCOUNT_ID;
3347
+ const accounts = { ...cfg.channels?.whatsapp?.accounts };
3348
+ delete accounts[accountKey];
3349
+ return {
3350
+ ...cfg,
3351
+ channels: {
3352
+ ...cfg.channels,
3353
+ whatsapp: {
3354
+ ...cfg.channels?.whatsapp,
3355
+ accounts: Object.keys(accounts).length ? accounts : void 0
3356
+ }
3357
+ }
3358
+ };
3359
+ },
3360
+ isEnabled: (account, cfg) => account.enabled && cfg.web?.enabled !== false,
3361
+ disabledReason: () => "disabled",
3362
+ isConfigured: async (account) => await webAuthExists(account.authDir),
3363
+ unconfiguredReason: () => "not linked",
3364
+ describeAccount: (account) => ({
3365
+ accountId: account.accountId,
3366
+ name: account.name,
3367
+ enabled: account.enabled,
3368
+ configured: Boolean(account.authDir),
3369
+ linked: Boolean(account.authDir),
3370
+ dmPolicy: account.dmPolicy,
3371
+ allowFrom: account.allowFrom
3372
+ }),
3373
+ resolveAllowFrom: ({ cfg, accountId }) => resolveWhatsAppConfigAllowFrom({
3374
+ cfg,
3375
+ accountId
3376
+ }),
3377
+ formatAllowFrom: ({ allowFrom }) => formatWhatsAppConfigAllowFromEntries(allowFrom),
3378
+ resolveDefaultTo: ({ cfg, accountId }) => resolveWhatsAppConfigDefaultTo({
3379
+ cfg,
3380
+ accountId
3381
+ })
3382
+ },
3383
+ security: {
3384
+ resolveDmPolicy: ({ cfg, accountId, account }) => {
3385
+ const resolvedAccountId = accountId ?? account.accountId ?? DEFAULT_ACCOUNT_ID;
3386
+ const basePath = Boolean(cfg.channels?.whatsapp?.accounts?.[resolvedAccountId]) ? `channels.whatsapp.accounts.${resolvedAccountId}.` : "channels.whatsapp.";
3387
+ return {
3388
+ policy: account.dmPolicy ?? "pairing",
3389
+ allowFrom: account.allowFrom ?? [],
3390
+ policyPath: `${basePath}dmPolicy`,
3391
+ allowFromPath: basePath,
3392
+ approveHint: formatPairingApproveHint("whatsapp"),
3393
+ normalizeEntry: (raw) => normalizeE164(raw)
3394
+ };
3395
+ },
3396
+ collectWarnings: ({ account, cfg }) => {
3397
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
3398
+ const { groupPolicy } = resolveAllowlistProviderRuntimeGroupPolicy({
3399
+ providerConfigPresent: cfg.channels?.whatsapp !== void 0,
3400
+ groupPolicy: account.groupPolicy,
3401
+ defaultGroupPolicy
3402
+ });
3403
+ if (groupPolicy !== "open") return [];
3404
+ if (Boolean(account.groups) && Object.keys(account.groups ?? {}).length > 0) return [`- WhatsApp groups: groupPolicy="open" allows any member in allowed groups to trigger (mention-gated). Set channels.whatsapp.groupPolicy="allowlist" + channels.whatsapp.groupAllowFrom to restrict senders.`];
3405
+ return [`- WhatsApp groups: groupPolicy="open" with no channels.whatsapp.groups allowlist; any group can add + ping (mention-gated). Set channels.whatsapp.groupPolicy="allowlist" + channels.whatsapp.groupAllowFrom or configure channels.whatsapp.groups.`];
3406
+ }
3407
+ },
3408
+ setup: {
3409
+ resolveAccountId: ({ accountId }) => normalizeAccountId(accountId),
3410
+ applyAccountName: ({ cfg, accountId, name }) => applyAccountNameToChannelSection({
3411
+ cfg,
3412
+ channelKey: "whatsapp",
3413
+ accountId,
3414
+ name,
3415
+ alwaysUseAccounts: true
3416
+ }),
3417
+ applyAccountConfig: ({ cfg, accountId, input }) => {
3418
+ const next = migrateBaseNameToDefaultAccount({
3419
+ cfg: applyAccountNameToChannelSection({
3420
+ cfg,
3421
+ channelKey: "whatsapp",
3422
+ accountId,
3423
+ name: input.name,
3424
+ alwaysUseAccounts: true
3425
+ }),
3426
+ channelKey: "whatsapp",
3427
+ alwaysUseAccounts: true
3428
+ });
3429
+ const entry = {
3430
+ ...next.channels?.whatsapp?.accounts?.[accountId],
3431
+ ...input.authDir ? { authDir: input.authDir } : {},
3432
+ enabled: true
3433
+ };
3434
+ return {
3435
+ ...next,
3436
+ channels: {
3437
+ ...next.channels,
3438
+ whatsapp: {
3439
+ ...next.channels?.whatsapp,
3440
+ accounts: {
3441
+ ...next.channels?.whatsapp?.accounts,
3442
+ [accountId]: entry
3443
+ }
3444
+ }
3445
+ }
3446
+ };
3447
+ }
3448
+ },
3449
+ groups: {
3450
+ resolveRequireMention: resolveWhatsAppGroupRequireMention,
3451
+ resolveToolPolicy: resolveWhatsAppGroupToolPolicy,
3452
+ resolveGroupIntroHint: resolveWhatsAppGroupIntroHint
3453
+ },
3454
+ mentions: { stripPatterns: ({ ctx }) => resolveWhatsAppMentionStripPatterns(ctx) },
3455
+ threading: { buildToolContext: ({ context, hasRepliedRef }) => {
3456
+ return {
3457
+ currentChannelId: context.From?.trim() || context.To?.trim() || void 0,
3458
+ currentThreadTs: context.ReplyToId,
3459
+ hasRepliedRef
3460
+ };
3461
+ } },
3462
+ commands: {
3463
+ enforceOwnerForCommands: true,
3464
+ skipWhenConfigEmpty: true
3465
+ },
3466
+ messaging: {
3467
+ normalizeTarget: normalizeWhatsAppMessagingTarget,
3468
+ targetResolver: {
3469
+ looksLikeId: looksLikeWhatsAppTargetId,
3470
+ hint: "<E.164|group JID>"
3471
+ }
3472
+ },
3473
+ directory: {
3474
+ self: async ({ cfg, accountId }) => {
3475
+ const account = resolveWhatsAppAccount$1({
3476
+ cfg,
3477
+ accountId
3478
+ });
3479
+ const { e164, jid } = readWebSelfId(account.authDir);
3480
+ const id = e164 ?? jid;
3481
+ if (!id) return null;
3482
+ return {
3483
+ kind: "user",
3484
+ id,
3485
+ name: account.name,
3486
+ raw: {
3487
+ e164,
3488
+ jid
3489
+ }
3490
+ };
3491
+ },
3492
+ listPeers: async (params) => listWhatsAppDirectoryPeersFromConfig(params),
3493
+ listGroups: async (params) => listWhatsAppDirectoryGroupsFromConfig(params)
3494
+ },
3495
+ actions: {
3496
+ listActions: ({ cfg }) => {
3497
+ if (!cfg.channels?.whatsapp) return [];
3498
+ const gate = createActionGate(cfg.channels.whatsapp.actions);
3499
+ const actions = /* @__PURE__ */ new Set();
3500
+ if (gate("reactions")) actions.add("react");
3501
+ if (gate("polls")) actions.add("poll");
3502
+ return Array.from(actions);
3503
+ },
3504
+ supportsAction: ({ action }) => action === "react",
3505
+ handleAction: async ({ action, params, cfg, accountId }) => {
3506
+ if (action !== "react") throw new Error(`Action ${action} is not supported for provider ${meta.id}.`);
3507
+ const messageId = readStringParam(params, "messageId", { required: true });
3508
+ const emoji = readStringParam(params, "emoji", { allowEmpty: true });
3509
+ const remove = typeof params.remove === "boolean" ? params.remove : void 0;
3510
+ return await handleWhatsAppAction({
3511
+ action: "react",
3512
+ chatJid: readStringParam(params, "chatJid") ?? readStringParam(params, "to", { required: true }),
3513
+ messageId,
3514
+ emoji,
3515
+ remove,
3516
+ participant: readStringParam(params, "participant"),
3517
+ accountId: accountId ?? void 0,
3518
+ fromMe: typeof params.fromMe === "boolean" ? params.fromMe : void 0
3519
+ }, cfg);
3520
+ }
3521
+ },
3522
+ outbound: whatsappOutbound,
3523
+ auth: { login: async ({ cfg, accountId, runtime, verbose }) => {
3524
+ const resolvedAccountId = accountId?.trim() || resolveDefaultWhatsAppAccountId(cfg);
3525
+ await loginWeb(Boolean(verbose), void 0, runtime, resolvedAccountId, cfg);
3526
+ } },
3527
+ heartbeat: {
3528
+ checkReady: async ({ cfg, accountId, deps }) => {
3529
+ if (cfg.web?.enabled === false) return {
3530
+ ok: false,
3531
+ reason: "whatsapp-disabled"
3532
+ };
3533
+ const account = resolveWhatsAppAccount$1({
3534
+ cfg,
3535
+ accountId
3536
+ });
3537
+ if (!await (deps?.webAuthExists ?? webAuthExists)(account.authDir)) return {
3538
+ ok: false,
3539
+ reason: "whatsapp-not-linked"
3540
+ };
3541
+ if (!(deps?.hasActiveWebListener ? deps.hasActiveWebListener() : Boolean(getActiveWebListener()))) return {
3542
+ ok: false,
3543
+ reason: "whatsapp-not-running"
3544
+ };
3545
+ return {
3546
+ ok: true,
3547
+ reason: "ok"
3548
+ };
3549
+ },
3550
+ resolveRecipients: ({ cfg, opts }) => resolveWhatsAppHeartbeatRecipients(cfg, opts)
3551
+ },
3552
+ status: {
3553
+ defaultRuntime: {
3554
+ accountId: DEFAULT_ACCOUNT_ID,
3555
+ running: false,
3556
+ connected: false,
3557
+ reconnectAttempts: 0,
3558
+ lastConnectedAt: null,
3559
+ lastDisconnect: null,
3560
+ lastMessageAt: null,
3561
+ lastEventAt: null,
3562
+ lastError: null
3563
+ },
3564
+ collectStatusIssues: collectWhatsAppStatusIssues,
3565
+ buildChannelSummary: async ({ account, snapshot }) => {
3566
+ const authDir = account.authDir;
3567
+ const linked = typeof snapshot.linked === "boolean" ? snapshot.linked : authDir ? await webAuthExists(authDir) : false;
3568
+ return {
3569
+ configured: linked,
3570
+ linked,
3571
+ authAgeMs: linked && authDir ? getWebAuthAgeMs(authDir) : null,
3572
+ self: linked && authDir ? readWebSelfId(authDir) : {
3573
+ e164: null,
3574
+ jid: null
3575
+ },
3576
+ running: snapshot.running ?? false,
3577
+ connected: snapshot.connected ?? false,
3578
+ lastConnectedAt: snapshot.lastConnectedAt ?? null,
3579
+ lastDisconnect: snapshot.lastDisconnect ?? null,
3580
+ reconnectAttempts: snapshot.reconnectAttempts,
3581
+ lastMessageAt: snapshot.lastMessageAt ?? null,
3582
+ lastEventAt: snapshot.lastEventAt ?? null,
3583
+ lastError: snapshot.lastError ?? null
3584
+ };
3585
+ },
3586
+ buildAccountSnapshot: async ({ account, runtime }) => {
3587
+ const linked = await webAuthExists(account.authDir);
3588
+ return {
3589
+ accountId: account.accountId,
3590
+ name: account.name,
3591
+ enabled: account.enabled,
3592
+ configured: true,
3593
+ linked,
3594
+ running: runtime?.running ?? false,
3595
+ connected: runtime?.connected ?? false,
3596
+ reconnectAttempts: runtime?.reconnectAttempts,
3597
+ lastConnectedAt: runtime?.lastConnectedAt ?? null,
3598
+ lastDisconnect: runtime?.lastDisconnect ?? null,
3599
+ lastMessageAt: runtime?.lastMessageAt ?? null,
3600
+ lastEventAt: runtime?.lastEventAt ?? null,
3601
+ lastError: runtime?.lastError ?? null,
3602
+ dmPolicy: account.dmPolicy,
3603
+ allowFrom: account.allowFrom
3604
+ };
3605
+ },
3606
+ resolveAccountState: ({ configured }) => configured ? "linked" : "not linked",
3607
+ logSelfId: ({ account, runtime, includeChannelPrefix }) => {
3608
+ logWebSelfId(account.authDir, runtime, includeChannelPrefix);
3609
+ }
3610
+ },
3611
+ gateway: {
3612
+ startAccount: async (ctx) => {
3613
+ const account = ctx.account;
3614
+ const { e164, jid } = readWebSelfId(account.authDir);
3615
+ const identity = e164 ? e164 : jid ? `jid ${jid}` : "unknown";
3616
+ ctx.log?.info(`[${account.accountId}] starting provider (${identity})`);
3617
+ return monitorWebChannel(getWhatsAppRuntime().logging.shouldLogVerbose(), void 0, true, void 0, ctx.runtime, ctx.abortSignal, {
3618
+ statusSink: (next) => ctx.setStatus({
3619
+ accountId: ctx.accountId,
3620
+ ...next
3621
+ }),
3622
+ accountId: account.accountId
3623
+ });
3624
+ },
3625
+ loginWithQrStart: async ({ accountId, force, timeoutMs, verbose }) => await startWebLoginWithQr({
3626
+ accountId,
3627
+ force,
3628
+ timeoutMs,
3629
+ verbose
3630
+ }),
3631
+ loginWithQrWait: async ({ accountId, timeoutMs }) => await waitForWebLogin({
3632
+ accountId,
3633
+ timeoutMs
3634
+ }),
3635
+ logoutAccount: async ({ account, cfg, runtime }) => {
3636
+ const { DisconnectReason } = await getBaileys();
3637
+ await closeActiveWebLoginsForAuthDir(account.authDir);
3638
+ const targetAuthDir = tryCanonicalWhatsAppAuthDir(account.authDir);
3639
+ const listenerAccountIds = new Set([account.accountId]);
3640
+ if (targetAuthDir) {
3641
+ for (const candidate of listWhatsAppAccountIds(cfg)) if (tryCanonicalWhatsAppAuthDir(resolveWhatsAppAccount$1({
3642
+ cfg,
3643
+ accountId: candidate
3644
+ }).authDir) === targetAuthDir) listenerAccountIds.add(candidate);
3645
+ }
3646
+ await Promise.all([...listenerAccountIds].map(async (accountId) => await stopActiveWebListener(accountId, {
3647
+ status: DisconnectReason.loggedOut,
3648
+ isLoggedOut: true,
3649
+ error: "logout"
3650
+ })));
3651
+ const cleared = await logoutWeb({
3652
+ authDir: account.authDir,
3653
+ isLegacyAuthDir: account.isLegacyAuthDir,
3654
+ runtime
3655
+ });
3656
+ return {
3657
+ cleared,
3658
+ loggedOut: cleared
3659
+ };
3660
+ }
3661
+ }
3662
+ };
3663
+
3664
+ //#endregion
3665
+ //#region index.ts
3666
+ const plugin = {
3667
+ id: "whatsapp",
3668
+ name: "WhatsApp",
3669
+ description: "WhatsApp channel plugin",
3670
+ configSchema: emptyPluginConfigSchema(),
3671
+ register(api) {
3672
+ setWhatsAppRuntime(api.runtime);
3673
+ api.registerChannel({ plugin: whatsappPlugin });
3674
+ }
3675
+ };
3676
+
3677
+ //#endregion
3678
+ export { plugin as default };