Agent Zero AI framework
Fix user plugin precedence in provider and profile merges
Alessandroa4e65d472183
diff --git a/helpers/plugins.py b/helpers/plugins.pyindex e1ed711b6..0d184788a 100644--- a/helpers/plugins.py+++ b/helpers/plugins.py@@ -241,6 +241,15 @@ def get_plugin_name_from_path(path: str | Path) -> str:return ""+def get_plugin_root_priority(path: str | Path | None) -> int:+ """Return root order for a plugin asset; unrecognized paths rank last."""+ roots = get_plugin_roots()+ for priority, root in enumerate(roots):+ if path and Path(path).is_relative_to(root):+ return priority+ return len(roots)++def get_plugins_list():if (cached := cache.get(PLUGINS_LIST_CACHE_AREA, "")) is not None:return cached@@ -455,21 +464,9 @@ def get_enabled_plugin_paths(agent: Agent | None, *subpaths: str) -> List[str]:enabled = get_enabled_plugins(agent)paths: list[str] = []- # Discovery is alphabetical, but asset overrides follow root priority.- # Keep the existing order within each root so same-root collisions retain- # their precedence, while user plugins can override bundled plugins.- roots = [Path(root) for root in get_plugin_roots()]+ # Stable root ordering preserves same-root asset precedence.resolved = [find_plugin_dir(plugin) for plugin in enabled]- resolved.sort(- key=lambda base_dir: next(- (- index- for index, root in enumerate(roots)- if base_dir and Path(base_dir).is_relative_to(root)- ),- len(roots),- )- )+ resolved.sort(key=get_plugin_root_priority)for base_dir in resolved:if not base_dir:diff --git a/helpers/plugins.py.dox.md b/helpers/plugins.py.dox.mdindex 28efbe9c9..2f854ef52 100644--- a/helpers/plugins.py.dox.md+++ b/helpers/plugins.py.dox.md@@ -22,6 +22,7 @@- `clear_plugin_cache(plugin_names: list[str] | None=...)`- `get_plugin_roots(plugin_name: str=...) -> List[str]`: Plugin root directories, ordered by priority (user first).- `get_plugin_name_from_path(path: str | Path) -> str`: Return the plugin directory name only for paths below a canonical user or bundled plugin root.+- `get_plugin_root_priority(path: str | Path | None) -> int`: Return the containing root's index; unrecognized paths rank after declared roots.- `get_plugins_list()`- `get_enhanced_plugins_list(custom: bool=..., builtin: bool=..., plugin_names: list[str] | None=...) -> List[PluginListItem]`: Discover plugins by directory convention. First root wins on ID conflict.- `get_custom_plugins_updates(plugin_names: list[str] | None=...) -> List[PluginUpdateInfo]`@@ -53,6 +54,10 @@tools, prompts and same-filename extensions therefore honor user pluginoverrides. This does not reorder the plugin list or change activation rules,project/profile precedence, or extension execution order after deduplication.+- Last-value-wins provider and profile consumers stably sort a copy by+ `get_plugin_root_priority` in descending order. Bundled roots apply before+ user roots without reversing same-root discovery order or mutating cached+ asset paths; path discovery exposes only its normal user-first order.- 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 ofstale global or scoped disable files, and disable attempts are rejected.@@ -82,7 +87,8 @@- Related tests observed by source search:- `tests/test_plugin_asset_precedence.py` covers root priority, stable ordering,tool/prompt/extension selection, higher-priority scoped overrides, disabled- plugin fallback, missing paths and cached empty results.+ plugin fallback, provider/profile/editor merges, missing paths and cached+ empty results.- `tests/test_a0_connector_computer_use_metadata.py`- `tests/test_a0_connector_prompt_gating.py`- `tests/test_browser_agent_regressions.py`diff --git a/helpers/providers.py b/helpers/providers.pyindex 35888b73f..c57b0129a 100644--- a/helpers/providers.py+++ b/helpers/providers.py@@ -67,9 +67,11 @@ class ProviderManager:merged = self._normalise_yaml(self._load_yaml(base_path))# Merge plugin provider configs (enabled plugins only)- from helpers.plugins import get_enabled_plugin_paths+ from helpers.plugins import get_enabled_plugin_paths, get_plugin_root_priorityplugin_yamls = get_enabled_plugin_paths(None, "conf", "model_providers.yaml")- for plugin_yaml_path in plugin_yamls:+ for plugin_yaml_path in sorted(+ plugin_yamls, key=get_plugin_root_priority, reverse=True+ ):plugin_data = self._normalise_yaml(self._load_yaml(plugin_yaml_path))for p_type, providers in plugin_data.items():if p_type not in merged:@@ -139,4 +141,4 @@ def get_provider_config(provider_type: ModelType, provider_id: str) -> Optional[def reload_providers():"""Re-merge base + plugin provider configs. Call after plugin changes."""- ProviderManager.reload()\ No newline at end of file+ ProviderManager.reload()diff --git a/helpers/providers.py.dox.md b/helpers/providers.py.dox.mdindex 083ccecfc..abdc04b32 100644--- a/helpers/providers.py.dox.md+++ b/helpers/providers.py.dox.md@@ -27,6 +27,10 @@## Runtime Contracts+- Provider definitions merge base configuration, bundled plugin roots, then+ user plugin roots. Later definitions replace matching provider IDs; discovery+ order within each root is preserved by a stable root-priority sort on a copy+ of the enabled asset paths.- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.- 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 deletion, plugin state, settings/state persistence.@@ -47,6 +51,8 @@- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.- Related tests observed by source search:+ - `tests/test_plugin_asset_precedence.py` covers cross-root provider overrides+ and same-root merge order.- `tests/test_fastmcp_openapi_security.py`- `tests/test_model_config_api_keys.py`- `tests/test_oauth_codex.py`diff --git a/helpers/subagents.py b/helpers/subagents.pyindex dbb9575f4..9168f64eb 100644--- a/helpers/subagents.py+++ b/helpers/subagents.py@@ -69,7 +69,10 @@ def get_agents_dict(merged: dict[str, SubAgentListItem] = dict(default_agents)# merge with plugin agents- for plugin_dir in plugins.get_enabled_plugin_paths(None, "agents"):+ plugin_dirs = plugins.get_enabled_plugin_paths(None, "agents")+ for plugin_dir in sorted(+ plugin_dirs, key=plugins.get_plugin_root_priority, reverse=True+ ):plugin_agents = _get_agents_list_from_dir(plugin_dir, origin="plugin")merged = _merge_agent_dicts(merged, plugin_agents)@@ -124,7 +127,10 @@ def load_agent_data(name: str, project_name: str | None = None) -> SubAgent:# merge with plugin agents# TODO review this- for plugin_dir in plugins.get_enabled_plugin_paths(None, "agents"):+ plugin_dirs = plugins.get_enabled_plugin_paths(None, "agents")+ for plugin_dir in sorted(+ plugin_dirs, key=plugins.get_plugin_root_priority, reverse=True+ ):plugin_agent = _load_agent_data_from_dir(plugin_dir, name, origin="plugin")merged = _merge_agent(merged, plugin_agent)@@ -257,7 +263,11 @@ def _merge_agent_metadata(def get_agents_roots() -> list[str]:# from helpers import plugins- plugin_agents = plugins.get_enabled_plugin_paths(None, "agents")+ plugin_agents = sorted(+ plugins.get_enabled_plugin_paths(None, "agents"),+ key=plugins.get_plugin_root_priority,+ reverse=True,+ )project_agents = files.find_existing_paths_by_pattern("usr/projects/*/.a0proj/agents")paths = [files.get_abs_path(DEFAULT_AGENTS_DIR),diff --git a/helpers/subagents.py.dox.md b/helpers/subagents.py.dox.mdindex 4ae967cb8..27fc26798 100644--- a/helpers/subagents.py.dox.md+++ b/helpers/subagents.py.dox.md@@ -41,6 +41,11 @@- 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, plugin state, settings/state persistence.- Nonexistent profile layers return `None` instead of synthesizing empty overrides.+- Profile loading and catalogs merge bundled plugin roots before user plugin+ roots through a stable sort by `plugins.get_plugin_root_priority`, preserving+ discovery order within each root and leaving cached path lists unchanged.+ User/profile and project definitions still apply after plugin definitions;+ asset lookup retains high-priority-first order.- Imported dependency areas include: `helpers`, `json`, `os`, `pydantic`, `typing`.## Key Concepts@@ -69,6 +74,9 @@- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.- Related tests observed by source search:+ - `tests/test_plugin_asset_precedence.py` covers cross-root profile metadata,+ prompt, catalog and editor overrides, same-root merge order and higher+ user/project layers.- `tests/test_skills_runtime.py`- `tests/test_subagent_metadata_merge.py`diff --git a/plugins/_agent_editor/AGENTS.md b/plugins/_agent_editor/AGENTS.mdindex da9b8da55..856239940 100644--- a/plugins/_agent_editor/AGENTS.md+++ b/plugins/_agent_editor/AGENTS.md@@ -15,6 +15,8 @@## Local Contracts+- Plugin profile metadata layers merge bundled roots before user roots using+ stable root-priority sorting, matching runtime profile loading and catalogs.- The editor performs zero model calls.- Profile list requests stay lightweight: summary rows inspect only sparseeditor-owned keys and files and never construct full save or removal plans.diff --git a/plugins/_agent_editor/helpers/editor.py b/plugins/_agent_editor/helpers/editor.pyindex f59a5bcaf..1269cdba9 100644--- a/plugins/_agent_editor/helpers/editor.py+++ b/plugins/_agent_editor/helpers/editor.py@@ -554,7 +554,11 @@ def _profile_directories(Path(files.get_abs_path("agents", profile_id)),)]- for directory in plugins.get_enabled_plugin_paths(agent, "agents", profile_id):+ for directory in sorted(+ plugins.get_enabled_plugin_paths(agent, "agents", profile_id),+ key=plugins.get_plugin_root_priority,+ reverse=True,+ ):directories.append(("plugin", Path(directory)))directories.append(("user", USER_AGENTS_ROOT / profile_id))diff --git a/tests/test_plugin_asset_precedence.py b/tests/test_plugin_asset_precedence.pyindex bd07fbca2..8eb7bc012 100644--- a/tests/test_plugin_asset_precedence.py+++ b/tests/test_plugin_asset_precedence.py@@ -1,12 +1,14 @@"""User plugin assets must take precedence over bundled plugin assets."""+import asyncio+import jsonfrom pathlib import Pathfrom types import SimpleNamespaceimport pytestfrom agent import Agent-from helpers import cache, extension, files, plugins, subagents+from helpers import cache, extension, files, plugins, providers, responses_tools, subagents@pytest.fixture@@ -178,3 +180,122 @@ def test_empty_asset_results_are_cached(plugin_tree, monkeypatch):monkeypatch.setattr(plugins, "get_enabled_plugins", unexpected_lookup)assert plugins.get_enabled_plugin_paths(None, "missing") == []++def test_provider_merges_apply_user_roots_last_and_preserve_same_root_order(plugin_tree):+ roots = [+ plugin_tree("_alpha", bundled=True), plugin_tree("_zulu", bundled=True),+ plugin_tree("alpha"), plugin_tree("zulu"),+ ]+ for root in roots:+ (root / "conf").mkdir()+ (root / "conf/model_providers.yaml").write_text(+ json.dumps({"chat": {"codex_oauth": {+ "name": root.name,+ "kwargs": {"api_base": f"https://{root.name}.example/v1"},+ }}}),+ encoding="utf-8",+ )++ config = providers.ProviderManager().get_provider_config("chat", "codex_oauth")+ assert config["name"] == "zulu"+ assert config["kwargs"]["api_base"] == "https://zulu.example/v1"++ for root in roots[2:]:+ (root / ".toggle-0").touch()+ cache.clear("*(plugins)*")+ config = providers.ProviderManager().get_provider_config("chat", "codex_oauth")+ assert config["name"] == "_zulu"++[email protected]("reader", ["load", "catalog", "all_catalog", "editor"])+def test_profile_merges_preserve_root_order_and_higher_scope_overrides(+ plugin_tree, tmp_path, monkeypatch, reader+):+ from plugins._agent_editor.helpers import editor++ monkeypatch.setattr(editor, "USER_AGENTS_ROOT", tmp_path / "usr/agents")+ roots = [+ plugin_tree("_alpha", bundled=True), plugin_tree("_zulu", bundled=True),+ plugin_tree("alpha"), plugin_tree("zulu"),+ ]++ def write_profile(root, title):+ profile = root / "agents/researcher"+ (profile / "prompts").mkdir(parents=True)+ (profile / "agent.yaml").write_text(+ f"title: {title}\ncontext: {title}\n", encoding="utf-8"+ )+ (profile / "prompts/agent.system.main.specifics.md").write_text(+ title, encoding="utf-8"+ )++ def assert_profile(title, project_name=None):+ if reader == "load":+ profile = subagents.load_agent_data("researcher", project_name)+ assert profile.title == profile.context == title+ assert profile.prompts["agent.system.main.specifics.md"] == title+ elif reader == "catalog":+ assert subagents.get_agents_dict(project_name)["researcher"].title == title+ elif reader == "editor":+ state = editor.metadata_state("researcher", editor._EditorContext(project_name or ""))+ assert state["title"]["effective"] == state["context"]["effective"] == title+ else:+ assert subagents.get_all_agents_list() == [{"key": "researcher", "label": title}]++ for root in roots:+ write_profile(root, root.name)+ assert_profile("zulu")+ assert plugins.get_enabled_plugin_paths(None, "agents") == [+ str(root / "agents") for root in [*roots[2:], *roots[:2]]+ ]++ for root in roots[2:]:+ (root / ".toggle-0").touch()+ cache.clear("*(plugins)*")+ assert_profile("_zulu")++ write_profile(tmp_path / "usr", "User profile")+ assert_profile("User profile")+ write_profile(tmp_path / "usr/projects/demo/.a0proj", "Project profile")+ assert_profile("Project profile", "demo")+++def test_model_prompt_native_schema_and_dispatch_use_the_same_plugin(+ plugin_tree, monkeypatch, tmp_path+):+ from extensions.python.system_prompt._11_tools_prompt import build_prompt+ from plugins._model_config.helpers import model_config++ bundled = plugin_tree("_memory", bundled=True)+ user = plugin_tree("db_hub")+ for root, field in [(bundled, "text"), (user, "content")]:+ schema = {"type": "object", "properties": {field: {"type": "string"}}}+ (root / "prompts/agent.system.tool.memory.md").write_text(+ f"### memory_save\n{root.name}\nInput schema for tool_args:\n"+ + json.dumps(schema),+ encoding="utf-8",+ )+ template = tmp_path / "usr/prompts/agent.system.tools.md"+ template.parent.mkdir(parents=True)+ template.write_text("{{tools}}", encoding="utf-8")+ agent = object.__new__(Agent)+ agent.config = SimpleNamespace(profile="")+ agent.context = SimpleNamespace(get_data=lambda *args: None)+ agent.data = {}+ monkeypatch.setattr(responses_tools, "_mcp_tools", lambda _agent: [])+ monkeypatch.setattr(model_config, "get_chat_model_config", lambda _agent: {})+ monkeypatch.setattr(model_config, "get_vision_model_config", lambda _agent: {})++ for root, field, other in [(user, "content", bundled), (bundled, "text", user)]:+ prompt = asyncio.run(build_prompt(agent))+ assert prompt.count(root.name) == 1 and other.name not in prompt+ native, names = responses_tools.build_responses_function_tools(agent)+ assert len(native) == 1 and names == {"memory_save": "memory_save"}+ assert root.name in native[0]["description"]+ assert other.name not in native[0]["description"]+ assert set(native[0]["parameters"]["properties"]) == {field}+ tool = agent.get_tool("memory_save", None, {field: "probe"}, "", None)+ assert asyncio.run(tool.execute()).message == root.name+ (user / ".toggle-0").touch()+ cache.clear("*(plugins)*")+ cache.clear("*(extensions)*")