Skip to content

Self-improving AI Employees for everyone

feat(agent): in-run tool rebind after canvas mutation + needs_canvas plugin flag

trohitg657502a92c67
diff --git a/client/src/components/ui/SettingsPanel.tsx b/client/src/components/ui/SettingsPanel.tsx
index e56ea0ae..01510f09 100644
--- a/client/src/components/ui/SettingsPanel.tsx
+++ b/client/src/components/ui/SettingsPanel.tsx
@@ -250,6 +250,16 @@ const SettingsPanel: React.FC<SettingsPanelProps> = ({
disabled={isSaving}
/>
</Row>
+ <Row
+ label="Auto-Rebind Tools After Canvas Changes"
+ description="When an agent's Agent Builder tool spawns new tools/skills/teammates mid-run, immediately rebind the LLM so the new wiring is callable in the same turn. Disable to require a Run-stop-Run cycle before the LLM can call the new tool."
+ >
+ <Switch
+ checked={settings.autoRebindToolsAfterCanvasChange}
+ onCheckedChange={(checked) => handleChange('autoRebindToolsAfterCanvasChange', checked)}
+ disabled={isSaving}
+ />
+ </Row>
</Section>
{/* Auto-save */}
diff --git a/client/src/components/ui/settingsPanel/schema.ts b/client/src/components/ui/settingsPanel/schema.ts
index b1fa9081..5fb70782 100644
--- a/client/src/components/ui/settingsPanel/schema.ts
+++ b/client/src/components/ui/settingsPanel/schema.ts
@@ -20,6 +20,7 @@ export const workflowSettingsSchema = z.object({
compactionRatio: z.number().min(0.1).max(0.9).default(0.5),
maxProcesses: z.number().int().min(1).max(50).default(10),
autoAddSkillForTools: z.boolean().default(true),
+ autoRebindToolsAfterCanvasChange: z.boolean().default(true),
});
export type WorkflowSettings = z.infer<typeof workflowSettingsSchema>;
@@ -42,6 +43,7 @@ export function fromServerRow(row: Record<string, any> | null | undefined): Work
compactionRatio: row.compaction_ratio,
maxProcesses: row.max_processes,
autoAddSkillForTools: row.auto_add_skill_for_tools,
+ autoRebindToolsAfterCanvasChange: row.auto_rebind_tools_after_canvas_change,
});
}
@@ -60,5 +62,6 @@ export function toServerRow(s: WorkflowSettings): Record<string, any> {
compaction_ratio: s.compactionRatio,
max_processes: s.maxProcesses,
auto_add_skill_for_tools: s.autoAddSkillForTools,
+ auto_rebind_tools_after_canvas_change: s.autoRebindToolsAfterCanvasChange,
};
}
diff --git a/server/core/database.py b/server/core/database.py
index 5039f825..8ad63139 100644
--- a/server/core/database.py
+++ b/server/core/database.py
@@ -129,6 +129,10 @@ class Database:
await conn.execute(text("ALTER TABLE user_settings ADD COLUMN auto_add_skill_for_tools BOOLEAN DEFAULT 1"))
logger.info("Added auto_add_skill_for_tools column to user_settings")
+ if "auto_rebind_tools_after_canvas_change" not in columns:
+ await conn.execute(text("ALTER TABLE user_settings ADD COLUMN auto_rebind_tools_after_canvas_change BOOLEAN DEFAULT 1"))
+ logger.info("Added auto_rebind_tools_after_canvas_change column to user_settings")
+
# Migrate token_usage_metrics table - add cost columns
result = await conn.execute(text("PRAGMA table_info(token_usage_metrics)"))
columns = {row[1] for row in result.fetchall()}
@@ -1567,6 +1571,7 @@ class Database:
"default_llm_provider": settings.default_llm_provider,
"default_llm_model": settings.default_llm_model,
"auto_add_skill_for_tools": settings.auto_add_skill_for_tools,
+ "auto_rebind_tools_after_canvas_change": settings.auto_rebind_tools_after_canvas_change,
"created_at": settings.created_at.isoformat() if settings.created_at else None,
"updated_at": settings.updated_at.isoformat() if settings.updated_at else None,
}
@@ -1612,6 +1617,8 @@ class Database:
existing.default_llm_model = settings_data["default_llm_model"]
if "auto_add_skill_for_tools" in settings_data:
existing.auto_add_skill_for_tools = settings_data["auto_add_skill_for_tools"]
+ if "auto_rebind_tools_after_canvas_change" in settings_data:
+ existing.auto_rebind_tools_after_canvas_change = settings_data["auto_rebind_tools_after_canvas_change"]
else:
# Create new settings
existing = UserSettings(
@@ -1629,6 +1636,7 @@ class Database:
default_llm_provider=settings_data.get("default_llm_provider"),
default_llm_model=settings_data.get("default_llm_model"),
auto_add_skill_for_tools=settings_data.get("auto_add_skill_for_tools", True),
+ auto_rebind_tools_after_canvas_change=settings_data.get("auto_rebind_tools_after_canvas_change", True),
)
session.add(existing)
diff --git a/server/models/database.py b/server/models/database.py
index fb810234..4cb09bb1 100644
--- a/server/models/database.py
+++ b/server/models/database.py
@@ -257,6 +257,9 @@ class UserSettings(SQLModel, table=True):
auto_add_skill_for_tools: bool = Field(
default=True
) # When a tool node connects to an AI agent's input-tools, auto-enable the matching skill
+ auto_rebind_tools_after_canvas_change: bool = Field(
+ default=True
+ ) # After agentBuilder mutates the canvas mid-run, refresh the LLM's bound tools so the new wiring is callable in the same execution
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc), sa_column=Column(DateTime(timezone=True), server_default=func.now())
)
diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.py
index 8846c886..9f5b2f93 100644
--- a/server/nodes/tool/agent_builder/__init__.py
+++ b/server/nodes/tool/agent_builder/__init__.py
@@ -112,6 +112,21 @@ def _is_team_lead(node_type: str) -> bool:
return node_type in _TEAM_LEAD_TYPES
+def _summary_suffix(ctx: NodeContext) -> str:
+ """Trailing sentence on agentBuilder op summaries.
+
+ When the user's "Auto-Rebind Tools After Canvas Changes" toggle is
+ on (default), the agent loop rebinds its LLM tool surface after
+ every canvas-mutating tool — the new wiring IS callable in the
+ same turn. When off, the LLM must wait for the next Run.
+
+ The flag rides on ``ctx.raw["auto_rebind_tools"]`` (set by the
+ agent loop dispatcher reading the UserSettings field).
+ """
+ rebind_on = bool((ctx.raw or {}).get("auto_rebind_tools", True))
+ return "Available immediately — call it in your next response." if rebind_on else "Available on your next turn."
+
+
def _toggle_skill(
config: Optional[Dict[str, Dict[str, Any]]],
skill_name: str,
@@ -297,6 +312,13 @@ class AgentBuilderNode(ToolNode):
"agent calls operations through the standard tool path."
)
component_kind = "tool"
+ # Operations walk ctx.edges to resolve the calling agent (input-tools
+ # source) and mutate ctx.nodes — the F4.B AgentWorkflow tool-dispatch
+ # path reads this flag to forward the parent workflow's canvas into
+ # the per-tool activity context. Without it, _resolve_caller falls
+ # back to self-as-caller and new nodes wire to agentBuilder instead
+ # of the parent AI Agent.
+ needs_canvas = True
tool_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)."
handles = (
@@ -426,7 +448,7 @@ class AgentBuilderNode(ToolNode):
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.",
+ summary=f"Added '{node_type}' as a tool. {_summary_suffix(ctx)}",
operations=ops,
)
@@ -480,7 +502,7 @@ class AgentBuilderNode(ToolNode):
await _broadcast(ctx.workflow_id, caller_id, ops)
return AgentBuilderOutput(
operation="add_skill",
- summary=f"Enabled '{skill}' skill. Available on your next turn.",
+ summary=f"Enabled '{skill}' skill. {_summary_suffix(ctx)}",
operations=ops,
)
@@ -504,7 +526,7 @@ class AgentBuilderNode(ToolNode):
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."),
+ summary=f"Created Master Skill node and enabled '{skill}'. {_summary_suffix(ctx)}",
operations=ops,
)
@@ -571,7 +593,7 @@ class AgentBuilderNode(ToolNode):
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)."),
+ summary=(f"Added '{agent_type}' as a teammate. {_summary_suffix(ctx)} " "(configure provider/model first)."),
operations=ops,
)
diff --git a/server/services/ai.py b/server/services/ai.py
index e84d124f..efae9f1d 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -8,7 +8,7 @@ import time
import httpx
from dataclasses import dataclass
from datetime import datetime
-from typing import Dict, Any, List, Optional, Callable, Type, TYPE_CHECKING
+from typing import Awaitable, Dict, Any, List, Optional, Callable, Type, TYPE_CHECKING
# ---------------------------------------------------------------------------
# LangChain imports — fully lazy except for ``BaseMessage``.
@@ -748,6 +748,7 @@ async def _run_agent_loop(
tool_executor: Optional[Callable] = None,
max_iterations: int = 500,
progress_callback: Optional[Callable[[int], Any]] = None,
+ rebind_from_operations: Optional[Callable[[List[Dict[str, Any]]], Awaitable[List[Any]]]] = None,
) -> Dict[str, Any]:
"""Drive an LLM agent loop with optional tool calling.
@@ -779,7 +780,10 @@ async def _run_agent_loop(
"""
from langchain_core.messages import AIMessage, ToolMessage
- model = chat_model.bind_tools(tools) if tools else chat_model
+ # Local mutable tools list so canvas-mutating tools (agentBuilder)
+ # can extend the bound surface mid-loop via ``rebind_from_operations``.
+ current_tools: List[Any] = list(tools or [])
+ model = chat_model.bind_tools(current_tools) if current_tools else chat_model
messages: List[BaseMessage] = list(initial_messages)
thinking_accumulated = ""
iteration = 0
@@ -832,6 +836,7 @@ async def _run_agent_loop(
"truncated": False,
}
+ iteration_new_tools: List[Any] = []
for call in tool_calls:
tool_name = call.get("name", "")
tool_args = call.get("args", {}) or {}
@@ -841,6 +846,26 @@ async def _run_agent_loop(
except Exception as e:
logger.error(f"[Agent loop] Tool {tool_name!r} raised: {e}")
result = {"error": str(e)}
+
+ # Canvas-mutation rebind: any tool can return an ``operations``
+ # field (workflow_ops protocol). When the agent loop has a
+ # ``rebind_from_operations`` callback wired AND the toggle is
+ # on, build new StructuredTools off the ops list so the LLM
+ # can call them in the very next iteration without a restart.
+ if (
+ rebind_from_operations is not None
+ and isinstance(result, dict)
+ and result.get("operations")
+ ):
+ try:
+ added = await rebind_from_operations(result["operations"])
+ if added:
+ iteration_new_tools.extend(added)
+ except Exception as exc: # noqa: BLE001 — defensive; rebind is opt-in
+ logger.warning(
+ "[Agent loop] rebind_from_operations raised: %s", exc, exc_info=True
+ )
+
messages.append(
ToolMessage(
content=json.dumps(result, default=str),
@@ -849,6 +874,15 @@ async def _run_agent_loop(
)
)
+ if iteration_new_tools:
+ current_tools.extend(iteration_new_tools)
+ model = chat_model.bind_tools(current_tools)
+ logger.info(
+ "[Agent loop] rebound %d tool(s) after canvas mutation (total bound=%d)",
+ len(iteration_new_tools),
+ len(current_tools),
+ )
+
# Loop exited without returning -- hit max_iterations. Append a
# terminal AIMessage so downstream extraction (and post-loop token
# tracking / memory persistence) still have a usable state.
@@ -1762,6 +1796,9 @@ class AIService:
config["ai_service"] = self
config["database"] = self.database
config["parent_node_id"] = node_id
+ # Surface the auto-rebind toggle so agentBuilder's summary
+ # text reflects the user's current preference.
+ config["auto_rebind_tools"] = auto_rebind_enabled
if context:
config["nodes"] = context.get("nodes", [])
config["edges"] = context.get("edges", [])
@@ -1784,6 +1821,67 @@ class AIService:
# Re-raise to let _run_agent_loop surface the error to the LLM
raise
+ # Auto-rebind toggle: when the user enables "Auto-Rebind Tools
+ # After Canvas Changes" in Settings, canvas-mutating tools
+ # (agentBuilder) extend the LLM's bound surface mid-loop. The
+ # default is True; lookup failures fall back to True so the
+ # feature doesn't silently disable itself on a transient DB hiccup.
+ auto_rebind_enabled = True
+ try:
+ user_settings = await self.database.get_user_settings()
+ if user_settings is not None:
+ auto_rebind_enabled = bool(
+ user_settings.get("auto_rebind_tools_after_canvas_change", True)
+ )
+ except Exception as exc: # noqa: BLE001 — defensive read
+ logger.debug("[Agent] auto_rebind settings read failed: %s", exc)
+
+ async def _rebind_from_operations(operations: List[Dict[str, Any]]) -> List[Any]:
+ """Translate workflow_ops add_node ops (component_kind='tool')
+ into fresh ``StructuredTool``s via the canonical
+ :meth:`_build_tool_from_node` helper. The returned list is
+ appended to ``_run_agent_loop``'s ``current_tools`` and
+ rebound onto the LLM so the LLM can invoke the new tool in
+ its NEXT iteration without a Run-stop-Run cycle.
+
+ Tool configs are folded into the existing ``tool_configs``
+ closure so ``tool_executor`` can route the LLM's eventual
+ tool_call to the right node.
+ """
+ from services.node_registry import get_node_class
+
+ new_tools: List[Any] = []
+ for op in operations:
+ if op.get("type") != "add_node":
+ continue
+ node_type = op.get("node_type")
+ if not node_type:
+ continue
+ cls = get_node_class(node_type)
+ if cls is None or getattr(cls, "component_kind", "") != "tool":
+ continue
+ tool_info = {
+ "node_id": 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,
+ }
+ try:
+ tool, tool_config = await self._build_tool_from_node(tool_info)
+ except Exception as exc: # noqa: BLE001 — log + skip one tool
+ logger.warning(
+ "[Agent] rebind: _build_tool_from_node raised for %s: %s",
+ node_type,
+ exc,
+ )
+ continue
+ if tool is None:
+ continue
+ new_tools.append(tool)
+ if tool_config:
+ tool_configs[tool.name] = tool_config
+ return new_tools
+
# Broadcast: Building agent
await broadcast_status(
"building_graph",
@@ -1836,6 +1934,7 @@ class AIService:
tool_executor=tool_executor if tools else None,
max_iterations=recursion_limit,
progress_callback=_emit_progress if broadcaster else None,
+ rebind_from_operations=_rebind_from_operations if auto_rebind_enabled else None,
)
# Extract the AI response (last message in the accumulated messages)
@@ -2227,6 +2326,7 @@ class AIService:
config["ai_service"] = self
config["database"] = self.database
config["parent_node_id"] = node_id
+ config["auto_rebind_tools"] = auto_rebind_enabled
if context:
config["nodes"] = context.get("nodes", [])
config["edges"] = context.get("edges", [])
@@ -2240,6 +2340,56 @@ class AIService:
logger.error(f"[ChatAgent] Tool execution failed: {tool_name}", error=str(e))
return {"error": str(e)}
+ # Auto-rebind toggle: same machinery as ``execute_agent``.
+ auto_rebind_enabled = True
+ try:
+ user_settings = await self.database.get_user_settings()
+ if user_settings is not None:
+ auto_rebind_enabled = bool(
+ user_settings.get("auto_rebind_tools_after_canvas_change", True)
+ )
+ except Exception as exc: # noqa: BLE001 — defensive read
+ logger.debug("[ChatAgent] auto_rebind settings read failed: %s", exc)
+
+ async def _rebind_from_operations(operations: List[Dict[str, Any]]) -> List[Any]:
+ """Mirror of execute_agent._rebind_from_operations — see that
+ function for the contract. We can't dedupe cleanly because
+ the two agent paths capture different closure variables
+ (``tool_configs`` vs ``tool_node_configs``)."""
+ from services.node_registry import get_node_class
+
+ new_tools: List[Any] = []
+ for op in operations:
+ if op.get("type") != "add_node":
+ continue
+ node_type = op.get("node_type")
+ if not node_type:
+ continue
+ cls = get_node_class(node_type)
+ if cls is None or getattr(cls, "component_kind", "") != "tool":
+ continue
+ tool_info = {
+ "node_id": 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,
+ }
+ try:
+ tool, tool_config = await self._build_tool_from_node(tool_info)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[ChatAgent] rebind: _build_tool_from_node raised for %s: %s",
+ node_type,
+ exc,
+ )
+ continue
+ if tool is None:
+ continue
+ new_tools.append(tool)
+ if tool_config:
+ tool_node_configs[tool.name] = tool_config
+ return new_tools
+
# Run the agent loop. See ``execute_agent`` for the
# rationale on ``recursion_limit`` + the truncation
# behaviour on hit.
@@ -2263,6 +2413,7 @@ class AIService:
tool_executor=chat_tool_executor,
max_iterations=recursion_limit,
progress_callback=_emit_progress if broadcaster else None,
+ rebind_from_operations=_rebind_from_operations if auto_rebind_enabled else None,
)
# Extract response
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 2dabe63d..911e55c4 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -144,6 +144,15 @@ class BaseNode:
component_kind: ClassVar[str] = "generic"
usable_as_tool: ClassVar[bool] = False
+ # Whether this plugin requires the parent workflow's full canvas
+ # (``nodes`` + ``edges`` arrays) in its NodeContext. Default ``False``
+ # — most tools execute against their own params alone. Set ``True``
+ # on plugins that walk or mutate the canvas (the F4.B AgentWorkflow
+ # tool-dispatch path reads this attribute to decide whether to
+ # forward the parent workflow's canvas into the per-tool activity
+ # context). Currently only :class:`AgentBuilderNode` opts in.
+ needs_canvas: ClassVar[bool] = False
+
# Wave 12 D5: LLM-visible name + description for plugins surfaced as
# AI tools (ToolNode subclasses, ActionNodes marked usable_as_tool=True,
# SpecializedAgentBase subclasses).
@@ -557,6 +566,22 @@ class BaseNode:
method = spec.method.__get__(self, type(self))
return await method(ctx, params_obj)
+ @classmethod
+ def interpret_result(cls, result: Dict[str, Any]) -> tuple[bool, Any, Optional[str]]:
+ """Unify success/error semantics across node base classes.
+
+ Returns ``(success, payload, error_message)``. The F4.A activity
+ wrapper calls this so broadcast plumbing stays plugin-agnostic.
+
+ Default contract: the standard ``{success, result, error?, …}``
+ envelope produced by :meth:`_wrap_success` / :meth:`_wrap_error`.
+ :class:`ToolNode` overrides — its :meth:`_wrap_success` returns
+ a flat dict (the LLM-feedable shape).
+ """
+ if result.get("success"):
+ return True, result.get("result", {}), None
+ return False, None, result.get("error")
+
def _wrap_success(self, *, start_time: float, result: Any) -> Dict[str, Any]:
"""95%-universal return shape. Subclasses (ToolNode) override."""
if isinstance(result, BaseModel):
@@ -679,6 +704,12 @@ class BaseNode:
# per-type activities skip the loopback because the worker
# shares the FastAPI process.
workflow_service = container.workflow_service()
+ # Forward any non-standard context keys (e.g.
+ # ``auto_rebind_tools`` for agentBuilder) through the
+ # ``extras`` channel so they land in NodeContext.raw.
+ extras: Dict[str, Any] = {}
+ if "auto_rebind_tools" in context:
+ extras["auto_rebind_tools"] = context["auto_rebind_tools"]
result = await workflow_service.execute_node(
node_id=node_id,
node_type=cls.type,
@@ -688,31 +719,38 @@ class BaseNode:
session_id=context.get("session_id", "default"),
workflow_id=workflow_id,
outputs=context.get("inputs", {}),
+ extras=extras or None,
)
result["node_id"] = node_id
result["node_type"] = cls.type
result["timestamp"] = datetime.now().isoformat()
- if result.get("success"):
+ # Polymorphic dispatch — each node base class owns its
+ # result contract. ToolNode returns flat dicts; ActionNode
+ # / TriggerNode return the {success, result} envelope.
+ # cls.interpret_result() normalizes both into (success,
+ # payload, error_message).
+ success, payload, error = cls.interpret_result(result)
+ if success:
activity.logger.info(f"Node {node_id} succeeded")
await broadcaster.update_node_status(
node_id,
"success",
- result.get("result", {}),
+ payload,
workflow_id=workflow_id,
)
await broadcaster.update_node_output(
node_id,
- result.get("result", {}),
+ payload,
workflow_id=workflow_id,
)
else:
- activity.logger.warning(f"Node {node_id} failed: {result.get('error')}")
+ activity.logger.warning(f"Node {node_id} failed: {error}")
await broadcaster.update_node_status(
node_id,
"error",
- {"error": result.get("error")},
+ {"error": error},
workflow_id=workflow_id,
)
diff --git a/server/services/plugin/tool.py b/server/services/plugin/tool.py
index 47d6dcdb..37026f15 100644
--- a/server/services/plugin/tool.py
+++ b/server/services/plugin/tool.py
@@ -7,7 +7,7 @@ JSON Schema the LLM sees — derived from :class:`Params` automatically.
from __future__ import annotations
-from typing import Any, ClassVar, Dict
+from typing import Any, ClassVar, Dict, Optional
from services.plugin.base import BaseNode
from services.plugin.scaling import TaskQueue
@@ -49,3 +49,13 @@ class ToolNode(BaseNode, abstract=True):
if isinstance(result, dict):
return result
return {"result": result}
+
+ @classmethod
+ def interpret_result(cls, result: Dict[str, Any]) -> tuple[bool, Any, Optional[str]]:
+ """ToolNode contract: a flat dict (no ``success`` key) IS the
+ success payload. Operation exceptions still flow through
+ :meth:`_wrap_error` and produce the standard envelope — those
+ get the base-class semantics."""
+ if isinstance(result, dict) and "success" not in result:
+ return True, result, None
+ return super().interpret_result(result)
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index 1bf2fd46..40d7fc85 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -642,6 +642,20 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
prompt = str(out[field])
break
+ # Read the user toggle for mid-loop tool rebinding once at prep
+ # time. ``AgentWorkflow.run`` reads it from the returned payload and
+ # forwards into per-tool activity payloads so agentBuilder + the
+ # workflow's own rebind branch see the same value.
+ auto_rebind_tools = True
+ try:
+ user_settings = await database.get_user_settings()
+ if user_settings is not None:
+ auto_rebind_tools = bool(
+ user_settings.get("auto_rebind_tools_after_canvas_change", True)
+ )
+ except Exception as exc: # noqa: BLE001 — defensive read
+ activity.logger.debug(f"auto_rebind settings read failed: {exc}")
+
return {
"node_id": node_id,
"node_type": node_type,
@@ -661,11 +675,93 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
"max_iterations": int(parameters.get("max_iterations") or 50),
"thinking_config": thinking_config_dict,
"compaction_threshold": compaction_threshold,
+ "auto_rebind_tools": auto_rebind_tools,
}
[email protected](name="agent.refresh_tools.v1")
+async def refresh_agent_tools(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Build fresh ``tool_payload`` entries from a workflow_ops batch.
+
+ Called by ``AgentWorkflow.run`` after a tool returns
+ ``operations`` (canvas mutation, today only from ``agentBuilder``).
+ The activity translates each ``add_node`` op with
+ ``component_kind="tool"`` into the same ``tool_payload`` shape
+ :func:`prepare_agent_payload` emits — so the workflow body can
+ splice the new entries into its existing ``tools`` / ``tool_index``
+ structures with zero schema drift.
+
+ Reuses (no duplication):
+
+ * :meth:`AIService._build_tool_from_node` — the canonical
+ StructuredTool builder.
+ * :func:`services.node_registry.get_node_class` — for
+ ``component_kind`` + ``version`` + ``task_queue`` metadata.
+ * The exact loop body from :func:`prepare_agent_payload`
+ lines 584-614.
+
+ Payload shape::
+
+ {"operations": [<workflow_op>, ...]}
+
+ Returns::
+
+ {"tools": [<tool_payload entry>, ...]}
+ """
+ from services.node_registry import get_node_class
+
+ ai_service = container.ai_service()
+ operations: List[Dict[str, Any]] = payload.get("operations") or []
+ new_tools_payload: List[Dict[str, Any]] = []
+
+ for op in operations:
+ if op.get("type") != "add_node":
+ continue
+ node_type = op.get("node_type") or ""
+ if not node_type:
+ continue
+ cls = get_node_class(node_type)
+ if cls is None or getattr(cls, "component_kind", "") != "tool":
+ continue
+ tool_info: Dict[str, Any] = {
+ "node_id": 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,
+ }
+ try:
+ tool, _config = await ai_service._build_tool_from_node(tool_info)
+ except Exception as e: # noqa: BLE001 — skip one, keep building the batch
+ activity.logger.warning(
+ f"refresh_tools: failed to build tool {node_type!r}: {e}"
+ )
+ continue
+ if tool is None:
+ continue
+ version = getattr(cls, "version", 1)
+ task_queue = getattr(cls, "task_queue", "machina-default")
+ new_tools_payload.append(
+ {
+ "name": tool.name,
+ "node_type": node_type,
+ "version": version,
+ "task_queue": task_queue,
+ "tool_node_id": tool_info["node_id"],
+ "parameters": tool_info["parameters"],
+ "tool_info": tool_info,
+ }
+ )
+
+ activity.logger.info(
+ "refresh_tools: built %d tool(s) from %d operation(s)",
+ len(new_tools_payload),
+ len(operations),
+ )
+ return {"tools": new_tools_payload}
+
+
def collect_agent_activities() -> List[Any]:
- """Return the five F4.B agent activities for worker registration.
+ """Return the F4.B agent activities for worker registration.
Mirrors :func:`services.temporal.plugin_activities.collect_plugin_activities`
for the workflow-orchestrated agent loop. Workers register these so
@@ -680,4 +776,5 @@ def collect_agent_activities() -> List[Any]:
prepare_agent_payload,
broadcast_agent_progress,
store_agent_output,
+ refresh_agent_tools,
]
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index 92abdbb8..f4c451c7 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -52,6 +52,8 @@ from typing import Any, Dict, List, Optional
from temporalio import workflow
from temporalio.common import RetryPolicy # kept for type hints
+from services.node_registry import get_node_class
+
from ._retry_policies import DEFAULT_ACTIVITY_RETRY
from .workflow import AGENT_WORKFLOW_TYPES
@@ -355,8 +357,18 @@ class AgentWorkflow:
**(tool_info.get("parameters") or {}),
**call_args,
}
- child_nodes = [] # regular tool activity doesn't need full canvas
- child_edges = []
+ # Canvas-aware tools (currently only agentBuilder, which
+ # walks edges to resolve its calling agent + mutates
+ # the canvas) opt in via the BaseNode.needs_canvas
+ # ClassVar. Default tools execute against their own
+ # params alone and don't see the parent canvas.
+ plugin_cls = get_node_class(tool_info["node_type"])
+ if plugin_cls is not None and plugin_cls.needs_canvas:
+ child_nodes = context.get("nodes") or []
+ child_edges = context.get("edges") or []
+ else:
+ child_nodes = []
+ child_edges = []
tool_payload = {
"node_id": tool_info["tool_node_id"],
@@ -367,6 +379,10 @@ class AgentWorkflow:
"session_id": payload.get("session_id", "default"),
"nodes": child_nodes,
"edges": child_edges,
+ # Surface the auto-rebind toggle into the tool's ctx
+ # so canvas-mutating tools (agentBuilder) render their
+ # summary text to match the user's current preference.
+ "auto_rebind_tools": bool(payload.get("auto_rebind_tools", True)),
}
tool_activity_name = f"node.{tool_info['node_type']}.v{tool_info['version']}"
@@ -407,6 +423,36 @@ class AgentWorkflow:
phase="tool_completed",
extra={"tool_name": call.get("name", "")},
)
+
+ # Hot-rebind: if the tool returned ``operations`` (canvas
+ # mutation), schedule ``agent.refresh_tools.v1`` to build
+ # new tool_payload entries from the ops and splice them
+ # into the workflow's live ``tools`` / ``tool_index``.
+ # The next ``execute_llm_step`` invocation rebuilds the
+ # bound LLM surface from this updated list, so the new
+ # tool is callable in the very next iteration without a
+ # Run-stop-Run cycle.
+ auto_rebind_enabled = bool(payload.get("auto_rebind_tools", True))
+ if auto_rebind_enabled and isinstance(tool_result, dict):
+ ops_from_tool = tool_result.get("operations") or []
+ if ops_from_tool:
+ refresh_result = await workflow.execute_activity(
+ "agent.refresh_tools.v1",
+ args=[{"operations": ops_from_tool}],
+ activity_id=f"refresh-tools-{tool_info['tool_node_id']}-{iteration + 1}",
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+ added_tools = refresh_result.get("tools") or []
+ for new_tool in added_tools:
+ tools.append(new_tool)
+ tool_index[new_tool["name"]] = new_tool
+ if added_tools:
+ workflow.logger.info(
+ "AgentWorkflow rebound %d tool(s) after canvas mutation (total bound=%d)",
+ len(added_tools),
+ len(tools),
+ )
except Exception as e: # noqa: BLE001 — Temporal handles retries
# After all retries exhausted, surface the error to
# the LLM (per user decision: LLM sees error and
diff --git a/server/services/workflow.py b/server/services/workflow.py
index 7c424119..0f2053e3 100644
--- a/server/services/workflow.py
+++ b/server/services/workflow.py
@@ -183,8 +183,15 @@ class WorkflowService:
workflow_id: str = None,
workflow_slug: str = None,
outputs: Dict[str, Any] = None,
+ extras: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
- """Execute a single workflow node."""
+ """Execute a single workflow node.
+
+ ``extras`` is merged into the ``NodeContext.raw`` dict so callers
+ (notably the F4.A per-type activity wrapper) can plumb context
+ fields like ``auto_rebind_tools`` through without adding a
+ dedicated parameter per flag.
+ """
# Resolve slug from DB if caller passed only workflow_id.
if workflow_slug is None:
workflow_slug = await self._resolve_workflow_slug(workflow_id)
@@ -200,6 +207,8 @@ class WorkflowService:
"get_output_fn": self.get_node_output,
"outputs": outputs or {}, # Upstream node outputs for data flow (e.g., taskTrigger -> chatAgent)
}
+ if extras:
+ context.update(extras)
return await self._node_executor.execute(
node_id=node_id,
node_type=node_type,
diff --git a/server/tests/nodes/test_agent_builder.py b/server/tests/nodes/test_agent_builder.py
index e95ed189..c47248a1 100644
--- a/server/tests/nodes/test_agent_builder.py
+++ b/server/tests/nodes/test_agent_builder.py
@@ -221,7 +221,35 @@ class TestAddTool:
assert result.operations[1]["target"] == "agent-1"
assert result.operations[1]["target_handle"] == "input-tools"
mock_bcast.assert_awaited_once()
+ # Default ctx has no ``auto_rebind_tools`` in raw → defaults True
+ # → the LLM is told the new tool is callable in the same turn.
+ assert "Available immediately" in result.summary
+
+ async def test_summary_branches_on_auto_rebind_flag(self):
+ """When the user disables the "Auto-Rebind Tools After Canvas
+ Changes" toggle, the operation summary must read
+ "Available on your next turn" so the LLM doesn't try to call
+ the new tool before a Run-stop-Run cycle."""
+ node = ab.AgentBuilderNode()
+ edges = [_edge("ab-1", "agent-1", "input-tools")]
+ ctx = NodeContext(
+ node_id="ab-1",
+ node_type="agentBuilder",
+ workflow_id="wf-test",
+ nodes=[],
+ edges=edges,
+ raw={"workflow_id": "wf-test", "auto_rebind_tools": False},
+ )
+ 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)
+
assert "Available on your next turn" in result.summary
+ assert "Available immediately" not in result.summary
# ============================================================================
diff --git a/server/tests/services/test_agent_loop_rebind.py b/server/tests/services/test_agent_loop_rebind.py
new file mode 100644
index 00000000..4ea4c884
--- /dev/null
+++ b/server/tests/services/test_agent_loop_rebind.py
@@ -0,0 +1,262 @@
+"""Unit tests for the mid-loop tool-rebind path in ``_run_agent_loop``.
+
+The agent loop, after each tool call, must:
+
+* Detect a ``operations`` field in the tool result (canvas-mutating
+ tools like ``agentBuilder`` emit a ``workflow_ops`` batch there).
+* Invoke the supplied ``rebind_from_operations`` callback with the ops.
+* Append the returned tools to the bound LLM surface and re-call
+ ``chat_model.bind_tools`` so the LLM sees the new wiring on the
+ NEXT iteration (no Run-stop-Run cycle).
+
+Driven by source-aware mocks of ``chat_model`` so the test runs
+without a live LLM. The ``execute_agent`` + ``execute_chat_agent``
+wirings get source-introspection coverage in
+``test_agent_loop_rebind_wiring`` below — full end-to-end live testing
+of those happens in the existing integration suite.
+"""
+
+from __future__ import annotations
+
+import inspect
+from typing import Any, Dict, List
+
+import pytest
+
+from langchain_core.messages import AIMessage, HumanMessage
+
+from services import ai as ai_module
+
+
+# ----------------------------------------------------------------------------
+# Mock chat-model harness
+# ----------------------------------------------------------------------------
+
+
+class _FakeBoundModel:
+ """Returns scripted ``AIMessage`` responses. The response queue is
+ a SHARED list reference across all bound models built from the
+ same _FakeChatModel — so a rebind doesn't restart the script."""
+
+ def __init__(self, shared_responses: List[AIMessage]):
+ self._responses = shared_responses # SHARED ref, not a copy
+ self.invocations: List[List[Any]] = []
+
+ async def ainvoke(self, messages):
+ self.invocations.append(messages)
+ if not self._responses:
+ return AIMessage(content="done")
+ return self._responses.pop(0)
+
+
+class _FakeChatModel:
+ """Toplevel chat model. ``bind_tools`` returns a _FakeBoundModel
+ that pops from a single shared response queue."""
+
+ def __init__(self, responses: List[AIMessage]):
+ self._responses = list(responses) # local mutable copy
+ self.bind_calls: List[List[Any]] = []
+ self.last_bound: _FakeBoundModel | None = None
+
+ def bind_tools(self, tools):
+ self.bind_calls.append(list(tools))
+ self.last_bound = _FakeBoundModel(self._responses)
+ return self.last_bound
+
+ async def ainvoke(self, messages):
+ # Only reached when no tools wired — _run_agent_loop binds tools
+ # if any are present.
+ if not self._responses:
+ return AIMessage(content="done")
+ return self._responses.pop(0)
+
+
+class _FakeTool:
+ """Minimal stand-in matching ``StructuredTool`` surface that
+ ``chat_model.bind_tools`` accepts. Just needs a ``name``."""
+
+ def __init__(self, name: str):
+ self.name = name
+
+
+# ----------------------------------------------------------------------------
+# Tests
+# ----------------------------------------------------------------------------
+
+
+class TestAgentLoopRebind:
+ async def test_rebind_callback_invoked_with_operations(self):
+ """When a tool result carries ``operations``, the loop must
+ invoke ``rebind_from_operations`` with that list."""
+ # Iteration 1: LLM emits a tool_call. Iteration 2: returns final.
+ responses = [
+ AIMessage(content="", tool_calls=[{"name": "agentBuilder", "args": {}, "id": "c1"}]),
+ AIMessage(content="done"),
+ ]
+ chat_model = _FakeChatModel(responses)
+ initial_tool = _FakeTool("agentBuilder")
+
+ async def tool_executor(name: str, args: Dict[str, Any]) -> Any:
+ # Return ops so the loop triggers rebind.
+ return {
+ "operation": "add_tool",
+ "summary": "Added 'httpRequest'.",
+ "operations": [
+ {"type": "add_node", "client_ref": "new_httpRequest", "node_type": "httpRequest"},
+ {"type": "add_edge", "source": {"client_ref": "new_httpRequest"}, "target": "agent-1"},
+ ],
+ }
+
+ captured_ops: List[List[Dict[str, Any]]] = []
+
+ async def rebind_from_operations(ops: List[Dict[str, Any]]) -> List[Any]:
+ captured_ops.append(ops)
+ return [_FakeTool("httpRequest")]
+
+ await ai_module._run_agent_loop(
+ chat_model,
+ [HumanMessage(content="go")],
+ tools=[initial_tool],
+ tool_executor=tool_executor,
+ max_iterations=5,
+ rebind_from_operations=rebind_from_operations,
+ )
+
+ assert len(captured_ops) == 1, "rebind_from_operations must be called once per tool result with operations"
+ assert captured_ops[0][0]["type"] == "add_node"
+ assert captured_ops[0][0]["node_type"] == "httpRequest"
+
+ async def test_bind_tools_called_again_after_rebind(self):
+ """Returned tools from ``rebind_from_operations`` must extend
+ the bound surface — ``chat_model.bind_tools`` is invoked a
+ second time with the larger list."""
+ responses = [
+ AIMessage(content="", tool_calls=[{"name": "agentBuilder", "args": {}, "id": "c1"}]),
+ AIMessage(content="done"),
+ ]
+ chat_model = _FakeChatModel(responses)
+ initial_tool = _FakeTool("agentBuilder")
+ new_tool = _FakeTool("httpRequest")
+
+ async def tool_executor(name, args):
+ return {"operations": [{"type": "add_node", "node_type": "httpRequest", "client_ref": "x"}]}
+
+ async def rebind_from_operations(ops):
+ return [new_tool]
+
+ await ai_module._run_agent_loop(
+ chat_model,
+ [HumanMessage(content="go")],
+ tools=[initial_tool],
+ tool_executor=tool_executor,
+ max_iterations=5,
+ rebind_from_operations=rebind_from_operations,
+ )
+
+ # bind_tools must be called twice: once at loop start, once
+ # after the canvas mutation.
+ assert len(chat_model.bind_calls) == 2
+ # First call: only the initial tool.
+ assert chat_model.bind_calls[0] == [initial_tool]
+ # Second call: initial + new tool (extending, not replacing).
+ assert chat_model.bind_calls[1] == [initial_tool, new_tool]
+
+ async def test_no_rebind_when_callback_omitted(self):
+ """Without ``rebind_from_operations`` (toggle off), the loop
+ does NOT rebind even when ops are present — preserves the
+ legacy "wait for next run" behaviour."""
+ responses = [
+ AIMessage(content="", tool_calls=[{"name": "agentBuilder", "args": {}, "id": "c1"}]),
+ AIMessage(content="done"),
+ ]
+ chat_model = _FakeChatModel(responses)
+ initial_tool = _FakeTool("agentBuilder")
+
+ async def tool_executor(name, args):
+ return {"operations": [{"type": "add_node", "node_type": "httpRequest", "client_ref": "x"}]}
+
+ await ai_module._run_agent_loop(
+ chat_model,
+ [HumanMessage(content="go")],
+ tools=[initial_tool],
+ tool_executor=tool_executor,
+ max_iterations=5,
+ rebind_from_operations=None,
+ )
+
+ # Only the initial bind_tools call — no rebind.
+ assert len(chat_model.bind_calls) == 1
+
+ async def test_no_rebind_when_tool_returns_no_operations(self):
+ """A tool that returns a regular result (no ``operations`` key)
+ must not trigger a rebind even when the callback is wired."""
+ responses = [
+ AIMessage(content="", tool_calls=[{"name": "calculator", "args": {}, "id": "c1"}]),
+ AIMessage(content="done"),
+ ]
+ chat_model = _FakeChatModel(responses)
+ initial_tool = _FakeTool("calculator")
+
+ async def tool_executor(name, args):
+ return {"result": 42} # No ``operations`` field.
+
+ called = False
+
+ async def rebind_from_operations(ops):
+ nonlocal called
+ called = True
+ return []
+
+ await ai_module._run_agent_loop(
+ chat_model,
+ [HumanMessage(content="go")],
+ tools=[initial_tool],
+ tool_executor=tool_executor,
+ max_iterations=5,
+ rebind_from_operations=rebind_from_operations,
+ )
+
+ assert not called
+ assert len(chat_model.bind_calls) == 1
+
+
+# ----------------------------------------------------------------------------
+# Wiring source-introspection — confirm execute_agent + execute_chat_agent
+# provide the rebind callback to _run_agent_loop.
+# ----------------------------------------------------------------------------
+
+
+class TestAgentLoopRebindWiring:
+ def test_execute_agent_passes_rebind_callback(self):
+ from services.ai import AIService
+
+ src = inspect.getsource(AIService.execute_agent)
+ assert "_rebind_from_operations" in src, (
+ "execute_agent must define a rebind closure backed by "
+ "_build_tool_from_node and pass it into _run_agent_loop."
+ )
+ assert "rebind_from_operations=" in src, "execute_agent must wire the rebind callback into _run_agent_loop."
+ assert "auto_rebind_tools_after_canvas_change" in src, (
+ "execute_agent must gate the rebind on the UserSettings flag."
+ )
+
+ def test_execute_chat_agent_passes_rebind_callback(self):
+ from services.ai import AIService
+
+ src = inspect.getsource(AIService.execute_chat_agent)
+ assert "_rebind_from_operations" in src
+ assert "rebind_from_operations=" in src
+ assert "auto_rebind_tools_after_canvas_change" in src
+
+ def test_both_agents_inject_flag_into_tool_config(self):
+ """Both agent paths must inject ``auto_rebind_tools`` into the
+ per-tool config so agentBuilder's summary text reflects the
+ user's preference."""
+ from services.ai import AIService
+
+ for func in (AIService.execute_agent, AIService.execute_chat_agent):
+ src = inspect.getsource(func)
+ assert 'config["auto_rebind_tools"] = auto_rebind_enabled' in src, (
+ f"{func.__name__} must inject the auto_rebind_tools flag into the tool config."
+ )
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index c7bf1599..5de48b4d 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -62,11 +62,12 @@ class TestAgentActivities:
defn = getattr(compact_agent_memory, "__temporal_activity_definition")
assert defn.name == "agent.compact_memory.v1"
- def test_collect_returns_all_six(self):
+ def test_collect_returns_all_seven(self):
"""Each successive sprint added one F4.B agent activity:
infra (3) → per-agent-wiring +prepare_payload (4) → CloudEvents
- cleanup +broadcast_progress (5). All five must register so the
- AgentWorkflow loop can schedule them by name."""
+ cleanup +broadcast_progress (5) → +store_output (6) →
+ +refresh_tools (7). All must register so the AgentWorkflow loop
+ can schedule them by name."""
from services.temporal.agent_activities import collect_agent_activities
activities = collect_agent_activities()
@@ -77,6 +78,7 @@ class TestAgentActivities:
"agent.execute_llm_step.v1",
"agent.persist_turn.v1",
"agent.prepare_payload.v1",
+ "agent.refresh_tools.v1",
"agent.store_output.v1",
]
@@ -213,3 +215,125 @@ class TestDelegationToolDispatch:
"for the same reason — both are needed by "
"``collect_agent_connections``."
)
+
+
+class TestAutoRebindTools:
+ """Mid-run tool rebind after canvas-mutating tools return
+ ``operations`` (workflow_ops batch). The flag is read once in
+ ``prepare_agent_payload``, forwarded into every tool's payload, and
+ surfaced into ``ctx.raw["auto_rebind_tools"]`` so agentBuilder's
+ summary text reflects the user's preference. The rebind itself
+ happens in ``AgentWorkflow.run`` via a new
+ ``agent.refresh_tools.v1`` activity.
+ """
+
+ def test_refresh_tools_activity_registered(self):
+ from services.temporal.agent_activities import refresh_agent_tools
+
+ defn = getattr(refresh_agent_tools, "__temporal_activity_definition", None)
+ assert defn is not None, "refresh_agent_tools missing @activity.defn"
+ assert defn.name == "agent.refresh_tools.v1"
+
+ def test_refresh_tools_in_collect(self):
+ """Worker registration must include the new activity so
+ AgentWorkflow can schedule it."""
+ from services.temporal.agent_activities import collect_agent_activities, refresh_agent_tools
+
+ names = {getattr(a, "__temporal_activity_definition").name for a in collect_agent_activities()}
+ assert "agent.refresh_tools.v1" in names
+ assert refresh_agent_tools in collect_agent_activities()
+
+ def test_workflow_calls_refresh_after_ops(self):
+ """AgentWorkflow.run must schedule ``agent.refresh_tools.v1``
+ when a tool result carries an ``operations`` field."""
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ src = inspect.getsource(AgentWorkflow.run)
+ assert '"agent.refresh_tools.v1"' in src, (
+ "AgentWorkflow tool dispatch must schedule agent.refresh_tools.v1 "
+ "when a tool result returns workflow_ops operations."
+ )
+ # The rebind branch must extend `tools` and `tool_index` so the
+ # next execute_llm_step iteration sees the new tools.
+ assert "tools.append" in src or "tools.extend" in src, (
+ "AgentWorkflow must extend its tools list after refresh."
+ )
+ assert "tool_index[" in src, "AgentWorkflow must extend tool_index after refresh."
+
+ def test_prepare_payload_surfaces_auto_rebind_flag(self):
+ """prepare_agent_payload reads the UserSettings flag and includes
+ ``auto_rebind_tools`` in its returned payload so AgentWorkflow
+ + the tool dispatch see the user's preference."""
+ import inspect
+
+ from services.temporal.agent_activities import prepare_agent_payload
+
+ src = inspect.getsource(prepare_agent_payload)
+ assert "auto_rebind_tools_after_canvas_change" in src, (
+ "prepare_agent_payload must read the user setting."
+ )
+ assert '"auto_rebind_tools"' in src, (
+ "prepare_agent_payload return must include the resolved flag."
+ )
+
+ def test_tool_payload_forwards_auto_rebind(self):
+ """The per-tool activity payload must forward
+ ``auto_rebind_tools`` so the F4.A wrapper can land it into
+ ctx.raw for agentBuilder's summary text."""
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ src = inspect.getsource(AgentWorkflow.run)
+ assert '"auto_rebind_tools"' in src, (
+ "AgentWorkflow tool_payload must include auto_rebind_tools "
+ "so the per-tool activity surfaces it into ctx.raw."
+ )
+
+
+class TestNeedsCanvasDispatch:
+ """Regression: regular (non-delegation) tools opt into canvas
+ propagation via the ``BaseNode.needs_canvas`` ClassVar. The F4.B
+ tool-dispatch path must read the flag via
+ ``services.node_registry.get_node_class`` rather than hardcoding
+ per-plugin type strings. Locks the principled fix for the
+ agentBuilder ``nodes=0 edges=0`` bug.
+ """
+
+ def test_dispatch_uses_get_node_class_lookup(self):
+ """The non-delegation branch must look the plugin class up at
+ dispatch time so ``cls.needs_canvas`` decides canvas
+ propagation. A hardcoded type-string check would silently break
+ for any future canvas-aware tool."""
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ src = inspect.getsource(AgentWorkflow.run)
+ assert "get_node_class(" in src, (
+ "AgentWorkflow tool dispatch must call ``get_node_class("
+ "tool_info['node_type'])`` so it can read the plugin's "
+ "``needs_canvas`` ClassVar. Hardcoded type-string checks "
+ "are forbidden — they don't compose for future canvas-"
+ "aware tools."
+ )
+ assert "needs_canvas" in src, (
+ "AgentWorkflow tool dispatch must read the resolved "
+ "``plugin_cls.needs_canvas`` flag. Without it the canvas "
+ "never reaches agentBuilder and ``_resolve_caller`` falls "
+ "back to self-as-caller."
+ )
+
+ def test_get_node_class_imported_at_module_level(self):
+ """The helper must be importable from the workflow module
+ — Temporal's ``@workflow.defn(sandboxed=False)`` lets us touch
+ ``services.node_registry`` deterministically."""
+ from services.temporal import agent_workflow
+
+ assert hasattr(agent_workflow, "get_node_class"), (
+ "agent_workflow.py must import ``get_node_class`` at module "
+ "level so the workflow body can resolve plugin classes by "
+ "type string."
+ )
diff --git a/server/tests/test_plugin_contract.py b/server/tests/test_plugin_contract.py
index 8f735a78..976bf35e 100644
--- a/server/tests/test_plugin_contract.py
+++ b/server/tests/test_plugin_contract.py
@@ -204,6 +204,130 @@ class TestToolSchemaFastPath:
assert hasattr(resolved, "Params"), f"{cls.__qualname__} has no Params — fast-path would miss it"
+class TestInterpretResultContract:
+ """``BaseNode.interpret_result`` + ``ToolNode.interpret_result`` are
+ the polymorphic envelope-unwrap contract the F4.A Temporal activity
+ wrapper calls in :meth:`BaseNode.as_activity` (see
+ ``server/services/plugin/base.py``). Locks the
+ behaviour so the writeTodos / agentBuilder bug-fix doesn't regress.
+ """
+
+ def test_basenode_envelope_success(self):
+ from services.plugin.base import BaseNode
+
+ success, payload, error = BaseNode.interpret_result({"success": True, "result": {"value": 42}})
+ assert success is True
+ assert payload == {"value": 42}
+ assert error is None
+
+ def test_basenode_envelope_success_with_missing_result_key(self):
+ from services.plugin.base import BaseNode
+
+ # Defensive: an envelope with success=True but no result key
+ # surfaces an empty dict, not None — protects downstream code
+ # that does `.get(...)` on payload.
+ success, payload, error = BaseNode.interpret_result({"success": True})
+ assert success is True
+ assert payload == {}
+
+ def test_basenode_envelope_failure(self):
+ from services.plugin.base import BaseNode
+
+ success, payload, error = BaseNode.interpret_result({"success": False, "error": "boom"})
+ assert success is False
+ assert payload is None
+ assert error == "boom"
+
+ def test_toolnode_flat_dict_is_success(self):
+ """ToolNode plugins return their Output as a flat dict (no
+ ``success`` key); the wrapper must treat absence of the key as
+ success, not failure. This was the writeTodos bug — the F4.A
+ wrapper was checking ``result.get("success")`` directly and
+ misclassifying every ToolNode as failed."""
+ from services.plugin.tool import ToolNode
+
+ success, payload, error = ToolNode.interpret_result({"message": "ok", "todos": [1, 2, 3], "count": 3})
+ assert success is True
+ assert payload == {"message": "ok", "todos": [1, 2, 3], "count": 3}
+ assert error is None
+
+ def test_toolnode_error_envelope_routes_to_failure(self):
+ """When a ToolNode operation throws, BaseNode._wrap_error still
+ produces the standard ``{success: False, error: ...}`` envelope.
+ ToolNode.interpret_result must route that to the failure path
+ rather than treating it as a success payload."""
+ from services.plugin.tool import ToolNode
+
+ success, payload, error = ToolNode.interpret_result({"success": False, "error": "tool crashed"})
+ assert success is False
+ assert payload is None
+ assert error == "tool crashed"
+
+ def test_every_toolnode_subclass_inherits_override(self):
+ """Every ToolNode subclass must resolve ``interpret_result`` to
+ the ToolNode override (or further override it). If a subclass
+ accidentally reverts to BaseNode's contract, every flat-dict
+ result is misclassified as failure."""
+ from services.plugin.base import BaseNode
+ from services.plugin.tool import ToolNode
+
+ for cls in _all_plugin_classes():
+ if not issubclass(cls, ToolNode):
+ continue
+ # Resolved method must come from ToolNode or a ToolNode
+ # subclass — NEVER from BaseNode directly.
+ owner = cls.interpret_result.__func__.__qualname__.split(".")[0]
+ assert owner != BaseNode.__name__, (
+ f"{cls.__qualname__}.interpret_result resolves to "
+ f"BaseNode — flat-dict ToolNode results will be "
+ f"misclassified as failure. Override on ToolNode or the "
+ f"subclass must shadow the base method."
+ )
+
+
+class TestNeedsCanvasContract:
+ """``needs_canvas`` is the declarative flag plugins opt into when
+ their operations require the parent workflow's full canvas
+ (``nodes`` + ``edges``) inside ``NodeContext``. The F4.B
+ AgentWorkflow tool-dispatch path reads this attribute to decide
+ whether to forward the canvas; default ``False`` keeps the regular-
+ tool fast path canvas-free.
+ """
+
+ def test_basenode_default_is_false(self):
+ from services.plugin.base import BaseNode
+
+ assert BaseNode.needs_canvas is False, "BaseNode.needs_canvas must default to False — only canvas-mutating " "plugins (agentBuilder) opt in to True"
+
+ def test_agent_builder_opts_in(self):
+ """AgentBuilderNode walks edges to resolve its calling agent
+ and mutates the canvas. Without ``needs_canvas = True`` the
+ F4.B path drops the canvas and ``_resolve_caller`` falls back
+ to self-as-caller — newly-spawned tools wire to agentBuilder
+ instead of the parent AI Agent."""
+ from nodes.tool.agent_builder import AgentBuilderNode
+
+ assert AgentBuilderNode.needs_canvas is True
+
+ def test_regular_tools_do_not_need_canvas(self):
+ """Sanity check that the common case (calculatorTool,
+ currentTimeTool, writeTodos, …) does NOT leak the canvas into
+ their per-tool activity context."""
+ from services.plugin.tool import ToolNode
+
+ for cls in _all_plugin_classes():
+ if not issubclass(cls, ToolNode):
+ continue
+ if cls.type == "agentBuilder":
+ continue
+ assert cls.needs_canvas is False, (
+ f"{cls.__qualname__} declares needs_canvas=True but isn't agentBuilder. "
+ f"Add the plugin to the canvas-aware allowlist in the "
+ f"AgentWorkflow tool-dispatch comment if this is intentional, "
+ f"or remove the override if accidental."
+ )
+
+
class TestTriggerRegistryAutoPopulate:
"""Wave 11.D.11: every event-mode TriggerNode plugin must register
itself into event_waiter.TRIGGER_REGISTRY + FILTER_BUILDERS