Include full contents of all nested repositories

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 16:25:02 +01:00
parent 14ff8fd54c
commit 2401ed446f
7271 changed files with 1310112 additions and 6 deletions

View File

@@ -0,0 +1,17 @@
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
import { whatsappPlugin } from "./src/channel.js";
import { setWhatsAppRuntime } from "./src/runtime.js";
const plugin = {
id: "whatsapp",
name: "WhatsApp",
description: "WhatsApp channel plugin",
configSchema: emptyPluginConfigSchema(),
register(api: OpenClawPluginApi) {
setWhatsAppRuntime(api.runtime);
api.registerChannel({ plugin: whatsappPlugin });
},
};
export default plugin;

View File

@@ -0,0 +1,9 @@
{
"id": "whatsapp",
"channels": ["whatsapp"],
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {}
}
}

View File

@@ -0,0 +1,12 @@
{
"name": "@openclaw/whatsapp",
"version": "2026.2.26",
"private": true,
"description": "OpenClaw WhatsApp channel plugin",
"type": "module",
"openclaw": {
"extensions": [
"./index.ts"
]
}
}

View File

@@ -0,0 +1,459 @@
import {
applyAccountNameToChannelSection,
buildChannelConfigSchema,
collectWhatsAppStatusIssues,
createActionGate,
DEFAULT_ACCOUNT_ID,
formatPairingApproveHint,
getChatChannelMeta,
listWhatsAppAccountIds,
listWhatsAppDirectoryGroupsFromConfig,
listWhatsAppDirectoryPeersFromConfig,
looksLikeWhatsAppTargetId,
migrateBaseNameToDefaultAccount,
normalizeAccountId,
normalizeE164,
normalizeWhatsAppAllowFromEntries,
normalizeWhatsAppMessagingTarget,
readStringParam,
resolveDefaultWhatsAppAccountId,
resolveWhatsAppOutboundTarget,
resolveAllowlistProviderRuntimeGroupPolicy,
resolveDefaultGroupPolicy,
resolveWhatsAppAccount,
resolveWhatsAppGroupRequireMention,
resolveWhatsAppGroupIntroHint,
resolveWhatsAppGroupToolPolicy,
resolveWhatsAppHeartbeatRecipients,
resolveWhatsAppMentionStripPatterns,
whatsappOnboardingAdapter,
WhatsAppConfigSchema,
type ChannelMessageActionName,
type ChannelPlugin,
type ResolvedWhatsAppAccount,
} from "openclaw/plugin-sdk";
import { getWhatsAppRuntime } from "./runtime.js";
const meta = getChatChannelMeta("whatsapp");
export const whatsappPlugin: ChannelPlugin<ResolvedWhatsAppAccount> = {
id: "whatsapp",
meta: {
...meta,
showConfigured: false,
quickstartAllowFrom: true,
forceAccountBinding: true,
preferSessionLookupForAnnounceTarget: true,
},
onboarding: whatsappOnboardingAdapter,
agentTools: () => [getWhatsAppRuntime().channel.whatsapp.createLoginTool()],
pairing: {
idLabel: "whatsappSenderId",
},
capabilities: {
chatTypes: ["direct", "group"],
polls: true,
reactions: true,
media: true,
},
reload: { configPrefixes: ["web"], noopPrefixes: ["channels.whatsapp"] },
gatewayMethods: ["web.login.start", "web.login.wait"],
configSchema: buildChannelConfigSchema(WhatsAppConfigSchema),
config: {
listAccountIds: (cfg) => listWhatsAppAccountIds(cfg),
resolveAccount: (cfg, accountId) => resolveWhatsAppAccount({ cfg, accountId }),
defaultAccountId: (cfg) => resolveDefaultWhatsAppAccountId(cfg),
setAccountEnabled: ({ cfg, accountId, enabled }) => {
const accountKey = accountId || DEFAULT_ACCOUNT_ID;
const accounts = { ...cfg.channels?.whatsapp?.accounts };
const existing = accounts[accountKey] ?? {};
return {
...cfg,
channels: {
...cfg.channels,
whatsapp: {
...cfg.channels?.whatsapp,
accounts: {
...accounts,
[accountKey]: {
...existing,
enabled,
},
},
},
},
};
},
deleteAccount: ({ cfg, accountId }) => {
const accountKey = accountId || DEFAULT_ACCOUNT_ID;
const accounts = { ...cfg.channels?.whatsapp?.accounts };
delete accounts[accountKey];
return {
...cfg,
channels: {
...cfg.channels,
whatsapp: {
...cfg.channels?.whatsapp,
accounts: Object.keys(accounts).length ? accounts : undefined,
},
},
};
},
isEnabled: (account, cfg) => account.enabled && cfg.web?.enabled !== false,
disabledReason: () => "disabled",
isConfigured: async (account) =>
await getWhatsAppRuntime().channel.whatsapp.webAuthExists(account.authDir),
unconfiguredReason: () => "not linked",
describeAccount: (account) => ({
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: Boolean(account.authDir),
linked: Boolean(account.authDir),
dmPolicy: account.dmPolicy,
allowFrom: account.allowFrom,
}),
resolveAllowFrom: ({ cfg, accountId }) =>
resolveWhatsAppAccount({ cfg, accountId }).allowFrom ?? [],
formatAllowFrom: ({ allowFrom }) => normalizeWhatsAppAllowFromEntries(allowFrom),
resolveDefaultTo: ({ cfg, accountId }) => {
const root = cfg.channels?.whatsapp;
const normalized = normalizeAccountId(accountId);
const account = root?.accounts?.[normalized];
return (account?.defaultTo ?? root?.defaultTo)?.trim() || undefined;
},
},
security: {
resolveDmPolicy: ({ cfg, accountId, account }) => {
const resolvedAccountId = accountId ?? account.accountId ?? DEFAULT_ACCOUNT_ID;
const useAccountPath = Boolean(cfg.channels?.whatsapp?.accounts?.[resolvedAccountId]);
const basePath = useAccountPath
? `channels.whatsapp.accounts.${resolvedAccountId}.`
: "channels.whatsapp.";
return {
policy: account.dmPolicy ?? "pairing",
allowFrom: account.allowFrom ?? [],
policyPath: `${basePath}dmPolicy`,
allowFromPath: basePath,
approveHint: formatPairingApproveHint("whatsapp"),
normalizeEntry: (raw) => normalizeE164(raw),
};
},
collectWarnings: ({ account, cfg }) => {
const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
const { groupPolicy } = resolveAllowlistProviderRuntimeGroupPolicy({
providerConfigPresent: cfg.channels?.whatsapp !== undefined,
groupPolicy: account.groupPolicy,
defaultGroupPolicy,
});
if (groupPolicy !== "open") {
return [];
}
const groupAllowlistConfigured =
Boolean(account.groups) && Object.keys(account.groups ?? {}).length > 0;
if (groupAllowlistConfigured) {
return [
`- WhatsApp groups: groupPolicy="open" allows any member in allowed groups to trigger (mention-gated). Set channels.whatsapp.groupPolicy="allowlist" + channels.whatsapp.groupAllowFrom to restrict senders.`,
];
}
return [
`- WhatsApp groups: groupPolicy="open" with no channels.whatsapp.groups allowlist; any group can add + ping (mention-gated). Set channels.whatsapp.groupPolicy="allowlist" + channels.whatsapp.groupAllowFrom or configure channels.whatsapp.groups.`,
];
},
},
setup: {
resolveAccountId: ({ accountId }) => normalizeAccountId(accountId),
applyAccountName: ({ cfg, accountId, name }) =>
applyAccountNameToChannelSection({
cfg,
channelKey: "whatsapp",
accountId,
name,
alwaysUseAccounts: true,
}),
applyAccountConfig: ({ cfg, accountId, input }) => {
const namedConfig = applyAccountNameToChannelSection({
cfg,
channelKey: "whatsapp",
accountId,
name: input.name,
alwaysUseAccounts: true,
});
const next = migrateBaseNameToDefaultAccount({
cfg: namedConfig,
channelKey: "whatsapp",
alwaysUseAccounts: true,
});
const entry = {
...next.channels?.whatsapp?.accounts?.[accountId],
...(input.authDir ? { authDir: input.authDir } : {}),
enabled: true,
};
return {
...next,
channels: {
...next.channels,
whatsapp: {
...next.channels?.whatsapp,
accounts: {
...next.channels?.whatsapp?.accounts,
[accountId]: entry,
},
},
},
};
},
},
groups: {
resolveRequireMention: resolveWhatsAppGroupRequireMention,
resolveToolPolicy: resolveWhatsAppGroupToolPolicy,
resolveGroupIntroHint: resolveWhatsAppGroupIntroHint,
},
mentions: {
stripPatterns: ({ ctx }) => resolveWhatsAppMentionStripPatterns(ctx),
},
commands: {
enforceOwnerForCommands: true,
skipWhenConfigEmpty: true,
},
messaging: {
normalizeTarget: normalizeWhatsAppMessagingTarget,
targetResolver: {
looksLikeId: looksLikeWhatsAppTargetId,
hint: "<E.164|group JID>",
},
},
directory: {
self: async ({ cfg, accountId }) => {
const account = resolveWhatsAppAccount({ cfg, accountId });
const { e164, jid } = getWhatsAppRuntime().channel.whatsapp.readWebSelfId(account.authDir);
const id = e164 ?? jid;
if (!id) {
return null;
}
return {
kind: "user",
id,
name: account.name,
raw: { e164, jid },
};
},
listPeers: async (params) => listWhatsAppDirectoryPeersFromConfig(params),
listGroups: async (params) => listWhatsAppDirectoryGroupsFromConfig(params),
},
actions: {
listActions: ({ cfg }) => {
if (!cfg.channels?.whatsapp) {
return [];
}
const gate = createActionGate(cfg.channels.whatsapp.actions);
const actions = new Set<ChannelMessageActionName>();
if (gate("reactions")) {
actions.add("react");
}
if (gate("polls")) {
actions.add("poll");
}
return Array.from(actions);
},
supportsAction: ({ action }) => action === "react",
handleAction: async ({ action, params, cfg, accountId }) => {
if (action !== "react") {
throw new Error(`Action ${action} is not supported for provider ${meta.id}.`);
}
const messageId = readStringParam(params, "messageId", {
required: true,
});
const emoji = readStringParam(params, "emoji", { allowEmpty: true });
const remove = typeof params.remove === "boolean" ? params.remove : undefined;
return await getWhatsAppRuntime().channel.whatsapp.handleWhatsAppAction(
{
action: "react",
chatJid:
readStringParam(params, "chatJid") ?? readStringParam(params, "to", { required: true }),
messageId,
emoji,
remove,
participant: readStringParam(params, "participant"),
accountId: accountId ?? undefined,
fromMe: typeof params.fromMe === "boolean" ? params.fromMe : undefined,
},
cfg,
);
},
},
outbound: {
deliveryMode: "gateway",
chunker: (text, limit) => getWhatsAppRuntime().channel.text.chunkText(text, limit),
chunkerMode: "text",
textChunkLimit: 4000,
pollMaxOptions: 12,
resolveTarget: ({ to, allowFrom, mode }) =>
resolveWhatsAppOutboundTarget({ to, allowFrom, mode }),
sendText: async ({ to, text, accountId, deps, gifPlayback }) => {
const send = deps?.sendWhatsApp ?? getWhatsAppRuntime().channel.whatsapp.sendMessageWhatsApp;
const result = await send(to, text, {
verbose: false,
accountId: accountId ?? undefined,
gifPlayback,
});
return { channel: "whatsapp", ...result };
},
sendMedia: async ({ to, text, mediaUrl, accountId, deps, gifPlayback }) => {
const send = deps?.sendWhatsApp ?? getWhatsAppRuntime().channel.whatsapp.sendMessageWhatsApp;
const result = await send(to, text, {
verbose: false,
mediaUrl,
accountId: accountId ?? undefined,
gifPlayback,
});
return { channel: "whatsapp", ...result };
},
sendPoll: async ({ to, poll, accountId }) =>
await getWhatsAppRuntime().channel.whatsapp.sendPollWhatsApp(to, poll, {
verbose: getWhatsAppRuntime().logging.shouldLogVerbose(),
accountId: accountId ?? undefined,
}),
},
auth: {
login: async ({ cfg, accountId, runtime, verbose }) => {
const resolvedAccountId = accountId?.trim() || resolveDefaultWhatsAppAccountId(cfg);
await getWhatsAppRuntime().channel.whatsapp.loginWeb(
Boolean(verbose),
undefined,
runtime,
resolvedAccountId,
);
},
},
heartbeat: {
checkReady: async ({ cfg, accountId, deps }) => {
if (cfg.web?.enabled === false) {
return { ok: false, reason: "whatsapp-disabled" };
}
const account = resolveWhatsAppAccount({ cfg, accountId });
const authExists = await (
deps?.webAuthExists ?? getWhatsAppRuntime().channel.whatsapp.webAuthExists
)(account.authDir);
if (!authExists) {
return { ok: false, reason: "whatsapp-not-linked" };
}
const listenerActive = deps?.hasActiveWebListener
? deps.hasActiveWebListener()
: Boolean(getWhatsAppRuntime().channel.whatsapp.getActiveWebListener());
if (!listenerActive) {
return { ok: false, reason: "whatsapp-not-running" };
}
return { ok: true, reason: "ok" };
},
resolveRecipients: ({ cfg, opts }) => resolveWhatsAppHeartbeatRecipients(cfg, opts),
},
status: {
defaultRuntime: {
accountId: DEFAULT_ACCOUNT_ID,
running: false,
connected: false,
reconnectAttempts: 0,
lastConnectedAt: null,
lastDisconnect: null,
lastMessageAt: null,
lastEventAt: null,
lastError: null,
},
collectStatusIssues: collectWhatsAppStatusIssues,
buildChannelSummary: async ({ account, snapshot }) => {
const authDir = account.authDir;
const linked =
typeof snapshot.linked === "boolean"
? snapshot.linked
: authDir
? await getWhatsAppRuntime().channel.whatsapp.webAuthExists(authDir)
: false;
const authAgeMs =
linked && authDir ? getWhatsAppRuntime().channel.whatsapp.getWebAuthAgeMs(authDir) : null;
const self =
linked && authDir
? getWhatsAppRuntime().channel.whatsapp.readWebSelfId(authDir)
: { e164: null, jid: null };
return {
configured: linked,
linked,
authAgeMs,
self,
running: snapshot.running ?? false,
connected: snapshot.connected ?? false,
lastConnectedAt: snapshot.lastConnectedAt ?? null,
lastDisconnect: snapshot.lastDisconnect ?? null,
reconnectAttempts: snapshot.reconnectAttempts,
lastMessageAt: snapshot.lastMessageAt ?? null,
lastEventAt: snapshot.lastEventAt ?? null,
lastError: snapshot.lastError ?? null,
};
},
buildAccountSnapshot: async ({ account, runtime }) => {
const linked = await getWhatsAppRuntime().channel.whatsapp.webAuthExists(account.authDir);
return {
accountId: account.accountId,
name: account.name,
enabled: account.enabled,
configured: true,
linked,
running: runtime?.running ?? false,
connected: runtime?.connected ?? false,
reconnectAttempts: runtime?.reconnectAttempts,
lastConnectedAt: runtime?.lastConnectedAt ?? null,
lastDisconnect: runtime?.lastDisconnect ?? null,
lastMessageAt: runtime?.lastMessageAt ?? null,
lastEventAt: runtime?.lastEventAt ?? null,
lastError: runtime?.lastError ?? null,
dmPolicy: account.dmPolicy,
allowFrom: account.allowFrom,
};
},
resolveAccountState: ({ configured }) => (configured ? "linked" : "not linked"),
logSelfId: ({ account, runtime, includeChannelPrefix }) => {
getWhatsAppRuntime().channel.whatsapp.logWebSelfId(
account.authDir,
runtime,
includeChannelPrefix,
);
},
},
gateway: {
startAccount: async (ctx) => {
const account = ctx.account;
const { e164, jid } = getWhatsAppRuntime().channel.whatsapp.readWebSelfId(account.authDir);
const identity = e164 ? e164 : jid ? `jid ${jid}` : "unknown";
ctx.log?.info(`[${account.accountId}] starting provider (${identity})`);
return getWhatsAppRuntime().channel.whatsapp.monitorWebChannel(
getWhatsAppRuntime().logging.shouldLogVerbose(),
undefined,
true,
undefined,
ctx.runtime,
ctx.abortSignal,
{
statusSink: (next) => ctx.setStatus({ accountId: ctx.accountId, ...next }),
accountId: account.accountId,
},
);
},
loginWithQrStart: async ({ accountId, force, timeoutMs, verbose }) =>
await getWhatsAppRuntime().channel.whatsapp.startWebLoginWithQr({
accountId,
force,
timeoutMs,
verbose,
}),
loginWithQrWait: async ({ accountId, timeoutMs }) =>
await getWhatsAppRuntime().channel.whatsapp.waitForWebLogin({ accountId, timeoutMs }),
logoutAccount: async ({ account, runtime }) => {
const cleared = await getWhatsAppRuntime().channel.whatsapp.logoutWeb({
authDir: account.authDir,
isLegacyAuthDir: account.isLegacyAuthDir,
runtime,
});
return { cleared, loggedOut: cleared };
},
},
};

View File

@@ -0,0 +1,172 @@
import { describe, expect, it, vi } from "vitest";
import { installCommonResolveTargetErrorCases } from "../../shared/resolve-target-test-helpers.js";
vi.mock("openclaw/plugin-sdk", () => ({
getChatChannelMeta: () => ({ id: "whatsapp", label: "WhatsApp" }),
normalizeWhatsAppTarget: (value: string) => {
if (value === "invalid-target") return null;
// Simulate E.164 normalization: strip leading + and whatsapp: prefix
const stripped = value.replace(/^whatsapp:/i, "").replace(/^\+/, "");
return stripped.includes("@g.us") ? stripped : `${stripped}@s.whatsapp.net`;
},
isWhatsAppGroupJid: (value: string) => value.endsWith("@g.us"),
resolveWhatsAppOutboundTarget: ({
to,
allowFrom,
mode,
}: {
to?: string;
allowFrom: string[];
mode: "explicit" | "implicit";
}) => {
const raw = typeof to === "string" ? to.trim() : "";
if (!raw) {
return { ok: false, error: new Error("missing target") };
}
const normalizeWhatsAppTarget = (value: string) => {
if (value === "invalid-target") return null;
const stripped = value.replace(/^whatsapp:/i, "").replace(/^\+/, "");
return stripped.includes("@g.us") ? stripped : `${stripped}@s.whatsapp.net`;
};
const normalized = normalizeWhatsAppTarget(raw);
if (!normalized) {
return { ok: false, error: new Error("invalid target") };
}
if (mode === "implicit" && !normalized.endsWith("@g.us")) {
const allowAll = allowFrom.includes("*");
const allowExact = allowFrom.some((entry) => {
if (!entry) {
return false;
}
const normalizedEntry = normalizeWhatsAppTarget(entry.trim());
return normalizedEntry?.toLowerCase() === normalized.toLowerCase();
});
if (!allowAll && !allowExact) {
return { ok: false, error: new Error("target not allowlisted") };
}
}
return { ok: true, to: normalized };
},
missingTargetError: (provider: string, hint: string) =>
new Error(`Delivering to ${provider} requires target ${hint}`),
WhatsAppConfigSchema: {},
whatsappOnboardingAdapter: {},
resolveWhatsAppHeartbeatRecipients: vi.fn(),
buildChannelConfigSchema: vi.fn(),
collectWhatsAppStatusIssues: vi.fn(),
createActionGate: vi.fn(),
DEFAULT_ACCOUNT_ID: "default",
escapeRegExp: vi.fn(),
formatPairingApproveHint: vi.fn(),
listWhatsAppAccountIds: vi.fn(),
listWhatsAppDirectoryGroupsFromConfig: vi.fn(),
listWhatsAppDirectoryPeersFromConfig: vi.fn(),
looksLikeWhatsAppTargetId: vi.fn(),
migrateBaseNameToDefaultAccount: vi.fn(),
normalizeAccountId: vi.fn(),
normalizeE164: vi.fn(),
normalizeWhatsAppMessagingTarget: vi.fn(),
readStringParam: vi.fn(),
resolveDefaultWhatsAppAccountId: vi.fn(),
resolveWhatsAppAccount: vi.fn(),
resolveWhatsAppGroupIntroHint: vi.fn(),
resolveWhatsAppGroupRequireMention: vi.fn(),
resolveWhatsAppGroupToolPolicy: vi.fn(),
resolveWhatsAppMentionStripPatterns: vi.fn(() => []),
applyAccountNameToChannelSection: vi.fn(),
}));
vi.mock("./runtime.js", () => ({
getWhatsAppRuntime: vi.fn(() => ({
channel: {
text: { chunkText: vi.fn() },
whatsapp: {
sendMessageWhatsApp: vi.fn(),
createLoginTool: vi.fn(),
},
},
})),
}));
import { whatsappPlugin } from "./channel.js";
const resolveTarget = whatsappPlugin.outbound!.resolveTarget!;
describe("whatsapp resolveTarget", () => {
it("should resolve valid target in explicit mode", () => {
const result = resolveTarget({
to: "5511999999999",
mode: "explicit",
allowFrom: [],
});
expect(result.ok).toBe(true);
if (!result.ok) {
throw result.error;
}
expect(result.to).toBe("5511999999999@s.whatsapp.net");
});
it("should resolve target in implicit mode with wildcard", () => {
const result = resolveTarget({
to: "5511999999999",
mode: "implicit",
allowFrom: ["*"],
});
expect(result.ok).toBe(true);
if (!result.ok) {
throw result.error;
}
expect(result.to).toBe("5511999999999@s.whatsapp.net");
});
it("should resolve target in implicit mode when in allowlist", () => {
const result = resolveTarget({
to: "5511999999999",
mode: "implicit",
allowFrom: ["5511999999999"],
});
expect(result.ok).toBe(true);
if (!result.ok) {
throw result.error;
}
expect(result.to).toBe("5511999999999@s.whatsapp.net");
});
it("should allow group JID regardless of allowlist", () => {
const result = resolveTarget({
to: "120363123456789@g.us",
mode: "implicit",
allowFrom: ["5511999999999"],
});
expect(result.ok).toBe(true);
if (!result.ok) {
throw result.error;
}
expect(result.to).toBe("120363123456789@g.us");
});
it("should error when target not in allowlist (implicit mode)", () => {
const result = resolveTarget({
to: "5511888888888",
mode: "implicit",
allowFrom: ["5511999999999", "5511777777777"],
});
expect(result.ok).toBe(false);
if (result.ok) {
throw new Error("expected resolution to fail");
}
expect(result.error).toBeDefined();
});
installCommonResolveTargetErrorCases({
resolveTarget,
implicitAllowFrom: ["5511999999999"],
});
});

View File

@@ -0,0 +1,14 @@
import type { PluginRuntime } from "openclaw/plugin-sdk";
let runtime: PluginRuntime | null = null;
export function setWhatsAppRuntime(next: PluginRuntime) {
runtime = next;
}
export function getWhatsAppRuntime(): PluginRuntime {
if (!runtime) {
throw new Error("WhatsApp runtime not initialized");
}
return runtime;
}