Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(plugin): Wave 11.D.10 — utility.py split across 12 plugins
trohitg8e0d67b14f9d
diff --git a/server/nodes/chat/chat_history.py b/server/nodes/chat/chat_history.pyindex 73c3ea8d..5fc1a055 100644--- a/server/nodes/chat/chat_history.py+++ b/server/nodes/chat/chat_history.py@@ -1,8 +1,12 @@-"""Chat History — Wave 11.C migration. Retrieves chat conversation history."""+"""Chat History — Wave 11.D.10 fix.++Retrieves chat history via the external chat backend JSON-RPC 2.0+WebSocket (``services.chat_client``).+"""from __future__ import annotations-from typing import Any, Optional+from typing import Optionalfrom pydantic import BaseModel, ConfigDict, Field@@ -10,7 +14,10 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass ChatHistoryParams(BaseModel):+ host: str = Field(default="localhost")+ port: int = Field(default=8080, ge=1, le=65535)session_id: str = Field(default="default", alias="sessionId")+ api_key: str = Field(default="", alias="apiKey")limit: int = Field(default=50, ge=1, le=500)model_config = ConfigDict(populate_by_name=True, extra="ignore")@@ -38,16 +45,25 @@ class ChatHistoryNode(ActionNode):{"name": "output-main", "kind": "output", "position": "right","label": "Output", "role": "main"},)- annotations = {"destructive": False, "readonly": True, "open_world": False}+ annotations = {"destructive": False, "readonly": True, "open_world": True}task_queue = TaskQueue.DEFAULTParams = ChatHistoryParamsOutput = ChatHistoryOutput@Operation("read")- async def read(self, ctx: NodeContext, params: ChatHistoryParams) -> Any:- from core.container import container+ async def read(self, ctx: NodeContext, params: ChatHistoryParams) -> ChatHistoryOutput:+ from services.chat_client import get_chat_history++ result = await get_chat_history(+ host=params.host,+ port=params.port,+ session_id=params.session_id,+ api_key=params.api_key,+ limit=params.limit,+ )+ if not result.get("success"):+ raise RuntimeError(result.get("error", "chatHistory fetch failed"))- database = container.database()- messages = await database.get_chat_messages(params.session_id, limit=params.limit)+ messages = result.get("messages", []) or []return ChatHistoryOutput(messages=messages, count=len(messages))diff --git a/server/nodes/chat/chat_send.py b/server/nodes/chat/chat_send.pyindex 20565c64..636c4521 100644--- a/server/nodes/chat/chat_send.py+++ b/server/nodes/chat/chat_send.py@@ -1,4 +1,10 @@-"""Chat Send — Wave 11.C migration. Sends messages to chat conversations."""+"""Chat Send — Wave 11.D.10 fix.++Sends a message via the external chat backend JSON-RPC 2.0 WebSocket+(``services.chat_client``). Replaces my earlier 11.D.1 placeholder that+wrote to the local ``chat_messages`` table — that was a different+semantic (console-panel history, not chat backend).+"""from __future__ import annotations@@ -10,7 +16,12 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass ChatSendParams(BaseModel):+ host: str = Field(default="localhost")+ port: int = Field(default=8080, ge=1, le=65535)session_id: str = Field(default="default", alias="sessionId")+ api_key: str = Field(default="", alias="apiKey")+ content: str = Field(default="")+ # legacy field alias — earlier migration used ``message``message: str = Field(default="")model_config = ConfigDict(populate_by_name=True, extra="ignore")@@ -38,21 +49,33 @@ class ChatSendNode(ActionNode):{"name": "output-main", "kind": "output", "position": "right","label": "Output", "role": "main"},)- annotations = {"destructive": False, "readonly": False, "open_world": False}+ annotations = {"destructive": False, "readonly": False, "open_world": True}task_queue = TaskQueue.DEFAULTParams = ChatSendParamsOutput = ChatSendOutput@Operation("send")- async def send(self, ctx: NodeContext, params: ChatSendParams) -> Any:- from core.container import container-- if not params.message:- raise RuntimeError("Chat message is required")-- database = container.database()- ok = await database.add_chat_message(params.session_id, "assistant", params.message)- if not ok:- raise RuntimeError("Failed to persist chat message")- return ChatSendOutput(sent=True, message_id=None)+ async def send(self, ctx: NodeContext, params: ChatSendParams) -> ChatSendOutput:+ from services.chat_client import send_chat_message++ content = params.content or params.message+ if not content:+ raise RuntimeError("Message content is required")++ result = await send_chat_message(+ host=params.host,+ port=params.port,+ session_id=params.session_id,+ api_key=params.api_key,+ content=content,+ )+ if not result.get("success"):+ raise RuntimeError(result.get("error", "chatSend failed"))++ payload = result.get("result") or {}+ return ChatSendOutput(+ sent=True,+ message_id=payload.get("message_id") if isinstance(payload, dict) else None,+ **({k: v for k, v in payload.items() if k != "message_id"} if isinstance(payload, dict) else {}),+ )diff --git a/server/nodes/location/gmaps_create.py b/server/nodes/location/gmaps_create.pyindex d292101b..0b2b0630 100644--- a/server/nodes/location/gmaps_create.py+++ b/server/nodes/location/gmaps_create.py@@ -52,13 +52,10 @@ class GmapsCreateNode(ActionNode):@Operation("create")async def create(self, ctx: NodeContext, params: GmapsCreateParams) -> Any:from core.container import container- from services.handlers.utility import handle_create_mapmaps_service = container.maps_service()- response = await handle_create_map(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True),- context=ctx.raw, maps_service=maps_service,+ response = await maps_service.create_map(+ ctx.node_id, params.model_dump(by_alias=True), ctx.raw,)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/location/gmaps_locations.py b/server/nodes/location/gmaps_locations.pyindex f08c0498..971e3825 100644--- a/server/nodes/location/gmaps_locations.py+++ b/server/nodes/location/gmaps_locations.py@@ -50,13 +50,10 @@ class GmapsLocationsNode(ActionNode):@Operation("geocode", cost={"service": "google_maps", "action": "geocode", "count": 1})async def geocode(self, ctx: NodeContext, params: GmapsLocationsParams) -> Any:from core.container import container- from services.handlers.utility import handle_add_locationsmaps_service = container.maps_service()- response = await handle_add_locations(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True),- context=ctx.raw, maps_service=maps_service,+ response = await maps_service.geocode_location(+ ctx.node_id, params.model_dump(by_alias=True), ctx.raw,)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/location/gmaps_nearby_places.py b/server/nodes/location/gmaps_nearby_places.pyindex 05910f6c..beac6bd5 100644--- a/server/nodes/location/gmaps_nearby_places.py+++ b/server/nodes/location/gmaps_nearby_places.py@@ -51,13 +51,10 @@ class GmapsNearbyPlacesNode(ActionNode):@Operation("nearby", cost={"service": "google_maps", "action": "places_nearby", "count": 1})async def nearby(self, ctx: NodeContext, params: GmapsNearbyPlacesParams) -> Any:from core.container import container- from services.handlers.utility import handle_nearby_placesmaps_service = container.maps_service()- response = await handle_nearby_places(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True),- context=ctx.raw, maps_service=maps_service,+ response = await maps_service.find_nearby_places(+ ctx.node_id, params.model_dump(by_alias=True), ctx.raw,)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/scheduler/cron_scheduler.py b/server/nodes/scheduler/cron_scheduler.pyindex 6a402f16..5149d462 100644--- a/server/nodes/scheduler/cron_scheduler.py+++ b/server/nodes/scheduler/cron_scheduler.py@@ -1,29 +1,110 @@-"""Cron Scheduler — Wave 11.C migration.+"""Cron Scheduler — Wave 11.D.10 inlined.Cron-expression-based scheduling trigger. Deployment-mode lifecycle(starting/stopping the cron job) is owned by ``deployment/triggers.py``;-the run-button path runs handle_cron_scheduler directly for one-shot-testing.+the run-button path executes this plugin once for testing."""from __future__ import annotations-from typing import Any, Optional+import asyncio+import time+from datetime import datetime, timedelta+from 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__)+++def _calculate_wait_seconds(p: Dict[str, Any]) -> int:+ frequency = p.get("frequency", "minutes")+ match frequency:+ case "seconds":+ return int(p.get("interval", 30))+ case "minutes":+ return int(p.get("interval_minutes", 5)) * 60+ case "hours":+ return int(p.get("interval_hours", 1)) * 3600+ case "days":+ return 24 * 3600+ case "weeks":+ return 7 * 24 * 3600+ case "months":+ return 30 * 24 * 3600+ case "once":+ return 0+ case _:+ return 300+++def _format_wait_time(seconds: int) -> str:+ if seconds < 60:+ return f"{seconds} seconds"+ if seconds < 3600:+ m = seconds // 60+ return f"{m} minute{'s' if m != 1 else ''}"+ if seconds < 86400:+ h = seconds // 3600+ return f"{h} hour{'s' if h != 1 else ''}"+ d = seconds // 86400+ return f"{d} day{'s' if d != 1 else ''}"+++def _get_schedule_description(p: Dict[str, Any]) -> str:+ frequency = p.get("frequency", "minutes")+ match frequency:+ case "seconds":+ return f"Every {p.get('interval', 30)} seconds"+ case "minutes":+ return f"Every {p.get('interval_minutes', 5)} minutes"+ case "hours":+ return f"Every {p.get('interval_hours', 1)} hours"+ case "days":+ return f"Daily at {p.get('daily_time', '09:00')}"+ case "weeks":+ weekday = str(p.get("weekday", "1"))+ days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]+ day_name = days[int(weekday)] if weekday.isdigit() else weekday+ return f"Weekly on {day_name} at {p.get('weekly_time', '09:00')}"+ case "months":+ return f"Monthly on day {p.get('month_day', '1')} at {p.get('monthly_time', '09:00')}"+ case "once":+ return "Once (no repeat)"+ case _:+ return "Unknown schedule"+class CronSchedulerParams(BaseModel):cron_expression: str = Field(default="0 * * * *", alias="cronExpression")timezone: str = Field(default="UTC")+ frequency: str = Field(default="minutes")+ interval: int = Field(default=30)+ interval_minutes: int = Field(default=5, alias="intervalMinutes")+ interval_hours: int = Field(default=1, alias="intervalHours")+ daily_time: str = Field(default="09:00", alias="dailyTime")+ weekly_time: str = Field(default="09:00", alias="weeklyTime")+ weekday: str = Field(default="1")+ monthly_time: str = Field(default="09:00", alias="monthlyTime")+ month_day: str = Field(default="1", alias="monthDay")- model_config = ConfigDict(populate_by_name=True, extra="ignore")+ model_config = ConfigDict(populate_by_name=True, extra="allow")class CronSchedulerOutput(BaseModel):+ timestamp: Optional[str] = None+ iteration: Optional[int] = None+ frequency: Optional[str] = None+ timezone: Optional[str] = None+ schedule: Optional[str] = None+ scheduled_time: Optional[str] = Nonetriggered_at: Optional[str] = None+ waited_seconds: Optional[int] = None+ next_run: Optional[str] = None+ message: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")@@ -48,12 +129,57 @@ class CronSchedulerNode(ActionNode):Output = CronSchedulerOutput@Operation("trigger")- async def trigger(self, ctx: NodeContext, params: CronSchedulerParams) -> Any:- from services.handlers.utility import handle_cron_scheduler- response = await handle_cron_scheduler(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,+ async def trigger(self, ctx: NodeContext, params: CronSchedulerParams) -> CronSchedulerOutput:+ from services.status_broadcaster import get_status_broadcaster++ start_time = time.time()+ p = params.model_dump(by_alias=False)+ frequency = p.get("frequency", "minutes")+ timezone = p.get("timezone", "UTC")++ schedule_desc = _get_schedule_description(p)+ wait_seconds = _calculate_wait_seconds(p)++ now = datetime.now()+ trigger_time = now + timedelta(seconds=wait_seconds)++ await get_status_broadcaster().update_node_status(+ ctx.node_id, "waiting",+ {+ "message": f"Waiting {schedule_desc}...",+ "trigger_time": trigger_time.isoformat(),+ "wait_seconds": wait_seconds,+ },+ workflow_id=ctx.workflow_id,+ )++ logger.info(+ f"[CronScheduler] Waiting {wait_seconds}s for trigger",+ node_id=ctx.node_id, trigger_time=trigger_time.isoformat(),+ )++ try:+ await asyncio.sleep(wait_seconds)+ except asyncio.CancelledError:+ raise RuntimeError("Scheduler cancelled")++ triggered_at = datetime.now()+ output = CronSchedulerOutput(+ timestamp=triggered_at.isoformat(),+ iteration=1,+ frequency=frequency,+ timezone=timezone,+ schedule=schedule_desc,+ scheduled_time=trigger_time.isoformat(),+ triggered_at=triggered_at.isoformat(),+ waited_seconds=wait_seconds,)- if response.get("success") is False:- raise RuntimeError(response.get("error") or "Cron failed")- return response.get("result") or {}+ if frequency == "once":+ output.message = f"Triggered after waiting {_format_wait_time(wait_seconds)}"+ else:+ output.next_run = schedule_desc+ output.message = (+ f"Triggered after {_format_wait_time(wait_seconds)}, "+ f"will repeat: {schedule_desc}"+ )+ return outputdiff --git a/server/nodes/scheduler/timer.py b/server/nodes/scheduler/timer.pyindex e7e3824c..a323b733 100644--- a/server/nodes/scheduler/timer.py+++ b/server/nodes/scheduler/timer.py@@ -51,11 +51,44 @@ class TimerNode(ActionNode):@Operation("wait")async def wait(self, ctx: NodeContext, params: TimerParams) -> Any:- from services.handlers.utility import handle_timer- response = await handle_timer(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,+ import asyncio+ import time+ from datetime import datetime, timedelta++ from services.status_broadcaster import get_status_broadcaster++ start_time = time.time()+ duration = int(params.duration)+ unit = params.unit+ match unit:+ case "minutes":+ wait_seconds = duration * 60+ case "hours":+ wait_seconds = duration * 3600+ case _:+ wait_seconds = duration++ complete_time = datetime.now() + timedelta(seconds=wait_seconds)+ await get_status_broadcaster().update_node_status(+ ctx.node_id, "waiting",+ {+ "message": f"Waiting {duration} {unit}...",+ "complete_time": complete_time.isoformat(),+ "wait_seconds": wait_seconds,+ },+ workflow_id=ctx.workflow_id,)- if response.get("success") is False:- raise RuntimeError(response.get("error") or "Timer failed")- return response.get("result") or {}++ try:+ await asyncio.sleep(wait_seconds)+ except asyncio.CancelledError:+ raise RuntimeError("Timer cancelled")++ elapsed_ms = int((time.time() - start_time) * 1000)+ return {+ "timestamp": datetime.now().isoformat(),+ "elapsed_ms": elapsed_ms,+ "duration": duration,+ "unit": unit,+ "message": f"Timer completed after {duration} {unit}",+ }diff --git a/server/nodes/text/file_handler.py b/server/nodes/text/file_handler.pyindex 92d290ca..51667e8d 100644--- a/server/nodes/text/file_handler.py+++ b/server/nodes/text/file_handler.py@@ -48,13 +48,10 @@ class FileHandlerNode(ActionNode):@Operation("dispatch")async def dispatch(self, ctx: NodeContext, params: FileHandlerParams) -> Any:from core.container import container- from services.handlers.utility import handle_file_handlertext_service = container.text_service()- response = await handle_file_handler(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True),- context=ctx.raw, text_service=text_service,+ response = await text_service.execute_file_handler(+ ctx.node_id, params.model_dump(by_alias=True),)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/text/text_generator.py b/server/nodes/text/text_generator.pyindex efd60cc3..bc218603 100644--- a/server/nodes/text/text_generator.py+++ b/server/nodes/text/text_generator.py@@ -47,13 +47,10 @@ class TextGeneratorNode(ActionNode):@Operation("generate")async def generate(self, ctx: NodeContext, params: TextGeneratorParams) -> Any:from core.container import container- from services.handlers.utility import handle_text_generatortext_service = container.text_service()- response = await handle_text_generator(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True),- context=ctx.raw, text_service=text_service,+ response = await text_service.execute_text_generator(+ ctx.node_id, params.model_dump(by_alias=True),)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/utility/console.py b/server/nodes/utility/console.pyindex 9333da98..d65c1153 100644--- a/server/nodes/utility/console.py+++ b/server/nodes/utility/console.py@@ -1,24 +1,90 @@-"""Console — Wave 11.C migration.--Sink node that logs upstream outputs to the Console panel for-debugging. Reads ``connected_outputs`` + ``source_nodes`` injected-by ``NodeExecutor._dispatch`` (any plugin needing upstream data-declares its type in ``_NEEDS_CONNECTED_OUTPUTS``).--Delegates the actual log-formatting + broadcast to the existing-``handlers/utility.handle_console`` — that body is non-trivial-(JSON / table / expression formatting + WS broadcast) and stable,-so 11.C ports the shell only.+"""Console — Wave 11.D.10 inlined.++Sink node that logs upstream outputs to the Console panel. Reads+``connected_outputs`` + ``source_nodes`` injected by+``NodeExecutor._dispatch`` (any plugin needing upstream data declares+its type in ``_NEEDS_CONNECTED_OUTPUTS``).++Supports three log modes — ``all`` (dump the merged input),+``field`` (dot-path navigation with ``items[0]`` array indexing),+``expression`` (use the already-resolved parameter value). Output is+formatted as JSON (pretty / compact), plain text, or an ASCII table+for lists of dicts."""from __future__ import annotations+import json+import re+import time+from datetime import datetimefrom typing import Any, Dict, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field+from core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue+logger = get_logger(__name__)+++def _navigate_field_path(data: Any, path: str) -> Any:+ if not path:+ return data+ current = data+ for part in path.split("."):+ if current is None:+ return None+ m = re.match(r"^(\w+)\[(\d+)\]$", part)+ if m:+ field, idx = m.group(1), int(m.group(2))+ if isinstance(current, dict) and field in current:+ current = current[field]+ else:+ return None+ if isinstance(current, list) and 0 <= idx < len(current):+ current = current[idx]+ else:+ return None+ else:+ if isinstance(current, dict) and part in current:+ current = current[part]+ else:+ return None+ return current+++def _format_console_output(data: Any, format_type: str) -> str:+ match format_type:+ case "json":+ try:+ return json.dumps(data, indent=2, default=str, ensure_ascii=False)+ except Exception:+ return str(data)+ case "json_compact":+ try:+ return json.dumps(data, default=str, ensure_ascii=False)+ except Exception:+ return str(data)+ case "text":+ return str(data)+ case "table":+ if isinstance(data, list) and data and isinstance(data[0], dict):+ headers = list(data[0].keys())+ rows = [[str(r.get(h, "")) for h in headers] for r in data]+ widths = [max(len(h), max((len(r[i]) for r in rows), default=0))+ for i, h in enumerate(headers)]+ header_line = " | ".join(h.ljust(widths[i]) for i, h in enumerate(headers))+ sep = "-+-".join("-" * w for w in widths)+ body = ["\n" .join(+ " | ".join(r[i].ljust(widths[i]) for i in range(len(headers)))+ for r in rows+ )]+ return "\n".join([header_line, sep, *body])+ return json.dumps(data, indent=2, default=str, ensure_ascii=False)+ case _:+ return str(data)+class ConsoleParams(BaseModel):label: str = ""@@ -39,9 +105,11 @@ class ConsoleParams(BaseModel):class ConsoleOutput(BaseModel):- logged: Optional[Any] = Nonelabel: Optional[str] = None- timestamp: Optional[str] = None+ logged_at: Optional[str] = None+ format: Optional[str] = None+ data: Optional[Any] = None+ formatted: Optional[str] = Nonemodel_config = ConfigDict(extra="allow")@@ -68,17 +136,65 @@ class ConsoleNode(ActionNode):Output = ConsoleOutput@Operation("log")- async def log(self, ctx: NodeContext, params: ConsoleParams) -> Any:- from services.handlers.utility import handle_console- outputs = ctx.raw.get("connected_outputs") or {}+ async def log(self, ctx: NodeContext, params: ConsoleParams) -> Dict[str, Any]:+ from services.status_broadcaster import get_status_broadcaster++ label = params.label+ log_mode = params.log_mode+ format_type = params.format+ field_path = params.field_path+ expression = params.expression++ connected_outputs = ctx.raw.get("connected_outputs") or {}source_nodes = ctx.raw.get("source_nodes") or []- response = await handle_console(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True),- context=ctx.raw,- connected_outputs=outputs,- source_nodes=source_nodes,- )- if response.get("success") is False:- raise RuntimeError(response.get("error") or "console log failed")- return response.get("result") or {}++ input_data: Dict[str, Any] = {}+ for _node_type, output in connected_outputs.items():+ if isinstance(output, dict):+ input_data.update(output)+ else:+ input_data["value"] = output++ source_info = source_nodes[0] if source_nodes else None++ log_value: Any = None+ match log_mode:+ case "all":+ log_value = input_data+ case "field":+ if field_path:+ if "{{" not in field_path and field_path not in input_data:+ log_value = field_path+ else:+ log_value = _navigate_field_path(input_data, field_path)+ else:+ log_value = input_data+ case "expression":+ log_value = expression if expression else input_data+ case _:+ log_value = input_data++ formatted_output = _format_console_output(log_value, format_type)++ await get_status_broadcaster().broadcast_console_log({+ "node_id": ctx.node_id,+ "label": label or f"Console ({ctx.node_id[:8]})",+ "timestamp": datetime.now().isoformat(),+ "data": log_value,+ "formatted": formatted_output,+ "format": format_type,+ "workflow_id": ctx.workflow_id,+ "source_node_id": source_info.get("id") if source_info else None,+ "source_node_type": source_info.get("type") if source_info else None,+ "source_node_label": source_info.get("label") if source_info else None,+ })++ # Pass through original input for downstream nodes.+ return {+ "label": label or f"Console ({ctx.node_id[:8]})",+ "logged_at": datetime.now().isoformat(),+ "format": format_type,+ "data": log_value,+ "formatted": formatted_output,+ **input_data,+ }diff --git a/server/nodes/utility/team_monitor.py b/server/nodes/utility/team_monitor.pyindex 18ef4cd1..a522111b 100644--- a/server/nodes/utility/team_monitor.py+++ b/server/nodes/utility/team_monitor.py@@ -46,11 +46,37 @@ class TeamMonitorNode(ActionNode):@Operation("monitor")async def monitor(self, ctx: NodeContext, params: TeamMonitorParams) -> Any:- from services.handlers.utility import handle_team_monitor- response = await handle_team_monitor(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,- )- if response.get("success") is False:- raise RuntimeError(response.get("error") or "Team monitor failed")- return response.get("result") or {}+ from services.agent_team import get_agent_team_service++ team_id = ctx.raw.get("team_id")+ if not team_id:+ for output in (ctx.raw.get("outputs", {}) or {}).values():+ if isinstance(output, dict) and output.get("team_id"):+ team_id = output["team_id"]+ break++ if not team_id:+ return {+ "message": "No team connected",+ "team_id": None,+ "members": [],+ "tasks": {"total": 0, "completed": 0, "active": 0, "pending": 0, "failed": 0},+ "active_tasks": [],+ "recent_events": [],+ }++ status = await get_agent_team_service().get_team_status(team_id)+ max_history = ctx.raw.get("parameters", {}).get("maxHistoryItems", 50)+ return {+ "team_id": team_id,+ "members": status.get("members", []),+ "tasks": {+ "total": status.get("task_count", 0),+ "completed": status.get("completed_count", 0),+ "active": status.get("active_count", 0),+ "pending": status.get("pending_count", 0),+ "failed": status.get("failed_count", 0),+ },+ "active_tasks": status.get("active_tasks", []),+ "recent_events": status.get("recent_events", [])[-max_history:],+ }diff --git a/server/nodes/workflow/start.py b/server/nodes/workflow/start.pyindex 710b00f3..49415207 100644--- a/server/nodes/workflow/start.py+++ b/server/nodes/workflow/start.py@@ -53,11 +53,14 @@ class StartNode(ActionNode):@Operation("emit")async def emit(self, ctx: NodeContext, params: StartParams) -> Any:- from services.handlers.utility import handle_start- response = await handle_start(- node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,- )- if response.get("success") is False:- raise RuntimeError(response.get("error") or "Start failed")- return response.get("result") or {}+ import json++ raw = params.initial_data+ if raw is None:+ return {}+ if isinstance(raw, str):+ try:+ return json.loads(raw)+ except Exception:+ return {}+ return rawdiff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex 1e104f0e..4da51e08 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -50,21 +50,7 @@ from .triggers import (handle_trigger_node,)-# Utility handlers-from .utility import (- handle_create_map,- handle_add_locations,- handle_nearby_places,- handle_text_generator,- handle_file_handler,- handle_chat_send,- handle_chat_history,- handle_start,- handle_cron_scheduler,- handle_timer,- handle_console,- handle_team_monitor,-)+# Utility handlers inlined into their plugin files (Wave 11.D.10).# WhatsApp handlers inlined into nodes/whatsapp/*.py (Wave 11.D.9).@@ -135,18 +121,6 @@ __all__ = [# Triggers'handle_trigger_node',# Utility- 'handle_create_map',- 'handle_add_locations',- 'handle_nearby_places',- 'handle_text_generator',- 'handle_file_handler',- 'handle_chat_send',- 'handle_chat_history',- 'handle_start',- 'handle_cron_scheduler',- 'handle_timer',- 'handle_console',- 'handle_team_monitor',# Socialdiff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 62df51e6..b497ba20 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -135,29 +135,7 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],context=context,)- # Timer tool (dual-purpose: workflow node + AI tool)- # LLM fills duration/unit via Pydantic schema; calls existing handle_timer handler- if node_type == 'timer':- from services.handlers.utility import handle_timer- parameters = {**config.get('parameters', {}), **tool_args}- return await handle_timer(- node_id=config.get('node_id', 'tool_timer'),- node_type='timer',- parameters=parameters,- context={}- )-- # Cron Scheduler tool (dual-purpose: workflow node + AI tool)- # LLM fills schedule params via CronSchedulerParams schema; calls existing handler- if node_type == 'cronScheduler':- from services.handlers.utility import handle_cron_scheduler- parameters = {**config.get('parameters', {}), **tool_args}- return await handle_cron_scheduler(- node_id=config.get('node_id', 'tool_cron_scheduler'),- node_type='cronScheduler',- parameters=parameters,- context={}- )+ # timer / cronScheduler: handled by the plugin fast-path above.# WhatsApp / Twitter / Google Workspace / Search / Maps tool branches# all migrated to plugin classes — routed via the Wave 11.B.1 fast-path@@ -782,106 +760,9 @@ async def _execute_android_service(args: Dict[str, Any],return {"error": str(e)}-async def _execute_geocoding(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Maps geocoding (gmaps_locations node as tool).-- Args:- args: LLM-provided arguments (snake_case: service_type, address, lat, lng)- node_params: Node parameters (may contain api_key)-- Returns:- Geocoding result with coordinates or address- """- from services.handlers.utility import handle_add_locations- from core.container import container-- # Fetch API key from database (source of truth)- auth_service = container.auth_service()- api_key = await auth_service.get_api_key("google_maps", "default") or ''-- # Args use snake_case matching Pydantic schema and node params- parameters = {**args, 'api_key': api_key}-- service_type = parameters.get('service_type', 'geocode')-- # Validate required fields- if service_type == 'geocode' and not parameters.get('address'):- return {"error": "address is required for geocoding"}- if service_type == 'reverse_geocode':- if parameters.get('lat') is None or parameters.get('lng') is None:- return {"error": "lat and lng are required for reverse geocoding"}-- lat, lng = parameters.get('lat'), parameters.get('lng')- location_str = parameters.get('address') or f"({lat}, {lng})"- logger.info(f"[Geocoding Tool] {service_type}: {location_str}")-- try:- maps_service = container.maps_service()- result = await handle_add_locations(- node_id="tool_geocoding",- node_type="gmaps_locations",- parameters=parameters,- context={},- maps_service=maps_service- )-- if result.get('success'):- return {"success": True, "service_type": service_type, **result.get('result', {})}- else:- return {"error": result.get('error', 'Geocoding failed')}-- except Exception as e:- logger.error(f"[Geocoding Tool] Error: {e}")- return {"error": f"Geocoding failed: {str(e)}"}---async def _execute_nearby_places(args: Dict[str, Any],- node_params: Dict[str, Any]) -> Dict[str, Any]:- """Execute Google Maps nearby places search (gmaps_nearby_places node as tool).-- Args:- args: LLM-provided arguments (snake_case: lat, lng, radius, type, keyword)- node_params: Node parameters (may contain api_key)-- Returns:- Nearby places search results- """- from services.handlers.utility import handle_nearby_places- from core.container import container-- # Fetch API key from database (source of truth)- auth_service = container.auth_service()- api_key = await auth_service.get_api_key("google_maps", "default") or ''-- # Args use snake_case matching Pydantic schema and node params- parameters = {**args, 'api_key': api_key}-- # Validate required fields- if parameters.get('lat') is None or parameters.get('lng') is None:- return {"error": "lat and lng are required for nearby places search"}-- place_type = parameters.get('type', 'restaurant')- logger.info(f"[Nearby Places Tool] Searching {place_type} near ({parameters['lat']}, {parameters['lng']})")-- try:- maps_service = container.maps_service()- result = await handle_nearby_places(- node_id="tool_nearby_places",- node_type="gmaps_nearby_places",- parameters=parameters,- context={},- maps_service=maps_service- )-- if result.get('success'):- return {"success": True, "type": place_type, **result.get('result', {})}- else:- return {"error": result.get('error', 'Nearby places search failed')}-- except Exception as e:- logger.error(f"[Nearby Places Tool] Error: {e}")- return {"error": f"Nearby places search failed: {str(e)}"}+# Wave 11.D.10: _execute_geocoding / _execute_nearby_places deleted.+# gmaps_locations + gmaps_nearby_places now route through the plugin+# fast-path (nodes/location/*.py).# _execute_google_gmail: deleted in Wave 11.C cleanup. gmail now routesdiff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.pydeleted file mode 100644index fac959c4..00000000--- a/server/services/handlers/utility.py+++ /dev/null@@ -1,913 +0,0 @@-"""Utility node handlers - Maps, Text, Chat, Cron, Start."""--import asyncio-import json-import time-from datetime import datetime, timedelta-from typing import Dict, Any, TYPE_CHECKING-from core.logging import get_logger--if TYPE_CHECKING:- from services.maps import MapsService- from services.text import TextService--logger = get_logger(__name__)---# =============================================================================-# MAPS HANDLERS-# =============================================================================--async def handle_create_map(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- maps_service: "MapsService"-) -> Dict[str, Any]:- """Handle create map node execution.-- Args:- node_id: The node ID- node_type: The node type (gmaps_create)- parameters: Resolved parameters- context: Execution context- maps_service: The maps service instance-- Returns:- Execution result dict- """- logger.info("[Maps Execution] Executing gmaps_create", node_id=node_id)- result = await maps_service.create_map(node_id, parameters, context)- logger.info("[Maps Execution] gmaps_create result", success=result.get('success'),- has_result='result' in result,- result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')- return result---async def handle_add_locations(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- maps_service: "MapsService"-) -> Dict[str, Any]:- """Handle add locations node execution (geocoding).-- Args:- node_id: The node ID- node_type: The node type (gmaps_locations)- parameters: Resolved parameters- context: Execution context- maps_service: The maps service instance-- Returns:- Execution result dict- """- logger.info("[Maps Execution] Executing gmaps_locations", node_id=node_id)- result = await maps_service.geocode_location(node_id, parameters, context)- logger.info("[Maps Execution] gmaps_locations result", success=result.get('success'),- has_result='result' in result,- result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')- return result---async def handle_nearby_places(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- maps_service: "MapsService"-) -> Dict[str, Any]:- """Handle show nearby places node execution.-- Args:- node_id: The node ID- node_type: The node type (gmaps_nearby_places)- parameters: Resolved parameters- context: Execution context- maps_service: The maps service instance-- Returns:- Execution result dict- """- logger.info("[Maps Execution] Executing gmaps_nearby_places", node_id=node_id)- result = await maps_service.find_nearby_places(node_id, parameters, context)- logger.info("[Maps Execution] gmaps_nearby_places result", success=result.get('success'),- has_result='result' in result,- result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')- return result---# =============================================================================-# TEXT HANDLERS-# =============================================================================--async def handle_text_generator(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- text_service: "TextService"-) -> Dict[str, Any]:- """Handle text generator node execution.-- Args:- node_id: The node ID- node_type: The node type (textGenerator)- parameters: Resolved parameters- context: Execution context- text_service: The text service instance-- Returns:- Execution result dict- """- return await text_service.execute_text_generator(node_id, parameters)---async def handle_file_handler(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- text_service: "TextService"-) -> Dict[str, Any]:- """Handle file handler node execution.-- Args:- node_id: The node ID- node_type: The node type (fileHandler)- parameters: Resolved parameters- context: Execution context- text_service: The text service instance-- Returns:- Execution result dict- """- return await text_service.execute_file_handler(node_id, parameters)---# =============================================================================-# CHAT HANDLERS-# =============================================================================--async def handle_chat_send(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle chat send message via JSON-RPC 2.0 WebSocket.-- Args:- node_id: The node ID- node_type: The node type (chatSend)- parameters: Resolved parameters- context: Execution context-- Returns:- Execution result dict- """- from services.chat_client import send_chat_message- start_time = time.time()-- try:- host = parameters.get('host', 'localhost')- port = int(parameters.get('port', 8080))- session_id = parameters.get('session_id', 'default')- api_key = parameters.get('api_key', '')- content = parameters.get('content', '')-- if not content:- raise ValueError("Message content is required")-- result = await send_chat_message(- host=host, port=port, session_id=session_id,- api_key=api_key, content=content- )-- if result.get('success'):- return {- "success": True,- "node_id": node_id,- "node_type": "chatSend",- "result": result.get('result', {}),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- else:- raise Exception(result.get('error', 'Send failed'))-- except Exception as e:- logger.error("Chat send failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "chatSend",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---async def handle_chat_history(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle chat get history via JSON-RPC 2.0 WebSocket.-- Args:- node_id: The node ID- node_type: The node type (chatHistory)- parameters: Resolved parameters- context: Execution context-- Returns:- Execution result dict with messages- """- from services.chat_client import get_chat_history- start_time = time.time()-- try:- host = parameters.get('host', 'localhost')- port = int(parameters.get('port', 8080))- session_id = parameters.get('session_id', 'default')- api_key = parameters.get('api_key', '')- limit = int(parameters.get('limit', 50))-- result = await get_chat_history(- host=host, port=port, session_id=session_id,- api_key=api_key, limit=limit- )-- if result.get('success'):- return {- "success": True,- "node_id": node_id,- "node_type": "chatHistory",- "result": {"messages": result.get('messages', [])},- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- else:- raise Exception(result.get('error', 'History fetch failed'))-- except Exception as e:- logger.error("Chat history failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "chatHistory",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---# =============================================================================-# WORKFLOW CONTROL HANDLERS-# =============================================================================--async def handle_start(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle start node execution.-- Args:- node_id: The node ID- node_type: The node type (start)- parameters: Resolved parameters- context: Execution context-- Returns:- Execution result dict with initial data- """- initial_data_str = parameters.get('initialData', '{}')- try:- initial_data = json.loads(initial_data_str)- except Exception:- initial_data = {}-- return {- "success": True,- "node_id": node_id,- "node_type": "start",- "result": initial_data- }---async def handle_cron_scheduler(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle cron scheduler node execution.-- Waits for the configured interval duration before triggering.- Used for recurring scheduled tasks.-- Args:- node_id: The node ID- node_type: The node type (cronScheduler)- parameters: Resolved parameters- context: Execution context-- Returns:- Execution result dict with schedule info- """- from services.status_broadcaster import get_status_broadcaster- start_time = time.time()-- try:- frequency = parameters.get('frequency', 'minutes')- timezone = parameters.get('timezone', 'UTC')-- # Build human-readable schedule description- schedule_desc = _get_schedule_description(parameters)-- logger.info("[CronScheduler] Executing",- node_id=node_id,- frequency=frequency,- schedule=schedule_desc)-- # Calculate wait time in seconds based on frequency- wait_seconds = _calculate_wait_seconds(parameters)-- now = datetime.now()- trigger_time = now + timedelta(seconds=wait_seconds)-- # Get workflow_id from context for per-workflow status scoping (n8n pattern)- workflow_id = context.get('workflow_id')-- # Broadcast waiting status to frontend- broadcaster = get_status_broadcaster()- await broadcaster.update_node_status(node_id, "waiting", {- "message": f"Waiting {schedule_desc}...",- "trigger_time": trigger_time.isoformat(),- "wait_seconds": wait_seconds- }, workflow_id=workflow_id)-- logger.info(f"[CronScheduler] Waiting {wait_seconds} seconds until trigger",- node_id=node_id, trigger_time=trigger_time.isoformat())-- # Wait for the duration- await asyncio.sleep(wait_seconds)-- # Build result data after wait completes- triggered_at = datetime.now()- result_data = {- "timestamp": triggered_at.isoformat(),- "iteration": 1,- "frequency": frequency,- "timezone": timezone,- "schedule": schedule_desc,- "scheduled_time": trigger_time.isoformat(),- "triggered_at": triggered_at.isoformat(),- "waited_seconds": wait_seconds- }-- if frequency == 'once':- result_data["message"] = f"Triggered after waiting {_format_wait_time(wait_seconds)}"- else:- result_data["next_run"] = schedule_desc- result_data["message"] = f"Triggered after {_format_wait_time(wait_seconds)}, will repeat: {schedule_desc}"-- return {- "success": True,- "node_id": node_id,- "node_type": "cronScheduler",- "result": result_data,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except asyncio.CancelledError:- logger.info("[CronScheduler] Cancelled while waiting", node_id=node_id)- return {- "success": False,- "node_id": node_id,- "node_type": "cronScheduler",- "error": "Scheduler cancelled",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- except Exception as e:- logger.error("CronScheduler execution failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "cronScheduler",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---# =============================================================================-# CRON HELPER FUNCTIONS-# =============================================================================--def _calculate_wait_seconds(parameters: Dict[str, Any]) -> int:- """Calculate wait time in seconds based on frequency and interval."""- frequency = parameters.get('frequency', 'minutes')-- # Calculate wait based on frequency type- match frequency:- case 'seconds':- return int(parameters.get('interval', 30))- case 'minutes':- return int(parameters.get('interval_minutes', 5)) * 60- case 'hours':- return int(parameters.get('interval_hours', 1)) * 3600- case 'days':- return 24 * 3600 # Wait 24 hours- case 'weeks':- return 7 * 24 * 3600 # Wait 7 days- case 'months':- return 30 * 24 * 3600 # Wait ~30 days- case 'once':- return 0 # Trigger immediately- case _:- return 300 # Default: 5 minutes---def _format_wait_time(seconds: int) -> str:- """Format seconds into human-readable time string."""- if seconds < 60:- return f"{seconds} seconds"- elif seconds < 3600:- minutes = seconds // 60- return f"{minutes} minute{'s' if minutes != 1 else ''}"- elif seconds < 86400:- hours = seconds // 3600- return f"{hours} hour{'s' if hours != 1 else ''}"- else:- days = seconds // 86400- return f"{days} day{'s' if days != 1 else ''}"---def _get_schedule_description(parameters: Dict[str, Any]) -> str:- """Get human-readable schedule description from parameters."""- frequency = parameters.get('frequency', 'minutes')-- match frequency:- case 'seconds':- interval = parameters.get('interval', 30)- return f"Every {interval} seconds"- case 'minutes':- interval = parameters.get('interval_minutes', 5)- return f"Every {interval} minutes"- case 'hours':- interval = parameters.get('interval_hours', 1)- return f"Every {interval} hours"- case 'days':- time_str = parameters.get('daily_time', '09:00')- return f"Daily at {time_str}"- case 'weeks':- weekday = parameters.get('weekday', '1')- time_str = parameters.get('weekly_time', '09:00')- days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']- day_name = days[int(weekday)] if weekday.isdigit() else weekday- return f"Weekly on {day_name} at {time_str}"- case 'months':- day = parameters.get('month_day', '1')- time_str = parameters.get('monthly_time', '09:00')- return f"Monthly on day {day} at {time_str}"- case 'once':- return "Once (no repeat)"- case _:- return "Unknown schedule"---# =============================================================================-# TIMER HANDLER-# =============================================================================--async def handle_timer(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle timer node execution - waits for specified duration.-- Args:- node_id: The node ID- node_type: The node type (timer)- parameters: Resolved parameters with duration and unit- context: Execution context-- Returns:- Execution result dict with timing info- """- from services.status_broadcaster import get_status_broadcaster- start_time = time.time()-- try:- duration = int(parameters.get('duration', 5))- unit = parameters.get('unit', 'seconds')-- # Convert duration to seconds- match unit:- case 'seconds':- wait_seconds = duration- case 'minutes':- wait_seconds = duration * 60- case 'hours':- wait_seconds = duration * 3600- case _:- wait_seconds = duration-- now = datetime.now()- complete_time = now + timedelta(seconds=wait_seconds)-- # Get workflow_id from context for per-workflow status scoping (n8n pattern)- workflow_id = context.get('workflow_id')- logger.info("[Timer] Context workflow_id", node_id=node_id, workflow_id=workflow_id, context_keys=list(context.keys()))-- # Broadcast waiting status- broadcaster = get_status_broadcaster()- await broadcaster.update_node_status(node_id, "waiting", {- "message": f"Waiting {duration} {unit}...",- "complete_time": complete_time.isoformat(),- "wait_seconds": wait_seconds- }, workflow_id=workflow_id)-- logger.info("[Timer] Starting wait",- node_id=node_id,- duration=duration,- unit=unit,- wait_seconds=wait_seconds)-- # Wait for the duration- await asyncio.sleep(wait_seconds)-- elapsed_ms = int((time.time() - start_time) * 1000)-- result_data = {- "timestamp": datetime.now().isoformat(),- "elapsed_ms": elapsed_ms,- "duration": duration,- "unit": unit,- "message": f"Timer completed after {duration} {unit}"- }-- logger.info("[Timer] Completed",- node_id=node_id,- elapsed_ms=elapsed_ms)-- return {- "success": True,- "node_id": node_id,- "node_type": "timer",- "result": result_data,- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except asyncio.CancelledError:- logger.info("[Timer] Cancelled", node_id=node_id)- return {- "success": False,- "node_id": node_id,- "node_type": "timer",- "error": "Timer cancelled",- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }- except Exception as e:- logger.error("[Timer] Failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "timer",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---# =============================================================================-# CONSOLE HANDLER-# =============================================================================--async def handle_console(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any],- connected_outputs: Dict[str, Any] = None,- source_nodes: list = None-) -> Dict[str, Any]:- """Handle console node execution - logs input data for debugging.-- The console node:- 1. Receives input data from connected upstream nodes (via _get_connected_outputs_with_info)- 2. Logs the data to the console panel based on log mode- 3. Passes the input through unchanged to downstream nodes-- Args:- node_id: The node ID- node_type: The node type (console)- parameters: Resolved parameters including label, logMode, format- context: Execution context- connected_outputs: Outputs from connected upstream nodes (keyed by node type)- source_nodes: List of source node info dicts with id, type, label-- Returns:- Execution result dict with logged data and passthrough output- """- from services.status_broadcaster import get_status_broadcaster- start_time = time.time()-- try:- label = parameters.get('label', '')- log_mode = parameters.get('logMode', 'all')- format_type = parameters.get('format', 'json')- field_path = parameters.get('fieldPath', '')- expression = parameters.get('expression', '')-- # Get input data from connected outputs (passed from _get_connected_outputs_with_info)- connected_outputs = connected_outputs or {}- source_nodes = source_nodes or []-- logger.debug(f"[Console] connected_outputs keys: {list(connected_outputs.keys())}, count: {len(connected_outputs)}")-- # Merge all connected outputs into a single dict- input_data = {}- for node_type, output in connected_outputs.items():- logger.debug(f"[Console] Processing output from {node_type}: type={type(output).__name__}")- if isinstance(output, dict):- input_data.update(output)- else:- input_data['value'] = output-- logger.debug(f"[Console] input_data keys: {list(input_data.keys()) if input_data else 'empty'}")-- # Get first source node info for display- source_info = source_nodes[0] if source_nodes else None-- # Determine what to log based on mode- logger.debug(f"[Console] log_mode={log_mode}, field_path={field_path[:50] if field_path else 'none'}...")- log_value = None- match log_mode:- case 'all':- log_value = input_data- case 'field':- if field_path:- # Check if fieldPath was a template that got resolved (no longer contains {{}})- # If it was resolved, use the resolved value directly- if '{{' not in field_path and field_path not in input_data:- # fieldPath was likely a template like {{aiagent.response}} that got resolved- # Use the resolved value directly instead of navigating- log_value = field_path- logger.debug("[Console] Using resolved fieldPath value directly")- else:- # fieldPath is a literal path like "response" or "data.items[0]"- log_value = _navigate_field_path(input_data, field_path)- else:- log_value = input_data- case 'expression':- # Expression is already resolved by parameter resolver- log_value = expression if expression else input_data- case _:- log_value = input_data-- # Format the output- formatted_output = _format_console_output(log_value, format_type)-- # Get workflow_id for scoped broadcasting- workflow_id = context.get('workflow_id')-- # Broadcast console log to frontend- broadcaster = get_status_broadcaster()- await broadcaster.broadcast_console_log({- "node_id": node_id,- "label": label or f"Console ({node_id[:8]})",- "timestamp": datetime.now().isoformat(),- "data": log_value,- "formatted": formatted_output,- "format": format_type,- "workflow_id": workflow_id,- "source_node_id": source_info.get('id') if source_info else None,- "source_node_type": source_info.get('type') if source_info else None,- "source_node_label": source_info.get('label') if source_info else None- })-- logger.info("[Console] Logged",- node_id=node_id,- label=label,- format=format_type,- data_type=type(log_value).__name__)-- # Return success with the logged data AND pass input through as output- return {- "success": True,- "node_id": node_id,- "node_type": "console",- "result": {- "label": label or f"Console ({node_id[:8]})",- "logged_at": datetime.now().isoformat(),- "format": format_type,- "data": log_value,- "formatted": formatted_output,- # Pass through original input for downstream nodes- **input_data- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error("[Console] Failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "console",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }---def _navigate_field_path(data: Any, path: str) -> Any:- """Navigate through nested dict/list using dot notation path.-- Supports:- - Dict keys: 'field' -> data['field']- - Array indexing: 'items[0]' -> data['items'][0]- - Nested paths: 'data.items[0].name' -> data['data']['items'][0]['name']- """- import re-- if not path:- return data-- current = data- parts = path.split('.')-- for part in parts:- if current is None:- return None-- # Check for array index notation: field[index]- bracket_match = re.match(r'^(\w+)\[(\d+)\]$', part)- if bracket_match:- field_name = bracket_match.group(1)- index = int(bracket_match.group(2))-- # Navigate to the field first- if isinstance(current, dict) and field_name in current:- current = current[field_name]- else:- return None-- # Then access the array index- if isinstance(current, list) and 0 <= index < len(current):- current = current[index]- else:- return None- else:- # Standard dict key navigation- if isinstance(current, dict) and part in current:- current = current[part]- else:- return None-- return current---def _format_console_output(data: Any, format_type: str) -> str:- """Format data for console display based on format type."""- match format_type:- case 'json':- try:- return json.dumps(data, indent=2, default=str, ensure_ascii=False)- except Exception:- return str(data)- case 'json_compact':- try:- return json.dumps(data, default=str, ensure_ascii=False)- except Exception:- return str(data)- case 'text':- return str(data)- case 'table':- # Format as table if data is list of dicts- if isinstance(data, list) and data and isinstance(data[0], dict):- headers = list(data[0].keys())- rows = [[str(row.get(h, '')) for h in headers] for row in data]-- # Calculate column widths- widths = [max(len(h), max((len(r[i]) for r in rows), default=0))- for i, h in enumerate(headers)]-- # Build table string- header_line = ' | '.join(h.ljust(widths[i]) for i, h in enumerate(headers))- separator = '-+-'.join('-' * w for w in widths)- data_lines = [' | '.join(r[i].ljust(widths[i]) for i in range(len(headers)))- for r in rows]-- return '\n'.join([header_line, separator] + data_lines)- else:- # Fall back to JSON for non-tabular data- return json.dumps(data, indent=2, default=str, ensure_ascii=False)- case _:- return str(data)---# =============================================================================-# TEAM MONITOR HANDLER-# =============================================================================--async def handle_team_monitor(- node_id: str,- node_type: str,- parameters: Dict[str, Any],- context: Dict[str, Any]-) -> Dict[str, Any]:- """Handle team monitor node - returns team status snapshot.-- Args:- node_id: The node ID- node_type: The node type (teamMonitor)- parameters: Resolved parameters- context: Execution context with team_id from connected team node-- Returns:- Execution result dict with team status- """- from services.agent_team import get_agent_team_service- start_time = time.time()-- try:- # Get team_id from context (set by connected team lead node)- team_id = context.get('team_id')-- # Try to get from connected node outputs- if not team_id:- outputs = context.get('outputs', {})- for output in outputs.values():- if isinstance(output, dict) and output.get('team_id'):- team_id = output.get('team_id')- break-- if not team_id:- return {- "success": True,- "node_id": node_id,- "node_type": "teamMonitor",- "result": {- "message": "No team connected",- "team_id": None,- "members": [],- "tasks": {"total": 0, "completed": 0, "active": 0, "pending": 0, "failed": 0},- "active_tasks": [],- "recent_events": []- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- team_service = get_agent_team_service()- status = await team_service.get_team_status(team_id)-- max_history = parameters.get('maxHistoryItems', 50)-- return {- "success": True,- "node_id": node_id,- "node_type": "teamMonitor",- "result": {- "team_id": team_id,- "members": status.get('members', []),- "tasks": {- "total": status.get('task_count', 0),- "completed": status.get('completed_count', 0),- "active": status.get('active_count', 0),- "pending": status.get('pending_count', 0),- "failed": status.get('failed_count', 0)- },- "active_tasks": status.get('active_tasks', []),- "recent_events": status.get('recent_events', [])[-max_history:]- },- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- logger.error("[TeamMonitor] Failed", node_id=node_id, error=str(e))- return {- "success": False,- "node_id": node_id,- "node_type": "teamMonitor",- "error": str(e),- "execution_time": time.time() - start_time,- "timestamp": datetime.now().isoformat()- }