Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(plugins): keep a node's locked settings out of the model's reach
trohitgcc3cdff7728b
diff --git a/docs-internal/tool_building_pipeline.md b/docs-internal/tool_building_pipeline.mdindex f85e5d90..d704df8b 100644--- a/docs-internal/tool_building_pipeline.md+++ b/docs-internal/tool_building_pipeline.md@@ -275,12 +275,14 @@ The shortest path:`tool_description` class variables.4. (Optional) Add a special schema clause to `_get_tool_schema` only when theplugin's `Params` model is not the correct invocation contract.-5. (Optional) Override `execute_as_tool` on the plugin class when the- model's arguments need adjusting before the operation runs —- `AccountScopedNode` in `nodes/discord/_base.py` strips its- `server_controlled_fields` this way. Do not add a clause to- `_dispatch_tool`: its plugin fast path already runs `execute_as_tool`- for every registered plugin.+5. (Optional) List settings the model must never choose (an account, a+ profile, a mount) in `server_controlled_fields`. The framework keeps them+ out of the model's reach on every path: `execute_as_tool` strips them from+ the model's arguments, and `NodeExecutor` restores the saved value on the+ Temporal path. Override `execute_as_tool` only when the model's arguments+ need some other adjustment. Do not add a clause to `_dispatch_tool`: its+ plugin fast path already runs `execute_as_tool` for every registered+ plugin.Steps 4-5 are usually unnecessary — most new tools are fully described bytheir plugin class.diff --git a/server/nodes/discord/_base.py b/server/nodes/discord/_base.pyindex af355155..cdae3c42 100644--- a/server/nodes/discord/_base.py+++ b/server/nodes/discord/_base.py@@ -29,18 +29,16 @@ logger = get_logger(__name__)class AccountScopedNode(ActionNode, abstract=True):"""ActionNode whose ``server_controlled_fields`` survive the tool path.- ``BaseNode.execute_as_tool`` enforces ``server_controlled_fields`` only in- its ToolNode branch. A dual-purpose ActionNode takes an earlier return- that merges ``{**node_params, **tool_args}`` with model arguments winning,- so the declaration alone protects nothing here.-- That matters because inbound Discord messages are the realistic source of- hostile tool arguments, and ``account_id`` selects which bot identity- sends. Stripping the locked fields from the model's arguments before the- merge is what makes the declaration real. whatsapp_business solves the- same problem by sourcing its sending number from the credential instead;- that is not available here, because choosing between several stored- accounts is the point.+ ``account_id`` selects which bot identity sends, and inbound Discord+ messages are the realistic source of hostile tool arguments, so each+ subclass lists ``account_id`` in ``server_controlled_fields``. The+ framework enforces that on every tool path (``BaseNode.execute_as_tool``+ strips locked fields from the model's arguments, and ``NodeExecutor``+ restores the saved value on the Temporal path); this override strips them+ again so the guarantee stays local to the nodes that depend on it.+ whatsapp_business solves the same problem by taking its sending number+ from the credential instead; that is not available here, because+ choosing between several stored accounts is the point."""async def execute_as_tool(diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex d007dd2d..d837a4e3 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -19,6 +19,7 @@ from constants import (from pydantic import ValidationErrorfrom services.node_registry import get_node_classfrom services.parameter_resolver import template_view+from services.plugin.base import locked_tool_fields# Wave 11.D.13 sunset: every handler that was imported here is now# either (a) called lazily from a plugin's execute_op / execute method,# or (b) retired entirely. The dispatcher itself only needs the@@ -139,8 +140,23 @@ class NodeExecutor:execution_id = context.get("execution_id") or str(uuid.uuid4())[:8]try:+ # An LLM tool call carries the model's own arguments in+ # ``tool_args``; ``parameters`` already has them merged on top of+ # the node's settings (the agent workflow builds+ # ``{**tool params, **call args}``).+ tool_args = context.get("tool_args")+ if isinstance(tool_args, dict):+ locked = locked_tool_fields(get_node_class(node_type))+ if locked:+ context = {+ **context,+ "tool_args": {k: v for k, v in tool_args.items() if k not in locked},+ }+ else:+ tool_args = None+# Load, validate, enhance parameters- params = await self._prepare_parameters(node_id, node_type, parameters, session_id)+ params = await self._prepare_parameters(node_id, node_type, parameters, session_id, tool_args=tool_args)# Resolve templates if resolver providednodes = context.get("nodes")@@ -221,12 +237,33 @@ class NodeExecutor:False, node_id, node_type, error=str(e), execution_id=execution_id, execution_time=time.time() - start_time).to_dict()- async def _prepare_parameters(self, node_id: str, node_type: str, params: Dict, session_id: str) -> Dict:+ async def _prepare_parameters(+ self,+ node_id: str,+ node_type: str,+ params: Dict,+ session_id: str,+ tool_args: Optional[Dict[str, Any]] = None,+ ) -> Dict:"""Load from DB, validate, inject API keys."""# Merge with DB parameters (DB provides defaults, frontend can override)db_params = await self.database.get_node_parameters(node_id) or {}merged = {**db_params, **params} if params else db_params+ # On an LLM tool call the model never chooses a node's locked fields+ # (``server_controlled_fields``: the sending account, the browser+ # profile, data mounts...). The saved setting wins; with none saved,+ # the field falls back to its default rather than to the model's value.+ if tool_args:+ locked = locked_tool_fields(get_node_class(node_type))+ if locked & tool_args.keys():+ merged = dict(merged)+ for field_name in locked & tool_args.keys():+ if field_name in db_params:+ merged[field_name] = db_params[field_name]+ else:+ merged.pop(field_name, None)+# Validate via plugin Params (snake_case, plugin-only path).node_cls = get_node_class(node_type)params_model = getattr(node_cls, "Params", None) if node_cls else Nonediff --git a/server/services/plugin/base.py b/server/services/plugin/base.pyindex ba82786e..d1be9cf4 100644--- a/server/services/plugin/base.py+++ b/server/services/plugin/base.py@@ -80,6 +80,20 @@ class NodeUserError(Exception):}+def locked_tool_fields(node_cls: Any) -> frozenset:+ """Fields a model may never set through tool arguments.++ A plugin lists them in ``server_controlled_fields``: the sending account,+ the browser profile, data mounts and the like. ``execute_as_tool`` strips+ them from the model's arguments, and ``NodeExecutor`` restores the saved+ value on the Temporal path, where the agent workflow has already merged+ the arguments into the node's parameters.+ """+ if node_cls is None:+ return frozenset()+ return frozenset(getattr(node_cls, "server_controlled_fields", ()) or ())++NODE_WAIT_INTERRUPTED = "NodeWaitInterrupted"@@ -711,13 +725,17 @@ class BaseNode:"""from services.plugin.tool import ToolNode+ locked = locked_tool_fields(type(self))is_tool_node = isinstance(self, ToolNode)if not is_tool_node:- # Dual-purpose ActionNodes retain the established tool contract.- # ToolInput is a ToolNode extension and must not change them.+ # Dual-purpose ActionNodes retain the established tool contract+ # (model arguments win the merge) except for locked fields, which+ # come from the node's settings only. ToolInput is a ToolNode+ # extension and must not change them.+ model_args = {k: v for k, v in (tool_args or {}).items() if k not in locked}envelope = await self.execute(context.node_id,- {**node_params, **tool_args},+ {**node_params, **model_args},context,)if "success" not in envelope:@@ -745,11 +763,13 @@ class BaseNode:# malformed node configuration.type(self).partial_config_model().model_validate(node_params)# Preserve the legacy contract for existing plugins, while- # allowing a plugin to lock specific persisted settings.- effective = {**node_params, **input_payload}- for field_name in getattr(type(self), "server_controlled_fields", ()):- if field_name in node_params:- effective[field_name] = node_params[field_name]+ # letting a plugin lock specific settings: a locked field+ # comes from the node's settings, or else its default, never+ # from the model.+ effective = {+ **node_params,+ **{k: v for k, v in input_payload.items() if k not in locked},+ }validated_config = self.Params.model_validate(effective)invocation_payload = validated_config.model_dump()split_schema = Falsediff --git a/server/tests/services/test_tool_input_security.py b/server/tests/services/test_tool_input_security.pyindex 2b905d40..71309c40 100644--- a/server/tests/services/test_tool_input_security.py+++ b/server/tests/services/test_tool_input_security.py@@ -296,3 +296,130 @@ async def test_memory_panel_scope_is_resolved_from_workflow_and_auth(assert scope.memory_node_id == "memory-1"assert scope.owner_id == "authenticated-user"assert scope.namespace_id != "client-chosen-namespace"+++class _LockedModeParams(BaseModel):+ query: str = ""+ mode: str = "safe"+++class _LockedModeOutput(BaseModel):+ query: str+ mode: str+++class _LockedLegacyToolNode(ToolNode, abstract=True):+ type = "_testLockedLegacyTool"+ display_name = "Locked Legacy Tool Test"+ group = ("tool",)+ description = "Test-only locked field on a ToolInput-is-Params tool"+ handles = _ConfiguredToolNode.handles+ ui_hints = {"hideRunButton": True}+ Params = _LockedModeParams+ ToolInput = _LockedModeParams+ Output = _LockedModeOutput+ server_controlled_fields = frozenset({"mode"})++ @Operation("run")+ async def run(self, ctx: NodeContext, params: _LockedModeParams) -> _LockedModeOutput:+ return _LockedModeOutput(query=params.query, mode=params.mode)+++class _LockedDualPurposeActionNode(ActionNode, abstract=True):+ type = "_testLockedDualPurposeAction"+ usable_as_tool = True+ Params = _LockedModeParams+ Output = _LockedModeOutput+ server_controlled_fields = frozenset({"mode"})++ @Operation("run")+ async def run(self, ctx: NodeContext, params: _LockedModeParams) -> _LockedModeOutput:+ return _LockedModeOutput(query=params.query, mode=params.mode)+++async def test_locked_field_falls_back_to_its_default_not_the_model():+ result = await _LockedLegacyToolNode().execute_as_tool(+ {"query": "hello", "mode": "unsafe"},+ {},+ NodeContext(node_id="locked-tool", node_type=_LockedLegacyToolNode.type, raw={}),+ )+ assert result == {"query": "hello", "mode": "safe"}++[email protected]("saved", [{"mode": "saved"}, {}])+async def test_action_node_tools_cannot_set_locked_fields(saved):+ result = await _LockedDualPurposeActionNode().execute_as_tool(+ {"query": "hello", "mode": "unsafe"},+ saved,+ NodeContext(node_id="locked-action", node_type=_LockedDualPurposeActionNode.type, raw={}),+ )+ assert result == {"query": "hello", "mode": saved.get("mode", "safe")}+++def _capture_dispatch(harness, monkeypatch):+ captured: dict = {}++ async def fake_dispatch(node_id, node_type, params, ctx):+ captured["params"] = params+ captured["ctx"] = ctx+ return {"success": True, "result": {}}++ monkeypatch.setattr(harness.executor, "_dispatch", fake_dispatch)+ return captured+++ ("node_type", "field", "saved", "model"),+ [+ ("discordSend", "account_id", "default", "attacker-bot"),+ ("browser", "interaction", "read_only", "full"),+ ("browser", "profile_id", "owner-profile", "someone-elses-profile"),+ ],+)+async def test_temporal_tool_calls_cannot_override_locked_settings(harness, monkeypatch, node_type, field, saved, model):+ # The agent workflow hands the per-type activity ``{**tool params, **call+ # args}`` plus the raw call args as ``tool_args``; the saved setting must win.+ harness.database.get_node_parameters = AsyncMock(return_value={field: saved})+ captured = _capture_dispatch(harness, monkeypatch)+ model_args = {field: model, "note": "from the model"}++ await harness.executor.execute(+ node_id="tool-1",+ node_type=node_type,+ parameters=dict(model_args),+ context=harness.build_context(extra={"tool_args": dict(model_args)}),+ )++ assert captured["params"][field] == saved+ assert captured["params"]["note"] == "from the model"+ assert field not in captured["ctx"]["tool_args"]+ assert captured["ctx"]["tool_args"]["note"] == "from the model"+++async def test_temporal_tool_call_drops_a_locked_field_that_was_never_saved(harness, monkeypatch):+ harness.database.get_node_parameters = AsyncMock(return_value={})+ captured = _capture_dispatch(harness, monkeypatch)++ await harness.executor.execute(+ node_id="discord-1",+ node_type="discordSend",+ parameters={"account_id": "attacker-bot"},+ context=harness.build_context(extra={"tool_args": {"account_id": "attacker-bot"}}),+ )++ assert "account_id" not in captured["params"]+++async def test_locked_fields_bind_only_tool_calls(harness, monkeypatch):+ # A canvas run or a workflow edge is the operator's own configuration.+ harness.database.get_node_parameters = AsyncMock(return_value={"account_id": "default"})+ captured = _capture_dispatch(harness, monkeypatch)++ await harness.executor.execute(+ node_id="discord-1",+ node_type="discordSend",+ parameters={"account_id": "ops-bot"},+ context=harness.build_context(),+ )++ assert captured["params"]["account_id"] == "ops-bot"