@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,354 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const events: string[] = [];
4
+ const transcribeFirstAudioMock = vi.fn();
5
+ const maybeSendAckReactionMock = vi.fn();
6
+ const processMessageMock = vi.fn();
7
+ const maybeBroadcastMessageMock = vi.fn();
8
+ const ackReactionHandle = {
9
+ ackReactionPromise: Promise.resolve(true),
10
+ ackReactionValue: "👀",
11
+ remove: vi.fn(async () => undefined),
12
+ };
13
+ const applyGroupGatingMock = vi.fn();
14
+
15
+ vi.mock("./audio-preflight.runtime.js", () => ({
16
+ transcribeFirstAudio: (...args: unknown[]) => transcribeFirstAudioMock(...args),
17
+ }));
18
+
19
+ vi.mock("./ack-reaction.js", () => ({
20
+ maybeSendAckReaction: (...args: unknown[]) => maybeSendAckReactionMock(...args),
21
+ }));
22
+
23
+ vi.mock("./process-message.js", () => ({
24
+ processMessage: (...args: unknown[]) => processMessageMock(...args),
25
+ }));
26
+
27
+ vi.mock("./broadcast.js", () => ({
28
+ maybeBroadcastMessage: (...args: unknown[]) => maybeBroadcastMessageMock(...args),
29
+ }));
30
+
31
+ vi.mock("./group-gating.js", () => ({
32
+ applyGroupGating: (...args: unknown[]) => applyGroupGatingMock(...args),
33
+ }));
34
+
35
+ vi.mock("./last-route.js", () => ({
36
+ updateLastRouteInBackground: () => {},
37
+ }));
38
+
39
+ vi.mock("./peer.js", () => ({
40
+ resolvePeerId: (msg: { from: string }) => msg.from,
41
+ }));
42
+
43
+ vi.mock("../config.runtime.js", () => ({
44
+ getRuntimeConfig: () => ({
45
+ channels: {
46
+ whatsapp: {
47
+ ackReaction: { enabled: true },
48
+ },
49
+ },
50
+ }),
51
+ }));
52
+
53
+ vi.mock("../../group-session-key.js", () => ({
54
+ resolveWhatsAppGroupSessionRoute: (route: unknown) => route,
55
+ }));
56
+
57
+ vi.mock("../../identity.js", () => ({
58
+ getPrimaryIdentityId: () => undefined,
59
+ getSenderIdentity: () => ({ e164: "+15550000002", name: "Alice" }),
60
+ }));
61
+
62
+ vi.mock("../../text-runtime.js", () => ({
63
+ normalizeE164: (value: string) => value,
64
+ }));
65
+
66
+ vi.mock("openclaw/plugin-sdk/routing", () => ({
67
+ buildGroupHistoryKey: () => "group-key",
68
+ resolveAgentRoute: () => ({
69
+ agentId: "main",
70
+ accountId: "default",
71
+ sessionKey: "agent:main:whatsapp:+15550000002",
72
+ mainSessionKey: "agent:main:main",
73
+ }),
74
+ }));
75
+
76
+ import type { WebInboundMsg } from "../types.js";
77
+ import { createWebOnMessageHandler } from "./on-message.js";
78
+
79
+ function makeAudioMsg(): WebInboundMsg {
80
+ return {
81
+ id: "msg-1",
82
+ from: "+15550000002",
83
+ to: "+15550000001",
84
+ accessControlPassed: true,
85
+ body: "<media:audio>",
86
+ chatType: "direct",
87
+ mediaType: "audio/ogg; codecs=opus",
88
+ mediaPath: "/tmp/voice.ogg",
89
+ timestamp: 1700000000,
90
+ accountId: "default",
91
+ } as WebInboundMsg;
92
+ }
93
+
94
+ function makeGroupAudioMsg(): WebInboundMsg {
95
+ return {
96
+ ...makeAudioMsg(),
97
+ from: "1203630@g.us",
98
+ chatId: "1203630@g.us",
99
+ chatType: "group",
100
+ conversationId: "1203630@g.us",
101
+ wasMentioned: false,
102
+ } as WebInboundMsg;
103
+ }
104
+
105
+ function makeEchoTracker() {
106
+ return {
107
+ has: () => false,
108
+ forget: () => {},
109
+ rememberText: () => {},
110
+ buildCombinedKey: (p: { combinedBody: string }) => p.combinedBody,
111
+ };
112
+ }
113
+
114
+ describe("createWebOnMessageHandler audio preflight", () => {
115
+ beforeEach(() => {
116
+ events.length = 0;
117
+ maybeBroadcastMessageMock.mockReset();
118
+ maybeBroadcastMessageMock.mockImplementation(async () => false);
119
+ maybeSendAckReactionMock.mockReset();
120
+ maybeSendAckReactionMock.mockImplementation(async () => {
121
+ events.push("ack");
122
+ return ackReactionHandle;
123
+ });
124
+ transcribeFirstAudioMock.mockReset();
125
+ transcribeFirstAudioMock.mockImplementation(async () => {
126
+ events.push("stt");
127
+ return "transcribed voice note";
128
+ });
129
+ processMessageMock.mockReset();
130
+ processMessageMock.mockResolvedValue(true);
131
+ applyGroupGatingMock.mockReset();
132
+ applyGroupGatingMock.mockResolvedValue({ shouldProcess: true });
133
+ });
134
+
135
+ it("sends ack reaction before audio preflight for voice notes", async () => {
136
+ const handler = createWebOnMessageHandler({
137
+ cfg: {
138
+ channels: {
139
+ whatsapp: {
140
+ ackReaction: { enabled: true },
141
+ },
142
+ },
143
+ } as never,
144
+ verbose: false,
145
+ connectionId: "conn-1",
146
+ maxMediaBytes: 1024 * 1024,
147
+ groupHistoryLimit: 20,
148
+ groupHistories: new Map(),
149
+ groupMemberNames: new Map(),
150
+ echoTracker: makeEchoTracker() as never,
151
+ backgroundTasks: new Set(),
152
+ replyResolver: vi.fn() as never,
153
+ replyLogger: {
154
+ info: () => {},
155
+ warn: () => {},
156
+ debug: () => {},
157
+ error: () => {},
158
+ } as never,
159
+ baseMentionConfig: {} as never,
160
+ account: { authDir: "/tmp/auth", accountId: "default" },
161
+ });
162
+
163
+ await handler(makeAudioMsg());
164
+
165
+ expect(events).toEqual(["ack", "stt"]);
166
+ expect(processMessageMock).toHaveBeenCalledWith(
167
+ expect.objectContaining({
168
+ preflightAudioTranscript: "transcribed voice note",
169
+ ackAlreadySent: true,
170
+ ackReaction: ackReactionHandle,
171
+ }),
172
+ );
173
+ });
174
+
175
+ it("skips early DM ack/preflight when access-control was not explicitly passed through", async () => {
176
+ const handler = createWebOnMessageHandler({
177
+ cfg: {
178
+ channels: {
179
+ whatsapp: {
180
+ ackReaction: { enabled: true },
181
+ },
182
+ },
183
+ } as never,
184
+ verbose: false,
185
+ connectionId: "conn-1",
186
+ maxMediaBytes: 1024 * 1024,
187
+ groupHistoryLimit: 20,
188
+ groupHistories: new Map(),
189
+ groupMemberNames: new Map(),
190
+ echoTracker: makeEchoTracker() as never,
191
+ backgroundTasks: new Set(),
192
+ replyResolver: vi.fn() as never,
193
+ replyLogger: {
194
+ info: () => {},
195
+ warn: () => {},
196
+ debug: () => {},
197
+ error: () => {},
198
+ } as never,
199
+ baseMentionConfig: {} as never,
200
+ account: { authDir: "/tmp/auth", accountId: "default" },
201
+ });
202
+
203
+ await handler({ ...makeAudioMsg(), accessControlPassed: undefined });
204
+
205
+ expect(events).toEqual([]);
206
+ expect(transcribeFirstAudioMock).not.toHaveBeenCalled();
207
+ expect(maybeSendAckReactionMock).not.toHaveBeenCalled();
208
+ expect(processMessageMock).toHaveBeenCalledWith(
209
+ expect.not.objectContaining({
210
+ preflightAudioTranscript: expect.anything(),
211
+ ackAlreadySent: true,
212
+ }),
213
+ );
214
+ });
215
+
216
+ it("preserves per-agent ack checks for group broadcast voice notes", async () => {
217
+ maybeBroadcastMessageMock.mockImplementation(
218
+ async (params: {
219
+ ackAlreadySent?: boolean;
220
+ ackReaction?: unknown;
221
+ preflightAudioTranscript?: string | null;
222
+ }) => {
223
+ expect(params.preflightAudioTranscript).toBe("transcribed voice note");
224
+ expect(params.ackAlreadySent).toBeUndefined();
225
+ expect(params.ackReaction).toBeUndefined();
226
+ return true;
227
+ },
228
+ );
229
+ const handler = createWebOnMessageHandler({
230
+ cfg: {
231
+ channels: {
232
+ whatsapp: {
233
+ ackReaction: { enabled: true },
234
+ },
235
+ },
236
+ broadcast: {
237
+ "1203630@g.us": ["main", "backup"],
238
+ },
239
+ } as never,
240
+ verbose: false,
241
+ connectionId: "conn-1",
242
+ maxMediaBytes: 1024 * 1024,
243
+ groupHistoryLimit: 20,
244
+ groupHistories: new Map(),
245
+ groupMemberNames: new Map(),
246
+ echoTracker: makeEchoTracker() as never,
247
+ backgroundTasks: new Set(),
248
+ replyResolver: vi.fn() as never,
249
+ replyLogger: {
250
+ info: () => {},
251
+ warn: () => {},
252
+ debug: () => {},
253
+ error: () => {},
254
+ } as never,
255
+ baseMentionConfig: {} as never,
256
+ account: { authDir: "/tmp/auth", accountId: "default" },
257
+ });
258
+
259
+ await handler(makeGroupAudioMsg());
260
+
261
+ expect(events).toEqual(["ack", "stt"]);
262
+ expect(processMessageMock).not.toHaveBeenCalled();
263
+ });
264
+
265
+ it("uses group voice transcript for mention gating before dispatch", async () => {
266
+ applyGroupGatingMock
267
+ .mockResolvedValueOnce({ shouldProcess: false, needsMentionText: true })
268
+ .mockResolvedValueOnce({ shouldProcess: true });
269
+ const handler = createWebOnMessageHandler({
270
+ cfg: {
271
+ channels: {
272
+ whatsapp: {
273
+ ackReaction: { enabled: true },
274
+ },
275
+ },
276
+ } as never,
277
+ verbose: false,
278
+ connectionId: "conn-1",
279
+ maxMediaBytes: 1024 * 1024,
280
+ groupHistoryLimit: 20,
281
+ groupHistories: new Map(),
282
+ groupMemberNames: new Map(),
283
+ echoTracker: makeEchoTracker() as never,
284
+ backgroundTasks: new Set(),
285
+ replyResolver: vi.fn() as never,
286
+ replyLogger: {
287
+ info: () => {},
288
+ warn: () => {},
289
+ debug: () => {},
290
+ error: () => {},
291
+ } as never,
292
+ baseMentionConfig: {} as never,
293
+ account: { authDir: "/tmp/auth", accountId: "default" },
294
+ });
295
+
296
+ await handler(makeGroupAudioMsg());
297
+
298
+ expect(applyGroupGatingMock).toHaveBeenNthCalledWith(
299
+ 1,
300
+ expect.objectContaining({
301
+ deferMissingMention: true,
302
+ }),
303
+ );
304
+ expect(events).toEqual(["ack", "stt"]);
305
+ expect(applyGroupGatingMock).toHaveBeenNthCalledWith(
306
+ 2,
307
+ expect.objectContaining({
308
+ mentionText: "transcribed voice note",
309
+ }),
310
+ );
311
+ expect(processMessageMock).toHaveBeenCalledWith(
312
+ expect.objectContaining({
313
+ preflightAudioTranscript: "transcribed voice note",
314
+ ackAlreadySent: true,
315
+ }),
316
+ );
317
+ });
318
+
319
+ it("does not transcribe group voice when policy gating rejects before mention", async () => {
320
+ applyGroupGatingMock.mockResolvedValueOnce({ shouldProcess: false });
321
+ const handler = createWebOnMessageHandler({
322
+ cfg: {
323
+ channels: {
324
+ whatsapp: {
325
+ ackReaction: { enabled: true },
326
+ },
327
+ },
328
+ } as never,
329
+ verbose: false,
330
+ connectionId: "conn-1",
331
+ maxMediaBytes: 1024 * 1024,
332
+ groupHistoryLimit: 20,
333
+ groupHistories: new Map(),
334
+ groupMemberNames: new Map(),
335
+ echoTracker: makeEchoTracker() as never,
336
+ backgroundTasks: new Set(),
337
+ replyResolver: vi.fn() as never,
338
+ replyLogger: {
339
+ info: () => {},
340
+ warn: () => {},
341
+ debug: () => {},
342
+ error: () => {},
343
+ } as never,
344
+ baseMentionConfig: {} as never,
345
+ account: { authDir: "/tmp/auth", accountId: "default" },
346
+ });
347
+
348
+ await handler(makeGroupAudioMsg());
349
+
350
+ expect(transcribeFirstAudioMock).not.toHaveBeenCalled();
351
+ expect(maybeSendAckReactionMock).not.toHaveBeenCalled();
352
+ expect(processMessageMock).not.toHaveBeenCalled();
353
+ });
354
+ });
@@ -0,0 +1,291 @@
1
+ import type { AckReactionHandle } from "openclaw/plugin-sdk/channel-feedback";
2
+ import type { getReplyFromConfig } from "openclaw/plugin-sdk/reply-runtime";
3
+ import type { MsgContext } from "openclaw/plugin-sdk/reply-runtime";
4
+ import { resolveAgentRoute } from "openclaw/plugin-sdk/routing";
5
+ import { buildGroupHistoryKey } from "openclaw/plugin-sdk/routing";
6
+ import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
7
+ import { resolveWhatsAppGroupSessionRoute } from "../../group-session-key.js";
8
+ import { getPrimaryIdentityId, getSenderIdentity } from "../../identity.js";
9
+ import { normalizeE164 } from "../../text-runtime.js";
10
+ import { getRuntimeConfig } from "../config.runtime.js";
11
+ import type { MentionConfig } from "../mentions.js";
12
+ import type { WebInboundMsg } from "../types.js";
13
+ import { maybeSendAckReaction } from "./ack-reaction.js";
14
+ import { maybeBroadcastMessage } from "./broadcast.js";
15
+ import type { EchoTracker } from "./echo.js";
16
+ import type { GroupHistoryEntry } from "./group-gating.js";
17
+ import { applyGroupGating } from "./group-gating.js";
18
+ import { updateLastRouteInBackground } from "./last-route.js";
19
+ import { resolvePeerId } from "./peer.js";
20
+ import { processMessage } from "./process-message.js";
21
+
22
+ export function createWebOnMessageHandler(params: {
23
+ cfg: ReturnType<typeof getRuntimeConfig>;
24
+ verbose: boolean;
25
+ connectionId: string;
26
+ maxMediaBytes: number;
27
+ groupHistoryLimit: number;
28
+ groupHistories: Map<string, GroupHistoryEntry[]>;
29
+ groupMemberNames: Map<string, Map<string, string>>;
30
+ echoTracker: EchoTracker;
31
+ backgroundTasks: Set<Promise<unknown>>;
32
+ replyResolver: typeof getReplyFromConfig;
33
+ replyLogger: ReturnType<(typeof import("openclaw/plugin-sdk/runtime-env"))["getChildLogger"]>;
34
+ baseMentionConfig: MentionConfig;
35
+ account: { authDir?: string; accountId?: string; selfChatMode?: boolean };
36
+ }) {
37
+ const processForRoute = async (
38
+ msg: WebInboundMsg,
39
+ route: ReturnType<typeof resolveAgentRoute>,
40
+ groupHistoryKey: string,
41
+ opts?: {
42
+ groupHistory?: GroupHistoryEntry[];
43
+ suppressGroupHistoryClear?: boolean;
44
+ preflightAudioTranscript?: string | null;
45
+ ackAlreadySent?: boolean;
46
+ ackReaction?: AckReactionHandle | null;
47
+ },
48
+ ) => {
49
+ const processParams: Parameters<typeof processMessage>[0] = {
50
+ cfg: params.cfg,
51
+ msg,
52
+ route,
53
+ groupHistoryKey,
54
+ groupHistories: params.groupHistories,
55
+ groupMemberNames: params.groupMemberNames,
56
+ connectionId: params.connectionId,
57
+ verbose: params.verbose,
58
+ maxMediaBytes: params.maxMediaBytes,
59
+ replyResolver: params.replyResolver,
60
+ replyLogger: params.replyLogger,
61
+ backgroundTasks: params.backgroundTasks,
62
+ rememberSentText: params.echoTracker.rememberText,
63
+ echoHas: params.echoTracker.has,
64
+ echoForget: params.echoTracker.forget,
65
+ buildCombinedEchoKey: params.echoTracker.buildCombinedKey,
66
+ };
67
+ if (opts?.groupHistory !== undefined) {
68
+ processParams.groupHistory = opts.groupHistory;
69
+ }
70
+ if (opts?.suppressGroupHistoryClear !== undefined) {
71
+ processParams.suppressGroupHistoryClear = opts.suppressGroupHistoryClear;
72
+ }
73
+ if (opts?.preflightAudioTranscript !== undefined) {
74
+ processParams.preflightAudioTranscript = opts.preflightAudioTranscript;
75
+ }
76
+ if (opts?.ackAlreadySent === true) {
77
+ processParams.ackAlreadySent = true;
78
+ }
79
+ if (opts?.ackReaction !== undefined) {
80
+ processParams.ackReaction = opts.ackReaction;
81
+ }
82
+ return processMessage(processParams);
83
+ };
84
+
85
+ return async (msg: WebInboundMsg) => {
86
+ const conversationId = msg.conversationId ?? msg.from;
87
+ const peerId = resolvePeerId(msg);
88
+ // Fresh config for bindings lookup; other routing inputs are payload-derived.
89
+ const baseRoute = resolveAgentRoute({
90
+ cfg: getRuntimeConfig(),
91
+ channel: "whatsapp",
92
+ accountId: msg.accountId,
93
+ peer: {
94
+ kind: msg.chatType === "group" ? "group" : "direct",
95
+ id: peerId,
96
+ },
97
+ });
98
+ const route =
99
+ msg.chatType === "group" ? resolveWhatsAppGroupSessionRoute(baseRoute) : baseRoute;
100
+ const groupHistoryKey =
101
+ msg.chatType === "group"
102
+ ? buildGroupHistoryKey({
103
+ channel: "whatsapp",
104
+ accountId: route.accountId,
105
+ peerKind: "group",
106
+ peerId,
107
+ })
108
+ : route.sessionKey;
109
+
110
+ // Same-phone mode logging retained
111
+ if (msg.from === msg.to) {
112
+ logVerbose(`📱 Same-phone mode detected (from === to: ${msg.from})`);
113
+ }
114
+
115
+ // Skip if this is a message we just sent (echo detection)
116
+ if (params.echoTracker.has(msg.body)) {
117
+ logVerbose("Skipping auto-reply: detected echo (message matches recently sent text)");
118
+ params.echoTracker.forget(msg.body);
119
+ return;
120
+ }
121
+
122
+ // Preflight audio transcription: run once before broadcast fan-out so all
123
+ // agents share the same transcript instead of each making a separate STT call.
124
+ // For DMs, only do this on the real inbound path after access-control/pairing
125
+ // checks have already passed in inbound/monitor.ts. For groups, the first
126
+ // gating pass must approve the group/sender before STT is attempted.
127
+ // null = preflight was attempted but produced no transcript (failed / disabled / no audio);
128
+ // undefined = preflight was not attempted (non-audio message).
129
+ let preflightAudioTranscript: string | null | undefined;
130
+ const hasAudioBody =
131
+ msg.mediaType?.startsWith("audio/") === true && msg.body === "<media:audio>";
132
+ const canRunEarlyAudioPreflight = msg.chatType === "group" || msg.accessControlPassed === true;
133
+ let ackAlreadySent = false;
134
+ let ackReaction: AckReactionHandle | null = null;
135
+ const runAudioPreflightOnce = async () => {
136
+ if (
137
+ preflightAudioTranscript !== undefined ||
138
+ !canRunEarlyAudioPreflight ||
139
+ !hasAudioBody ||
140
+ !msg.mediaPath
141
+ ) {
142
+ return;
143
+ }
144
+ ackReaction = await maybeSendAckReaction({
145
+ cfg: params.cfg,
146
+ msg,
147
+ agentId: route.agentId,
148
+ sessionKey: route.sessionKey,
149
+ conversationId,
150
+ verbose: params.verbose,
151
+ accountId: route.accountId,
152
+ info: params.replyLogger.info.bind(params.replyLogger),
153
+ warn: params.replyLogger.warn.bind(params.replyLogger),
154
+ });
155
+ ackAlreadySent = ackReaction !== null;
156
+ try {
157
+ const { transcribeFirstAudio } = await import("./audio-preflight.runtime.js");
158
+ // transcribeFirstAudio returns undefined on failure/disabled; store null so
159
+ // processMessage knows the attempt was already made and does not retry.
160
+ preflightAudioTranscript =
161
+ (await transcribeFirstAudio({
162
+ ctx: {
163
+ MediaPaths: [msg.mediaPath],
164
+ MediaTypes: msg.mediaType ? [msg.mediaType] : undefined,
165
+ },
166
+ cfg: params.cfg,
167
+ })) ?? null;
168
+ } catch {
169
+ // Non-fatal: store null so per-agent retries are suppressed.
170
+ preflightAudioTranscript = null;
171
+ }
172
+ };
173
+
174
+ if (msg.chatType === "group") {
175
+ const sender = getSenderIdentity(msg);
176
+ const metaCtx = {
177
+ From: msg.from,
178
+ To: msg.to,
179
+ SessionKey: route.sessionKey,
180
+ AccountId: route.accountId,
181
+ ChatType: msg.chatType,
182
+ ConversationLabel: conversationId,
183
+ GroupSubject: msg.groupSubject,
184
+ SenderName: sender.name ?? undefined,
185
+ SenderId: getPrimaryIdentityId(sender) ?? undefined,
186
+ SenderE164: sender.e164 ?? undefined,
187
+ Provider: "whatsapp",
188
+ Surface: "whatsapp",
189
+ OriginatingChannel: "whatsapp",
190
+ OriginatingTo: conversationId,
191
+ } satisfies MsgContext;
192
+ updateLastRouteInBackground({
193
+ cfg: params.cfg,
194
+ backgroundTasks: params.backgroundTasks,
195
+ storeAgentId: route.agentId,
196
+ sessionKey: route.sessionKey,
197
+ channel: "whatsapp",
198
+ to: conversationId,
199
+ accountId: route.accountId,
200
+ ctx: metaCtx,
201
+ warn: params.replyLogger.warn.bind(params.replyLogger),
202
+ });
203
+
204
+ let gating = await applyGroupGating({
205
+ cfg: params.cfg,
206
+ msg,
207
+ deferMissingMention: hasAudioBody && Boolean(msg.mediaPath),
208
+ conversationId,
209
+ groupHistoryKey,
210
+ agentId: route.agentId,
211
+ sessionKey: route.sessionKey,
212
+ baseMentionConfig: params.baseMentionConfig,
213
+ authDir: params.account.authDir,
214
+ selfChatMode: params.account.selfChatMode,
215
+ groupHistories: params.groupHistories,
216
+ groupHistoryLimit: params.groupHistoryLimit,
217
+ groupMemberNames: params.groupMemberNames,
218
+ logVerbose,
219
+ replyLogger: params.replyLogger,
220
+ });
221
+ if (
222
+ !gating.shouldProcess &&
223
+ "needsMentionText" in gating &&
224
+ gating.needsMentionText === true
225
+ ) {
226
+ await runAudioPreflightOnce();
227
+ gating = await applyGroupGating({
228
+ cfg: params.cfg,
229
+ msg,
230
+ ...(typeof preflightAudioTranscript === "string"
231
+ ? { mentionText: preflightAudioTranscript }
232
+ : {}),
233
+ conversationId,
234
+ groupHistoryKey,
235
+ agentId: route.agentId,
236
+ sessionKey: route.sessionKey,
237
+ baseMentionConfig: params.baseMentionConfig,
238
+ authDir: params.account.authDir,
239
+ selfChatMode: params.account.selfChatMode,
240
+ groupHistories: params.groupHistories,
241
+ groupHistoryLimit: params.groupHistoryLimit,
242
+ groupMemberNames: params.groupMemberNames,
243
+ logVerbose,
244
+ replyLogger: params.replyLogger,
245
+ });
246
+ }
247
+ if (!gating.shouldProcess) {
248
+ return;
249
+ }
250
+ } else {
251
+ // Ensure `peerId` for DMs is stable and stored as E.164 when possible.
252
+ if (!msg.sender?.e164 && !msg.senderE164 && peerId && peerId.startsWith("+")) {
253
+ const normalized = normalizeE164(peerId);
254
+ if (normalized) {
255
+ msg.sender = { ...msg.sender, e164: normalized };
256
+ msg.senderE164 = normalized;
257
+ }
258
+ }
259
+ }
260
+
261
+ await runAudioPreflightOnce();
262
+
263
+ // Broadcast groups: when we'd reply anyway, run multiple agents.
264
+ // Does not bypass group mention/activation gating above.
265
+ if (
266
+ await maybeBroadcastMessage({
267
+ cfg: params.cfg,
268
+ msg,
269
+ peerId,
270
+ route,
271
+ groupHistoryKey,
272
+ groupHistories: params.groupHistories,
273
+ ...(preflightAudioTranscript !== undefined ? { preflightAudioTranscript } : {}),
274
+ // Group ack eligibility depends on the target agent/session, so a
275
+ // preflight ack attempt on the base route must not suppress downstream
276
+ // per-agent checks during broadcast fan-out.
277
+ ...(ackAlreadySent && msg.chatType !== "group" ? { ackAlreadySent: true } : {}),
278
+ ...(ackReaction && msg.chatType !== "group" ? { ackReaction } : {}),
279
+ processMessage: (m, r, k, opts) => processForRoute(m, r, k, opts),
280
+ })
281
+ ) {
282
+ return;
283
+ }
284
+
285
+ await processForRoute(msg, route, groupHistoryKey, {
286
+ ...(preflightAudioTranscript !== undefined ? { preflightAudioTranscript } : {}),
287
+ ...(ackAlreadySent ? { ackAlreadySent: true } : {}),
288
+ ...(ackReaction ? { ackReaction } : {}),
289
+ });
290
+ };
291
+ }
@@ -0,0 +1,17 @@
1
+ import { getSenderIdentity } from "../../identity.js";
2
+ import { jidToE164, normalizeE164 } from "../../text-runtime.js";
3
+ import type { WebInboundMsg } from "../types.js";
4
+
5
+ export function resolvePeerId(msg: WebInboundMsg) {
6
+ if (msg.chatType === "group") {
7
+ return msg.conversationId ?? msg.from;
8
+ }
9
+ const sender = getSenderIdentity(msg);
10
+ if (sender.e164) {
11
+ return normalizeE164(sender.e164) ?? sender.e164;
12
+ }
13
+ if (msg.from.includes("@")) {
14
+ return jidToE164(msg.from) ?? msg.from;
15
+ }
16
+ return normalizeE164(msg.from) ?? msg.from;
17
+ }