Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(plugin): Wave 11.D.9 — WhatsApp + Social inlined
trohitg08fb98a04c94
diff --git a/server/services/handlers/social.py b/server/nodes/social/_base.pysimilarity index 97%rename from server/services/handlers/social.pyrename to server/nodes/social/_base.pyindex 25cf907f..e50decb4 100644--- a/server/services/handlers/social.py+++ b/server/nodes/social/_base.py@@ -1,9 +1,14 @@-"""Social node handlers - Unified messaging across platforms.+"""Social unified-messaging business logic (Wave 11.D.9 inlined).-socialReceive: Normalizes messages from platform-specific triggers into unified format-socialSend: Routes outbound messages to appropriate platform (also works as AI tool)+socialReceive normalizes messages from platform-specific triggers into+a unified format. socialSend routes outbound messages to the correct+platform (WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat,+Email, Matrix, Teams).-Supported platforms: WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat, Email, Matrix, Teams+Imported by :class:`nodes.social.social_receive.SocialReceiveNode` and+:class:`nodes.social.social_send.SocialSendNode`. Calls into+``routers.whatsapp`` for the WhatsApp bridge stay unchanged — moving+them out is a separate refactor."""import timediff --git a/server/nodes/social/social_receive.py b/server/nodes/social/social_receive.pyindex 00188033..44160be8 100644--- a/server/nodes/social/social_receive.py+++ b/server/nodes/social/social_receive.py@@ -60,7 +60,7 @@ class SocialReceiveNode(ActionNode):@Operation("normalize")async def normalize(self, ctx: NodeContext, params: SocialReceiveParams) -> Any:- from services.handlers.social import handle_social_receive+ from ._base import handle_social_receiveoutputs = ctx.raw.get("connected_outputs") or {}source_nodes = ctx.raw.get("source_nodes") or []response = await handle_social_receive(diff --git a/server/nodes/social/social_send.py b/server/nodes/social/social_send.pyindex cb92466d..a7913596 100644--- a/server/nodes/social/social_send.py+++ b/server/nodes/social/social_send.py@@ -57,7 +57,7 @@ class SocialSendNode(ActionNode):@Operation("send", cost={"service": "social", "action": "send", "count": 1})async def send(self, ctx: NodeContext, params: SocialSendParams) -> Any:- from services.handlers.social import handle_social_send+ from ._base import handle_social_sendresponse = await handle_social_send(node_id=ctx.node_id, node_type=self.type,parameters=params.model_dump(by_alias=True), context=ctx.raw,diff --git a/server/services/handlers/whatsapp.py b/server/nodes/whatsapp/_base.pysimilarity index 99%rename from server/services/handlers/whatsapp.pyrename to server/nodes/whatsapp/_base.pyindex 00413081..4b5ae102 100644--- a/server/services/handlers/whatsapp.py+++ b/server/nodes/whatsapp/_base.py@@ -1,4 +1,10 @@-"""WhatsApp node handlers - Send and DB operations."""+"""WhatsApp send + DB business logic (Wave 11.D.9 inlined).++Imported by nodes.whatsapp.whatsapp_send and nodes.whatsapp.whatsapp_db.+RPC dispatch still flows through routers.whatsapp (HTTP to the Go+bridge) — extracting that is a separate refactor, not required for the+plugin migration.+"""import asyncioimport timediff --git a/server/nodes/whatsapp/whatsapp_db.py b/server/nodes/whatsapp/whatsapp_db.pyindex 17d1335b..4f54e9c0 100644--- a/server/nodes/whatsapp/whatsapp_db.py+++ b/server/nodes/whatsapp/whatsapp_db.py@@ -69,7 +69,7 @@ class WhatsAppDbNode(ActionNode):@Operation("query", cost={"service": "whatsapp", "action": "db_query", "count": 1})async def query(self, ctx: NodeContext, params: WhatsAppDbParams) -> Any:- from services.handlers.whatsapp import handle_whatsapp_db+ from ._base import handle_whatsapp_dbresponse = await handle_whatsapp_db(node_id=ctx.node_id, node_type=self.type,parameters=params.model_dump(by_alias=True), context=ctx.raw,diff --git a/server/nodes/whatsapp/whatsapp_send.py b/server/nodes/whatsapp/whatsapp_send.pyindex facebbb2..e62a957e 100644--- a/server/nodes/whatsapp/whatsapp_send.py+++ b/server/nodes/whatsapp/whatsapp_send.py@@ -69,7 +69,7 @@ class WhatsAppSendNode(ActionNode):@Operation("send", cost={"service": "whatsapp", "action": "send", "count": 1})async def send(self, ctx: NodeContext, params: WhatsAppSendParams) -> Any:- from services.handlers.whatsapp import handle_whatsapp_send+ from ._base import handle_whatsapp_sendresponse = await handle_whatsapp_send(node_id=ctx.node_id, node_type=self.type,parameters=params.model_dump(by_alias=True), context=ctx.raw,diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex d677e20b..1e104f0e 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -66,21 +66,13 @@ from .utility import (handle_team_monitor,)-# WhatsApp handlers-from .whatsapp import (- handle_whatsapp_send,- handle_whatsapp_db,-)+# WhatsApp handlers inlined into nodes/whatsapp/*.py (Wave 11.D.9).# Twitter handlers inlined into nodes/twitter/*.py (Wave 11.D.8).# Google Workspace handlers inlined into nodes/google/*.py (Wave 11.D.4).-# Social handlers (unified messaging)-from .social import (- handle_social_receive,- handle_social_send,-)+# Social handlers inlined into nodes/social/*.py (Wave 11.D.9).# Document handlers inlined into nodes/document/*.py (Wave 11.D.7).@@ -156,12 +148,8 @@ __all__ = ['handle_console','handle_team_monitor',- 'handle_whatsapp_send',- 'handle_whatsapp_db',# Social- 'handle_social_receive',- 'handle_social_send',# Search'handle_brave_search','handle_serper_search',diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 79033e12..62df51e6 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -525,309 +525,8 @@ async def _execute_current_time(args: Dict[str, Any],# to nodes/search/duckduckgo_search.py DuckDuckGoSearchNode.search().-async def _execute_whatsapp_send(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Send WhatsApp message with full message type support.-- Supports all message types: text, image, video, audio, document, sticker, location, contact- Recipients: phone number, group_id, or channel_jid (newsletter)- Media sources: URL-- Args:- args: LLM-provided arguments matching WhatsAppSendSchema (snake_case)- node_params: Node parameters (used as fallback)-- Returns:- Dict with success status and message details- """- from services.handlers.whatsapp import handle_whatsapp_send-- # Args are snake_case matching Pydantic schema and frontend node params- parameters = {- 'recipient_type': args.get('recipient_type', 'phone'),- 'phone': args.get('phone', ''),- 'group_id': args.get('group_id', ''),- 'channel_jid': args.get('channel_jid', ''),- 'message_type': args.get('message_type', 'text'),- 'message': args.get('message', ''),- 'media_source': 'url' if args.get('media_url') else 'none',- 'media_url': args.get('media_url', ''),- 'caption': args.get('caption', ''),- 'latitude': args.get('latitude'),- 'longitude': args.get('longitude'),- 'location_name': args.get('location_name', ''),- 'address': args.get('address', ''),- 'contact_name': args.get('contact_name', ''),- 'vcard': args.get('vcard', ''),- }-- # Validate required fields based on message type- recipient_type = parameters['recipient_type']- message_type = parameters['message_type']-- if recipient_type == 'phone' and not parameters['phone']:- return {"error": "Phone number is required for recipient_type='phone'"}- if recipient_type == 'group' and not parameters['group_id']:- return {"error": "Group ID is required for recipient_type='group'"}- if recipient_type == 'channel' and not parameters['channel_jid']:- return {"error": "Channel JID is required for recipient_type='channel'"}- if recipient_type == 'channel' and message_type not in ('text', 'image', 'video', 'audio', 'document'):- return {"error": f"Channels only support: text, image, video, audio, document. Got: {message_type}"}- if message_type == 'text' and not parameters['message']:- return {"error": "Message content is required for message_type='text'"}- if message_type in ('image', 'video', 'audio', 'document', 'sticker') and not parameters['media_url']:- return {"error": f"media_url is required for message_type='{message_type}'"}- if message_type == 'location' and (parameters['latitude'] is None or parameters['longitude'] is None):- return {"error": "latitude and longitude are required for message_type='location'"}- if message_type == 'contact' and not parameters['vcard']:- return {"error": "vcard is required for message_type='contact'"}-- if recipient_type == 'channel':- recipient = parameters['channel_jid']- elif recipient_type == 'phone':- recipient = parameters['phone']- else:- recipient = parameters['group_id']- logger.info(f"[WhatsApp Tool] Sending {message_type} to {recipient[:15]}...")-- try:- result = await handle_whatsapp_send(- node_id="tool_whatsapp_send",- node_type="whatsappSend",- parameters=parameters,- context={}- )-- if result.get('success'):- return {- "success": True,- "recipient": recipient,- "recipient_type": recipient_type,- "message_type": message_type,- "details": result.get('result', {})- }- else:- return {"error": result.get('error', 'Unknown error')}-- except Exception as e:- logger.error(f"[WhatsApp Tool] Error: {e}")- return {"error": f"WhatsApp send failed: {str(e)}"}---async def _execute_whatsapp_db(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Query WhatsApp database - contacts, groups, messages.-- Supports 13 operations:- - chat_history: Retrieve messages from a chat- - search_groups: Search groups by name- - get_group_info: Get group details with participant names- - get_contact_info: Get full contact info (for send/reply)- - list_contacts: List contacts with saved names- - check_contacts: Check WhatsApp registration status- - list_channels: List subscribed newsletter channels- - get_channel_info: Get channel details- - channel_messages: Get channel message history- - channel_stats: Get channel subscriber/view stats- - channel_follow: Follow/subscribe to a channel- - channel_unfollow: Unfollow/unsubscribe from a channel- - channel_create: Create a new newsletter channel-- Args:- args: LLM-provided arguments matching WhatsAppDbSchema (snake_case)- node_params: Node parameters (used as fallback)-- Returns:- Dict with operation-specific results- """- from services.handlers.whatsapp import handle_whatsapp_db-- operation = args.get('operation', 'chat_history')- logger.info(f"[WhatsApp DB Tool] Executing operation: {operation}")-- # Build parameters for handler (snake_case matching frontend nodes)- parameters = {'operation': operation}-- if operation == 'chat_history':- parameters.update({- 'chat_type': args.get('chat_type', 'individual'),- 'phone': args.get('phone', ''),- 'group_id': args.get('group_id', ''),- 'message_filter': args.get('message_filter', 'all'),- 'group_filter': args.get('group_filter', 'all'),- 'sender_phone': args.get('sender_phone', ''),- 'limit': args.get('limit', 50),- 'offset': args.get('offset', 0),- })- if args.get('include_media_data'):- parameters['include_media_data'] = True- # Validate required fields- chat_type = parameters['chat_type']- if chat_type == 'individual' and not parameters['phone']:- return {"error": "Phone number is required for chat_type='individual'"}- if chat_type == 'group' and not parameters['group_id']:- return {"error": "Group ID is required for chat_type='group'"}-- elif operation == 'search_groups':- parameters['query'] = args.get('query', '')- parameters['limit'] = min(args.get('limit', 20), 50) # Cap at 50 to prevent overflow-- elif operation == 'get_group_info':- group_id = args.get('group_id', '')- if not group_id:- return {"error": "group_id is required for get_group_info"}- parameters['group_id_for_info'] = group_id- parameters['participant_limit'] = min(args.get('participant_limit', 50), 100) # Cap at 100-- elif operation == 'get_contact_info':- phone = args.get('phone', '')- if not phone:- return {"error": "phone is required for get_contact_info"}- parameters['contact_phone'] = phone-- elif operation == 'list_contacts':- parameters['query'] = args.get('query', '')- parameters['limit'] = min(args.get('limit', 50), 100) # Cap at 100 to prevent overflow-- elif operation == 'check_contacts':- phones = args.get('phones', '')- if not phones:- return {"error": "phones (comma-separated) is required for check_contacts"}- parameters['phones'] = phones-- elif operation == 'list_channels':- if args.get('refresh'):- parameters['refresh'] = True- parameters['limit'] = min(args.get('limit', 20), 50)-- elif operation == 'get_channel_info':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for get_channel_info"}- parameters['channel_jid'] = channel_jid- if args.get('refresh'):- parameters['refresh'] = True-- elif operation == 'channel_messages':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for channel_messages"}- parameters['channel_jid'] = channel_jid- parameters['channel_count'] = min(args.get('channel_count', 20), 100)- if args.get('before_server_id'):- parameters['before_server_id'] = args['before_server_id']- if args.get('message_offset'):- parameters['message_offset'] = args['message_offset']- if args.get('since'):- parameters['since'] = args['since']- if args.get('until'):- parameters['until'] = args['until']- if args.get('media_type'):- parameters['media_type'] = args['media_type']- if args.get('search'):- parameters['search'] = args['search']- if args.get('refresh'):- parameters['refresh'] = True- if args.get('include_media_data'):- parameters['include_media_data'] = True-- elif operation == 'channel_stats':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for channel_stats"}- parameters['channel_jid'] = channel_jid- parameters['channel_count'] = min(args.get('channel_count', 10), 100)-- elif operation == 'channel_follow':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for channel_follow"}- parameters['channel_jid'] = channel_jid-- elif operation == 'channel_unfollow':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for channel_unfollow"}- parameters['channel_jid'] = channel_jid-- elif operation == 'channel_create':- channel_name = args.get('channel_name', '')- if not channel_name:- return {"error": "channel_name is required for channel_create"}- parameters['channel_name'] = channel_name- if args.get('channel_description'):- parameters['channel_description'] = args['channel_description']-- elif operation == 'channel_mute':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for channel_mute"}- parameters['channel_jid'] = channel_jid- parameters['mute'] = args.get('mute', True)-- elif operation == 'channel_mark_viewed':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for channel_mark_viewed"}- parameters['channel_jid'] = channel_jid- server_ids = args.get('server_ids', '')- if not server_ids:- return {"error": "server_ids is required for channel_mark_viewed"}- parameters['server_ids'] = server_ids-- elif operation == 'newsletter_react':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for newsletter_react"}- parameters['channel_jid'] = channel_jid- react_server_id = args.get('react_server_id')- if not react_server_id:- return {"error": "react_server_id is required for newsletter_react"}- parameters['react_server_id'] = react_server_id- parameters['reaction'] = args.get('reaction', '')-- elif operation == 'newsletter_live_updates':- channel_jid = args.get('channel_jid', '')- if not channel_jid:- return {"error": "channel_jid is required for newsletter_live_updates"}- parameters['channel_jid'] = channel_jid- server_ids = args.get('server_ids', '')- if not server_ids:- return {"error": "server_ids is required for newsletter_live_updates"}- parameters['server_ids'] = server_ids-- elif operation == 'contact_profile_pic':- profile_pic_jid = args.get('profile_pic_jid', '') or args.get('phone', '')- if not profile_pic_jid:- return {"error": "profile_pic_jid or phone is required for contact_profile_pic"}- parameters['profile_pic_jid'] = profile_pic_jid- if args.get('preview'):- parameters['preview'] = True-- else:- return {"error": f"Unknown operation: {operation}"}-- try:- result = await handle_whatsapp_db(- node_id="tool_whatsapp_db",- node_type="whatsappDb",- parameters=parameters,- context={}- )-- if result.get('success'):- # Return the result section for LLM consumption- return {- "success": True,- "operation": operation,- **result.get('result', {})- }- else:- return {"error": result.get('error', 'Unknown error')}-- except Exception as e:- logger.error(f"[WhatsApp DB Tool] Error: {e}")- return {"error": f"WhatsApp DB operation failed: {str(e)}"}+# Wave 11.D.9: _execute_whatsapp_{send,db} deleted. WhatsApp tool execution+# now routes through the plugin fast-path (nodes/whatsapp/*.py).async def _execute_android_toolkit(args: Dict[str, Any],