AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(copilot): add tool/block capability filtering to AutoPilotBlock (#12482)
Zamil Majdyee5382a06407
diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.pyindex 88eea3fbd2..27765f6744 100644--- a/autogpt_platform/backend/backend/blocks/autopilot.py+++ b/autogpt_platform/backend/backend/blocks/autopilot.py@@ -15,6 +15,12 @@ from backend.blocks._base import (BlockSchemaInput,BlockSchemaOutput,)+from backend.copilot.permissions import (+ CopilotPermissions,+ ToolName,+ all_known_tool_names,+ validate_block_identifiers,+)from backend.data.model import SchemaFieldif TYPE_CHECKING:@@ -96,6 +102,50 @@ class AutoPilotBlock(Block):advanced=True,)+ tools: list[ToolName] = SchemaField(+ description=(+ "Tool names to filter. Works with tools_exclude to form an "+ "allow-list or deny-list. "+ "Leave empty to apply no tool filter."+ ),+ default=[],+ advanced=True,+ )++ tools_exclude: bool = SchemaField(+ description=(+ "Controls how the 'tools' list is interpreted. "+ "True (default): 'tools' is a deny-list — listed tools are blocked, "+ "all others are allowed. An empty 'tools' list means allow everything. "+ "False: 'tools' is an allow-list — only listed tools are permitted."+ ),+ default=True,+ advanced=True,+ )++ blocks: list[str] = SchemaField(+ description=(+ "Block identifiers to filter when the copilot uses run_block. "+ "Each entry can be: a block name (e.g. 'HTTP Request'), "+ "a full block UUID, or the first 8 hex characters of the UUID "+ "(e.g. 'c069dc6b'). Works with blocks_exclude. "+ "Leave empty to apply no block filter."+ ),+ default=[],+ advanced=True,+ )++ blocks_exclude: bool = SchemaField(+ description=(+ "Controls how the 'blocks' list is interpreted. "+ "True (default): 'blocks' is a deny-list — listed blocks are blocked, "+ "all others are allowed. An empty 'blocks' list means allow everything. "+ "False: 'blocks' is an allow-list — only listed blocks are permitted."+ ),+ default=True,+ advanced=True,+ )+# timeout_seconds removed: the SDK manages its own heartbeat-based# timeouts internally; wrapping with asyncio.timeout corrupts the# SDK's internal stream (see service.py CRITICAL comment).@@ -184,7 +234,7 @@ class AutoPilotBlock(Block):async def create_session(self, user_id: str) -> str:"""Create a new chat session and return its ID (mockable for tests)."""- from backend.copilot.model import create_chat_session+ from backend.copilot.model import create_chat_session # avoid circular importsession = await create_chat_session(user_id)return session.session_id@@ -196,6 +246,7 @@ class AutoPilotBlock(Block):session_id: str,max_recursion_depth: int,user_id: str,+ permissions: "CopilotPermissions | None" = None,) -> tuple[str, list[ToolCallEntry], str, str, TokenUsage]:"""Invoke the copilot and collect all stream results.@@ -209,14 +260,21 @@ class AutoPilotBlock(Block):session_id: Chat session to use.max_recursion_depth: Maximum allowed recursion nesting.user_id: Authenticated user ID.+ permissions: Optional capability filter restricting tools/blocks.Returns:A tuple of (response_text, tool_calls, history_json, session_id, usage)."""- from backend.copilot.sdk.collect import collect_copilot_response+ from backend.copilot.sdk.collect import (+ collect_copilot_response, # avoid circular import+ )tokens = _check_recursion(max_recursion_depth)+ perm_token = Nonetry:+ effective_permissions, perm_token = _merge_inherited_permissions(+ permissions+ )effective_prompt = promptif system_context:effective_prompt = f"[System Context: {system_context}]\n\n{prompt}"@@ -225,6 +283,7 @@ class AutoPilotBlock(Block):session_id=session_id,message=effective_prompt,user_id=user_id,+ permissions=effective_permissions,)# Build a lightweight conversation summary from streamed data.@@ -271,6 +330,8 @@ class AutoPilotBlock(Block):)finally:_reset_recursion(tokens)+ if perm_token is not None:+ _inherited_permissions.reset(perm_token)async def run(self,@@ -295,6 +356,13 @@ class AutoPilotBlock(Block):yield "error", "max_recursion_depth must be at least 1."return+ # Validate and build permissions eagerly — fail before creating a session.+ permissions = await _build_and_validate_permissions(input_data)+ if isinstance(permissions, str):+ # Validation error returned as a string message.+ yield "error", permissions+ return+# Create session eagerly so the user always gets the session_id,# even if the downstream stream fails (avoids orphaned sessions).sid = input_data.session_id@@ -312,6 +380,7 @@ class AutoPilotBlock(Block):session_id=sid,max_recursion_depth=input_data.max_recursion_depth,user_id=execution_context.user_id,+ permissions=permissions,)yield "response", response@@ -374,3 +443,78 @@ def _reset_recursion("""Restore recursion depth and limit to their previous values."""_autopilot_recursion_depth.reset(tokens[0])_autopilot_recursion_limit.reset(tokens[1])+++# ---------------------------------------------------------------------------+# Permission helpers+# ---------------------------------------------------------------------------++# Inherited permissions from a parent AutoPilotBlock execution.+# This acts as a ceiling: child executions can only be more restrictive.+_inherited_permissions: contextvars.ContextVar["CopilotPermissions | None"] = (+ contextvars.ContextVar("_inherited_permissions", default=None)+)+++async def _build_and_validate_permissions(+ input_data: "AutoPilotBlock.Input",+) -> "CopilotPermissions | str":+ """Build a :class:`CopilotPermissions` from block input and validate it.++ Returns a :class:`CopilotPermissions` on success or a human-readable+ error string if validation fails.+ """+ # Tool names are validated by Pydantic via the ToolName Literal type+ # at model construction time — no runtime check needed here.+ # Validate block identifiers against live block registry.+ if input_data.blocks:+ invalid_blocks = await validate_block_identifiers(input_data.blocks)+ if invalid_blocks:+ return (+ f"Unknown block identifier(s) in 'blocks': {invalid_blocks}. "+ "Use find_block to discover valid block names and IDs. "+ "You may also use the first 8 characters of a block UUID."+ )++ return CopilotPermissions(+ tools=list(input_data.tools),+ tools_exclude=input_data.tools_exclude,+ blocks=input_data.blocks,+ blocks_exclude=input_data.blocks_exclude,+ )+++def _merge_inherited_permissions(+ permissions: "CopilotPermissions | None",+) -> "tuple[CopilotPermissions | None, contextvars.Token[CopilotPermissions | None] | None]":+ """Merge *permissions* with any inherited parent permissions.++ The merged result is stored back into the contextvar so that any nested+ AutoPilotBlock invocation (sub-agent) inherits the merged ceiling.++ Returns a tuple of (merged_permissions, reset_token). The caller MUST+ reset the contextvar via ``_inherited_permissions.reset(token)`` in a+ ``finally`` block when ``reset_token`` is not None — this prevents+ permission leakage between sequential independent executions in the same+ asyncio task.+ """+ parent = _inherited_permissions.get()++ if permissions is None and parent is None:+ return None, None++ all_tools = all_known_tool_names()++ if permissions is None:+ permissions = CopilotPermissions() # allow-all; will be narrowed by parent++ merged = (+ permissions.merged_with_parent(parent, all_tools)+ if parent is not None+ else permissions+ )++ # Store merged permissions as the new inherited ceiling for nested calls.+ # Return the token so the caller can restore the previous value in finally.+ token = _inherited_permissions.set(merged)+ return merged, tokendiff --git a/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py b/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.pynew file mode 100644index 0000000000..0e406d1eb8--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py@@ -0,0 +1,265 @@+"""Tests for AutoPilotBlock permission fields and validation."""++from __future__ import annotations++from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from pydantic import ValidationError++from backend.blocks.autopilot import (+ AutoPilotBlock,+ _build_and_validate_permissions,+ _inherited_permissions,+ _merge_inherited_permissions,+)+from backend.copilot.permissions import CopilotPermissions, all_known_tool_names+from backend.data.execution import ExecutionContext++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_input(**kwargs) -> AutoPilotBlock.Input:+ defaults = {+ "prompt": "Do something",+ "system_context": "",+ "session_id": "",+ "max_recursion_depth": 3,+ "tools": [],+ "tools_exclude": True,+ "blocks": [],+ "blocks_exclude": True,+ }+ defaults.update(kwargs)+ return AutoPilotBlock.Input(**defaults)+++# ---------------------------------------------------------------------------+# _build_and_validate_permissions+# ---------------------------------------------------------------------------+++class TestBuildAndValidatePermissions:+ async def test_empty_inputs_returns_empty_permissions(self):+ inp = _make_input()+ result = await _build_and_validate_permissions(inp)+ assert isinstance(result, CopilotPermissions)+ assert result.is_empty()++ async def test_valid_tool_names_accepted(self):+ inp = _make_input(tools=["run_block", "web_fetch"], tools_exclude=True)+ result = await _build_and_validate_permissions(inp)+ assert isinstance(result, CopilotPermissions)+ assert result.tools == ["run_block", "web_fetch"]+ assert result.tools_exclude is True++ async def test_invalid_tool_rejected_by_pydantic(self):+ """Invalid tool names are now caught at Pydantic validation time+ (Literal type), before ``_build_and_validate_permissions`` is called."""+ with pytest.raises(ValidationError, match="not_a_real_tool"):+ _make_input(tools=["not_a_real_tool"])++ async def test_valid_block_name_accepted(self):+ mock_block_cls = MagicMock()+ mock_block_cls.return_value.name = "HTTP Request"+ with patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block_cls},+ ):+ inp = _make_input(blocks=["HTTP Request"], blocks_exclude=True)+ result = await _build_and_validate_permissions(inp)+ assert isinstance(result, CopilotPermissions)+ assert result.blocks == ["HTTP Request"]++ async def test_valid_partial_uuid_accepted(self):+ mock_block_cls = MagicMock()+ mock_block_cls.return_value.name = "HTTP Request"+ with patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block_cls},+ ):+ inp = _make_input(blocks=["c069dc6b"], blocks_exclude=False)+ result = await _build_and_validate_permissions(inp)+ assert isinstance(result, CopilotPermissions)++ async def test_invalid_block_identifier_returns_error(self):+ mock_block_cls = MagicMock()+ mock_block_cls.return_value.name = "HTTP Request"+ with patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block_cls},+ ):+ inp = _make_input(blocks=["totally_fake_block"])+ result = await _build_and_validate_permissions(inp)+ assert isinstance(result, str)+ assert "totally_fake_block" in result+ assert "Unknown block identifier" in result++ async def test_sdk_builtin_tool_names_accepted(self):+ inp = _make_input(tools=["Read", "Task", "WebSearch"], tools_exclude=False)+ result = await _build_and_validate_permissions(inp)+ assert isinstance(result, CopilotPermissions)+ assert not result.tools_exclude++ async def test_empty_blocks_skips_validation(self):+ # Should not call validate_block_identifiers at all when blocks=[].+ with patch(+ "backend.copilot.permissions.validate_block_identifiers"+ ) as mock_validate:+ inp = _make_input(blocks=[])+ await _build_and_validate_permissions(inp)+ mock_validate.assert_not_called()+++# ---------------------------------------------------------------------------+# _merge_inherited_permissions+# ---------------------------------------------------------------------------+++class TestMergeInheritedPermissions:+ def test_no_permissions_no_parent_returns_none(self):+ merged, token = _merge_inherited_permissions(None)+ assert merged is None+ assert token is None++ def test_permissions_no_parent_returned_unchanged(self):+ perms = CopilotPermissions(tools=["bash_exec"], tools_exclude=True)+ merged, token = _merge_inherited_permissions(perms)+ try:+ assert merged is perms+ assert token is not None+ finally:+ if token is not None:+ _inherited_permissions.reset(token)++ def test_child_narrows_parent(self):+ parent = CopilotPermissions(tools=["bash_exec"], tools_exclude=True)+ # Set parent as inherited+ outer_token = _inherited_permissions.set(parent)+ try:+ child = CopilotPermissions(tools=["web_fetch"], tools_exclude=True)+ merged, inner_token = _merge_inherited_permissions(child)+ try:+ assert merged is not None+ all_t = all_known_tool_names()+ effective = merged.effective_allowed_tools(all_t)+ assert "bash_exec" not in effective+ assert "web_fetch" not in effective+ finally:+ if inner_token is not None:+ _inherited_permissions.reset(inner_token)+ finally:+ _inherited_permissions.reset(outer_token)++ def test_none_permissions_with_parent_uses_parent(self):+ parent = CopilotPermissions(tools=["bash_exec"], tools_exclude=True)+ outer_token = _inherited_permissions.set(parent)+ try:+ merged, inner_token = _merge_inherited_permissions(None)+ try:+ assert merged is not None+ # Merged should have parent's restrictions+ effective = merged.effective_allowed_tools(all_known_tool_names())+ assert "bash_exec" not in effective+ finally:+ if inner_token is not None:+ _inherited_permissions.reset(inner_token)+ finally:+ _inherited_permissions.reset(outer_token)++ def test_child_cannot_expand_parent_whitelist(self):+ parent = CopilotPermissions(tools=["run_block"], tools_exclude=False)+ outer_token = _inherited_permissions.set(parent)+ try:+ # Child tries to allow more tools+ child = CopilotPermissions(+ tools=["run_block", "bash_exec"], tools_exclude=False+ )+ merged, inner_token = _merge_inherited_permissions(child)+ try:+ assert merged is not None+ effective = merged.effective_allowed_tools(all_known_tool_names())+ assert "bash_exec" not in effective+ assert "run_block" in effective+ finally:+ if inner_token is not None:+ _inherited_permissions.reset(inner_token)+ finally:+ _inherited_permissions.reset(outer_token)+++# ---------------------------------------------------------------------------+# AutoPilotBlock.run — validation integration+# ---------------------------------------------------------------------------+++class TestAutoPilotBlockRunPermissions:+ async def _collect_outputs(self, block, input_data, user_id="test-user"):+ """Helper to collect all yields from block.run()."""+ ctx = ExecutionContext(+ user_id=user_id,+ graph_id="g1",+ graph_exec_id="ge1",+ node_exec_id="ne1",+ node_id="n1",+ )+ outputs = {}+ async for key, val in block.run(input_data, execution_context=ctx):+ outputs[key] = val+ return outputs++ async def test_invalid_tool_rejected_by_pydantic(self):+ """Invalid tool names are caught at Pydantic validation (Literal type)."""+ with pytest.raises(ValidationError, match="not_a_tool"):+ _make_input(tools=["not_a_tool"])++ async def test_invalid_block_yields_error(self):+ mock_block_cls = MagicMock()+ mock_block_cls.return_value.name = "HTTP Request"+ with patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block_cls},+ ):+ block = AutoPilotBlock()+ inp = _make_input(blocks=["nonexistent_block"])+ outputs = await self._collect_outputs(block, inp)+ assert "error" in outputs+ assert "nonexistent_block" in outputs["error"]++ async def test_empty_prompt_yields_error_before_permission_check(self):+ block = AutoPilotBlock()+ inp = _make_input(prompt=" ", tools=["run_block"])+ outputs = await self._collect_outputs(block, inp)+ assert "error" in outputs+ assert "Prompt cannot be empty" in outputs["error"]++ async def test_valid_permissions_passed_to_execute(self):+ """Permissions are forwarded to execute_copilot when valid."""+ block = AutoPilotBlock()+ captured: dict = {}++ async def fake_execute_copilot(self_inner, **kwargs):+ captured["permissions"] = kwargs.get("permissions")+ return (+ "ok",+ [],+ '[{"role":"user","content":"hi"}]',+ "test-sid",+ {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ )++ with patch.object(+ AutoPilotBlock, "create_session", new=AsyncMock(return_value="test-sid")+ ), patch.object(AutoPilotBlock, "execute_copilot", new=fake_execute_copilot):+ inp = _make_input(tools=["run_block"], tools_exclude=False)+ outputs = await self._collect_outputs(block, inp)++ assert "error" not in outputs+ perms = captured.get("permissions")+ assert isinstance(perms, CopilotPermissions)+ assert perms.tools == ["run_block"]+ assert perms.tools_exclude is Falsediff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.pyindex 81fdb44451..1b32a9b92d 100644--- a/autogpt_platform/backend/backend/copilot/context.py+++ b/autogpt_platform/backend/backend/copilot/context.py@@ -17,6 +17,9 @@ from backend.util.workspace import WorkspaceManagerif TYPE_CHECKING:from e2b import AsyncSandbox+ from backend.copilot.permissions import CopilotPermissions++# Allowed base directory for the Read tool. Public so service.py can use it# for sweep operations without depending on a private implementation detail.# Respects CLAUDE_CONFIG_DIR env var, consistent with transcript.py's@@ -43,6 +46,12 @@ _current_sandbox: ContextVar["AsyncSandbox | None"] = ContextVar()_current_sdk_cwd: ContextVar[str] = ContextVar("_current_sdk_cwd", default="")+# Current execution's capability filter. None means "no restrictions".+# Set by set_execution_context(); read by run_block and service.py.+_current_permissions: "ContextVar[CopilotPermissions | None]" = ContextVar(+ "_current_permissions", default=None+)+def encode_cwd_for_cli(cwd: str) -> str:"""Encode a working directory path the same way the Claude CLI does.@@ -63,6 +72,7 @@ def set_execution_context(session: ChatSession,sandbox: "AsyncSandbox | None" = None,sdk_cwd: str | None = None,+ permissions: "CopilotPermissions | None" = None,) -> None:"""Set per-turn context variables used by file-resolution tool handlers."""_current_user_id.set(user_id)@@ -70,6 +80,7 @@ def set_execution_context(_current_sandbox.set(sandbox)_current_sdk_cwd.set(sdk_cwd or "")_current_project_dir.set(_encode_cwd_for_cli(sdk_cwd) if sdk_cwd else "")+ _current_permissions.set(permissions)def get_execution_context() -> tuple[str | None, ChatSession | None]:@@ -77,6 +88,11 @@ def get_execution_context() -> tuple[str | None, ChatSession | None]:return _current_user_id.get(), _current_session.get()+def get_current_permissions() -> "CopilotPermissions | None":+ """Return the capability filter for the current execution, or None if unrestricted."""+ return _current_permissions.get()++def get_current_sandbox() -> "AsyncSandbox | None":"""Return the E2B sandbox for the current session, or None if not active."""return _current_sandbox.get()diff --git a/autogpt_platform/backend/backend/copilot/context_test.py b/autogpt_platform/backend/backend/copilot/context_test.pyindex 9c530ab911..f3f6bb9a6a 100644--- a/autogpt_platform/backend/backend/copilot/context_test.py+++ b/autogpt_platform/backend/backend/copilot/context_test.py@@ -11,6 +11,7 @@ import pytestfrom backend.copilot.context import (SDK_PROJECTS_DIR,_current_project_dir,+ get_current_permissions,get_current_sandbox,get_execution_context,get_sdk_cwd,@@ -18,6 +19,7 @@ from backend.copilot.context import (resolve_sandbox_path,set_execution_context,)+from backend.copilot.permissions import CopilotPermissionsdef _make_session() -> MagicMock:@@ -61,6 +63,19 @@ def test_get_current_sandbox_returns_set_value():assert get_current_sandbox() is mock_sandbox+def test_set_and_get_current_permissions():+ """set_execution_context stores permissions; get_current_permissions returns it."""+ perms = CopilotPermissions(tools=["run_block"], tools_exclude=False)+ set_execution_context("u1", _make_session(), permissions=perms)+ assert get_current_permissions() is perms+++def test_get_current_permissions_defaults_to_none():+ """get_current_permissions returns None when no permissions have been set."""+ set_execution_context("u1", _make_session())+ assert get_current_permissions() is None++def test_get_sdk_cwd_empty_when_not_set():"""get_sdk_cwd returns empty string when sdk_cwd is not set."""set_execution_context("u1", _make_session(), sdk_cwd=None)diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pynew file mode 100644index 0000000000..5c902b23be--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -0,0 +1,430 @@+"""Copilot execution permissions — tool and block allow/deny filtering.++:class:`CopilotPermissions` is the single model used everywhere:++- ``AutoPilotBlock`` reads four block-input fields and builds one instance.+- ``stream_chat_completion_sdk`` applies it when constructing+ ``ClaudeAgentOptions.allowed_tools`` / ``disallowed_tools``.+- ``run_block`` reads it from the contextvar to gate block execution.+- Recursive (sub-agent) invocations merge parent and child so children+ can only be *more* restrictive, never more permissive.++Tool names+----------+Users specify the **short name** as it appears in ``TOOL_REGISTRY`` (e.g.+``run_block``, ``web_fetch``) or as an SDK built-in (e.g. ``Read``,+``Task``, ``WebSearch``). Internally these are mapped to the full SDK+format (``mcp__copilot__run_block``, ``Read``, …) by+:func:`apply_tool_permissions`.++Block identifiers+-----------------+Each entry in ``blocks`` may be one of:++- A **full UUID** (``c069dc6b-c3ed-4c12-b6e5-d47361e64ce6``)+- A **partial UUID** — the first 8-character hex segment (``c069dc6b``)+- A **block name** (case-insensitive, e.g. ``"HTTP Request"``)++:func:`validate_block_identifiers` resolves all entries against the live+block registry and returns any that could not be matched.++Semantics+---------+``tools_exclude=True`` (default) — ``tools`` is a **blacklist**; listed+tools are denied and everything else is allowed. An empty list means+"allow all" (no filtering).++``tools_exclude=False`` — ``tools`` is a **whitelist**; only listed tools+are allowed.++``blocks_exclude`` follows the same pattern for ``blocks``.++Recursion inheritance+---------------------+:meth:`CopilotPermissions.merged_with_parent` produces a new instance that+is at most as permissive as the parent:++- Tools: effective-allowed sets are intersected then stored as a whitelist.+- Blocks: the parent is stored in ``_parent`` and consulted during every+ :meth:`is_block_allowed` call so both constraints must pass.+"""++from __future__ import annotations++import re+from typing import Literal, get_args++from pydantic import BaseModel, PrivateAttr++# ---------------------------------------------------------------------------+# Constants — single source of truth for all accepted tool names+# ---------------------------------------------------------------------------++# Literal type combining all valid tool names — used by AutoPilotBlock.Input+# so the frontend renders a multi-select dropdown.+# This is the SINGLE SOURCE OF TRUTH. All other name sets are derived from it.+ToolName = Literal[+ # Platform tools (must match keys in TOOL_REGISTRY)+ "add_understanding",+ "bash_exec",+ "browser_act",+ "browser_navigate",+ "browser_screenshot",+ "connect_integration",+ "continue_run_block",+ "create_agent",+ "create_feature_request",+ "create_folder",+ "customize_agent",+ "delete_folder",+ "delete_workspace_file",+ "edit_agent",+ "find_agent",+ "find_block",+ "find_library_agent",+ "fix_agent_graph",+ "get_agent_building_guide",+ "get_doc_page",+ "get_mcp_guide",+ "list_folders",+ "list_workspace_files",+ "move_agents_to_folder",+ "move_folder",+ "read_workspace_file",+ "run_agent",+ "run_block",+ "run_mcp_tool",+ "search_docs",+ "search_feature_requests",+ "update_folder",+ "validate_agent_graph",+ "view_agent_output",+ "web_fetch",+ "write_workspace_file",+ # SDK built-ins+ "Edit",+ "Glob",+ "Grep",+ "Read",+ "Task",+ "TodoWrite",+ "WebSearch",+ "Write",+]++# Frozen set of all valid tool names — derived from the Literal.+ALL_TOOL_NAMES: frozenset[str] = frozenset(get_args(ToolName))++# SDK built-in tool names — uppercase-initial names are SDK built-ins.+SDK_BUILTIN_TOOL_NAMES: frozenset[str] = frozenset(+ n for n in ALL_TOOL_NAMES if n[0].isupper()+)++# Platform tool names — everything that isn't an SDK built-in.+PLATFORM_TOOL_NAMES: frozenset[str] = ALL_TOOL_NAMES - SDK_BUILTIN_TOOL_NAMES++# Compiled regex patterns for block identifier classification.+_FULL_UUID_RE = re.compile(+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",+ re.IGNORECASE,+)+_PARTIAL_UUID_RE = re.compile(r"^[0-9a-f]{8}$", re.IGNORECASE)+++# ---------------------------------------------------------------------------+# Helper — block identifier matching+# ---------------------------------------------------------------------------+++def _block_matches(identifier: str, block_id: str, block_name: str) -> bool:+ """Return True if *identifier* resolves to the given block.++ Resolution order:+ 1. Full UUID — exact case-insensitive match against *block_id*.+ 2. Partial UUID (8 hex chars, first segment) — prefix match.+ 3. Name — case-insensitive equality against *block_name*.+ """+ ident = identifier.strip()+ if _FULL_UUID_RE.match(ident):+ return ident.lower() == block_id.lower()+ if _PARTIAL_UUID_RE.match(ident):+ return block_id.lower().startswith(ident.lower())+ return ident.lower() == block_name.lower()+++# ---------------------------------------------------------------------------+# Model+# ---------------------------------------------------------------------------+++class CopilotPermissions(BaseModel):+ """Capability filter for a single copilot execution.++ Attributes:+ tools: Tool names to filter (short names, e.g. ``run_block``).+ tools_exclude: When True (default) ``tools`` is a blacklist;+ when False it is a whitelist. Ignored when *tools* is empty.+ blocks: Block identifiers (name, full UUID, or 8-char partial UUID).+ blocks_exclude: Same semantics as *tools_exclude* but for blocks.+ """++ tools: list[str] = []+ tools_exclude: bool = True+ blocks: list[str] = []+ blocks_exclude: bool = True++ # Private: parent permissions for recursion inheritance.+ # Set only by merged_with_parent(); never exposed in block input schema.+ _parent: CopilotPermissions | None = PrivateAttr(default=None)++ # ------------------------------------------------------------------+ # Tool helpers+ # ------------------------------------------------------------------++ def effective_allowed_tools(self, all_tools: frozenset[str]) -> frozenset[str]:+ """Compute the set of short tool names that are permitted.++ Args:+ all_tools: Universe of valid short tool names.++ Returns:+ Subset of *all_tools* that pass the filter.+ """+ if not self.tools:+ return frozenset(all_tools)+ tool_set = frozenset(self.tools)+ if self.tools_exclude:+ return all_tools - tool_set+ return all_tools & tool_set++ # ------------------------------------------------------------------+ # Block helpers+ # ------------------------------------------------------------------++ def is_block_allowed(self, block_id: str, block_name: str) -> bool:+ """Return True if the block may be executed under these permissions.++ Checks this instance first, then consults the parent (if any) so+ the entire inheritance chain is respected.+ """+ if not self._check_block_locally(block_id, block_name):+ return False+ if self._parent is not None:+ return self._parent.is_block_allowed(block_id, block_name)+ return True++ def _check_block_locally(self, block_id: str, block_name: str) -> bool:+ """Check *only* this instance's block filter (ignores parent)."""+ if not self.blocks:+ return True # No filter → allow all+ matched = any(+ _block_matches(identifier, block_id, block_name)+ for identifier in self.blocks+ )+ return not matched if self.blocks_exclude else matched++ # ------------------------------------------------------------------+ # Recursion / merging+ # ------------------------------------------------------------------++ def merged_with_parent(+ self,+ parent: CopilotPermissions,+ all_tools: frozenset[str],+ ) -> CopilotPermissions:+ """Return a new instance that is at most as permissive as *parent*.++ - Tools: intersection of effective-allowed sets, stored as a whitelist.+ - Blocks: parent is stored internally; both constraints are applied+ during :meth:`is_block_allowed`.+ """+ merged_tools = self.effective_allowed_tools(+ all_tools+ ) & parent.effective_allowed_tools(all_tools)+ result = CopilotPermissions(+ tools=sorted(merged_tools),+ tools_exclude=False,+ blocks=self.blocks,+ blocks_exclude=self.blocks_exclude,+ )+ result._parent = parent+ return result++ # ------------------------------------------------------------------+ # Convenience+ # ------------------------------------------------------------------++ def is_empty(self) -> bool:+ """Return True when no filtering is configured (allow-all passthrough)."""+ return not self.tools and not self.blocks and self._parent is None+++# ---------------------------------------------------------------------------+# Validation helpers+# ---------------------------------------------------------------------------+++def all_known_tool_names() -> frozenset[str]:+ """Return all short tool names accepted in *tools*.++ Returns the pre-computed ``ALL_TOOL_NAMES`` set (derived from the+ ``ToolName`` Literal). On first call, also verifies consistency with+ the live ``TOOL_REGISTRY``.+ """+ _assert_tool_names_consistent()+ return ALL_TOOL_NAMES+++def validate_tool_names(tools: list[str]) -> list[str]:+ """Return entries in *tools* that are not valid tool names.++ Args:+ tools: List of short tool name strings to validate.++ Returns:+ List of invalid names (empty if all are valid).+ """+ return [t for t in tools if t not in ALL_TOOL_NAMES]+++_tool_names_checked = False+++def _assert_tool_names_consistent() -> None:+ """Verify that ``PLATFORM_TOOL_NAMES`` matches ``TOOL_REGISTRY`` keys.++ Called once lazily (TOOL_REGISTRY has heavy imports). Raises+ ``AssertionError`` with a helpful diff if they diverge.+ """+ global _tool_names_checked+ if _tool_names_checked:+ return+ _tool_names_checked = True++ from backend.copilot.tools import TOOL_REGISTRY++ registry_keys: frozenset[str] = frozenset(TOOL_REGISTRY.keys())+ declared: frozenset[str] = PLATFORM_TOOL_NAMES+ if registry_keys != declared:+ missing = registry_keys - declared+ extra = declared - registry_keys+ parts: list[str] = [+ "PLATFORM_TOOL_NAMES in permissions.py is out of sync with TOOL_REGISTRY."+ ]+ if missing:+ parts.append(f" Missing from PLATFORM_TOOL_NAMES: {sorted(missing)}")+ if extra:+ parts.append(f" Extra in PLATFORM_TOOL_NAMES: {sorted(extra)}")+ parts.append(" Update the ToolName Literal to match.")+ raise AssertionError("\n".join(parts))+++async def validate_block_identifiers(+ identifiers: list[str],+) -> list[str]:+ """Resolve each block identifier and return those that could not be matched.++ Args:+ identifiers: List of block identifiers (name, full UUID, or partial UUID).++ Returns:+ List of identifiers that matched no known block.+ """+ from backend.blocks import get_blocks++ # get_blocks() returns dict[block_id_str, BlockClass]; instantiate once to get names.+ block_registry = get_blocks()+ block_info = {bid: cls().name for bid, cls in block_registry.items()}+ invalid: list[str] = []+ for ident in identifiers:+ matched = any(+ _block_matches(ident, bid, bname) for bid, bname in block_info.items()+ )+ if not matched:+ invalid.append(ident)+ return invalid+++# ---------------------------------------------------------------------------+# SDK tool-list application+# ---------------------------------------------------------------------------+++def apply_tool_permissions(+ permissions: CopilotPermissions,+ *,+ use_e2b: bool = False,+) -> tuple[list[str], list[str]]:+ """Compute (allowed_tools, extra_disallowed) for :class:`ClaudeAgentOptions`.++ Takes the base allowed/disallowed lists from+ :func:`~backend.copilot.sdk.tool_adapter.get_copilot_tool_names` /+ :func:`~backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools` and+ applies *permissions* on top.++ Returns:+ ``(allowed_tools, extra_disallowed)`` where *allowed_tools* is the+ possibly-narrowed list to pass to ``ClaudeAgentOptions.allowed_tools``+ and *extra_disallowed* is the list to pass to+ ``ClaudeAgentOptions.disallowed_tools``.+ """+ from backend.copilot.sdk.tool_adapter import (+ _READ_TOOL_NAME,+ MCP_TOOL_PREFIX,+ get_copilot_tool_names,+ get_sdk_disallowed_tools,+ )+ from backend.copilot.tools import TOOL_REGISTRY++ base_allowed = get_copilot_tool_names(use_e2b=use_e2b)+ base_disallowed = get_sdk_disallowed_tools(use_e2b=use_e2b)++ if permissions.is_empty():+ return base_allowed, base_disallowed++ all_tools = all_known_tool_names()+ effective = permissions.effective_allowed_tools(all_tools)++ # In E2B mode, SDK built-in file tools (Read, Write, Edit, Glob, Grep)+ # are replaced by MCP equivalents (read_file, write_file, ...).+ # Map each SDK built-in name to its E2B MCP name so users can use the+ # familiar names in their permissions and the E2B tools are included.+ _SDK_TO_E2B: dict[str, str] = {}+ if use_e2b:+ from backend.copilot.sdk.e2b_file_tools import E2B_FILE_TOOL_NAMES++ _SDK_TO_E2B = dict(+ zip(+ ["Read", "Write", "Edit", "Glob", "Grep"],+ E2B_FILE_TOOL_NAMES,+ strict=False,+ )+ )++ # Build an updated allowed list by mapping short names → SDK names and+ # keeping only those present in the original base_allowed list.+ def to_sdk_names(short: str) -> list[str]:+ names: list[str] = []+ if short in TOOL_REGISTRY:+ names.append(f"{MCP_TOOL_PREFIX}{short}")+ elif short in _SDK_TO_E2B:+ # E2B mode: map SDK built-in file tool to its MCP equivalent.+ names.append(f"{MCP_TOOL_PREFIX}{_SDK_TO_E2B[short]}")+ else:+ names.append(short) # SDK built-in — used as-is+ return names++ # short names permitted by permissions+ permitted_sdk: set[str] = set()+ for s in effective:+ permitted_sdk.update(to_sdk_names(s))+ # Always include the internal Read tool (used by SDK for large/truncated outputs)+ permitted_sdk.add(f"{MCP_TOOL_PREFIX}{_READ_TOOL_NAME}")++ filtered_allowed = [t for t in base_allowed if t in permitted_sdk]++ # Extra disallowed = tools that were in base_allowed but are now removed+ removed = set(base_allowed) - set(filtered_allowed)+ extra_disallowed = list(set(base_disallowed) | removed)++ return filtered_allowed, extra_disalloweddiff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.pynew file mode 100644index 0000000000..94f1de3ee3--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py@@ -0,0 +1,579 @@+"""Tests for CopilotPermissions — tool/block capability filtering."""++from __future__ import annotations++import pytest++from backend.copilot.permissions import (+ ALL_TOOL_NAMES,+ PLATFORM_TOOL_NAMES,+ SDK_BUILTIN_TOOL_NAMES,+ CopilotPermissions,+ _block_matches,+ all_known_tool_names,+ apply_tool_permissions,+ validate_block_identifiers,+ validate_tool_names,+)+from backend.copilot.tools import TOOL_REGISTRY++# ---------------------------------------------------------------------------+# _block_matches+# ---------------------------------------------------------------------------+++class TestBlockMatches:+ BLOCK_ID = "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"+ BLOCK_NAME = "HTTP Request"++ def test_full_uuid_match(self):+ assert _block_matches(self.BLOCK_ID, self.BLOCK_ID, self.BLOCK_NAME)++ def test_full_uuid_case_insensitive(self):+ assert _block_matches(self.BLOCK_ID.upper(), self.BLOCK_ID, self.BLOCK_NAME)++ def test_full_uuid_no_match(self):+ other = "aaaaaaaa-0000-0000-0000-000000000000"+ assert not _block_matches(other, self.BLOCK_ID, self.BLOCK_NAME)++ def test_partial_uuid_match(self):+ assert _block_matches("c069dc6b", self.BLOCK_ID, self.BLOCK_NAME)++ def test_partial_uuid_case_insensitive(self):+ assert _block_matches("C069DC6B", self.BLOCK_ID, self.BLOCK_NAME)++ def test_partial_uuid_no_match(self):+ assert not _block_matches("deadbeef", self.BLOCK_ID, self.BLOCK_NAME)++ def test_name_match(self):+ assert _block_matches("HTTP Request", self.BLOCK_ID, self.BLOCK_NAME)++ def test_name_case_insensitive(self):+ assert _block_matches("http request", self.BLOCK_ID, self.BLOCK_NAME)+ assert _block_matches("HTTP REQUEST", self.BLOCK_ID, self.BLOCK_NAME)++ def test_name_no_match(self):+ assert not _block_matches("Unknown Block", self.BLOCK_ID, self.BLOCK_NAME)++ def test_partial_uuid_not_matching_as_name(self):+ # "c069dc6b" is 8 hex chars → treated as partial UUID, NOT name match+ assert not _block_matches(+ "c069dc6b", "ffffffff-0000-0000-0000-000000000000", "c069dc6b"+ )+++# ---------------------------------------------------------------------------+# CopilotPermissions.effective_allowed_tools+# ---------------------------------------------------------------------------+++ALL_TOOLS = frozenset(+ ["run_block", "web_fetch", "bash_exec", "find_agent", "Task", "Read"]+)+++class TestEffectiveAllowedTools:+ def test_empty_list_allows_all(self):+ perms = CopilotPermissions(tools=[], tools_exclude=True)+ assert perms.effective_allowed_tools(ALL_TOOLS) == ALL_TOOLS++ def test_empty_whitelist_allows_all(self):+ # edge: tools_exclude=False but empty list → allow all+ perms = CopilotPermissions(tools=[], tools_exclude=False)+ assert perms.effective_allowed_tools(ALL_TOOLS) == ALL_TOOLS++ def test_blacklist_removes_listed(self):+ perms = CopilotPermissions(tools=["bash_exec", "web_fetch"], tools_exclude=True)+ result = perms.effective_allowed_tools(ALL_TOOLS)+ assert "bash_exec" not in result+ assert "web_fetch" not in result+ assert "run_block" in result+ assert "Task" in result++ def test_whitelist_keeps_only_listed(self):+ perms = CopilotPermissions(tools=["run_block", "Task"], tools_exclude=False)+ result = perms.effective_allowed_tools(ALL_TOOLS)+ assert result == frozenset(["run_block", "Task"])++ def test_whitelist_unknown_tool_yields_empty(self):+ perms = CopilotPermissions(tools=["nonexistent"], tools_exclude=False)+ result = perms.effective_allowed_tools(ALL_TOOLS)+ assert result == frozenset()++ def test_blacklist_unknown_tool_ignored(self):+ perms = CopilotPermissions(tools=["nonexistent"], tools_exclude=True)+ result = perms.effective_allowed_tools(ALL_TOOLS)+ assert result == ALL_TOOLS+++# ---------------------------------------------------------------------------+# CopilotPermissions.is_block_allowed+# ---------------------------------------------------------------------------+++BLOCK_ID = "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"+BLOCK_NAME = "HTTP Request"+++class TestIsBlockAllowed:+ def test_empty_allows_everything(self):+ perms = CopilotPermissions(blocks=[], blocks_exclude=True)+ assert perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_blacklist_blocks_listed(self):+ perms = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=True)+ assert not perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_blacklist_allows_unlisted(self):+ perms = CopilotPermissions(blocks=["Other Block"], blocks_exclude=True)+ assert perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_whitelist_allows_listed(self):+ perms = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=False)+ assert perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_whitelist_blocks_unlisted(self):+ perms = CopilotPermissions(blocks=["Other Block"], blocks_exclude=False)+ assert not perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_partial_uuid_blacklist(self):+ perms = CopilotPermissions(blocks=["c069dc6b"], blocks_exclude=True)+ assert not perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_full_uuid_whitelist(self):+ perms = CopilotPermissions(blocks=[BLOCK_ID], blocks_exclude=False)+ assert perms.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_parent_blocks_when_child_allows(self):+ parent = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=True)+ child = CopilotPermissions(blocks=[], blocks_exclude=True)+ child._parent = parent+ assert not child.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_parent_allows_when_child_blocks(self):+ parent = CopilotPermissions(blocks=[], blocks_exclude=True)+ child = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=True)+ child._parent = parent+ assert not child.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_both_must_allow(self):+ parent = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=False)+ child = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=False)+ child._parent = parent+ assert child.is_block_allowed(BLOCK_ID, BLOCK_NAME)++ def test_grandparent_blocks_propagate(self):+ grandparent = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=True)+ parent = CopilotPermissions(blocks=[], blocks_exclude=True)+ parent._parent = grandparent+ child = CopilotPermissions(blocks=[], blocks_exclude=True)+ child._parent = parent+ assert not child.is_block_allowed(BLOCK_ID, BLOCK_NAME)+++# ---------------------------------------------------------------------------+# CopilotPermissions.merged_with_parent+# ---------------------------------------------------------------------------+++class TestMergedWithParent:+ def test_tool_intersection(self):+ all_t = frozenset(["run_block", "web_fetch", "bash_exec"])+ parent = CopilotPermissions(tools=["bash_exec"], tools_exclude=True)+ child = CopilotPermissions(tools=["web_fetch"], tools_exclude=True)+ merged = child.merged_with_parent(parent, all_t)+ effective = merged.effective_allowed_tools(all_t)+ assert "bash_exec" not in effective+ assert "web_fetch" not in effective+ assert "run_block" in effective++ def test_parent_whitelist_narrows_child(self):+ all_t = frozenset(["run_block", "web_fetch", "bash_exec"])+ parent = CopilotPermissions(tools=["run_block"], tools_exclude=False)+ child = CopilotPermissions(tools=[], tools_exclude=True) # allow all+ merged = child.merged_with_parent(parent, all_t)+ effective = merged.effective_allowed_tools(all_t)+ assert effective == frozenset(["run_block"])++ def test_child_cannot_expand_parent_whitelist(self):+ all_t = frozenset(["run_block", "web_fetch", "bash_exec"])+ parent = CopilotPermissions(tools=["run_block"], tools_exclude=False)+ child = CopilotPermissions(+ tools=["run_block", "bash_exec"], tools_exclude=False+ )+ merged = child.merged_with_parent(parent, all_t)+ effective = merged.effective_allowed_tools(all_t)+ # bash_exec was not in parent's whitelist → must not appear+ assert "bash_exec" not in effective+ assert "run_block" in effective++ def test_merged_stored_as_whitelist(self):+ all_t = frozenset(["run_block", "web_fetch"])+ parent = CopilotPermissions(tools=[], tools_exclude=True)+ child = CopilotPermissions(tools=[], tools_exclude=True)+ merged = child.merged_with_parent(parent, all_t)+ assert not merged.tools_exclude # stored as whitelist+ assert set(merged.tools) == {"run_block", "web_fetch"}++ def test_block_parent_stored(self):+ all_t = frozenset(["run_block"])+ parent = CopilotPermissions(blocks=["HTTP Request"], blocks_exclude=True)+ child = CopilotPermissions(blocks=[], blocks_exclude=True)+ merged = child.merged_with_parent(parent, all_t)+ # Parent restriction is preserved via _parent+ assert not merged.is_block_allowed(BLOCK_ID, BLOCK_NAME)+++# ---------------------------------------------------------------------------+# CopilotPermissions.is_empty+# ---------------------------------------------------------------------------+++class TestIsEmpty:+ def test_default_is_empty(self):+ assert CopilotPermissions().is_empty()++ def test_with_tools_not_empty(self):+ assert not CopilotPermissions(tools=["bash_exec"]).is_empty()++ def test_with_blocks_not_empty(self):+ assert not CopilotPermissions(blocks=["HTTP Request"]).is_empty()++ def test_with_parent_not_empty(self):+ perms = CopilotPermissions()+ perms._parent = CopilotPermissions(tools=["bash_exec"])+ assert not perms.is_empty()+++# ---------------------------------------------------------------------------+# validate_tool_names+# ---------------------------------------------------------------------------+++class TestValidateToolNames:+ def test_valid_registry_tool(self):+ assert validate_tool_names(["run_block", "web_fetch"]) == []++ def test_valid_sdk_builtin(self):+ assert validate_tool_names(["Read", "Task", "WebSearch"]) == []++ def test_invalid_tool(self):+ result = validate_tool_names(["nonexistent_tool"])+ assert "nonexistent_tool" in result++ def test_mixed(self):+ result = validate_tool_names(["run_block", "fake_tool"])+ assert "fake_tool" in result+ assert "run_block" not in result++ def test_empty_list(self):+ assert validate_tool_names([]) == []+++# ---------------------------------------------------------------------------+# validate_block_identifiers (async)+# ---------------------------------------------------------------------------+++class TestValidateBlockIdentifiers:+ async def test_empty_list(self):+ result = await validate_block_identifiers([])+ assert result == []++ async def test_valid_full_uuid(self, mocker):+ mock_block = mocker.MagicMock()+ mock_block.return_value.name = "HTTP Request"+ mocker.patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block},+ )+ result = await validate_block_identifiers(+ ["c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"]+ )+ assert result == []++ async def test_invalid_identifier(self, mocker):+ mock_block = mocker.MagicMock()+ mock_block.return_value.name = "HTTP Request"+ mocker.patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block},+ )+ result = await validate_block_identifiers(["totally_unknown"])+ assert "totally_unknown" in result++ async def test_partial_uuid_match(self, mocker):+ mock_block = mocker.MagicMock()+ mock_block.return_value.name = "HTTP Request"+ mocker.patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block},+ )+ result = await validate_block_identifiers(["c069dc6b"])+ assert result == []++ async def test_name_match(self, mocker):+ mock_block = mocker.MagicMock()+ mock_block.return_value.name = "HTTP Request"+ mocker.patch(+ "backend.blocks.get_blocks",+ return_value={"c069dc6b-c3ed-4c12-b6e5-d47361e64ce6": mock_block},+ )+ result = await validate_block_identifiers(["http request"])+ assert result == []+++# ---------------------------------------------------------------------------+# apply_tool_permissions+# ---------------------------------------------------------------------------+++class TestApplyToolPermissions:+ def test_empty_permissions_returns_base_unchanged(self, mocker):+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=["mcp__copilot__run_block", "mcp__copilot__web_fetch", "Task"],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=["Bash"],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {"run_block": object(), "web_fetch": object()},+ )+ perms = CopilotPermissions()+ allowed, disallowed = apply_tool_permissions(perms, use_e2b=False)+ assert "mcp__copilot__run_block" in allowed+ assert "mcp__copilot__web_fetch" in allowed++ def test_blacklist_removes_tool(self, mocker):+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=[+ "mcp__copilot__run_block",+ "mcp__copilot__web_fetch",+ "mcp__copilot__bash_exec",+ "Task",+ ],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=["Bash"],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {+ "run_block": object(),+ "web_fetch": object(),+ "bash_exec": object(),+ },+ )+ mocker.patch(+ "backend.copilot.permissions.all_known_tool_names",+ return_value=frozenset(["run_block", "web_fetch", "bash_exec", "Task"]),+ )+ perms = CopilotPermissions(tools=["bash_exec"], tools_exclude=True)+ allowed, _ = apply_tool_permissions(perms, use_e2b=False)+ assert "mcp__copilot__bash_exec" not in allowed+ assert "mcp__copilot__run_block" in allowed++ def test_whitelist_keeps_only_listed(self, mocker):+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=[+ "mcp__copilot__run_block",+ "mcp__copilot__web_fetch",+ "Task",+ "WebSearch",+ ],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=["Bash"],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {"run_block": object(), "web_fetch": object()},+ )+ mocker.patch(+ "backend.copilot.permissions.all_known_tool_names",+ return_value=frozenset(["run_block", "web_fetch", "Task", "WebSearch"]),+ )+ perms = CopilotPermissions(tools=["run_block"], tools_exclude=False)+ allowed, _ = apply_tool_permissions(perms, use_e2b=False)+ assert "mcp__copilot__run_block" in allowed+ assert "mcp__copilot__web_fetch" not in allowed+ assert "Task" not in allowed++ def test_read_tool_always_included_even_when_blacklisted(self, mocker):+ """mcp__copilot__Read must stay in allowed even if Read is explicitly blacklisted."""+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=[+ "mcp__copilot__run_block",+ "mcp__copilot__Read",+ "Task",+ ],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=[],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {"run_block": object()},+ )+ mocker.patch(+ "backend.copilot.permissions.all_known_tool_names",+ return_value=frozenset(["run_block", "Read", "Task"]),+ )+ # Explicitly blacklist Read+ perms = CopilotPermissions(tools=["Read"], tools_exclude=True)+ allowed, _ = apply_tool_permissions(perms, use_e2b=False)+ assert "mcp__copilot__Read" in allowed # always preserved for SDK internals+ assert "mcp__copilot__run_block" in allowed+ assert "Task" in allowed++ def test_read_tool_always_included_with_narrow_whitelist(self, mocker):+ """mcp__copilot__Read must stay in allowed even when not in a whitelist."""+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=[+ "mcp__copilot__run_block",+ "mcp__copilot__Read",+ "Task",+ ],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=[],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {"run_block": object()},+ )+ mocker.patch(+ "backend.copilot.permissions.all_known_tool_names",+ return_value=frozenset(["run_block", "Read", "Task"]),+ )+ # Whitelist only run_block — Read not listed+ perms = CopilotPermissions(tools=["run_block"], tools_exclude=False)+ allowed, _ = apply_tool_permissions(perms, use_e2b=False)+ assert "mcp__copilot__Read" in allowed # always preserved for SDK internals+ assert "mcp__copilot__run_block" in allowed++ def test_e2b_file_tools_included_when_sdk_builtin_whitelisted(self, mocker):+ """In E2B mode, whitelisting 'Read' must include mcp__copilot__read_file."""+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=[+ "mcp__copilot__run_block",+ "mcp__copilot__Read",+ "mcp__copilot__read_file",+ "mcp__copilot__write_file",+ "Task",+ ],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=["Bash", "Read", "Write", "Edit", "Glob", "Grep"],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {"run_block": object()},+ )+ mocker.patch(+ "backend.copilot.permissions.all_known_tool_names",+ return_value=frozenset(["run_block", "Read", "Write", "Task"]),+ )+ mocker.patch(+ "backend.copilot.sdk.e2b_file_tools.E2B_FILE_TOOL_NAMES",+ ["read_file", "write_file", "edit_file", "glob", "grep"],+ )+ # Whitelist Read and run_block — E2B read_file should be included+ perms = CopilotPermissions(tools=["Read", "run_block"], tools_exclude=False)+ allowed, _ = apply_tool_permissions(perms, use_e2b=True)+ assert "mcp__copilot__read_file" in allowed+ assert "mcp__copilot__run_block" in allowed+ # Write not whitelisted — write_file should NOT be included+ assert "mcp__copilot__write_file" not in allowed++ def test_e2b_file_tools_excluded_when_sdk_builtin_blacklisted(self, mocker):+ """In E2B mode, blacklisting 'Read' must also remove mcp__copilot__read_file."""+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_copilot_tool_names",+ return_value=[+ "mcp__copilot__run_block",+ "mcp__copilot__Read",+ "mcp__copilot__read_file",+ "Task",+ ],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.get_sdk_disallowed_tools",+ return_value=["Bash", "Read", "Write", "Edit", "Glob", "Grep"],+ )+ mocker.patch(+ "backend.copilot.sdk.tool_adapter.TOOL_REGISTRY",+ {"run_block": object()},+ )+ mocker.patch(+ "backend.copilot.permissions.all_known_tool_names",+ return_value=frozenset(["run_block", "Read", "Task"]),+ )+ mocker.patch(+ "backend.copilot.sdk.e2b_file_tools.E2B_FILE_TOOL_NAMES",+ ["read_file", "write_file", "edit_file", "glob", "grep"],+ )+ # Blacklist Read — E2B read_file should also be removed+ perms = CopilotPermissions(tools=["Read"], tools_exclude=True)+ allowed, _ = apply_tool_permissions(perms, use_e2b=True)+ assert "mcp__copilot__read_file" not in allowed+ assert "mcp__copilot__run_block" in allowed+ # mcp__copilot__Read is always preserved for SDK internals+ assert "mcp__copilot__Read" in allowed+++# ---------------------------------------------------------------------------+# SDK_BUILTIN_TOOL_NAMES sanity check+# ---------------------------------------------------------------------------+++class TestSdkBuiltinToolNames:+ def test_expected_builtins_present(self):+ expected = {+ "Read",+ "Write",+ "Edit",+ "Glob",+ "Grep",+ "Task",+ "WebSearch",+ "TodoWrite",+ }+ assert expected.issubset(SDK_BUILTIN_TOOL_NAMES)++ def test_platform_names_match_tool_registry(self):+ """PLATFORM_TOOL_NAMES (derived from ToolName Literal) must match TOOL_REGISTRY keys."""+ registry_keys = frozenset(TOOL_REGISTRY.keys())+ assert PLATFORM_TOOL_NAMES == registry_keys, (+ f"ToolName Literal is out of sync with TOOL_REGISTRY. "+ f"Missing: {registry_keys - PLATFORM_TOOL_NAMES}, "+ f"Extra: {PLATFORM_TOOL_NAMES - registry_keys}"+ )++ def test_all_tool_names_is_union(self):+ """ALL_TOOL_NAMES must equal PLATFORM_TOOL_NAMES | SDK_BUILTIN_TOOL_NAMES."""+ assert ALL_TOOL_NAMES == PLATFORM_TOOL_NAMES | SDK_BUILTIN_TOOL_NAMES++ def test_no_overlap_between_platform_and_sdk(self):+ """Platform and SDK built-in names must not overlap."""+ assert PLATFORM_TOOL_NAMES.isdisjoint(SDK_BUILTIN_TOOL_NAMES)++ def test_known_tools_includes_registry_and_builtins(self):+ known = all_known_tool_names()+ assert "run_block" in known+ assert "Read" in known+ assert "Task" in knowndiff --git a/autogpt_platform/backend/backend/copilot/sdk/collect.py b/autogpt_platform/backend/backend/copilot/sdk/collect.pyindex ea687a98d7..184bbfb5a3 100644--- a/autogpt_platform/backend/backend/copilot/sdk/collect.py+++ b/autogpt_platform/backend/backend/copilot/sdk/collect.py@@ -7,7 +7,20 @@ without implementing their own event loop.from __future__ import annotations-from typing import Any+from typing import TYPE_CHECKING, Any++from backend.copilot.response_model import (+ StreamError,+ StreamTextDelta,+ StreamToolInputAvailable,+ StreamToolOutputAvailable,+ StreamUsage,+)++from .service import stream_chat_completion_sdk++if TYPE_CHECKING:+ from backend.copilot.permissions import CopilotPermissionsclass CopilotResult:@@ -39,6 +52,7 @@ async def collect_copilot_response(message: str,user_id: str,is_user_message: bool = True,+ permissions: "CopilotPermissions | None" = None,) -> CopilotResult:"""Consume :func:`stream_chat_completion_sdk` and return aggregated results.@@ -53,6 +67,8 @@ async def collect_copilot_response(message: The user message / prompt.user_id: Authenticated user ID.is_user_message: Whether this is a user-initiated message.+ permissions: Optional capability filter. When provided, restricts+ which tools and blocks the copilot may use during this execution.Returns:A :class:`CopilotResult` with the aggregated response text,@@ -61,16 +77,6 @@ async def collect_copilot_response(Raises:RuntimeError: If the stream yields a ``StreamError`` event."""- from backend.copilot.response_model import (- StreamError,- StreamTextDelta,- StreamToolInputAvailable,- StreamToolOutputAvailable,- StreamUsage,- )-- from .service import stream_chat_completion_sdk-result = CopilotResult()response_parts: list[str] = []tool_calls_by_id: dict[str, dict[str, Any]] = {}@@ -80,6 +86,7 @@ async def collect_copilot_response(message=message,is_user_message=is_user_message,user_id=user_id,+ permissions=permissions,):if isinstance(event, StreamTextDelta):response_parts.append(event.delta)diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 36428a77bd..c654f6510a 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -12,7 +12,10 @@ import timeimport uuidfrom collections.abc import AsyncGenerator, AsyncIteratorfrom dataclasses import dataclass-from typing import Any, NamedTuple, cast+from typing import TYPE_CHECKING, Any, NamedTuple, cast++if TYPE_CHECKING:+ from backend.copilot.permissions import CopilotPermissionsfrom claude_agent_sdk import (AssistantMessage,@@ -29,6 +32,7 @@ from langsmith.integrations.claude_agent_sdk import configure_claude_agent_sdkfrom pydantic import BaseModelfrom backend.copilot.context import get_workspace_manager+from backend.copilot.permissions import apply_tool_permissionsfrom backend.data.redis_client import get_redis_asyncfrom backend.executor.cluster_lock import AsyncClusterLockfrom backend.util.exceptions import NotFoundError@@ -1480,6 +1484,7 @@ async def stream_chat_completion_sdk(user_id: str | None = None,session: ChatSession | None = None,file_ids: list[str] | None = None,+ permissions: "CopilotPermissions | None" = None,**_kwargs: Any,) -> AsyncIterator[StreamBaseResponse]:"""Stream chat completion using Claude Agent SDK.@@ -1725,7 +1730,13 @@ async def stream_chat_completion_sdk(yield StreamStart(messageId=message_id, sessionId=session_id)- set_execution_context(user_id, session, sandbox=e2b_sandbox, sdk_cwd=sdk_cwd)+ set_execution_context(+ user_id,+ session,+ sandbox=e2b_sandbox,+ sdk_cwd=sdk_cwd,+ permissions=permissions,+ )# Fail fast when no API credentials are available at all.sdk_env = _build_sdk_env(session_id=session_id, user_id=user_id)@@ -1751,8 +1762,11 @@ async def stream_chat_completion_sdk(on_compact=compaction.on_compact,)- allowed = get_copilot_tool_names(use_e2b=use_e2b)- disallowed = get_sdk_disallowed_tools(use_e2b=use_e2b)+ if permissions is not None:+ allowed, disallowed = apply_tool_permissions(permissions, use_e2b=use_e2b)+ else:+ allowed = get_copilot_tool_names(use_e2b=use_e2b)+ disallowed = get_sdk_disallowed_tools(use_e2b=use_e2b)def _on_stderr(line: str) -> None:"""Log a stderr line emitted by the Claude CLI subprocess."""diff --git a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.pyindex 8f8c214512..378107d048 100644--- a/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/tool_adapter.py@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Anyfrom claude_agent_sdk import create_sdk_mcp_server, toolfrom backend.copilot.context import (+ _current_permissions,_current_project_dir,_current_sandbox,_current_sdk_cwd,@@ -41,6 +42,8 @@ from .e2b_file_tools import E2B_FILE_TOOL_NAMES, E2B_FILE_TOOLSif TYPE_CHECKING:from e2b import AsyncSandbox+ from backend.copilot.permissions import CopilotPermissions+logger = logging.getLogger(__name__)# Max MCP response size in chars — keeps tool output under the SDK's 10 MB JSON buffer.@@ -82,6 +85,7 @@ def set_execution_context(session: ChatSession,sandbox: "AsyncSandbox | None" = None,sdk_cwd: str | None = None,+ permissions: "CopilotPermissions | None" = None,) -> None:"""Set the execution context for tool calls.@@ -93,12 +97,14 @@ def set_execution_context(session: Current chat session.sandbox: Optional E2B sandbox; when set, bash_exec routes commands there.sdk_cwd: SDK working directory; used to scope tool-results reads.+ permissions: Optional capability filter restricting tools/blocks."""_current_user_id.set(user_id)_current_session.set(session)_current_sandbox.set(sandbox)_current_sdk_cwd.set(sdk_cwd or "")_current_project_dir.set(_encode_cwd_for_cli(sdk_cwd) if sdk_cwd else "")+ _current_permissions.set(permissions)_pending_tool_outputs.set({})_stash_event.set(asyncio.Event())_consecutive_tool_failures.set({})diff --git a/autogpt_platform/backend/backend/copilot/tools/find_block.py b/autogpt_platform/backend/backend/copilot/tools/find_block.pyindex 79c5bdc529..9367484c66 100644--- a/autogpt_platform/backend/backend/copilot/tools/find_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/find_block.py@@ -5,6 +5,7 @@ from prisma.enums import ContentTypefrom backend.blocks import get_blockfrom backend.blocks._base import BlockType+from backend.copilot.context import get_current_permissionsfrom backend.copilot.model import ChatSessionfrom backend.data.db_accessors import search@@ -149,6 +150,19 @@ class FindBlockTool(BaseTool):session_id=session_id,)+ # Check block-level permissions — hide denied blocks entirely+ perms = get_current_permissions()+ if perms is not None and not perms.is_block_allowed(+ block.id, block.name+ ):+ return NoResultsResponse(+ message=f"No blocks found for '{query}'",+ suggestions=[+ "Search for an alternative block by name",+ ],+ session_id=session_id,+ )+summary = BlockInfoSummary(id=block.id,name=block.name,@@ -195,6 +209,7 @@ class FindBlockTool(BaseTool):)# Enrich results with block information+ perms = get_current_permissions()blocks: list[BlockInfoSummary] = []for result in results:block_id = result["content_id"]@@ -211,6 +226,12 @@ class FindBlockTool(BaseTool):):continue+ # Skip blocks denied by execution permissions+ if perms is not None and not perms.is_block_allowed(+ block.id, block.name+ ):+ continue+summary = BlockInfoSummary(id=block_id,name=block.name,diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.pyindex 43108a6007..32d6b1761d 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py@@ -11,6 +11,7 @@ from backend.copilot.constants import (COPILOT_NODE_PREFIX,COPILOT_SESSION_PREFIX,)+from backend.copilot.context import get_current_permissionsfrom backend.copilot.model import ChatSessionfrom backend.copilot.sdk.file_ref import FileRefExpansionError, expand_file_refs_in_argsfrom backend.data.db_accessors import review_db@@ -146,6 +147,27 @@ class RunBlockTool(BaseTool):session_id=session_id,)+ # Check block-level permissions before execution.+ perms = get_current_permissions()+ if perms is not None and not perms.is_block_allowed(block_id, block.name):+ available_hint = (+ f"Allowed identifiers: {perms.blocks!r}. "+ if not perms.blocks_exclude and perms.blocks+ else (+ f"Blocked identifiers: {perms.blocks!r}. "+ if perms.blocks_exclude and perms.blocks+ else ""+ )+ )+ return ErrorResponse(+ message=(+ f"Block '{block.name}' ({block_id}) is not permitted "+ f"by the current execution permissions. {available_hint}"+ "Use find_block to discover blocks that are allowed."+ ),+ session_id=session_id,+ )+logger.info(f"Executing block {block.name} ({block_id}) for user {user_id}")(diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.pyindex 189099f82a..9cbe98fb64 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py@@ -5,6 +5,8 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.blocks._base import BlockType+from backend.copilot.context import _current_permissions+from backend.copilot.permissions import CopilotPermissionsfrom ._test_data import make_sessionfrom .models import (@@ -132,6 +134,69 @@ class TestRunBlockFiltering:assert isinstance(response, ErrorResponse)assert "cannot be run directly" in response.message+ @pytest.mark.asyncio(loop_scope="session")+ async def test_block_denied_by_permissions_returns_error(self):+ """A block denied by CopilotPermissions returns an ErrorResponse."""+ session = make_session(user_id=_TEST_USER_ID)+ block_id = "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"+ standard_block = make_mock_block(block_id, "HTTP Request", BlockType.STANDARD)++ perms = CopilotPermissions(blocks=[block_id], blocks_exclude=True)+ token = _current_permissions.set(perms)+ try:+ with patch(+ "backend.copilot.tools.run_block.get_block",+ return_value=standard_block,+ ):+ tool = RunBlockTool()+ response = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ block_id=block_id,+ input_data={},+ )+ finally:+ _current_permissions.reset(token)++ assert isinstance(response, ErrorResponse)+ assert "not permitted" in response.message++ @pytest.mark.asyncio(loop_scope="session")+ async def test_allowed_by_permissions_passes_guard(self):+ """A block explicitly allowed by a whitelist CopilotPermissions passes the guard."""+ session = make_session(user_id=_TEST_USER_ID)+ block_id = "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"+ standard_block = make_mock_block(block_id, "HTTP Request", BlockType.STANDARD)++ perms = CopilotPermissions(blocks=[block_id], blocks_exclude=False)+ token = _current_permissions.set(perms)+ try:+ with (+ patch(+ "backend.copilot.tools.run_block.get_block",+ return_value=standard_block,+ ),+ patch(+ "backend.copilot.tools.helpers.match_credentials_to_requirements",+ return_value=({}, []),+ ),+ ):+ tool = RunBlockTool()+ response = await tool._execute(+ user_id=_TEST_USER_ID,+ session=session,+ block_id=block_id,+ input_data={},+ )+ finally:+ _current_permissions.reset(token)++ # Must NOT be blocked by permissions — assert it's not a permission error+ assert (+ not isinstance(response, ErrorResponse)+ or "not permitted" not in response.message+ )+@pytest.mark.asyncio(loop_scope="session")async def test_non_excluded_block_passes_guard(self):"""Non-excluded blocks pass the filtering guard (may fail later for other reasons)."""diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.mdindex 02f9cdf1f8..30f6aaf499 100644--- a/docs/integrations/block-integrations/misc.md+++ b/docs/integrations/block-integrations/misc.md@@ -46,6 +46,8 @@ Execute tasks using AutoGPT AutoPilot with full access to platform tools (agent### How it works<!-- MANUAL: how_it_works -->This block invokes the platform's copilot system directly via `stream_chat_completion_sdk`. It creates (or resumes) a chat session, streams the autopilot's response collecting text deltas, tool call details, and token usage, then returns the aggregated results. A recursion depth guard prevents infinite loops when the autopilot calls this block as a sub-agent.++Tool and block identifiers provided in `tools` and `blocks` are validated at run time before any execution begins — unknown names or UUIDs produce an error output immediately. When valid, the permissions object is passed into the SDK layer, which narrows the `allowed_tools` list sent to Claude; blocks are enforced at the `run_block` tool call site so the copilot cannot circumvent the filter by calling `run_block` directly. For sub-agent patterns (where an autopilot invokes another AutoPilot block), permissions are inherited: the child's effective allowed set is intersected with the parent's, so a sub-agent can only be *more* restrictive than its parent, never more permissive.<!-- END MANUAL -->### Inputs@@ -56,6 +58,10 @@ This block invokes the platform's copilot system directly via `stream_chat_compl| system_context | Optional additional context prepended to the prompt. Use this to constrain autopilot behavior, provide domain context, or set output format requirements. | str | No || session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No || max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "delete_folder" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "list_folders" \| "list_workspace_files" \| "move_agents_to_folder" \| "move_folder" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "search_docs" \| "search_feature_requests" \| "update_folder" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "write_workspace_file" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |+| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |+| blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |+| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |### Outputs