Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Fix sub-agent task completion handling and data flow
trohitgbca0149ea308
diff --git a/.env.template b/.env.templateindex c5c8432a..98a89368 100644--- a/.env.template+++ b/.env.template@@ -57,6 +57,22 @@ MAPS_TIMEOUT=30# Health CheckHEALTH_CHECK_INTERVAL=60+# Cleanup Configuration (for long-running daemon)+CLEANUP_ENABLED=true+CLEANUP_INTERVAL=3600+CLEANUP_LOGS_MAX_COUNT=1000+CLEANUP_CACHE_MAX_AGE_HOURS=24++# Feature Toggles+WS_LOGGING_ENABLED=true++# Gunicorn Configuration (for production deployment)+# GUNICORN_TIMEOUT=120+# GUNICORN_GRACEFUL_TIMEOUT=30+# GUNICORN_KEEPALIVE=5+# GUNICORN_MAX_REQUESTS=10000+# GUNICORN_MAX_REQUESTS_JITTER=1000+# WebSocket Configuration (For remote Android device connections)WEBSOCKET_URL=WEBSOCKET_API_KEY=diff --git a/CLAUDE.md b/CLAUDE.mdindex f695eb2d..db9db87e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -14,6 +14,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Specialized Agent Guide](./docs-internal/specialized_agent_node_creation.md)** | Guide for creating specialized AI agents (Android, Coding, Web, Task, Social, Travel, Tool, Productivity, Payments, Consumer) with full AI configuration || **[Dual-Purpose Tool Guide](./docs-internal/dual_purpose_tool_node_creation.md)** | Guide for nodes that work as both workflow nodes AND AI Agent tools (e.g., whatsappSend) || **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute via LangGraph |+| **[Agent Delegation](./docs-internal/agent_delegation.md)** | How memory, parameters, and execution context flow when one AI agent delegates work to another agent connected as a tool |+| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action || **[Workflow Schema](./docs-internal/workflow-schema.md)** | JSON schema for workflows, edge handle conventions, config node architecture || **[Execution Engine Design](./docs-internal/DESIGN.md)** | Architecture patterns, design standards, and implementation details for the workflow execution engine || **[Execution Roadmap](./docs-internal/ROADMAP.md)** | Implementation status, completed phases, and pending features |@@ -78,7 +80,8 @@ server/core/├── container.py # Dependency injection container├── database.py # SQLite database with cache CRUD methods├── cache.py # CacheService with Redis/SQLite/Memory fallback-└── settings.py # Application configuration+├── config.py # Application configuration+└── logging.py # Logging configurationserver/models/├── cache.py # CacheEntry SQLModel for SQLite cache@@ -286,15 +289,15 @@ class CacheEntry(SQLModel, table=True):## Codebase Summary- **Hybrid architecture**: Node.js + Python + React TypeScript-- **68 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 10 specialized agents + 10 skills + 4 dedicated tools + 2 dual-purpose tools + 16 Android + 4 WhatsApp + 3 Location + 1 Code + 3 Utility + 6 Document)-- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (32 message types)+- **75 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 10 specialized agents + 11 skills + 3 dedicated tools + 6 dual-purpose tools + 16 Android + 3 WhatsApp + 2 Social + 3 Location + 2 Code + 5 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow)+- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (84 message handlers)- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated## Architecture RefactoringThe project was completely refactored from schema-based node definitions to explicit INodeProperties interface system inspired by n8n architecture. Key changes:- **Pure INodeProperties System**: Removed all backward compatibility layers-- **35 Implemented Node Components**: AI models, agents, location services, Android automation, WhatsApp, Python code execution, and HTTP/Webhook utilities with full execution support-- **WebSocket-First Communication**: 25 WebSocket message handlers replace most REST API calls+- **75 Implemented Node Components**: AI models, agents, skills, location services, Android automation, WhatsApp, social, code execution, HTTP/Webhook utilities, document processing, chat, and schedulers+- **WebSocket-First Communication**: 84 WebSocket message handlers replace most REST API calls- **Resource-Operation Pattern**: Organized by functional categories (AI, Location, Android, WhatsApp)- **TypeScript-First**: Full type safety with proper interface alignment- **Code Cleanup**: Removed dead code, unused files, and legacy methods@@ -307,18 +310,22 @@ The project was completely refactored from schema-based node definitions to expl- `src/types/NodeTypes.ts` - Legacy compatibility types (NodeParameter, NodeOutput)### Node System-- `src/nodeDefinitions.ts` - Main registry importing modular node definitions+- `src/nodeDefinitions.ts` - Main registry importing and merging all modular node definitions- `src/nodeDefinitions/aiModelNodes.ts` - AI chat model definitions using factory pattern- `src/nodeDefinitions/aiAgentNodes.ts` - AI agent and processing components-- `src/nodeDefinitions/skillNodes.ts` - Skill node definitions (10 nodes including masterSkill)+- `src/nodeDefinitions/skillNodes.ts` - Skill node definitions (11 nodes including masterSkill and customSkill)- `src/nodeDefinitions/specializedAgentNodes.ts` - Specialized AI agent definitions (10 nodes) with shared AI_AGENT_PROPERTIES and centralized dracula theming+- `src/nodeDefinitions/toolNodes.ts` - AI Agent tool nodes (calculatorTool, currentTimeTool, webSearchTool)- `src/nodeDefinitions/androidServiceNodes.ts` - 16 Android service nodes (monitoring, apps, automation, sensors, media)-- `src/nodeDefinitions/androidDeviceNodes.ts` - Android device setup and ADB port forwarding- `src/nodeDefinitions/locationNodes.ts` - Google Maps and location services-- `src/nodeDefinitions/whatsappNodes.ts` - WhatsApp messaging integration-- `src/nodeDefinitions/codeNodes.ts` - Python code execution node with syntax highlighting-- `src/nodeDefinitions/utilityNodes.ts` - HTTP Request and Webhook nodes (httpRequest, webhookTrigger, webhookResponse)+- `src/nodeDefinitions/whatsappNodes.ts` - WhatsApp messaging integration (3 nodes)+- `src/nodeDefinitions/socialNodes.ts` - Unified social messaging nodes (socialReceive, socialSend)+- `src/nodeDefinitions/codeNodes.ts` - Python and JavaScript code execution nodes+- `src/nodeDefinitions/utilityNodes.ts` - HTTP, Webhook, chatTrigger, and console nodes- `src/nodeDefinitions/documentNodes.ts` - Document processing nodes (httpScraper, fileDownloader, documentParser, textChunker, embeddingGenerator, vectorStore)+- `src/nodeDefinitions/chatNodes.ts` - Chat send and history nodes+- `src/nodeDefinitions/schedulerNodes.ts` - Timer and cron scheduler nodes+- `src/nodeDefinitions/workflowNodes.ts` - Workflow start node- `src/factories/baseChatModelFactory.ts` - Factory for creating standardized chat models- `src/services/executionService.ts` - Node execution engine with routing to Python backend@@ -429,11 +436,11 @@ React Flow edges use dynamic Dracula colors via `getEdgeStyles(theme.dracula)`:### WebSocket-First ArchitectureThe project uses WebSocket as the primary communication method between frontend and backend, replacing most REST API calls:- `src/contexts/WebSocketContext.tsx` - Central WebSocket context with request/response pattern-- `server/routers/websocket.py` - WebSocket endpoint with 32 message handlers+- `server/routers/websocket.py` - WebSocket endpoint with 84 message handlers- `server/services/status_broadcaster.py` - Connection management and broadcasting## Implemented Node Types-The following 58 nodes are currently implemented and functional:+The following 75 nodes are currently implemented and functional:### AI Chat Models (6 nodes)- **openaiChatModel**: OpenAI GPT models with response format options. O-series models (o1, o3, o4) support reasoning effort parameter.@@ -448,10 +455,10 @@ The following 58 nodes are currently implemented and functional:- **chatAgent**: Conversational AI agent with memory and skill support for multi-turn chat interactions. Parameters: Provider, Model, Prompt (supports `{{chatTrigger.message}}` template or auto-fallback from connected input), System Message. Behavior extended by connected skills.- **simpleMemory**: Markdown-based conversation memory with editable UI, window-based trimming, and optional vector DB for long-term semantic retrieval-### Zeenie Skill Nodes (10 nodes)+### Zeenie Skill Nodes (11 nodes)Skill nodes connect to Zeenie's `input-skill` handle to provide capabilities defined in SKILL.md files following the [Agent Skills specification](https://agentskills.io/specification):- **masterSkill**: Master Skill (icon: target) - Aggregates multiple skills with enable/disable toggles. Split-panel UI: left panel shows skill list with checkboxes, right panel shows selected skill's markdown editor. Enabled skills are expanded into individual skill entries when the AI Agent executes.-- **claudeSkill**: Assistant Skill (icon: sparkles) - default assistant personality with helpful, harmless, honest responses+- **assistantPersonality**: Assistant Skill (icon: sparkles) - default assistant personality with helpful, harmless, honest responses- **whatsappSkill**: Send and receive WhatsApp messages via Zeenie- **memorySkill**: Long-term memory management across conversations- **mapsSkill**: Location services - geocoding, nearby places, directions via Google Maps@@ -716,7 +723,7 @@ Android device connection is configured via the Credentials Modal (Android panel- **cameraControl**: Camera control - get camera info, take photos, camera capabilities- **mediaControl**: Media playback control - volume control, playback control, play media files-### WhatsApp Nodes (4 nodes)+### WhatsApp Nodes (3 nodes)- **whatsappSend**: **Dual-purpose node** - Send WhatsApp messages (text, image, video, audio, document, sticker, location, contact). Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Full parameter schema for recipient type, message type, media URL, location coordinates, contact vCard.- **whatsappDb**: **Dual-purpose node** - Comprehensive WhatsApp database query node with 6 operations. Works as workflow node OR AI Agent tool. Group: `['whatsapp', 'tool']`. Operations:- `chat_history`: Retrieve messages from individual or group chats with filtering and pagination@@ -725,7 +732,6 @@ Android device connection is configured via the Credentials Modal (Android panel- `get_contact_info`: Get full contact info (name, phone, profile picture) for sending/replying- `list_contacts`: List all contacts with saved names- `check_contacts`: Check WhatsApp registration status for phone numbers-- **whatsappConnect**: Check WhatsApp connection status and device info- **whatsappReceive**: Event-driven trigger that waits for incoming WhatsApp messages with filters (message type, sender, group, keywords, forwarded status). Marked with `['whatsapp', 'trigger']` group for n8n-style trigger identification. Stores group/sender names alongside JID/phone for display persistence. The Go RPC resolves LIDs to phone numbers before sending events - `sender_phone` field is already resolved. Filter options: All Messages, From Any Contact (Non-Group), From Specific Contact, From Specific Group, Contains Keywords### Social Nodes (2 nodes)@@ -734,17 +740,20 @@ Unified social messaging nodes for multi-platform communication. Supports WhatsA- **socialReceive**: Normalizes messages from platform triggers into unified format. Multiple outputs: Message, Media, Contact, Metadata. Filters by channel, message type, sender.- **socialSend**: **Dual-purpose node** - Send messages to any supported platform. Works as workflow node OR AI Agent tool. Supports text, image, video, audio, document, sticker, location, contact, poll, buttons, list message types.-### Workflow Nodes (1 node)-- **workflowTrigger**: Manual workflow trigger to start workflow execution+### Workflow Nodes (2 nodes)+- **start**: Manual workflow trigger to start workflow execution+- **taskTrigger**: Event-driven trigger that fires when a delegated child agent completes its task (success or error). Filters by task_id, agent_name, status (all/completed/error), and parent_node_id. Output includes task_id, status, agent_name, result/error, workflow_id.### Code Nodes (2 nodes)- **pythonExecutor**: **Dual-purpose node** - Execute Python code with syntax-highlighted editor, input_data access, and console output. Works as workflow node OR AI Agent tool (`python_code`). Available libraries: math, json, datetime, timedelta, re, random, Counter, defaultdict.- **javascriptExecutor**: **Dual-purpose node** - Execute JavaScript code with syntax-highlighted editor and console output. Works as workflow node OR AI Agent tool (`javascript_code`).-### Utility Nodes (3 nodes)+### Utility Nodes (5 nodes)- **httpRequest**: Make HTTP requests to external APIs (GET, POST, PUT, DELETE, PATCH) with configurable headers, body, and timeout- **webhookTrigger**: Event-driven trigger that waits for incoming HTTP requests at `/webhook/{path}` with method filtering and authentication options- **webhookResponse**: Send custom response back to webhook caller with configurable status code, body, and content type+- **chatTrigger**: Trigger node that receives messages from the Console Panel chat interface+- **console**: Console output node for logging workflow execution data### Document Processing Nodes (6 nodes)RAG pipeline nodes for document ingestion, processing, and vector storage. Supports multiple providers and backends.@@ -756,6 +765,14 @@ RAG pipeline nodes for document ingestion, processing, and vector storage. Suppo- **embeddingGenerator**: Generate vector embeddings from text chunks. Providers: HuggingFace (local), OpenAI, Ollama. Default model: BAAI/bge-small-en-v1.5.- **vectorStore**: Store and query vector embeddings. Operations: store, query, delete. Backends: ChromaDB (local), Qdrant (production), Pinecone (cloud).+### Chat Nodes (2 nodes)+- **chatSend**: Send messages to chat conversations+- **chatHistory**: Retrieve chat conversation history++### Scheduler Nodes (2 nodes)+- **timer**: Timer-based trigger with configurable delay+- **cronScheduler**: Cron expression-based scheduling trigger+#### Document Processing Dependencies```# Required (in server/requirements.txt)@@ -947,8 +964,8 @@ All scripts in `scripts/` are cross-platform Node.js (Windows, macOS, Linux, WSLSee **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.## Current Status-✅ **INodeProperties System**: Fully implemented with 41 functional components-✅ **WebSocket-First Architecture**: 32 message handlers replacing REST APIs+✅ **INodeProperties System**: Fully implemented with 75 functional node components+✅ **WebSocket-First Architecture**: 84 message handlers replacing REST APIs✅ **Code Editor**: Python executor with syntax-highlighted editor (react-simple-code-editor + prismjs) and console output✅ **Component Palette**: Emoji icons with distinct dracula-themed category colors, localStorage persistence for collapsed sections✅ **Android Integration**: 16 Android service nodes with ADB automation and remote WebSocket support@@ -1474,8 +1491,12 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {subtitle: 'LangGraph Agent',themeColorKey: 'purple',bottomHandles: [- { id: 'input-memory', label: 'Memory', position: '35%' },- { id: 'input-tools', label: 'Tool', position: '65%' },+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],},chatAgent: {@@ -1484,13 +1505,17 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {subtitle: 'Conversational Agent',themeColorKey: 'cyan',bottomHandles: [- { id: 'input-memory', label: 'Memory', position: '35%' },- { id: 'input-skill', label: 'Skill', position: '65%' },+ { id: 'input-skill', label: 'Skill', position: '25%' },+ { id: 'input-tools', label: 'Tool', position: '75%' },+ ],+ leftHandles: [+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],},// ... 10 specialized agents (android_agent, coding_agent, web_agent, task_agent,// social_agent, travel_agent, tool_agent, productivity_agent, payments_agent, consumer_agent)- // each with themeColorKey, standard Skill/Tool bottom handles, Memory left handle+ // each with themeColorKey, standard Skill/Tool bottom handles, Memory/Task left handles};```@@ -1509,8 +1534,9 @@ In `Dashboard.tsx`, both agent types map to the same component:| Tool Calling | Yes (LangGraph) | Yes (LangGraph) || Memory Support | Yes | Yes || Skill Support | Yes | Yes |+| Task Input | Yes (input-task) | Yes (input-task) || Bottom Handles | Skill, Tools | Skill, Tools |-| Left Handles | Input, Memory | Input, Memory |+| Left Handles | Input, Memory, Task | Input, Memory, Task || Backend Method | `execute_agent()` | `execute_chat_agent()` || Async Delegation | Yes (fire-and-forget) | Yes (fire-and-forget) |@@ -2139,6 +2165,116 @@ python-jose[cryptography]>=3.3.0email-validator>=2.0.0```+## Example Workflows++### Overview+Example workflows are pre-built workflow templates that auto-load on first use. They provide users with starting points to explore the platform's capabilities. Examples are stored as JSON files in the `workflows/` folder at the project root.++### Architecture+```+workflows/ # Example workflow JSON files (project root)+├── hello_world.json+├── zeenie_chat.json+└── ...++server/services/+└── example_loader.py # Loads and imports examples++server/models/database.py # UserSettings.examples_loaded flag+server/core/database.py # Migration for examples_loaded column+server/routers/database.py # Auto-load logic in get_all_workflows+```++### How It Works+1. **First Fetch Detection**: When `get_all_workflows` API is called, it checks `UserSettings.examples_loaded`+2. **Auto-Import**: If `examples_loaded=false`, imports all JSON files from `workflows/` folder+3. **Mark Complete**: Sets `examples_loaded=true` to prevent re-import on subsequent fetches+4. **Anonymous Support**: Uses `user_id="default"` when `VITE_AUTH_ENABLED=false`++### Workflow JSON Format+Example workflows use the same format as UI exports:+```json+{+ "id": "hello_world",+ "name": "Hello World",+ "description": "A simple workflow with a start node",+ "nodes": [+ {+ "id": "start_1",+ "type": "start",+ "position": {"x": 250, "y": 150},+ "data": {"label": "Start"}+ }+ ],+ "edges": [],+ "version": "0.0.10"+}+```++**Fields:**+| Field | Description |+|-------|-------------|+| `id` | Unique identifier (prefixed with `example_` when imported) |+| `name` | Display name in workflow sidebar |+| `description` | Optional description |+| `nodes` | Array of node objects with id, type, position, data |+| `edges` | Array of edge connections between nodes |+| `version` | App version (e.g., "0.0.10") |++### Key Files+| File | Description |+|------|-------------|+| `workflows/*.json` | Example workflow JSON files |+| `server/services/example_loader.py` | `get_example_workflows()`, `import_examples_for_user()` |+| `server/models/database.py` | `UserSettings.examples_loaded` field |+| `server/core/database.py` | Migration adds `examples_loaded` column |+| `server/routers/database.py` | Auto-load check in `get_all_workflows` |++### Example Loader Service+```python+# server/services/example_loader.py+EXAMPLES_DIR = Path(__file__).parent.parent.parent / "workflows"++def get_example_workflows() -> List[Dict[str, Any]]:+ """Load all example workflow JSON files from disk."""++async def import_examples_for_user(database) -> int:+ """Import all examples using existing database.save_workflow().+ Returns count of workflows imported."""+```++### Auto-Load Logic+```python+# server/routers/database.py - get_all_workflows endpoint+user_id = "default"+settings = await database.get_user_settings(user_id)++if not settings or not settings.get("examples_loaded", False):+ count = await import_examples_for_user(database)+ if count > 0:+ logger.info(f"Auto-loaded {count} example workflows")+ current = settings or {}+ current["examples_loaded"] = True+ await database.save_user_settings(current, user_id)+```++### Adding Custom Examples+1. Export a workflow from the UI (File > Export)+2. Copy the JSON file to `workflows/` folder at project root+3. Edit the `id` and `name` fields as needed+4. Delete `server/machina.db` (or set `examples_loaded=false` in database)+5. Restart server - examples auto-load on first workflow list fetch++### Database Migration+The `examples_loaded` column is automatically added to existing databases:+```python+# server/core/database.py - _migrate_user_settings()+if "examples_loaded" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN examples_loaded BOOLEAN DEFAULT 0"+ ))+```+## AI Chat Model Development Guide### Adding New AI Providers@@ -3110,6 +3246,8 @@ class TriggerConfig:TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {'whatsappReceive': TriggerConfig('whatsappReceive', 'whatsapp_message_received', 'WhatsApp Message'),'webhookTrigger': TriggerConfig('webhookTrigger', 'webhook_received', 'Webhook Request'),+ 'chatTrigger': TriggerConfig('chatTrigger', 'chat_message_received', 'Chat Message'),+ 'taskTrigger': TriggerConfig('taskTrigger', 'task_completed', 'Task Completed'),# Future: 'emailTrigger', 'mqttTrigger', 'telegramTrigger', etc.}@@ -3237,6 +3375,72 @@ const sampleSchemas = {};```+### Task Trigger Node++The Task Trigger node fires when a delegated child agent completes its task (success or error). This enables parent agents to react to child completion via workflow nodes.++#### Node Definition (`client/src/nodeDefinitions/workflowNodes.ts`)+```typescript+taskTrigger: {+ displayName: 'Task Completed',+ name: 'taskTrigger',+ icon: '📨',+ group: ['trigger', 'workflow'],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main',+ description: 'task_id, status, agent_name, result/error, parent_node_id'+ }],+ properties: [+ // Task ID Filter: Optional specific task ID to watch+ // Agent Name Filter: Optional partial match on agent name+ // Status Filter: all, completed, error+ // Parent Node ID: Optional filter by parent agent node+ ]+}+```++#### Output Schema (`client/src/components/parameterPanel/InputSection.tsx`)+```typescript+taskTrigger: {+ task_id: 'string',+ status: 'string', // 'completed' or 'error'+ agent_name: 'string',+ agent_node_id: 'string',+ parent_node_id: 'string',+ result: 'string', // Present when status='completed'+ error: 'string', // Present when status='error'+ workflow_id: 'string',+}+```++#### Event Dispatch (`server/services/handlers/tools.py`)+The `task_completed` event is dispatched when a delegated child agent finishes:+```python+# On success:+await broadcaster.send_custom_event('task_completed', {+ 'task_id': task_id,+ 'status': 'completed',+ 'agent_name': agent_label,+ 'agent_node_id': node_id,+ 'parent_node_id': config.get('parent_node_id', ''),+ 'result': result.get('result', {}).get('response', ...),+ 'workflow_id': workflow_id,+})++# On error:+await broadcaster.send_custom_event('task_completed', {+ 'task_id': task_id,+ 'status': 'error',+ 'agent_name': agent_label,+ 'agent_node_id': node_id,+ 'parent_node_id': config.get('parent_node_id', ''),+ 'error': str(e),+ 'workflow_id': workflow_id,+})+```+### Adding New Trigger Types1. **Add to Registry** in `server/services/event_waiter.py`:@@ -3423,41 +3627,31 @@ def has_real_android_devices(self) -> bool:Updated `client_left` and presence handlers use `has_real_android_devices()` instead of checking total device count.-### WebSocket Message Types (32 Handlers)+### WebSocket Message Types (84 Handlers)#### Request/Response Messages (Client -> Server -> Client)-| Message Type | Description |-|--------------|-------------|-| `get_node_parameters` | Get parameters for a single node |-| `get_all_node_parameters` | Get parameters for multiple nodes |-| `save_node_parameters` | Save node parameters to database |-| `delete_node_parameters` | Delete node parameters |-| `execute_node` | Execute a workflow node |-| `cancel_execution` | Cancel running node execution |-| `execute_ai_node` | Execute AI model node |-| `get_ai_models` | Get available models for provider |-| `validate_api_key` | Validate AI provider API key |-| `get_stored_api_key` | Get stored API key for provider |-| `save_api_key` | Save API key to secure storage |-| `delete_api_key` | Delete stored API key |-| `get_android_devices` | List connected Android devices |-| `execute_android_action` | Execute Android service action |-| `setup_android_device` | Setup Android device connection |-| `validate_maps_key` | Validate Google Maps API key |-| `whatsapp_status` | Get WhatsApp connection status |-| `whatsapp_qr` | Get WhatsApp QR code |-| `whatsapp_send` | Send WhatsApp message |-| `whatsapp_start` | Start WhatsApp connection |-| `cancel_event_wait` | Cancel active event waiter (trigger nodes) |-| `get_active_waiters` | Get list of active event waiters |-| `send_chat_message` | Send chat message, optionally to specific node |-| `get_chat_messages` | Get chat history for session |-| `clear_chat_messages` | Clear chat history for session |-| `get_skill_content` | Get skill instructions from database or SKILL.md file |-| `save_skill_content` | Save skill instructions to database |-| `list_skill_folders` | List available skill folders under server/skills/ |-| `scan_skill_folder` | Scan a folder for skills, returns name/description/metadata |-| `ping` | Keep-alive request |+| Category | Message Types |+|----------|--------------|+| **Status/Ping** | `ping`, `get_status`, `get_android_status`, `get_node_status`, `get_variable` |+| **Node Parameters** | `get_node_parameters`, `get_all_node_parameters`, `save_node_parameters`, `delete_node_parameters` |+| **Tool Schemas** | `get_tool_schema`, `save_tool_schema`, `delete_tool_schema`, `get_all_tool_schemas` |+| **Node Execution** | `execute_node`, `execute_workflow`, `cancel_execution`, `get_node_output`, `clear_node_output` |+| **Triggers/Events** | `cancel_event_wait`, `get_active_waiters` |+| **Dead Letter Queue** | `get_dlq_entries`, `get_dlq_entry`, `get_dlq_stats`, `replay_dlq_entry`, `remove_dlq_entry`, `purge_dlq` |+| **Deployment** | `deploy_workflow`, `cancel_deployment`, `get_deployment_status`, `get_workflow_lock`, `update_deployment_settings` |+| **AI Operations** | `execute_ai_node`, `get_ai_models` |+| **API Keys** | `validate_api_key`, `get_stored_api_key`, `save_api_key`, `delete_api_key` |+| **Claude OAuth** | `claude_oauth_login`, `claude_oauth_status` |+| **Android** | `get_android_devices`, `execute_android_action`, `android_relay_connect`, `android_relay_disconnect`, `android_relay_reconnect` |+| **Maps** | `validate_maps_key` |+| **WhatsApp** | `whatsapp_status`, `whatsapp_qr`, `whatsapp_send`, `whatsapp_start`, `whatsapp_restart`, `whatsapp_groups`, `whatsapp_group_info`, `whatsapp_chat_history`, `whatsapp_rate_limit_get`, `whatsapp_rate_limit_set`, `whatsapp_rate_limit_stats`, `whatsapp_rate_limit_unpause` |+| **Workflow Storage** | `save_workflow`, `get_workflow`, `get_all_workflows`, `delete_workflow` |+| **Chat Messages** | `send_chat_message`, `get_chat_messages`, `clear_chat_messages`, `save_chat_message` |+| **Console/Terminal** | `get_console_logs`, `clear_console_logs`, `get_terminal_logs`, `clear_terminal_logs` |+| **User Skills** | `get_user_skills`, `get_user_skill`, `create_user_skill`, `update_user_skill`, `delete_user_skill` |+| **Built-in Skills** | `get_skill_content`, `save_skill_content`, `scan_skill_folder`, `list_skill_folders` |+| **Memory/Skill Reset** | `clear_memory`, `reset_skill` |+| **User Settings** | `get_user_settings`, `save_user_settings` |#### Broadcast Messages (Server -> All Clients)| Message Type | Description |@@ -3614,7 +3808,7 @@ This function:- **Performance**: Fast HMR updates and clean TypeScript compilation- **AI Architecture**: 5-layer system with factory pattern and secure credential management- **Android Architecture**: Factory-based node creation with ADB integration for device automation-- **WebSocket-First Architecture**: 32 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations+- **WebSocket-First Architecture**: 84 message handlers replace REST APIs for parameters, execution, API keys, Android, WhatsApp, and skill operations- **WebSocket Hooks**: Dedicated React hooks (useWhatsApp, useExecution, useApiKeys, useAndroidOperations, useParameterPanel) for clean component integration- **WebSocket Support**: Persistent remote Android device connections via WebSocket proxy with background tasks- Connection stays alive across multiple API requests until switched to local ADB@@ -3699,4 +3893,5 @@ This function:- **Node Data Architecture**: `node.data` only stores `label` (display name). All parameters are stored in the database via `save_node_parameters` WebSocket handler. This prevents parameter bloat in workflow JSON exports and keeps React Flow state lightweight. `useDragAndDrop.ts` saves default parameters to DB on drop, not to `node.data`.- **Workflow Export Sanitization**: `exportWorkflow()` in `useWorkflow.ts` strips transient fields (`selected`, `dragging`, `width`, `height`, `measured`, `positionAbsolute`) from nodes and edges before export. Only `id`, `type`, `position`, `data.label` are included per node.- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB is source of truth for skill instructions (seeded from SKILL.md on first load). Icon resolution: node definition (SVG) > SKILL.md metadata (emoji) > fallback. Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor.+- **Example Workflows**: Auto-load example workflows from `workflows/` folder on first use. Uses `UserSettings.examples_loaded` flag to track import status. Supports anonymous users (`user_id="default"`). Reuses existing `database.save_workflow()` for import. See "Example Workflows" section for details.- never use emojis in prints\ No newline at end of filediff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex e35b6f0f..d9e9ed93 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -65,7 +65,7 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {const types: Record<string, React.ComponentType<any>> = {};// Trigger nodes (no input handles) - check by group or specific types- const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'chatTrigger'];+ const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'chatTrigger', 'taskTrigger'];// Pre-register specialized agent nodes explicitly to ensure they're always available// This handles cases where nodeDefinitions iteration order might miss them@@ -651,8 +651,8 @@ const DashboardContent: React.FC = () => {if (!currentWorkflow) return;// Check if there's at least one trigger node (workflow entry points)- // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, workflowTrigger, chatTrigger- const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger', 'chatTrigger'];+ // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, workflowTrigger, chatTrigger, taskTrigger+ const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];const hasTriggerNode = nodes.some(node => triggerTypes.includes(node.type || ''));if (!hasTriggerNode) {alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, Chat Trigger, etc.) to begin deployment.');diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex bf32efb7..2d9b0d45 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -66,7 +66,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -82,7 +83,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],width: 260,height: 160,@@ -128,7 +130,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -144,7 +147,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -160,7 +164,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -176,7 +181,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -192,7 +198,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -208,7 +215,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -224,7 +232,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -240,7 +249,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -256,7 +266,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,@@ -272,7 +283,8 @@ const AGENT_CONFIGS: Record<string, AgentConfig> = {{ id: 'input-tools', label: 'Tool', position: '75%' },],leftHandles: [- { id: 'input-memory', label: 'Memory', position: '70%' },+ { id: 'input-memory', label: 'Memory', position: '55%' },+ { id: 'input-task', label: 'Task', position: '85%' },],topOutputHandle: { id: 'output-top', label: 'Output' },width: 260,diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex 794e05ce..0b2a7304 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -379,6 +379,16 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =timestamp: 'string',session_id: 'string'},+ taskTrigger: {+ task_id: 'string',+ status: 'string', // 'completed' or 'error'+ agent_name: 'string',+ agent_node_id: 'string',+ parent_node_id: 'string',+ result: 'string', // Present when status='completed'+ error: 'string', // Present when status='error'+ workflow_id: 'string',+ },// Social nodes schema (4 output handles)social: {// Output 1: message text for LLM input@@ -487,6 +497,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const isCodeExecutor = isPython || isJavaScript;const isCronScheduler = nodeType === 'cronScheduler';const isChatTrigger = nodeType === 'chatTrigger';+ const isTaskTrigger = nodeType === 'taskTrigger';const isSocialReceive = nodeType === 'socialReceive';const isSocialSend = nodeType === 'socialSend';@@ -528,6 +539,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =isCodeExecutor ? sampleSchemas.python :isCronScheduler ? sampleSchemas.cronScheduler :isChatTrigger ? sampleSchemas.chatTrigger :+ isTaskTrigger ? sampleSchemas.taskTrigger :isSocialReceive ? sampleSchemas.social :isSocialSend ? sampleSchemas.socialSend :{ data: 'any' };diff --git a/client/src/nodeDefinitions/aiAgentNodes.ts b/client/src/nodeDefinitions/aiAgentNodes.tsindex fffc26bd..db94bd0d 100644--- a/client/src/nodeDefinitions/aiAgentNodes.ts+++ b/client/src/nodeDefinitions/aiAgentNodes.ts@@ -43,6 +43,12 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {displayName: 'Tool',type: 'main' as NodeConnectionType,description: 'Tool nodes for agent capabilities'+ },+ {+ name: 'task',+ displayName: 'Task',+ type: 'main' as NodeConnectionType,+ description: 'Task completion events from taskTrigger'}],outputs: [{@@ -199,6 +205,12 @@ export const aiAgentNodes: Record<string, INodeTypeDescription> = {displayName: 'Tool',type: 'main' as NodeConnectionType,description: 'Tool nodes (httpRequest, etc.) for LangGraph tool calling'+ },+ {+ name: 'task',+ displayName: 'Task',+ type: 'main' as NodeConnectionType,+ description: 'Task completion events from taskTrigger'}],outputs: [{diff --git a/client/src/nodeDefinitions/specializedAgentNodes.ts b/client/src/nodeDefinitions/specializedAgentNodes.tsindex 58e921e3..afdbad41 100644--- a/client/src/nodeDefinitions/specializedAgentNodes.ts+++ b/client/src/nodeDefinitions/specializedAgentNodes.ts@@ -6,6 +6,54 @@ import {} from '../types/INodeProperties';import { dracula } from '../styles/theme';+// ============================================================================+// SHARED AI AGENT INPUTS - Used by Specialized Agent Nodes+// ============================================================================++// Inputs shared by AI Agent and all Specialized Agent nodes+export const AI_AGENT_INPUTS = [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ {+ name: 'skill',+ displayName: 'Skill',+ type: 'main' as NodeConnectionType,+ description: 'Skill nodes that provide context and instructions'+ },+ {+ name: 'memory',+ displayName: 'Memory',+ type: 'main' as NodeConnectionType,+ description: 'Memory node for conversation history'+ },+ {+ name: 'tools',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Tool nodes for agent capabilities'+ },+ {+ name: 'task',+ displayName: 'Task',+ type: 'main' as NodeConnectionType,+ description: 'Task completion events from taskTrigger'+ }+];++// Outputs shared by AI Agent and all Specialized Agent nodes+export const AI_AGENT_OUTPUTS = [+ {+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Agent output'+ }+];+// ============================================================================// SHARED AI AGENT PROPERTIES - Used by Specialized Agent Nodes// ============================================================================@@ -128,38 +176,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Device Control',description: 'AI Agent specialized for Android device control. Connect skills, memory, and tool nodes to enable Android automation capabilities.',defaults: { name: 'Android Control Agent', color: dracula.green },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Tool nodes for Android device operations'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -173,38 +191,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Code Execution',description: 'AI Agent specialized for code execution. Connect skills, memory, and code executor nodes to enable coding capabilities.',defaults: { name: 'Coding Agent', color: dracula.cyan },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Code executor nodes (Python, JavaScript, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -218,38 +206,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Browser Automation',description: 'AI Agent specialized for web automation. Connect skills, memory, and web control nodes to enable browser automation and HTTP capabilities.',defaults: { name: 'Web Control Agent', color: dracula.pink },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Web control nodes (browser, scraper, HTTP, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -263,38 +221,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Task Automation',description: 'AI Agent specialized for task management. Connect skills, memory, and task nodes to enable scheduling and reminder capabilities.',defaults: { name: 'Task Management Agent', color: dracula.purple },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Task management nodes (scheduler, reminders, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -308,38 +236,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Social Messaging',description: 'AI Agent specialized for social media. Connect skills, memory, and messaging nodes to enable WhatsApp, Telegram, and other social capabilities.',defaults: { name: 'Social Media Agent', color: dracula.green },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Social media nodes (WhatsApp, Telegram, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -353,38 +251,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Travel Planning',description: 'AI Agent specialized for travel planning. Connect skills, memory, and tool nodes to enable itinerary building, location lookups, and travel recommendations.',defaults: { name: 'Travel Agent', color: dracula.orange },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Tool nodes for travel planning (maps, HTTP, search, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -398,38 +266,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Tool Orchestration',description: 'AI Agent specialized for tool orchestration. Connect skills, memory, and multiple tool nodes to enable multi-tool workflows and complex task execution.',defaults: { name: 'Tool Agent', color: dracula.yellow },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Tool nodes to orchestrate (calculators, HTTP, search, code, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -443,38 +281,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Productivity',description: 'AI Agent specialized for productivity. Connect skills, memory, and tool nodes to enable scheduling, reminders, note-taking, and workflow automation.',defaults: { name: 'Productivity Agent', color: dracula.cyan },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Tool nodes for productivity (scheduler, HTTP, code, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -488,38 +296,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Payment Processing',description: 'AI Agent specialized for payment processing. Connect skills, memory, and tool nodes to enable payment workflows, invoice generation, and financial operations.',defaults: { name: 'Payments Agent', color: dracula.green },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Tool nodes for payment processing (HTTP, code, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES},@@ -533,38 +311,8 @@ export const specializedAgentNodes: Record<string, INodeTypeDescription> = {subtitle: 'Consumer Support',description: 'AI Agent specialized for consumer interactions. Connect skills, memory, and tool nodes to enable customer support, product recommendations, and order management.',defaults: { name: 'Consumer Agent', color: dracula.purple },- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Tool nodes for consumer operations (HTTP, search, code, etc.)'- }- ],- outputs: [{- name: 'main',- displayName: 'Output',- type: 'main' as NodeConnectionType,- description: 'Agent output'- }],+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,properties: AI_AGENT_PROPERTIES}};diff --git a/client/src/nodeDefinitions/toolNodes.ts b/client/src/nodeDefinitions/toolNodes.tsindex 36e124b7..e6570971 100644--- a/client/src/nodeDefinitions/toolNodes.ts+++ b/client/src/nodeDefinitions/toolNodes.ts@@ -158,6 +158,92 @@ export const toolNodes: Record<string, INodeTypeDescription> = {description: 'Maximum number of results to return'}]+ },++ // Task Manager Tool - allows AI Agent to track and manage delegated tasks+ taskManager: {+ displayName: 'Task Manager',+ name: 'taskManager',+ icon: '📋',+ group: ['tool', 'ai'],+ version: 1,+ subtitle: 'Track Delegated Tasks',+ description: 'Manage and track delegated sub-agent tasks. Works as AI tool OR standalone workflow node.',+ defaults: { name: 'Task Manager', color: '#8B5CF6' },+ inputs: [],+ outputs: [+ {+ name: 'tool',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Connect to AI Agent tool handle'+ },+ {+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Task list output for workflow use'+ }+ ],+ properties: [+ {+ displayName: 'Tool Name',+ name: 'toolName',+ type: 'string',+ default: 'task_manager',+ description: 'Name visible to the AI agent'+ },+ {+ displayName: 'Tool Description',+ name: 'toolDescription',+ type: 'string',+ default: 'Manage delegated tasks - list active/completed tasks, check task status, mark tasks done',+ typeOptions: { rows: 2 },+ description: 'Description for the AI agent'+ },+ {+ displayName: 'Operation',+ name: 'operation',+ type: 'options',+ options: [+ { name: 'List Tasks', value: 'list_tasks' },+ { name: 'Get Task', value: 'get_task' },+ { name: 'Mark Done', value: 'mark_done' }+ ],+ default: 'list_tasks',+ description: 'Operation to perform when run as workflow node'+ },+ {+ displayName: 'Task ID',+ name: 'task_id',+ type: 'string',+ default: '',+ description: 'Task ID for get_task/mark_done operations',+ displayOptions: {+ show: {+ operation: ['get_task', 'mark_done']+ }+ }+ },+ {+ displayName: 'Status Filter',+ name: 'status_filter',+ type: 'options',+ options: [+ { name: 'All', value: '' },+ { name: 'Running', value: 'running' },+ { name: 'Completed', value: 'completed' },+ { name: 'Error', value: 'error' }+ ],+ default: '',+ description: 'Filter tasks by status',+ displayOptions: {+ show: {+ operation: ['list_tasks']+ }+ }+ }+ ]}};@@ -166,4 +252,4 @@ export const toolNodes: Record<string, INodeTypeDescription> = {// ============================================================================// List of tool node types for identification-export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'webSearchTool'];+export const TOOL_NODE_TYPES = ['calculatorTool', 'currentTimeTool', 'webSearchTool', 'taskManager'];diff --git a/client/src/nodeDefinitions/workflowNodes.ts b/client/src/nodeDefinitions/workflowNodes.tsindex 5f050a06..77cc7327 100644--- a/client/src/nodeDefinitions/workflowNodes.ts+++ b/client/src/nodeDefinitions/workflowNodes.ts@@ -35,7 +35,61 @@ export const workflowNodes: Record<string, INodeTypeDescription> = {placeholder: '{\n "message": "Hello World",\n "value": 123\n}'}]+ },++ // Task Trigger - Event-driven trigger for child agent completion+ taskTrigger: {+ displayName: 'Task Completed',+ name: 'taskTrigger',+ icon: '📨',+ group: ['trigger', 'workflow'],+ version: 1,+ subtitle: 'Child Agent Completed',+ description: 'Triggers when a delegated child agent completes its task (success or error)',+ defaults: { name: 'Task Completed', color: '#bd93f9' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'task_id, status, agent_name, result/error, parent_node_id'+ }],+ properties: [+ {+ displayName: 'Task ID Filter',+ name: 'task_id',+ type: 'string',+ default: '',+ description: 'Optional: Only trigger for specific task ID'+ },+ {+ displayName: 'Agent Name Filter',+ name: 'agent_name',+ type: 'string',+ default: '',+ description: 'Optional: Only trigger for agents containing this name'+ },+ {+ displayName: 'Status Filter',+ name: 'status_filter',+ type: 'options',+ default: 'all',+ options: [+ { name: 'All', value: 'all' },+ { name: 'Completed Only', value: 'completed' },+ { name: 'Errors Only', value: 'error' }+ ],+ description: 'Filter by completion status'+ },+ {+ displayName: 'Parent Node ID',+ name: 'parent_node_id',+ type: 'string',+ default: '',+ description: 'Optional: Only trigger for delegations from specific parent agent'+ }+ ]}};-export const WORKFLOW_NODE_TYPES = ['start'];+export const WORKFLOW_NODE_TYPES = ['start', 'taskTrigger'];diff --git a/docs-internal/agent_delegation.md b/docs-internal/agent_delegation.mdnew file mode 100644index 00000000..b6909895--- /dev/null+++ b/docs-internal/agent_delegation.md@@ -0,0 +1,703 @@+# Agent-to-Agent Delegation (Nested Agents)++How memory, parameters, and execution context flow when one AI agent delegates work to another agent connected as a tool.++## Overview++AI Agents can delegate tasks to other agents connected to their `input-tools` handle. The parent agent's LLM decides when to call the child agent by invoking a `delegate_to_<agent>` tool. The child spawns as an independent `asyncio.Task` and the parent continues working immediately -- a **fire-and-forget** pattern.++The parent passes only a `task` string and optional `context` string. Everything else -- the child's provider, model, system message, memory, skills, and tools -- comes from the child's own configuration and workflow connections.++## Architecture++```+Parent Agent (chatAgent / aiAgent / specialized)+ |+ | LLM calls: delegate_to_ai_agent(task="...", context="...")+ |+ v+tool_executor callback (closure in ai.py)+ | Injects: ai_service, database, nodes, edges, workflow_id+ |+ v+execute_tool() dispatcher (handlers/tools.py)+ | Routes agent node_types to _execute_delegated_agent()+ |+ v+_execute_delegated_agent() (handlers/tools.py)+ | 1. Fetches child_params from DATABASE+ | 2. Injects API key from credential store+ | 3. OVERWRITES prompt with delegated task+ | 4. Builds child_context with all nodes/edges+ | 5. Spawns asyncio.create_task()+ | 6. Returns immediately: {status: "delegated", task_id: "..."}+ |+ v v+Parent continues reasoning Child runs independently+(non-blocking) |+ v+ handle_ai_agent() or handle_chat_agent()+ |+ _collect_agent_connections(child_node_id)+ | Filters edges by child's ID+ | Finds child's own memory/skills/tools+ |+ execute_agent() or execute_chat_agent()+ | Uses child's provider/model/system_message+ | Uses child's memory (isolated session)+ | Uses child's skills + tools+ | Prompt = delegated task from parent+ |+ Result broadcast via WebSocket+ (NOT returned to parent LLM)+```++## The Delegation Chain (7 Steps)++### Step 1: Parent Builds Tool from Child Agent Node++**File:** `server/services/ai.py`, `_build_tool_from_node()` (line 2041)++When the parent agent starts executing and finds a child agent connected to its `input-tools` handle, `_build_tool_from_node()` is called during tool setup:++```python+for tool_info in tool_data:+ tool, config = await self._build_tool_from_node(tool_info)+ tools.append(tool)+ tool_configs[tool.name] = config+```++For agent node types, the method:++1. Looks up the tool name from `DEFAULT_TOOL_NAMES` (line 2054):+ ```python+ 'aiAgent': 'delegate_to_ai_agent',+ 'chatAgent': 'delegate_to_chat_agent',+ 'android_agent': 'delegate_to_android_agent',+ 'coding_agent': 'delegate_to_coding_agent',+ # ... all 12 agent types have entries+ ```++2. Creates a `DelegateToAgentSchema` Pydantic model (line 2622) with two fields:+ ```python+ class DelegateToAgentSchema(BaseModel):+ task: str = Field(+ description=f"The task/instruction to delegate to '{agent_label}'."+ )+ context: Optional[str] = Field(+ default=None,+ description="Additional context or data the child agent needs"+ )+ ```++3. Returns a config dict (line 2202):+ ```python+ config = {+ 'node_type': node_type, # e.g., 'aiAgent'+ 'node_id': node_id, # child's node ID+ 'parameters': node_params, # child's stored params (from tool_info)+ 'label': node_label,+ 'connected_services': []+ }+ ```++The LLM sees a tool like `delegate_to_ai_agent(task="...", context="...")`. It does NOT see or fill the child's actual configuration (provider, model, temperature, etc.).++---++### Step 2: Tool Executor Callback Injects Services++**File:** `server/services/ai.py`, `tool_executor` (line 1406) / `chat_tool_executor` (line 1835)++Both `execute_agent()` and `execute_chat_agent()` define nearly identical tool executor callbacks as closures. When the parent's LLM decides to call the delegation tool, the callback fires.++The callback captures from outer scope:++| Variable | Source | Purpose |+|----------|--------|---------|+| `tool_configs` | Built in step 1 | Maps tool name to config dict |+| `self` | AIService instance | Provides `.database`, `.auth` |+| `broadcaster` | Function parameter | WebSocket status broadcasts |+| `workflow_id` | Function parameter | Scopes broadcasts to workflow |+| `context` | Function parameter | Contains `nodes` and `edges` arrays |++Before calling `execute_tool()`, the callback injects 5 fields into the config (line 1434-1443):++```python+config['workflow_id'] = workflow_id+config['ai_service'] = self # AIService instance (shared)+config['database'] = self.database # Database instance (shared)+if context:+ config['nodes'] = context.get('nodes', []) # ALL workflow nodes+ config['edges'] = context.get('edges', []) # ALL workflow edges+```++These injected fields are what enable the child agent to discover its own connections and execute independently. Without them, the child would have no access to the workflow graph or services.++---++### Step 3: Dispatch to Delegation Handler++**File:** `server/services/handlers/tools.py`, `execute_tool()` (line 27)++The dispatcher checks `node_type` and routes all 12 agent types to `_execute_delegated_agent()` (line 120):++```python+if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent',+ 'web_agent', 'task_agent', 'social_agent', 'travel_agent',+ 'tool_agent', 'productivity_agent', 'payments_agent',+ 'consumer_agent'):+ return await _execute_delegated_agent(tool_args, config)+```++---++### Step 4: Delegated Agent Execution (Fire-and-Forget)++**File:** `server/services/handlers/tools.py`, `_execute_delegated_agent()` (line 1126)++This is where the actual parameter assembly happens.++**4a. Extract injected services from config** (line 1149-1153):+```python+ai_service = config.get('ai_service')+database = config.get('database')+nodes = config.get('nodes', [])+edges = config.get('edges', [])+workflow_id = config.get('workflow_id')+```++**4b. Fetch child's OWN parameters from database** (line 1165):+```python+child_params = await database.get_node_parameters(node_id) or {}+```++The child's stored parameters (provider, model, system message, etc.) come from the database -- whatever the user configured in the child node's parameter panel. They are NOT inherited from the parent.++**4c. Inject API key if missing** (line 1169-1175):+```python+if not child_params.get('api_key') and not child_params.get('apiKey'):+ provider = detect_ai_provider(node_type, child_params)+ key = await ai_service.auth.get_api_key(provider, "default")+ if key:+ child_params['api_key'] = key+```++The child gets its API key from the credential store based on its own provider setting. If the child is configured for Anthropic and the parent uses OpenAI, the child gets the Anthropic key.++**4d. Inject default model if not set** (line 1178-1183):+```python+if not child_params.get('model'):+ provider = detect_ai_provider(node_type, child_params)+ models = await ai_service.auth.get_stored_models(provider, "default")+ if models:+ child_params['model'] = models[0]+```++**4e. OVERWRITE prompt with delegated task** (line 1186-1189):+```python+full_prompt = task_description+if task_context:+ full_prompt = f"{task_description}\n\nContext:\n{task_context}"+child_params['prompt'] = full_prompt+```++This is the **only parameter the parent passes to the child** -- the task instruction. Everything else comes from the child's own stored configuration.++**4f. Build child execution context** (line 1192-1198):+```python+child_context = {+ 'nodes': nodes, # ALL workflow nodes (not just child's)+ 'edges': edges, # ALL workflow edges (not just child's)+ 'workflow_id': workflow_id, # Parent's workflow ID (for status scoping)+ 'outputs': {}, # Empty -- child starts fresh+ 'parent_task_id': task_id # Link back to parent's delegation task+}+```++**4g. Spawn as background task and return immediately** (line 1269-1281):+```python+task = asyncio.create_task(run_child_agent())+_delegated_tasks[task_id] = task++return {+ "success": True,+ "status": "delegated",+ "task_id": task_id,+ "agent_node_id": node_id,+ "agent_name": agent_label,+ "message": f"Task delegated to '{agent_label}'. Agent is now working independently..."+}+```++Inside `run_child_agent()` (line 1208-1267), the child handler is selected based on node_type:+- `aiAgent` -> `handle_ai_agent()` (LangGraph state machine)+- All others -> `handle_chat_agent()` (direct LLM invoke)++---++### Step 5: Child Handler Collects Its Own Connections++**File:** `server/services/handlers/ai.py`, `handle_ai_agent()` (line 225) / `handle_chat_agent()` (line 280)++The spawned child calls `_collect_agent_connections()` with **its own node_id**:++```python+memory_data, skill_data, tool_data, input_data = await _collect_agent_connections(+ node_id, # CHILD's node ID+ child_context, # Contains ALL nodes/edges+ database,+ log_prefix="[AI Agent]"+)+```++---++### Step 6: Connection Filtering by Node ID++**File:** `server/services/handlers/ai.py`, `_collect_agent_connections()` (line 14)++This function receives ALL nodes/edges but filters by the child's `node_id` (line 65-66):++```python+for edge in edges:+ if edge.get('target') != node_id: # Only edges pointing TO this child+ continue++ target_handle = edge.get('targetHandle')+ source_node_id = edge.get('source')+```++For each matching edge, it checks the target handle:++| Handle | Action |+|--------|--------|+| `input-memory` | Loads markdown memory content from child's connected `simpleMemory` node (line 77-93) |+| `input-skill` | Loads skill instructions; expands masterSkill into individual enabled skills (line 97-153) |+| `input-tools` | Discovers tool nodes; for androidTool, finds connected Android services (line 156-205) |+| `input-main` / `input-chat` | Reads upstream node output for auto-prompt fallback (line 209-213) |++The child only gets connections that are physically wired to it in the workflow graph. If the child has no memory node connected, `memory_data` is `None`. If the child has its own tools, it gets those tools -- and can delegate further.++---++### Step 7: Child Executes with Its Own Resources++**File:** `server/services/ai.py`, `execute_agent()` / `execute_chat_agent()`++The child now executes with:++| Resource | Source |+|----------|--------|+| Prompt | Delegated task from parent's LLM |+| System message | Child's own (from its DB params) |+| Provider / model | Child's own (from its DB params) |+| API key | Injected from credential store based on child's provider |+| Temperature / max tokens | Child's own (from its DB params) |+| Memory | Child's own connected simpleMemory node (if any) |+| Skills | Child's own connected skill nodes (if any) |+| Tools | Child's own connected tool nodes (if any) |++The child's result is broadcast to the UI via WebSocket but is NOT fed back into the parent's reasoning loop.++---++## Memory Isolation++Parent and child agents have completely separate memory systems:++| Aspect | Parent Agent | Child Agent |+|--------|-------------|-------------|+| Memory source | Parent's connected simpleMemory | Child's connected simpleMemory |+| Session ID | From parent's memory node params | From child's memory node params |+| Memory content | Parent's conversation markdown | Child's conversation markdown |+| Vector store | `_memory_vector_stores[parent_session]` | `_memory_vector_stores[child_session]` |+| Memory updates | Parent appends its own exchanges | Child appends its own exchanges |+| Shared? | **No** -- completely isolated | **No** -- completely isolated |++If the child has **no memory node connected**, it has no conversation history and executes statelessly with just the delegated task prompt.++---++## Parameter Flow Summary++### What the parent passes to the child++| Parameter | How it arrives |+|-----------|---------------|+| `task` (string) | Parent's LLM generates it via `DelegateToAgentSchema` tool call |+| `context` (optional string) | Parent's LLM generates it via `DelegateToAgentSchema` tool call |+| `workflow_id` | Injected by tool_executor callback from parent's execution context |+| `nodes` / `edges` | Injected by tool_executor callback -- ALL workflow nodes and edges |+| `ai_service` / `database` | Injected by tool_executor callback -- shared instances (by reference) |++### What the child gets from its own config++| Parameter | Source |+|-----------|--------|+| `provider` | Child's DB params (e.g., `'openai'`, `'anthropic'`) |+| `model` | Child's DB params (e.g., `'gpt-4o'`), or first stored model as fallback |+| `systemMessage` | Child's DB params |+| `temperature` | Child's DB params |+| `max_tokens` / `maxTokens` | Child's DB params |+| `thinkingEnabled` / `thinkingBudget` | Child's DB params |+| `api_key` | Credential store, resolved by child's own provider |+| Memory | Child's own connected simpleMemory node |+| Skills | Child's own connected skill nodes |+| Tools | Child's own connected tool nodes |++### What the parent does NOT pass++- Provider, model, temperature, max tokens, system message+- Memory or conversation history+- Skills or skill instructions+- Tool configurations+- API keys++---++## What the Parent Receives Back++### Immediate Response (Fire-and-Forget)++The parent LLM receives this immediate response from the tool call:++```json+{+ "success": true,+ "status": "delegated",+ "task_id": "delegated_node123_a1b2c3d4",+ "agent_node_id": "child_agent_node_123",+ "agent_name": "Research Agent",+ "message": "Task delegated to 'Research Agent'. Agent is now working independently..."+}+```++The parent does NOT wait for the child's result. The child's output is broadcast to the UI via WebSocket (`broadcaster.update_node_status`).++### Result Retrieval (check_delegated_tasks Tool)++When a parent agent has delegation tools, a `check_delegated_tasks` tool is automatically injected. The parent LLM can call this tool to check on child status and retrieve results:++```python+# LLM calls:+check_delegated_tasks(task_ids=["delegated_abc123"])++# Returns:+{+ "total_tasks": 1,+ "completed": 1,+ "running": 0,+ "errors": 0,+ "tasks": [{+ "task_id": "delegated_abc123",+ "status": "completed",+ "agent_name": "Research Agent",+ "result": "The research findings show..."+ }]+}+```++### 3-Layer Result Storage (Celery AsyncResult / Ray ObjectRef Pattern)++Results are stored in a 3-layer hierarchy for fast access and durability:++| Layer | Storage | Survives Restart | Access Speed |+|-------|---------|------------------|--------------|+| 1 | `asyncio.Task` in `_delegated_tasks` | No | O(1), task.result() |+| 2 | `_delegation_results` dict | No | O(1), dict lookup |+| 3 | `NodeOutput` SQLite table | Yes | DB query |++**Layer 1**: Live tasks are tracked in `_delegated_tasks`. When a task completes, `task.result()` extracts the return value.++**Layer 2**: Results are cached in `_delegation_results` dict immediately after child completion/error. This survives the task cleanup in the `finally` block.++**Layer 3**: Results are persisted to the existing `NodeOutput` table with `session_id="delegation_{task_id}"`. This survives server restarts indefinitely.++```python+# On child completion:+_delegation_results[task_id] = {+ "task_id": task_id,+ "status": "completed",+ "agent_name": agent_label,+ "result": result.get('result', {}).get('response', ...),+}++# Persist to NodeOutput table+await database.save_node_output(+ node_id=node_id,+ session_id=f"delegation_{task_id}",+ output_name="delegation_result",+ data={...}+)+```++### Auto-Injection Logic++The `check_delegated_tasks` tool is only injected when the parent has delegation tools:++```python+# In execute_agent() and execute_chat_agent():+if any(name.startswith('delegate_to_') for name in tool_configs):+ check_info = {+ 'node_type': '_builtin_check_delegated_tasks',+ 'node_id': f'{node_id}_check_tasks',+ 'parameters': {},+ 'label': 'Check Delegated Tasks',+ }+ check_tool, check_config = await self._build_tool_from_node(check_info)+ if check_tool:+ tools.append(check_tool)+ tool_configs[check_tool.name] = check_config+```++---++## Recursive Delegation++If the child agent has other agents connected to its own `input-tools` handle, it can delegate further. Each level follows the same pattern:++1. Child's `_build_tool_from_node()` creates a `DelegateToAgentSchema` tool for the grandchild+2. Child's `tool_executor` callback injects services and the same `nodes`/`edges` graph+3. Grandchild spawns as its own `asyncio.create_task()`+4. Grandchild collects its own connections by filtering edges with its own `node_id`++There is no hard recursion limit. Each agent in the chain is memory-isolated and independently configured.++---++## Status Broadcasting++Every delegated agent broadcasts status at key phases via WebSocket:++| Phase | When | Broadcast to |+|-------|------|-------------|+| `delegated_task` | Child starts executing | Child's node ID |+| `initializing` | Creating LLM model | Child's node ID |+| `loading_memory` | Parsing markdown history | Child's node ID |+| `building_tools` | Converting tool nodes to StructuredTool | Child's node ID |+| `invoking_llm` | Calling model | Child's node ID |+| `executing_tool` | Running a tool called by child's LLM | Tool node ID |+| `delegated_complete` | Child finishes successfully | Child's node ID |+| `delegated_error` | Child fails | Child's node ID |++All broadcasts include `workflow_id` for UI scoping. The frontend uses these to show real-time execution animations on the child agent node.++---++## Key Files++| File | Role |+|------|------|+| `server/services/ai.py` | `_build_tool_from_node()`, `_get_tool_schema()`, `DelegateToAgentSchema`, `tool_executor` callback, `DEFAULT_TOOL_NAMES/DESCRIPTIONS` |+| `server/services/handlers/ai.py` | `_collect_agent_connections()`, `handle_ai_agent()`, `handle_chat_agent()` |+| `server/services/handlers/tools.py` | `execute_tool()` dispatcher, `_execute_delegated_agent()`, `_delegated_tasks` tracking |+| `server/constants.py` | `AI_AGENT_TYPES` frozenset, `detect_ai_provider()` |+| `client/src/components/AIAgentNode.tsx` | Frontend rendering of execution phase animations |+| `client/src/nodeDefinitions/specializedAgentNodes.ts` | Agent node definitions with `AI_AGENT_PROPERTIES` |++---++## Key Findings++1. **Only task/context strings flow from parent to child.** No other parameters (model, temperature, memory, skills) are inherited.++2. **Child configuration comes from its own database params.** Whatever the user set in the child's parameter panel is what the child uses.++3. **Memory is fully isolated.** Parent and child have separate simpleMemory nodes with separate session IDs and separate vector stores.++4. **The child sees the full workflow graph** via `nodes`/`edges`, but `_collect_agent_connections()` filters by the child's own `node_id`, so it only gets resources physically connected to it.++5. **Services are shared, not duplicated.** `ai_service` and `database` are passed by reference. They share the same credential store and DB connection.++6. **Delegation is non-blocking.** `asyncio.create_task()` spawns the child; the parent continues immediately. The child's result is NOT returned to the parent's LLM.++7. **Recursive delegation is supported.** If the child has agents connected to its own `input-tools`, it can delegate further with no hard depth limit.++8. **Task Trigger enables workflow-based result handling.** The `taskTrigger` node fires when delegated tasks complete, allowing workflows to process child agent results.++---++## Event-Driven Task Completion (taskTrigger)++In addition to the `check_delegated_tasks` tool (LLM-driven result checking), the system provides an event-driven approach via the `taskTrigger` workflow node. This enables parent workflows to react to child completion without polling.++### Architecture++```+Child Agent completes (success or error)+ ↓+tools.py: _execute_delegated_agent.run_child_agent()+ ↓+broadcaster.send_custom_event('task_completed', event_data)+ ↓+event_waiter.dispatch_async('task_completed', event_data)+ ↓+Matching taskTrigger nodes resolve their Futures+ ↓+Downstream workflow nodes execute with delegation result+```++### Event Data Schema++The `task_completed` event carries:++```python+{+ 'task_id': str, # e.g., "delegated_abc123_xyz"+ 'status': str, # 'completed' or 'error'+ 'agent_name': str, # Label of child agent+ 'agent_node_id': str, # Node ID of child agent+ 'parent_node_id': str, # Node ID of parent that delegated+ 'result': str, # Response text (if completed)+ 'error': str, # Error message (if error)+ 'workflow_id': str, # For scoping+}+```++### Filter Options++The `taskTrigger` node supports filtering to match specific delegation events:++| Filter | Description |+|--------|-------------|+| `task_id` | Exact match on specific task ID |+| `agent_name` | Partial match on child agent name |+| `status_filter` | `all`, `completed`, or `error` |+| `parent_node_id` | Only trigger for delegations from specific parent |++### Usage Example++```+[Parent Agent] --delegates--> [Research Agent]+ ↓ (completes)+ [task_completed event]+ ↓+ [Task Trigger]+ (filters: agent_name="Research")+ ↓+ [Process Results Node]+ (uses {{taskTrigger.result}})+```++### Key Files++| File | Changes |+|------|---------|+| `server/services/event_waiter.py` | TriggerConfig, filter builder, FILTER_BUILDERS entry |+| `server/services/handlers/tools.py` | `send_custom_event()` calls (success + error paths) |+| `server/constants.py` | `taskTrigger` in EVENT_TRIGGER_TYPES, WORKFLOW_TRIGGER_TYPES |+| `client/src/nodeDefinitions/workflowNodes.ts` | Node definition |+| `client/src/components/parameterPanel/InputSection.tsx` | Output schema for draggable variables |++### LLM-Driven vs Event-Driven vs Agent-Handled++| Approach | Tool/Handle | When to Use |+|----------|-------------|-------------|+| **LLM-Driven** | `check_delegated_tasks` | Parent LLM decides when to check results and how to process them |+| **Event-Driven** | `taskTrigger` | Workflow automatically reacts to completion, processes via downstream nodes |+| **Agent-Handled** | `input-task` handle | Parent agent receives task result and reports to user conversationally |++All approaches can coexist. The LLM-driven approach is better for dynamic reasoning about results; the event-driven approach is better for deterministic post-processing workflows; the agent-handled approach is best when you want the parent agent to interpret and communicate results naturally.++---++## Agent Task Input Handle (input-task)++All AI agents (aiAgent, chatAgent, and 10 specialized agents) have an `input-task` handle on the left side that can receive task completion events from `taskTrigger` nodes. This enables a conversational pattern where the parent agent reports delegated task results to the user.++### Architecture++```+[Child Agent] completes+ ↓+[taskTrigger] fires (filters by agent_name/status)+ ↓+[Parent Agent] (input-task handle)+ ↓+Agent generates conversational response about completed task+```++### How It Works++1. **Backend Detection**: `_collect_agent_connections()` in `handlers/ai.py` detects nodes connected to `input-task` handle+2. **Task Data Collection**: Collects output from connected `taskTrigger` node+3. **Context Injection**: `_format_task_context()` formats task data as prompt context+4. **Prompt Prepending**: Task context is prepended to the agent's prompt before execution++### Task Context Format++When a task completes successfully:+```+A delegated task has completed:+- Agent: Research Agent+- Task ID: delegated_abc123_xyz+- Status: Completed Successfully+- Result: [child agent's response]++Please report this result to the user in a conversational way.+```++When a task fails:+```+A delegated task has failed:+- Agent: Research Agent+- Task ID: delegated_abc123_xyz+- Status: Error+- Error: [error message]++Please report this error to the user and suggest next steps if appropriate.+```++### Key Files++| File | Changes |+|------|---------|+| `client/src/components/AIAgentNode.tsx` | `input-task` handle in leftHandles for all 12 agent configs |+| `client/src/nodeDefinitions/aiAgentNodes.ts` | Task input in aiAgent and chatAgent inputs arrays |+| `client/src/nodeDefinitions/specializedAgentNodes.ts` | `AI_AGENT_INPUTS` constant with task input |+| `server/services/handlers/ai.py` | `task_data` collection, `_format_task_context()`, prompt injection |++### Usage Example++```+[Parent Agent] ──delegates──> [Research Agent]+ ↓ (completes)+ [Task Trigger]+ (filters: agent_name="Research")+ ↓+ [Chat Agent]+ (input-task handle)+ ↓+ Generates response:+ "The research task has completed!+ Here's what was found: ..."+```++### Shared Input/Output Constants++Specialized agents use shared constants for consistency:++```typescript+// In specializedAgentNodes.ts+export const AI_AGENT_INPUTS = [+ { name: 'main', displayName: 'Input', ... },+ { name: 'skill', displayName: 'Skill', ... },+ { name: 'memory', displayName: 'Memory', ... },+ { name: 'tools', displayName: 'Tool', ... },+ { name: 'task', displayName: 'Task', ... }, // Task completion events+];++export const AI_AGENT_OUTPUTS = [+ { name: 'main', displayName: 'Output', ... },+];+```++All 10 specialized agents reference these constants:+```typescript+android_agent: {+ inputs: AI_AGENT_INPUTS,+ outputs: AI_AGENT_OUTPUTS,+ properties: AI_AGENT_PROPERTIES+}+```diff --git a/docs-internal/ci_cd.md b/docs-internal/ci_cd.mdnew file mode 100644index 00000000..c4a017d1--- /dev/null+++ b/docs-internal/ci_cd.md@@ -0,0 +1,328 @@+# CI/CD Pipeline++Internal reference for the GitHub Actions CI/CD pipeline. Covers all workflows, the shared composite action, predeploy validation, release publishing, and documentation deployment.++---++## Overview++```+ +------------------++ push to main ---------> | ci.yml |---++ PR to main -----------> | | |+ +------------------+ |+ | +--------------------++ PR to main (Dockerfile +------------------+ +--> | predeploy.yml |+ or compose changes) --> | docker-build.yml |---+--> | (reusable) |+ +------------------+ | | |+ | | - build-and-lint |+ v*.*.* tag push ------> +------------------+ | | - docker-build |+ GitHub release -------> | release.yml |---+ | - docker-compose |+ manual dispatch ------> | | | - test-install |+ | +-- predeploy --+ +--------------------++ | |+ | +-- publish-npm ---------> npmjs.org (machinaos)+ | +-- publish-github-pkgs -> GitHub Packages (@trohitg/machinaos)+ +------------------+++ push to docs-MachinaOs/ +------------------++ manual dispatch ------> | docs.yml |-------> Mintlify (docs site)+ +------------------++```++### Workflow Summary++| Workflow | File | Triggers | Purpose |+|----------|------|----------|---------|+| CI | `.github/workflows/ci.yml` | Push to main, PRs to main | Validate every code change via predeploy |+| Docker Build | `.github/workflows/docker-build.yml` | PRs to main (Dockerfile/compose changes) | Validate Docker-specific changes via predeploy |+| Release | `.github/workflows/release.yml` | `v*.*.*` tags, GitHub releases, manual | Predeploy gate then publish to npm + GitHub Packages |+| Deploy Docs | `.github/workflows/docs.yml` | Push to `docs-MachinaOs/**` on main, manual | Deploy Mintlify documentation |+| Predeploy | `.github/workflows/predeploy.yml` | Called by other workflows (`workflow_call`) | Reusable validation: build, lint, Docker, cross-platform install |+| Setup Action | `.github/actions/setup/action.yml` | Used as composite action step | Shared Node.js + Python + uv environment setup |++### Required Secrets++| Secret | Used By | Description |+|--------|---------|-------------|+| `NPM_TOKEN` | release.yml | npm registry authentication for publishing |+| `GITHUB_TOKEN` | release.yml | GitHub Packages authentication (auto-provided by Actions) |+| `MINTLIFY_TOKEN` | docs.yml | Mintlify documentation deployment token |++---++## Composite Setup Action++**File:** `.github/actions/setup/action.yml`++Shared environment setup used by `predeploy.yml` jobs. Eliminates duplicated Node/Python/uv installation across workflows.++```yaml+# Usage in workflow steps:+- uses: ./.github/actions/setup+- uses: ./.github/actions/setup+ with:+ node-version: '22'+```++### What It Installs++| Tool | Default Version | Action Used |+|------|----------------|-------------|+| Node.js | 20 | `actions/setup-node@v4` (with npm cache) |+| Python | 3.12 | `actions/setup-python@v5` |+| uv | latest | `astral-sh/setup-uv@v4` |++### Inputs++| Input | Default | Description |+|-------|---------|-------------|+| `node-version` | `'20'` | Node.js version to install |+| `python-version` | `'3.12'` | Python version to install |++Python and uv are needed because `postinstall.js` skips Python venv setup in CI, so they must be available for the `machinaos build` command in `test-install`.++---++## Predeploy Validation++**File:** `.github/workflows/predeploy.yml`++The core reusable workflow. Triggered via `workflow_call` by `ci.yml`, `docker-build.yml`, and `release.yml`. Contains 4 jobs -- `build-and-lint`, `docker-build`, and `test-install` run in parallel; `docker-compose-test` depends on `docker-build`.++### Job: build-and-lint++Validates that the full project builds and the client passes linting.++| Step | Command | Description |+|------|---------|-------------|+| Checkout | `actions/checkout@v4` | Clone repo |+| Setup environment | `./.github/actions/setup` | Install Node.js 20, Python 3.12, uv |+| Build all services | `npm run build` | Full production build |+| Lint client | `cd client && npm run lint` | ESLint/TypeScript validation |++### Job: docker-build++Validates all 3 Docker images build successfully. Uses Docker Buildx with GitHub Actions cache for layer reuse.++| Image | Context | Dockerfile | Notes |+|-------|---------|------------|-------|+| Frontend | `./client` | `./client/Dockerfile` | Multi-stage build, `target: production` |+| Backend | `./server` | `./server/Dockerfile` | Python 3.12-slim |+| WhatsApp | `./docker` | `./docker/Dockerfile.whatsapp` | Node.js 20-alpine with whatsapp-rpc |++All builds use:+- `docker/setup-buildx-action@v3`+- `docker/build-push-action@v6`+- `push: false` (validation only, no registry push)+- `cache-from: type=gha` / `cache-to: type=gha,mode=max` (GitHub Actions layer cache)++### Job: docker-compose-test++**Depends on:** `docker-build`++Full-stack smoke test using the production Docker Compose configuration.++**Steps:**+1. Create `.env` from `.env.template`+2. Build with `docker compose -f docker-compose.prod.yml build`+3. Start services with `docker compose -f docker-compose.prod.yml up -d`+4. Health check loop (30 retries, 2s interval = 60s max):+ - Backend: `curl -sf http://localhost:3010/health`+ - Frontend: `curl -f http://localhost:3000`+ - Print `docker compose ps` on success+5. On failure: dump all container logs+6. Always: `docker compose -f docker-compose.prod.yml down -v` (cleanup)++### Job: test-install++Cross-platform npm package installation and CLI validation.++**Matrix:**++| Axis | Values |+|------|--------|+| OS | `ubuntu-latest`, `macos-latest`, `windows-latest` |+| Node.js | 20, 22 |++Total: **6 combinations**, `fail-fast: false` (all run regardless of individual failures).++**Steps:**+1. Checkout+2. Setup environment (composite action with matrix `node-version`)+3. `npm pack` -- create tarball+4. `npm install -g machinaos-*.tgz` -- global install from tarball+5. `machinaos --help` -- verify CLI is available+6. `machinaos build` -- install client deps, build client, setup Python venv+7. Verify build artifacts exist at `$(npm root -g)/machinaos`:+ - `.env` file+ - `client/dist/` directory+ - `server/.venv/` directory+8. `machinaos start &` -- start in background, wait 10s, verify process is still running++All steps use `shell: bash` for cross-platform compatibility (Windows uses Git Bash).++---++## CI Workflow++**File:** `.github/workflows/ci.yml`++Thin wrapper that delegates all validation to `predeploy.yml`.++```yaml+on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++jobs:+ predeploy:+ uses: ./.github/workflows/predeploy.yml+```++Every push to main and every PR targeting main runs the full predeploy suite (build, lint, Docker, cross-platform install).++---++## Docker Build Workflow++**File:** `.github/workflows/docker-build.yml`++Scoped validation for Docker-related changes. Only triggers when specific files are modified in a PR.++```yaml+on:+ pull_request:+ branches: [main]+ paths:+ - 'client/Dockerfile'+ - 'server/Dockerfile'+ - 'docker/Dockerfile.whatsapp'+ - 'docker-compose*.yml'+```++Delegates to `predeploy.yml`. Dockerfile changes in PRs get validated by both `ci.yml` (always runs on PRs) and `docker-build.yml` (path-scoped). The reusable workflow pattern and GHA caching make this overlap low-cost.++---++## Release Workflow++**File:** `.github/workflows/release.yml`++Publishes the npm package after predeploy validation passes.++### Triggers++| Trigger | Condition |+|---------|-----------|+| Push tags | `v*.*.*` (e.g., `v1.0.0`, `v2.3.1`) |+| Release | GitHub release published |+| Manual | `workflow_dispatch` |++### Job: predeploy (gate)++Calls `predeploy.yml` as a prerequisite. Both publish jobs require this to pass (`needs: predeploy`).++### Job: publish-npm++Publishes the unscoped `machinaos` package to the public npm registry.++```+npm install --ignore-scripts # Install deps without running postinstall+npm pack --dry-run # Verify package contents+npm publish --access public # Publish to npmjs.org+```++Uses `NODE_AUTH_TOKEN` from `secrets.NPM_TOKEN`. Registry URL: `https://registry.npmjs.org`.++### Job: publish-github-packages++Publishes the scoped `@trohitg/machinaos` package to GitHub Packages.++Requires `packages: write` permission. Before publishing, an inline Node.js script rewrites `package.json`:++```javascript+// Executed at build time to scope the package name:+const pkg = require('./package.json');+pkg.name = '@trohitg/machinaos';+pkg.publishConfig = { registry: 'https://npm.pkg.github.com' };+require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));+```++Then publishes via `npm publish` with `GITHUB_TOKEN` as auth token. Registry URL: `https://npm.pkg.github.com`.++---++## Docs Workflow++**File:** `.github/workflows/docs.yml`++Deploys the Mintlify documentation site when docs change.++### Triggers++| Trigger | Condition |+|---------|-----------|+| Push | Changes to `docs-MachinaOs/**` on main branch |+| Manual | `workflow_dispatch` |++### Steps++1. Checkout repo+2. Setup Node.js 20+3. `npm install -g mintlify` -- install Mintlify CLI+4. `mintlify deploy` -- deploy docs (working directory: `docs-MachinaOs`)++Uses `MINTLIFY_TOKEN` secret for authentication.++---++## Workflow Dependency Graph++```++------------------+ +---------------------++| ci.yml |------->| |+| (push/PR main) | | predeploy.yml |++------------------+ | (workflow_call) |+ | |++------------------+ | +-- build-and-lint |+| docker-build.yml |------->| +-- docker-build |+| (PR, Dockerfiles)| | +-- compose-test |++------------------+ | +-- test-install |+ | |++------------------+ +---------------------++| release.yml |------->| |+| (tags, releases) | | v++------------------+ | +-- publish-npm+ | +-- publish-github-packages+ +---------------------++++------------------++| docs.yml |------> Mintlify deployment+| (docs-MachinaOs/)| (independent pipeline)++------------------++```++### Key Design Decisions++- **Reusable `predeploy.yml`**: Single source of truth for validation logic. All entry-point workflows delegate to it, avoiding duplication.+- **Composite setup action**: Node.js, Python, and uv installation centralized in `.github/actions/setup/action.yml`. Workflows pass version overrides as inputs.+- **`fail-fast: false` in test-install**: All 6 OS/Node combinations run to completion, giving visibility into platform-specific failures even when one platform fails.+- **Docker layer caching via GHA**: `cache-from: type=gha` reuses layers across runs, reducing Docker build times.+- **Scoped `docker-build.yml`**: Prevents full Docker rebuild on every PR -- only triggers when Dockerfile or compose files change.+- **Dual npm publish**: Unscoped `machinaos` for public npm, scoped `@trohitg/machinaos` for GitHub Packages. The scoped name is rewritten at publish time, not in source.++---++## Source Files++| File | Lines | Description |+|------|-------|-------------|+| `.github/workflows/ci.yml` | 15 | CI entry point, delegates to predeploy |+| `.github/workflows/predeploy.yml` | 157 | Reusable validation (build, lint, Docker, install) |+| `.github/workflows/release.yml` | 73 | Predeploy gate + dual npm publish |+| `.github/workflows/docker-build.yml` | 18 | Docker-scoped PR validation |+| `.github/workflows/docs.yml` | 33 | Mintlify documentation deployment |+| `.github/actions/setup/action.yml` | 37 | Composite action: Node.js + Python + uv |diff --git a/docs-internal/claude_code_agent_architecture.md b/docs-internal/claude_code_agent_architecture.mdnew file mode 100644index 00000000..ff996ed6--- /dev/null+++ b/docs-internal/claude_code_agent_architecture.md@@ -0,0 +1,1257 @@+# Claude Code Agent Architecture++## Table of Contents+1. [Memory & Context Compaction Architecture](#1-memory--context-compaction-architecture)+2. [Sub-Agent Creation & Handling](#2-sub-agent-creation--handling)+3. [Execution Flow Diagrams](#3-execution-flow-diagrams)+4. [Data Structures Reference](#4-data-structures-reference)++---++# 1. Memory & Context Compaction Architecture++## 1.1 Overview Diagram++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ CONTEXT WINDOW MANAGEMENT │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Message │ │ Message │ │ Message │ │+│ │ History │───▶│ Counter │───▶│ Compaction │ │+│ │ Buffer │ │ (Tokens) │ │ Decision │ │+│ └──────────────┘ └──────────────┘ └──────┬───────┘ │+│ │ │+│ ┌────────────────────┴────────────────────┐ │+│ │ │ │+│ ▼ ▼ │+│ ┌──────────────────┐ ┌────────────┐ │+│ │ BELOW THRESHOLD │ │ ABOVE │ │+│ │ (< 100K tokens)│ │ THRESHOLD │ │+│ └────────┬─────────┘ └─────┬──────┘ │+│ │ │ │+│ ▼ ▼ │+│ ┌──────────────────┐ ┌───────────────────┐ │+│ │ Continue │ │ COMPACTION │ │+│ │ Normal │ │ PIPELINE │ │+│ │ Execution │ │ │ │+│ └──────────────────┘ └───────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 1.2 Token Counting Algorithm++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ TOKEN COUNTING FORMULA │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ total_tokens = input_tokens │+│ + cache_creation_input_tokens (or 0) │+│ + cache_read_input_tokens (or 0) │+│ + output_tokens │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ TOKEN SOURCES │ │+│ ├─────────────────────┬───────────────────────────────────────────────┤ │+│ │ input_tokens │ Tokens in all messages sent to model │ │+│ │ cache_creation │ Tokens written to prompt cache (first time) │ │+│ │ cache_read │ Tokens read from prompt cache (subsequent) │ │+│ │ output_tokens │ Tokens in model's response │ │+│ └─────────────────────┴───────────────────────────────────────────────┘ │+│ │+│ DEFAULT_THRESHOLD = 100,000 tokens │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 1.3 Compaction Pipeline (Detailed)++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ COMPACTION PIPELINE │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ STEP 1: CHECK THRESHOLD │+│ ════════════════════════ │+│ │+│ if compaction_control is None or not enabled: │+│ return False ──────────────────────────────▶ [SKIP COMPACTION] │+│ │+│ total_tokens = calculate_tokens(last_message) │+│ threshold = config.get("context_token_threshold", 100_000) │+│ │+│ if total_tokens < threshold: │+│ return False ──────────────────────────────▶ [SKIP COMPACTION] │+│ │+│ │ │+│ ▼ │+│ STEP 2: PREPARE MESSAGES │+│ ═════════════════════════ │+│ │+│ messages = copy(current_messages) │+│ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ CRITICAL: Remove tool_use blocks from last assistant message │ │+│ │ │ │+│ │ WHY? tool_use requires tool_result, which we don't have yet │ │+│ │ This prevents API 400 validation errors │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │+│ if messages[-1]["role"] == "assistant": │+│ non_tool_blocks = [b for b in content if b.type != "tool_use"] │+│ if non_tool_blocks: │+│ messages[-1]["content"] = non_tool_blocks │+│ else: │+│ messages.pop() # Remove entire message if only tool_use │+│ │+│ │ │+│ ▼ │+│ STEP 3: APPEND SUMMARY PROMPT │+│ ══════════════════════════════ │+│ │+│ messages.append({ │+│ "role": "user", │+│ "content": SUMMARY_PROMPT # See Section 1.4 │+│ }) │+│ │+│ │ │+│ ▼ │+│ STEP 4: CALL MODEL FOR SUMMARY │+│ ══════════════════════════════ │+│ │+│ response = client.beta.messages.create( │+│ model = config.get("model", current_model), │+│ messages = messages, │+│ max_tokens = params["max_tokens"], │+│ extra_headers = {"X-Stainless-Helper": "compaction"} │+│ ) │+│ │+│ │ │+│ ▼ │+│ STEP 5: REPLACE MESSAGE HISTORY │+│ ════════════════════════════════ │+│ │+│ summary_text = response.content[0].text │+│ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ ENTIRE HISTORY REPLACED WITH SINGLE MESSAGE │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │+│ self.set_messages_params({ │+│ "messages": [{ │+│ "role": "user", │+│ "content": [{"type": "text", "text": summary_text}] │+│ }] │+│ }) │+│ │+│ return True ───────────────────────────────────▶ [COMPACTION DONE] │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 1.4 Summary Prompt Structure++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ DEFAULT SUMMARY PROMPT │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ "You have been working on the task described above but have not yet │+│ completed it. Write a continuation summary that will allow you (or │+│ another instance of yourself) to resume work efficiently in a future │+│ context window where the conversation history will be replaced with │+│ this summary. │+│ │+│ Your summary should be structured, concise, and actionable. Include: │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ 1. TASK OVERVIEW │ │+│ │ • The user's core request and success criteria │ │+│ │ • Any clarifications or constraints they specified │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ 2. CURRENT STATE │ │+│ │ • What has been completed so far │ │+│ │ • Files created, modified, or analyzed (with paths if relevant) │ │+│ │ • Key outputs or artifacts produced │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ 3. IMPORTANT DISCOVERIES │ │+│ │ • Technical constraints or requirements uncovered │ │+│ │ • Decisions made and their rationale │ │+│ │ • Errors encountered and how they were resolved │ │+│ │ • What approaches were tried that didn't work (and why) │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ 4. NEXT STEPS │ │+│ │ • Specific actions needed to complete the task │ │+│ │ • Any blockers or open questions to resolve │ │+│ │ • Priority order if multiple steps remain │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ 5. CONTEXT TO PRESERVE │ │+│ │ • User preferences or style requirements │ │+│ │ • Domain-specific details that aren't obvious │ │+│ │ • Any promises made to the user │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ Be concise but complete—err on the side of including information that │+│ would prevent duplicate work or repeated mistakes. │+│ │+│ Wrap your summary in <summary></summary> tags." │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 1.5 Tool Runner Main Loop with Compaction++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ TOOL RUNNER EXECUTION LOOP │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────┐ │+│ │ START │ │+│ └──────┬──────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────┐ │+│ ┌───────▶│ Check: should_stop()? │ │+│ │ │ (max_iterations check) │ │+│ │ └───────────┬─────────────┘ │+│ │ │ │+│ │ ┌──────────┴──────────┐ │+│ │ │ │ │+│ │ ▼ NO ▼ YES │+│ │ ┌──────────────┐ ┌──────────────┐ │+│ │ │ Make API │ │ EXIT │ │+│ │ │ Request │ │ LOOP │ │+│ │ └──────┬───────┘ └──────────────┘ │+│ │ │ │+│ │ ▼ │+│ │ ┌──────────────────────┐ │+│ │ │ yield message │ ◀─── Emit to caller │+│ │ │ iteration_count++ │ │+│ │ └──────────┬───────────┘ │+│ │ │ │+│ │ ▼ │+│ │ ┌──────────────────────────────┐ │+│ │ │ _check_and_compact() │ │+│ │ │ │ │+│ │ │ Compaction performed? │ │+│ │ └──────────────┬───────────────┘ │+│ │ │ │+│ │ ┌──────────┴──────────┐ │+│ │ │ │ │+│ │ ▼ YES ▼ NO │+│ │ ┌───────────┐ ┌────────────────────────┐ │+│ │ │ SKIP tool │ │ generate_tool_call_ │ │+│ │ │ generation│ │ response() │ │+│ │ │ │ └───────────┬────────────┘ │+│ │ │ │ │ │+│ │ │ │ ┌──────────┴──────────┐ │+│ │ │ │ │ │ │+│ │ │ │ ▼ None ▼ Response │+│ │ │ │ ┌────────────┐ ┌───────────────────┐ │+│ │ │ │ │ No tool │ │ append_messages() │ │+│ │ │ │ │ calls │ │ (message + tool │ │+│ │ │ │ │ EXIT LOOP │ │ results) │ │+│ │ │ │ └────────────┘ └─────────┬─────────┘ │+│ │ │ │ │ │+│ │ └─────┬─────┘ │ │+│ │ │ │ │+│ │ └───────────────┬───────────────────┘ │+│ │ │ │+│ │ ▼ │+│ │ ┌──────────────────────┐ │+│ │ │ Reset flags: │ │+│ │ │ • _messages_modified │ │+│ │ │ • _cached_response │ │+│ │ └──────────┬───────────┘ │+│ │ │ │+│ └────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 1.6 Memory Tool Operations++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ MEMORY TOOL COMMAND DISPATCH │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────────┐ │+│ │ Tool Input │ │+│ │ (command obj) │ │+│ └────────┬────────┘ │+│ │ │+│ ▼ │+│ ┌───────────────────────────────────────┐ │+│ │ command.command == ? │ │+│ └───────────────────┬───────────────────┘ │+│ │ │+│ ┌────────┬────────┬─────────┼─────────┬────────┬────────┐ │+│ ▼ ▼ ▼ ▼ ▼ ▼ ▼ │+│ ┌──────┐┌──────┐┌─────────┐┌──────┐┌──────┐┌──────┐┌───────────┐ │+│ │"view"││"crea-││"str_ ││"inse-││"dele-││"rena-││ unknown │ │+│ │ ││ te" ││replace" ││ rt" ││ te" ││ me" ││ │ │+│ └──┬───┘└──┬───┘└────┬────┘└──┬───┘└──┬───┘└──┬───┘└─────┬─────┘ │+│ │ │ │ │ │ │ │ │+│ ▼ ▼ ▼ ▼ ▼ ▼ ▼ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ ABSTRACT METHODS │ │+│ │ (Must be implemented by subclass) │ │+│ ├──────────────────────────────────────────────────────────────────┤ │+│ │ │ │+│ │ view(command) │ View contents at memory path │ │+│ │ │ Returns: file content or directory list │ │+│ │ ─────────────────────┼──────────────────────────────────────────│ │+│ │ create(command) │ Create new memory file │ │+│ │ │ Params: path, file_text │ │+│ │ ─────────────────────┼──────────────────────────────────────────│ │+│ │ str_replace(command) │ Replace text in memory file │ │+│ │ │ Params: path, old_str, new_str │ │+│ │ ─────────────────────┼──────────────────────────────────────────│ │+│ │ insert(command) │ Insert text at line number │ │+│ │ │ Params: path, insert_line, new_str │ │+│ │ ─────────────────────┼──────────────────────────────────────────│ │+│ │ delete(command) │ Delete memory file or directory │ │+│ │ │ Params: path │ │+│ │ ─────────────────────┼──────────────────────────────────────────│ │+│ │ rename(command) │ Rename/move memory file or directory │ │+│ │ │ Params: old_path, new_path │ │+│ │ │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌──────────────────────────────────────────────────────────────────┐ │+│ │ IMPLEMENTATION EXAMPLE (Custom Backend) │ │+│ ├──────────────────────────────────────────────────────────────────┤ │+│ │ │ │+│ │ class DatabaseMemoryTool(BetaAbstractMemoryTool): │ │+│ │ def __init__(self, db_connection): │ │+│ │ self.db = db_connection │ │+│ │ │ │+│ │ def view(self, command): │ │+│ │ path = command.path │ │+│ │ return self.db.query(f"SELECT content FROM memory │ │+│ │ WHERE path = ?", path) │ │+│ │ │ │+│ │ def create(self, command): │ │+│ │ self.db.execute(f"INSERT INTO memory (path, content) │ │+│ │ VALUES (?, ?)", │ │+│ │ command.path, command.file_text) │ │+│ │ return "Created successfully" │ │+│ │ # ... other methods │ │+│ │ │ │+│ └──────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++---++# 2. Sub-Agent Creation & Handling++## 2.1 LangGraph Sub-Agent Architecture Overview++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ SUB-AGENT ARCHITECTURE OVERVIEW │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ PARENT GRAPH │ │+│ │ │ │+│ │ ┌──────────┐ ┌──────────┐ ┌──────────────────────────────┐ │ │+│ │ │ START │───▶│ Agent │───▶│ Conditional Edge │ │ │+│ │ └──────────┘ │ Node │ │ (router function) │ │ │+│ │ └──────────┘ └──────────────┬───────────────┘ │ │+│ │ │ │ │+│ │ ┌──────────────────────────────┼──────────────┐ │ │+│ │ │ │ │ │ │+│ │ ▼ ▼ ▼ │ │+│ │ ┌─────────────────┐ ┌──────────────┐ ┌─────┐ │ │+│ │ │ Tool Node │ │ Sub-Agent │ │ END │ │ │+│ │ │ (parallel) │ │ (nested │ │ │ │ │+│ │ │ │ │ graph) │ │ │ │ │+│ │ └────────┬────────┘ └──────┬───────┘ └─────┘ │ │+│ │ │ │ │ │+│ │ │ ┌──────────────────────┘ │ │+│ │ │ │ │ │+│ │ ▼ ▼ │ │+│ │ ┌─────────────────────────────────────────────────────┐ │ │+│ │ │ State Reducer │ │ │+│ │ │ (aggregates results from parallel executions) │ │ │+│ │ └─────────────────────────────────────────────────────┘ │ │+│ │ │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 2.2 Send API - Parallel Sub-Task Spawning++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ SEND API MECHANISM │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ PURPOSE: Spawn multiple parallel tasks with independent state │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ Send(node: str, arg: Any) │ │+│ │ │ │+│ │ • node: Target node name to invoke │ │+│ │ • arg: Custom state/input for that invocation │ │+│ │ (can differ from main graph state!) │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ EXAMPLE: Map-Reduce Pattern │+│ ─────────────────────────── │+│ │+│ class OverallState(TypedDict): │+│ subjects: list[str] │+│ results: Annotated[list[str], operator.add] # Reducer! │+│ │+│ def fan_out(state: OverallState) -> list[Send]: │+│ """Conditional edge that spawns parallel tasks.""" │+│ return [ │+│ Send("worker", {"subject": s}) │+│ for s in state["subjects"] │+│ ] │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ EXECUTION FLOW: │+│ │+│ subjects = ["A", "B", "C"] │+│ │ │+│ ▼ │+│ ┌────────────────────────┐ │+│ │ fan_out(state) │ │+│ │ Returns: │ │+│ │ [Send("worker", A), │ │+│ │ Send("worker", B), │ │+│ │ Send("worker", C)] │ │+│ └───────────┬────────────┘ │+│ │ │+│ ┌─────────────┼─────────────┐ │+│ │ │ │ │+│ ▼ ▼ ▼ │+│ ┌──────┐ ┌──────┐ ┌──────┐ │+│ │worker│ │worker│ │worker│ ◀── PARALLEL EXECUTION │+│ │ (A) │ │ (B) │ │ (C) │ │+│ └──┬───┘ └──┬───┘ └──┬───┘ │+│ │ │ │ │+│ ▼ ▼ ▼ │+│ result_A result_B result_C │+│ │ │ │ │+│ └────────────┼────────────┘ │+│ │ │+│ ▼ │+│ ┌────────────────────────┐ │+│ │ State Reducer │ │+│ │ operator.add │ │+│ │ │ │+│ │ results = [A, B, C] │ │+│ └────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 2.3 create_react_agent - Sub-Agent Factory++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ create_react_agent ARCHITECTURE │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ SIGNATURE: │+│ ────────── │+│ create_react_agent( │+│ model: LanguageModelLike | Callable, # Static or dynamic model │+│ tools: Sequence[BaseTool] | ToolNode, # Tools for the agent │+│ prompt: Prompt | None = None, # System prompt │+│ response_format: Schema | None = None, # Structured output │+│ pre_model_hook: Runnable | None = None, # Before model call │+│ post_model_hook: Runnable | None = None,# After model call │+│ state_schema: Type | None = None, # Custom state type │+│ checkpointer: Checkpointer = None, # For persistence │+│ interrupt_before: list[str] | None, # HITL breakpoints │+│ interrupt_after: list[str] | None, # HITL breakpoints │+│ version: "v1" | "v2" = "v2", # Execution mode │+│ name: str | None = None, # For sub-graph usage │+│ ) -> CompiledStateGraph │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ GENERATED GRAPH STRUCTURE: │+│ │+│ ┌──────────────────────────────────────────────┐ │+│ │ StateGraph │ │+│ │ │ │+│ │ ┌─────────────────────────────────────────┐ │ │+│ │ │ pre_model_hook │ │ │+│ │ │ (optional: message trimming, etc.) │ │ │+│ │ └────────────────┬────────────────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ ┌─────────┐ │ ┌─────────────────────────────────────────┐ │ │+│ │ START │──────▶│ │ agent │ │ │+│ └─────────┘ │ │ • Applies prompt │ │ │+│ │ │ • Calls model │ │ │+│ │ │ • Returns AIMessage │ │ │+│ │ └────────────────┬────────────────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ │ ┌─────────────────────────────────────────┐ │ │+│ │ │ should_continue │ │ │+│ │ │ (conditional edge) │ │ │+│ │ └────────┬────────────────┬───────────────┘ │ │+│ │ │ │ │ │+│ │ tool_calls? no tool_calls │ │+│ │ │ │ │ │+│ │ ▼ ▼ │ │+│ │ ┌────────────────┐ ┌──────────────────┐ │ │+│ │ │ tools │ │ post_model_hook │ │ │+│ │ │ (ToolNode) │ │ (optional) │ │ │+│ │ └───────┬────────┘ └────────┬─────────┘ │ │+│ │ │ │ │ │+│ │ │ ▼ │ │+│ │ │ ┌───────────────────┐ │ │+│ │ │ │ structured_output │ │ │+│ │ │ │ (if response_ │ │ │+│ │ │ │ format set) │ │ │+│ │ │ └─────────┬─────────┘ │ │+│ │ │ │ │ │+│ │ │ ▼ │ │+│ │ └─────────▶ ┌─────────┐ │ │+│ │ │ END │ │ │+│ │ └─────────┘ │ │+│ │ │ │+│ └──────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 2.4 Version v1 vs v2 Tool Execution++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ TOOL EXECUTION VERSIONS │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ VERSION v1 (Legacy) │+│ ═══════════════════ │+│ │+│ ┌─────────────┐ │+│ │ agent │ │+│ │ (AIMsg │ │+│ │ w/ 3 │ │+│ │ tool_calls│ │+│ └──────┬──────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────┐ │+│ │ tools (ToolNode) │ │+│ │ │ │+│ │ ┌────────┐ ┌────────┐ ┌────────┐ │ │+│ │ │ tool_1 │ │ tool_2 │ │ tool_3 │ │ ◀── All in SAME node │+│ │ └────────┘ └────────┘ └────────┘ │ (parallel within) │+│ │ │ │+│ │ Single message with all results │ │+│ └─────────────────────────────────────────────┘ │+│ │+│ │+│ VERSION v2 (Current - Uses Send API) │+│ ════════════════════════════════════ │+│ │+│ ┌─────────────┐ │+│ │ agent │ │+│ │ (AIMsg │ │+│ │ w/ 3 │ │+│ │ tool_calls│ │+│ └──────┬──────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────┐ │+│ │ should_continue │ │+│ │ │ │+│ │ Returns: [ │ │+│ │ Send("tools", ToolCallWithContext( │ │+│ │ tool_call=call_1, state=state)), │ │+│ │ Send("tools", ToolCallWithContext( │ │+│ │ tool_call=call_2, state=state)), │ │+│ │ Send("tools", ToolCallWithContext( │ │+│ │ tool_call=call_3, state=state)), │ │+│ │ ] │ │+│ └───────────────────┬─────────────────────────┘ │+│ │ │+│ ┌─────────────┼─────────────┐ │+│ │ │ │ │+│ ▼ ▼ ▼ │+│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │+│ │ tools │ │ tools │ │ tools │ ◀── SEPARATE Send instances │+│ │ (call_1) │ │ (call_2) │ │ (call_3) │ (true parallelism) │+│ └──────────┘ └──────────┘ └──────────┘ │+│ │+│ │+│ ADVANTAGES OF v2: │+│ • Human-in-the-loop can pause between individual tool calls │+│ • Better interrupt/resume granularity │+│ • State preserved per-tool-call via ToolCallWithContext │+│ • More resilient to long-running tools │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 2.5 ToolNode Execution Algorithm++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ TOOLNODE EXECUTION ALGORITHM │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ INITIALIZATION: │+│ ═══════════════ │+│ │+│ def __init__(self, tools, handle_tool_errors, messages_key, ...): │+│ # Build tool registry │+│ self._tools_by_name = {tool.name: tool for tool in tools} │+│ │+│ # Pre-compute injection specs (ONCE, not per-call) │+│ self._injected_args = { │+│ tool.name: _get_all_injected_args(tool) │+│ for tool in tools │+│ } │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ EXECUTION FLOW (_func / _afunc): │+│ ═════════════════════════════════ │+│ │+│ ┌─────────────────────────────┐ │+│ │ INPUT │ │+│ │ (state dict or message │ │+│ │ list or ToolCallWithCtx) │ │+│ └─────────────┬───────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────┐ │+│ │ _parse_input() │ │+│ │ │ │+│ │ Extract tool_calls from: │ │+│ │ • Last AIMessage │ │+│ │ • Direct tool_call list │ │+│ │ • ToolCallWithContext │ │+│ └─────────────┬───────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────┐ │+│ │ Build ToolRuntime for │ │+│ │ each tool call: │ │+│ │ │ │+│ │ ToolRuntime( │ │+│ │ state=extracted_state, │ │+│ │ tool_call_id=call["id"], │ │+│ │ config=cfg, │ │+│ │ context=runtime.context, │ │+│ │ store=runtime.store, │ │+│ │ stream_writer=..., │ │+│ │ ) │ │+│ └─────────────┬───────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────┐ │+│ │ PARALLEL EXECUTION │ │+│ │ │ │+│ │ with get_executor_for_config(config) as executor: │ │+│ │ outputs = executor.map( │ │+│ │ self._run_one, │ │+│ │ tool_calls, │ │+│ │ input_types, │ │+│ │ tool_runtimes │ │+│ │ ) │ │+│ │ │ │+│ └─────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────┐ │+│ │ _combine_tool_outputs() │ │+│ │ │ │+│ │ • Regular: {messages: [...]}│ │+│ │ • Command: [Command(...)] │ │+│ │ • Mixed: both types │ │+│ └─────────────────────────────┘ │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ SINGLE TOOL EXECUTION (_run_one): │+│ ══════════════════════════════════ │+│ │+│ ┌─────────────────────────────┐ │+│ │ Build ToolCallRequest │ │+│ │ │ │+│ │ request = ToolCallRequest(│ │+│ │ tool_call=call, │ │+│ │ tool=tools_by_name[...],│ │+│ │ state=state, │ │+│ │ runtime=tool_runtime, │ │+│ │ ) │ │+│ └─────────────┬───────────────┘ │+│ │ │+│ ┌──────────┴──────────┐ │+│ │ │ │+│ wrap_tool_call? No wrapper │+│ │ │ │+│ ▼ ▼ │+│ ┌───────────────┐ ┌───────────────────┐ │+│ │ Call wrapper │ │ _execute_tool_ │ │+│ │ with execute │ │ sync() directly │ │+│ │ callback │ │ │ │+│ └───────────────┘ └───────────────────┘ │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ ARGUMENT INJECTION (_inject_tool_args): │+│ ═══════════════════════════════════════ │+│ │+│ ┌─────────────────────────────────────────────────────────────┐ │+│ │ Pre-computed _InjectedArgs structure: │ │+│ │ │ │+│ │ _InjectedArgs( │ │+│ │ state = {"param_name": "state_field" or None}, │ │+│ │ store = "store_param_name" or None, │ │+│ │ runtime = "runtime_param_name" or None, │ │+│ │ ) │ │+│ └─────────────────────────────────────────────────────────────┘ │+│ │+│ INJECTION PROCESS: │+│ │+│ 1. STATE INJECTION │+│ ├─ InjectedState("field") → inject state["field"] │+│ └─ InjectedState() → inject entire state │+│ │+│ 2. STORE INJECTION │+│ └─ InjectedStore() → inject runtime.store │+│ │+│ 3. RUNTIME INJECTION │+│ └─ ToolRuntime param → inject full ToolRuntime object │+│ │+│ # Injected args HIDDEN from LLM schema │+│ tool_call["args"] = {**original_args, **injected_args} │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 2.6 Command-Based Flow Control++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ COMMAND-BASED FLOW CONTROL │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ Command( │+│ graph: str | None = None, # Target graph (None=current) │+│ update: Any | None = None, # State update │+│ resume: dict | Any = None, # Resume from interrupt │+│ goto: Send | Sequence | str, # Navigation target │+│ ) │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ PATTERN 1: Tool Controls Navigation │+│ ──────────────────────────────────── │+│ │+│ @tool │+│ def decision_tool(query: str) -> Command: │+│ if "urgent" in query: │+│ return Command( │+│ update={"priority": "high"}, │+│ goto="urgent_handler", # Jump to specific node │+│ ) │+│ return Command(goto=END) # End the graph │+│ │+│ │+│ PATTERN 2: Delegate to Parent Graph │+│ ──────────────────────────────────── │+│ │+│ @tool │+│ def spawn_workers(tasks: list[str]) -> Command: │+│ return Command( │+│ graph=Command.PARENT, # Send to parent │+│ goto=[ │+│ Send("worker", {"task": t}) │+│ for t in tasks │+│ ] │+│ ) │+│ │+│ │+│ PATTERN 3: Resume from Interrupt │+│ ──────────────────────────────── │+│ │+│ # In node: │+│ answer = interrupt("What should I do?") │+│ │+│ # Client resumes with: │+│ graph.stream(Command(resume="proceed"), config) │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ COMMAND FLOW DIAGRAM: │+│ │+│ ┌───────────────────────────────────────────────────────────────┐ │+│ │ TOOL NODE │ │+│ │ │ │+│ │ tool execution returns Command │ │+│ └───────────────────────────┬───────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌───────────────────────────────────────────────────────────────┐ │+│ │ _validate_tool_command() │ │+│ │ │ │+│ │ • Ensure ToolMessage exists for current graph │ │+│ │ • Process Command.update │ │+│ │ • Validate Command.goto targets │ │+│ └───────────────────────────┬───────────────────────────────────┘ │+│ │ │+│ ┌──────────────┴──────────────┐ │+│ │ │ │+│ graph == None graph == PARENT │+│ │ │ │+│ ▼ ▼ │+│ ┌────────────────────────┐ ┌────────────────────────┐ │+│ │ Apply to CURRENT │ │ Bubble up to │ │+│ │ graph │ │ PARENT graph │ │+│ │ │ │ │ │+│ │ • Update state │ │ • ParentCommand │ │+│ │ • Navigate via goto │ │ exception raised │ │+│ └────────────────────────┘ └────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 2.7 Interrupt & Resume Flow++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ INTERRUPT & RESUME FLOW │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ INTERRUPT MECHANISM: │+│ ════════════════════ │+│ │+│ ┌────────────────────────────────────────────────────────────────┐ │+│ │ NODE EXECUTION │ │+│ │ │ │+│ │ def approval_node(state): │ │+│ │ # First call: raises GraphInterrupt │ │+│ │ # Resume call: returns stored value │ │+│ │ answer = interrupt("Approve action?") │ │+│ │ return {"approved": answer == "yes"} │ │+│ │ │ │+│ └─────────────────────────────┬──────────────────────────────────┘ │+│ │ │+│ FIRST CALL │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ interrupt() INTERNALS │ │+│ │ │ │+│ │ 1. Get config from context │ │+│ │ 2. Increment interrupt_counter (scratchpad.idx) │ │+│ │ 3. Check for resume values (scratchpad.resume) │ │+│ │ ├─ Found at idx → return resume[idx] │ │+│ │ └─ Not found → raise GraphInterrupt │ │+│ │ │ │+│ │ raise GraphInterrupt(( │ │+│ │ Interrupt( │ │+│ │ value="Approve action?", │ │+│ │ id=xxh3_hash(checkpoint_ns) │ │+│ │ ), │ │+│ │ )) │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ EXECUTION HALTS │ │+│ │ │ │+│ │ • State checkpointed │ │+│ │ • Interrupt info returned to client: │ │+│ │ {"__interrupt__": (Interrupt(value="...", id="..."),)} │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ RESUME MECHANISM: │+│ ═════════════════ │+│ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ CLIENT RESUMES │ │+│ │ │ │+│ │ # Option 1: Resume with value │ │+│ │ graph.stream(Command(resume="yes"), config) │ │+│ │ │ │+│ │ # Option 2: Resume specific interrupt by ID │ │+│ │ graph.stream(Command(resume={"abc123": "yes"}), config) │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────┐ │+│ │ NODE RE-EXECUTES │ │+│ │ │ │+│ │ • Node runs FROM THE START │ │+│ │ • interrupt() called again │ │+│ │ • This time: scratchpad.resume[idx] exists │ │+│ │ • Returns "yes" instead of raising │ │+│ │ │ │+│ └─────────────────────────────────────────────────────────────────┘ │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ MULTIPLE INTERRUPTS IN SAME NODE: │+│ ══════════════════════════════════ │+│ │+│ def multi_approval_node(state): │+│ step1 = interrupt("Approve step 1?") # idx=0 │+│ step2 = interrupt("Approve step 2?") # idx=1 │+│ step3 = interrupt("Approve step 3?") # idx=2 │+│ return {"steps": [step1, step2, step3]} │+│ │+│ # Resume with list: │+│ graph.stream(Command(resume=["yes", "no", "yes"]), config) │+│ │+│ # Or resume one at a time (3 separate calls): │+│ graph.stream(Command(resume="yes"), config) # step1 │+│ graph.stream(Command(resume="no"), config) # step2 │+│ graph.stream(Command(resume="yes"), config) # step3 │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++---++# 3. Execution Flow Diagrams++## 3.1 Complete Agent Execution Cycle++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ COMPLETE AGENT EXECUTION CYCLE │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────┐ │+│ │ USER │ │+│ │ INPUT │ │+│ └────┬────┘ │+│ │ │+│ ▼ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ SUPERSTEP LOOP │ │+│ │ │ │+│ │ ┌─────────────────────────────────────────────────────────────┐ │ │+│ │ │ 1. LOAD CHECKPOINT (if exists) │ │ │+│ │ │ • Restore channel values │ │ │+│ │ │ • Restore versions_seen │ │ │+│ │ │ • Check for pending interrupts │ │ │+│ │ └─────────────────────────────────────────────────────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ │ ┌─────────────────────────────────────────────────────────────┐ │ │+│ │ │ 2. DETERMINE NEXT TASKS │ │ │+│ │ │ • Check conditional edges │ │ │+│ │ │ • Process Send objects │ │ │+│ │ │ • Filter by versions_seen │ │ │+│ │ └─────────────────────────────────────────────────────────────┘ │ │+│ │ │ │ │+│ │ no tasks? │ tasks to run │ │+│ │ ┌───────────────┴───────────────┐ │ │+│ │ │ │ │ │+│ │ ▼ ▼ │ │+│ │ ┌────────────┐ ┌─────────────────────────────┐ │ │+│ │ │ EXIT │ │ 3. EXECUTE TASKS │ │ │+│ │ │ LOOP │ │ (parallel) │ │ │+│ │ └────────────┘ │ │ │ │+│ │ │ ┌─────┐ ┌─────┐ ┌─────┐ │ │ │+│ │ │ │task1│ │task2│ │task3│ │ │ │+│ │ │ └──┬──┘ └──┬──┘ └──┬──┘ │ │ │+│ │ │ │ │ │ │ │ │+│ │ └─────┼──────┼──────┼────────┘ │ │+│ │ │ │ │ │ │+│ │ ▼ ▼ ▼ │ │+│ │ ┌─────────────────────────────────────────────────────────────┐ │ │+│ │ │ 4. APPLY UPDATES TO CHANNELS │ │ │+│ │ │ • Run reducers (e.g., add_messages) │ │ │+│ │ │ • Update channel_versions │ │ │+│ │ │ • Handle Overwrite values │ │ │+│ │ └─────────────────────────────────────────────────────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ │ ┌─────────────────────────────────────────────────────────────┐ │ │+│ │ │ 5. SAVE CHECKPOINT │ │ │+│ │ │ • Serialize channel_values │ │ │+│ │ │ • Store metadata (step, source, parents) │ │ │+│ │ │ • Persist pending_writes │ │ │+│ │ └─────────────────────────────────────────────────────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ │ ┌─────────────────────────────────────────────────────────────┐ │ │+│ │ │ 6. YIELD STATE UPDATE │ │ │+│ │ │ • stream_mode="values": full state │ │ │+│ │ │ • stream_mode="updates": node outputs │ │ │+│ │ │ • stream_mode="messages": LLM tokens │ │ │+│ │ └─────────────────────────────────────────────────────────────┘ │ │+│ │ │ │ │+│ │ └──────────────┐ │ │+│ │ │ │ │+│ │ LOOP BACK TO STEP 2 │ │+│ │ │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 3.2 Nested Sub-Agent Execution++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ NESTED SUB-AGENT EXECUTION │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌───────────────────────────────────────────────────────────────────────┐ │+│ │ PARENT GRAPH │ │+│ │ │ │+│ │ ┌────────────┐ │ │+│ │ │ coordinator│ │ │+│ │ │ node │ │ │+│ │ └─────┬──────┘ │ │+│ │ │ │ │+│ │ │ Returns: [Send("coding_agent", task1), │ │+│ │ │ Send("research_agent", task2)] │ │+│ │ │ │ │+│ │ ┌─────┴─────────────────────────────────────────┐ │ │+│ │ │ │ │ │+│ │ ▼ ▼ │ │+│ │ ┌─────────────────────────────┐ ┌─────────────────────────────┐ │ │+│ │ │ coding_agent │ │ research_agent │ │ │+│ │ │ (compiled sub-graph) │ │ (compiled sub-graph) │ │ │+│ │ │ │ │ │ │ │+│ │ │ ┌────────────────────────┐│ │ ┌────────────────────────┐ │ │ │+│ │ │ │ Has own: ││ │ │ Has own: │ │ │ │+│ │ │ │ • State schema ││ │ │ • State schema │ │ │ │+│ │ │ │ • Checkpointer (opt) ││ │ │ • Checkpointer (opt) │ │ │ │+│ │ │ │ • Tools ││ │ │ • Tools │ │ │ │+│ │ │ │ • Model ││ │ │ • Model │ │ │ │+│ │ │ └────────────────────────┘│ │ └────────────────────────┘ │ │ │+│ │ │ │ │ │ │ │+│ │ │ ┌─────┐ ┌─────┐ │ │ ┌─────┐ ┌─────┐ │ │ │+│ │ │ │agent│──▶│tools│──┐ │ │ │agent│──▶│tools│──┐ │ │ │+│ │ │ └─────┘ └─────┘ │ │ │ └─────┘ └─────┘ │ │ │ │+│ │ │ │ │ │ │ │ │ │+│ │ │ loop──────────┘ │ │ loop──────────┘ │ │ │+│ │ │ │ │ │ │ │+│ │ └─────────────┬───────────────┘ └─────────────┬───────────────┘ │ │+│ │ │ │ │ │+│ │ │ code_result │ research_result │ │+│ │ │ │ │ │+│ │ └────────────┬───────────────────┘ │ │+│ │ │ │ │+│ │ ▼ │ │+│ │ ┌──────────────────────────────────┐ │ │+│ │ │ State Reducer │ │ │+│ │ │ (aggregates sub-agent results) │ │ │+│ │ │ │ │ │+│ │ │ results: [code_result, │ │ │+│ │ │ research_result] │ │ │+│ │ └──────────────────────────────────┘ │ │+│ │ │ │+│ └───────────────────────────────────────────────────────────────────────┘ │+│ │+│ ═══════════════════════════════════════════════════════════════════════ │+│ │+│ CHECKPOINTING INHERITANCE: │+│ ══════════════════════════ │+│ │+│ checkpointer = None │ Inherit from parent (recommended) │+│ checkpointer = True │ Enable independent checkpointing │+│ checkpointer = False │ Disable even if parent has checkpointer │+│ checkpointer = saver │ Use specific checkpointer instance │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++---++# 4. Data Structures Reference++## 4.1 Core Types++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ CORE DATA STRUCTURES │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ Checkpoint │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ v: int # Format version (currently 1) │ │+│ │ id: str # Unique, monotonically increasing │ │+│ │ ts: str # ISO 8601 timestamp │ │+│ │ channel_values: dict # Serialized state per channel │ │+│ │ channel_versions: dict # Version string per channel │ │+│ │ versions_seen: dict # Node -> channel versions it saw │ │+│ │ updated_channels: list # Channels updated in this checkpoint │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ Send │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ node: str # Target node to invoke │ │+│ │ arg: Any # Custom state for that invocation │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ Command │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ graph: str | None # Target (None=current, PARENT=parent) │ │+│ │ update: Any | None # State update to apply │ │+│ │ resume: dict | Any # Resume value for interrupt │ │+│ │ goto: Send | Sequence | str # Navigation target(s) │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ Interrupt │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ value: Any # Value surfaced to client │ │+│ │ id: str # Unique ID for targeted resume │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ ToolRuntime │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ state: StateT # Current graph state │ │+│ │ context: ContextT # Runtime context │ │+│ │ config: RunnableConfig # Runnable configuration │ │+│ │ stream_writer: StreamWriter # For custom streaming │ │+│ │ tool_call_id: str | None # Current tool call ID │ │+│ │ store: BaseStore | None # Persistent storage │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ CompactionControl │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ enabled: Required[bool] # Must be explicitly enabled │ │+│ │ context_token_threshold: int # Default: 100,000 │ │+│ │ model: str # Model for summarization │ │+│ │ summary_prompt: str # Custom summary prompt │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ _InjectedArgs (internal) │ │+│ ├─────────────────────────────────────────────────────────────────────┤ │+│ │ state: dict[str, str|None] # param -> state_field (None=full) │ │+│ │ store: str | None # Param name for store injection │ │+│ │ runtime: str | None # Param name for runtime injection │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++## 4.2 State Channel Types++```+┌─────────────────────────────────────────────────────────────────────────────┐+│ STATE CHANNEL TYPES │+├─────────────────────────────────────────────────────────────────────────────┤+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ LastValue │ │+│ │ ────────── │ │+│ │ Default channel type. Last write wins. │ │+│ │ │ │+│ │ class State(TypedDict): │ │+│ │ current_task: str # LastValue (implicit) │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ BinaryOperatorAggregate │ │+│ │ ──────────────────────── │ │+│ │ Uses a reducer function to combine values. │ │+│ │ │ │+│ │ class State(TypedDict): │ │+│ │ messages: Annotated[list, add_messages] # Append │ │+│ │ total: Annotated[int, operator.add] # Sum │ │+│ │ all_items: Annotated[list, operator.add] # Concat │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ EphemeralValue │ │+│ │ ────────────── │ │+│ │ Value exists only within a single superstep. │ │+│ │ Reset to default after each step. │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ NamedBarrierValue │ │+│ │ ───────────────── │ │+│ │ Synchronization primitive. Waits for all named writers. │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+│ ┌─────────────────────────────────────────────────────────────────────┐ │+│ │ Managed Values (Special) │ │+│ │ ──────────────────────── │ │+│ │ Not channels - computed/managed by the runtime. │ │+│ │ │ │+│ │ class State(TypedDict): │ │+│ │ remaining_steps: RemainingSteps # Auto-decremented │ │+│ └─────────────────────────────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────────────────┘+```++---++## Version Information++| Package | Version |+|---------|---------|+| anthropic | 0.77.0 |+| langgraph | 1.0.7 |+| langgraph-sdk | 0.3.3 |+| langgraph-checkpoint | 4.0.0 |+| langchain-core | 1.2.7 |+| langchain-anthropic | 1.3.1 |++---++## Quick Reference++### Memory Compaction Trigger+```python+if total_tokens >= 100_000: # Default threshold+ trigger_compaction()+```++### Create Sub-Agent+```python+sub_agent = create_react_agent(model, tools, name="sub_agent")+parent_graph.add_node("sub_agent", sub_agent)+```++### Spawn Parallel Tasks+```python+def router(state):+ return [Send("worker", {"task": t}) for t in state["tasks"]]+```++### Control Flow from Tool+```python+return Command(update={"status": "done"}, goto=END)+```++### Human-in-the-Loop+```python+answer = interrupt("Need approval") # Pauses execution+# Client: graph.stream(Command(resume="approved"), config)+```diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.mdindex 3167a378..4f4302a6 100644--- a/docs-internal/node_creation.md+++ b/docs-internal/node_creation.md@@ -239,10 +239,31 @@ const createNodeTypes = () => {| Component | Shape | Use Case ||-----------|-------|----------|-| `SquareNode` | 80x80px square | Standard nodes, triggers |+| `SquareNode` | 80x80px square | Standard nodes, action nodes |+| `TriggerNode` | 80x80px square | Trigger nodes (no input handles) || `ModelNode` | 80x80px circle | AI models, config nodes || `AIAgentNode` | Rectangle with handles | AI agents with tool/memory inputs |-| `WhatsAppNode` | Square with status | WhatsApp-specific features |+| `ToolkitNode` | Square with vertical handles | Skill nodes, toolkit aggregators |++### Trigger Node Registration++Trigger nodes must be added to `TRIGGER_NODE_TYPES` array in Dashboard.tsx:++```typescript+// In createNodeTypes()+const TRIGGER_NODE_TYPES = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'chatTrigger', 'taskTrigger'];++// Trigger nodes map to TriggerNode component+if (TRIGGER_NODE_TYPES.includes(type)) {+ types[type] = TriggerNode;+}+```++Also add to the deploy validation array in `handleDeploy()`:++```typescript+const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];+```---@@ -847,6 +868,99 @@ event_waiter.dispatch('my_event_received', {})```+### Example: Task Trigger (Agent Delegation)++The `taskTrigger` node demonstrates a complete trigger implementation that fires when delegated child agents complete:++**Frontend Definition** (`client/src/nodeDefinitions/workflowNodes.ts`):+```typescript+taskTrigger: {+ displayName: 'Task Completed',+ name: 'taskTrigger',+ icon: '📨',+ group: ['trigger', 'workflow'],+ version: 1,+ subtitle: 'Child Agent Completed',+ description: 'Triggers when a delegated child agent completes its task',+ defaults: { name: 'Task Completed', color: '#bd93f9' },+ inputs: [],+ outputs: [{+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'task_id, status, agent_name, result/error, parent_node_id'+ }],+ properties: [+ { displayName: 'Task ID Filter', name: 'task_id', type: 'string', default: '' },+ { displayName: 'Agent Name Filter', name: 'agent_name', type: 'string', default: '' },+ { displayName: 'Status Filter', name: 'status_filter', type: 'options', default: 'all',+ options: [{ name: 'All', value: 'all' }, { name: 'Completed Only', value: 'completed' }, { name: 'Errors Only', value: 'error' }] },+ { displayName: 'Parent Node ID', name: 'parent_node_id', type: 'string', default: '' }+ ]+}+```++**Backend Registry** (`server/services/event_waiter.py`):+```python+'taskTrigger': TriggerConfig(+ node_type='taskTrigger',+ event_type='task_completed',+ display_name='Task Completed'+),++def build_task_completed_filter(params: Dict) -> Callable[[Dict], bool]:+ """Build filter for task completed events."""+ task_id_filter = params.get('task_id', '')+ agent_name_filter = params.get('agent_name', '')+ status_filter = params.get('status_filter', 'all')+ parent_node_id = params.get('parent_node_id', '')++ def matches(data: Dict) -> bool:+ if task_id_filter and data.get('task_id') != task_id_filter:+ return False+ if agent_name_filter:+ if agent_name_filter.lower() not in data.get('agent_name', '').lower():+ return False+ if status_filter == 'completed' and data.get('status') != 'completed':+ return False+ if status_filter == 'error' and data.get('status') != 'error':+ return False+ if parent_node_id and data.get('parent_node_id') != parent_node_id:+ return False+ return True+ return matches++FILTER_BUILDERS['taskTrigger'] = build_task_completed_filter+```++**Event Dispatch** (`server/services/handlers/tools.py`):+```python+# In _execute_delegated_agent(), after child completes:+await broadcaster.send_custom_event('task_completed', {+ 'task_id': task_id,+ 'status': 'completed', # or 'error'+ 'agent_name': agent_label,+ 'agent_node_id': node_id,+ 'parent_node_id': config.get('parent_node_id', ''),+ 'result': result.get('result', {}).get('response', ...),+ 'workflow_id': workflow_id,+})+```++**Output Schema** (`client/src/components/parameterPanel/InputSection.tsx`):+```typescript+taskTrigger: {+ task_id: 'string',+ status: 'string',+ agent_name: 'string',+ agent_node_id: 'string',+ parent_node_id: 'string',+ result: 'string',+ error: 'string',+ workflow_id: 'string',+}+```+---## AI Provider Nodesdiff --git a/docs-internal/specialized_agent_node_creation.md b/docs-internal/specialized_agent_node_creation.mdindex 63ae49e2..fb1a043e 100644--- a/docs-internal/specialized_agent_node_creation.md+++ b/docs-internal/specialized_agent_node_creation.md@@ -15,13 +15,15 @@ Memory Node --------+ (AI Agent)Tool Nodes ---------+[Battery Monitor][WiFi Automation]+Task Trigger -------+ (input-task handle)```**Key Characteristics:**- **Full AI Agent Inheritance**: Same AI configuration options as base AI Agent (provider, model, prompt, system message, temperature, thinking)-- **Left Input Handles**: Main input (30%) and Memory input (70%) on the left side+- **Left Input Handles**: Main input (30%), Memory input (55%), Task input (85%) on the left side- **Bottom Handles**: Skill (25%) and Tool (75%) connections at the bottom- **Right Output Handle**: Agent output for workflow continuation+- **Task Input**: Receives task completion events from taskTrigger nodes for delegation result handling- **Domain-Specific**: Pre-configured descriptions and use cases for specific capabilities## Existing Specialized Agents@@ -149,6 +151,31 @@ const AI_AGENT_PROPERTIES: INodeProperties[] = [];```+## Shared Constants++All specialized agents use shared constants defined in `specializedAgentNodes.ts`:++```typescript+// Inputs shared by AI Agent and all Specialized Agent nodes+export const AI_AGENT_INPUTS = [+ { name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Agent input' },+ { name: 'skill', displayName: 'Skill', type: 'main' as NodeConnectionType, description: 'Skill nodes that provide context and instructions' },+ { name: 'memory', displayName: 'Memory', type: 'main' as NodeConnectionType, description: 'Memory node for conversation history' },+ { name: 'tools', displayName: 'Tool', type: 'main' as NodeConnectionType, description: 'Tool nodes for agent capabilities' },+ { name: 'task', displayName: 'Task', type: 'main' as NodeConnectionType, description: 'Task completion events from taskTrigger' },+];++// Outputs shared by AI Agent and all Specialized Agent nodes+export const AI_AGENT_OUTPUTS = [+ { name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'Agent output' }+];++// Properties shared by AI Agent and all Specialized Agent nodes+export const AI_AGENT_PROPERTIES: INodeProperties[] = [+ // Provider, Model, Prompt, System Message, Options (temperature, maxTokens, thinking)+];+```+## Creating a New Specialized Agent### Step 1: Add Node Definition@@ -168,35 +195,41 @@ database_agent: {subtitle: 'Data Operations',description: 'AI Agent specialized for database operations. Connect skills, memory, and database nodes.',defaults: { name: 'Database Agent', color: dracula.cyan }, // Use centralized dracula theme- inputs: [- {- name: 'main',- displayName: 'Input',- type: 'main' as NodeConnectionType,- description: 'Agent input'- },- {- name: 'skill',- displayName: 'Skill',- type: 'main' as NodeConnectionType,- description: 'Skill nodes that provide context and instructions'- },- {- name: 'memory',- displayName: 'Memory',- type: 'main' as NodeConnectionType,- description: 'Memory node for conversation history'- },- {- name: 'tools',- displayName: 'Tool',- type: 'main' as NodeConnectionType,- description: 'Database tool nodes (SQL, MongoDB, Redis, etc.)'- }- ],- outputs: [{+ inputs: AI_AGENT_INPUTS, // Use shared constant+ outputs: AI_AGENT_OUTPUTS, // Use shared constant+ properties: AI_AGENT_PROPERTIES // Use shared constant+}+```++**Important**: Always use the shared constants (`AI_AGENT_INPUTS`, `AI_AGENT_OUTPUTS`, `AI_AGENT_PROPERTIES`) instead of defining inputs/outputs inline. This ensures all agents have consistent handles including the `input-task` handle for delegation.++### Step 1b: Add to SPECIALIZED_AGENT_TYPES++```typescript+export const SPECIALIZED_AGENT_TYPES = [+ 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',+ 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',+ 'database_agent' // Add new agent+];+```++### Step 2 (Legacy Pattern - NOT RECOMMENDED)++The old pattern defined inputs inline:++```typescript+inputs: [+ {name: 'main',- displayName: 'Output',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Agent input'+ },+ // ... more inputs+],+outputs: [{+ name: 'main',+ displayName: 'Output',type: 'main' as NodeConnectionType,description: 'Agent output'}],diff --git a/package-lock.json b/package-lock.jsonindex cafa86ab..c50a2018 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "machinaos",- "version": "0.0.9",+ "version": "0.0.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "machinaos",- "version": "0.0.9",+ "version": "0.0.10","hasInstallScript": true,"license": "MIT","workspaces": [@@ -16,13 +16,13 @@"concurrently": "^9.2.1","cross-env": "^7.0.3","rimraf": "^6.0.1",- "whatsapp-rpc": "^0.0.5"+ "whatsapp-rpc": "^0.0.8"},"bin": {"machinaos": "bin/cli.js"},"engines": {- "node": ">=18.0.0"+ "node": ">=20.0.0"}},"client": {@@ -11369,9 +11369,9 @@}},"node_modules/whatsapp-rpc": {- "version": "0.0.5",- "resolved": "https://registry.npmjs.org/whatsapp-rpc/-/whatsapp-rpc-0.0.5.tgz",- "integrity": "sha512-k7mXm1bZdnpP22FA/tLrQEyAOGX9Dzz+qKgbv54SW8l3M34bTZApNDWWZmfz3V/7f5fjQ08gRy4mjGN5l9rXLw==",+ "version": "0.0.8",+ "resolved": "https://registry.npmjs.org/whatsapp-rpc/-/whatsapp-rpc-0.0.8.tgz",+ "integrity": "sha512-G5iwmj3CC6zFLLdNUgbdtDiIlLpGN/GQ71HvqOWgAV+mWHEDiuCrHWjcdHEN5fLKP4siBBHvVv487b5dwcD9eA==","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex 2b371992..856dca78 100644--- a/package.json+++ b/package.json@@ -60,9 +60,11 @@],"scripts": {"start": "node scripts/start.js",+ "start:daemon": "node scripts/start.js --daemon","start:temporal": "cross-env TEMPORAL_ENABLED=true node scripts/start.js","client:start": "cd client && npm run start","python:start": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning",+ "python:daemon": "cd server && uv run gunicorn main:app -c gunicorn.conf.py","temporal:worker": "cd server && uv run python -m services.temporal.worker","whatsapp:start": "whatsapp-rpc start","whatsapp:stop": "whatsapp-rpc stop",@@ -82,11 +84,17 @@"docker:prod:logs": "docker-compose -f docker-compose.prod.yml logs -f","deploy": "bash deploy.sh","deploy:gcp": "bash deploy.sh",+ "daemon:install": "node scripts/daemon.js install",+ "daemon:uninstall": "node scripts/daemon.js uninstall",+ "daemon:status": "node scripts/daemon.js status",+ "daemon:start": "node scripts/daemon.js start",+ "daemon:stop": "node scripts/daemon.js stop",+ "daemon:restart": "node scripts/daemon.js restart","prepublishOnly": "node -e \"const p=require('./package.json'); if(!p.bin||!p.version){process.exit(1)}\"","postinstall": "node scripts/postinstall.js"},"dependencies": {- "whatsapp-rpc": "^0.0.5",+ "whatsapp-rpc": "^0.0.8","concurrently": "^9.2.1","cross-env": "^7.0.3","rimraf": "^6.0.1"diff --git a/scripts/daemon.js b/scripts/daemon.jsnew file mode 100644index 00000000..f134d303--- /dev/null+++ b/scripts/daemon.js@@ -0,0 +1,427 @@+#!/usr/bin/env node+/**+ * Cross-platform service installer for MachinaOS.+ * Works on: Windows (NSSM), Linux (systemd), macOS (launchd)+ *+ * Usage:+ * node scripts/service.js install [OPTIONS]+ * node scripts/service.js uninstall+ * node scripts/service.js status+ * node scripts/service.js start+ * node scripts/service.js stop+ * node scripts/service.js restart+ *+ * Options:+ * --dir=PATH Installation directory (default: current directory)+ * --user=USER Service user (default: current user)+ * --memory=LIMIT Memory limit (default: 2G, Linux only)+ */+import { execSync, spawnSync } from 'child_process';+import { existsSync, writeFileSync, mkdirSync, unlinkSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';+import { homedir } from 'os';++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');++// Platform detection+const isWindows = process.platform === 'win32';+const isMac = process.platform === 'darwin';+const isLinux = process.platform === 'linux';++// Service name+const SERVICE_NAME = 'MachinaOs';++// Parse command line arguments+const args = process.argv.slice(2);+const command = args[0] || 'help';+const options = {};+args.slice(1).forEach(arg => {+ const match = arg.match(/^--(\w+)=(.+)$/);+ if (match) {+ options[match[1]] = match[2];+ }+});++// Default options+const installDir = options.dir || ROOT;+const serviceUser = options.user || (isWindows ? process.env.USERNAME : process.env.USER);+const memoryLimit = options.memory || '2G';++function run(cmd, opts = {}) {+ try {+ return execSync(cmd, {+ encoding: 'utf-8',+ stdio: opts.silent ? 'pipe' : 'inherit',+ shell: true,+ ...opts+ });+ } catch (e) {+ if (!opts.ignoreError) {+ throw e;+ }+ return '';+ }+}++function runSilent(cmd) {+ try {+ execSync(cmd, { encoding: 'utf-8', stdio: 'pipe', shell: true });+ return true;+ } catch {+ return false;+ }+}++// ============================================================================+// Windows (NSSM)+// ============================================================================++function windowsCheckNssm() {+ if (!runSilent('where nssm')) {+ console.log('NSSM not found. Install from https://nssm.cc/');+ console.log('Or use: winget install nssm');+ process.exit(1);+ }+}++function windowsInstall() {+ windowsCheckNssm();++ const pythonExe = resolve(installDir, 'server', '.venv', 'Scripts', 'python.exe');+ const serverDir = resolve(installDir, 'server');+ const logsDir = resolve(installDir, 'logs');++ if (!existsSync(pythonExe)) {+ console.log(`Python venv not found at ${pythonExe}`);+ console.log('Run "npm run build" first.');+ process.exit(1);+ }++ // Create logs directory+ if (!existsSync(logsDir)) {+ mkdirSync(logsDir, { recursive: true });+ }++ console.log(`Installing ${SERVICE_NAME} service...`);+ console.log(` Directory: ${installDir}`);+ console.log(` Python: ${pythonExe}`);++ // Remove existing service if present+ run(`nssm stop ${SERVICE_NAME}`, { ignoreError: true, silent: true });+ run(`nssm remove ${SERVICE_NAME} confirm`, { ignoreError: true, silent: true });++ // Install service+ run(`nssm install ${SERVICE_NAME} "${pythonExe}" -m gunicorn main:app -c gunicorn.conf.py`);+ run(`nssm set ${SERVICE_NAME} AppDirectory "${serverDir}"`);+ run(`nssm set ${SERVICE_NAME} AppEnvironmentExtra "PYTHONPATH=${serverDir}"`);+ run(`nssm set ${SERVICE_NAME} Start SERVICE_AUTO_START`);+ run(`nssm set ${SERVICE_NAME} AppStdout "${logsDir}\\service.log"`);+ run(`nssm set ${SERVICE_NAME} AppStderr "${logsDir}\\service.log"`);+ run(`nssm set ${SERVICE_NAME} AppRotateFiles 1`);+ run(`nssm set ${SERVICE_NAME} AppRotateBytes 10485760`); // 10MB++ console.log('Service installed successfully.');+ console.log(`Logs: ${logsDir}\\service.log`);+}++function windowsUninstall() {+ windowsCheckNssm();+ run(`nssm stop ${SERVICE_NAME}`, { ignoreError: true });+ run(`nssm remove ${SERVICE_NAME} confirm`, { ignoreError: true });+ console.log('Service uninstalled.');+}++function windowsStatus() {+ windowsCheckNssm();+ run(`nssm status ${SERVICE_NAME}`, { ignoreError: true });+}++function windowsStart() {+ windowsCheckNssm();+ run(`nssm start ${SERVICE_NAME}`);+}++function windowsStop() {+ windowsCheckNssm();+ run(`nssm stop ${SERVICE_NAME}`);+}++function windowsRestart() {+ windowsCheckNssm();+ run(`nssm restart ${SERVICE_NAME}`);+}++// ============================================================================+// Linux (systemd)+// ============================================================================++function linuxGenerateServiceFile() {+ const venvPath = resolve(installDir, 'server', '.venv');+ const serverDir = resolve(installDir, 'server');++ return `[Unit]+Description=MachinaOs Backend+After=network.target++[Service]+Type=simple+User=${serviceUser}+WorkingDirectory=${serverDir}+EnvironmentFile=${installDir}/.env+ExecStart=${venvPath}/bin/gunicorn main:app -c gunicorn.conf.py+Restart=always+RestartSec=5+StartLimitIntervalSec=60+StartLimitBurst=5++# Resource limits+MemoryMax=${memoryLimit}++[Install]+WantedBy=multi-user.target+`;+}++function linuxInstall() {+ const venvPath = resolve(installDir, 'server', '.venv', 'bin', 'python');++ if (!existsSync(venvPath)) {+ console.log(`Python venv not found at ${venvPath}`);+ console.log('Run "npm run build" first.');+ process.exit(1);+ }++ console.log(`Installing ${SERVICE_NAME} service...`);+ console.log(` Directory: ${installDir}`);+ console.log(` User: ${serviceUser}`);+ console.log(` Memory limit: ${memoryLimit}`);++ const serviceContent = linuxGenerateServiceFile();+ const tempFile = '/tmp/machina.service';+ writeFileSync(tempFile, serviceContent);++ run(`sudo cp ${tempFile} /etc/systemd/system/machina.service`);+ run('sudo systemctl daemon-reload');+ run('sudo systemctl enable machina');++ console.log('Service installed successfully.');+ console.log('Start with: sudo systemctl start machina');+ console.log('View logs: journalctl -u machina -f');+}++function linuxUninstall() {+ run('sudo systemctl stop machina', { ignoreError: true });+ run('sudo systemctl disable machina', { ignoreError: true });+ if (existsSync('/etc/systemd/system/machina.service')) {+ run('sudo rm /etc/systemd/system/machina.service');+ }+ run('sudo systemctl daemon-reload');+ console.log('Service uninstalled.');+}++function linuxStatus() {+ run('systemctl status machina', { ignoreError: true });+}++function linuxStart() {+ run('sudo systemctl start machina');+}++function linuxStop() {+ run('sudo systemctl stop machina');+}++function linuxRestart() {+ run('sudo systemctl restart machina');+}++// ============================================================================+// macOS (launchd)+// ============================================================================++function macGeneratePlist() {+ const venvPath = resolve(installDir, 'server', '.venv');+ const serverDir = resolve(installDir, 'server');+ const logsDir = resolve(installDir, 'logs');++ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.machinaos.backend</string>+ <key>ProgramArguments</key>+ <array>+ <string>${venvPath}/bin/gunicorn</string>+ <string>main:app</string>+ <string>-c</string>+ <string>gunicorn.conf.py</string>+ </array>+ <key>WorkingDirectory</key>+ <string>${serverDir}</string>+ <key>EnvironmentVariables</key>+ <dict>+ <key>PATH</key>+ <string>${venvPath}/bin:/usr/local/bin:/usr/bin:/bin</string>+ </dict>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <true/>+ <key>StandardOutPath</key>+ <string>${logsDir}/service.log</string>+ <key>StandardErrorPath</key>+ <string>${logsDir}/service.log</string>+</dict>+</plist>+`;+}++function macGetPlistPath() {+ return resolve(homedir(), 'Library', 'LaunchAgents', 'com.machinaos.backend.plist');+}++function macInstall() {+ const venvPath = resolve(installDir, 'server', '.venv', 'bin', 'python');+ const logsDir = resolve(installDir, 'logs');++ if (!existsSync(venvPath)) {+ console.log(`Python venv not found at ${venvPath}`);+ console.log('Run "npm run build" first.');+ process.exit(1);+ }++ // Create logs directory+ if (!existsSync(logsDir)) {+ mkdirSync(logsDir, { recursive: true });+ }++ console.log(`Installing ${SERVICE_NAME} service...`);+ console.log(` Directory: ${installDir}`);++ const plistContent = macGeneratePlist();+ const plistPath = macGetPlistPath();++ // Ensure LaunchAgents directory exists+ const launchAgentsDir = dirname(plistPath);+ if (!existsSync(launchAgentsDir)) {+ mkdirSync(launchAgentsDir, { recursive: true });+ }++ // Unload existing if present+ run(`launchctl unload "${plistPath}"`, { ignoreError: true, silent: true });++ writeFileSync(plistPath, plistContent);++ console.log('Service installed successfully.');+ console.log(`Plist: ${plistPath}`);+ console.log(`Logs: ${logsDir}/service.log`);+ console.log('Start with: node scripts/service.js start');+}++function macUninstall() {+ const plistPath = macGetPlistPath();+ run(`launchctl unload "${plistPath}"`, { ignoreError: true });+ if (existsSync(plistPath)) {+ unlinkSync(plistPath);+ }+ console.log('Service uninstalled.');+}++function macStatus() {+ run('launchctl list | grep machinaos', { ignoreError: true });+}++function macStart() {+ const plistPath = macGetPlistPath();+ run(`launchctl load "${plistPath}"`);+}++function macStop() {+ const plistPath = macGetPlistPath();+ run(`launchctl unload "${plistPath}"`);+}++function macRestart() {+ macStop();+ macStart();+}++// ============================================================================+// Main+// ============================================================================++function showHelp() {+ console.log(`+MachinaOS Service Manager++Usage: node scripts/service.js <command> [options]++Commands:+ install Install as system service+ uninstall Remove system service+ status Show service status+ start Start the service+ stop Stop the service+ restart Restart the service++Options:+ --dir=PATH Installation directory (default: current)+ --user=USER Service user (Linux only, default: current user)+ --memory=LIMIT Memory limit (Linux only, default: 2G)++Platform: ${isWindows ? 'Windows (NSSM)' : isMac ? 'macOS (launchd)' : 'Linux (systemd)'}++Examples:+ node scripts/service.js install+ node scripts/service.js install --dir=/opt/machinaos --user=machina+ node scripts/service.js status+ node scripts/service.js restart+`);+}++// Dispatch to platform-specific functions+const handlers = {+ windows: {+ install: windowsInstall,+ uninstall: windowsUninstall,+ status: windowsStatus,+ start: windowsStart,+ stop: windowsStop,+ restart: windowsRestart,+ },+ linux: {+ install: linuxInstall,+ uninstall: linuxUninstall,+ status: linuxStatus,+ start: linuxStart,+ stop: linuxStop,+ restart: linuxRestart,+ },+ mac: {+ install: macInstall,+ uninstall: macUninstall,+ status: macStatus,+ start: macStart,+ stop: macStop,+ restart: macRestart,+ },+};++const platform = isWindows ? 'windows' : isMac ? 'mac' : 'linux';++if (command === 'help' || command === '--help' || command === '-h') {+ showHelp();+ process.exit(0);+}++const handler = handlers[platform][command];+if (!handler) {+ console.log(`Unknown command: ${command}`);+ showHelp();+ process.exit(1);+}++handler();diff --git a/scripts/start.js b/scripts/start.jsindex a6631409..67da5dfd 100644--- a/scripts/start.js+++ b/scripts/start.js@@ -12,6 +12,10 @@ const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');const START_TIME = Date.now();+// Parse command line arguments+const args = process.argv.slice(2);+const isDaemonMode = args.includes('--daemon');+// ============================================================================// Platform Detection// ============================================================================@@ -158,6 +162,7 @@ process.env.PYTHONUTF8 = '1';console.log('\n=== MachinaOS Starting ===\n');log(`Platform: ${getPlatformName()}`);+log(`Mode: ${isDaemonMode ? 'Daemon (Gunicorn)' : 'Development (uvicorn)'}`);log(`Ports: ${config.ports.join(', ')}`);log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);@@ -219,7 +224,8 @@ if (isProduction) {services.push('npm:client:start');}-services.push('npm:python:start');+// Python backend: use gunicorn in daemon mode, uvicorn in development+services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');// WhatsApp RPC: only start if the pre-built binary existsconst whatsappBin = resolve(ROOT, 'node_modules', 'whatsapp-rpc', 'bin',diff --git a/server/constants.py b/server/constants.pyindex 9981f5b0..d09c2c23 100644--- a/server/constants.py+++ b/server/constants.py@@ -214,6 +214,7 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset(['whatsappReceive','workflowTrigger','chatTrigger',+ 'taskTrigger',])# Legacy alias for backwards compatibility@@ -235,6 +236,7 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset(['whatsappReceive','workflowTrigger','chatTrigger',+ 'taskTrigger',])# =============================================================================diff --git a/server/core/cleanup.py b/server/core/cleanup.pynew file mode 100644index 00000000..c29b4db5--- /dev/null+++ b/server/core/cleanup.py@@ -0,0 +1,123 @@+"""Periodic cleanup service for long-running daemon.++Follows the RecoverySweeper pattern from execution/recovery.py.+All configuration from Settings (environment variables).+"""+import asyncio+import gc+from typing import Optional, TYPE_CHECKING++from core.logging import get_logger++if TYPE_CHECKING:+ from core.config import Settings+ from core.database import Database+ from core.cache import CacheService++logger = get_logger(__name__)+++class CleanupService:+ """Background cleanup to prevent resource exhaustion.++ Periodically cleans up:+ - Expired cache entries+ - Old console logs (keeps configurable count)+ - Old cache entries by age+ - Forces garbage collection+ """++ def __init__(+ self,+ database: "Database",+ cache: "CacheService",+ settings: "Settings"+ ):+ self.database = database+ self.cache = cache+ self.settings = settings+ self._running = False+ self._task: Optional[asyncio.Task] = None++ async def start(self) -> None:+ """Start the cleanup service background task."""+ if self._running:+ return+ self._running = True+ self._task = asyncio.create_task(self._cleanup_loop())+ logger.info(+ "Cleanup service started",+ interval=self.settings.cleanup_interval,+ logs_max=self.settings.cleanup_logs_max_count,+ cache_max_age_hours=self.settings.cleanup_cache_max_age_hours+ )++ async def stop(self) -> None:+ """Stop the cleanup service gracefully."""+ self._running = False+ if self._task:+ self._task.cancel()+ try:+ await self._task+ except asyncio.CancelledError:+ pass+ logger.info("Cleanup service stopped")++ async def _cleanup_loop(self) -> None:+ """Main cleanup loop - runs at configured interval."""+ while self._running:+ try:+ await self._run_cleanup()+ except Exception as e:+ logger.error("Cleanup failed", error=str(e))+ await asyncio.sleep(self.settings.cleanup_interval)++ async def _run_cleanup(self) -> None:+ """Execute all cleanup tasks."""+ results = {}++ # 1. Expired cache entries (TTL-based)+ try:+ results['expired_cache'] = await self.database.cleanup_expired_cache()+ except Exception as e:+ logger.warning("Failed to cleanup expired cache", error=str(e))+ results['expired_cache'] = 0++ # 2. Old console logs (keep last N)+ try:+ results['old_logs'] = await self.database.cleanup_old_console_logs(+ keep=self.settings.cleanup_logs_max_count+ )+ except Exception as e:+ logger.warning("Failed to cleanup old console logs", error=str(e))+ results['old_logs'] = 0++ # 3. Old cache entries by age+ try:+ results['old_cache'] = await self.database.cleanup_old_cache(+ max_age_hours=self.settings.cleanup_cache_max_age_hours+ )+ except Exception as e:+ logger.warning("Failed to cleanup old cache", error=str(e))+ results['old_cache'] = 0++ # 4. Force garbage collection+ gc.collect()++ # Only log if something was cleaned up+ total_cleaned = sum(results.values())+ if total_cleaned > 0:+ logger.info("Cleanup completed", **results)++ async def run_once(self) -> dict:+ """Run cleanup once and return results. Useful for testing."""+ results = {}+ results['expired_cache'] = await self.database.cleanup_expired_cache()+ results['old_logs'] = await self.database.cleanup_old_console_logs(+ keep=self.settings.cleanup_logs_max_count+ )+ results['old_cache'] = await self.database.cleanup_old_cache(+ max_age_hours=self.settings.cleanup_cache_max_age_hours+ )+ gc.collect()+ return resultsdiff --git a/server/core/config.py b/server/core/config.pyindex fdac22e7..aa1f809a 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -100,6 +100,22 @@ class Settings(BaseSettings):# Health Checkhealth_check_interval: int = Field(default=30, env="HEALTH_CHECK_INTERVAL", ge=10)+ # Cleanup Configuration (for long-running daemon)+ cleanup_enabled: bool = Field(default=True, env="CLEANUP_ENABLED")+ cleanup_interval: int = Field(default=3600, env="CLEANUP_INTERVAL", ge=60)+ cleanup_logs_max_count: int = Field(default=1000, env="CLEANUP_LOGS_MAX_COUNT", ge=100)+ cleanup_cache_max_age_hours: int = Field(default=24, env="CLEANUP_CACHE_MAX_AGE_HOURS", ge=1)++ # Feature Toggles+ ws_logging_enabled: bool = Field(default=True, env="WS_LOGGING_ENABLED")++ # Gunicorn Configuration (for production deployment)+ gunicorn_timeout: int = Field(default=120, env="GUNICORN_TIMEOUT", ge=30)+ gunicorn_graceful_timeout: int = Field(default=30, env="GUNICORN_GRACEFUL_TIMEOUT", ge=10)+ gunicorn_keepalive: int = Field(default=5, env="GUNICORN_KEEPALIVE", ge=1)+ gunicorn_max_requests: int = Field(default=10000, env="GUNICORN_MAX_REQUESTS", ge=0)+ gunicorn_max_requests_jitter: int = Field(default=1000, env="GUNICORN_MAX_REQUESTS_JITTER", ge=0)+@field_validator("database_url")@classmethoddef validate_database_url(cls, v):diff --git a/server/core/database.py b/server/core/database.pyindex 49655a0b..17b9bed7 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -5,7 +5,7 @@ from typing import Dict, Any, List, Optionalfrom sqlmodel import SQLModel, select, Sessionfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmakerfrom sqlalchemy.exc import IntegrityError-from sqlalchemy import text+from sqlalchemy import text, funcfrom contextlib import asynccontextmanagerfrom core.config import Settings@@ -77,6 +77,12 @@ class Database:"ALTER TABLE user_settings ADD COLUMN console_panel_default_open BOOLEAN DEFAULT 0"))logger.info("Added console_panel_default_open column to user_settings")++ if "examples_loaded" not in columns:+ await conn.execute(text(+ "ALTER TABLE user_settings ADD COLUMN examples_loaded BOOLEAN DEFAULT 0"+ ))+ logger.info("Added examples_loaded column to user_settings")except Exception as e:logger.warning(f"Migration check failed (table may not exist yet): {e}")@@ -489,6 +495,27 @@ class Database:logger.error("Failed to get node output", node_id=node_id, error=str(e))return None+ async def get_node_output_by_session(self, session_id: str,+ output_name: str = "output_0") -> Optional[Dict[str, Any]]:+ """Get node output by session_id only (for delegation result lookup).++ Used when node_id is unknown but session_id encodes the lookup key.+ """+ try:+ async with self.get_session() as session:+ stmt = select(NodeOutput).where(+ NodeOutput.session_id == session_id,+ NodeOutput.output_name == output_name+ )+ result = await session.execute(stmt)+ output = result.scalar_one_or_none()++ return {"data": output.data} if output else None++ except Exception as e:+ logger.error("Failed to get node output by session", session_id=session_id, error=str(e))+ return None+async def delete_node_output(self, node_id: str) -> int:"""Delete all outputs for a node (any session). Returns count deleted."""try:@@ -814,6 +841,47 @@ class Database:logger.error("Failed to clear console logs", error=str(e))return 0+ async def cleanup_old_console_logs(self, keep: int = 1000) -> int:+ """Keep only the most recent N console logs. Returns count deleted."""+ from models.database import ConsoleLog++ try:+ async with self.get_session() as session:+ # Count total logs+ count_stmt = select(func.count()).select_from(ConsoleLog)+ total_result = await session.execute(count_stmt)+ total = total_result.scalar() or 0++ if total <= keep:+ return 0++ # Get IDs of logs to keep (most recent)+ keep_stmt = (+ select(ConsoleLog.id)+ .order_by(ConsoleLog.created_at.desc())+ .limit(keep)+ )+ keep_result = await session.execute(keep_stmt)+ keep_ids = {row[0] for row in keep_result.fetchall()}++ # Delete logs not in keep list+ delete_stmt = select(ConsoleLog).where(ConsoleLog.id.notin_(keep_ids))+ result = await session.execute(delete_stmt)+ old_logs = result.scalars().all()++ count = len(old_logs)+ for log in old_logs:+ await session.delete(log)++ await session.commit()+ if count > 0:+ logger.info("Cleaned up old console logs", deleted=count, kept=keep)+ return count++ except Exception as e:+ logger.error("Failed to cleanup old console logs", error=str(e))+ return 0+# ============================================================================# Cache Entries (SQLite-backed Redis alternative)# ============================================================================@@ -941,6 +1009,29 @@ class Database:logger.error("Failed to cleanup expired cache", error=str(e))return 0+ async def cleanup_old_cache(self, max_age_hours: int = 24) -> int:+ """Remove cache entries older than max_age_hours. Returns count deleted."""+ import time+ try:+ async with self.get_session() as session:+ cutoff_time = time.time() - (max_age_hours * 3600)+ stmt = select(CacheEntry).where(CacheEntry.created_at < cutoff_time)+ result = await session.execute(stmt)+ entries = result.scalars().all()++ count = len(entries)+ for entry in entries:+ await session.delete(entry)++ await session.commit()+ if count > 0:+ logger.info("Cleaned up old cache entries", count=count, max_age_hours=max_age_hours)+ return count++ except Exception as e:+ logger.error("Failed to cleanup old cache", error=str(e))+ return 0+async def cache_exists(self, key: str) -> bool:"""Check if cache key exists and is not expired."""import timediff --git a/server/core/health.py b/server/core/health.pynew file mode 100644index 00000000..a1ae2d4b--- /dev/null+++ b/server/core/health.py@@ -0,0 +1,121 @@+"""Health check utilities for daemon monitoring.++Provides uptime tracking and comprehensive health status for /health endpoint.+"""+import time+from typing import Dict, Any, TYPE_CHECKING++try:+ import psutil+ PSUTIL_AVAILABLE = True+except ImportError:+ PSUTIL_AVAILABLE = False++if TYPE_CHECKING:+ from core.config import Settings+ from core.database import Database+ from core.cache import CacheService++# Module-level startup time tracking+_startup_time: float = 0.0+++def set_startup_time() -> None:+ """Record the application startup time. Call once during lifespan startup."""+ global _startup_time+ _startup_time = time.time()+++def get_uptime() -> float:+ """Get uptime in seconds since startup."""+ return time.time() - _startup_time if _startup_time else 0.0+++def get_memory_mb() -> float:+ """Get current process memory usage in MB."""+ if not PSUTIL_AVAILABLE:+ return 0.0+ try:+ return psutil.Process().memory_info().rss / (1024 * 1024)+ except Exception:+ return 0.0+++def get_disk_percent(path: str = ".") -> float:+ """Get disk usage percentage for given path."""+ if not PSUTIL_AVAILABLE:+ return 0.0+ try:+ return psutil.disk_usage(path).percent+ except Exception:+ return 0.0+++def get_cpu_percent() -> float:+ """Get current process CPU usage percentage."""+ if not PSUTIL_AVAILABLE:+ return 0.0+ try:+ return psutil.Process().cpu_percent(interval=0.1)+ except Exception:+ return 0.0+++async def check_database(database: "Database") -> bool:+ """Check database connectivity."""+ try:+ async with database.get_session() as session:+ from sqlalchemy import text+ await session.execute(text("SELECT 1"))+ return True+ except Exception:+ return False+++async def check_cache(cache: "CacheService") -> bool:+ """Check cache connectivity."""+ try:+ test_key = "_health_check"+ await cache.set(test_key, "ok", ttl=10)+ result = await cache.get(test_key)+ await cache.delete(test_key)+ return result == "ok"+ except Exception:+ return False+++async def get_health_status(+ database: "Database",+ cache: "CacheService",+ settings: "Settings"+) -> Dict[str, Any]:+ """Get comprehensive health status for /health endpoint.++ Returns:+ Dict containing status, uptime, resource usage, and feature flags.+ """+ # Run health checks+ db_healthy = await check_database(database)+ cache_healthy = await check_cache(cache)++ # Determine overall status+ overall_status = "healthy" if (db_healthy and cache_healthy) else "degraded"++ return {+ "status": overall_status,+ "uptime_seconds": round(get_uptime(), 1),+ "memory_mb": round(get_memory_mb(), 1),+ "disk_percent": round(get_disk_percent(), 1),+ "cpu_percent": round(get_cpu_percent(), 1),+ "checks": {+ "database": db_healthy,+ "cache": cache_healthy,+ },+ "features": {+ "redis": settings.redis_enabled,+ "temporal": settings.temporal_enabled,+ "cleanup": settings.cleanup_enabled,+ "ws_logging": settings.ws_logging_enabled,+ },+ "psutil_available": PSUTIL_AVAILABLE,+ }diff --git a/server/examples/__init__.py b/server/examples/__init__.pynew file mode 100644index 00000000..8271408d--- /dev/null+++ b/server/examples/__init__.py@@ -0,0 +1 @@+# Example workflows packagediff --git a/server/gunicorn.conf.py b/server/gunicorn.conf.pynew file mode 100644index 00000000..d0f6f426--- /dev/null+++ b/server/gunicorn.conf.py@@ -0,0 +1,46 @@+"""Gunicorn configuration for production deployment.++Reads settings from environment variables (same as config.py).+No hardcoded values - everything from .env file.++Usage:+ gunicorn main:app -c gunicorn.conf.py+"""+import os+import multiprocessing++# Load from environment (same vars used by config.py)+host = os.getenv("HOST", "0.0.0.0")+port = os.getenv("PORT", "3010")+workers_env = os.getenv("WORKERS", "0") # 0 = auto-calculate+log_level = os.getenv("LOG_LEVEL", "INFO").lower()+debug = os.getenv("DEBUG", "false").lower() == "true"++# Bind - use HOST and PORT from .env+bind = f"{host}:{port}"++# Workers - from WORKERS env or auto-calculate+# WORKERS=0 means auto (2 * cpu + 1), WORKERS=N means use N+workers_count = int(workers_env)+workers = workers_count if workers_count > 0 else (multiprocessing.cpu_count() * 2 + 1)+worker_class = "uvicorn.workers.UvicornWorker"++# Timeouts - configurable via env+timeout = int(os.getenv("GUNICORN_TIMEOUT", "120"))+graceful_timeout = int(os.getenv("GUNICORN_GRACEFUL_TIMEOUT", "30"))+keepalive = int(os.getenv("GUNICORN_KEEPALIVE", "5"))++# Restart workers periodically to prevent memory leaks+max_requests = int(os.getenv("GUNICORN_MAX_REQUESTS", "10000"))+max_requests_jitter = int(os.getenv("GUNICORN_MAX_REQUESTS_JITTER", "1000"))++# Logging - use LOG_LEVEL from .env+accesslog = "-" if not debug else None+errorlog = "-"+loglevel = log_level++# Process naming+proc_name = "machina-backend"++# Preload app for faster worker startup (disable in debug for reload)+preload_app = not debugdiff --git a/server/main.py b/server/main.pyindex fdecf275..3231acde 100644--- a/server/main.py+++ b/server/main.py@@ -104,6 +104,21 @@ async def lifespan(app: FastAPI):setup_websocket_logging(loop)logger.info("WebSocket logging handler started")+ # Start cleanup service for long-running daemon+ from core.cleanup import CleanupService+ from core.health import set_startup_time+ cleanup_service = None+ if settings.cleanup_enabled:+ cleanup_service = CleanupService(+ database=container.database(),+ cache=container.cache(),+ settings=settings+ )+ await cleanup_service.start()++ # Record startup time for health reporting+ set_startup_time()+# Initialize Temporal if enabledtemporal_worker_manager = Noneif settings.temporal_enabled:@@ -165,6 +180,10 @@ async def lifespan(app: FastAPI):from services.android.manager import close_relay_clientawait close_relay_client(clear_stored_session=False)+ # Stop cleanup service+ if cleanup_service is not None:+ await cleanup_service.stop()+# Stop recovery sweeper firstif settings.redis_enabled:await recovery_sweeper.stop()@@ -239,12 +258,20 @@ app.include_router(webhook.router)@app.get("/health")async def health_check():- """Detailed health check."""+ """Detailed health check with resource monitoring."""from services import event_waiterfrom services.execution import get_recovery_sweeper+ from core.health import get_health_status, get_uptime, get_memory_mb, get_disk_percent, get_cpu_percentsweeper = get_recovery_sweeper()+ # Get comprehensive health status+ health = await get_health_status(+ database=container.database(),+ cache=container.cache(),+ settings=settings+ )+# Check Temporal statustemporal_status = {"enabled": settings.temporal_enabled,@@ -259,10 +286,18 @@ async def health_check():passreturn {- "status": "OK",+ "status": health["status"],"service": "python",- "version": "3.2.0", # Bumped for Temporal integration+ "version": "3.3.0", # Bumped for daemon service support"environment": "development" if settings.debug else "production",+ "uptime_seconds": health["uptime_seconds"],+ "resources": {+ "memory_mb": health["memory_mb"],+ "disk_percent": health["disk_percent"],+ "cpu_percent": health["cpu_percent"],+ },+ "checks": health["checks"],+ "features": health["features"],"redis_enabled": settings.redis_enabled,"event_waiter_mode": event_waiter.get_backend_mode(),"execution_engine": {diff --git a/server/models/database.py b/server/models/database.pyindex c4c43434..4f7fad6b 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -252,6 +252,7 @@ class UserSettings(SQLModel, table=True):sidebar_default_open: bool = Field(default=True)component_palette_default_open: bool = Field(default=True)console_panel_default_open: bool = Field(default=False)+ examples_loaded: bool = Field(default=False) # Track if example workflows were importedcreated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc),sa_column=Column(DateTime(timezone=True), server_default=func.now())diff --git a/server/models/nodes.py b/server/models/nodes.pyindex 08f0fbae..e6fa566e 100644--- a/server/models/nodes.py+++ b/server/models/nodes.py@@ -147,6 +147,22 @@ class WhatsAppReceiveParams(BaseNodeParams):include_media: bool = Field(default=False, alias="includeMediaData")+class WhatsAppDbParams(BaseNodeParams):+ """Parameters for WhatsApp database query node."""+ type: Literal["whatsappDb"]+ operation: Literal["chat_history", "search_groups", "get_group_info", "get_contact_info", "list_contacts", "check_contacts"] = "chat_history"+ # chat_history params+ phone_number: str = Field(default="", alias="phoneNumber")+ group_id: str = Field(default="", alias="groupId")+ group_name: str = Field(default="", alias="groupName")+ limit: int = Field(default=50, ge=1, le=500)+ offset: int = Field(default=0, ge=0)+ # search_groups params+ search_query: str = Field(default="", alias="searchQuery")+ # check_contacts params+ phone_numbers: str = Field(default="", alias="phoneNumbers")++# =============================================================================# CODE EXECUTOR NODE MODELS# =============================================================================@@ -277,7 +293,7 @@ MapsNodeParams = Annotated[# WhatsApp NodesWhatsAppNodeParams = Annotated[- Union[WhatsAppSendParams, WhatsAppReceiveParams],+ Union[WhatsAppSendParams, WhatsAppReceiveParams, WhatsAppDbParams],Field(discriminator="type")]@@ -319,7 +335,7 @@ KnownNodeParams = Annotated[# MapsCreateMapParams, GmapsLocationsParams, GmapsNearbyPlacesParams,- WhatsAppSendParams, WhatsAppReceiveParams,+ WhatsAppSendParams, WhatsAppReceiveParams, WhatsAppDbParams,# CodePythonExecutorParams, JavaScriptExecutorParams,# HTTPdiff --git a/server/routers/database.py b/server/routers/database.pyindex 0a216821..1f6b2b0d 100644--- a/server/routers/database.py+++ b/server/routers/database.py@@ -7,6 +7,7 @@ from typing import Dict, Any, Optional, Listfrom core.container import containerfrom core.database import Databasefrom core.logging import get_logger+from services.example_loader import import_examples_for_userlogger = get_logger(__name__)router = APIRouter(prefix="/api/database", tags=["database"])@@ -93,6 +94,21 @@ async def get_all_workflows():"""Get all workflows."""try:+ # Auto-load example workflows on first fetch+ user_id = "default"+ settings = await database.get_user_settings(user_id)++ if not settings or not settings.get("examples_loaded", False):+ # First time - import examples+ count = await import_examples_for_user(database)+ if count > 0:+ logger.info(f"Auto-loaded {count} example workflows")++ # Mark as loaded using existing save_user_settings+ current = settings or {}+ current["examples_loaded"] = True+ await database.save_user_settings(current, user_id)+workflows = await database.get_all_workflows()return {"success": True,diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 39eff719..58194140 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -244,6 +244,7 @@ async def handle_execute_node(data: Dict[str, Any], websocket: WebSocket) -> Dicnodes=data.get("nodes", []), edges=data.get("edges", []),session_id=data.get("session_id", "default"),workflow_id=workflow_id,+ outputs=data.get("outputs", {}), # Upstream node outputs for data flow)if result.get("success"):diff --git a/server/services/ai.py b/server/services/ai.pyindex 9324e28d..06eac87a 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1402,6 +1402,20 @@ class AIService:logger.debug(f"[LangGraph] Built {len(tools)} tools")+ # Auto-inject check_delegated_tasks tool when delegation tools present+ if any(name.startswith('delegate_to_') for name in tool_configs):+ check_info = {+ 'node_type': '_builtin_check_delegated_tasks',+ 'node_id': f'{node_id}_check_tasks',+ 'parameters': {},+ 'label': 'Check Delegated Tasks',+ }+ check_tool, check_config = await self._build_tool_from_node(check_info)+ if check_tool:+ tools.append(check_tool)+ tool_configs[check_tool.name] = check_config+ logger.debug(f"[LangGraph] Auto-injected check_delegated_tasks tool")+# Create tool executor callbackasync def tool_executor(tool_name: str, tool_args: Dict) -> Any:"""Execute a tool by name."""@@ -1438,6 +1452,7 @@ class AIService:# These allow child agents to execute with their own toolsconfig['ai_service'] = selfconfig['database'] = self.database+ config['parent_node_id'] = node_id # For delegation result trackingif context:config['nodes'] = context.get('nodes', [])config['edges'] = context.get('edges', [])@@ -1709,6 +1724,20 @@ class AIService:logger.debug(f"[ChatAgent] Built {len(all_tools)} tools from tool_data")+ # Auto-inject check_delegated_tasks tool when delegation tools present+ if any(name.startswith('delegate_to_') for name in tool_node_configs):+ check_info = {+ 'node_type': '_builtin_check_delegated_tasks',+ 'node_id': f'{node_id}_check_tasks',+ 'parameters': {},+ 'label': 'Check Delegated Tasks',+ }+ check_tool, check_config = await self._build_tool_from_node(check_info)+ if check_tool:+ all_tools.append(check_tool)+ tool_node_configs[check_tool.name] = check_config+ logger.debug(f"[ChatAgent] Auto-injected check_delegated_tasks tool")+logger.debug(f"[ChatAgent] Total tools available: {len(all_tools)}")# Debug: log all tool schemas to verify they're correctfor t in all_tools:@@ -1861,6 +1890,7 @@ class AIService:# These allow child agents to execute with their own toolsconfig['ai_service'] = selfconfig['database'] = self.database+ config['parent_node_id'] = node_id # For delegation result trackingif context:config['nodes'] = context.get('nodes', [])config['edges'] = context.get('edges', [])@@ -2064,6 +2094,9 @@ class AIService:'gmaps_nearby_places': 'nearby_places','timer': 'timer','cronScheduler': 'cron_scheduler',+ # Built-in check tool for delegation results+ '_builtin_check_delegated_tasks': 'check_delegated_tasks',+ # Agent delegation tools'aiAgent': 'delegate_to_ai_agent','chatAgent': 'delegate_to_chat_agent','android_agent': 'delegate_to_android_agent',@@ -2107,18 +2140,21 @@ class AIService:'gmaps_nearby_places': 'Search for nearby places (restaurants, hospitals, banks, etc.) using Google Maps Places API.','timer': 'Wait/sleep for a specified duration. Specify duration (1-3600) and unit (seconds, minutes, or hours). Returns timestamp and elapsed time after waiting.','cronScheduler': 'Schedule a delayed or recurring execution. Supports seconds, minutes, hours, daily, weekly, monthly frequencies with timezone. Use frequency to set schedule type, then set the relevant interval/time parameters.',- 'aiAgent': 'Delegate a task to another AI Agent. The agent works independently without blocking.',- 'chatAgent': 'Delegate a task to a Chat Agent. The agent works independently without blocking.',- 'android_agent': 'Delegate a task to an Android Control Agent for device automation. Works independently.',- 'coding_agent': 'Delegate a task to a Coding Agent for code execution. Works independently.',- 'web_agent': 'Delegate a task to a Web Control Agent for web automation. Works independently.',- 'task_agent': 'Delegate a task to a Task Management Agent for task automation. Works independently.',- 'social_agent': 'Delegate a task to a Social Media Agent for social messaging. Works independently.',- 'travel_agent': 'Delegate a task to a Travel Agent for travel planning and itinerary building. Works independently.',- 'tool_agent': 'Delegate a task to a Tool Agent for multi-tool orchestration and complex task execution. Works independently.',- 'productivity_agent': 'Delegate a task to a Productivity Agent for scheduling, reminders, and workflow automation. Works independently.',- 'payments_agent': 'Delegate a task to a Payments Agent for payment processing, invoice generation, and financial operations. Works independently.',- 'consumer_agent': 'Delegate a task to a Consumer Agent for customer support, product recommendations, and order management. Works independently.',+ # Built-in check tool for delegation results+ '_builtin_check_delegated_tasks': 'Check status and retrieve results of previously delegated tasks.',+ # Agent delegation tools+ 'aiAgent': 'Delegate a task to another AI Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'chatAgent': 'Delegate a task to a Chat Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'android_agent': 'Delegate to Android Control Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'coding_agent': 'Delegate to Coding Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'web_agent': 'Delegate to Web Control Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'task_agent': 'Delegate to Task Management Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'social_agent': 'Delegate to Social Media Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'travel_agent': 'Delegate to Travel Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'tool_agent': 'Delegate to Tool Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'productivity_agent': 'Delegate to Productivity Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'payments_agent': 'Delegate to Payments Agent. Returns task_id. Use check_delegated_tasks for results.',+ 'consumer_agent': 'Delegate to Consumer Agent. Returns task_id. Use check_delegated_tasks for results.',# Android service nodes (direct tool usage)'batteryMonitor': 'Monitor Android battery status, level, charging state, temperature, and health.','networkMonitor': 'Monitor Android network connectivity, type, and internet availability.',@@ -2615,6 +2651,45 @@ class AIService:return NearbyPlacesSchema+ # Task Manager schema (dual-purpose: AI tool + workflow node)+ if node_type == 'taskManager':+ class TaskManagerSchema(BaseModel):+ """Manage delegated tasks - list, check status, mark done.++ Use this to track sub-agent tasks you've delegated.+ - list_tasks: See all active and completed tasks+ - get_task: Get details on a specific task+ - mark_done: Clean up a completed task from tracking+ """+ operation: str = Field(+ description="Operation: 'list_tasks', 'get_task', or 'mark_done'"+ )+ task_id: Optional[str] = Field(+ default=None,+ description="Task ID (required for get_task/mark_done)"+ )+ status_filter: Optional[str] = Field(+ default=None,+ description="Filter by status: 'running', 'completed', or 'error' (for list_tasks)"+ )++ return TaskManagerSchema++ # Check delegated tasks schema (built-in tool for result retrieval)+ if node_type == '_builtin_check_delegated_tasks':+ class CheckDelegatedTasksSchema(BaseModel):+ """Check on previously delegated tasks and retrieve their results.++ Call this to see if delegated agents have completed their work.+ Returns status and results for each task.+ """+ task_ids: Optional[List[str]] = Field(+ default=None,+ description="Specific task IDs to check. Omit to get ALL delegated tasks."+ )++ return CheckDelegatedTasksSchema+# AI Agent delegation schema (fire-and-forget async delegation)if node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'):agent_label = params.get('label', node_type)@@ -2622,8 +2697,9 @@ class AIService:class DelegateToAgentSchema(BaseModel):"""Delegate a task to another AI Agent (non-blocking).- The child agent will work independently without blocking the parent.- Use this to assign subtasks to specialized agents.+ The child agent works independently in the background.+ Returns a task_id immediately. Use 'check_delegated_tasks'+ tool to check status and retrieve results when ready."""task: str = Field(description=f"The task/instruction to delegate to '{agent_label}'. Be specific about what you want done."diff --git a/server/services/auth.py b/server/services/auth.pyindex 3842bd2e..e2a0df67 100644--- a/server/services/auth.py+++ b/server/services/auth.py@@ -86,7 +86,12 @@ class AuthService:api_key_record = await self.database.get_api_key_by_provider(provider, session_id)if api_key_record and api_key_record.is_valid:# Check if not expired (30 days)- if datetime.now(timezone.utc) - api_key_record.last_validated < timedelta(days=30):+ # Ensure both datetimes are timezone-aware for comparison+ # SQLite may return offset-naive datetimes+ last_validated = api_key_record.last_validated+ if last_validated.tzinfo is None:+ last_validated = last_validated.replace(tzinfo=timezone.utc)+ if datetime.now(timezone.utc) - last_validated < timedelta(days=30):return self.decrypt_api_key(api_key_record.key_encrypted)return Nonediff --git a/server/services/event_waiter.py b/server/services/event_waiter.pyindex 4bbb5912..5e6a3eaa 100644--- a/server/services/event_waiter.py+++ b/server/services/event_waiter.py@@ -105,6 +105,11 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {event_type='chat_message_received',display_name='Chat Message'),+ 'taskTrigger': TriggerConfig(+ node_type='taskTrigger',+ event_type='task_completed',+ display_name='Task Completed'+ ),# Future triggers - just add to registry:# 'emailTrigger': TriggerConfig('emailTrigger', 'email_received', 'Email'),# 'mqttTrigger': TriggerConfig('mqttTrigger', 'mqtt_message', 'MQTT Message'),@@ -282,11 +287,61 @@ def build_chat_filter(params: Dict) -> Callable[[Dict], bool]:return matches+def build_task_completed_filter(params: Dict) -> Callable[[Dict], bool]:+ """Build filter function for task completed events.++ Filters by:+ - task_id: Specific task ID to watch (optional)+ - agent_name: Filter by child agent name (optional)+ - status_filter: 'all', 'completed', 'error' (default: 'all')+ - parent_node_id: Filter by parent node (optional, for scoping)++ Args:+ params: Node parameters++ Returns:+ Filter function that checks if event matches criteria+ """+ task_id_filter = params.get('task_id', '')+ agent_name_filter = params.get('agent_name', '')+ status_filter = params.get('status_filter', 'all') # all, completed, error+ parent_node_id = params.get('parent_node_id', '')++ def matches(data: Dict) -> bool:+ # Task ID filter (exact match if specified)+ if task_id_filter:+ if data.get('task_id') != task_id_filter:+ return False++ # Agent name filter (contains match)+ if agent_name_filter:+ event_agent = data.get('agent_name', '')+ if agent_name_filter.lower() not in event_agent.lower():+ return False++ # Status filter+ event_status = data.get('status', '')+ if status_filter == 'completed' and event_status != 'completed':+ return False+ if status_filter == 'error' and event_status != 'error':+ return False++ # Parent node filter (for scoping to specific parent agent)+ if parent_node_id:+ if data.get('parent_node_id') != parent_node_id:+ return False++ return True++ return matches++# Registry of filter builders per trigger typeFILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {'whatsappReceive': build_whatsapp_filter,'webhookTrigger': build_webhook_filter,'chatTrigger': build_chat_filter,+ 'taskTrigger': build_task_completed_filter,}diff --git a/server/services/example_loader.py b/server/services/example_loader.pynew file mode 100644index 00000000..3e7409f3--- /dev/null+++ b/server/services/example_loader.py@@ -0,0 +1,60 @@+"""Example workflow loader - reuses existing database.save_workflow()"""+import json+import logging+from pathlib import Path+from typing import List, Dict, Any++logger = logging.getLogger(__name__)++# Workflows folder at project root (parent of server/)+EXAMPLES_DIR = Path(__file__).parent.parent.parent / "workflows"+++def get_example_workflows() -> List[Dict[str, Any]]:+ """Load all example workflow JSON files from disk."""+ examples = []+ if not EXAMPLES_DIR.exists():+ logger.warning(f"Examples directory not found: {EXAMPLES_DIR}")+ return examples++ for file in sorted(EXAMPLES_DIR.glob("*.json")):+ try:+ with open(file, encoding="utf-8") as f:+ workflow = json.load(f)+ workflow["_filename"] = file.name # Track source+ examples.append(workflow)+ logger.debug(f"Loaded example: {file.name}")+ except (json.JSONDecodeError, IOError) as e:+ logger.error(f"Failed to load {file}: {e}")++ return examples+++async def import_examples_for_user(database) -> int:+ """Import all examples using existing database.save_workflow().++ Returns count of workflows imported.+ """+ examples = get_example_workflows()+ imported = 0++ for example in examples:+ # Use ID from JSON, prefixed with 'example_' for clarity+ workflow_id = f"example_{example.get('id', 'unknown')}"++ # Reuse existing save_workflow method+ success = await database.save_workflow(+ workflow_id=workflow_id,+ name=example.get("name", "Example Workflow"),+ description=example.get("description"),+ data={+ "nodes": example.get("nodes", []),+ "edges": example.get("edges", [])+ }+ )++ if success:+ imported += 1+ logger.info(f"Imported example: {example.get('name')}")++ return importeddiff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex c7d8c335..b5c28a7a 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -84,6 +84,7 @@ from .document import (# Tool execution handlers (for AI Agent tool calling)from .tools import (execute_tool,+ handle_task_manager,)__all__ = [@@ -129,4 +130,5 @@ __all__ = ['handle_vector_store',# Tools'execute_tool',+ 'handle_task_manager',]diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.pyindex 36e5b02c..24bdcda7 100644--- a/server/services/handlers/ai.py+++ b/server/services/handlers/ai.py@@ -2,7 +2,7 @@from typing import Dict, Any, List, Optional, Tuple, TYPE_CHECKINGfrom core.logging import get_logger-from constants import ANDROID_SERVICE_NODE_TYPES+from constants import ANDROID_SERVICE_NODE_TYPES, AI_AGENT_TYPESif TYPE_CHECKING:from services.ai import AIService@@ -16,14 +16,15 @@ async def _collect_agent_connections(context: Dict[str, Any],database: "Database",log_prefix: str = "[Agent]"-) -> Tuple[Optional[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], Optional[Dict[str, Any]]]:- """Shared logic for collecting memory, skill, tool, and input data from connected nodes.+) -> Tuple[Optional[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]], Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:+ """Shared logic for collecting memory, skill, tool, input, and task data from connected nodes.Scans edges targeting the given node and collects:- Memory data from input-memory handle (simpleMemory nodes)- Skill data from input-skill handle (skill nodes)- Tool data from input-tools handle (tool nodes, including androidTool Sub-Node pattern)- Input data from input-main or input-chat handle (for auto-prompting fallback)+ - Task data from input-task handle (taskTrigger nodes for delegated task results)Args:node_id: The agent node ID to collect connections for@@ -32,7 +33,7 @@ async def _collect_agent_connections(log_prefix: Prefix for log messages (e.g., "[AI Agent]" or "[Chat Agent]")Returns:- Tuple of (memory_data, skill_data, tool_data, input_data)+ Tuple of (memory_data, skill_data, tool_data, input_data, task_data)"""nodes = context.get('nodes')edges = context.get('edges')@@ -42,11 +43,12 @@ async def _collect_agent_connections(skill_data: List[Dict[str, Any]] = []tool_data: List[Dict[str, Any]] = []input_data: Optional[Dict[str, Any]] = None+ task_data: Optional[Dict[str, Any]] = Nonelogger.info(f"{log_prefix} Processing node {node_id}, edges={len(edges) if edges else 0}, nodes={len(nodes) if nodes else 0}, workflow_id={workflow_id}")if not edges or not nodes:- return memory_data, skill_data, tool_data, input_data+ return memory_data, skill_data, tool_data, input_data, task_data# Log incoming edges for debuggingincoming_edges = [e for e in edges if e.get('target') == node_id]@@ -212,14 +214,75 @@ async def _collect_agent_connections(input_data = source_outputlogger.debug(f"{log_prefix} Input from {source_node.get('type')}: {list(source_output.keys()) if isinstance(source_output, dict) else type(source_output)}")+ # Task data detection - taskTrigger nodes connected to input-task handle+ # Used to receive results from delegated child agents+ elif target_handle == 'input-task':+ logger.info(f"{log_prefix} Found input-task edge from {source_node_id} (type={source_node.get('type')})")+ all_outputs = context.get('outputs', {})+ logger.info(f"{log_prefix} Available outputs in context: {list(all_outputs.keys())}")+ source_output = all_outputs.get(source_node_id)+ logger.info(f"{log_prefix} Source output for {source_node_id}: {source_output is not None}, type={type(source_output).__name__ if source_output else 'None'}")+ if source_output:+ # Handle nested result structure - taskTrigger may return {"result": {...}} or flat dict+ if isinstance(source_output, dict) and 'result' in source_output and isinstance(source_output.get('result'), dict):+ # Nested structure - extract inner result+ task_data = source_output.get('result')+ logger.info(f"{log_prefix} Extracted nested task_data from result key")+ else:+ task_data = source_output+ logger.info(f"{log_prefix} Task completion data: task_id={task_data.get('task_id')}, status={task_data.get('status')}, agent_name={task_data.get('agent_name')}")+# Log collection results- logger.info(f"{log_prefix} Collected: {len(skill_data)} skills, {len(tool_data)} tools, memory={'yes' if memory_data else 'no'}, input={'yes' if input_data else 'no'}")+ logger.info(f"{log_prefix} Collected: {len(skill_data)} skills, {len(tool_data)} tools, memory={'yes' if memory_data else 'no'}, input={'yes' if input_data else 'no'}, task={'yes' if task_data else 'no'}")for sd in skill_data:logger.debug(f"{log_prefix} Skill: type={sd.get('node_type')}, label={sd.get('label')}")for td in tool_data:logger.info(f"{log_prefix} Tool: type={td.get('node_type')}, node_id={td.get('node_id')}")- return memory_data, skill_data, tool_data, input_data+ return memory_data, skill_data, tool_data, input_data, task_data+++def _format_task_context(task_data: Dict[str, Any]) -> str:+ """Format task completion data as context for the agent.++ Args:+ task_data: Task completion data from taskTrigger node++ Returns:+ Formatted string to prepend to agent prompt+ """+ status = task_data.get('status', 'unknown')+ agent_name = task_data.get('agent_name', 'Unknown Agent')+ task_id = task_data.get('task_id', '')++ if status == 'completed':+ result = task_data.get('result', 'No result provided')+ return f"""A delegated task has completed:+- Agent: {agent_name}+- Task ID: {task_id}+- Status: Completed Successfully+- Result: {result}++IMPORTANT: This task is COMPLETE. Do NOT delegate or call any agent tools.+Simply report this result to the user in a natural, conversational way."""++ elif status == 'error':+ error = task_data.get('error', 'Unknown error')+ return f"""A delegated task has failed:+- Agent: {agent_name}+- Task ID: {task_id}+- Status: Error+- Error: {error}++IMPORTANT: This task has FAILED. Do NOT retry or delegate again.+Report this error to the user and suggest next steps if appropriate."""++ else:+ return f"""Task update received:+- Agent: {agent_name}+- Task ID: {task_id}+- Status: {status}+- Data: {task_data}"""async def handle_ai_agent(@@ -245,11 +308,32 @@ async def handle_ai_agent("""workflow_id = context.get('workflow_id')- # Collect connected memory, skill, tool, and input nodes using shared base function- memory_data, skill_data, tool_data, input_data = await _collect_agent_connections(+ # Collect connected memory, skill, tool, input, and task nodes using shared base function+ memory_data, skill_data, tool_data, input_data, task_data = await _collect_agent_connections(node_id, context, database, log_prefix="[AI Agent]")+ # If task data is present, format it as context for the agent+ if task_data:+ task_context = _format_task_context(task_data)+ original_prompt = parameters.get('prompt', '')+ parameters = {**parameters, 'prompt': f"{task_context}\n\n{original_prompt}"}+ logger.info(f"[AI Agent] Task context injected for task_id={task_data.get('task_id')}")++ # CRITICAL FIX: Strip delegation tools when handling task completion+ # This prevents LLM confusion - tools bound but told not to use them+ task_status = task_data.get('status', '')+ if task_status in ('completed', 'error') and tool_data:+ original_tool_count = len(tool_data)+ # Filter out AI agent tools (delegation tools)+ tool_data = [+ t for t in tool_data+ if t.get('node_type') not in AI_AGENT_TYPES+ ]+ filtered_count = original_tool_count - len(tool_data)+ if filtered_count > 0:+ logger.info(f"[AI Agent] Stripped {filtered_count} delegation tools for task completion handling")+# Auto-use input data if prompt is empty (fallback for trigger nodes)if not parameters.get('prompt') and input_data:prompt = (@@ -306,11 +390,32 @@ async def handle_chat_agent("""workflow_id = context.get('workflow_id')- # Collect connected memory, skill, tool, and input nodes using shared base function- memory_data, skill_data, tool_data, input_data = await _collect_agent_connections(+ # Collect connected memory, skill, tool, input, and task nodes using shared base function+ memory_data, skill_data, tool_data, input_data, task_data = await _collect_agent_connections(node_id, context, database, log_prefix="[Chat Agent]")+ # If task data is present, format it as context for the agent+ if task_data:+ task_context = _format_task_context(task_data)+ original_prompt = parameters.get('prompt', '')+ parameters = {**parameters, 'prompt': f"{task_context}\n\n{original_prompt}"}+ logger.info(f"[Chat Agent] Task context injected for task_id={task_data.get('task_id')}")++ # CRITICAL FIX: Strip delegation tools when handling task completion+ # This prevents LLM confusion - tools bound but told not to use them+ task_status = task_data.get('status', '')+ if task_status in ('completed', 'error') and tool_data:+ original_tool_count = len(tool_data)+ # Filter out AI agent tools (delegation tools)+ tool_data = [+ t for t in tool_data+ if t.get('node_type') not in AI_AGENT_TYPES+ ]+ filtered_count = original_tool_count - len(tool_data)+ if filtered_count > 0:+ logger.info(f"[Chat Agent] Stripped {filtered_count} delegation tools for task completion handling")+# Auto-use input data if prompt is empty (fallback for trigger nodes)if not parameters.get('prompt') and input_data:prompt = (diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex f3ee9223..be8aefdd 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -9,7 +9,7 @@ import mathimport jsonimport asyncioimport uuid-from typing import Dict, Any, Optional, TYPE_CHECKING+from typing import Dict, Any, Optional, List, TYPE_CHECKINGfrom core.logging import get_loggerfrom constants import ANDROID_SERVICE_NODE_TYPES@@ -23,6 +23,10 @@ logger = get_logger(__name__)# Track running delegated tasks for status checking_delegated_tasks: Dict[str, asyncio.Task] = {}+# In-memory cache of delegation results (fast path, survives task cleanup)+# Follows Celery AsyncResult / Ray ObjectRef pattern+_delegation_results: Dict[str, Dict[str, Any]] = {}+async def execute_tool(tool_name: str, tool_args: Dict[str, Any],config: Dict[str, Any]) -> Dict[str, Any]:@@ -115,6 +119,15 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],if node_type == 'gmaps_nearby_places':return await _execute_nearby_places(tool_args, config.get('parameters', {}))+ # Task Manager (dual-purpose: AI tool + workflow node)+ if node_type == 'taskManager':+ return await _execute_task_manager(tool_args, config)++ # Built-in: Check delegated task results+ # Auto-injected when parent has delegation tools+ if node_type == '_builtin_check_delegated_tasks':+ return await _execute_check_delegated_tasks(tool_args, config)+# AI Agent delegation (fire-and-forget async delegation)# Includes specialized agents: android_agent, coding_agent, web_agent, task_agent, social_agentif node_type in ('aiAgent', 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent', 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent'):@@ -1246,6 +1259,42 @@ async def _execute_delegated_agent(args: Dict[str, Any],workflow_id=workflow_id)+ # Cache result for parent retrieval (Layer 2: in-memory)+ _delegation_results[task_id] = {+ "task_id": task_id,+ "status": "completed",+ "agent_name": agent_label,+ "agent_node_id": node_id,+ "result": result.get('result', {}).get('response', str(result.get('result', ''))),+ "error": None,+ }++ # Persist to DB (Layer 3: cross-restart via existing NodeOutput)+ if database:+ await database.save_node_output(+ node_id=node_id,+ session_id=f"delegation_{task_id}",+ output_name="delegation_result",+ data={+ "task_id": task_id,+ "parent_node_id": config.get('parent_node_id', ''),+ "agent_name": agent_label,+ "status": "completed",+ "result": result.get('result', {}),+ }+ )++ # Dispatch task_completed event for trigger nodes+ await broadcaster.send_custom_event('task_completed', {+ 'task_id': task_id,+ 'status': 'completed',+ 'agent_name': agent_label,+ 'agent_node_id': node_id,+ 'parent_node_id': config.get('parent_node_id', ''),+ 'result': result.get('result', {}).get('response', str(result.get('result', ''))),+ 'workflow_id': workflow_id,+ })+return resultexcept Exception as e:@@ -1260,6 +1309,43 @@ async def _execute_delegated_agent(args: Dict[str, Any],},workflow_id=workflow_id)++ # Cache error for parent retrieval (Layer 2: in-memory)+ _delegation_results[task_id] = {+ "task_id": task_id,+ "status": "error",+ "agent_name": agent_label,+ "agent_node_id": node_id,+ "result": None,+ "error": str(e),+ }++ # Persist to DB (Layer 3: cross-restart)+ if database:+ await database.save_node_output(+ node_id=node_id,+ session_id=f"delegation_{task_id}",+ output_name="delegation_result",+ data={+ "task_id": task_id,+ "parent_node_id": config.get('parent_node_id', ''),+ "agent_name": agent_label,+ "status": "error",+ "error": str(e),+ }+ )++ # Dispatch task_completed event for trigger nodes (error case)+ await broadcaster.send_custom_event('task_completed', {+ 'task_id': task_id,+ 'status': 'error',+ 'agent_name': agent_label,+ 'agent_node_id': node_id,+ 'parent_node_id': config.get('parent_node_id', ''),+ 'error': str(e),+ 'workflow_id': workflow_id,+ })+return {"success": False, "error": str(e)}finally:@@ -1281,20 +1367,268 @@ async def _execute_delegated_agent(args: Dict[str, Any],}-def get_delegated_task_status(task_id: str) -> Dict[str, Any]:- """Check status of a delegated task (optional utility).+async def get_delegated_task_status(task_ids: Optional[List[str]] = None,+ database=None) -> Dict[str, Any]:+ """Check status and retrieve results of delegated tasks.++ 3-layer lookup: live tasks -> memory cache -> DB (NodeOutput).+ Follows Celery AsyncResult / Ray ObjectRef pattern.Args:- task_id: The task_id returned from delegation+ task_ids: Optional list of specific task IDs to check. If None, returns all known tasks.+ database: Database instance for Layer 3 (SQLite) lookup.Returns:- Status dict with task state+ Dict with 'tasks' list containing status and results for each task.+ """+ if not task_ids:+ # Return all known from memory+ task_ids = list(set(+ list(_delegated_tasks.keys()) + list(_delegation_results.keys())+ ))++ tasks = []+ db_lookup_ids = []++ for tid in task_ids:+ # Layer 1: Live asyncio.Task (still running or just finished)+ live_task = _delegated_tasks.get(tid)+ if live_task is not None:+ if not live_task.done():+ tasks.append({"task_id": tid, "status": "running"})+ else:+ # Task finished -- extract result via task.result()+ try:+ result = live_task.result()+ response = result.get('result', {}).get('response', str(result.get('result', '')))+ tasks.append({"task_id": tid, "status": "completed", "result": response})+ except Exception as e:+ tasks.append({"task_id": tid, "status": "error", "error": str(e)})+ continue++ # Layer 2: In-memory result cache+ cached = _delegation_results.get(tid)+ if cached:+ tasks.append(cached)+ continue++ # Layer 3: Need DB lookup+ db_lookup_ids.append(tid)++ # DB fallback for results not in memory (cross-restart)+ if db_lookup_ids and database:+ for tid in list(db_lookup_ids):+ db_result = await database.get_node_output_by_session(+ session_id=f"delegation_{tid}",+ output_name="delegation_result"+ )+ if db_result:+ data = db_result.get('data', {})+ result_data = data.get("result", {})+ response_text = result_data.get("response", str(result_data)) if isinstance(result_data, dict) else str(result_data)+ tasks.append({+ "task_id": tid,+ "status": data.get("status", "completed"),+ "agent_name": data.get("agent_name", ""),+ "result": response_text,+ "error": data.get("error"),+ })+ db_lookup_ids.remove(tid)++ # Remaining IDs not found anywhere+ for tid in db_lookup_ids:+ tasks.append({"task_id": tid, "status": "not_found"})++ return {"tasks": tasks}+++async def _execute_check_delegated_tasks(args: Dict[str, Any],+ config: Dict[str, Any]) -> Dict[str, Any]:+ """LLM-callable tool: check on delegated child agents.++ Returns status and results for previously delegated tasks.+ Follows Celery AsyncResult / Ray ObjectRef patterns."""- task = _delegated_tasks.get(task_id)+ task_ids = args.get('task_ids')+ database = config.get('database')+ result = await get_delegated_task_status(task_ids=task_ids, database=database)++ formatted = []+ for task in result.get("tasks", []):+ entry = {+ "task_id": task.get("task_id"),+ "status": task.get("status"),+ "agent_name": task.get("agent_name"),+ }+ if task.get("status") == "completed":+ text = str(task.get("result", ""))+ entry["result"] = text[:4000] + "... [truncated]" if len(text) > 4000 else text+ elif task.get("status") == "error":+ entry["error"] = task.get("error")+ elif task.get("status") == "running":+ entry["message"] = f"Agent '{task.get('agent_name', 'unknown')}' is still working"+ formatted.append(entry)- if task is None:- return {"status": "not_found_or_completed", "task_id": task_id}- elif task.done():- return {"status": "completed", "task_id": task_id}- else:- return {"status": "running", "task_id": task_id}+ return {+ "total_tasks": len(formatted),+ "completed": sum(1 for t in formatted if t.get("status") == "completed"),+ "running": sum(1 for t in formatted if t.get("status") == "running"),+ "errors": sum(1 for t in formatted if t.get("status") == "error"),+ "tasks": formatted,+ }+++async def _execute_task_manager(+ tool_args: Dict[str, Any],+ config: Dict[str, Any]+) -> Dict[str, Any]:+ """Execute task manager operations.++ Dual-purpose: works as AI tool (LLM fills args) or workflow node (uses params).++ Operations:+ - list_tasks: List all active and completed delegated tasks+ - get_task: Get status details for a specific task+ - mark_done: Remove a task from active tracking++ Args:+ tool_args: Arguments from LLM tool call (operation, task_id, status_filter)+ config: Tool configuration with node parameters++ Returns:+ Dict with operation results+ """+ # Merge tool_args with node parameters (tool_args takes precedence)+ params = config.get('parameters', {})+ operation = tool_args.get('operation') or params.get('operation', 'list_tasks')+ task_id = tool_args.get('task_id') or params.get('task_id')+ status_filter = tool_args.get('status_filter') or params.get('status_filter')+ database = config.get('database')++ logger.debug(f"[TaskManager] Operation: {operation}, task_id: {task_id}, filter: {status_filter}")++ if operation == 'list_tasks':+ # Collect all tasks from _delegated_tasks and _delegation_results+ tasks = []++ # Active tasks from asyncio.Task tracking+ for tid, task in _delegated_tasks.items():+ if task.done():+ try:+ if task.cancelled():+ status = 'cancelled'+ elif task.exception():+ status = 'error'+ else:+ status = 'completed'+ except Exception:+ status = 'completed'+ else:+ status = 'running'++ tasks.append({+ 'task_id': tid,+ 'status': status,+ 'active': True+ })++ # Completed tasks from in-memory cache+ for tid, result in _delegation_results.items():+ if tid not in [t['task_id'] for t in tasks]:+ tasks.append({+ 'task_id': tid,+ 'status': result.get('status', 'completed'),+ 'agent_name': result.get('agent_name'),+ 'result_summary': str(result.get('result', ''))[:200],+ 'active': False+ })++ # Apply status filter+ if status_filter:+ tasks = [t for t in tasks if t.get('status') == status_filter]++ return {+ 'success': True,+ 'operation': 'list_tasks',+ 'tasks': tasks,+ 'count': len(tasks),+ 'running': sum(1 for t in tasks if t.get('status') == 'running'),+ 'completed': sum(1 for t in tasks if t.get('status') == 'completed'),+ 'errors': sum(1 for t in tasks if t.get('status') == 'error')+ }++ elif operation == 'get_task':+ if not task_id:+ return {'success': False, 'error': 'task_id is required for get_task operation'}++ # Use existing get_delegated_task_status for detailed lookup+ result = await get_delegated_task_status(task_ids=[task_id], database=database)+ tasks = result.get('tasks', [])++ if not tasks:+ return {+ 'success': False,+ 'error': f'Task {task_id} not found',+ 'task_id': task_id+ }++ task_info = tasks[0]+ return {+ 'success': True,+ 'operation': 'get_task',+ 'task_id': task_id,+ 'status': task_info.get('status'),+ 'agent_name': task_info.get('agent_name'),+ 'result': task_info.get('result'),+ 'error': task_info.get('error')+ }++ elif operation == 'mark_done':+ if not task_id:+ return {'success': False, 'error': 'task_id is required for mark_done operation'}++ # Remove from active tracking+ removed = False+ if task_id in _delegated_tasks:+ del _delegated_tasks[task_id]+ removed = True+ if task_id in _delegation_results:+ del _delegation_results[task_id]+ removed = True++ return {+ 'success': True,+ 'operation': 'mark_done',+ 'task_id': task_id,+ 'removed': removed,+ 'message': f'Task {task_id} marked as done and removed from tracking' if removed else f'Task {task_id} was not in active tracking'+ }++ return {'success': False, 'error': f'Unknown operation: {operation}'}+++async def handle_task_manager(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Handle taskManager as workflow node.++ Wrapper for _execute_task_manager that conforms to the standard+ workflow node handler signature.++ Args:+ node_id: The node ID+ node_type: Should be 'taskManager'+ parameters: Node parameters (operation, task_id, status_filter)+ context: Execution context++ Returns:+ Task manager operation results+ """+ config = {+ 'parameters': parameters,+ 'database': context.get('database')+ }+ return await _execute_task_manager({}, config)diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex 2dce9900..b9ac1c7a 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -35,6 +35,7 @@ from services.handlers import (handle_social_receive, handle_social_send,handle_http_scraper, handle_file_downloader, handle_document_parser,handle_text_chunker, handle_embedding_generator, handle_vector_store,+ handle_task_manager,)if TYPE_CHECKING:@@ -145,6 +146,8 @@ class NodeExecutor:'textChunker': handle_text_chunker,'embeddingGenerator': handle_embedding_generator,'vectorStore': handle_vector_store,+ # Task management+ 'taskManager': handle_task_manager,# Note: 'console' handled in _dispatch with connected_outputs}diff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.pyindex 55e6fc7f..5c86c1e5 100644--- a/server/services/temporal/activities.py+++ b/server/services/temporal/activities.py@@ -208,6 +208,9 @@ class NodeExecutionActivities:"edges": context.get("edges", []),"session_id": context.get("session_id", "default"),"workflow_id": context.get("workflow_id"),+ # CRITICAL: Pass upstream node outputs for downstream nodes to access+ # This enables taskTrigger -> chatAgent data flow via input-task handle+ "outputs": context.get("inputs", {}),}print(f"[Activity] WebSocket execute for {node_id}")diff --git a/server/services/workflow.py b/server/services/workflow.pyindex dae89672..4723b3d9 100644--- a/server/services/workflow.py+++ b/server/services/workflow.py@@ -142,6 +142,7 @@ class WorkflowService:session_id: str = "default",execution_id: str = None,workflow_id: str = None,+ outputs: Dict[str, Any] = None,) -> Dict[str, Any]:"""Execute a single workflow node."""context = {@@ -151,6 +152,7 @@ class WorkflowService:"execution_id": execution_id,"workflow_id": workflow_id, # For per-workflow status scoping (n8n pattern)"get_output_fn": self.get_node_output,+ "outputs": outputs or {}, # Upstream node outputs for data flow (e.g., taskTrigger -> chatAgent)}return await self._node_executor.execute(node_id=node_id,diff --git a/server/skills/assistant/subagent-skill/SKILL.md b/server/skills/assistant/subagent-skill/SKILL.mdnew file mode 100644index 00000000..7f6305e8--- /dev/null+++ b/server/skills/assistant/subagent-skill/SKILL.md@@ -0,0 +1,173 @@+---+name: subagent-skill+description: Manage sub-agent delegation, handle task completion events, and coordinate multi-agent workflows.+metadata:+ author: machina+ version: "1.0"+ category: assistant+ icon: "🤖"+ color: "#8B5CF6"+---++# Sub-Agent Management Skill++You are a parent agent that can delegate tasks to specialized sub-agents. This skill helps you understand, delegate to, and handle results from sub-agents effectively.++## Available Sub-Agent Types++You can delegate tasks to these specialized agents (when connected to your tools):++### Domain-Specific Agents++| Agent | Icon | Specialty | Best For |+|-------|------|-----------|----------|+| **Android Control Agent** | 📱 | Android device automation | Battery checks, WiFi control, app launching, location tracking, sensor data |+| **Coding Agent** | 💻 | Code execution | Python/JavaScript execution, calculations, data processing |+| **Web Control Agent** | 🌐 | Browser automation | Web scraping, HTTP requests, form filling |+| **Social Media Agent** | 📱 | Social messaging | WhatsApp, Telegram, multi-platform messaging |+| **Travel Agent** | ✈️ | Travel planning | Itineraries, location lookups, travel recommendations |++### Task & Workflow Agents++| Agent | Icon | Specialty | Best For |+|-------|------|-----------|----------|+| **Task Management Agent** | 📋 | Task automation | Scheduling, reminders, to-do management |+| **Tool Agent** | 🔧 | Tool orchestration | Multi-tool workflows, complex task execution |+| **Productivity Agent** | ⏰ | Productivity | Time management, note-taking, workflow automation |++### Business Agents++| Agent | Icon | Specialty | Best For |+|-------|------|-----------|----------|+| **Payments Agent** | 💳 | Payment processing | Payment workflows, invoices, financial operations |+| **Consumer Agent** | 🛒 | Consumer support | Customer service, product recommendations, order management |++## How Delegation Works++### Fire-and-Forget Pattern+When you delegate a task:+1. The sub-agent receives the task and starts working immediately+2. You continue your conversation - delegation is non-blocking+3. The sub-agent works independently with its own tools and memory+4. When complete, a `task_completed` event is fired++### What You Receive Back+- **Task ID**: Unique identifier (e.g., `delegated_abc123_xyz`)+- **Status**: `completed` or `error`+- **Agent Name**: Which sub-agent completed the work+- **Result/Error**: The outcome or error message++## Delegation Best Practices++### When to Delegate+- Task requires specialized tools you don't have connected+- Task is time-consuming and can run in background+- Task matches a sub-agent's specialty area+- User explicitly asks for a specific capability++### When NOT to Delegate+- Simple questions you can answer directly+- Tasks that need immediate response in conversation+- When you already have the required tools connected++### Delegation Format+When delegating, provide clear instructions:+```+Task: [Clear description of what needs to be done]+Context: [Any relevant background information]+Expected Output: [What format/information you need back]+```++## Handling Task Completion++### Successful Completion+When a delegated task completes successfully:++1. **DO NOT delegate again** - The task is finished+2. **Extract key information** from the result+3. **Report to the user** naturally and conversationally+4. **Suggest next steps** if appropriate++**Example Response:**+"The Android agent has checked your battery status. Your device is at 78% with approximately 5 hours of usage remaining. Would you like me to enable power-saving mode?"++### Failed Tasks+When a delegated task fails:++1. **DO NOT retry automatically** - Let the user decide+2. **Explain what went wrong** clearly+3. **Suggest alternatives** or troubleshooting steps++**Example Response:**+"I wasn't able to send the WhatsApp message because the contact wasn't found. Could you verify the phone number? Alternatively, I can try searching for the contact by name."++## Task Tracking++If you have the Task Manager tool connected, use it to:+- **List tasks**: See all active and completed delegated tasks+- **Check status**: Get details on a specific task+- **Mark done**: Clean up completed task tracking++### Checking Task Status+Before re-delegating similar work:+1. Use Task Manager to list recent tasks+2. Check if the same task is already running+3. Avoid duplicate delegations++## Multi-Agent Coordination++### Sequential Delegation+For tasks requiring multiple steps:+1. Delegate first task to appropriate agent+2. Wait for completion via task trigger+3. Use result to delegate next task+4. Continue until workflow complete++### Parallel Delegation+For independent tasks:+- Delegate multiple tasks to different agents+- Each runs independently+- Collect results as they complete++## Critical Rules++1. **NEVER re-delegate after receiving a result** - Report it instead+2. **NEVER retry failed tasks automatically** - Ask user first+3. **ALWAYS acknowledge task completion** to the user+4. **ALWAYS match task to agent specialty** for best results+5. **When in doubt, ask the user** before taking action++## Error Handling++| Error Type | Action |+|------------|--------|+| Agent not found | Check if agent is connected to your tools |+| Task timeout | Report to user, suggest retry |+| Invalid parameters | Clarify requirements with user |+| Agent error | Report error details, suggest alternatives |++## Example Workflows++### Battery Check Workflow+```+User: "Check my phone battery"+You: Delegate to Android Control Agent with task "Get battery status"+Agent: Returns {status: 'completed', result: 'Battery at 78%, charging'}+You: "Your phone battery is at 78% and currently charging."+```++### Message Sending Workflow+```+User: "Send a WhatsApp to John saying I'll be late"+You: Delegate to Social Media Agent with message details+Agent: Returns {status: 'completed', result: 'Message sent to John'}+You: "Done! I've sent the message to John letting him know you'll be late."+```++### Failed Task Workflow+```+User: "Run the Python script at /scripts/analyze.py"+You: Delegate to Coding Agent+Agent: Returns {status: 'error', error: 'File not found'}+You: "I couldn't run that script - the file wasn't found at /scripts/analyze.py. Could you verify the path is correct?"+```diff --git a/workflows/Zeenie_full.json b/workflows/Zeenie_full.jsonnew file mode 100644index 00000000..931f25f4--- /dev/null+++ b/workflows/Zeenie_full.json@@ -0,0 +1,459 @@+{+ "id": "workflow-1770568399727-b5zkjpuda",+ "name": "Zeenie",+ "nodes": [+ {+ "id": "chatAgent-1770207244010",+ "type": "chatAgent",+ "position": {+ "x": 260,+ "y": 180+ },+ "data": {+ "label": "Zeenie"+ },+ "width": 260,+ "height": 160,+ "selected": false,+ "positionAbsolute": {+ "x": 260,+ "y": 180+ },+ "dragging": false+ },+ {+ "id": "chatTrigger-1770207686160",+ "type": "chatTrigger",+ "position": {+ "x": -400,+ "y": 260+ },+ "data": {+ "label": "Chat Trigger"+ },+ "width": 67,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": -400,+ "y": 260+ },+ "dragging": false+ },+ {+ "id": "console-1770207687094",+ "type": "console",+ "position": {+ "x": 780,+ "y": 300+ },+ "data": {+ "label": "Console"+ },+ "width": 60,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 780,+ "y": 300+ },+ "dragging": true+ },+ {+ "id": "whatsappSend-1770207695172",+ "type": "whatsappSend",+ "position": {+ "x": 760,+ "y": 140+ },+ "data": {+ "label": "WhatsApp Send"+ },+ "width": 87,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 760,+ "y": 140+ },+ "dragging": false+ },+ {+ "id": "whatsappReceive-1770207696316",+ "type": "whatsappReceive",+ "position": {+ "x": -420,+ "y": 140+ },+ "data": {+ "label": "WhatsApp Receive"+ },+ "width": 101,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": -420,+ "y": 140+ },+ "dragging": true+ },+ {+ "id": "whatsappDb-1770207697703",+ "type": "whatsappDb",+ "position": {+ "x": 1460,+ "y": 540+ },+ "data": {+ "label": "WhatsApp DB"+ },+ "width": 76,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1460,+ "y": 540+ },+ "dragging": true+ },+ {+ "id": "webSearchTool-1770207714722",+ "type": "webSearchTool",+ "position": {+ "x": 640,+ "y": 540+ },+ "data": {+ "label": "Web Search Tool"+ },+ "width": 91,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 640,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "httpRequest-1770207725414",+ "type": "httpRequest",+ "position": {+ "x": 760,+ "y": 540+ },+ "data": {+ "label": "HTTP Request"+ },+ "width": 76,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 760,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "gmaps_locations-1770207738763",+ "type": "gmaps_locations",+ "position": {+ "x": 1180,+ "y": 540+ },+ "data": {+ "label": "GMaps Locations"+ },+ "width": 93,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1180,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "gmaps_nearby_places-1770207740402",+ "type": "gmaps_nearby_places",+ "position": {+ "x": 1300,+ "y": 540+ },+ "data": {+ "label": "GMaps Nearby Places"+ },+ "width": 118,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1300,+ "y": 540+ },+ "dragging": true+ },+ {+ "id": "pythonExecutor-1770207749221",+ "type": "pythonExecutor",+ "position": {+ "x": 1000,+ "y": 540+ },+ "data": {+ "label": "Python Executor"+ },+ "width": 89,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1000,+ "y": 540+ },+ "dragging": true+ },+ {+ "id": "javascriptExecutor-1770207751142",+ "type": "javascriptExecutor",+ "position": {+ "x": 860,+ "y": 540+ },+ "data": {+ "label": "JavaScript Executor"+ },+ "width": 105,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 860,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "masterSkill-1770207855144",+ "type": "masterSkill",+ "position": {+ "x": 200,+ "y": 540+ },+ "data": {+ "label": "Master Skill"+ },+ "width": 63,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 200,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "simpleMemory-1770207943830",+ "type": "simpleMemory",+ "position": {+ "x": 60,+ "y": 540+ },+ "data": {+ "label": "Simple Memory"+ },+ "width": 87,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 60,+ "y": 540+ },+ "dragging": true+ }+ ],+ "edges": [+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "chatTrigger-1770207686160",+ "sourceHandle": "output-main",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-main",+ "id": "reactflow__edge-chatTrigger-1770207686160output-main-chatAgent-1770207244010input-main",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "whatsappReceive-1770207696316",+ "sourceHandle": "output-main",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-main",+ "id": "reactflow__edge-whatsappReceive-1770207696316output-main-chatAgent-1770207244010input-main",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "masterSkill-1770207855144",+ "sourceHandle": "output-main",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-skill",+ "id": "reactflow__edge-masterSkill-1770207855144output-main-chatAgent-1770207244010input-skill",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "simpleMemory-1770207943830",+ "sourceHandle": "output-memory",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-memory",+ "id": "reactflow__edge-simpleMemory-1770207943830output-memory-chatAgent-1770207244010input-memory",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "httpRequest-1770207725414",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-httpRequest-1770207725414output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "javascriptExecutor-1770207751142",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-javascriptExecutor-1770207751142output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "webSearchTool-1770207714722",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-webSearchTool-1770207714722output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "pythonExecutor-1770207749221",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-pythonExecutor-1770207749221output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "gmaps_locations-1770207738763",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-gmaps_locations-1770207738763output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "gmaps_nearby_places-1770207740402",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-gmaps_nearby_places-1770207740402output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "whatsappDb-1770207697703",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-whatsappDb-1770207697703output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "chatAgent-1770207244010",+ "sourceHandle": "output-main",+ "target": "console-1770207687094",+ "targetHandle": "input-main",+ "id": "reactflow__edge-chatAgent-1770207244010output-main-console-1770207687094input-main",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "chatAgent-1770207244010",+ "sourceHandle": "output-main",+ "target": "whatsappSend-1770207695172",+ "targetHandle": "input-main",+ "id": "reactflow__edge-chatAgent-1770207244010output-main-whatsappSend-1770207695172input-main",+ "selected": false+ }+ ],+ "createdAt": "2026-02-08T16:33:19.727Z",+ "lastModified": "2026-02-08T16:35:36.239Z",+ "version": "0.0.10"+}\ No newline at end of filediff --git a/workflows/Zeenie_small.json b/workflows/Zeenie_small.jsonnew file mode 100644index 00000000..931f25f4--- /dev/null+++ b/workflows/Zeenie_small.json@@ -0,0 +1,459 @@+{+ "id": "workflow-1770568399727-b5zkjpuda",+ "name": "Zeenie",+ "nodes": [+ {+ "id": "chatAgent-1770207244010",+ "type": "chatAgent",+ "position": {+ "x": 260,+ "y": 180+ },+ "data": {+ "label": "Zeenie"+ },+ "width": 260,+ "height": 160,+ "selected": false,+ "positionAbsolute": {+ "x": 260,+ "y": 180+ },+ "dragging": false+ },+ {+ "id": "chatTrigger-1770207686160",+ "type": "chatTrigger",+ "position": {+ "x": -400,+ "y": 260+ },+ "data": {+ "label": "Chat Trigger"+ },+ "width": 67,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": -400,+ "y": 260+ },+ "dragging": false+ },+ {+ "id": "console-1770207687094",+ "type": "console",+ "position": {+ "x": 780,+ "y": 300+ },+ "data": {+ "label": "Console"+ },+ "width": 60,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 780,+ "y": 300+ },+ "dragging": true+ },+ {+ "id": "whatsappSend-1770207695172",+ "type": "whatsappSend",+ "position": {+ "x": 760,+ "y": 140+ },+ "data": {+ "label": "WhatsApp Send"+ },+ "width": 87,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 760,+ "y": 140+ },+ "dragging": false+ },+ {+ "id": "whatsappReceive-1770207696316",+ "type": "whatsappReceive",+ "position": {+ "x": -420,+ "y": 140+ },+ "data": {+ "label": "WhatsApp Receive"+ },+ "width": 101,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": -420,+ "y": 140+ },+ "dragging": true+ },+ {+ "id": "whatsappDb-1770207697703",+ "type": "whatsappDb",+ "position": {+ "x": 1460,+ "y": 540+ },+ "data": {+ "label": "WhatsApp DB"+ },+ "width": 76,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1460,+ "y": 540+ },+ "dragging": true+ },+ {+ "id": "webSearchTool-1770207714722",+ "type": "webSearchTool",+ "position": {+ "x": 640,+ "y": 540+ },+ "data": {+ "label": "Web Search Tool"+ },+ "width": 91,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 640,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "httpRequest-1770207725414",+ "type": "httpRequest",+ "position": {+ "x": 760,+ "y": 540+ },+ "data": {+ "label": "HTTP Request"+ },+ "width": 76,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 760,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "gmaps_locations-1770207738763",+ "type": "gmaps_locations",+ "position": {+ "x": 1180,+ "y": 540+ },+ "data": {+ "label": "GMaps Locations"+ },+ "width": 93,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1180,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "gmaps_nearby_places-1770207740402",+ "type": "gmaps_nearby_places",+ "position": {+ "x": 1300,+ "y": 540+ },+ "data": {+ "label": "GMaps Nearby Places"+ },+ "width": 118,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1300,+ "y": 540+ },+ "dragging": true+ },+ {+ "id": "pythonExecutor-1770207749221",+ "type": "pythonExecutor",+ "position": {+ "x": 1000,+ "y": 540+ },+ "data": {+ "label": "Python Executor"+ },+ "width": 89,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 1000,+ "y": 540+ },+ "dragging": true+ },+ {+ "id": "javascriptExecutor-1770207751142",+ "type": "javascriptExecutor",+ "position": {+ "x": 860,+ "y": 540+ },+ "data": {+ "label": "JavaScript Executor"+ },+ "width": 105,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 860,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "masterSkill-1770207855144",+ "type": "masterSkill",+ "position": {+ "x": 200,+ "y": 540+ },+ "data": {+ "label": "Master Skill"+ },+ "width": 63,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 200,+ "y": 540+ },+ "dragging": false+ },+ {+ "id": "simpleMemory-1770207943830",+ "type": "simpleMemory",+ "position": {+ "x": 60,+ "y": 540+ },+ "data": {+ "label": "Simple Memory"+ },+ "width": 87,+ "height": 82,+ "selected": false,+ "positionAbsolute": {+ "x": 60,+ "y": 540+ },+ "dragging": true+ }+ ],+ "edges": [+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "chatTrigger-1770207686160",+ "sourceHandle": "output-main",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-main",+ "id": "reactflow__edge-chatTrigger-1770207686160output-main-chatAgent-1770207244010input-main",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "whatsappReceive-1770207696316",+ "sourceHandle": "output-main",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-main",+ "id": "reactflow__edge-whatsappReceive-1770207696316output-main-chatAgent-1770207244010input-main",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "masterSkill-1770207855144",+ "sourceHandle": "output-main",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-skill",+ "id": "reactflow__edge-masterSkill-1770207855144output-main-chatAgent-1770207244010input-skill",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "simpleMemory-1770207943830",+ "sourceHandle": "output-memory",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-memory",+ "id": "reactflow__edge-simpleMemory-1770207943830output-memory-chatAgent-1770207244010input-memory",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "httpRequest-1770207725414",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-httpRequest-1770207725414output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "javascriptExecutor-1770207751142",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-javascriptExecutor-1770207751142output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "webSearchTool-1770207714722",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-webSearchTool-1770207714722output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "pythonExecutor-1770207749221",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-pythonExecutor-1770207749221output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "gmaps_locations-1770207738763",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-gmaps_locations-1770207738763output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "gmaps_nearby_places-1770207740402",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-gmaps_nearby_places-1770207740402output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "whatsappDb-1770207697703",+ "sourceHandle": "output-tool",+ "target": "chatAgent-1770207244010",+ "targetHandle": "input-tools",+ "id": "reactflow__edge-whatsappDb-1770207697703output-tool-chatAgent-1770207244010input-tools",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "chatAgent-1770207244010",+ "sourceHandle": "output-main",+ "target": "console-1770207687094",+ "targetHandle": "input-main",+ "id": "reactflow__edge-chatAgent-1770207244010output-main-console-1770207687094input-main",+ "selected": false+ },+ {+ "type": "smoothstep",+ "animated": true,+ "style": {+ "stroke": "#8be9fd",+ "strokeWidth": 3+ },+ "source": "chatAgent-1770207244010",+ "sourceHandle": "output-main",+ "target": "whatsappSend-1770207695172",+ "targetHandle": "input-main",+ "id": "reactflow__edge-chatAgent-1770207244010output-main-whatsappSend-1770207695172input-main",+ "selected": false+ }+ ],+ "createdAt": "2026-02-08T16:33:19.727Z",+ "lastModified": "2026-02-08T16:35:36.239Z",+ "version": "0.0.10"+}\ No newline at end of file