@openclaw/whatsapp 2026.5.1-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 (239) hide show
  1. package/action-runtime-api.ts +1 -0
  2. package/action-runtime.runtime.ts +1 -0
  3. package/api.ts +213 -0
  4. package/auth-presence.ts +80 -0
  5. package/channel-config-api.ts +1 -0
  6. package/channel-plugin-api.ts +3 -0
  7. package/config-api.ts +4 -0
  8. package/constants.ts +1 -0
  9. package/contract-api.ts +29 -0
  10. package/directory-contract-api.ts +4 -0
  11. package/dist/.boundary-tsc.stamp +1 -0
  12. package/dist/.boundary-tsc.tsbuildinfo +1 -0
  13. package/doctor-contract-api.ts +8 -0
  14. package/index.test.ts +13 -0
  15. package/index.ts +16 -0
  16. package/legacy-session-surface-api.ts +6 -0
  17. package/legacy-state-migrations-api.ts +1 -0
  18. package/light-runtime-api.ts +12 -0
  19. package/login-qr-api.ts +1 -0
  20. package/login-qr-runtime.ts +23 -0
  21. package/openclaw.plugin.json +742 -0
  22. package/outbound-payload-test-api.ts +1 -0
  23. package/package.json +74 -0
  24. package/runtime-api.ts +86 -0
  25. package/secret-contract-api.ts +4 -0
  26. package/security-contract-api.ts +4 -0
  27. package/setup-entry.test.ts +21 -0
  28. package/setup-entry.ts +21 -0
  29. package/setup-plugin-api.ts +3 -0
  30. package/src/account-config.ts +77 -0
  31. package/src/account-ids.ts +13 -0
  32. package/src/account-types.ts +5 -0
  33. package/src/accounts.test.ts +182 -0
  34. package/src/accounts.ts +176 -0
  35. package/src/accounts.whatsapp-auth.test.ts +59 -0
  36. package/src/action-runtime-target-auth.ts +27 -0
  37. package/src/action-runtime.test.ts +330 -0
  38. package/src/action-runtime.ts +76 -0
  39. package/src/active-listener.test.ts +65 -0
  40. package/src/active-listener.ts +17 -0
  41. package/src/agent-tools-login.test.ts +81 -0
  42. package/src/agent-tools-login.ts +113 -0
  43. package/src/approval-auth.test.ts +24 -0
  44. package/src/approval-auth.ts +27 -0
  45. package/src/auth-store.runtime.ts +1 -0
  46. package/src/auth-store.test.ts +311 -0
  47. package/src/auth-store.ts +502 -0
  48. package/src/auto-reply/config.runtime.ts +16 -0
  49. package/src/auto-reply/constants.ts +1 -0
  50. package/src/auto-reply/deliver-reply.test.ts +843 -0
  51. package/src/auto-reply/deliver-reply.ts +279 -0
  52. package/src/auto-reply/heartbeat-runner.runtime.ts +33 -0
  53. package/src/auto-reply/heartbeat-runner.test.ts +214 -0
  54. package/src/auto-reply/heartbeat-runner.ts +330 -0
  55. package/src/auto-reply/loggers.ts +6 -0
  56. package/src/auto-reply/mentions.ts +131 -0
  57. package/src/auto-reply/monitor/ack-reaction.test.ts +170 -0
  58. package/src/auto-reply/monitor/ack-reaction.ts +99 -0
  59. package/src/auto-reply/monitor/audio-preflight.runtime.ts +9 -0
  60. package/src/auto-reply/monitor/broadcast.ts +153 -0
  61. package/src/auto-reply/monitor/commands.ts +19 -0
  62. package/src/auto-reply/monitor/echo.ts +64 -0
  63. package/src/auto-reply/monitor/group-activation.runtime.ts +1 -0
  64. package/src/auto-reply/monitor/group-activation.test.ts +189 -0
  65. package/src/auto-reply/monitor/group-activation.ts +73 -0
  66. package/src/auto-reply/monitor/group-gating.audio-preflight.test.ts +103 -0
  67. package/src/auto-reply/monitor/group-gating.runtime.ts +8 -0
  68. package/src/auto-reply/monitor/group-gating.ts +217 -0
  69. package/src/auto-reply/monitor/group-members.test.ts +56 -0
  70. package/src/auto-reply/monitor/group-members.ts +65 -0
  71. package/src/auto-reply/monitor/inbound-context.test.ts +97 -0
  72. package/src/auto-reply/monitor/inbound-context.ts +92 -0
  73. package/src/auto-reply/monitor/inbound-dispatch.runtime.ts +21 -0
  74. package/src/auto-reply/monitor/inbound-dispatch.test.ts +895 -0
  75. package/src/auto-reply/monitor/inbound-dispatch.ts +422 -0
  76. package/src/auto-reply/monitor/last-route.test.ts +37 -0
  77. package/src/auto-reply/monitor/last-route.ts +61 -0
  78. package/src/auto-reply/monitor/message-line.runtime.ts +38 -0
  79. package/src/auto-reply/monitor/message-line.ts +54 -0
  80. package/src/auto-reply/monitor/on-message.audio-preflight.test.ts +354 -0
  81. package/src/auto-reply/monitor/on-message.ts +291 -0
  82. package/src/auto-reply/monitor/peer.ts +17 -0
  83. package/src/auto-reply/monitor/process-message.audio-preflight.test.ts +420 -0
  84. package/src/auto-reply/monitor/process-message.test.ts +355 -0
  85. package/src/auto-reply/monitor/process-message.ts +531 -0
  86. package/src/auto-reply/monitor/runtime-api.ts +30 -0
  87. package/src/auto-reply/monitor-state.test.ts +64 -0
  88. package/src/auto-reply/monitor-state.ts +106 -0
  89. package/src/auto-reply/monitor.ts +600 -0
  90. package/src/auto-reply/reply-resolver.runtime.ts +1 -0
  91. package/src/auto-reply/session-snapshot.ts +69 -0
  92. package/src/auto-reply/types.ts +48 -0
  93. package/src/auto-reply/util.ts +63 -0
  94. package/src/auto-reply/web-auto-reply-monitor.test.ts +687 -0
  95. package/src/auto-reply/web-auto-reply-utils.test.ts +327 -0
  96. package/src/auto-reply.broadcast-groups.combined.test.ts +246 -0
  97. package/src/auto-reply.broadcast-groups.test-harness.ts +47 -0
  98. package/src/auto-reply.impl.ts +7 -0
  99. package/src/auto-reply.test-harness.ts +421 -0
  100. package/src/auto-reply.ts +1 -0
  101. package/src/auto-reply.web-auto-reply.compresses-common-formats-jpeg-cap.test.ts +427 -0
  102. package/src/auto-reply.web-auto-reply.connection-and-logging.e2e.test.ts +908 -0
  103. package/src/auto-reply.web-auto-reply.last-route.test.ts +184 -0
  104. package/src/channel-actions.runtime.ts +7 -0
  105. package/src/channel-actions.test.ts +216 -0
  106. package/src/channel-actions.ts +84 -0
  107. package/src/channel-outbound.test.ts +131 -0
  108. package/src/channel-outbound.ts +36 -0
  109. package/src/channel-react-action.runtime.ts +7 -0
  110. package/src/channel-react-action.test.ts +294 -0
  111. package/src/channel-react-action.ts +84 -0
  112. package/src/channel.runtime.ts +117 -0
  113. package/src/channel.setup.test.ts +461 -0
  114. package/src/channel.setup.ts +28 -0
  115. package/src/channel.ts +336 -0
  116. package/src/command-policy.ts +7 -0
  117. package/src/config-accessors.test.ts +34 -0
  118. package/src/config-accessors.ts +22 -0
  119. package/src/config-schema.test.ts +121 -0
  120. package/src/config-schema.ts +6 -0
  121. package/src/config-ui-hints.ts +24 -0
  122. package/src/connection-controller-registry.test.ts +27 -0
  123. package/src/connection-controller-registry.ts +49 -0
  124. package/src/connection-controller.test.ts +282 -0
  125. package/src/connection-controller.ts +679 -0
  126. package/src/creds-files.ts +19 -0
  127. package/src/creds-persistence.ts +102 -0
  128. package/src/directory-config.test.ts +60 -0
  129. package/src/directory-config.ts +40 -0
  130. package/src/directory-contract.test.ts +56 -0
  131. package/src/doctor-contract.ts +11 -0
  132. package/src/doctor.test.ts +74 -0
  133. package/src/doctor.ts +56 -0
  134. package/src/group-intro.ts +15 -0
  135. package/src/group-policy.test.ts +36 -0
  136. package/src/group-policy.ts +40 -0
  137. package/src/group-session-contract.ts +20 -0
  138. package/src/group-session-key.test.ts +53 -0
  139. package/src/group-session-key.ts +41 -0
  140. package/src/heartbeat-recipients.runtime.ts +6 -0
  141. package/src/heartbeat-recipients.test.ts +203 -0
  142. package/src/heartbeat-recipients.ts +104 -0
  143. package/src/heartbeat.ts +34 -0
  144. package/src/identity.ts +164 -0
  145. package/src/inbound/access-control.test-harness.ts +37 -0
  146. package/src/inbound/access-control.test.ts +375 -0
  147. package/src/inbound/access-control.ts +237 -0
  148. package/src/inbound/dedupe.ts +132 -0
  149. package/src/inbound/extract.test.ts +282 -0
  150. package/src/inbound/extract.ts +488 -0
  151. package/src/inbound/lifecycle.ts +39 -0
  152. package/src/inbound/media.node.test.ts +83 -0
  153. package/src/inbound/media.ts +102 -0
  154. package/src/inbound/monitor.ts +890 -0
  155. package/src/inbound/runtime-api.ts +7 -0
  156. package/src/inbound/save-media.runtime.ts +1 -0
  157. package/src/inbound/send-api.test.ts +307 -0
  158. package/src/inbound/send-api.ts +141 -0
  159. package/src/inbound/send-result.ts +61 -0
  160. package/src/inbound/types.ts +106 -0
  161. package/src/inbound-context.contract.test.ts +32 -0
  162. package/src/inbound-policy.ts +231 -0
  163. package/src/inbound.media.test.ts +320 -0
  164. package/src/inbound.test.ts +290 -0
  165. package/src/inbound.ts +9 -0
  166. package/src/login-qr.test.ts +483 -0
  167. package/src/login-qr.ts +542 -0
  168. package/src/login.coverage.test.ts +133 -0
  169. package/src/login.test.ts +89 -0
  170. package/src/login.ts +70 -0
  171. package/src/logout.test.ts +162 -0
  172. package/src/media.test.ts +480 -0
  173. package/src/media.ts +10 -0
  174. package/src/monitor-inbox.allows-messages-from-senders-allowfrom-list.test-support.ts +400 -0
  175. package/src/monitor-inbox.append-upsert.test-support.ts +133 -0
  176. package/src/monitor-inbox.behavior.test.ts +5 -0
  177. package/src/monitor-inbox.blocks-messages-from-unauthorized-senders-not-allowfrom.test-support.ts +362 -0
  178. package/src/monitor-inbox.captures-media-path-image-messages.test-support.ts +306 -0
  179. package/src/monitor-inbox.streams-inbound-messages.test-support.ts +729 -0
  180. package/src/monitor-inbox.test-harness.ts +304 -0
  181. package/src/normalize-target.ts +112 -0
  182. package/src/normalize.ts +6 -0
  183. package/src/outbound-adapter.poll.test.ts +62 -0
  184. package/src/outbound-adapter.sendpayload.test.ts +195 -0
  185. package/src/outbound-adapter.ts +36 -0
  186. package/src/outbound-base.test.ts +560 -0
  187. package/src/outbound-base.ts +244 -0
  188. package/src/outbound-media-contract.ts +278 -0
  189. package/src/outbound-media.runtime.ts +36 -0
  190. package/src/outbound-payload.contract.test.ts +61 -0
  191. package/src/outbound-send-deps.ts +1 -0
  192. package/src/outbound-test-support.ts +16 -0
  193. package/src/pairing-security.test-harness.ts +59 -0
  194. package/src/qr-image.ts +1 -0
  195. package/src/qr-terminal.ts +1 -0
  196. package/src/quoted-message.test.ts +83 -0
  197. package/src/quoted-message.ts +184 -0
  198. package/src/reaction-level.test.ts +94 -0
  199. package/src/reaction-level.ts +21 -0
  200. package/src/reconnect.test.ts +51 -0
  201. package/src/reconnect.ts +55 -0
  202. package/src/resolve-outbound-target.test.ts +265 -0
  203. package/src/resolve-outbound-target.ts +54 -0
  204. package/src/resolve-target.test.ts +97 -0
  205. package/src/runtime-api.ts +60 -0
  206. package/src/runtime-group-policy.ts +16 -0
  207. package/src/runtime.ts +9 -0
  208. package/src/security-contract.ts +47 -0
  209. package/src/security-fix.ts +71 -0
  210. package/src/send.test.ts +515 -0
  211. package/src/send.ts +287 -0
  212. package/src/session-contract.test.ts +31 -0
  213. package/src/session-contract.ts +43 -0
  214. package/src/session-errors.ts +125 -0
  215. package/src/session-route.ts +26 -0
  216. package/src/session.runtime.ts +8 -0
  217. package/src/session.test.ts +559 -0
  218. package/src/session.ts +330 -0
  219. package/src/setup-core.ts +52 -0
  220. package/src/setup-finalize.ts +446 -0
  221. package/src/setup-surface.test.ts +367 -0
  222. package/src/setup-surface.ts +69 -0
  223. package/src/setup-test-helpers.ts +216 -0
  224. package/src/shared.ts +291 -0
  225. package/src/socket-timing.test.ts +49 -0
  226. package/src/socket-timing.ts +38 -0
  227. package/src/state-migrations.ts +54 -0
  228. package/src/status-issues.test.ts +137 -0
  229. package/src/status-issues.ts +185 -0
  230. package/src/system-prompt.test.ts +199 -0
  231. package/src/system-prompt.ts +31 -0
  232. package/src/targets-runtime.ts +180 -0
  233. package/src/test-helpers.ts +690 -0
  234. package/src/text-runtime.test.ts +162 -0
  235. package/src/text-runtime.ts +11 -0
  236. package/src/vcard.ts +84 -0
  237. package/targets.ts +5 -0
  238. package/test-api.ts +2 -0
  239. package/tsconfig.json +16 -0
@@ -0,0 +1,690 @@
1
+ import fsSync from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { formatEnvelopeTimestamp } from "openclaw/plugin-sdk/channel-test-helpers";
5
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import { vi } from "vitest";
7
+ import type { MockBaileysSocket } from "../../../test/mocks/baileys.js";
8
+ import { createMockBaileys } from "../../../test/mocks/baileys.js";
9
+
10
+ // Use globalThis to store the mock config so it survives vi.mock hoisting
11
+ const CONFIG_KEY = Symbol.for("openclaw:testConfigMock");
12
+ const SOURCE_CONFIG_KEY = Symbol.for("openclaw:testSourceConfigMock");
13
+ const DEFAULT_CONFIG = {
14
+ channels: {
15
+ whatsapp: {
16
+ // Tests can override; default remains open to avoid surprising fixtures
17
+ allowFrom: ["*"],
18
+ },
19
+ },
20
+ messages: {
21
+ messagePrefix: undefined,
22
+ responsePrefix: undefined,
23
+ },
24
+ };
25
+
26
+ // Initialize default if not set
27
+ if (!(globalThis as Record<symbol, unknown>)[CONFIG_KEY]) {
28
+ (globalThis as Record<symbol, unknown>)[CONFIG_KEY] = () => DEFAULT_CONFIG;
29
+ }
30
+ if (!(globalThis as Record<symbol, unknown>)[SOURCE_CONFIG_KEY]) {
31
+ (globalThis as Record<symbol, unknown>)[SOURCE_CONFIG_KEY] = () => loadConfigMock();
32
+ }
33
+
34
+ export function setLoadConfigMock(fn: unknown) {
35
+ (globalThis as Record<symbol, unknown>)[CONFIG_KEY] = typeof fn === "function" ? fn : () => fn;
36
+ }
37
+
38
+ export function setRuntimeConfigSourceSnapshotMock(fn: unknown) {
39
+ (globalThis as Record<symbol, unknown>)[SOURCE_CONFIG_KEY] =
40
+ typeof fn === "function" ? fn : () => fn;
41
+ }
42
+
43
+ export function resetLoadConfigMock() {
44
+ (globalThis as Record<symbol, unknown>)[CONFIG_KEY] = () => DEFAULT_CONFIG;
45
+ (globalThis as Record<symbol, unknown>)[SOURCE_CONFIG_KEY] = () => loadConfigMock();
46
+ }
47
+
48
+ function resolveStorePathFallback(store?: string, opts?: { agentId?: string }) {
49
+ if (!store) {
50
+ const agentId = normalizeLowercaseStringOrEmpty(opts?.agentId?.trim() || "main");
51
+ return path.join(
52
+ process.env.HOME ?? "/tmp",
53
+ ".openclaw",
54
+ "agents",
55
+ agentId,
56
+ "sessions",
57
+ "sessions.json",
58
+ );
59
+ }
60
+ return path.resolve(store.replaceAll("{agentId}", opts?.agentId?.trim() || "main"));
61
+ }
62
+
63
+ function loadConfigMock() {
64
+ const getter = (globalThis as Record<symbol, unknown>)[CONFIG_KEY];
65
+ if (typeof getter === "function") {
66
+ return getter();
67
+ }
68
+ return DEFAULT_CONFIG;
69
+ }
70
+
71
+ function loadRuntimeConfigSourceSnapshotMock() {
72
+ const getter = (globalThis as Record<symbol, unknown>)[SOURCE_CONFIG_KEY];
73
+ if (typeof getter === "function") {
74
+ return getter();
75
+ }
76
+ return loadConfigMock();
77
+ }
78
+
79
+ async function updateLastRouteMock(params: {
80
+ storePath: string;
81
+ sessionKey: string;
82
+ deliveryContext: { channel: string; to: string; accountId?: string };
83
+ }) {
84
+ const raw = await fs.readFile(params.storePath, "utf8").catch(() => "{}");
85
+ const store = JSON.parse(raw) as Record<string, Record<string, unknown>>;
86
+ const current = store[params.sessionKey] ?? {};
87
+ store[params.sessionKey] = {
88
+ ...current,
89
+ lastChannel: params.deliveryContext.channel,
90
+ lastTo: params.deliveryContext.to,
91
+ lastAccountId: params.deliveryContext.accountId,
92
+ };
93
+ await fs.writeFile(params.storePath, JSON.stringify(store));
94
+ }
95
+
96
+ function loadSessionStoreMock(storePath: string) {
97
+ try {
98
+ return JSON.parse(fsSync.readFileSync(storePath, "utf8")) as Record<string, unknown>;
99
+ } catch {
100
+ return {};
101
+ }
102
+ }
103
+
104
+ type BufferedDispatchReplyParams = {
105
+ ctx: Record<string, unknown>;
106
+ replyResolver: (
107
+ ctx: Record<string, unknown>,
108
+ opts?: BufferedReplyOptions,
109
+ ) => Promise<Record<string, unknown> | undefined>;
110
+ replyOptions?: BufferedReplyOptions;
111
+ dispatcherOptions: {
112
+ deliver: (
113
+ payload: Record<string, unknown>,
114
+ info: { kind: "tool" | "block" | "final" },
115
+ ) => Promise<void>;
116
+ onReplyStart?: (() => Promise<void>) | (() => void);
117
+ };
118
+ };
119
+
120
+ type MockTypingController = {
121
+ markDispatchIdle?: () => void;
122
+ markRunComplete?: () => void;
123
+ };
124
+
125
+ type BufferedReplyOptions = Record<string, unknown> & {
126
+ onTypingController?: (typing: MockTypingController) => void;
127
+ };
128
+
129
+ type TestEnvelopeOptions = {
130
+ timezone?: string;
131
+ includeTimestamp?: boolean;
132
+ includeElapsed?: boolean;
133
+ userTimezone?: string;
134
+ };
135
+
136
+ type TestInboundEnvelopeParams = {
137
+ channel?: string;
138
+ from?: string;
139
+ body: string;
140
+ timestamp?: number | Date;
141
+ chatType?: string;
142
+ senderLabel?: string;
143
+ sender?: { name?: string; e164?: string; id?: string };
144
+ previousTimestamp?: number | Date;
145
+ envelope?: TestEnvelopeOptions;
146
+ fromMe?: boolean;
147
+ };
148
+
149
+ function sanitizeEnvelopeHeaderPart(value: string) {
150
+ return value
151
+ .replace(/\r\n|\r|\n/g, " ")
152
+ .replaceAll("[", "(")
153
+ .replaceAll("]", ")")
154
+ .replace(/\s+/g, " ")
155
+ .trim();
156
+ }
157
+
158
+ function resolveEnvelopeOptionsMock(cfg?: {
159
+ agents?: {
160
+ defaults?: {
161
+ envelopeTimezone?: string;
162
+ envelopeTimestamp?: "on" | "off";
163
+ envelopeElapsed?: "on" | "off";
164
+ userTimezone?: string;
165
+ };
166
+ };
167
+ }): TestEnvelopeOptions {
168
+ const defaults = cfg?.agents?.defaults;
169
+ return {
170
+ timezone: defaults?.envelopeTimezone,
171
+ includeTimestamp: defaults?.envelopeTimestamp !== "off",
172
+ includeElapsed: defaults?.envelopeElapsed !== "off",
173
+ userTimezone: defaults?.userTimezone,
174
+ };
175
+ }
176
+
177
+ function resolveEnvelopeTimestampMock(
178
+ timestamp: number | Date | undefined,
179
+ envelope?: TestEnvelopeOptions,
180
+ ) {
181
+ if (!timestamp || envelope?.includeTimestamp === false) {
182
+ return undefined;
183
+ }
184
+ const date = timestamp instanceof Date ? timestamp : new Date(timestamp);
185
+ if (Number.isNaN(date.getTime())) {
186
+ return undefined;
187
+ }
188
+ const zone = envelope?.timezone?.trim();
189
+ if (zone === "user") {
190
+ return formatEnvelopeTimestamp(date, envelope?.userTimezone?.trim() || "local");
191
+ }
192
+ return formatEnvelopeTimestamp(date, zone || "local");
193
+ }
194
+
195
+ function resolveSenderLabelMock(sender?: TestInboundEnvelopeParams["sender"]) {
196
+ const display = sender?.name?.trim();
197
+ const idPart = sender?.e164?.trim() || sender?.id?.trim();
198
+ if (display && idPart && display !== idPart) {
199
+ return `${display} (${idPart})`;
200
+ }
201
+ return display || idPart || undefined;
202
+ }
203
+
204
+ function formatInboundEnvelopeMock(params: TestInboundEnvelopeParams) {
205
+ const chatType = normalizeLowercaseStringOrEmpty(params.chatType);
206
+ const isDirect = !chatType || chatType === "direct";
207
+ const sender = params.senderLabel?.trim() || resolveSenderLabelMock(params.sender);
208
+ const body =
209
+ isDirect && params.fromMe
210
+ ? `(self): ${params.body}`
211
+ : !isDirect && sender
212
+ ? `${sanitizeEnvelopeHeaderPart(sender)}: ${params.body}`
213
+ : params.body;
214
+ const parts = [sanitizeEnvelopeHeaderPart(params.channel?.trim() || "Channel")];
215
+ const from = params.from?.trim();
216
+ if (from) {
217
+ parts.push(sanitizeEnvelopeHeaderPart(from));
218
+ }
219
+ const timestamp = resolveEnvelopeTimestampMock(params.timestamp, params.envelope);
220
+ if (timestamp) {
221
+ parts.push(timestamp);
222
+ }
223
+ return `[${parts.join(" ")}] ${body}`;
224
+ }
225
+
226
+ function createChannelReplyPipelineMock() {
227
+ return {
228
+ onModelSelected: undefined,
229
+ responsePrefix: undefined,
230
+ };
231
+ }
232
+
233
+ function normalizePhoneLikeToE164(value: string) {
234
+ const digits = value.replace(/\D+/g, "");
235
+ return digits ? `+${digits}` : null;
236
+ }
237
+
238
+ function resolveIdentityNamePrefixMock(
239
+ cfg: { messages?: { responsePrefix?: string } },
240
+ _agentId: string,
241
+ ) {
242
+ return cfg.messages?.responsePrefix;
243
+ }
244
+
245
+ function resolveSendableOutboundReplyPartsMock(payload: Record<string, unknown>) {
246
+ return {
247
+ text: typeof payload.text === "string" ? payload.text : "",
248
+ hasMedia:
249
+ typeof payload.mediaUrl === "string" ||
250
+ typeof payload.mediaPath === "string" ||
251
+ typeof payload.fileUrl === "string",
252
+ };
253
+ }
254
+
255
+ function toLocationContextMock(location: unknown) {
256
+ return { Location: location };
257
+ }
258
+
259
+ function createBufferedDispatchReplyMock() {
260
+ return vi.fn(async (params: BufferedDispatchReplyParams) => {
261
+ let typingController: MockTypingController | undefined;
262
+ const replyOptions: BufferedReplyOptions = {
263
+ ...params.replyOptions,
264
+ onTypingController: (typing) => {
265
+ typingController = typing;
266
+ params.replyOptions?.onTypingController?.(typing);
267
+ },
268
+ };
269
+ await params.dispatcherOptions.onReplyStart?.();
270
+ try {
271
+ const payload = await params.replyResolver(params.ctx, replyOptions);
272
+ if (!payload || typeof payload !== "object") {
273
+ return {
274
+ queuedFinal: false,
275
+ counts: { tool: 0, block: 0, final: 0 },
276
+ };
277
+ }
278
+ const text = typeof payload.text === "string" ? payload.text.trim() : "";
279
+ const hasMedia =
280
+ typeof payload.mediaUrl === "string" ||
281
+ typeof payload.mediaPath === "string" ||
282
+ typeof payload.fileUrl === "string";
283
+ if (!text && !hasMedia) {
284
+ return {
285
+ queuedFinal: false,
286
+ counts: { tool: 0, block: 0, final: 0 },
287
+ };
288
+ }
289
+ await params.dispatcherOptions.deliver(payload, { kind: "final" });
290
+ return {
291
+ queuedFinal: true,
292
+ counts: { tool: 0, block: 0, final: 1 },
293
+ };
294
+ } finally {
295
+ typingController?.markRunComplete?.();
296
+ typingController?.markDispatchIdle?.();
297
+ }
298
+ });
299
+ }
300
+
301
+ function resolveChannelContextVisibilityModeMock(params: {
302
+ cfg: {
303
+ channels?: Record<
304
+ string,
305
+ { contextVisibility?: string; accounts?: Record<string, { contextVisibility?: string }> }
306
+ >;
307
+ };
308
+ channel: string;
309
+ accountId?: string | null;
310
+ configuredContextVisibility?: string;
311
+ }) {
312
+ if (params.configuredContextVisibility) {
313
+ return params.configuredContextVisibility;
314
+ }
315
+ const channelConfig = params.cfg.channels?.[params.channel];
316
+ const accountMode =
317
+ (params.accountId
318
+ ? channelConfig?.accounts?.[params.accountId]?.contextVisibility
319
+ : undefined) ?? channelConfig?.accounts?.main?.contextVisibility;
320
+ return accountMode ?? channelConfig?.contextVisibility ?? "all";
321
+ }
322
+
323
+ function resolveGroupSessionKeyMock(ctx: { From?: string; ChatType?: string; Provider?: string }) {
324
+ const from = ctx.From?.trim() ?? "";
325
+ const chatType = normalizeLowercaseStringOrEmpty(ctx.ChatType);
326
+ const normalizedFrom = normalizeLowercaseStringOrEmpty(from);
327
+ if (!from) {
328
+ return null;
329
+ }
330
+ const isGroup =
331
+ chatType === "group" ||
332
+ chatType === "channel" ||
333
+ from.includes(":group:") ||
334
+ from.endsWith("@g.us");
335
+ if (!isGroup) {
336
+ return null;
337
+ }
338
+ return {
339
+ key: `whatsapp:group:${normalizedFrom}`,
340
+ channel: normalizeLowercaseStringOrEmpty(ctx.Provider) || "whatsapp",
341
+ id: normalizedFrom,
342
+ chatType: chatType === "channel" ? "channel" : "group",
343
+ };
344
+ }
345
+
346
+ function resolveChannelGroupPolicyMock(params: {
347
+ cfg: {
348
+ channels?: {
349
+ whatsapp?: {
350
+ groups?: Record<string, Record<string, unknown>>;
351
+ groupPolicy?: string;
352
+ allowFrom?: string[];
353
+ groupAllowFrom?: string[];
354
+ };
355
+ };
356
+ };
357
+ groupId?: string | null;
358
+ hasGroupAllowFrom?: boolean;
359
+ }) {
360
+ const whatsappCfg = params.cfg.channels?.whatsapp;
361
+ const groups = whatsappCfg?.groups;
362
+ const groupConfig = params.groupId ? groups?.[params.groupId] : undefined;
363
+ const defaultConfig = groups?.["*"];
364
+ const hasGroups = Boolean(groups && Object.keys(groups).length > 0);
365
+ const allowAll = Boolean(defaultConfig);
366
+ const groupPolicy = whatsappCfg?.groupPolicy ?? "disabled";
367
+ const senderFilterBypass =
368
+ groupPolicy === "allowlist" && !hasGroups && Boolean(params.hasGroupAllowFrom);
369
+ const allowed =
370
+ groupPolicy === "disabled"
371
+ ? false
372
+ : groupPolicy !== "allowlist" || allowAll || Boolean(groupConfig) || senderFilterBypass;
373
+ return {
374
+ allowlistEnabled: groupPolicy === "allowlist" || hasGroups,
375
+ allowed,
376
+ groupConfig,
377
+ defaultConfig,
378
+ };
379
+ }
380
+
381
+ function resolveChannelGroupRequireMentionMock(params: {
382
+ cfg: {
383
+ channels?: {
384
+ whatsapp?: {
385
+ groups?: Record<string, { requireMention?: boolean }>;
386
+ };
387
+ };
388
+ };
389
+ groupId?: string | null;
390
+ requireMentionOverride?: boolean;
391
+ }) {
392
+ const groups = params.cfg.channels?.whatsapp?.groups;
393
+ const groupConfig = params.groupId ? groups?.[params.groupId] : undefined;
394
+ const defaultConfig = groups?.["*"];
395
+ if (typeof groupConfig?.requireMention === "boolean") {
396
+ return groupConfig.requireMention;
397
+ }
398
+ if (typeof defaultConfig?.requireMention === "boolean") {
399
+ return defaultConfig.requireMention;
400
+ }
401
+ if (typeof params.requireMentionOverride === "boolean") {
402
+ return params.requireMentionOverride;
403
+ }
404
+ return true;
405
+ }
406
+
407
+ vi.mock("./auto-reply/config.runtime.js", () => ({
408
+ getRuntimeConfig: loadConfigMock,
409
+ getRuntimeConfigSourceSnapshot: loadRuntimeConfigSourceSnapshotMock,
410
+ loadConfig: loadConfigMock,
411
+ updateLastRoute: updateLastRouteMock,
412
+ loadSessionStore: loadSessionStoreMock,
413
+ recordSessionMetaFromInbound: async () => undefined,
414
+ resolveStorePath: resolveStorePathFallback,
415
+ evaluateSessionFreshness: () => ({ fresh: false }),
416
+ resolveChannelContextVisibilityMode: resolveChannelContextVisibilityModeMock,
417
+ resolveChannelGroupPolicy: resolveChannelGroupPolicyMock,
418
+ resolveChannelGroupRequireMention: resolveChannelGroupRequireMentionMock,
419
+ resolveChannelResetConfig: () => undefined,
420
+ resolveGroupSessionKey: resolveGroupSessionKeyMock,
421
+ resolveSessionKey: (_scope: string, msg: { From?: string }, mainKey?: string) =>
422
+ msg.From?.trim() || mainKey || "main",
423
+ resolveSessionResetPolicy: () => undefined,
424
+ resolveSessionResetType: () => "message",
425
+ resolveThreadFlag: () => false,
426
+ }));
427
+
428
+ vi.mock("./inbound/runtime-api.js", () => ({
429
+ DisconnectReason: { loggedOut: 401 },
430
+ isJidGroup: (jid: string) => typeof jid === "string" && jid.endsWith("@g.us"),
431
+ normalizeMessageContent: (message: unknown) => message,
432
+ downloadMediaMessage: vi.fn().mockResolvedValue(Buffer.from("img")),
433
+ saveMediaBuffer: vi.fn().mockImplementation(async (_buf: Buffer, contentType?: string) => ({
434
+ id: "mid",
435
+ path: "/tmp/mid",
436
+ size: _buf.length,
437
+ contentType,
438
+ })),
439
+ }));
440
+
441
+ vi.mock("./auto-reply/monitor/inbound-dispatch.runtime.js", () => ({
442
+ createChannelReplyPipeline: createChannelReplyPipelineMock,
443
+ dispatchReplyWithBufferedBlockDispatcher: createBufferedDispatchReplyMock(),
444
+ finalizeInboundContext: <T>(ctx: T) => ctx,
445
+ getAgentScopedMediaLocalRoots: () => [] as string[],
446
+ jidToE164: normalizePhoneLikeToE164,
447
+ logVerbose: (_msg: string) => undefined,
448
+ resolveChunkMode: () => undefined,
449
+ resolveIdentityNamePrefix: resolveIdentityNamePrefixMock,
450
+ resolveInboundLastRouteSessionKey: (params: { sessionKey: string }) => params.sessionKey,
451
+ resolveMarkdownTableMode: () => undefined,
452
+ resolveSendableOutboundReplyParts: resolveSendableOutboundReplyPartsMock,
453
+ resolveTextChunkLimit: () => 64_000,
454
+ shouldLogVerbose: () => false,
455
+ toLocationContext: toLocationContextMock,
456
+ }));
457
+
458
+ vi.mock("./auto-reply/monitor/runtime-api.js", () => ({
459
+ buildHistoryContextFromEntries: (params: {
460
+ entries: Array<{ sender?: string; body: string; timestamp?: number }>;
461
+ currentMessage: string;
462
+ formatEntry?: (entry: { sender?: string; body: string; timestamp?: number }) => string;
463
+ }) => {
464
+ const rendered = params.entries
465
+ .map((entry) => params.formatEntry?.(entry) ?? `${entry.sender ?? "Unknown"}: ${entry.body}`)
466
+ .join("\n");
467
+ return rendered
468
+ ? `Chat messages since your last reply:\n${rendered}\n\n${params.currentMessage}`
469
+ : params.currentMessage;
470
+ },
471
+ createChannelReplyPipeline: createChannelReplyPipelineMock,
472
+ dispatchReplyWithBufferedBlockDispatcher: createBufferedDispatchReplyMock(),
473
+ finalizeInboundContext: <T>(ctx: T) => ctx,
474
+ formatInboundEnvelope: formatInboundEnvelopeMock,
475
+ getAgentScopedMediaLocalRoots: () => [] as string[],
476
+ jidToE164: normalizePhoneLikeToE164,
477
+ logVerbose: (_msg: string) => undefined,
478
+ normalizeE164: normalizePhoneLikeToE164,
479
+ readStoreAllowFromForDmPolicy: async () => [] as string[],
480
+ recordSessionMetaFromInbound: async () => undefined,
481
+ resolveChannelContextVisibilityMode: resolveChannelContextVisibilityModeMock,
482
+ resolveChunkMode: () => undefined,
483
+ resolveIdentityNamePrefix: resolveIdentityNamePrefixMock,
484
+ resolveInboundLastRouteSessionKey: (params: { sessionKey: string }) => params.sessionKey,
485
+ resolveInboundSessionEnvelopeContext: (params: {
486
+ cfg: { session?: { store?: string } } & Parameters<typeof resolveEnvelopeOptionsMock>[0];
487
+ agentId: string;
488
+ }) => ({
489
+ storePath: resolveStorePathFallback(params.cfg.session?.store, { agentId: params.agentId }),
490
+ envelopeOptions: resolveEnvelopeOptionsMock(params.cfg),
491
+ previousTimestamp: undefined,
492
+ }),
493
+ resolveMarkdownTableMode: () => undefined,
494
+ resolvePinnedMainDmOwnerFromAllowlist: (params: {
495
+ allowFrom?: string[];
496
+ normalizeEntry: (entry: string) => string | null;
497
+ }) => {
498
+ const first = params.allowFrom?.[0];
499
+ return first ? params.normalizeEntry(first) : null;
500
+ },
501
+ resolveDmGroupAccessWithCommandGate: () => ({ commandAuthorized: true }),
502
+ resolveSendableOutboundReplyParts: resolveSendableOutboundReplyPartsMock,
503
+ resolveTextChunkLimit: () => 64_000,
504
+ shouldComputeCommandAuthorized: () => false,
505
+ shouldLogVerbose: () => false,
506
+ toLocationContext: toLocationContextMock,
507
+ }));
508
+
509
+ vi.mock("./auto-reply/monitor/group-gating.runtime.js", () => ({
510
+ hasControlCommand: (body: string) => body.trim().startsWith("/"),
511
+ implicitMentionKindWhen: (kind: string, enabled: boolean) => (enabled ? [kind] : []),
512
+ normalizeE164: normalizePhoneLikeToE164,
513
+ parseActivationCommand: (body: string) => ({
514
+ hasCommand: body.trim().startsWith("/"),
515
+ }),
516
+ recordPendingHistoryEntryIfEnabled: (params: {
517
+ historyMap: Map<string, unknown[]>;
518
+ historyKey: string;
519
+ limit: number;
520
+ entry: unknown;
521
+ }) => {
522
+ const current = params.historyMap.get(params.historyKey) ?? [];
523
+ const next = [...current, params.entry].slice(-params.limit);
524
+ params.historyMap.set(params.historyKey, next);
525
+ },
526
+ resolveInboundMentionDecision: (params: {
527
+ facts?: {
528
+ canDetectMention: boolean;
529
+ wasMentioned: boolean;
530
+ implicitMentionKinds?: string[];
531
+ };
532
+ policy?: {
533
+ isGroup: boolean;
534
+ requireMention: boolean;
535
+ allowTextCommands: boolean;
536
+ hasControlCommand: boolean;
537
+ commandAuthorized: boolean;
538
+ };
539
+ isGroup?: boolean;
540
+ requireMention?: boolean;
541
+ canDetectMention?: boolean;
542
+ wasMentioned?: boolean;
543
+ implicitMentionKinds?: string[];
544
+ allowTextCommands?: boolean;
545
+ hasControlCommand?: boolean;
546
+ commandAuthorized?: boolean;
547
+ }) => {
548
+ const facts =
549
+ "facts" in params && params.facts
550
+ ? params.facts
551
+ : {
552
+ canDetectMention: Boolean(params.canDetectMention),
553
+ wasMentioned: Boolean(params.wasMentioned),
554
+ implicitMentionKinds: params.implicitMentionKinds,
555
+ };
556
+ const policy =
557
+ "policy" in params && params.policy
558
+ ? params.policy
559
+ : {
560
+ isGroup: Boolean(params.isGroup),
561
+ requireMention: Boolean(params.requireMention),
562
+ allowTextCommands: Boolean(params.allowTextCommands),
563
+ hasControlCommand: Boolean(params.hasControlCommand),
564
+ commandAuthorized: Boolean(params.commandAuthorized),
565
+ };
566
+ const effectiveWasMentioned = facts.wasMentioned || Boolean(facts.implicitMentionKinds?.length);
567
+ return {
568
+ effectiveWasMentioned,
569
+ shouldSkip:
570
+ policy.isGroup && policy.requireMention && facts.canDetectMention && !effectiveWasMentioned,
571
+ shouldBypassMention: false,
572
+ implicitMention: Boolean(facts.implicitMentionKinds?.length),
573
+ matchedImplicitMentionKinds: facts.implicitMentionKinds ?? [],
574
+ };
575
+ },
576
+ }));
577
+
578
+ vi.mock("./auto-reply/monitor/group-activation.runtime.js", () => ({
579
+ normalizeGroupActivation: (value: unknown) =>
580
+ value === "always" || value === "mention" ? value : undefined,
581
+ }));
582
+
583
+ vi.mock("./auto-reply/monitor/message-line.runtime.js", () => ({
584
+ formatInboundEnvelope: formatInboundEnvelopeMock,
585
+ resolveMessagePrefix: (
586
+ cfg: {
587
+ channels?: { whatsapp?: { messagePrefix?: string; allowFrom?: string[] } };
588
+ messages?: { messagePrefix?: string };
589
+ },
590
+ _agentId: string,
591
+ params?: { configured?: string; hasAllowFrom?: boolean },
592
+ ) => {
593
+ const configured = params?.configured ?? cfg.messages?.messagePrefix;
594
+ if (configured !== undefined) {
595
+ return configured;
596
+ }
597
+ return params?.hasAllowFrom === true ? "" : "[openclaw]";
598
+ },
599
+ }));
600
+
601
+ vi.mock("./auth-store.runtime.js", () => ({
602
+ resolveOAuthDir: () => "/tmp/openclaw-oauth",
603
+ }));
604
+
605
+ vi.mock("./session.runtime.js", () => {
606
+ const created = createMockBaileys();
607
+ (globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw:lastSocket")] =
608
+ created.lastSocket;
609
+ return {
610
+ ...created.mod,
611
+ };
612
+ });
613
+
614
+ vi.mock("./qr-terminal.js", () => ({
615
+ renderQrTerminal: vi.fn(async () => "ASCII-QR"),
616
+ }));
617
+
618
+ export const baileys = await import("./session.runtime.js");
619
+
620
+ function resetMockExport<T extends (...args: never[]) => unknown>(params: {
621
+ current: T;
622
+ implementation: T;
623
+ }) {
624
+ if (!("mockReset" in params.current) || typeof params.current.mockReset !== "function") {
625
+ return;
626
+ }
627
+ params.current.mockReset();
628
+ if (
629
+ "mockImplementation" in params.current &&
630
+ typeof params.current.mockImplementation === "function"
631
+ ) {
632
+ params.current.mockImplementation(params.implementation);
633
+ }
634
+ }
635
+
636
+ export function resetBaileysMocks() {
637
+ const recreated = createMockBaileys();
638
+ (globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw:lastSocket")] =
639
+ recreated.lastSocket;
640
+
641
+ const makeWASocket = vi.mocked(baileys.makeWASocket);
642
+ const makeWASocketImpl: typeof baileys.makeWASocket = (...args) =>
643
+ (recreated.mod.makeWASocket as unknown as typeof baileys.makeWASocket)(...args);
644
+ resetMockExport({
645
+ current: makeWASocket,
646
+ implementation: makeWASocketImpl,
647
+ });
648
+
649
+ const useMultiFileAuthState = vi.mocked(baileys.useMultiFileAuthState);
650
+ const useMultiFileAuthStateImpl: typeof baileys.useMultiFileAuthState = (...args) =>
651
+ (recreated.mod.useMultiFileAuthState as unknown as typeof baileys.useMultiFileAuthState)(
652
+ ...args,
653
+ );
654
+ resetMockExport({
655
+ current: useMultiFileAuthState,
656
+ implementation: useMultiFileAuthStateImpl,
657
+ });
658
+
659
+ const fetchLatestBaileysVersion = vi.mocked(baileys.fetchLatestBaileysVersion);
660
+ const fetchLatestBaileysVersionImpl: typeof baileys.fetchLatestBaileysVersion = (...args) =>
661
+ (
662
+ recreated.mod.fetchLatestBaileysVersion as unknown as typeof baileys.fetchLatestBaileysVersion
663
+ )(...args);
664
+ resetMockExport({
665
+ current: fetchLatestBaileysVersion,
666
+ implementation: fetchLatestBaileysVersionImpl,
667
+ });
668
+
669
+ const makeCacheableSignalKeyStore = vi.mocked(baileys.makeCacheableSignalKeyStore);
670
+ const makeCacheableSignalKeyStoreImpl: typeof baileys.makeCacheableSignalKeyStore = (...args) =>
671
+ (
672
+ recreated.mod
673
+ .makeCacheableSignalKeyStore as unknown as typeof baileys.makeCacheableSignalKeyStore
674
+ )(...args);
675
+ resetMockExport({
676
+ current: makeCacheableSignalKeyStore,
677
+ implementation: makeCacheableSignalKeyStoreImpl,
678
+ });
679
+ }
680
+
681
+ export function getLastSocket(): MockBaileysSocket {
682
+ const getter = (globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw:lastSocket")];
683
+ if (typeof getter === "function") {
684
+ return (getter as () => MockBaileysSocket)();
685
+ }
686
+ if (!getter) {
687
+ throw new Error("Baileys mock not initialized");
688
+ }
689
+ throw new Error("Invalid Baileys socket getter");
690
+ }