Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(agent_builder): multi-op plugin with 5 canvas-mutation operations
trohitg26eefb7dc34b
diff --git a/server/nodes/tool/agent_builder.py b/server/nodes/tool/agent_builder.pynew file mode 100644index 00000000..d6eeb57f--- /dev/null+++ b/server/nodes/tool/agent_builder.py@@ -0,0 +1,586 @@+"""Agent Builder -- runtime canvas-mutation tool for AI agents.++Multi-op plugin matching the gmail / calendar / drive convention:+ONE node, ONE Params model with an ``operation: Literal[...]``+discriminator, FIVE ``@Operation`` methods. The LLM sees ONE tool+``agentBuilder`` with a select-style ``operation`` field; agents wire+the node into their standard ``input-tools`` handle (no special+topology, no parallel dispatch system).++The five operations are pure canvas mutations:++* ``inspect_canvas`` (read-only) -- snapshot of nodes / edges + what's+ wired to the calling agent.+* ``add_tool`` -- spawn a tool node + edge into caller's input-tools.+* ``add_skill`` -- toggle a skill on caller's Master Skill (or+ spawn a Master Skill if absent).+* ``add_subagent`` -- spawn a delegate agent + wire to caller's+ input-teammates (team-leads only).+* ``create_workflow`` -- persist a fresh empty workflow + return its+ workflow_id.++Each mutation pushes a ``workflow_ops_apply`` event via+``status_broadcaster.send_custom_event`` so the live canvas updates.+LangGraph binds tools at graph compile time, so a mutation made+mid-run does NOT add a callable tool to the current run; the+agent's NEXT invocation rediscovers it. Each summary string ends+with "Available on your next turn" so the LLM doesn't loop trying+to call something that isn't there yet.+"""++from __future__ import annotations++import logging+import uuid+from pathlib import Path+from typing import Any, Dict, List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from services import workflow_ops+from services.node_registry import registered_node_classes+from services.plugin import ActionNode, NodeContext, Operation, TaskQueue+++logger = logging.getLogger(__name__)+++# ----------------------------------------------------------------------------+# Constants+# ----------------------------------------------------------------------------++_TOOL_HANDLE = "input-tools"+_SKILL_HANDLE = "input-skill"+_SKILL_OUTPUT_HANDLE = "output-tool"+_TEAMMATES_HANDLE = "input-teammates"+_TEAMMATES_OUTPUT_HANDLE = "output-main"+_TOOL_OUTPUT_HANDLE = "output-main"+_MASTER_SKILL_TYPE = "masterSkill"+_MASTER_SKILL_LABEL = "Master Skill"+_AGENT_BUILDER_TYPE = "agentBuilder"+_TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee", "deep_agent"})+_DENIED_TOOL_TYPES = frozenset({_AGENT_BUILDER_TYPE, _MASTER_SKILL_TYPE})+_KEY_PARAM_FIELDS = ("provider", "model", "operation", "url", "query")+_SKILLS_DIR = Path(__file__).resolve().parents[2] / "skills"+++# ----------------------------------------------------------------------------+# Helpers+# ----------------------------------------------------------------------------+++async def _broadcast(workflow_id: Optional[str], caller_id: str, ops: List[Dict[str, Any]]) -> None:+ """Push a workflow_ops_apply event so the live canvas updates."""+ if not ops:+ return+ try:+ from services.status_broadcaster import get_status_broadcaster+ broadcaster = get_status_broadcaster()+ await broadcaster.send_custom_event(+ "workflow_ops_apply",+ {"workflow_id": workflow_id, "caller_node_id": caller_id, "operations": ops},+ )+ except Exception as exc:+ logger.warning(f"[agentBuilder] broadcast failed: {exc}", exc_info=True)+++def _allowed_tool_types() -> set[str]:+ """Tool nodes the LLM may spawn -- excludes the builder + masterSkill."""+ return {+ ntype for ntype, cls in registered_node_classes().items()+ if getattr(cls, "component_kind", "") == "tool"+ and ntype not in _DENIED_TOOL_TYPES+ }+++def _allowed_subagent_types() -> set[str]:+ return {+ ntype for ntype, cls in registered_node_classes().items()+ if getattr(cls, "component_kind", "") == "agent"+ }+++def _is_team_lead(node_type: str) -> bool:+ return node_type in _TEAM_LEAD_TYPES+++def _toggle_skill(+ config: Optional[Dict[str, Dict[str, Any]]],+ skill_name: str,+ enabled: bool,+) -> Dict[str, Dict[str, Any]]:+ """Return a new skills_config dict with ``skill_name`` toggled."""+ base: Dict[str, Dict[str, Any]] = dict(config or {})+ existing = base.get(skill_name, {})+ base[skill_name] = {+ "enabled": enabled,+ "instructions": existing.get("instructions", ""),+ "isCustomized": existing.get("isCustomized", False),+ }+ return base+++def _skill_folder_exists(skill_folder: str) -> bool:+ if not _SKILLS_DIR.exists():+ return False+ for path in _SKILLS_DIR.rglob(skill_folder):+ if path.is_dir() and (path / "SKILL.md").exists():+ return True+ return False+++def _key_params(node: Dict[str, Any]) -> Dict[str, Any]:+ params = (node.get("data") or {}).get("parameters") or {}+ return {k: params[k] for k in _KEY_PARAM_FIELDS if k in params}+++def _resolve_caller(ctx: NodeContext) -> str:+ """Return the calling agent's node_id, or fall back to self.++ Convention: an agentBuilder is wired to ONE agent's input-tools+ handle. We find that edge and treat the agent as the caller.+ Falls back to ctx.node_id if no such edge exists (standalone Run+ or no agent wired yet) so the operations still produce something+ sensible instead of crashing.+ """+ self_id = ctx.node_id+ for edge in ctx.edges or []:+ if (+ edge.get("source") == self_id+ and edge.get("targetHandle") == _TOOL_HANDLE+ ):+ target = edge.get("target")+ if target:+ return target+ return self_id+++# ----------------------------------------------------------------------------+# Params + Output schemas+# ----------------------------------------------------------------------------+++class AgentBuilderParams(BaseModel):+ """Multi-op schema. The LLM picks ``operation``, then fills the+ fields whose ``displayOptions`` enable them for that op.+ """++ operation: Literal[+ "inspect_canvas",+ "add_tool",+ "add_skill",+ "add_subagent",+ "create_workflow",+ ] = Field(+ default="inspect_canvas",+ description=(+ "Which canvas-mutation to perform. Always call "+ "'inspect_canvas' first to see what's already wired before "+ "spawning new nodes."+ ),+ )++ # add_tool+ node_type: str = Field(+ default="",+ description=(+ "For add_tool: tool node type to spawn (e.g. 'httpRequest', "+ "'braveSearch'). Must be a registered node with "+ "component_kind='tool'."+ ),+ json_schema_extra={"displayOptions": {"show": {"operation": ["add_tool"]}}},+ )++ # add_skill+ skill_folder: str = Field(+ default="",+ description=(+ "For add_skill: skill folder name under server/skills/** "+ "(e.g. 'http-request-skill', 'memory-skill')."+ ),+ json_schema_extra={"displayOptions": {"show": {"operation": ["add_skill"]}}},+ )++ # add_subagent+ agent_type: str = Field(+ default="",+ description=(+ "For add_subagent: agent node type to spawn (e.g. "+ "'coding_agent', 'web_agent'). Must be component_kind='agent' "+ "and not a team-lead. Caller must itself be a team-lead "+ "(orchestrator_agent / ai_employee / deep_agent)."+ ),+ json_schema_extra={"displayOptions": {"show": {"operation": ["add_subagent"]}}},+ )++ # create_workflow+ workflow_name: str = Field(+ default="",+ description="For create_workflow: display name (non-empty).",+ json_schema_extra={+ "displayOptions": {"show": {"operation": ["create_workflow"]}},+ },+ )+ workflow_description: str = Field(+ default="",+ description="For create_workflow: optional one-line description.",+ json_schema_extra={+ "displayOptions": {"show": {"operation": ["create_workflow"]}},+ },+ )++ model_config = ConfigDict(extra="ignore")+++class AgentBuilderOutput(BaseModel):+ operation: Optional[str] = None+ summary: Optional[str] = None+ operations: Optional[List[Dict[str, Any]]] = None+ # inspect_canvas extras+ nodes: Optional[List[Dict[str, Any]]] = None+ edges: Optional[List[Dict[str, Any]]] = None+ you: Optional[Dict[str, Any]] = None+ # create_workflow extras+ workflow_id: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++# ----------------------------------------------------------------------------+# Node+# ----------------------------------------------------------------------------+++class AgentBuilderNode(ActionNode):+ type = _AGENT_BUILDER_TYPE+ display_name = "Agent Builder"+ subtitle = "Runtime canvas-mutation tool"+ group = ("tool", "ai")+ description = (+ "Inspect the workflow canvas and mutate it at runtime: spawn "+ "tools, enable skills, add delegate agents, or create new "+ "workflows. Wire to an AI agent's input-tools handle; the "+ "agent calls operations through the standard tool path."+ )+ component_kind = "tool"+ handles = (+ {"name": "output-main", "kind": "output", "position": "right",+ "label": "Tool", "role": "main"},+ )+ annotations = {"destructive": False, "readonly": False, "open_world": True}+ task_queue = TaskQueue.DEFAULT+ usable_as_tool = True++ Params = AgentBuilderParams+ Output = AgentBuilderOutput++ # ---- inspect_canvas (read-only) ---------------------------------------++ @Operation("inspect_canvas")+ async def inspect_canvas(+ self, ctx: NodeContext, params: AgentBuilderParams,+ ) -> AgentBuilderOutput:+ nodes = list(ctx.nodes or [])+ edges = list(ctx.edges or [])+ caller_id = _resolve_caller(ctx)+ type_by_id = {n.get("id"): n.get("type") for n in nodes}++ node_summaries = [+ {+ "id": n.get("id"),+ "type": n.get("type"),+ "label": (n.get("data") or {}).get("label") or n.get("type"),+ "key_params": _key_params(n),+ }+ for n in nodes+ ]+ edge_summaries = [+ {+ "source": e.get("source"),+ "target": e.get("target"),+ "source_handle": e.get("sourceHandle"),+ "target_handle": e.get("targetHandle"),+ }+ for e in edges+ ]+ incoming = [+ {+ "source_id": e.get("source"),+ "source_type": type_by_id.get(e.get("source")),+ "target_handle": e.get("targetHandle"),+ }+ for e in edges if e.get("target") == caller_id+ ]+ outgoing = [+ {+ "target_id": e.get("target"),+ "target_type": type_by_id.get(e.get("target")),+ "source_handle": e.get("sourceHandle"),+ }+ for e in edges if e.get("source") == caller_id+ ]++ tools = [c for c in incoming if c["target_handle"] == _TOOL_HANDLE]+ skills = [c for c in incoming if c["target_handle"] == _SKILL_HANDLE]+ teammates = [c for c in incoming if c["target_handle"] == _TEAMMATES_HANDLE]+ parts = [f"{len(nodes)} nodes"]+ if tools:+ types = ", ".join(sorted({c["source_type"] or "?" for c in tools}))+ parts.append(f"{len(tools)} tool(s) wired to you ({types})")+ if skills:+ parts.append(f"{len(skills)} skill source(s) wired")+ if teammates:+ parts.append(f"{len(teammates)} teammate(s)")++ return AgentBuilderOutput(+ operation="inspect_canvas",+ summary=", ".join(parts) + ".",+ nodes=node_summaries,+ edges=edge_summaries,+ you={"node_id": caller_id, "incoming": incoming, "outgoing": outgoing},+ )++ # ---- add_tool ---------------------------------------------------------++ @Operation("add_tool")+ async def add_tool(+ self, ctx: NodeContext, params: AgentBuilderParams,+ ) -> AgentBuilderOutput:+ node_type = (params.node_type or "").strip()+ if not node_type:+ return AgentBuilderOutput(+ operation="add_tool",+ summary="add_tool: node_type is required.",+ operations=[],+ )+ allowed = _allowed_tool_types()+ if node_type not in allowed:+ sample = ", ".join(sorted(allowed)[:10])+ return AgentBuilderOutput(+ operation="add_tool",+ summary=(+ f"add_tool: '{node_type}' is not an allowed tool type. "+ f"Examples of allowed types: {sample}..."+ ),+ operations=[],+ )++ caller_id = _resolve_caller(ctx)+ client_ref = f"new_{node_type}"+ ops = [+ workflow_ops.add_node(+ client_ref, node_type, {},+ label=node_type,+ position=workflow_ops.anchored(caller_id, offset_x=200, offset_y=80),+ ),+ workflow_ops.add_edge(+ {"client_ref": client_ref}, caller_id,+ source_handle=_TOOL_OUTPUT_HANDLE, target_handle=_TOOL_HANDLE,+ ),+ ]+ await _broadcast(ctx.workflow_id, caller_id, ops)+ return AgentBuilderOutput(+ operation="add_tool",+ summary=f"Added '{node_type}' as a tool. Available on your next turn.",+ operations=ops,+ )++ # ---- add_skill --------------------------------------------------------++ @Operation("add_skill")+ async def add_skill(+ self, ctx: NodeContext, params: AgentBuilderParams,+ ) -> AgentBuilderOutput:+ skill = (params.skill_folder or "").strip()+ if not skill:+ return AgentBuilderOutput(+ operation="add_skill",+ summary="add_skill: skill_folder is required.",+ operations=[],+ )+ if not _skill_folder_exists(skill):+ return AgentBuilderOutput(+ operation="add_skill",+ summary=f"add_skill: skill '{skill}' not found under server/skills.",+ operations=[],+ )++ nodes = list(ctx.nodes or [])+ edges = list(ctx.edges or [])+ caller_id = _resolve_caller(ctx)++ skill_edge = next(+ (e for e in edges if e.get("target") == caller_id+ and e.get("targetHandle") == _SKILL_HANDLE),+ None,+ )+ master_skill = None+ if skill_edge:+ master_skill = next(+ (n for n in nodes if n.get("id") == skill_edge.get("source")+ and n.get("type") == _MASTER_SKILL_TYPE),+ None,+ )++ if master_skill:+ existing = (+ ((master_skill.get("data") or {}).get("parameters") or {})+ .get("skills_config") or {}+ )+ new_config = _toggle_skill(existing, skill, True)+ ops = [workflow_ops.set_node_parameters(+ master_skill["id"], {"skills_config": new_config},+ )]+ await _broadcast(ctx.workflow_id, caller_id, ops)+ return AgentBuilderOutput(+ operation="add_skill",+ summary=f"Enabled '{skill}' skill. Available on your next turn.",+ operations=ops,+ )++ new_config = _toggle_skill(None, skill, True)+ client_ref = "new_master_skill"+ ops = [+ workflow_ops.add_node(+ client_ref, _MASTER_SKILL_TYPE,+ {"skills_config": new_config},+ label=_MASTER_SKILL_LABEL,+ position=workflow_ops.anchored(caller_id, offset_x=-60, offset_y=220),+ ),+ workflow_ops.add_edge(+ {"client_ref": client_ref}, caller_id,+ source_handle=_SKILL_OUTPUT_HANDLE, target_handle=_SKILL_HANDLE,+ ),+ ]+ await _broadcast(ctx.workflow_id, caller_id, ops)+ return AgentBuilderOutput(+ operation="add_skill",+ summary=(+ f"Created Master Skill node and enabled '{skill}'. "+ "Available on your next turn."+ ),+ operations=ops,+ )++ # ---- add_subagent -----------------------------------------------------++ @Operation("add_subagent")+ async def add_subagent(+ self, ctx: NodeContext, params: AgentBuilderParams,+ ) -> AgentBuilderOutput:+ agent_type = (params.agent_type or "").strip()+ if not agent_type:+ return AgentBuilderOutput(+ operation="add_subagent",+ summary="add_subagent: agent_type is required.",+ operations=[],+ )++ nodes = list(ctx.nodes or [])+ caller_id = _resolve_caller(ctx)+ caller = next((n for n in nodes if n.get("id") == caller_id), None)+ caller_type = (caller or {}).get("type") or ""++ if not _is_team_lead(caller_type):+ leads = ", ".join(sorted(_TEAM_LEAD_TYPES))+ return AgentBuilderOutput(+ operation="add_subagent",+ summary=(+ f"add_subagent: only team-lead agents ({leads}) can spawn "+ f"delegates. This agent is '{caller_type}'."+ ),+ operations=[],+ )+ allowed = _allowed_subagent_types()+ if agent_type not in allowed:+ sample = ", ".join(sorted(allowed)[:10])+ return AgentBuilderOutput(+ operation="add_subagent",+ summary=(+ f"add_subagent: '{agent_type}' is not an allowed agent "+ f"type. Examples: {sample}..."+ ),+ operations=[],+ )+ if _is_team_lead(agent_type):+ return AgentBuilderOutput(+ operation="add_subagent",+ summary=(+ f"add_subagent: cannot spawn another team-lead "+ f"('{agent_type}'); pick a specialized agent instead."+ ),+ operations=[],+ )++ client_ref = f"new_{agent_type}"+ ops = [+ workflow_ops.add_node(+ client_ref, agent_type, {},+ label=agent_type,+ position=workflow_ops.anchored(caller_id, offset_x=300, offset_y=200),+ ),+ workflow_ops.add_edge(+ {"client_ref": client_ref}, caller_id,+ source_handle=_TEAMMATES_OUTPUT_HANDLE, target_handle=_TEAMMATES_HANDLE,+ ),+ ]+ await _broadcast(ctx.workflow_id, caller_id, ops)+ return AgentBuilderOutput(+ operation="add_subagent",+ summary=(+ f"Added '{agent_type}' as a teammate. Available on your "+ "next turn (configure provider/model first)."+ ),+ operations=ops,+ )++ # ---- create_workflow --------------------------------------------------++ @Operation("create_workflow")+ async def create_workflow(+ self, ctx: NodeContext, params: AgentBuilderParams,+ ) -> AgentBuilderOutput:+ name = (params.workflow_name or "").strip()+ if not name:+ return AgentBuilderOutput(+ operation="create_workflow",+ summary="create_workflow: workflow_name is required.",+ )++ workflow_id = f"wf_{uuid.uuid4().hex[:12]}"+ start_node_id = f"start-{uuid.uuid4().hex[:8]}"+ description = (params.workflow_description or "").strip()+ workflow_data = {+ "id": workflow_id,+ "name": name,+ "description": description,+ "nodes": [+ {+ "id": start_node_id,+ "type": "start",+ "position": {"x": 200, "y": 200},+ "data": {"label": "Start"},+ }+ ],+ "edges": [],+ "nodeParameters": {},+ }++ from core.container import container+ database = container.database()+ ok = await database.save_workflow(+ workflow_id, name, workflow_data, description=description or None,+ )+ if not ok:+ return AgentBuilderOutput(+ operation="create_workflow",+ summary=f"create_workflow: failed to persist '{name}'.",+ )+ return AgentBuilderOutput(+ operation="create_workflow",+ summary=(+ f"Created workflow '{name}' (id: {workflow_id}). "+ "User can switch to it from the toast notification."+ ),+ workflow_id=workflow_id,+ )diff --git a/server/nodes/visuals.json b/server/nodes/visuals.jsonindex 984d5a97..b529cbbd 100644--- a/server/nodes/visuals.json+++ b/server/nodes/visuals.json@@ -1,4 +1,9 @@{+ "agentBuilder": {+ "icon": "🛠️",+ "color": "#ffb86c",+ "skill": "agent-builder-skill"+ },"aiAgent": {"icon": "🤖","color": "#bd93f9"diff --git a/server/tests/nodes/test_agent_builder.py b/server/tests/nodes/test_agent_builder.pynew file mode 100644index 00000000..71d82842--- /dev/null+++ b/server/tests/nodes/test_agent_builder.py@@ -0,0 +1,427 @@+"""Contract tests for the agentBuilder multi-op plugin.++agentBuilder is a single multi-op tool node exposing 5 canvas-mutation+operations through the standard `@Operation` plugin pattern (matching+gmail / calendar / drive). The LLM sees one tool with an `operation`+discriminator; we test each operation's happy + reject paths directly+on the node instance, mocking the broadcaster and registry lookups so+no live state is touched.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from nodes.tool import agent_builder as ab+from services.plugin import NodeContext+++pytestmark = pytest.mark.node_contract+++# ============================================================================+# Helpers+# ============================================================================+++def _make_ctx(+ *,+ nodes=None,+ edges=None,+ workflow_id: str = "wf-test",+ self_id: str = "ab-1",+) -> NodeContext:+ return NodeContext(+ node_id=self_id,+ node_type="agentBuilder",+ workflow_id=workflow_id,+ nodes=nodes or [],+ edges=edges or [],+ raw={"workflow_id": workflow_id},+ )+++def _agent_node(node_id: str, node_type: str = "aiAgent", **params) -> dict:+ return {+ "id": node_id,+ "type": node_type,+ "data": {"label": node_type, "parameters": params},+ }+++def _edge(source: str, target: str, target_handle: str = "input-tools") -> dict:+ return {+ "source": source,+ "target": target,+ "sourceHandle": "output-main",+ "targetHandle": target_handle,+ }+++def _node_class(component_kind: str) -> SimpleNamespace:+ return SimpleNamespace(component_kind=component_kind)+++def _registry(**type_to_kind) -> dict:+ return {ntype: _node_class(kind) for ntype, kind in type_to_kind.items()}+++# ============================================================================+# Plugin registration+# ============================================================================+++class TestRegistration:+ def test_node_is_registered(self):+ from services.node_registry import get_node_class+ cls = get_node_class("agentBuilder")+ assert cls is ab.AgentBuilderNode++ def test_has_five_operations(self):+ ops = set(ab.AgentBuilderNode._operations.keys())+ assert ops == {+ "inspect_canvas", "add_tool", "add_skill",+ "add_subagent", "create_workflow",+ }++ def test_default_operation_is_inspect_canvas(self):+ params = ab.AgentBuilderParams()+ assert params.operation == "inspect_canvas"++ def test_usable_as_tool(self):+ assert ab.AgentBuilderNode.usable_as_tool is True++ def test_handle_topology_is_standard_tool_output(self):+ handles = list(ab.AgentBuilderNode.handles)+ assert len(handles) == 1+ assert handles[0]["name"] == "output-main"+ assert handles[0]["kind"] == "output"+ assert handles[0]["position"] == "right"++ def test_no_provided_tools_dict(self):+ """Sanity check: the tribal PROVIDED_TOOLS attr from the original+ design must NOT exist on the multi-op rewrite."""+ assert not hasattr(ab.AgentBuilderNode, "PROVIDED_TOOLS")+++# ============================================================================+# inspect_canvas+# ============================================================================+++class TestInspectCanvas:+ async def test_returns_node_and_edge_summaries(self):+ nodes = [+ _agent_node("agent-1"),+ {"id": "ab-1", "type": "agentBuilder", "data": {"label": "AB"}},+ {"id": "tool-1", "type": "httpRequest",+ "data": {"label": "HTTP", "parameters": {"url": "https://x"}}},+ ]+ edges = [+ _edge("ab-1", "agent-1", "input-tools"),+ _edge("tool-1", "agent-1", "input-tools"),+ ]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=nodes, edges=edges)+ params = ab.AgentBuilderParams(operation="inspect_canvas")++ result = await node.inspect_canvas(ctx, params)++ assert result.operation == "inspect_canvas"+ assert len(result.nodes) == 3+ assert len(result.edges) == 2+ assert result.you["node_id"] == "agent-1" # caller resolved via input-tools edge+ assert "1 tool(s) wired" in result.summary++ async def test_falls_back_to_self_when_no_caller_wired(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[], edges=[], self_id="ab-1")+ params = ab.AgentBuilderParams(operation="inspect_canvas")++ result = await node.inspect_canvas(ctx, params)++ assert result.you["node_id"] == "ab-1"+++# ============================================================================+# add_tool+# ============================================================================+++class TestAddTool:+ async def test_rejects_empty_node_type(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="add_tool", node_type="")++ result = await node.add_tool(ctx, params)++ assert result.operations == []+ assert "node_type is required" in result.summary++ async def test_rejects_disallowed_type(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="add_tool", node_type="unknownTool")++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(httpRequest="tool")):+ result = await node.add_tool(ctx, params)++ assert result.operations == []+ assert "not an allowed tool type" in result.summary++ async def test_rejects_self_and_master_skill(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(+ agentBuilder="tool", masterSkill="tool",+ httpRequest="tool")):+ for forbidden in ("agentBuilder", "masterSkill"):+ params = ab.AgentBuilderParams(operation="add_tool", node_type=forbidden)+ result = await node.add_tool(ctx, params)+ assert result.operations == []+ assert "not an allowed tool type" in result.summary++ async def test_emits_add_node_and_add_edge_ops(self):+ node = ab.AgentBuilderNode()+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ ctx = _make_ctx(edges=edges)+ params = ab.AgentBuilderParams(operation="add_tool", node_type="httpRequest")++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(httpRequest="tool")), \+ patch.object(ab, "_broadcast", new_callable=AsyncMock) as mock_bcast:+ result = await node.add_tool(ctx, params)++ assert len(result.operations) == 2+ assert result.operations[0]["type"] == "add_node"+ assert result.operations[0]["node_type"] == "httpRequest"+ assert result.operations[1]["type"] == "add_edge"+ assert result.operations[1]["target"] == "agent-1"+ assert result.operations[1]["target_handle"] == "input-tools"+ mock_bcast.assert_awaited_once()+ assert "Available on your next turn" in result.summary+++# ============================================================================+# add_skill+# ============================================================================+++class TestAddSkill:+ async def test_rejects_empty_skill_folder(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="add_skill", skill_folder="")++ result = await node.add_skill(ctx, params)++ assert result.operations == []+ assert "skill_folder is required" in result.summary++ async def test_rejects_unknown_skill_folder(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(+ operation="add_skill", skill_folder="nonexistent-skill",+ )++ with patch.object(ab, "_skill_folder_exists", return_value=False):+ result = await node.add_skill(ctx, params)++ assert result.operations == []+ assert "not found" in result.summary++ async def test_toggles_on_existing_master_skill(self):+ master = {+ "id": "ms-1", "type": "masterSkill",+ "data": {"parameters": {"skills_config": {"old-skill": {"enabled": True}}}},+ }+ agent = _agent_node("agent-1")+ edges = [+ _edge("ab-1", "agent-1", "input-tools"),+ _edge("ms-1", "agent-1", "input-skill"),+ ]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[agent, master], edges=edges)+ params = ab.AgentBuilderParams(+ operation="add_skill", skill_folder="http-request-skill",+ )++ with patch.object(ab, "_skill_folder_exists", return_value=True), \+ patch.object(ab, "_broadcast", new_callable=AsyncMock):+ result = await node.add_skill(ctx, params)++ assert len(result.operations) == 1+ op = result.operations[0]+ assert op["type"] == "set_node_parameters"+ assert op["node_id"] == "ms-1"+ new_cfg = op["parameters"]["skills_config"]+ assert new_cfg["http-request-skill"]["enabled"] is True+ assert new_cfg["old-skill"]["enabled"] is True # preserved++ async def test_spawns_master_skill_when_absent(self):+ agent = _agent_node("agent-1")+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[agent], edges=edges)+ params = ab.AgentBuilderParams(+ operation="add_skill", skill_folder="memory-skill",+ )++ with patch.object(ab, "_skill_folder_exists", return_value=True), \+ patch.object(ab, "_broadcast", new_callable=AsyncMock):+ result = await node.add_skill(ctx, params)++ assert len(result.operations) == 2+ assert result.operations[0]["type"] == "add_node"+ assert result.operations[0]["node_type"] == "masterSkill"+ seeded = result.operations[0]["parameters"]["skills_config"]+ assert seeded["memory-skill"]["enabled"] is True+ assert result.operations[1]["type"] == "add_edge"+++# ============================================================================+# add_subagent+# ============================================================================+++class TestAddSubagent:+ async def test_rejects_empty_agent_type(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="add_subagent", agent_type="")++ result = await node.add_subagent(ctx, params)++ assert result.operations == []+ assert "agent_type is required" in result.summary++ async def test_rejects_when_caller_is_not_team_lead(self):+ agent = _agent_node("agent-1", "aiAgent") # aiAgent is NOT a team-lead+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[agent], edges=edges)+ params = ab.AgentBuilderParams(+ operation="add_subagent", agent_type="coding_agent",+ )++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(coding_agent="agent")):+ result = await node.add_subagent(ctx, params)++ assert result.operations == []+ assert "team-lead" in result.summary++ async def test_rejects_disallowed_agent_type(self):+ agent = _agent_node("agent-1", "orchestrator_agent")+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[agent], edges=edges)+ params = ab.AgentBuilderParams(+ operation="add_subagent", agent_type="not_a_real_agent",+ )++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(coding_agent="agent")):+ result = await node.add_subagent(ctx, params)++ assert result.operations == []+ assert "not an allowed agent type" in result.summary++ async def test_rejects_spawning_another_team_lead(self):+ agent = _agent_node("agent-1", "orchestrator_agent")+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[agent], edges=edges)+ params = ab.AgentBuilderParams(+ operation="add_subagent", agent_type="ai_employee",+ )++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(ai_employee="agent")):+ result = await node.add_subagent(ctx, params)++ assert result.operations == []+ assert "cannot spawn another team-lead" in result.summary++ async def test_emits_add_node_and_teammate_edge(self):+ agent = _agent_node("agent-1", "orchestrator_agent")+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ node = ab.AgentBuilderNode()+ ctx = _make_ctx(nodes=[agent], edges=edges)+ params = ab.AgentBuilderParams(+ operation="add_subagent", agent_type="coding_agent",+ )++ with patch.object(ab, "registered_node_classes",+ return_value=_registry(coding_agent="agent")), \+ patch.object(ab, "_broadcast", new_callable=AsyncMock):+ result = await node.add_subagent(ctx, params)++ assert len(result.operations) == 2+ assert result.operations[0]["node_type"] == "coding_agent"+ assert result.operations[1]["target_handle"] == "input-teammates"+++# ============================================================================+# create_workflow+# ============================================================================+++class TestCreateWorkflow:+ async def test_rejects_empty_name(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="create_workflow", workflow_name="")++ result = await node.create_workflow(ctx, params)++ assert result.workflow_id is None+ assert "workflow_name is required" in result.summary++ async def test_persists_via_database_and_returns_id(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(+ operation="create_workflow",+ workflow_name="My New Workflow",+ workflow_description="An optional description",+ )++ mock_db = MagicMock()+ mock_db.save_workflow = AsyncMock(return_value=True)+ mock_container = MagicMock()+ mock_container.database.return_value = mock_db++ with patch("core.container.container", mock_container):+ result = await node.create_workflow(ctx, params)++ assert result.workflow_id is not None+ assert result.workflow_id.startswith("wf_")+ assert "My New Workflow" in result.summary+ mock_db.save_workflow.assert_awaited_once()++ async def test_returns_failure_summary_when_persist_fails(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(+ operation="create_workflow", workflow_name="Doomed Workflow",+ )++ mock_db = MagicMock()+ mock_db.save_workflow = AsyncMock(return_value=False)+ mock_container = MagicMock()+ mock_container.database.return_value = mock_db++ with patch("core.container.container", mock_container):+ result = await node.create_workflow(ctx, params)++ assert result.workflow_id is None+ assert "failed to persist" in result.summary