Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: Telegram senderFilter, WhatsApp media download, auto-reconnect, bump to v0.0.42
trohitg22f3fe6f0b4b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8f8dc1c4..dc08175a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -375,14 +375,14 @@ class CacheEntry(SQLModel, table=True):## Codebase Summary- **Hybrid architecture**: Node.js + Python + React TypeScript- **93 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 13 specialized agents + 1 skill + 4 dedicated tools + 3 search + 16 Android + 3 WhatsApp + 4 Twitter + 2 Telegram + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 2 Workflow + 7 Google Workspace + 1 Apify + 1 Crawlee + 3 Proxy)-- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (120 message handlers)+- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (125 message handlers)- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated## Architecture RefactoringThe project was completely refactored from schema-based node definitions to explicit INodeProperties interface system inspired by n8n architecture. Key changes:- **Pure INodeProperties System**: Removed all backward compatibility layers-- **92 Implemented Node Components**: AI models, agents, skills, location services, Android automation, WhatsApp, Twitter/X, Telegram, social, code execution, HTTP/Webhook utilities, document processing, chat, schedulers, search, and proxy-- **WebSocket-First Communication**: 119 WebSocket message handlers replace most REST API calls+- **93 Implemented Node Components**: AI models, agents, skills, location services, Android automation, WhatsApp, Twitter/X, Telegram, social, code execution, HTTP/Webhook utilities, document processing, chat, schedulers, search, and proxy+- **WebSocket-First Communication**: 125 WebSocket message handlers replace most REST API calls- **Resource-Operation Pattern**: Organized by functional categories (AI, Location, Android, WhatsApp)- **TypeScript-First**: Full type safety with proper interface alignment- **Code Cleanup**: Removed dead code, unused files, and legacy methods@@ -530,7 +530,7 @@ React Flow edges use dynamic Dracula colors via `getEdgeStyles(theme.dracula)`:### WebSocket-First ArchitectureThe project uses WebSocket as the primary communication method between frontend and backend, replacing most REST API calls:- `src/contexts/WebSocketContext.tsx` - Central WebSocket context with request/response pattern-- `server/routers/websocket.py` - WebSocket endpoint with 120 message handlers+- `server/routers/websocket.py` - WebSocket endpoint with 125 message handlers- `server/services/status_broadcaster.py` - Connection management and broadcasting## Implemented Node Types@@ -904,8 +904,8 @@ Android device connection is configured via the Credentials Modal (Android panel### WhatsApp Nodes (3 nodes)- **whatsappSend**: **Dual-purpose node** - Send WhatsApp messages (text, image, video, audio, document, sticker, location, contact) to contacts, groups, or newsletter channels. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Recipient types: Self (connected phone), Phone Number, Group, Channel (newsletter). Channel messages only support text, image, video, audio, document (NOT sticker, location, contact). Full parameter schema for message type, media URL, location coordinates, contact vCard, channel JID.-- **whatsappDb**: **Dual-purpose node** - Comprehensive WhatsApp database query node with 13 operations. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Operations:- - `chat_history`: Retrieve messages from individual or group chats with filtering and pagination+- **whatsappDb**: **Dual-purpose node** - Comprehensive WhatsApp database query node with 18 operations. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Operations:+ - `chat_history`: Retrieve messages from individual or group chats with filtering, pagination, and optional media download- `search_groups`: Search groups by name- `get_group_info`: Get group details with participant names and phone numbers- `get_contact_info`: Get full contact info (name, phone, profile picture) for sending/replying@@ -913,11 +913,16 @@ Android device connection is configured via the Credentials Modal (Android panel- `check_contacts`: Check WhatsApp registration status for phone numbers- `list_channels`: List subscribed newsletter channels with optional server refresh- `get_channel_info`: Get channel details (name, description, subscribers)- - `channel_messages`: Get channel message history with pagination+ - `channel_messages`: Get channel message history with pagination, date range, media type filter, text search, and optional media download- `channel_stats`: Get channel subscriber/view statistics- `channel_follow`: Follow/subscribe to a newsletter channel- `channel_unfollow`: Unfollow/unsubscribe from a newsletter channel- - `channel_create`: Create a new newsletter channel+ - `channel_create`: Create a new newsletter channel (with optional picture)+ - `channel_mute`: Mute/unmute a newsletter channel+ - `channel_mark_viewed`: Mark channel messages as viewed+ - `newsletter_react`: React to a channel message with an emoji+ - `newsletter_live_updates`: Subscribe to live view/reaction counts for channel messages+ - `contact_profile_pic`: Get profile picture for a contact or group- **whatsappReceive**: Event-driven trigger that waits for incoming WhatsApp messages with filters (message type, sender, group, channel, keywords, forwarded status). Marked with `['whatsapp', 'trigger']` group for n8n-style trigger identification. Stores group/sender names alongside JID/phone for display persistence. The Go RPC resolves LIDs to phone numbers before sending events - `sender_phone` field is already resolved. Filter options: All Messages, From Self (notes to self chat only), From Any Contact (Non-Group), From Specific Contact, From Specific Group, From Channel (Newsletter), Contains Keywords### Social Nodes (2 nodes)@@ -996,8 +1001,8 @@ TWITTER_CLIENT_SECRET=your_client_secret### Telegram Nodes (2 nodes)Telegram bot integration using `python-telegram-bot` SDK with long-polling for incoming messages.-- **telegramSend**: **Dual-purpose node** - Send text, photo, document, location, or contact messages via Telegram bot. Works as workflow node OR AI Agent tool. Group: `['social', 'tool']`. Recipient types: Self (bot owner), User/Chat ID, Group. Parameters: recipient_type, chat_id, message_type, text, media_url, caption, parse_mode, silent, reply_to_message_id.-- **telegramReceive**: Event-driven trigger that waits for incoming Telegram messages. Group: `['social', 'trigger']`. Filters: chat type (all/private/group/supergroup/channel), content type (text/photo/video/audio/document/sticker/location/contact/poll), chat ID, user ID, keywords. Option to ignore bot messages.+- **telegramSend**: **Dual-purpose node** - Send text, photo, document, location, or contact messages via Telegram bot. Works as workflow node OR AI Agent tool. Group: `['social', 'tool']`. Recipient types: Self (bot owner), User/Chat ID, Group. Parameters: recipient_type, chat_id, message_type, text, media_url, caption, parse_mode, silent, reply_to_message_id. MarkdownV2/Markdown text auto-escaped via `_escape_text()`; falls back to plain text on `BadRequest`. "Self" restores `owner_chat_id` from credentials DB if not in memory.+- **telegramReceive**: Event-driven trigger that waits for incoming Telegram messages. Group: `['social', 'trigger']`. Uses `senderFilter` dropdown: All Messages, From Self (Bot Owner) (zero-config), Private/Group/Supergroup/Channel Only, Specific Chat, Specific User, Keywords. Content type filter and ignore bots option. "From Self" uses lazy `_get_owner_chat_id()` lookup at match time. Auto-reconnects on server restart via `StatusBroadcaster._refresh_telegram_status()`.**Key Files:**| File | Description |@@ -1007,7 +1012,7 @@ Telegram bot integration using `python-telegram-bot` SDK with long-polling for i| `client/src/nodeDefinitions/telegramNodes.ts` | 2 node definitions || `client/src/components/CredentialsModal.tsx` | Telegram bot token panel |-**Authentication:** Bot token from @BotFather on Telegram. Stored via `auth_service.get_api_key('telegram_bot_token')`.+**Authentication:** Bot token from @BotFather on Telegram. Stored via `auth_service.store_api_key('telegram_bot_token', token, models=[])`. Owner auto-captured on first private message, persisted as `telegram_owner_chat_id`. Credentials panel: Save (store only), Connect (store + connect), Reconnect. All credential access uses `from core.container import container; container.auth_service()` (NOT `from services.auth import get_auth_service`).**Environment Variables:**```bash@@ -1382,7 +1387,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.## Current Status✅ **INodeProperties System**: Fully implemented with 93 functional node components-✅ **WebSocket-First Architecture**: 120 message handlers replacing REST APIs+✅ **WebSocket-First Architecture**: 125 message handlers replacing REST APIs✅ **Code Editor**: Python, JavaScript, and TypeScript executors with syntax-highlighted editor (react-simple-code-editor + prismjs) and console output✅ **Node.js Executor**: Persistent Node.js server (Express + tsx) for fast JS/TS execution, replacing subprocess spawning✅ **Component Palette**: Emoji icons with distinct dracula-themed category colors, localStorage persistence for collapsed sections@@ -1394,7 +1399,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.✅ **Location Services**: Interactive map picker with coordinate handling, Google Maps API key fetched from backend credentials✅ **Code Cleanup**: Dead code removed, unused files deleted✅ **Process Management**: Robust stop scripts with duplicate process detection-✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, newsletter channel support (send, query, follow/unfollow, create), and proper error handling+✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, newsletter channel support (send, query, follow/unfollow, create, mute, mark viewed, react, live updates), media download, profile pics, and proper error handling✅ **Backend Stability**: Fixed dependency injection and error handling preventing crashes✅ **Development Server**: Running at **http://localhost:3001** (frontend) and **http://localhost:3010** (backend)✅ **WebSocket Integration**: Persistent WebSocket connections for remote Android devices with background tasks and message queue@@ -4128,7 +4133,7 @@ export interface AndroidStatus {## WhatsApp Integration### Overview-WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp RPC service (default port 9400, configurable via `WHATSAPP_RPC_PORT` env var or `--port` CLI flag). Supports individual chats, groups, and newsletter channels (sending, querying, follow/unfollow, create).+WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp RPC service (default port 9400, configurable via `WHATSAPP_RPC_PORT` env var or `--port` CLI flag). Supports individual chats, groups, and newsletter channels (sending, querying, follow/unfollow, create, mute, mark viewed, react, live updates, media download, profile pics). All 14 WhatsApp events handled.### Architecture```@@ -4325,7 +4330,8 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {'webhookTrigger': TriggerConfig('webhookTrigger', 'webhook_received', 'Webhook Request'),'chatTrigger': TriggerConfig('chatTrigger', 'chat_message_received', 'Chat Message'),'taskTrigger': TriggerConfig('taskTrigger', 'task_completed', 'Task Completed'),- # Future: 'emailTrigger', 'mqttTrigger', 'telegramTrigger', etc.+ 'telegramReceive': TriggerConfig('telegramReceive', 'telegram_message_received', 'Telegram Message'),+ # Future: 'emailTrigger', 'mqttTrigger', etc.}@dataclass@@ -4739,7 +4745,7 @@ def has_real_android_devices(self) -> bool:Updated `client_left` and presence handlers use `has_real_android_devices()` instead of checking total device count.-### WebSocket Message Types (119 Handlers)+### WebSocket Message Types (125 Handlers)#### Request/Response Messages (Client -> Server -> Client)| Category | Message Types |@@ -4760,7 +4766,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins| **Android** | `get_android_devices`, `execute_android_action`, `android_relay_connect`, `android_relay_disconnect`, `android_relay_reconnect` || **Maps** | `validate_maps_key` || **Apify** | `validate_apify_key` |-| **WhatsApp** | `whatsapp_status`, `whatsapp_connected_phone`, `whatsapp_qr`, `whatsapp_send`, `whatsapp_start`, `whatsapp_restart`, `whatsapp_groups`, `whatsapp_group_info`, `whatsapp_chat_history`, `whatsapp_newsletters`, `whatsapp_rate_limit_get`, `whatsapp_rate_limit_set`, `whatsapp_rate_limit_stats`, `whatsapp_rate_limit_unpause` |+| **WhatsApp** | `whatsapp_status`, `whatsapp_connected_phone`, `whatsapp_qr`, `whatsapp_send`, `whatsapp_start`, `whatsapp_restart`, `whatsapp_groups`, `whatsapp_group_info`, `whatsapp_chat_history`, `whatsapp_newsletters`, `whatsapp_rate_limit_get`, `whatsapp_rate_limit_set`, `whatsapp_rate_limit_stats`, `whatsapp_rate_limit_unpause`, `whatsapp_mark_read`, `whatsapp_typing`, `whatsapp_presence`, `whatsapp_stop`, `whatsapp_diagnostics` || **Telegram** | `telegram_connect`, `telegram_disconnect`, `telegram_status`, `telegram_send`, `telegram_reconnect`, `telegram_get_me`, `telegram_get_chat` || **Workflow Storage** | `save_workflow`, `get_workflow`, `get_all_workflows`, `delete_workflow` || **Chat Messages** | `send_chat_message`, `get_chat_messages`, `clear_chat_messages`, `save_chat_message`, `get_chat_sessions` |@@ -4930,7 +4936,7 @@ This function:- **Performance**: Fast HMR updates and clean TypeScript compilation- **AI Architecture**: 5-layer system with factory pattern and secure credential management- **Android Architecture**: Factory-based node creation with ADB integration for device automation-- **WebSocket-First Architecture**: 120 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations+- **WebSocket-First Architecture**: 125 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations- **WebSocket Hooks**: Dedicated React hooks (useWhatsApp, useExecution, useApiKeys, useAndroidOperations, useParameterPanel) for clean component integration- **WebSocket Support**: Persistent remote Android device connections via WebSocket proxy with background tasks- Connection stays alive across multiple API requests until switched to local ADB@@ -4961,10 +4967,13 @@ This function:- WebSocket handlers for status, QR code, send message, and start connection- useWhatsApp hook provides clean React component integration- Uses external npm package `whatsapp-rpc` with pre-built Go binaries- - Newsletter channels: send to channels (text/image/video/audio/document), query channel DB (list, info, messages, stats), follow/unfollow, create. Channel JID format: `<numeric_id>@newsletter`. Channel events dispatched via `event.newsletter_*` handlers.+ - Newsletter channels: send to channels (text/image/video/audio/document), query channel DB (list, info, messages, stats), follow/unfollow, create, mute, mark viewed, react, live updates. Channel JID format: `<numeric_id>@newsletter`. All 14 WhatsApp events handled (including `event.history_sync_complete`).+ - Media download: `include_media_data` param on chat_history and channel_messages triggers `media` RPC for base64 media retrieval+ - Channel message filters: date range (since/until), media type, text search, pagination offset+ - WebSocket RPC passthroughs: mark_read, typing, presence, stop, diagnostics- **Event-Driven Triggers**: Generic trigger node architecture with asyncio.Future- `server/services/event_waiter.py` - Waiter registration, dispatch, cancellation- - TRIGGER_REGISTRY for extensible trigger types (WhatsApp, Webhook, future: Email, MQTT, Telegram)+ - TRIGGER_REGISTRY for extensible trigger types (WhatsApp, Webhook, Telegram, future: Email, MQTT)- Filter builders create closures from node parameters (whatsapp_filter, webhook_filter)- No timeout - wait indefinitely until event or user cancel- WebSocket handlers: `cancel_event_wait`, `get_active_waiters`diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsxindex 227b00b7..492053a6 100644--- a/client/src/components/CredentialsModal.tsx+++ b/client/src/components/CredentialsModal.tsx@@ -814,6 +814,23 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,}};+ const handleTelegramSave = async () => {+ if (!telegramToken.trim()) {+ setTelegramError('Bot token is required');+ return;+ }+ setTelegramLoading('save');+ setTelegramError(null);+ try {+ await saveApiKey('telegram_bot_token', telegramToken.trim());+ setTelegramTokenStored(true);+ } catch (err: any) {+ setTelegramError(err.message || 'Failed to save token');+ } finally {+ setTelegramLoading(null);+ }+ };+const handleTelegramRefreshStatus = async () => {setTelegramLoading('refresh');setTelegramError(null);@@ -1940,7 +1957,7 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,<ButtononClick={handleTelegramConnect}loading={telegramLoading === 'connect'}- disabled={!telegramToken.trim() && !telegramTokenStored}+ disabled={!telegramToken.trim()}style={{backgroundColor: `${theme.dracula.green}25`,borderColor: `${theme.dracula.green}60`,@@ -1949,6 +1966,19 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,>Connect</Button>+ {telegramToken.trim() && (+ <Button+ onClick={handleTelegramSave}+ loading={telegramLoading === 'save'}+ style={{+ backgroundColor: `${theme.dracula.yellow}25`,+ borderColor: `${theme.dracula.yellow}60`,+ color: theme.dracula.yellow,+ }}+ >+ Save+ </Button>+ )}{telegramTokenStored && (<ButtononClick={handleTelegramReconnect}diff --git a/client/src/components/onboarding/OnboardingWizard.tsx b/client/src/components/onboarding/OnboardingWizard.tsxindex 359c6737..2f09fd20 100644--- a/client/src/components/onboarding/OnboardingWizard.tsx+++ b/client/src/components/onboarding/OnboardingWizard.tsx@@ -57,8 +57,8 @@ const OnboardingWizard: React.FC<OnboardingWizardProps> = ({ onOpenCredentials,isOpen={isVisible}onClose={skip}title="Welcome Guide"- maxWidth="580px"- maxHeight="70vh"+ maxWidth="95vw"+ maxHeight="95vh"autoHeight><div style={{@@ -77,8 +77,8 @@ const OnboardingWizard: React.FC<OnboardingWizardProps> = ({ onOpenCredentials,{/* Step content */}<div style={{overflowY: 'auto',- minHeight: 340,- maxHeight: 'calc(70vh - 200px)',+ minHeight: 500,+ maxHeight: 'calc(95vh - 200px)',paddingRight: 4,}}>{renderStep()}diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex 69afce91..35c07d86 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -255,6 +255,44 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =server_ids: 'string',status: 'string'},+ telegram: {+ message_id: 'number',+ chat_id: 'number',+ chat_type: 'string',+ chat_title: 'string',+ from_id: 'number',+ from_username: 'string',+ from_first_name: 'string',+ from_last_name: 'string',+ is_bot: 'boolean',+ text: 'string',+ content_type: 'string',+ date: 'string',+ reply_to_message_id: 'number',+ photo: {+ file_id: 'string',+ file_unique_id: 'string',+ width: 'number',+ height: 'number',+ file_size: 'number'+ },+ document: {+ file_id: 'string',+ file_name: 'string',+ mime_type: 'string',+ file_size: 'number'+ },+ location: {+ latitude: 'number',+ longitude: 'number'+ },+ contact: {+ phone_number: 'string',+ first_name: 'string',+ last_name: 'string',+ user_id: 'number'+ }+ },webhook: {method: 'string',path: 'string',@@ -704,6 +742,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const isCronScheduler = nodeType === 'cronScheduler';const isChatTrigger = nodeType === 'chatTrigger';const isTaskTrigger = nodeType === 'taskTrigger';+ const isTelegramReceive = nodeType === 'telegramReceive';const isSocialReceive = nodeType === 'socialReceive';const isSocialSend = nodeType === 'socialSend';const isSearchNode = nodeType === 'braveSearch' || nodeType === 'serperSearch' || nodeType === 'perplexitySearch';@@ -765,6 +804,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =isCronScheduler ? sampleSchemas.cronScheduler :isChatTrigger ? sampleSchemas.chatTrigger :isTaskTrigger ? sampleSchemas.taskTrigger :+ isTelegramReceive ? sampleSchemas.telegram :isSocialReceive ? sampleSchemas.social :isSocialSend ? sampleSchemas.socialSend :isApify ? sampleSchemas.apify :diff --git a/client/src/nodeDefinitions/telegramNodes.ts b/client/src/nodeDefinitions/telegramNodes.tsindex fedfdf5d..98a37b12 100644--- a/client/src/nodeDefinitions/telegramNodes.ts+++ b/client/src/nodeDefinitions/telegramNodes.ts@@ -247,22 +247,6 @@ export const telegramNodes: Record<string, INodeTypeDescription> = {description: 'Received message data (message_id, chat_id, chat_type, from_id, from_username, text, content_type, date)'}],properties: [- // ===== CHAT TYPE FILTER =====- {- displayName: 'Chat Type',- name: 'chatTypeFilter',- type: 'options',- options: [- { name: 'All Types', value: 'all' },- { name: 'Private Only', value: 'private' },- { name: 'Group Only', value: 'group' },- { name: 'Supergroup Only', value: 'supergroup' },- { name: 'Channel Only', value: 'channel' }- ],- default: 'all',- description: 'Filter by chat type'- },-// ===== CONTENT TYPE FILTER ====={displayName: 'Content Type',@@ -285,30 +269,62 @@ export const telegramNodes: Record<string, INodeTypeDescription> = {description: 'Filter by message content type'},- // ===== SPECIFIC FILTERS =====+ // ===== SENDER FILTER (WhatsApp-style dropdown) ====={- displayName: 'Chat ID Filter',+ displayName: 'Sender Filter',+ name: 'senderFilter',+ type: 'options',+ options: [+ { name: 'All Messages', value: 'all' },+ { name: 'From Self (Bot Owner)', value: 'self' },+ { name: 'Private Chats Only', value: 'private' },+ { name: 'Groups Only', value: 'group' },+ { name: 'Supergroups Only', value: 'supergroup' },+ { name: 'Channels Only', value: 'channel' },+ { name: 'From Specific Chat', value: 'specific_chat' },+ { name: 'From Specific User', value: 'specific_user' },+ { name: 'Contains Keywords', value: 'keywords' }+ ],+ default: 'all',+ description: 'Filter which messages trigger the workflow'+ },++ // ===== CONDITIONAL FIELDS =====+ {+ displayName: 'Chat ID',name: 'chat_id',type: 'string',default: '',+ required: true,placeholder: '123456789',- description: 'Only trigger for messages from this specific chat (leave empty for all chats)'+ description: 'Only trigger for messages from this specific chat ID',+ displayOptions: {+ show: { senderFilter: ['specific_chat'] }+ }},{- displayName: 'From User ID Filter',+ displayName: 'User ID',name: 'from_user',type: 'string',default: '',+ required: true,placeholder: '987654321',- description: 'Only trigger for messages from this specific user ID (leave empty for all users)'+ description: 'Only trigger for messages from this specific user ID',+ displayOptions: {+ show: { senderFilter: ['specific_user'] }+ }},{displayName: 'Keywords',name: 'keywords',type: 'string',default: '',+ required: true,placeholder: 'help, support, info',- description: 'Comma-separated keywords to trigger on (case-insensitive, leave empty to trigger on all)'+ description: 'Comma-separated keywords to trigger on (case-insensitive)',+ displayOptions: {+ show: { senderFilter: ['keywords'] }+ }},// ===== OPTIONS =====@@ -317,7 +333,10 @@ export const telegramNodes: Record<string, INodeTypeDescription> = {name: 'ignoreBots',type: 'boolean',default: true,- description: 'Do not trigger on messages from other bots'+ description: 'Do not trigger on messages from other bots',+ displayOptions: {+ show: { senderFilter: ['all', 'private', 'group', 'supergroup', 'channel', 'specific_chat', 'specific_user', 'keywords'] }+ }}]}diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.tsindex ee2bf01c..0de2a78e 100644--- a/client/src/nodeDefinitions/whatsappNodes.ts+++ b/client/src/nodeDefinitions/whatsappNodes.ts@@ -685,7 +685,10 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {{ name: 'Unfollow Channel', value: 'channel_unfollow' },{ name: 'Create Channel', value: 'channel_create' },{ name: 'Mute/Unmute Channel', value: 'channel_mute' },- { name: 'Mark Channel Viewed', value: 'channel_mark_viewed' }+ { name: 'Mark Channel Viewed', value: 'channel_mark_viewed' },+ { name: 'React to Channel Message', value: 'newsletter_react' },+ { name: 'Channel Live Updates', value: 'newsletter_live_updates' },+ { name: 'Contact Profile Picture', value: 'contact_profile_pic' }],default: 'chat_history',description: 'Operation to perform'@@ -792,6 +795,18 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {}},+ // ===== MEDIA DOWNLOAD =====+ {+ displayName: 'Include Media Data',+ name: 'include_media_data',+ type: 'boolean',+ default: false,+ description: 'Download base64 media data for image/video/audio/document/sticker messages. May be slow for many messages.',+ displayOptions: {+ show: { operation: ['chat_history', 'channel_messages'] }+ }+ },+// ===== SEARCH GROUPS PARAMETERS ====={displayName: 'Search Query',@@ -857,7 +872,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: '120363198765432101@newsletter or https://whatsapp.com/channel/...',description: 'Newsletter JID or invite link (use Load button to select)',displayOptions: {- show: { operation: ['get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_mute', 'channel_mark_viewed'] }+ show: { operation: ['get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_mute', 'channel_mark_viewed', 'newsletter_react', 'newsletter_live_updates'] }}},{@@ -867,7 +882,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {default: false,description: 'Bypass 24h cache and fetch fresh data from WhatsApp servers',displayOptions: {- show: { operation: ['list_channels', 'get_channel_info'] }+ show: { operation: ['list_channels', 'get_channel_info', 'channel_messages'] }}},{@@ -892,6 +907,68 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {show: { operation: ['channel_messages'] }}},+ {+ displayName: 'Offset',+ name: 'message_offset',+ type: 'number',+ default: 0,+ typeOptions: { minValue: 0 },+ description: 'Pagination offset - skip this many messages',+ displayOptions: {+ show: { operation: ['channel_messages'] }+ }+ },+ {+ displayName: 'Since (Unix Timestamp)',+ name: 'since',+ type: 'string',+ default: '',+ placeholder: '1704067200',+ description: 'Only return messages after this Unix timestamp',+ displayOptions: {+ show: { operation: ['channel_messages'] }+ }+ },+ {+ displayName: 'Until (Unix Timestamp)',+ name: 'until',+ type: 'string',+ default: '',+ placeholder: '1706745600',+ description: 'Only return messages before this Unix timestamp',+ displayOptions: {+ show: { operation: ['channel_messages'] }+ }+ },+ {+ displayName: 'Media Type Filter',+ name: 'media_type',+ type: 'options',+ options: [+ { name: 'All Types', value: 'all' },+ { name: 'Image', value: 'image' },+ { name: 'Video', value: 'video' },+ { name: 'Audio', value: 'audio' },+ { name: 'Document', value: 'document' },+ { name: 'Sticker', value: 'sticker' }+ ],+ default: 'all',+ description: 'Filter messages by media type',+ displayOptions: {+ show: { operation: ['channel_messages'] }+ }+ },+ {+ displayName: 'Search Text',+ name: 'search',+ type: 'string',+ default: '',+ placeholder: 'keyword...',+ description: 'Search for messages containing this text',+ displayOptions: {+ show: { operation: ['channel_messages'] }+ }+ },{displayName: 'Channel Name',name: 'channel_name',@@ -932,9 +1009,70 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {type: 'string',default: '',placeholder: '100, 101, 102',- description: 'Comma-separated message server IDs to mark as viewed',+ description: 'Comma-separated message server IDs',+ displayOptions: {+ show: { operation: ['channel_mark_viewed', 'newsletter_live_updates'] }+ }+ },++ // ===== NEWSLETTER REACT PARAMETERS =====+ {+ displayName: 'Message Server ID',+ name: 'react_server_id',+ type: 'number',+ default: 0,+ typeOptions: { minValue: 0 },+ description: 'Server ID of the message to react to',+ displayOptions: {+ show: { operation: ['newsletter_react'] }+ }+ },+ {+ displayName: 'Reaction',+ name: 'reaction',+ type: 'string',+ default: '',+ placeholder: '\ud83d\udc4d',+ description: 'Reaction emoji (empty to remove reaction)',+ displayOptions: {+ show: { operation: ['newsletter_react'] }+ }+ },++ // ===== CHANNEL CREATE - PICTURE =====+ {+ displayName: 'Channel Picture (Base64)',+ name: 'picture',+ type: 'string',+ default: '',+ typeOptions: { rows: 3 },+ placeholder: 'base64 encoded image...',+ description: 'Optional base64-encoded profile picture for the new channel',+ displayOptions: {+ show: { operation: ['channel_create'] }+ }+ },++ // ===== CONTACT PROFILE PICTURE PARAMETERS =====+ {+ displayName: 'JID or Phone',+ name: 'profile_pic_jid',+ type: 'string',+ default: '',+ placeholder: '1234567890 or [email protected]',+ description: 'Contact JID or phone number to get profile picture for',+ displayOptions: {+ show: { operation: ['contact_profile_pic'] }+ }+ },+ {+ displayName: 'Preview (Low Res)',+ name: 'preview',+ type: 'boolean',+ default: false,+ description: 'Get low-resolution preview instead of full picture',displayOptions: {- show: { operation: ['channel_mark_viewed'] }+ show: { operation: ['contact_profile_pic'] }}}diff --git a/package-lock.json b/package-lock.jsonindex c16121d6..83a188d5 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "machinaos",- "version": "0.0.38",+ "version": "0.0.41","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "machinaos",- "version": "0.0.38",+ "version": "0.0.41","hasInstallScript": true,"license": "MIT","workspaces": [diff --git a/package.json b/package.jsonindex bcf13a91..7ef09811 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "machinaos",- "version": "0.0.41",+ "version": "0.0.42","description": "Open source workflow automation platform with AI agents, React Flow, and n8n-inspired architecture","type": "module","keywords": [diff --git a/server/config/model_registry.json b/server/config/model_registry.jsonindex 85c46f52..c5180c93 100644--- a/server/config/model_registry.json+++ b/server/config/model_registry.json@@ -1,8 +1,69 @@{- "_generated": "2026-03-02T05:51:12.590903+00:00",+ "_generated": "2026-03-04T13:29:06.065648+00:00","_source": "openrouter",- "_model_count": 342,+ "_model_count": 343,"models": {+ "openai/gpt-5.3-chat": {+ "id": "openai/gpt-5.3-chat",+ "name": "OpenAI: GPT-5.3 Chat",+ "provider": "openai",+ "local_id": "gpt-5.3-chat",+ "context_length": 128000,+ "max_output_tokens": 16384,+ "input_price_per_mtok": 1.75,+ "output_price_per_mtok": 14.0,+ "supports_thinking": true,+ "thinking_type": "effort",+ "temperature_range": [+ 0.0,+ 2.0+ ],+ "is_reasoning_model": false,+ "supported_parameters": [+ "frequency_penalty",+ "logit_bias",+ "logprobs",+ "max_tokens",+ "presence_penalty",+ "response_format",+ "seed",+ "stop",+ "structured_outputs",+ "tool_choice",+ "tools",+ "top_logprobs"+ ]+ },+ "gemini/gemini-3.1-flash-lite-preview": {+ "id": "google/gemini-3.1-flash-lite-preview",+ "name": "Google: Gemini 3.1 Flash Lite Preview",+ "provider": "gemini",+ "local_id": "gemini-3.1-flash-lite-preview",+ "context_length": 1048576,+ "max_output_tokens": 65536,+ "input_price_per_mtok": 0.25,+ "output_price_per_mtok": 1.5,+ "supports_thinking": true,+ "thinking_type": "budget",+ "temperature_range": [+ 0.0,+ 2.0+ ],+ "is_reasoning_model": false,+ "supported_parameters": [+ "include_reasoning",+ "max_tokens",+ "reasoning",+ "response_format",+ "seed",+ "stop",+ "structured_outputs",+ "temperature",+ "tool_choice",+ "tools",+ "top_p"+ ]+ },"bytedance-seed/seed-2.0-mini": {"id": "bytedance-seed/seed-2.0-mini","name": "ByteDance Seed: Seed-2.0-Mini",@@ -40,8 +101,8 @@"local_id": "gemini-3.1-flash-image-preview","context_length": 65536,"max_output_tokens": 65536,- "input_price_per_mtok": 0.25,- "output_price_per_mtok": 1.5,+ "input_price_per_mtok": 0.5,+ "output_price_per_mtok": 3.0,"supports_thinking": true,"thinking_type": "budget","temperature_range": [@@ -68,8 +129,8 @@"local_id": "qwen3.5-35b-a3b","context_length": 262144,"max_output_tokens": 65536,- "input_price_per_mtok": 0.25,- "output_price_per_mtok": 2.0,+ "input_price_per_mtok": 0.1625,+ "output_price_per_mtok": 1.3,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -78,17 +139,23 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty","include_reasoning",+ "logit_bias","logprobs","max_tokens",+ "min_p","presence_penalty","reasoning",+ "repetition_penalty","response_format","seed",+ "stop","structured_outputs","temperature","tool_choice","tools",+ "top_k","top_logprobs","top_p"]@@ -100,8 +167,8 @@"local_id": "qwen3.5-27b","context_length": 262144,"max_output_tokens": 65536,- "input_price_per_mtok": 0.3,- "output_price_per_mtok": 2.4,+ "input_price_per_mtok": 0.195,+ "output_price_per_mtok": 1.56,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -110,17 +177,23 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty","include_reasoning",+ "logit_bias","logprobs","max_tokens",+ "min_p","presence_penalty","reasoning",+ "repetition_penalty","response_format","seed",+ "stop","structured_outputs","temperature","tool_choice","tools",+ "top_k","top_logprobs","top_p"]@@ -132,8 +205,8 @@"local_id": "qwen3.5-122b-a10b","context_length": 262144,"max_output_tokens": 65536,- "input_price_per_mtok": 0.4,- "output_price_per_mtok": 3.2,+ "input_price_per_mtok": 0.26,+ "output_price_per_mtok": 2.08,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -142,17 +215,23 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty","include_reasoning",+ "logit_bias","logprobs","max_tokens",+ "min_p","presence_penalty","reasoning",+ "repetition_penalty","response_format","seed",+ "stop","structured_outputs","temperature","tool_choice","tools",+ "top_k","top_logprobs","top_p"]@@ -365,8 +444,8 @@"local_id": "qwen3.5-plus-02-15","context_length": 1000000,"max_output_tokens": 65536,- "input_price_per_mtok": 0.4,- "output_price_per_mtok": 2.4,+ "input_price_per_mtok": 0.26,+ "output_price_per_mtok": 1.56,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -395,8 +474,8 @@"local_id": "qwen3.5-397b-a17b","context_length": 262144,"max_output_tokens": 65536,- "input_price_per_mtok": 0.55,- "output_price_per_mtok": 3.5,+ "input_price_per_mtok": 0.39,+ "output_price_per_mtok": 2.34,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -469,10 +548,10 @@"name": "Z.ai: GLM 5","provider": "z-ai","local_id": "glm-5",- "context_length": 204800,- "max_output_tokens": 131072,- "input_price_per_mtok": 0.95,- "output_price_per_mtok": 2.55,+ "context_length": 202752,+ "max_output_tokens": 0,+ "input_price_per_mtok": 0.8,+ "output_price_per_mtok": 2.56,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -509,8 +588,8 @@"local_id": "qwen3-max-thinking","context_length": 262144,"max_output_tokens": 32768,- "input_price_per_mtok": 1.2,- "output_price_per_mtok": 6.0,+ "input_price_per_mtok": 0.78,+ "output_price_per_mtok": 3.9,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -752,15 +831,15 @@"top_p"]},- "upstage/solar-pro-3:free": {- "id": "upstage/solar-pro-3:free",- "name": "Upstage: Solar Pro 3 (free)",+ "upstage/solar-pro-3": {+ "id": "upstage/solar-pro-3",+ "name": "Upstage: Solar Pro 3","provider": "upstage",- "local_id": "solar-pro-3:free",+ "local_id": "solar-pro-3","context_length": 128000,"max_output_tokens": 0,- "input_price_per_mtok": 0.0,- "output_price_per_mtok": 0.0,+ "input_price_per_mtok": 0.15,+ "output_price_per_mtok": 0.6,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -1211,7 +1290,7 @@"provider": "gemini","local_id": "gemini-3-flash-preview","context_length": 1048576,- "max_output_tokens": 65535,+ "max_output_tokens": 65536,"input_price_per_mtok": 0.5,"output_price_per_mtok": 3.0,"supports_thinking": true,@@ -1256,6 +1335,39 @@"tools"]},+ "allenai/olmo-3.1-32b-think": {+ "id": "allenai/olmo-3.1-32b-think",+ "name": "AllenAI: Olmo 3.1 32B Think",+ "provider": "allenai",+ "local_id": "olmo-3.1-32b-think",+ "context_length": 65536,+ "max_output_tokens": 65536,+ "input_price_per_mtok": 0.15,+ "output_price_per_mtok": 0.5,+ "supports_thinking": false,+ "thinking_type": "none",+ "temperature_range": [+ 0.0,+ 2.0+ ],+ "is_reasoning_model": false,+ "supported_parameters": [+ "frequency_penalty",+ "include_reasoning",+ "logit_bias",+ "max_tokens",+ "presence_penalty",+ "reasoning",+ "repetition_penalty",+ "response_format",+ "seed",+ "stop",+ "structured_outputs",+ "temperature",+ "top_k",+ "top_p"+ ]+ },"xiaomi/mimo-v2-flash": {"id": "xiaomi/mimo-v2-flash","name": "Xiaomi: MiMo-V2-Flash",@@ -1575,6 +1687,8 @@"stop","structured_outputs","temperature",+ "tool_choice",+ "tools","top_k","top_p"]@@ -1836,7 +1950,7 @@"provider": "deepseek","local_id": "deepseek-v3.2-speciale","context_length": 163840,- "max_output_tokens": 65536,+ "max_output_tokens": 163840,"input_price_per_mtok": 0.4,"output_price_per_mtok": 1.2,"supports_thinking": false,@@ -1847,12 +1961,20 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty","include_reasoning",+ "logit_bias","max_tokens",+ "min_p",+ "presence_penalty","reasoning",+ "repetition_penalty","response_format",+ "seed",+ "stop","structured_outputs","temperature",+ "top_k","top_p"]},@@ -1862,7 +1984,7 @@"provider": "deepseek","local_id": "deepseek-v3.2","context_length": 163840,- "max_output_tokens": 163840,+ "max_output_tokens": 65536,"input_price_per_mtok": 0.25,"output_price_per_mtok": 0.4,"supports_thinking": false,@@ -2302,7 +2424,9 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logit_bias","max_tokens",+ "min_p","presence_penalty","repetition_penalty","response_format",@@ -2530,7 +2654,7 @@"provider": "minimax","local_id": "minimax-m2","context_length": 196608,- "max_output_tokens": 65536,+ "max_output_tokens": 196608,"input_price_per_mtok": 0.255,"output_price_per_mtok": 1.0,"supports_thinking": false,@@ -2543,7 +2667,9 @@"supported_parameters": ["frequency_penalty","include_reasoning",+ "logit_bias","max_tokens",+ "min_p","presence_penalty","reasoning","repetition_penalty",@@ -3290,7 +3416,7 @@"provider": "gemini","local_id": "gemini-2.5-flash-lite-preview-09-2025","context_length": 1048576,- "max_output_tokens": 65535,+ "max_output_tokens": 65536,"input_price_per_mtok": 0.1,"output_price_per_mtok": 0.4,"supports_thinking": true,@@ -3416,8 +3542,8 @@"local_id": "qwen3-coder-plus","context_length": 1000000,"max_output_tokens": 65536,- "input_price_per_mtok": 1.0,- "output_price_per_mtok": 5.0,+ "input_price_per_mtok": 0.65,+ "output_price_per_mtok": 3.25,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -3518,6 +3644,7 @@"supported_parameters": ["frequency_penalty","include_reasoning",+ "logit_bias","max_tokens","min_p","presence_penalty",@@ -3582,14 +3709,22 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty","include_reasoning",+ "logit_bias","max_tokens",+ "min_p",+ "presence_penalty","reasoning",+ "repetition_penalty","response_format",+ "seed",+ "stop","structured_outputs","temperature","tool_choice","tools",+ "top_k","top_p"]},@@ -3600,8 +3735,8 @@"local_id": "qwen3-coder-flash","context_length": 1000000,"max_output_tokens": 65536,- "input_price_per_mtok": 0.3,- "output_price_per_mtok": 1.5,+ "input_price_per_mtok": 0.195,+ "output_price_per_mtok": 0.975,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -3726,7 +3861,7 @@"provider": "meituan","local_id": "longcat-flash-chat","context_length": 131072,- "max_output_tokens": 32768,+ "max_output_tokens": 131072,"input_price_per_mtok": 0.2,"output_price_per_mtok": 0.8,"supports_thinking": false,@@ -3737,12 +3872,20 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty",+ "logit_bias","max_tokens",+ "min_p",+ "presence_penalty",+ "repetition_penalty","response_format",+ "seed",+ "stop","structured_outputs","temperature","tool_choice","tools",+ "top_k","top_p"]},@@ -3753,8 +3896,8 @@"local_id": "qwen-plus-2025-07-28:thinking","context_length": 1000000,"max_output_tokens": 32768,- "input_price_per_mtok": 0.4,- "output_price_per_mtok": 1.2,+ "input_price_per_mtok": 0.26,+ "output_price_per_mtok": 0.78,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -3783,8 +3926,8 @@"local_id": "qwen-plus-2025-07-28","context_length": 1000000,"max_output_tokens": 32768,- "input_price_per_mtok": 0.4,- "output_price_per_mtok": 1.2,+ "input_price_per_mtok": 0.26,+ "output_price_per_mtok": 0.78,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -3953,12 +4096,15 @@"supported_parameters": ["frequency_penalty","include_reasoning",+ "logit_bias","max_tokens",+ "min_p","presence_penalty","reasoning","repetition_penalty","response_format","seed",+ "stop","structured_outputs","temperature","tool_choice",@@ -4418,8 +4564,8 @@"local_id": "gpt-oss-120b","context_length": 131072,"max_output_tokens": 0,- "input_price_per_mtok": 0.039,- "output_price_per_mtok": 0.19,+ "input_price_per_mtok": 0.02,+ "output_price_per_mtok": 0.1,"supports_thinking": true,"thinking_type": "effort","temperature_range": [@@ -4659,11 +4805,14 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logit_bias","max_tokens",+ "min_p","presence_penalty","repetition_penalty","response_format","seed",+ "stop","structured_outputs","temperature","tool_choice",@@ -4905,13 +5054,10 @@],"is_reasoning_model": false,"supported_parameters": [- "frequency_penalty","max_tokens",- "presence_penalty","repetition_penalty","response_format","seed",- "stop","structured_outputs","temperature","tool_choice",@@ -5216,12 +5362,9 @@],"is_reasoning_model": false,"supported_parameters": [- "frequency_penalty","max_tokens",- "presence_penalty","response_format","seed",- "stop","temperature","top_p"]@@ -5399,7 +5542,7 @@"context_length": 128000,"max_output_tokens": 16384,"input_price_per_mtok": 0.25,- "output_price_per_mtok": 1.0,+ "output_price_per_mtok": 0.75,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -5779,12 +5922,9 @@],"is_reasoning_model": false,"supported_parameters": [- "frequency_penalty","max_tokens",- "presence_penalty","response_format","seed",- "stop","temperature","top_p"]@@ -6004,7 +6144,7 @@"context_length": 128000,"max_output_tokens": 16384,"input_price_per_mtok": 0.25,- "output_price_per_mtok": 1.0,+ "output_price_per_mtok": 0.75,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -6141,16 +6281,22 @@],"is_reasoning_model": false,"supported_parameters": [+ "frequency_penalty","include_reasoning",+ "logit_bias","max_tokens",+ "min_p","presence_penalty","reasoning",+ "repetition_penalty","response_format","seed",+ "stop","structured_outputs","temperature","tool_choice","tools",+ "top_k","top_p"]},@@ -6173,6 +6319,7 @@"supported_parameters": ["frequency_penalty","include_reasoning",+ "logprobs","max_tokens","min_p","presence_penalty",@@ -6186,6 +6333,7 @@"tool_choice","tools","top_k",+ "top_logprobs","top_p"]},@@ -7389,8 +7537,8 @@"local_id": "qwen-vl-plus","context_length": 131072,"max_output_tokens": 8192,- "input_price_per_mtok": 0.21,- "output_price_per_mtok": 0.63,+ "input_price_per_mtok": 0.1365,+ "output_price_per_mtok": 0.4095,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -7511,8 +7659,8 @@"local_id": "qwen-turbo","context_length": 131072,"max_output_tokens": 8192,- "input_price_per_mtok": 0.05,- "output_price_per_mtok": 0.2,+ "input_price_per_mtok": 0.0325,+ "output_price_per_mtok": 0.13,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -7596,8 +7744,8 @@"local_id": "qwen-max","context_length": 32768,"max_output_tokens": 8192,- "input_price_per_mtok": 1.6,- "output_price_per_mtok": 6.4,+ "input_price_per_mtok": 1.04,+ "output_price_per_mtok": 4.16,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -7840,6 +7988,7 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logprobs","max_tokens","min_p","presence_penalty",@@ -7850,6 +7999,7 @@"structured_outputs","temperature","top_k",+ "top_logprobs","top_p"]},@@ -8347,7 +8497,9 @@"logprobs","max_tokens","presence_penalty",+ "repetition_penalty","response_format",+ "seed","stop","structured_outputs","temperature",@@ -8621,10 +8773,10 @@"name": "Meta: Llama 3.2 3B Instruct","provider": "meta","local_id": "llama-3.2-3b-instruct",- "context_length": 131072,- "max_output_tokens": 16384,- "input_price_per_mtok": 0.02,- "output_price_per_mtok": 0.02,+ "context_length": 80000,+ "max_output_tokens": 0,+ "input_price_per_mtok": 0.051,+ "output_price_per_mtok": 0.34,"supports_thinking": false,"thinking_type": "none","temperature_range": [@@ -8639,7 +8791,6 @@"min_p","presence_penalty","repetition_penalty",- "response_format","seed","stop","temperature",@@ -8755,12 +8906,14 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logprobs","max_tokens","presence_penalty","response_format","stop","structured_outputs","temperature",+ "top_logprobs","top_p"]},@@ -8844,6 +8997,7 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logprobs","max_tokens","min_p","presence_penalty",@@ -8856,6 +9010,7 @@"tool_choice","tools","top_k",+ "top_logprobs","top_p"]},@@ -8907,6 +9062,7 @@"is_reasoning_model": false,"supported_parameters": ["frequency_penalty",+ "logprobs","max_tokens","min_p","presence_penalty",@@ -8917,6 +9073,7 @@"structured_outputs","temperature","top_k",+ "top_logprobs","top_p"]},@@ -9388,64 +9545,6 @@"top_p"]},- "mistralai/mistral-7b-instruct": {- "id": "mistralai/mistral-7b-instruct",- "name": "Mistral: Mistral 7B Instruct",- "provider": "mistralai",- "local_id": "mistral-7b-instruct",- "context_length": 32768,- "max_output_tokens": 4096,- "input_price_per_mtok": 0.2,- "output_price_per_mtok": 0.2,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "logit_bias",- "max_tokens",- "min_p",- "presence_penalty",- "repetition_penalty",- "stop",- "temperature",- "top_k",- "top_p"- ]- },- "mistralai/mistral-7b-instruct-v0.3": {- "id": "mistralai/mistral-7b-instruct-v0.3",- "name": "Mistral: Mistral 7B Instruct v0.3",- "provider": "mistralai",- "local_id": "mistral-7b-instruct-v0.3",- "context_length": 32768,- "max_output_tokens": 4096,- "input_price_per_mtok": 0.2,- "output_price_per_mtok": 0.2,- "supports_thinking": false,- "thinking_type": "none",- "temperature_range": [- 0.0,- 2.0- ],- "is_reasoning_model": false,- "supported_parameters": [- "frequency_penalty",- "logit_bias",- "max_tokens",- "min_p",- "presence_penalty",- "repetition_penalty",- "stop",- "temperature",- "top_k",- "top_p"- ]- },"meta/llama-guard-2-8b": {"id": "meta-llama/llama-guard-2-8b","name": "Meta: LlamaGuard 2 8B",diff --git a/server/core/logging.py b/server/core/logging.pyindex dabefa1f..466a3a8d 100644--- a/server/core/logging.py+++ b/server/core/logging.py@@ -177,6 +177,10 @@ def configure_logging(settings: Settings) -> None:level=getattr(logging, settings.log_level.upper()))+ # Silence noisy third-party loggers+ logging.getLogger("httpx").setLevel(logging.WARNING)+ logging.getLogger("httpcore").setLevel(logging.WARNING)+# Configure structlogprocessors = [structlog.stdlib.filter_by_level,diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex ea6a33e8..fb458c8e 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1778,6 +1778,53 @@ async def handle_whatsapp_rate_limit_unpause(data: Dict[str, Any], websocket: Wereturn result+async def handle_whatsapp_mark_read(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Mark messages as read. Schema: mark_read({message_ids, chat_jid, sender_jid?})"""+ message_ids = data.get("message_ids", [])+ chat_jid = data.get("chat_jid", "")+ if not message_ids or not chat_jid:+ return {"success": False, "error": "message_ids (array) and chat_jid are required"}+ params: Dict[str, Any] = {"message_ids": message_ids, "chat_jid": chat_jid}+ sender_jid = data.get("sender_jid")+ if sender_jid:+ params["sender_jid"] = sender_jid+ result = await _wa_rpc_call("mark_read", params)+ return result+++async def handle_whatsapp_typing(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Send typing indicator. Schema: typing({jid, state: 'composing'|'paused', media?})"""+ jid = data.get("jid", "")+ state = data.get("state", "composing")+ if not jid:+ return {"success": False, "error": "jid is required"}+ params: Dict[str, Any] = {"jid": jid, "state": state}+ media = data.get("media")+ if media:+ params["media"] = media+ result = await _wa_rpc_call("typing", params)+ return result+++async def handle_whatsapp_presence(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Set online/offline presence. Schema: presence({status: 'available'|'unavailable'})"""+ status = data.get("status", "available")+ result = await _wa_rpc_call("presence", {"status": status})+ return result+++async def handle_whatsapp_stop(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Graceful WhatsApp shutdown."""+ result = await _wa_rpc_call("stop", {})+ return result+++async def handle_whatsapp_diagnostics(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get WhatsApp diagnostics/debug info."""+ result = await _wa_rpc_call("diagnostics", {})+ return result++# ============================================================================# Telegram Handlers - Connect/disconnect/status for Telegram bot# ============================================================================@@ -1815,17 +1862,19 @@ async def handle_telegram_connect(data: Dict[str, Any], websocket: WebSocket) ->async def handle_telegram_disconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:- """Disconnect Telegram bot and remove stored token."""+ """Disconnect Telegram bot and remove stored token and owner chat ID."""service = get_telegram_service()result = await service.disconnect()- # Remove stored token+ # Remove stored token and owner chat IDtry:auth_service = get_auth_service()await auth_service.remove_api_key("telegram_bot_token")+ await auth_service.remove_api_key("telegram_owner_chat_id")except Exception as e:- logger.warning(f"[Telegram] Failed to remove stored token: {e}")+ logger.warning(f"[Telegram] Failed to remove stored credentials: {e}")+ result["has_stored_token"] = Falsereturn result@@ -2956,6 +3005,11 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {"whatsapp_rate_limit_set": handle_whatsapp_rate_limit_set,"whatsapp_rate_limit_stats": handle_whatsapp_rate_limit_stats,"whatsapp_rate_limit_unpause": handle_whatsapp_rate_limit_unpause,+ "whatsapp_mark_read": handle_whatsapp_mark_read,+ "whatsapp_typing": handle_whatsapp_typing,+ "whatsapp_presence": handle_whatsapp_presence,+ "whatsapp_stop": handle_whatsapp_stop,+ "whatsapp_diagnostics": handle_whatsapp_diagnostics,# Telegram operations"telegram_connect": handle_telegram_connect,diff --git a/server/routers/whatsapp.py b/server/routers/whatsapp.pyindex f62ea962..cf0e472a 100644--- a/server/routers/whatsapp.py+++ b/server/routers/whatsapp.py@@ -237,6 +237,9 @@ class RPCClient:elif method == "event.newsletter_live_update":await broadcaster.send_custom_event("whatsapp_newsletter_live_update", params)+ elif method == "event.history_sync_complete":+ await broadcaster.send_custom_event("whatsapp_history_sync_complete", params)+# Forward to custom handler if setif self._event_handler:await self._event_handler(method, params)diff --git a/server/services/ai.py b/server/services/ai.pyindex 2b378d95..7319433d 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -2868,7 +2868,7 @@ class AIService:"""operation: str = Field(default="chat_history",- description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts', 'list_channels', 'get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_create', 'channel_mute', 'channel_mark_viewed'"+ description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts', 'list_channels', 'get_channel_info', 'channel_messages', 'channel_stats', 'channel_follow', 'channel_unfollow', 'channel_create', 'channel_mute', 'channel_mark_viewed', 'newsletter_react', 'newsletter_live_updates', 'contact_profile_pic'")# For chat_historychat_type: Optional[str] = Field(@@ -2932,6 +2932,30 @@ class AIService:default=None,description="For channel_messages: fetch messages before this server ID (pagination).")+ message_offset: Optional[int] = Field(+ default=None,+ description="For channel_messages: pagination offset - skip this many messages."+ )+ since: Optional[str] = Field(+ default=None,+ description="For channel_messages: only return messages after this Unix timestamp."+ )+ until: Optional[str] = Field(+ default=None,+ description="For channel_messages: only return messages before this Unix timestamp."+ )+ media_type: Optional[str] = Field(+ default=None,+ description="For channel_messages: filter by media type ('image', 'video', 'audio', 'document', 'sticker'). Omit for all types."+ )+ search: Optional[str] = Field(+ default=None,+ description="For channel_messages: search for messages containing this text."+ )+ include_media_data: Optional[bool] = Field(+ default=None,+ description="For chat_history/channel_messages: download base64 media data for media messages. May be slow."+ )channel_name: Optional[str] = Field(default=None,description="For channel_create: name of the new channel."@@ -2946,7 +2970,30 @@ class AIService:)server_ids: Optional[str] = Field(default=None,- description="For channel_mark_viewed: comma-separated message server IDs to mark as viewed (e.g., '100, 101, 102')."+ description="For channel_mark_viewed/newsletter_live_updates: comma-separated message server IDs (e.g., '100, 101, 102')."+ )+ # Newsletter react+ react_server_id: Optional[int] = Field(+ default=None,+ description="For newsletter_react: server ID of the message to react to."+ )+ reaction: Optional[str] = Field(+ default=None,+ description="For newsletter_react: reaction emoji (empty string to remove reaction)."+ )+ # Channel create picture+ picture: Optional[str] = Field(+ default=None,+ description="For channel_create: base64-encoded profile picture for the channel."+ )+ # Contact profile picture+ profile_pic_jid: Optional[str] = Field(+ default=None,+ description="For contact_profile_pic: JID or phone number to get profile picture for."+ )+ preview: Optional[bool] = Field(+ default=None,+ description="For contact_profile_pic: get low-resolution preview instead of full picture.")return WhatsAppDbSchemadiff --git a/server/services/event_waiter.py b/server/services/event_waiter.pyindex bc1b5814..c78930f6 100644--- a/server/services/event_waiter.py+++ b/server/services/event_waiter.py@@ -432,78 +432,112 @@ def build_gmail_filter(params: Dict) -> Callable[[Dict], bool]:def build_telegram_filter(params: Dict) -> Callable[[Dict], bool]:"""Build filter function for Telegram messages.- Filters by:- - chatTypeFilter: 'all', 'private', 'group', 'supergroup', 'channel'- - contentTypeFilter: 'all', 'text', 'photo', 'video', 'audio', 'voice', 'document', 'sticker', 'location', 'contact', 'poll'- - chat_id: Filter to specific chat (optional)- - from_user: Filter to specific user ID (optional)- - keywords: Comma-separated keywords to match in text (optional)- - ignoreBots: Ignore messages from bots (default: True)+ Supports new senderFilter-based params and legacy chatTypeFilter/chat_id/from_user params.++ New parameter: senderFilter+ - 'all': Accept all messages+ - 'self': Only messages from the bot owner (uses injected _owner_chat_id)+ - 'private': Only private (DM) chats+ - 'group': Only group chats+ - 'supergroup': Only supergroup chats+ - 'channel': Only channel posts+ - 'specific_chat': Only from specific chat_id+ - 'specific_user': Only from specific from_user+ - 'keywords': Messages containing specific keywords++ Legacy parameters (backward compat):+ - chatTypeFilter: 'all', 'private', 'group', 'supergroup', 'channel'+ - chat_id, from_user, keywords, ignoreBotsEvent data fields (from TelegramService._format_message):- - message_id: int- - chat_id: int- - chat_type: str ('private', 'group', 'supergroup', 'channel')- - chat_title: str (for groups/channels)- - from_id: int (sender user ID)- - from_username: str (sender username)- - from_first_name: str- - from_last_name: str- - is_bot: bool- - text: str (message text or caption)- - content_type: str- - date: str (ISO format)- - reply_to_message_id: int (optional)- - photo/document/location/contact: dict (media info if present)+ message_id, chat_id, chat_type, chat_title, from_id, from_username,+ from_first_name, from_last_name, is_bot, text, content_type, date,+ reply_to_message_id, photo/document/location/contact dictsArgs:- params: Node parameters+ params: Node parameters (may include injected _owner_chat_id)Returns:Filter function that checks if event matches criteria"""- chat_type_filter = params.get('chatTypeFilter', 'all')+ # New-style senderFilter (takes precedence)+ sender_filter = params.get('senderFilter', '')++ # Legacy fallback: reconstruct from old params if senderFilter absent+ if not sender_filter:+ chat_type_filter = params.get('chatTypeFilter', 'all')+ old_chat_id = params.get('chat_id', '')+ old_from_user = params.get('from_user', '')+ old_keywords = params.get('keywords', '')++ if old_chat_id:+ sender_filter = 'specific_chat'+ elif old_from_user:+ sender_filter = 'specific_user'+ elif old_keywords:+ sender_filter = 'keywords'+ elif chat_type_filter != 'all':+ sender_filter = chat_type_filter+ else:+ sender_filter = 'all'+content_type_filter = params.get('contentTypeFilter', 'all')chat_id_filter = params.get('chat_id', '')from_user_filter = params.get('from_user', '')keywords = [k.strip().lower() for k in params.get('keywords', '').split(',') if k.strip()]ignore_bots = params.get('ignoreBots', True)+ owner_chat_id = params.get('_owner_chat_id')++ logger.debug(f"[TelegramFilter] Built: sender={sender_filter}, content_type={content_type_filter}, owner_chat_id={owner_chat_id}")- logger.debug(f"[TelegramFilter] Built: chat_type={chat_type_filter}, content_type={content_type_filter}, chat_id='{chat_id_filter}', ignore_bots={ignore_bots}")+ def _get_owner_chat_id() -> object:+ """Get owner_chat_id dynamically - handles case where owner is detected+ after the filter was built (first message to bot captures the owner)."""+ if owner_chat_id:+ return owner_chat_id+ # Lazy lookup from service at match time+ try:+ from services.telegram_service import get_telegram_service+ service = get_telegram_service()+ return service.owner_chat_id+ except Exception:+ return Nonedef matches(m: Dict) -> bool:- # Chat type filter- if chat_type_filter != 'all':- msg_chat_type = m.get('chat_type', '')- if msg_chat_type != chat_type_filter:+ # Content type filter (always applies)+ if content_type_filter != 'all':+ if m.get('content_type', '') != content_type_filter:return False- # Content type filter- if content_type_filter != 'all':- msg_content_type = m.get('content_type', '')- if msg_content_type != content_type_filter:+ # Sender filter+ if sender_filter == 'self':+ current_owner = _get_owner_chat_id()+ if not current_owner:+ logger.debug("[TelegramFilter] Rejecting: owner_chat_id not available")+ return False+ if str(m.get('from_id', '')) != str(current_owner):return False- # Chat ID filter (exact match)- if chat_id_filter:- msg_chat_id = str(m.get('chat_id', ''))- if msg_chat_id != str(chat_id_filter):+ elif sender_filter in ('private', 'group', 'supergroup', 'channel'):+ if m.get('chat_type', '') != sender_filter:return False- # From user filter (user ID)- if from_user_filter:- msg_from_id = str(m.get('from_id', ''))- if msg_from_id != str(from_user_filter):+ elif sender_filter == 'specific_chat':+ if chat_id_filter and str(m.get('chat_id', '')) != str(chat_id_filter):return False- # Keywords filter (any keyword in text)- if keywords:- text = (m.get('text') or '').lower()- if not any(kw in text for kw in keywords):+ elif sender_filter == 'specific_user':+ if from_user_filter and str(m.get('from_id', '')) != str(from_user_filter):return False- # Ignore bot messages- if ignore_bots and m.get('is_bot', False):+ elif sender_filter == 'keywords':+ if keywords:+ text = (m.get('text') or '').lower()+ if not any(kw in text for kw in keywords):+ return False++ # Ignore bot messages (skip for 'self' filter)+ if sender_filter != 'self' and ignore_bots and m.get('is_bot', False):return Falselogger.debug(f"[TelegramFilter] Matched message from {m.get('from_username', m.get('from_id'))}")@@ -816,16 +850,26 @@ def dispatch(event_type: str, data: Dict) -> int:resolved = 0to_remove = []- for wid, w in _waiters.items():- if w.event_type == event_type and w.future and not w.future.done():- try:- if w.filter_fn(data):- w.future.set_result(data)- to_remove.append(wid)- resolved += 1- logger.debug(f"[EventWaiter] Resolved {w.node_type} waiter {wid}")- except Exception as e:- logger.error(f"[EventWaiter] Filter error for waiter {wid}: {e}")+ matching_waiters = [(wid, w) for wid, w in _waiters.items()+ if w.event_type == event_type and w.future and not w.future.done()]++ if not matching_waiters:+ logger.debug(f"[EventWaiter] No active waiters for {event_type} (total waiters: {len(_waiters)})")+ else:+ logger.info(f"[EventWaiter] Dispatching {event_type} to {len(matching_waiters)} waiter(s)",+ event_type=event_type, from_id=data.get('from_id'), text=str(data.get('text', ''))[:50])++ for wid, w in matching_waiters:+ try:+ if w.filter_fn(data):+ w.future.set_result(data)+ to_remove.append(wid)+ resolved += 1+ logger.info(f"[EventWaiter] Resolved {w.node_type} waiter {wid}")+ else:+ logger.debug(f"[EventWaiter] Filter rejected for {w.node_type} waiter {wid}")+ except Exception as e:+ logger.error(f"[EventWaiter] Filter error for waiter {wid}: {e}")for wid in to_remove:_waiters.pop(wid, None)diff --git a/server/services/handlers/telegram.py b/server/services/handlers/telegram.pyindex 8b1aadf2..bb440121 100644--- a/server/services/handlers/telegram.py+++ b/server/services/handlers/telegram.py@@ -1,9 +1,8 @@"""Telegram Node Handlers-Handles execution of Telegram workflow nodes:- telegramSend: Send messages via Telegram bot-- telegramReceive: Trigger node that waits for incoming messages+- telegramReceive: Routed via generic handle_trigger_node + event_waiter.build_telegram_filter()"""import time@@ -59,6 +58,19 @@ async def handle_telegram_send(if recipient_type == "self":chat_id = service.owner_chat_id+ # Fallback: restore from credentials DB+ if not chat_id:+ try:+ from core.container import container+ auth = container.auth_service()+ saved_owner = await auth.get_api_key("telegram_owner_chat_id")+ if saved_owner:+ owner_id = int(saved_owner)+ await service.set_owner(owner_id)+ chat_id = owner_id+ logger.info(f"[Telegram] Owner restored from credentials: {owner_id}")+ except Exception as e:+ logger.warning(f"[Telegram] Failed to restore owner from credentials: {e}")if not chat_id:return {"success": False,@@ -228,89 +240,5 @@ async def handle_telegram_send(}-async def handle_telegram_receive(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Telegram receive trigger node.-- This is an event-driven trigger that waits for incoming Telegram messages.- Uses the event_waiter system to register a waiter and wait for matching events.-- Filter Parameters:- - chatTypeFilter: all, private, group, supergroup, channel- - contentTypeFilter: all, text, photo, video, document, location, contact- - chat_id: Filter to specific chat (optional)- - from_user: Filter to specific user ID (optional)- - keywords: Comma-separated keywords to match in text (optional)- - ignoreBots: Ignore messages from bots (default: True)-- Returns:- The matched Telegram message data- """- from services import event_waiter- from services.status_broadcaster import get_status_broadcaster- from services.telegram_service import get_telegram_service-- start_time = time.time()- broadcaster = get_status_broadcaster()- service = get_telegram_service()-- try:- # Check if bot is connected- if not service.connected:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "Telegram bot not connected. Add bot token in Credentials.",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- # Register waiter with filter- waiter = event_waiter.register(node_type, node_id, parameters)-- logger.info(f"[Telegram] Trigger {node_id} waiting for message (waiter_id={waiter.id})")-- # Broadcast waiting status- await broadcaster.update_node_status(- node_id,- "waiting",- {- "message": "Waiting for Telegram message...",- "waiter_id": waiter.id,- "filters": {- "chat_type": parameters.get("chatTypeFilter", "all"),- "content_type": parameters.get("contentTypeFilter", "all"),- "keywords": parameters.get("keywords", ""),- }- }- )-- # Wait for matching event (no timeout - user cancels via cancel_event_wait)- event_data = await waiter.future-- logger.info(f"[Telegram] Trigger {node_id} received message: {event_data.get('content_type')} from {event_data.get('from_username', event_data.get('from_id'))}")-- return {- "success": True,- "node_id": node_id,- "node_type": node_type,- "result": event_data,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error(f"[Telegram] Receive failed: {e}")- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }+ # telegramReceive: routed via generic handle_trigger_node in node_executor.py+ # Filter logic lives in event_waiter.build_telegram_filter() with lazy _get_owner_chat_id()diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 48f979a0..efe65b42 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -794,6 +794,8 @@ async def _execute_whatsapp_db(args: Dict[str, Any],'limit': args.get('limit', 50),'offset': args.get('offset', 0),})+ if args.get('include_media_data'):+ parameters['include_media_data'] = True# Validate required fieldschat_type = parameters['chat_type']if chat_type == 'individual' and not parameters['phone']:@@ -849,6 +851,20 @@ async def _execute_whatsapp_db(args: Dict[str, Any],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'] = Trueelif operation == 'channel_stats':channel_jid = args.get('channel_jid', '')@@ -894,6 +910,35 @@ async def _execute_whatsapp_db(args: Dict[str, Any],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}"}diff --git a/server/services/handlers/triggers.py b/server/services/handlers/triggers.pyindex 38a53dc7..f7b36ada 100644--- a/server/services/handlers/triggers.py+++ b/server/services/handlers/triggers.py@@ -48,6 +48,25 @@ async def handle_trigger_node(}try:+ # Telegram pre-check: verify bot is connected before waiting+ if node_type == 'telegramReceive':+ from services.telegram_service import get_telegram_service+ service = get_telegram_service()+ if not service.connected:+ return {+ "success": False,+ "node_id": node_id,+ "node_type": node_type,+ "error": "Telegram bot not connected. Add bot token in Credentials.",+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+ sender_filter = parameters.get('senderFilter', 'all')+ logger.info("Telegram trigger starting",+ node_id=node_id, sender_filter=sender_filter,+ owner_detected=service.owner_chat_id is not None,+ execution_id=execution_id)+# Register waiter for this trigger (async to pre-fetch LID cache)waiter = await event_waiter.register(node_type, node_id, parameters)@@ -71,7 +90,7 @@ async def handle_trigger_node(# Uses wait_for_event which handles both Redis Streams and asyncio.Future modestry:event_data = await event_waiter.wait_for_event(waiter)- logger.info("Event received", node_id=node_id, execution_id=execution_id)+ logger.info("Event received", node_id=node_id, node_type=node_type, execution_id=execution_id)# Success - event receivedreturn {diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.pyindex 4c3a5ab1..16b79e60 100644--- a/server/services/handlers/whatsapp.py+++ b/server/services/handlers/whatsapp.py@@ -1,8 +1,9 @@"""WhatsApp node handlers - Send and DB operations."""+import asyncioimport timefrom datetime import datetime-from typing import Dict, Any+from typing import Dict, Any, Listfrom core.logging import get_loggerlogger = get_logger(__name__)@@ -50,6 +51,73 @@ async def _resolve_to_jid(value: str, rpc_call) -> str:raise ValueError(f"Could not resolve invite link to channel JID: {value}")+# Media types that can be downloaded via the media RPC+MEDIA_MESSAGE_TYPES = frozenset({'image', 'video', 'audio', 'document', 'sticker'})+++async def _download_single_media(message: Dict[str, Any], rpc_call) -> None:+ """Download media for a single message in-place. Mutates the message dict."""+ message_id = message.get('message_id') or message.get('id')+ if not message_id:+ return+ try:+ data = await rpc_call('media', {'message_id': message_id})+ if isinstance(data, dict):+ result = data.get('result', data)+ if result.get('data'):+ message['media_data'] = result['data']+ message['media_mime_type'] = result.get('mime_type', '')+ else:+ message['media_error'] = result.get('error', 'No media data returned')+ else:+ message['media_error'] = 'Unexpected response format'+ except Exception as e:+ message['media_error'] = str(e)+++async def _enrich_messages_with_media(+ messages: List[Dict[str, Any]],+ rpc_call,+ max_concurrent: int = 5+) -> List[Dict[str, Any]]:+ """Download media for messages that contain media types.++ Uses asyncio.Semaphore for concurrency control and asyncio.gather+ for parallel downloads. Gracefully handles per-message failures.++ Args:+ messages: List of message dicts (mutated in-place)+ rpc_call: The whatsapp_rpc_call function+ max_concurrent: Max parallel media downloads++ Returns:+ The same messages list (mutated with media_data/media_error fields)+ """+ semaphore = asyncio.Semaphore(max_concurrent)++ async def download_with_semaphore(msg: Dict[str, Any]) -> None:+ async with semaphore:+ await _download_single_media(msg, rpc_call)++ # Filter to only media messages+ media_messages = [+ msg for msg in messages+ if msg.get('message_type', msg.get('type', '')) in MEDIA_MESSAGE_TYPES+ ]++ if not media_messages:+ return messages++ logger.info(f"Downloading media for {len(media_messages)} messages (max concurrent: {max_concurrent})")++ await asyncio.gather(+ *(download_with_semaphore(msg) for msg in media_messages),+ return_exceptions=True+ )++ return messages++async def handle_whatsapp_send(node_id: str,node_type: str,@@ -220,7 +288,7 @@ async def handle_whatsapp_db(operation = parameters.get('operation', 'chat_history')if operation == 'chat_history':- return await _handle_chat_history(node_id, parameters, start_time, whatsapp_chat_history_handler)+ return await _handle_chat_history(node_id, parameters, start_time, whatsapp_chat_history_handler, whatsapp_rpc_call)elif operation == 'search_groups':return await _handle_search_groups(node_id, parameters, start_time, whatsapp_rpc_call)elif operation == 'get_group_info':@@ -249,6 +317,12 @@ async def handle_whatsapp_db(return await _handle_channel_mute(node_id, parameters, start_time, whatsapp_rpc_call)elif operation == 'channel_mark_viewed':return await _handle_channel_mark_viewed(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'newsletter_react':+ return await _handle_newsletter_react(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'newsletter_live_updates':+ return await _handle_newsletter_live_updates(node_id, parameters, start_time, whatsapp_rpc_call)+ elif operation == 'contact_profile_pic':+ return await _handle_contact_profile_pic(node_id, parameters, start_time, whatsapp_rpc_call)else:raise ValueError(f"Unknown operation: {operation}")@@ -264,7 +338,7 @@ async def handle_whatsapp_db(}-async def _handle_chat_history(node_id: str, parameters: Dict[str, Any], start_time: float, handler) -> Dict[str, Any]:+async def _handle_chat_history(node_id: str, parameters: Dict[str, Any], start_time: float, handler, rpc_call=None) -> Dict[str, Any]:"""Handle chat_history operation."""chat_type = parameters.get('chat_type', 'individual')rpc_params: Dict[str, Any] = {}@@ -301,6 +375,10 @@ async def _handle_chat_history(node_id: str, parameters: Dict[str, Any], start_tfor i, msg in enumerate(messages):msg['index'] = base_offset + i + 1+ # Enrich with media data if requested+ if parameters.get('include_media_data') and rpc_call and messages:+ await _enrich_messages_with_media(messages, rpc_call)+return {"success": True,"node_id": node_id,@@ -512,6 +590,38 @@ async def _handle_check_contacts(node_id: str, parameters: Dict[str, Any], start}+async def _handle_contact_profile_pic(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle contact_profile_pic operation - get profile picture for a contact/group."""+ jid = parameters.get('profile_pic_jid') or parameters.get('phone')+ if not jid:+ raise ValueError("JID or phone number is required")++ rpc_params: Dict[str, Any] = {'jid': jid}+ preview = parameters.get('preview', False)+ if preview:+ rpc_params['preview'] = True++ data = await rpc_call('contact_profile_pic', rpc_params)++ if isinstance(data, dict) and not data.get('success', True):+ raise Exception(data.get('error', 'Failed to get profile picture'))++ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "contact_profile_pic",+ **(result if isinstance(result, dict) else {"url": result}),+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++async def _handle_list_channels(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:"""Handle list_channels operation - list subscribed newsletter channels."""refresh = parameters.get('refresh', False)@@ -585,7 +695,11 @@ async def _handle_get_channel_info(node_id: str, parameters: Dict[str, Any], staasync def _handle_channel_messages(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:- """Handle channel_messages operation - get channel message history."""+ """Handle channel_messages operation - get channel message history.++ Schema params (newsletter_messages RPC):+ jid (required), count, offset, before, since, until, media_type, search, refresh+ """channel_jid = parameters.get('channel_jid')jid = await _resolve_to_jid(channel_jid, rpc_call)@@ -596,6 +710,34 @@ async def _handle_channel_messages(node_id: str, parameters: Dict[str, Any], staif before_server_id:rpc_params['before'] = int(before_server_id)+ # Pagination offset+ msg_offset = parameters.get('message_offset')+ if msg_offset:+ rpc_params['offset'] = int(msg_offset)++ # Date range filters (unix timestamps as strings)+ since = parameters.get('since')+ if since:+ rpc_params['since'] = str(since)++ until = parameters.get('until')+ if until:+ rpc_params['until'] = str(until)++ # Media type filter+ media_type = parameters.get('media_type')+ if media_type and media_type != 'all':+ rpc_params['media_type'] = media_type++ # Text search+ search = parameters.get('search')+ if search:+ rpc_params['search'] = search++ # Force refresh bypassing cache+ if parameters.get('refresh'):+ rpc_params['refresh'] = True+data = await rpc_call('newsletter_messages', rpc_params)if isinstance(data, dict) and not data.get('success', True):@@ -603,6 +745,10 @@ async def _handle_channel_messages(node_id: str, parameters: Dict[str, Any], stamessages = data if isinstance(data, list) else data.get('result', [])+ # Enrich with media data if requested+ if parameters.get('include_media_data') and messages:+ await _enrich_messages_with_media(messages, rpc_call)+return {"success": True,"node_id": node_id,@@ -710,6 +856,9 @@ async def _handle_channel_create(node_id: str, parameters: Dict[str, Any], startdescription = parameters.get('channel_description')if description:rpc_params['description'] = description+ picture = parameters.get('picture')+ if picture:+ rpc_params['picture'] = picturedata = await rpc_call('newsletter_create', rpc_params)@@ -797,3 +946,78 @@ async def _handle_channel_mark_viewed(node_id: str, parameters: Dict[str, Any],}+async def _handle_newsletter_react(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle newsletter_react operation - react to a channel message."""+ channel_jid = parameters.get('channel_jid')+ jid = await _resolve_to_jid(channel_jid, rpc_call)++ server_id = parameters.get('react_server_id')+ if not server_id:+ raise ValueError("Message server ID is required")++ reaction = parameters.get('reaction', '')++ rpc_params: Dict[str, Any] = {+ 'jid': jid,+ 'server_id': int(server_id),+ 'reaction': reaction+ }++ data = await rpc_call('newsletter_react', rpc_params)++ if isinstance(data, dict) and not data.get('success', True):+ raise Exception(data.get('error', 'Failed to react to channel message'))++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "newsletter_react",+ "channel_jid": channel_jid,+ "server_id": int(server_id),+ "reaction": reaction,+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+++async def _handle_newsletter_live_updates(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:+ """Handle newsletter_live_updates operation - subscribe to live view/reaction counts."""+ channel_jid = parameters.get('channel_jid')+ jid = await _resolve_to_jid(channel_jid, rpc_call)++ server_ids_raw = parameters.get('server_ids', '')+ if not server_ids_raw:+ raise ValueError("server_ids is required (comma-separated message IDs)")++ server_ids = [int(sid.strip()) for sid in str(server_ids_raw).split(',') if sid.strip()]+ if not server_ids:+ raise ValueError("At least one server_id is required")++ rpc_params = {'jid': jid, 'server_ids': server_ids}++ data = await rpc_call('newsletter_live_updates', rpc_params)++ if isinstance(data, dict) and not data.get('success', True):+ raise Exception(data.get('error', 'Failed to subscribe to live updates'))++ result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "whatsappDb",+ "result": {+ "operation": "newsletter_live_updates",+ "channel_jid": channel_jid,+ **(result if isinstance(result, dict) else {}),+ "timestamp": datetime.now().isoformat()+ },+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }++diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex d679f58e..b92b41fe 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -39,7 +39,7 @@ from services.handlers import (handle_twitter_send, handle_twitter_search, handle_twitter_user,handle_brave_search, handle_serper_search, handle_perplexity_search,)-from services.handlers.telegram import handle_telegram_send, handle_telegram_receive+from services.handlers.telegram import handle_telegram_sendfrom services.handlers.apify import handle_apify_actorfrom services.handlers.crawlee import handle_crawlee_scraperfrom services.handlers.proxy import handle_proxy_request, handle_proxy_status, handle_proxy_config@@ -147,9 +147,8 @@ class NodeExecutor:'whatsappSend': handle_whatsapp_send,'whatsappDb': handle_whatsapp_db,- # Telegram+ # Telegram (telegramReceive routed via generic handle_trigger_node)'telegramSend': handle_telegram_send,- 'telegramReceive': handle_telegram_receive,# Twitter/X'twitterSend': handle_twitter_send,'twitterSearch': handle_twitter_search,diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.pyindex f217d13d..fb5918b3 100644--- a/server/services/status_broadcaster.py+++ b/server/services/status_broadcaster.py@@ -96,6 +96,9 @@ class StatusBroadcaster:# Fetch Google Workspace status from stored OAuth tokensawait self._refresh_google_status()+ # Refresh Telegram status from stored token and auto-reconnect+ await self._refresh_telegram_status()+# Auto-reconnect Android relay if there's a stored sessionawait self._auto_reconnect_android_relay()@@ -328,6 +331,83 @@ class StatusBroadcaster:except Exception as e:logger.debug(f"[StatusBroadcaster] Could not refresh Google status: {e}")+ async def _refresh_telegram_status(self):+ """Refresh Telegram status from stored credentials and auto-reconnect.++ Called on client connect. If bot has a stored token and isn't connected,+ attempts auto-reconnect (mirrors the Android relay reconnect pattern).+ """+ try:+ from services.telegram_service import get_telegram_service+ service = get_telegram_service()++ # If already connected, just sync status cache+ if service.connected:+ status = service.get_status()+ self._status["telegram"] = {+ "connected": True,+ "bot_id": status.get("bot_id"),+ "bot_username": status.get("bot_username"),+ "bot_name": status.get("bot_name"),+ "owner_chat_id": status.get("owner_chat_id"),+ "has_stored_token": True,+ }+ logger.debug(f"[StatusBroadcaster] Telegram already connected: @{status.get('bot_username')}")+ return++ # Not connected - check for stored token+ from core.container import container+ auth_service = container.auth_service()+ stored_token = await auth_service.get_api_key("telegram_bot_token")++ if not stored_token:+ self._status["telegram"] = {+ "connected": False,+ "bot_id": None,+ "bot_username": None,+ "bot_name": None,+ "owner_chat_id": None,+ "has_stored_token": False,+ }+ return++ # Has stored token but not connected - auto-reconnect+ logger.info("[StatusBroadcaster] Auto-reconnecting Telegram bot...")+ result = await service.connect(stored_token)++ if result.get("success"):+ # Restore owner_chat_id from credentials+ try:+ saved_owner = await auth_service.get_api_key("telegram_owner_chat_id")+ if saved_owner:+ await service.set_owner(int(saved_owner))+ except Exception:+ pass++ status = service.get_status()+ self._status["telegram"] = {+ "connected": True,+ "bot_id": status.get("bot_id"),+ "bot_username": status.get("bot_username"),+ "bot_name": status.get("bot_name"),+ "owner_chat_id": status.get("owner_chat_id"),+ "has_stored_token": True,+ }+ logger.info(f"[StatusBroadcaster] Telegram auto-reconnected: @{status.get('bot_username')}")+ else:+ self._status["telegram"] = {+ "connected": False,+ "bot_id": None,+ "bot_username": None,+ "bot_name": None,+ "owner_chat_id": None,+ "has_stored_token": True,+ }+ logger.warning(f"[StatusBroadcaster] Telegram auto-reconnect failed: {result.get('error')}")++ except Exception as e:+ logger.debug(f"[StatusBroadcaster] Could not refresh Telegram status: {e}")+async def _auto_reconnect_android_relay(self):"""Auto-reconnect to Android relay if there's a stored pairing session.diff --git a/server/services/telegram_service.py b/server/services/telegram_service.pyindex 3a92c1a9..1da76ae0 100644--- a/server/services/telegram_service.py+++ b/server/services/telegram_service.py@@ -11,7 +11,9 @@ from datetime import datetimefrom typing import Any, Dict, Optionalfrom telegram import Bot, Update+from telegram.error import BadRequestfrom telegram.ext import Application, ContextTypes, MessageHandler, filters+from telegram.helpers import escape_markdownlogger = logging.getLogger(__name__)@@ -171,6 +173,7 @@ class TelegramService:self._connected = Falseself._polling_task = Noneself._owner_chat_id = None+ self._bot_info = {}# Broadcast disconnected statusawait self._broadcast_status()@@ -218,20 +221,21 @@ class TelegramService:logger.info(f"[Telegram] Owner detected: @{msg.from_user.username} (ID: {msg.from_user.id})")# Persist to credentials DB so it survives reconnectstry:- from services.auth import get_auth_service- auth = get_auth_service()- await auth.store_api_key("telegram_owner_chat_id", str(msg.from_user.id))+ from core.container import container+ auth = container.auth_service()+ await auth.store_api_key("telegram_owner_chat_id", str(msg.from_user.id), models=[])except Exception as persist_err:logger.warning(f"[Telegram] Failed to persist owner chat_id: {persist_err}")await self._broadcast_status()event_data = self._format_message(msg)- logger.debug(f"[Telegram] Message received: {event_data.get('content_type')} from {event_data.get('from_username', event_data.get('from_id'))}")+ logger.info(f"[Telegram] Message received: {event_data.get('content_type')} from {event_data.get('from_username', event_data.get('from_id'))}, chat_type={event_data.get('chat_type')}")# Dispatch to event_waiter for trigger nodesfrom services import event_waiter- event_waiter.dispatch("telegram_message_received", event_data)+ resolved = event_waiter.dispatch("telegram_message_received", event_data)+ logger.info(f"[Telegram] Dispatched to {resolved} waiter(s)")except Exception as e:logger.error(f"[Telegram] Message handler error: {e}")@@ -328,6 +332,22 @@ class TelegramService:# Send Methods# =========================================================================+ @staticmethod+ def _escape_text(text: str, parse_mode: Optional[str]) -> str:+ """Escape reserved characters for the given parse mode.++ MarkdownV2 reserves: _ * [ ] ( ) ~ ` > # + - = | { } . !+ Markdown (v1) reserves: _ * ` [+ HTML: no escaping needed (Telegram handles it).+ """+ if not text or not parse_mode:+ return text+ if parse_mode == "MarkdownV2":+ return escape_markdown(text, version=2)+ if parse_mode == "Markdown":+ return escape_markdown(text, version=1)+ return text+async def send_message(self,chat_id: str | int,@@ -351,13 +371,29 @@ class TelegramService:if not self._bot:raise ValueError("Telegram bot not connected")- msg = await self._bot.send_message(- chat_id=chat_id,- text=text,- parse_mode=parse_mode if parse_mode else None,- disable_notification=disable_notification,- reply_to_message_id=reply_to_message_id,- )+ effective_pm = parse_mode if parse_mode else None+ safe_text = self._escape_text(text, effective_pm)++ try:+ msg = await self._bot.send_message(+ chat_id=chat_id,+ text=safe_text,+ parse_mode=effective_pm,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+ except BadRequest as e:+ if "can't parse entities" in str(e).lower() and effective_pm:+ logger.warning(f"[Telegram] Parse mode {effective_pm} failed, sending as plain text")+ msg = await self._bot.send_message(+ chat_id=chat_id,+ text=text,+ parse_mode=None,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+ else:+ raisereturn {"message_id": msg.message_id,@@ -391,14 +427,31 @@ class TelegramService:if not self._bot:raise ValueError("Telegram bot not connected")- msg = await self._bot.send_photo(- chat_id=chat_id,- photo=photo,- caption=caption,- parse_mode=parse_mode if parse_mode else None,- disable_notification=disable_notification,- reply_to_message_id=reply_to_message_id,- )+ effective_pm = parse_mode if parse_mode else None+ safe_caption = self._escape_text(caption, effective_pm) if caption else caption++ try:+ msg = await self._bot.send_photo(+ chat_id=chat_id,+ photo=photo,+ caption=safe_caption,+ parse_mode=effective_pm,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+ except BadRequest as e:+ if "can't parse entities" in str(e).lower() and effective_pm:+ logger.warning(f"[Telegram] Parse mode {effective_pm} failed for photo caption, sending as plain text")+ msg = await self._bot.send_photo(+ chat_id=chat_id,+ photo=photo,+ caption=caption,+ parse_mode=None,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+ else:+ raisereturn {"message_id": msg.message_id,@@ -431,14 +484,31 @@ class TelegramService:if not self._bot:raise ValueError("Telegram bot not connected")- msg = await self._bot.send_document(- chat_id=chat_id,- document=document,- caption=caption,- parse_mode=parse_mode if parse_mode else None,- disable_notification=disable_notification,- reply_to_message_id=reply_to_message_id,- )+ effective_pm = parse_mode if parse_mode else None+ safe_caption = self._escape_text(caption, effective_pm) if caption else caption++ try:+ msg = await self._bot.send_document(+ chat_id=chat_id,+ document=document,+ caption=safe_caption,+ parse_mode=effective_pm,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+ except BadRequest as e:+ if "can't parse entities" in str(e).lower() and effective_pm:+ logger.warning(f"[Telegram] Parse mode {effective_pm} failed for document caption, sending as plain text")+ msg = await self._bot.send_document(+ chat_id=chat_id,+ document=document,+ caption=caption,+ parse_mode=None,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+ else:+ raisereturn {"message_id": msg.message_id,diff --git a/server/skills/social_agent/whatsapp-db-skill/SKILL.md b/server/skills/social_agent/whatsapp-db-skill/SKILL.mdindex ecc24c3f..36412be8 100644--- a/server/skills/social_agent/whatsapp-db-skill/SKILL.md+++ b/server/skills/social_agent/whatsapp-db-skill/SKILL.md@@ -39,13 +39,24 @@ Query contacts, groups, channels, and chat history.| phones | string | For check_contacts | Comma-separated phone numbers || participant_limit | int | No | Max participants (for get_group_info, 1-100) || channel_jid | string | For channel ops | Newsletter JID or invite link URL (e.g., `120363198765432101@newsletter` or `https://whatsapp.com/channel/...`) |-| refresh | boolean | No | Force refresh from server (for list_channels, get_channel_info) |+| refresh | boolean | No | Force refresh from server (for list_channels, get_channel_info, channel_messages) || channel_count | int | No | Number of items to fetch (for channel_messages, channel_stats) || before_server_id | int | No | Pagination cursor (for channel_messages) |+| message_offset | int | No | Skip this many messages (for channel_messages) |+| since | string | No | Unix timestamp - messages after this time (for channel_messages) |+| until | string | No | Unix timestamp - messages before this time (for channel_messages) |+| media_type | string | No | Filter by media type: image, video, audio, document, sticker (for channel_messages) |+| search | string | No | Text search within messages (for channel_messages) |+| include_media_data | boolean | No | Download base64 media data for media messages (for chat_history, channel_messages) || channel_name | string | For channel_create | Name of the new channel || channel_description | string | No | Description (for channel_create) |+| picture | string | No | Base64-encoded profile picture (for channel_create) || mute | boolean | For channel_mute | True to mute, false to unmute |-| server_ids | string | For channel_mark_viewed | Comma-separated message server IDs to mark as viewed |+| server_ids | string | For mark_viewed/live_updates | Comma-separated message server IDs |+| react_server_id | int | For newsletter_react | Server ID of message to react to |+| reaction | string | For newsletter_react | Reaction emoji (empty to remove) |+| profile_pic_jid | string | For contact_profile_pic | JID or phone number |+| preview | boolean | No | Get low-res preview (for contact_profile_pic) |### Operations@@ -59,13 +70,16 @@ Query contacts, groups, channels, and chat history.| `check_contacts` | Check WhatsApp registration | phones || `list_channels` | List subscribed newsletter channels | refresh (optional), limit || `get_channel_info` | Get channel details | channel_jid |-| `channel_messages` | Get channel message history | channel_jid, channel_count |+| `channel_messages` | Get channel messages with filters (date, media type, search) | channel_jid, channel_count || `channel_stats` | Get channel subscriber/view stats | channel_jid || `channel_follow` | Follow/subscribe to a channel | channel_jid || `channel_unfollow` | Unfollow/unsubscribe from a channel | channel_jid || `channel_create` | Create a new newsletter channel | channel_name || `channel_mute` | Mute or unmute a channel | channel_jid, mute || `channel_mark_viewed` | Mark channel messages as viewed | channel_jid, server_ids |+| `newsletter_react` | React to a channel message | channel_jid, react_server_id, reaction |+| `newsletter_live_updates` | Subscribe to live view/reaction counts | channel_jid, server_ids |+| `contact_profile_pic` | Get contact/group profile picture | profile_pic_jid |### Limits@@ -358,6 +372,58 @@ Get channel details using an invite link instead of JID.}```+### channel_messages (with filters)++Get channel messages filtered by media type and date range.++```json+{+ "operation": "channel_messages",+ "channel_jid": "120363198765432101@newsletter",+ "channel_count": 20,+ "media_type": "image",+ "since": "1704067200",+ "include_media_data": true+}+```++### channel_messages (text search)++Search channel messages by text content.++```json+{+ "operation": "channel_messages",+ "channel_jid": "120363198765432101@newsletter",+ "search": "announcement",+ "channel_count": 10+}+```++### newsletter_react++React to a channel message with an emoji.++```json+{+ "operation": "newsletter_react",+ "channel_jid": "120363198765432101@newsletter",+ "react_server_id": 42,+ "reaction": "\ud83d\udc4d"+}+```++### contact_profile_pic++Get a contact's profile picture.++```json+{+ "operation": "contact_profile_pic",+ "profile_pic_jid": "919876543210"+}+```+## Common Workflows### Find and message someone by name