Skip to content

Self-improving AI Employees for everyone

refactor: Wave 11.E.2 — dead code sweep after audit

trohitgec469986b3a3
diff --git a/server/core/logging.py b/server/core/logging.py
index 466a3a8d..8c85db4a 100644
--- a/server/core/logging.py
+++ b/server/core/logging.py
@@ -33,7 +33,7 @@ class WebSocketLogHandler(logging.Handler):
'services.workflow': 'workflow',
'services.ai': 'ai',
'services.android': 'android',
- 'routers.whatsapp': 'whatsapp',
+ 'services.whatsapp_service': 'whatsapp',
'routers.android': 'android',
'routers.websocket': 'websocket',
'routers.workflow': 'workflow',
diff --git a/server/nodes/agent/claude_code_agent.py b/server/nodes/agent/claude_code_agent.py
index 8bd9837a..cd8f920f 100644
--- a/server/nodes/agent/claude_code_agent.py
+++ b/server/nodes/agent/claude_code_agent.py
@@ -34,7 +34,7 @@ class ClaudeCodeAgentNode(ActionNode):
@Operation("execute", cost={"service": "claude_code_agent", "action": "run", "count": 1})
async def execute_op(self, ctx: NodeContext, params: SpecializedAgentParams) -> Any:
from core.container import container
- from services.handlers.ai import handle_claude_code_agent
+ from services.handlers.claude_code import handle_claude_code_agent
ai_service = container.ai_service()
database = container.database()
diff --git a/server/nodes/agent/rlm_agent.py b/server/nodes/agent/rlm_agent.py
index 87d3054a..75e696b8 100644
--- a/server/nodes/agent/rlm_agent.py
+++ b/server/nodes/agent/rlm_agent.py
@@ -35,7 +35,7 @@ class RLMAgentNode(ActionNode):
@Operation("execute", cost={"service": "rlm_agent", "action": "run", "count": 1})
async def execute_op(self, ctx: NodeContext, params: SpecializedAgentParams) -> Any:
from core.container import container
- from services.handlers.ai import handle_rlm_agent
+ from services.handlers.rlm import handle_rlm_agent
ai_service = container.ai_service()
database = container.database()
diff --git a/server/nodes/social/_base.py b/server/nodes/social/_base.py
index e50decb4..b26be680 100644
--- a/server/nodes/social/_base.py
+++ b/server/nodes/social/_base.py
@@ -7,7 +7,7 @@ Email, Matrix, Teams).
Imported by :class:`nodes.social.social_receive.SocialReceiveNode` and
:class:`nodes.social.social_send.SocialSendNode`. Calls into
-``routers.whatsapp`` for the WhatsApp bridge stay unchanged — moving
+``services.whatsapp_service`` for the WhatsApp bridge stay unchanged — moving
them out is a separate refactor.
"""
@@ -475,7 +475,7 @@ async def _send_via_whatsapp(
Maps socialSend parameters to whatsappSend parameters.
"""
- from routers.whatsapp import handle_whatsapp_send as whatsapp_send_handler
+ from services.whatsapp_service import handle_whatsapp_send as whatsapp_send_handler
# Map socialSend params to whatsappSend format
whatsapp_params = {
diff --git a/server/nodes/whatsapp/_base.py b/server/nodes/whatsapp/_base.py
index 4b5ae102..eeb08fe9 100644
--- a/server/nodes/whatsapp/_base.py
+++ b/server/nodes/whatsapp/_base.py
@@ -1,7 +1,7 @@
"""WhatsApp send + DB business logic (Wave 11.D.9 inlined).
Imported by nodes.whatsapp.whatsapp_send and nodes.whatsapp.whatsapp_db.
-RPC dispatch still flows through routers.whatsapp (HTTP to the Go
+RPC dispatch still flows through services.whatsapp_service (HTTP to the Go
bridge) — extracting that is a separate refactor, not required for the
plugin migration.
"""
@@ -145,7 +145,7 @@ async def handle_whatsapp_send(
Returns:
Execution result dict
"""
- from routers.whatsapp import handle_whatsapp_send as whatsapp_send_handler
+ from services.whatsapp_service import handle_whatsapp_send as whatsapp_send_handler
start_time = time.time()
try:
@@ -289,7 +289,7 @@ async def handle_whatsapp_db(
Returns:
Execution result dict
"""
- from routers.whatsapp import (
+ from services.whatsapp_service import (
handle_whatsapp_chat_history as whatsapp_chat_history_handler,
whatsapp_rpc_call
)
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 29d7b3f9..a223e22e 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1865,10 +1865,10 @@ async def handle_validate_apify_key(data: Dict[str, Any], websocket: WebSocket)
# ============================================================================
-# WhatsApp Handlers - Wrappers for routers.whatsapp functions
+# WhatsApp Handlers - Wrappers for services.whatsapp_service functions
# ============================================================================
-from routers.whatsapp import (
+from services.whatsapp_service import (
handle_whatsapp_status as _wa_status,
handle_whatsapp_connected_phone as _wa_connected_phone,
handle_whatsapp_qr as _wa_qr,
diff --git a/server/services/handlers/proxy.py b/server/services/handlers/proxy.py
deleted file mode 100644
index fe60e244..00000000
--- a/server/services/handlers/proxy.py
+++ /dev/null
@@ -1,326 +0,0 @@
-"""Proxy node handlers - proxyRequest, proxyStatus, proxyConfig.
-
-proxyRequest: HTTP request with full proxy controls, retry/failover loop.
-proxyStatus: Returns provider health stats for dashboard display.
-proxyConfig: Manage proxy providers and routing rules (dual-purpose tool).
-"""
-
-import json
-import time
-from datetime import datetime
-from typing import Dict, Any
-
-import httpx
-
-from core.logging import get_logger
-from services.proxy.models import ProxyResult
-from services.proxy.service import get_proxy_service
-
-logger = get_logger(__name__)
-
-
-async def _track_proxy_usage(
- node_id: str,
- provider_name: str,
- bytes_transferred: int,
- workflow_id: str = None,
- session_id: str = "default",
-) -> Dict[str, float]:
- """Track proxy usage and persist cost to database.
-
- Cost is calculated as bytes_transferred / 1GB * cost_per_gb
- from server/config/pricing.json proxy section.
- """
- from core.container import container
- from services.pricing import get_pricing_service
-
- pricing = get_pricing_service()
-
- # Read cost_per_gb from pricing config
- proxy_pricing = pricing._config.get("proxy", {})
- provider_pricing = proxy_pricing.get(provider_name, {})
- cost_per_gb = provider_pricing.get("cost_per_gb", 0.0)
-
- gb_transferred = bytes_transferred / (1024 ** 3)
- total_cost = round(gb_transferred * cost_per_gb, 8)
-
- db = container.database()
- await db.save_api_usage_metric({
- "session_id": session_id,
- "node_id": node_id,
- "workflow_id": workflow_id,
- "service": f"proxy_{provider_name}" if provider_name else "proxy",
- "operation": "proxy_request",
- "endpoint": "proxy",
- "resource_count": 1,
- "cost": total_cost,
- })
-
- logger.debug(
- f"[Proxy] Tracked {provider_name} usage: {bytes_transferred} bytes = ${total_cost:.8f}"
- )
- return {"cost_per_gb": cost_per_gb, "bytes": bytes_transferred, "total_cost": total_cost}
-
-
-async def handle_proxy_request(
- node_id: str,
- node_type: str,
- parameters: Dict[str, Any],
- context: Dict[str, Any],
-) -> Dict[str, Any]:
- """Handle proxyRequest node execution.
-
- Makes HTTP requests through configured proxy providers with
- retry/failover, geo-targeting, and result reporting.
-
- Args:
- node_id: The node ID
- node_type: The node type (proxyRequest)
- parameters: Resolved parameters
- context: Execution context
-
- Returns:
- Execution result dict with response data
- """
- start_time = time.time()
-
- try:
- proxy_svc = get_proxy_service()
- if not proxy_svc or not proxy_svc.is_enabled():
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "proxyRequest",
- "error": "Proxy service not initialized. Use proxy_config tool to add a provider first.",
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
- method = parameters.get('method', 'GET')
- url = parameters.get('url', '')
- headers_str = parameters.get('headers', '{}')
- body = parameters.get('body', '')
- timeout = float(parameters.get('timeout', 30))
- max_retries = int(parameters.get('maxRetries', parameters.get('proxyMaxRetries', 3)))
- failover = parameters.get('proxyFailover', True)
-
- if not url:
- raise ValueError("URL is required")
-
- # Parse headers JSON
- try:
- headers = json.loads(headers_str) if headers_str else {}
- except json.JSONDecodeError:
- headers = {}
-
- # Get proxy URL
- proxy_url = await proxy_svc.get_proxy_url(url, parameters)
- if not proxy_url:
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "proxyRequest",
- "error": "No proxy provider available",
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
- # Determine provider name for result reporting
- provider_name = parameters.get('proxyProvider', '')
-
- last_error = None
- for attempt in range(max_retries + 1):
- req_start = time.monotonic()
- try:
- async with httpx.AsyncClient(proxy=proxy_url, timeout=timeout) as client:
- kwargs: Dict[str, Any] = {
- 'method': method,
- 'url': url,
- 'headers': headers,
- }
- if method in ['POST', 'PUT', 'PATCH'] and body:
- try:
- kwargs['json'] = json.loads(body)
- except json.JSONDecodeError:
- kwargs['content'] = body
-
- response = await client.request(**kwargs)
-
- latency_ms = (time.monotonic() - req_start) * 1000
- bytes_transferred = len(response.content) if response.content else 0
-
- # Report success to health scorer
- proxy_svc.report_result(provider_name, ProxyResult(
- success=response.status_code < 400,
- latency_ms=latency_ms,
- bytes_transferred=bytes_transferred,
- status_code=response.status_code,
- ))
-
- # Track cost in database
- workflow_id = context.get("workflow_id")
- session_id = context.get("session_id", "default")
- await _track_proxy_usage(
- node_id, provider_name, bytes_transferred,
- workflow_id=workflow_id, session_id=session_id,
- )
-
- # Parse response
- try:
- response_data = response.json()
- except Exception:
- response_data = response.text
-
- return {
- "success": response.status_code < 400,
- "node_id": node_id,
- "node_type": "proxyRequest",
- "result": {
- "status": response.status_code,
- "data": response_data,
- "headers": dict(response.headers),
- "url": str(response.url),
- "method": method,
- "proxy_provider": provider_name,
- "latency_ms": round(latency_ms, 1),
- "bytes_transferred": bytes_transferred,
- "attempt": attempt + 1,
- },
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
- except Exception as e:
- latency_ms = (time.monotonic() - req_start) * 1000
- last_error = str(e)
-
- # Report failure
- proxy_svc.report_result(provider_name, ProxyResult(
- success=False,
- latency_ms=latency_ms,
- error=last_error,
- ))
-
- logger.warning("Proxy request attempt failed",
- node_id=node_id, attempt=attempt + 1,
- max_retries=max_retries, error=last_error)
-
- if not failover or attempt >= max_retries:
- break
-
- # Try a different proxy URL for failover
- try:
- proxy_url = await proxy_svc.get_proxy_url(url, parameters)
- except Exception:
- break
-
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "proxyRequest",
- "error": f"All {max_retries + 1} attempts failed. Last error: {last_error}",
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
- except Exception as e:
- logger.error("Proxy request failed", node_id=node_id, error=str(e))
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "proxyRequest",
- "error": str(e),
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
-
-async def handle_proxy_status(
- node_id: str,
- node_type: str,
- parameters: Dict[str, Any],
- context: Dict[str, Any],
-) -> Dict[str, Any]:
- """Handle proxyStatus node execution.
-
- Returns provider health stats for dashboard display.
- """
- start_time = time.time()
-
- try:
- proxy_svc = get_proxy_service()
- if not proxy_svc or not proxy_svc.is_enabled():
- return {
- "success": True,
- "node_id": node_id,
- "node_type": "proxyStatus",
- "result": {
- "enabled": False,
- "providers": [],
- "stats": {},
- },
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
- stats = proxy_svc.get_stats()
- providers = [p.model_dump() for p in proxy_svc.get_providers()]
-
- return {
- "success": True,
- "node_id": node_id,
- "node_type": "proxyStatus",
- "result": {
- "enabled": True,
- "providers": providers,
- "stats": stats,
- },
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
- except Exception as e:
- logger.error("Proxy status check failed", node_id=node_id, error=str(e))
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "proxyStatus",
- "error": str(e),
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
-
-
-async def handle_proxy_config(
- node_id: str,
- node_type: str,
- parameters: Dict[str, Any],
- context: Dict[str, Any],
-) -> Dict[str, Any]:
- """Handle proxyConfig node execution (standalone workflow mode).
-
- Routes to the tool handler for operation-based dispatch.
- """
- from services.handlers.tools import _execute_proxy_config
-
- start_time = time.time()
- try:
- result = await _execute_proxy_config(parameters, parameters)
- return {
- "success": result.get("success", False),
- "node_id": node_id,
- "node_type": "proxyConfig",
- "result": result,
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
- except Exception as e:
- logger.error("Proxy config failed", node_id=node_id, error=str(e))
- return {
- "success": False,
- "node_id": node_id,
- "node_type": "proxyConfig",
- "error": str(e),
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat(),
- }
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index b497ba20..cf1dbf02 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -98,85 +98,31 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
)
return await instance.execute_as_tool(tool_args, node_params, ctx)
- # calculatorTool: migrated to plugin (Wave 11.B). Handled by fast-path above.
-
- # HTTP Request tool (existing httpRequest node as tool)
- if node_type in ('httpRequest', 'httpRequestTool'):
- return await _execute_http_request(tool_args, node_params)
-
- # Python executor tool (dual-purpose: workflow node + AI tool)
- if node_type == 'pythonExecutor':
- return await _execute_python_code(tool_args, node_params, context)
-
- # JavaScript executor tool (dual-purpose: workflow node + AI tool)
- if node_type == 'javascriptExecutor':
- return await _execute_javascript_code(tool_args, node_params, context)
-
- # Current time tool
- if node_type == 'currentTimeTool':
- return await _execute_current_time(tool_args, node_params)
-
- # duckduckgoSearch: migrated to plugin (Wave 11.C). Handled by fast-path above.
-
- # Filesystem and shell tools (deepagents backends)
- if node_type in ('fileRead', 'fileModify', 'shell', 'fsSearch'):
- from services.handlers.filesystem import handle_file_read, handle_file_modify, handle_shell, handle_fs_search
- params = {**node_params, **tool_args}
- handler_map = {
- 'fileRead': handle_file_read,
- 'fileModify': handle_file_modify,
- 'shell': handle_shell,
- 'fsSearch': handle_fs_search,
- }
- return await handler_map[node_type](
- node_id=config.get('node_id', f'tool_{node_type}'),
- node_type=node_type,
- parameters=params,
- context=context,
- )
-
- # timer / cronScheduler: handled by the plugin fast-path above.
-
- # WhatsApp / Twitter / Google Workspace / Search / Maps tool branches
- # all migrated to plugin classes — routed via the Wave 11.B.1 fast-path
- # at the top of execute_tool. Branches below kept only for the few
- # tool types still on the legacy path:
-
- # androidTool (toolkit aggregator): kept until 11.D.
+ # Wave 11.E.2: every per-type legacy dispatch branch retired —
+ # the plugin fast-path above intercepts every registered plugin
+ # (httpRequest / pythonExecutor / javascriptExecutor / currentTime
+ # / filesystem / writeTodos / processManager / taskManager /
+ # browser / email{Send,Read} / proxy{Request,Status,Config}).
+ # Branches below are only for built-ins without a plugin
+ # representation or cases needing special argument translation.
+
+ # androidTool (toolkit aggregator): dynamic schema derived from
+ # connected services; no plugin class.
if node_type == 'androidTool':
return await _execute_android_toolkit(tool_args, config)
- # Direct Android service node (connected directly to AI Agent tools handle)
+ # Direct Android service node — LLM args use keys (action/parameters)
+ # that don't map 1-to-1 onto the plugin's Params schema, so we keep
+ # the dedicated dispatcher with its camelCase -> snake_case service
+ # id translation.
if node_type in ANDROID_SERVICE_NODE_TYPES:
return await _execute_android_service(tool_args, config)
- # Write Todos (dedicated AI tool for task planning)
- if node_type == 'writeTodos':
- from services.handlers.todo import execute_write_todos
- return await execute_write_todos(tool_args, config)
-
- # Process Manager (dual-purpose: AI tool + workflow node)
- if node_type == 'processManager':
- from services.handlers.process import execute_process_manager
- return await execute_process_manager(tool_args, config)
-
- # Task Manager (dual-purpose: AI tool + workflow node)
+ # taskManager + proxyConfig: plugin bodies delegate back to the
+ # _execute_* stubs below for their operation-dispatch matrices, so
+ # keep those branches live.
if node_type == 'taskManager':
return await _execute_task_manager(tool_args, config)
-
- # Browser automation (dual-purpose: workflow node + AI tool)
- if node_type == 'browser':
- return await _execute_browser(tool_args, config.get('parameters', {}), config)
-
- # Proxy nodes (dual-purpose: workflow node + AI tool)
- # Email nodes (dual-purpose: workflow node + AI tool)
- if node_type in ('emailSend', 'emailRead'):
- return await _execute_email_tool(node_type, tool_args, config.get('parameters', {}))
-
- if node_type == 'proxyRequest':
- return await _execute_proxy_request(tool_args, config.get('parameters', {}), config)
- if node_type == 'proxyStatus':
- return await _execute_proxy_status(tool_args, config.get('parameters', {}))
if node_type == 'proxyConfig':
return await _execute_proxy_config(tool_args, config.get('parameters', {}))
@@ -199,304 +145,12 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
# nodes/tool/calculator_tool.py CalculatorToolNode.calculate().
-async def _execute_http_request(args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute HTTP request tool.
-
- Args:
- args: Dict with 'url', 'method', optionally 'body'
- node_params: Node parameters containing base_url, headers, etc.
-
- Returns:
- Dict with status code, data, and url
- """
- import httpx
-
- base_url = node_params.get('url', '')
- url = args.get('url', '')
- method = args.get('method', 'GET').upper()
- body = args.get('body')
-
- # Build full URL
- if base_url and url and not url.startswith('http'):
- full_url = f"{base_url.rstrip('/')}/{url.lstrip('/')}"
- else:
- full_url = url or base_url
-
- if not full_url:
- return {"error": "No URL provided"}
-
- # Parse headers from node params
- try:
- default_headers = json.loads(node_params.get('headers', '{}'))
- except Exception:
- default_headers = {}
-
- # Transparent proxy injection (useProxy from node params or LLM args)
- proxy_url = None
- use_proxy = args.get('useProxy', node_params.get('useProxy', False))
- if use_proxy:
- try:
- from services.proxy.service import get_proxy_service
- proxy_svc = get_proxy_service()
- if proxy_svc and proxy_svc.is_enabled():
- merged = {**node_params, **args}
- proxy_url = await proxy_svc.get_proxy_url(full_url, merged)
- except Exception as e:
- logger.warning(f"[HTTP Tool] Proxy lookup failed, proceeding without proxy: {e}")
-
- logger.debug(f"[HTTP Tool] {method} {full_url}", proxy=bool(proxy_url))
-
- try:
- client_kwargs: dict = {"timeout": 30.0}
- if proxy_url:
- client_kwargs["proxy"] = proxy_url
-
- async with httpx.AsyncClient(**client_kwargs) as client:
- response = await client.request(
- method=method,
- url=full_url,
- headers=default_headers,
- json=body if body else None
- )
-
- # Try to parse JSON response
- try:
- data = response.json()
- except Exception:
- data = response.text
-
- return {
- "status": response.status_code,
- "data": data,
- "url": full_url,
- "method": method,
- "proxied": proxy_url is not None,
- }
- except httpx.TimeoutException:
- return {"error": "Request timed out"}
- except httpx.ConnectError as e:
- return {"error": f"Connection failed: {str(e)}"}
- except Exception as e:
- logger.error(f"[HTTP Tool] Error: {e}")
- return {"error": str(e)}
-async def _execute_python_code(args: Dict[str, Any],
- node_params: Dict[str, Any],
- context: Dict[str, Any] = None) -> Dict[str, Any]:
- """Execute Python code (dual-purpose: workflow node + AI tool).
- Args:
- args: Dict with 'code' from LLM (when used as AI tool)
- node_params: Node parameters containing code (when used as workflow node), timeout, etc.
- context: Execution context with workspace_dir for cwd
- """
- import subprocess
- import tempfile
- import os
- # Get code from LLM args first (AI tool mode), fall back to node parameters (workflow mode)
- code = args.get('code', '') or node_params.get('code', '')
- timeout = int(node_params.get('timeout', 30))
- if not code:
- return {"error": "No code provided. When using as AI tool, the LLM must provide the 'code' argument with Python code to execute."}
-
- # Wrap code to capture output and result
- wrapped_code = f'''
-import json
-import sys
-import math
-from datetime import datetime, timedelta
-from collections import Counter, defaultdict
-
-input_data = {{}}
-output = None
-_stdout_lines = []
-
-class _PrintCapture:
- def write(self, text):
- if text.strip():
- _stdout_lines.append(text.rstrip())
- def flush(self):
- pass
-
-_old_stdout = sys.stdout
-sys.stdout = _PrintCapture()
-
-try:
-{chr(10).join(" " + line for line in code.split(chr(10)))}
-
- sys.stdout = _old_stdout
- result = {{"success": True}}
- if output is not None:
- result["result"] = output
- if _stdout_lines:
- result["output"] = chr(10).join(_stdout_lines)
- print(json.dumps(result, default=str))
-except Exception as e:
- sys.stdout = _old_stdout
- print(json.dumps({{"error": str(e)}}))
-'''
-
- with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
- f.write(wrapped_code)
- temp_path = f.name
-
- try:
- cwd = (context or {}).get('workspace_dir') or None
- logger.debug(f"[Python Tool] Executing code (timeout: {timeout}s, cwd: {cwd})")
- result = subprocess.run(
- ['python', temp_path],
- capture_output=True,
- text=True,
- timeout=timeout,
- cwd=cwd or None,
- )
-
- if result.returncode == 0:
- try:
- return json.loads(result.stdout.strip())
- except Exception:
- return {"success": True, "output": result.stdout.strip()}
- else:
- return {"error": result.stderr or "Python execution failed"}
-
- except subprocess.TimeoutExpired:
- return {"error": f"Python execution timed out after {timeout} seconds"}
- except Exception as e:
- logger.error(f"[Python Tool] Error: {e}")
- return {"error": str(e)}
- finally:
- try:
- os.unlink(temp_path)
- except Exception:
- pass
-
-
-async def _execute_javascript_code(args: Dict[str, Any],
- node_params: Dict[str, Any],
- context: Dict[str, Any] = None) -> Dict[str, Any]:
- """Execute JavaScript code (dual-purpose: workflow node + AI tool).
-
- Args:
- args: Dict with 'code' from LLM (when used as AI tool)
- node_params: Node parameters containing code (when used as workflow node), timeout, etc.
- context: Execution context with workspace_dir for cwd
-
- Returns:
- Dict with success, result, output, or error
- """
- import subprocess
- import tempfile
- import os
-
- # Get code from LLM args first (AI tool mode), fall back to node parameters (workflow mode)
- code = args.get('code', '') or node_params.get('code', '')
- timeout = int(node_params.get('timeout', 30))
-
- if not code:
- return {"error": "No code provided. When using as AI tool, the LLM must provide the 'code' argument with JavaScript code to execute."}
-
- # Wrap code to capture output and result
- wrapped_code = f'''
-const input_data = {{}};
-let output = undefined;
-const _stdout_lines = [];
-
-const _originalLog = console.log;
-console.log = (...args) => {{
- _stdout_lines.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' '));
-}};
-
-try {{
-{chr(10).join(" " + line for line in code.split(chr(10)))}
-
- const result = {{ success: true }};
- if (output !== undefined) {{
- result.result = output;
- }}
- if (_stdout_lines.length > 0) {{
- result.output = _stdout_lines.join('\\n');
- }}
- _originalLog(JSON.stringify(result));
-}} catch (e) {{
- _originalLog(JSON.stringify({{ error: e.message }}));
-}}
-'''
-
- with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False) as f:
- f.write(wrapped_code)
- temp_path = f.name
-
- try:
- cwd = (context or {}).get('workspace_dir') or None
- logger.debug(f"[JavaScript Tool] Executing code (timeout: {timeout}s, cwd: {cwd})")
- result = subprocess.run(
- ['node', temp_path],
- capture_output=True,
- text=True,
- timeout=timeout,
- cwd=cwd or None,
- )
-
- if result.returncode == 0:
- try:
- return json.loads(result.stdout.strip())
- except Exception:
- return {"success": True, "output": result.stdout.strip()}
- else:
- return {"error": result.stderr or "JavaScript execution failed"}
-
- except subprocess.TimeoutExpired:
- return {"error": f"JavaScript execution timed out after {timeout} seconds"}
- except FileNotFoundError:
- return {"error": "Node.js is not installed. Cannot execute JavaScript code."}
- except Exception as e:
- logger.error(f"[JavaScript Tool] Error: {e}")
- return {"error": str(e)}
- finally:
- try:
- os.unlink(temp_path)
- except Exception:
- pass
-
-
-async def _execute_current_time(args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Get current date and time.
-
- Args:
- args: Dict with optional 'timezone'
- node_params: Node parameters containing default timezone
-
- Returns:
- Dict with datetime, date, time, timezone, day_of_week, timestamp
- """
- from datetime import datetime
- import pytz
-
- timezone_str = args.get('timezone') or node_params.get('timezone', 'UTC')
-
- try:
- tz = pytz.timezone(timezone_str)
- now = datetime.now(tz)
-
- result = {
- "datetime": now.isoformat(),
- "date": now.strftime("%Y-%m-%d"),
- "time": now.strftime("%H:%M:%S"),
- "timezone": timezone_str,
- "day_of_week": now.strftime("%A"),
- "timestamp": int(now.timestamp())
- }
- logger.debug(f"[CurrentTime] {timezone_str}: {result['datetime']}")
- return result
- except Exception as e:
- logger.error(f"[CurrentTime] Error: {e}")
- return {"error": f"Invalid timezone: {timezone_str}. Error: {str(e)}"}
# _execute_duckduckgo_search: deleted in Wave 11.C cleanup. Logic moved
@@ -774,79 +428,10 @@ async def _execute_android_service(args: Dict[str, Any],
# (nodes/google/*.py). These functions were defined but unreferenced.
-async def _execute_browser(args: Dict[str, Any],
- node_params: Dict[str, Any],
- config: Dict[str, Any]) -> Dict[str, Any]:
- """Execute browser automation as an AI tool."""
- from services.handlers.browser import handle_browser
-
- parameters = {
- **node_params,
- 'operation': args.get('operation', node_params.get('operation', 'navigate')),
- 'url': args.get('url', node_params.get('url', '')),
- 'selector': args.get('selector', node_params.get('selector', '')),
- 'text': args.get('text', node_params.get('text', '')),
- 'value': args.get('value', node_params.get('value', '')),
- 'expression': args.get('expression', node_params.get('expression', '')),
- 'direction': args.get('direction', node_params.get('direction', 'down')),
- 'amount': args.get('amount', node_params.get('amount', 500)),
- 'fullPage': args.get('fullPage', node_params.get('fullPage', False)),
- }
-
- return await handle_browser(
- node_id=config.get('node_id', 'tool_browser'),
- node_type='browser',
- parameters=parameters,
- context={'execution_id': config.get('execution_id', 'default')},
- )
-
-
-async def _execute_proxy_request(args: Dict[str, Any],
- node_params: Dict[str, Any],
- config: Dict[str, Any]) -> Dict[str, Any]:
- """Execute proxy HTTP request as an AI tool.
-
- Delegates to the standalone proxy request handler.
-
- Args:
- args: LLM-provided arguments (url, method, headers, body, etc.)
- node_params: Node parameters
- config: Full tool config with context
-
- Returns:
- Request result dict
- """
- from services.handlers.proxy import handle_proxy_request
-
- # Merge LLM args over node params
- merged = {**node_params, **{k: v for k, v in args.items() if v is not None}}
-
- context = config.get('context', {})
- node_id = config.get('node_id', 'tool_proxy_request')
- result = await handle_proxy_request(node_id, 'proxyRequest', merged, context)
- return result.get('result', result)
-async def _execute_proxy_status(args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute proxy status check as an AI tool.
- Delegates to the standalone proxy status handler.
-
- Args:
- args: LLM-provided arguments (providerFilter)
- node_params: Node parameters
-
- Returns:
- Status result dict
- """
- from services.handlers.proxy import handle_proxy_status
-
- merged = {**node_params, **{k: v for k, v in args.items() if v is not None}}
-
- result = await handle_proxy_status('tool_proxy_status', 'proxyStatus', merged, {})
- return result.get('result', result)
async def _execute_proxy_config(args: Dict[str, Any],
@@ -1666,26 +1251,5 @@ async def handle_task_manager(
# the BaseNode.execute_as_tool method on the plugin class.
# _execute_serper_search_tool stays until serperSearch is migrated.
-async def _execute_serper_search_tool(args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute Serper Search via handler (AI Agent tool wrapper)."""
- from services.handlers.search import handle_serper_search
-
- parameters = {**node_params, **args}
- return await handle_serper_search(
- node_id="tool_serper_search",
- node_type="serperSearch",
- parameters=parameters,
- context={}
- )
-
-
-async def _execute_email_tool(node_type: str, args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute email send/read as AI tool via EmailService."""
- from services.email_service import get_email_service
- svc = get_email_service()
- params = {**node_params, **{k: v for k, v in args.items() if v is not None}}
- if node_type == 'emailSend':
- return await svc.send(params)
- return await svc.read(params)
+
+
diff --git a/server/services/node_option_loaders/whatsapp_loaders.py b/server/services/node_option_loaders/whatsapp_loaders.py
index dc2d9964..f0e5e921 100644
--- a/server/services/node_option_loaders/whatsapp_loaders.py
+++ b/server/services/node_option_loaders/whatsapp_loaders.py
@@ -18,7 +18,7 @@ from typing import Any
async def load_whatsapp_groups(params: dict[str, Any]) -> list[dict[str, Any]]:
"""List WhatsApp groups for the recipient_type='group' selector."""
- from routers.whatsapp import handle_whatsapp_groups as _wa_groups
+ from services.whatsapp_service import handle_whatsapp_groups as _wa_groups
response = await _wa_groups()
groups = response.get("groups", []) if isinstance(response, dict) else []
@@ -34,7 +34,7 @@ async def load_whatsapp_groups(params: dict[str, Any]) -> list[dict[str, Any]]:
async def load_whatsapp_channels(params: dict[str, Any]) -> list[dict[str, Any]]:
"""List subscribed newsletter channels for the channel_jid selector."""
- from routers.whatsapp import handle_whatsapp_newsletters as _wa_newsletters
+ from services.whatsapp_service import handle_whatsapp_newsletters as _wa_newsletters
response = await _wa_newsletters()
channels = response.get("newsletters", []) if isinstance(response, dict) else []
@@ -51,7 +51,7 @@ async def load_whatsapp_group_members(params: dict[str, Any]) -> list[dict[str,
"""List members of a specific WhatsApp group for the senderNumber
selector. Depends on ``params['group_id']``."""
- from routers.whatsapp import handle_whatsapp_group_info as _wa_group_info
+ from services.whatsapp_service import handle_whatsapp_group_info as _wa_group_info
group_id = params.get("group_id") or params.get("groupId") or ""
if not group_id:
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index 722b5281..9bb80983 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -249,7 +249,7 @@ class StatusBroadcaster:
Silently fails if WhatsApp service is unavailable.
"""
try:
- from routers.whatsapp import get_client
+ from services.whatsapp_service import get_client
import time
client = await get_client()
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index 5586568e..c0e1828a 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -22,13 +22,10 @@ from temporalio.common import RetryPolicy
# Zeenie handles: input-skill, input-tools
CONFIG_HANDLES = {"input-tools", "input-memory", "input-model", "input-skill", "input-task", "input-teammates"}
-# Trigger node types - event listeners that should never be scheduled as blocking activities
-# Must be kept in sync with constants.WORKFLOW_TRIGGER_TYPES
-TRIGGER_NODE_TYPES = frozenset([
- "start", "cronScheduler", "webhookTrigger", "whatsappReceive",
- "workflowTrigger", "chatTrigger", "taskTrigger",
- "twitterReceive", "gmailReceive", "telegramReceive",
-])
+# Trigger node types — event listeners that should never be scheduled
+# as blocking activities. Imported from constants to avoid drift (was
+# previously redefined here with a "keep in sync" comment — Wave 11.E.2).
+from constants import WORKFLOW_TRIGGER_TYPES as TRIGGER_NODE_TYPES
# Android service types (connect to androidTool, not executed directly)
ANDROID_SERVICE_TYPES = {
diff --git a/server/routers/whatsapp.py b/server/services/whatsapp_service.py
similarity index 100%
rename from server/routers/whatsapp.py
rename to server/services/whatsapp_service.py