Skip to content

Commit 71ca30a

Browse files
committed
feat(whatsapp): agent tools for group create / add participants / invite link
Adds three WhatsApp agent tools, gated behind a new channels.whatsapp.actions.groups flag (default false, since they can add arbitrary people to chats): - whatsapp_group_create — create a group with a subject + E.164 participants, returns the new group JID - whatsapp_group_add_participants — add E.164 participants to a group JID - whatsapp_group_invite_link — resolve the invite code + chat.whatsapp.com link The tools are registered via the channel's agentTools factory and only appear when the gate is enabled. They operate through the existing active web listener, so they require WhatsApp to be linked and the gateway listener to be running — group ops are added to ActiveWebListener (createGroup / addGroupParticipants / getGroupInviteCode) and implemented in createWebSendApi via the reconnect-aware socket (Baileys groupCreate / groupParticipantsUpdate / groupInviteCode). Phone numbers are normalized to JIDs with the same helper used for outbound sends. Includes unit tests for the listener group methods and the agent-tool wrapper (gate visibility + enforcement, JID/participant validation, not-linked error), the actions.groups config schema + type, regenerated channel config metadata, and docs.
1 parent bc47071 commit 71ca30a

14 files changed

Lines changed: 587 additions & 25 deletions

‎docs/channels/whatsapp.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,8 +587,33 @@ Behavior notes:
587587
- Action gates:
588588
- `channels.whatsapp.actions.reactions`
589589
- `channels.whatsapp.actions.polls`
590+
- `channels.whatsapp.actions.groups`
590591
- Channel-initiated config writes are enabled by default (disable via `channels.whatsapp.configWrites=false`).
591592

593+
### Group management tools
594+
595+
When `channels.whatsapp.actions.groups` is `true` (default `false`), the agent gains three group tools, available only while WhatsApp is linked and the gateway listener is active:
596+
597+
| Tool | Purpose |
598+
| --------------------------------- | ----------------------------------------------------------------------------------------------- |
599+
| `whatsapp_group_create` | Create a group with a subject and participants (E.164 numbers). Returns the new group JID. |
600+
| `whatsapp_group_add_participants` | Add participants (E.164 numbers) to an existing group JID. |
601+
| `whatsapp_group_invite_link` | Resolve the invite code + `https://chat.whatsapp.com/...` link for a group the bot administers. |
602+
603+
These actions can add arbitrary people to chats, so they are opt-in:
604+
605+
```json5
606+
{
607+
channels: {
608+
whatsapp: {
609+
actions: {
610+
groups: true,
611+
},
612+
},
613+
},
614+
}
615+
```
616+
592617
## Troubleshooting
593618

594619
<AccordionGroup>
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
import { getActiveWebListener, resolveWebAccountId } from "./active-listener.js";
4+
import { createWhatsAppGroupTools } from "./agent-tools-groups.js";
5+
import type { ActiveWebListener } from "./inbound/types.js";
6+
7+
const getRuntimeConfigMock = vi.fn<() => OpenClawConfig>();
8+
9+
vi.mock("openclaw/plugin-sdk/runtime-config-snapshot", () => ({
10+
getRuntimeConfig: () => getRuntimeConfigMock(),
11+
}));
12+
13+
vi.mock("./active-listener.js", () => ({
14+
getActiveWebListener: vi.fn(),
15+
resolveWebAccountId: vi.fn(() => "default"),
16+
}));
17+
18+
const getActiveWebListenerMock = vi.mocked(getActiveWebListener);
19+
const resolveWebAccountIdMock = vi.mocked(resolveWebAccountId);
20+
21+
function cfgWithGroups(enabled: boolean): OpenClawConfig {
22+
return {
23+
channels: { whatsapp: { actions: { groups: enabled } } },
24+
} as unknown as OpenClawConfig;
25+
}
26+
27+
function stubListener(): ActiveWebListener {
28+
return {
29+
sendMessage: vi.fn(),
30+
sendPoll: vi.fn(),
31+
sendReaction: vi.fn(),
32+
sendComposingTo: vi.fn(),
33+
createGroup: vi.fn(async (subject: string) => ({
34+
groupJid: "[email protected]",
35+
subject,
36+
})),
37+
addGroupParticipants: vi.fn(async (_jid: string, participants: string[]) =>
38+
participants.map((jid) => ({ jid, status: "200" })),
39+
),
40+
getGroupInviteCode: vi.fn(async () => ({
41+
code: "INVITE1234",
42+
inviteLink: "https://chat.whatsapp.com/INVITE1234",
43+
})),
44+
} as unknown as ActiveWebListener;
45+
}
46+
47+
function toolsByName() {
48+
const tools = createWhatsAppGroupTools({ cfg: cfgWithGroups(true) });
49+
return new Map(tools.map((t) => [t.name, t]));
50+
}
51+
52+
describe("createWhatsAppGroupTools", () => {
53+
beforeEach(() => {
54+
vi.clearAllMocks();
55+
resolveWebAccountIdMock.mockReturnValue("default");
56+
});
57+
58+
it("returns no tools when the groups action gate is disabled", () => {
59+
expect(createWhatsAppGroupTools({ cfg: cfgWithGroups(false) })).toEqual([]);
60+
expect(createWhatsAppGroupTools({ cfg: undefined })).toEqual([]);
61+
});
62+
63+
it("registers the three group tools when the gate is enabled", () => {
64+
const names = createWhatsAppGroupTools({ cfg: cfgWithGroups(true) }).map((t) => t.name);
65+
expect(names).toEqual([
66+
"whatsapp_group_create",
67+
"whatsapp_group_add_participants",
68+
"whatsapp_group_invite_link",
69+
]);
70+
});
71+
72+
it("creates a group via the active listener", async () => {
73+
const listener = stubListener();
74+
getActiveWebListenerMock.mockReturnValue(listener);
75+
getRuntimeConfigMock.mockReturnValue(cfgWithGroups(true));
76+
77+
const tool = toolsByName().get("whatsapp_group_create")!;
78+
const result = await tool.execute("call-1", {
79+
subject: "Team",
80+
participants: ["+15555550000"],
81+
});
82+
83+
expect(listener.createGroup).toHaveBeenCalledWith("Team", ["+15555550000"]);
84+
expect(result.details).toEqual({ groupJid: "[email protected]", subject: "Team" });
85+
});
86+
87+
it("throws when the gate is disabled at execute time", async () => {
88+
getRuntimeConfigMock.mockReturnValue(cfgWithGroups(false));
89+
const tool = toolsByName().get("whatsapp_group_create")!;
90+
await expect(
91+
tool.execute("call-1", { subject: "Team", participants: ["+15555550000"] }),
92+
).rejects.toThrow(/disabled/);
93+
});
94+
95+
it("throws when WhatsApp is not linked", async () => {
96+
getActiveWebListenerMock.mockReturnValue(null);
97+
getRuntimeConfigMock.mockReturnValue(cfgWithGroups(true));
98+
const tool = toolsByName().get("whatsapp_group_create")!;
99+
await expect(
100+
tool.execute("call-1", { subject: "Team", participants: ["+15555550000"] }),
101+
).rejects.toThrow(/not linked/);
102+
});
103+
104+
it("rejects an invalid group JID for add-participants", async () => {
105+
getActiveWebListenerMock.mockReturnValue(stubListener());
106+
getRuntimeConfigMock.mockReturnValue(cfgWithGroups(true));
107+
const tool = toolsByName().get("whatsapp_group_add_participants")!;
108+
await expect(
109+
tool.execute("call-1", { group_jid: "not-a-jid", participants: ["+15555550000"] }),
110+
).rejects.toThrow(/group_jid/);
111+
});
112+
113+
it("returns the invite link", async () => {
114+
getActiveWebListenerMock.mockReturnValue(stubListener());
115+
getRuntimeConfigMock.mockReturnValue(cfgWithGroups(true));
116+
const tool = toolsByName().get("whatsapp_group_invite_link")!;
117+
const result = await tool.execute("call-1", { group_jid: "[email protected]" });
118+
expect(result.content).toEqual([
119+
{ type: "text", text: "https://chat.whatsapp.com/INVITE1234" },
120+
]);
121+
});
122+
});
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
import { createActionGate } from "openclaw/plugin-sdk/channel-actions";
2+
import type { ChannelAgentTool } from "openclaw/plugin-sdk/channel-contract";
3+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
4+
import { getRuntimeConfig } from "openclaw/plugin-sdk/runtime-config-snapshot";
5+
import { Type } from "typebox";
6+
import { getActiveWebListener, resolveWebAccountId } from "./active-listener.js";
7+
import type { ActiveWebListener } from "./inbound/types.js";
8+
9+
const GROUP_JID_PATTERN = "@g.us";
10+
11+
function areWhatsAppGroupActionsEnabled(cfg: OpenClawConfig): boolean {
12+
if (!cfg.channels?.whatsapp) {
13+
return false;
14+
}
15+
// Default false: group creation/participant changes can add arbitrary people
16+
// to chats, so they are opt-in via channels.whatsapp.actions.groups.
17+
return createActionGate(cfg.channels.whatsapp.actions)("groups", false);
18+
}
19+
20+
/**
21+
* Resolve the active, linked WhatsApp listener for the given account, enforcing
22+
* the `groups` action gate. Reads live config so a runtime toggle is honored
23+
* without a gateway restart. Throws a clear, agent-readable error otherwise.
24+
*/
25+
function requireGroupCapableListener(accountIdArg: unknown): ActiveWebListener {
26+
const cfg = getRuntimeConfig();
27+
if (!areWhatsAppGroupActionsEnabled(cfg)) {
28+
throw new Error(
29+
"WhatsApp group actions are disabled. Set channels.whatsapp.actions.groups = true to enable them.",
30+
);
31+
}
32+
const accountId = resolveWebAccountId({
33+
cfg,
34+
accountId: typeof accountIdArg === "string" ? accountIdArg : null,
35+
});
36+
const listener = getActiveWebListener(accountId);
37+
if (!listener) {
38+
throw new Error(`WhatsApp is not linked (account: ${accountId}). Link it first, then retry.`);
39+
}
40+
return listener;
41+
}
42+
43+
function readParticipants(value: unknown): string[] {
44+
if (!Array.isArray(value) || value.length === 0) {
45+
throw new Error("participants must be a non-empty array of phone numbers (E.164).");
46+
}
47+
const participants = value
48+
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
49+
.filter(Boolean);
50+
if (participants.length === 0) {
51+
throw new Error("participants must contain at least one phone number (E.164).");
52+
}
53+
return participants;
54+
}
55+
56+
function readGroupJid(value: unknown): string {
57+
const jid = typeof value === "string" ? value.trim() : "";
58+
if (!jid.endsWith(GROUP_JID_PATTERN)) {
59+
throw new Error("group_jid must be a WhatsApp group JID, e.g. [email protected].");
60+
}
61+
return jid;
62+
}
63+
64+
function createWhatsAppGroupCreateTool(): ChannelAgentTool {
65+
return {
66+
label: "WhatsApp Create Group",
67+
name: "whatsapp_group_create",
68+
description:
69+
"Create a new WhatsApp group with the given subject and participants. Returns the new group JID — use it for future group operations.",
70+
parameters: Type.Object({
71+
subject: Type.String({ description: "Group name." }),
72+
participants: Type.Array(Type.String(), {
73+
description: "Phone numbers in E.164 format, e.g. +15551234567.",
74+
}),
75+
accountId: Type.Optional(Type.String()),
76+
}),
77+
execute: async (_toolCallId, args) => {
78+
const { subject, participants, accountId } = args as {
79+
subject?: string;
80+
participants?: unknown;
81+
accountId?: string;
82+
};
83+
const trimmedSubject = typeof subject === "string" ? subject.trim() : "";
84+
if (!trimmedSubject) {
85+
throw new Error("subject is required.");
86+
}
87+
const listener = requireGroupCapableListener(accountId);
88+
const result = await listener.createGroup(trimmedSubject, readParticipants(participants));
89+
return {
90+
content: [
91+
{
92+
type: "text",
93+
text: `Created WhatsApp group "${result.subject}" (${result.groupJid}).`,
94+
},
95+
],
96+
details: result,
97+
};
98+
},
99+
};
100+
}
101+
102+
function createWhatsAppGroupAddTool(): ChannelAgentTool {
103+
return {
104+
label: "WhatsApp Add Group Participants",
105+
name: "whatsapp_group_add_participants",
106+
description: "Add participants to an existing WhatsApp group.",
107+
parameters: Type.Object({
108+
group_jid: Type.String({
109+
description: "Group JID, e.g. [email protected].",
110+
}),
111+
participants: Type.Array(Type.String(), {
112+
description: "Phone numbers in E.164 format to add.",
113+
}),
114+
accountId: Type.Optional(Type.String()),
115+
}),
116+
execute: async (_toolCallId, args) => {
117+
const { group_jid, participants, accountId } = args as {
118+
group_jid?: unknown;
119+
participants?: unknown;
120+
accountId?: string;
121+
};
122+
const groupJid = readGroupJid(group_jid);
123+
const listener = requireGroupCapableListener(accountId);
124+
const results = await listener.addGroupParticipants(groupJid, readParticipants(participants));
125+
return {
126+
content: [
127+
{
128+
type: "text",
129+
text: results.map((r) => `${r.jid ?? "(unknown)"}: ${r.status}`).join("\n"),
130+
},
131+
],
132+
details: { groupJid, results },
133+
};
134+
},
135+
};
136+
}
137+
138+
function createWhatsAppGroupInviteLinkTool(): ChannelAgentTool {
139+
return {
140+
label: "WhatsApp Group Invite Link",
141+
name: "whatsapp_group_invite_link",
142+
description: "Get the invite link for a WhatsApp group the bot administers.",
143+
parameters: Type.Object({
144+
group_jid: Type.String({
145+
description: "Group JID, e.g. [email protected].",
146+
}),
147+
accountId: Type.Optional(Type.String()),
148+
}),
149+
execute: async (_toolCallId, args) => {
150+
const { group_jid, accountId } = args as {
151+
group_jid?: unknown;
152+
accountId?: string;
153+
};
154+
const groupJid = readGroupJid(group_jid);
155+
const listener = requireGroupCapableListener(accountId);
156+
const result = await listener.getGroupInviteCode(groupJid);
157+
return {
158+
content: [{ type: "text", text: result.inviteLink }],
159+
details: { groupJid, ...result },
160+
};
161+
},
162+
};
163+
}
164+
165+
/**
166+
* WhatsApp group-management agent tools. Returned only when
167+
* `channels.whatsapp.actions.groups` is enabled, so disabled installs don't
168+
* advertise tools the agent can't use. Each tool also re-checks the gate at
169+
* execute time and requires an active linked listener.
170+
*/
171+
export function createWhatsAppGroupTools(params: { cfg?: OpenClawConfig }): ChannelAgentTool[] {
172+
if (!params.cfg || !areWhatsAppGroupActionsEnabled(params.cfg)) {
173+
return [];
174+
}
175+
return [
176+
createWhatsAppGroupCreateTool(),
177+
createWhatsAppGroupAddTool(),
178+
createWhatsAppGroupInviteLinkTool(),
179+
];
180+
}

‎extensions/whatsapp/src/auto-reply.test-harness.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ type MockWebListener = {
3131
sendPoll: () => Promise<WhatsAppSendResult>;
3232
sendReaction: () => Promise<WhatsAppSendResult>;
3333
sendComposingTo: () => Promise<void>;
34+
createGroup: () => Promise<{ groupJid: string; subject: string }>;
35+
addGroupParticipants: () => Promise<Array<{ jid: string | undefined; status: string }>>;
36+
getGroupInviteCode: () => Promise<{ code: string; inviteLink: string }>;
3437
};
3538
type UnknownMock = Mock<(...args: unknown[]) => unknown>;
3639
type AsyncUnknownMock = Mock<(...args: unknown[]) => Promise<unknown>>;
@@ -265,6 +268,12 @@ export function createMockWebListener(): MockWebListener {
265268
sendPoll: vi.fn(async () => createAcceptedWhatsAppSendResult("poll", "poll-1")),
266269
sendReaction: vi.fn(async () => createAcceptedWhatsAppSendResult("reaction", "reaction-1")),
267270
sendComposingTo: vi.fn(async () => undefined),
271+
createGroup: vi.fn(async () => ({ groupJid: "[email protected]", subject: "Group" })),
272+
addGroupParticipants: vi.fn(async () => []),
273+
getGroupInviteCode: vi.fn(async () => ({
274+
code: "INVITE1234",
275+
inviteLink: "https://chat.whatsapp.com/INVITE1234",
276+
})),
268277
};
269278
}
270279

‎extensions/whatsapp/src/channel.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
createDefaultChannelRuntimeState,
88
} from "openclaw/plugin-sdk/status-helpers";
99
import { resolveWhatsAppAccount, type ResolvedWhatsAppAccount } from "./accounts.js";
10+
import { createWhatsAppGroupTools } from "./agent-tools-groups.js";
1011
import { createWhatsAppLoginTool } from "./agent-tools-login.js";
1112
import { whatsappApprovalCapability } from "./approval-native.js";
1213
import type { WebChannelStatus } from "./auto-reply/types.js";
@@ -93,7 +94,7 @@ export const whatsappPlugin: ChannelPlugin<ResolvedWhatsAppAccount> =
9394
return (await channelRuntime.readWebAuthState(account.authDir)) === "linked";
9495
},
9596
}),
96-
agentTools: () => [createWhatsAppLoginTool()],
97+
agentTools: (params) => [createWhatsAppLoginTool(), ...createWhatsAppGroupTools(params)],
9798
allowlist: buildDmGroupAccountAllowlistAdapter({
9899
channelId: "whatsapp",
99100
resolveAccount: resolveWhatsAppAccount,

‎extensions/whatsapp/src/connection-controller.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,17 @@ function createListenerStub(messageId = "ok") {
3737
sendPoll: vi.fn(async () => acceptedSendResult("poll", messageId)),
3838
sendReaction: vi.fn(async () => acceptedSendResult("reaction", messageId)),
3939
sendComposingTo: vi.fn(async () => {}),
40+
createGroup: vi.fn(async (subject: string) => ({
41+
groupJid: "[email protected]",
42+
subject,
43+
})),
44+
addGroupParticipants: vi.fn(async (_groupJid: string, participants: string[]) =>
45+
participants.map((jid) => ({ jid, status: "200" })),
46+
),
47+
getGroupInviteCode: vi.fn(async () => ({
48+
code: "INVITE1234",
49+
inviteLink: "https://chat.whatsapp.com/INVITE1234",
50+
})),
4051
};
4152
}
4253

0 commit comments

Comments
 (0)