Skip to content

Self-improving AI Employees for everyone

refactor(plugin): Wave 11.D.6 — inline agent bodies via prepare_agent_call

trohitg30e9d202ed28
diff --git a/server/nodes/agent/_inline.py b/server/nodes/agent/_inline.py
new file mode 100644
index 00000000..77b38fe0
--- /dev/null
+++ b/server/nodes/agent/_inline.py
@@ -0,0 +1,110 @@
+"""Shared pre-dispatch logic for every agent plugin.
+
+Every agent (ai_agent, chat_agent, 13 specialized agents, team leads)
+shares the same 3-step preamble before calling its specific AIService
+method:
+
+1. :func:`services.plugin.edge_walker.collect_agent_connections` —
+ gather memory / skills / tools / input / task data.
+2. Task-context injection + tool-strip when ``task_data.status`` is
+ ``completed`` / ``error`` (so the agent reports results instead of
+ re-delegating).
+3. Auto-prompt fallback when the ``prompt`` field is empty and a
+ connected upstream node produced output.
+
+For team-lead agents (``orchestrator_agent`` / ``ai_employee``),
+teammate agents connected via ``input-teammates`` become delegation
+tools (appended to ``tool_data``).
+
+:func:`prepare_agent_call` returns the fully-prepared kwargs to pass
+to ``ai_service.execute_agent(...)`` or ``ai_service.execute_chat_agent(...)``.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Optional
+
+from core.logging import get_logger
+from services.plugin.edge_walker import (
+ collect_agent_connections,
+ collect_teammate_connections,
+ format_task_context,
+)
+
+logger = get_logger(__name__)
+
+# Team-lead agent types where teammates become delegation tools.
+TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee"})
+
+
+async def prepare_agent_call(
+ *,
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+ database: Any,
+ log_prefix: str = "[Agent]",
+) -> Dict[str, Any]:
+ """Run the 3-step pre-dispatch flow and return a kwargs dict ready
+ to splat into ``AIService.execute_agent`` or ``execute_chat_agent``.
+ """
+ memory_data, skill_data, tool_data, input_data, task_data = await collect_agent_connections(
+ node_id, context, database, log_prefix=log_prefix,
+ )
+
+ # Step 1: task-context injection + tool-strip.
+ 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"{log_prefix} Task context injected for task_id={task_data.get('task_id')}",
+ )
+ task_status = task_data.get("status", "")
+ if task_status in ("completed", "error") and tool_data:
+ original_tool_count = len(tool_data)
+ tool_data = []
+ logger.info(
+ f"{log_prefix} Stripped ALL {original_tool_count} tools for "
+ "task completion handling",
+ )
+
+ # Step 2: auto-prompt fallback.
+ if not parameters.get("prompt") and input_data:
+ prompt = (
+ (input_data.get("message") if isinstance(input_data, dict) else None)
+ or (input_data.get("text") if isinstance(input_data, dict) else None)
+ or (input_data.get("content") if isinstance(input_data, dict) else None)
+ or str(input_data)
+ )
+ parameters = {**parameters, "prompt": prompt}
+ shown = prompt[:100] if isinstance(prompt, str) and len(prompt) > 100 else prompt
+ logger.info(f"{log_prefix} Auto-using input as prompt: {shown}...")
+
+ # Step 3: team-lead delegation-tool injection.
+ if node_type in TEAM_LEAD_TYPES:
+ teammates = await collect_teammate_connections(node_id, context, database)
+ if teammates:
+ 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")
+
+ from services.status_broadcaster import get_status_broadcaster
+
+ return {
+ "parameters": parameters,
+ "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": context.get("workflow_id"),
+ "context": context,
+ "database": database,
+ }
diff --git a/server/nodes/agent/_specialized.py b/server/nodes/agent/_specialized.py
index d8bfac24..4f6c1c8e 100644
--- a/server/nodes/agent/_specialized.py
+++ b/server/nodes/agent/_specialized.py
@@ -76,20 +76,26 @@ class SpecializedAgentBase(ActionNode, abstract=True):
@Operation("execute", cost={"service": "specialized_agent", "action": "run", "count": 1})
async def execute_op(self, ctx: NodeContext, params: SpecializedAgentParams) -> Any:
+ """Inlined via ``prepare_agent_call`` (Wave 11.D.6).
+
+ All 13 specialized agents + orchestrator + ai_employee route
+ through :func:`AIService.execute_chat_agent` with identical
+ pre-dispatch flow. Team-lead teammate injection happens inside
+ ``prepare_agent_call`` based on ``self.type``.
+ """
from core.container import container
- from services.handlers.ai import handle_chat_agent
+
+ from ._inline import prepare_agent_call
ai_service = container.ai_service()
database = container.database()
- payload = params.model_dump(by_alias=True)
- response = await handle_chat_agent(
- ai_service=ai_service,
- database=database,
- node_id=ctx.node_id,
- node_type=self.type,
- parameters=payload,
- context=ctx.raw,
+ kwargs = await prepare_agent_call(
+ node_id=ctx.node_id, node_type=self.type,
+ parameters=params.model_dump(by_alias=True),
+ context=ctx.raw, database=database,
+ log_prefix=f"[{self.type}]",
)
+ response = await ai_service.execute_chat_agent(ctx.node_id, **kwargs)
if response.get("success"):
return response.get("result") or response
raise RuntimeError(response.get("error") or f"{self.type} execution failed")
diff --git a/server/nodes/agent/ai_agent.py b/server/nodes/agent/ai_agent.py
index 6f740af7..af4fbbe0 100644
--- a/server/nodes/agent/ai_agent.py
+++ b/server/nodes/agent/ai_agent.py
@@ -80,20 +80,27 @@ class AIAgentNode(ActionNode):
@Operation("execute", cost={"service": "ai_agent", "action": "run", "count": 1})
async def execute_op(self, ctx: NodeContext, params: AIAgentParams) -> Any:
+ """Inlined from handlers/ai.handle_ai_agent (Wave 11.D.6).
+
+ Pre-dispatch flow (edge walk + task inject + prompt fallback)
+ lives in :mod:`nodes.agent._inline`. This method just calls
+ ``AIService.execute_agent`` with the prepared kwargs. The
+ underlying LangGraph orchestration + tool binding + memory
+ I/O + streaming hooks stay in AIService.
+ """
from core.container import container
- from services.handlers.ai import handle_ai_agent
+
+ from ._inline import prepare_agent_call
ai_service = container.ai_service()
database = container.database()
- payload = params.model_dump(by_alias=True)
- response = await handle_ai_agent(
- ai_service=ai_service,
- database=database,
- node_id=ctx.node_id,
- node_type=self.type,
- parameters=payload,
- context=ctx.raw,
+ kwargs = await prepare_agent_call(
+ node_id=ctx.node_id, node_type=self.type,
+ parameters=params.model_dump(by_alias=True),
+ context=ctx.raw, database=database,
+ log_prefix="[AI Agent]",
)
+ response = await ai_service.execute_agent(ctx.node_id, **kwargs)
if response.get("success"):
return response.get("result") or response
raise RuntimeError(response.get("error") or "AI Agent execution failed")
diff --git a/server/nodes/agent/chat_agent.py b/server/nodes/agent/chat_agent.py
index 011657b5..3e8d053c 100644
--- a/server/nodes/agent/chat_agent.py
+++ b/server/nodes/agent/chat_agent.py
@@ -74,20 +74,20 @@ class ChatAgentNode(ActionNode):
@Operation("execute", cost={"service": "chat_agent", "action": "run", "count": 1})
async def execute_op(self, ctx: NodeContext, params: ChatAgentParams) -> Any:
+ """Inlined from handlers/ai.handle_chat_agent (Wave 11.D.6)."""
from core.container import container
- from services.handlers.ai import handle_chat_agent
+
+ from ._inline import prepare_agent_call
ai_service = container.ai_service()
database = container.database()
- payload = params.model_dump(by_alias=True)
- response = await handle_chat_agent(
- ai_service=ai_service,
- database=database,
- node_id=ctx.node_id,
- node_type=self.type,
- parameters=payload,
- context=ctx.raw,
+ kwargs = await prepare_agent_call(
+ node_id=ctx.node_id, node_type=self.type,
+ parameters=params.model_dump(by_alias=True),
+ context=ctx.raw, database=database,
+ log_prefix="[Chat Agent]",
)
+ response = await ai_service.execute_chat_agent(ctx.node_id, **kwargs)
if response.get("success"):
return response.get("result") or response
raise RuntimeError(response.get("error") or "Chat Agent execution failed")