Agent Zero AI framework
Harden scoped tool policy enforcement
Alessandroafff2e3c055d
diff --git a/api/plugins.py b/api/plugins.pyindex 130ce7e8f..45edc57b4 100644--- a/api/plugins.py+++ b/api/plugins.py@@ -248,9 +248,12 @@ class Plugins(ApiHandler):if enabled is None:return Response(status=400, response="Missing enabled state")- plugins.toggle_plugin(- plugin_name, bool(enabled), project_name, agent_profile, clear_overrides- )+ try:+ plugins.toggle_plugin(+ plugin_name, bool(enabled), project_name, agent_profile, clear_overrides+ )+ except ValueError as exc:+ return Response(status=400, response=str(exc))return {"ok": True}@extension.extensiblediff --git a/api/plugins.py.dox.md b/api/plugins.py.dox.mdindex e64b22dc9..e60576fbc 100644--- a/api/plugins.py.dox.md+++ b/api/plugins.py.dox.md@@ -20,6 +20,8 @@- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.- `Plugins` is an `ApiHandler`.- `Plugins` defines `process(...)`.+- Toggle requests that try to disable an `always_enabled` plugin return HTTP+ 400 without changing plugin state.- Observed side-effect areas: filesystem reads, filesystem writes, filesystem deletion, subprocess/runtime control, plugin state, settings/state persistence.- Imported dependency areas include: `helpers`, `helpers.api`, `helpers.localization`, `json`, `os`, `subprocess`, `sys`.diff --git a/helpers/mcp_handler.py b/helpers/mcp_handler.pyindex d1926d930..64565ed1e 100644--- a/helpers/mcp_handler.py+++ b/helpers/mcp_handler.py@@ -434,10 +434,14 @@ class MCPTool(Tool):return message, additionalasync def execute(self, **kwargs: Any):- from helpers.tool_policy import ensure_tool_allowed+ from helpers.tool_policy import canonical_mcp_id, ensure_tool_allowedif "." in self.name:- ensure_tool_allowed(self.agent, self.name)+ ensure_tool_allowed(+ self.agent,+ self.name,+ canonical_id=canonical_mcp_id(self.name),+ )error = ""additional: dict[str, Any] | None = Nonetry:diff --git a/helpers/mcp_handler.py.dox.md b/helpers/mcp_handler.py.dox.mdindex da849f428..d5240fb25 100644--- a/helpers/mcp_handler.py.dox.md+++ b/helpers/mcp_handler.py.dox.md@@ -83,7 +83,8 @@- Server status and detail responses include `scope`, and MCP tools resolve through `MCPConfig.get_for_agent(agent)` before execution.- MCP tool names are qualified as `server_name.tool_name`; server names are normalized without dots, and the tool portion may contain dots.- Agent-facing MCP prompt descriptions filter through the central profile tool- policy, and `MCPTool.execute()` rechecks the same policy before invocation.+ policy, and `MCPTool.execute()` rechecks the same policy with the explicit MCP+ canonical ID before invocation.- `MCPConfig.get_tool()` tries the supplied qualified name first, then restores an advertised Responses alias from the calling agent's name map; names that still do not identify an MCP tool return `None` unchanged for downstream local-tool resolution.- Servers may define `disabled_tools` as a list of MCP tool names. Disabled tools are omitted from agent-facing prompts, status counts, `has_tool`, and calls, while detail views can still retrieve them through `get_all_tools()` with a `disabled` flag so users can re-enable them.- Server-specific `init_timeout` and `tool_timeout` override global MCP client timeout settings for list-tools and call-tool operations.diff --git a/helpers/parallel_tools.py b/helpers/parallel_tools.pyindex b4f978b68..eacc7367b 100644--- a/helpers/parallel_tools.py+++ b/helpers/parallel_tools.py@@ -412,17 +412,23 @@ async def _run_parallel_job(parent_context_id: str, job_id: str) -> None:async def _run_subordinate_context_job(parent_context_id: str, job: ParallelJob) -> str:from agent import AgentContext, AgentContextType, UserMessagefrom helpers import message_queue, persist_chat+ from helpers.tool_policy import ensure_tool_allowed+ from tools.call_subordinate import _validate_subordinate_profileparent_context = AgentContext.get(parent_context_id)if not parent_context:raise ValueError("Parent context not found.")+ ensure_tool_allowed(parent_context.agent0, "call_subordinate")args = job.tool_argsmessage = str(args.get("message") or "").strip()if not message:raise ValueError("call_subordinate requires `tool_args.message`.")- profile = str(args.get("profile") or args.get("agent_profile") or "").strip()+ profile = _validate_subordinate_profile(+ parent_context.agent0,+ str(args.get("profile") or args.get("agent_profile") or ""),+ )attachments = args.get("attachments") if isinstance(args.get("attachments"), list) else []attachments = [str(item) for item in attachments]diff --git a/helpers/parallel_tools.py.dox.md b/helpers/parallel_tools.py.dox.mdindex 31d4221f7..a729458ca 100644--- a/helpers/parallel_tools.py.dox.md+++ b/helpers/parallel_tools.py.dox.md@@ -26,7 +26,11 @@- Normalization accepts full agent-reply-shaped objects when `tool_name` and `tool_args` are present; non-contract planning fields such as `thoughts` or `headline` are ignored.- `tool_calls` should be an array, but normalization also accepts a valid JSON string encoding of that array to recover provider/model stringification.- Normalization rejects `document_query` and `response` inside `parallel`: document parsing and Q&A must run sequentially, while `response` must remain top-level so it can end the message loop.-- `call_subordinate` jobs run in isolated child chat contexts tagged with parent-chat metadata; they must not be added to the scheduler task list and may use normal child-chat tools, including `parallel`.+- `call_subordinate` jobs first enforce the parent profile's delegation policy+ and validate the requested profile through the sequential delegation owner,+ then run in isolated child chat contexts tagged with parent-chat metadata;+ they must not be added to the scheduler task list and may use normal child-chat+ tools, including `parallel`.- Direct tool jobs run in isolated background contexts and are blocked from recursively invoking `parallel`.- Direct tool background context cleanup removes both the in-memory context and any transient chat folder left on disk.- Parent-visible child log items are created for each wrapped call so the WebUI can inspect concurrent children separately while the wrapper result remains model-history-only.diff --git a/helpers/plugins.py b/helpers/plugins.pyindex 88ab14556..73db58f6d 100644--- a/helpers/plugins.py+++ b/helpers/plugins.py@@ -475,6 +475,11 @@ def get_enabled_plugins(agent: Agent | None):active = []for plugin in plugins:+ meta = get_plugin_meta(plugin)+ if meta and meta.always_enabled:+ active.append(plugin)+ continue+# plugins are toggled via .enabled / .disabled files# every plugin is on by default, unless disabled in usr direnabled = True@@ -546,6 +551,10 @@ def toggle_plugin(agent_profile: str = "",clear_overrides: bool = False,):+ meta = get_plugin_meta(plugin_name)+ if meta and meta.always_enabled and not enabled:+ raise ValueError(f'Plugin "{plugin_name}" is always enabled.')+if clear_overrides:all_toggles = find_plugin_assets(TOGGLE_FILE_PATTERN,diff --git a/helpers/plugins.py.dox.md b/helpers/plugins.py.dox.mdindex f094cce5e..45bd1fbef 100644--- a/helpers/plugins.py.dox.md+++ b/helpers/plugins.py.dox.md@@ -49,6 +49,8 @@## Runtime Contracts- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.+- Plugins marked `always_enabled` remain in runtime discovery regardless of+ stale global or scoped disable files, and disable attempts are rejected.- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.- Observed side-effect areas: filesystem reads, filesystem writes, filesystem deletion, WebSocket state, plugin state, settings/state persistence, secret handling.- Imported dependency areas include: `__future__`, `asyncio`, `glob`, `helpers`, `helpers.defer`, `helpers.watchdog`, `json`, `pathlib`, `pydantic`, `re`, `regex`, `time`, `typing`.diff --git a/helpers/tool_policy.py b/helpers/tool_policy.pyindex 854d59dba..a448ccd3b 100644--- a/helpers/tool_policy.py+++ b/helpers/tool_policy.py@@ -36,7 +36,26 @@ def normalize_policy(config: Any) -> dict[str, Any]:def get_policy(agent: Any) -> dict[str, Any]:- return normalize_policy(plugins.get_plugin_config(PLUGIN_NAME, agent=agent))+ from helpers import projects++ project_name = projects.get_context_project_name(agent.context) or ""+ profile = str(getattr(agent.config, "profile", "") or "")+ for asset in plugins.find_plugin_assets(+ plugins.CONFIG_FILE_NAME,+ plugin_name=PLUGIN_NAME,+ project_name=project_name,+ agent_profile=profile,+ only_first=False,+ ):+ config = files.read_file_json(asset["path"])+ if not isinstance(config, dict) or not any(+ key in config for key in ("mode", "default", "allowed", "blocked")+ ):+ continue+ policy = normalize_policy(config)+ if policy["mode"] == "custom":+ return policy+ return normalize_policy(plugins.get_default_plugin_config(PLUGIN_NAME))def get_tool_catalog(agent: Any) -> list[dict[str, Any]]:@@ -162,12 +181,13 @@ def resolve_tool()-def ensure_tool_allowed(agent: Any, tool_name: str) -> ToolPolicyDecision:- decision = resolve_tool(- agent,- tool_name,- canonical_id=canonical_mcp_id(tool_name),- )+def ensure_tool_allowed(+ agent: Any,+ tool_name: str,+ *,+ canonical_id: str = "",+) -> ToolPolicyDecision:+ decision = resolve_tool(agent, tool_name, canonical_id=canonical_id)if decision.allowed:return decisionprofile = str(getattr(getattr(agent, "config", None), "profile", "") or "default")@@ -197,6 +217,17 @@ def filter_tool_prompt(agent: Any, prompt_file: str, prompt: str) -> str:)for name in sorted(blocked_names, key=len, reverse=True)]+ prompt = re.sub(+ r"^[ \t]*(?P<fence>`{3,}|~{3,})[ \t]*json\b[^\r\n]*\r?\n"+ r".*?^[ \t]*(?P=fence)[ \t]*(?:\r?\n|$)",+ lambda match: (+ ""+ if any(pattern.search(match.group(0)) for pattern in patterns)+ else match.group(0)+ ),+ prompt,+ flags=re.IGNORECASE | re.MULTILINE | re.DOTALL,+ )return "".join(linefor line in prompt.splitlines(keepends=True)@@ -301,7 +332,7 @@ def tool_prompt_description(fallback: str = "",) -> str:declaration = re.search(- rf"^\s*-\s+`{re.escape(name)}`:\s+(args?\b.*)$",+ rf"^\s*-\s+`{re.escape(name)}`:\s+(.+)$",prompt or "",re.IGNORECASE | re.MULTILINE,)diff --git a/helpers/tool_policy.py.dox.md b/helpers/tool_policy.py.dox.mdindex 99ceea590..1c7a1d4d4 100644--- a/helpers/tool_policy.py.dox.md+++ b/helpers/tool_policy.py.dox.md@@ -10,21 +10,27 @@- `normalize_policy` owns the sparse allow/block configuration shape.- `get_tool_catalog` owns canonical local, plugin, and MCP identities plusunavailable-policy retention; local entries come from executable `tools/*.py`- files in the runtime path hierarchy. Catalog entries describe tools; the- editor applies the current draft policy instead of receiving duplicated+ files in the runtime path hierarchy. The catalog describes installed+ capabilities independently of transient transport availability; connector+ prompt/schema extensions remain responsible for live remote-tool exposure.+ The editor applies the current draft policy instead of receiving duplicatedallowed/required flags from the backend.- `tool_prompt_description` owns the shared compact description extracted forthe editor catalog and provider-native schemas; transport-specific names andschemas remain with their transports.- `resolve_tool` returns the effective decision and provenance.-- `ensure_tool_allowed` raises the stable repairable runtime policy error.-- `filter_tool_prompt` removes denied local capabilities from the text protocol- without taking ownership of provider-native naming rules.+- `ensure_tool_allowed` raises the stable repairable runtime policy error and+ accepts an explicit canonical ID from transports that already resolved one.+- `filter_tool_prompt` removes denied local capabilities from the text protocol,+ including complete fenced JSON examples that reference them, without taking+ ownership of provider-native naming rules.## Runtime Contracts-- Scoped config resolution is delegated to `helpers.plugins`: active project- profile, active project, user profile, bundled/plugin profile, then default.+- Scoped asset precedence comes from `helpers.plugins`: active project profile,+ active project, user profile, bundled/plugin profile, then default.+ `get_policy` selects the first custom policy; unknown-only and+ explicit-inherit files remain on disk but defer to the next lower layer.- Missing policy inherits standard access; custom policy always records whetherfuture tools default to allowed or blocked.- The `response` capability is a framework-required invariant: profile policy@@ -33,6 +39,8 @@it is not exposed as a profile-policy choice and legacy policy IDs cannotsuppress the chat-configured capability.- Policy IDs are namespaced as `local:`, `plugin:<id>:`, or `mcp:<server>:`.+ Generic execution resolves canonical IDs from executable paths; MCP+ invocation supplies its explicit namespaced ID.- Plugin IDs are derived relative to the canonical roots from `helpers.plugins`,not by independently parsing repository-relative path strings.- Each executable local tool has its own policy identity, including tools thatdiff --git a/plugins/_a0_connector/prompts/agent.system.tool.code_execution_remote.md b/plugins/_a0_connector/prompts/agent.system.tool.code_execution_remote.mdindex 8c334d0a8..9706b17b2 100644--- a/plugins/_a0_connector/prompts/agent.system.tool.code_execution_remote.md+++ b/plugins/_a0_connector/prompts/agent.system.tool.code_execution_remote.md@@ -1,5 +1,6 @@# code_execution_remote tool+Run shell-backed commands on a connected A0 CLI host.Shown when a connected A0 CLI advertises remote execution, which the user enableswith F4 in the CLI. Runs shell-backed execution on the machine where that CLI isrunning. Use this tool, not `code_execution_tool`, when the user asks for thediff --git a/plugins/_a0_connector/prompts/agent.system.tool.computer_use_remote.md b/plugins/_a0_connector/prompts/agent.system.tool.computer_use_remote.mdindex 39de1b82b..34c8cd49d 100644--- a/plugins/_a0_connector/prompts/agent.system.tool.computer_use_remote.md+++ b/plugins/_a0_connector/prompts/agent.system.tool.computer_use_remote.md@@ -1,5 +1,6 @@### computer_use_remote+Control the desktop on a connected A0 CLI or Launcher host.Shown when a connected A0 CLI or Launcher host gateway advertises enabled Computer Use (`/computer-use on`) and does not need re-arming. Runtime-gated beta desktop control through that host bridge on the user's machine. Availability, backend support, and trust mode are checked when the tool runs, together with host-bridge presence, local enablement, and re-arm state. Computer Use enablement is scoped to the current CLI session or Launcher Host access lease, not scoped to a single chat context.Use this for native host desktop UI inspection, screenshots, background-safe window/element actions when supported, clicking, scrolling, typing, key presses, and status checks. Do not use it for ordinary web-page navigation or host-browser control; use the browser tool for web pages unless browser automation cannot express the task. For complex desktop workflows, load and follow skill `host-computer-use` before proceeding.diff --git a/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md b/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.mdindex 0c2b0341f..52ce6786b 100644--- a/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md+++ b/plugins/_a0_connector/prompts/agent.system.tool.text_editor_remote.md@@ -1,5 +1,6 @@# text_editor_remote tool+Read, write, and patch files on a connected A0 CLI host.Shown when a connected A0 CLI advertises remote file access. Reads, writes, andpatches files on the machine where that CLI is running. Use this tool, notserver-side file tools, when the user asks for files on the connected localdiff --git a/plugins/_code_execution/prompts/agent.system.tool.input.md b/plugins/_code_execution/prompts/agent.system.tool.input.mdindex 4a0becadd..63354017c 100644--- a/plugins/_code_execution/prompts/agent.system.tool.input.md+++ b/plugins/_code_execution/prompts/agent.system.tool.input.md@@ -1,4 +1,5 @@### input:+send keyboard input to an interactive terminal programuse keyboard arg for terminal program inputuse session arg for terminal session numberanswer dialogues enter passwords etcdiff --git a/plugins/_memory/prompts/agent.system.tool.memory.md b/plugins/_memory/prompts/agent.system.tool.memory.mdindex 36a91f025..02f10a974 100644--- a/plugins/_memory/prompts/agent.system.tool.memory.md+++ b/plugins/_memory/prompts/agent.system.tool.memory.md@@ -1,9 +1,10 @@## memory toolsuse when durable recall or storage is useful-- `memory_load`: args `query`, optional `threshold`, `limit`, `filter`-- `memory_save`: args `text`, optional `area` and metadata kwargs-- `memory_delete`: arg `ids` comma-separated ids-- `memory_forget`: args `query`, optional `threshold`, `filter`+- `memory_load`: search stored memories by meaning and metadata+- `memory_save`: store durable information for future recall+- `memory_delete`: delete memories by exact ID+- `memory_forget`: find and remove memories matching a query+args: load uses `query`, optional `threshold`, `limit`, `filter`; save uses `text`, optional `area` and metadata; delete uses comma-separated `ids`; forget uses `query`, optional `threshold`, `filter`notes:- `threshold` is similarity from `0` to `1`diff --git a/prompts/agent.system.tool.behaviour.md b/prompts/agent.system.tool.behaviour.mdindex d078ab181..cfb096e93 100644--- a/prompts/agent.system.tool.behaviour.md+++ b/prompts/agent.system.tool.behaviour.md@@ -1,6 +1,6 @@### behaviour_adjustment-exact tool name uses british spelling: `behaviour_adjustment`update persistent behavioral rules+exact tool name uses british spelling: `behaviour_adjustment`arg: `adjustments` text describing what to add or removeuse for durable behavior, personality, style, response-format, greeting, and exact-response ruleswhen the user asks for an exact word, phrase, token, or casing, preserve it verbatim in `adjustments`diff --git a/tests/test_parallel_tool.py b/tests/test_parallel_tool.pyindex b6cadf001..0b7ef4850 100644--- a/tests/test_parallel_tool.py+++ b/tests/test_parallel_tool.py@@ -384,6 +384,97 @@ async def test_parallel_subordinate_jobs_are_visible_child_logs_not_scheduler_taassert "parallel_child" not in agent.context.log.items[0].kvps+async def test_parallel_subordinate_enforces_parent_delegation_policy(+ monkeypatch,+) -> None:+ from agent import AgentContext+ from helpers import tool_policy+ from helpers.errors import RepairableException++ parent_agent = SimpleNamespace(+ config=SimpleNamespace(profile="restricted"),+ context=_FakeContext(),+ )+ parent_context = SimpleNamespace(agent0=parent_agent)+ monkeypatch.setattr(+ AgentContext,+ "get",+ staticmethod(lambda _context_id: parent_context),+ )+ monkeypatch.setattr(tool_policy.subagents, "get_paths", lambda *args, **kwargs: [])+ monkeypatch.setattr(+ tool_policy,+ "get_policy",+ lambda agent: {+ "mode": "custom",+ "default": "allow",+ "allowed": [],+ "blocked": ["local:call_subordinate"],+ },+ )+ job = parallel_tools.ParallelJob(+ id="callsubordin-blocked",+ parent_context_id="ctx",+ index=0,+ tool_name="call_subordinate",+ tool_args={"profile": "developer", "message": "Work"},+ kind="subordinate",+ )++ with pytest.raises(+ RepairableException,+ match='Tool "call_subordinate" is blocked for agent profile "restricted"',+ ):+ await parallel_tools._run_subordinate_context_job("ctx", job)+++async def test_parallel_subordinate_reuses_profile_validation(monkeypatch) -> None:+ from agent import AgentContext+ from helpers import tool_policy+ from helpers.errors import RepairableException+ from tools import call_subordinate++ parent_agent = SimpleNamespace(+ config=SimpleNamespace(profile="agent0"),+ context=_FakeContext(),+ )+ parent_context = SimpleNamespace(agent0=parent_agent)+ monkeypatch.setattr(+ AgentContext,+ "get",+ staticmethod(lambda _context_id: parent_context),+ )+ monkeypatch.setattr(tool_policy.subagents, "get_paths", lambda *args, **kwargs: [])+ monkeypatch.setattr(+ tool_policy,+ "get_policy",+ lambda agent: {+ "mode": "inherit",+ "default": "allow",+ "allowed": [],+ "blocked": [],+ },+ )+ monkeypatch.setattr(+ call_subordinate.subagents,+ "get_available_agents_dict",+ lambda project_name: {"developer": SimpleNamespace(title="Developer")},+ )+ job = parallel_tools.ParallelJob(+ id="callsubordin-invalid",+ parent_context_id="ctx",+ index=0,+ tool_name="call_subordinate",+ tool_args={"profile": "ghost", "message": "Work"},+ kind="subordinate",+ )++ with pytest.raises(RepairableException, match="Agent profile 'ghost' not found"):+ await parallel_tools._run_subordinate_context_job("ctx", job)++@pytest.mark.asyncioasync def test_parallel_direct_tool_jobs_fallback_to_generic_tool_log_type(monkeypatch) -> None:class FakeDeferredTask:@@ -704,4 +795,3 @@ def test_chats_sidebar_projects_parallel_children_as_indented_accordion() -> Nonassert "left: 2px" in htmlassert "padding-left: 24px" in htmlassert "color: var(--color-text-muted)" in html- assert "padding: 8px;" in htmldiff --git a/tests/test_plugin_activation_ui.py b/tests/test_plugin_activation_ui.pyindex e839aa30c..afb21486b 100644--- a/tests/test_plugin_activation_ui.py+++ b/tests/test_plugin_activation_ui.py@@ -2,11 +2,13 @@ import sysfrom pathlib import Pathfrom types import SimpleNamespace+import pytestPROJECT_ROOT = Path(__file__).resolve().parents[1]if str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))+from api.plugins import Pluginsfrom helpers import files, plugins@@ -57,6 +59,50 @@ def test_list_toggle_state_is_global_even_when_scoped_rules_exist(monkeypatch):assert plugins.get_toggle_state("example") == "disabled"+def test_always_enabled_plugin_ignores_disable_files_at_runtime(monkeypatch):+ monkeypatch.setattr(plugins.cache, "get", lambda *args, **kwargs: None)+ monkeypatch.setattr(plugins.cache, "add", lambda *args, **kwargs: None)+ monkeypatch.setattr(plugins, "get_plugins_list", lambda: ["_required"])+ monkeypatch.setattr(+ plugins,+ "get_plugin_meta",+ lambda _plugin_name: SimpleNamespace(always_enabled=True),+ )++ def fail_on_toggle_lookup(*_args, **_kwargs):+ raise AssertionError("always-enabled plugins must ignore toggle files")++ monkeypatch.setattr(plugins, "determined_toggle_from_paths", fail_on_toggle_lookup)++ assert plugins.get_enabled_plugins(None) == ["_required"]+++def test_always_enabled_plugin_rejects_disable_attempt(monkeypatch):+ monkeypatch.setattr(+ plugins,+ "get_plugin_meta",+ lambda _plugin_name: SimpleNamespace(always_enabled=True),+ )++ with pytest.raises(ValueError, match="always enabled"):+ plugins.toggle_plugin.__wrapped__("_required", False)+++def test_plugin_api_returns_bad_request_for_rejected_disable(monkeypatch):+ def reject(*_args, **_kwargs):+ raise ValueError('Plugin "_required" is always enabled.')++ monkeypatch.setattr(plugins, "toggle_plugin", reject)++ response = Plugins._toggle_plugin.__wrapped__(+ object.__new__(Plugins),+ {"plugin_name": "_required", "enabled": False},+ )++ assert response.status_code == 400+ assert "always enabled" in response.get_data(as_text=True)++def test_config_scope_activation_toggle_saves_immediately_for_selected_scope():html = (PROJECT_ROOT / "webui/components/plugins/plugin-settings.html").read_text(encoding="utf-8"diff --git a/tests/test_tool_policy.py b/tests/test_tool_policy.pyindex f2c3283cd..11a4e1a42 100644--- a/tests/test_tool_policy.py+++ b/tests/test_tool_policy.py@@ -1,6 +1,8 @@from __future__ import annotationsfrom pathlib import Path+import subprocess+import sysfrom types import SimpleNamespaceimport pytest@@ -60,6 +62,14 @@ def _custom_policy(*, default: str, allowed=(), blocked=()):}+def test_agent_import_does_not_cycle_through_tool_policy() -> None:+ subprocess.run(+ [sys.executable, "-c", "import agent"],+ cwd=Path(__file__).parents[1],+ check=True,+ )++@pytest.fixturedef local_prompt_agent(monkeypatch, tmp_path: Path) -> _Agent:_write_prompt(tmp_path, "agent.system.tools.md", "TOOLS\n{{tools}}")@@ -197,6 +207,39 @@ def test_catalog_comes_from_executable_tools_not_prompt_names(assert catalog[0]["description"] == "Actual description"+def test_catalog_keeps_installed_remote_tools_without_live_connector(+ monkeypatch, tmp_path: Path+) -> None:+ tool_root = tmp_path / "tools"+ tool_root.mkdir()+ (tool_root / "code_execution_remote.py").write_text("", encoding="utf-8")+ (tool_root / "shell.py").write_text("", encoding="utf-8")+ monkeypatch.setattr(+ tool_policy.subagents,+ "get_paths",+ lambda *args, **kwargs: [str(tool_root)],+ )+ monkeypatch.setattr(+ mcp_handler.MCPConfig,+ "get_for_agent",+ lambda agent: _NoMCPTools(),+ )+ monkeypatch.setattr(+ tool_policy,+ "get_policy",+ lambda agent: {+ "mode": "inherit",+ "default": "allow",+ "allowed": [],+ "blocked": [],+ },+ )++ catalog = tool_policy.get_tool_catalog(_Agent(tmp_path))++ assert [item["name"] for item in catalog] == ["code_execution_remote", "shell"]++def test_tool_prompt_description_skips_fenced_examples() -> None:prompt = """### example~~~json@@ -208,6 +251,62 @@ Visible summaryassert tool_policy.tool_prompt_description(prompt, "example") == "Visible summary"+def test_tool_prompt_description_prefers_declared_summary() -> None:+ prompt = """## tools+- `memory_load`: search stored memories by meaning and metadata+ args: `query`, optional `limit`+"""++ assert (+ tool_policy.tool_prompt_description(prompt, "memory_load")+ == "search stored memories by meaning and metadata"+ )+++def test_prompt_filter_removes_complete_blocked_json_example(+ monkeypatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(+ tool_policy,+ "_policy_tool_names",+ lambda agent: {"memory_load", "memory_save"},+ )+ monkeypatch.setattr(tool_policy.subagents, "get_paths", lambda *args, **kwargs: [])+ monkeypatch.setattr(+ tool_policy,+ "get_policy",+ lambda agent: _custom_policy(+ default="allow", blocked=["local:memory_load"]+ ),+ )+ prompt = """## memory tools+- `memory_load`: load memory+- `memory_save`: save memory+~~~json+{+ "tool_name": "memory_load",+ "tool_args": {"query": "blocked example"}+}+~~~+~~~json+{+ "tool_name": "memory_save",+ "tool_args": {"text": "allowed example"}+}+~~~+"""++ filtered = tool_policy.filter_tool_prompt(+ _Agent(tmp_path), "agent.system.tool.memory.md", prompt+ )++ assert "blocked example" not in filtered+ assert "memory_load" not in filtered+ assert "allowed example" in filtered+ assert filtered.count("~~~json") == 1+ assert filtered.count("~~~") == 2++def test_plugin_tool_identity_uses_canonical_plugin_roots(monkeypatch, tmp_path: Path) -> None:@@ -250,6 +349,34 @@ def test_plugin_tool_identity_uses_canonical_plugin_roots(assert tool_policy.resolve_tool(agent, "actual").tool_id == "local:actual"+def test_dotted_local_tool_keeps_local_identity_at_execution_gate(+ monkeypatch, tmp_path: Path+) -> None:+ tool_path = tmp_path / "docs.read.py"+ tool_path.write_text("class Tool: pass\n", encoding="utf-8")+ monkeypatch.setattr(+ tool_policy.subagents,+ "get_paths",+ lambda *args, **kwargs: [str(tool_path)],+ )+ monkeypatch.setattr(+ mcp_handler.MCPConfig,+ "get_for_agent",+ lambda agent: _NoMCPTools(),+ )+ monkeypatch.setattr(+ tool_policy,+ "get_policy",+ lambda agent: _custom_policy(+ default="allow", blocked=["local:docs.read"]+ ),+ )+ agent = _Agent(tmp_path)++ with pytest.raises(RepairableException, match='Tool "docs.read" is blocked'):+ tool_policy.ensure_tool_allowed(agent, "docs.read")++def test_legacy_response_and_vision_policy_ids_stay_out_of_catalog(monkeypatch, tmp_path: Path) -> None:@@ -424,12 +551,12 @@ async def test_delegated_agent_uses_its_own_profile_policy_at_execution_gate(child = _Agent(tmp_path, profile="researcher")monkeypatch.setattr(tool_policy.subagents, "get_paths", lambda *args, **kwargs: [])- def config_for_profile(plugin_name, agent=None, **kwargs):+ def policy_for_profile(agent):if agent.config.profile == "researcher":return _custom_policy(default="block")return {"mode": "inherit"}- monkeypatch.setattr(tool_policy.plugins, "get_plugin_config", config_for_profile)+ monkeypatch.setattr(tool_policy, "get_policy", policy_for_profile)assert tool_policy.resolve_tool(parent, "shell").allowed is Trueassert tool_policy.resolve_tool(child, "shell").allowed is False@@ -506,7 +633,17 @@ def test_project_policy_precedes_profile_policy(assert decision.allowed is Falseassert decision.source == "scoped-policy"- project_profile_path.unlink()+ project_profile_path.write_text('{"manual": true}\n', encoding="utf-8")+ decision = tool_policy.resolve_tool(agent, "shell")+ assert decision.allowed is True+ assert decision.source == "scoped-default"+ assert project_profile_path.read_text(encoding="utf-8") == '{"manual": true}\n'++ project_profile_path.write_text(+ '{"manual": true, "mode": "inherit", "default": "block", '+ '"allowed": [], "blocked": ["local:shell"]}\n',+ encoding="utf-8",+ )decision = tool_policy.resolve_tool(agent, "shell")assert decision.allowed is Trueassert decision.source == "scoped-default"