@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,690 +0,0 @@
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
- }