Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Add SimpleMemory markdown-based short/long-term memory and ConsolePanel enhancements
trohitgad13548388c2
diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.ymlnew file mode 100644index 00000000..06dccd77--- /dev/null+++ b/.github/workflows/npm-publish.yml@@ -0,0 +1,63 @@+# Publish to npm registry when a release is created+# Also publishes to GitHub Packages as a mirror+#+# NOTE: npm now requires Granular Access Tokens (classic tokens revoked)+# - Granular tokens require 2FA and expire after 90 days max+# - Create token at: https://www.npmjs.com/settings/YOUR_USERNAME/tokens+# - Select "Granular Access Token" with publish permissions for this package+# - Add as NPM_TOKEN secret in GitHub repo settings+# - Remember to rotate before expiry (max 90 days)++name: Publish to npm++on:+ release:+ types: [published]+ # Allow manual trigger for token rotation testing+ workflow_dispatch:++jobs:+ publish-npm:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ registry-url: 'https://registry.npmjs.org'++ - name: Install dependencies+ run: npm ci++ - name: Build client+ run: cd client && npm ci && npm run build++ - name: Publish to npm+ run: npm publish --access public+ env:+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}++ publish-gpr:+ runs-on: ubuntu-latest+ permissions:+ contents: read+ packages: write+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ registry-url: 'https://npm.pkg.github.com/'++ - name: Install dependencies+ run: npm ci++ - name: Build client+ run: cd client && npm ci && npm run build++ - name: Publish to GitHub Packages+ run: npm publish+ env:+ NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}diff --git a/.npmignore b/.npmignorenew file mode 100644index 00000000..1898b3d4--- /dev/null+++ b/.npmignore@@ -0,0 +1,89 @@+# Git+.git/+.gitignore+.github/++# Environment & secrets+.env+.env.*+!.env.template+*.db+*.sqlite+*.db-journal+*.db-shm+*.db-wal+data/++# Python virtual environment+.venv/+venv/+__pycache__/+*.pyc+*.pyo+*.egg-info/++# Node modules (installed on user's machine)+node_modules/+**/node_modules/+client/node_modules/+server/whatsapp-rpc/node_modules/++# Vite cache+**/.vite/+client/.vite/++# IDE & editors+.vscode/+.idea/+*.sw?+*.suo+*.ntvs*+*.njsproj+*.sln++# OS files+.DS_Store+Thumbs.db++# Build artifacts & logs+*.log+*.tmp+*.temp+logs/+build/++# Test files+__tests__/+*.test.ts+*.test.js+*.spec.ts+*.spec.js+coverage/++# Internal documentation+docs-internal/+CLAUDE.md+.claude/++# Duplicate folder+MachinaOS/++# WhatsApp session data+server/whatsapp-rpc/.wwebjs_*/+server/whatsapp-rpc/session/+server/whatsapp-rpc/qr_*.png+server/whatsapp-rpc/*.db+server/whatsapp-rpc/data/+server/whatsapp-rpc/bin/++# Server data directories+server/data/+server/*.db++# Credentials (should never be committed anyway)+**/credentials.json+**/secrets.json+**/apikeys.json+**/*.pem+**/*.key+**/*.crtdiff --git a/bin/cli.js b/bin/cli.jsnew file mode 100644index 00000000..3525a0a6--- /dev/null+++ b/bin/cli.js@@ -0,0 +1,159 @@+#!/usr/bin/env node++import { spawn, execSync } from 'child_process';+import { existsSync, copyFileSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const ROOT_DIR = resolve(__dirname, '..');++const COMMANDS = {+ start: 'Start the development server',+ stop: 'Stop all running services',+ build: 'Build the project for production',+ 'docker:up': 'Start with Docker Compose',+ 'docker:down': 'Stop Docker Compose services',+ 'docker:logs': 'View Docker logs',+ init: 'Initialize environment file from template',+ help: 'Show this help message',+};++function printHelp() {+ console.log(`+MachinaOS - Workflow Automation Platform++Usage: machinaos <command>++Commands:+${Object.entries(COMMANDS)+ .map(([cmd, desc]) => ` ${cmd.padEnd(14)} ${desc}`)+ .join('\n')}++Examples:+ machinaos init # Create .env from template+ machinaos start # Start development server+ machinaos docker:up # Start with Docker++Documentation: https://github.com/trohitg/MachinaOS+`);+}++function checkDependencies() {+ const missing = [];++ // Check Node.js version+ const nodeVersion = process.version.slice(1).split('.')[0];+ if (parseInt(nodeVersion) < 18) {+ console.error(`Error: Node.js 18+ required (found ${process.version})`);+ process.exit(1);+ }++ // Check Python+ try {+ execSync('python --version', { stdio: 'pipe' });+ } catch {+ missing.push('Python 3.11+');+ }++ // Check uv (Python package manager)+ try {+ execSync('uv --version', { stdio: 'pipe' });+ } catch {+ missing.push('uv (install: curl -LsSf https://astral.sh/uv/install.sh | sh)');+ }++ if (missing.length > 0) {+ console.error('Missing dependencies:');+ missing.forEach((dep) => console.error(` - ${dep}`));+ console.error('\nPlease install the missing dependencies and try again.');+ process.exit(1);+ }+}++function initEnv() {+ const envPath = resolve(ROOT_DIR, 'server', '.env');+ const templatePath = resolve(ROOT_DIR, '.env.template');++ if (existsSync(envPath)) {+ console.log('.env file already exists at server/.env');+ return;+ }++ if (!existsSync(templatePath)) {+ console.error('Error: .env.template not found');+ process.exit(1);+ }++ copyFileSync(templatePath, envPath);+ console.log('Created server/.env from template');+ console.log('Edit server/.env to configure your API keys and settings');+}++function runNpmScript(script) {+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';+ const child = spawn(npm, ['run', script], {+ cwd: ROOT_DIR,+ stdio: 'inherit',+ shell: true,+ });++ child.on('error', (err) => {+ console.error(`Failed to run: ${err.message}`);+ process.exit(1);+ });++ child.on('close', (code) => {+ process.exit(code || 0);+ });+}++// Main+const [, , command = 'help'] = process.argv;++switch (command) {+ case 'help':+ case '--help':+ case '-h':+ printHelp();+ break;++ case 'init':+ initEnv();+ break;++ case 'start':+ checkDependencies();+ if (!existsSync(resolve(ROOT_DIR, 'server', '.env'))) {+ console.log('No .env found. Running init first...');+ initEnv();+ }+ runNpmScript('start');+ break;++ case 'stop':+ runNpmScript('stop');+ break;++ case 'build':+ runNpmScript('build');+ break;++ case 'docker:up':+ runNpmScript('docker:up');+ break;++ case 'docker:down':+ runNpmScript('docker:down');+ break;++ case 'docker:logs':+ runNpmScript('docker:logs');+ break;++ default:+ console.error(`Unknown command: ${command}`);+ printHelp();+ process.exit(1);+}diff --git a/client/package.json b/client/package.jsonindex 4d3fe4cd..1c324634 100644--- a/client/package.json+++ b/client/package.json@@ -21,6 +21,7 @@"react": "^19.1.1","react-dom": "^19.1.1","react-js-cron": "^5.2.0",+ "react-markdown": "^10.1.0","react-simple-code-editor": "^0.14.1","reactflow": "^11.11.4","styled-components": "^6.1.19",diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 6d1787ec..8dd2c15d 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -53,8 +53,10 @@ import { useWebSocket } from './contexts/WebSocketContext';import { useTheme } from './contexts/ThemeContext';import {sanitizeNodesForComparison,- sanitizeEdgesForComparison+ sanitizeEdgesForComparison,+ generateWorkflowId} from './utils/workflow';+import { importWorkflowFromFile } from './utils/workflowExport';import 'reactflow/dist/style.css';@@ -404,15 +406,22 @@ const DashboardContent: React.FC = () => {className = 'memory-active';}}- // Tool connection highlights during tool-related phases+ // Tool connection highlights when the specific tool node is executing+ // Only highlight the edge whose source (tool node) is actually being usedelse if (isToolConnection) {- if (phase === 'invoking_llm' || phase === 'building_graph') {+ const toolNodeStatus = sourceStatus?.status;+ if (toolNodeStatus === 'executing') {+ // This specific tool is being executed - highlight its edgeclassName = 'tool-active';+ } else if ((phase === 'invoking_llm' || phase === 'building_graph') && toolNodeStatus === 'success') {+ // Tool completed successfully - keep edge showing success+ className = 'completed';}}- // Skill connection highlights during skill-related phases (Chat Agent)+ // Skill connection highlights during skill loading phase (Chat Agent)+ // Skills provide context to LLM, so highlight only when loading skillselse if (isSkillConnection) {- if (phase === 'invoking_llm' || phase === 'loading_skills') {+ if (phase === 'loading_skills') {className = 'skill-active';}}@@ -688,8 +697,6 @@ const DashboardContent: React.FC = () => {const file = (e.target as HTMLInputElement).files?.[0];if (!file) return;- const { importWorkflowFromFile } = await import('./utils/workflowExport');- const { generateWorkflowId } = await import('./utils/workflow');const importedWorkflow = await importWorkflowFromFile(file);const workflow = {@@ -1095,6 +1102,7 @@ const DashboardContent: React.FC = () => {<ConsolePanelisOpen={consolePanelOpen}onToggle={() => setConsolePanelOpen(prev => !prev)}+ nodes={nodes}/>{/* Parameter Panels */}diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex 9a2f6a6c..2c869d06 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -65,8 +65,9 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {subtitle: 'Skill-based Agent',accentColor: '#3B82F6',bottomHandles: [- { id: 'input-skill', label: 'Skill', position: '35%' },- { id: 'input-tools', label: 'Tool', position: '65%' },+ { id: 'input-memory', label: 'Memory', position: '25%' },+ { id: 'input-skill', label: 'Skill', position: '50%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },],},};diff --git a/client/src/components/ParameterRenderer.tsx b/client/src/components/ParameterRenderer.tsxindex d045eca8..3d0f6ce5 100644--- a/client/src/components/ParameterRenderer.tsx+++ b/client/src/components/ParameterRenderer.tsx@@ -6,6 +6,7 @@ import CodeEditor from './ui/CodeEditor';import DynamicParameterService from '../services/dynamicParameterService';import { useAppStore } from '../store/useAppStore';import { ANDROID_SERVICE_NODE_TYPES } from '../nodeDefinitions/androidServiceNodes';+import { nodeDefinitions } from '../nodeDefinitions';import { useAppTheme } from '../hooks/useAppTheme';import { API_CONFIG } from '../config/api';import { useWebSocket } from '../contexts/WebSocketContext';@@ -932,7 +933,6 @@ const ParameterRenderer: React.FC<ParameterRendererProps> = ({try {// Get the node definition to access methods- const { nodeDefinitions } = await import('../nodeDefinitions');const nodeType = selectedNode.data?.nodeType || selectedNode.type;const nodeDef = nodeType ? nodeDefinitions[nodeType] : null;diff --git a/client/src/components/ToolkitNode.tsx b/client/src/components/ToolkitNode.tsxindex 342e6c12..bcfaa2c0 100644--- a/client/src/components/ToolkitNode.tsx+++ b/client/src/components/ToolkitNode.tsx@@ -89,10 +89,43 @@ const ToolkitNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta// Get the node color from definition or use Android greenconst nodeColor = definition?.defaults?.color || '#3DDC84';+ // Helper to check if string is emoji+ const isEmoji = (str: string): boolean => {+ const emojiRegex = /^(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(?:\u200D(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u;+ return emojiRegex.test(str);+ };++ // Helper to render icon (handles URLs, emojis, and icon names)+ const renderIcon = (icon: string) => {+ // Handle image URLs and data URIs+ if (icon.startsWith('http') || icon.startsWith('data:') || icon.startsWith('/')) {+ return (+ <img+ src={icon}+ alt="icon"+ style={{+ width: '28px',+ height: '28px',+ objectFit: 'contain',+ borderRadius: '4px'+ }}+ />+ );+ }++ // If it's already an emoji, return it directly+ if (isEmoji(icon)) {+ return icon;+ }++ // Fallback+ return icon;+ };+// Get icon from definitionconst getIcon = () => {if (definition?.icon) {- return definition.icon;+ return renderIcon(definition.icon);}return '📱'; // Default Android icon};diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex 37f62069..7473759d 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -77,8 +77,11 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({// Check if this is a skill node with code editor (needs similar flex layout)const isSkillNode = SKILL_NODE_TYPES.includes(nodeDefinition.name) && nodeDefinition.name !== 'customSkill';+ // Check if this is a memory node with markdown editor+ const isMemoryNode = nodeDefinition.name === 'simpleMemory';+// Nodes that need flexible code editor layout- const needsCodeEditorLayout = isCodeExecutorNode || isSkillNode;+ const needsCodeEditorLayout = isCodeExecutorNode || isSkillNode || isMemoryNode;// Check if this is a tool node that supports schema editingconst isToolNode = TOOL_NODE_TYPES.includes(nodeDefinition.name);diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsxindex 26d570f9..5b47426d 100644--- a/client/src/components/ui/ConsolePanel.tsx+++ b/client/src/components/ui/ConsolePanel.tsx@@ -9,18 +9,25 @@*/import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react';+import { Node } from 'reactflow';import { useWebSocket, ConsoleLogEntry } from '../../contexts/WebSocketContext';import { useAppTheme } from '../../hooks/useAppTheme';import { useTheme } from '../../contexts/ThemeContext';import Prism from 'prismjs';import 'prismjs/components/prism-json';+// Node types that can be targeted by chat messages+const CHAT_TRIGGER_TYPES = ['chatTrigger'];+// Node types that produce console output+const CONSOLE_NODE_TYPES = ['console'];+interface ConsolePanelProps {isOpen: boolean;onToggle: () => void;defaultHeight?: number;minHeight?: number;maxHeight?: number;+ nodes?: Node[]; // Workflow nodes for dropdown selection}// Storage keys for persisting state@@ -32,11 +39,26 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({onToggle,defaultHeight = 250,minHeight = 100,- maxHeight = 600+ maxHeight = 600,+ nodes = []}) => {const theme = useAppTheme();const { isDarkMode } = useTheme();const { consoleLogs, clearConsoleLogs, terminalLogs, clearTerminalLogs, sendChatMessage, chatMessages, clearChatMessages } = useWebSocket();++ // Filter nodes to get chatTrigger and console nodes+ const chatTriggerNodes = useMemo(() =>+ nodes.filter(n => CHAT_TRIGGER_TYPES.includes(n.type || '')),+ [nodes]+ );+ const consoleNodes = useMemo(() =>+ nodes.filter(n => CONSOLE_NODE_TYPES.includes(n.type || '')),+ [nodes]+ );++ // Selected node states (stored as node ID, empty string means "all")+ const [selectedChatTriggerId, setSelectedChatTriggerId] = useState<string>('');+ const [selectedConsoleId, setSelectedConsoleId] = useState<string>('');const [filter, setFilter] = useState('');const [terminalFilter, setTerminalFilter] = useState('');const [terminalLogLevel, setTerminalLogLevel] = useState<'all' | 'error' | 'warning' | 'info' | 'debug'>('all');@@ -191,16 +213,27 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({};}, [isHorizontalResizing]);- // Filter console logs based on search input+ // Filter console logs based on search input and selected console nodeconst filteredLogs = useMemo(() => {- if (!filter) return consoleLogs;- const lowerFilter = filter.toLowerCase();- return consoleLogs.filter(log =>- log.label.toLowerCase().includes(lowerFilter) ||- log.formatted.toLowerCase().includes(lowerFilter) ||- log.node_id.toLowerCase().includes(lowerFilter)- );- }, [consoleLogs, filter]);+ let logs = consoleLogs;++ // Filter by selected console node (if one is selected)+ if (selectedConsoleId) {+ logs = logs.filter(log => log.node_id === selectedConsoleId);+ }++ // Filter by search text+ if (filter) {+ const lowerFilter = filter.toLowerCase();+ logs = logs.filter(log =>+ log.label.toLowerCase().includes(lowerFilter) ||+ log.formatted.toLowerCase().includes(lowerFilter) ||+ log.node_id.toLowerCase().includes(lowerFilter)+ );+ }++ return logs;+ }, [consoleLogs, filter, selectedConsoleId]);// Filter terminal logs based on search input and log levelconst filteredTerminalLogs = useMemo(() => {@@ -254,14 +287,15 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({setIsSending(true);try {- await sendChatMessage(message);+ // Pass selected chatTrigger node ID if one is selected (empty string means broadcast to all)+ await sendChatMessage(message, selectedChatTriggerId || undefined);setChatInput('');} catch (error) {console.error('Failed to send chat message:', error);} finally {setIsSending(false);}- }, [chatInput, isSending, sendChatMessage]);+ }, [chatInput, isSending, sendChatMessage, selectedChatTriggerId]);// Handle Enter key in chat inputconst handleChatKeyDown = useCallback((e: React.KeyboardEvent) => {@@ -450,10 +484,10 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({border: 'none',cursor: 'pointer',padding: '2px 6px',- borderRadius: '4px',- fontSize: '10px',+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,color: theme.colors.textSecondary,- transition: 'background-color 0.15s ease'+ transition: theme.transitions.fast};const clearButtonStyle: React.CSSProperties = {@@ -464,15 +498,28 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({const filterInputStyle: React.CSSProperties = {padding: '2px 6px',- fontSize: '10px',+ fontSize: theme.fontSize.xs,backgroundColor: isDarkMode ? theme.dracula.background : theme.colors.background,border: `1px solid ${theme.colors.border}`,- borderRadius: '4px',+ borderRadius: theme.borderRadius.sm,color: theme.colors.text,width: '100px',outline: 'none'};+ // Shared select/dropdown style using theme+ const selectStyle: React.CSSProperties = {+ padding: '2px 4px',+ fontSize: theme.fontSize.xs,+ backgroundColor: isDarkMode ? theme.dracula.currentLine : theme.colors.background,+ color: theme.colors.text,+ border: `1px solid ${isDarkMode ? theme.dracula.selection : theme.colors.border}`,+ borderRadius: theme.borderRadius.sm,+ cursor: 'pointer',+ outline: 'none',+ maxWidth: '120px'+ };+const logEntryStyle: React.CSSProperties = {display: 'flex',padding: '4px 12px',@@ -483,14 +530,14 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({const timestampStyle: React.CSSProperties = {color: isDarkMode ? theme.dracula.comment : theme.colors.textMuted,- fontSize: '11px',+ fontSize: theme.fontSize.xs,whiteSpace: 'nowrap',minWidth: '90px'};const labelStyle: React.CSSProperties = {color: isDarkMode ? theme.dracula.yellow : theme.colors.warning,- fontSize: '12px',+ fontSize: theme.fontSize.sm,fontWeight: theme.fontWeight.medium,minWidth: '80px',maxWidth: '120px',@@ -500,8 +547,8 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({};const nodeInfoStyle: React.CSSProperties = {- color: isDarkMode ? theme.dracula.pink : '#db2777',- fontSize: '11px',+ color: isDarkMode ? theme.dracula.pink : theme.colors.categoryTrigger,+ fontSize: theme.fontSize.xs,fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace',minWidth: '80px',maxWidth: '120px',@@ -584,8 +631,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({const chatMessageTextStyle: React.CSSProperties = {fontSize: theme.fontSize.xs,color: theme.colors.text,- margin: 0,- whiteSpace: 'pre-wrap'+ margin: 0};const chatMessageTimeStyle: React.CSSProperties = {@@ -646,18 +692,37 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({{/* Chat Section - Left */}<div style={chatSectionStyle}><div style={sectionHeaderStyle}>- <span style={sectionTitleStyle}>- Chat- {chatMessages && chatMessages.length > 0 && (- <span style={{- ...badgeStyle,- backgroundColor: isDarkMode ? `${theme.dracula.green}40` : `${theme.colors.success}20`,- color: isDarkMode ? theme.dracula.green : theme.colors.success- }}>- {chatMessages.length}- </span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={sectionTitleStyle}>+ Chat+ {chatMessages && chatMessages.length > 0 && (+ <span style={{+ ...badgeStyle,+ backgroundColor: isDarkMode ? `${theme.dracula.green}40` : `${theme.colors.success}20`,+ color: isDarkMode ? theme.dracula.green : theme.colors.success+ }}>+ {chatMessages.length}+ </span>+ )}+ </span>+ {/* ChatTrigger node selector dropdown */}+ {chatTriggerNodes.length > 0 && (+ <select+ value={selectedChatTriggerId}+ onChange={e => setSelectedChatTriggerId(e.target.value)}+ onClick={e => e.stopPropagation()}+ style={selectStyle}+ title="Select chatTrigger node to target"+ >+ <option value="">All Triggers</option>+ {chatTriggerNodes.map(node => (+ <option key={node.id} value={node.id}>+ {node.data?.label || node.id}+ </option>+ ))}+ </select>)}- </span>+ </div>{chatMessages && chatMessages.length > 0 && (<buttonstyle={clearButtonStyle}@@ -682,7 +747,17 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({<div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>{chatMessages.map((msg, index) => (<div key={`${msg.timestamp}-${index}`} style={chatMessageStyle(msg.role === 'user')}>- <p style={chatMessageTextStyle}>{msg.message}</p>+ <pre style={{+ ...chatMessageTextStyle,+ margin: 0,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ lineHeight: 1.15,+ fontFamily: 'inherit',+ fontSize: 'inherit'+ }}>+ {msg.message}+ </pre><div style={chatMessageTimeStyle}>{formatTimestamp(msg.timestamp)}</div>@@ -791,16 +866,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({value={terminalLogLevel}onChange={e => setTerminalLogLevel(e.target.value as 'all' | 'error' | 'warning' | 'info' | 'debug')}onClick={e => e.stopPropagation()}- style={{- padding: '2px 4px',- fontSize: '10px',- backgroundColor: isDarkMode ? theme.dracula.currentLine : theme.colors.background,- color: theme.colors.text,- border: `1px solid ${isDarkMode ? theme.dracula.selection : theme.colors.border}`,- borderRadius: '4px',- cursor: 'pointer',- outline: 'none'- }}+ style={selectStyle}><option value="all">All Levels</option><option value="error">Error</option>@@ -809,6 +875,23 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({<option value="debug">Debug+</option></select>)}+ {/* Console node selector dropdown */}+ {consoleTab === 'console' && consoleNodes.length > 0 && (+ <select+ value={selectedConsoleId}+ onChange={e => setSelectedConsoleId(e.target.value)}+ onClick={e => e.stopPropagation()}+ style={selectStyle}+ title="Filter logs by Console node"+ >+ <option value="">All Consoles</option>+ {consoleNodes.map(node => (+ <option key={node.id} value={node.id}>+ {node.data?.label || node.id}+ </option>+ ))}+ </select>+ )}<inputtype="text"placeholder="Filter..."@@ -823,8 +906,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({display: 'flex',alignItems: 'center',gap: '3px',- cursor: 'pointer',- fontSize: '10px'+ cursor: 'pointer'}}><input@@ -843,12 +925,9 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({alignItems: 'center',gap: '3px',cursor: 'pointer',- fontSize: '10px',backgroundColor: prettyPrint? (isDarkMode ? `${theme.dracula.cyan}30` : `${theme.colors.info}20`)- : 'transparent',- padding: '2px 6px',- borderRadius: '4px'+ : 'transparent'}}title="Format JSON and convert escaped newlines">@@ -877,7 +956,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({)}</div></div>- <div style={{ flex: 1, overflow: 'auto', fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace', fontSize: '12px' }}>+ <div style={{ flex: 1, overflow: 'auto', fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace', fontSize: theme.fontSize.sm }}>{consoleTab === 'console' ? (// Console Logs TabfilteredLogs.length === 0 ? (@@ -920,7 +999,10 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({overflow: 'auto',color: getFormatColor(log.format),whiteSpace: 'pre-wrap',- wordBreak: 'break-word'+ wordBreak: 'break-word',+ lineHeight: 1.15,+ fontFamily: 'inherit',+ fontSize: 'inherit'}}>{formatted}@@ -953,25 +1035,25 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({}}><span style={{color: isDarkMode ? theme.dracula.comment : theme.colors.textMuted,- fontSize: '11px'+ fontSize: theme.fontSize.xs}}>{formatTimestamp(log.timestamp)}</span>{log.source && (<span style={{color: isDarkMode ? theme.dracula.cyan : theme.colors.info,- fontSize: '11px',- marginLeft: '8px'+ fontSize: theme.fontSize.xs,+ marginLeft: theme.spacing.sm}}>[{log.source}]</span>)}<span style={{color: theme.colors.text,- fontSize: '12px',- marginLeft: '8px'+ fontSize: theme.fontSize.sm,+ marginLeft: theme.spacing.sm}}>{log.message}{log.details && (- <span style={{ color: isDarkMode ? theme.dracula.comment : theme.colors.textMuted, marginLeft: '8px' }}>+ <span style={{ color: isDarkMode ? theme.dracula.comment : theme.colors.textMuted, marginLeft: theme.spacing.sm }}>{typeof log.details === 'string' ? log.details : JSON.stringify(log.details)}</span>)}diff --git a/client/src/components/ui/TopToolbar.tsx b/client/src/components/ui/TopToolbar.tsxindex a682b621..e572b150 100644--- a/client/src/components/ui/TopToolbar.tsx+++ b/client/src/components/ui/TopToolbar.tsx@@ -402,7 +402,7 @@ const TopToolbar: React.FC<TopToolbarProps> = ({padding: '2px',border: `1px solid ${theme.colors.border}`,}}- title={proMode ? 'Pro mode: All components visible' : 'Simple mode: Only AI components'}+ title={proMode ? 'Dev mode: All components visible' : 'Normal mode: Only AI components'}><buttononClick={() => !proMode ? undefined : onToggleProMode()}@@ -412,7 +412,7 @@ const TopToolbar: React.FC<TopToolbarProps> = ({alignItems: 'center',gap: '4px',backgroundColor: !proMode ? `${theme.dracula.green}25` : 'transparent',- color: !proMode ? theme.dracula.green : theme.accent.base0,+ color: !proMode ? theme.dracula.green : theme.dracula.orange,border: !proMode ? `1px solid ${theme.dracula.green}60` : '1px solid transparent',borderRadius: theme.borderRadius.sm,fontSize: theme.fontSize.xs,@@ -426,7 +426,7 @@ const TopToolbar: React.FC<TopToolbarProps> = ({<circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>- Simple+ Normal</button><buttononClick={() => proMode ? undefined : onToggleProMode()}@@ -436,7 +436,7 @@ const TopToolbar: React.FC<TopToolbarProps> = ({alignItems: 'center',gap: '4px',backgroundColor: proMode ? `${theme.dracula.purple}25` : 'transparent',- color: proMode ? theme.dracula.purple : theme.accent.base0,+ color: proMode ? theme.dracula.purple : theme.dracula.orange,border: proMode ? `1px solid ${theme.dracula.purple}60` : '1px solid transparent',borderRadius: theme.borderRadius.sm,fontSize: theme.fontSize.xs,@@ -449,7 +449,7 @@ const TopToolbar: React.FC<TopToolbarProps> = ({<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>- Pro+ Dev</button></div></div>diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex f75eac69..18e39bc3 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -198,7 +198,7 @@ interface WebSocketContextValue {clearConsoleLogs: () => void;clearTerminalLogs: () => void;clearChatMessages: () => void;- sendChatMessage: (message: string, sessionId?: string) => Promise<void>;+ sendChatMessage: (message: string, nodeId?: string) => Promise<void>;// Generic request methodsendRequest: <T = any>(type: string, data?: Record<string, any>) => Promise<T>;@@ -917,6 +917,39 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi} catch {// Ignore errors loading terminal logs}++ // Load chat message history from database+ try {+ const chatResponse = await new Promise<any>((resolve, reject) => {+ const requestId = `chat_messages_${Date.now()}`;+ const timeout = setTimeout(() => reject(new Error('Timeout')), 5000);++ const handler = (event: MessageEvent) => {+ try {+ const msg = JSON.parse(event.data);+ if (msg.request_id === requestId) {+ clearTimeout(timeout);+ ws.removeEventListener('message', handler);+ resolve(msg);+ }+ } catch {}+ };++ ws.addEventListener('message', handler);+ ws.send(JSON.stringify({ type: 'get_chat_messages', session_id: 'default', request_id: requestId }));+ });++ if (chatResponse.success && chatResponse.messages) {+ const messages: ChatMessage[] = chatResponse.messages.map((msg: any) => ({+ role: msg.role as 'user' | 'assistant',+ message: msg.message,+ timestamp: msg.timestamp+ }));+ setChatMessages(messages);+ }+ } catch {+ // Ignore errors loading chat messages+ }};ws.onmessage = handleMessage;@@ -1026,9 +1059,14 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}}, []);- // Clear chat messages+ // Clear chat messages (both local state and database)+ // Uses direct WebSocket send to avoid dependency on sendRequest (which is defined later)const clearChatMessages = useCallback(() => {setChatMessages([]);+ // Also clear from database via direct WebSocket send+ if (wsRef.current?.readyState === WebSocket.OPEN) {+ wsRef.current.send(JSON.stringify({ type: 'clear_chat_messages', session_id: 'default' }));+ }}, []);// Derive current workflow's node statuses (n8n pattern)@@ -1090,24 +1128,26 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Chat Message Operations// =========================================================================- // Send chat message (triggers chatTrigger nodes)- const sendChatMessageAsync = useCallback(async (message: string, sessionId?: string): Promise<void> => {+ // Send chat message (triggers chatTrigger nodes and saves to database)+ // nodeId: optional specific chatTrigger node to target+ const sendChatMessageAsync = useCallback(async (message: string, nodeId?: string): Promise<void> => {const timestamp = new Date().toISOString();const chatMessage: ChatMessage = {role: 'user',message,- timestamp,- session_id: sessionId || 'default'+ timestamp};// Add to local messages immediately for UI feedbacksetChatMessages(prev => [...prev, chatMessage]);- // Send to backend to dispatch to chatTrigger nodes+ // Send to backend to dispatch to chatTrigger nodes (also saves to database)try {await sendRequest('send_chat_message', {message,- session_id: sessionId || 'default',+ role: 'user',+ node_id: nodeId, // Target specific chatTrigger node if specified+ session_id: 'default',timestamp});} catch (error) {diff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.tsindex ae7e6a4a..ab1ced09 100644--- a/client/src/nodeDefinitions/aiAgentNodes.ts+++ b/client/src/nodeDefinitions/aiAgentNodes.ts@@ -170,6 +170,12 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {type: 'main' as NodeConnectionType,description: 'Chat input'},+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },{name: 'skill',displayName: 'Skill',@@ -253,21 +259,21 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {},// Simple Memory Node - conversation history storage for AI agents- // No run button - memory is accessed automatically when AI Agent runs+ // Markdown-based memory visible and editable in UIsimpleMemory: {displayName: 'Simple Memory',name: 'simpleMemory',icon: '🧠',group: ['skill', 'memory'], // 'skill' = appears in AI Skills categoryversion: 1,- description: 'Store conversation history for AI agents',+ description: 'Markdown-based conversation memory with optional vector DB for long-term retrieval',defaults: { name: 'Memory', color: '#8b5cf6' },inputs: [], // No input - memory node is passiveoutputs: [{name: 'memory',displayName: 'Memory',type: 'main' as NodeConnectionType,- description: 'session_id, messages, message_count, memory_type'+ description: 'session_id, messages, message_count'}],properties: [{@@ -276,18 +282,7 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {type: 'string',default: 'default',required: true,- description: 'Unique identifier for conversation session. Use different IDs for separate conversations.'- },- {- displayName: 'Memory Type',- name: 'memoryType',- type: 'options',- default: 'buffer',- options: [- { name: 'Buffer (All Messages)', value: 'buffer' },- { name: 'Window (Last N)', value: 'window' }- ],- description: 'Buffer keeps all messages, Window keeps only the last N messages'+ description: 'Unique identifier for conversation session'},{displayName: 'Window Size',@@ -295,10 +290,37 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {type: 'number',default: 10,typeOptions: { minValue: 1, maxValue: 100 },- description: 'Number of recent messages to keep (for Window type)',+ description: 'Number of message pairs to keep in short-term memory'+ },+ {+ displayName: 'Conversation History',+ name: 'memoryContent',+ type: 'string',+ default: '# Conversation History\n\n*No messages yet.*\n',+ typeOptions: {+ rows: 15,+ editor: 'code',+ editorLanguage: 'markdown'+ },+ description: 'Recent conversation history (editable)'+ },+ {+ displayName: 'Enable Long-Term Memory',+ name: 'longTermEnabled',+ type: 'boolean',+ default: false,+ description: 'Archive old messages to vector DB for semantic retrieval'+ },+ {+ displayName: 'Retrieval Count',+ name: 'retrievalCount',+ type: 'number',+ default: 3,+ typeOptions: { minValue: 1, maxValue: 10 },+ description: 'Number of relevant memories to retrieve from long-term storage',displayOptions: {show: {- memoryType: ['window']+ longTermEnabled: [true]}}}diff --git a/client/src/nodeDefinitions/locationNodes.ts b/client/src/nodeDefinitions/locationNodes.tsindex 782b3c10..0cf5e2d4 100644--- a/client/src/nodeDefinitions/locationNodes.ts+++ b/client/src/nodeDefinitions/locationNodes.ts@@ -45,7 +45,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {{ displayName: 'Center Latitude', name: 'lat', type: 'number', typeOptions: { minValue: -90, maxValue: 90, numberStepSize: 0.000001 }, default: 40.7128, required: true, description: 'Latitude for map center (decimal degrees)' },{ displayName: 'Center Longitude', name: 'lng', type: 'number', typeOptions: { minValue: -180, maxValue: 180, numberStepSize: 0.000001 }, default: -74.0060, required: true, description: 'Longitude for map center (decimal degrees)' },{ displayName: 'Zoom Level', name: 'zoom', type: 'number', typeOptions: { minValue: 0, maxValue: 21 }, default: 13, description: 'Map zoom level (0-21, where 21 is building level)' },- { displayName: 'Map Type', name: 'mapTypeId', type: 'options', options: [+ { displayName: 'Map Type', name: 'map_type_id', type: 'options', options: [{ name: 'Roadmap', value: 'ROADMAP' },{ name: 'Satellite', value: 'SATELLITE' },{ name: 'Hybrid', value: 'HYBRID' },@@ -60,35 +60,35 @@ export const locationNodes: Record<string, INodeTypeDescription> = {options: [{displayName: 'Disable Default UI',- name: 'disableDefaultUI',+ name: 'disable_default_ui',type: 'boolean',default: false,description: 'Disable default Google Maps UI controls'},{displayName: 'Zoom Control',- name: 'zoomControl',+ name: 'zoom_control',type: 'boolean',default: true,description: 'Enable zoom control buttons'},{displayName: 'Map Type Control',- name: 'mapTypeControl',+ name: 'map_type_control',type: 'boolean',default: true,description: 'Enable map type selection control'},{displayName: 'Street View Control',- name: 'streetViewControl',+ name: 'street_view_control',type: 'boolean',default: true,description: 'Enable street view control'},{displayName: 'Fullscreen Control',- name: 'fullscreenControl',+ name: 'fullscreen_control',type: 'boolean',default: true,description: 'Enable fullscreen control'@@ -98,12 +98,12 @@ export const locationNodes: Record<string, INodeTypeDescription> = {]},- // Add Locations - Google Maps Geocoding Service+ // Add Locations - Google Maps Geocoding Service (Dual-purpose: workflow node + AI tool)addLocations: {displayName: 'Add Locations',name: 'addLocations',icon: '🌍',- group: ['location', 'service'],+ group: ['location', 'service', 'tool'], // 'tool' enables AI Agent tool callingversion: 1,subtitle: 'Geocoding Service',description: 'Use Google Maps Geocoding Service for address-to-coordinates conversion and reverse geocoding with detailed location information',@@ -127,17 +127,17 @@ export const locationNodes: Record<string, INodeTypeDescription> = {displayName: 'Google Maps API Key'}],properties: [- { displayName: 'Service Type', name: 'serviceType', type: 'options', options: [+ { displayName: 'Service Type', name: 'service_type', type: 'options', options: [{ name: 'Geocoding (Address → LatLng)', value: 'geocode' },{ name: 'Reverse Geocoding (LatLng → Address)', value: 'reverse_geocode' }], default: 'geocode', required: true, description: 'Google Maps Geocoding service operation' },// Geocoding Request Parameters- { displayName: 'Address Query', name: 'address', type: 'string', default: '', placeholder: 'e.g., "1600 Amphitheatre Parkway, Mountain View, CA"', required: true, displayOptions: { show: { serviceType: ['geocode'] } }, description: 'The address to geocode' },+ { displayName: 'Address Query', name: 'address', type: 'string', default: '', placeholder: 'e.g., "1600 Amphitheatre Parkway, Mountain View, CA"', required: true, displayOptions: { show: { service_type: ['geocode'] } }, description: 'The address to geocode' },// Reverse Geocoding Parameters- { displayName: 'Location Latitude', name: 'lat', type: 'number', typeOptions: { minValue: -90, maxValue: 90, numberStepSize: 0.000001 }, default: 37.4224, required: true, displayOptions: { show: { serviceType: ['reverse_geocode'] } }, description: 'Latitude for reverse geocoding' },- { displayName: 'Location Longitude', name: 'lng', type: 'number', typeOptions: { minValue: -180, maxValue: 180, numberStepSize: 0.000001 }, default: -122.0842, required: true, displayOptions: { show: { serviceType: ['reverse_geocode'] } }, description: 'Longitude for reverse geocoding' },+ { displayName: 'Location Latitude', name: 'lat', type: 'number', typeOptions: { minValue: -90, maxValue: 90, numberStepSize: 0.000001 }, default: 37.4224, required: true, displayOptions: { show: { service_type: ['reverse_geocode'] } }, description: 'Latitude for reverse geocoding' },+ { displayName: 'Location Longitude', name: 'lng', type: 'number', typeOptions: { minValue: -180, maxValue: 180, numberStepSize: 0.000001 }, default: -122.0842, required: true, displayOptions: { show: { service_type: ['reverse_geocode'] } }, description: 'Longitude for reverse geocoding' },{displayName: 'Options',@@ -148,7 +148,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {options: [{displayName: 'Result Types',- name: 'resultTypes',+ name: 'result_types',type: 'multiOptions',options: [{ name: 'Street Address', value: 'street_address' },@@ -167,7 +167,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Location Types',- name: 'locationTypes',+ name: 'location_types',type: 'multiOptions',options: [{ name: 'Rooftop', value: 'ROOFTOP' },@@ -208,7 +208,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Component Restrictions',- name: 'componentRestrictions',+ name: 'component_restrictions',type: 'string',default: '',placeholder: 'e.g., "country:US|administrative_area:CA"',@@ -219,12 +219,12 @@ export const locationNodes: Record<string, INodeTypeDescription> = {]},- // Show Nearby Places - Google Maps Places API nearbySearch+ // Show Nearby Places - Google Maps Places API nearbySearch (Dual-purpose: workflow node + AI tool)showNearbyPlaces: {displayName: 'Show Nearby Places',name: 'showNearbyPlaces',icon: '🔍',- group: ['location', 'service'],+ group: ['location', 'service', 'tool'], // 'tool' enables AI Agent tool callingversion: 1,subtitle: 'Places API nearbySearch',description: 'Search for places near a location using Google Maps Places API nearbySearch with detailed place information in JSON format',@@ -378,7 +378,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Min Price Level',- name: 'minPrice',+ name: 'min_price',type: 'options',options: [{ name: 'Any', value: '' },@@ -393,7 +393,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Max Price Level',- name: 'maxPrice',+ name: 'max_price',type: 'options',options: [{ name: 'Any', value: '' },@@ -408,7 +408,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Open Now',- name: 'openNow',+ name: 'open_now',type: 'boolean',default: false,description: 'Only return places open at query time'@@ -436,7 +436,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Rank By',- name: 'rankBy',+ name: 'rank_by',type: 'options',options: [{ name: 'Prominence (Default)', value: 'prominence' },@@ -447,7 +447,7 @@ export const locationNodes: Record<string, INodeTypeDescription> = {},{displayName: 'Page Size',- name: 'pageSize',+ name: 'page_size',type: 'number',typeOptions: { minValue: 1, maxValue: 20 },default: 20,diff --git a/client/src/nodeDefinitions/skillNodes.ts b/client/src/nodeDefinitions/skillNodes.tsindex 89717d8a..8ccc8b3c 100644--- a/client/src/nodeDefinitions/skillNodes.ts+++ b/client/src/nodeDefinitions/skillNodes.ts@@ -3,6 +3,7 @@ import {INodeTypeDescription,NodeConnectionType} from '../types/INodeProperties';+import { WHATSAPP_CONNECT_ICON } from './whatsappNodes';// ============================================================================// SKILL NODES - Connect to Chat Agent's input-skill handle@@ -78,7 +79,7 @@ export const skillNodes: Record<string, INodeTypeDescription> = {whatsappSkill: createSkillNode({name: 'whatsappSkill',displayName: 'WhatsApp Skill',- icon: '💬',+ icon: WHATSAPP_CONNECT_ICON,color: '#25D366',skillName: 'whatsapp-skill',subtitle: 'Messaging',diff --git a/client/src/nodeDefinitions/whatsappNodes.ts b/client/src/nodeDefinitions/whatsappNodes.tsindex b65df24d..e736dc9d 100644--- a/client/src/nodeDefinitions/whatsappNodes.ts+++ b/client/src/nodeDefinitions/whatsappNodes.ts@@ -61,8 +61,8 @@ async function wsRequest(type: string, data: Record<string, unknown> = {}): Prom// WhatsApp Send - Paper plane (send message)const WHATSAPP_SEND_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M2.01 21L23 12 2.01 3 2 10l15 2-15 2z'/%3E%3C/svg%3E";-// WhatsApp Connect - Official WhatsApp logo-const WHATSAPP_CONNECT_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z'/%3E%3C/svg%3E";+// WhatsApp Connect - Official WhatsApp logo (exported for use in skill nodes)+export const WHATSAPP_CONNECT_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z'/%3E%3C/svg%3E";// WhatsApp Receive - Notification bell with dot (trigger node)const WHATSAPP_RECEIVE_ICON = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%2325D366'%3E%3Cpath d='M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z'/%3E%3Ccircle cx='18' cy='6' r='4'/%3E%3C/svg%3E";@@ -109,7 +109,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {// ===== RECIPIENT ====={displayName: 'Send To',- name: 'recipientType',+ name: 'recipient_type',type: 'options',options: [{ name: 'Phone Number', value: 'phone' },@@ -127,7 +127,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: '1234567890',description: 'Recipient phone number (without + prefix)',displayOptions: {- show: { recipientType: ['phone'] }+ show: { recipient_type: ['phone'] }}},{@@ -139,14 +139,14 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: '[email protected]',description: 'Group JID to send message to (use Load button to select)',displayOptions: {- show: { recipientType: ['group'] }+ show: { recipient_type: ['group'] }}},// ===== MESSAGE TYPE ====={displayName: 'Message Type',- name: 'messageType',+ name: 'message_type',type: 'options',options: [{ name: 'Text', value: 'text' },@@ -173,14 +173,14 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {description: 'Text message content',placeholder: 'Enter your message...',displayOptions: {- show: { messageType: ['text'] }+ show: { message_type: ['text'] }}},// ===== MEDIA MESSAGES (image, video, audio, document, sticker) ====={displayName: 'Media Source',- name: 'mediaSource',+ name: 'media_source',type: 'options',options: [{ name: 'Base64 Data', value: 'base64' },@@ -190,24 +190,24 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {default: 'base64',description: 'Source of media data',displayOptions: {- show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'] }+ show: { message_type: ['image', 'video', 'audio', 'document', 'sticker'] }}},{displayName: 'Media Data (Base64)',- name: 'mediaData',+ name: 'media_data',type: 'string',default: '',required: true,typeOptions: { rows: 3 },description: 'Base64-encoded media data',displayOptions: {- show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['base64'] }+ show: { message_type: ['image', 'video', 'audio', 'document', 'sticker'], media_source: ['base64'] }}},{displayName: 'File',- name: 'filePath',+ name: 'file_path',type: 'file',default: '',required: true,@@ -217,30 +217,30 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {accept: '*/*'},displayOptions: {- show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['file'] }+ show: { message_type: ['image', 'video', 'audio', 'document', 'sticker'], media_source: ['file'] }}},{displayName: 'Media URL',- name: 'mediaUrl',+ name: 'media_url',type: 'string',default: '',required: true,placeholder: 'https://example.com/image.jpg',description: 'URL to download media from',displayOptions: {- show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'], mediaSource: ['url'] }+ show: { message_type: ['image', 'video', 'audio', 'document', 'sticker'], media_source: ['url'] }}},{displayName: 'MIME Type',- name: 'mimeType',+ name: 'mime_type',type: 'string',default: '',placeholder: 'image/jpeg, video/mp4, audio/ogg',description: 'MIME type of the media (auto-detected if empty)',displayOptions: {- show: { messageType: ['image', 'video', 'audio', 'document', 'sticker'] }+ show: { message_type: ['image', 'video', 'audio', 'document', 'sticker'] }}},{@@ -251,7 +251,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {typeOptions: { rows: 2 },description: 'Optional caption for media',displayOptions: {- show: { messageType: ['image', 'video', 'document'] }+ show: { message_type: ['image', 'video', 'document'] }}},{@@ -262,7 +262,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: 'document.pdf',description: 'Filename for document',displayOptions: {- show: { messageType: ['document'] }+ show: { message_type: ['document'] }}},@@ -275,7 +275,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {required: true,description: 'Location latitude',displayOptions: {- show: { messageType: ['location'] }+ show: { message_type: ['location'] }}},{@@ -286,18 +286,18 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {required: true,description: 'Location longitude',displayOptions: {- show: { messageType: ['location'] }+ show: { message_type: ['location'] }}},{displayName: 'Location Name',- name: 'locationName',+ name: 'location_name',type: 'string',default: '',placeholder: 'San Francisco',description: 'Display name for location',displayOptions: {- show: { messageType: ['location'] }+ show: { message_type: ['location'] }}},{@@ -308,21 +308,21 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: 'California, USA',description: 'Address text',displayOptions: {- show: { messageType: ['location'] }+ show: { message_type: ['location'] }}},// ===== CONTACT MESSAGE ====={displayName: 'Contact Name',- name: 'contactName',+ name: 'contact_name',type: 'string',default: '',required: true,placeholder: 'John Doe',description: 'Display name for contact',displayOptions: {- show: { messageType: ['contact'] }+ show: { message_type: ['contact'] }}},{@@ -335,51 +335,51 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: 'BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nTEL:+1234567890\nEND:VCARD',description: 'vCard 3.0 format string',displayOptions: {- show: { messageType: ['contact'] }+ show: { message_type: ['contact'] }}},// ===== REPLY (QUOTE) ====={displayName: 'Reply To Message',- name: 'isReply',+ name: 'is_reply',type: 'boolean',default: false,description: 'Quote an existing message'},{displayName: 'Reply Message ID',- name: 'replyMessageId',+ name: 'reply_message_id',type: 'string',default: '',required: true,placeholder: 'ABC123DEF456',description: 'ID of message to reply to',displayOptions: {- show: { isReply: [true] }+ show: { is_reply: [true] }}},{displayName: 'Reply Sender',- name: 'replySender',+ name: 'reply_sender',type: 'string',default: '',required: true,placeholder: '[email protected]',description: 'Sender JID of quoted message',displayOptions: {- show: { isReply: [true] }+ show: { is_reply: [true] }}},{displayName: 'Reply Preview',- name: 'replyContent',+ name: 'reply_content',type: 'string',default: '',placeholder: 'Original message text...',description: 'Text preview of quoted message',displayOptions: {- show: { isReply: [true] }+ show: { is_reply: [true] }}}]@@ -677,7 +677,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {// ===== CHAT HISTORY PARAMETERS ====={displayName: 'Chat Type',- name: 'chatType',+ name: 'chat_type',type: 'options',options: [{ name: 'Individual Chat', value: 'individual' },@@ -698,7 +698,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: '1234567890',description: 'Phone number of the contact (without + prefix)',displayOptions: {- show: { operation: ['chat_history'], chatType: ['individual'] }+ show: { operation: ['chat_history'], chat_type: ['individual'] }}},{@@ -710,12 +710,12 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {placeholder: '[email protected]',description: 'Group JID',displayOptions: {- show: { operation: ['chat_history', 'get_group_info'], chatType: ['group'] }+ show: { operation: ['chat_history', 'get_group_info'], chat_type: ['group'] }}},{displayName: 'Message Filter',- name: 'groupFilter',+ name: 'group_filter',type: 'options',options: [{ name: 'All Messages', value: 'all' },@@ -724,23 +724,23 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {default: 'all',description: 'Filter messages in group',displayOptions: {- show: { operation: ['chat_history'], chatType: ['group'] }+ show: { operation: ['chat_history'], chat_type: ['group'] }}},{displayName: 'Sender Phone',- name: 'senderPhone',+ name: 'sender_phone',type: 'string',default: '',placeholder: '1234567890',description: 'Filter messages from specific group member',displayOptions: {- show: { operation: ['chat_history'], chatType: ['group'], groupFilter: ['contact'] }+ show: { operation: ['chat_history'], chat_type: ['group'], group_filter: ['contact'] }}},{displayName: 'Message Type',- name: 'messageFilter',+ name: 'message_filter',type: 'options',options: [{ name: 'All Types', value: 'all' },@@ -791,7 +791,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {// ===== GET GROUP INFO PARAMETERS ====={displayName: 'Group',- name: 'groupIdForInfo',+ name: 'group_id_for_info',type: 'string',default: '',required: true,@@ -805,7 +805,7 @@ export const whatsappNodes: Record<string, INodeTypeDescription> = {// ===== GET CONTACT INFO PARAMETERS ====={displayName: 'Phone Number',- name: 'contactPhone',+ name: 'contact_phone',type: 'string',default: '',required: true,diff --git a/client/src/utils/formatters.ts b/client/src/utils/formatters.tsindex fc2a3497..71563687 100644--- a/client/src/utils/formatters.ts+++ b/client/src/utils/formatters.ts@@ -1,4 +1,5 @@// Common utility functions for formatting and clipboard operations+import { message } from 'antd';/*** Copy text to clipboard with error handling@@ -8,8 +9,6 @@ export const copyToClipboard = async (data: any, successMessage?: string): Promiconst text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);await navigator.clipboard.writeText(text);if (successMessage) {- // Import message from antd dynamically to avoid circular dependencies- const { message } = await import('antd');message.success(successMessage);}return true;diff --git a/client/vite.config.js b/client/vite.config.jsindex 2092246f..3f89633f 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -27,5 +27,9 @@ export default defineConfig(({ mode }) => {strictPort: false,host: true},+ build: {+ // antd + reactflow are large libraries - this is expected+ chunkSizeWarningLimit: 1500,+ },}})diff --git a/package-lock.json b/package-lock.jsonindex bb4426d9..9e98496d 100644--- a/package-lock.json+++ b/package-lock.json@@ -28,6 +28,7 @@"react": "^19.1.1","react-dom": "^19.1.1","react-js-cron": "^5.2.0",+ "react-markdown": "^10.1.0","react-simple-code-editor": "^0.14.1","reactflow": "^11.11.4","styled-components": "^6.1.19",diff --git a/package.json b/package.jsonindex 3306c42e..6c786c0f 100644--- a/package.json+++ b/package.json@@ -1,8 +1,46 @@{- "name": "react-flow-project",- "private": true,- "version": "0.0.0",+ "name": "machinaos",+ "version": "0.0.1",+ "description": "Open source workflow automation platform with AI agents, React Flow, and n8n-inspired architecture","type": "module",+ "keywords": [+ "workflow",+ "automation",+ "react-flow",+ "ai-agent",+ "langchain",+ "langgraph",+ "n8n",+ "whatsapp",+ "android",+ "low-code",+ "no-code"+ ],+ "author": "Rohit G <[email protected]>",+ "license": "MIT",+ "homepage": "https://github.com/trohitg/MachinaOS#readme",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/trohitg/MachinaOS.git"+ },+ "bugs": {+ "url": "https://github.com/trohitg/MachinaOS/issues"+ },+ "bin": {+ "machinaos": "./bin/cli.js"+ },+ "files": [+ "bin/",+ "client/",+ "server/",+ "scripts/",+ "docker-compose.yml",+ "docker-compose.prod.yml",+ ".env.template"+ ],+ "engines": {+ "node": ">=18.0.0"+ },"workspaces": ["client"],@@ -10,19 +48,17 @@"dev": "concurrently --raw --kill-others-on-fail \"npm:client:dev\" \"npm:python:dev\" \"npm:whatsapp:api\"","dev:temporal": "concurrently --raw --kill-others-on-fail \"npm:client:dev\" \"npm:python:dev\" \"npm:whatsapp:api\" \"npm:temporal:worker\"","temporal:worker": "cd server && uv run python -m services.temporal.worker",- "client:dev": "cd client && set NO_COLOR=1&& npm run dev",+ "client:dev": "cd client && npm run dev","python:dev": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning","whatsapp:start": "cd server/whatsapp-rpc && npm start","whatsapp:stop": "cd server/whatsapp-rpc && npm stop","whatsapp:status": "cd server/whatsapp-rpc && npm run status","whatsapp:api": "cd server/whatsapp-rpc && npm run api","whatsapp:build": "cd server/whatsapp-rpc && npm run build",- "build": "node -e \"const fs=require('fs'),p='.env';if(!fs.existsSync(p))fs.copyFileSync('.env.template',p)\" && echo '[1/5] Installing root deps...' && npm ci && echo '[2/5] Building client...' && cd client && npm run build && echo '[3/5] Installing Python deps...' && cd ../server && uv venv && uv sync && echo '[4/5] Installing WhatsApp deps...' && cd whatsapp-rpc && npm ci && echo '[5/5] Building WhatsApp server...' && npm run build && echo 'Build complete.'",+ "build": "node scripts/build.js","clean": "node scripts/clean.js","start": "node scripts/start.js","stop": "node scripts/stop.js",- "restart": "node scripts/restart.js",- "status": "node scripts/status.js","docker:up": "node scripts/docker.js up","docker:down": "node scripts/docker.js down","docker:logs": "node scripts/docker.js logs",@@ -36,6 +72,8 @@"deploy:gcp": "bash deploy.sh"},"devDependencies": {- "concurrently": "^9.2.1"+ "concurrently": "^9.2.1",+ "cross-env": "^7.0.3",+ "rimraf": "^6.0.1"}}diff --git a/scripts/build.js b/scripts/build.jsnew file mode 100644index 00000000..e0a46905--- /dev/null+++ b/scripts/build.js@@ -0,0 +1,158 @@+#!/usr/bin/env node+/**+ * Cross-platform build script for MachinaOS.+ * Works on: Windows, macOS, Linux, WSL, Git Bash+ */+import { execSync } from 'child_process';+import { existsSync, copyFileSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');++// Ensure Python UTF-8 encoding+process.env.PYTHONUTF8 = '1';++function run(cmd, cwd = ROOT) {+ execSync(cmd, { cwd, stdio: 'inherit', shell: true });+}++function check(cmd) {+ try {+ execSync(cmd, { stdio: 'pipe', shell: true });+ return true;+ } catch {+ return false;+ }+}++function getVersion(cmd) {+ try {+ return execSync(cmd, { encoding: 'utf-8', shell: true }).trim();+ } catch {+ return null;+ }+}++function log(step, msg) {+ console.log(`[${step}] ${msg}`);+}++function npmInstall(cwd = ROOT) {+ // Try npm ci first (fast), fall back to npm install if lock file out of sync+ try {+ execSync('npm ci', { cwd, stdio: 'pipe', shell: true });+ } catch {+ execSync('npm install', { cwd, stdio: 'inherit', shell: true });+ }+}++// ============================================================================+// Check Dependencies+// ============================================================================++console.log('Checking dependencies...\n');++const missing = [];++// Node.js+const nodeVersion = getVersion('node --version');+if (nodeVersion) {+ console.log(` Node.js: ${nodeVersion}`);+} else {+ missing.push('Node.js - https://nodejs.org/');+}++// npm+const npmVersion = getVersion('npm --version');+if (npmVersion) {+ console.log(` npm: ${npmVersion}`);+} else {+ missing.push('npm - comes with Node.js');+}++// Python+let pyCmd = null;+if (check('python --version')) {+ pyCmd = 'python';+} else if (check('python3 --version')) {+ pyCmd = 'python3';+}+if (pyCmd) {+ const pyVersion = getVersion(`${pyCmd} --version`);+ console.log(` ${pyVersion}`);+} else {+ missing.push('Python 3.11+ - https://python.org/');+}++// uv (Python package manager)+const uvVersion = getVersion('uv --version');+if (uvVersion) {+ console.log(` uv: ${uvVersion}`);+} else {+ missing.push('uv - https://docs.astral.sh/uv/getting-started/installation/');+}++// Go (required for WhatsApp server)+const goVersionFull = getVersion('go version');+if (goVersionFull) {+ const goVersion = goVersionFull.match(/go\d+\.\d+(\.\d+)?/)?.[0] || 'go';+ console.log(` Go: ${goVersion}`);+} else {+ missing.push('Go - https://go.dev/dl/');+}++if (missing.length > 0) {+ console.error('\nMissing required dependencies:\n');+ for (const dep of missing) {+ console.error(` - ${dep}`);+ }+ console.error('\nPlease install the missing dependencies and try again.');+ process.exit(1);+}++console.log('\nAll dependencies found.\n');++// ============================================================================+// Build+// ============================================================================++try {+ // Step 0: Create .env if not exists+ const envPath = resolve(ROOT, '.env');+ const templatePath = resolve(ROOT, '.env.template');+ if (!existsSync(envPath) && existsSync(templatePath)) {+ copyFileSync(templatePath, envPath);+ log('0/5', 'Created .env from template');+ }++ // Step 1: Install root dependencies+ log('1/5', 'Installing root dependencies...');+ npmInstall(ROOT);++ // Step 2: Build client+ log('2/5', 'Building client...');+ run('npm run build', resolve(ROOT, 'client'));++ // Step 3: Install Python dependencies+ log('3/5', 'Installing Python dependencies...');+ const serverDir = resolve(ROOT, 'server');+ run('uv venv', serverDir);+ run('uv sync', serverDir);++ // Step 4: Install WhatsApp dependencies+ log('4/5', 'Installing WhatsApp dependencies...');+ const whatsappDir = resolve(ROOT, 'server/whatsapp-rpc');+ npmInstall(whatsappDir);++ // Step 5: Build WhatsApp server (Go binary)+ log('5/5', 'Building WhatsApp server...');+ run('npm run build', whatsappDir);++ console.log('\nBuild complete.');++} catch (err) {+ console.error('\nBuild failed:', err.message);+ process.exit(1);+}diff --git a/scripts/clean.js b/scripts/clean.jsindex efe712c5..6df45e4d 100644--- a/scripts/clean.js+++ b/scripts/clean.js@@ -1,6 +1,9 @@#!/usr/bin/env node-import { execSync } from 'child_process';-import { existsSync } from 'fs';+/**+ * Cross-platform clean script using Node.js native APIs.+ * Works on: Windows, macOS, Linux, WSL, Git Bash+ */+import { rmSync, existsSync } from 'fs';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';@@ -13,33 +16,24 @@ const targets = ['client/dist','client/.vite','server/whatsapp-rpc/node_modules',- 'server/whatsapp-rpc/dist',+ 'server/whatsapp-rpc/bin','server/whatsapp-rpc/data','server/data','server/.venv',];-process.chdir(ROOT);console.log('Cleaning...');-// Detect if running in WSL on Windows filesystem-const isWSL = process.platform === 'linux' && ROOT.startsWith('/mnt/');-const isWindows = process.platform === 'win32';-for (const target of targets) {- if (existsSync(target)) {+ const fullPath = resolve(ROOT, target);+ if (existsSync(fullPath)) {console.log(` Removing: ${target}`);try {- if (isWSL) {- // Use cmd.exe for WSL on /mnt/ - much faster- const winPath = target.replace(/\//g, '\\\\');- execSync(`cmd.exe /c "rmdir /s /q ${winPath}"`, { stdio: 'ignore' });- } else if (isWindows) {- execSync(`rmdir /s /q "${target}"`, { stdio: 'ignore' });- } else {- execSync(`rm -rf "${target}"`, { stdio: 'ignore' });- }- } catch {}+ // Node.js native rmSync - works cross-platform+ rmSync(fullPath, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });+ } catch (err) {+ console.log(` Warning: Could not remove ${target}: ${err.message}`);+ }}}diff --git a/scripts/restart.js b/scripts/restart.jsdeleted file mode 100644index 48930937..00000000--- a/scripts/restart.js+++ /dev/null@@ -1,21 +0,0 @@-#!/usr/bin/env node-import { execSync } from 'child_process';-import { fileURLToPath } from 'url';-import { dirname, join } from 'path';--const __dirname = dirname(fileURLToPath(import.meta.url));-const sleep = ms => new Promise(r => setTimeout(r, ms));--// Set Python UTF-8 encoding to avoid charmap errors on Windows-process.env.PYTHONUTF8 = '1';--console.log('Restarting all services...\n');--console.log('--- Stopping ---');-try { execSync(`node "${join(__dirname, 'stop.js')}"`, { stdio: 'inherit' }); } catch {}--console.log('\nWaiting 2s...\n');-await sleep(2000);--console.log('--- Starting ---');-execSync(`node "${join(__dirname, 'start.js')}"`, { stdio: 'inherit' });diff --git a/scripts/start.js b/scripts/start.jsindex b38b9d23..15ee9632 100644--- a/scripts/start.js+++ b/scripts/start.js@@ -1,35 +1,77 @@#!/usr/bin/env node-import { execSync, spawn, spawnSync } from 'child_process';-import { fileURLToPath } from 'url';-import { dirname, resolve } from 'path';+/**+ * Cross-platform start script for MachinaOS services.+ * Works on: Windows, macOS, Linux, WSL, Git Bash+ */+import { execSync, spawn } from 'child_process';import { readFileSync, existsSync, copyFileSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');-const START = Date.now();+const START_TIME = Date.now();-// Detect environment: Git Bash on Windows reports win32 but uses Unix commands-const isGitBash = process.platform === 'win32' && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));-const isWindows = process.platform === 'win32' && !isGitBash;+// ============================================================================+// Platform Detection+// ============================================================================+const isWindows = process.platform === 'win32';+const isGitBash = isWindows && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));const isMac = process.platform === 'darwin';+const useUnixCommands = !isWindows || isGitBash;++function getPlatformName() {+ if (isGitBash) return 'Git Bash';+ if (isWindows) return 'Windows';+ if (isMac) return 'macOS';+ return 'Linux';+}-// Timing helper-const elapsed = () => `${((Date.now() - START) / 1000).toFixed(2)}s`;+// ============================================================================+// Utilities+// ============================================================================++const elapsed = () => `${((Date.now() - START_TIME) / 1000).toFixed(2)}s`;const log = (msg) => console.log(`[${elapsed()}] ${msg}`);-// Load env config-function loadEnvConfig() {- const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');+function exec(cmd, options = {}) {+ try {+ return execSync(cmd, {+ encoding: 'utf-8',+ stdio: ['pipe', 'pipe', 'pipe'],+ timeout: options.timeout || 10000,+ cwd: ROOT,+ ...options+ }).trim();+ } catch {+ return '';+ }+}++function sleep(ms) {+ try {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+ } catch {+ const end = Date.now() + ms;+ while (Date.now() < end) { /* spin */ }+ }+}++function loadConfig() {+ const envPath = existsSync(resolve(ROOT, '.env'))+ ? resolve(ROOT, '.env')+ : resolve(ROOT, '.env.template');+const env = {};if (existsSync(envPath)) {- const content = readFileSync(envPath, 'utf-8');- for (const line of content.split('\n')) {+ for (const line of readFileSync(envPath, 'utf-8').split('\n')) {const match = line.match(/^([^#=]+)=(.*)$/);if (match) {- env[match[1].trim()] = match[2].trim();+ env[match[1].trim()] = match[2].trim().replace(/^["']|["']$/g, '');}}}+return {ports: [parseInt(env.VITE_CLIENT_PORT) || 3000,@@ -40,133 +82,77 @@ function loadEnvConfig() {};}-// Legacy function for backwards compatibility-function loadPorts() {- return loadEnvConfig().ports;-}+// ============================================================================+// Port Management+// ============================================================================-// Execute command and return output (suppressing errors)-function exec(cmd) {- try {- return execSync(cmd, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();- } catch {- return '';- }-}--// Get PIDs using a port - Windows-function getPidsWindows(port) {+function getPidsOnPort(port) {const pids = new Set();- const netstatOutput = exec(`netstat -ano | findstr :${port} | findstr LISTENING`);- for (const line of netstatOutput.split('\n')) {- const parts = line.trim().split(/\s+/);- const pid = parts[parts.length - 1];- if (pid && /^\d+$/.test(pid) && pid !== '0') {- pids.add(pid);- }- }- return Array.from(pids);-}-// Get PIDs using a port - Unix-function getPidsUnix(port) {- const pids = new Set();- const lsofOutput = exec(`lsof -ti:${port} -sTCP:LISTEN 2>/dev/null`);- for (const pid of lsofOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- pids.add(pid.trim());+ if (useUnixCommands) {+ const output = exec(`lsof -ti:${port} -sTCP:LISTEN 2>/dev/null`);+ for (const pid of output.split('\n')) {+ if (pid.trim() && /^\d+$/.test(pid.trim())) {+ pids.add(pid.trim());+ }}- }- // Fallback to ss on Linux- if (pids.size === 0 && !isMac) {- const ssOutput = exec(`ss -tlnp 2>/dev/null | grep :${port}`);- const matches = ssOutput.matchAll(/pid=(\d+)/g);- for (const match of matches) {- pids.add(match[1]);+ if (pids.size === 0 && !isMac && !isGitBash) {+ const ssOutput = exec(`ss -tlnp 2>/dev/null | grep :${port}`);+ for (const match of ssOutput.matchAll(/pid=(\d+)/g)) {+ pids.add(match[1]);+ }}- }- return Array.from(pids);-}--// Get child process PIDs - Windows-function getChildPidsWindows(parentPid) {- const children = new Set();- const wmicOutput = exec(`wmic process where (ParentProcessId=${parentPid}) get ProcessId 2>nul`);- for (const line of wmicOutput.split('\n')) {- const pid = line.trim();- if (pid && /^\d+$/.test(pid)) {- children.add(pid);- for (const grandchild of getChildPidsWindows(pid)) {- children.add(grandchild);+ } else {+ const output = exec(`netstat -ano | findstr :${port} | findstr LISTENING`);+ for (const line of output.split('\n')) {+ const parts = line.trim().split(/\s+/);+ const pid = parts[parts.length - 1];+ if (pid && /^\d+$/.test(pid) && pid !== '0') {+ pids.add(pid);}}}- return Array.from(children);++ return Array.from(pids);}-// Get child process PIDs - Unix-function getChildPidsUnix(parentPid) {- const children = new Set();- const pgrepOutput = exec(`pgrep -P ${parentPid} 2>/dev/null`);- for (const pid of pgrepOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- children.add(pid.trim());- for (const grandchild of getChildPidsUnix(pid.trim())) {- children.add(grandchild);- }- }+function killPid(pid) {+ if (useUnixCommands) {+ exec(`kill -15 ${pid} 2>/dev/null`);+ sleep(100);+ exec(`kill -9 ${pid} 2>/dev/null`);+ } else {+ exec(`taskkill /PID ${pid} /F 2>nul`);}- return Array.from(children);}-// Kill process by port thoroughly-function killPort(port) {- const getPids = isWindows ? getPidsWindows : getPidsUnix;- const getChildPids = isWindows ? getChildPidsWindows : getChildPidsUnix;-- let pids = getPids(port);- if (pids.length === 0) return false;+function freePort(port) {+ const pids = getPidsOnPort(port);+ if (pids.length === 0) return true;- // Collect all PIDs including children- const allPids = new Set(pids);for (const pid of pids) {- for (const childPid of getChildPids(pid)) {- allPids.add(childPid);- }+ killPid(pid);}+ sleep(500);- // Kill all processes (no /T flag to avoid killing parent shell)- for (const pid of allPids) {- if (isWindows) {- exec(`taskkill /PID ${pid} /F 2>nul`);- } else {- exec(`kill -9 ${pid} 2>/dev/null`);- }- }+ return getPidsOnPort(port).length === 0;+}- // Wait for processes to die- if (isWindows) {- exec('ping -n 2 127.0.0.1 >nul');- } else {- spawnSync('sleep', ['0.5'], { stdio: 'pipe' });- }+// ============================================================================+// Main+// ============================================================================- // Verify port is free- const remainingPids = getPids(port);- return remainingPids.length === 0;-}+const config = loadConfig();-const config = loadEnvConfig();-const PORTS = config.ports;+// Ensure Python UTF-8 encodingprocess.env.PYTHONUTF8 = '1';console.log('\n=== MachinaOS Starting ===\n');-const platformName = isWindows ? 'Windows' : isGitBash ? 'Git Bash' : isMac ? 'macOS' : 'Linux';-log(`Platform: ${platformName}`);-log(`Ports: ${PORTS.join(', ')}`);+log(`Platform: ${getPlatformName()}`);+log(`Ports: ${config.ports.join(', ')}`);log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);-// Step 1: Create .env if not exists+// Create .env if not existsconst envPath = resolve(ROOT, '.env');const templatePath = resolve(ROOT, '.env.template');if (!existsSync(envPath) && existsSync(templatePath)) {@@ -174,14 +160,13 @@ if (!existsSync(envPath) && existsSync(templatePath)) {log('Created .env from template');}-// Step 2: Free ports+// Free portslog('Freeing ports...');let allFree = true;-for (const port of PORTS) {- const getPids = isWindows ? getPidsWindows : getPidsUnix;- const pids = getPids(port);+for (const port of config.ports) {+ const pids = getPidsOnPort(port);if (pids.length > 0) {- const freed = killPort(port);+ const freed = freePort(port);if (freed) {log(` Port ${port}: Freed (killed PIDs: ${pids.join(', ')})`);} else {@@ -197,42 +182,29 @@ if (!allFree) {log('Warning: Some ports could not be freed. Services may fail to start.');}-// Step 3: Start dev server+// Start dev serverlog('Starting services...');-log('Press Ctrl+C to stop (use npm run stop to kill all services)');-log('');--// Build the dev command - conditionally include Temporal worker-const devCommand = config.temporalEnabled ? 'npm run dev:temporal' : 'npm run dev';--// On Git Bash/mintty, Ctrl+C doesn't propagate properly to Node.js child processes-// due to Cygwin pseudo-terminal limitations. The workaround is to run concurrently-// directly without a Node.js wrapper.-//-// This script's job is done - it freed ports and set up env.-// Now exec into npm run dev so the terminal controls it directly.--if (isGitBash) {- // For Git Bash: Use exec to replace this process with npm- // This way Ctrl+C goes directly to npm/concurrently, not through Node.js- const { execFileSync } = await import('child_process');- try {- // Use bash -c to run npm, replacing this process- execFileSync('bash', ['-c', `exec ${devCommand}`], {- cwd: ROOT,- stdio: 'inherit',- windowsHide: false- });- } catch {- // Normal exit from Ctrl+C- }-} else {- // For native Windows cmd or Unix: execSync works fine- try {- execSync(devCommand, { cwd: ROOT, stdio: 'inherit' });- } catch {- // Ctrl+C causes non-zero exit, which is normal- }-}--console.log('\nDev server stopped.');+log('Press Ctrl+C to stop (use npm run stop to kill all services)\n');++const devCommand = config.temporalEnabled ? 'dev:temporal' : 'dev';++// Use spawn with shell:true for cross-platform compatibility+const proc = spawn('npm', ['run', devCommand], {+ cwd: ROOT,+ stdio: 'inherit',+ shell: true,+ env: { ...process.env, FORCE_COLOR: '1' }+});++// Handle Ctrl+C gracefully+process.on('SIGINT', () => {+ proc.kill('SIGINT');+});+process.on('SIGTERM', () => {+ proc.kill('SIGTERM');+});++proc.on('close', (code) => {+ console.log('\nDev server stopped.');+ process.exit(code || 0);+});diff --git a/scripts/status.js b/scripts/status.jsdeleted file mode 100644index 63a9b223..00000000--- a/scripts/status.js+++ /dev/null@@ -1,60 +0,0 @@-#!/usr/bin/env node-import http from 'http';-import { readFileSync, existsSync } from 'fs';-import { resolve, dirname } from 'path';-import { fileURLToPath } from 'url';--const __dirname = dirname(fileURLToPath(import.meta.url));-const ROOT = resolve(__dirname, '..');--// Load ports from .env-function loadPorts() {- const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');- const content = readFileSync(envPath, 'utf-8');- const env = {};- for (const line of content.split('\n')) {- const [key, val] = line.split('=');- if (key && val) env[key.trim()] = val.trim();- }- return {- frontend: parseInt(env.VITE_CLIENT_PORT),- backend: parseInt(env.PYTHON_BACKEND_PORT),- whatsapp: parseInt(env.WHATSAPP_RPC_PORT)- };-}--const ports = loadPorts();--const SERVICES = [- { name: 'Frontend', port: ports.frontend },- { name: 'Python Backend', port: ports.backend, health: '/health' },- { name: 'WhatsApp RPC', port: ports.whatsapp }-];--const checkHealth = (port, path) => new Promise(resolve => {- const req = http.get(`http://localhost:${port}${path}`, { timeout: 2000 }, res => resolve(res.statusCode === 200));- req.on('error', () => resolve(false));- req.on('timeout', () => { req.destroy(); resolve(false); });-});--const checkPort = port => new Promise(resolve => {- const req = http.get(`http://localhost:${port}`, { timeout: 1000 }, () => resolve(true));- req.on('error', () => resolve(false));- req.on('timeout', () => { req.destroy(); resolve(false); });-});--console.log('Service Status\n' + '='.repeat(60));--for (const svc of SERVICES) {- const running = await checkPort(svc.port);- const healthy = svc.health && running ? await checkHealth(svc.port, svc.health) : null;-- let status = running ? 'RUNNING' : 'STOPPED';- if (healthy === true) status += ' (healthy)';- if (healthy === false) status += ' (unhealthy)';-- console.log(`${running ? '[OK]' : '[--]'} ${svc.name.padEnd(20)} Port ${svc.port.toString().padEnd(5)} ${status}`);-}--console.log('='.repeat(60));-console.log('\nCommands: npm run start | stop | restart | status');diff --git a/scripts/stop.js b/scripts/stop.jsindex 574cf5c7..b0f78069 100644--- a/scripts/stop.js+++ b/scripts/stop.js@@ -1,4 +1,11 @@#!/usr/bin/env node+/**+ * Cross-platform stop script for MachinaOS services.+ * Works on: Windows, macOS, Linux, WSL, Git Bash+ *+ * Uses Node.js native APIs where possible, with platform-specific+ * fallbacks for process management (no cross-platform alternative exists).+ */import { execSync } from 'child_process';import { readFileSync, existsSync } from 'fs';import { resolve, dirname } from 'path';@@ -7,47 +14,35 @@ import { fileURLToPath } from 'url';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');-// Detect environment: Git Bash on Windows reports win32 but uses Unix commands-const isGitBash = process.platform === 'win32' && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));-const isWindows = process.platform === 'win32' && !isGitBash;+// ============================================================================+// Platform Detection+// ============================================================================+const isWindows = process.platform === 'win32';+const isGitBash = isWindows && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));const isMac = process.platform === 'darwin';-// Load env config-function loadEnvConfig() {- const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');- const env = {};- if (existsSync(envPath)) {- const content = readFileSync(envPath, 'utf-8');- for (const line of content.split('\n')) {- const match = line.match(/^([^#=]+)=(.*)$/);- if (match) {- env[match[1].trim()] = match[2].trim();- }- }- }- return {- ports: [- parseInt(env.VITE_CLIENT_PORT) || 3000,- parseInt(env.PYTHON_BACKEND_PORT) || 3010,- parseInt(env.WHATSAPP_RPC_PORT) || 9400- ],- temporalEnabled: env.TEMPORAL_ENABLED?.toLowerCase() === 'true'- };-}+// Git Bash on Windows uses Unix commands+const useUnixCommands = !isWindows || isGitBash;-// Legacy function for backwards compatibility-function loadPorts() {- return loadEnvConfig().ports;+function getPlatformName() {+ if (isGitBash) return 'Git Bash';+ if (isWindows) return 'Windows';+ if (isMac) return 'macOS';+ return 'Linux';}-// Execute command and return output (suppressing errors)-// Added timeout to prevent hanging+// ============================================================================+// Utilities+// ============================================================================++/** Execute command silently, return output or empty string */function exec(cmd, options = {}) {try {return execSync(cmd, {encoding: 'utf-8',stdio: ['pipe', 'pipe', 'pipe'],- timeout: 10000, // 10 second timeout to prevent hanging+ timeout: options.timeout || 10000,+ cwd: ROOT,...options}).trim();} catch {@@ -55,313 +50,274 @@ function exec(cmd, options = {}) {}}-// Get PIDs using a port - Windows-function getPidsWindows(port) {- const pids = new Set();-- // Method 1: netstat (most reliable)- const netstatOutput = exec(`netstat -ano | findstr :${port} | findstr LISTENING`);- for (const line of netstatOutput.split('\n')) {- const parts = line.trim().split(/\s+/);- const pid = parts[parts.length - 1];- if (pid && /^\d+$/.test(pid) && pid !== '0') {- pids.add(pid);- }+/** Cross-platform sleep using Atomics (efficient, no busy wait) */+function sleep(ms) {+ try {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+ } catch {+ // Fallback for older Node.js+ const end = Date.now() + ms;+ while (Date.now() < end) { /* spin */ }}+}- // Method 2: PowerShell Get-NetTCPConnection (backup)- if (pids.size === 0) {- const psOutput = exec(`powershell -Command "Get-NetTCPConnection -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess"`);- for (const pid of psOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim()) && pid.trim() !== '0') {- pids.add(pid.trim());+/** Load config from .env file */+function loadConfig() {+ const envPath = existsSync(resolve(ROOT, '.env'))+ ? resolve(ROOT, '.env')+ : resolve(ROOT, '.env.template');++ const env = {};+ if (existsSync(envPath)) {+ for (const line of readFileSync(envPath, 'utf-8').split('\n')) {+ const match = line.match(/^([^#=]+)=(.*)$/);+ if (match) {+ env[match[1].trim()] = match[2].trim().replace(/^["']|["']$/g, '');}}}- return Array.from(pids);+ return {+ ports: [+ parseInt(env.VITE_CLIENT_PORT) || 3000,+ parseInt(env.PYTHON_BACKEND_PORT) || 3010,+ parseInt(env.WHATSAPP_RPC_PORT) || 9400+ ],+ temporalEnabled: env.TEMPORAL_ENABLED?.toLowerCase() === 'true'+ };}-// Get PIDs using a port - Unix (Linux/macOS)-function getPidsUnix(port) {- const pids = new Set();-- // Method 1: lsof (most common)- const lsofOutput = exec(`lsof -ti:${port} -sTCP:LISTEN 2>/dev/null`);- for (const pid of lsofOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- pids.add(pid.trim());- }- }+// ============================================================================+// Process Management (platform-specific - no cross-platform alternative)+// ============================================================================- // Method 2: ss (Linux, if lsof not available)- if (pids.size === 0 && !isMac) {- const ssOutput = exec(`ss -tlnp 2>/dev/null | grep :${port}`);- const matches = ssOutput.matchAll(/pid=(\d+)/g);- for (const match of matches) {- pids.add(match[1]);- }- }+/** Get PIDs listening on a port */+function getPidsOnPort(port) {+ const pids = new Set();- // Method 3: fuser (Linux fallback)- if (pids.size === 0 && !isMac) {- const fuserOutput = exec(`fuser ${port}/tcp 2>/dev/null`);- for (const pid of fuserOutput.split(/\s+/)) {+ if (useUnixCommands) {+ // lsof (macOS/Linux/Git Bash)+ const lsofOutput = exec(`lsof -ti:${port} -sTCP:LISTEN 2>/dev/null`);+ for (const pid of lsofOutput.split('\n')) {if (pid.trim() && /^\d+$/.test(pid.trim())) {pids.add(pid.trim());}}+ // ss fallback (Linux)+ if (pids.size === 0 && !isMac && !isGitBash) {+ const ssOutput = exec(`ss -tlnp 2>/dev/null | grep :${port}`);+ for (const match of ssOutput.matchAll(/pid=(\d+)/g)) {+ pids.add(match[1]);+ }+ }+ } else {+ // netstat (Windows native)+ const output = exec(`netstat -ano | findstr :${port} | findstr LISTENING`);+ for (const line of output.split('\n')) {+ const parts = line.trim().split(/\s+/);+ const pid = parts[parts.length - 1];+ if (pid && /^\d+$/.test(pid) && pid !== '0') {+ pids.add(pid);+ }+ }}return Array.from(pids);}-// Get child process PIDs - Windows-function getChildPidsWindows(parentPid) {+/** Get child PIDs recursively */+function getChildPids(parentPid) {const children = new Set();- const wmicOutput = exec(`wmic process where (ParentProcessId=${parentPid}) get ProcessId 2>nul`);- for (const line of wmicOutput.split('\n')) {- const pid = line.trim();- if (pid && /^\d+$/.test(pid)) {- children.add(pid);- // Recursively get grandchildren- for (const grandchild of getChildPidsWindows(pid)) {- children.add(grandchild);++ if (useUnixCommands) {+ const output = exec(`pgrep -P ${parentPid} 2>/dev/null`);+ for (const pid of output.split('\n')) {+ if (pid.trim() && /^\d+$/.test(pid.trim())) {+ children.add(pid.trim());+ for (const grandchild of getChildPids(pid.trim())) {+ children.add(grandchild);+ }}}- }- return Array.from(children);-}--// Get child process PIDs - Unix-function getChildPidsUnix(parentPid) {- const children = new Set();- // pgrep -P gets direct children- const pgrepOutput = exec(`pgrep -P ${parentPid} 2>/dev/null`);- for (const pid of pgrepOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- children.add(pid.trim());- // Recursively get grandchildren- for (const grandchild of getChildPidsUnix(pid.trim())) {- children.add(grandchild);+ } else {+ const output = exec(`wmic process where (ParentProcessId=${parentPid}) get ProcessId 2>nul`);+ for (const line of output.split('\n')) {+ const pid = line.trim();+ if (pid && /^\d+$/.test(pid)) {+ children.add(pid);+ for (const grandchild of getChildPids(pid)) {+ children.add(grandchild);+ }}}}- return Array.from(children);-}-// Kill a single PID - Windows-// NOTE: Removed /T flag (tree kill) as it can kill the parent PowerShell terminal-// Child processes are killed explicitly via getChildPidsWindows() instead-function killPidWindows(pid) {- // First try graceful termination (no /T)- exec(`taskkill /PID ${pid} 2>nul`);- // Then force kill (no /T)- exec(`taskkill /PID ${pid} /F 2>nul`);-}--// Cross-platform sleep using Atomics (efficient, no busy wait)-function sleepMs(ms) {- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+ return Array.from(children);}-// Kill a single PID - Unix-function killPidUnix(pid) {- // First try SIGTERM (graceful)- exec(`kill -15 ${pid} 2>/dev/null`);- // Give it a moment- sleepMs(100);- // Then SIGKILL (force)- exec(`kill -9 ${pid} 2>/dev/null`);+/** Check if process is running */+function isRunning(pid) {+ if (useUnixCommands) {+ return exec(`kill -0 ${pid} 2>&1 && echo running`).includes('running');+ } else {+ return exec(`tasklist /FI "PID eq ${pid}" 2>nul`).includes(pid);+ }}-// Check if process is still running-function isProcessRunning(pid) {- if (isWindows) {- const output = exec(`tasklist /FI "PID eq ${pid}" 2>nul`);- return output.includes(pid);+/** Kill a single process */+function killPid(pid) {+ if (useUnixCommands) {+ exec(`kill -15 ${pid} 2>/dev/null`);+ sleep(100);+ exec(`kill -9 ${pid} 2>/dev/null`);} else {- // Use kill -0 via exec (returns empty string on error = process dead)- const output = exec(`kill -0 ${pid} 2>&1 && echo "running"`);- return output.includes('running');+ exec(`taskkill /PID ${pid} 2>nul`);+ exec(`taskkill /PID ${pid} /F 2>nul`);}}-// Kill all processes on a port with verification+/** Kill all processes on a port */function killPort(port) {- const getPids = isWindows ? getPidsWindows : getPidsUnix;- const getChildPids = isWindows ? getChildPidsWindows : getChildPidsUnix;- const killPid = isWindows ? killPidWindows : killPidUnix;-- // Get all PIDs on this port- let pids = getPids(port);+ const pids = getPidsOnPort(port);if (pids.length === 0) {- return { killed: false, pids: [], portFree: true, message: 'Free' };+ return { killed: [], portFree: true };}// Collect all PIDs including childrenconst allPids = new Set(pids);for (const pid of pids) {- for (const childPid of getChildPids(pid)) {- allPids.add(childPid);+ for (const child of getChildPids(pid)) {+ allPids.add(child);}}- const pidsToKill = Array.from(allPids);- const killedPids = [];-- // Kill all processes- for (const pid of pidsToKill) {+ // Kill all+ for (const pid of allPids) {killPid(pid);}- // Wait a bit for processes to die- sleepMs(500);+ sleep(500);- // Verify which ones are actually dead- for (const pid of pidsToKill) {- if (!isProcessRunning(pid)) {- killedPids.push(pid);+ // Verify+ const killed = [];+ for (const pid of allPids) {+ if (!isRunning(pid)) {+ killed.push(pid);}}- // Retry for stubborn processes- const stillRunning = pidsToKill.filter(pid => isProcessRunning(pid));+ // Retry stubborn ones+ const stillRunning = Array.from(allPids).filter(pid => isRunning(pid));if (stillRunning.length > 0) {for (const pid of stillRunning) {- // Force kill again (no /T flag to avoid killing parent shell)- if (isWindows) {- exec(`taskkill /PID ${pid} /F 2>nul`);- } else {+ if (useUnixCommands) {exec(`kill -9 ${pid} 2>/dev/null`);+ } else {+ exec(`taskkill /PID ${pid} /F 2>nul`);}}-- // Final check- sleepMs(500);-+ sleep(500);for (const pid of stillRunning) {- if (!isProcessRunning(pid)) {- killedPids.push(pid);+ if (!isRunning(pid)) {+ killed.push(pid);}}}- // Final verification - check if port is actually free- const remainingPids = getPids(port);- const portFree = remainingPids.length === 0;-return {- killed: killedPids.length > 0,- pids: killedPids,- portFree,- message: portFree- ? (killedPids.length > 0 ? `Killed ${killedPids.length} process(es)` : 'Free')- : `Warning: Port still in use by PID(s): ${remainingPids.join(', ')}`+ killed,+ portFree: getPidsOnPort(port).length === 0};}-// Kill Temporal worker processes by command line pattern-function killTemporalWorkers() {- const killedPids = [];+/** Kill processes by command pattern */+function killByPattern(pattern, debug = false) {+ const killed = [];- if (isWindows) {- // Find Python processes running temporal worker (matches both python and uv run)- const wmicOutput = exec('wmic process where "CommandLine like \'%services.temporal.worker%\'" get ProcessId 2>nul');- for (const line of wmicOutput.split('\n')) {- const pid = line.trim();- if (pid && /^\d+$/.test(pid)) {- exec(`taskkill /PID ${pid} /F 2>nul`);- killedPids.push(pid);+ if (useUnixCommands) {+ const output = exec(`pgrep -f "${pattern}" 2>/dev/null`);+ if (debug && output) console.log(` [DEBUG] pgrep output: ${output}`);+ for (const pid of output.split('\n')) {+ if (pid.trim() && /^\d+$/.test(pid.trim())) {+ exec(`kill -9 ${pid.trim()} 2>/dev/null`);+ killed.push(pid.trim());}}} else {- // Unix: Use pgrep to find temporal worker processes (matches both python and uv run)- const pgrepOutput = exec('pgrep -f "services.temporal.worker" 2>/dev/null');- for (const pid of pgrepOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- exec(`kill -9 ${pid.trim()} 2>/dev/null`);- killedPids.push(pid.trim());+ // Use tasklist with image name filter first for Python processes+ if (pattern.includes('uvicorn') || pattern.includes('python')) {+ const pythonPids = exec(`wmic process where "name='python.exe'" get ProcessId,CommandLine 2>nul`);+ if (debug && pythonPids) console.log(` [DEBUG] Python processes:\n${pythonPids}`);++ for (const line of pythonPids.split('\n')) {+ if (line.toLowerCase().includes(pattern.toLowerCase().replace('.*', ''))) {+ const pidMatch = line.match(/(\d+)\s*$/);+ if (pidMatch) {+ const pid = pidMatch[1];+ exec(`taskkill /PID ${pid} /F 2>nul`);+ killed.push(pid);+ }+ }}}- }-- return killedPids;-}-// Kill uv/uvicorn processes-function killUvProcesses() {- const killedPids = [];-- if (isWindows) {- // Find uv/uvicorn processes- const wmicOutput = exec('wmic process where "CommandLine like \'%uvicorn%main:app%\'" get ProcessId 2>nul');- for (const line of wmicOutput.split('\n')) {+ // Also try the original pattern match+ const output = exec(`wmic process where "CommandLine like '%${pattern.replace('.*', '%')}%'" get ProcessId 2>nul`);+ if (debug && output) console.log(` [DEBUG] wmic pattern output: ${output}`);+ for (const line of output.split('\n')) {const pid = line.trim();- if (pid && /^\d+$/.test(pid)) {+ if (pid && /^\d+$/.test(pid) && !killed.includes(pid)) {exec(`taskkill /PID ${pid} /F 2>nul`);- killedPids.push(pid);- }- }- } else {- // Unix: Kill uv/uvicorn processes- const pgrepOutput = exec('pgrep -f "uvicorn.*main:app" 2>/dev/null');- for (const pid of pgrepOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- exec(`kill -9 ${pid.trim()} 2>/dev/null`);- killedPids.push(pid.trim());+ killed.push(pid);}}}- return killedPids;+ return killed;}-// Main execution-const config = loadEnvConfig();-const PORTS = config.ports;+// ============================================================================+// Main+// ============================================================================++const config = loadConfig();-console.log('Stopping MachinaOs services...\n');-const platformName = isWindows ? 'Windows' : isGitBash ? 'Git Bash' : isMac ? 'macOS' : 'Linux';-console.log(`Platform: ${platformName}`);-console.log(`Ports: ${PORTS.join(', ')}`);+console.log('Stopping MachinaOS services...\n');+console.log(`Platform: ${getPlatformName()}`);+console.log(`Ports: ${config.ports.join(', ')}`);console.log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}\n`);let allStopped = true;-for (const port of PORTS) {+// Stop services on ports+for (const port of config.ports) {const result = killPort(port);const status = result.portFree ? '[OK]' : '[!!]';- console.log(`${status} Port ${port}: ${result.message}`);- if (result.pids.length > 0) {- console.log(` PIDs: ${result.pids.join(', ')}`);+ const message = result.portFree+ ? (result.killed.length > 0 ? `Killed ${result.killed.length} process(es)` : 'Free')+ : 'Warning: Port still in use';++ console.log(`${status} Port ${port}: ${message}`);+ if (result.killed.length > 0) {+ console.log(` PIDs: ${result.killed.join(', ')}`);}if (!result.portFree) {allStopped = false;}}-// Kill uv/uvicorn processes that might not be on a specific port-const uvPids = killUvProcesses();-if (uvPids.length > 0) {- console.log(`[OK] uv/uvicorn: Killed ${uvPids.length} process(es)`);- console.log(` PIDs: ${uvPids.join(', ')}`);-}--// Kill Temporal workers if enabled+// Kill Temporal workers if enabled (must include project path)if (config.temporalEnabled) {- const temporalPids = killTemporalWorkers();+ const temporalPids = killByPattern(`${ROOT}.*temporal`);if (temporalPids.length > 0) {- console.log(`[OK] Temporal worker: Killed ${temporalPids.length} process(es)`);+ console.log(`[OK] Temporal: Killed ${temporalPids.length} process(es)`);console.log(` PIDs: ${temporalPids.join(', ')}`);- } else {- console.log(`[OK] Temporal worker: Not running`);}}console.log('');if (allStopped) {- console.log('All services stopped successfully.');+ console.log('All services stopped.');} else {console.log('Warning: Some ports may still be in use.');console.log('Try running the script again or manually kill the processes.');diff --git a/server/core/database.py b/server/core/database.pyindex a74a3e4a..3021027e 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -8,7 +8,7 @@ from sqlalchemy.exc import IntegrityErrorfrom contextlib import asynccontextmanagerfrom core.config import Settings-from models.database import NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput, ConversationMessage, ToolSchema, UserSkill+from models.database import NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput, ConversationMessage, ToolSchema, UserSkill, ChatMessagefrom models.cache import CacheEntry # SQLite-backed cache for Redis alternativefrom models.auth import User # Import User model to ensure table creationfrom core.logging import get_logger@@ -609,6 +609,105 @@ class Database:logger.error("Failed to get conversation sessions", error=str(e))return []+ # ============================================================================+ # Chat Messages (Console Panel persistence)+ # ============================================================================++ async def add_chat_message(self, session_id: str, role: str, message: str) -> bool:+ """Add a chat message to the console panel history."""+ try:+ async with self.get_session() as session:+ chat_msg = ChatMessage(+ session_id=session_id,+ role=role,+ message=message+ )+ session.add(chat_msg)+ await session.commit()+ logger.debug(f"[Chat] Added {role} message to session '{session_id}'")+ return True++ except Exception as e:+ logger.error("Failed to add chat message", session_id=session_id, error=str(e))+ return False++ async def get_chat_messages(self, session_id: str, limit: Optional[int] = None) -> List[Dict[str, Any]]:+ """Get chat messages for a session, optionally limited to last N."""+ try:+ async with self.get_session() as session:+ stmt = select(ChatMessage).where(+ ChatMessage.session_id == session_id+ ).order_by(ChatMessage.created_at.asc())++ result = await session.execute(stmt)+ messages = result.scalars().all()++ # Apply limit if specified+ if limit and limit > 0:+ messages = messages[-limit:]++ return [+ {+ "role": m.role,+ "message": m.message,+ "timestamp": m.created_at.isoformat()+ }+ for m in messages+ ]++ except Exception as e:+ logger.error("Failed to get chat messages", session_id=session_id, error=str(e))+ return []++ async def clear_chat_messages(self, session_id: str) -> int:+ """Clear all chat messages for a session. Returns count deleted."""+ try:+ async with self.get_session() as session:+ stmt = select(ChatMessage).where(+ ChatMessage.session_id == session_id+ )+ result = await session.execute(stmt)+ messages = result.scalars().all()++ count = len(messages)+ for message in messages:+ await session.delete(message)++ await session.commit()+ logger.info(f"[Chat] Cleared {count} messages from session '{session_id}'")+ return count++ except Exception as e:+ logger.error("Failed to clear chat messages", session_id=session_id, error=str(e))+ return 0++ async def get_chat_sessions(self) -> List[Dict[str, Any]]:+ """Get list of all chat sessions with message counts."""+ try:+ async with self.get_session() as session:+ from sqlalchemy import func as sa_func+ stmt = select(+ ChatMessage.session_id,+ sa_func.count(ChatMessage.id).label('message_count'),+ sa_func.max(ChatMessage.created_at).label('last_message_at')+ ).group_by(ChatMessage.session_id).order_by(sa_func.max(ChatMessage.created_at).desc())++ result = await session.execute(stmt)+ rows = result.all()++ return [+ {+ "session_id": row.session_id,+ "message_count": row.message_count,+ "last_message_at": row.last_message_at.isoformat() if row.last_message_at else None+ }+ for row in rows+ ]++ except Exception as e:+ logger.error("Failed to get chat sessions", error=str(e))+ return []+# ============================================================================# Cache Entries (SQLite-backed Redis alternative)# ============================================================================diff --git a/server/models/database.py b/server/models/database.pyindex ff3af4e6..0bb03dc1 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -161,6 +161,25 @@ class ToolSchema(SQLModel, table=True):)+class ChatMessage(SQLModel, table=True):+ """Chat panel messages - persisted across server restarts.++ Stores user and assistant messages from the chat panel (Console Panel chat section).+ These are separate from ConversationMessage which stores AI agent memory.+ """++ __tablename__ = "chat_messages"++ id: Optional[int] = Field(default=None, primary_key=True)+ session_id: str = Field(default="default", index=True, max_length=255)+ role: str = Field(max_length=20) # 'user' or 'assistant'+ message: str = Field(max_length=50000) # Large content support+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )++class UserSkill(SQLModel, table=True):"""User-created custom skills for Chat Agent.diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex f8afe601..726ada87 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1424,13 +1424,19 @@ async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -This handler receives messages from the frontend chat panel and dispatchesthem as 'chat_message_received' events to any waiting chatTrigger nodes.+ Also saves the message to database for persistence across restarts."""from services import event_waitermessage = data["message"]+ role = data.get("role", "user")session_id = data.get("session_id", "default")timestamp = data.get("timestamp") or datetime.now().isoformat()+ # Save to database for persistence+ database = container.database()+ await database.add_chat_message(session_id, role, message)+# Build event data matching chatTrigger output schemaevent_data = {"message": message,@@ -1446,7 +1452,67 @@ async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -return {"success": True,"message": "Chat message sent",- "resolved_count": resolved+ "resolved_count": resolved,+ "timestamp": timestamp+ }+++@ws_handler()+async def handle_get_chat_messages(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get chat messages from database for a session."""+ session_id = data.get("session_id", "default")+ limit = data.get("limit") # Optional limit++ database = container.database()+ messages = await database.get_chat_messages(session_id, limit)++ return {+ "success": True,+ "messages": messages,+ "session_id": session_id+ }+++@ws_handler()+async def handle_clear_chat_messages(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Clear all chat messages for a session."""+ session_id = data.get("session_id", "default")++ database = container.database()+ count = await database.clear_chat_messages(session_id)++ return {+ "success": True,+ "message": f"Cleared {count} chat messages",+ "cleared_count": count+ }+++@ws_handler("message", "role")+async def handle_save_chat_message(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save a single chat message (used for assistant responses)."""+ message = data["message"]+ role = data["role"]+ session_id = data.get("session_id", "default")++ database = container.database()+ success = await database.add_chat_message(session_id, role, message)++ return {+ "success": success,+ "message": "Chat message saved" if success else "Failed to save chat message"+ }+++@ws_handler()+async def handle_get_chat_sessions(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get list of all chat sessions."""+ database = container.database()+ sessions = await database.get_chat_sessions()++ return {+ "success": True,+ "sessions": sessions}@@ -1775,6 +1841,9 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {# Chat message (for chatTrigger nodes)"send_chat_message": handle_send_chat_message,+ "get_chat_messages": handle_get_chat_messages,+ "clear_chat_messages": handle_clear_chat_messages,+ "save_chat_message": handle_save_chat_message,# Terminal logs"get_terminal_logs": handle_get_terminal_logs,diff --git a/server/routers/whatsapp.py b/server/routers/whatsapp.pyindex a1567288..433729ba 100644--- a/server/routers/whatsapp.py+++ b/server/routers/whatsapp.py@@ -386,26 +386,26 @@ async def handle_whatsapp_send(params: dict) -> dict:Uses _send_lock to serialize sends - Go service processes sequentially.- Params from frontend node:- - recipientType: 'phone' or 'group'- - phone: recipient phone number (if recipientType='phone')- - group_id: group JID (if recipientType='group')- - messageType: text, image, video, audio, document, sticker, location, contact+ Params from frontend node (snake_case):+ - recipient_type: 'phone' or 'group'+ - phone: recipient phone number (if recipient_type='phone')+ - group_id: group JID (if recipient_type='group')+ - message_type: text, image, video, audio, document, sticker, location, contact- message: text content (for text type)- - mediaSource: base64, file, url (for media types)- - mediaData/filePath/mediaUrl: media content based on source- - mimeType, caption, filename: media options- - latitude, longitude, locationName, address: location data- - contactName, vcard: contact data- - isReply, replyMessageId, replySender, replyContent: reply context+ - media_source: base64, file, url (for media types)+ - media_data/file_path/media_url: media content based on source+ - mime_type, caption, filename: media options+ - latitude, longitude, location_name, address: location data+ - contact_name, vcard: contact data+ - is_reply, reply_message_id, reply_sender, reply_content: reply context"""async with _send_lock:try:# Build RPC params matching schema.jsonrpc_params: dict[str, Any] = {}- # Recipient- recipient_type = params.get("recipientType", "phone")+ # Recipient (snake_case)+ recipient_type = params.get("recipient_type", "phone")if recipient_type == "group":group_id = params.get("group_id")if not group_id:@@ -417,8 +417,8 @@ async def handle_whatsapp_send(params: dict) -> dict:return {"success": False, "error": "phone is required"}rpc_params["phone"] = phone- # Message type- msg_type = params.get("messageType", "text")+ # Message type (snake_case)+ msg_type = params.get("message_type", "text")rpc_params["type"] = msg_type# Content based on type@@ -429,15 +429,15 @@ async def handle_whatsapp_send(params: dict) -> dict:rpc_params["message"] = messageelif msg_type in ["image", "video", "audio", "document", "sticker"]:- media_source = params.get("mediaSource", "base64")+ media_source = params.get("media_source", "base64")media_data = None- mime_type = params.get("mimeType")+ mime_type = params.get("mime_type")filename = params.get("filename")if media_source == "base64":- media_data = params.get("mediaData")+ media_data = params.get("media_data")elif media_source == "file":- file_param = params.get("filePath")+ file_param = params.get("file_path")if isinstance(file_param, dict) and file_param.get("type") == "upload":media_data = file_param.get("data")mime_type = mime_type or file_param.get("mimeType")@@ -450,7 +450,7 @@ async def handle_whatsapp_send(params: dict) -> dict:except Exception as e:return {"success": False, "error": f"Failed to read file: {e}"}elif media_source == "url":- media_url = params.get("mediaUrl")+ media_url = params.get("media_url")if media_url:import httpximport base64 as b64@@ -480,27 +480,27 @@ async def handle_whatsapp_send(params: dict) -> dict:if lat is None or lng is None:return {"success": False, "error": "latitude and longitude are required"}rpc_params["location"] = {"latitude": float(lat), "longitude": float(lng)}- if params.get("locationName"):- rpc_params["location"]["name"] = params["locationName"]+ if params.get("location_name"):+ rpc_params["location"]["name"] = params["location_name"]if params.get("address"):rpc_params["location"]["address"] = params["address"]elif msg_type == "contact":- contact_name = params.get("contactName")+ contact_name = params.get("contact_name")vcard = params.get("vcard")if not contact_name or not vcard:- return {"success": False, "error": "contactName and vcard are required"}+ return {"success": False, "error": "contact_name and vcard are required"}rpc_params["contact"] = {"display_name": contact_name, "vcard": vcard}- # Reply context- if params.get("isReply"):- reply_id = params.get("replyMessageId")- reply_sender = params.get("replySender")+ # Reply context (snake_case)+ if params.get("is_reply"):+ reply_id = params.get("reply_message_id")+ reply_sender = params.get("reply_sender")if reply_id and reply_sender:rpc_params["reply"] = {"message_id": reply_id,"sender": reply_sender,- "content": params.get("replyContent", "")+ "content": params.get("reply_content", "")}if params.get("metadata"):@@ -510,8 +510,8 @@ async def handle_whatsapp_send(params: dict) -> dict:result = await client.call("send", rpc_params)return {"success": True,- "messageId": result.get("message_id"),- "messageType": msg_type,+ "message_id": result.get("message_id"),+ "message_type": msg_type,"timestamp": time.time()}except Exception as e:diff --git a/server/services/ai.py b/server/services/ai.pyindex 5d1b8cd5..e8aaa872 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -33,6 +33,88 @@ from services.auth import AuthServicelogger = get_logger(__name__)+# =============================================================================+# MARKDOWN MEMORY HELPERS - Parse/append/trim conversation markdown+# =============================================================================++def _parse_memory_markdown(content: str) -> List[BaseMessage]:+ """Parse markdown memory content into LangChain messages.++ Markdown format:+ ### **Human** (timestamp)+ message content++ ### **Assistant** (timestamp)+ response content+ """+ messages = []+ pattern = r'### \*\*(Human|Assistant)\*\*[^\n]*\n(.*?)(?=\n### \*\*|$)'+ for role, text in re.findall(pattern, content, re.DOTALL):+ text = text.strip()+ if text:+ msg_class = HumanMessage if role == 'Human' else AIMessage+ messages.append(msg_class(content=text))+ return messages+++def _append_to_memory_markdown(content: str, role: str, message: str) -> str:+ """Append a message to markdown memory content."""+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")+ label = "Human" if role == "human" else "Assistant"+ entry = f"\n### **{label}** ({ts})\n{message}\n"+ # Remove empty state message if present+ return content.replace("*No messages yet.*\n", "") + entry+++def _trim_markdown_window(content: str, window_size: int) -> tuple:+ """Keep last N message pairs, return (trimmed_content, removed_texts).++ Args:+ content: Full markdown content+ window_size: Number of message PAIRS to keep (human+assistant)++ Returns:+ Tuple of (trimmed markdown, list of removed message texts for archival)+ """+ pattern = r'(### \*\*(Human|Assistant)\*\*[^\n]*\n.*?)(?=\n### \*\*|$)'+ blocks = [m[0] for m in re.findall(pattern, content, re.DOTALL)]++ if len(blocks) <= window_size * 2:+ return content, []++ keep = blocks[-(window_size * 2):]+ removed = blocks[:-(window_size * 2)]++ # Extract text from removed blocks for vector storage+ removed_texts = []+ for block in removed:+ match = re.search(r'\n(.*)$', block, re.DOTALL)+ if match:+ removed_texts.append(match.group(1).strip())++ return "# Conversation History\n" + "\n".join(keep), removed_texts+++# Global cache for vector stores per session (InMemoryVectorStore)+_memory_vector_stores: Dict[str, Any] = {}+++def _get_memory_vector_store(session_id: str):+ """Get or create InMemoryVectorStore for a session."""+ if session_id not in _memory_vector_stores:+ try:+ from langchain_core.vectorstores import InMemoryVectorStore+ from langchain_huggingface import HuggingFaceEmbeddings++ embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")+ _memory_vector_stores[session_id] = InMemoryVectorStore(embeddings)+ logger.debug(f"[Memory] Created vector store for session '{session_id}'")+ except ImportError as e:+ logger.warning(f"[Memory] Vector store not available: {e}")+ return None+ return _memory_vector_stores[session_id]++# =============================================================================# AI PROVIDER REGISTRY - Single source of truth for provider configurations# =============================================================================@@ -1204,12 +1286,12 @@ class AIService:if system_message:initial_messages.append(SystemMessage(content=system_message))- # Add memory history if connected simpleMemory node provided data+ # Add memory history from connected simpleMemory node (markdown-based)session_id = Nonehistory_count = 0if memory_data and memory_data.get('session_id'):session_id = memory_data['session_id']- window_size = memory_data.get('window_size')+ memory_content = memory_data.get('memory_content', '')# Broadcast: Loading memoryawait broadcast_status("loading_memory", {@@ -1218,22 +1300,28 @@ class AIService:"has_memory": True})- # Get conversation history from database- history_data = await self.database.get_conversation_messages(session_id, window_size)- history_count = len(history_data)-- # Convert to LangChain messages using standardized content validation- for m in history_data:- content = m.get('content', '')- if not is_valid_message_content(content):- logger.debug(f"[LangGraph Memory] Skipping empty {m['role']} message")- continue- if m['role'] == 'human':- initial_messages.append(HumanMessage(content=content))- elif m['role'] == 'ai':- initial_messages.append(AIMessage(content=content))-- logger.info(f"[LangGraph Memory] Loaded {history_count} messages from session '{session_id}'")+ # Parse short-term memory from markdown+ history_messages = _parse_memory_markdown(memory_content)+ history_count = len(history_messages)++ # If long-term memory enabled, retrieve relevant context+ if memory_data.get('long_term_enabled'):+ store = _get_memory_vector_store(session_id)+ if store:+ try:+ k = memory_data.get('retrieval_count', 3)+ docs = store.similarity_search(prompt, k=k)+ if docs:+ context = "\n---\n".join(d.page_content for d in docs)+ initial_messages.append(SystemMessage(content=f"Relevant past context:\n{context}"))+ logger.info(f"[LangGraph Memory] Retrieved {len(docs)} relevant memories from long-term store")+ except Exception as e:+ logger.debug(f"[LangGraph Memory] Long-term retrieval skipped: {e}")++ # Add parsed history messages+ initial_messages.extend(history_messages)++ logger.info(f"[LangGraph Memory] Loaded {history_count} messages from markdown")# Broadcast: Memory loadedawait broadcast_status("memory_loaded", {@@ -1392,9 +1480,9 @@ class AIService:logger.info(f"[LangGraph] Agent completed in {iterations} iteration(s), thinking={'yes' if thinking_content else 'no'}")- # Save to memory if connected (persist to database)+ # Save to memory if connected (markdown-based with optional vector DB)# Only save non-empty messages using standardized validation- if session_id and is_valid_message_content(prompt) and is_valid_message_content(response_content):+ if memory_data and memory_data.get('node_id') and is_valid_message_content(prompt) and is_valid_message_content(response_content):# Broadcast: Saving to memoryawait broadcast_status("saving_memory", {"message": "Saving to conversation memory...",@@ -1403,9 +1491,31 @@ class AIService:"history_count": history_count})- await self.database.add_conversation_message(session_id, 'human', prompt)- await self.database.add_conversation_message(session_id, 'ai', response_content)- logger.info(f"[LangGraph Memory] Saved exchange to session '{session_id}'")+ # Update markdown content+ updated_content = memory_data.get('memory_content', '# Conversation History\n\n*No messages yet.*\n')+ updated_content = _append_to_memory_markdown(updated_content, 'human', prompt)+ updated_content = _append_to_memory_markdown(updated_content, 'ai', response_content)++ # Trim to window size, archive removed to vector DB+ window_size = memory_data.get('window_size', 10)+ updated_content, removed_texts = _trim_markdown_window(updated_content, window_size)++ # Store removed messages in long-term vector DB+ if removed_texts and memory_data.get('long_term_enabled'):+ store = _get_memory_vector_store(session_id)+ if store:+ try:+ store.add_texts(removed_texts)+ logger.info(f"[LangGraph Memory] Archived {len(removed_texts)} messages to long-term store")+ except Exception as e:+ logger.warning(f"[LangGraph Memory] Failed to archive to vector store: {e}")++ # Save updated markdown to node parameters+ memory_node_id = memory_data['node_id']+ current_params = await self.database.get_node_parameters(memory_node_id) or {}+ current_params['memoryContent'] = updated_content+ await self.database.save_node_parameters(memory_node_id, current_params)+ logger.info(f"[LangGraph Memory] Saved markdown to memory node '{memory_node_id}'")result = {"response": response_content,@@ -1460,16 +1570,17 @@ class AIService:tool_data: Optional[List[Dict[str, Any]]] = None,broadcaster=None,workflow_id: Optional[str] = None) -> Dict[str, Any]:- """Execute Chat Agent - conversational AI with skill-based tool calling.+ """Execute Chat Agent - conversational AI with memory, skills, and tool calling.Chat Agent supports:+ - Memory (input-memory): Markdown-based conversation history (same as AI Agent)- Skills (input-skill): Provide context/instructions via SKILL.md- Tools (input-tools): Tool nodes (httpRequest, etc.) for LangGraph tool callingArgs:node_id: The node identifierparameters: Node parameters including prompt, model, etc.- memory_data: Optional memory data (deprecated - use skills for memory)+ memory_data: Optional memory data from connected SimpleMemory node (markdown-based)skill_data: Optional skill configurations from connected skill nodestool_data: Optional tool configurations from connected tool nodes (httpRequest, etc.)broadcaster: Optional StatusBroadcaster for real-time UI updates@@ -1590,12 +1701,13 @@ class AIService:if system_message:messages.append(SystemMessage(content=system_message))- # Load memory history if connected+ # Load memory history if connected (markdown-based like AI Agent)session_id = Nonehistory_count = 0- if memory_data and memory_data.get('session_id'):- session_id = memory_data['session_id']- window_size = memory_data.get('window_size')+ memory_content = None+ if memory_data and memory_data.get('node_id'):+ session_id = memory_data.get('session_id', 'default')+ memory_content = memory_data.get('memory_content', '# Conversation History\n\n*No messages yet.*\n')await broadcast_status("loading_memory", {"message": "Loading conversation history...",@@ -1603,19 +1715,28 @@ class AIService:"has_memory": True})- history_data = await self.database.get_conversation_messages(session_id, window_size)- history_count = len(history_data)-- for m in history_data:- content = m.get('content', '')- if not is_valid_message_content(content):- continue- if m['role'] == 'human':- messages.append(HumanMessage(content=content))- elif m['role'] == 'ai':- messages.append(AIMessage(content=content))-- logger.info(f"[ChatAgent] Loaded {history_count} messages from session '{session_id}'")+ # Parse short-term memory from markdown+ history_messages = _parse_memory_markdown(memory_content)+ history_count = len(history_messages)++ # If long-term memory enabled, retrieve relevant context+ if memory_data.get('long_term_enabled'):+ store = _get_memory_vector_store(session_id)+ if store:+ try:+ k = memory_data.get('retrieval_count', 3)+ docs = store.similarity_search(prompt, k=k)+ if docs:+ context = "\n---\n".join(d.page_content for d in docs)+ messages.append(SystemMessage(content=f"Relevant past context:\n{context}"))+ logger.info(f"[ChatAgent Memory] Retrieved {len(docs)} relevant memories from long-term store")+ except Exception as e:+ logger.debug(f"[ChatAgent Memory] Long-term retrieval skipped: {e}")++ # Add parsed history messages+ messages.extend(history_messages)++ logger.info(f"[ChatAgent Memory] Loaded {history_count} messages from markdown")await broadcast_status("memory_loaded", {"message": f"Loaded {history_count} messages from memory",@@ -1735,17 +1856,39 @@ class AIService:logger.info(f"[ChatAgent] Response generated, thinking={'yes' if thinking_content else 'no'}, iterations={iterations}")- # Save to memory if connected- if session_id and is_valid_message_content(prompt) and is_valid_message_content(response_content):+ # Save to memory if connected (markdown-based like AI Agent)+ if memory_data and memory_data.get('node_id') and is_valid_message_content(prompt) and is_valid_message_content(response_content):await broadcast_status("saving_memory", {"message": "Saving to conversation memory...","session_id": session_id,"has_memory": True})- await self.database.add_conversation_message(session_id, 'human', prompt)- await self.database.add_conversation_message(session_id, 'ai', response_content)- logger.info(f"[ChatAgent] Saved exchange to session '{session_id}'")+ # Update markdown content+ updated_content = memory_content or '# Conversation History\n\n*No messages yet.*\n'+ updated_content = _append_to_memory_markdown(updated_content, 'human', prompt)+ updated_content = _append_to_memory_markdown(updated_content, 'ai', response_content)++ # Trim to window size, archive removed to vector DB+ window_size = memory_data.get('window_size', 10)+ updated_content, removed_texts = _trim_markdown_window(updated_content, window_size)++ # Store removed messages in long-term vector DB+ if removed_texts and memory_data.get('long_term_enabled'):+ store = _get_memory_vector_store(session_id)+ if store:+ try:+ store.add_texts(removed_texts)+ logger.info(f"[ChatAgent Memory] Archived {len(removed_texts)} messages to long-term store")+ except Exception as e:+ logger.warning(f"[ChatAgent Memory] Failed to archive to vector store: {e}")++ # Save updated markdown to node parameters+ memory_node_id = memory_data['node_id']+ current_params = await self.database.get_node_parameters(memory_node_id) or {}+ current_params['memoryContent'] = updated_content+ await self.database.save_node_parameters(memory_node_id, current_params)+ logger.info(f"[ChatAgent Memory] Saved markdown to memory node '{memory_node_id}'")# Determine agent type based on configurationagent_type = "chat"@@ -1793,6 +1936,12 @@ class AIService:log_execution_time(logger, "chat_agent", start_time, time.time())log_api_call(logger, provider, model, "chat_agent", True)+ # Save assistant response to chat messages database for console panel persistence+ try:+ await self.database.add_chat_message("default", "assistant", response_content)+ except Exception as e:+ logger.warning(f"[ChatAgent] Failed to save chat response to database: {e}")+return {"success": True,"node_id": node_id,@@ -1834,6 +1983,8 @@ class AIService:'androidTool': 'android_device','whatsappSend': 'whatsapp_send','whatsappDb': 'whatsapp_db',+ 'addLocations': 'geocode',+ 'showNearbyPlaces': 'nearby_places',}DEFAULT_TOOL_DESCRIPTIONS = {'calculatorTool': 'Perform mathematical calculations. Operations: add, subtract, multiply, divide, power, sqrt, mod, abs',@@ -1842,6 +1993,8 @@ class AIService:'androidTool': 'Control Android device. Available services are determined by connected nodes.','whatsappSend': 'Send WhatsApp messages to contacts or groups. Supports text, media, location, and contact messages.','whatsappDb': 'Query WhatsApp database - list contacts, search groups, get contact/group info, retrieve chat history.',+ 'addLocations': 'Geocode addresses to coordinates or reverse geocode coordinates to addresses using Google Maps.',+ 'showNearbyPlaces': 'Search for nearby places (restaurants, hospitals, banks, etc.) using Google Maps Places API.',}try:@@ -2070,18 +2223,26 @@ class AIService:default=None,description="For chat_history (group with group_filter='contact'): filter messages from this phone")- limit: Optional[int] = Field(default=None, description="For chat_history: max messages (1-500)")+ limit: Optional[int] = Field(+ default=None,+ description="Max results to return. chat_history: 1-500 (default 50), search_groups: 1-50 (default 20), list_contacts: 1-100 (default 50). Use smaller limits to avoid context overflow."+ )offset: Optional[int] = Field(default=None, description="For chat_history: pagination offset")# For search_groups, list_contactsquery: Optional[str] = Field(default=None,- description="Search query for search_groups or list_contacts"+ description="Search query for search_groups or list_contacts. Use specific queries to narrow results.")# For check_contactsphones: Optional[str] = Field(default=None,description="For check_contacts: comma-separated phone numbers")+ # For get_group_info+ participant_limit: Optional[int] = Field(+ default=None,+ description="For get_group_info: max participants to return (1-100, default 50). Large groups may have hundreds of members."+ )return WhatsAppDbSchema@@ -2127,6 +2288,56 @@ class AIService:return AndroidToolSchema+ # Google Maps Geocoding schema (addLocations node as tool)+ # camelCase to match JSON/frontend convention+ if node_type == 'addLocations':+ class GeocodingSchema(BaseModel):+ """Geocode addresses to coordinates or reverse geocode coordinates to addresses."""+ service_type: str = Field(+ default="geocode",+ description="Operation: 'geocode' (address to coordinates) or 'reverse_geocode' (coordinates to address)"+ )+ address: Optional[str] = Field(+ default=None,+ description="Address to geocode (e.g., '1600 Amphitheatre Parkway, Mountain View, CA'). Required for service_type='geocode'"+ )+ lat: Optional[float] = Field(+ default=None,+ description="Latitude for reverse geocoding. Required for service_type='reverse_geocode'"+ )+ lng: Optional[float] = Field(+ default=None,+ description="Longitude for reverse geocoding. Required for service_type='reverse_geocode'"+ )++ return GeocodingSchema++ # Google Maps Nearby Places schema (showNearbyPlaces node as tool)+ # snake_case to match Python convention+ if node_type == 'showNearbyPlaces':+ class NearbyPlacesSchema(BaseModel):+ """Search for nearby places using Google Maps Places API."""+ lat: float = Field(+ description="Center latitude for search (e.g., 40.7484)"+ )+ lng: float = Field(+ description="Center longitude for search (e.g., -73.9857)"+ )+ radius: int = Field(+ default=500,+ description="Search radius in meters (max 50000)"+ )+ type: str = Field(+ default="restaurant",+ description="Place type: restaurant, cafe, bar, hospital, pharmacy, bank, atm, gas_station, supermarket, park, gym, etc."+ )+ keyword: Optional[str] = Field(+ default=None,+ description="Optional keyword to filter results (e.g., 'pizza', 'italian', '24 hour')"+ )++ return NearbyPlacesSchema+# Generic schema for other nodesclass GenericToolSchema(BaseModel):"""Generic schema for tool arguments."""diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.pyindex 46ad1f68..946bc260 100644--- a/server/services/handlers/ai.py+++ b/server/services/handlers/ai.py@@ -63,19 +63,25 @@ async def handle_ai_agent(if not source_node:continue- # Memory detection (existing)+ # Memory detection - load markdown content for editingif target_handle == 'input-memory':if source_node.get('type') == 'simpleMemory':memory_params = await database.get_node_parameters(source_node_id) or {}memory_session_id = memory_params.get('sessionId', 'default')- memory_type = memory_params.get('memoryType', 'buffer')- window_size = int(memory_params.get('windowSize', 10)) if memory_type == 'window' else None+ window_size = int(memory_params.get('windowSize', 10))+ memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')+ long_term_enabled = memory_params.get('longTermEnabled', False)+ retrieval_count = int(memory_params.get('retrievalCount', 3))+memory_data = {+ 'node_id': source_node_id, # For saving updated content'session_id': memory_session_id,- 'memory_type': memory_type,- 'window_size': window_size+ 'window_size': window_size,+ 'memory_content': memory_content,+ 'long_term_enabled': long_term_enabled,+ 'retrieval_count': retrieval_count}- logger.debug("AI Agent connected memory node", memory_session=memory_session_id)+ logger.debug("AI Agent connected memory node", memory_session=memory_session_id, content_length=len(memory_content))# Tool detection (new) - any node connected to input-tools becomes a toolelif target_handle == 'input-tools':@@ -159,8 +165,9 @@ async def handle_chat_agent("""Handle Chat Agent node execution with skill-based tool calling.Chat Agent supports:+ - Memory (input-memory): SimpleMemory node for conversation history- Skills (input-skill): Provide context/instructions via SKILL.md- - Tools (input-tool): Tool nodes (httpRequest, etc.) for LangGraph tool calling+ - Tools (input-tools): Tool nodes (httpRequest, etc.) for LangGraph tool callingArgs:node_id: The node ID@@ -176,6 +183,7 @@ async def handle_chat_agent(nodes = context.get('nodes')edges = context.get('edges')workflow_id = context.get('workflow_id')+ memory_data = Noneskill_data: List[Dict[str, Any]] = []tool_data: List[Dict[str, Any]] = [] # Tools for LangGraphinput_data: Optional[Dict[str, Any]] = None@@ -197,8 +205,28 @@ async def handle_chat_agent(if not source_node:continue+ # Memory detection - load markdown content (same as AI Agent)+ if target_handle == 'input-memory':+ if source_node.get('type') == 'simpleMemory':+ memory_params = await database.get_node_parameters(source_node_id) or {}+ memory_session_id = memory_params.get('sessionId', 'default')+ window_size = int(memory_params.get('windowSize', 10))+ memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')+ long_term_enabled = memory_params.get('longTermEnabled', False)+ retrieval_count = int(memory_params.get('retrievalCount', 3))++ memory_data = {+ 'node_id': source_node_id,+ 'session_id': memory_session_id,+ 'window_size': window_size,+ 'memory_content': memory_content,+ 'long_term_enabled': long_term_enabled,+ 'retrieval_count': retrieval_count+ }+ logger.info(f"[Chat Agent] Connected memory node: session={memory_session_id}, content_length={len(memory_content)}")+# Skill detection - nodes connected to input-skill handle- if target_handle == 'input-skill':+ elif target_handle == 'input-skill':skill_type = source_node.get('type')skill_params = await database.get_node_parameters(source_node_id) or {}skill_entry = {@@ -231,8 +259,8 @@ async def handle_chat_agent(input_data = source_outputlogger.debug(f"[Chat Agent] Input from {source_node.get('type')}: {list(source_output.keys())}")- # Log discovered skills and tools- logger.info(f"[Chat Agent] Discovered: {len(skill_data)} skills, {len(tool_data)} tools")+ # Log discovered connections+ logger.info(f"[Chat Agent] Discovered: memory={'yes' if memory_data else 'no'}, {len(skill_data)} skills, {len(tool_data)} tools")for td in tool_data:logger.debug(f"[Chat Agent] Tool: type={td.get('node_type')}, label={td.get('label')}")@@ -251,11 +279,11 @@ async def handle_chat_agent(from services.status_broadcaster import get_status_broadcasterbroadcaster = get_status_broadcaster()- # Execute Chat Agent with skills and tools+ # Execute Chat Agent with memory, skills and toolsreturn await ai_service.execute_chat_agent(node_id,parameters,- memory_data=None, # Memory removed - use skill-based conversation management+ memory_data=memory_data,skill_data=skill_data if skill_data else None,tool_data=tool_data if tool_data else None,broadcaster=broadcaster,diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 31039742..27738be7 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -64,6 +64,14 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],if node_type == 'androidTool':return await _execute_android_toolkit(tool_args, config)+ # Google Maps Geocoding (addLocations node as tool)+ if node_type == 'addLocations':+ return await _execute_geocoding(tool_args, config.get('parameters', {}))++ # Google Maps Nearby Places (showNearbyPlaces node as tool)+ if node_type == 'showNearbyPlaces':+ return await _execute_nearby_places(tool_args, config.get('parameters', {}))+# Generic fallback for unknown node typeslogger.warning(f"[Tool] Unknown tool type: {node_type}, using generic handler")return await _execute_generic(tool_args, config)@@ -420,7 +428,7 @@ async def _execute_whatsapp_send(args: Dict[str, Any],Media sources: URLArgs:- args: LLM-provided arguments matching WhatsAppSendSchema+ args: LLM-provided arguments matching WhatsAppSendSchema (snake_case)node_params: Node parameters (used as fallback)Returns:@@ -428,27 +436,27 @@ async def _execute_whatsapp_send(args: Dict[str, Any],"""from services.handlers.whatsapp import handle_whatsapp_send- # Map LLM args to node parameter format (camelCase for handler)+ # Args are snake_case matching Pydantic schema and frontend node paramsparameters = {- 'recipientType': args.get('recipient_type', 'phone'),+ 'recipient_type': args.get('recipient_type', 'phone'),'phone': args.get('phone', ''),'group_id': args.get('group_id', ''),- 'messageType': args.get('message_type', 'text'),+ 'message_type': args.get('message_type', 'text'),'message': args.get('message', ''),- 'mediaSource': 'url' if args.get('media_url') else 'none',- 'mediaUrl': args.get('media_url', ''),+ 'media_source': 'url' if args.get('media_url') else 'none',+ 'media_url': args.get('media_url', ''),'caption': args.get('caption', ''),'latitude': args.get('latitude'),'longitude': args.get('longitude'),- 'locationName': args.get('location_name', ''),+ 'location_name': args.get('location_name', ''),'address': args.get('address', ''),- 'contactName': args.get('contact_name', ''),+ 'contact_name': args.get('contact_name', ''),'vcard': args.get('vcard', ''),}# Validate required fields based on message type- recipient_type = parameters['recipientType']- message_type = parameters['messageType']+ recipient_type = parameters['recipient_type']+ message_type = parameters['message_type']if recipient_type == 'phone' and not parameters['phone']:return {"error": "Phone number is required for recipient_type='phone'"}@@ -456,7 +464,7 @@ async def _execute_whatsapp_send(args: Dict[str, Any],return {"error": "Group ID is required for recipient_type='group'"}if message_type == 'text' and not parameters['message']:return {"error": "Message content is required for message_type='text'"}- if message_type in ('image', 'video', 'audio', 'document', 'sticker') and not parameters['mediaUrl']:+ if message_type in ('image', 'video', 'audio', 'document', 'sticker') and not parameters['media_url']:return {"error": f"media_url is required for message_type='{message_type}'"}if message_type == 'location' and (parameters['latitude'] is None or parameters['longitude'] is None):return {"error": "latitude and longitude are required for message_type='location'"}@@ -503,7 +511,7 @@ async def _execute_whatsapp_db(args: Dict[str, Any],- check_contacts: Check WhatsApp registration statusArgs:- args: LLM-provided arguments matching WhatsAppDbSchema+ args: LLM-provided arguments matching WhatsAppDbSchema (snake_case)node_params: Node parameters (used as fallback)Returns:@@ -514,22 +522,22 @@ async def _execute_whatsapp_db(args: Dict[str, Any],operation = args.get('operation', 'chat_history')logger.info(f"[WhatsApp DB Tool] Executing operation: {operation}")- # Build parameters for handler+ # Build parameters for handler (snake_case matching frontend nodes)parameters = {'operation': operation}if operation == 'chat_history':parameters.update({- 'chatType': args.get('chat_type', 'individual'),+ 'chat_type': args.get('chat_type', 'individual'),'phone': args.get('phone', ''),'group_id': args.get('group_id', ''),- 'messageFilter': args.get('message_filter', 'all'),- 'groupFilter': args.get('group_filter', 'all'),- 'senderPhone': args.get('sender_phone', ''),+ 'message_filter': args.get('message_filter', 'all'),+ 'group_filter': args.get('group_filter', 'all'),+ 'sender_phone': args.get('sender_phone', ''),'limit': args.get('limit', 50),'offset': args.get('offset', 0),})# Validate required fields- chat_type = parameters['chatType']+ chat_type = parameters['chat_type']if chat_type == 'individual' and not parameters['phone']:return {"error": "Phone number is required for chat_type='individual'"}if chat_type == 'group' and not parameters['group_id']:@@ -537,21 +545,24 @@ async def _execute_whatsapp_db(args: Dict[str, Any],elif operation == 'search_groups':parameters['query'] = args.get('query', '')+ parameters['limit'] = min(args.get('limit', 20), 50) # Cap at 50 to prevent overflowelif operation == 'get_group_info':group_id = args.get('group_id', '')if not group_id:return {"error": "group_id is required for get_group_info"}- parameters['groupIdForInfo'] = group_id+ parameters['group_id_for_info'] = group_id+ parameters['participant_limit'] = min(args.get('participant_limit', 50), 100) # Cap at 100elif operation == 'get_contact_info':phone = args.get('phone', '')if not phone:return {"error": "phone is required for get_contact_info"}- parameters['contactPhone'] = phone+ parameters['contact_phone'] = phoneelif operation == 'list_contacts':parameters['query'] = args.get('query', '')+ parameters['limit'] = min(args.get('limit', 50), 100) # Cap at 100 to prevent overflowelif operation == 'check_contacts':phones = args.get('phones', '')@@ -718,6 +729,100 @@ async def _execute_android_toolkit(args: Dict[str, Any],return {"error": str(e)}+async def _execute_geocoding(args: Dict[str, Any],+ node_params: Dict[str, Any]) -> Dict[str, Any]:+ """Execute Google Maps geocoding (addLocations node as tool).++ Args:+ args: LLM-provided arguments (snake_case: service_type, address, lat, lng)+ node_params: Node parameters (may contain api_key)++ Returns:+ Geocoding result with coordinates or address+ """+ from services.handlers.utility import handle_add_locations+ from core.container import container++ # Args use snake_case matching Pydantic schema and node params+ parameters = {**args, 'api_key': node_params.get('api_key', '')}++ service_type = parameters.get('service_type', 'geocode')++ # Validate required fields+ if service_type == 'geocode' and not parameters.get('address'):+ return {"error": "address is required for geocoding"}+ if service_type == 'reverse_geocode':+ if parameters.get('lat') is None or parameters.get('lng') is None:+ return {"error": "lat and lng are required for reverse geocoding"}++ lat, lng = parameters.get('lat'), parameters.get('lng')+ location_str = parameters.get('address') or f"({lat}, {lng})"+ logger.info(f"[Geocoding Tool] {service_type}: {location_str}")++ try:+ maps_service = container.maps_service()+ result = await handle_add_locations(+ node_id="tool_geocoding",+ node_type="addLocations",+ parameters=parameters,+ context={},+ maps_service=maps_service+ )++ if result.get('success'):+ return {"success": True, "service_type": service_type, **result.get('result', {})}+ else:+ return {"error": result.get('error', 'Geocoding failed')}++ except Exception as e:+ logger.error(f"[Geocoding Tool] Error: {e}")+ return {"error": f"Geocoding failed: {str(e)}"}+++async def _execute_nearby_places(args: Dict[str, Any],+ node_params: Dict[str, Any]) -> Dict[str, Any]:+ """Execute Google Maps nearby places search (showNearbyPlaces node as tool).++ Args:+ args: LLM-provided arguments (snake_case: lat, lng, radius, type, keyword)+ node_params: Node parameters (may contain api_key)++ Returns:+ Nearby places search results+ """+ from services.handlers.utility import handle_nearby_places+ from core.container import container++ # Args use snake_case matching Pydantic schema and node params+ parameters = {**args, 'api_key': node_params.get('api_key', '')}++ # Validate required fields+ if parameters.get('lat') is None or parameters.get('lng') is None:+ return {"error": "lat and lng are required for nearby places search"}++ place_type = parameters.get('type', 'restaurant')+ logger.info(f"[Nearby Places Tool] Searching {place_type} near ({parameters['lat']}, {parameters['lng']})")++ try:+ maps_service = container.maps_service()+ result = await handle_nearby_places(+ node_id="tool_nearby_places",+ node_type="showNearbyPlaces",+ parameters=parameters,+ context={},+ maps_service=maps_service+ )++ if result.get('success'):+ return {"success": True, "type": place_type, **result.get('result', {})}+ else:+ return {"error": result.get('error', 'Nearby places search failed')}++ except Exception as e:+ logger.error(f"[Nearby Places Tool] Error: {e}")+ return {"error": f"Nearby places search failed: {str(e)}"}++async def _execute_generic(args: Dict[str, Any],config: Dict[str, Any]) -> Dict[str, Any]:"""Execute a generic tool (fallback handler).diff --git a/server/services/handlers/whatsapp.py b/server/services/handlers/whatsapp.pyindex 0a1253f4..363a1dd5 100644--- a/server/services/handlers/whatsapp.py+++ b/server/services/handlers/whatsapp.py@@ -33,12 +33,11 @@ async def handle_whatsapp_send(start_time = time.time()try:- # Determine recipient- recipient_type = parameters.get('recipientType', 'phone')- # Support both group_id (node definition) and groupId (legacy)- group_id = parameters.get('group_id') or parameters.get('groupId')+ # Determine recipient (snake_case parameters)+ recipient_type = parameters.get('recipient_type', 'phone')+ group_id = parameters.get('group_id')recipient = parameters.get('phone') if recipient_type == 'phone' else group_id- message_type = parameters.get('messageType', 'text')+ message_type = parameters.get('message_type', 'text')if not recipient:raise ValueError(f"{'Phone number' if recipient_type == 'phone' else 'Group ID'} is required")@@ -54,12 +53,12 @@ async def handle_whatsapp_send(if not success:raise Exception(data.get('error', 'Send failed'))- # Build informative result based on message type+ # Build informative result based on message type (snake_case output)result = {"status": "sent","recipient": recipient,- "recipientType": recipient_type,- "messageType": message_type,+ "recipient_type": recipient_type,+ "message_type": message_type,"timestamp": datetime.now().isoformat()}@@ -69,28 +68,28 @@ async def handle_whatsapp_send(msg_content = parameters.get('message', '')result["preview"] = msg_content[:100] + "..." if len(msg_content) > 100 else msg_contentcase 'image' | 'video' | 'audio' | 'document' | 'sticker':- media_source = parameters.get('mediaSource', 'base64')- result["mediaSource"] = media_source+ media_source = parameters.get('media_source', 'base64')+ result["media_source"] = media_sourceif parameters.get('caption'):result["caption"] = parameters.get('caption')if parameters.get('filename'):result["filename"] = parameters.get('filename')- if parameters.get('mimeType'):- result["mimeType"] = parameters.get('mimeType')+ if parameters.get('mime_type'):+ result["mime_type"] = parameters.get('mime_type')# For file uploads, include the uploaded filename- file_param = parameters.get('filePath')+ file_param = parameters.get('file_path')if isinstance(file_param, dict) and file_param.get('type') == 'upload':- result["uploadedFile"] = file_param.get('filename')- result["mimeType"] = file_param.get('mimeType')+ result["uploaded_file"] = file_param.get('filename')+ result["mime_type"] = file_param.get('mimeType')case 'location':result["location"] = {"latitude": parameters.get('latitude'),"longitude": parameters.get('longitude'),- "name": parameters.get('locationName'),+ "name": parameters.get('location_name'),"address": parameters.get('address')}case 'contact':- result["contactName"] = parameters.get('contactName')+ result["contact_name"] = parameters.get('contact_name')return {"success": success,@@ -229,7 +228,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]:"""Handle chat_history operation."""- chat_type = parameters.get('chatType', 'individual')+ chat_type = parameters.get('chat_type', 'individual')rpc_params: Dict[str, Any] = {}if chat_type == 'individual':@@ -243,13 +242,13 @@ async def _handle_chat_history(node_id: str, parameters: Dict[str, Any], start_traise ValueError("Group ID is required for group chats")rpc_params['group_id'] = group_id- group_filter = parameters.get('groupFilter', 'all')+ group_filter = parameters.get('group_filter', 'all')if group_filter == 'contact':- sender_phone = parameters.get('senderPhone')+ sender_phone = parameters.get('sender_phone')if sender_phone:rpc_params['sender_phone'] = sender_phone- message_filter = parameters.get('messageFilter', 'all')+ message_filter = parameters.get('message_filter', 'all')rpc_params['text_only'] = message_filter == 'text_only'rpc_params['limit'] = parameters.get('limit', 50)rpc_params['offset'] = parameters.get('offset', 0)@@ -285,6 +284,7 @@ async def _handle_chat_history(node_id: str, parameters: Dict[str, Any], start_tasync def _handle_search_groups(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:"""Handle search_groups operation."""query = parameters.get('query', '')+ limit = parameters.get('limit', 20) # Default limit to prevent context overflowdata = await rpc_call('groups', {})if not data.get('success', True):@@ -297,15 +297,27 @@ async def _handle_search_groups(node_id: str, parameters: Dict[str, Any], start_query_lower = query.lower()groups = [g for g in groups if query_lower in g.get('name', '').lower()]+ total_found = len(groups)++ # Apply limit to prevent context overflow (51 groups * ~4KB = 200KB+ tokens)+ # Only return essential fields: jid and name+ groups_limited = [+ {"jid": g.get("jid", ""), "name": g.get("name", "")}+ for g in groups[:limit]+ ]+return {"success": True,"node_id": node_id,"node_type": "whatsappDb","result": {"operation": "search_groups",- "groups": groups,- "total": len(groups),+ "groups": groups_limited,+ "total": total_found,+ "returned": len(groups_limited),+ "has_more": total_found > limit,"query": query,+ "hint": f"Showing {len(groups_limited)} of {total_found} groups. Use a more specific query or get_group_info for details." if total_found > limit else None,"timestamp": datetime.now().isoformat()},"execution_time": time.time() - start_time,@@ -315,10 +327,12 @@ async def _handle_search_groups(node_id: str, parameters: Dict[str, Any], start_async def _handle_get_group_info(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:"""Handle get_group_info operation."""- group_id = parameters.get('groupIdForInfo') or parameters.get('group_id')+ group_id = parameters.get('group_id_for_info') or parameters.get('group_id')if not group_id:raise ValueError("Group ID is required")+ participant_limit = parameters.get('participant_limit', 50) # Limit participants to prevent overflow+data = await rpc_call('group_info', {'group_id': group_id})if not data.get('success', True) if isinstance(data, dict) else True:@@ -326,13 +340,33 @@ async def _handle_get_group_info(node_id: str, parameters: Dict[str, Any], startresult = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)+ # Limit participants and return only essential fields+ participants = result.get('participants', [])+ total_participants = len(participants)+ participants_limited = [+ {"phone": p.get("phone", ""), "name": p.get("name", ""), "is_admin": p.get("is_admin", False)}+ for p in participants[:participant_limit]+ ]++ # Build limited result+ limited_result = {+ "name": result.get("name", ""),+ "jid": result.get("jid", group_id),+ "participants": participants_limited,+ "total_participants": total_participants,+ "participants_shown": len(participants_limited),+ }++ if total_participants > participant_limit:+ limited_result["hint"] = f"Showing {participant_limit} of {total_participants} participants."+return {"success": True,"node_id": node_id,"node_type": "whatsappDb","result": {"operation": "get_group_info",- **result,+ **limited_result,"timestamp": datetime.now().isoformat()},"execution_time": time.time() - start_time,@@ -342,7 +376,7 @@ async def _handle_get_group_info(node_id: str, parameters: Dict[str, Any], startasync def _handle_get_contact_info(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:"""Handle get_contact_info operation."""- phone = parameters.get('contactPhone') or parameters.get('phone')+ phone = parameters.get('contact_phone') or parameters.get('phone')if not phone:raise ValueError("Phone number is required")@@ -370,6 +404,7 @@ async def _handle_get_contact_info(node_id: str, parameters: Dict[str, Any], staasync def _handle_list_contacts(node_id: str, parameters: Dict[str, Any], start_time: float, rpc_call) -> Dict[str, Any]:"""Handle list_contacts operation."""query = parameters.get('query', '')+ limit = parameters.get('limit', 50) # Default limit to prevent context overflowdata = await rpc_call('contacts', {'query': query})@@ -379,15 +414,26 @@ async def _handle_list_contacts(node_id: str, parameters: Dict[str, Any], start_result = data if not isinstance(data, dict) or 'result' not in data else data.get('result', data)contacts = result.get('contacts', []) if isinstance(result, dict) else result+ total_found = len(contacts)++ # Apply limit and return only essential fields: phone, name, jid+ contacts_limited = [+ {"phone": c.get("phone", ""), "name": c.get("name", ""), "jid": c.get("jid", "")}+ for c in contacts[:limit]+ ]+return {"success": True,"node_id": node_id,"node_type": "whatsappDb","result": {"operation": "list_contacts",- "contacts": contacts,- "total": len(contacts),+ "contacts": contacts_limited,+ "total": total_found,+ "returned": len(contacts_limited),+ "has_more": total_found > limit,"query": query,+ "hint": f"Showing {len(contacts_limited)} of {total_found} contacts. Use a more specific query to narrow results." if total_found > limit else None,"timestamp": datetime.now().isoformat()},"execution_time": time.time() - start_time,diff --git a/server/services/maps.py b/server/services/maps.pyindex 7705e651..47b66e20 100644--- a/server/services/maps.py+++ b/server/services/maps.py@@ -36,11 +36,11 @@ class MapsService:if not api_key:raise ValueError("Google Maps API key is required")- # Extract and validate parameters+ # Extract and validate parameters (snake_case)lat = float(parameters.get('lat', 40.7128))lng = float(parameters.get('lng', -74.0060))zoom = int(parameters.get('zoom', 13))- map_type = parameters.get('mapTypeId', 'ROADMAP')+ map_type = parameters.get('map_type_id', 'ROADMAP')if not self.validate_coordinates(lat, lng):raise ValueError("Invalid coordinates")@@ -92,7 +92,7 @@ class MapsService:raise ValueError("Google Maps API key is required")gmaps = googlemaps.Client(key=api_key)- service_type = parameters.get('serviceType', 'geocode')+ service_type = parameters.get('service_type', 'geocode')if service_type == 'geocode':address = parameters.get('address', '')@@ -180,21 +180,21 @@ class MapsService:if not (1 <= radius <= 50000):raise ValueError("Radius must be between 1 and 50000 meters")- # Optional parameters+ # Optional parameters (snake_case)place_type = parameters.get('type', 'restaurant')- page_size = min(int(parameters.get('pageSize', 20)), 20)+ page_size = min(int(parameters.get('page_size', 20)), 20)- # Extract options (may contain keyword, name, minPrice, maxPrice, openNow, language, rankBy)+ # Extract options (may contain keyword, name, min_price, max_price, open_now, language, rank_by)options = parameters.get('options', {})- # Support both nested options and top-level parameters+ # Support both nested options and top-level parameters (snake_case)keyword = options.get('keyword', '') if isinstance(options, dict) else parameters.get('keyword', '')name_filter = options.get('name', '') if isinstance(options, dict) else parameters.get('name', '')- min_price = options.get('minPrice') if isinstance(options, dict) else parameters.get('minPrice')- max_price = options.get('maxPrice') if isinstance(options, dict) else parameters.get('maxPrice')- open_now = options.get('openNow', False) if isinstance(options, dict) else parameters.get('openNow', False)+ min_price = options.get('min_price') if isinstance(options, dict) else parameters.get('min_price')+ max_price = options.get('max_price') if isinstance(options, dict) else parameters.get('max_price')+ open_now = options.get('open_now', False) if isinstance(options, dict) else parameters.get('open_now', False)language = options.get('language', 'en') if isinstance(options, dict) else parameters.get('language', 'en')- rank_by = options.get('rankBy', 'prominence') if isinstance(options, dict) else parameters.get('rankBy', 'prominence')+ rank_by = options.get('rank_by', 'prominence') if isinstance(options, dict) else parameters.get('rank_by', 'prominence')logger.debug("[Nearby Places] Extracted parameters",keyword=keyword,diff --git a/server/services/skill_executor.py b/server/services/skill_executor.pydeleted file mode 100644index 322281ae..00000000--- a/server/services/skill_executor.py+++ /dev/null@@ -1,624 +0,0 @@-"""Skill executor service for executing skill tools via node handlers.--Maps skill tool names to existing node handlers, enabling Chat Agent-to use skills that leverage the existing workflow node infrastructure.-"""--import json-from typing import Dict, Any, List, Optional, Callable, Type, TYPE_CHECKING-from dataclasses import dataclass-from pydantic import BaseModel, Field-from langchain_core.tools import StructuredTool-from core.logging import get_logger--if TYPE_CHECKING:- from services.skill_loader import SkillLoader--logger = get_logger(__name__)---# =============================================================================-# TOOL SCHEMA DEFINITIONS-# =============================================================================--class WhatsAppSendSchema(BaseModel):- """Schema for WhatsApp send tool."""- phone_number: str = Field(description="Recipient phone number with country code (e.g., +1234567890)")- message: str = Field(description="Message text to send")---class WhatsAppStatusSchema(BaseModel):- """Schema for WhatsApp status tool."""- pass # No parameters needed---class MemorySaveSchema(BaseModel):- """Schema for memory save tool."""- key: str = Field(description="Identifier for the memory entry")- value: str = Field(description="Information to remember")- session_id: Optional[str] = Field(default=None, description="Session for organization")---class MemoryGetSchema(BaseModel):- """Schema for memory get tool."""- key: str = Field(description="Identifier to look up")- session_id: Optional[str] = Field(default=None, description="Specific session to search")---class MemoryClearSchema(BaseModel):- """Schema for memory clear tool."""- key: Optional[str] = Field(default=None, description="Specific key to clear, or all if not specified")- session_id: Optional[str] = Field(default=None, description="Specific session to clear")---class MapsGeocodeSchema(BaseModel):- """Schema for maps geocode tool."""- address: str = Field(description="Address or location name to geocode")---class MapsNearbySchema(BaseModel):- """Schema for maps nearby places tool."""- location: str = Field(description="Center point (address or 'lat,lng')")- type: str = Field(description="Place type (restaurant, cafe, hospital, etc.)")- radius: int = Field(default=1000, description="Search radius in meters")---class MapsCreateSchema(BaseModel):- """Schema for maps create tool."""- center: str = Field(description="Map center (address or 'lat,lng')")- zoom: int = Field(default=14, description="Zoom level 1-20")---class HttpRequestSchema(BaseModel):- """Schema for HTTP request tool."""- url: str = Field(description="Full URL to request")- method: str = Field(default="GET", description="HTTP method (GET, POST, PUT, DELETE, PATCH)")- body: Optional[Dict[str, Any]] = Field(default=None, description="Request body as JSON object")- headers: Optional[Dict[str, str]] = Field(default=None, description="Custom headers")---class SchedulerTimerSchema(BaseModel):- """Schema for scheduler timer tool."""- duration: str = Field(description="Time until execution (e.g., '5m', '1h', '30s')")- action: str = Field(description="What to do when timer fires")- name: Optional[str] = Field(default=None, description="Timer identifier")---class SchedulerCronSchema(BaseModel):- """Schema for scheduler cron tool."""- expression: str = Field(description="Cron expression (e.g., '0 9 * * *')")- action: str = Field(description="What to do on each trigger")- name: Optional[str] = Field(default=None, description="Schedule identifier")- timezone: str = Field(default="UTC", description="Timezone for schedule")---class SchedulerListSchema(BaseModel):- """Schema for scheduler list tool."""- pass # No parameters needed---class SchedulerCancelSchema(BaseModel):- """Schema for scheduler cancel tool."""- name: str = Field(description="Name of schedule to cancel")---class AndroidBatterySchema(BaseModel):- """Schema for Android battery tool."""- action: str = Field(default="status", description="Action to perform")---class AndroidWifiSchema(BaseModel):- """Schema for Android WiFi tool."""- action: str = Field(description="Action: status, enable, disable, scan")---class AndroidBluetoothSchema(BaseModel):- """Schema for Android Bluetooth tool."""- action: str = Field(description="Action: status, enable, disable, paired_devices")---class AndroidAppsSchema(BaseModel):- """Schema for Android apps tool."""- action: str = Field(description="Action: list, launch")- package_name: Optional[str] = Field(default=None, description="App package name (for launch)")---class AndroidLocationSchema(BaseModel):- """Schema for Android location tool."""- action: str = Field(default="current", description="Action to perform")---class AndroidAudioSchema(BaseModel):- """Schema for Android audio tool."""- action: str = Field(description="Action: get_volume, set_volume, mute, unmute")- volume: Optional[int] = Field(default=None, description="Volume level 0-100 (for set_volume)")---class AndroidScreenSchema(BaseModel):- """Schema for Android screen tool."""- action: str = Field(description="Action: brightness, set_brightness, wake, sleep")- level: Optional[int] = Field(default=None, description="Brightness level 0-255 (for set_brightness)")---class AndroidCameraSchema(BaseModel):- """Schema for Android camera tool."""- action: str = Field(description="Action: info, capture")- camera: str = Field(default="back", description="Camera: front or back")---class AndroidSensorsSchema(BaseModel):- """Schema for Android sensors tool."""- action: str = Field(description="Action: motion, environment")---class CodePythonSchema(BaseModel):- """Schema for Python code execution tool."""- code: str = Field(description="Python code to execute")- input_data: Optional[Any] = Field(default=None, description="Data to pass to the script")---class CodeJavaScriptSchema(BaseModel):- """Schema for JavaScript code execution tool."""- code: str = Field(description="JavaScript code to execute")- input_data: Optional[Any] = Field(default=None, description="Data to pass to the script")---# =============================================================================-# TOOL REGISTRY-# =============================================================================--@dataclass-class ToolConfig:- """Configuration for a skill tool."""- name: str- description: str- schema: Type[BaseModel]- handler_type: str # Node type or special handler name- handler_params: Dict[str, Any] = None # Additional params for handler---# Map tool names to configurations-TOOL_REGISTRY: Dict[str, ToolConfig] = {- # WhatsApp tools- 'whatsapp-send': ToolConfig(- name='whatsapp-send',- description='Send a WhatsApp message to a phone number',- schema=WhatsAppSendSchema,- handler_type='whatsappSend'- ),- 'whatsapp-status': ToolConfig(- name='whatsapp-status',- description='Check WhatsApp connection status',- schema=WhatsAppStatusSchema,- handler_type='whatsappConnect'- ),-- # Memory tools- 'memory-save': ToolConfig(- name='memory-save',- description='Save information to long-term memory',- schema=MemorySaveSchema,- handler_type='memory_save'- ),- 'memory-get': ToolConfig(- name='memory-get',- description='Retrieve saved information from memory',- schema=MemoryGetSchema,- handler_type='memory_get'- ),- 'memory-clear': ToolConfig(- name='memory-clear',- description='Clear memory entries',- schema=MemoryClearSchema,- handler_type='memory_clear'- ),-- # Maps tools- 'maps-geocode': ToolConfig(- name='maps-geocode',- description='Convert an address to geographic coordinates',- schema=MapsGeocodeSchema,- handler_type='addLocations'- ),- 'maps-nearby': ToolConfig(- name='maps-nearby',- description='Search for nearby places',- schema=MapsNearbySchema,- handler_type='showNearbyPlaces'- ),- 'maps-create': ToolConfig(- name='maps-create',- description='Create an interactive map',- schema=MapsCreateSchema,- handler_type='createMap'- ),-- # HTTP tools- 'http-request': ToolConfig(- name='http-request',- description='Make an HTTP request to a URL',- schema=HttpRequestSchema,- handler_type='httpRequest'- ),-- # Scheduler tools- 'scheduler-timer': ToolConfig(- name='scheduler-timer',- description='Set a one-time timer',- schema=SchedulerTimerSchema,- handler_type='timer'- ),- 'scheduler-cron': ToolConfig(- name='scheduler-cron',- description='Create a recurring schedule using cron expression',- schema=SchedulerCronSchema,- handler_type='cronScheduler'- ),- 'scheduler-list': ToolConfig(- name='scheduler-list',- description='List all active schedules and timers',- schema=SchedulerListSchema,- handler_type='scheduler_list'- ),- 'scheduler-cancel': ToolConfig(- name='scheduler-cancel',- description='Cancel a scheduled task',- schema=SchedulerCancelSchema,- handler_type='scheduler_cancel'- ),-- # Android tools- 'android-battery': ToolConfig(- name='android-battery',- description='Get Android device battery information',- schema=AndroidBatterySchema,- handler_type='batteryMonitor'- ),- 'android-wifi': ToolConfig(- name='android-wifi',- description='Control Android WiFi settings',- schema=AndroidWifiSchema,- handler_type='wifiAutomation'- ),- 'android-bluetooth': ToolConfig(- name='android-bluetooth',- description='Control Android Bluetooth settings',- schema=AndroidBluetoothSchema,- handler_type='bluetoothAutomation'- ),- 'android-apps': ToolConfig(- name='android-apps',- description='Manage Android applications',- schema=AndroidAppsSchema,- handler_type='appLauncher'- ),- 'android-location': ToolConfig(- name='android-location',- description='Get Android device location',- schema=AndroidLocationSchema,- handler_type='location'- ),- 'android-audio': ToolConfig(- name='android-audio',- description='Control Android audio settings',- schema=AndroidAudioSchema,- handler_type='audioAutomation'- ),- 'android-screen': ToolConfig(- name='android-screen',- description='Control Android screen settings',- schema=AndroidScreenSchema,- handler_type='screenControlAutomation'- ),- 'android-camera': ToolConfig(- name='android-camera',- description='Access Android camera',- schema=AndroidCameraSchema,- handler_type='cameraControl'- ),- 'android-sensors': ToolConfig(- name='android-sensors',- description='Read Android sensor data',- schema=AndroidSensorsSchema,- handler_type='environmentalSensors'- ),-- # Code tools- 'code-python': ToolConfig(- name='code-python',- description='Execute Python code',- schema=CodePythonSchema,- handler_type='pythonExecutor'- ),- 'code-javascript': ToolConfig(- name='code-javascript',- description='Execute JavaScript code',- schema=CodeJavaScriptSchema,- handler_type='javascriptExecutor'- ),-}---class SkillExecutor:- """Executes skill tools by delegating to node handlers."""-- def __init__(self, skill_loader: "SkillLoader", node_executor, database=None):- """Initialize skill executor.-- Args:- skill_loader: SkillLoader instance for loading skill instructions- node_executor: NodeExecutor or function to execute node handlers- database: Database instance for memory operations- """- self.skill_loader = skill_loader- self.node_executor = node_executor- self.database = database-- async def execute_tool(self, tool_name: str, args: Dict[str, Any],- context: Dict[str, Any] = None) -> Any:- """Execute a skill tool by name.-- Args:- tool_name: Name of the tool to execute- args: Arguments for the tool- context: Optional execution context-- Returns:- Tool execution result- """- if tool_name not in TOOL_REGISTRY:- raise ValueError(f"Unknown tool: {tool_name}")-- config = TOOL_REGISTRY[tool_name]- handler_type = config.handler_type-- logger.info(f"[SkillExecutor] Executing tool: {tool_name} -> {handler_type}")-- # Special handlers for memory operations- if handler_type == 'memory_save':- return await self._handle_memory_save(args)- elif handler_type == 'memory_get':- return await self._handle_memory_get(args)- elif handler_type == 'memory_clear':- return await self._handle_memory_clear(args)- elif handler_type == 'scheduler_list':- return await self._handle_scheduler_list()- elif handler_type == 'scheduler_cancel':- return await self._handle_scheduler_cancel(args)-- # Map args to node parameters- parameters = self._map_args_to_parameters(tool_name, args)-- # Execute via node executor- result = await self.node_executor(- node_id=f"skill_{tool_name}",- node_type=handler_type,- parameters=parameters,- context=context or {}- )-- return result-- def _map_args_to_parameters(self, tool_name: str, args: Dict[str, Any]) -> Dict[str, Any]:- """Map tool arguments to node parameters.-- Different tools may need different parameter mappings to match- the expected format of their underlying node handlers.- """- # WhatsApp send- if tool_name == 'whatsapp-send':- return {- 'phoneNumber': args.get('phone_number'),- 'message': args.get('message')- }-- # HTTP request - serialize headers and body to JSON strings (handler expects JSON strings)- if tool_name == 'http-request':- headers = args.get('headers')- body = args.get('body')- return {- 'url': args.get('url'),- 'method': args.get('method', 'GET'),- 'body': json.dumps(body) if isinstance(body, dict) else (body or ''),- 'headers': json.dumps(headers) if isinstance(headers, dict) else (headers or '{}'),- 'timeout': 30- }-- # Maps geocode- if tool_name == 'maps-geocode':- return {- 'addresses': [args.get('address')]- }-- # Maps nearby- if tool_name == 'maps-nearby':- return {- 'location': args.get('location'),- 'type': args.get('type'),- 'radius': args.get('radius', 1000)- }-- # Maps create- if tool_name == 'maps-create':- return {- 'center': args.get('center'),- 'zoom': args.get('zoom', 14)- }-- # Scheduler timer- if tool_name == 'scheduler-timer':- return {- 'duration': args.get('duration'),- 'action': args.get('action'),- 'name': args.get('name')- }-- # Scheduler cron- if tool_name == 'scheduler-cron':- return {- 'expression': args.get('expression'),- 'action': args.get('action'),- 'name': args.get('name'),- 'timezone': args.get('timezone', 'UTC')- }-- # Android tools - pass action directly- if tool_name.startswith('android-'):- return args-- # Code execution- if tool_name in ('code-python', 'code-javascript'):- return {- 'code': args.get('code'),- 'input_data': args.get('input_data')- }-- # Default: pass through- return args-- async def _handle_memory_save(self, args: Dict[str, Any]) -> Dict[str, Any]:- """Handle memory save operation."""- if not self.database:- return {"success": False, "error": "Database not available"}-- key = args.get('key')- value = args.get('value')- session_id = args.get('session_id', 'skill_memory')-- try:- # Use conversation message storage for persistence- await self.database.add_conversation_message(- session_id=f"memory_{session_id}_{key}",- role='memory',- content=value- )- return {"success": True, "key": key, "saved": True}- except Exception as e:- logger.error(f"[SkillExecutor] Memory save failed: {e}")- return {"success": False, "error": str(e)}-- async def _handle_memory_get(self, args: Dict[str, Any]) -> Dict[str, Any]:- """Handle memory get operation."""- if not self.database:- return {"success": False, "error": "Database not available"}-- key = args.get('key')- session_id = args.get('session_id', 'skill_memory')-- try:- messages = await self.database.get_conversation_messages(- session_id=f"memory_{session_id}_{key}",- limit=1- )- if messages:- return {"success": True, "key": key, "value": messages[-1].get('content')}- return {"success": True, "key": key, "value": None, "found": False}- except Exception as e:- logger.error(f"[SkillExecutor] Memory get failed: {e}")- return {"success": False, "error": str(e)}-- async def _handle_memory_clear(self, args: Dict[str, Any]) -> Dict[str, Any]:- """Handle memory clear operation."""- if not self.database:- return {"success": False, "error": "Database not available"}-- key = args.get('key')- session_id = args.get('session_id', 'skill_memory')-- try:- if key:- count = await self.database.clear_conversation(f"memory_{session_id}_{key}")- else:- # Clear all memory for session - would need pattern matching- count = 0- return {"success": True, "cleared": count}- except Exception as e:- logger.error(f"[SkillExecutor] Memory clear failed: {e}")- return {"success": False, "error": str(e)}-- async def _handle_scheduler_list(self) -> Dict[str, Any]:- """Handle scheduler list operation."""- # This would integrate with the deployment manager's cron tracking- return {"success": True, "schedules": [], "message": "Scheduler list not yet implemented"}-- async def _handle_scheduler_cancel(self, args: Dict[str, Any]) -> Dict[str, Any]:- """Handle scheduler cancel operation."""- name = args.get('name')- return {"success": True, "cancelled": name, "message": "Scheduler cancel not yet implemented"}-- def build_tools_for_skills(self, skill_names: List[str]) -> List[StructuredTool]:- """Build LangChain StructuredTools for the given skills.-- Args:- skill_names: List of skill names to build tools for-- Returns:- List of LangChain StructuredTool instances- """- tools = []-- for skill_name in skill_names:- skill = self.skill_loader.load_skill(skill_name)- if not skill:- logger.warning(f"[SkillExecutor] Skill not found: {skill_name}")- continue-- # Get allowed tools for this skill- for tool_name in skill.metadata.allowed_tools:- if tool_name not in TOOL_REGISTRY:- logger.warning(f"[SkillExecutor] Unknown tool in skill {skill_name}: {tool_name}")- continue-- config = TOOL_REGISTRY[tool_name]-- # Create placeholder function (actual execution via execute_tool)- def make_placeholder(tn):- def placeholder(**kwargs):- return {"tool_name": tn, "args": kwargs}- return placeholder-- tool = StructuredTool.from_function(- name=tool_name.replace('-', '_'), # LangChain prefers underscores- description=config.description,- func=make_placeholder(tool_name),- args_schema=config.schema- )- tools.append(tool)-- logger.debug(f"[SkillExecutor] Built tool: {tool_name} for skill {skill_name}")-- logger.info(f"[SkillExecutor] Built {len(tools)} tools for {len(skill_names)} skills")- return tools-- def get_tool_config(self, tool_name: str) -> Optional[ToolConfig]:- """Get configuration for a tool by name."""- return TOOL_REGISTRY.get(tool_name)-- def get_all_tools(self) -> List[str]:- """Get list of all available tool names."""- return list(TOOL_REGISTRY.keys())---# Global skill executor instance-_skill_executor: Optional[SkillExecutor] = None---def get_skill_executor() -> Optional[SkillExecutor]:- """Get the global skill executor instance."""- return _skill_executor---def init_skill_executor(skill_loader: "SkillLoader", node_executor, database=None) -> SkillExecutor:- """Initialize the global skill executor.-- Args:- skill_loader: SkillLoader instance- node_executor: NodeExecutor or function to execute node handlers- database: Database instance for memory operations-- Returns:- Initialized SkillExecutor- """- global _skill_executor- _skill_executor = SkillExecutor(skill_loader, node_executor, database)- return _skill_executordiff --git a/server/skills/android-skill/SKILL.md b/server/skills/android-skill/SKILL.mdindex a8ff243d..04ce39c8 100644--- a/server/skills/android-skill/SKILL.md+++ b/server/skills/android-skill/SKILL.md@@ -1,123 +1,71 @@---name: android-skilldescription: Control Android devices - battery, wifi, bluetooth, apps, location, camera, and sensors. Use when user wants to interact with their Android phone or tablet.-allowed-tools: android-battery android-wifi android-bluetooth android-apps android-location android-audio android-screen android-camera android-sensorsmetadata:author: machina- version: "1.0"+ version: "2.0"category: device---# Android Device Control-This skill enables you to monitor and control Android devices connected via ADB or remote WebSocket.+This skill provides context for monitoring and controlling Android devices.-## Capabilities+## How It Works-- Monitor battery status and health-- Control WiFi and Bluetooth-- Launch and list applications-- Get device location-- Control audio and screen-- Access camera and sensors+This skill provides instructions and context. To execute Android actions, connect the **Android Toolkit** node to the Chat Agent's `input-tools` handle, then connect Android service nodes to the toolkit:-## Tool Reference+```+[Battery Monitor] --++ |+[WiFi Automation] --+--> [Android Toolkit] --> [Chat Agent]+ |+[Location] ---++```-### android-battery-Get battery information.+## Available Android Service Nodes-Parameters:-- `action`: "status" (default)+Connect these to the Android Toolkit:-Returns: level, charging, health, temperature+| Node | Capabilities |+|------|-------------|+| **Battery Monitor** | Battery level, charging status, health, temperature |+| **WiFi Automation** | Enable/disable WiFi, scan networks, get status |+| **Bluetooth Automation** | Enable/disable Bluetooth, paired devices |+| **App Launcher** | Launch applications by package name |+| **App List** | List installed applications |+| **Location** | Get current GPS coordinates |+| **Audio Automation** | Volume control, mute/unmute |+| **Screen Control** | Brightness, wake/sleep screen |+| **Camera Control** | Camera info, capture photos |+| **Motion Detection** | Accelerometer, gyroscope data |+| **Environmental Sensors** | Temperature, humidity, pressure |-### android-wifi-Control WiFi settings.--Parameters:-- `action`: "status", "enable", "disable", "scan"--### android-bluetooth-Control Bluetooth settings.--Parameters:-- `action`: "status", "enable", "disable", "paired_devices"--### android-apps-Manage applications.--Parameters:-- `action`: "list", "launch"-- `package_name` (for launch): App package name--### android-location-Get device location.--Parameters:-- `action`: "current"--Returns: latitude, longitude, accuracy, provider--### android-audio-Control audio settings.--Parameters:-- `action`: "get_volume", "set_volume", "mute", "unmute"-- `volume` (for set_volume): 0-100--### android-screen-Control screen settings.--Parameters:-- `action`: "brightness", "set_brightness", "wake", "sleep"-- `level` (for set_brightness): 0-255--### android-camera-Access camera.--Parameters:-- `action`: "info", "capture"-- `camera` (optional): "front" or "back" (default: back)--### android-sensors-Read sensor data.--Parameters:-- `action`: "motion", "environment"--## Examples+## Example Interactions**User**: "What's my phone's battery level?"-**Action**: Use android-battery with:-- action: "status"+- Use the Battery Monitor service with action "status"**User**: "Turn off WiFi"-**Action**: Use android-wifi with:-- action: "disable"+- Use the WiFi Automation service with action "disable"**User**: "What apps are installed?"-**Action**: Use android-apps with:-- action: "list"+- Use the App List service with action "list"**User**: "Open Chrome"-**Action**: Use android-apps with:-- action: "launch"-- package_name: "com.android.chrome"+- Use the App Launcher service with action "launch", package_name "com.android.chrome"**User**: "Where is my phone?"-**Action**: Use android-location with:-- action: "current"+- Use the Location service with action "current"**User**: "Set volume to 50%"-**Action**: Use android-audio with:-- action: "set_volume"-- volume: 50+- Use the Audio Automation service with action "set_volume", volume 50## Device ConnectionBefore using Android tools, ensure:1. Device is connected via ADB (USB) or remote WebSocket-2. Android Device Setup node shows connected status+2. Android Device Setup node shows connected status (green indicator)3. Required permissions are granted on the device## Error Handling@@ -125,3 +73,10 @@ Before using Android tools, ensure:- If device is not connected, inform user to check connection- If permission is denied, suggest enabling it in device settings- If action fails, provide the error message and suggest alternatives++## Setup Requirements++1. Connect this skill to Chat Agent's `input-skill` handle+2. Add **Android Toolkit** node and connect to Chat Agent's `input-tools` handle+3. Connect desired Android service nodes to the Android Toolkit+4. Ensure Android device is paired (green status indicator)diff --git a/server/skills/maps-skill/SKILL.md b/server/skills/maps-skill/SKILL.mdindex cbdad57f..88014354 100644--- a/server/skills/maps-skill/SKILL.md+++ b/server/skills/maps-skill/SKILL.md@@ -1,88 +1,170 @@---name: maps-skilldescription: Location services including geocoding, nearby places, and maps. Use when user asks about addresses, locations, places nearby, or wants to see a map.-allowed-tools: maps-geocode maps-nearby maps-createmetadata:author: machina- version: "1.0"+ version: "3.0"category: location---# Location Services-This skill provides location-based capabilities using Google Maps services.--## Capabilities--- Convert addresses to coordinates (geocoding)-- Find nearby places (restaurants, stores, etc.)-- Create and display maps-- Get place details and information--## Tool Reference--### maps-geocode-Convert an address to geographic coordinates.--Parameters:-- `address` (required): Address or location name to geocode--Returns:-- latitude, longitude-- formatted address-- place ID--### maps-nearby-Search for nearby places.--Parameters:-- `location` (required): Center point (address or "lat,lng")-- `type` (required): Place type (restaurant, cafe, hospital, etc.)-- `radius` (optional): Search radius in meters (default: 1000)--Returns:-- List of places with name, address, rating-- Distance from center point--### maps-create-Create an interactive map.--Parameters:-- `center` (required): Map center (address or "lat,lng")-- `zoom` (optional): Zoom level 1-20 (default: 14)-- `markers` (optional): List of markers to add+This skill provides context for location-based capabilities using Google Maps services.++## How It Works++This skill provides instructions and context. To execute location actions, connect the appropriate **tool nodes** to the Chat Agent's `input-tools` handle:++- **Add Locations** node - Geocode addresses to coordinates or reverse geocode+- **Show Nearby Places** node - Search for nearby places++## add_locations Tool (Geocoding)++Convert addresses to coordinates or coordinates to addresses.++### Schema Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| service_type | string | Yes | "geocode" (address to coordinates) or "reverse_geocode" (coordinates to address) |+| address | string | If geocode | Address to geocode (e.g., "1600 Amphitheatre Parkway, Mountain View, CA") |+| lat | float | If reverse_geocode | Latitude coordinate |+| lng | float | If reverse_geocode | Longitude coordinate |++### Examples++**Geocode address:**+```json+{+ "service_type": "geocode",+ "address": "Eiffel Tower, Paris"+}+```++**Reverse geocode:**+```json+{+ "service_type": "reverse_geocode",+ "lat": 48.8584,+ "lng": 2.2945+}+```++### Response Format++```json+{+ "success": true,+ "service_type": "geocoding",+ "input": {"address": "Eiffel Tower, Paris"},+ "results": [+ {+ "formatted_address": "Champ de Mars, 5 Av. Anatole France, 75007 Paris, France",+ "geometry": {+ "location": {"lat": 48.8583701, "lng": 2.2944813}+ },+ "address_components": [...]+ }+ ],+ "status": "OK"+}+```++## show_nearby_places Tool++Search for places near a location.++### Schema Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| lat | float | Yes | Center latitude for search |+| lng | float | Yes | Center longitude for search |+| radius | int | No | Search radius in meters (default: 500, max: 50000) |+| type | string | No | Place type (default: "restaurant") |+| keyword | string | No | Optional keyword to filter results |++### Examples++**Find nearby restaurants:**+```json+{+ "lat": 40.7484,+ "lng": -73.9857,+ "radius": 500,+ "type": "restaurant"+}+```++**Find coffee shops near a location:**+```json+{+ "lat": 37.7749,+ "lng": -122.4194,+ "type": "cafe",+ "keyword": "starbucks"+}+```++### Response Format++```json+{+ "success": true,+ "type": "restaurant",+ "search_parameters": {+ "location": {"lat": 40.7484, "lng": -73.9857},+ "radius": 500,+ "type": "restaurant"+ },+ "results": [+ {+ "name": "Example Restaurant",+ "vicinity": "123 Main St",+ "rating": 4.5,+ "user_ratings_total": 150,+ "price_level": 2,+ "geometry": {+ "location": {"lat": 40.7485, "lng": -73.9860}+ },+ "types": ["restaurant", "food"],+ "opening_hours": {"open_now": true}+ }+ ],+ "total_results": 10,+ "status": "OK"+}+```## Place TypesCommon place types for nearby search:-- Food: restaurant, cafe, bakery, bar-- Shopping: store, supermarket, shopping_mall-- Services: bank, atm, gas_station, pharmacy-- Health: hospital, doctor, dentist-- Transport: bus_station, train_station, airport-- Entertainment: movie_theater, gym, park+- Food: restaurant, cafe, bakery, bar, meal_takeaway+- Shopping: store, supermarket, shopping_mall, clothing_store+- Services: bank, atm, gas_station, pharmacy, post_office+- Health: hospital, doctor, dentist, pharmacy+- Transport: bus_station, train_station, airport, taxi_stand+- Entertainment: movie_theater, gym, park, museum, zoo-## Examples+## Common Workflows-**User**: "What restaurants are near Times Square?"-**Action**: Use maps-nearby with:-- location: "Times Square, New York"-- type: "restaurant"-- radius: 500+### Find nearby places by address+1. Use `add_locations` with service_type="geocode" to get coordinates+2. Use `show_nearby_places` with the returned lat/lng-**User**: "What's the address of the Eiffel Tower?"-**Action**: Use maps-geocode with:-- address: "Eiffel Tower, Paris"+### Get address from coordinates+1. Use `add_locations` with service_type="reverse_geocode"-**User**: "Show me a map of downtown Seattle"-**Action**: Use maps-create with:-- center: "Downtown Seattle, WA"-- zoom: 15--## Response Format+## Response GuidelinesWhen presenting location results:-1. List the top results with key details-2. Include ratings and distances when available-3. Offer to show more details or refine the search-4. Suggest related searches if appropriate+1. List the top results with name, rating, and address+2. Include distance if available+3. Mention if places are currently open+4. Offer to search for different types or expand radius++## Setup Requirements++1. Connect this skill to Chat Agent's `input-skill` handle+2. Connect location tool nodes to Chat Agent's `input-tools` handle+3. Ensure Google Maps API key is configured in credentialsdiff --git a/server/skills/memory-skill/SKILL.md b/server/skills/memory-skill/SKILL.mdindex 06a649c2..4501b216 100644--- a/server/skills/memory-skill/SKILL.md+++ b/server/skills/memory-skill/SKILL.md@@ -1,91 +1,154 @@---name: memory-skill-description: Remember information across conversations. Use when user asks you to remember something, recall previous information, or manage conversation history.-allowed-tools: memory-save memory-get memory-clear+description: Manage conversation memory. Use when user asks to remember something, recall information, view/edit conversation history, or manage short/long-term memory.+allowed-tools: memory-save memory-get memory-clear memory-view memory-searchmetadata:author: machina- version: "1.0"+ version: "2.0"category: memory----# Memory Management+# Memory Management Skill-This skill enables you to save and recall information across conversations using short-term and long-term memory.+This skill enables you to manage conversation memory using the SimpleMemory node's markdown-based storage system.-## Memory Types+## Memory Architecture-### Short-term Memory (Buffer)-- Keeps recent conversation context-- Automatically managed by the system-- Limited to recent messages+### Short-Term Memory (Markdown)+- Visible and editable in the SimpleMemory node's UI+- Stored as markdown with timestamped entries+- Window-based: keeps last N message pairs (configurable)+- Format: `### **Human** (timestamp)` and `### **Assistant** (timestamp)`-### Long-term Memory (Session)-- Persists information across conversations-- Explicitly saved by you or the user-- Organized by session ID+### Long-Term Memory (Vector DB)+- Automatically archives messages that exceed the window+- Semantic search for relevant past conversations+- Enabled via `longTermEnabled` in SimpleMemory node## Capabilities-- Save important information for later recall-- Retrieve previously saved information-- Clear memory when no longer needed-- Track conversation topics and preferences+1. **View History**: See recent conversation in markdown format+2. **Save Notes**: Add explicit notes/memories to the conversation+3. **Search Memory**: Find relevant past conversations semantically+4. **Clear Memory**: Reset conversation history-## When to Use Memory+## When to Use-Save information when the user:-- Says "remember this" or "don't forget"-- Shares personal preferences-- Provides important context for future use-- Asks you to track something+**Save information when:**+- User says "remember this" or "don't forget"+- Important context is shared for future use+- User wants to note something specific-Recall information when the user:-- Asks "do you remember..."-- References previous conversations-- Needs context from earlier discussions+**Recall information when:**+- User asks "do you remember..."+- Context from earlier is needed+- User references previous discussions++**View history when:**+- User wants to see conversation log+- Debugging or reviewing past exchanges## Tool Reference### memory-save-Save information to long-term memory.+Add a note or memory entry to the conversation history.Parameters:-- `key` (required): Identifier for the memory-- `value` (required): Information to remember-- `session_id` (optional): Session for organization+- `content` (required): Information to remember+- `role` (optional): "note" (default) or "context"++Example:+```json+{+ "content": "User's favorite color is blue",+ "role": "note"+}+```### memory-get-Retrieve saved information.+Get recent conversation history or search for specific content.Parameters:-- `key` (required): Identifier to look up-- `session_id` (optional): Specific session to search+- `count` (optional): Number of recent messages (default: 10)+- `search` (optional): Search term to find specific memories++Example - Recent history:+```json+{+ "count": 5+}+```++Example - Search:+```json+{+ "search": "favorite color"+}+```### memory-clear-Clear memory entries.+Clear conversation history.++Parameters:+- `confirm` (required): Must be true to clear++Example:+```json+{+ "confirm": true+}+```++### memory-view+View the current conversation history in markdown format.++Parameters: None++Returns the full markdown content of the conversation history.++### memory-search+Semantic search in long-term memory (if enabled).Parameters:-- `key` (optional): Specific key to clear, or all if not specified-- `session_id` (optional): Specific session to clear+- `query` (required): Search query+- `count` (optional): Number of results (default: 3)++Example:+```json+{+ "query": "what did we discuss about the project",+ "count": 5+}+```++## Markdown Format++The conversation history uses this format:++```markdown+# Conversation History++### **Human** (2025-01-30 10:15:32)+Hello, how are you?-## Examples+### **Assistant** (2025-01-30 10:15:35)+I'm doing well! How can I help you today?-**User**: "Remember that my favorite color is blue"-**Action**: Use memory-save with:-- key: "user_preference_color"-- value: "blue"+### **Note** (2025-01-30 10:16:00)+User prefers formal language.+```-**User**: "What's my favorite color?"-**Action**: Use memory-get with:-- key: "user_preference_color"+## Integration with SimpleMemory Node-**User**: "Forget everything about my preferences"-**Action**: Use memory-clear with:-- key: "user_preference_*" (wildcard pattern)+When connected to a Chat Agent:+1. Conversation is automatically logged to markdown+2. Window size limits short-term memory+3. Overflow archives to vector DB (if long-term enabled)+4. You can view/edit the markdown in the node's parameter panel## Best Practices-1. Use descriptive keys for easy retrieval-2. Group related information under session IDs-3. Don't store sensitive information without consent-4. Periodically review and clean up old memories+1. Use memory-save for explicit user requests to remember+2. Use memory-search for semantic recall of past discussions+3. Don't save sensitive information without user consent+4. The markdown is editable - users can manually curate their historydiff --git a/server/skills/scheduler-skill/SKILL.md b/server/skills/scheduler-skill/SKILL.mdindex 4e08f542..f4e1263b 100644--- a/server/skills/scheduler-skill/SKILL.md+++ b/server/skills/scheduler-skill/SKILL.md@@ -1,53 +1,30 @@---name: scheduler-skilldescription: Schedule tasks and set timers. Use when user wants to schedule something, set a reminder, create a recurring task, or use cron expressions.-allowed-tools: scheduler-cron scheduler-timer scheduler-list scheduler-cancelmetadata:author: machina- version: "1.0"+ version: "2.0"category: automation---# Task Scheduling-This skill enables you to schedule tasks, set timers, and create recurring jobs.+This skill provides context for scheduling tasks, setting timers, and creating recurring jobs.-## Capabilities--- Create one-time timers-- Set up recurring schedules with cron expressions-- List active schedules-- Cancel scheduled tasks--## Tool Reference--### scheduler-timer-Set a one-time timer.--Parameters:-- `duration` (required): Time until execution (e.g., "5m", "1h", "30s")-- `action` (required): What to do when timer fires-- `name` (optional): Timer identifier--### scheduler-cron-Create a recurring schedule using cron expression.+## How It Works-Parameters:-- `expression` (required): Cron expression (e.g., "0 9 * * *")-- `action` (required): What to do on each trigger-- `name` (optional): Schedule identifier-- `timezone` (optional): Timezone for schedule (default: UTC)+This skill provides instructions and context. Scheduling is handled through workflow deployment:-### scheduler-list-List all active schedules and timers.+- **Cron Scheduler** trigger node - Recurring schedules using cron expressions+- **Timer** trigger node - One-time delayed execution+- **Workflow Trigger** node - Manual workflow execution-Parameters: None--### scheduler-cancel-Cancel a scheduled task.+## Capabilities-Parameters:-- `name` (required): Name of schedule to cancel+When used with workflow triggers:+- Create one-time timers+- Set up recurring schedules with cron expressions+- Deploy workflows that run on schedule## Cron Expression Format@@ -71,36 +48,37 @@ Parameters:| `0 0 1 * *` | First day of each month || `0 8,12,18 * * *` | At 8am, noon, and 6pm |-## Examples+## Example Interactions**User**: "Remind me in 30 minutes"-**Action**: Use scheduler-timer with:-- duration: "30m"-- action: "Send reminder notification"-- name: "user_reminder"+- This requires setting up a Timer trigger workflow+- Inform user: "I can help you create a scheduled workflow. Set up a Timer trigger node with 30 minute delay."**User**: "Send a daily report at 9am"-**Action**: Use scheduler-cron with:-- expression: "0 9 * * *"-- action: "Generate and send daily report"-- name: "daily_report"+- This requires a Cron Scheduler workflow+- Inform user: "Create a workflow with Cron Scheduler trigger using expression '0 9 * * *'"**User**: "Check for updates every hour"-**Action**: Use scheduler-cron with:-- expression: "0 * * * *"-- action: "Check for system updates"-- name: "hourly_update_check"+- This requires a Cron Scheduler workflow+- Inform user: "Create a workflow with Cron Scheduler trigger using expression '0 * * * *'"-**User**: "What schedules are active?"-**Action**: Use scheduler-list+## Workflow-Based Scheduling-**User**: "Cancel the daily report"-**Action**: Use scheduler-cancel with:-- name: "daily_report"+In this system, scheduling is achieved through:++1. **Trigger Nodes**: Cron Scheduler or Timer nodes start workflows+2. **Workflow Deployment**: Deploy the workflow to activate the schedule+3. **Cancel**: Undeploy the workflow to cancel the schedule## Best Practices-1. Always give schedules descriptive names-2. Confirm timezone with user for time-sensitive tasks-3. List active schedules before creating duplicates-4. Provide feedback when schedules are created/cancelled+1. Explain that schedules require workflow deployment+2. Provide the cron expression for the user's request+3. Confirm timezone considerations for time-sensitive tasks+4. Help users understand workflow-based scheduling model++## Limitations++- This skill provides guidance only+- Actual scheduling requires workflow creation and deployment+- Cannot directly create/cancel schedules via chat commandsdiff --git a/server/skills/whatsapp-skill/SKILL.md b/server/skills/whatsapp-skill/SKILL.mdindex e1259fa0..88ed1d63 100644--- a/server/skills/whatsapp-skill/SKILL.md+++ b/server/skills/whatsapp-skill/SKILL.md@@ -1,7 +1,6 @@---name: whatsapp-skilldescription: Send WhatsApp messages, query contacts/groups, retrieve chat history. Look up contact info by name or phone for sending/replying.-allowed-tools: whatsapp_send whatsapp_dbmetadata:author: machinaversion: "3.0"@@ -10,36 +9,30 @@ metadata:# WhatsApp Messaging Skill-Send and receive WhatsApp messages, query contacts and groups using connected WhatsApp nodes.+This skill provides context for WhatsApp messaging capabilities.-## Capabilities+## How It Works-- Send text messages to phone numbers or groups-- Send media messages (images, videos, audio, documents, stickers)-- Send location information-- Send contact cards (vCard)-- **Query contacts** - List contacts with saved names (e.g., "Mummy", "Dad")-- **Get contact info** - Get full info including phone, name, profile picture URL-- **Search groups** - Find groups by name-- **Get group info** - Get group details with participant names and phone numbers-- **Retrieve chat history** - Messages from individual chats or groups-- **Check WhatsApp registration** - Verify if phone numbers are on WhatsApp+This skill provides instructions and context. To execute WhatsApp actions, connect the appropriate **tool nodes** to the Chat Agent's `input-tools` handle:-## whatsapp_send+- **WhatsApp Send** node - Send messages to contacts or groups+- **WhatsApp DB** node - Query contacts, groups, and chat history++## whatsapp_send ToolSend messages to contacts or groups.-### Parameters+### Schema Fields-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|+| Field | Type | Required | Description |+|-------|------|----------|-------------|| recipient_type | string | Yes | "phone" for individual or "group" for group chat || phone | string | If phone | Phone number without + prefix (e.g., 1234567890) || group_id | string | If group | Group JID (e.g., [email protected]) || message_type | string | Yes | "text", "image", "video", "audio", "document", "sticker", "location", "contact" || message | string | If text | Text message content || media_url | string | If media | URL for image/video/audio/document/sticker |-| caption | string | No | Caption for media messages (image, video, document) |+| caption | string | No | Caption for media messages || latitude | float | If location | Latitude coordinate || longitude | float | If location | Longitude coordinate || location_name | string | No | Display name for location |@@ -93,61 +86,61 @@ Send messages to contacts or groups.}```-## whatsapp_db+### Response Format-Query WhatsApp database - contacts, groups, messages.+```json+{+ "success": true,+ "recipient": "1234567890",+ "recipient_type": "phone",+ "message_type": "text",+ "details": {+ "status": "sent",+ "preview": "Hello! How are you?",+ "timestamp": "2025-01-30T12:00:00"+ }+}+```-### Operations+## whatsapp_db Tool-| Operation | Description |-|-----------|-------------|-| `list_contacts` | List all contacts with saved names |-| `get_contact_info` | Get full info for a contact (for sending/replying) |-| `search_groups` | Search groups by name |-| `get_group_info` | Get group details with participant names |-| `chat_history` | Retrieve message history |-| `check_contacts` | Check WhatsApp registration status |+Query WhatsApp database - contacts, groups, messages.-### list_contacts+### Schema Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| operation | string | Yes | "chat_history", "search_groups", "get_group_info", "get_contact_info", "list_contacts", "check_contacts" |+| chat_type | string | For chat_history | "individual" or "group" |+| phone | string | Varies | Phone number for chat_history (individual), get_contact_info |+| group_id | string | Varies | Group JID for chat_history (group), get_group_info |+| message_filter | string | No | For chat_history: "all" or "text_only" |+| group_filter | string | No | For chat_history (group): "all" or "contact" |+| sender_phone | string | No | For chat_history with group_filter="contact" |+| limit | int | No | Max results. chat_history: 1-500 (default 50), search_groups: 1-50 (default 20), list_contacts: 1-100 (default 50) |+| offset | int | No | For chat_history: pagination offset |+| query | string | No | Search query for search_groups, list_contacts. Use specific queries to narrow results |+| phones | string | For check_contacts | Comma-separated phone numbers |+| participant_limit | int | No | For get_group_info: max participants (1-100, default 50) |++**Important:** Always use small limits and specific queries to avoid context overflow errors.-List contacts with their saved names. Useful for finding someone by name.+### Operations-**Parameters:**-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| operation | string | Yes | "list_contacts" |-| query | string | No | Filter by name or phone (empty = all) |+#### list_contacts+List contacts with saved names. Useful for finding someone by name.-**Example - Find contact by name:**```json{"operation": "list_contacts",- "query": "mom"+ "query": "mom",+ "limit": 10}```-**Response:**-```json-{- "contacts": [- {"jid": "[email protected]", "phone": "919876543210", "name": "Mummy", "push_name": "Mom"},- {"jid": "[email protected]", "phone": "918765432109", "name": "Mom Home", "push_name": ""}- ],- "total": 2-}-```+#### get_contact_info+Get full contact info for sending/replying.-### get_contact_info--Get full contact info including profile picture URL. Use this to get phone number from a name for sending messages.--**Parameters:**-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| operation | string | Yes | "get_contact_info" |-| phone | string | Yes | Phone number (without + prefix) |--**Example:**```json{"operation": "get_contact_info",@@ -155,97 +148,31 @@ Get full contact info including profile picture URL. Use this to get phone numbe}```-**Response:**-```json-{- "jid": "[email protected]",- "phone": "919876543210",- "name": "Ajay Flatmate",- "push_name": "Ajay K",- "business_name": "",- "is_business": false,- "is_contact": true,- "profile_pic": "https://pps.whatsapp.net/v/..."-}-```--### search_groups+#### search_groups+Search groups by name. Use specific query to narrow results.-Search for groups by name.--**Parameters:**-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| operation | string | Yes | "search_groups" |-| query | string | No | Group name search (empty = all groups) |--**Example:**```json{"operation": "search_groups",- "query": "family"+ "query": "family",+ "limit": 10}```-**Response:**-```json-{- "groups": [- {"jid": "[email protected]", "name": "Family Group", "participant_count": 12}- ],- "total": 1-}-```+#### get_group_info+Get group details with participant names. Large groups may have many participants.-### get_group_info--Get group details including participant names and phone numbers. Use this to find who is in a group and reply to specific members.--**Parameters:**-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| operation | string | Yes | "get_group_info" |-| group_id | string | Yes | Group JID (e.g., [email protected]) |--**Example:**```json{"operation": "get_group_info",- "group_id": "[email protected]"+ "group_id": "[email protected]",+ "participant_limit": 20}```-**Response:**-```json-{- "jid": "[email protected]",- "name": "Family Group",- "participants": [- {"jid": "[email protected]", "phone": "919876543210", "name": "Dad", "is_admin": true},- {"jid": "[email protected]", "phone": "919987654321", "name": "Mom", "is_admin": false},- {"jid": "[email protected]", "phone": "919123456789", "name": "", "is_admin": false}- ]-}-```+#### chat_history+Retrieve message history.-### chat_history--Retrieve message history from chats.--**Parameters:**-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| operation | string | Yes | "chat_history" |-| chat_type | string | Yes | "individual" or "group" |-| phone | string | If individual | Phone number without + prefix |-| group_id | string | If group | Group JID |-| message_filter | string | No | "all" (default) or "text_only" |-| group_filter | string | No | For groups: "all" (default) or "contact" to filter by sender |-| sender_phone | string | No | For groups with group_filter="contact": filter messages from this phone |-| limit | int | No | Max messages (1-500, default 50) |-| offset | int | No | Skip for pagination (default 0) |--**Example - Individual chat:**```json{"operation": "chat_history",@@ -255,7 +182,6 @@ Retrieve message history from chats.}```-**Example - Group chat:**```json{"operation": "chat_history",@@ -266,33 +192,61 @@ Retrieve message history from chats.}```-**Example - Group chat filtered by sender:**+#### check_contacts+Check WhatsApp registration status.+```json{- "operation": "chat_history",- "chat_type": "group",- "group_id": "[email protected]",- "group_filter": "contact",- "sender_phone": "919876543210",- "limit": 20+ "operation": "check_contacts",+ "phones": "1234567890,0987654321"}```-### check_contacts+### Response Formats-Check if phone numbers are registered on WhatsApp.+**list_contacts response:**+```json+{+ "success": true,+ "operation": "list_contacts",+ "contacts": [+ {"phone": "919876543210", "name": "Mom", "jid": "[email protected]"}+ ],+ "total": 1+}+```-**Parameters:**-| Parameter | Type | Required | Description |-|-----------|------|----------|-------------|-| operation | string | Yes | "check_contacts" |-| phones | string | Yes | Comma-separated phone numbers |+**chat_history response:**+```json+{+ "success": true,+ "operation": "chat_history",+ "messages": [+ {+ "index": 1,+ "message_id": "ABC123",+ "sender": "[email protected]",+ "text": "Hello!",+ "timestamp": "2025-01-30T12:00:00",+ "is_from_me": false+ }+ ],+ "total": 50,+ "has_more": true+}+```-**Example:**+**get_group_info response:**```json{- "operation": "check_contacts",- "phones": "1234567890, 0987654321"+ "success": true,+ "operation": "get_group_info",+ "name": "Family Group",+ "jid": "[email protected]",+ "participants": [+ {"phone": "919876543210", "name": "Mom", "is_admin": true},+ {"phone": "919876543211", "name": "Dad", "is_admin": false}+ ]}```@@ -304,71 +258,26 @@ Check if phone numbers are registered on WhatsApp.2. Get their phone number from the result3. Use `whatsapp_send` with the phone number-```-User: "Send 'Happy Birthday!' to Mom"-1. list_contacts with query="mom" -> finds phone 919876543210-2. whatsapp_send with phone=919876543210, message="Happy Birthday!"-```-### Reply to someone in a group1. Use `get_group_info` to get participant names and phones2. Use `whatsapp_send` with recipient_type="phone" and the person's phone-```-User: "Reply to Dad in Family Group saying 'I'll be there'"-1. search_groups with query="family" -> gets group JID-2. get_group_info -> finds Dad's phone 919876543210-3. whatsapp_send with phone=919876543210, message="I'll be there"-```-### Find and message a group1. Use `search_groups` to find the group by name2. Use `whatsapp_send` with recipient_type="group" and the group_id-## Using as Workflow Node--The WhatsApp DB node can be used directly in workflows (not just as an AI Agent tool):--1. **Add the node**: Drag "WhatsApp DB" from the Component Palette (WhatsApp category)-2. **Select operation**: Choose from the dropdown (Chat History, Search Groups, etc.)-3. **Configure parameters**: The UI shows only relevant parameters based on operation-4. **Connect**: Wire the node's output to downstream nodes-5. **Run**: Click Run to execute and see results in the Output Panel--### Output Variables--Each operation produces different output variables that can be dragged to downstream nodes:--| Operation | Output Fields |-|-----------|--------------|-| chat_history | `messages[]`, `total`, `has_more`, `count` |-| search_groups | `groups[]`, `total`, `query` |-| get_group_info | `jid`, `name`, `participants[]` |-| get_contact_info | `jid`, `phone`, `name`, `push_name`, `profile_pic` |-| list_contacts | `contacts[]`, `total`, `query` |-| check_contacts | `results[]`, `total` |--### Dual-Purpose Node--This node works both as:-- **Workflow Node**: Configure via UI parameters, outputs connect to other nodes-- **AI Agent Tool**: Connect to AI Agent's "Tool" handle for LLM-driven queries-## Guidelines1. **Phone numbers**: Always use without + prefix, just digits (e.g., 919876543210)2. **Groups**: Use JID format ending in @g.us3. **Contact lookup**: Use list_contacts first if you only have a name-4. **Group participants**: Use get_group_info to see who's in a group with their names-5. **Profile pictures**: get_contact_info returns a URL that may expire-6. **Media URLs**: Must be publicly accessible URLs-7. **Pagination**: Use offset with limit to page through chat history+4. **Media URLs**: Must be publicly accessible URLs+5. **Pagination**: Use offset with limit to page through chat history-## Error Handling+## Setup Requirements-- If recipient info is missing, use list_contacts or search_groups to find them-- If message type requires media URL but none provided, request the URL-- If location is requested but coordinates missing, ask for latitude and longitude-- If WhatsApp is not connected, inform the user to check connection status+1. Connect this skill to Chat Agent's `input-skill` handle+2. Connect WhatsApp tool nodes to Chat Agent's `input-tools` handle+3. Ensure WhatsApp is connected (green status indicator)