Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Add Simple/Pro mode toggle and Chat Agent skill system
trohitg4b5d5b2f697f
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 91486dac..4125dfbe 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -28,6 +28,7 @@ import { CHAT_NODE_TYPES } from './nodeDefinitions/chatNodes';import { CODE_NODE_TYPES } from './nodeDefinitions/codeNodes';import { UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes';import { TOOL_NODE_TYPES } from './nodeDefinitions/toolNodes';+import { SKILL_NODE_TYPES } from './nodeDefinitions/skillNodes';import ParameterPanel from './ParameterPanel';import LocationParameterPanel from './components/LocationParameterPanel';import { useAppStore } from './store/useAppStore';@@ -73,7 +74,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {} else if (type === 'openaiChatModel' || type === 'anthropicChatModel' || type === 'geminiChatModel' || type === 'openrouterChatModel' || type === 'groqChatModel' || type === 'cerebrasChatModel') {// AI chat model nodes use square designtypes[type] = SquareNode;- } else if (type === 'aiAgent') {+ } else if (type === 'aiAgent' || type === 'chatAgent') {types[type] = AIAgentNode;} else if (type === 'simpleMemory') {// Simple Memory node for AI conversation history - uses circular ModelNode design@@ -105,6 +106,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {} else {types[type] = ModelNode;}+ } else if (SKILL_NODE_TYPES.includes(type)) {+ // Skill nodes use circular ModelNode design (connect to Chat Agent's input-skill handle)+ types[type] = ModelNode;} else if (definition?.group?.includes('model')) {// Fallback for other model nodestypes[type] = ModelNode;@@ -238,6 +242,8 @@ const DashboardContent: React.FC = () => {migrateCurrentWorkflow,toggleSidebar,toggleComponentPalette,+ proMode,+ toggleProMode,exportWorkflowToJSON,exportWorkflowToFile,setCurrentWorkflow,@@ -374,10 +380,11 @@ const DashboardContent: React.FC = () => {let className = '';- // Check if this edge connects to an AI Agent's memory or tools handle+ // Check if this edge connects to an AI Agent's memory or tools/skill handleconst isMemoryConnection = edge.targetHandle === 'input-memory';const isToolConnection = edge.targetHandle === 'input-tools';- const isAIAgentTarget = targetNode?.type === 'aiAgent';+ const isSkillConnection = edge.targetHandle === 'input-skill';+ const isAIAgentTarget = targetNode?.type === 'aiAgent' || targetNode?.type === 'chatAgent';// Highlight memory/tool connections when AI Agent is executing and using themif (isAIAgentTarget && targetStatus?.status === 'executing') {@@ -399,6 +406,12 @@ const DashboardContent: React.FC = () => {className = 'tool-active';}}+ // Skill connection highlights during skill-related phases (Chat Agent)+ else if (isSkillConnection) {+ if (phase === 'invoking_llm' || phase === 'loading_skills') {+ className = 'skill-active';+ }+ }}// Standard edge status classes - ONLY apply during active execution or deployment@@ -963,6 +976,8 @@ const DashboardContent: React.FC = () => {onToggleSidebar={toggleSidebar}componentPaletteVisible={componentPaletteVisible}onToggleComponentPalette={toggleComponentPalette}+ proMode={proMode}+ onToggleProMode={toggleProMode}onOpenSettings={() => setSettingsOpen(true)}onOpenCredentials={() => setCredentialsOpen(true)}onExportJSON={handleExportJSON}@@ -1065,6 +1080,7 @@ const DashboardContent: React.FC = () => {collapsedSections={collapsedSections}onToggleSection={toggleSection}onDragStart={handleComponentDragStart}+ proMode={proMode}/>)}</div>diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex 93ed158f..a7f6bed7 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -19,19 +19,74 @@ const PHASE_CONFIG: Record<string, { icon: string; label: string; color: stringsaving_memory: { icon: '💾', label: 'Saving Memory', color: '#bd93f9' },};+// Configuration for different agent types+interface AgentConfig {+ icon: React.ReactNode;+ title: string;+ subtitle: string;+ accentColor: string;+ bottomHandles: Array<{ id: string; label: string; position: string }>;+}++// Lucide-style SVG icons+const RobotIcon = ({ size = 32, color = 'currentColor' }: { size?: number; color?: string }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">+ <rect x="3" y="11" width="18" height="10" rx="2" />+ <circle cx="12" cy="5" r="2" />+ <path d="M12 7v4" />+ <line x1="8" y1="16" x2="8" y2="16" />+ <line x1="16" y1="16" x2="16" y2="16" />+ <circle cx="8" cy="16" r="1" fill={color} />+ <circle cx="16" cy="16" r="1" fill={color} />+ </svg>+);++// Lucide MessageSquare icon - clean chat bubble+const ChatAgentIcon = ({ size = 32, color = 'currentColor' }: { size?: number; color?: string }) => (+ <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />+ </svg>+);++const AGENT_CONFIGS: Record<string, AgentConfig> = {+ aiAgent: {+ icon: <RobotIcon />,+ title: 'AI Agent',+ subtitle: 'LangGraph Agent',+ accentColor: '#9333EA',+ bottomHandles: [+ { id: 'input-memory', label: 'Memory', position: '35%' },+ { id: 'input-tools', label: 'Tool', position: '65%' },+ ],+ },+ chatAgent: {+ icon: <ChatAgentIcon />,+ title: 'Chat Agent',+ subtitle: 'Conversational Agent',+ accentColor: '#3B82F6',+ bottomHandles: [+ { id: 'input-memory', label: 'Memory', position: '35%' },+ { id: 'input-skill', label: 'Skill', position: '65%' },+ ],+ },+};+const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectable, selected }) => {const theme = useAppTheme();const { setSelectedNode } = useAppStore();const [_configValid, setConfigValid] = useState(true);const [_configErrors, setConfigErrors] = useState<string[]>([]);+ // Get config based on node type+ const config = AGENT_CONFIGS[type || 'aiAgent'] || AGENT_CONFIGS.aiAgent;+// Get real-time node status from WebSocketconst nodeStatus = useNodeStatus(id);const isExecuting = nodeStatus?.status === 'executing';const currentPhase = nodeStatus?.data?.phase as string | undefined;const phaseConfig = currentPhase ? PHASE_CONFIG[currentPhase] : null;- // Validate AI Agent configuration whenever data changes+ // Validate configuration whenever data changesuseEffect(() => {try {const validation = AIAgentExecutionService.validateConfiguration(data || {});@@ -39,26 +94,24 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectasetConfigErrors(validation.errors);if (!validation.valid) {- console.warn(`AI Agent ${id} configuration issues:`, validation.errors);+ console.warn(`${config.title} ${id} configuration issues:`, validation.errors);}} catch (error) {console.error('Configuration validation error:', error);setConfigValid(false);setConfigErrors(['Configuration validation failed']);}- }, [data, id]);+ }, [data, id, config.title]);const handleParametersClick = (e: React.MouseEvent) => {e.stopPropagation();setSelectedNode({ id, type, data, position: { x: 0, y: 0 } });};- // Determine border and glow based on execution stateconst getBorderColor = () => {if (isExecuting) {if (theme.isDarkMode && phaseConfig) return phaseConfig.color;- // Light mode - use consistent blue- return '#2563eb';+ return config.accentColor;}if (selected) return theme.colors.focus;return theme.colors.border;@@ -69,8 +122,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaif (theme.isDarkMode && phaseConfig) {return `0 0 20px ${phaseConfig.color}80, 0 0 40px ${phaseConfig.color}40`;}- // Light mode - use consistent blue- return `0 0 0 3px rgba(37, 99, 235, 0.5), 0 4px 16px rgba(37, 99, 235, 0.35)`;+ return `0 0 0 3px ${config.accentColor}80, 0 4px 16px ${config.accentColor}60`;}if (selected) {return `0 4px 12px ${theme.colors.focusRing}, 0 0 0 1px ${theme.colors.focusRing}`;@@ -104,7 +156,6 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaanimation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none'}}>-{/* Input Handle */}<Handleid="input-main"@@ -152,7 +203,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta⚙️</button>- {/* Status Indicator - Top Left */}+ {/* Status Indicator */}<divstyle={{position: 'absolute',@@ -169,7 +220,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaboxShadow: isExecuting? (theme.isDarkMode? `0 0 8px ${phaseConfig?.color || theme.dracula.cyan}`- : '0 0 4px rgba(37, 99, 235, 0.5)')+ : `0 0 4px ${config.accentColor}80`): 'none',animation: isExecuting ? 'pulse 1s ease-in-out infinite' : 'none',zIndex: 20@@ -177,16 +228,12 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectatitle={isExecuting ? (phaseConfig?.label || 'Executing') : (nodeStatus?.status || 'Idle')}/>- {/* Robot Icon */}- <div style={{- fontSize: theme.iconSize.xl,- lineHeight: '1',- marginBottom: theme.spacing.xs- }}>- 🤖+ {/* Icon */}+ <div style={{ lineHeight: '1', marginBottom: theme.spacing.xs, color: config.accentColor }}>+ {config.icon}</div>- {/* AI Agent Text */}+ {/* Title */}<div style={{fontSize: theme.fontSize.base,fontWeight: theme.fontWeight.semibold,@@ -194,10 +241,10 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectalineHeight: '1.2',marginBottom: theme.spacing.xs}}>- AI Agent+ {config.title}</div>- {/* Subtitle - shows execution phase or default */}+ {/* Subtitle */}<div style={{fontSize: theme.fontSize.xs,fontWeight: theme.fontWeight.normal,@@ -206,10 +253,10 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectamarginBottom: theme.spacing.lg,transition: 'color 0.3s ease'}}>- {isExecuting && phaseConfig ? phaseConfig.label : 'LangGraph Agent'}+ {isExecuting && phaseConfig ? phaseConfig.label : config.subtitle}</div>- {/* Parameter Labels */}+ {/* Bottom Handle Labels */}<div style={{position: 'absolute',bottom: theme.spacing.lg,@@ -221,50 +268,33 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectacolor: theme.colors.textSecondary,fontWeight: theme.fontWeight.normal}}>- <span>Memory</span>- <span>Tool</span>+ {config.bottomHandles.map(h => <span key={h.id}>{h.label}</span>)}</div>- {/* Parameter Handles */}- <Handle- id="input-memory"- type="target"- position={Position.Bottom}- isConnectable={isConnectable}- style={{- position: 'absolute',- bottom: '-6px',- left: '35%',- width: theme.nodeSize.handle,- height: theme.nodeSize.handle,- backgroundColor: theme.colors.background,- border: `2px solid ${theme.colors.textSecondary}`,- borderRadius: '0',- transform: 'translateX(-50%) rotate(45deg)'- }}- title="Memory"- />-- <Handle- id="input-tools"- type="target"- position={Position.Bottom}- isConnectable={isConnectable}- style={{- position: 'absolute',- bottom: '-6px',- left: '65%',- width: theme.nodeSize.handle,- height: theme.nodeSize.handle,- backgroundColor: theme.colors.background,- border: `2px solid ${theme.colors.textSecondary}`,- borderRadius: '0',- transform: 'translateX(-50%) rotate(45deg)'- }}- title="Tools"- />+ {/* Bottom Handles */}+ {config.bottomHandles.map(h => (+ <Handle+ key={h.id}+ id={h.id}+ type="target"+ position={Position.Bottom}+ isConnectable={isConnectable}+ style={{+ position: 'absolute',+ bottom: '-6px',+ left: h.position,+ width: theme.nodeSize.handle,+ height: theme.nodeSize.handle,+ backgroundColor: theme.colors.background,+ border: `2px solid ${theme.colors.textSecondary}`,+ borderRadius: '0',+ transform: 'translateX(-50%) rotate(45deg)'+ }}+ title={h.label}+ />+ ))}- {/* Output Handles */}+ {/* Output Handle */}<Handleid="output-main"type="source"@@ -283,7 +313,6 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta}}title="Main Output"/>-</div>);};diff --git a/client/src/components/SkillEditorModal.tsx b/client/src/components/SkillEditorModal.tsxnew file mode 100644index 00000000..db517039--- /dev/null+++ b/client/src/components/SkillEditorModal.tsx@@ -0,0 +1,417 @@+import React, { useState, useEffect, useCallback } from 'react';+import Modal from './ui/Modal';+import CodeEditor from './ui/CodeEditor';+import { useAppTheme } from '../hooks/useAppTheme';+import { useWebSocket } from '../contexts/WebSocketContext';++interface UserSkill {+ id?: number;+ name: string;+ display_name: string;+ description: string;+ instructions: string;+ allowed_tools: string[];+ category: string;+ icon: string;+ color: string;+ is_active: boolean;+}++interface SkillEditorModalProps {+ isOpen: boolean;+ onClose: () => void;+ skill?: UserSkill | null;+ onSave?: (skill: UserSkill) => void;+}++const DEFAULT_SKILL: UserSkill = {+ name: '',+ display_name: '',+ description: '',+ instructions: `# My Custom Skill++## Capabilities+- Describe what this skill can do+- List the main functions++## Usage+Explain when and how the Chat Agent should use this skill.++## Examples++**User**: "Example request"+**Action**: Describe what the skill does in response+`,+ allowed_tools: [],+ category: 'custom',+ icon: 'star',+ color: '#6366F1',+ is_active: true+};++const ICON_OPTIONS = [+ { value: 'star', label: 'Star', icon: '...' },+ { value: 'sparkles', label: 'Sparkles', icon: '...' },+ { value: 'brain', label: 'Brain', icon: '...' },+ { value: 'code', label: 'Code', icon: '...' },+ { value: 'globe', label: 'Globe', icon: '...' },+ { value: 'chat', label: 'Chat', icon: '...' },+ { value: 'calendar', label: 'Calendar', icon: '...' },+ { value: 'settings', label: 'Settings', icon: '...' },+];++const CATEGORY_OPTIONS = [+ { value: 'custom', label: 'Custom' },+ { value: 'communication', label: 'Communication' },+ { value: 'productivity', label: 'Productivity' },+ { value: 'automation', label: 'Automation' },+ { value: 'integration', label: 'Integration' },+ { value: 'utility', label: 'Utility' },+];++const COLOR_OPTIONS = [+ '#6366F1', // Indigo+ '#8B5CF6', // Purple+ '#EC4899', // Pink+ '#EF4444', // Red+ '#F59E0B', // Amber+ '#10B981', // Emerald+ '#3B82F6', // Blue+ '#06B6D4', // Cyan+];++const SkillEditorModal: React.FC<SkillEditorModalProps> = ({+ isOpen,+ onClose,+ skill,+ onSave+}) => {+ const theme = useAppTheme();+ const { sendRequest } = useWebSocket();+ const [formData, setFormData] = useState<UserSkill>(DEFAULT_SKILL);+ const [isSaving, setIsSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [activeTab, setActiveTab] = useState<'details' | 'instructions'>('details');++ // Reset form when skill changes or modal opens+ useEffect(() => {+ if (isOpen) {+ if (skill) {+ setFormData(skill);+ } else {+ setFormData(DEFAULT_SKILL);+ }+ setError(null);+ }+ }, [isOpen, skill]);++ const handleInputChange = useCallback((field: keyof UserSkill, value: any) => {+ setFormData(prev => ({ ...prev, [field]: value }));+ }, []);++ const handleNameChange = useCallback((value: string) => {+ // Auto-generate internal name from display name (lowercase, hyphenated)+ const internalName = value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');+ setFormData(prev => ({+ ...prev,+ display_name: value,+ name: prev.id ? prev.name : internalName // Only auto-generate for new skills+ }));+ }, []);++ const validateForm = (): boolean => {+ if (!formData.name.trim()) {+ setError('Skill name is required');+ return false;+ }+ if (!formData.display_name.trim()) {+ setError('Display name is required');+ return false;+ }+ if (!formData.description.trim()) {+ setError('Description is required');+ return false;+ }+ if (!formData.instructions.trim()) {+ setError('Instructions are required');+ return false;+ }+ return true;+ };++ const handleSave = async () => {+ if (!validateForm()) return;++ setIsSaving(true);+ setError(null);++ try {+ const messageType = skill?.id ? 'update_user_skill' : 'create_user_skill';+ const response = await sendRequest(messageType, {+ ...formData,+ allowed_tools: formData.allowed_tools.join(',')+ });++ if (response?.success) {+ onSave?.(response.skill);+ onClose();+ } else {+ setError(response?.error || 'Failed to save skill');+ }+ } catch (err: any) {+ setError(err.message || 'Failed to save skill');+ } finally {+ setIsSaving(false);+ }+ };++ const inputStyle: React.CSSProperties = {+ width: '100%',+ padding: theme.spacing.sm,+ backgroundColor: theme.colors.backgroundAlt,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ color: theme.colors.text,+ fontSize: theme.fontSize.sm,+ outline: 'none'+ };++ const labelStyle: React.CSSProperties = {+ display: 'block',+ marginBottom: theme.spacing.xs,+ fontSize: theme.fontSize.sm,+ color: theme.colors.textSecondary,+ fontWeight: theme.fontWeight.medium+ };++ const tabStyle = (isActive: boolean): React.CSSProperties => ({+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ backgroundColor: isActive ? theme.colors.backgroundPanel : 'transparent',+ border: 'none',+ borderBottom: isActive ? `2px solid ${theme.dracula.purple}` : '2px solid transparent',+ color: isActive ? theme.colors.text : theme.colors.textSecondary,+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ cursor: 'pointer',+ transition: `all ${theme.transitions.fast}`+ });++ return (+ <Modal+ isOpen={isOpen}+ onClose={onClose}+ title={skill?.id ? 'Edit Skill' : 'Create Skill'}+ maxWidth="700px"+ maxHeight="85vh"+ >+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Tabs */}+ <div style={{+ display: 'flex',+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.background+ }}>+ <button style={tabStyle(activeTab === 'details')} onClick={() => setActiveTab('details')}>+ Details+ </button>+ <button style={tabStyle(activeTab === 'instructions')} onClick={() => setActiveTab('instructions')}>+ Instructions+ </button>+ </div>++ {/* Tab Content */}+ <div style={{ flex: 1, overflow: 'auto', padding: theme.spacing.lg }}>+ {activeTab === 'details' && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: theme.spacing.lg }}>+ {/* Display Name */}+ <div>+ <label style={labelStyle}>Display Name *</label>+ <input+ type="text"+ value={formData.display_name}+ onChange={(e) => handleNameChange(e.target.value)}+ placeholder="My Custom Skill"+ style={inputStyle}+ />+ </div>++ {/* Internal Name (readonly for existing skills) */}+ <div>+ <label style={labelStyle}>Internal Name *</label>+ <input+ type="text"+ value={formData.name}+ onChange={(e) => handleInputChange('name', e.target.value.toLowerCase().replace(/\s+/g, '-'))}+ placeholder="my-custom-skill"+ style={{ ...inputStyle, opacity: skill?.id ? 0.7 : 1 }}+ readOnly={!!skill?.id}+ />+ <span style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ Used internally to identify the skill+ </span>+ </div>++ {/* Description */}+ <div>+ <label style={labelStyle}>Description *</label>+ <textarea+ value={formData.description}+ onChange={(e) => handleInputChange('description', e.target.value)}+ placeholder="A short description of what this skill does..."+ rows={3}+ style={{ ...inputStyle, resize: 'vertical', minHeight: '80px' }}+ />+ <span style={{ fontSize: theme.fontSize.xs, color: theme.colors.textMuted }}>+ This appears in the skill registry to help the Chat Agent decide when to use it+ </span>+ </div>++ {/* Category & Color Row */}+ <div style={{ display: 'flex', gap: theme.spacing.lg }}>+ <div style={{ flex: 1 }}>+ <label style={labelStyle}>Category</label>+ <select+ value={formData.category}+ onChange={(e) => handleInputChange('category', e.target.value)}+ style={inputStyle}+ >+ {CATEGORY_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ </div>+ <div style={{ flex: 1 }}>+ <label style={labelStyle}>Color</label>+ <div style={{ display: 'flex', gap: theme.spacing.xs, flexWrap: 'wrap' }}>+ {COLOR_OPTIONS.map(color => (+ <button+ key={color}+ onClick={() => handleInputChange('color', color)}+ style={{+ width: '28px',+ height: '28px',+ borderRadius: theme.borderRadius.sm,+ backgroundColor: color,+ border: formData.color === color ? '2px solid white' : 'none',+ cursor: 'pointer',+ boxShadow: formData.color === color ? `0 0 0 2px ${color}` : 'none'+ }}+ />+ ))}+ </div>+ </div>+ </div>++ {/* Icon */}+ <div>+ <label style={labelStyle}>Icon</label>+ <select+ value={formData.icon}+ onChange={(e) => handleInputChange('icon', e.target.value)}+ style={inputStyle}+ >+ {ICON_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ </div>++ {/* Active Toggle */}+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <input+ type="checkbox"+ checked={formData.is_active}+ onChange={(e) => handleInputChange('is_active', e.target.checked)}+ style={{ width: '18px', height: '18px', cursor: 'pointer' }}+ />+ <label style={{ ...labelStyle, margin: 0 }}>Skill is active</label>+ </div>+ </div>+ )}++ {activeTab === 'instructions' && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: theme.spacing.md, height: '100%' }}>+ <div style={{ fontSize: theme.fontSize.sm, color: theme.colors.textSecondary }}>+ Write markdown instructions for the Chat Agent. Include capabilities, usage guidelines, and examples.+ </div>+ <div style={{ flex: 1, minHeight: '400px' }}>+ <CodeEditor+ value={formData.instructions}+ onChange={(value) => handleInputChange('instructions', value)}+ language="markdown"+ placeholder="# Skill Instructions++## Capabilities+- ...++## Usage+...++## Examples+..."+ />+ </div>+ </div>+ )}+ </div>++ {/* Error */}+ {error && (+ <div style={{+ padding: theme.spacing.md,+ backgroundColor: `${theme.dracula.red}20`,+ color: theme.dracula.red,+ fontSize: theme.fontSize.sm,+ borderTop: `1px solid ${theme.colors.border}`+ }}>+ {error}+ </div>+ )}++ {/* Footer */}+ <div style={{+ display: 'flex',+ justifyContent: 'flex-end',+ gap: theme.spacing.md,+ padding: theme.spacing.lg,+ borderTop: `1px solid ${theme.colors.border}`,+ backgroundColor: theme.colors.backgroundPanel+ }}>+ <button+ onClick={onClose}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ backgroundColor: 'transparent',+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ color: theme.colors.text,+ fontSize: theme.fontSize.sm,+ cursor: 'pointer'+ }}+ >+ Cancel+ </button>+ <button+ onClick={handleSave}+ disabled={isSaving}+ style={{+ padding: `${theme.spacing.sm} ${theme.spacing.lg}`,+ backgroundColor: theme.dracula.purple,+ border: 'none',+ borderRadius: theme.borderRadius.md,+ color: 'white',+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ cursor: isSaving ? 'not-allowed' : 'pointer',+ opacity: isSaving ? 0.7 : 1+ }}+ >+ {isSaving ? 'Saving...' : (skill?.id ? 'Update Skill' : 'Create Skill')}+ </button>+ </div>+ </div>+ </Modal>+ );+};++export default SkillEditorModal;diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex f573c9b0..557f0501 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -337,7 +337,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =// Node type detectionconst isMemory = nodeType === 'simpleMemory';const nodeTypeLower = nodeType.toLowerCase();- const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || nodeTypeLower.includes('aiagent'));+ const isAI = !isMemory && (nodeTypeLower.includes('chatmodel') || nodeTypeLower.includes('aiagent') || nodeTypeLower.includes('chatagent'));const isFile = nodeType.includes('file');const isWhatsAppChatHistory = nodeType === 'whatsappChatHistory';const isWhatsApp = !isWhatsAppChatHistory && (nodeType.includes('whatsapp') || nodeType.includes('Whatsapp'));diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsxindex a2b9558c..37f62069 100644--- a/client/src/components/parameterPanel/MiddleSection.tsx+++ b/client/src/components/parameterPanel/MiddleSection.tsx@@ -1,13 +1,26 @@-import React, { useState } from 'react';+import React, { useState, useEffect } from 'react';import ParameterRenderer from '../ParameterRenderer';import ToolSchemaEditor from './ToolSchemaEditor';import { useAppTheme } from '../../hooks/useAppTheme';+import { useAppStore } from '../../store/useAppStore';+import { nodeDefinitions } from '../../nodeDefinitions';import { INodeTypeDescription, INodeProperties } from '../../types/INodeProperties';import { ExecutionResult } from '../../services/executionService';+import { Edge } from 'reactflow';+import { SKILL_NODE_TYPES } from '../../nodeDefinitions/skillNodes';// Tool node types that support schema editingconst TOOL_NODE_TYPES = ['androidTool', 'calculatorTool', 'currentTimeTool', 'webSearchTool'];+interface ConnectedSkill {+ id: string;+ name: string;+ type: string;+ icon: string;+ description: string;+ color: string;+}+interface MiddleSectionProps {nodeId: string;nodeDefinition: INodeTypeDescription;@@ -50,7 +63,10 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({executionResults = []}) => {const theme = useAppTheme();+ const { currentWorkflow } = useAppStore();const [isConsoleExpanded, setIsConsoleExpanded] = useState(true);+ const [connectedSkills, setConnectedSkills] = useState<ConnectedSkill[]>([]);+ const [isSkillsExpanded, setIsSkillsExpanded] = useState(true);const visibleParams = (nodeDefinition.properties || []).filter((param: INodeProperties) => shouldShowParameter(param, parameters));@@ -58,9 +74,52 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({// Check if this is a code executor node (Python or JavaScript)const isCodeExecutorNode = nodeDefinition.name === 'pythonExecutor' || nodeDefinition.name === 'javascriptExecutor';+ // 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';++ // Nodes that need flexible code editor layout+ const needsCodeEditorLayout = isCodeExecutorNode || isSkillNode;+// Check if this is a tool node that supports schema editingconst isToolNode = TOOL_NODE_TYPES.includes(nodeDefinition.name);+ // Check if this is a Chat Agent node+ const isChatAgentNode = nodeDefinition.name === 'chatAgent';++ // Get connected skills for Chat Agent nodes+ useEffect(() => {+ if (!isChatAgentNode || !currentWorkflow) {+ setConnectedSkills([]);+ return;+ }++ const nodes = currentWorkflow.nodes || [];+ const edges = currentWorkflow.edges || [];++ // Find edges connecting to this node's input-skill handle+ const skillEdges = edges.filter((edge: Edge) =>+ edge.target === nodeId && edge.targetHandle === 'input-skill'+ );++ // Get skill node data+ const skills: ConnectedSkill[] = skillEdges.map((edge: Edge) => {+ const sourceNode = nodes.find((n: any) => n.id === edge.source);+ const nodeType = sourceNode?.type || '';+ const nodeDef = nodeDefinitions[nodeType];++ return {+ id: edge.source,+ name: sourceNode?.data?.label || nodeDef?.displayName || nodeType,+ type: nodeType,+ icon: nodeDef?.icon || '',+ description: nodeDef?.description || '',+ color: nodeDef?.defaults?.color as string || '#6366F1',+ };+ });++ setConnectedSkills(skills);+ }, [nodeId, isChatAgentNode, currentWorkflow]);+// Extract console output from execution resultsconst getConsoleOutput = (): string => {if (executionResults.length === 0) return '';@@ -95,8 +154,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({overflow: 'hidden',position: 'relative'}}>- {/* Description - hide for Python nodes */}- {!isCodeExecutorNode && (+ {/* Description - hide for code editor nodes (Python, Skill) */}+ {!needsCodeEditorLayout && (<div style={{padding: `${theme.spacing.lg} ${theme.spacing.xl} ${theme.spacing.sm}`,borderBottom: `1px solid ${theme.colors.border}`,@@ -119,13 +178,13 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({{/* Parameters */}<div style={{padding: theme.spacing.xl,- flex: isCodeExecutorNode ? '3' : 1,- overflowY: isCodeExecutorNode ? 'hidden' : 'auto',+ flex: needsCodeEditorLayout ? '3' : 1,+ overflowY: needsCodeEditorLayout ? 'hidden' : 'auto',overflowX: 'hidden',width: '100%',boxSizing: 'border-box',minHeight: 0,- display: isCodeExecutorNode ? 'flex' : 'block',+ display: needsCodeEditorLayout ? 'flex' : 'block',flexDirection: 'column'}}>{/* Parameters Container */}@@ -135,23 +194,26 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({borderRadius: theme.borderRadius.md,padding: theme.spacing.lg,boxShadow: `0 1px 3px ${theme.colors.shadowLight}`,- height: isCodeExecutorNode ? '100%' : 'auto',- display: isCodeExecutorNode ? 'flex' : 'block',+ height: needsCodeEditorLayout ? '100%' : 'auto',+ display: needsCodeEditorLayout ? 'flex' : 'block',flexDirection: 'column',boxSizing: 'border-box'}}>{/* All Parameters - standard n8n style */}- {visibleParams.map((param: INodeProperties, index: number) => (+ {visibleParams.map((param: INodeProperties, index: number) => {+ // Check if this parameter is a code editor - give it more flex space+ const isCodeParam = (param as any).typeOptions?.editor === 'code';+ return (<divkey={param.name}style={{paddingBottom: index < visibleParams.length - 1 ? theme.spacing.md : 0,marginBottom: index < visibleParams.length - 1 ? theme.spacing.md : 0,borderBottom: index < visibleParams.length - 1 ? `1px solid ${theme.colors.border}` : 'none',- flex: isCodeExecutorNode ? 1 : 'none',- display: isCodeExecutorNode ? 'flex' : 'block',+ flex: needsCodeEditorLayout && isCodeParam ? 1 : 'none',+ display: needsCodeEditorLayout ? 'flex' : 'block',flexDirection: 'column',- minHeight: 0+ minHeight: needsCodeEditorLayout && isCodeParam ? '300px' : 0}}><ParameterRenderer@@ -164,7 +226,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({isLoadingParameters={isLoadingParameters}/></div>- ))}+ );+ })}{/* Tool Schema Editor - Only for tool nodes */}{isToolNode && (@@ -175,6 +238,186 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({/>)}</div>++ {/* Connected Skills Section - Only for Chat Agent nodes */}+ {isChatAgentNode && (+ <div style={{+ marginTop: theme.spacing.lg,+ backgroundColor: theme.colors.background,+ border: `1px solid ${theme.colors.border}`,+ borderRadius: theme.borderRadius.md,+ boxShadow: `0 1px 3px ${theme.colors.shadowLight}`,+ overflow: 'hidden'+ }}>+ {/* Skills Header */}+ <div+ onClick={() => setIsSkillsExpanded(!isSkillsExpanded)}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: `${theme.spacing.sm} ${theme.spacing.md}`,+ backgroundColor: theme.colors.backgroundAlt,+ borderBottom: isSkillsExpanded ? `1px solid ${theme.colors.border}` : 'none',+ cursor: 'pointer',+ userSelect: 'none'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.colors.textSecondary}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{+ transform: isSkillsExpanded ? 'rotate(90deg)' : 'rotate(0deg)',+ transition: 'transform 0.2s ease'+ }}+ >+ <polyline points="9 18 15 12 9 6" />+ </svg>+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.dracula.purple}+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />+ </svg>+ <span style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.medium,+ color: theme.colors.text+ }}>+ Connected Skills+ </span>+ </div>+ <span style={{+ fontSize: theme.fontSize.xs,+ color: connectedSkills.length > 0 ? theme.dracula.purple : theme.colors.textMuted,+ padding: `2px ${theme.spacing.sm}`,+ backgroundColor: connectedSkills.length > 0 ? theme.dracula.purple + '20' : theme.colors.backgroundAlt,+ borderRadius: theme.borderRadius.sm,+ fontWeight: theme.fontWeight.medium+ }}>+ {connectedSkills.length}+ </span>+ </div>++ {/* Skills Content */}+ {isSkillsExpanded && (+ <div style={{ padding: theme.spacing.md }}>+ {connectedSkills.length === 0 ? (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: theme.spacing.lg,+ color: theme.colors.textMuted,+ textAlign: 'center'+ }}>+ <svg+ width="32"+ height="32"+ viewBox="0 0 24 24"+ fill="none"+ stroke={theme.colors.textMuted}+ strokeWidth="1.5"+ strokeLinecap="round"+ strokeLinejoin="round"+ style={{ marginBottom: theme.spacing.sm, opacity: 0.5 }}+ >+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />+ </svg>+ <span style={{ fontSize: theme.fontSize.sm, marginBottom: theme.spacing.xs }}>+ No skills connected+ </span>+ <span style={{ fontSize: theme.fontSize.xs }}>+ Connect skill nodes to the Skill handle to add capabilities+ </span>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: theme.spacing.sm }}>+ {connectedSkills.map((skill) => (+ <div+ key={skill.id}+ style={{+ display: 'flex',+ alignItems: 'flex-start',+ gap: theme.spacing.md,+ padding: theme.spacing.md,+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: theme.borderRadius.md,+ border: `1px solid ${theme.colors.border}`,+ borderLeft: `3px solid ${skill.color}`+ }}+ >+ {/* Skill Icon */}+ <div style={{+ width: 36,+ height: 36,+ borderRadius: theme.borderRadius.md,+ backgroundColor: skill.color + '20',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0+ }}>+ <span style={{ fontSize: 18 }}>{skill.icon}</span>+ </div>++ {/* Skill Info */}+ <div style={{ flex: 1, minWidth: 0 }}>+ <div style={{+ fontSize: theme.fontSize.sm,+ fontWeight: theme.fontWeight.semibold,+ color: theme.colors.text,+ marginBottom: 2+ }}>+ {skill.name}+ </div>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textMuted,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ display: '-webkit-box',+ WebkitLineClamp: 2,+ WebkitBoxOrient: 'vertical'+ }}>+ {skill.description}+ </div>+ </div>++ {/* Active Badge */}+ <div style={{+ fontSize: '10px',+ fontWeight: theme.fontWeight.medium,+ color: theme.dracula.green,+ padding: `2px ${theme.spacing.xs}`,+ backgroundColor: theme.dracula.green + '20',+ borderRadius: theme.borderRadius.sm,+ flexShrink: 0+ }}>+ Active+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ )}</div>{/* Console Output Section - Only for Python nodes */}diff --git a/client/src/components/ui/CodeEditor.tsx b/client/src/components/ui/CodeEditor.tsxindex 2d1c8ea6..d8ea3e9c 100644--- a/client/src/components/ui/CodeEditor.tsx+++ b/client/src/components/ui/CodeEditor.tsx@@ -4,6 +4,7 @@ import Prism from 'prismjs';import 'prismjs/components/prism-python';import 'prismjs/components/prism-javascript';import 'prismjs/components/prism-typescript';+import 'prismjs/components/prism-markdown';import { useAppTheme } from '../../hooks/useAppTheme';interface CodeEditorProps {diff --git a/client/src/components/ui/ComponentPalette.tsx b/client/src/components/ui/ComponentPalette.tsxindex 89333560..0da4112f 100644--- a/client/src/components/ui/ComponentPalette.tsx+++ b/client/src/components/ui/ComponentPalette.tsx@@ -10,6 +10,9 @@ const CATEGORY_EMOJIS: Record<string, string> = {workflow: '⚡',trigger: '🕐',ai: '🤖',+ agent: '🤖',+ model: '🧬',+ skill: '🎯',tool: '🛠️',location: '📍',whatsapp: '💬',@@ -20,6 +23,9 @@ const CATEGORY_EMOJIS: Record<string, string> = {util: '🔧',};+// Categories shown in simple (noob) mode - only AI related+const SIMPLE_MODE_CATEGORIES = ['agent', 'model', 'skill'];+const ComponentPalette: React.FC<ComponentPaletteProps> = ({nodeDefinitions,searchQuery,@@ -27,6 +33,7 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({collapsedSections,onToggleSection,onDragStart,+ proMode = false, // Default to simple mode}) => {const theme = useAppTheme();@@ -38,6 +45,9 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({workflow: colors.categoryWorkflow || theme.dracula.orange,trigger: colors.categoryTrigger || theme.dracula.pink,ai: colors.categoryAI || theme.dracula.purple,+ agent: colors.categoryAgent || theme.dracula.purple,+ model: colors.categoryModel || theme.dracula.cyan,+ skill: colors.categorySkill || theme.dracula.green,tool: colors.categoryTool || theme.dracula.green,location: colors.categoryLocation || theme.dracula.red,whatsapp: colors.categoryWhatsapp || theme.dracula.green,@@ -51,6 +61,9 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({workflow: 'Workflow',trigger: 'Triggers',ai: 'AI',+ agent: 'AI Agents',+ model: 'AI Models',+ skill: 'AI Skills',tool: 'AI Tools',location: 'Google Maps',whatsapp: 'WhatsApp',@@ -69,22 +82,34 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({const categorizedComponents = React.useMemo(() => {const categories: Record<string, INodeTypeDescription[]> = {};-+const filteredDefinitions = Object.values(nodeDefinitions).filter((definition) => {- if (!searchQuery.trim()) return true;-- try {- const query = searchQuery.toLowerCase();- return (- (definition.displayName || '').toLowerCase().includes(query) ||- (definition.description || '').toLowerCase().includes(query) ||- (definition.group?.[0] || '').toLowerCase().includes(query)- );- } catch (error) {- return false;+ // Filter by search query+ if (searchQuery.trim()) {+ try {+ const query = searchQuery.toLowerCase();+ const matchesQuery = (+ (definition.displayName || '').toLowerCase().includes(query) ||+ (definition.description || '').toLowerCase().includes(query) ||+ (definition.group?.[0] || '').toLowerCase().includes(query)+ );+ if (!matchesQuery) return false;+ } catch (error) {+ return false;+ }}++ // Filter by proMode - in simple mode, only show AI-related categories+ if (!proMode) {+ const categoryKey = (definition.group?.[0] || '').toLowerCase();+ if (!SIMPLE_MODE_CATEGORIES.includes(categoryKey)) {+ return false;+ }+ }++ return true;});-+filteredDefinitions.forEach((definition) => {try {const categoryKey = definition.group?.[0] || 'Uncategorized';@@ -98,7 +123,7 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({});return categories;- }, [nodeDefinitions, searchQuery]);+ }, [nodeDefinitions, searchQuery, proMode]);const totalComponents = Object.values(categorizedComponents).reduce((acc, components) => acc + components.length,diff --git a/client/src/components/ui/TopToolbar.tsx b/client/src/components/ui/TopToolbar.tsxindex 7c6c4a1a..a682b621 100644--- a/client/src/components/ui/TopToolbar.tsx+++ b/client/src/components/ui/TopToolbar.tsx@@ -19,6 +19,8 @@ interface TopToolbarProps {onToggleSidebar: () => void;componentPaletteVisible: boolean;onToggleComponentPalette: () => void;+ proMode: boolean;+ onToggleProMode: () => void;onOpenSettings: () => void;onOpenCredentials: () => void;onExportJSON: () => void;@@ -42,6 +44,8 @@ const TopToolbar: React.FC<TopToolbarProps> = ({onToggleSidebar,componentPaletteVisible,onToggleComponentPalette,+ proMode,+ onToggleProMode,onOpenSettings,onOpenCredentials,onExportJSON,@@ -379,6 +383,80 @@ const TopToolbar: React.FC<TopToolbarProps> = ({{/* Right Section */}<div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ {/* Mode Toggle - Segmented control style */}+ <div style={{ display: 'flex', alignItems: 'center', gap: theme.spacing.sm }}>+ <span style={{+ fontSize: theme.fontSize.sm,+ color: theme.accent.cyan,+ fontWeight: theme.fontWeight.semibold,+ fontFamily: 'system-ui, sans-serif',+ }}>+ Mode:+ </span>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ backgroundColor: theme.colors.backgroundAlt,+ borderRadius: theme.borderRadius.md,+ padding: '2px',+ border: `1px solid ${theme.colors.border}`,+ }}+ title={proMode ? 'Pro mode: All components visible' : 'Simple mode: Only AI components'}+ >+ <button+ onClick={() => !proMode ? undefined : onToggleProMode()}+ style={{+ padding: '4px 10px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ backgroundColor: !proMode ? `${theme.dracula.green}25` : 'transparent',+ color: !proMode ? theme.dracula.green : theme.accent.base0,+ border: !proMode ? `1px solid ${theme.dracula.green}60` : '1px solid transparent',+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ cursor: proMode ? 'pointer' : 'default',+ transition: `all ${theme.transitions.fast}`,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <circle cx="12" cy="12" r="10"/>+ <path d="M12 6v6l4 2"/>+ </svg>+ Simple+ </button>+ <button+ onClick={() => proMode ? undefined : onToggleProMode()}+ style={{+ padding: '4px 10px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ backgroundColor: proMode ? `${theme.dracula.purple}25` : 'transparent',+ color: proMode ? theme.dracula.purple : theme.accent.base0,+ border: proMode ? `1px solid ${theme.dracula.purple}60` : '1px solid transparent',+ borderRadius: theme.borderRadius.sm,+ fontSize: theme.fontSize.xs,+ fontWeight: theme.fontWeight.semibold,+ cursor: !proMode ? 'pointer' : 'default',+ transition: `all ${theme.transitions.fast}`,+ fontFamily: 'system-ui, sans-serif',+ }}+ >+ <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+ </button>+ </div>+ </div>++ {/* Divider */}+ <div style={{ width: '1px', height: theme.spacing.xl, backgroundColor: theme.colors.border, margin: `0 ${theme.spacing.xs}` }} />+{/* Settings Button */}<buttononClick={onOpenSettings}diff --git a/client/src/factories/baseChatModelFactory.ts b/client/src/factories/baseChatModelFactory.tsindex 1391757d..04686a6b 100644--- a/client/src/factories/baseChatModelFactory.ts+++ b/client/src/factories/baseChatModelFactory.ts@@ -33,7 +33,7 @@ export function createBaseChatModel(config: ChatModelConfig): INodeTypeDescriptidisplayName: `${config.displayName} Chat Model`,name: config.nodeName || `${config.providerId}ChatModel`,icon: config.icon,- group: ['ai', 'model'],+ group: ['model'],version: 1,subtitle: '={{$parameter["model"]}}',description: config.description,diff --git a/client/src/hooks/useParameterPanel.ts b/client/src/hooks/useParameterPanel.tsindex 11f02fa7..6aba74be 100644--- a/client/src/hooks/useParameterPanel.ts+++ b/client/src/hooks/useParameterPanel.ts@@ -2,6 +2,7 @@ import { useState, useEffect, useMemo, useCallback } from 'react';import { useAppStore } from '../store/useAppStore';import { nodeDefinitions } from '../nodeDefinitions';import { useWebSocket } from '../contexts/WebSocketContext';+import { SKILL_NODE_TYPES } from '../nodeDefinitions/skillNodes';export const useParameterPanel = () => {const { selectedNode, setSelectedNode, updateNodeData } = useAppStore();@@ -12,7 +13,7 @@ export const useParameterPanel = () => {const [error, setError] = useState<string | null>(null);// Use WebSocket for parameter operations- const { getNodeParameters, saveNodeParameters, isConnected } = useWebSocket();+ const { getNodeParameters, saveNodeParameters, sendRequest, isConnected } = useWebSocket();// Use stable references to prevent multiple effect runsconst nodeId = selectedNode?.id;@@ -47,11 +48,32 @@ export const useParameterPanel = () => {const result = await getNodeParameters(nodeId);// Extract parameters from NodeParameters responseconst savedParams = result?.parameters || {};- const initialParams = { ...defaults, ...savedParams };+ let initialParams = { ...defaults, ...savedParams };console.log('[useParameterPanel] Loading params for node:', nodeId, nodeType);console.log('[useParameterPanel] Defaults:', defaults);console.log('[useParameterPanel] Saved from backend:', savedParams);++ // For skill nodes, load skill content (instructions) from SKILL.md files+ if (SKILL_NODE_TYPES.includes(nodeType) && nodeType !== 'customSkill') {+ const skillName = initialParams.skillName;+ if (skillName) {+ try {+ console.log('[useParameterPanel] Loading skill content for:', skillName);+ const skillResult = await sendRequest('get_skill_content', { skill_name: skillName });+ if (skillResult?.success && skillResult?.instructions) {+ initialParams = {+ ...initialParams,+ instructions: skillResult.instructions+ };+ console.log('[useParameterPanel] Loaded skill instructions:', skillResult.instructions.substring(0, 100) + '...');+ }+ } catch (skillErr) {+ console.error('[useParameterPanel] Failed to load skill content:', skillErr);+ }+ }+ }+console.log('[useParameterPanel] Merged initial:', initialParams);setParameters(initialParams);@@ -68,7 +90,7 @@ export const useParameterPanel = () => {};loadParameters();- }, [nodeId, nodeType, getNodeParameters]);+ }, [nodeId, nodeType, getNodeParameters, sendRequest]);const hasUnsavedChanges = useMemo(() => {return JSON.stringify(parameters) !== JSON.stringify(originalParameters);@@ -91,6 +113,30 @@ export const useParameterPanel = () => {const success = await saveNodeParameters(selectedNode.id, parameters);if (success) {+ // For skill nodes, also save skill content (instructions) to SKILL.md files+ if (selectedNode.type && SKILL_NODE_TYPES.includes(selectedNode.type) && selectedNode.type !== 'customSkill') {+ const skillName = parameters.skillName;+ const instructions = parameters.instructions;+ if (skillName && instructions !== undefined) {+ try {+ console.log('[useParameterPanel] Saving skill content for:', skillName);+ const skillResult = await sendRequest('save_skill_content', {+ skill_name: skillName,+ instructions: instructions+ });+ if (!skillResult?.success) {+ console.error('[useParameterPanel] Failed to save skill content:', skillResult?.error);+ setError(skillResult?.error || 'Failed to save skill content');+ } else {+ console.log('[useParameterPanel] Skill content saved successfully');+ }+ } catch (skillErr) {+ console.error('[useParameterPanel] Failed to save skill content:', skillErr);+ setError('Failed to save skill content');+ }+ }+ }+// Also update the node data in store for faster loadingupdateNodeData(selectedNode.id, parameters);setOriginalParameters({ ...parameters });@@ -104,7 +150,7 @@ export const useParameterPanel = () => {setIsSaving(false);}}- }, [selectedNode, parameters, updateNodeData, saveNodeParameters]);+ }, [selectedNode, parameters, updateNodeData, saveNodeParameters, sendRequest]);const handleCancel = useCallback(() => {setParameters({ ...originalParameters });diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.tsindex 2c6e39f4..aed2e61d 100644--- a/client/src/nodeDefinitions.ts+++ b/client/src/nodeDefinitions.ts@@ -14,6 +14,7 @@ import { androidDeviceNodes } from './nodeDefinitions/androidDeviceNodes';import { chatNodes, CHAT_NODE_TYPES } from './nodeDefinitions/chatNodes';import { codeNodes, CODE_NODE_TYPES } from './nodeDefinitions/codeNodes';import { utilityNodes, UTILITY_NODE_TYPES } from './nodeDefinitions/utilityNodes';+import { skillNodes, SKILL_NODE_TYPES } from './nodeDefinitions/skillNodes';// ============================================================================// MAIN NODE REGISTRY - Combining all modular definitions@@ -32,7 +33,8 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {...androidDeviceNodes,...chatNodes,...codeNodes,- ...utilityNodes+ ...utilityNodes,+ ...skillNodes};// ============================================================================@@ -88,5 +90,9 @@ export const TOOL_NODES = [...TOOL_NODE_TYPES];+export const SKILL_NODES = [+ ...SKILL_NODE_TYPES+];+// Re-export types and utilities from modular files for external accessexport { createBaseChatModel } from './nodeDefinitions/aiModelNodes';\ No newline at end of filediff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.tsindex 7553233b..b4403b28 100644--- a/client/src/nodeDefinitions/aiAgentNodes.ts+++ b/client/src/nodeDefinitions/aiAgentNodes.ts@@ -9,12 +9,12 @@ import {// ============================================================================export const aiAgentNodes: Record<string, INodeTypeDescription> = {- // AI Agent Node - n8n official style implementation (first for top position in AI category)+ // AI Agent Node - n8n official style implementation (first for top position in Agents category)aiAgent: {displayName: 'AI Agent',name: 'aiAgent',icon: '🤖',- group: ['ai'],+ group: ['agent'],version: 1,subtitle: 'Tools Agent',description: 'Advanced AI agent with tool calling capabilities, memory, and iterative reasoning',@@ -153,13 +153,95 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {]},+ // Chat Agent Node - Conversational AI agent with memory and skill support (no tools)+ chatAgent: {+ displayName: 'Chat Agent',+ name: 'chatAgent',+ icon: '💬',+ group: ['agent'],+ version: 1,+ subtitle: 'Conversational Agent',+ description: 'Conversational AI agent with memory and skill support for multi-turn chat interactions',+ defaults: { name: 'Chat Agent', color: '#3B82F6' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Chat input'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node connection for conversation history'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'AI Skill node connection'+ }+ ],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'response, model, provider, timestamp'+ }],+ properties: [+ {+ displayName: 'AI Provider',+ name: 'provider',+ type: 'options',+ options: [+ {+ name: 'OpenAI',+ value: 'openai'+ },+ {+ name: 'Anthropic (Claude)',+ value: 'anthropic'+ },+ {+ name: 'Google (Gemini)',+ value: 'gemini'+ },+ {+ name: 'Groq',+ value: 'groq'+ },+ {+ name: 'OpenRouter',+ value: 'openrouter'+ }+ ],+ default: 'openai',+ description: 'The AI provider to use (configure API keys in Credentials)'+ },+ {+ displayName: 'Model',+ name: 'model',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'Select a model...',+ description: 'AI model to use for the chat',+ typeOptions: {+ dynamicOptions: true,+ dependsOn: ['provider']+ }+ }+ ]+ },+// Simple Memory Node - conversation history storage for AI agents// No run button - memory is accessed automatically when AI Agent runssimpleMemory: {displayName: 'Simple Memory',name: 'simpleMemory',icon: '🧠',- group: ['tool', 'memory'], // 'tool' = appears in AI Tools category+ group: ['skill', 'memory'], // 'skill' = appears in AI Skills categoryversion: 1,description: 'Store conversation history for AI agents',defaults: { name: 'Memory', color: '#8b5cf6' },@@ -212,4 +294,4 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {// ============================================================================// List of AI-related node types for easy identification (chat models removed - now in aiModelNodes.ts)-export const AI_NODE_TYPES = ['aiAgent', 'simpleMemory'];\ No newline at end of file+export const AI_NODE_TYPES = ['aiAgent', 'chatAgent', 'simpleMemory'];\ No newline at end of filediff --git a/client/src/nodeDefinitions/skillNodes.ts b/client/src/nodeDefinitions/skillNodes.tsnew file mode 100644index 00000000..c77a9ce7--- /dev/null+++ b/client/src/nodeDefinitions/skillNodes.ts@@ -0,0 +1,210 @@+// Skill Node Definitions - Skill nodes for Chat Agent capabilities+import {+ INodeTypeDescription,+ NodeConnectionType+} from '../types/INodeProperties';++// ============================================================================+// SKILL NODES - Connect to Chat Agent's input-skill handle+// ============================================================================++// Factory function for creating skill node definitions+function createSkillNode(config: {+ name: string;+ displayName: string;+ icon: string;+ color: string;+ skillName: string;+ description: string;+ subtitle: string;+ properties?: any[];+}): INodeTypeDescription {+ return {+ displayName: config.displayName,+ name: config.name,+ icon: config.icon,+ group: ['skill'],+ version: 1,+ subtitle: config.subtitle,+ description: config.description,+ defaults: { name: config.displayName, color: config.color },+ inputs: [], // No input - skill node is passive+ outputs: [{+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Connect to Chat Agent skill handle'+ }],+ properties: [+ {+ displayName: 'Skill Name',+ name: 'skillName',+ type: 'string',+ default: config.skillName,+ required: true,+ description: 'Internal skill identifier',+ typeOptions: { readonly: true }+ },+ {+ displayName: 'Instructions',+ name: 'instructions',+ type: 'string',+ default: '',+ description: 'Skill instructions in Markdown format. Loaded from SKILL.md file.',+ typeOptions: {+ rows: 20,+ editor: 'code',+ editorLanguage: 'markdown'+ }+ },+ ...(config.properties || [])+ ]+ };+}++export const skillNodes: Record<string, INodeTypeDescription> = {+ // Claude Assistant Skill - Default assistant personality+ claudeSkill: createSkillNode({+ name: 'claudeSkill',+ displayName: 'Claude Assistant',+ icon: '🤖',+ color: '#D97706',+ skillName: 'claude-assistant',+ subtitle: 'AI Personality',+ description: 'Default Claude assistant with helpful, harmless, and honest responses'+ }),++ // WhatsApp Skill - Send and receive messages+ whatsappSkill: createSkillNode({+ name: 'whatsappSkill',+ displayName: 'WhatsApp Skill',+ icon: '💬',+ color: '#25D366',+ skillName: 'whatsapp-skill',+ subtitle: 'Messaging',+ description: 'Send and receive WhatsApp messages via Chat Agent'+ }),++ // Memory Skill - Remember and recall information+ memorySkill: createSkillNode({+ name: 'memorySkill',+ displayName: 'Memory Skill',+ icon: '🧠',+ color: '#8B5CF6',+ skillName: 'memory-skill',+ subtitle: 'Long-term Memory',+ description: 'Remember information across conversations with short and long-term memory',+ properties: [+ {+ displayName: 'Default Session',+ name: 'defaultSession',+ type: 'string',+ default: 'default',+ description: 'Default session ID for memory storage'+ }+ ]+ }),++ // Maps Skill - Location and geocoding services+ mapsSkill: createSkillNode({+ name: 'mapsSkill',+ displayName: 'Maps Skill',+ icon: '🗺️',+ color: '#4285F4',+ skillName: 'maps-skill',+ subtitle: 'Location Services',+ description: 'Geocoding, nearby places, and map creation via Google Maps'+ }),++ // HTTP Skill - Make API requests+ httpSkill: createSkillNode({+ name: 'httpSkill',+ displayName: 'HTTP Skill',+ icon: '🌐',+ color: '#EF4444',+ skillName: 'http-skill',+ subtitle: 'API Requests',+ description: 'Make HTTP requests to external APIs and web services'+ }),++ // Scheduler Skill - Timers and cron jobs+ schedulerSkill: createSkillNode({+ name: 'schedulerSkill',+ displayName: 'Scheduler Skill',+ icon: '⏰',+ color: '#10B981',+ skillName: 'scheduler-skill',+ subtitle: 'Task Scheduling',+ description: 'Schedule tasks with timers and cron expressions'+ }),++ // Android Skill - Device control+ androidSkill: createSkillNode({+ name: 'androidSkill',+ displayName: 'Android Skill',+ icon: '📱',+ color: '#3DDC84',+ skillName: 'android-skill',+ subtitle: 'Device Control',+ description: 'Control Android devices - battery, wifi, bluetooth, apps, location, camera'+ }),++ // Code Skill - Execute code+ codeSkill: createSkillNode({+ name: 'codeSkill',+ displayName: 'Code Skill',+ icon: '💻',+ color: '#F59E0B',+ skillName: 'code-skill',+ subtitle: 'Code Execution',+ description: 'Execute Python or JavaScript code for calculations and data processing'+ }),++ // Custom Skill - User-created skill+ customSkill: {+ displayName: 'Custom Skill',+ name: 'customSkill',+ icon: '⭐',+ group: ['skill'],+ version: 1,+ subtitle: 'User-defined',+ description: 'User-created custom skill with configurable capabilities',+ defaults: { name: 'Custom Skill', color: '#6366F1' },+ inputs: [],+ outputs: [{+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Connect to Chat Agent skill handle'+ }],+ properties: [+ {+ displayName: 'Skill',+ name: 'selectedSkill',+ type: 'options',+ default: '',+ required: true,+ description: 'Select a user-created skill',+ typeOptions: {+ dynamicOptions: true+ }+ }+ ]+ }+};++// List of skill node types for easy identification+export const SKILL_NODE_TYPES = [+ 'claudeSkill',+ 'whatsappSkill',+ 'memorySkill',+ 'mapsSkill',+ 'httpSkill',+ 'schedulerSkill',+ 'androidSkill',+ 'codeSkill',+ 'customSkill'+];++// Export for nodeDefinitions.ts+export default skillNodes;diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.tsindex b00d2723..783e0e68 100644--- a/client/src/services/executionService.ts+++ b/client/src/services/executionService.ts@@ -188,6 +188,7 @@ export class ExecutionService {const supportedTypes = [// AI Nodes'aiAgent',+ 'chatAgent',// Note: simpleMemory is passive - accessed by AI Agent automatically, not executed directly'openaiChatModel','anthropicChatModel',diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.tsindex 6c4ad27b..76f24de4 100644--- a/client/src/store/useAppStore.ts+++ b/client/src/store/useAppStore.ts@@ -40,6 +40,7 @@ interface AppStore {selectedNode: Node | null; // Kept for backward compatibility, derived from workflowUIStatessidebarVisible: boolean;componentPaletteVisible: boolean;+ proMode: boolean; // false = noob mode (only AI categories), true = pro mode (all categories)whatsappSettingsOpen: boolean;androidSettingsOpen: boolean;renamingNodeId: string | null;@@ -61,6 +62,7 @@ interface AppStore {setSelectedNode: (node: Node | null) => void;toggleSidebar: () => void;toggleComponentPalette: () => void;+ toggleProMode: () => void;setWhatsAppSettingsOpen: (open: boolean) => void;setAndroidSettingsOpen: (open: boolean) => void;setRenamingNodeId: (nodeId: string | null) => void;@@ -119,6 +121,7 @@ const migrateNodes = (nodes: Node[]): Node[] => {const STORAGE_KEYS = {sidebarVisible: 'ui_sidebar_visible',componentPaletteVisible: 'ui_component_palette_visible',+ proMode: 'ui_pro_mode',};// Helper to load boolean from localStorage@@ -150,6 +153,7 @@ export const useAppStore = create<AppStore>((set, get) => ({selectedNode: null,sidebarVisible: loadBooleanFromStorage(STORAGE_KEYS.sidebarVisible, true),componentPaletteVisible: loadBooleanFromStorage(STORAGE_KEYS.componentPaletteVisible, true),+ proMode: loadBooleanFromStorage(STORAGE_KEYS.proMode, false), // Default to noob modewhatsappSettingsOpen: false,androidSettingsOpen: false,renamingNodeId: null,@@ -347,6 +351,14 @@ export const useAppStore = create<AppStore>((set, get) => ({});},+ toggleProMode: () => {+ set((state) => {+ const newValue = !state.proMode;+ saveBooleanToStorage(STORAGE_KEYS.proMode, newValue);+ return { proMode: newValue };+ });+ },+setWhatsAppSettingsOpen: (open) => {set({ whatsappSettingsOpen: open });},diff --git a/client/src/types/ComponentTypes.ts b/client/src/types/ComponentTypes.tsindex f3ba7cde..e50a0833 100644--- a/client/src/types/ComponentTypes.ts+++ b/client/src/types/ComponentTypes.ts@@ -13,6 +13,7 @@ export interface ComponentPaletteActions {export interface ComponentPaletteProps extends ComponentPaletteState, ComponentPaletteActions {nodeDefinitions: Record<string, INodeTypeDescription>;+ proMode?: boolean; // false = simple mode (only AI categories), true = pro mode (all categories)}export interface WorkflowHandlers {diff --git a/server/constants.py b/server/constants.pyindex 541ad1d3..1db10e89 100644--- a/server/constants.py+++ b/server/constants.py@@ -21,6 +21,7 @@ AI_CHAT_MODEL_TYPES: FrozenSet[str] = frozenset([AI_AGENT_TYPES: FrozenSet[str] = frozenset(['aiAgent',+ 'chatAgent',])AI_MEMORY_TYPES: FrozenSet[str] = frozenset([@@ -210,12 +211,13 @@ def detect_ai_provider(node_type: str, parameters: dict = None) -> str:Args:node_type: The node type string- parameters: Optional parameters dict (used for aiAgent)+ parameters: Optional parameters dict (used for aiAgent/chatAgent)Returns:Provider string: 'openai', 'anthropic', 'gemini', 'openrouter', 'groq', or 'cerebras'"""- if node_type == 'aiAgent':+ # AI Agent types get provider from parameters+ if node_type in AI_AGENT_TYPES:return (parameters or {}).get('provider', 'openai')elif 'cerebras' in node_type.lower():return 'cerebras'diff --git a/server/core/database.py b/server/core/database.pyindex 20a28a7d..a74a3e4a 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+from models.database import NodeParameter, Workflow, Execution, APIKey, APIKeyValidation, NodeOutput, ConversationMessage, ToolSchema, UserSkillfrom 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@@ -924,4 +924,189 @@ class Database:return await self.delete_cache_entry("android_relay_session")except Exception as e:logger.error("Failed to clear Android relay session", error=str(e))- return False\ No newline at end of file+ return False++ # ============================================================================+ # User Skills (Custom skills for Chat Agent)+ # ============================================================================++ async def create_user_skill(+ self,+ name: str,+ display_name: str,+ description: str,+ instructions: str,+ allowed_tools: Optional[str] = None,+ category: str = "custom",+ icon: str = "star",+ color: str = "#6366F1",+ metadata_json: Optional[Dict[str, Any]] = None,+ created_by: Optional[int] = None+ ) -> Optional[Dict[str, Any]]:+ """Create a new user skill."""+ try:+ async with self.get_session() as session:+ skill = UserSkill(+ name=name,+ display_name=display_name,+ description=description,+ instructions=instructions,+ allowed_tools=allowed_tools,+ category=category,+ icon=icon,+ color=color,+ metadata_json=metadata_json,+ created_by=created_by+ )+ session.add(skill)+ await session.commit()+ await session.refresh(skill)++ logger.info(f"[DB] Created user skill: {name}")+ return self._skill_to_dict(skill)++ except IntegrityError:+ logger.error(f"User skill with name '{name}' already exists")+ return None+ except Exception as e:+ logger.error("Failed to create user skill", name=name, error=str(e))+ return None++ async def get_user_skill(self, name: str) -> Optional[Dict[str, Any]]:+ """Get user skill by name."""+ try:+ async with self.get_session() as session:+ stmt = select(UserSkill).where(UserSkill.name == name)+ result = await session.execute(stmt)+ skill = result.scalar_one_or_none()++ return self._skill_to_dict(skill) if skill else None++ except Exception as e:+ logger.error("Failed to get user skill", name=name, error=str(e))+ return None++ async def get_user_skill_by_id(self, skill_id: int) -> Optional[Dict[str, Any]]:+ """Get user skill by ID."""+ try:+ async with self.get_session() as session:+ stmt = select(UserSkill).where(UserSkill.id == skill_id)+ result = await session.execute(stmt)+ skill = result.scalar_one_or_none()++ return self._skill_to_dict(skill) if skill else None++ except Exception as e:+ logger.error("Failed to get user skill by id", skill_id=skill_id, error=str(e))+ return None++ async def get_all_user_skills(self, active_only: bool = True) -> List[Dict[str, Any]]:+ """Get all user skills, optionally filtered by active status."""+ try:+ async with self.get_session() as session:+ if active_only:+ stmt = select(UserSkill).where(UserSkill.is_active == True).order_by(UserSkill.display_name)+ else:+ stmt = select(UserSkill).order_by(UserSkill.display_name)++ result = await session.execute(stmt)+ skills = result.scalars().all()++ return [self._skill_to_dict(s) for s in skills]++ except Exception as e:+ logger.error("Failed to get all user skills", error=str(e))+ return []++ async def update_user_skill(+ self,+ name: str,+ display_name: Optional[str] = None,+ description: Optional[str] = None,+ instructions: Optional[str] = None,+ allowed_tools: Optional[str] = None,+ category: Optional[str] = None,+ icon: Optional[str] = None,+ color: Optional[str] = None,+ metadata_json: Optional[Dict[str, Any]] = None,+ is_active: Optional[bool] = None+ ) -> Optional[Dict[str, Any]]:+ """Update an existing user skill."""+ try:+ async with self.get_session() as session:+ stmt = select(UserSkill).where(UserSkill.name == name)+ result = await session.execute(stmt)+ skill = result.scalar_one_or_none()++ if not skill:+ logger.error(f"User skill '{name}' not found for update")+ return None++ # Update only provided fields+ if display_name is not None:+ skill.display_name = display_name+ if description is not None:+ skill.description = description+ if instructions is not None:+ skill.instructions = instructions+ if allowed_tools is not None:+ skill.allowed_tools = allowed_tools+ if category is not None:+ skill.category = category+ if icon is not None:+ skill.icon = icon+ if color is not None:+ skill.color = color+ if metadata_json is not None:+ skill.metadata_json = metadata_json+ if is_active is not None:+ skill.is_active = is_active++ await session.commit()+ await session.refresh(skill)++ logger.info(f"[DB] Updated user skill: {name}")+ return self._skill_to_dict(skill)++ except Exception as e:+ logger.error("Failed to update user skill", name=name, error=str(e))+ return None++ async def delete_user_skill(self, name: str) -> bool:+ """Delete a user skill by name."""+ try:+ async with self.get_session() as session:+ stmt = select(UserSkill).where(UserSkill.name == name)+ result = await session.execute(stmt)+ skill = result.scalar_one_or_none()++ if skill:+ await session.delete(skill)+ await session.commit()+ logger.info(f"[DB] Deleted user skill: {name}")+ return True++ return False++ except Exception as e:+ logger.error("Failed to delete user skill", name=name, error=str(e))+ return False++ def _skill_to_dict(self, skill: UserSkill) -> Dict[str, Any]:+ """Convert UserSkill model to dictionary."""+ return {+ "id": skill.id,+ "name": skill.name,+ "display_name": skill.display_name,+ "description": skill.description,+ "instructions": skill.instructions,+ "allowed_tools": skill.allowed_tools.split(",") if skill.allowed_tools else [],+ "category": skill.category,+ "icon": skill.icon,+ "color": skill.color,+ "metadata": skill.metadata_json,+ "is_active": skill.is_active,+ "created_by": skill.created_by,+ "created_at": skill.created_at.isoformat() if skill.created_at else None,+ "updated_at": skill.updated_at.isoformat() if skill.updated_at else None+ }\ No newline at end of filediff --git a/server/models/database.py b/server/models/database.pyindex 20f1d558..ff3af4e6 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -155,6 +155,37 @@ class ToolSchema(SQLModel, table=True):default_factory=lambda: datetime.now(timezone.utc),sa_column=Column(DateTime(timezone=True), server_default=func.now()))+ updated_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), onupdate=func.now())+ )+++class UserSkill(SQLModel, table=True):+ """User-created custom skills for Chat Agent.++ Skills are defined using the Agent Skills specification format with YAML frontmatter.+ This allows non-technical users to create and manage skills via the UI editor.+ """++ __tablename__ = "user_skills"++ id: Optional[int] = Field(default=None, primary_key=True)+ name: str = Field(unique=True, index=True, max_length=100) # Unique skill identifier+ display_name: str = Field(max_length=200) # Human-readable name+ description: str = Field(max_length=1000) # Short description for skill registry+ instructions: str = Field(max_length=50000) # Full markdown instructions+ allowed_tools: Optional[str] = Field(default=None, max_length=1000) # Comma-separated tool names+ category: str = Field(default="custom", max_length=50) # Skill category+ icon: str = Field(default="star", max_length=50) # Icon identifier+ color: str = Field(default="#6366F1", max_length=20) # Color hex code+ metadata_json: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # Additional metadata+ is_active: bool = Field(default=True) # Whether skill is available+ created_by: Optional[int] = Field(default=None) # User ID who created it+ created_at: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc),sa_column=Column(DateTime(timezone=True), onupdate=func.now())diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 23b3db4f..defa99f9 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -1470,6 +1470,222 @@ async def handle_clear_terminal_logs(data: Dict[str, Any], websocket: WebSocket)return {"success": True, "message": "Terminal logs cleared"}+# ============================================================================+# User Skills Handlers+# ============================================================================++@ws_handler("skill_name")+async def handle_get_skill_content(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get skill content (instructions) by skill name.++ Works for both built-in skills (from SKILL.md files) and user skills (from database).+ """+ from services.skill_loader import get_skill_loader++ skill_name = data["skill_name"]+ skill_loader = get_skill_loader()++ # Try to load the skill+ skill = skill_loader.load_skill(skill_name)+ if skill:+ return {+ "success": True,+ "skill_name": skill_name,+ "instructions": skill.instructions,+ "description": skill.metadata.description,+ "allowed_tools": skill.metadata.allowed_tools,+ "is_builtin": skill.metadata.path is not None,+ "timestamp": time.time()+ }++ # Try loading from database for user skills+ database = container.database()+ user_skill = await database.get_user_skill(skill_name)+ if user_skill:+ return {+ "success": True,+ "skill_name": skill_name,+ "instructions": user_skill.instructions,+ "description": user_skill.description,+ "allowed_tools": user_skill.allowed_tools.split(',') if user_skill.allowed_tools else [],+ "is_builtin": False,+ "timestamp": time.time()+ }++ return {"success": False, "error": f"Skill '{skill_name}' not found"}+++@ws_handler("skill_name", "instructions")+async def handle_save_skill_content(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save skill content (instructions) by skill name.++ For built-in skills, writes to the SKILL.md file.+ For user skills, updates the database.+ """+ import re+ from pathlib import Path+ from services.skill_loader import get_skill_loader++ skill_name = data["skill_name"]+ new_instructions = data["instructions"]+ skill_loader = get_skill_loader()++ # Check if it's a built-in skill+ if skill_name in skill_loader._registry:+ metadata = skill_loader._registry[skill_name]+ if metadata.path is not None:+ # It's a built-in skill - update SKILL.md file+ skill_md_path = metadata.path / "SKILL.md"++ if not skill_md_path.exists():+ return {"success": False, "error": f"SKILL.md not found for '{skill_name}'"}++ # Read existing file to preserve frontmatter+ content = skill_md_path.read_text(encoding='utf-8')++ # Parse frontmatter+ frontmatter_match = re.match(r'^(---\s*\n.*?\n---\s*\n)', content, re.DOTALL)+ if frontmatter_match:+ # Keep frontmatter, replace body+ new_content = frontmatter_match.group(1) + new_instructions+ else:+ # No frontmatter, just write instructions+ new_content = new_instructions++ # Write back to file+ skill_md_path.write_text(new_content, encoding='utf-8')++ # Clear cache so next load gets fresh content+ skill_loader.clear_cache()++ logger.info(f"[Skills] Updated built-in skill: {skill_name}")+ return {+ "success": True,+ "skill_name": skill_name,+ "is_builtin": True,+ "message": f"Skill '{skill_name}' saved to SKILL.md",+ "timestamp": time.time()+ }++ # It's a user skill - update in database+ database = container.database()+ user_skill = await database.get_user_skill(skill_name)+ if user_skill:+ updated = await database.update_user_skill(+ name=skill_name,+ instructions=new_instructions+ )+ if updated:+ logger.info(f"[Skills] Updated user skill: {skill_name}")+ return {+ "success": True,+ "skill_name": skill_name,+ "is_builtin": False,+ "message": f"Skill '{skill_name}' saved to database",+ "timestamp": time.time()+ }++ return {"success": False, "error": f"Skill '{skill_name}' not found"}+++@ws_handler()+async def handle_get_user_skills(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get all user-created skills."""+ database = container.database()+ active_only = data.get("active_only", True)+ skills = await database.get_all_user_skills(active_only=active_only)+ return {"skills": skills, "count": len(skills), "timestamp": time.time()}+++@ws_handler("name")+async def handle_get_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get a specific user skill by name."""+ database = container.database()+ skill = await database.get_user_skill(data["name"])+ if skill:+ return {"skill": skill, "timestamp": time.time()}+ return {"success": False, "error": f"Skill '{data['name']}' not found"}+++@ws_handler("name", "display_name", "description", "instructions")+async def handle_create_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Create a new user skill."""+ database = container.database()+ broadcaster = get_status_broadcaster()++ skill = await database.create_user_skill(+ name=data["name"],+ display_name=data["display_name"],+ description=data["description"],+ instructions=data["instructions"],+ allowed_tools=data.get("allowed_tools"),+ category=data.get("category", "custom"),+ icon=data.get("icon", "star"),+ color=data.get("color", "#6366F1"),+ metadata_json=data.get("metadata"),+ created_by=data.get("created_by")+ )++ if skill:+ # Broadcast skill created to all clients+ await broadcaster.broadcast({+ "type": "user_skill_created",+ "skill": skill,+ "timestamp": time.time()+ })+ return {"skill": skill, "timestamp": time.time()}+ return {"success": False, "error": f"Failed to create skill. Name '{data['name']}' may already exist."}+++@ws_handler("name")+async def handle_update_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Update an existing user skill."""+ database = container.database()+ broadcaster = get_status_broadcaster()++ skill = await database.update_user_skill(+ name=data["name"],+ display_name=data.get("display_name"),+ description=data.get("description"),+ instructions=data.get("instructions"),+ allowed_tools=data.get("allowed_tools"),+ category=data.get("category"),+ icon=data.get("icon"),+ color=data.get("color"),+ metadata_json=data.get("metadata"),+ is_active=data.get("is_active")+ )++ if skill:+ # Broadcast skill updated to all clients+ await broadcaster.broadcast({+ "type": "user_skill_updated",+ "skill": skill,+ "timestamp": time.time()+ })+ return {"skill": skill, "timestamp": time.time()}+ return {"success": False, "error": f"Skill '{data['name']}' not found"}+++@ws_handler("name")+async def handle_delete_user_skill(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Delete a user skill."""+ database = container.database()+ broadcaster = get_status_broadcaster()++ deleted = await database.delete_user_skill(data["name"])++ if deleted:+ # Broadcast skill deleted to all clients+ await broadcaster.broadcast({+ "type": "user_skill_deleted",+ "name": data["name"],+ "timestamp": time.time()+ })+ return {"deleted": True, "name": data["name"], "timestamp": time.time()}+ return {"success": False, "error": f"Skill '{data['name']}' not found"}++# ============================================================================# Message Router# ============================================================================@@ -1563,6 +1779,17 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {# Terminal logs"get_terminal_logs": handle_get_terminal_logs,"clear_terminal_logs": handle_clear_terminal_logs,++ # User Skills+ "get_user_skills": handle_get_user_skills,+ "get_user_skill": handle_get_user_skill,+ "create_user_skill": handle_create_user_skill,+ "update_user_skill": handle_update_user_skill,+ "delete_user_skill": handle_delete_user_skill,++ # Skill Content (built-in and user skills)+ "get_skill_content": handle_get_skill_content,+ "save_skill_content": handle_save_skill_content,}diff --git a/server/services/ai.py b/server/services/ai.pyindex 0a1532ed..d82b7cde 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1454,6 +1454,312 @@ class AIService:"timestamp": datetime.now().isoformat()}+ async def execute_chat_agent(self, node_id: str, parameters: Dict[str, Any],+ memory_data: Optional[Dict[str, Any]] = None,+ skill_data: Optional[List[Dict[str, Any]]] = None,+ broadcaster=None,+ workflow_id: Optional[str] = None) -> Dict[str, Any]:+ """Execute Chat Agent - conversational AI with skill support.++ Chat Agent supports conversation with memory and skills. When skills are+ connected, the agent can use LangGraph for tool calling (like AI Agent).++ Args:+ node_id: The node identifier+ parameters: Node parameters including prompt, model, etc.+ memory_data: Optional memory data from connected simpleMemory node+ skill_data: Optional skill configurations from connected skill nodes+ broadcaster: Optional StatusBroadcaster for real-time UI updates+ workflow_id: Optional workflow ID for scoped status broadcasts+ """+ start_time = time.time()+ provider = 'unknown'+ model = 'unknown'++ logger.info(f"[ChatAgent] execute_chat_agent called: node_id={node_id}, workflow_id={workflow_id}, skill_count={len(skill_data) if skill_data else 0}")++ async def broadcast_status(phase: str, details: Dict[str, Any] = None):+ if broadcaster:+ await broadcaster.update_node_status(node_id, "executing", {+ "phase": phase,+ "agent_type": "chat_with_skills" if skill_data else "chat",+ **(details or {})+ }, workflow_id=workflow_id)++ try:+ # Extract parameters+ prompt = parameters.get('prompt', 'Hello')+ system_message = parameters.get('systemMessage', 'You are a helpful assistant')++ # Load skills and enhance system message+ skill_names = []+ skill_tools = []+ if skill_data:+ from services.skill_loader import get_skill_loader+ from services.skill_executor import get_skill_executor, init_skill_executor++ skill_loader = get_skill_loader()+ skill_loader.scan_skills()++ # Extract skill names from connected skill nodes+ for skill_info in skill_data:+ skill_name = skill_info.get('skill_name') or skill_info.get('node_type', '').replace('Skill', '-skill').lower()+ # Convert node type to skill name (e.g., 'whatsappSkill' -> 'whatsapp-skill')+ if skill_name.endswith('skill') and not '-' in skill_name:+ skill_name = skill_name[:-5] + '-skill' # whatsappskill -> whatsapp-skill+ skill_names.append(skill_name)+ logger.debug(f"[ChatAgent] Skill detected: {skill_name}")++ # Add skill registry to system message+ skill_prompt = skill_loader.get_registry_prompt(skill_names)+ if skill_prompt:+ system_message = f"{system_message}\n\n{skill_prompt}"+ logger.info(f"[ChatAgent] Enhanced system message with {len(skill_names)} skills")++ # Build tools from skills+ skill_executor = get_skill_executor()+ if not skill_executor:+ # Initialize skill executor with node executor callback+ async def node_executor_callback(node_id, node_type, parameters, context):+ from services.node_executor import NodeExecutor+ executor = NodeExecutor(self, self.database)+ return await executor.execute_node(node_id, node_type, parameters, context)++ skill_executor = init_skill_executor(skill_loader, node_executor_callback, self.database)++ skill_tools = skill_executor.build_tools_for_skills(skill_names)+ logger.info(f"[ChatAgent] Built {len(skill_tools)} tools from skills")++ # Flatten options collection from frontend+ options = parameters.get('options', {})+ flattened = {**parameters, **options}++ api_key = flattened.get('api_key') or flattened.get('apiKey')+ provider = parameters.get('provider', 'openai')+ model = parameters.get('model', '')+ temperature = float(flattened.get('temperature', 0.7))+ max_tokens = int(flattened.get('max_tokens') or flattened.get('maxTokens') or 1000)++ logger.info(f"[ChatAgent] Provider: {provider}, Model: {model}")++ # Validate model for provider+ if not model or not is_model_valid_for_provider(model, provider):+ old_model = model+ model = get_default_model(provider)+ if old_model:+ logger.warning(f"Model '{old_model}' invalid for provider '{provider}', using default: {model}")+ else:+ logger.info(f"No model specified, using default: {model}")++ if not api_key:+ raise ValueError("API key is required for Chat Agent")++ # Build thinking config from parameters+ thinking_config = None+ if flattened.get('thinkingEnabled'):+ thinking_config = ThinkingConfig(+ enabled=True,+ budget=int(flattened.get('thinkingBudget', 2048)),+ effort=flattened.get('reasoningEffort', 'medium'),+ level=flattened.get('thinkingLevel', 'medium'),+ format=flattened.get('reasoningFormat', 'parsed'),+ )++ # Broadcast: Initializing+ await broadcast_status("initializing", {+ "message": f"Initializing {provider} model...",+ "provider": provider,+ "model": model+ })++ # Create chat model+ chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config)++ # Build messages+ messages: List[BaseMessage] = []+ if system_message:+ messages.append(SystemMessage(content=system_message))++ # Load memory history if connected+ session_id = None+ history_count = 0+ if memory_data and memory_data.get('session_id'):+ session_id = memory_data['session_id']+ window_size = memory_data.get('window_size')++ await broadcast_status("loading_memory", {+ "message": "Loading conversation history...",+ "session_id": session_id,+ "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}'")++ await broadcast_status("memory_loaded", {+ "message": f"Loaded {history_count} messages from memory",+ "session_id": session_id,+ "history_count": history_count+ })++ # Add current prompt+ messages.append(HumanMessage(content=prompt))++ # Broadcast: Invoking LLM+ await broadcast_status("invoking_llm", {+ "message": "Generating response...",+ "has_memory": session_id is not None,+ "history_count": history_count,+ "skill_count": len(skill_names) if skill_data else 0+ })++ # Execute with or without skill tools+ thinking_content = None+ iterations = 1++ if skill_tools:+ # Use LangGraph for skill tool execution (like AI Agent)+ logger.info(f"[ChatAgent] Using LangGraph with {len(skill_tools)} skill tools")++ # Create skill tool executor callback+ async def skill_tool_executor(tool_name: str, tool_args: Dict) -> Any:+ """Execute a skill tool by name."""+ from services.skill_executor import get_skill_executor++ # Convert tool name back to skill tool format (underscores to hyphens)+ skill_tool_name = tool_name.replace('_', '-')+ logger.info(f"[ChatAgent] Executing skill tool: {skill_tool_name}")++ executor = get_skill_executor()+ if executor:+ try:+ result = await executor.execute_tool(skill_tool_name, tool_args)+ return result+ except Exception as e:+ logger.error(f"[ChatAgent] Skill tool execution failed: {skill_tool_name}", error=str(e))+ return {"error": str(e)}+ return {"error": "Skill executor not initialized"}++ # Build LangGraph agent+ agent_graph = build_agent_graph(+ chat_model,+ tools=skill_tools,+ tool_executor=skill_tool_executor+ )++ # Create initial state+ initial_state: AgentState = {+ "messages": messages,+ "tool_outputs": {},+ "pending_tool_calls": [],+ "iteration": 0,+ "max_iterations": 10,+ "should_continue": False,+ "thinking_content": None+ }++ # Execute the graph+ final_state = await agent_graph.ainvoke(initial_state)++ # Extract response+ all_messages = final_state["messages"]+ ai_response = all_messages[-1] if all_messages else None++ if not ai_response or not hasattr(ai_response, 'content'):+ raise ValueError("No response generated from agent")++ raw_content = ai_response.content+ response_content = self._extract_text_content(raw_content, ai_response)+ iterations = final_state.get("iteration", 1)+ thinking_content = final_state.get("thinking_content")+ else:+ # Simple invoke without tools+ response = await chat_model.ainvoke(messages)++ # Extract response content+ raw_content = response.content+ response_content = self._extract_text_content(raw_content, response)++ # Extract thinking content if available+ _, thinking_content = extract_thinking_from_response(response)++ 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):+ 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}'")++ result = {+ "response": response_content,+ "thinking": thinking_content,+ "thinking_enabled": thinking_config.enabled if thinking_config else False,+ "model": model,+ "provider": provider,+ "agent_type": "chat_with_skills" if skill_tools else "chat",+ "iterations": iterations,+ "finish_reason": "stop",+ "timestamp": datetime.now().isoformat(),+ "input": {+ "prompt": prompt,+ "system_message": system_message,+ }+ }++ if session_id:+ result["memory"] = {+ "session_id": session_id,+ "history_loaded": history_count+ }++ if skill_names:+ result["skills"] = {+ "connected": skill_names,+ "tools_available": len(skill_tools) if skill_tools else 0+ }++ log_execution_time(logger, "chat_agent", start_time, time.time())+ log_api_call(logger, provider, model, "chat_agent", True)++ return {+ "success": True,+ "node_id": node_id,+ "node_type": "chatAgent",+ "result": result,+ "execution_time": time.time() - start_time+ }++ except Exception as e:+ logger.error("[ChatAgent] Execution failed", node_id=node_id, error=str(e))+ log_api_call(logger, provider, model, "chat_agent", False, error=str(e))++ return {+ "success": False,+ "node_id": node_id,+ "node_type": "chatAgent",+ "error": str(e),+ "execution_time": time.time() - start_time,+ "timestamp": datetime.now().isoformat()+ }+async def _build_tool_from_node(self, tool_info: Dict[str, Any]) -> tuple:"""Convert a node configuration into a LangChain StructuredTool.diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex 694e100e..3a759d22 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -14,6 +14,7 @@ This package contains all node execution handlers organized by category:# AI handlersfrom .ai import (handle_ai_agent,+ handle_chat_agent,handle_ai_chat_model,handle_simple_memory,)@@ -71,6 +72,7 @@ from .tools import (__all__ = [# AI'handle_ai_agent',+ 'handle_chat_agent','handle_ai_chat_model','handle_simple_memory',# Androiddiff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.pyindex 9070cb5b..4bb90aa0 100644--- a/server/services/handlers/ai.py+++ b/server/services/handlers/ai.py@@ -1,6 +1,6 @@-"""AI node handlers - AI Agent, AI Chat Model, Simple Memory."""+"""AI node handlers - AI Agent, Chat Agent, AI Chat Model, Simple Memory."""-from typing import Dict, Any, List, TYPE_CHECKING+from typing import Dict, Any, List, Optional, TYPE_CHECKINGfrom core.logging import get_loggerfrom constants import ANDROID_SERVICE_NODE_TYPES@@ -148,6 +148,95 @@ async def handle_ai_agent()+async def handle_chat_agent(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+ ai_service: "AIService",+ database: "Database"+) -> Dict[str, Any]:+ """Handle Chat Agent node execution with memory and skill support.++ Chat Agent is a conversational AI agent without tool calling capabilities.+ It supports memory for conversation history and skills for extended capabilities.++ Args:+ node_id: The node ID+ node_type: The node type (chatAgent)+ parameters: Resolved parameters+ context: Execution context with nodes, edges, session_id, start_time, execution_id+ ai_service: The AI service instance+ database: The database instance++ Returns:+ Execution result dict+ """+ nodes = context.get('nodes')+ edges = context.get('edges')+ workflow_id = context.get('workflow_id')+ memory_data: Optional[Dict[str, Any]] = None+ skill_data: List[Dict[str, Any]] = []++ logger.info(f"[Chat Agent] Processing node {node_id}, workflow_id={workflow_id}")++ if edges and nodes:+ incoming_edges = [e for e in edges if e.get('target') == node_id]+ logger.debug(f"[Chat Agent] Incoming edges: {len(incoming_edges)}")++ for edge in edges:+ if edge.get('target') != node_id:+ continue++ target_handle = edge.get('targetHandle')+ source_node_id = edge.get('source')+ source_node = next((n for n in nodes if n.get('id') == source_node_id), None)++ if not source_node:+ continue++ # Memory detection+ 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')+ memory_type = memory_params.get('memoryType', 'buffer')+ window_size = int(memory_params.get('windowSize', 10)) if memory_type == 'window' else None+ memory_data = {+ 'session_id': memory_session_id,+ 'memory_type': memory_type,+ 'window_size': window_size+ }+ logger.debug(f"Chat Agent connected memory node, session={memory_session_id}")++ # Skill detection - nodes connected to input-skill handle+ elif target_handle == 'input-skill':+ skill_type = source_node.get('type')+ skill_params = await database.get_node_parameters(source_node_id) or {}+ skill_entry = {+ 'node_id': source_node_id,+ 'node_type': skill_type,+ 'parameters': skill_params,+ 'label': source_node.get('data', {}).get('label', skill_type)+ }+ skill_data.append(skill_entry)+ logger.debug(f"Chat Agent connected skill: {skill_type}")++ # Get broadcaster for real-time status updates+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()++ # Execute as chat (no tool calling) with memory support+ return await ai_service.execute_chat_agent(+ node_id,+ parameters,+ memory_data=memory_data,+ skill_data=skill_data if skill_data else None,+ broadcaster=broadcaster,+ workflow_id=workflow_id+ )++async def handle_ai_chat_model(node_id: str,node_type: str,diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex ab40d7f3..06d93ec1 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -23,7 +23,7 @@ from models.nodes import validate_node_paramsfrom pydantic import ValidationErrorfrom services import event_waiterfrom services.handlers import (- handle_ai_agent, handle_ai_chat_model, handle_simple_memory,+ handle_ai_agent, handle_chat_agent, handle_ai_chat_model, handle_simple_memory,handle_android_device_setup, handle_android_service,handle_python_executor, handle_javascript_executor,handle_http_request, handle_webhook_response, handle_trigger_node,@@ -104,6 +104,7 @@ class NodeExecutor:'timer': handle_timer,# AI'aiAgent': partial(handle_ai_agent, ai_service=self.ai_service, database=self.database),+ 'chatAgent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),'simpleMemory': handle_simple_memory,# Maps'createMap': partial(handle_create_map, maps_service=self.maps_service),diff --git a/server/services/skill_executor.py b/server/services/skill_executor.pynew file mode 100644index 00000000..dbd6a696--- /dev/null+++ b/server/services/skill_executor.py@@ -0,0 +1,621 @@+"""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.+"""++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+ if tool_name == 'http-request':+ return {+ 'url': args.get('url'),+ 'method': args.get('method', 'GET'),+ 'body': args.get('body'),+ 'headers': args.get('headers'),+ 'timeout': 30000+ }++ # 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/services/skill_loader.py b/server/services/skill_loader.pynew file mode 100644index 00000000..22f5551f--- /dev/null+++ b/server/services/skill_loader.py@@ -0,0 +1,417 @@+"""Skill loader service for discovering and loading Agent Skills.++Implements the Agent Skills specification (https://agentskills.io/specification).+Skills are modular capabilities defined in Markdown files that the Chat Agent+can discover and use on demand.+"""++import re+import yaml+from pathlib import Path+from dataclasses import dataclass, field+from typing import Dict, List, Any, Optional+from core.logging import get_logger++logger = get_logger(__name__)+++@dataclass+class SkillMetadata:+ """Metadata from SKILL.md frontmatter (loaded at startup for all skills)."""+ name: str+ description: str+ allowed_tools: List[str] = field(default_factory=list)+ metadata: Dict[str, Any] = field(default_factory=dict)+ path: Optional[Path] = None # Path to skill directory+++@dataclass+class Skill:+ """Full skill content (loaded on-demand when activated)."""+ metadata: SkillMetadata+ instructions: str # Markdown body after frontmatter+ scripts: Dict[str, str] = field(default_factory=dict) # filename -> content+ references: Dict[str, str] = field(default_factory=dict) # filename -> content+ assets: Dict[str, bytes] = field(default_factory=dict) # filename -> binary content+++class SkillLoader:+ """Loads and manages Agent Skills from filesystem and database.++ Skills are loaded from multiple directories with priority:+ 1. Built-in skills: server/skills/+ 2. Project skills: .machina/skills/ (in current directory)+ 3. User skills from database (created via UI)++ Follows progressive disclosure pattern:+ - scan_skills(): Load only metadata (~100 tokens per skill)+ - load_skill(): Load full content when activated (~5000 tokens max)+ """++ def __init__(self, skill_dirs: List[Path] = None, database=None):+ """Initialize skill loader.++ Args:+ skill_dirs: List of directories to scan for skills+ database: Database instance for loading user-created skills+ """+ self._skill_dirs = skill_dirs or []+ self._database = database+ self._registry: Dict[str, SkillMetadata] = {}+ self._cache: Dict[str, Skill] = {} # Cache loaded skills++ def scan_skills(self) -> Dict[str, SkillMetadata]:+ """Scan all skill directories and load metadata.++ Returns:+ Dict mapping skill name to SkillMetadata+ """+ self._registry.clear()++ # Scan filesystem directories+ for skill_dir in self._skill_dirs:+ if not skill_dir.exists():+ logger.debug(f"[SkillLoader] Skill directory not found: {skill_dir}")+ continue++ for skill_path in skill_dir.iterdir():+ if skill_path.is_dir():+ skill_md = skill_path / "SKILL.md"+ if skill_md.exists():+ try:+ metadata = self._parse_skill_metadata(skill_md)+ if metadata:+ metadata.path = skill_path+ self._registry[metadata.name] = metadata+ logger.debug(f"[SkillLoader] Loaded skill: {metadata.name}")+ except Exception as e:+ logger.error(f"[SkillLoader] Failed to parse {skill_md}: {e}")++ logger.info(f"[SkillLoader] Loaded {len(self._registry)} skills from filesystem")+ return self._registry++ async def scan_skills_with_database(self) -> Dict[str, SkillMetadata]:+ """Scan skills from filesystem and database.++ Returns:+ Dict mapping skill name to SkillMetadata+ """+ # First scan filesystem+ self.scan_skills()++ # Then load from database (overrides filesystem if same name)+ if self._database:+ try:+ user_skills = await self._database.get_all_user_skills()+ for skill in user_skills:+ allowed_tools = []+ if skill.allowed_tools:+ allowed_tools = [t.strip() for t in skill.allowed_tools.split(',')]++ metadata_dict = {}+ if skill.metadata_json:+ import json+ metadata_dict = json.loads(skill.metadata_json)++ self._registry[skill.name] = SkillMetadata(+ name=skill.name,+ description=skill.description,+ allowed_tools=allowed_tools,+ metadata=metadata_dict,+ path=None # Database skills have no path+ )+ logger.info(f"[SkillLoader] Loaded {len(user_skills)} skills from database")+ except Exception as e:+ logger.error(f"[SkillLoader] Failed to load skills from database: {e}")++ return self._registry++ def _parse_skill_metadata(self, skill_md_path: Path) -> Optional[SkillMetadata]:+ """Parse SKILL.md frontmatter to extract metadata.++ Args:+ skill_md_path: Path to SKILL.md file++ Returns:+ SkillMetadata or None if parsing fails+ """+ content = skill_md_path.read_text(encoding='utf-8')++ # Parse YAML frontmatter (between --- markers)+ frontmatter_match = re.match(r'^---\s*\n(.*?)\n---\s*\n', content, re.DOTALL)+ if not frontmatter_match:+ logger.warning(f"[SkillLoader] No frontmatter in {skill_md_path}")+ return None++ try:+ frontmatter = yaml.safe_load(frontmatter_match.group(1))+ except yaml.YAMLError as e:+ logger.error(f"[SkillLoader] Invalid YAML in {skill_md_path}: {e}")+ return None++ # Validate required fields+ name = frontmatter.get('name')+ description = frontmatter.get('description')++ if not name or not description:+ logger.warning(f"[SkillLoader] Missing name or description in {skill_md_path}")+ return None++ # Validate name format (lowercase, hyphens, no consecutive hyphens)+ if not re.match(r'^[a-z0-9]+(-[a-z0-9]+)*$', name):+ logger.warning(f"[SkillLoader] Invalid skill name format: {name}")+ return None++ # Parse allowed-tools (space-delimited)+ allowed_tools = []+ if 'allowed-tools' in frontmatter:+ allowed_tools = frontmatter['allowed-tools'].split()++ return SkillMetadata(+ name=name,+ description=description,+ allowed_tools=allowed_tools,+ metadata=frontmatter.get('metadata', {})+ )++ def load_skill(self, name: str) -> Optional[Skill]:+ """Load full skill content by name.++ Args:+ name: Skill name to load++ Returns:+ Skill with full content or None if not found+ """+ # Check cache first+ if name in self._cache:+ return self._cache[name]++ # Check registry+ if name not in self._registry:+ logger.warning(f"[SkillLoader] Skill not found: {name}")+ return None++ metadata = self._registry[name]++ # Database skills have no path - load from database+ if metadata.path is None:+ return self._load_skill_from_database(name, metadata)++ # Filesystem skills+ skill_path = metadata.path+ skill_md = skill_path / "SKILL.md"++ if not skill_md.exists():+ logger.error(f"[SkillLoader] SKILL.md not found for {name}")+ return None++ # Parse full content+ content = skill_md.read_text(encoding='utf-8')++ # Extract body (after frontmatter)+ frontmatter_match = re.match(r'^---\s*\n.*?\n---\s*\n', content, re.DOTALL)+ if frontmatter_match:+ instructions = content[frontmatter_match.end():]+ else:+ instructions = content++ # Load scripts directory+ scripts = {}+ scripts_dir = skill_path / "scripts"+ if scripts_dir.exists():+ for script_file in scripts_dir.iterdir():+ if script_file.is_file():+ try:+ scripts[script_file.name] = script_file.read_text(encoding='utf-8')+ except Exception as e:+ logger.warning(f"[SkillLoader] Failed to read script {script_file}: {e}")++ # Load references directory+ references = {}+ refs_dir = skill_path / "references"+ if refs_dir.exists():+ for ref_file in refs_dir.iterdir():+ if ref_file.is_file() and ref_file.suffix in ['.md', '.txt', '.json']:+ try:+ references[ref_file.name] = ref_file.read_text(encoding='utf-8')+ except Exception as e:+ logger.warning(f"[SkillLoader] Failed to read reference {ref_file}: {e}")++ skill = Skill(+ metadata=metadata,+ instructions=instructions,+ scripts=scripts,+ references=references+ )++ # Cache the loaded skill+ self._cache[name] = skill+ logger.debug(f"[SkillLoader] Loaded full skill: {name} ({len(instructions)} chars)")++ return skill++ def _load_skill_from_database(self, name: str, metadata: SkillMetadata) -> Optional[Skill]:+ """Load skill from database (synchronous wrapper for cached data)."""+ # This should be called after scan_skills_with_database+ # The full instructions should be loaded via async method+ logger.warning(f"[SkillLoader] Database skill {name} requires async loading")+ return None++ async def load_skill_async(self, name: str) -> Optional[Skill]:+ """Async version of load_skill for database skills.++ Args:+ name: Skill name to load++ Returns:+ Skill with full content or None if not found+ """+ # Check cache first+ if name in self._cache:+ return self._cache[name]++ # Try filesystem first+ if name in self._registry and self._registry[name].path is not None:+ return self.load_skill(name)++ # Load from database+ if self._database:+ try:+ user_skill = await self._database.get_user_skill_by_name(name)+ if user_skill:+ allowed_tools = []+ if user_skill.allowed_tools:+ allowed_tools = [t.strip() for t in user_skill.allowed_tools.split(',')]++ metadata_dict = {}+ if user_skill.metadata_json:+ import json+ metadata_dict = json.loads(user_skill.metadata_json)++ metadata = SkillMetadata(+ name=user_skill.name,+ description=user_skill.description,+ allowed_tools=allowed_tools,+ metadata=metadata_dict,+ path=None+ )++ skill = Skill(+ metadata=metadata,+ instructions=user_skill.instructions,+ scripts={},+ references={}+ )++ self._cache[name] = skill+ return skill+ except Exception as e:+ logger.error(f"[SkillLoader] Failed to load skill {name} from database: {e}")++ return None++ def get_registry_prompt(self, skill_names: List[str] = None) -> str:+ """Generate skill registry for LLM system prompt.++ Args:+ skill_names: Optional list of skill names to include.+ If None, includes all registered skills.++ Returns:+ Formatted string listing available skills+ """+ skills_to_include = skill_names or list(self._registry.keys())++ if not skills_to_include:+ return ""++ lines = ["## Available Skills", ""]+ lines.append("You have access to the following skills. When a user's request matches a skill's purpose, activate it to help them.")+ lines.append("")++ for name in skills_to_include:+ if name in self._registry:+ metadata = self._registry[name]+ lines.append(f"- **{name}**: {metadata.description}")+ if metadata.allowed_tools:+ tools_str = ", ".join(metadata.allowed_tools)+ lines.append(f" - Tools: {tools_str}")++ lines.append("")+ lines.append("To use a skill, identify when the user's request matches its purpose and apply the skill's instructions.")++ return "\n".join(lines)++ def get_skill_instructions(self, name: str) -> Optional[str]:+ """Get full instructions for a skill (loads if not cached).++ Args:+ name: Skill name++ Returns:+ Markdown instructions or None if not found+ """+ skill = self.load_skill(name)+ return skill.instructions if skill else None++ def get_available_skills(self) -> List[Dict[str, Any]]:+ """Get list of available skills for frontend display.++ Returns:+ List of skill info dicts+ """+ return [+ {+ "name": metadata.name,+ "description": metadata.description,+ "allowed_tools": metadata.allowed_tools,+ "metadata": metadata.metadata,+ "is_builtin": metadata.path is not None+ }+ for metadata in self._registry.values()+ ]++ def clear_cache(self):+ """Clear the skill cache."""+ self._cache.clear()+ logger.debug("[SkillLoader] Cache cleared")+++# Global skill loader instance+_skill_loader: Optional[SkillLoader] = None+++def get_skill_loader() -> SkillLoader:+ """Get the global skill loader instance."""+ global _skill_loader+ if _skill_loader is None:+ # Default directories+ server_dir = Path(__file__).parent.parent+ skill_dirs = [+ server_dir / "skills", # Built-in skills+ Path.cwd() / ".machina" / "skills", # Project skills+ ]+ _skill_loader = SkillLoader(skill_dirs=skill_dirs)+ _skill_loader.scan_skills()+ return _skill_loader+++def init_skill_loader(database=None) -> SkillLoader:+ """Initialize the global skill loader with database support.++ Args:+ database: Database instance for user skill storage++ Returns:+ Initialized SkillLoader+ """+ global _skill_loader+ server_dir = Path(__file__).parent.parent+ skill_dirs = [+ server_dir / "skills", # Built-in skills+ Path.cwd() / ".machina" / "skills", # Project skills+ ]+ _skill_loader = SkillLoader(skill_dirs=skill_dirs, database=database)+ _skill_loader.scan_skills()+ return _skill_loaderdiff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.pyindex e2423f0d..55e6fc7f 100644--- a/server/services/temporal/activities.py+++ b/server/services/temporal/activities.py@@ -92,6 +92,9 @@ class NodeExecutionActivities:)print(f"[Activity] Starting node: {node_id} (type={node_type})")+ # Heartbeat at start to signal activity is alive+ activity.heartbeat(f"Starting {node_type}: {node_id}")+# Handle pre-executed trigger nodes (already have their output)if context.get("pre_executed"):print(f"[Activity] Node {node_id} is pre-executed, returning cached result")@@ -129,6 +132,9 @@ class NodeExecutionActivities:)try:+ # Heartbeat before potentially long WebSocket operation+ activity.heartbeat(f"Executing via WebSocket: {node_id}")+# Execute node via WebSocket (each call gets own connection from pool)result = await self._execute_via_websocket(context)diff --git a/server/skills/android-skill/SKILL.md b/server/skills/android-skill/SKILL.mdnew file mode 100644index 00000000..a8ff243d--- /dev/null+++ b/server/skills/android-skill/SKILL.md@@ -0,0 +1,127 @@+---+name: android-skill+description: 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-sensors+metadata:+ author: machina+ version: "1.0"+ category: device+---++# Android Device Control++This skill enables you to monitor and control Android devices connected via ADB or remote WebSocket.++## Capabilities++- Monitor battery status and health+- Control WiFi and Bluetooth+- Launch and list applications+- Get device location+- Control audio and screen+- Access camera and sensors++## Tool Reference++### android-battery+Get battery information.++Parameters:+- `action`: "status" (default)++Returns: level, charging, health, temperature++### 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++**User**: "What's my phone's battery level?"+**Action**: Use android-battery with:+- action: "status"++**User**: "Turn off WiFi"+**Action**: Use android-wifi with:+- action: "disable"++**User**: "What apps are installed?"+**Action**: Use android-apps with:+- action: "list"++**User**: "Open Chrome"+**Action**: Use android-apps with:+- action: "launch"+- package_name: "com.android.chrome"++**User**: "Where is my phone?"+**Action**: Use android-location with:+- action: "current"++**User**: "Set volume to 50%"+**Action**: Use android-audio with:+- action: "set_volume"+- volume: 50++## Device Connection++Before using Android tools, ensure:+1. Device is connected via ADB (USB) or remote WebSocket+2. Android Device Setup node shows connected status+3. Required permissions are granted on the device++## Error Handling++- 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 alternativesdiff --git a/server/skills/claude-assistant/SKILL.md b/server/skills/claude-assistant/SKILL.mdnew file mode 100644index 00000000..2705f211--- /dev/null+++ b/server/skills/claude-assistant/SKILL.md@@ -0,0 +1,45 @@+---+name: claude-assistant+description: General AI assistant with helpful, harmless, and honest responses. Use as the default personality for conversations.+metadata:+ author: machina+ version: "1.0"+ category: assistant+---++# Claude Assistant++You are a helpful, harmless, and honest AI assistant. Your goal is to assist users with their requests while being truthful and avoiding harmful content.++## Core Principles++1. **Helpfulness**: Provide clear, accurate, and useful information+2. **Honesty**: Be truthful about your capabilities and limitations+3. **Safety**: Avoid generating harmful, illegal, or unethical content++## Communication Style++- Be concise but thorough+- Use clear, simple language+- Break down complex topics into understandable parts+- Ask clarifying questions when needed+- Admit when you don't know something++## Response Guidelines++When responding to users:+1. Understand the intent behind their question+2. Provide the most helpful response possible+3. Include relevant context or caveats+4. Suggest follow-up questions if appropriate++## Examples++User: "What's the weather like?"+Response: I don't have access to real-time weather data. However, I can help you find weather information if you tell me your location, or you can use a weather service like weather.com.++User: "Help me write an email"+Response: I'd be happy to help you write an email. Could you tell me:+- Who is the recipient?+- What is the purpose of the email?+- What tone would you like (formal, casual, etc.)?diff --git a/server/skills/code-skill/SKILL.md b/server/skills/code-skill/SKILL.mdnew file mode 100644index 00000000..1631e495--- /dev/null+++ b/server/skills/code-skill/SKILL.md@@ -0,0 +1,140 @@+---+name: code-skill+description: Execute Python or JavaScript code for calculations, data processing, and automation. Use when user needs to run code, do calculations, or process data.+allowed-tools: code-python code-javascript+metadata:+ author: machina+ version: "1.0"+ category: code+---++# Code Execution++This skill enables you to execute Python and JavaScript code for various tasks.++## Capabilities++- Run Python code with full standard library+- Execute JavaScript code+- Perform complex calculations+- Process and transform data+- Generate outputs and visualizations++## Tool Reference++### code-python+Execute Python code.++Parameters:+- `code` (required): Python code to execute+- `input_data` (optional): Data to pass to the script (available as `input_data` variable)++Returns:+- output: Script output (print statements)+- result: Return value if any+- error: Error message if execution failed++### code-javascript+Execute JavaScript code.++Parameters:+- `code` (required): JavaScript code to execute+- `input_data` (optional): Data to pass to the script++Returns:+- output: Console output+- result: Return value+- error: Error message if execution failed++## Python Guidelines++### Available Libraries+- Standard library (math, json, datetime, re, etc.)+- Data processing (collections, itertools)+- String manipulation++### Input Data Access+```python+# Access input data from previous nodes+data = input_data # Available as global variable+print(f"Received: {data}")+```++### Output+```python+# Print for output display+print("Hello, World!")++# Return value for downstream nodes+result = {"status": "success", "value": 42}+```++## JavaScript Guidelines++### Input Data Access+```javascript+// Access input data from previous nodes+const data = input_data;+console.log(`Received: ${JSON.stringify(data)}`);+```++### Output+```javascript+// Console for output display+console.log("Hello, World!");++// Return value for downstream nodes+return { status: "success", value: 42 };+```++## Examples++**User**: "Calculate 15% tip on $85.50"+**Action**: Use code-python with:+```python+bill = 85.50+tip_percent = 15+tip = bill * (tip_percent / 100)+total = bill + tip+print(f"Tip: ${tip:.2f}")+print(f"Total: ${total:.2f}")+```++**User**: "Convert this JSON to CSV"+**Action**: Use code-python with:+```python+import json+import csv+import io++data = input_data # JSON from previous node+output = io.StringIO()+writer = csv.DictWriter(output, fieldnames=data[0].keys())+writer.writeheader()+writer.writerows(data)+print(output.getvalue())+```++**User**: "Generate 5 random numbers between 1 and 100"+**Action**: Use code-python with:+```python+import random+numbers = [random.randint(1, 100) for _ in range(5)]+print(f"Random numbers: {numbers}")+```++## Security Guidelines++1. **No file system access** outside designated directories+2. **No network requests** from code (use http-skill instead)+3. **No system commands** or shell access+4. **Limited execution time** (timeout after 30 seconds)+5. **No sensitive data** in code outputs++## Best Practices++1. Keep code simple and focused on one task+2. Use descriptive variable names+3. Add comments for complex logic+4. Validate input data before processing+5. Handle potential errors gracefullydiff --git a/server/skills/http-skill/SKILL.md b/server/skills/http-skill/SKILL.mdnew file mode 100644index 00000000..44a78c1b--- /dev/null+++ b/server/skills/http-skill/SKILL.md@@ -0,0 +1,93 @@+---+name: http-skill+description: Make HTTP requests to external APIs and web services. Use when user needs to fetch data from URLs, call APIs, or interact with web services.+allowed-tools: http-request+metadata:+ author: machina+ version: "1.0"+ category: integration+---++# HTTP Requests++This skill enables you to make HTTP requests to external APIs and web services.++## Capabilities++- Make GET, POST, PUT, DELETE, PATCH requests+- Send JSON payloads+- Set custom headers+- Handle API responses++## Tool Reference++### http-request+Make an HTTP request to a URL.++Parameters:+- `url` (required): Full URL to request+- `method` (optional): HTTP method (GET, POST, PUT, DELETE, PATCH). Default: GET+- `body` (optional): Request body as JSON object+- `headers` (optional): Custom headers as key-value pairs+- `timeout` (optional): Timeout in milliseconds (default: 30000)++Returns:+- status: HTTP status code+- body: Response body+- headers: Response headers++## Common Use Cases++### Fetching Data+```+GET https://api.example.com/data+```++### Creating Resources+```+POST https://api.example.com/items+Body: {"name": "New Item", "value": 100}+```++### Updating Resources+```+PUT https://api.example.com/items/123+Body: {"name": "Updated Item"}+```++## Examples++**User**: "Get the current Bitcoin price"+**Action**: Use http-request with:+- url: "https://api.coindesk.com/v1/bpi/currentprice.json"+- method: "GET"++**User**: "Post this data to my webhook"+**Action**: Use http-request with:+- url: "[user's webhook URL]"+- method: "POST"+- body: {"data": "..."}++**User**: "Check if example.com is up"+**Action**: Use http-request with:+- url: "https://example.com"+- method: "GET"++## Security Guidelines++1. **Never expose API keys** in responses+2. **Validate URLs** before making requests+3. **Don't make requests** to internal/private networks+4. **Respect rate limits** of external services+5. **Handle errors gracefully** and inform the user++## Error Handling++Common HTTP status codes:+- 200: Success+- 400: Bad request (check parameters)+- 401: Unauthorized (check API key)+- 403: Forbidden (access denied)+- 404: Not found+- 429: Too many requests (rate limited)+- 500: Server error (try again later)diff --git a/server/skills/maps-skill/SKILL.md b/server/skills/maps-skill/SKILL.mdnew file mode 100644index 00000000..cbdad57f--- /dev/null+++ b/server/skills/maps-skill/SKILL.md@@ -0,0 +1,88 @@+---+name: maps-skill+description: 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-create+metadata:+ author: machina+ version: "1.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++## Place Types++Common 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++## Examples++**User**: "What restaurants are near Times Square?"+**Action**: Use maps-nearby with:+- location: "Times Square, New York"+- type: "restaurant"+- radius: 500++**User**: "What's the address of the Eiffel Tower?"+**Action**: Use maps-geocode with:+- address: "Eiffel Tower, Paris"++**User**: "Show me a map of downtown Seattle"+**Action**: Use maps-create with:+- center: "Downtown Seattle, WA"+- zoom: 15++## Response Format++When 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 appropriatediff --git a/server/skills/memory-skill/SKILL.md b/server/skills/memory-skill/SKILL.mdnew file mode 100644index 00000000..06a649c2--- /dev/null+++ b/server/skills/memory-skill/SKILL.md@@ -0,0 +1,91 @@+---+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+metadata:+ author: machina+ version: "1.0"+ category: memory+---++# Memory Management++This skill enables you to save and recall information across conversations using short-term and long-term memory.++## Memory Types++### Short-term Memory (Buffer)+- Keeps recent conversation context+- Automatically managed by the system+- Limited to recent messages++### Long-term Memory (Session)+- Persists information across conversations+- Explicitly saved by you or the user+- Organized by session ID++## Capabilities++- Save important information for later recall+- Retrieve previously saved information+- Clear memory when no longer needed+- Track conversation topics and preferences++## When to Use Memory++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++Recall information when the user:+- Asks "do you remember..."+- References previous conversations+- Needs context from earlier discussions++## Tool Reference++### memory-save+Save information to long-term memory.++Parameters:+- `key` (required): Identifier for the memory+- `value` (required): Information to remember+- `session_id` (optional): Session for organization++### memory-get+Retrieve saved information.++Parameters:+- `key` (required): Identifier to look up+- `session_id` (optional): Specific session to search++### memory-clear+Clear memory entries.++Parameters:+- `key` (optional): Specific key to clear, or all if not specified+- `session_id` (optional): Specific session to clear++## Examples++**User**: "Remember that my favorite color is blue"+**Action**: Use memory-save with:+- key: "user_preference_color"+- value: "blue"++**User**: "What's my favorite color?"+**Action**: Use memory-get with:+- key: "user_preference_color"++**User**: "Forget everything about my preferences"+**Action**: Use memory-clear with:+- key: "user_preference_*" (wildcard pattern)++## 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 memoriesdiff --git a/server/skills/scheduler-skill/SKILL.md b/server/skills/scheduler-skill/SKILL.mdnew file mode 100644index 00000000..4e08f542--- /dev/null+++ b/server/skills/scheduler-skill/SKILL.md@@ -0,0 +1,106 @@+---+name: scheduler-skill+description: 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-cancel+metadata:+ author: machina+ version: "1.0"+ category: automation+---++# Task Scheduling++This skill enables you to schedule tasks, set timers, and create 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.++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)++### scheduler-list+List all active schedules and timers.++Parameters: None++### scheduler-cancel+Cancel a scheduled task.++Parameters:+- `name` (required): Name of schedule to cancel++## Cron Expression Format++```+* * * * *+| | | | |+| | | | +-- Day of week (0-7, Sun=0 or 7)+| | | +---- Month (1-12)+| | +------ Day of month (1-31)+| +-------- Hour (0-23)++---------- Minute (0-59)+```++### Common Patterns++| Pattern | Description |+|---------|-------------|+| `0 9 * * *` | Every day at 9:00 AM |+| `0 9 * * 1-5` | Weekdays at 9:00 AM |+| `*/15 * * * *` | Every 15 minutes |+| `0 0 1 * *` | First day of each month |+| `0 8,12,18 * * *` | At 8am, noon, and 6pm |++## Examples++**User**: "Remind me in 30 minutes"+**Action**: Use scheduler-timer with:+- duration: "30m"+- action: "Send reminder notification"+- name: "user_reminder"++**User**: "Send a daily report at 9am"+**Action**: Use scheduler-cron with:+- expression: "0 9 * * *"+- action: "Generate and send daily report"+- name: "daily_report"++**User**: "Check for updates every hour"+**Action**: Use scheduler-cron with:+- expression: "0 * * * *"+- action: "Check for system updates"+- name: "hourly_update_check"++**User**: "What schedules are active?"+**Action**: Use scheduler-list++**User**: "Cancel the daily report"+**Action**: Use scheduler-cancel with:+- name: "daily_report"++## 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/cancelleddiff --git a/server/skills/whatsapp-skill/SKILL.md b/server/skills/whatsapp-skill/SKILL.mdnew file mode 100644index 00000000..b7df713d--- /dev/null+++ b/server/skills/whatsapp-skill/SKILL.md@@ -0,0 +1,68 @@+---+name: whatsapp-skill+description: Send and receive WhatsApp messages. Use when user mentions WhatsApp, messaging, texting someone, or wants to send a message to a phone number.+allowed-tools: whatsapp-send whatsapp-status+metadata:+ author: machina+ version: "1.0"+ category: communication+---++# WhatsApp Messaging++This skill enables you to send WhatsApp messages to contacts and groups.++## Capabilities++- Send text messages to phone numbers+- Send messages to groups+- Check WhatsApp connection status++## Usage++### Sending Messages++When the user wants to send a message:++1. **Extract the recipient**: Phone number (with country code) or contact name+2. **Extract the message**: The content to send+3. **Use the whatsapp-send tool** with the extracted information++### Phone Number Format++- Always use international format with country code+- Example: +1234567890 (US), +447123456789 (UK)+- Remove spaces and dashes from numbers++## Tool Reference++### whatsapp-send+Send a message via WhatsApp.++Parameters:+- `phone_number` (required): Recipient phone number with country code+- `message` (required): Message text to send++### whatsapp-status+Check WhatsApp connection status.++Parameters: None++## Examples++**User**: "Send a WhatsApp to +1234567890 saying I'll be late"+**Action**: Use whatsapp-send with:+- phone_number: "+1234567890"+- message: "I'll be late"++**User**: "Text John that the meeting is at 3pm"+**Response**: I need John's phone number to send the message. Could you provide his number with the country code?++**User**: "Is WhatsApp connected?"+**Action**: Use whatsapp-status to check connection++## Error Handling++- If WhatsApp is not connected, inform the user and suggest checking the connection+- If phone number is invalid, ask for the correct format+- If message fails to send, provide the error and suggest retryingdiff --git a/server/whatsapp-rpc/src/go/whatsapp/service.go b/server/whatsapp-rpc/src/go/whatsapp/service.goindex 37061eaf..c3b0e990 100644--- a/server/whatsapp-rpc/src/go/whatsapp/service.go+++ b/server/whatsapp-rpc/src/go/whatsapp/service.go@@ -14,6 +14,7 @@ import ("github.com/sirupsen/logrus""github.com/skip2/go-qrcode""go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/proto/waCompanionReg""go.mau.fi/whatsmeow/proto/waE2E""go.mau.fi/whatsmeow/store""go.mau.fi/whatsmeow/store/sqlstore"@@ -54,8 +55,10 @@ type Service struct {func NewService(dbConfig config.DatabaseConfig, logger *logrus.Logger) (*Service, error) {- // Set device name (shows in WhatsApp linked devices)- store.SetOSInfo("MachinaOs", [3]uint32{1, 0, 0})+ // Configure device to appear as legitimate WhatsApp Web on Chrome+ // Uses default WhatsApp Web version and Chrome platform type for natural appearance+ store.DeviceProps.PlatformType = waCompanionReg.DeviceProps_CHROME.Enum()+ store.SetOSInfo("Windows - Zeenie", store.GetWAVersion())// Ensure database directory existsdbDir := filepath.Dir(dbConfig.Path)