@openclaw/whatsapp 2026.5.2 → 2026.5.3-beta.1

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.
Files changed (302) hide show
  1. package/dist/access-control-BQ3tCkH8.js +288 -0
  2. package/dist/account-config-CNQ33oav.js +47 -0
  3. package/dist/account-ids-DG18xddX.js +5 -0
  4. package/dist/accounts-BDqgpFEB.js +116 -0
  5. package/dist/action-runtime-DTGNgG-i.js +74 -0
  6. package/dist/action-runtime-api.js +2 -0
  7. package/dist/action-runtime.runtime.js +2 -0
  8. package/dist/active-listener-N7GFKsuN.js +11 -0
  9. package/dist/agent-tools-login-DpRxLNRB.js +89 -0
  10. package/dist/api.js +148 -0
  11. package/dist/audio-preflight.runtime-Bcdsl_ri.js +7 -0
  12. package/dist/auth-presence.js +32 -0
  13. package/dist/auth-store-BjCb50Ry.js +381 -0
  14. package/dist/channel-DQ-5Xoj9.js +542 -0
  15. package/dist/channel-config-api.js +2 -0
  16. package/dist/channel-plugin-api.js +2 -0
  17. package/dist/channel-react-action-Df20qAy9.js +42 -0
  18. package/dist/channel.runtime-DKXRnA8x.js +55 -0
  19. package/dist/channel.setup-DOHR2BGp.js +20 -0
  20. package/dist/command-policy-O8sRnqUV.js +8 -0
  21. package/dist/config-schema-Dmo66Ubb.js +27 -0
  22. package/dist/connection-controller-BiHAsTM8.js +596 -0
  23. package/dist/connection-controller-registry-D_iIGz5m.js +22 -0
  24. package/dist/constants-DLGCIbfl.js +4 -0
  25. package/dist/constants.js +2 -0
  26. package/dist/contract-api.js +19 -0
  27. package/dist/creds-files-_2V8jzQa.js +19 -0
  28. package/dist/directory-config-DVs4ffXu.js +37 -0
  29. package/dist/directory-contract-api.js +2 -0
  30. package/dist/doctor-A9tXm9Om.js +48 -0
  31. package/dist/doctor-contract-api.js +10 -0
  32. package/dist/group-session-contract-B8QBn0I2.js +15 -0
  33. package/dist/identity-QHAlV7Fu.js +75 -0
  34. package/dist/index.js +18 -0
  35. package/dist/legacy-session-surface-api.js +8 -0
  36. package/dist/legacy-state-migrations-api.js +2 -0
  37. package/dist/light-runtime-api.js +5 -0
  38. package/dist/login-DymdrKca.js +52 -0
  39. package/dist/login-qr-DIS0Iv-7.js +378 -0
  40. package/dist/login-qr-api.js +2 -0
  41. package/dist/login-qr-runtime.js +16 -0
  42. package/dist/monitor-C4Fhg_lD.js +3349 -0
  43. package/dist/normalize-CWYiGkXw.js +2 -0
  44. package/dist/normalize-target-BPVHNsM5.js +74 -0
  45. package/dist/outbound-adapter-BssVnZdz.js +29 -0
  46. package/dist/outbound-base-Bq1UYEK5.js +119 -0
  47. package/dist/outbound-media-contract-CGss_QHy.js +163 -0
  48. package/dist/outbound-payload-test-api.js +2 -0
  49. package/dist/quoted-message-TENQzyxV.js +108 -0
  50. package/dist/reaction-level-CRVEVAfi.js +16 -0
  51. package/dist/reply-resolver.runtime-BRCgoO4C.js +2 -0
  52. package/dist/resolve-outbound-target-CN-Wo6IY.js +39 -0
  53. package/dist/rolldown-runtime-RkAeH_Qm.js +27 -0
  54. package/dist/runtime-6fZ67abR.js +8 -0
  55. package/dist/runtime-api.js +15 -0
  56. package/dist/runtime-group-policy-Gp1lQ0at.js +11 -0
  57. package/dist/secret-contract-api.js +5 -0
  58. package/dist/security-contract-DqH8JDX6.js +26 -0
  59. package/dist/security-contract-api.js +2 -0
  60. package/dist/send-CIyLFxdZ.js +234 -0
  61. package/dist/session-contract-B0efQf9P.js +27 -0
  62. package/dist/session-errors-CSuKZPub.js +63 -0
  63. package/dist/session.runtime-C1eSE_KK.js +13 -0
  64. package/dist/setup-core-DZKvpzbH.js +46 -0
  65. package/dist/setup-entry.js +23 -0
  66. package/dist/setup-plugin-api.js +2 -0
  67. package/dist/setup-surface-ieFnIW4g.js +344 -0
  68. package/dist/shared-D_wzSVar.js +307 -0
  69. package/dist/state-migrations-DnCdvoYD.js +39 -0
  70. package/dist/targets.js +2 -0
  71. package/dist/test-api.js +3 -0
  72. package/dist/text-runtime-C1zNiZeO.js +116 -0
  73. package/package.json +14 -6
  74. package/action-runtime-api.ts +0 -1
  75. package/action-runtime.runtime.ts +0 -1
  76. package/api.ts +0 -213
  77. package/auth-presence.ts +0 -80
  78. package/channel-config-api.ts +0 -1
  79. package/channel-plugin-api.ts +0 -3
  80. package/config-api.ts +0 -4
  81. package/constants.ts +0 -1
  82. package/contract-api.ts +0 -29
  83. package/directory-contract-api.ts +0 -4
  84. package/doctor-contract-api.ts +0 -8
  85. package/index.test.ts +0 -13
  86. package/index.ts +0 -16
  87. package/legacy-session-surface-api.ts +0 -6
  88. package/legacy-state-migrations-api.ts +0 -1
  89. package/light-runtime-api.ts +0 -12
  90. package/login-qr-api.ts +0 -1
  91. package/login-qr-runtime.ts +0 -23
  92. package/outbound-payload-test-api.ts +0 -1
  93. package/runtime-api.ts +0 -84
  94. package/secret-contract-api.ts +0 -4
  95. package/security-contract-api.ts +0 -4
  96. package/setup-entry.test.ts +0 -21
  97. package/setup-entry.ts +0 -21
  98. package/setup-plugin-api.ts +0 -3
  99. package/src/account-config.ts +0 -77
  100. package/src/account-ids.ts +0 -13
  101. package/src/account-types.ts +0 -5
  102. package/src/accounts.test.ts +0 -182
  103. package/src/accounts.ts +0 -176
  104. package/src/accounts.whatsapp-auth.test.ts +0 -59
  105. package/src/action-runtime-target-auth.ts +0 -27
  106. package/src/action-runtime.test.ts +0 -330
  107. package/src/action-runtime.ts +0 -76
  108. package/src/active-listener.test.ts +0 -65
  109. package/src/active-listener.ts +0 -17
  110. package/src/agent-tools-login.test.ts +0 -81
  111. package/src/agent-tools-login.ts +0 -113
  112. package/src/approval-auth.test.ts +0 -24
  113. package/src/approval-auth.ts +0 -27
  114. package/src/auth-store.runtime.ts +0 -1
  115. package/src/auth-store.test.ts +0 -311
  116. package/src/auth-store.ts +0 -502
  117. package/src/auto-reply/config.runtime.ts +0 -16
  118. package/src/auto-reply/constants.ts +0 -1
  119. package/src/auto-reply/deliver-reply.test.ts +0 -843
  120. package/src/auto-reply/deliver-reply.ts +0 -279
  121. package/src/auto-reply/loggers.ts +0 -6
  122. package/src/auto-reply/mentions.ts +0 -131
  123. package/src/auto-reply/monitor/ack-reaction.test.ts +0 -170
  124. package/src/auto-reply/monitor/ack-reaction.ts +0 -99
  125. package/src/auto-reply/monitor/audio-preflight.runtime.ts +0 -9
  126. package/src/auto-reply/monitor/broadcast.ts +0 -153
  127. package/src/auto-reply/monitor/commands.ts +0 -19
  128. package/src/auto-reply/monitor/echo.ts +0 -64
  129. package/src/auto-reply/monitor/group-activation.runtime.ts +0 -1
  130. package/src/auto-reply/monitor/group-activation.test.ts +0 -189
  131. package/src/auto-reply/monitor/group-activation.ts +0 -73
  132. package/src/auto-reply/monitor/group-gating.audio-preflight.test.ts +0 -103
  133. package/src/auto-reply/monitor/group-gating.runtime.ts +0 -8
  134. package/src/auto-reply/monitor/group-gating.ts +0 -217
  135. package/src/auto-reply/monitor/group-members.test.ts +0 -56
  136. package/src/auto-reply/monitor/group-members.ts +0 -65
  137. package/src/auto-reply/monitor/inbound-context.test.ts +0 -97
  138. package/src/auto-reply/monitor/inbound-context.ts +0 -92
  139. package/src/auto-reply/monitor/inbound-dispatch.runtime.ts +0 -21
  140. package/src/auto-reply/monitor/inbound-dispatch.test.ts +0 -895
  141. package/src/auto-reply/monitor/inbound-dispatch.ts +0 -422
  142. package/src/auto-reply/monitor/last-route.test.ts +0 -37
  143. package/src/auto-reply/monitor/last-route.ts +0 -61
  144. package/src/auto-reply/monitor/message-line.runtime.ts +0 -38
  145. package/src/auto-reply/monitor/message-line.ts +0 -54
  146. package/src/auto-reply/monitor/on-message.audio-preflight.test.ts +0 -354
  147. package/src/auto-reply/monitor/on-message.ts +0 -291
  148. package/src/auto-reply/monitor/peer.ts +0 -17
  149. package/src/auto-reply/monitor/process-message.audio-preflight.test.ts +0 -420
  150. package/src/auto-reply/monitor/process-message.test.ts +0 -355
  151. package/src/auto-reply/monitor/process-message.ts +0 -531
  152. package/src/auto-reply/monitor/runtime-api.ts +0 -30
  153. package/src/auto-reply/monitor-state.test.ts +0 -64
  154. package/src/auto-reply/monitor-state.ts +0 -106
  155. package/src/auto-reply/monitor.ts +0 -600
  156. package/src/auto-reply/reply-resolver.runtime.ts +0 -1
  157. package/src/auto-reply/types.ts +0 -48
  158. package/src/auto-reply/util.ts +0 -63
  159. package/src/auto-reply/web-auto-reply-monitor.test.ts +0 -687
  160. package/src/auto-reply/web-auto-reply-utils.test.ts +0 -392
  161. package/src/auto-reply.broadcast-groups.combined.test.ts +0 -246
  162. package/src/auto-reply.broadcast-groups.test-harness.ts +0 -47
  163. package/src/auto-reply.impl.ts +0 -6
  164. package/src/auto-reply.test-harness.ts +0 -421
  165. package/src/auto-reply.ts +0 -1
  166. package/src/auto-reply.web-auto-reply.compresses-common-formats-jpeg-cap.test.ts +0 -427
  167. package/src/auto-reply.web-auto-reply.connection-and-logging.e2e.test.ts +0 -908
  168. package/src/auto-reply.web-auto-reply.last-route.test.ts +0 -184
  169. package/src/channel-actions.runtime.ts +0 -7
  170. package/src/channel-actions.test.ts +0 -216
  171. package/src/channel-actions.ts +0 -84
  172. package/src/channel-outbound.test.ts +0 -131
  173. package/src/channel-outbound.ts +0 -36
  174. package/src/channel-react-action.runtime.ts +0 -7
  175. package/src/channel-react-action.test.ts +0 -294
  176. package/src/channel-react-action.ts +0 -84
  177. package/src/channel.runtime.ts +0 -117
  178. package/src/channel.setup.test.ts +0 -461
  179. package/src/channel.setup.ts +0 -28
  180. package/src/channel.ts +0 -339
  181. package/src/command-policy.ts +0 -7
  182. package/src/config-accessors.test.ts +0 -34
  183. package/src/config-accessors.ts +0 -22
  184. package/src/config-schema.test.ts +0 -121
  185. package/src/config-schema.ts +0 -6
  186. package/src/config-ui-hints.ts +0 -24
  187. package/src/connection-controller-registry.test.ts +0 -27
  188. package/src/connection-controller-registry.ts +0 -49
  189. package/src/connection-controller.test.ts +0 -282
  190. package/src/connection-controller.ts +0 -679
  191. package/src/creds-files.ts +0 -19
  192. package/src/creds-persistence.ts +0 -102
  193. package/src/directory-config.test.ts +0 -60
  194. package/src/directory-config.ts +0 -40
  195. package/src/directory-contract.test.ts +0 -56
  196. package/src/doctor-contract.ts +0 -11
  197. package/src/doctor.test.ts +0 -74
  198. package/src/doctor.ts +0 -56
  199. package/src/group-intro.ts +0 -15
  200. package/src/group-policy.test.ts +0 -36
  201. package/src/group-policy.ts +0 -40
  202. package/src/group-session-contract.ts +0 -20
  203. package/src/group-session-key.test.ts +0 -53
  204. package/src/group-session-key.ts +0 -41
  205. package/src/heartbeat.ts +0 -34
  206. package/src/identity.ts +0 -164
  207. package/src/inbound/access-control.test-harness.ts +0 -37
  208. package/src/inbound/access-control.test.ts +0 -375
  209. package/src/inbound/access-control.ts +0 -237
  210. package/src/inbound/dedupe.ts +0 -132
  211. package/src/inbound/extract.test.ts +0 -282
  212. package/src/inbound/extract.ts +0 -488
  213. package/src/inbound/lifecycle.ts +0 -39
  214. package/src/inbound/media.node.test.ts +0 -83
  215. package/src/inbound/media.ts +0 -102
  216. package/src/inbound/monitor.ts +0 -890
  217. package/src/inbound/runtime-api.ts +0 -7
  218. package/src/inbound/save-media.runtime.ts +0 -1
  219. package/src/inbound/send-api.test.ts +0 -319
  220. package/src/inbound/send-api.ts +0 -145
  221. package/src/inbound/send-result.ts +0 -61
  222. package/src/inbound/types.ts +0 -106
  223. package/src/inbound-context.contract.test.ts +0 -32
  224. package/src/inbound-policy.ts +0 -231
  225. package/src/inbound.media.test.ts +0 -320
  226. package/src/inbound.test.ts +0 -290
  227. package/src/inbound.ts +0 -9
  228. package/src/login-qr.test.ts +0 -483
  229. package/src/login-qr.ts +0 -542
  230. package/src/login.coverage.test.ts +0 -133
  231. package/src/login.test.ts +0 -89
  232. package/src/login.ts +0 -70
  233. package/src/logout.test.ts +0 -162
  234. package/src/media.test.ts +0 -480
  235. package/src/media.ts +0 -10
  236. package/src/monitor-inbox.allows-messages-from-senders-allowfrom-list.test-support.ts +0 -400
  237. package/src/monitor-inbox.append-upsert.test-support.ts +0 -133
  238. package/src/monitor-inbox.behavior.test.ts +0 -5
  239. package/src/monitor-inbox.blocks-messages-from-unauthorized-senders-not-allowfrom.test-support.ts +0 -362
  240. package/src/monitor-inbox.captures-media-path-image-messages.test-support.ts +0 -306
  241. package/src/monitor-inbox.streams-inbound-messages.test-support.ts +0 -729
  242. package/src/monitor-inbox.test-harness.ts +0 -304
  243. package/src/normalize-target.ts +0 -123
  244. package/src/normalize.ts +0 -7
  245. package/src/outbound-adapter.poll.test.ts +0 -62
  246. package/src/outbound-adapter.sendpayload.test.ts +0 -195
  247. package/src/outbound-adapter.ts +0 -36
  248. package/src/outbound-base.test.ts +0 -560
  249. package/src/outbound-base.ts +0 -244
  250. package/src/outbound-media-contract.ts +0 -278
  251. package/src/outbound-media.runtime.ts +0 -36
  252. package/src/outbound-payload.contract.test.ts +0 -61
  253. package/src/outbound-send-deps.ts +0 -1
  254. package/src/outbound-test-support.ts +0 -16
  255. package/src/pairing-security.test-harness.ts +0 -59
  256. package/src/qr-image.ts +0 -1
  257. package/src/qr-terminal.ts +0 -1
  258. package/src/quoted-message.test.ts +0 -83
  259. package/src/quoted-message.ts +0 -184
  260. package/src/reaction-level.test.ts +0 -94
  261. package/src/reaction-level.ts +0 -21
  262. package/src/reconnect.test.ts +0 -51
  263. package/src/reconnect.ts +0 -55
  264. package/src/resolve-outbound-target.test.ts +0 -288
  265. package/src/resolve-outbound-target.ts +0 -58
  266. package/src/resolve-target.test.ts +0 -120
  267. package/src/runtime-api.ts +0 -59
  268. package/src/runtime-group-policy.ts +0 -16
  269. package/src/runtime.ts +0 -9
  270. package/src/security-contract.ts +0 -47
  271. package/src/security-fix.ts +0 -71
  272. package/src/send.test.ts +0 -534
  273. package/src/send.ts +0 -292
  274. package/src/session-contract.test.ts +0 -31
  275. package/src/session-contract.ts +0 -43
  276. package/src/session-errors.ts +0 -125
  277. package/src/session-route.test.ts +0 -41
  278. package/src/session-route.ts +0 -32
  279. package/src/session.runtime.ts +0 -8
  280. package/src/session.test.ts +0 -559
  281. package/src/session.ts +0 -330
  282. package/src/setup-core.ts +0 -52
  283. package/src/setup-finalize.ts +0 -446
  284. package/src/setup-surface.test.ts +0 -367
  285. package/src/setup-surface.ts +0 -69
  286. package/src/setup-test-helpers.ts +0 -216
  287. package/src/shared.ts +0 -291
  288. package/src/socket-timing.test.ts +0 -49
  289. package/src/socket-timing.ts +0 -38
  290. package/src/state-migrations.ts +0 -54
  291. package/src/status-issues.test.ts +0 -137
  292. package/src/status-issues.ts +0 -185
  293. package/src/system-prompt.test.ts +0 -199
  294. package/src/system-prompt.ts +0 -31
  295. package/src/targets-runtime.ts +0 -180
  296. package/src/test-helpers.ts +0 -690
  297. package/src/text-runtime.test.ts +0 -162
  298. package/src/text-runtime.ts +0 -11
  299. package/src/vcard.ts +0 -84
  300. package/targets.ts +0 -5
  301. package/test-api.ts +0 -2
  302. package/tsconfig.json +0 -16
@@ -1,106 +0,0 @@
1
- import {
2
- createConnectedChannelStatusPatch,
3
- createTransportActivityStatusPatch,
4
- } from "openclaw/plugin-sdk/gateway-runtime";
5
- import type { WebChannelHealthState, WebChannelStatus } from "./types.js";
6
-
7
- function cloneStatus(status: WebChannelStatus): WebChannelStatus {
8
- return {
9
- ...status,
10
- lastDisconnect: status.lastDisconnect ? { ...status.lastDisconnect } : null,
11
- };
12
- }
13
-
14
- function isTerminalHealthState(healthState: WebChannelHealthState | undefined): boolean {
15
- return healthState === "conflict" || healthState === "logged-out" || healthState === "stopped";
16
- }
17
-
18
- export function createWebChannelStatusController(statusSink?: (status: WebChannelStatus) => void) {
19
- const status: WebChannelStatus = {
20
- running: true,
21
- connected: false,
22
- reconnectAttempts: 0,
23
- lastConnectedAt: null,
24
- lastDisconnect: null,
25
- lastInboundAt: null,
26
- lastMessageAt: null,
27
- lastEventAt: null,
28
- lastError: null,
29
- healthState: "starting",
30
- };
31
-
32
- const emit = () => {
33
- statusSink?.(cloneStatus(status));
34
- };
35
-
36
- return {
37
- emit,
38
- snapshot: () => status,
39
- noteConnected(at = Date.now()) {
40
- Object.assign(status, createConnectedChannelStatusPatch(at));
41
- Object.assign(status, createTransportActivityStatusPatch(at));
42
- status.lastError = null;
43
- status.healthState = "healthy";
44
- emit();
45
- },
46
- noteInbound(at = Date.now()) {
47
- status.lastInboundAt = at;
48
- status.lastMessageAt = at;
49
- status.lastEventAt = at;
50
- Object.assign(status, createTransportActivityStatusPatch(at));
51
- if (status.connected) {
52
- status.healthState = "healthy";
53
- }
54
- emit();
55
- },
56
- noteTransportActivity(at = Date.now()) {
57
- if (status.lastTransportActivityAt === at) {
58
- return;
59
- }
60
- Object.assign(status, createTransportActivityStatusPatch(at));
61
- emit();
62
- },
63
- noteWatchdogStale(at = Date.now()) {
64
- status.lastEventAt = at;
65
- if (status.connected) {
66
- status.healthState = "stale";
67
- }
68
- emit();
69
- },
70
- noteReconnectAttempts(reconnectAttempts: number) {
71
- status.reconnectAttempts = reconnectAttempts;
72
- emit();
73
- },
74
- noteClose(params: {
75
- at?: number;
76
- statusCode?: number;
77
- loggedOut?: boolean;
78
- error?: string;
79
- reconnectAttempts: number;
80
- healthState: WebChannelHealthState;
81
- }) {
82
- const at = params.at ?? Date.now();
83
- status.connected = false;
84
- status.lastEventAt = at;
85
- status.lastDisconnect = {
86
- at,
87
- status: params.statusCode,
88
- error: params.error,
89
- loggedOut: Boolean(params.loggedOut),
90
- };
91
- status.lastError = params.error ?? null;
92
- status.reconnectAttempts = params.reconnectAttempts;
93
- status.healthState = params.healthState;
94
- emit();
95
- },
96
- markStopped(at = Date.now()) {
97
- status.running = false;
98
- status.connected = false;
99
- status.lastEventAt = at;
100
- if (!isTerminalHealthState(status.healthState)) {
101
- status.healthState = "stopped";
102
- }
103
- emit();
104
- },
105
- };
106
- }
@@ -1,600 +0,0 @@
1
- import { resolveAccountEntry } from "openclaw/plugin-sdk/account-core";
2
- import { resolveInboundDebounceMs } from "openclaw/plugin-sdk/channel-inbound-debounce";
3
- import { formatCliCommand } from "openclaw/plugin-sdk/cli-runtime";
4
- import { hasControlCommand } from "openclaw/plugin-sdk/command-detection";
5
- import { drainPendingDeliveries } from "openclaw/plugin-sdk/delivery-queue-runtime";
6
- import { DEFAULT_GROUP_HISTORY_LIMIT } from "openclaw/plugin-sdk/reply-history";
7
- import { resolveAgentRoute } from "openclaw/plugin-sdk/routing";
8
- import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
9
- import { registerUnhandledRejectionHandler } from "openclaw/plugin-sdk/runtime-env";
10
- import { getChildLogger } from "openclaw/plugin-sdk/runtime-env";
11
- import {
12
- defaultRuntime,
13
- formatDurationPrecise,
14
- type RuntimeEnv,
15
- } from "openclaw/plugin-sdk/runtime-env";
16
- import { enqueueSystemEvent } from "openclaw/plugin-sdk/system-event-runtime";
17
- import { resolveWhatsAppAccount, resolveWhatsAppMediaMaxBytes } from "../accounts.js";
18
- import { WHATSAPP_AUTH_UNSTABLE_CODE, WhatsAppAuthUnstableError } from "../auth-store.js";
19
- import {
20
- WhatsAppConnectionController,
21
- type ManagedWhatsAppListener,
22
- } from "../connection-controller.js";
23
- import { attachWebInboxToSocket, type WhatsAppGroupMetadataCache } from "../inbound/monitor.js";
24
- import {
25
- newConnectionId,
26
- resolveHeartbeatSeconds,
27
- resolveReconnectPolicy,
28
- sleepWithAbort,
29
- } from "../reconnect.js";
30
- import { formatError, getWebAuthAgeMs, logoutWeb, readWebSelfId } from "../session.js";
31
- import { resolveWhatsAppSocketTiming } from "../socket-timing.js";
32
- import { getRuntimeConfig, getRuntimeConfigSourceSnapshot } from "./config.runtime.js";
33
- import { whatsappHeartbeatLog, whatsappLog } from "./loggers.js";
34
- import { buildMentionConfig } from "./mentions.js";
35
- import { createWebChannelStatusController } from "./monitor-state.js";
36
- import { createEchoTracker } from "./monitor/echo.js";
37
- import { createWebOnMessageHandler } from "./monitor/on-message.js";
38
- import type { WebInboundMsg, WebMonitorTuning } from "./types.js";
39
- import { isLikelyWhatsAppCryptoError } from "./util.js";
40
-
41
- function isNonRetryableWebCloseStatus(statusCode: unknown): boolean {
42
- // WhatsApp 440 = session conflict ("Unknown Stream Errored (conflict)").
43
- // This is persistent until the operator resolves the conflicting session.
44
- return statusCode === 440;
45
- }
46
-
47
- type ReplyResolver = typeof import("./reply-resolver.runtime.js").getReplyFromConfig;
48
-
49
- let replyResolverRuntimePromise: Promise<typeof import("./reply-resolver.runtime.js")> | null =
50
- null;
51
-
52
- function loadReplyResolverRuntime() {
53
- replyResolverRuntimePromise ??= import("./reply-resolver.runtime.js");
54
- return replyResolverRuntimePromise;
55
- }
56
-
57
- function normalizeReconnectAccountId(accountId?: string | null): string {
58
- return (accountId ?? "").trim() || "default";
59
- }
60
-
61
- function isNoListenerReconnectError(lastError?: string): boolean {
62
- return typeof lastError === "string" && /No active WhatsApp Web listener/i.test(lastError);
63
- }
64
-
65
- function resolveExplicitWhatsAppDebounceOverride(params: {
66
- cfg: ReturnType<typeof getRuntimeConfig>;
67
- sourceCfg?: ReturnType<typeof getRuntimeConfig> | null;
68
- accountId: string;
69
- }): number | undefined {
70
- const channel = params.sourceCfg?.channels?.whatsapp;
71
- if (!channel) {
72
- return undefined;
73
- }
74
-
75
- const accountId = normalizeReconnectAccountId(params.accountId);
76
- const accountDebounce = resolveAccountEntry(channel.accounts, accountId)?.debounceMs;
77
- if (accountDebounce !== undefined) {
78
- return accountDebounce;
79
- }
80
- if (accountId !== "default") {
81
- const defaultAccountDebounce = resolveAccountEntry(channel.accounts, "default")?.debounceMs;
82
- if (defaultAccountDebounce !== undefined) {
83
- return defaultAccountDebounce;
84
- }
85
- }
86
-
87
- return channel.debounceMs;
88
- }
89
-
90
- function isRetryableAuthUnstableError(error: unknown): error is WhatsAppAuthUnstableError {
91
- return (
92
- error instanceof WhatsAppAuthUnstableError ||
93
- (typeof error === "object" &&
94
- error !== null &&
95
- "code" in error &&
96
- (error as { code?: unknown }).code === WHATSAPP_AUTH_UNSTABLE_CODE)
97
- );
98
- }
99
-
100
- async function clearTerminalWebAuthState(params: {
101
- account: ReturnType<typeof resolveWhatsAppAccount>;
102
- runtime: RuntimeEnv;
103
- statusLabel: number | "unknown";
104
- healthState: "logged-out" | "conflict";
105
- log: ReturnType<typeof getChildLogger>;
106
- }) {
107
- try {
108
- const cleared = await logoutWeb({
109
- authDir: params.account.authDir,
110
- isLegacyAuthDir: params.account.isLegacyAuthDir,
111
- runtime: params.runtime,
112
- });
113
- params.log.warn(
114
- {
115
- accountId: params.account.accountId,
116
- cleared,
117
- healthState: params.healthState,
118
- status: params.statusLabel,
119
- },
120
- "web reconnect: cleared cached auth after terminal close",
121
- );
122
- } catch (error) {
123
- params.log.warn(
124
- {
125
- accountId: params.account.accountId,
126
- error: formatError(error),
127
- healthState: params.healthState,
128
- status: params.statusLabel,
129
- },
130
- "web reconnect: failed clearing cached auth after terminal close",
131
- );
132
- params.runtime.error(
133
- `WhatsApp Web cleanup failed after terminal close (status ${params.statusLabel}). Run \`${formatCliCommand("openclaw channels logout --channel whatsapp")}\`, then relink with \`${formatCliCommand("openclaw channels login --channel whatsapp")}\`.`,
134
- );
135
- }
136
- }
137
- const DEFAULT_TRANSPORT_TIMEOUT_MS = 5 * 60 * 1000;
138
-
139
- export async function monitorWebChannel(
140
- verbose: boolean,
141
- listenerFactory: typeof attachWebInboxToSocket | undefined = attachWebInboxToSocket,
142
- keepAlive = true,
143
- replyResolver?: ReplyResolver,
144
- runtime: RuntimeEnv = defaultRuntime,
145
- abortSignal?: AbortSignal,
146
- tuning: WebMonitorTuning = {},
147
- ) {
148
- const activeReplyResolver =
149
- replyResolver ?? (await loadReplyResolverRuntime()).getReplyFromConfig;
150
- const runId = newConnectionId();
151
- const replyLogger = getChildLogger({ module: "web-auto-reply", runId });
152
- const heartbeatLogger = getChildLogger({ module: "web-heartbeat", runId });
153
- const reconnectLogger = getChildLogger({ module: "web-reconnect", runId });
154
- const statusController = createWebChannelStatusController(tuning.statusSink);
155
- statusController.emit();
156
-
157
- const baseCfg = getRuntimeConfig();
158
- const sourceCfg = getRuntimeConfigSourceSnapshot();
159
- const account = resolveWhatsAppAccount({
160
- cfg: baseCfg,
161
- accountId: tuning.accountId,
162
- });
163
- const cfg = {
164
- ...baseCfg,
165
- channels: {
166
- ...baseCfg.channels,
167
- whatsapp: {
168
- ...baseCfg.channels?.whatsapp,
169
- ackReaction: account.ackReaction,
170
- messagePrefix: account.messagePrefix,
171
- allowFrom: account.allowFrom,
172
- groupAllowFrom: account.groupAllowFrom,
173
- groupPolicy: account.groupPolicy,
174
- textChunkLimit: account.textChunkLimit,
175
- chunkMode: account.chunkMode,
176
- mediaMaxMb: account.mediaMaxMb,
177
- blockStreaming: account.blockStreaming,
178
- groups: account.groups,
179
- },
180
- },
181
- } satisfies ReturnType<typeof getRuntimeConfig>;
182
-
183
- const maxMediaBytes = resolveWhatsAppMediaMaxBytes(account);
184
- const heartbeatSeconds = resolveHeartbeatSeconds(cfg, tuning.heartbeatSeconds);
185
- const reconnectPolicy = resolveReconnectPolicy(cfg, tuning.reconnect);
186
- const socketTiming = resolveWhatsAppSocketTiming(cfg, tuning.socketTiming);
187
- const baseMentionConfig = buildMentionConfig(cfg);
188
- const groupHistoryLimit =
189
- account.historyLimit ??
190
- cfg.channels?.whatsapp?.historyLimit ??
191
- cfg.messages?.groupChat?.historyLimit ??
192
- DEFAULT_GROUP_HISTORY_LIMIT;
193
- const groupHistories = new Map<
194
- string,
195
- Array<{
196
- sender: string;
197
- body: string;
198
- timestamp?: number;
199
- id?: string;
200
- senderJid?: string;
201
- }>
202
- >();
203
- const groupMemberNames = new Map<string, Map<string, string>>();
204
- const groupMetadataCache: WhatsAppGroupMetadataCache = new Map();
205
- const echoTracker = createEchoTracker({ maxItems: 100, logVerbose });
206
-
207
- const sleep =
208
- tuning.sleep ??
209
- ((ms: number, signal?: AbortSignal) => sleepWithAbort(ms, signal ?? abortSignal));
210
- const stopRequested = () => abortSignal?.aborted === true;
211
-
212
- // Avoid noisy MaxListenersExceeded warnings in test environments where
213
- // multiple gateway instances may be constructed.
214
- const currentMaxListeners = process.getMaxListeners?.() ?? 10;
215
- if (process.setMaxListeners && currentMaxListeners < 50) {
216
- process.setMaxListeners(50);
217
- }
218
-
219
- let sigintStop = false;
220
- const handleSigint = () => {
221
- sigintStop = true;
222
- };
223
- process.once("SIGINT", handleSigint);
224
-
225
- const transportTimeoutMs = tuning.transportTimeoutMs ?? DEFAULT_TRANSPORT_TIMEOUT_MS;
226
- const messageTimeoutMs = tuning.messageTimeoutMs ?? 30 * 60 * 1000;
227
- const watchdogCheckMs = tuning.watchdogCheckMs ?? 60 * 1000;
228
- const controller = new WhatsAppConnectionController({
229
- accountId: account.accountId,
230
- authDir: account.authDir,
231
- verbose,
232
- keepAlive,
233
- heartbeatSeconds,
234
- transportTimeoutMs,
235
- messageTimeoutMs,
236
- watchdogCheckMs,
237
- reconnectPolicy,
238
- socketTiming,
239
- abortSignal,
240
- sleep,
241
- isNonRetryableStatus: isNonRetryableWebCloseStatus,
242
- });
243
-
244
- try {
245
- while (true) {
246
- if (stopRequested()) {
247
- break;
248
- }
249
-
250
- const connectionId = newConnectionId();
251
- const inboundDebounceMs = resolveInboundDebounceMs({
252
- cfg,
253
- channel: "whatsapp",
254
- overrideMs: resolveExplicitWhatsAppDebounceOverride({
255
- cfg,
256
- sourceCfg,
257
- accountId: account.accountId,
258
- }),
259
- });
260
- const shouldDebounce = (msg: WebInboundMsg) => {
261
- if (msg.mediaPath || msg.mediaType) {
262
- return false;
263
- }
264
- if (msg.location) {
265
- return false;
266
- }
267
- if (msg.replyToId || msg.replyToBody) {
268
- return false;
269
- }
270
- return !hasControlCommand(msg.body, cfg);
271
- };
272
-
273
- let connection;
274
- try {
275
- connection = await controller.openConnection({
276
- connectionId,
277
- createListener: async ({ sock, connection }) => {
278
- const onMessage = createWebOnMessageHandler({
279
- cfg,
280
- verbose,
281
- connectionId,
282
- maxMediaBytes,
283
- groupHistoryLimit,
284
- groupHistories,
285
- groupMemberNames,
286
- echoTracker,
287
- backgroundTasks: connection.backgroundTasks,
288
- replyResolver: activeReplyResolver,
289
- replyLogger,
290
- baseMentionConfig,
291
- account,
292
- });
293
-
294
- return (await (listenerFactory ?? attachWebInboxToSocket)({
295
- cfg,
296
- verbose,
297
- accountId: account.accountId,
298
- authDir: account.authDir,
299
- mediaMaxMb: account.mediaMaxMb,
300
- selfChatMode: account.selfChatMode,
301
- sendReadReceipts: account.sendReadReceipts,
302
- debounceMs: inboundDebounceMs,
303
- shouldDebounce,
304
- socketRef: controller.socketRef,
305
- shouldRetryDisconnect: () => !sigintStop && controller.shouldRetryDisconnect(),
306
- disconnectRetryPolicy: reconnectPolicy,
307
- disconnectRetryAbortSignal: controller.getDisconnectRetryAbortSignal(),
308
- groupMetadataCache,
309
- onMessage: async (msg: WebInboundMsg) => {
310
- const inboundAt = Date.now();
311
- controller.noteInbound(inboundAt);
312
- statusController.noteInbound(inboundAt);
313
- await onMessage(msg);
314
- },
315
- sock,
316
- })) as ManagedWhatsAppListener;
317
- },
318
- onHeartbeat: (snapshot) => {
319
- const authAgeMs = getWebAuthAgeMs(account.authDir);
320
- const minutesSinceLastMessage = snapshot.lastInboundAt
321
- ? Math.floor((Date.now() - snapshot.lastInboundAt) / 60000)
322
- : null;
323
-
324
- const logData = {
325
- connectionId: snapshot.connectionId,
326
- reconnectAttempts: snapshot.reconnectAttempts,
327
- messagesHandled: snapshot.handledMessages,
328
- lastInboundAt: snapshot.lastInboundAt,
329
- lastTransportActivityAt: snapshot.lastTransportActivityAt,
330
- authAgeMs,
331
- uptimeMs: snapshot.uptimeMs,
332
- ...(minutesSinceLastMessage !== null && minutesSinceLastMessage > 30
333
- ? { minutesSinceLastMessage }
334
- : {}),
335
- };
336
- statusController.noteTransportActivity(snapshot.lastTransportActivityAt);
337
-
338
- if (minutesSinceLastMessage && minutesSinceLastMessage > 30) {
339
- heartbeatLogger.warn(
340
- logData,
341
- "⚠️ web gateway heartbeat - no messages in 30+ minutes",
342
- );
343
- } else {
344
- heartbeatLogger.info(logData, "web gateway heartbeat");
345
- }
346
- },
347
- onWatchdogTimeout: (snapshot) => {
348
- const now = Date.now();
349
- const transportSilentMs = now - snapshot.lastTransportActivityAt;
350
- const appBaselineAt = snapshot.lastInboundAt ?? snapshot.startedAt;
351
- const minutesSinceTransportActivity = Math.floor(transportSilentMs / 60000);
352
- const minutesSinceAppActivity = Math.floor((now - appBaselineAt) / 60000);
353
- const watchdogReason =
354
- transportSilentMs > transportTimeoutMs ? "transport-inactive" : "app-silent";
355
- statusController.noteWatchdogStale();
356
- heartbeatLogger.warn(
357
- {
358
- connectionId: snapshot.connectionId,
359
- watchdogReason,
360
- minutesSinceTransportActivity,
361
- minutesSinceAppActivity,
362
- lastInboundAt: snapshot.lastInboundAt ? new Date(snapshot.lastInboundAt) : null,
363
- lastTransportActivityAt: new Date(snapshot.lastTransportActivityAt),
364
- messagesHandled: snapshot.handledMessages,
365
- },
366
- "WhatsApp watchdog timeout detected - forcing reconnect",
367
- );
368
- whatsappHeartbeatLog.warn(
369
- `WhatsApp watchdog timeout (${watchdogReason}) - restarting connection`,
370
- );
371
- },
372
- });
373
- } catch (error) {
374
- if (!isRetryableAuthUnstableError(error)) {
375
- throw error;
376
- }
377
- const retryDecision = controller.consumeReconnectAttempt();
378
- statusController.noteReconnectAttempts(retryDecision.reconnectAttempts);
379
- statusController.noteClose({
380
- error: error.message,
381
- reconnectAttempts: retryDecision.reconnectAttempts,
382
- healthState: retryDecision.healthState,
383
- });
384
- if (retryDecision.action === "stop") {
385
- reconnectLogger.warn(
386
- {
387
- connectionId,
388
- reconnectAttempts: retryDecision.reconnectAttempts,
389
- maxAttempts: reconnectPolicy.maxAttempts,
390
- },
391
- "web reconnect: auth state stayed unstable; max attempts reached",
392
- );
393
- runtime.error(
394
- `WhatsApp auth state is still stabilizing after ${retryDecision.reconnectAttempts}/${reconnectPolicy.maxAttempts} attempts. Stopping web monitoring.`,
395
- );
396
- await controller.shutdown();
397
- break;
398
- }
399
- reconnectLogger.info(
400
- {
401
- connectionId,
402
- reconnectAttempts: retryDecision.reconnectAttempts,
403
- delayMs: retryDecision.delayMs,
404
- },
405
- "web reconnect: auth state still stabilizing during inbox attach; retrying",
406
- );
407
- runtime.error(
408
- `WhatsApp auth state is still stabilizing. Retry ${retryDecision.reconnectAttempts}/${reconnectPolicy.maxAttempts || "∞"} for inbox attach in ${formatDurationPrecise(retryDecision.delayMs ?? 0)}.`,
409
- );
410
- try {
411
- await controller.waitBeforeRetry(retryDecision.delayMs ?? 0);
412
- } catch {
413
- break;
414
- }
415
- continue;
416
- }
417
-
418
- statusController.noteConnected();
419
- controller.setUnhandledRejectionCleanup(
420
- registerUnhandledRejectionHandler((reason) => {
421
- if (!isLikelyWhatsAppCryptoError(reason)) {
422
- return false;
423
- }
424
- const errorStr = formatError(reason);
425
- reconnectLogger.warn(
426
- { connectionId: connection.connectionId, error: errorStr },
427
- "web reconnect: unhandled rejection from WhatsApp socket; forcing reconnect",
428
- );
429
- controller.forceClose({
430
- status: 499,
431
- isLoggedOut: false,
432
- error: reason,
433
- });
434
- return true;
435
- }),
436
- );
437
-
438
- const { e164: selfE164 } = readWebSelfId(account.authDir);
439
- const connectRoute = resolveAgentRoute({
440
- cfg,
441
- channel: "whatsapp",
442
- accountId: account.accountId,
443
- });
444
- enqueueSystemEvent(`WhatsApp gateway connected${selfE164 ? ` as ${selfE164}` : ""}.`, {
445
- sessionKey: connectRoute.sessionKey,
446
- trusted: true,
447
- });
448
-
449
- const normalizedAccountId = normalizeReconnectAccountId(account.accountId);
450
- void drainPendingDeliveries({
451
- drainKey: `whatsapp:${normalizedAccountId}`,
452
- logLabel: "WhatsApp reconnect drain",
453
- cfg,
454
- log: reconnectLogger,
455
- selectEntry: (entry) => ({
456
- match:
457
- entry.channel === "whatsapp" &&
458
- normalizeReconnectAccountId(entry.accountId) === normalizedAccountId,
459
- bypassBackoff: isNoListenerReconnectError(entry.lastError),
460
- }),
461
- }).catch((err) => {
462
- reconnectLogger.warn(
463
- { connectionId: connection.connectionId, error: String(err) },
464
- "reconnect drain failed",
465
- );
466
- });
467
-
468
- whatsappLog.info("Listening for personal WhatsApp inbound messages.");
469
- if (process.stdout.isTTY || process.stderr.isTTY) {
470
- whatsappLog.raw("Ctrl+C to stop.");
471
- }
472
-
473
- if (!keepAlive) {
474
- await controller.shutdown();
475
- return;
476
- }
477
-
478
- const reason = await controller.waitForClose();
479
- if (stopRequested() || sigintStop || reason === "aborted") {
480
- await controller.shutdown();
481
- break;
482
- }
483
-
484
- const decision = controller.resolveCloseDecision(reason);
485
- if (decision === "aborted") {
486
- await controller.shutdown();
487
- break;
488
- }
489
- statusController.noteReconnectAttempts(controller.getReconnectAttempts());
490
-
491
- reconnectLogger.info(
492
- {
493
- connectionId: connection.connectionId,
494
- status: decision.normalized.statusLabel,
495
- loggedOut: decision.normalized.isLoggedOut,
496
- reconnectAttempts: decision.reconnectAttempts,
497
- error: decision.normalized.errorText,
498
- },
499
- "web reconnect: connection closed",
500
- );
501
-
502
- enqueueSystemEvent(
503
- `WhatsApp gateway disconnected (status ${decision.normalized.statusLabel})`,
504
- {
505
- sessionKey: connectRoute.sessionKey,
506
- trusted: true,
507
- },
508
- );
509
-
510
- if (decision.action === "stop") {
511
- await controller.closeCurrentConnection();
512
- statusController.noteClose({
513
- statusCode: decision.normalized.statusCode,
514
- loggedOut: decision.normalized.isLoggedOut,
515
- error: decision.normalized.errorText,
516
- reconnectAttempts: decision.reconnectAttempts,
517
- healthState: decision.healthState,
518
- });
519
-
520
- if (decision.healthState === "logged-out") {
521
- await clearTerminalWebAuthState({
522
- account,
523
- runtime,
524
- statusLabel: decision.normalized.statusLabel,
525
- healthState: decision.healthState,
526
- log: reconnectLogger,
527
- });
528
- runtime.error(
529
- `WhatsApp session logged out. Run \`${formatCliCommand("openclaw channels login --channel whatsapp")}\` to relink.`,
530
- );
531
- } else if (decision.healthState === "conflict") {
532
- await clearTerminalWebAuthState({
533
- account,
534
- runtime,
535
- statusLabel: decision.normalized.statusLabel,
536
- healthState: decision.healthState,
537
- log: reconnectLogger,
538
- });
539
- reconnectLogger.warn(
540
- {
541
- connectionId: connection.connectionId,
542
- status: decision.normalized.statusLabel,
543
- error: decision.normalized.errorText,
544
- },
545
- "web reconnect: non-retryable close status; stopping monitor",
546
- );
547
- runtime.error(
548
- `WhatsApp Web connection closed (status ${decision.normalized.statusLabel}: session conflict). Resolve conflicting WhatsApp Web sessions, then relink with \`${formatCliCommand("openclaw channels login --channel whatsapp")}\`. Stopping web monitoring.`,
549
- );
550
- } else {
551
- reconnectLogger.warn(
552
- {
553
- connectionId: connection.connectionId,
554
- status: decision.normalized.statusLabel,
555
- reconnectAttempts: decision.reconnectAttempts,
556
- maxAttempts: reconnectPolicy.maxAttempts,
557
- },
558
- "web reconnect: max attempts reached; continuing in degraded mode",
559
- );
560
- runtime.error(
561
- `WhatsApp Web reconnect: max attempts reached (${decision.reconnectAttempts}/${reconnectPolicy.maxAttempts}). Stopping web monitoring.`,
562
- );
563
- }
564
-
565
- await controller.shutdown();
566
- break;
567
- }
568
-
569
- statusController.noteClose({
570
- statusCode: decision.normalized.statusCode,
571
- error: decision.normalized.errorText,
572
- reconnectAttempts: decision.reconnectAttempts,
573
- healthState: decision.healthState,
574
- });
575
- reconnectLogger.info(
576
- {
577
- connectionId: connection.connectionId,
578
- status: decision.normalized.statusLabel,
579
- reconnectAttempts: decision.reconnectAttempts,
580
- maxAttempts: reconnectPolicy.maxAttempts || "unlimited",
581
- delayMs: decision.delayMs,
582
- },
583
- "web reconnect: scheduling retry",
584
- );
585
- runtime.error(
586
- `WhatsApp Web connection closed (status ${decision.normalized.statusLabel}). Retry ${decision.reconnectAttempts}/${reconnectPolicy.maxAttempts || "∞"} in ${formatDurationPrecise(decision.delayMs ?? 0)}… (${decision.normalized.errorText})`,
587
- );
588
- await controller.closeCurrentConnection();
589
- try {
590
- await controller.waitBeforeRetry(decision.delayMs ?? 0);
591
- } catch {
592
- break;
593
- }
594
- }
595
- } finally {
596
- statusController.markStopped();
597
- process.removeListener("SIGINT", handleSigint);
598
- await controller.shutdown();
599
- }
600
- }
@@ -1 +0,0 @@
1
- export { getReplyFromConfig } from "openclaw/plugin-sdk/reply-runtime";