Skip to content

Self-improving AI Employees for everyone

refactor: Wave 11.E.4 — relocate tools.py movables to their domains

trohitg08b9fd41a9b7
diff --git a/server/nodes/android/_base.py b/server/nodes/android/_base.py
index c8063425..dcd552c6 100644
--- a/server/nodes/android/_base.py
+++ b/server/nodes/android/_base.py
@@ -121,3 +121,177 @@ class AndroidServiceBase(ActionNode, abstract=True):
if isinstance(result, dict):
return result.get("result") or result
return result
+
+
+# ============================================================================
+# AI-tool-time dispatchers (Wave 11.E.3)
+# ----------------------------------------------------------------------------
+# When an Android service or the androidTool aggregator is connected to an
+# AI agent's input-tools handle, the LLM emits ``{action, parameters}`` —
+# different shape from the workflow-node Params schema. These two helpers
+# do the LLM-arg-to-service-call translation + status broadcast and are
+# called from ``services/handlers/tools.py:execute_tool`` for the
+# ``androidTool`` and ``ANDROID_SERVICE_NODE_TYPES`` branches.
+# ============================================================================
+
+
+async def _execute_with_broadcast(
+ *, target_node_id: Optional[str], workflow_id: Optional[str],
+ service_id: str, action: str, parameters: Dict[str, Any],
+ host: str, port: int, log_label: str,
+) -> Dict[str, Any]:
+ """Run an Android service call with broadcast status for the UI node."""
+ from services.android_service import AndroidService
+ from services.status_broadcaster import get_status_broadcaster
+
+ broadcaster = get_status_broadcaster()
+ if target_node_id:
+ await broadcaster.update_node_status(
+ target_node_id, "executing",
+ {"message": f"Executing {action} via {log_label}"},
+ workflow_id=workflow_id,
+ )
+
+ try:
+ result = await AndroidService().execute_service(
+ node_id=target_node_id or 'tool',
+ service_id=service_id,
+ action=action,
+ parameters=parameters,
+ android_host=host,
+ android_port=port,
+ )
+
+ if target_node_id:
+ if result.get('success'):
+ await broadcaster.update_node_status(
+ target_node_id, "success",
+ {"message": f"{action} completed", "result": result.get('result', {})},
+ workflow_id=workflow_id,
+ )
+ else:
+ await broadcaster.update_node_status(
+ target_node_id, "error",
+ {"message": result.get('error', 'Unknown error')},
+ workflow_id=workflow_id,
+ )
+
+ if result.get('success'):
+ return {
+ "success": True,
+ "service": service_id,
+ "action": action,
+ "data": result.get('result', {}).get('data', result.get('result', {})),
+ }
+ return {
+ "error": result.get('error', 'Unknown error'),
+ "service": service_id,
+ "action": action,
+ }
+ except Exception as e:
+ logger.error(f"[{log_label}] Unexpected error: {e}")
+ if target_node_id:
+ await broadcaster.update_node_status(
+ target_node_id, "error",
+ {"message": str(e)},
+ workflow_id=workflow_id,
+ )
+ return {"error": str(e)}
+
+
+async def execute_android_toolkit(
+ args: Dict[str, Any], config: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Route an LLM tool call through the Android toolkit aggregator.
+
+ Looks up the connected service in ``config['connected_services']``
+ by ``service_id``, then executes through the broadcast helper.
+ """
+ service_id = args.get('service_id', '')
+ action = args.get('action', '')
+ parameters = args.get('parameters') or {}
+
+ connected_services = config.get('connected_services', [])
+ if not service_id:
+ available = [s.get('service_id') or s.get('node_type') for s in connected_services]
+ return {
+ "error": "No service_id provided",
+ "hint": (
+ f"Available services: {', '.join(available)}"
+ if available else "No services connected"
+ ),
+ }
+
+ target_service = next(
+ (
+ s for s in connected_services
+ if (s.get('service_id') or s.get('node_type')) == service_id
+ ),
+ None,
+ )
+ if not target_service:
+ available = [s.get('service_id') or s.get('node_type') for s in connected_services]
+ return {
+ "error": f"Service '{service_id}' not connected to toolkit",
+ "available_services": available,
+ }
+
+ svc_params = target_service.get('parameters', {})
+ host = svc_params.get('android_host', 'localhost')
+ port = int(svc_params.get('android_port', 8888))
+ if not action:
+ action = svc_params.get('action') or target_service.get('action', 'status')
+
+ target_node_id = target_service.get('node_id')
+ workflow_id = config.get('workflow_id')
+
+ logger.info(
+ "[Android Toolkit] Executing %s.%s via '%s' (node: %s, workflow: %s)",
+ service_id, action, target_service.get('label'),
+ target_node_id, workflow_id,
+ )
+
+ return await _execute_with_broadcast(
+ target_node_id=target_node_id,
+ workflow_id=workflow_id,
+ service_id=service_id,
+ action=action,
+ parameters=parameters,
+ host=host, port=port,
+ log_label="Android Toolkit",
+ )
+
+
+async def execute_android_service_tool(
+ args: Dict[str, Any], config: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Route an LLM tool call to a directly-connected Android service node.
+
+ Uses ``SERVICE_ID_MAP[node_type]`` instead of the synthetic toolkit
+ indirection — the LLM addresses each service node by its own type.
+ """
+ node_type = config.get('node_type', '')
+ node_id = config.get('node_id', '')
+ node_params = config.get('parameters', {})
+ workflow_id = config.get('workflow_id')
+
+ service_id = SERVICE_ID_MAP.get(node_type, node_type)
+ action = args.get('action') or node_params.get('action', 'status')
+ parameters = args.get('parameters') or {}
+ host = node_params.get('android_host', 'localhost')
+ port = int(node_params.get('android_port', 8888))
+
+ logger.info(
+ "[Android Service] Executing %s.%s (node: %s, workflow: %s)",
+ service_id, action, node_id, workflow_id,
+ )
+
+ return await _execute_with_broadcast(
+ target_node_id=node_id,
+ workflow_id=workflow_id,
+ service_id=service_id,
+ action=action,
+ parameters=parameters,
+ host=host, port=port,
+ log_label="Android Service",
+ )
diff --git a/server/nodes/proxy/proxy_config.py b/server/nodes/proxy/proxy_config.py
index 4bc3dd07..9e928d5b 100644
--- a/server/nodes/proxy/proxy_config.py
+++ b/server/nodes/proxy/proxy_config.py
@@ -1,13 +1,24 @@
-"""Proxy Config — Wave 11.C migration."""
+"""Proxy Config — Wave 11.E.3 inlined.
+
+10-operation dispatcher for managing proxy providers, credentials,
+and routing rules. Both the workflow node and the AI-tool fast-path
+land here.
+"""
from __future__ import annotations
+import json
+import time
from typing import Any, Dict, Literal, Optional
+import httpx
from pydantic import BaseModel, ConfigDict, Field
+from core.logging import get_logger
from services.plugin import ActionNode, NodeContext, Operation, TaskQueue
+logger = get_logger(__name__)
+
class ProxyConfigParams(BaseModel):
operation: Literal[
@@ -15,21 +26,257 @@ class ProxyConfigParams(BaseModel):
"set_credentials", "test_provider", "get_stats",
"add_routing_rule", "list_routing_rules", "remove_routing_rule",
] = "list_providers"
+ name: str = Field(default="")
provider_name: str = Field(default="", alias="providerName")
- config: Dict[str, Any] = Field(default_factory=dict)
+ gateway_host: str = Field(default="", alias="gateway_host")
+ gateway_port: int = Field(default=0, alias="gateway_port")
+ url_template: Any = Field(default="{}", alias="url_template")
+ cost_per_gb: float = Field(default=0.0, alias="cost_per_gb")
+ enabled: Optional[bool] = None
+ priority: int = Field(default=50)
+ username: str = Field(default="")
+ password: str = Field(default="")
+ domain_pattern: str = Field(default="", alias="domain_pattern")
+ preferred_providers: Any = Field(default="[]", alias="preferred_providers")
+ required_country: str = Field(default="", alias="required_country")
+ session_type: str = Field(default="rotating", alias="session_type")
+ rule_id: Optional[int] = None
model_config = ConfigDict(populate_by_name=True, extra="allow")
class ProxyConfigOutput(BaseModel):
operation: Optional[str] = None
+ success: Optional[bool] = None
providers: Optional[list] = None
rules: Optional[list] = None
- success: Optional[bool] = None
+ stats: Optional[dict] = None
+ name: Optional[str] = None
+ updated_fields: Optional[list] = None
+ domain_pattern: Optional[str] = None
+ rule_id: Optional[int] = None
+ ip: Optional[str] = None
+ latency_ms: Optional[float] = None
+ status_code: Optional[int] = None
model_config = ConfigDict(extra="allow")
+async def _list_providers(proxy_svc) -> Dict[str, Any]:
+ providers = proxy_svc.get_providers() if proxy_svc else []
+ return {"success": True, "providers": [p.model_dump() for p in providers]}
+
+
+async def _get_stats(proxy_svc) -> Dict[str, Any]:
+ return {"success": True, "stats": proxy_svc.get_stats() if proxy_svc else {}}
+
+
+async def _list_routing_rules(proxy_svc) -> Dict[str, Any]:
+ rules = proxy_svc.get_routing_rules() if proxy_svc else []
+ return {"success": True, "rules": [r.model_dump() for r in rules]}
+
+
+async def _add_provider(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ from core.container import container
+
+ name = p.get("name") or p.get("providerName")
+ if not name:
+ return {"success": False, "error": "Provider name is required"}
+
+ url_template_raw = p.get("url_template", "{}")
+ try:
+ url_template = (
+ json.loads(url_template_raw) if isinstance(url_template_raw, str) else url_template_raw
+ )
+ except json.JSONDecodeError:
+ return {"success": False, "error": f"Invalid url_template JSON: {url_template_raw}"}
+
+ db = container.database()
+ await db.save_proxy_provider({
+ "name": name,
+ "enabled": p.get("enabled", True),
+ "priority": int(p.get("priority", 50)),
+ "cost_per_gb": float(p.get("cost_per_gb", 0)),
+ "gateway_host": p.get("gateway_host", ""),
+ "gateway_port": int(p.get("gateway_port", 0)),
+ "url_template": json.dumps(url_template),
+ })
+ if proxy_svc:
+ await proxy_svc.reload_providers()
+ return {"success": True, "name": name}
+
+
+async def _update_provider(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ from core.container import container
+
+ name = p.get("name") or p.get("providerName")
+ if not name:
+ return {"success": False, "error": "Provider name is required"}
+ db = container.database()
+ existing = await db.get_proxy_provider(name)
+ if not existing:
+ return {"success": False, "error": f"Provider '{name}' not found"}
+
+ updates: Dict[str, Any] = {}
+ for field in ("gateway_host", "gateway_port", "cost_per_gb", "enabled", "priority"):
+ if p.get(field) is not None:
+ updates[field] = p[field]
+
+ url_template_raw = p.get("url_template")
+ if url_template_raw:
+ try:
+ url_template = (
+ json.loads(url_template_raw) if isinstance(url_template_raw, str) else url_template_raw
+ )
+ updates["url_template"] = json.dumps(url_template)
+ except json.JSONDecodeError:
+ return {"success": False, "error": "Invalid url_template JSON"}
+
+ if updates:
+ await db.save_proxy_provider({**existing, **updates})
+ if proxy_svc:
+ await proxy_svc.reload_providers()
+ return {"success": True, "name": name, "updated_fields": list(updates.keys())}
+
+
+async def _remove_provider(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ from core.container import container
+
+ name = p.get("name") or p.get("providerName")
+ if not name:
+ return {"success": False, "error": "Provider name is required"}
+ db = container.database()
+ await db.delete_proxy_provider(name)
+ if proxy_svc:
+ await proxy_svc.reload_providers()
+ return {"success": True, "name": name}
+
+
+async def _set_credentials(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ from core.container import container
+
+ name = p.get("name") or p.get("providerName")
+ if not name:
+ return {"success": False, "error": "Provider name is required"}
+ username, password = p.get("username", ""), p.get("password", "")
+ if not username or not password:
+ return {"success": False, "error": "Username and password are required"}
+
+ auth_svc = container.auth_service()
+ await auth_svc.store_api_key(f"proxy_{name}_username", username, [])
+ await auth_svc.store_api_key(f"proxy_{name}_password", password, [])
+ if proxy_svc:
+ await proxy_svc.reload_providers()
+ return {"success": True, "name": name}
+
+
+async def _test_provider(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ name = p.get("name") or p.get("providerName")
+ if not name:
+ return {"success": False, "error": "Provider name is required"}
+ if not proxy_svc:
+ return {"success": False, "error": "Proxy service not enabled"}
+
+ try:
+ proxy_url = await proxy_svc.get_proxy_url(
+ "https://httpbin.org/ip", {"proxyProvider": name},
+ )
+ if not proxy_url:
+ return {"success": False, "error": f"Could not get proxy URL for '{name}'"}
+
+ start = time.monotonic()
+ async with httpx.AsyncClient(proxy=proxy_url, timeout=30) as client:
+ resp = await client.get("https://httpbin.org/ip")
+ latency_ms = (time.monotonic() - start) * 1000
+
+ try:
+ ip = resp.json().get("origin", "unknown")
+ except Exception:
+ ip = "unknown"
+
+ return {
+ "success": resp.status_code == 200,
+ "name": name,
+ "ip": ip,
+ "latency_ms": round(latency_ms, 1),
+ "status_code": resp.status_code,
+ }
+ except Exception as e:
+ return {"success": False, "name": name, "error": str(e)}
+
+
+async def _add_routing_rule(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ from core.container import container
+
+ domain_pattern = p.get("domain_pattern", "")
+ if not domain_pattern:
+ return {"success": False, "error": "domain_pattern is required"}
+
+ preferred_raw = p.get("preferred_providers", "[]")
+ try:
+ preferred = (
+ json.loads(preferred_raw) if isinstance(preferred_raw, str) else preferred_raw
+ )
+ except json.JSONDecodeError:
+ preferred = []
+
+ db = container.database()
+ await db.save_proxy_routing_rule({
+ "domain_pattern": domain_pattern,
+ "preferred_providers": json.dumps(preferred),
+ "required_country": p.get("required_country", ""),
+ "session_type": p.get("session_type", "rotating"),
+ })
+ if proxy_svc:
+ await proxy_svc.reload_providers()
+ return {"success": True, "domain_pattern": domain_pattern}
+
+
+async def _remove_routing_rule(p: Dict[str, Any], proxy_svc) -> Dict[str, Any]:
+ from core.container import container
+
+ rule_id = p.get("rule_id")
+ if not rule_id:
+ return {"success": False, "error": "rule_id is required"}
+ db = container.database()
+ await db.delete_proxy_routing_rule(int(rule_id))
+ if proxy_svc:
+ await proxy_svc.reload_providers()
+ return {"success": True, "rule_id": rule_id}
+
+
+_OPS = {
+ "list_providers": lambda p, svc: _list_providers(svc),
+ "get_stats": lambda p, svc: _get_stats(svc),
+ "list_routing_rules": lambda p, svc: _list_routing_rules(svc),
+ "add_provider": _add_provider,
+ "update_provider": _update_provider,
+ "remove_provider": _remove_provider,
+ "set_credentials": _set_credentials,
+ "test_provider": _test_provider,
+ "add_routing_rule": _add_routing_rule,
+ "remove_routing_rule": _remove_routing_rule,
+}
+
+
+async def execute_proxy_config(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Run a proxy_config operation. Public entry point used by the
+ plugin's ``dispatch`` op AND by the legacy AI-tool fast-path in
+ ``handlers/tools.py:execute_tool``.
+ """
+ from services.proxy.service import get_proxy_service
+
+ operation = payload.get("operation", "list_providers")
+ handler = _OPS.get(operation)
+ if handler is None:
+ return {"success": False, "error": f"Unknown operation: {operation}"}
+
+ proxy_svc = get_proxy_service()
+ result = await handler(payload, proxy_svc)
+ result["operation"] = operation
+ return result
+
+
class ProxyConfigNode(ActionNode):
type = "proxyConfig"
display_name = "Proxy Config"
@@ -52,16 +299,7 @@ class ProxyConfigNode(ActionNode):
@Operation("dispatch")
async def dispatch(self, ctx: NodeContext, params: ProxyConfigParams) -> Any:
- """Wave 11.D.3: routes directly to tools.py dispatcher which
- owns the 10-operation matrix (list_providers / add_provider /
- update_provider / ... / list_routing_rules). Plugin body stays
- thin — the operation dispatcher is legacy AI-tool dispatch
- that predates the plugin fast-path and is scheduled for
- removal in 11.D.13."""
- from services.handlers.tools import _execute_proxy_config
-
- raw = params.model_dump(by_alias=True)
- result = await _execute_proxy_config(raw, raw)
+ result = await execute_proxy_config(params.model_dump(by_alias=True))
if not result.get("success"):
raise RuntimeError(result.get("error") or "Proxy config failed")
return result
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 8e23a1b1..ec3dddba 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -107,24 +107,29 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
# representation or cases needing special argument translation.
# androidTool (toolkit aggregator): dynamic schema derived from
- # connected services; no plugin class.
+ # connected services; no plugin class. Direct Android service nodes
+ # also need LLM-arg translation that doesn't fit the plugin Params
+ # shape. Both dispatchers live with their domain on
+ # nodes/android/_base.py (Wave 11.E.3 move).
if node_type == 'androidTool':
- return await _execute_android_toolkit(tool_args, config)
-
- # 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.
+ from nodes.android._base import execute_android_toolkit
+ return await execute_android_toolkit(tool_args, config)
if node_type in ANDROID_SERVICE_NODE_TYPES:
- return await _execute_android_service(tool_args, config)
+ from nodes.android._base import execute_android_service_tool
+ return await execute_android_service_tool(tool_args, config)
- # taskManager + proxyConfig: plugin bodies delegate back to the
- # _execute_* stubs below for their operation-dispatch matrices, so
- # keep those branches live.
+ # taskManager: dispatcher shares state with the agent-delegation
+ # tracking dicts (_delegated_tasks / _delegation_results) defined
+ # below in this module, so the operation matrix stays here.
if node_type == 'taskManager':
return await _execute_task_manager(tool_args, config)
+
+ # proxyConfig: 10-operation matrix lives on the plugin
+ # (nodes/proxy/proxy_config.execute_proxy_config). Plugin params win.
if node_type == 'proxyConfig':
- return await _execute_proxy_config(tool_args, config.get('parameters', {}))
+ from nodes.proxy.proxy_config import execute_proxy_config
+ merged = {**config.get('parameters', {}), **tool_args}
+ return await execute_proxy_config(merged)
# Built-in: Check delegated task results
# Auto-injected when parent has delegation tools
@@ -161,257 +166,8 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
# now routes through the plugin fast-path (nodes/whatsapp/*.py).
-async def _execute_android_toolkit(args: Dict[str, Any],
- config: Dict[str, Any]) -> Dict[str, Any]:
- """Execute Android toolkit by routing to connected service.
-
- Follows n8n Sub-Node execution pattern - the toolkit routes
- to the appropriate connected Android service node.
-
- Uses the existing AndroidService which handles both relay (remote)
- and local HTTP connections automatically.
-
- Args:
- args: LLM-provided arguments {service_id, action, parameters}
- config: Toolkit config with connected_services list
-
- Returns:
- Service execution result
- """
- from services.android_service import AndroidService
- from services.status_broadcaster import get_status_broadcaster
-
- service_id = args.get('service_id', '')
- action = args.get('action', '')
- parameters = args.get('parameters') or {}
-
- connected_services = config.get('connected_services', [])
-
- # Validate service_id provided
- if not service_id:
- available = [s.get('service_id') or s.get('node_type') for s in connected_services]
- return {
- "error": "No service_id provided",
- "hint": f"Available services: {', '.join(available)}" if available else "No services connected"
- }
-
- # Find matching connected service
- target_service = None
- for svc in connected_services:
- svc_id = svc.get('service_id') or svc.get('node_type')
- if svc_id == service_id:
- target_service = svc
- break
-
- if not target_service:
- available = [s.get('service_id') or s.get('node_type') for s in connected_services]
- return {
- "error": f"Service '{service_id}' not connected to toolkit",
- "available_services": available
- }
-
- # Get connection parameters from connected Android node
- svc_params = target_service.get('parameters', {})
- host = svc_params.get('android_host', 'localhost')
- port = int(svc_params.get('android_port', 8888))
-
- # Use provided action, or fall back to node's default action
- if not action:
- action = svc_params.get('action') or target_service.get('action', 'status')
-
- # Get the connected service's node_id for status broadcast
- service_node_id = target_service.get('node_id')
- # Get workflow_id from config for proper status scoping
- workflow_id = config.get('workflow_id')
-
- logger.info(f"[Android Toolkit] Executing {service_id}.{action} via '{target_service.get('label')}' (node: {service_node_id}, workflow: {workflow_id})")
-
- # Broadcast executing status for the connected Android service node
- # This makes the SquareNode show the animation
- broadcaster = get_status_broadcaster()
- if service_node_id:
- await broadcaster.update_node_status(
- service_node_id,
- "executing",
- {"message": f"Executing {action} via AI Agent toolkit"},
- workflow_id=workflow_id
- )
-
- try:
- # Use AndroidService which handles relay vs local connection automatically
- android_service = AndroidService()
- result = await android_service.execute_service(
- node_id=config.get('node_id', 'toolkit'),
- service_id=service_id,
- action=action,
- parameters=parameters,
- android_host=host,
- android_port=port
- )
-
- # Broadcast success/error status for the connected service node
- if service_node_id:
- if result.get('success'):
- await broadcaster.update_node_status(
- service_node_id,
- "success",
- {"message": f"{action} completed", "result": result.get('result', {})},
- workflow_id=workflow_id
- )
- else:
- await broadcaster.update_node_status(
- service_node_id,
- "error",
- {"message": result.get('error', 'Unknown error')},
- workflow_id=workflow_id
- )
-
- # Extract and return the relevant data
- if result.get('success'):
- return {
- "success": True,
- "service": service_id,
- "action": action,
- "data": result.get('result', {}).get('data', result.get('result', {}))
- }
- else:
- return {
- "error": result.get('error', 'Unknown error'),
- "service": service_id,
- "action": action
- }
-
- except Exception as e:
- logger.error(f"[Android Toolkit] Unexpected error: {e}")
- # Broadcast error status for the connected service node
- if service_node_id:
- await broadcaster.update_node_status(
- service_node_id,
- "error",
- {"message": str(e)},
- workflow_id=workflow_id
- )
- return {"error": str(e)}
-async def _execute_android_service(args: Dict[str, Any],
- config: Dict[str, Any]) -> Dict[str, Any]:
- """Execute a direct Android service node (not via toolkit).
-
- This handles Android service nodes (batteryMonitor, wifiAutomation, etc.)
- connected directly to the AI Agent's input-tools handle.
-
- Args:
- args: LLM-provided arguments {action, parameters}
- config: Tool config with node_type, node_id, parameters
-
- Returns:
- Service execution result
- """
- from services.android_service import AndroidService
- from services.status_broadcaster import get_status_broadcaster
-
- node_type = config.get('node_type', '')
- node_id = config.get('node_id', '')
- node_params = config.get('parameters', {})
- workflow_id = config.get('workflow_id')
-
- # Map node type to service_id (convert camelCase to snake_case)
- # e.g., batteryMonitor -> battery, wifiAutomation -> wifi_automation
- service_id_map = {
- 'batteryMonitor': 'battery',
- 'networkMonitor': 'network',
- 'systemInfo': 'system_info',
- 'location': 'location',
- 'appLauncher': 'app_launcher',
- 'appList': 'app_list',
- 'wifiAutomation': 'wifi_automation',
- 'bluetoothAutomation': 'bluetooth_automation',
- 'audioAutomation': 'audio_automation',
- 'deviceStateAutomation': 'device_state',
- 'screenControlAutomation': 'screen_control',
- 'airplaneModeControl': 'airplane_mode',
- 'motionDetection': 'motion_detection',
- 'environmentalSensors': 'environmental_sensors',
- 'cameraControl': 'camera_control',
- 'mediaControl': 'media_control',
- }
- service_id = service_id_map.get(node_type, node_type)
-
- # Get action from LLM args or fall back to node params or default
- action = args.get('action') or node_params.get('action', 'status')
- parameters = args.get('parameters') or {}
-
- # Get connection parameters from node
- host = node_params.get('android_host', 'localhost')
- port = int(node_params.get('android_port', 8888))
-
- logger.info(f"[Android Service] Executing {service_id}.{action} (node: {node_id}, workflow: {workflow_id})")
-
- # Broadcast executing status
- broadcaster = get_status_broadcaster()
- if node_id:
- await broadcaster.update_node_status(
- node_id,
- "executing",
- {"message": f"Executing {action} via AI Agent"},
- workflow_id=workflow_id
- )
-
- try:
- # Use AndroidService which handles relay vs local connection automatically
- android_service = AndroidService()
- result = await android_service.execute_service(
- node_id=node_id,
- service_id=service_id,
- action=action,
- parameters=parameters,
- android_host=host,
- android_port=port
- )
-
- # Broadcast success/error status
- if node_id:
- if result.get('success'):
- await broadcaster.update_node_status(
- node_id,
- "success",
- {"message": f"{action} completed", "result": result.get('result', {})},
- workflow_id=workflow_id
- )
- else:
- await broadcaster.update_node_status(
- node_id,
- "error",
- {"message": result.get('error', 'Unknown error')},
- workflow_id=workflow_id
- )
-
- # Extract and return the relevant data
- if result.get('success'):
- return {
- "success": True,
- "service": service_id,
- "action": action,
- "data": result.get('result', {}).get('data', result.get('result', {}))
- }
- else:
- return {
- "error": result.get('error', 'Unknown error'),
- "service": service_id,
- "action": action
- }
-
- except Exception as e:
- logger.error(f"[Android Service] Unexpected error: {e}")
- if node_id:
- await broadcaster.update_node_status(
- node_id,
- "error",
- {"message": str(e)},
- workflow_id=workflow_id
- )
- return {"error": str(e)}
# Wave 11.D.10: _execute_geocoding / _execute_nearby_places deleted.
@@ -434,201 +190,6 @@ async def _execute_android_service(args: Dict[str, Any],
-async def _execute_proxy_config(args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute proxy configuration operations.
-
- Manages proxy providers, credentials, and routing rules.
-
- Args:
- args: LLM-provided arguments (operation, name, etc.)
- node_params: Node parameters
-
- Returns:
- Operation result dict
- """
- import json as _json
- from core.container import container
- from services.proxy.service import get_proxy_service
-
- operation = args.get('operation', node_params.get('operation', ''))
- name = args.get('name', node_params.get('name', ''))
- proxy_svc = get_proxy_service()
-
- if operation == 'list_providers':
- providers = proxy_svc.get_providers() if proxy_svc else []
- return {"success": True, "operation": operation, "providers": [p.model_dump() for p in providers]}
-
- if operation == 'get_stats':
- stats = proxy_svc.get_stats() if proxy_svc else {}
- return {"success": True, "operation": operation, "stats": stats}
-
- if operation == 'list_routing_rules':
- rules = proxy_svc.get_routing_rules() if proxy_svc else []
- return {"success": True, "operation": operation, "rules": [r.model_dump() for r in rules]}
-
- if operation == 'add_provider':
- if not name:
- return {"success": False, "error": "Provider name is required"}
- gateway_host = args.get('gateway_host', node_params.get('gateway_host', ''))
- gateway_port = int(args.get('gateway_port', node_params.get('gateway_port', 0)))
- url_template_str = args.get('url_template', node_params.get('url_template', '{}'))
- cost_per_gb = float(args.get('cost_per_gb', node_params.get('cost_per_gb', 0)))
- enabled = args.get('enabled', node_params.get('enabled', True))
- priority = int(args.get('priority', node_params.get('priority', 50)))
-
- try:
- url_template = _json.loads(url_template_str) if isinstance(url_template_str, str) else url_template_str
- except _json.JSONDecodeError:
- return {"success": False, "error": f"Invalid url_template JSON: {url_template_str}"}
-
- db = container.database()
- await db.save_proxy_provider({
- "name": name,
- "enabled": enabled,
- "priority": priority,
- "cost_per_gb": cost_per_gb,
- "gateway_host": gateway_host,
- "gateway_port": gateway_port,
- "url_template": _json.dumps(url_template),
- })
-
- if proxy_svc:
- await proxy_svc.reload_providers()
-
- return {"success": True, "operation": operation, "name": name}
-
- if operation == 'update_provider':
- if not name:
- return {"success": False, "error": "Provider name is required"}
- db = container.database()
- existing = await db.get_proxy_provider(name)
- if not existing:
- return {"success": False, "error": f"Provider '{name}' not found"}
-
- updates = {}
- for field in ['gateway_host', 'gateway_port', 'cost_per_gb', 'enabled', 'priority']:
- val = args.get(field, node_params.get(field))
- if val is not None:
- updates[field] = val
-
- url_template_str = args.get('url_template', node_params.get('url_template'))
- if url_template_str:
- try:
- url_template = _json.loads(url_template_str) if isinstance(url_template_str, str) else url_template_str
- updates['url_template'] = _json.dumps(url_template)
- except _json.JSONDecodeError:
- return {"success": False, "error": f"Invalid url_template JSON"}
-
- if updates:
- merged = {**existing, **updates}
- await db.save_proxy_provider(merged)
- if proxy_svc:
- await proxy_svc.reload_providers()
-
- return {"success": True, "operation": operation, "name": name, "updated_fields": list(updates.keys())}
-
- if operation == 'remove_provider':
- if not name:
- return {"success": False, "error": "Provider name is required"}
- db = container.database()
- await db.delete_proxy_provider(name)
- if proxy_svc:
- await proxy_svc.reload_providers()
- return {"success": True, "operation": operation, "name": name}
-
- if operation == 'set_credentials':
- if not name:
- return {"success": False, "error": "Provider name is required"}
- username = args.get('username', node_params.get('username', ''))
- password = args.get('password', node_params.get('password', ''))
- if not username or not password:
- return {"success": False, "error": "Username and password are required"}
-
- auth_svc = container.auth_service()
- await auth_svc.store_api_key(f"proxy_{name}_username", username, [])
- await auth_svc.store_api_key(f"proxy_{name}_password", password, [])
-
- if proxy_svc:
- await proxy_svc.reload_providers()
-
- return {"success": True, "operation": operation, "name": name}
-
- if operation == 'test_provider':
- if not name:
- return {"success": False, "error": "Provider name is required"}
- if not proxy_svc:
- return {"success": False, "error": "Proxy service not enabled"}
-
- import time as _time
- import httpx
-
- try:
- proxy_url = await proxy_svc.get_proxy_url("https://httpbin.org/ip", {"proxyProvider": name})
- if not proxy_url:
- return {"success": False, "error": f"Could not get proxy URL for '{name}'"}
-
- start = _time.monotonic()
- async with httpx.AsyncClient(proxy=proxy_url, timeout=30) as client:
- resp = await client.get("https://httpbin.org/ip")
- latency_ms = (_time.monotonic() - start) * 1000
-
- try:
- data = resp.json()
- ip = data.get("origin", "unknown")
- except Exception:
- ip = "unknown"
-
- return {
- "success": resp.status_code == 200,
- "operation": operation,
- "name": name,
- "ip": ip,
- "latency_ms": round(latency_ms, 1),
- "status_code": resp.status_code,
- }
- except Exception as e:
- return {"success": False, "operation": operation, "name": name, "error": str(e)}
-
- if operation == 'add_routing_rule':
- domain_pattern = args.get('domain_pattern', node_params.get('domain_pattern', ''))
- if not domain_pattern:
- return {"success": False, "error": "domain_pattern is required"}
-
- preferred_str = args.get('preferred_providers', node_params.get('preferred_providers', '[]'))
- try:
- preferred = _json.loads(preferred_str) if isinstance(preferred_str, str) else preferred_str
- except _json.JSONDecodeError:
- preferred = []
-
- db = container.database()
- rule_data = {
- "domain_pattern": domain_pattern,
- "preferred_providers": _json.dumps(preferred),
- "required_country": args.get('required_country', node_params.get('required_country', '')),
- "session_type": args.get('session_type', node_params.get('session_type', 'rotating')),
- }
- await db.save_proxy_routing_rule(rule_data)
-
- if proxy_svc:
- await proxy_svc.reload_providers()
-
- return {"success": True, "operation": operation, "domain_pattern": domain_pattern}
-
- if operation == 'remove_routing_rule':
- rule_id = args.get('rule_id', node_params.get('rule_id'))
- if not rule_id:
- return {"success": False, "error": "rule_id is required"}
-
- db = container.database()
- await db.delete_proxy_routing_rule(int(rule_id))
-
- if proxy_svc:
- await proxy_svc.reload_providers()
-
- return {"success": True, "operation": operation, "rule_id": rule_id}
-
- return {"success": False, "error": f"Unknown operation: {operation}"}
async def _execute_generic(args: Dict[str, Any],