Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(agent_builder): full catalogue + idempotent mutations + DB persistence + dual-purpose rebind
trohitg27f90b801ab4
diff --git a/client/src/lib/workflowOps.ts b/client/src/lib/workflowOps.tsindex 0c70939e..6252395b 100644--- a/client/src/lib/workflowOps.ts+++ b/client/src/lib/workflowOps.ts@@ -40,6 +40,15 @@ export interface AddNodeOp {parameters: Record<string, any>;label?: string;position?: PositionSpec;+ /**+ * Optional BE-minted node id. When the backend hot-spawns a node+ * mid-execution (agentBuilder + the agent-loop rebind path) it needs+ * to dispatch status broadcasts against the same id the canvas+ * renders under. The applier adopts this id verbatim when present,+ * falling back to `newId()` otherwise so frontend-initiated spawns+ * keep their existing semantics.+ */+ minted_id?: string;}export interface AddEdgeOp {@@ -176,7 +185,10 @@ export async function applyOperations(try {switch (op.type) {case 'add_node': {- const id = newId(op.node_type);+ // Prefer the BE-minted id when present (agentBuilder hot-spawn+ // path) so status broadcasts dispatched against the same id+ // land on this React Flow node and the canvas glows.+ const id = op.minted_id || newId(op.node_type);result.refMap[op.client_ref] = id;const position = resolvePosition(op.position, ctx, liveNodes);const label = op.label ?? op.parameters?.label ?? op.node_type;diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex 3d071885..61f522a9 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -32,7 +32,8 @@],"disabled_nodes": ["android_agent",- "androidTool"+ "androidTool",+ "taskManager"],"disabled_credential_categories": ["android",diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.pyindex 9f5b2f93..71d70935 100644--- a/server/nodes/tool/agent_builder/__init__.py+++ b/server/nodes/tool/agent_builder/__init__.py@@ -64,19 +64,146 @@ _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"+# Temporary feature flag — set to True to re-enable the create_workflow+# operation. Flipping this constant restores the operation's prior+# behaviour (validation + slug allocation + database.save_workflow).+# The implementation below stays intact so re-enabling is one line.+_CREATE_WORKFLOW_ENABLED = False+# ----------------------------------------------------------------------------# Helpers# ----------------------------------------------------------------------------+async def _persist_canvas_mutation(workflow_id: Optional[str], ops: List[Dict[str, Any]]) -> None:+ """Apply the three op types agentBuilder emits to the persisted+ ``workflow.data`` via the existing ``database.get_workflow`` ++ ``database.save_workflow`` round-trip.++ Without this, every chat-message trigger reloads the workflow JSON+ from the DB and sees the pre-mutation snapshot — the agent then+ re-spawns the same tools the LLM already added in a prior run.+ Persisting after each mutation makes the DB the source of truth+ for cross-run canvas state.++ Adopts the BE-side ``minted_id`` (already stamped on ``add_node``+ ops for FE alignment) so the persisted row matches the React Flow+ state exactly — no id divergence on reload.+ """+ if not ops or not workflow_id:+ return+ try:+ from services.plugin.deps import get_database++ database = get_database()+ workflow = await database.get_workflow(workflow_id)+ if workflow is None:+ logger.debug("[agentBuilder] persist skipped: workflow %s not found", workflow_id)+ return++ data = dict(workflow.data or {})+ nodes = list(data.get("nodes") or [])+ edges = list(data.get("edges") or [])+ ref_to_id: Dict[str, str] = {}++ def _resolve(ref: Any) -> Optional[str]:+ if isinstance(ref, str):+ return ref+ if isinstance(ref, dict) and "client_ref" in ref:+ return ref_to_id.get(ref["client_ref"])+ return None++ for op in ops:+ op_type = op.get("type")+ if op_type == "add_node":+ node_type = op.get("node_type") or ""+ if not node_type:+ continue+ # ``minted_id`` is set by add_tool / add_skill / add_subagent+ # so the FE applier adopts the same id. Reuse it for the+ # persisted row to keep BE/FE views aligned.+ new_id = op.get("minted_id") or op.get("client_ref") or ""+ if not new_id:+ continue+ client_ref = op.get("client_ref") or ""+ if client_ref:+ ref_to_id[client_ref] = new_id+ params = op.get("parameters") or {}+ nodes.append(+ {+ "id": new_id,+ "type": node_type,+ "position": op.get("position") if isinstance(op.get("position"), dict) and "x" in op["position"] else {"x": 0, "y": 0},+ "data": {+ "label": op.get("label") or params.get("label") or node_type,+ "parameters": dict(params),+ },+ }+ )+ elif op_type == "add_edge":+ source = _resolve(op.get("source"))+ target = _resolve(op.get("target"))+ if not source or not target:+ continue+ edges.append(+ {+ "id": f"e-{source}-{target}",+ "source": source,+ "target": target,+ "sourceHandle": op.get("source_handle"),+ "targetHandle": op.get("target_handle"),+ }+ )+ elif op_type == "set_node_parameters":+ node_id = op.get("node_id")+ merge = op.get("parameters") or {}+ for n in nodes:+ if n.get("id") != node_id:+ continue+ node_data = dict(n.get("data") or {})+ existing = dict(node_data.get("parameters") or {})+ existing.update(merge)+ node_data["parameters"] = existing+ n["data"] = node_data+ break++ data["nodes"] = nodes+ data["edges"] = edges+ await database.save_workflow(+ workflow_id=workflow_id,+ name=workflow.name,+ slug=workflow.slug,+ data=data,+ description=workflow.description,+ )+ logger.info(+ "[agentBuilder] persisted %s ops to workflow %s (nodes=%d edges=%d)",+ [op.get("type") for op in ops],+ workflow_id,+ len(nodes),+ len(edges),+ )+ except Exception as exc:+ logger.warning(+ "[agentBuilder] persist failed for workflow %s: %s", workflow_id, exc, exc_info=True+ )++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.+ """Persist the canvas mutation to the DB, then push a+ ``workflow_ops_apply`` event so the live React Flow canvas updates.++ Persist-then-broadcast: the next agentBuilder call (within this run+ OR on the next chat-message trigger) reads from the DB and sees the+ new state, so duplicate detection in ``_find_wired_types`` catches+ repeat add_tool calls instead of silently spawning copies.Wave 12 B10: routes through plugin _events.py wrapper."""if not ops:return+ await _persist_canvas_mutation(workflow_id, ops)try:from ._events import broadcast_workflow_ops@@ -95,23 +222,103 @@ async def _broadcast(workflow_id: Optional[str], caller_id: str, ops: List[Dict[logger.warning(f"[agentBuilder] broadcast failed: {exc}", exc_info=True)+def _allowlist_config() -> Dict[str, Any]:+ """Load the operator allowlist config once per call — same source of+ truth the UI palette uses (server/config/node_allowlist.json). The+ NodeAllowlistService singleton handles parse failures with a safe+ show_all fallback, so this never raises on missing / malformed JSON.+ """+ try:+ from services.node_allowlist import get_node_allowlist_service++ return get_node_allowlist_service().get_config()+ except Exception as exc: # noqa: BLE001 — defensive: never fail catalogue+ logger.debug("[agentBuilder] node_allowlist read failed: %s", exc)+ return {"disabled_nodes": [], "disabled_groups": [], "disabled_skill_folders": []}+++def _is_blocked_by_allowlist(cls: Any, ntype: str, config: Dict[str, Any]) -> bool:+ """``True`` when ``ntype`` or any group in ``cls.group`` is in the+ operator blocklist. Honors both ``disabled_nodes`` (per-type) and+ ``disabled_groups`` (every plugin in the named group)."""+ if ntype in (config.get("disabled_nodes") or ()):+ return True+ disabled_groups = set(config.get("disabled_groups") or ())+ if disabled_groups:+ plugin_groups = set(getattr(cls, "group", ()) or ())+ if plugin_groups & disabled_groups:+ return True+ return False++def _allowed_tool_types() -> set[str]:- """Tool nodes the LLM may spawn -- excludes the builder + masterSkill."""+ """Tool node types the LLM may spawn via ``add_tool``.++ Includes:+ - Pure ToolNode plugins (``component_kind == 'tool'``).+ - Dual-purpose ActionNode plugins with ``usable_as_tool=True``+ (e.g. ``twitterSearch``, ``googleGmail``, ``pythonExecutor``,+ ``fileRead``). These are the bulk of the actually-useful tools;+ excluding them was the source of "only a few nodes visible" reports.+ - Excludes chat-model plugins (``component_kind == 'model'``) even+ when they carry ``usable_as_tool=True`` — models are configured+ via input-model handles, not spawned as agent tools.++ Excludes ``_DENIED_TOOL_TYPES`` (recursion guard: no agentBuilder /+ masterSkill spawnable) AND anything the operator has marked+ ``disabled_nodes`` / ``disabled_groups`` in node_allowlist.json.+ """+ config = _allowlist_config()+ out: set[str] = set()+ for ntype, cls in registered_node_classes().items():+ if ntype in _DENIED_TOOL_TYPES:+ continue+ kind = getattr(cls, "component_kind", "")+ is_tool = kind == "tool"+ is_dual_purpose = bool(getattr(cls, "usable_as_tool", False)) and kind != "model"+ if not (is_tool or is_dual_purpose):+ continue+ if _is_blocked_by_allowlist(cls, ntype, config):+ continue+ out.add(ntype)+ return out+++def _allowed_subagent_types() -> set[str]:+ """Agent types the LLM may spawn as teammates. Honors+ ``disabled_nodes`` + ``disabled_groups`` from node_allowlist.json+ so the same config governs both UI palette and LLM spawnable set.+ """+ config = _allowlist_config()return {ntypefor ntype, cls in registered_node_classes().items()- if getattr(cls, "component_kind", "") == "tool" and ntype not in _DENIED_TOOL_TYPES+ if getattr(cls, "component_kind", "") == "agent"+ and not _is_blocked_by_allowlist(cls, ntype, config)}-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 _mint_node_id(prefix: str) -> str:+ """Mint a fresh node id sharing the convention used by+ :func:`services.workflow_import.remap_node_ids` and the frontend's+ ``client/src/lib/workflowOps.ts::newId``.++ The minted id is stamped onto ``add_node`` ops as ``minted_id`` so+ the FE applier adopts it instead of generating its own — keeping+ the BE-side ``tool_node_id`` (used for ``update_node_status``+ broadcasts in the rebind path) aligned with the React Flow node id+ the canvas glows on.+ """+ import secrets+ import time++ return f"{prefix}-{int(time.time() * 1000)}-{secrets.token_hex(3)}"++def _summary_suffix(ctx: NodeContext) -> str:"""Trailing sentence on agentBuilder op summaries.@@ -152,6 +359,131 @@ def _skill_folder_exists(skill_folder: str) -> bool:return False+# ----------------------------------------------------------------------------+# Duplicate-detection + catalogue helpers+# ----------------------------------------------------------------------------+++def _find_wired_types(+ ctx: NodeContext,+ target_node_id: str,+ target_handle: str,+) -> Dict[str, str]:+ """Walk ``ctx.edges`` for edges arriving at ``target_node_id`` on+ ``target_handle`` and return ``{source_node_type: source_node_id}``+ for every match.++ Used by ``add_tool`` / ``add_subagent`` to detect already-wired+ nodes before spawning duplicates. Sync + ctx-only (no DB) — same+ lightweight pattern as :func:`_resolve_caller`.+ """+ nodes_by_id = {n.get("id"): n for n in (ctx.nodes or []) if n.get("id")}+ wired: Dict[str, str] = {}+ for edge in ctx.edges or []:+ if edge.get("target") != target_node_id:+ continue+ if edge.get("targetHandle") != target_handle:+ continue+ source_id = edge.get("source")+ if not source_id:+ continue+ source_node = nodes_by_id.get(source_id)+ if source_node is None:+ continue+ source_type = source_node.get("type")+ if source_type:+ wired[source_type] = source_id+ return wired+++def _catalogue_tools() -> List[Dict[str, Any]]:+ """Enrich :func:`_allowed_tool_types` with display_name + description+ so ``inspect_canvas`` can hand the LLM the FULL spawnable set with+ enough context to pick the right one (instead of guessing or+ waiting for an error-message hint capped at 10 examples)."""+ registry = registered_node_classes()+ catalogue: List[Dict[str, Any]] = []+ for ntype in sorted(_allowed_tool_types()):+ cls = registry.get(ntype)+ if cls is None:+ continue+ catalogue.append(+ {+ "type": ntype,+ "display_name": getattr(cls, "display_name", "") or ntype,+ "description": getattr(cls, "tool_description", "") or getattr(cls, "description", "") or "",+ }+ )+ return catalogue+++def _catalogue_agents() -> List[Dict[str, Any]]:+ """Same shape as :func:`_catalogue_tools` for the agent registry —+ fed into ``inspect_canvas`` so ``add_subagent`` knows the full set+ of delegate-able agent types."""+ registry = registered_node_classes()+ catalogue: List[Dict[str, Any]] = []+ for ntype in sorted(_allowed_subagent_types()):+ cls = registry.get(ntype)+ if cls is None:+ continue+ catalogue.append(+ {+ "type": ntype,+ "display_name": getattr(cls, "display_name", "") or ntype,+ "description": getattr(cls, "description", "") or "",+ }+ )+ return catalogue+++def _disabled_skill_folders() -> set[str]:+ """Skill-folder blocklist from node_allowlist.json. Top-level+ folder names whose every skill is hidden from the catalogue."""+ return set(_allowlist_config().get("disabled_skill_folders") or [])+++def _catalogue_skills() -> List[Dict[str, Any]]:+ """Enumerate every skill the agentBuilder can enable via+ ``add_skill``. Reuses the existing :class:`SkillLoader` singleton+ (populated at startup) so we don't re-walk SKILL.md frontmatter+ on every ``inspect_canvas`` call. Honors ``disabled_skill_folders``+ from node_allowlist.json so the LLM-facing catalogue matches the+ UI palette's filter.+ """+ try:+ from services.skill_loader import get_skill_loader++ loader = get_skill_loader()+ registry = loader._registry # SkillMetadata is the public type; the dict is a frozen-at-startup snapshot+ except Exception as exc: # noqa: BLE001 — defensive: catalogue is best-effort+ logger.debug("[agentBuilder] skill catalogue load failed: %s", exc)+ return []+ blocked_folders = _disabled_skill_folders()+ catalogue: List[Dict[str, Any]] = []+ for name, meta in sorted(registry.items()):+ # SkillMetadata.path is the leaf SKILL.md directory; the+ # blocklist matches against any ancestor folder under+ # server/skills/ (e.g. "android_agent" blocks every skill+ # under server/skills/android_agent/).+ if meta.path is not None and blocked_folders:+ try:+ ancestors = {p.name for p in meta.path.parents}+ if ancestors & blocked_folders:+ continue+ except Exception: # noqa: BLE001+ pass+ folder = meta.path.name if meta.path is not None else name+ catalogue.append(+ {+ "folder": folder,+ "name": meta.name,+ "description": meta.description or "",+ }+ )+ return catalogue++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}@@ -289,6 +621,14 @@ class AgentBuilderOutput(BaseModel):nodes: Optional[List[Dict[str, Any]]] = Noneedges: Optional[List[Dict[str, Any]]] = Noneyou: Optional[Dict[str, Any]] = None+ # Registry catalogues — populated by ``inspect_canvas`` so the LLM+ # sees the FULL spawnable set instead of guessing or waiting for an+ # error-message hint capped at 10 examples. Each entry carries+ # display_name + description so the model can pick the right one+ # in a single response.+ available_tools: Optional[List[Dict[str, Any]]] = None+ available_agents: Optional[List[Dict[str, Any]]] = None+ available_skills: Optional[List[Dict[str, Any]]] = None# create_workflow extrasworkflow_id: Optional[str] = None@@ -320,7 +660,19 @@ class AgentBuilderNode(ToolNode):# of the parent AI Agent.needs_canvas = Truetool_name = "agent_builder"- tool_description = "Inspect and modify the workflow canvas at runtime. Operations: inspect_canvas (read current nodes/edges), spawn_tool (add a tool node + wire it), enable_skill (add a skill folder to a connected masterSkill), add_delegate_agent (add a specialized agent), create_workflow (spawn a brand-new workflow)."+ tool_description = (+ "Inspect and modify the workflow canvas at runtime. ALWAYS call "+ "inspect_canvas FIRST — its response includes the full catalogue "+ "of every tool, agent, and skill you can spawn (with display_name "+ "and description), plus the current canvas state. Operations: "+ "inspect_canvas (read current nodes/edges + available_tools / "+ "available_agents / available_skills catalogues), add_tool (spawn "+ "a tool node + wire it; idempotent if already wired), add_skill "+ "(enable a skill folder on a connected masterSkill; idempotent if "+ "already enabled), add_subagent (add a delegate agent; idempotent "+ "if already wired). NOTE: create_workflow is temporarily disabled "+ "— mutate the current workflow instead."+ )handles = ({"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},{"name": "output-tool", "kind": "output", "position": "top", "label": "Tool", "role": "tools"},@@ -386,6 +738,9 @@ class AgentBuilderNode(ToolNode):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]+ available_tools = _catalogue_tools()+ available_agents = _catalogue_agents()+ available_skills = _catalogue_skills()parts = [f"{len(nodes)} nodes"]if tools:types = ", ".join(sorted({c["source_type"] or "?" for c in tools}))@@ -394,6 +749,10 @@ class AgentBuilderNode(ToolNode):parts.append(f"{len(skills)} skill source(s) wired")if teammates:parts.append(f"{len(teammates)} teammate(s)")+ parts.append(+ f"{len(available_tools)} tool / {len(available_agents)} agent / "+ f"{len(available_skills)} skill types available to spawn"+ )return AgentBuilderOutput(operation="inspect_canvas",@@ -401,6 +760,9 @@ class AgentBuilderNode(ToolNode):nodes=node_summaries,edges=edge_summaries,you={"node_id": caller_id, "incoming": incoming, "outgoing": outgoing},+ available_tools=available_tools,+ available_agents=available_agents,+ available_skills=available_skills,)# ---- add_tool ---------------------------------------------------------@@ -421,23 +783,44 @@ class AgentBuilderNode(ToolNode):)allowed = _allowed_tool_types()if node_type not in allowed:- sample = ", ".join(sorted(allowed)[:10])+ all_types = ", ".join(sorted(allowed))return AgentBuilderOutput(operation="add_tool",- summary=(f"add_tool: '{node_type}' is not an allowed tool type. " f"Examples of allowed types: {sample}..."),+ summary=(+ f"add_tool: '{node_type}' is not an allowed tool type. "+ f"Allowed types: {all_types}. "+ "Call inspect_canvas for the full catalogue with descriptions."+ ),operations=[],)caller_id = _resolve_caller(ctx)+ # Idempotent duplicate check — if this tool type is already wired+ # to the caller's input-tools handle, reuse the existing instance+ # rather than spawning another. Surfaces the existing node id in+ # the summary so the LLM knows it CAN call the tool.+ existing_tools = _find_wired_types(ctx, caller_id, _TOOL_HANDLE)+ if node_type in existing_tools:+ return AgentBuilderOutput(+ operation="add_tool",+ summary=(+ f"Tool '{node_type}' is already wired to you "+ f"(node id={existing_tools[node_type]}). Reusing existing instance."+ ),+ operations=[],+ )client_ref = f"new_{node_type}"+ minted_id = _mint_node_id(node_type)+ add_node_op = workflow_ops.add_node(+ client_ref,+ node_type,+ {},+ label=node_type,+ position=workflow_ops.anchored(caller_id, offset_x=200, offset_y=80),+ )+ add_node_op["minted_id"] = minted_id # FE applier adopts; BE rebind reads.ops = [- workflow_ops.add_node(- client_ref,- node_type,- {},- label=node_type,- position=workflow_ops.anchored(caller_id, offset_x=200, offset_y=80),- ),+ add_node_op,workflow_ops.add_edge({"client_ref": client_ref},caller_id,@@ -492,6 +875,19 @@ class AgentBuilderNode(ToolNode):if master_skill:existing = ((master_skill.get("data") or {}).get("parameters") or {}).get("skills_config") or {}+ # Idempotent: skill already enabled in this masterSkill's+ # config — no-op + tell the LLM the skill is already active+ # so it doesn't loop trying to enable.+ if existing.get(skill, {}).get("enabled"):+ return AgentBuilderOutput(+ operation="add_skill",+ summary=(+ f"Skill '{skill}' is already enabled on your "+ f"Master Skill (node id={master_skill['id']}). "+ "No change needed."+ ),+ operations=[],+ )new_config = _toggle_skill(existing, skill, True)ops = [workflow_ops.set_node_parameters(@@ -508,14 +904,17 @@ class AgentBuilderNode(ToolNode):new_config = _toggle_skill(None, skill, True)client_ref = "new_master_skill"+ minted_id = _mint_node_id(_MASTER_SKILL_TYPE)+ master_skill_op = 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),+ )+ master_skill_op["minted_id"] = minted_idops = [- 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),- ),+ master_skill_op,workflow_ops.add_edge({"client_ref": client_ref},caller_id,@@ -561,10 +960,14 @@ class AgentBuilderNode(ToolNode):)allowed = _allowed_subagent_types()if agent_type not in allowed:- sample = ", ".join(sorted(allowed)[:10])+ all_types = ", ".join(sorted(allowed))return AgentBuilderOutput(operation="add_subagent",- summary=(f"add_subagent: '{agent_type}' is not an allowed agent " f"type. Examples: {sample}..."),+ summary=(+ f"add_subagent: '{agent_type}' is not an allowed agent type. "+ f"Allowed types: {all_types}. "+ "Call inspect_canvas for the full catalogue with descriptions."+ ),operations=[],)if _is_team_lead(agent_type):@@ -574,15 +977,30 @@ class AgentBuilderNode(ToolNode):operations=[],)+ # Idempotent duplicate check — see add_tool above for rationale.+ existing_teammates = _find_wired_types(ctx, caller_id, _TEAMMATES_HANDLE)+ if agent_type in existing_teammates:+ return AgentBuilderOutput(+ operation="add_subagent",+ summary=(+ f"Teammate '{agent_type}' is already wired to you "+ f"(node id={existing_teammates[agent_type]}). Reusing existing instance."+ ),+ operations=[],+ )+client_ref = f"new_{agent_type}"+ minted_id = _mint_node_id(agent_type)+ add_node_op = workflow_ops.add_node(+ client_ref,+ agent_type,+ {},+ label=agent_type,+ position=workflow_ops.anchored(caller_id, offset_x=300, offset_y=200),+ )+ add_node_op["minted_id"] = minted_idops = [- workflow_ops.add_node(- client_ref,- agent_type,- {},- label=agent_type,- position=workflow_ops.anchored(caller_id, offset_x=300, offset_y=200),- ),+ add_node_op,workflow_ops.add_edge({"client_ref": client_ref},caller_id,@@ -611,6 +1029,19 @@ class AgentBuilderNode(ToolNode):workflow_name=params.workflow_name,workflow_description=params.workflow_description,)+ # Temporary disable — flip ``_CREATE_WORKFLOW_ENABLED`` at the+ # module top to restore. The body below is intact so the+ # feature can be re-enabled without rewriting validation ++ # persistence logic.+ if not _CREATE_WORKFLOW_ENABLED:+ return AgentBuilderOutput(+ operation="create_workflow",+ summary=(+ "create_workflow is temporarily disabled. Mutate the "+ "current workflow instead — add_tool / add_skill / "+ "add_subagent are still available."+ ),+ )name = (params.workflow_name or "").strip()if not name:return AgentBuilderOutput(diff --git a/server/services/ai.py b/server/services/ai.pyindex efae9f1d..37ad52da 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1858,10 +1858,19 @@ class AIService:if not node_type:continuecls = get_node_class(node_type)- if cls is None or getattr(cls, "component_kind", "") != "tool":+ if cls is None:+ continue+ # Match the catalogue filter — pure ToolNode OR+ # dual-purpose ActionNode (usable_as_tool=True),+ # excluding chat models. Without this the rebind+ # silently drops twitterSearch / googleGmail /+ # pythonExecutor etc. and the LLM tries to call+ # tools it never got bound to.+ _kind = getattr(cls, "component_kind", "")+ if not (_kind == "tool" or (bool(getattr(cls, "usable_as_tool", False)) and _kind != "model")):continuetool_info = {- "node_id": op.get("client_ref") or f"new_{node_type}",+ "node_id": op.get("minted_id") or op.get("client_ref") or f"new_{node_type}","node_type": node_type,"parameters": op.get("parameters") or {},"label": op.get("label") or node_type,@@ -2366,10 +2375,18 @@ class AIService:if not node_type:continuecls = get_node_class(node_type)- if cls is None or getattr(cls, "component_kind", "") != "tool":+ if cls is None:+ continue+ # Match the catalogue filter — pure ToolNode OR+ # dual-purpose ActionNode (usable_as_tool=True),+ # excluding chat models. Without this the rebind+ # silently drops twitterSearch / googleGmail /+ # pythonExecutor etc.+ _kind = getattr(cls, "component_kind", "")+ if not (_kind == "tool" or (bool(getattr(cls, "usable_as_tool", False)) and _kind != "model")):continuetool_info = {- "node_id": op.get("client_ref") or f"new_{node_type}",+ "node_id": op.get("minted_id") or op.get("client_ref") or f"new_{node_type}","node_type": node_type,"parameters": op.get("parameters") or {},"label": op.get("label") or node_type,diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex 40d7fc85..38ba9803 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -708,6 +708,7 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:{"tools": [<tool_payload entry>, ...]}"""+ from core.container import containerfrom services.node_registry import get_node_classai_service = container.ai_service()@@ -721,10 +722,20 @@ async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:if not node_type:continuecls = get_node_class(node_type)- if cls is None or getattr(cls, "component_kind", "") != "tool":+ if cls is None:+ continue+ kind = getattr(cls, "component_kind", "")+ # Match the catalogue filter: pure ToolNode (kind=='tool') OR+ # dual-purpose ActionNode with usable_as_tool=True (the bulk of+ # spawnable plugins — twitterSearch / googleGmail / pythonExecutor+ # / fileRead / etc.). Exclude chat-model plugins even when+ # usable_as_tool=True.+ is_tool = kind == "tool"+ is_dual_purpose = bool(getattr(cls, "usable_as_tool", False)) and kind != "model"+ if not (is_tool or is_dual_purpose):continuetool_info: Dict[str, Any] = {- "node_id": op.get("client_ref") or f"new_{node_type}",+ "node_id": op.get("minted_id") or op.get("client_ref") or f"new_{node_type}","node_type": node_type,"parameters": op.get("parameters") or {},"label": op.get("label") or node_type,diff --git a/server/services/workflow_ops.py b/server/services/workflow_ops.pyindex e5011c7f..a5758017 100644--- a/server/services/workflow_ops.py+++ b/server/services/workflow_ops.py@@ -86,6 +86,10 @@ class AddNodeOp(TypedDict, total=False):parameters: Dict[str, Any]label: strposition: PositionSpec+ # BE-minted node id adopted by the FE applier verbatim. Set by+ # agentBuilder so the rebind path's status broadcasts route to the+ # same React Flow node id the canvas renders the new node under.+ minted_id: strclass AddEdgeOp(TypedDict, total=False):diff --git a/server/skills/assistant/agent-builder-skill/SKILL.md b/server/skills/assistant/agent-builder-skill/SKILL.mdindex 79111433..b0a8b383 100644--- a/server/skills/assistant/agent-builder-skill/SKILL.md+++ b/server/skills/assistant/agent-builder-skill/SKILL.md@@ -4,7 +4,7 @@ description: How to use the Agent Builder tool's five canvas-mutation operationsallowed-tools: "agentBuilder"metadata:author: machina- version: "2.0"+ version: "3.0"category: autonomous---@@ -16,60 +16,64 @@ canvas-mutation operations via the `operation` field:| `operation` value | Purpose ||---|---|-| `inspect_canvas` | Read-only view of nodes, edges, and what's already wired to you. ALWAYS call this first. |-| `add_tool` | Spawn a tool node + wire it to your `input-tools` handle. |-| `add_skill` | Toggle a skill on your Master Skill (auto-creates one if missing). |-| `add_subagent` | Team-leads only -- spawn a delegate agent + wire to your `input-teammates`. |-| `create_workflow` | Persist a fresh empty workflow + return its id. Doesn't switch the user's view. |+| `inspect_canvas` | Read-only view of the canvas PLUS the full catalogue of every tool, agent, and skill you can spawn. ALWAYS call this first. |+| `add_tool` | Spawn a tool node + wire it to your `input-tools` handle. Idempotent — already-wired tools return success with no change. |+| `add_skill` | Toggle a skill on your Master Skill (auto-creates one if missing). Idempotent — already-enabled skills return success with no change. |+| `add_subagent` | Team-leads only — spawn a delegate agent + wire to your `input-teammates`. Idempotent — already-wired teammates return success with no change. |+| `create_workflow` | **Temporarily disabled.** Mutate the current workflow instead. |Every call is `agentBuilder({operation: "<one-of-above>", ...op-specific-fields})`. There are no separate tools.## The cardinal rule**Call `agentBuilder({operation: "inspect_canvas"})` BEFORE any-mutation operation.** Without it you cannot tell whether a tool /-skill / subagent is already wired and will create duplicates.-Workflow becomes cluttered and your tool list confused.+mutation.** The response carries the full registry of spawnable types+(plus the live canvas) so you can pick the right one in a single+follow-up call instead of guessing. Skipping `inspect_canvas` means+you're flying blind on what's available.-The `inspect_canvas` summary tells you:-- which tools are already connected to your `input-tools`-- whether a Master Skill is wired to your `input-skill` (and what- skills it has enabled)-- whether you have any teammate delegates (`input-teammates`)+## Hot rebind (default: ON)-Pick the smallest action that solves the problem. If the tool you-need is already on your canvas, USE IT -- don't add a duplicate.+By default, tools / skills / teammates you spawn become callable+**in the same run, on your very next response**. The mutation summary+ends with *"Available immediately — call it in your next response."*+Take this literally: you may invoke the new tool right away. No need+to tell the user "send another message".-## Soft-reload semantics (important)+If the user has disabled the **"Auto-Rebind Tools After Canvas Changes"**+toggle in Settings, mutation summaries end with *"Available on your+next turn."* In that case the new wiring is staged but not callable+this run — tell the user and stop calling that tool.-The agent loop binds your tool list at the start of each invocation.-Tools / skills / teammates added mid-run **do NOT become callable-in the current run**. They become available on your **next-invocation** (next chat message, next workflow trigger, next call).--Each mutation returns a summary ending in "available on your next-turn". Take this literally. Do NOT loop trying to call something-you just added -- it isn't there yet. Tell the user what you added-and that they can use it on the next message.+The summary text is your signal. Read it.## Operation reference### `operation: "inspect_canvas"`No additional fields. Returns:+```json{"operation": "inspect_canvas",+ "summary": "<live counts: nodes, tools wired, available types>","nodes": [{ "id", "type", "label", "key_params" }, ...],"edges": [{ "source", "target", "source_handle", "target_handle" }, ...],"you": {"node_id": "agent-1","incoming": [...], "outgoing": [...]},- "summary": "5 nodes, 1 tool(s) wired to you (httpRequest), no skills."+ "available_tools": [{ "type", "display_name", "description" }, ...],+ "available_agents": [{ "type", "display_name", "description" }, ...],+ "available_skills": [{ "folder", "name", "description" }, ...]}```+- `available_tools` — every value `add_tool({node_type: ...})` will accept, with descriptions.+- `available_agents` — every value `add_subagent({agent_type: ...})` will accept (team-leads only).+- `available_skills` — every value `add_skill({skill_folder: ...})` will accept.+- `you.incoming` — connections wired TO your handles. Use this to see what tools / skills / teammates you already have.+API keys, prompts, and other secrets are **stripped** from`key_params`. Only safe planner-relevant fields surface(`provider`, `model`, `operation`, `url`, `query`).@@ -78,89 +82,112 @@ API keys, prompts, and other secrets are **stripped** fromRequired field: `node_type` (string).-Spawns a tool node and wires it to your `input-tools`. Allowed-types are anything registered with `component_kind="tool"` ---typically things like `httpRequest`, `braveSearch`,-`pythonExecutor`, etc. (NOT `agentBuilder` itself; NOT-`masterSkill`, which is managed via `add_skill` instead.)+Spawns a tool node and wires it to your `input-tools` handle. Pick+`node_type` from `inspect_canvas.available_tools`.++**Idempotency**: if a tool of this exact type is already wired to+you, `add_tool` returns success with `operations: []` and a summary+like *"Tool 'httpRequest' is already wired (node id=…). Reusing+existing instance."* Don't loop trying again — the tool is callable.If the tool has a paired teaching skill, the auto-add-skill-handler enables it too -- no separate `add_skill` call needed.+handler enables it too — no separate `add_skill` call needed.### `operation: "add_skill"`Required field: `skill_folder` (string).-Enables a skill on your Master Skill. If you don't have a Master-Skill connected to `input-skill` yet, one is created and wired for-you. The skill folder must exist under `server/skills/**`-(e.g. `http-request-skill`, `memory-skill`, `python-skill`).+Enables a skill on your Master Skill. Pick `skill_folder` from+`inspect_canvas.available_skills`. If no Master Skill is wired to+your `input-skill` yet, one is created and wired automatically.-The skill's `SKILL.md` instructions become part of your system-message on your next turn.+**Idempotency**: if the skill is already `enabled=True` in your+Master Skill's config, `add_skill` returns success with `operations: []`+and *"Skill 'X' is already enabled on your Master Skill. No change+needed."*### `operation: "add_subagent"`Required field: `agent_type` (string).-**Team-leads only** (`orchestrator_agent`, `ai_employee`).-Spawns a specialized agent (`coding_agent`, `web_agent`,-`task_agent`, etc.) and wires it to your `input-teammates`-handle. The new agent appears as a `delegate_to_<name>` tool-on your next turn.+**Team-leads only** (`orchestrator_agent`, `ai_employee`). Pick+`agent_type` from `inspect_canvas.available_agents`. Spawns a+specialized agent (`coding_agent`, `web_agent`, `task_agent`, etc.)+and wires it to your `input-teammates` handle. The new agent appears+as a `delegate_to_<name>` tool on your next turn.-The new agent starts with empty configuration -- the user will-need to set its provider/model after the run. Mention this in your-response.+**Idempotency**: if a teammate of this exact type is already wired+to you, `add_subagent` returns *"Teammate 'X' is already wired+(node id=…). Reusing existing instance."*-### `operation: "create_workflow"`+The new agent starts with empty configuration — the user will need+to set its provider/model after the run. Mention this in your+response.-Required field: `workflow_name` (string).-Optional field: `workflow_description` (string).+### `operation: "create_workflow"` — temporarily disabled-Persists a fresh empty workflow with a single Start node and-returns its `workflow_id`. The user's current view does NOT-change; the frontend toasts a "Switch" link.+This operation is currently disabled. Calling it returns a polite+"temporarily disabled" summary; no workflow is created. Mutate the+current workflow instead via `add_tool` / `add_skill` /+`add_subagent`.-Use sparingly. Prefer mutating the current workflow over creating-new ones. Good cases for `create_workflow`:-- Templating / saving a solved pattern as a starting point.-- Splitting work into a separate workflow when the current one- is getting too large.+## Worked examples-## Worked example+### Adding a new tool and using it immediatelyUser: "Search the web for current weather in Tokyo and tell me."```1. agentBuilder({operation: "inspect_canvas"})- -> "1 nodes, no tool(s) wired to you, no skills."- You see no web-search tool exists. Plan: add one.+ → summary: "1 nodes, no tool(s) wired to you, 4 tool / 18 agent / 62 skill types available to spawn."+ → available_tools: [..., {type: "duckduckgoSearch", display_name: "DuckDuckGo Search", description: "..."}, ...]+ You see no web-search tool wired and one in the catalogue.++2. agentBuilder({operation: "add_tool", node_type: "duckduckgoSearch"})+ → "Added 'duckduckgoSearch' as a tool. Available immediately — call it in your next response."++3. duckduckgoSearch({query: "Tokyo weather today"})+ → search results++4. Tell the user the weather.+```++### Handling an already-wired tool++User: "Add the calculator tool and compute 17 + 25."++```+1. agentBuilder({operation: "inspect_canvas"})+ → you.incoming includes a tool wired with source_type "calculatorTool".++2. agentBuilder({operation: "add_tool", node_type: "calculatorTool"})+ → "Tool 'calculatorTool' is already wired to you (node id=calc-1). Reusing existing instance."+ → operations: []-2. agentBuilder({operation: "add_tool", node_type: "braveSearch"})- -> "Added 'braveSearch' as a tool. Available on your next turn."+3. calculator({a: 17, b: 25, op: "add"}) ← already callable; no rebind needed+ → 42-3. Reply to the user:- "I've added a Brave Search tool to my toolset. Send me the same- request on your next message and I'll search for the Tokyo- weather."+4. Tell the user the answer.```-DO NOT try to call `brave_search` in the same turn -- it's not in-your tool list yet. Just tell the user it's ready for next turn.+You did NOT need to retry `add_tool` or wait for "next turn" — the+existing instance is callable right now.## What NOT to do-- **Don't skip `inspect_canvas`**. Always run it first; it's- read-only and cheap.-- **Don't add a tool you already have**. The inspect summary tells- you what's wired.-- **Don't loop on freshly-added tools**. They're not callable until- next invocation.+- **Don't skip `inspect_canvas`**. It's read-only, cheap, and gives+ you the full catalogue + canvas state in one call.+- **Don't guess `node_type` / `agent_type` / `skill_folder` values.**+ Pick from the catalogues returned by `inspect_canvas`.+- **Don't retry `add_tool` / `add_skill` / `add_subagent` on success+ with `operations: []`.** That's an idempotent success, not a+ failure. The existing instance is callable.- **Don't add `agentBuilder` to yourself via `add_tool`** (rejected- -- avoids recursion; `agentBuilder` is excluded from the allowed- tool types).-- **Don't spawn another team-lead** as a subagent (rejected --+ — avoids recursion).+- **Don't spawn another team-lead** as a subagent (rejected —team-leads delegate to specialists, not to other team-leads).-- **Don't call `create_workflow`** unless the user explicitly asks- to start a fresh workflow.+- **Don't call `create_workflow`** — it's temporarily disabled and+ will return a no-op summary. Mutate the current workflow instead.+- **Don't ignore the "Available on your next turn" wording.** If+ you see it (toggle is OFF), the tool is staged but NOT callable+ this run. Tell the user and stop.diff --git a/server/tests/nodes/test_agent_builder.py b/server/tests/nodes/test_agent_builder.pyindex c47248a1..3d6556b6 100644--- a/server/tests/nodes/test_agent_builder.py+++ b/server/tests/nodes/test_agent_builder.py@@ -225,6 +225,33 @@ class TestAddTool:# → the LLM is told the new tool is callable in the same turn.assert "Available immediately" in result.summary+ async def test_add_node_op_carries_minted_id_for_fe_alignment(self):+ """The ``minted_id`` field is the contract that keeps the+ BE-side tool_node_id (used for status broadcasts in the rebind+ path) aligned with the React Flow node id the FE applier+ renders under. Without it the canvas node won't glow when the+ rebound tool runs because the broadcast target id never+ matches a real node."""+ 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),+ ):+ result = await node.add_tool(ctx, params)++ add_node_op = result.operations[0]+ assert add_node_op["type"] == "add_node"+ assert "minted_id" in add_node_op, "add_tool must stamp minted_id on the add_node op"+ # Convention: ``{type}-{ms}-{salt}`` — same shape as+ # services.workflow_import.remap_node_ids + frontend newId().+ assert add_node_op["minted_id"].startswith("httpRequest-")+ parts = add_node_op["minted_id"].split("-")+ assert len(parts) == 3, "minted_id must be 3 segments: type-timestamp-salt"+async def test_summary_branches_on_auto_rebind_flag(self):"""When the user disables the "Auto-Rebind Tools After CanvasChanges" toggle, the operation summary must read@@ -423,7 +450,35 @@ class TestAddSubagent:class TestCreateWorkflow:- async def test_rejects_empty_name(self):+ """create_workflow is temporarily disabled. The first test locks+ the disabled default; the remaining tests flip the+ ``_CREATE_WORKFLOW_ENABLED`` flag so the underlying implementation+ keeps being exercised — when the operator re-enables it, no test+ rewrite needed."""++ async def test_disabled_by_default(self):+ """With the temporary feature flag OFF, ``create_workflow``+ returns a polite no-op summary regardless of the workflow_name+ param. No DB calls, no workflow created."""+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(+ operation="create_workflow",+ workflow_name="Should Not Be Created",+ )++ # Ensure the flag is in its default OFF state (defensive — the+ # constant lives at module top so this also catches an+ # accidental commit of `_CREATE_WORKFLOW_ENABLED = True`).+ assert ab._CREATE_WORKFLOW_ENABLED is False, "Temporary disable flag must default to False"++ result = await node.create_workflow(ctx, params)++ assert result.workflow_id is None+ assert "temporarily disabled" in result.summary.lower()++ async def test_rejects_empty_name(self, monkeypatch):+ monkeypatch.setattr(ab, "_CREATE_WORKFLOW_ENABLED", True)node = ab.AgentBuilderNode()ctx = _make_ctx()params = ab.AgentBuilderParams(operation="create_workflow", workflow_name="")@@ -433,7 +488,8 @@ class TestCreateWorkflow:assert result.workflow_id is Noneassert "workflow_name is required" in result.summary- async def test_persists_via_database_and_returns_id(self):+ async def test_persists_via_database_and_returns_id(self, monkeypatch):+ monkeypatch.setattr(ab, "_CREATE_WORKFLOW_ENABLED", True)node = ab.AgentBuilderNode()ctx = _make_ctx()params = ab.AgentBuilderParams(@@ -461,7 +517,8 @@ class TestCreateWorkflow:assert "My_New_Workflow_1" in result.summarymock_db.save_workflow.assert_awaited_once()- async def test_returns_failure_summary_when_persist_fails(self):+ async def test_returns_failure_summary_when_persist_fails(self, monkeypatch):+ monkeypatch.setattr(ab, "_CREATE_WORKFLOW_ENABLED", True)node = ab.AgentBuilderNode()ctx = _make_ctx()params = ab.AgentBuilderParams(@@ -480,3 +537,434 @@ class TestCreateWorkflow:assert result.workflow_id is Noneassert "failed to persist" in result.summary+++# ============================================================================+# Catalogue visibility — inspect_canvas exposes the FULL registry of+# tools / agents / skills so the LLM can pick the right one in a single+# response instead of probing through error messages.+# ============================================================================+++def _node_class_full(+ component_kind: str,+ display_name: str = "",+ description: str = "",+ tool_description: str = "",+ *,+ usable_as_tool: bool = False,+ group: tuple = (),+) -> SimpleNamespace:+ """Like ``_node_class`` but carries every attr the catalogue helpers+ read (``component_kind`` / ``usable_as_tool`` / ``group`` /+ ``display_name`` / ``description`` / ``tool_description``)."""+ return SimpleNamespace(+ component_kind=component_kind,+ display_name=display_name,+ description=description,+ tool_description=tool_description,+ usable_as_tool=usable_as_tool,+ group=group,+ )+++class TestCatalogueVisibility:+ async def test_inspect_canvas_includes_available_tools(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")+ registry = {+ "httpRequest": _node_class_full("tool", "HTTP Request", "Make HTTP requests", ""),+ "braveSearch": _node_class_full("tool", "Brave Search", "Search the web", "Search the web via Brave"),+ "calculatorTool": _node_class_full("tool", "Calculator", "Arithmetic"),+ "agentBuilder": _node_class_full("tool", "Agent Builder"), # in DENIED set+ "masterSkill": _node_class_full("tool", "Master Skill"), # in DENIED set+ }++ with patch.object(ab, "registered_node_classes", return_value=registry):+ result = await node.inspect_canvas(ctx, params)++ assert result.available_tools is not None+ types = {t["type"] for t in result.available_tools}+ assert types == {"httpRequest", "braveSearch", "calculatorTool"}, (+ "available_tools must include every component_kind='tool' plugin "+ "minus the denylist (agentBuilder, masterSkill)."+ )++ async def test_available_tools_carry_metadata(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")+ registry = {+ "httpRequest": _node_class_full("tool", "HTTP Request", "Generic description", "LLM-facing description"),+ }++ with patch.object(ab, "registered_node_classes", return_value=registry):+ result = await node.inspect_canvas(ctx, params)++ entry = next(t for t in result.available_tools if t["type"] == "httpRequest")+ assert entry["display_name"] == "HTTP Request"+ # tool_description wins over description so the LLM sees the+ # spawnable-from-this-tool variant.+ assert entry["description"] == "LLM-facing description"++ async def test_inspect_canvas_includes_available_agents(self):+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")+ registry = {+ "coding_agent": _node_class_full("agent", "Coding Agent", "Writes code"),+ "web_agent": _node_class_full("agent", "Web Agent", "Browses the web"),+ "httpRequest": _node_class_full("tool", "HTTP Request"), # NOT an agent+ }++ with patch.object(ab, "registered_node_classes", return_value=registry):+ result = await node.inspect_canvas(ctx, params)++ types = {a["type"] for a in result.available_agents}+ assert types == {"coding_agent", "web_agent"}++ async def test_dual_purpose_plugins_in_available_tools(self):+ """Plugins like twitterSearch / googleGmail / pythonExecutor are+ ``component_kind='square'`` ActionNodes with ``usable_as_tool=True``.+ They form the bulk of useful LLM-callable tools; the catalogue+ MUST include them, not just the ~7 pure ToolNodes."""+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")+ registry = {+ "calculatorTool": _node_class_full("tool", "Calculator"), # pure ToolNode+ "twitterSearch": _node_class_full(+ "square", "Twitter Search", usable_as_tool=True, group=("social", "tool")+ ),+ "googleGmail": _node_class_full(+ "square", "Gmail", usable_as_tool=True, group=("google", "tool")+ ),+ "pythonExecutor": _node_class_full(+ "square", "Python Executor", usable_as_tool=True, group=("code", "tool")+ ),+ "openaiChatModel": _node_class_full(+ "model", "OpenAI", usable_as_tool=True, group=("model", "tool")+ ), # model — must be EXCLUDED+ }++ with patch.object(ab, "registered_node_classes", return_value=registry):+ result = await node.inspect_canvas(ctx, params)++ types = {t["type"] for t in (result.available_tools or [])}+ assert "calculatorTool" in types, "pure ToolNode plugins remain visible"+ assert "twitterSearch" in types, "dual-purpose plugins (usable_as_tool=True) must surface"+ assert "googleGmail" in types+ assert "pythonExecutor" in types+ assert "openaiChatModel" not in types, (+ "chat-model plugins must be excluded even when usable_as_tool=True "+ "— they're configured via input-model, not spawned as agent tools."+ )++ async def test_disabled_groups_excluded_from_available_tools(self):+ """``disabled_groups`` is a coarse blocklist — every plugin+ whose ``group`` tuple contains a disabled group name is hidden+ from the LLM's spawnable set. Mirrors the UI palette filter."""+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")+ registry = {+ "twitterSearch": _node_class_full(+ "square", "Twitter Search", usable_as_tool=True, group=("social", "tool")+ ),+ "emailSend": _node_class_full(+ "square", "Email Send", usable_as_tool=True, group=("email", "tool")+ ), # email group disabled+ "wifiAutomation": _node_class_full(+ "square", "WiFi", usable_as_tool=True, group=("android", "service")+ ), # android group disabled+ }+ from services import node_allowlist as nal++ def patched_get_config(self):+ return {+ "show_all": True,+ "enabled_nodes": [],+ "disabled_groups": ["android", "email"],+ "disabled_nodes": [],+ "disabled_credential_categories": [],+ "disabled_skill_folders": [],+ }++ with (+ patch.object(ab, "registered_node_classes", return_value=registry),+ patch.object(nal.NodeAllowlistService, "get_config", patched_get_config),+ ):+ result = await node.inspect_canvas(ctx, params)++ types = {t["type"] for t in (result.available_tools or [])}+ assert types == {"twitterSearch"}, (+ f"disabled_groups must exclude every plugin whose group tuple contains "+ f"a disabled group name (got {types})"+ )++ async def test_disabled_nodes_excluded_from_available_tools(self):+ """node_allowlist.json's ``disabled_nodes`` blocklist is the+ single source of truth for "what the LLM cannot spawn".+ Operators add an entry once and both the UI palette and the+ agentBuilder catalogue honor it (replaces the older+ per-callsite ``_DENIED_TOOL_TYPES``-only filter)."""+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")+ registry = {+ "httpRequest": _node_class_full("tool", "HTTP Request"),+ "taskManager": _node_class_full("tool", "Task Manager"), # disabled+ }+ # Mock the allowlist to mark taskManager as disabled.+ from services import node_allowlist as nal++ original_get_config = nal.NodeAllowlistService.get_config++ def patched_get_config(self):+ return {+ "show_all": True,+ "enabled_nodes": [],+ "disabled_groups": [],+ "disabled_nodes": ["taskManager"],+ "disabled_credential_categories": [],+ "disabled_skill_folders": [],+ }++ with (+ patch.object(ab, "registered_node_classes", return_value=registry),+ patch.object(nal.NodeAllowlistService, "get_config", patched_get_config),+ ):+ result = await node.inspect_canvas(ctx, params)++ types = {t["type"] for t in (result.available_tools or [])}+ assert "httpRequest" in types+ assert "taskManager" not in types, (+ "Disabled node types must be invisible to the LLM in inspect_canvas. "+ "If this fails, _allowed_tool_types isn't honoring the allowlist."+ )+ _ = original_get_config # silence unused-var lint++ def test_task_manager_disabled_in_allowlist_json(self):+ """End-to-end: the on-disk ``server/config/node_allowlist.json``+ marks ``taskManager`` as disabled, so the live+ ``_allowed_tool_types()`` excludes it. Locks the operator+ decision against accidental revert."""+ from services.node_allowlist import get_node_allowlist_service++ config = get_node_allowlist_service().get_config()+ assert "taskManager" in config["disabled_nodes"]+ # And the agentBuilder catalogue honors it.+ assert "taskManager" not in ab._allowed_tool_types()++ async def test_inspect_canvas_includes_available_skills(self):+ """available_skills must use the live SkillLoader registry. We+ don't mock the loader — agentBuilder reads it via the singleton+ so this is a smoke test that the integration works."""+ node = ab.AgentBuilderNode()+ ctx = _make_ctx()+ params = ab.AgentBuilderParams(operation="inspect_canvas")++ with patch.object(ab, "registered_node_classes", return_value={}):+ result = await node.inspect_canvas(ctx, params)++ # The SkillLoader populates 60+ skills under server/skills/.+ assert result.available_skills is not None+ assert len(result.available_skills) > 0, (+ "available_skills must surface the SkillLoader registry; the "+ "LLM can't pick a skill folder otherwise."+ )+ # Each entry has folder + name + description.+ for entry in result.available_skills:+ assert "folder" in entry+ assert "name" in entry+ assert "description" in entry+++# ============================================================================+# Duplicate detection — mutation ops are idempotent. Already-wired+# nodes / already-enabled skills return success with empty operations+# so the LLM doesn't loop trying again.+# ============================================================================+++class TestDbPersistence:+ """agentBuilder must persist canvas mutations to the DB via+ ``database.save_workflow`` so that:++ 1. The next chat-message trigger (next workflow run) sees the+ updated workflow.data instead of the stale snapshot. Without+ this, the LLM keeps re-spawning the same tools it already+ added in a prior run.+ 2. ``_find_wired_types`` duplicate detection works across runs+ because the persisted ``edges`` reflect the new wiring.+ """++ async def test_add_tool_persists_via_save_workflow(self):+ node = ab.AgentBuilderNode()+ edges = [_edge("ab-1", "agent-1", "input-tools")]+ ctx = _make_ctx(edges=edges, workflow_id="wf-test")+ params = ab.AgentBuilderParams(operation="add_tool", node_type="httpRequest")++ # Pre-mutation workflow snapshot.+ existing_workflow = SimpleNamespace(+ name="Test Workflow",+ slug="Test_Workflow_1",+ description="",+ data={"nodes": [{"id": "agent-1", "type": "aiAgent"}], "edges": []},+ )+ mock_db = MagicMock()+ mock_db.get_workflow = AsyncMock(return_value=existing_workflow)+ mock_db.save_workflow = AsyncMock(return_value=True)+ mock_container = MagicMock()+ mock_container.database.return_value = mock_db++ with (+ patch.object(ab, "registered_node_classes", return_value=_registry(httpRequest="tool")),+ patch("core.container.container", mock_container),+ ):+ result = await node.add_tool(ctx, params)++ # Tool was added (not duplicate) — broadcast + persist path fired.+ assert len(result.operations) == 2+ # save_workflow must be called with the mutated data dict containing+ # the new node + edge.+ mock_db.save_workflow.assert_awaited_once()+ save_kwargs = mock_db.save_workflow.await_args.kwargs+ new_data = save_kwargs["data"]+ new_nodes = new_data["nodes"]+ new_edges = new_data["edges"]+ assert any(n.get("type") == "httpRequest" for n in new_nodes), (+ "Persisted nodes must include the spawned httpRequest tool."+ )+ assert len(new_edges) == 1, "Persisted edges must include the new input-tools edge."+ # The persisted node id must match the minted_id surfaced on the+ # broadcast op so BE and FE views stay aligned across reload.+ add_node_op = result.operations[0]+ persisted_ids = {n.get("id") for n in new_nodes}+ assert add_node_op["minted_id"] in persisted_ids+++class TestDuplicateDetection:+ async def test_add_tool_is_idempotent_when_already_wired(self):+ """If the caller already has a node of the requested type wired+ via input-tools, ``add_tool`` returns empty operations + an+ "already wired" summary instead of spawning a duplicate."""+ node = ab.AgentBuilderNode()+ nodes = [+ _agent_node("agent-1"),+ {"id": "ab-1", "type": "agentBuilder", "data": {"label": "AB"}},+ {"id": "http-existing", "type": "httpRequest", "data": {"label": "HTTP"}},+ ]+ edges = [+ _edge("ab-1", "agent-1", "input-tools"),+ _edge("http-existing", "agent-1", "input-tools"),+ ]+ ctx = _make_ctx(nodes=nodes, 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 result.operations == []+ assert "already wired" in result.summary+ assert "http-existing" in result.summary # existing node id surfaced for the LLM+ mock_bcast.assert_not_awaited() # no canvas mutation fires++ async def test_add_tool_still_spawns_when_different_type_wired(self):+ """No false positives: if the caller has DIFFERENT tools wired,+ spawning a fresh type still proceeds normally."""+ node = ab.AgentBuilderNode()+ nodes = [+ _agent_node("agent-1"),+ {"id": "ab-1", "type": "agentBuilder", "data": {"label": "AB"}},+ {"id": "calc-1", "type": "calculatorTool", "data": {"label": "Calc"}},+ ]+ edges = [+ _edge("ab-1", "agent-1", "input-tools"),+ _edge("calc-1", "agent-1", "input-tools"),+ ]+ ctx = _make_ctx(nodes=nodes, edges=edges)+ params = ab.AgentBuilderParams(operation="add_tool", node_type="httpRequest")++ with (+ patch.object(ab, "registered_node_classes", return_value=_registry(httpRequest="tool", calculatorTool="tool")),+ patch.object(ab, "_broadcast", new_callable=AsyncMock) as mock_bcast,+ ):+ result = await node.add_tool(ctx, params)++ assert len(result.operations) == 2 # spawn + edge+ assert result.operations[0]["node_type"] == "httpRequest"+ mock_bcast.assert_awaited_once()++ async def test_add_subagent_is_idempotent_when_already_wired(self):+ node = ab.AgentBuilderNode()+ nodes = [+ {"id": "lead-1", "type": "orchestrator_agent", "data": {"label": "Lead"}},+ {"id": "ab-1", "type": "agentBuilder", "data": {"label": "AB"}},+ {"id": "coder-existing", "type": "coding_agent", "data": {"label": "Coder"}},+ ]+ edges = [+ _edge("ab-1", "lead-1", "input-tools"),+ _edge("coder-existing", "lead-1", "input-teammates"),+ ]+ ctx = _make_ctx(nodes=nodes, 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) as mock_bcast,+ ):+ result = await node.add_subagent(ctx, params)++ assert result.operations == []+ assert "already wired" in result.summary+ assert "coder-existing" in result.summary+ mock_bcast.assert_not_awaited()++ async def test_add_skill_is_idempotent_when_already_enabled(self):+ """When the masterSkill is already wired AND the requested skill+ is already ``enabled=True`` in its skills_config, ``add_skill``+ returns empty operations + an "already enabled" summary."""+ node = ab.AgentBuilderNode()+ master_skill_node = {+ "id": "ms-1",+ "type": "masterSkill",+ "data": {+ "label": "Master Skill",+ "parameters": {+ "skills_config": {+ "http-request-skill": {+ "enabled": True,+ "instructions": "",+ "isCustomized": False,+ },+ },+ },+ },+ }+ nodes = [+ _agent_node("agent-1"),+ {"id": "ab-1", "type": "agentBuilder", "data": {"label": "AB"}},+ master_skill_node,+ ]+ edges = [+ _edge("ab-1", "agent-1", "input-tools"),+ _edge("ms-1", "agent-1", "input-skill"),+ ]+ ctx = _make_ctx(nodes=nodes, 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) as mock_bcast,+ ):+ result = await node.add_skill(ctx, params)++ assert result.operations == []+ assert "already enabled" in result.summary+ assert "ms-1" in result.summary+ mock_bcast.assert_not_awaited()diff --git a/server/tests/services/test_agent_loop_rebind.py b/server/tests/services/test_agent_loop_rebind.pyindex 4ea4c884..3be8098d 100644--- a/server/tests/services/test_agent_loop_rebind.py+++ b/server/tests/services/test_agent_loop_rebind.py@@ -227,6 +227,99 @@ class TestAgentLoopRebind:# ----------------------------------------------------------------------------+class TestRebindAcceptsDualPurposePlugins:+ """The rebind path (both F4.A in-process closures and the F4.B+ ``agent.refresh_tools.v1`` activity) must build StructuredTools+ for **dual-purpose** ActionNode plugins (``usable_as_tool=True``),+ not only pure ToolNodes (``component_kind == 'tool'``).++ Without this, every ``twitterSearch`` / ``googleGmail`` /+ ``pythonExecutor`` add_tool call returns success on the LLM-visible+ surface but the tool never makes it into ``chat_model.bind_tools``+ — so the next iteration's LLM calls an unknown tool and the run+ burns iterations on retries.+ """++ def test_ai_rebind_accepts_dual_purpose(self):+ import inspect++ from services.ai import AIService++ src = inspect.getsource(AIService.execute_agent)+ # Must use the broader filter — pure tool OR dual-purpose+ # ActionNode (usable_as_tool=True), excluding chat models.+ assert "usable_as_tool" in src, (+ "execute_agent's rebind closure must look at usable_as_tool, "+ "not just component_kind=='tool'."+ )+ # Explicit ``!= 'model'`` guard so the broadening doesn't sweep+ # in chat-model plugins like openaiChatModel that carry+ # ``usable_as_tool=True`` but aren't agent tools.+ assert '"model"' in src or "'model'" in src, (+ "Rebind broadening must explicitly exclude component_kind='model'."+ )++ def test_ai_rebind_excludes_chat_models(self):+ """execute_chat_agent's rebind closure shares the same broadened+ filter — locks both call sites."""+ import inspect++ from services.ai import AIService++ src = inspect.getsource(AIService.execute_chat_agent)+ assert "usable_as_tool" in src++ def test_temporal_refresh_accepts_dual_purpose(self):+ import inspect++ from services.temporal.agent_activities import refresh_agent_tools++ src = inspect.getsource(refresh_agent_tools)+ assert "usable_as_tool" in src, (+ "agent.refresh_tools.v1 must build tools for dual-purpose "+ "plugins (twitterSearch, googleGmail, pythonExecutor, …) — "+ "the bulk of useful LLM-callable tools live there, not in "+ "pure ToolNode plugins."+ )+++class TestRebindIdAlignment:+ """The rebind path must use the BE-minted ``minted_id`` (set by+ agentBuilder so the FE applier adopts it verbatim) as the new+ tool's ``node_id``. Without this the dispatcher's status+ broadcasts target a synthesized id that doesn't match any React+ Flow node → canvas doesn't glow on the rebound tool's first run.+ """++ def test_ai_rebind_prefers_minted_id(self):+ import inspect++ from services.ai import AIService++ src = inspect.getsource(AIService.execute_agent)+ assert 'op.get("minted_id")' in src, (+ "execute_agent's rebind closure must prefer op['minted_id'] over "+ "op['client_ref'] when synthesizing the tool's node_id, otherwise "+ "the canvas can't glow on the rebound tool."+ )+ src = inspect.getsource(AIService.execute_chat_agent)+ assert 'op.get("minted_id")' in src, (+ "execute_chat_agent's rebind closure must prefer op['minted_id']."+ )++ def test_temporal_refresh_tools_prefers_minted_id(self):+ import inspect++ from services.temporal.agent_activities import refresh_agent_tools++ src = inspect.getsource(refresh_agent_tools)+ assert 'op.get("minted_id")' in src, (+ "agent.refresh_tools.v1 activity must prefer op['minted_id'] when "+ "synthesizing the tool's node_id so F4.B status broadcasts align "+ "with the FE-adopted React Flow id."+ )++class TestAgentLoopRebindWiring:def test_execute_agent_passes_rebind_callback(self):from services.ai import AIServicediff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.pyindex 5de48b4d..fcc9760e 100644--- a/server/tests/temporal/test_agent_workflow.py+++ b/server/tests/temporal/test_agent_workflow.py@@ -243,6 +243,19 @@ class TestAutoRebindTools:assert "agent.refresh_tools.v1" in namesassert refresh_agent_tools in collect_agent_activities()+ async def test_refresh_tools_runs_without_nameerror(self):+ """Smoke test: the activity body must import ``container`` and+ ``get_node_class`` so it doesn't NameError on first invocation.+ Mirrors the rest of the agent_activities.py pattern (lazy import+ inside each activity body)."""+ from services.temporal.agent_activities import refresh_agent_tools++ # Pass empty operations so the activity short-circuits before+ # any plugin lookup — we just want to confirm the imports + the+ # ``container.ai_service()`` call don't raise NameError.+ result = await refresh_agent_tools({"operations": []})+ assert result == {"tools": []}+def test_workflow_calls_refresh_after_ops(self):"""AgentWorkflow.run must schedule ``agent.refresh_tools.v1``when a tool result carries an ``operations`` field."""