Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor: Wave 11.E.3 — inline remaining handler bodies into plugins
trohitg0ee6c5aafc69
diff --git a/server/nodes/agent/claude_code_agent.py b/server/nodes/agent/claude_code_agent.pyindex cd8f920f..8a7ede6b 100644--- a/server/nodes/agent/claude_code_agent.py+++ b/server/nodes/agent/claude_code_agent.py@@ -1,18 +1,25 @@-"""Claude Code Agent — Claude Code CLI as a specialized agent.+"""Claude Code Agent — Wave 11.E.3 inlined.-Distinct execute path: routes through ``handle_claude_code_agent``-which shells out to the local ``claude`` CLI binary with isolated auth.+Shells out to the local ``claude`` CLI binary (isolated auth via+``services/claude_oauth.py``). Status updates broadcast on entry ++exit; skill instructions concatenated into the system prompt."""from __future__ import annotations+import time+from datetime import datetimefrom typing import Any+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from services.plugin.edge_walker import collect_agent_connectionsfrom ._handles import STD_AGENT_HINTS, std_agent_handlesfrom ._specialized import SpecializedAgentOutput, SpecializedAgentParams+logger = get_logger(__name__)+class ClaudeCodeAgentNode(ActionNode):type = "claude_code_agent"@@ -34,19 +41,79 @@ 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.claude_code import handle_claude_code_agent+ from services.claude_code_service import get_claude_code_service+ from services.status_broadcaster import get_status_broadcaster- ai_service = container.ai_service()- database = container.database()+ start_time = time.time()+ broadcaster = get_status_broadcaster()+ workflow_id = ctx.workflow_id+ node_id = ctx.node_idpayload = params.model_dump(by_alias=True)- response = await handle_claude_code_agent(- ai_service=ai_service,- database=database,- node_id=ctx.node_id,- node_type=self.type,- parameters=payload,- context=ctx.raw,++ await broadcaster.update_node_status(+ node_id, "executing",+ {"message": "Starting Claude Code..."},+ workflow_id=workflow_id,+ )++ # Resolve prompt: explicit param wins; otherwise pull text from+ # the upstream node connected to input-main.+ prompt = payload.get("prompt", "")+ if not prompt:+ for edge in ctx.raw.get("edges", []):+ if edge.get("target") == node_id and edge.get("targetHandle") in ("input-main", None):+ src = ctx.raw.get("outputs", {}).get(edge.get("source"), {})+ if isinstance(src, dict):+ prompt = src.get("message") or src.get("text") or src.get("content") or str(src)+ elif src:+ prompt = str(src)+ if prompt:+ break+ if not prompt:+ raise RuntimeError("No prompt provided")++ database = container.database()+ _, skill_data, _, _, _ = await collect_agent_connections(node_id, ctx.raw, database)++ system_parts = []+ if payload.get("systemPrompt"):+ system_parts.append(payload["systemPrompt"])+ for skill in skill_data:+ instr = skill.get("parameters", {}).get("instructions", "")+ if instr:+ system_parts.append(instr)++ model = payload.get("model", "claude-sonnet-4-6")+ await broadcaster.update_node_status(+ node_id, "executing",+ {"message": f"Running Claude Code ({model})..."},+ workflow_id=workflow_id,+ )++ service = get_claude_code_service()+ data = await service.execute(+ prompt=prompt,+ node_id=node_id,+ model=model,+ cwd=payload.get("workingDirectory") or None,+ allowed_tools=payload.get("allowedTools", "Read,Edit,Bash,Glob,Grep,Write"),+ max_turns=int(payload.get("maxTurns", 10)),+ max_budget_usd=float(payload.get("maxBudgetUsd", 5.0)),+ system_prompt="\n\n".join(system_parts) if system_parts else None,)- if response.get("success"):- return response.get("result") or response- raise RuntimeError(response.get("error") or "claude_code_agent execution failed")++ await broadcaster.update_node_status(+ node_id, "success",+ {"message": "Claude Code completed"},+ workflow_id=workflow_id,+ )+ logger.debug("[ClaudeCode] node=%s elapsed=%.2fs", node_id, time.time() - start_time)++ return {+ "response": data.get("result", ""),+ "model": model,+ "provider": "anthropic",+ "session_id": data.get("session_id", ""),+ "usage": data.get("usage", {}),+ "timestamp": datetime.now().isoformat(),+ }diff --git a/server/nodes/agent/deep_agent.py b/server/nodes/agent/deep_agent.pyindex 58ac3b77..5db94d3c 100644--- a/server/nodes/agent/deep_agent.py+++ b/server/nodes/agent/deep_agent.py@@ -1,19 +1,26 @@-"""Deep Agent — LangChain DeepAgents with FS tools + sub-agent delegation.+"""Deep Agent — Wave 11.E.3 inlined.-Distinct execute path: routes through ``handlers/deep_agent.handle_deep_agent``-rather than the generic ``handle_chat_agent``. Different bottom-handle-ordering (Skill / Team / Tool) for the team-delegation UX.+LangChain DeepAgents with filesystem tools + sub-agent delegation.+Distinct from the generic chat agent: different bottom-handle ordering+(Skill / Team / Tool) for the team-delegation UX, and dispatches via+``ai_service.deep_agent_service.execute``."""from __future__ import annotationsfrom typing import Any+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from services.plugin.edge_walker import (+ collect_agent_connections, collect_teammate_connections, format_task_context,+)from ._handles import STD_AGENT_HINTS, deep_agent_handlesfrom ._specialized import SpecializedAgentOutput, SpecializedAgentParams+logger = get_logger(__name__)+class DeepAgentNode(ActionNode):type = "deep_agent"@@ -35,19 +42,64 @@ class DeepAgentNode(ActionNode):@Operation("execute", cost={"service": "deep_agent", "action": "run", "count": 1})async def execute_op(self, ctx: NodeContext, params: SpecializedAgentParams) -> Any:from core.container import container- from services.handlers.deep_agent import handle_deep_agent+ from services.status_broadcaster import get_status_broadcasterai_service = container.ai_service()database = container.database()+ node_id = ctx.node_id+ workflow_id = ctx.workflow_idpayload = params.model_dump(by_alias=True)- response = await handle_deep_agent(- ai_service=ai_service,++ # 1. Edge-walk for memory / skill / tool / input / task connections.+ memory_data, skill_data, tool_data, input_data, task_data = await collect_agent_connections(+ node_id, ctx.raw, database, log_prefix="[Deep Agent]",+ )++ # 2. Inject task-completion context into the prompt; strip tools+ # if the parent task is already done/errored.+ if task_data:+ payload = {+ **payload,+ 'prompt': f"{format_task_context(task_data)}\n\n{payload.get('prompt', '')}",+ }+ if task_data.get('status') in ('completed', 'error') and tool_data:+ tool_data = []++ # 3. Auto-prompt fallback from connected input.+ if not payload.get('prompt') and input_data:+ payload = {+ **payload,+ 'prompt': (+ input_data.get('message')+ or input_data.get('text')+ or input_data.get('content')+ or str(input_data)+ ),+ }++ # 4. Teammates (sub-agents wired to input-teammates).+ teammates = await collect_teammate_connections(node_id, ctx.raw, database)++ # 5. Pass the per-workflow workspace dir through so DeepAgents'+ # filesystem tools confine themselves correctly.+ workspace_dir = ctx.raw.get('workspace_dir')+ logger.info("[Deep Agent] workspace_dir from context: %s", workspace_dir)+ if workspace_dir:+ payload = {**payload, 'workspace_dir': workspace_dir}++ # 6. Delegate to DeepAgentService — service builds tools via the+ # ToolAdapter using ai_service._build_tool_from_node.+ response = await ai_service.deep_agent_service.execute(+ node_id, payload,+ memory_data=memory_data if memory_data else None,+ skill_data=skill_data if skill_data else None,+ tool_data=tool_data if tool_data else None,+ teammates=teammates if teammates else None,+ build_tool_fn=ai_service._build_tool_from_node,+ broadcaster=get_status_broadcaster(),+ workflow_id=workflow_id,database=database,- node_id=ctx.node_id,- node_type=self.type,- parameters=payload,- context=ctx.raw,)- if response.get("success"):- return response.get("result") or response- raise RuntimeError(response.get("error") or "deep_agent execution failed")+ if response.get("success") is False:+ raise RuntimeError(response.get("error") or "deep_agent execution failed")+ return response.get("result") or responsediff --git a/server/nodes/agent/rlm_agent.py b/server/nodes/agent/rlm_agent.pyindex 75e696b8..d01bc710 100644--- a/server/nodes/agent/rlm_agent.py+++ b/server/nodes/agent/rlm_agent.py@@ -1,19 +1,25 @@-"""RLM Agent — Recursive Language Model agent (REPL-based).+"""RLM Agent — Wave 11.E.3 inlined.-Distinct from the standard LangGraph chat agent — uses-``handle_rlm_agent`` which spins a recursive language-model loop-inside a REPL sandbox.+Recursive Language Model agent. Distinct from the standard LangGraph+chat agent — spins a recursive LM loop inside a REPL sandbox via+``ai_service.rlm_service.execute``."""from __future__ import annotationsfrom typing import Any+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from services.plugin.edge_walker import (+ collect_agent_connections, format_task_context,+)from ._handles import STD_AGENT_HINTS, std_agent_handlesfrom ._specialized import SpecializedAgentOutput, SpecializedAgentParams+logger = get_logger(__name__)+class RLMAgentNode(ActionNode):type = "rlm_agent"@@ -35,19 +41,60 @@ 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.rlm import handle_rlm_agent+ from services.status_broadcaster import get_status_broadcasterai_service = container.ai_service()database = container.database()+ node_id = ctx.node_id+ workflow_id = ctx.workflow_idpayload = params.model_dump(by_alias=True)- response = await handle_rlm_agent(- ai_service=ai_service,- database=database,- node_id=ctx.node_id,- node_type=self.type,- parameters=payload,++ # 1. Edge-walk for memory / skill / tool / input / task connections.+ memory_data, skill_data, tool_data, input_data, task_data = await collect_agent_connections(+ node_id, ctx.raw, database, log_prefix="[RLM Agent]",+ )++ # 2. Inject task-completion context into the prompt.+ if task_data:+ payload = {+ **payload,+ 'prompt': f"{format_task_context(task_data)}\n\n{payload.get('prompt', '')}",+ }+ logger.info(+ "[RLM Agent] Task context injected for task_id=%s",+ task_data.get('task_id'),+ )+ # 3. Strip tools when the agent is being asked to react to a+ # completed/errored task — there's nothing to invoke.+ if task_data.get('status') in ('completed', 'error') and tool_data:+ tool_data = []+ logger.info("[RLM Agent] Stripped tools for task completion handling")++ # 4. Auto-prompt fallback: if no prompt + an input is connected,+ # use the input's text-shaped field.+ if not payload.get('prompt') and input_data:+ payload = {+ **payload,+ 'prompt': (+ input_data.get('message')+ or input_data.get('text')+ or input_data.get('content')+ or str(input_data)+ ),+ }+ logger.info("[RLM Agent] Auto-using input as prompt")++ # 5. Delegate to the RLM service.+ response = await ai_service.rlm_service.execute(+ node_id, payload,+ memory_data=memory_data,+ skill_data=skill_data if skill_data else None,+ tool_data=tool_data if tool_data else None,+ broadcaster=get_status_broadcaster(),+ workflow_id=workflow_id,context=ctx.raw,+ database=database,)- if response.get("success"):- return response.get("result") or response- raise RuntimeError(response.get("error") or "rlm_agent execution failed")+ if response.get("success") is False:+ raise RuntimeError(response.get("error") or "rlm_agent execution failed")+ return response.get("result") or responsediff --git a/server/nodes/android/_base.py b/server/nodes/android/_base.pyindex 69a2d671..c8063425 100644--- a/server/nodes/android/_base.py+++ b/server/nodes/android/_base.py@@ -1,20 +1,46 @@"""Shared base for Android service plugins.16 Android nodes (battery, network, wifi, bluetooth, audio, camera, …)-all dispatch through the same ``handle_android_service`` handler with-the node_type as the service ID. Subclass + set 5 attrs to mint a new-one. ``android_service`` is fetched from the DI container at call-time — Android relay client is process-singleton.+all dispatch through ``invoke()`` with the node_type as the service ID.+Subclass + set 5 attrs to mint a new one. ``android_service`` is fetched+from the DI container at call time — Android relay client is process+singleton."""from __future__ import annotations+import jsonfrom typing import Any, Dict, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+logger = get_logger(__name__)+++# Maps camelCase node types to snake_case service IDs.+# Same map is mirrored in services/handlers/tools.py for the AI-tool path.+SERVICE_ID_MAP: Dict[str, str] = {+ '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',+}+class AndroidServiceParams(BaseModel):action: str = Field(default="status", description="Service action to invoke")@@ -52,17 +78,46 @@ class AndroidServiceBase(ActionNode, abstract=True):@Operation("invoke", cost={"service": "android", "action": "service_call", "count": 1})async def invoke(self, ctx: NodeContext, params: AndroidServiceParams) -> Any:from core.container import container- from services.handlers.android import handle_android_serviceandroid_service = container.android_service()payload = params.model_dump()- response = await handle_android_service(- android_service=android_service,++ # Derive service_id from the registered node type (battery etc.) —+ # hidden params may not be in the DB so the type is the source of truth.+ service_id = SERVICE_ID_MAP.get(self.type, payload.get('service_id', 'battery'))+ action = payload.get('action', 'status')+ service_params = payload.get('parameters', {})+ android_host = payload.get('android_host', 'localhost')+ android_port = payload.get('android_port', 8888)++ # Parse JSON-string parameters defensively.+ if isinstance(service_params, str):+ try:+ service_params = json.loads(service_params)+ except json.JSONDecodeError:+ service_params = {}++ # Hoist root-level additional properties (e.g. package_name from+ # appLauncher's additionalProperties UI) into service_params.+ for key in ('package_name',):+ if payload.get(key):+ service_params[key] = payload[key]++ logger.debug(+ "[Android] node_type=%s -> service_id=%s action=%s host=%s:%s params=%s",+ self.type, service_id, action, android_host, android_port, service_params,+ )++ result = await android_service.execute_service(node_id=ctx.node_id,- node_type=self.type,- parameters=payload,- context=ctx.raw,+ service_id=service_id,+ action=action,+ parameters=service_params,+ android_host=android_host,+ android_port=android_port,)- if response.get("success"):- return response.get("result") or response- raise RuntimeError(response.get("error") or f"{self.type} failed")+ if isinstance(result, dict) and result.get("success") is False:+ raise RuntimeError(result.get("error") or f"{self.type} failed")+ if isinstance(result, dict):+ return result.get("result") or result+ return resultdiff --git a/server/nodes/browser/browser.py b/server/nodes/browser/browser.pyindex 5784e58a..dfd4b6bd 100644--- a/server/nodes/browser/browser.py+++ b/server/nodes/browser/browser.py@@ -1,13 +1,146 @@-"""Browser — Wave 11.C migration. agent-browser CLI wrapper."""+"""Browser — Wave 11.E.3 inlined.++Interactive browser automation via the agent-browser CLI. The plugin+maps the high-level operation enum to CLI argv, resolves the browser+binary (system Chrome / Edge / Chromium / bundled), and delegates the+subprocess invocation to ``services.browser_service``.+"""from __future__ import annotations-from typing import Any, Literal, Optional+import json+import shutil+import sys+import time+from typing import Any, Dict, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+logger = get_logger(__name__)+++# PATH-based names for shutil.which() (Linux/macOS/Windows where on PATH).+_BROWSER_PATH_NAMES = {+ "chrome": ["google-chrome", "google-chrome-stable", "chrome"],+ "edge": ["microsoft-edge", "microsoft-edge-stable", "msedge"],+ "chromium": ["chromium", "chromium-browser"],+}++# Windows registry App Paths keys (how Selenium/Playwright find browsers).+_BROWSER_REGISTRY_KEYS = {+ "chrome": "chrome.exe",+ "edge": "msedge.exe",+ "chromium": "chrome.exe",+}+++def _find_browser_via_registry(exe_name: str) -> Optional[str]:+ """Find a browser executable via the Windows App Paths registry.++ HKLM/HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\<exe>+ """+ try:+ import winreg+ for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):+ try:+ key = winreg.OpenKey(+ hive,+ rf"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{exe_name}",+ )+ path, _ = winreg.QueryValueEx(key, "")+ winreg.CloseKey(key)+ if path:+ return path+ except OSError:+ continue+ except ImportError:+ pass+ return None+++def _resolve_browser(selection: str, custom_path: str) -> Optional[str]:+ """Resolve a browser dropdown selection to an executable path."""+ if selection in ("bundled", "bundled_explicit") or not selection:+ return None+ if selection == "custom":+ return custom_path or None++ for name in _BROWSER_PATH_NAMES.get(selection, []):+ path = shutil.which(name)+ if path:+ return path++ if sys.platform == "win32":+ reg_name = _BROWSER_REGISTRY_KEYS.get(selection)+ if reg_name:+ path = _find_browser_via_registry(reg_name)+ if path:+ return path+ return None+++def _req(p: Dict[str, Any], key: str) -> str:+ v = (p.get(key) or "").strip()+ if not v:+ raise ValueError(f"{key} is required")+ return v+++def _req_sel(s: str) -> str:+ if not s:+ raise ValueError("selector is required")+ return s+++def _build_args(op: str, p: Dict[str, Any]) -> List[str]:+ """Map an operation name + parameters to agent-browser CLI arguments."""+ s = (p.get("selector") or "").strip()+ match op:+ case "navigate":+ return ["open", _req(p, "url")]+ case "click":+ return ["click", _req_sel(s)]+ case "type":+ return ["type", _req_sel(s), p.get("text") or ""]+ case "fill":+ return ["fill", _req_sel(s), p.get("value") or ""]+ case "screenshot":+ args = ["screenshot"]+ if p.get("fullPage"):+ args.append("--full")+ if p.get("annotate"):+ args.append("--annotate")+ fmt = p.get("screenshotFormat", "png")+ if fmt and fmt != "png":+ args.extend(["--screenshot-format", fmt])+ quality = p.get("screenshotQuality")+ if quality and fmt == "jpeg":+ args.extend(["--screenshot-quality", str(quality)])+ return args+ case "snapshot":+ return ["snapshot", "-i"]+ case "get_text":+ return ["get", "text", _req_sel(s)]+ case "get_html":+ return ["get", "html", _req_sel(s)]+ case "eval":+ return ["eval", _req(p, "expression")]+ case "wait":+ return ["wait", _req_sel(s)]+ case "scroll":+ return ["scroll", p.get("direction") or "down", str(p.get("amount") or 500)]+ case "select":+ return ["select", _req_sel(s), p.get("value") or ""]+ case "console":+ return ["console"]+ case "errors":+ return ["errors"]+ case _:+ raise ValueError(f"Unknown operation: {op}")+class BrowserParams(BaseModel):operation: Literal[@@ -24,8 +157,8 @@ class BrowserParams(BaseModel):class BrowserOutput(BaseModel):operation: Optional[str] = None- snapshot: Optional[Any] = None- text: Optional[str] = None+ data: Optional[Any] = None+ session: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")@@ -51,12 +184,53 @@ class BrowserNode(ActionNode):Output = BrowserOutput@Operation("dispatch")- async def dispatch(self, ctx: NodeContext, params: BrowserParams) -> Any:- from services.handlers.browser import handle_browser- response = await handle_browser(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,+ async def dispatch(self, ctx: NodeContext, params: BrowserParams) -> BrowserOutput:+ from services.browser_service import get_browser_service++ svc = get_browser_service()+ if not svc:+ raise RuntimeError(+ "agent-browser not installed. Run: pnpm install && npx agent-browser install",+ )++ p = params.model_dump(by_alias=True)+ op = p.get("operation") or "navigate"+ session = (+ (p.get("session") or "").strip()+ or f"machina_{ctx.raw.get('execution_id', 'default')}"+ )+ timeout = int(p.get("timeout") or 30)+ headed = bool(p.get("headed", True))+ auto_connect = bool(p.get("autoConnect", False))+ browser_sel = p.get("browser", "chrome")+ if not browser_sel or browser_sel == "bundled":+ browser_sel = "chrome"+ custom_path = (p.get("executablePath") or "").strip()+ executable_path = _resolve_browser(browser_sel, custom_path)+ logger.info("[Browser] browser=%s executable=%s", browser_sel, executable_path)+ new_window = bool(p.get("newWindow", True)) and executable_path is not None+ chrome_profile = (p.get("chromeProfile") or "").strip() or None+ user_agent = (p.get("userAgent") or "").strip() or None+ proxy = (p.get("proxy") or "").strip() or None+ action_delay = int(p.get("actionDelay") or 0)++ run_kw = dict(+ headed=headed, user_agent=user_agent, proxy=proxy,+ executable_path=executable_path, auto_connect=auto_connect,+ chrome_profile=chrome_profile, new_window=new_window,)- if response.get("success"):- return response.get("result") or response- raise RuntimeError(response.get("error") or "Browser op failed")++ if action_delay > 0:+ await svc.run(["wait", str(action_delay)], session, timeout, **run_kw)++ if op == "batch":+ cmds = json.loads(p.get("commands", "[]"))+ data = await svc.run(+ ["batch", "--json"], session, timeout,+ stdin=json.dumps(cmds).encode(),+ **run_kw,+ )+ else:+ data = await svc.run(_build_args(op, p), session, timeout, **run_kw)++ return BrowserOutput(operation=op, data=data, session=session)diff --git a/server/nodes/model/_base.py b/server/nodes/model/_base.pyindex 323ad271..3c6afc41 100644--- a/server/nodes/model/_base.py+++ b/server/nodes/model/_base.py@@ -84,16 +84,10 @@ class ChatModelBase(ActionNode, abstract=True):@Operation("chat", cost={"service": "chat_model", "action": "chat", "count": 1})async def chat(self, ctx: NodeContext, params: ChatModelParams) -> Any:from core.container import container- from services.handlers.ai import handle_ai_chat_modelai_service = container.ai_service()- payload = params.model_dump(by_alias=True)- response = await handle_ai_chat_model(- ai_service=ai_service,- node_id=ctx.node_id,- node_type=self.type,- parameters=payload,- context=ctx.raw,+ response = await ai_service.execute_chat(+ ctx.node_id, self.type, params.model_dump(by_alias=True),)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/skill/simple_memory.py b/server/nodes/skill/simple_memory.pyindex 9b9fc903..9af34919 100644--- a/server/nodes/skill/simple_memory.py+++ b/server/nodes/skill/simple_memory.py@@ -1,8 +1,10 @@-"""Simple Memory — Wave 11.C migration.+"""Simple Memory — Wave 11.E.3 inlined.Markdown-based conversation memory, optionally backed by a vectorstore for semantic recall. Connects upward to an agent's input-memory-handle. Delegates execution to the legacy ``handle_simple_memory``.+handle. The plugin queries the in-memory ``MessageStore`` directly;+agents read the ``memory_content`` parameter (the editable markdown)+plus the live message log returned here."""from __future__ import annotations@@ -11,8 +13,11 @@ from typing import Any, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+logger = get_logger(__name__)+class SimpleMemoryParams(BaseModel):session_id: str = Field(default="default", alias="sessionId")@@ -59,12 +64,34 @@ class SimpleMemoryNode(ActionNode):Output = SimpleMemoryOutput@Operation("read")- async def read(self, ctx: NodeContext, params: SimpleMemoryParams) -> Any:- from services.handlers.ai import handle_simple_memory- response = await handle_simple_memory(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,+ async def read(self, ctx: NodeContext, params: SimpleMemoryParams) -> SimpleMemoryOutput:+ """Return the current message log for the session.++ ``memory_type`` (legacy alias-only field, defaults to ``buffer``)+ and ``clear_on_run`` are read straight off the raw payload+ because they're optional UI toggles, not part of the canonical+ Params surface.+ """+ from services.memory_store import clear_session, get_messages++ payload = params.model_dump(by_alias=True)+ session_id = payload.get("sessionId", params.session_id)+ memory_type = payload.get("memoryType", "buffer")+ window_size = (+ int(payload.get("windowSize", params.window_size))+ if memory_type == "window" else None+ )++ if payload.get("clearOnRun"):+ cleared = clear_session(session_id)+ logger.info("[Memory] Cleared %d messages from session '%s'", cleared, session_id)++ messages = get_messages(session_id, window_size)+ return SimpleMemoryOutput(+ memory_content=params.memory_content,+ message_count=len(messages),+ session_id=session_id,+ messages=messages,+ memory_type=memory_type,+ window_size=window_size,)- if response.get("success") is False:- raise RuntimeError(response.get("error") or "simpleMemory failed")- return response.get("result") or {}diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex 4da51e08..fef2a517 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -1,150 +1,23 @@-"""Node handlers package - extracted from workflow.py for maintainability.--This package contains all node execution handlers organized by category:-- ai.py: AI Agent, AI Chat Model, Simple Memory-- android.py: Android Device Setup, Android Services-- code.py: Python Executor, JavaScript Executor-- document.py: HTTP Scraper, File Downloader, Document Parser, Text Chunker, Embedding Generator, Vector Store-- http.py: HTTP Request, Webhook Response-- tools.py: Tool execution handlers for AI Agent tool calling-- triggers.py: Generic trigger node handler-- utility.py: Maps, Text, Chat, Cron, Start-- whatsapp.py: WhatsApp Send, WhatsApp DB-- social.py: Social Receive, Social Send (unified messaging)-- gmail.py: Consolidated Gmail handler (send, search, read)-- calendar.py: Consolidated Calendar handler (create, list, update, delete)-- drive.py: Consolidated Drive handler (upload, download, list, share)-- sheets.py: Consolidated Sheets handler (read, write, append)-- tasks.py: Consolidated Tasks handler (create, list, complete, update, delete)-- contacts.py: Consolidated Contacts handler (create, list, search, get, update, delete)+"""Node handler shims.++Most handler bodies were inlined into their plugin files during Wave+11.D / 11.E. What remains here is the cross-cutting machinery:++- ``tools.py`` — AI-tool dispatcher + plugin fast-path + Android+ toolkit + agent delegation.+- ``ai.py`` — agent-execution shims (``handle_ai_agent`` etc.)+ called by the agent plugins via+ ``nodes/agent/_inline.prepare_agent_call``.+- ``android.py`` — direct Android service execution.+- ``browser.py`` — agent-browser CLI wrapper.+- ``claude_code.py`` — Claude Code SDK wrapper.+- ``deep_agent.py`` — DeepAgents bridge.+- ``rlm.py`` — RLM agent execution.+- ``triggers.py`` — generic trigger node handler.+- ``google_auth.py`` — shared OAuth helper for Google plugins (kept+ alive by ``credentials/google.GoogleCredential``).++The package ``__init__.py`` deliberately stays empty: nothing imports+from ``services.handlers`` at the package level — every consumer+imports the specific submodule it needs."""--# AI handlers-from .ai import (- handle_ai_agent,- handle_chat_agent,- handle_ai_chat_model,- handle_simple_memory,-)--# Android handlers-from .android import (- handle_android_service,-)--# Code execution handlers-from .code import (- handle_python_executor,- handle_javascript_executor,- handle_typescript_executor,-)--# HTTP handlers-from .http import (- handle_http_request,- handle_webhook_response,-)--# Trigger handlers-from .triggers import (- handle_trigger_node,-)--# Utility handlers inlined into their plugin files (Wave 11.D.10).--# WhatsApp handlers inlined into nodes/whatsapp/*.py (Wave 11.D.9).--# Twitter handlers inlined into nodes/twitter/*.py (Wave 11.D.8).--# Google Workspace handlers inlined into nodes/google/*.py (Wave 11.D.4).--# Social handlers inlined into nodes/social/*.py (Wave 11.D.9).--# Document handlers inlined into nodes/document/*.py (Wave 11.D.7).--# Search handlers-from .search import (- handle_brave_search,- handle_serper_search,- handle_perplexity_search,-)--# Email handlers (Himalaya CLI)-from .email import handle_email_send, handle_email_read, handle_email_receive--# Crawlee handler inlined into nodes/scraper/crawlee_scraper.py (Wave 11.D.8).--# Browser automation handler (agent-browser CLI)-from .browser import handle_browser--# RLM agent handler-from .rlm import handle_rlm_agent--# Deep Agent handler-from .deep_agent import handle_deep_agent--# Filesystem and shell handlers-from .filesystem import (- handle_file_read,- handle_file_modify,- handle_shell,- handle_fs_search,-)--# Tool execution handlers (for AI Agent tool calling)-from .tools import (- execute_tool,- handle_task_manager,-)--# Todo handler-from .todo import execute_write_todos, handle_write_todos--# Process manager handler-from .process import execute_process_manager, handle_process_manager--__all__ = [- # AI- 'handle_ai_agent',- 'handle_chat_agent',- 'handle_ai_chat_model',- 'handle_simple_memory',- # Android- 'handle_android_service',- # Code- 'handle_python_executor',- 'handle_javascript_executor',- 'handle_typescript_executor',- # HTTP- 'handle_http_request',- 'handle_webhook_response',- # Triggers- 'handle_trigger_node',- # Utility- # Social- # Search- 'handle_brave_search',- 'handle_serper_search',- 'handle_perplexity_search',- # RLM- 'handle_rlm_agent',- # Deep Agent- 'handle_deep_agent',- # Filesystem & Shell- 'handle_file_read',- 'handle_file_modify',- 'handle_shell',- 'handle_fs_search',- 'handle_email_send',- 'handle_email_read',- 'handle_email_receive',- # Tools- 'execute_tool',- 'handle_task_manager',- # Todo- 'execute_write_todos',- 'handle_write_todos',-]diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.pydeleted file mode 100644index e0a1c9f2..00000000--- a/server/services/handlers/ai.py+++ /dev/null@@ -1,286 +0,0 @@-"""AI node handlers - AI Agent, Zeenie, AI Chat Model, Simple Memory.--Wave 11.D.0: edge-walking helpers (collect_agent_connections,-collect_teammate_connections, format_task_context) moved to-``services/plugin/edge_walker.py``. The three underscore-prefixed-shims below keep this module's public surface intact while-agent plugins migrate to the new import path directly.-"""--from typing import Dict, Any, List, Optional, Tuple, TYPE_CHECKING-from core.logging import get_logger-from constants import ANDROID_SERVICE_NODE_TYPES, AI_AGENT_TYPES-from services.plugin.edge_walker import (- collect_agent_connections as _ew_collect_agent_connections,- collect_teammate_connections as _ew_collect_teammate_connections,- format_task_context as _ew_format_task_context,-)--if TYPE_CHECKING:- from services.ai import AIService- from core.database import Database--logger = get_logger(__name__)--# Team lead types that can create teams-TEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}---async def _collect_agent_connections(- node_id: str,- 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]], Optional[Dict[str, Any]]]:- """Back-compat shim — body moved to ``services/plugin/edge_walker.py``."""- return await _ew_collect_agent_connections(node_id, context, database, log_prefix)---async def _collect_teammate_connections(- node_id: str,- context: Dict[str, Any],- database: "Database",-) -> List[Dict[str, Any]]:- """Back-compat shim — body moved to ``services/plugin/edge_walker.py``."""- return await _ew_collect_teammate_connections(node_id, context, database)---def _format_task_context(task_data: Dict[str, Any]) -> str:- """Back-compat shim — body moved to ``services/plugin/edge_walker.py``."""- return _ew_format_task_context(task_data)---async def handle_ai_agent(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- ai_service: "AIService",- database: "Database"-) -> Dict[str, Any]:- """Handle AI agent node execution with memory, skill, and tool support.-- Args:- node_id: The node ID- node_type: The node type (aiAgent)- parameters: Resolved parameters- context: Execution context with nodes, edges, session_id, start_time, execution_id- ai_service: The AI service instance- database: The database instance-- Returns:- Execution result dict- """- workflow_id = context.get('workflow_id')-- # 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 ALL tools when handling task completion- # When reporting a delegated task result, the agent should NOT use any tools.- # Binding tools while instructing "do not use tools" confuses Gemini (returns empty []).- # The agent's only job is to report the result naturally.- task_status = task_data.get('status', '')- if task_status in ('completed', 'error') and tool_data:- original_tool_count = len(tool_data)- # Strip ALL tools - agent is just reporting result, not executing anything- tool_data = []- logger.info(f"[AI Agent] Stripped ALL {original_tool_count} 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 = (- input_data.get('message') or- input_data.get('text') or- input_data.get('content') or- str(input_data)- )- parameters = {**parameters, 'prompt': prompt}- logger.info(f"[AI Agent] Auto-using input as prompt: {prompt[:100] if len(str(prompt)) > 100 else prompt}...")-- # Get broadcaster for real-time status updates- from services.status_broadcaster import get_status_broadcaster- broadcaster = get_status_broadcaster()-- return await ai_service.execute_agent(- node_id,- parameters,- memory_data=memory_data,- skill_data=skill_data if skill_data else None,- tool_data=tool_data if tool_data else None,- broadcaster=broadcaster,- workflow_id=workflow_id,- context=context, # Pass context for nested agent delegation- database=database # Pass database for default model lookup- )---async def handle_chat_agent(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- ai_service: "AIService",- database: "Database"-) -> Dict[str, Any]:- """Handle Zeenie node execution with skill-based tool calling.-- Zeenie supports:- - Memory (input-memory): SimpleMemory node for conversation history- - Skills (input-skill): Provide context/instructions via SKILL.md- - Tools (input-tools): Tool nodes (httpRequest, etc.) for LangGraph tool calling- - Input fallback (input-main or input-chat): Auto-use connected node output as prompt-- Args:- node_id: The node ID- node_type: The node type (chatAgent)- parameters: Resolved parameters- context: Execution context with nodes, edges, session_id, start_time, execution_id- ai_service: The AI service instance- database: The database instance-- Returns:- Execution result dict- """- workflow_id = context.get('workflow_id')-- # 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 ALL tools when handling task completion- # When reporting a delegated task result, the agent should NOT use any tools.- # Binding tools while instructing "do not use tools" confuses Gemini (returns empty []).- # The agent's only job is to report the result naturally.- task_status = task_data.get('status', '')- if task_status in ('completed', 'error') and tool_data:- original_tool_count = len(tool_data)- # Strip ALL tools - agent is just reporting result, not executing anything- tool_data = []- logger.info(f"[Chat Agent] Stripped ALL {original_tool_count} 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 = (- input_data.get('message') or- input_data.get('text') or- input_data.get('content') or- str(input_data)- )- parameters = {**parameters, 'prompt': prompt}- logger.info(f"[Chat Agent] Auto-using input as prompt: {prompt[:100] if len(str(prompt)) > 100 else prompt}...")-- # Get broadcaster for real-time status updates- from services.status_broadcaster import get_status_broadcaster- broadcaster = get_status_broadcaster()-- # Team mode detection for orchestrator_agent and ai_employee nodes- # Teammates connected via input-teammates become delegation tools- if node_type in TEAM_LEAD_TYPES:- teammates = await _collect_teammate_connections(node_id, context, database)-- if teammates:- # Add teammates as delegation tools (they become delegate_to_* tools)- tool_data = tool_data or []- for tm in teammates:- tool_data.append({- 'node_id': tm['node_id'],- 'node_type': tm['node_type'],- 'label': tm['label'],- 'parameters': tm.get('parameters', {}),- })- logger.info(f"[Teams] Added {len(teammates)} teammates as delegation tools")-- # Standard execution (no team mode)- return await ai_service.execute_chat_agent(- node_id,- parameters,- memory_data=memory_data,- skill_data=skill_data if skill_data else None,- tool_data=tool_data if tool_data else None,- broadcaster=broadcaster,- workflow_id=workflow_id,- context=context,- database=database- )---async def handle_ai_chat_model(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- ai_service: "AIService"-) -> Dict[str, Any]:- """Handle AI chat model node execution.-- Args:- node_id: The node ID- node_type: The node type (openaiChatModel, anthropicChatModel, etc.)- parameters: Resolved parameters- context: Execution context- ai_service: The AI service instance-- Returns:- Execution result dict- """- return await ai_service.execute_chat(node_id, node_type, parameters)---async def handle_simple_memory(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle simple memory node execution.-- Args:- node_id: The node ID- node_type: The node type (simpleMemory)- parameters: Resolved parameters- context: Execution context-- Returns:- Execution result dict with session info and messages- """- from services.memory_store import get_messages, clear_session-- session_id = parameters.get('sessionId', 'default')- memory_type = parameters.get('memoryType', 'buffer')- window_size = int(parameters.get('windowSize', 10)) if memory_type == 'window' else None- clear_on_run = parameters.get('clearOnRun', False)-- if clear_on_run:- cleared = clear_session(session_id)- logger.info(f"[Memory] Cleared {cleared} messages from session '{session_id}'")-- messages = get_messages(session_id, window_size)-- return {- "success": True,- "result": {- "session_id": session_id,- "messages": messages,- "message_count": len(messages),- "memory_type": memory_type,- "window_size": window_size- }- }diff --git a/server/services/handlers/android.py b/server/services/handlers/android.pydeleted file mode 100644index 027585a6..00000000--- a/server/services/handlers/android.py+++ /dev/null@@ -1,88 +0,0 @@-"""Android node handlers - Android Services."""--import json-from typing import Dict, Any, TYPE_CHECKING-from core.logging import get_logger--if TYPE_CHECKING:- from services.android_service import AndroidService--logger = get_logger(__name__)---async def handle_android_service(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- android_service: "AndroidService"-) -> Dict[str, Any]:- """Handle Android service node execution.-- Executes Android service actions like battery status, network info, etc.-- Args:- node_id: The node ID- node_type: The node type (batteryMonitor, networkMonitor, etc.)- parameters: Resolved parameters- context: Execution context- android_service: The Android service instance-- Returns:- Execution result dict- """- logger.debug(f"[ANDROID DEBUG] Matched! node_type={node_type}")-- # Derive service_id from node_type (primary) since hidden params may not be in DB.- # Same map used in handlers/tools.py _execute_android_service().- 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, parameters.get('service_id', 'battery'))- action = parameters.get('action', 'status')- service_params = parameters.get('parameters', {})- android_host = parameters.get('android_host', 'localhost')- android_port = parameters.get('android_port', 8888)-- # Parse parameters if it's a JSON string- if isinstance(service_params, str):- try:- service_params = json.loads(service_params)- except json.JSONDecodeError:- service_params = {}-- # Extract additional parameters that are at root level (from additionalProperties in node definitions)- # These include: package_name (appLauncher), and any future custom parameters- additional_param_keys = ['package_name']- for key in additional_param_keys:- if key in parameters and parameters[key]:- service_params[key] = parameters[key]-- logger.debug(f"[ANDROID DEBUG] node_type={node_type} -> service_id={service_id}, action={action}, host={android_host}, port={android_port}, service_params={service_params}")- logger.debug("[ANDROID DEBUG] About to call android_service.execute_service")-- result = await android_service.execute_service(- node_id=node_id,- service_id=service_id,- action=action,- parameters=service_params,- android_host=android_host,- android_port=android_port- )- logger.debug("[ANDROID DEBUG] Got result from android_service")- return resultdiff --git a/server/services/handlers/browser.py b/server/services/handlers/browser.pydeleted file mode 100644index 670fc24e..00000000--- a/server/services/handlers/browser.py+++ /dev/null@@ -1,212 +0,0 @@-"""Browser automation handler — thin dispatcher to BrowserService.--Maps operation + parameters to CLI arguments, calls service, wraps response.-"""--import json-import shutil-import sys-import time-from typing import Any, Dict, Optional--from core.logging import get_logger-from services.browser_service import get_browser_service--logger = get_logger(__name__)---# PATH-based names for shutil.which() (Linux/macOS/Windows where on PATH).-_BROWSER_PATH_NAMES = {- "chrome": ["google-chrome", "google-chrome-stable", "chrome"],- "edge": ["microsoft-edge", "microsoft-edge-stable", "msedge"],- "chromium": ["chromium", "chromium-browser"],-}--# Windows registry App Paths keys (how Selenium/Playwright find browsers).-_BROWSER_REGISTRY_KEYS = {- "chrome": "chrome.exe",- "edge": "msedge.exe",- "chromium": "chrome.exe",-}---def _find_browser_via_registry(exe_name: str) -> Optional[str]:- """Find a browser executable via the Windows App Paths registry.-- This is the standard method used by Selenium and Playwright.- HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\<exe>- """- try:- import winreg- for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):- try:- key = winreg.OpenKey(- hive,- rf"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\{exe_name}",- )- path, _ = winreg.QueryValueEx(key, "")- winreg.CloseKey(key)- if path:- return path- except OSError:- continue- except ImportError:- pass- return None---def _resolve_browser(selection: str, custom_path: str) -> Optional[str]:- """Resolve a browser dropdown selection to an executable path.-- Tries shutil.which (PATH) first, then Windows registry App Paths.- Returns None for 'bundled' (let agent-browser use its own Chrome).- """- if selection in ("bundled", "bundled_explicit") or not selection:- return None- if selection == "custom":- return custom_path or None-- # Try PATH first (works on Linux/macOS where browsers are on PATH)- for name in _BROWSER_PATH_NAMES.get(selection, []):- path = shutil.which(name)- if path:- return path-- # On Windows, query the registry (standard App Paths lookup)- if sys.platform == "win32":- reg_name = _BROWSER_REGISTRY_KEYS.get(selection)- if reg_name:- path = _find_browser_via_registry(reg_name)- if path:- return path-- return None---async def handle_browser(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],-) -> Dict[str, Any]:- """Execute a browser automation operation."""- t0 = time.time()- svc = get_browser_service()- if not svc:- return _fail("agent-browser not installed. Run: pnpm install && npx agent-browser install", t0)-- op = parameters.get("operation") or "navigate"- session = (- (parameters.get("session") or "").strip()- or f"machina_{context.get('execution_id', 'default')}"- )- timeout = int(parameters.get("timeout") or 30)- headed = bool(parameters.get("headed", True))- auto_connect = bool(parameters.get("autoConnect", False))- browser_sel = parameters.get("browser", "chrome")- # "bundled" was the old default before system Chrome became default.- # Upgrade it to "chrome". Users who explicitly want bundled pick "bundled_explicit".- if not browser_sel or browser_sel == "bundled":- browser_sel = "chrome"- custom_path = (parameters.get("executablePath") or "").strip()- executable_path = _resolve_browser(browser_sel, custom_path)- logger.info("[Browser] browser=%s executable=%s", browser_sel, executable_path)- new_window = bool(parameters.get("newWindow", True)) and executable_path is not None- chrome_profile = (parameters.get("chromeProfile") or "").strip() or None- user_agent = (parameters.get("userAgent") or "").strip() or None- proxy = (parameters.get("proxy") or "").strip() or None- action_delay = int(parameters.get("actionDelay") or 0)-- run_kw = dict(- headed=headed, user_agent=user_agent, proxy=proxy,- executable_path=executable_path, auto_connect=auto_connect,- chrome_profile=chrome_profile, new_window=new_window,- )-- try:- # Native pacing via agent-browser's wait command- if action_delay > 0:- await svc.run(["wait", str(action_delay)], session, timeout, **run_kw)-- if op == "batch":- cmds = json.loads(parameters.get("commands", "[]"))- data = await svc.run(- ["batch", "--json"], session, timeout,- stdin=json.dumps(cmds).encode(),- **run_kw,- )- else:- args = _build_args(op, parameters)- data = await svc.run(args, session, timeout, **run_kw)-- return {- "success": True,- "result": {"operation": op, "data": data, "session": session},- "execution_time": time.time() - t0,- }- except (ValueError, TimeoutError, RuntimeError) as e:- return _fail(str(e), t0)---def _build_args(op: str, p: Dict[str, Any]) -> list:- """Map an operation name + parameters to agent-browser CLI arguments."""- s = (p.get("selector") or "").strip()- match op:- case "navigate":- return ["open", _req(p, "url")]- case "click":- return ["click", _req_sel(s)]- case "type":- return ["type", _req_sel(s), p.get("text") or ""]- case "fill":- return ["fill", _req_sel(s), p.get("value") or ""]- case "screenshot":- args = ["screenshot"]- if p.get("fullPage"):- args.append("--full")- if p.get("annotate"):- args.append("--annotate")- fmt = p.get("screenshotFormat", "png")- if fmt and fmt != "png":- args.extend(["--screenshot-format", fmt])- quality = p.get("screenshotQuality")- if quality and fmt == "jpeg":- args.extend(["--screenshot-quality", str(quality)])- return args- case "snapshot":- return ["snapshot", "-i"]- case "get_text":- return ["get", "text", _req_sel(s)]- case "get_html":- return ["get", "html", _req_sel(s)]- case "eval":- return ["eval", _req(p, "expression")]- case "wait":- return ["wait", _req_sel(s)]- case "scroll":- return ["scroll", p.get("direction") or "down", str(p.get("amount") or 500)]- case "select":- return ["select", _req_sel(s), p.get("value") or ""]- case "console":- return ["console"]- case "errors":- return ["errors"]- case _:- raise ValueError(f"Unknown operation: {op}")---def _req(p: Dict[str, Any], key: str) -> str:- v = (p.get(key) or "").strip()- if not v:- raise ValueError(f"{key} is required")- return v---def _req_sel(s: str) -> str:- if not s:- raise ValueError("selector is required")- return s---def _fail(error: str, t0: float) -> Dict[str, Any]:- return {"success": False, "error": error, "execution_time": time.time() - t0}diff --git a/server/services/handlers/claude_code.py b/server/services/handlers/claude_code.pydeleted file mode 100644index bc89e590..00000000--- a/server/services/handlers/claude_code.py+++ /dev/null@@ -1,97 +0,0 @@-"""Claude Code Agent handler."""--import time-from datetime import datetime-from typing import Any, Dict--from core.logging import get_logger-from services.status_broadcaster import get_status_broadcaster-from services.claude_code_service import get_claude_code_service--logger = get_logger(__name__)---async def handle_claude_code_agent(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- ai_service=None,- database=None,-) -> Dict[str, Any]:- """Execute task via Claude Code CLI."""- start_time = time.time()- broadcaster = get_status_broadcaster()- workflow_id = context.get("workflow_id")-- await broadcaster.update_node_status(- node_id, "executing", {"message": "Starting Claude Code..."}, workflow_id=workflow_id- )-- try:- # Resolve prompt from params or connected input- prompt = parameters.get("prompt", "")- if not prompt:- for edge in context.get("edges", []):- if edge.get("target") == node_id and edge.get("targetHandle") in ("input-main", None):- src = context.get("outputs", {}).get(edge.get("source"), {})- if isinstance(src, dict):- prompt = src.get("message") or src.get("text") or src.get("content") or str(src)- elif src:- prompt = str(src)- if prompt:- break-- if not prompt:- return {"success": False, "node_id": node_id, "error": "No prompt provided", "execution_time": time.time() - start_time}-- # Collect skill instructions- from services.handlers.ai import _collect_agent_connections- _, skill_data, _, _, _ = await _collect_agent_connections(node_id, context, database)-- system_parts = []- if parameters.get("systemPrompt"):- system_parts.append(parameters["systemPrompt"])- for skill in skill_data:- instr = skill.get("parameters", {}).get("instructions", "")- if instr:- system_parts.append(instr)-- model = parameters.get("model", "claude-sonnet-4-6")- await broadcaster.update_node_status(- node_id, "executing", {"message": f"Running Claude Code ({model})..."}, workflow_id=workflow_id- )-- service = get_claude_code_service()- data = await service.execute(- prompt=prompt,- node_id=node_id,- model=model,- cwd=parameters.get("workingDirectory") or None,- allowed_tools=parameters.get("allowedTools", "Read,Edit,Bash,Glob,Grep,Write"),- max_turns=int(parameters.get("maxTurns", 10)),- max_budget_usd=float(parameters.get("maxBudgetUsd", 5.0)),- system_prompt="\n\n".join(system_parts) if system_parts else None,- )-- execution_time = time.time() - start_time- await broadcaster.update_node_status(node_id, "success", {"message": "Claude Code completed"}, workflow_id=workflow_id)-- return {- "success": True,- "node_id": node_id,- "node_type": node_type,- "result": {- "response": data.get("result", ""),- "model": model,- "provider": "anthropic",- "session_id": data.get("session_id", ""),- "usage": data.get("usage", {}),- "timestamp": datetime.now().isoformat(),- },- "execution_time": execution_time,- }-- except Exception as e:- logger.error("Claude Code error for node %s: %s", node_id, e)- return {"success": False, "node_id": node_id, "error": str(e), "execution_time": time.time() - start_time}diff --git a/server/services/handlers/code.py b/server/services/handlers/code.pydeleted file mode 100644index 544a5338..00000000--- a/server/services/handlers/code.py+++ /dev/null@@ -1,320 +0,0 @@-"""Code execution node handlers - Python and JavaScript executors."""--import time-from datetime import datetime-from typing import Dict, Any, Optional-from core.logging import get_logger-from services.nodejs_client import NodeJSClient--logger = get_logger(__name__)--# Module-level client instance (initialized on first use)-_nodejs_client: Optional[NodeJSClient] = None---def get_nodejs_client(base_url: str, timeout: int) -> NodeJSClient:- """Get or create Node.js client instance."""- global _nodejs_client- if _nodejs_client is None:- _nodejs_client = NodeJSClient(base_url, timeout)- return _nodejs_client---async def handle_python_executor(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- connected_outputs: Dict[str, Any] = None-) -> Dict[str, Any]:- """Handle Python executor node execution.-- Executes Python code with input data access and console output capture.-- Args:- node_id: The node ID- node_type: The node type (pythonExecutor)- parameters: Resolved parameters- context: Execution context- connected_outputs: Outputs from connected nodes-- Returns:- Execution result dict with output and console output- """- import io- start_time = time.time()- console_output = ""-- try:- code = parameters.get('code', '')- int(parameters.get('timeout', 30))-- if not code.strip():- return {- "success": False,- "node_id": node_id,- "node_type": "pythonExecutor",- "error": "No code provided",- "console_output": "",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- # Get input data from connected nodes- input_data = connected_outputs or {}-- # Capture stdout for console output- stdout_capture = io.StringIO()-- # Create execution namespace with safe builtins- import math- import json as json_module-- # Custom print function that writes to our capture buffer- def captured_print(*args, **kwargs):- kwargs['file'] = stdout_capture- print(*args, **kwargs)-- safe_builtins = {- 'abs': abs, 'all': all, 'any': any, 'bool': bool,- 'dict': dict, 'enumerate': enumerate, 'filter': filter,- 'float': float, 'int': int, 'len': len, 'list': list,- 'map': map, 'max': max, 'min': min, 'print': captured_print,- 'range': range, 'round': round, 'set': set, 'sorted': sorted,- 'str': str, 'sum': sum, 'tuple': tuple, 'type': type, 'zip': zip,- 'True': True, 'False': False, 'None': None,- 'math': math, 'json': json_module- }-- namespace = {- '__builtins__': safe_builtins,- 'input_data': input_data,- 'workspace_dir': context.get('workspace_dir', ''),- 'output': None- }-- # Execute code with timeout- exec(code, namespace)-- # Get output and console output- output = namespace.get('output', None)- console_output = stdout_capture.getvalue()-- return {- "success": True,- "node_id": node_id,- "node_type": "pythonExecutor",- "result": {- "output": output,- "console_output": console_output,- "timestamp": datetime.now().isoformat()- },- "console_output": console_output,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error("Python execution failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "pythonExecutor",- "error": str(e),- "console_output": console_output,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---async def handle_javascript_executor(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- connected_outputs: Dict[str, Any] = None,- nodejs_url: str = None,- nodejs_timeout: int = None-) -> Dict[str, Any]:- """Handle JavaScript executor node execution.-- Executes JavaScript code via persistent Node.js server.-- Args:- node_id: The node ID- node_type: The node type (javascriptExecutor)- parameters: Resolved parameters- context: Execution context- connected_outputs: Outputs from connected nodes- nodejs_url: Node.js server URL (from settings)- nodejs_timeout: Request timeout in seconds (from settings)-- Returns:- Execution result dict with output and console output- """- start_time = time.time()-- try:- code = parameters.get('code', '')- timeout_ms = int(parameters.get('timeout', 30)) * 1000 # Convert to milliseconds-- if not code.strip():- return {- "success": False,- "node_id": node_id,- "node_type": "javascriptExecutor",- "error": "No code provided",- "console_output": "",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- # Get input data from connected nodes + workspace path- input_data = connected_outputs or {}- input_data['workspace_dir'] = context.get('workspace_dir', '')-- # Get Node.js client- client = get_nodejs_client(- nodejs_url or "http://localhost:3020",- nodejs_timeout or 30- )-- # Execute via Node.js server- result = await client.execute(- code=code,- input_data=input_data,- timeout=timeout_ms,- language="javascript"- )-- if result.get("success"):- return {- "success": True,- "node_id": node_id,- "node_type": "javascriptExecutor",- "result": {- "output": result.get("output"),- "console_output": result.get("console_output", ""),- "timestamp": datetime.now().isoformat()- },- "console_output": result.get("console_output", ""),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- else:- return {- "success": False,- "node_id": node_id,- "node_type": "javascriptExecutor",- "error": result.get("error", "Unknown error"),- "console_output": result.get("console_output", ""),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error("JavaScript execution failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "javascriptExecutor",- "error": str(e),- "console_output": "",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---async def handle_typescript_executor(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- connected_outputs: Dict[str, Any] = None,- nodejs_url: str = None,- nodejs_timeout: int = None-) -> Dict[str, Any]:- """Handle TypeScript executor node execution.-- Executes TypeScript code via persistent Node.js server.-- Args:- node_id: The node ID- node_type: The node type (typescriptExecutor)- parameters: Resolved parameters- context: Execution context- connected_outputs: Outputs from connected nodes- nodejs_url: Node.js server URL (from settings)- nodejs_timeout: Request timeout in seconds (from settings)-- Returns:- Execution result dict with output and console output- """- start_time = time.time()-- try:- code = parameters.get('code', '')- timeout_ms = int(parameters.get('timeout', 30)) * 1000-- if not code.strip():- return {- "success": False,- "node_id": node_id,- "node_type": "typescriptExecutor",- "error": "No code provided",- "console_output": "",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- input_data = connected_outputs or {}- input_data['workspace_dir'] = context.get('workspace_dir', '')-- client = get_nodejs_client(- nodejs_url or "http://localhost:3020",- nodejs_timeout or 30- )-- result = await client.execute(- code=code,- input_data=input_data,- timeout=timeout_ms,- language="typescript"- )-- if result.get("success"):- return {- "success": True,- "node_id": node_id,- "node_type": "typescriptExecutor",- "result": {- "output": result.get("output"),- "console_output": result.get("console_output", ""),- "timestamp": datetime.now().isoformat()- },- "console_output": result.get("console_output", ""),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- else:- return {- "success": False,- "node_id": node_id,- "node_type": "typescriptExecutor",- "error": result.get("error", "Unknown error"),- "console_output": result.get("console_output", ""),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error("TypeScript execution failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "typescriptExecutor",- "error": str(e),- "console_output": "",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }diff --git a/server/services/handlers/deep_agent.py b/server/services/handlers/deep_agent.pydeleted file mode 100644index 899d97fb..00000000--- a/server/services/handlers/deep_agent.py+++ /dev/null@@ -1,84 +0,0 @@-"""Deep Agent handler -- thin wrapper following handle_rlm_agent pattern.--Collects connections, delegates to DeepAgentService.-"""--from typing import Dict, Any, TYPE_CHECKING-from core.logging import get_logger--if TYPE_CHECKING:- from services.ai import AIService- from core.database import Database--logger = get_logger(__name__)---async def handle_deep_agent(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- ai_service: "AIService",- database: "Database",-) -> Dict[str, Any]:- """Handle Deep Agent node execution.-- Follows handle_rlm_agent pattern:- 1. _collect_agent_connections() [REUSE]- 2. _format_task_context() [REUSE]- 3. Auto-prompt fallback [REUSE]- 4. _collect_teammate_connections() [REUSE]- 5. Delegate to DeepAgentService.execute()- """- from .ai import _collect_agent_connections, _collect_teammate_connections, _format_task_context- from services.status_broadcaster import get_status_broadcaster-- workflow_id = context.get('workflow_id')-- # 1. Collect connections- memory_data, skill_data, tool_data, input_data, task_data = await _collect_agent_connections(- node_id, context, database, log_prefix="[Deep Agent]"- )-- # 2. Task context injection- 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}"}-- task_status = task_data.get('status', '')- if task_status in ('completed', 'error') and tool_data:- tool_data = []-- # 3. Auto-prompt fallback- if not parameters.get('prompt') and input_data:- prompt = (- input_data.get('message') or- input_data.get('text') or- input_data.get('content') or- str(input_data)- )- parameters = {**parameters, 'prompt': prompt}-- # 4. Collect teammates- teammates = await _collect_teammate_connections(node_id, context, database)-- # 5. Pass workspace directory for filesystem tools- workspace_dir = context.get('workspace_dir')- logger.info("[Deep Agent] workspace_dir from context: %s", workspace_dir)- if workspace_dir:- parameters = {**parameters, 'workspace_dir': workspace_dir}-- # 6. Delegate to DeepAgentService (raw tool_data, service builds via ToolAdapter)- broadcaster = get_status_broadcaster()- return await ai_service.deep_agent_service.execute(- node_id, parameters,- memory_data=memory_data if memory_data else None,- skill_data=skill_data if skill_data else None,- tool_data=tool_data if tool_data else None,- teammates=teammates if teammates else None,- build_tool_fn=ai_service._build_tool_from_node,- broadcaster=broadcaster,- workflow_id=workflow_id,- database=database,- )diff --git a/server/services/handlers/email.py b/server/services/handlers/email.pydeleted file mode 100644index f44a17a4..00000000--- a/server/services/handlers/email.py+++ /dev/null@@ -1,86 +0,0 @@-"""Email node handlers - thin wrappers around EmailService."""--import asyncio-import time-from datetime import datetime-from typing import Any, Dict, Set--from core.logging import get_logger--logger = get_logger(__name__)---def _ok(node_id, node_type, result, start):- return {"success": True, "node_id": node_id, "node_type": node_type,- "result": result, "execution_time": time.time() - start,- "timestamp": datetime.now().isoformat()}---def _err(node_id, node_type, error, start):- return {"success": False, "node_id": node_id, "node_type": node_type,- "error": str(error), "execution_time": time.time() - start,- "timestamp": datetime.now().isoformat()}---async def handle_email_send(node_id, node_type, parameters, context):- from services.email_service import get_email_service- t = time.time()- try:- return _ok(node_id, node_type, await get_email_service().send(parameters), t)- except Exception as e:- logger.error(f"[EmailSend] {e}")- return _err(node_id, node_type, e, t)---async def handle_email_read(node_id, node_type, parameters, context):- from services.email_service import get_email_service- t = time.time()- try:- return _ok(node_id, node_type, await get_email_service().read(parameters), t)- except Exception as e:- logger.error(f"[EmailRead] {e}")- return _err(node_id, node_type, e, t)---async def handle_email_receive(node_id, node_type, parameters, context):- """Polling trigger - baseline + poll loop (gmailReceive pattern)."""- from services.email_service import get_email_service- from services.status_broadcaster import get_status_broadcaster- t = time.time()- try:- svc = get_email_service()- creds = await svc.resolve_credentials(parameters)- poll = svc.resolve_poll_params(parameters)-- await get_status_broadcaster().update_node_status(node_id, "waiting", {- "message": f"Waiting for email (every {poll['interval']}s)...",- "event_type": "email_received",- }, workflow_id=context.get("workflow_id"))-- seen: Set[str] = await svc.poll_ids(creds, poll["folder"])- logger.info(f"[EmailReceive] Baseline: {len(seen)} emails in {poll['folder']}")-- while True:- await asyncio.sleep(poll["interval"])- new_ids = await svc.poll_ids(creds, poll["folder"]) - seen- if not new_ids:- continue-- msg_id = next(iter(new_ids))- seen.update(new_ids)- email_data = await svc.fetch_detail(creds, msg_id, poll["folder"])-- if poll["mark_as_read"]:- d = svc.defaults- await svc.himalaya.flag_message(- creds, msg_id, d.get("flag"), d.get("flag_action"), poll["folder"])-- from services import event_waiter- event_waiter.dispatch("email_received", email_data)- return _ok(node_id, node_type, email_data, t)-- except asyncio.CancelledError:- return _err(node_id, node_type, "Cancelled by user", t)- except Exception as e:- logger.error(f"[EmailReceive] {e}")- return _err(node_id, node_type, e, t)diff --git a/server/services/handlers/filesystem.py b/server/services/handlers/filesystem.pydeleted file mode 100644index 0ead9530..00000000--- a/server/services/handlers/filesystem.py+++ /dev/null@@ -1,169 +0,0 @@-"""Filesystem and shell handlers - delegates to deepagents backends.--Uses deepagents.backends.LocalShellBackend methods:- read() -> str, write() -> WriteResult, edit() -> EditResult,- ls_info() -> list[FileInfo], glob_info() -> list[FileInfo],- grep_raw() -> list[GrepMatch] | str, execute() -> ExecuteResponse.--All backend calls are synchronous (subprocess.run / file I/O), so they-run via asyncio.to_thread() to avoid blocking the event loop.-"""--import asyncio-import os-from typing import Any, Dict--from core.logging import get_logger--logger = get_logger(__name__)---def _get_backend(parameters: Dict[str, Any], context: Dict[str, Any] = None):- """Get a LocalShellBackend rooted at per-workflow workspace."""- from deepagents.backends import LocalShellBackend- from core.config import Settings- param_dir = parameters.get('working_directory')- ctx_dir = context.get('workspace_dir') if context else None- root = param_dir or ctx_dir or os.path.join(Settings().workspace_base_resolved, 'default')- os.makedirs(root, exist_ok=True)- logger.info("[Filesystem] root=%s", root)- return LocalShellBackend(root_dir=root, virtual_mode=True)---async def handle_file_read(- node_id: str, node_type: str, parameters: Dict[str, Any], context: Dict[str, Any],-) -> Dict[str, Any]:- """Read file via backend.read() which returns str content directly."""- file_path = parameters.get('file_path', '')- if not file_path:- return {"success": False, "node_id": node_id, "error": "file_path is required"}-- try:- backend = _get_backend(parameters, context)- content = await asyncio.to_thread(backend.read, file_path, offset=int(parameters.get('offset', 0)), limit=int(parameters.get('limit', 100)))- return {- "success": True, "node_id": node_id,- "result": {"content": content, "file_path": file_path},- }- except Exception as e:- return {"success": False, "node_id": node_id, "error": str(e)}---async def handle_file_modify(- node_id: str, node_type: str, parameters: Dict[str, Any], context: Dict[str, Any],-) -> Dict[str, Any]:- """Write or edit file via backend.write()/edit()."""- operation = parameters.get('operation', 'write')- file_path = parameters.get('file_path', '')- if not file_path:- return {"success": False, "node_id": node_id, "error": "file_path is required"}-- try:- backend = _get_backend(parameters, context)-- if operation == 'write':- content = parameters.get('content', '')- result = await asyncio.to_thread(backend.write, file_path, content)- if result.error:- return {"success": False, "node_id": node_id, "error": result.error}- return {- "success": True, "node_id": node_id,- "result": {"operation": "write", "file_path": result.path or file_path},- }-- elif operation == 'edit':- old_string = parameters.get('old_string', '')- new_string = parameters.get('new_string', '')- replace_all = parameters.get('replace_all', False)- if not old_string:- return {"success": False, "node_id": node_id, "error": "old_string is required for edit"}-- result = await asyncio.to_thread(backend.edit, file_path, old_string, new_string, replace_all=replace_all)- if result.error:- return {"success": False, "node_id": node_id, "error": result.error}- return {- "success": True, "node_id": node_id,- "result": {"operation": "edit", "file_path": result.path or file_path, "occurrences": result.occurrences},- }-- return {"success": False, "node_id": node_id, "error": f"Unknown operation: {operation}"}- except Exception as e:- return {"success": False, "node_id": node_id, "error": str(e)}---async def handle_shell(- node_id: str, node_type: str, parameters: Dict[str, Any], context: Dict[str, Any],-) -> Dict[str, Any]:- """Execute shell command via backend.execute()."""- command = parameters.get('command', '')- if not command:- return {"success": False, "node_id": node_id, "error": "command is required"}-- try:- timeout = int(parameters.get('timeout', 30))- backend = _get_backend(parameters, context)- logger.info("[Shell] Executing (non-blocking): %s (timeout=%ds)", command[:200], timeout)- result = await asyncio.to_thread(backend.execute, command, timeout=timeout)- if result.exit_code == 124:- logger.warning("[Shell] Timed out after %ds: %s", timeout, command[:100])- elif result.exit_code != 0:- logger.warning("[Shell] Non-zero exit (%d): %s -> %s", result.exit_code, command[:100], result.output[:300])- else:- logger.info("[Shell] Completed: exit=%d len=%d", result.exit_code, len(result.output))- return {- "success": True, "node_id": node_id,- "result": {- "stdout": result.output,- "exit_code": result.exit_code,- "truncated": result.truncated,- "command": command,- },- }- except Exception as e:- logger.error("[Shell] Failed: %s -> %s", command[:100], e)- return {"success": False, "node_id": node_id, "error": str(e)}---async def handle_fs_search(- node_id: str, node_type: str, parameters: Dict[str, Any], context: Dict[str, Any],-) -> Dict[str, Any]:- """Search filesystem via backend.ls_info()/glob_info()/grep_raw()."""- mode = parameters.get('mode', 'ls')- path = parameters.get('path', '.')- pattern = parameters.get('pattern', '')-- try:- backend = _get_backend(parameters, context)-- if mode == 'ls':- entries = await asyncio.to_thread(backend.ls_info, path)- return {- "success": True, "node_id": node_id,- "result": {"path": path, "entries": [dict(e) for e in entries], "count": len(entries)},- }-- elif mode == 'glob':- if not pattern:- return {"success": False, "node_id": node_id, "error": "pattern is required for glob mode"}- matches = await asyncio.to_thread(backend.glob_info, pattern, path=path)- return {- "success": True, "node_id": node_id,- "result": {"path": path, "pattern": pattern, "matches": [dict(m) for m in matches], "count": len(matches)},- }-- elif mode == 'grep':- if not pattern:- return {"success": False, "node_id": node_id, "error": "pattern is required for grep mode"}- file_filter = parameters.get('file_filter') or None- result = await asyncio.to_thread(backend.grep_raw, pattern, path=path, glob=file_filter)- # grep_raw returns list[GrepMatch] or str (error message)- if isinstance(result, str):- return {"success": False, "node_id": node_id, "error": result}- return {- "success": True, "node_id": node_id,- "result": {"path": path, "pattern": pattern, "matches": [dict(m) for m in result], "count": len(result)},- }-- return {"success": False, "node_id": node_id, "error": f"Unknown mode: {mode}"}- except Exception as e:- return {"success": False, "node_id": node_id, "error": str(e)}diff --git a/server/services/handlers/http.py b/server/services/handlers/http.pydeleted file mode 100644index aac89edc..00000000--- a/server/services/handlers/http.py+++ /dev/null@@ -1,221 +0,0 @@-"""HTTP node handlers - HTTP Request and Webhook Response."""--import json-import time-from datetime import datetime-from typing import Any, Dict, Optional-from core.logging import get_logger--logger = get_logger(__name__)---async def _get_proxy_url_if_enabled(url: str, parameters: Dict[str, Any]) -> Optional[str]:- """Return a proxy URL if useProxy is enabled and a provider is available.-- Returns None when proxy should not be used (disabled, no providers, etc.).- Exceptions from the proxy service are logged and swallowed so that the- request proceeds without a proxy rather than failing.- """- if not parameters.get('useProxy', False):- return None-- try:- from services.proxy.service import get_proxy_service- proxy_svc = get_proxy_service()- if not proxy_svc or not proxy_svc.is_enabled():- return None- return await proxy_svc.get_proxy_url(url, parameters)- except Exception as e:- logger.warning("Proxy URL lookup failed, proceeding without proxy", error=str(e))- return None---async def handle_http_request(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle HTTP request node execution.-- Makes HTTP requests to external APIs.-- Args:- node_id: The node ID- node_type: The node type (httpRequest)- parameters: Resolved parameters- context: Execution context-- Returns:- Execution result dict with response data- """- import httpx- start_time = time.time()-- try:- method = parameters.get('method', 'GET')- url = parameters.get('url', '')- headers_str = parameters.get('headers', '{}')- body = parameters.get('body', '')- timeout = float(parameters.get('timeout', 30))-- 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 = {}-- # Transparent proxy injection- proxy_url = await _get_proxy_url_if_enabled(url, parameters)- logger.info("[HTTP Request] Executing", node_id=node_id, method=method, url=url,- proxy=bool(proxy_url))-- client_kwargs: Dict[str, Any] = {"timeout": timeout}- if proxy_url:- client_kwargs["proxy"] = proxy_url-- async with httpx.AsyncClient(**client_kwargs) as client:- kwargs = {- 'method': method,- 'url': url,- 'headers': headers,- }-- # Add body for POST/PUT/PATCH- 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)-- # Parse response data- try:- response_data = response.json()- except Exception:- response_data = response.text-- result_data = {- "status": response.status_code,- "data": response_data,- "headers": dict(response.headers),- "url": str(response.url),- "method": method,- "proxied": proxy_url is not None,- }-- return {- "success": response.status_code < 400,- "node_id": node_id,- "node_type": "httpRequest",- "result": result_data,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- if "TimeoutException" in type(e).__name__:- logger.error("HTTP request timed out", node_id=node_id, url=parameters.get('url'))- return {- "success": False,- "node_id": node_id,- "node_type": "httpRequest",- "error": f"Request timed out after {parameters.get('timeout', 30)} seconds",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- logger.error("HTTP request failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "httpRequest",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---async def handle_webhook_response(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- connected_outputs: Dict[str, Any] = None-) -> Dict[str, Any]:- """Handle webhook response node execution.-- Sends response back to waiting webhook caller.-- Args:- node_id: The node ID- node_type: The node type (webhookResponse)- parameters: Resolved parameters- context: Execution context- connected_outputs: Outputs from connected nodes-- Returns:- Execution result dict- """- from routers.webhook import resolve_webhook_response- start_time = time.time()-- try:- status_code = int(parameters.get('statusCode', 200))- response_body = parameters.get('responseBody', '')- content_type = parameters.get('contentType', 'application/json')-- # Resolve template variables in response body- if response_body and connected_outputs:- for node_type_key, output_data in connected_outputs.items():- if isinstance(output_data, dict):- for key, value in output_data.items():- template = f"{{{{input.{key}}}}}"- response_body = response_body.replace(template, str(value))- # Also support {{nodeType.key}} format- template_alt = f"{{{{{node_type_key}.{key}}}}}"- response_body = response_body.replace(template_alt, str(value))-- # If response body is empty, serialize connected outputs as JSON- if not response_body and connected_outputs:- # Get the first connected output- first_output = next(iter(connected_outputs.values()), {})- response_body = json.dumps(first_output, default=str)-- logger.info("[Webhook Response] Sending", node_id=node_id, status_code=status_code,- content_type=content_type, body_length=len(response_body))-- # Resolve the pending webhook response- resolve_webhook_response(node_id, {- 'statusCode': status_code,- 'body': response_body,- 'contentType': content_type- })-- return {- "success": True,- "node_id": node_id,- "node_type": "webhookResponse",- "result": {- "sent": True,- "statusCode": status_code,- "contentType": content_type,- "bodyLength": len(response_body)- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error("Webhook response failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "webhookResponse",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }diff --git a/server/services/handlers/process.py b/server/services/handlers/process.pydeleted file mode 100644index e918fbec..00000000--- a/server/services/handlers/process.py+++ /dev/null@@ -1,83 +0,0 @@-"""Process manager handler -- dual-purpose (workflow node + AI tool).--Follows the same pattern as handlers/todo.py.-"""--import os-import time-from typing import Any, Dict--from core.logging import get_logger-from services.process_service import get_process_service--logger = get_logger(__name__)---async def handle_process_manager(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],-) -> Dict[str, Any]:- """Workflow node entry point."""- t0 = time.time()- workflow_id = context.get("workflow_id", "default")- workspace_dir = context.get("workspace_dir", "")-- # Each agent node gets its own subfolder in the workspace- agent_dir = os.path.join(workspace_dir, node_id) if workspace_dir else ""-- tool_args = {- "operation": parameters.get("operation", "list"),- "name": parameters.get("name", ""),- "command": parameters.get("command", ""),- "working_directory": parameters.get("working_directory", "") or agent_dir,- "text": parameters.get("text", ""),- }- config = {"workflow_id": workflow_id, "workspace_dir": agent_dir}-- result = await execute_process_manager(tool_args, config)- result["node_id"] = node_id- result["execution_time"] = time.time() - t0- return result---def _clean_arg(val: str) -> str:- """LLMs sometimes pass literal 'None' string instead of omitting the field."""- if not val or val == "None":- return ""- return val---async def execute_process_manager(tool_args: Dict[str, Any], config: Dict[str, Any]) -> Dict[str, Any]:- """AI tool entry point. Dispatches by operation."""- svc = get_process_service()- op = tool_args.get("operation", "list")- workflow_id = config.get("workflow_id", "default")- name = _clean_arg(tool_args.get("name", ""))- workspace_dir = config.get("workspace_dir", "")-- logger.info("[ProcessManager] op=%s name=%s workspace=%s", op, name, workspace_dir)-- if op == "start":- return await svc.start(- name=name,- command=_clean_arg(tool_args.get("command", "")),- workflow_id=workflow_id,- working_directory=_clean_arg(tool_args.get("working_directory", "")) or workspace_dir,- )- elif op == "stop":- return await svc.stop(name, workflow_id)- elif op == "restart":- return await svc.restart(name, workflow_id)- elif op == "send_input":- return await svc.send_input(name, workflow_id, _clean_arg(tool_args.get("text", "")))- elif op == "list":- return {"success": True, "result": {"processes": svc.list_processes(workflow_id)}}- elif op == "get_output":- stream = _clean_arg(tool_args.get("stream", "")) or "stdout"- tail = int(tool_args.get("tail", 50) or 50)- offset = int(tool_args.get("offset", 0))- return {"success": True, "result": svc.get_output(name, workflow_id, stream, tail, offset)}- else:- return {"success": False, "error": f"Unknown operation: {op}"}diff --git a/server/services/handlers/rlm.py b/server/services/handlers/rlm.pydeleted file mode 100644index f5904135..00000000--- a/server/services/handlers/rlm.py+++ /dev/null@@ -1,78 +0,0 @@-"""RLM agent handler -- thin wrapper following handle_chat_agent pattern.--Reference: docs-internal/specialized_agent_node_creation.md (Step 5)-"""--from typing import Dict, Any, TYPE_CHECKING-from core.logging import get_logger--if TYPE_CHECKING:- from services.ai import AIService- from core.database import Database--logger = get_logger(__name__)---async def handle_rlm_agent(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- ai_service: "AIService",- database: "Database",-) -> Dict[str, Any]:- """Handle RLM agent node execution.-- Follows handle_chat_agent pattern (handlers/ai.py:469-564):- 1. _collect_agent_connections() [REUSE]- 2. _format_task_context() [REUSE]- 3. Tool stripping on task completion [REUSE]- 4. Auto-prompt fallback [REUSE]- 5. Delegate to RLMService.execute()- """- from .ai import _collect_agent_connections, _format_task_context- from services.status_broadcaster import get_status_broadcaster-- workflow_id = context.get('workflow_id')-- # 1. Collect connections (handlers/ai.py:17)- memory_data, skill_data, tool_data, input_data, task_data = await _collect_agent_connections(- node_id, context, database, log_prefix="[RLM Agent]"- )-- # 2. Task context injection (handlers/ai.py:352)- 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"[RLM Agent] Task context injected for task_id={task_data.get('task_id')}")-- # 3. Tool stripping on task completion (handlers/ai.py:514-519)- task_status = task_data.get('status', '')- if task_status in ('completed', 'error') and tool_data:- tool_data = []- logger.info("[RLM Agent] Stripped tools for task completion handling")-- # 4. Auto-prompt fallback (handlers/ai.py:522-530)- if not parameters.get('prompt') and input_data:- prompt = (- input_data.get('message') or- input_data.get('text') or- input_data.get('content') or- str(input_data)- )- parameters = {**parameters, 'prompt': prompt}- logger.info("[RLM Agent] Auto-using input as prompt")-- # 5. Delegate to RLM service- broadcaster = get_status_broadcaster()- return await ai_service.rlm_service.execute(- node_id, parameters,- memory_data=memory_data,- skill_data=skill_data if skill_data else None,- tool_data=tool_data if tool_data else None,- broadcaster=broadcaster,- workflow_id=workflow_id,- context=context,- database=database,- )diff --git a/server/services/handlers/search.py b/server/services/handlers/search.pydeleted file mode 100644index 06f347fd..00000000--- a/server/services/handlers/search.py+++ /dev/null@@ -1,385 +0,0 @@-"""Search API node handlers - Brave Search, Serper, Perplexity Sonar.--Each handler fetches the API key from the encrypted credentials system-via auth_service, then calls the provider's API.-"""--import time-from typing import Dict, Any--import httpx--from core.logging import get_logger-from services.pricing import get_pricing_service--logger = get_logger(__name__)---async def _track_search_usage(- node_id: str,- service: str,- action: str,- resource_count: int = 1,- workflow_id: str = None,- session_id: str = "default"-) -> Dict[str, float]:- """Track search API usage for cost calculation."""- from core.container import container-- pricing = get_pricing_service()- cost_data = pricing.calculate_api_cost(service, action, resource_count)-- db = container.database()- await db.save_api_usage_metric({- 'session_id': session_id,- 'node_id': node_id,- 'workflow_id': workflow_id,- 'service': service,- 'operation': cost_data.get('operation', action),- 'endpoint': action,- 'resource_count': resource_count,- 'cost': cost_data.get('total_cost', 0.0)- })-- logger.debug(f"[Search] Tracked {service} usage: {action} x{resource_count} = ${cost_data.get('total_cost', 0):.6f}")- return cost_data---async def _get_api_key(provider: str) -> str:- """Get API key from encrypted credentials."""- from core.container import container- auth_service = container.auth_service()- api_key = await auth_service.get_api_key(provider)- if not api_key:- raise ValueError(- f"{provider} API key not configured. "- f"Please add it in Credentials > Search."- )- return api_key---# =============================================================================-# BRAVE SEARCH HANDLER-# =============================================================================--async def handle_brave_search(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Brave Search API requests.-- API: GET https://api.search.brave.com/res/v1/web/search- Auth: X-Subscription-Token header- """- start_time = time.time()-- query = parameters.get('query', '').strip()- if not query:- return {"success": False, "error": "Search query is required"}-- max_results = parameters.get('maxResults', 10)- country = parameters.get('country', '')- search_lang = parameters.get('searchLang', '')- safe_search = parameters.get('safeSearch', 'moderate')-- try:- api_key = await _get_api_key('brave_search')-- params = {- 'q': query,- 'count': min(max_results, 100),- }- if country:- params['country'] = country- if search_lang:- params['search_lang'] = search_lang- if safe_search:- params['safesearch'] = safe_search-- async with httpx.AsyncClient(timeout=30.0) as client:- response = await client.get(- 'https://api.search.brave.com/res/v1/web/search',- headers={- 'X-Subscription-Token': api_key,- 'Accept': 'application/json',- },- params=params,- )- response.raise_for_status()- data = response.json()-- # Extract web results- web_results = data.get('web', {}).get('results', [])- results = []- for item in web_results[:max_results]:- results.append({- 'title': item.get('title', ''),- 'snippet': item.get('description', ''),- 'url': item.get('url', ''),- })-- execution_time = time.time() - start_time-- # Track usage- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')- await _track_search_usage(node_id, 'brave_search', 'web_search', 1, workflow_id, session_id)-- return {- "success": True,- "result": {- "query": query,- "results": results,- "result_count": len(results),- "provider": "brave_search",- },- "execution_time": round(execution_time, 3),- }-- except httpx.HTTPStatusError as e:- logger.error(f"[BraveSearch] API error: {e.response.status_code} - {e.response.text}")- return {"success": False, "error": f"Brave Search API error: {e.response.status_code}"}- except ValueError as e:- return {"success": False, "error": str(e)}- except Exception as e:- logger.error(f"[BraveSearch] Error: {e}")- return {"success": False, "error": f"Brave Search failed: {str(e)}"}---# =============================================================================-# SERPER SEARCH HANDLER-# =============================================================================--async def handle_serper_search(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Serper (Google) Search API requests.-- API: POST https://google.serper.dev/search- Auth: X-API-KEY header- """- start_time = time.time()-- query = parameters.get('query', '').strip()- if not query:- return {"success": False, "error": "Search query is required"}-- max_results = parameters.get('maxResults', 10)- search_type = parameters.get('searchType', 'search')- country = parameters.get('country', '')- language = parameters.get('language', '')-- try:- api_key = await _get_api_key('serper')-- body: Dict[str, Any] = {- 'q': query,- 'num': min(max_results, 100),- }- if country:- body['gl'] = country- if language:- body['hl'] = language-- # Map search type to endpoint- endpoint_map = {- 'search': 'https://google.serper.dev/search',- 'news': 'https://google.serper.dev/news',- 'images': 'https://google.serper.dev/images',- 'places': 'https://google.serper.dev/places',- }- endpoint = endpoint_map.get(search_type, 'https://google.serper.dev/search')-- async with httpx.AsyncClient(timeout=30.0) as client:- response = await client.post(- endpoint,- headers={- 'X-API-KEY': api_key,- 'Content-Type': 'application/json',- },- json=body,- )- response.raise_for_status()- data = response.json()-- # Extract results based on search type- results = []- if search_type == 'search':- for item in data.get('organic', [])[:max_results]:- results.append({- 'title': item.get('title', ''),- 'snippet': item.get('snippet', ''),- 'url': item.get('link', ''),- 'position': item.get('position'),- })- elif search_type == 'news':- for item in data.get('news', [])[:max_results]:- results.append({- 'title': item.get('title', ''),- 'snippet': item.get('snippet', ''),- 'url': item.get('link', ''),- 'date': item.get('date', ''),- 'source': item.get('source', ''),- })- elif search_type == 'images':- for item in data.get('images', [])[:max_results]:- results.append({- 'title': item.get('title', ''),- 'imageUrl': item.get('imageUrl', ''),- 'url': item.get('link', ''),- })- elif search_type == 'places':- for item in data.get('places', [])[:max_results]:- results.append({- 'title': item.get('title', ''),- 'address': item.get('address', ''),- 'rating': item.get('rating'),- 'url': item.get('website', ''),- })-- # Include knowledge graph if available- knowledge_graph = data.get('knowledgeGraph')-- execution_time = time.time() - start_time-- # Track usage- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')- await _track_search_usage(node_id, 'serper', 'web_search', 1, workflow_id, session_id)-- result = {- "query": query,- "results": results,- "result_count": len(results),- "search_type": search_type,- "provider": "serper",- }- if knowledge_graph:- result["knowledge_graph"] = knowledge_graph-- return {- "success": True,- "result": result,- "execution_time": round(execution_time, 3),- }-- except httpx.HTTPStatusError as e:- logger.error(f"[Serper] API error: {e.response.status_code} - {e.response.text}")- return {"success": False, "error": f"Serper API error: {e.response.status_code}"}- except ValueError as e:- return {"success": False, "error": str(e)}- except Exception as e:- logger.error(f"[Serper] Error: {e}")- return {"success": False, "error": f"Serper search failed: {str(e)}"}---# =============================================================================-# PERPLEXITY SEARCH HANDLER-# =============================================================================--async def handle_perplexity_search(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Perplexity Sonar AI search requests.-- API: POST https://api.perplexity.ai/chat/completions- Auth: Authorization: Bearer header- """- start_time = time.time()-- query = parameters.get('query', '').strip()- if not query:- return {"success": False, "error": "Search query is required"}-- model = parameters.get('model', 'sonar')- search_recency_filter = parameters.get('searchRecencyFilter', '')- return_images = parameters.get('returnImages', False)- return_related_questions = parameters.get('returnRelatedQuestions', False)-- try:- api_key = await _get_api_key('perplexity')-- body: Dict[str, Any] = {- 'model': model,- 'messages': [- {'role': 'user', 'content': query}- ],- }-- if search_recency_filter:- body['search_recency_filter'] = search_recency_filter- if return_images:- body['return_images'] = True- if return_related_questions:- body['return_related_questions'] = True-- async with httpx.AsyncClient(timeout=60.0) as client:- response = await client.post(- 'https://api.perplexity.ai/chat/completions',- headers={- 'Authorization': f'Bearer {api_key}',- 'Content-Type': 'application/json',- },- json=body,- )- response.raise_for_status()- data = response.json()-- # Extract answer and citations- choices = data.get('choices', [])- answer = ''- if choices:- message = choices[0].get('message', {})- answer = message.get('content', '')-- citations = data.get('citations', [])- images = data.get('images', [])- related_questions = data.get('related_questions', [])-- # Build results from citations- results = []- for url in citations:- results.append({'url': url})-- execution_time = time.time() - start_time-- # Track usage- workflow_id = context.get('workflow_id')- session_id = context.get('session_id', 'default')- await _track_search_usage(node_id, 'perplexity', 'sonar_search', 1, workflow_id, session_id)-- result: Dict[str, Any] = {- "query": query,- "answer": answer,- "citations": citations,- "results": results,- "model": model,- "provider": "perplexity",- }- if images:- result["images"] = images- if related_questions:- result["related_questions"] = related_questions-- return {- "success": True,- "result": result,- "execution_time": round(execution_time, 3),- }-- except httpx.HTTPStatusError as e:- logger.error(f"[Perplexity] API error: {e.response.status_code} - {e.response.text}")- return {"success": False, "error": f"Perplexity API error: {e.response.status_code}"}- except ValueError as e:- return {"success": False, "error": str(e)}- except Exception as e:- logger.error(f"[Perplexity] Error: {e}")- return {"success": False, "error": f"Perplexity search failed: {str(e)}"}diff --git a/server/services/handlers/telegram.py b/server/services/handlers/telegram.pydeleted file mode 100644index cf481a51..00000000--- a/server/services/handlers/telegram.py+++ /dev/null@@ -1,244 +0,0 @@-"""-Telegram Node Handlers--- telegramSend: Send messages via Telegram bot-- telegramReceive: Routed via generic handle_trigger_node + event_waiter.build_telegram_filter()-"""--import time-from datetime import datetime-from typing import Any, Dict--from core.logging import get_logger--logger = get_logger(__name__)---async def handle_telegram_send(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle Telegram send message node execution.-- Parameters (snake_case):- - chat_id: Chat ID or @username (required)- - message_type: text, photo, document, location, contact (default: text)- - text: Message text (for text type)- - caption: Caption for media (for photo/document types)- - media_url: URL for photo/document- - parse_mode: HTML, Markdown, MarkdownV2 (optional)- - latitude, longitude: For location type- - phone_number, first_name, last_name: For contact type- - silent: Send without notification (default: False)- - reply_to_message_id: Reply to this message (optional)-- Returns:- Execution result with sent message info- """- from services.telegram_service import get_telegram_service-- start_time = time.time()- service = get_telegram_service()-- try:- if not service.connected:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "Telegram bot not connected. Add bot token in Credentials.",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- # Resolve recipient based on type (mirrors WhatsApp self-mode pattern)- recipient_type = parameters.get("recipient_type", "self")-- if recipient_type == "self":- chat_id = service.owner_chat_id- # Fallback: restore from credentials DB- if not chat_id:- try:- from core.container import container- auth = container.auth_service()- saved_owner = await auth.get_api_key("telegram_owner_chat_id")- if saved_owner:- owner_id = int(saved_owner)- await service.set_owner(owner_id)- chat_id = owner_id- logger.info(f"[Telegram] Owner restored from credentials: {owner_id}")- except Exception as e:- logger.warning(f"[Telegram] Failed to restore owner from credentials: {e}")- if not chat_id:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "Bot owner not detected. Send any private message to your bot on Telegram to auto-detect, or set TELEGRAM_OWNER_CHAT_ID in .env",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- else:- chat_id = parameters.get("chat_id")- if not chat_id:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "chat_id is required",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- message_type = parameters.get("message_type", "text")- parse_mode = parameters.get("parse_mode") or None- silent = parameters.get("silent", False)- reply_to = parameters.get("reply_to_message_id")- if reply_to:- reply_to = int(reply_to)-- # Route based on message type- result = {}- match message_type:- case "text":- text = parameters.get("text")- if not text:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "text is required for text message",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- result = await service.send_message(- chat_id=chat_id,- text=text,- parse_mode=parse_mode,- disable_notification=silent,- reply_to_message_id=reply_to,- )-- case "photo":- photo_url = parameters.get("media_url")- if not photo_url:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "media_url is required for photo message",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- result = await service.send_photo(- chat_id=chat_id,- photo=photo_url,- caption=parameters.get("caption"),- parse_mode=parse_mode,- disable_notification=silent,- reply_to_message_id=reply_to,- )-- case "document":- document_url = parameters.get("media_url")- if not document_url:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "media_url is required for document message",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- result = await service.send_document(- chat_id=chat_id,- document=document_url,- caption=parameters.get("caption"),- parse_mode=parse_mode,- disable_notification=silent,- reply_to_message_id=reply_to,- )-- case "location":- latitude = parameters.get("latitude")- longitude = parameters.get("longitude")- if latitude is None or longitude is None:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "latitude and longitude are required for location message",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- result = await service.send_location(- chat_id=chat_id,- latitude=float(latitude),- longitude=float(longitude),- disable_notification=silent,- reply_to_message_id=reply_to,- )-- case "contact":- phone_number = parameters.get("phone_number")- first_name = parameters.get("first_name")- if not phone_number or not first_name:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": "phone_number and first_name are required for contact message",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- result = await service.send_contact(- chat_id=chat_id,- phone_number=phone_number,- first_name=first_name,- last_name=parameters.get("last_name"),- disable_notification=silent,- reply_to_message_id=reply_to,- )-- case _:- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": f"Unsupported message type: {message_type}",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- logger.info(f"[Telegram] Message sent: type={message_type}, chat={chat_id}, msg_id={result.get('message_id')}")-- return {- "success": True,- "node_id": node_id,- "node_type": node_type,- "result": {- "message_id": result.get("message_id"),- "chat_id": result.get("chat_id"),- "message_type": message_type,- "date": result.get("date"),- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error(f"[Telegram] Send failed: {e}")- return {- "success": False,- "node_id": node_id,- "node_type": node_type,- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }--- # telegramReceive: routed via generic handle_trigger_node in node_executor.py- # Filter logic lives in event_waiter.build_telegram_filter() with lazy _get_owner_chat_id()diff --git a/server/services/handlers/todo.py b/server/services/handlers/todo.pydeleted file mode 100644index c5d58189..00000000--- a/server/services/handlers/todo.py+++ /dev/null@@ -1,73 +0,0 @@-"""Write Todos handler -- manages structured task lists for AI agents.--Dual-purpose: works as a workflow node (handle_write_todos) and as an-AI Agent tool (execute_write_todos). Follows the pattern of browser.py,-search.py, etc. Delegates state management to TodoService.-"""--from typing import Any, Dict--from core.logging import get_logger-from services.todo_service import get_todo_service--logger = get_logger(__name__)---async def handle_write_todos(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],-) -> Dict[str, Any]:- """Handle writeTodos as a workflow node.-- Standard workflow handler signature matching node_executor registry.- """- config = {- "node_id": node_id,- "workflow_id": context.get("workflow_id", ""),- "broadcaster": context.get("broadcaster"),- }- return await execute_write_todos(parameters, config)---async def execute_write_todos(- tool_args: Dict[str, Any],- config: Dict[str, Any],-) -> Dict[str, Any]:- """Execute write_todos tool call from AI Agent.-- Args:- tool_args: LLM-provided args matching WriteTodosSchema.- config: Tool config (node_id, workflow_id, broadcaster, etc.)-- Returns:- Dict with JSON-formatted todo list for LLM.- """- todos_input = tool_args.get("todos", [])- workflow_id = config.get("workflow_id", "")- node_id = config.get("node_id", "")- broadcaster = config.get("broadcaster")-- session_key = workflow_id or node_id or "default"-- service = get_todo_service()- stored = service.write(session_key, todos_input)-- # Broadcast todo update for real-time UI- if broadcaster and node_id:- await broadcaster.update_node_status(- node_id,- "executing",- {"phase": "todo_update", "todos": stored},- workflow_id=workflow_id,- )-- logger.info("[WriteTodos] Updated %d todos (session=%s)", len(stored), session_key)-- return {- "success": True,- "message": f"Updated todo list ({len(stored)} items)",- "todos": service.format_for_llm(session_key),- "count": len(stored),- }diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex cf1dbf02..8e23a1b1 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -772,17 +772,22 @@ async def _execute_delegated_agent(args: Dict[str, Any],workflow_id=workflow_id)- # Execute the child agent- if node_type == 'aiAgent':- from services.handlers.ai import handle_ai_agent- result = await handle_ai_agent(- node_id, node_type, child_params, child_context, ai_service, database- )- else:- from services.handlers.ai import handle_chat_agent- result = await handle_chat_agent(- node_id, node_type, child_params, child_context, ai_service, database- )+ # Execute the child agent via its own plugin class.+ # Wave 11.E.3: replaces the legacy handle_ai_agent /+ # handle_chat_agent imports — every agent type already owns+ # an @Operation method that wraps prepare_agent_call ++ # AIService dispatch, so we just go through BaseNode.execute.+ from services.node_registry import get_node_class+ from services.plugin import NodeContext++ plugin_cls = get_node_class(node_type)+ if plugin_cls is None:+ raise RuntimeError(f"Unknown delegated agent type: {node_type}")+ instance = plugin_cls()+ child_ctx = NodeContext.from_legacy(+ node_id=node_id, node_type=node_type, context=child_context,+ )+ result = await instance.execute(node_id, child_params, child_ctx)logger.info(f"[Delegated Agent] Task {task_id} completed: success={result.get('success')}")