Skip to content

Self-improving AI Employees for everyone

refactor(plugin): Wave 11.D.0 — extract edge_walker to services/plugin/

trohitg1b81215a130a
diff --git a/server/services/handlers/ai.py b/server/services/handlers/ai.py
index 3982e980..06e87493 100644
--- a/server/services/handlers/ai.py
+++ b/server/services/handlers/ai.py
@@ -1,8 +1,20 @@
-"""AI node handlers - AI Agent, Zeenie, AI Chat Model, Simple Memory."""
+"""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
@@ -18,379 +30,28 @@ async def _collect_agent_connections(
node_id: str,
context: Dict[str, Any],
database: "Database",
- log_prefix: str = "[Agent]"
+ 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]]]:
- """Shared logic for collecting memory, skill, tool, input, and task data from connected nodes.
-
- Scans edges targeting the given node and collects:
- - Memory data from input-memory handle (simpleMemory nodes)
- - Skill data from input-skill handle (skill nodes)
- - Tool data from input-tools handle (tool nodes, including androidTool Sub-Node pattern)
- - Input data from input-main or input-chat handle (for auto-prompting fallback)
- - Task data from input-task handle (taskTrigger nodes for delegated task results)
-
- Args:
- node_id: The agent node ID to collect connections for
- context: Execution context with nodes, edges, outputs
- database: The database instance for fetching node parameters
- log_prefix: Prefix for log messages (e.g., "[AI Agent]" or "[Chat Agent]")
-
- Returns:
- Tuple of (memory_data, skill_data, tool_data, input_data, task_data)
- """
- nodes = context.get('nodes')
- edges = context.get('edges')
- workflow_id = context.get('workflow_id')
-
- memory_data: Optional[Dict[str, Any]] = None
- skill_data: List[Dict[str, Any]] = []
- tool_data: List[Dict[str, Any]] = []
- input_data: Optional[Dict[str, Any]] = None
- task_data: Optional[Dict[str, Any]] = None
-
- logger.info(f"{log_prefix} Processing node {node_id}, edges={len(edges) if edges else 0}, nodes={len(nodes) if nodes else 0}, workflow_id={workflow_id}")
-
- if not edges or not nodes:
- return memory_data, skill_data, tool_data, input_data, task_data
-
- # Log incoming edges for debugging
- incoming_edges = [e for e in edges if e.get('target') == node_id]
- logger.info(f"{log_prefix} Incoming edges to {node_id}: {len(incoming_edges)}")
- if not incoming_edges:
- # Debug: show all edge targets to diagnose missing connections
- edge_targets = set(e.get('target') for e in edges)
- logger.debug(f"{log_prefix} All edge targets in graph: {edge_targets}")
- for e in incoming_edges:
- logger.debug(f"{log_prefix} Edge: source={e.get('source')}, targetHandle={e.get('targetHandle')}")
-
- # Check for tool edges specifically
- tool_incoming = [e for e in incoming_edges if e.get('targetHandle') == 'input-tools']
- logger.info(f"{log_prefix} Tool edges (input-tools handle): {len(tool_incoming)}")
-
- for edge in edges:
- if edge.get('target') != node_id:
- continue
-
- target_handle = edge.get('targetHandle')
- source_node_id = edge.get('source')
- source_node = next((n for n in nodes if n.get('id') == source_node_id), None)
-
- if not source_node:
- continue
-
- # Memory detection - load markdown content for editing
- if target_handle == 'input-memory':
- if source_node.get('type') == 'simpleMemory':
- memory_params = await database.get_node_parameters(source_node_id) or {}
- # Auto-derive session from connected AI Agent's node_id
- # Memory node's sessionId is used only if explicitly set (not empty or 'default')
- configured_session = memory_params.get('sessionId', '')
- if configured_session and configured_session != 'default':
- memory_session_id = configured_session # Explicit override
- else:
- memory_session_id = node_id # Auto: use AI Agent's node_id
- window_size = int(memory_params.get('windowSize', 10))
- memory_content = memory_params.get('memoryContent', '# Conversation History\n\n*No messages yet.*\n')
- long_term_enabled = memory_params.get('longTermEnabled', False)
- retrieval_count = int(memory_params.get('retrievalCount', 3))
-
- memory_data = {
- 'node_id': source_node_id,
- 'session_id': memory_session_id,
- 'window_size': window_size,
- 'memory_content': memory_content,
- 'long_term_enabled': long_term_enabled,
- 'retrieval_count': retrieval_count
- }
- logger.debug(f"{log_prefix} Connected memory node: session={memory_session_id} (auto={not configured_session or configured_session == 'default'}), content_length={len(memory_content)}")
-
- # Skill detection - nodes connected to input-skill handle
- elif target_handle == 'input-skill':
- skill_type = source_node.get('type')
- skill_params = await database.get_node_parameters(source_node_id) or {}
-
- # Special handling for masterSkill - expand skillsConfig into individual skills
- if skill_type == 'masterSkill':
- from services.skill_loader import get_skill_loader
-
- skills_config = skill_params.get('skillsConfig', {})
- logger.debug(f"{log_prefix} Master Skill found with {len(skills_config)} configured skills")
-
- # Get skill loader to load instructions from SKILL.md files
- skill_loader = get_skill_loader()
-
- for skill_key, skill_cfg in skills_config.items():
- # Only include enabled skills
- if not skill_cfg.get('enabled', False):
- continue
-
- # DB is source of truth - use instructions from skillsConfig
- instructions = skill_cfg.get('instructions', '')
- if instructions:
- logger.debug(f"{log_prefix} Using DB instructions for {skill_key}")
- else:
- # Fallback: load from skill folder for legacy data missing instructions
- try:
- skill = skill_loader.load_skill(skill_key)
- if skill:
- instructions = skill.instructions
- logger.debug(f"{log_prefix} Fallback: loaded instructions from skill folder for {skill_key}")
- except Exception as e:
- logger.warning(f"{log_prefix} Failed to load skill {skill_key}: {e}")
-
- # Create a skill entry for each enabled skill in the config
- skill_entry = {
- 'node_id': f"{source_node_id}_{skill_key}",
- 'node_type': 'masterSkill',
- 'skill_name': skill_key,
- 'parameters': {
- 'instructions': instructions,
- 'skillName': skill_key
- },
- 'label': skill_key
- }
- skill_data.append(skill_entry)
- logger.debug(f"{log_prefix} Master Skill enabled: {skill_key}")
- else:
- # Regular skill node
- skill_entry = {
- 'node_id': source_node_id,
- 'node_type': skill_type,
- 'skill_name': skill_params.get('skillName', skill_type),
- 'parameters': skill_params,
- 'label': source_node.get('data', {}).get('label', skill_type)
- }
- skill_data.append(skill_entry)
- logger.debug(f"{log_prefix} Connected skill: {skill_type}")
-
- # Tool detection - any node connected to input-tools becomes a tool
- elif target_handle == 'input-tools':
- tool_type = source_node.get('type')
- logger.info(f"{log_prefix} Found tool connected via input-tools: type={tool_type}, node_id={source_node_id}")
- tool_params = await database.get_node_parameters(source_node_id) or {}
-
- # Build base tool entry
- tool_entry = {
- 'node_id': source_node_id,
- 'node_type': tool_type,
- 'parameters': tool_params,
- 'label': source_node.get('data', {}).get('label', tool_type)
- }
-
- # Special handling for androidTool - discover connected Android services
- # Follows n8n Sub-Node pattern
- if tool_type == 'androidTool':
- connected_services = []
-
- # Scan edges for Android nodes connected to this toolkit
- for service_edge in edges:
- # Skip if not targeting this androidTool node
- if service_edge.get('target') != source_node_id:
- continue
-
- service_target_handle = service_edge.get('targetHandle')
- # Accept input-main or no handle (ReactFlow may omit handle for single-input nodes)
- if service_target_handle is not None and service_target_handle != 'input-main':
- logger.debug(f"{log_prefix} Android Toolkit: Skipping edge with targetHandle: {service_target_handle}")
- continue
-
- android_node_id = service_edge.get('source')
- android_node = next((n for n in nodes if n.get('id') == android_node_id), None)
-
- if android_node and android_node.get('type') in ANDROID_SERVICE_NODE_TYPES:
- android_params = await database.get_node_parameters(android_node_id) or {}
- connected_services.append({
- 'node_id': android_node_id,
- 'node_type': android_node.get('type'),
- 'service_id': android_params.get('service_id'),
- 'action': android_params.get('action'),
- 'parameters': android_params,
- 'label': android_node.get('data', {}).get('label', android_node.get('type'))
- })
- logger.debug(f"{log_prefix} Android toolkit connected service: {android_params.get('service_id')}")
-
- tool_entry['connected_services'] = connected_services
- logger.debug(f"{log_prefix} Android toolkit has {len(connected_services)} connected services")
-
- # Special handling for AI Agent nodes - discover their connected tools
- # This allows parent agent to know child agent's capabilities
- if tool_type in AI_AGENT_TYPES:
- child_tools = []
-
- # Count edges targeting this child agent
- child_incoming_edges = [e for e in edges if e.get('target') == source_node_id]
- child_tool_edges = [e for e in child_incoming_edges if e.get('targetHandle') == 'input-tools']
- logger.debug(f"{log_prefix} Child agent {source_node_id}: {len(child_incoming_edges)} incoming edges, {len(child_tool_edges)} input-tools edges")
-
- # Log all incoming edge handles for debugging
- if child_incoming_edges:
- handles = [e.get('targetHandle', 'None') for e in child_incoming_edges]
- logger.debug(f"{log_prefix} Child agent {source_node_id} incoming handles: {handles}")
-
- # Scan edges for tools connected to this child agent's input-tools handle
- for child_edge in edges:
- if child_edge.get('target') != source_node_id:
- continue
- if child_edge.get('targetHandle') != 'input-tools':
- continue
-
- child_tool_id = child_edge.get('source')
- child_tool_node = next((n for n in nodes if n.get('id') == child_tool_id), None)
-
- logger.debug(f"{log_prefix} Child agent {source_node_id}: tool edge from {child_tool_id}, node found: {child_tool_node is not None}")
-
- if child_tool_node:
- child_tool_type = child_tool_node.get('type', '')
- child_tool_label = child_tool_node.get('data', {}).get('label', child_tool_type)
- child_tools.append({
- 'node_type': child_tool_type,
- 'label': child_tool_label
- })
-
- if child_tools:
- tool_entry['child_tools'] = child_tools
- logger.debug(f"{log_prefix} Child agent {source_node_id} has tools: {[t['label'] for t in child_tools]}")
-
- tool_data.append(tool_entry)
- logger.debug(f"{log_prefix} Connected tool: {tool_type}")
-
- # Input data detection - nodes connected to input-main or input-chat handle
- # Used for auto-prompting when prompt parameter is empty
- elif target_handle == 'input-main' or target_handle == 'input-chat' or target_handle is None:
- source_output = context.get('outputs', {}).get(source_node_id)
- if source_output:
- input_data = source_output
- logger.debug(f"{log_prefix} Input from {source_node.get('type')}: {list(source_output.keys()) if isinstance(source_output, dict) else type(source_output)}")
-
- # Task data detection - taskTrigger nodes connected to input-task handle
- # Used to receive results from delegated child agents
- elif target_handle == 'input-task':
- logger.info(f"{log_prefix} Found input-task edge from {source_node_id} (type={source_node.get('type')})")
-
- # Try context.outputs first (parallel executor), then database via get_output_fn
- source_output = context.get('outputs', {}).get(source_node_id)
- logger.info(f"{log_prefix} Context outputs check for {source_node_id}: {source_output is not None}")
-
- if not source_output:
- # Database is source of truth - use get_output_fn to retrieve stored output
- get_output_fn = context.get('get_output_fn')
- session_id = context.get('session_id', 'default')
- if get_output_fn:
- try:
- source_output = await get_output_fn(session_id, source_node_id, 'output_0')
- logger.info(f"{log_prefix} DB lookup for {source_node_id}: {source_output is not None}")
- except Exception as e:
- logger.warning(f"{log_prefix} Failed to get output from DB: {e}")
- else:
- logger.warning(f"{log_prefix} No get_output_fn in context, cannot retrieve task output")
-
- logger.info(f"{log_prefix} Source output for {source_node_id}: {source_output is not None}, type={type(source_output).__name__ if source_output else 'None'}")
- if source_output:
- # Handle nested result structure - taskTrigger may return {"result": {...}} or flat dict
- if isinstance(source_output, dict) and 'result' in source_output and isinstance(source_output.get('result'), dict):
- # Nested structure - extract inner result
- task_data = source_output.get('result')
- logger.info(f"{log_prefix} Extracted nested task_data from result key")
- else:
- task_data = source_output
- logger.info(f"{log_prefix} Task completion data: task_id={task_data.get('task_id')}, status={task_data.get('status')}, agent_name={task_data.get('agent_name')}")
-
- # Log collection results
- logger.info(f"{log_prefix} Collected: {len(skill_data)} skills, {len(tool_data)} tools, memory={'yes' if memory_data else 'no'}, input={'yes' if input_data else 'no'}, task={'yes' if task_data else 'no'}")
- for sd in skill_data:
- logger.debug(f"{log_prefix} Skill: type={sd.get('node_type')}, label={sd.get('label')}")
- for td in tool_data:
- logger.info(f"{log_prefix} Tool: type={td.get('node_type')}, node_id={td.get('node_id')}")
-
- return memory_data, skill_data, tool_data, input_data, task_data
+ """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"
+ database: "Database",
) -> List[Dict[str, Any]]:
- """Collect agents connected via input-teammates handle for team mode.
-
- Args:
- node_id: The team lead node ID
- context: Execution context with nodes, edges
- database: Database instance
-
- Returns:
- List of teammate node info dicts
- """
- nodes = context.get('nodes', [])
- edges = context.get('edges', [])
- teammates = []
-
- for edge in edges:
- if edge.get('target') != node_id or edge.get('targetHandle') != 'input-teammates':
- continue
-
- source_id = edge.get('source')
- source_node = next((n for n in nodes if n.get('id') == source_id), None)
- if not source_node:
- continue
-
- node_type = source_node.get('type', '')
- if node_type not in AI_AGENT_TYPES:
- continue
-
- params = await database.get_node_parameters(source_id) or {}
- teammates.append({
- 'node_id': source_id,
- 'node_type': node_type,
- 'label': source_node.get('data', {}).get('label', node_type),
- 'parameters': params
- })
- logger.debug(f"[Teams] Found teammate: {node_type} ({source_id})")
-
- return teammates
+ """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:
- """Format task completion data as context for the agent.
-
- Args:
- task_data: Task completion data from taskTrigger node
+ """Back-compat shim — body moved to ``services/plugin/edge_walker.py``."""
+ return _ew_format_task_context(task_data)
- Returns:
- Formatted string to prepend to agent prompt
- """
- status = task_data.get('status', 'unknown')
- agent_name = task_data.get('agent_name', 'Unknown Agent')
- task_id = task_data.get('task_id', '')
-
- if status == 'completed':
- result = task_data.get('result', 'No result provided')
- return f"""A delegated task has completed:
-- Agent: {agent_name}
-- Task ID: {task_id}
-- Status: Completed Successfully
-- Result: {result}
-
-IMPORTANT: This task is COMPLETE. Do NOT delegate or call any agent tools.
-Simply report this result to the user in a natural, conversational way."""
-
- elif status == 'error':
- error = task_data.get('error', 'Unknown error')
- return f"""A delegated task has failed:
-- Agent: {agent_name}
-- Task ID: {task_id}
-- Status: Error
-- Error: {error}
-
-IMPORTANT: This task has FAILED. Do NOT retry or delegate again.
-Report this error to the user and suggest next steps if appropriate."""
-
- else:
- return f"""Task update received:
-- Agent: {agent_name}
-- Task ID: {task_id}
-- Status: {status}
-- Data: {task_data}"""
+# DELETED (Wave 11.D.0): the original inline bodies of
+# _collect_agent_connections / _collect_teammate_connections /
async def handle_ai_agent(
node_id: str,
diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.py
new file mode 100644
index 00000000..e5ce5229
--- /dev/null
+++ b/server/services/plugin/edge_walker.py
@@ -0,0 +1,444 @@
+"""Edge-walking utilities for agent plugins.
+
+Pure functions extracted from ``services/handlers/ai.py`` so every
+agent plugin can call them without depending on the legacy handler
+module. Used by :class:`AIAgentNode`, :class:`ChatAgentNode`,
+:class:`SpecializedAgentBase`, :class:`DeepAgentNode`,
+:class:`RLMAgentNode`, :class:`ClaudeCodeAgentNode`.
+
+Three helpers:
+
+- :func:`collect_agent_connections` — walks ``input-memory``,
+ ``input-skill``, ``input-tools``, ``input-main`` / ``input-chat``,
+ ``input-task`` edges into a single tuple. Knows about the
+ ``masterSkill`` expansion + the ``androidTool`` Sub-Node pattern +
+ child-agent tool discovery.
+- :func:`collect_teammate_connections` — walks ``input-teammates``
+ edges (orchestrator / ai_employee / deep_agent team-lead pattern).
+- :func:`format_task_context` — renders ``taskTrigger`` payload as a
+ prompt prepend block.
+
+These functions have **no service dependencies** beyond the
+``Database`` instance. They mutate nothing. Wave 11.D.6 inlines the
+old ``handlers/ai.py:_collect_*`` shims to call here directly.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+
+from constants import AI_AGENT_TYPES, ANDROID_SERVICE_NODE_TYPES
+from core.logging import get_logger
+
+if TYPE_CHECKING:
+ from core.database import Database
+
+logger = get_logger(__name__)
+
+
+async def collect_agent_connections(
+ node_id: str,
+ context: Dict[str, Any],
+ database: "Database",
+ log_prefix: str = "[Agent]",
+) -> Tuple[
+ Optional[Dict[str, Any]], # memory_data
+ List[Dict[str, Any]], # skill_data
+ List[Dict[str, Any]], # tool_data
+ Optional[Dict[str, Any]], # input_data
+ Optional[Dict[str, Any]], # task_data
+]:
+ """Walk edges targeting ``node_id`` and collect everything an agent
+ needs from its connected nodes.
+
+ Returns ``(memory, skills, tools, input, task)``. See module
+ docstring for behaviour notes.
+ """
+ nodes = context.get("nodes")
+ edges = context.get("edges")
+ workflow_id = context.get("workflow_id")
+
+ memory_data: Optional[Dict[str, Any]] = None
+ skill_data: List[Dict[str, Any]] = []
+ tool_data: List[Dict[str, Any]] = []
+ input_data: Optional[Dict[str, Any]] = None
+ task_data: Optional[Dict[str, Any]] = None
+
+ logger.info(
+ f"{log_prefix} Processing node {node_id}, "
+ f"edges={len(edges) if edges else 0}, "
+ f"nodes={len(nodes) if nodes else 0}, "
+ f"workflow_id={workflow_id}"
+ )
+
+ if not edges or not nodes:
+ return memory_data, skill_data, tool_data, input_data, task_data
+
+ incoming_edges = [e for e in edges if e.get("target") == node_id]
+ logger.info(f"{log_prefix} Incoming edges to {node_id}: {len(incoming_edges)}")
+ if not incoming_edges:
+ edge_targets = set(e.get("target") for e in edges)
+ logger.debug(f"{log_prefix} All edge targets in graph: {edge_targets}")
+ for e in incoming_edges:
+ logger.debug(
+ f"{log_prefix} Edge: source={e.get('source')}, "
+ f"targetHandle={e.get('targetHandle')}"
+ )
+
+ tool_incoming = [e for e in incoming_edges if e.get("targetHandle") == "input-tools"]
+ logger.info(f"{log_prefix} Tool edges (input-tools handle): {len(tool_incoming)}")
+
+ for edge in edges:
+ if edge.get("target") != node_id:
+ continue
+
+ target_handle = edge.get("targetHandle")
+ source_node_id = edge.get("source")
+ source_node = next((n for n in nodes if n.get("id") == source_node_id), None)
+ if not source_node:
+ continue
+
+ if target_handle == "input-memory":
+ if source_node.get("type") == "simpleMemory":
+ memory_data = await _build_memory_entry(
+ node_id, source_node_id, database, log_prefix,
+ )
+
+ elif target_handle == "input-skill":
+ await _append_skill_entries(
+ source_node, source_node_id, database, skill_data, log_prefix,
+ )
+
+ elif target_handle == "input-tools":
+ await _append_tool_entry(
+ source_node, source_node_id, edges, nodes, database,
+ tool_data, log_prefix,
+ )
+
+ elif target_handle in ("input-main", "input-chat") or target_handle is None:
+ source_output = context.get("outputs", {}).get(source_node_id)
+ if source_output:
+ input_data = source_output
+ logger.debug(
+ f"{log_prefix} Input from {source_node.get('type')}: "
+ f"{list(source_output.keys()) if isinstance(source_output, dict) else type(source_output)}"
+ )
+
+ elif target_handle == "input-task":
+ task_data = await _resolve_task_payload(
+ source_node_id, source_node, context, log_prefix,
+ )
+
+ logger.info(
+ f"{log_prefix} Collected: {len(skill_data)} skills, {len(tool_data)} tools, "
+ f"memory={'yes' if memory_data else 'no'}, "
+ f"input={'yes' if input_data else 'no'}, "
+ f"task={'yes' if task_data else 'no'}"
+ )
+ for sd in skill_data:
+ logger.debug(f"{log_prefix} Skill: type={sd.get('node_type')}, label={sd.get('label')}")
+ for td in tool_data:
+ logger.info(f"{log_prefix} Tool: type={td.get('node_type')}, node_id={td.get('node_id')}")
+
+ return memory_data, skill_data, tool_data, input_data, task_data
+
+
+async def _build_memory_entry(
+ agent_node_id: str,
+ memory_node_id: str,
+ database: "Database",
+ log_prefix: str,
+) -> Dict[str, Any]:
+ memory_params = await database.get_node_parameters(memory_node_id) or {}
+ configured_session = memory_params.get("sessionId", "")
+ if configured_session and configured_session != "default":
+ session_id = configured_session
+ else:
+ session_id = agent_node_id
+ entry = {
+ "node_id": memory_node_id,
+ "session_id": session_id,
+ "window_size": int(memory_params.get("windowSize", 10)),
+ "memory_content": memory_params.get(
+ "memoryContent", "# Conversation History\n\n*No messages yet.*\n",
+ ),
+ "long_term_enabled": memory_params.get("longTermEnabled", False),
+ "retrieval_count": int(memory_params.get("retrievalCount", 3)),
+ }
+ logger.debug(
+ f"{log_prefix} Connected memory node: session={session_id} "
+ f"(auto={not configured_session or configured_session == 'default'}), "
+ f"content_length={len(entry['memory_content'])}"
+ )
+ return entry
+
+
+async def _append_skill_entries(
+ source_node: Dict[str, Any],
+ source_node_id: str,
+ database: "Database",
+ skill_data: List[Dict[str, Any]],
+ log_prefix: str,
+) -> None:
+ skill_type = source_node.get("type")
+ skill_params = await database.get_node_parameters(source_node_id) or {}
+
+ if skill_type == "masterSkill":
+ from services.skill_loader import get_skill_loader
+
+ skills_config = skill_params.get("skillsConfig", {})
+ logger.debug(f"{log_prefix} Master Skill found with {len(skills_config)} configured skills")
+ skill_loader = get_skill_loader()
+
+ for skill_key, skill_cfg in skills_config.items():
+ if not skill_cfg.get("enabled", False):
+ continue
+ instructions = skill_cfg.get("instructions", "")
+ if instructions:
+ logger.debug(f"{log_prefix} Using DB instructions for {skill_key}")
+ else:
+ try:
+ skill = skill_loader.load_skill(skill_key)
+ if skill:
+ instructions = skill.instructions
+ logger.debug(
+ f"{log_prefix} Fallback: loaded instructions from skill folder for {skill_key}"
+ )
+ except Exception as e:
+ logger.warning(f"{log_prefix} Failed to load skill {skill_key}: {e}")
+
+ skill_data.append({
+ "node_id": f"{source_node_id}_{skill_key}",
+ "node_type": "masterSkill",
+ "skill_name": skill_key,
+ "parameters": {"instructions": instructions, "skillName": skill_key},
+ "label": skill_key,
+ })
+ logger.debug(f"{log_prefix} Master Skill enabled: {skill_key}")
+ else:
+ skill_data.append({
+ "node_id": source_node_id,
+ "node_type": skill_type,
+ "skill_name": skill_params.get("skillName", skill_type),
+ "parameters": skill_params,
+ "label": source_node.get("data", {}).get("label", skill_type),
+ })
+ logger.debug(f"{log_prefix} Connected skill: {skill_type}")
+
+
+async def _append_tool_entry(
+ source_node: Dict[str, Any],
+ source_node_id: str,
+ edges: List[Dict[str, Any]],
+ nodes: List[Dict[str, Any]],
+ database: "Database",
+ tool_data: List[Dict[str, Any]],
+ log_prefix: str,
+) -> None:
+ tool_type = source_node.get("type")
+ logger.info(f"{log_prefix} Found tool connected via input-tools: type={tool_type}, node_id={source_node_id}")
+ tool_params = await database.get_node_parameters(source_node_id) or {}
+
+ tool_entry: Dict[str, Any] = {
+ "node_id": source_node_id,
+ "node_type": tool_type,
+ "parameters": tool_params,
+ "label": source_node.get("data", {}).get("label", tool_type),
+ }
+
+ if tool_type == "androidTool":
+ connected_services: List[Dict[str, Any]] = []
+ for service_edge in edges:
+ if service_edge.get("target") != source_node_id:
+ continue
+ service_target_handle = service_edge.get("targetHandle")
+ if service_target_handle is not None and service_target_handle != "input-main":
+ logger.debug(
+ f"{log_prefix} Android Toolkit: Skipping edge with "
+ f"targetHandle: {service_target_handle}"
+ )
+ continue
+ android_node_id = service_edge.get("source")
+ android_node = next((n for n in nodes if n.get("id") == android_node_id), None)
+ if android_node and android_node.get("type") in ANDROID_SERVICE_NODE_TYPES:
+ android_params = await database.get_node_parameters(android_node_id) or {}
+ connected_services.append({
+ "node_id": android_node_id,
+ "node_type": android_node.get("type"),
+ "service_id": android_params.get("service_id"),
+ "action": android_params.get("action"),
+ "parameters": android_params,
+ "label": android_node.get("data", {}).get("label", android_node.get("type")),
+ })
+ logger.debug(
+ f"{log_prefix} Android toolkit connected service: "
+ f"{android_params.get('service_id')}"
+ )
+ tool_entry["connected_services"] = connected_services
+ logger.debug(f"{log_prefix} Android toolkit has {len(connected_services)} connected services")
+
+ if tool_type in AI_AGENT_TYPES:
+ child_tools: List[Dict[str, Any]] = []
+ child_incoming_edges = [e for e in edges if e.get("target") == source_node_id]
+ child_tool_edges = [e for e in child_incoming_edges if e.get("targetHandle") == "input-tools"]
+ logger.debug(
+ f"{log_prefix} Child agent {source_node_id}: "
+ f"{len(child_incoming_edges)} incoming edges, "
+ f"{len(child_tool_edges)} input-tools edges"
+ )
+ if child_incoming_edges:
+ handles = [e.get("targetHandle", "None") for e in child_incoming_edges]
+ logger.debug(f"{log_prefix} Child agent {source_node_id} incoming handles: {handles}")
+ for child_edge in edges:
+ if child_edge.get("target") != source_node_id:
+ continue
+ if child_edge.get("targetHandle") != "input-tools":
+ continue
+ child_tool_id = child_edge.get("source")
+ child_tool_node = next((n for n in nodes if n.get("id") == child_tool_id), None)
+ logger.debug(
+ f"{log_prefix} Child agent {source_node_id}: "
+ f"tool edge from {child_tool_id}, node found: {child_tool_node is not None}"
+ )
+ if child_tool_node:
+ child_tool_type = child_tool_node.get("type", "")
+ child_tool_label = child_tool_node.get("data", {}).get("label", child_tool_type)
+ child_tools.append({"node_type": child_tool_type, "label": child_tool_label})
+ if child_tools:
+ tool_entry["child_tools"] = child_tools
+ logger.debug(
+ f"{log_prefix} Child agent {source_node_id} has tools: "
+ f"{[t['label'] for t in child_tools]}"
+ )
+
+ tool_data.append(tool_entry)
+ logger.debug(f"{log_prefix} Connected tool: {tool_type}")
+
+
+async def _resolve_task_payload(
+ source_node_id: str,
+ source_node: Dict[str, Any],
+ context: Dict[str, Any],
+ log_prefix: str,
+) -> Optional[Dict[str, Any]]:
+ logger.info(f"{log_prefix} Found input-task edge from {source_node_id} (type={source_node.get('type')})")
+
+ source_output = context.get("outputs", {}).get(source_node_id)
+ logger.info(
+ f"{log_prefix} Context outputs check for {source_node_id}: {source_output is not None}"
+ )
+
+ if not source_output:
+ get_output_fn = context.get("get_output_fn")
+ session_id = context.get("session_id", "default")
+ if get_output_fn:
+ try:
+ source_output = await get_output_fn(session_id, source_node_id, "output_0")
+ logger.info(f"{log_prefix} DB lookup for {source_node_id}: {source_output is not None}")
+ except Exception as e:
+ logger.warning(f"{log_prefix} Failed to get output from DB: {e}")
+ else:
+ logger.warning(
+ f"{log_prefix} No get_output_fn in context, cannot retrieve task output"
+ )
+
+ logger.info(
+ f"{log_prefix} Source output for {source_node_id}: {source_output is not None}, "
+ f"type={type(source_output).__name__ if source_output else 'None'}"
+ )
+ if not source_output:
+ return None
+
+ if (
+ isinstance(source_output, dict)
+ and "result" in source_output
+ and isinstance(source_output.get("result"), dict)
+ ):
+ task_data = source_output.get("result")
+ logger.info(f"{log_prefix} Extracted nested task_data from result key")
+ else:
+ task_data = source_output
+ if isinstance(task_data, dict):
+ logger.info(
+ f"{log_prefix} Task completion data: task_id={task_data.get('task_id')}, "
+ f"status={task_data.get('status')}, agent_name={task_data.get('agent_name')}"
+ )
+ return task_data
+
+
+async def collect_teammate_connections(
+ node_id: str,
+ context: Dict[str, Any],
+ database: "Database",
+) -> List[Dict[str, Any]]:
+ """Walk ``input-teammates`` edges and return connected agents.
+
+ Used by ``orchestrator_agent`` / ``ai_employee`` / ``deep_agent``.
+ """
+ nodes = context.get("nodes", [])
+ edges = context.get("edges", [])
+ teammates: List[Dict[str, Any]] = []
+
+ for edge in edges:
+ if edge.get("target") != node_id or edge.get("targetHandle") != "input-teammates":
+ continue
+ source_id = edge.get("source")
+ source_node = next((n for n in nodes if n.get("id") == source_id), None)
+ if not source_node:
+ continue
+ node_type = source_node.get("type", "")
+ if node_type not in AI_AGENT_TYPES:
+ continue
+ params = await database.get_node_parameters(source_id) or {}
+ teammates.append({
+ "node_id": source_id,
+ "node_type": node_type,
+ "label": source_node.get("data", {}).get("label", node_type),
+ "parameters": params,
+ })
+ logger.debug(f"[Teams] Found teammate: {node_type} ({source_id})")
+
+ return teammates
+
+
+def format_task_context(task_data: Dict[str, Any]) -> str:
+ """Render a ``taskTrigger`` payload as a prompt-prepend block.
+
+ Tells the agent the delegated task is already done so it doesn't
+ re-delegate. Three branches: completed / error / other.
+ """
+ status = task_data.get("status", "unknown")
+ agent_name = task_data.get("agent_name", "Unknown Agent")
+ task_id = task_data.get("task_id", "")
+
+ if status == "completed":
+ result = task_data.get("result", "No result provided")
+ return (
+ "A delegated task has completed:\n"
+ f"- Agent: {agent_name}\n"
+ f"- Task ID: {task_id}\n"
+ "- Status: Completed Successfully\n"
+ f"- Result: {result}\n\n"
+ "IMPORTANT: This task is COMPLETE. Do NOT delegate or call any agent tools.\n"
+ "Simply report this result to the user in a natural, conversational way."
+ )
+
+ if status == "error":
+ error = task_data.get("error", "Unknown error")
+ return (
+ "A delegated task has failed:\n"
+ f"- Agent: {agent_name}\n"
+ f"- Task ID: {task_id}\n"
+ "- Status: Error\n"
+ f"- Error: {error}\n\n"
+ "IMPORTANT: This task has FAILED. Do NOT retry or delegate again.\n"
+ "Report this error to the user and suggest next steps if appropriate."
+ )
+
+ return (
+ f"Task update received:\n"
+ f"- Agent: {agent_name}\n"
+ f"- Task ID: {task_id}\n"
+ f"- Status: {status}\n"
+ f"- Data: {task_data}"
+ )