Skip to content

Agent Zero AI framework

Add project-scoped Agent Editor profiles

Alessandro027466c873b7
diff --git a/plugins/_agent_editor/AGENTS.md b/plugins/_agent_editor/AGENTS.md
index 5eba34891..ec3786b95 100644
--- a/plugins/_agent_editor/AGENTS.md
+++ b/plugins/_agent_editor/AGENTS.md
@@ -16,16 +16,19 @@
## Local Contracts
- The editor performs zero model calls.
-- Writes are limited to `usr/agents/<profile-id>` and only to paths or config
- keys listed in the validated change plan.
+- Writes are limited to the selected profile layer — global
+ `usr/agents/<profile-id>` or project
+ `usr/projects/<project>/.a0proj/agents/<profile-id>` — and only to paths or
+ config keys listed in the validated change plan.
- Never call `helpers.subagents.save_agent_data`.
- Authored profile definitions remain YAML; editor-written plugin configs remain
JSON.
-- Profile config paths use `helpers.plugins.determine_plugin_asset_path` while
- remaining rooted in the editor's validated user-profile boundary.
-- Active project tool policy is resolved through the standard plugin asset
- provenance and shown as higher priority; the editor still writes only the
- user-profile scope.
+- Profile config paths use `helpers.plugins.determine_plugin_asset_path` for the
+ selected Global or project scope and remain rooted in that exact validated
+ profile boundary.
+- Project profiles inherit the existing global, plugin, and bundled layers.
+ Removing or deleting in project scope never mutates those inherited layers;
+ only agents created in the selected scope are deletable.
- Bundled `agents/` files are read-only.
- Advanced prompt text is directly editable; per-file close/check actions
discard or accept the current edit checkpoint, while the editor's global save
@@ -37,6 +40,8 @@
tools remain absent from the tool catalog.
- Model selection reuses `_model_config`'s compact preset dropdown and preset
editor; Agent Editor persists only the scoped preset reference.
+- Manage agents reuses the plugin-settings project vocabulary: Global or one
+ existing project. Save & test activates that same scope in the fresh chat.
- The WebUI uses the shared modal stack, labeled prompt scroll regions, and
24px-or-larger policy and text-action targets.
diff --git a/plugins/_agent_editor/README.md b/plugins/_agent_editor/README.md
index fd9570689..23cca24cb 100644
--- a/plugins/_agent_editor/README.md
+++ b/plugins/_agent_editor/README.md
@@ -2,8 +2,13 @@
Agent Editor provides the deterministic Easy modal and Advanced workspace for
Agent Zero profiles. It reads the existing layered profile architecture and
-writes only sparse user overrides under `usr/agents/<profile-id>`.
+writes only sparse overrides in the selected Global or project profile layer.
The editor never invokes a model. Tool and skill controls are backed by the
central runtime policy owners, and every save is previewed as exact file writes
and deletions before the same validated plan is applied.
+
+Global agents and customizations live under `usr/agents/<profile-id>` and apply
+across projects. Project-scoped agents and customizations live under
+`usr/projects/<project>/.a0proj/agents/<profile-id>`, inherit the Global layer,
+and can be removed without changing it.
diff --git a/plugins/_agent_editor/api/agent_editor.py b/plugins/_agent_editor/api/agent_editor.py
index 9a2cacb6b..2f32dade5 100644
--- a/plugins/_agent_editor/api/agent_editor.py
+++ b/plugins/_agent_editor/api/agent_editor.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from pathlib import Path
from typing import Any
from agent import AgentContext
@@ -76,4 +77,6 @@ def _context(input: dict[str, Any]) -> Any:
project_name = str(input.get("project_name") or "").strip()
if project_name:
project_name = projects.validate_project_name(project_name)
+ if not Path(projects.get_project_folder(project_name)).is_dir():
+ raise ValueError("Project not found.")
return editor._EditorContext(project_name)
diff --git a/plugins/_agent_editor/helpers/editor.py b/plugins/_agent_editor/helpers/editor.py
index a3f5a3519..17def539e 100644
--- a/plugins/_agent_editor/helpers/editor.py
+++ b/plugins/_agent_editor/helpers/editor.py
@@ -81,6 +81,7 @@ class ChangePlan:
warnings: list[str] = field(default_factory=list)
staged_tokens: set[str] = field(default_factory=set)
profile_id: str = ""
+ project_name: str = ""
remove_empty_root: bool = False
def write(self, path: Path, content: str | bytes) -> None:
@@ -118,6 +119,34 @@ def validate_profile_id(profile_id: Any) -> str:
return value
+def _context_project_name(context: Any | None) -> str:
+ return str(projects.get_context_project_name(context) or "") if context else ""
+
+
+def _profile_root(profile_id: str, project_name: str = "") -> Path:
+ return (
+ Path(projects.get_project_meta(project_name, "agents", profile_id))
+ if project_name
+ else USER_AGENTS_ROOT / profile_id
+ )
+
+
+def _scope_has_files(root: Path) -> bool:
+ return root.is_dir() and any(
+ path.is_file() or path.is_symlink() for path in root.rglob("*")
+ )
+
+
+def _scope_owns_custom_profile(profile_id: str, project_name: str) -> bool:
+ if not _profile_root(profile_id, project_name).is_dir():
+ return False
+ if (Path(files.get_abs_path(subagents.DEFAULT_AGENTS_DIR)) / profile_id).is_dir():
+ return False
+ if any(Path(path).is_dir() for path in plugins.get_plugin_paths("agents", profile_id)):
+ return False
+ return not project_name or not (USER_AGENTS_ROOT / profile_id).is_dir()
+
+
def profile_exists(profile_id: str, context: Any | None = None) -> bool:
agent = EditorAgent(profile_id, context)
if (Path(files.get_abs_path(subagents.DEFAULT_AGENTS_DIR)) / profile_id).is_dir():
@@ -126,7 +155,7 @@ def profile_exists(profile_id: str, context: Any | None = None) -> bool:
return True
if any(Path(path).is_dir() for path in plugins.get_plugin_paths("agents", profile_id)):
return True
- project_name = projects.get_context_project_name(agent.context) or ""
+ project_name = _context_project_name(agent.context)
return bool(
project_name
and Path(projects.get_project_meta(project_name, "agents", profile_id)).is_dir()
@@ -134,10 +163,13 @@ def profile_exists(profile_id: str, context: Any | None = None) -> bool:
def list_profiles(context: Any | None = None) -> list[dict[str, Any]]:
- project_name = projects.get_context_project_name(context) if context else None
+ project_name = _context_project_name(context)
resolved = subagents.get_agents_dict(project_name)
names = set(resolved)
- for root in (Path(files.get_abs_path("agents")), USER_AGENTS_ROOT):
+ roots = [Path(files.get_abs_path("agents")), USER_AGENTS_ROOT]
+ if project_name:
+ roots.append(Path(projects.get_project_meta(project_name, "agents")))
+ for root in roots:
if root.is_dir():
names.update(path.name for path in root.iterdir() if path.is_dir())
@@ -154,10 +186,10 @@ def list_profiles(context: Any | None = None) -> list[dict[str, Any]]:
"origin": state["origin"],
"origin_chain": state["origin_chain"],
"built_in": state["built_in"],
- "has_user_overrides": state["has_user_overrides"],
+ "scope_has_overrides": state["scope_has_overrides"],
+ "deletable": state["deletable"],
"avatar": state["avatar"]["effective"],
"avatar_url": effective_avatar_url(profile_id, context),
- "project_override_active": state["project_override_active"],
"enabled": bool(getattr(resolved.get(profile_id), "enabled", True)),
"available": profile_exists(profile_id, context),
}
@@ -191,27 +223,21 @@ def build_editor_state(
"embedding": _model_identity(resolved.get("embedding_model")),
}
)
- model_path = _profile_config_path(profile_id, "_model_config")
- model_user = _read_mapping(model_path)
+ project_name = _context_project_name(agent.context)
+ model_path = _profile_config_path(profile_id, "_model_config", project_name)
+ model_scope = _read_mapping(model_path)
selected = model_config.get_configured_preset_name(agent=agent)
- tool_path = _profile_config_path(profile_id, tool_policy.PLUGIN_NAME)
- skill_path = _profile_config_path(profile_id, skills.ACTIVE_SKILLS_PLUGIN_NAME)
- tool_user = _read_mapping(tool_path)
- project_name = projects.get_context_project_name(agent.context) or ""
- tool_source = (
- plugins.find_plugin_asset(
- tool_policy.PLUGIN_NAME,
- plugins.CONFIG_FILE_NAME,
- project_name=project_name,
- agent_profile=profile_id,
- )
- if project_name
- else None
+ tool_path = _profile_config_path(profile_id, tool_policy.PLUGIN_NAME, project_name)
+ skill_path = _profile_config_path(
+ profile_id,
+ skills.ACTIVE_SKILLS_PLUGIN_NAME,
+ project_name,
)
- skill_user = _read_mapping(skill_path)
+ tool_scope = _read_mapping(tool_path)
+ skill_scope = _read_mapping(skill_path)
skill_policy = skills.normalize_visibility_policy(
- skill_user.get("visibility_policy")
+ skill_scope.get("visibility_policy")
)
effective_skill_policy = skills.get_visibility_policy(agent)
skill_catalog = [
@@ -255,23 +281,22 @@ def build_editor_state(
"profile": build_profile_state(profile_id, context),
"prompts": prompt_files,
"tools": {
- "policy": tool_policy.normalize_policy(tool_user),
- "has_override": any(key in tool_user for key in _POLICY_KEYS),
- "project_override_active": bool(
- tool_source and tool_source.get("project_name")
- ),
+ "policy": tool_policy.normalize_policy(tool_scope),
+ "effective_policy": tool_policy.get_policy(agent),
+ "has_override": any(key in tool_scope for key in _POLICY_KEYS),
"catalog": tool_catalog,
},
"skills": {
"policy": skill_policy,
- "has_override": "visibility_policy" in skill_user,
+ "effective_policy": effective_skill_policy,
+ "has_override": "visibility_policy" in skill_scope,
"catalog": skill_catalog,
},
"model_presets": presets,
"model_preset": {
"effective": selected,
- "override": model_user.get(model_config.MODEL_PRESET_CONFIG_KEY),
- "has_override": model_config.MODEL_PRESET_CONFIG_KEY in model_user,
+ "override": model_scope.get(model_config.MODEL_PRESET_CONFIG_KEY),
+ "has_override": model_config.MODEL_PRESET_CONFIG_KEY in model_scope,
},
}
@@ -287,8 +312,8 @@ def build_profile_state(
"origin": metadata.pop("origin"),
"origin_chain": metadata.pop("origin_chain"),
"built_in": metadata.pop("built_in"),
- "has_user_overrides": metadata.pop("has_user_overrides"),
- "project_override_active": metadata.pop("project_override_active"),
+ "scope_has_overrides": metadata.pop("scope_has_overrides"),
+ "deletable": metadata.pop("deletable"),
"metadata": metadata,
"avatar_url": effective_avatar_url(profile_id, context),
}
@@ -296,29 +321,28 @@ def build_profile_state(
def metadata_state(profile_id: str, context: Any | None = None) -> dict[str, Any]:
layers = _metadata_layers(profile_id, context)
- user_layer = next((layer for layer in layers if layer.kind == "user"), None)
- lower_layers = [
- layer for layer in layers if layer.kind not in {"user", "project"}
- ]
+ project_name = _context_project_name(context)
+ scope_kind = "project" if project_name else "user"
+ scope_layer = next((layer for layer in layers if layer.kind == scope_kind), None)
+ lower_layers = [layer for layer in layers if layer.kind != scope_kind]
state: dict[str, Any] = {}
for key in METADATA_KEYS:
- effective, source, source_kind = _layer_value(layers, key)
+ effective, source, _ = _layer_value(layers, key)
inherited, inherited_source, _ = _layer_value(lower_layers, key)
state[key] = {
"effective": effective,
"override": (
- user_layer.data.get(key)
- if user_layer and key in user_layer.data
+ scope_layer.data.get(key)
+ if scope_layer and key in scope_layer.data
else None
),
- "has_override": bool(user_layer and key in user_layer.data),
+ "has_override": bool(scope_layer and key in scope_layer.data),
"source": _relative_source(source),
"inherited": inherited,
"inherited_source": _relative_source(inherited_source),
- "project_override_active": source_kind == "project",
}
- user_dir = USER_AGENTS_ROOT / profile_id
+ scope_root = _profile_root(profile_id, project_name)
built_in = (Path(files.get_abs_path("agents")) / profile_id).is_dir()
plugin_origin = any(layer.kind == "plugin" for layer in layers)
state.update(
@@ -326,10 +350,8 @@ def metadata_state(profile_id: str, context: Any | None = None) -> dict[str, Any
"origin": "Built-in" if built_in else "Plugin" if plugin_origin else "Custom",
"origin_chain": list(dict.fromkeys(layer.kind for layer in layers)),
"built_in": built_in,
- "has_user_overrides": user_dir.is_dir() and any(user_dir.iterdir()),
- "project_override_active": any(
- layer.kind == "project" for layer in layers
- ),
+ "scope_has_overrides": _scope_has_files(scope_root),
+ "deletable": _scope_owns_custom_profile(profile_id, project_name),
}
)
return state
@@ -345,8 +367,8 @@ def prompt_catalog(agent: EditorAgent) -> list[dict[str, Any]]:
if path.is_file() and path.name not in NON_PROMPT_MARKDOWN
}
names.add(SPECIFICS_FILE)
- user_prompt_dir = USER_AGENTS_ROOT / agent.config.profile / "prompts"
- project_name = projects.get_context_project_name(agent.context) or ""
+ project_name = _context_project_name(agent.context)
+ scope_prompt_dir = _profile_root(agent.config.profile, project_name) / "prompts"
project_root = (
Path(projects.get_project_meta(project_name)) if project_name else None
)
@@ -356,34 +378,32 @@ def prompt_catalog(agent: EditorAgent) -> list[dict[str, Any]]:
for root in roots:
path = root / name
if path.is_file():
- kind, label = _prompt_source(root, user_prompt_dir, project_root)
+ kind, label = _prompt_source(root, scope_prompt_dir, project_root)
occurrences.append((path, kind, label))
effective = occurrences[0] if occurrences else None
- user = next((item for item in occurrences if item[1] == "user"), None)
+ override = next((item for item in occurrences if item[1] == "scope"), None)
inherited = next(
(
item
for item in occurrences
- if item[1] not in {"user", "project"}
+ if item[1] != "scope"
),
None,
)
effective_text, effective_error = _prompt_text(effective[0] if effective else None)
- user_text, user_error = _prompt_text(user[0] if user else None)
+ override_text, override_error = _prompt_text(override[0] if override else None)
inherited_text, inherited_error = _prompt_text(
inherited[0] if inherited else None
)
group_number, group_label = _prompt_group(name)
source_kind = effective[1] if effective else ""
- if effective_error or user_error or inherited_error:
+ if effective_error or override_error or inherited_error:
state = "Conflict"
- elif source_kind == "project":
- state = "Project override active"
- elif user:
+ elif override:
state = (
"Overridden here (empty)"
- if user_text == ""
+ if override_text == ""
else "Overridden here"
)
elif source_kind == "plugin":
@@ -402,8 +422,8 @@ def prompt_catalog(agent: EditorAgent) -> list[dict[str, Any]]:
"group_label": group_label,
"state": state,
"effective": effective_text,
- "override": user_text if user else None,
- "has_override": bool(user),
+ "override": override_text if override else None,
+ "has_override": bool(override),
"inherited": inherited_text,
"source": _relative_source(effective[0] if effective else None),
"inherited_source": _relative_source(
@@ -412,9 +432,8 @@ def prompt_catalog(agent: EditorAgent) -> list[dict[str, Any]]:
"source_chain": [
label for _, _, label in reversed(occurrences)
],
- "project_override_active": source_kind == "project",
"preview": preview,
- "error": effective_error or user_error or inherited_error,
+ "error": effective_error or override_error or inherited_error,
"dynamic_processor": any(
(root / f"{Path(name).stem}.py").is_file() for root in roots
),
@@ -443,7 +462,7 @@ def effective_avatar_url(profile_id: str, context: Any | None = None) -> str:
"profile_id": profile_id,
"v": str(path.stat().st_mtime_ns),
}
- project_name = projects.get_context_project_name(context) if context else ""
+ project_name = _context_project_name(context)
if project_name:
query["project_name"] = project_name
return "/api/plugins/_agent_editor/agent_editor_avatar?" + urlencode(query)
@@ -461,7 +480,7 @@ def _metadata_layers(profile_id: str, context: Any | None) -> list[ProfileLayer]
directories.append(("plugin", Path(directory)))
directories.append(("user", USER_AGENTS_ROOT / profile_id))
- project_name = projects.get_context_project_name(agent.context) or ""
+ project_name = _context_project_name(agent.context)
if project_name:
directories.append(
(
@@ -511,10 +530,10 @@ def _layer_value(
def _prompt_source(
- root: Path, user_prompt_dir: Path, project_root: Path | None
+ root: Path, scope_prompt_dir: Path, project_root: Path | None
) -> tuple[str, str]:
- if root.resolve() == user_prompt_dir.resolve():
- return "user", "Your override"
+ if root.resolve() == scope_prompt_dir.resolve():
+ return "scope", "Your override"
if project_root and files.is_in_dir(str(root), str(project_root)):
return "project", f"Project · {project_root.parent.name}"
plugin = plugins.get_plugin_name_from_path(root)
@@ -558,11 +577,15 @@ def _model_identity(value: Any) -> dict[str, str]:
}
-def _profile_config_path(profile_id: str, plugin_name: str) -> Path:
+def _profile_config_path(
+ profile_id: str,
+ plugin_name: str,
+ project_name: str = "",
+) -> Path:
return Path(
plugins.determine_plugin_asset_path(
plugin_name,
- "",
+ project_name,
profile_id,
plugins.CONFIG_FILE_NAME,
)
@@ -639,6 +662,8 @@ def build_change_plan(
raise ValueError("The save patch must be an object.")
profile_id = validate_profile_id(patch.get("profile_id"))
+ project_name = _context_project_name(context)
+ profile_root = _profile_root(profile_id, project_name)
creating = bool(patch.get("creating"))
easy = str(patch.get("editor_mode") or "advanced").lower() == "easy"
exists = profile_exists(profile_id, context)
@@ -650,7 +675,7 @@ def build_change_plan(
if not creating and not exists:
raise ValueError(f'Agent profile "{profile_id}" does not exist.')
- plan = ChangePlan(profile_id=profile_id)
+ plan = ChangePlan(profile_id=profile_id, project_name=project_name)
if "metadata" in patch:
_plan_metadata(plan, patch["metadata"], context, creating=creating)
if "prompts" in patch:
@@ -669,10 +694,10 @@ def build_change_plan(
_plan_skill_policy(plan, patch["skill_policy"])
if creating:
- metadata = _planned_mapping(plan, USER_AGENTS_ROOT / profile_id / "agent.yaml")
+ metadata = _planned_mapping(plan, profile_root / "agent.yaml")
if not str(metadata.get("title") or "").strip():
raise ValueError("Agent name is required.")
- specifics = USER_AGENTS_ROOT / profile_id / "prompts" / SPECIFICS_FILE
+ specifics = profile_root / "prompts" / SPECIFICS_FILE
change = plan.changes.get(specifics)
if not change or change.action != "write" or not (change.content or b"").strip():
raise ValueError("Instructions are required for a new agent.")
@@ -697,8 +722,9 @@ def _plan_metadata(
raise ValueError("A metadata field cannot be set and reset in one save.")
profile_id = plan.profile_id
- yaml_path = USER_AGENTS_ROOT / profile_id / "agent.yaml"
- legacy_path = USER_AGENTS_ROOT / profile_id / "agent.json"
+ profile_root = _profile_root(profile_id, plan.project_name)
+ yaml_path = profile_root / "agent.yaml"
+ legacy_path = profile_root / "agent.json"
data = _read_mapping_strict(
yaml_path if yaml_path.is_file() else legacy_path,
"profile metadata",
@@ -709,7 +735,7 @@ def _plan_metadata(
for key in reset_values:
data.pop(key, None)
if key == "avatar" and _editor_image_avatar(current_user_avatar):
- plan.delete(USER_AGENTS_ROOT / profile_id / "assets" / "avatar.webp")
+ plan.delete(profile_root / "assets" / "avatar.webp")
for key, raw in set_values.items():
if key in {"title", "description", "context"}:
@@ -723,7 +749,7 @@ def _plan_metadata(
if normalized.get("kind") == "color" and _editor_image_avatar(
current_user_avatar
):
- plan.delete(USER_AGENTS_ROOT / profile_id / "assets" / "avatar.webp")
+ plan.delete(profile_root / "assets" / "avatar.webp")
inherited = state[key]["inherited"]
if not creating and normalized == inherited:
@@ -773,7 +799,7 @@ def _plan_prompts(
"Restore original instructions."
)
item = catalog[filename]
- path = USER_AGENTS_ROOT / plan.profile_id / "prompts" / filename
+ path = _profile_root(plan.profile_id, plan.project_name) / "prompts" / filename
if (
not creating
and item.get("inherited_source")
@@ -786,13 +812,15 @@ def _plan_prompts(
if total > MAX_PROMPTS_BYTES:
raise ValueError("The combined prompt changes are too large.")
for filename in reset_values:
- plan.delete(USER_AGENTS_ROOT / plan.profile_id / "prompts" / filename)
+ plan.delete(
+ _profile_root(plan.profile_id, plan.project_name) / "prompts" / filename
+ )
def _plan_model_preset(plan: ChangePlan, value: Any) -> None:
section = _mapping(value, "model_preset")
mode = str(section.get("mode") or "inherit").strip().lower()
- path = _profile_config_path(plan.profile_id, "_model_config")
+ path = _profile_config_path(plan.profile_id, "_model_config", plan.project_name)
data = _read_mapping_strict(path, "model preset configuration")
from plugins._model_config.helpers import model_config
@@ -813,7 +841,11 @@ def _plan_model_preset(plan: ChangePlan, value: Any) -> None:
def _plan_tool_policy(plan: ChangePlan, value: Any) -> None:
section = _mapping(value, "tool_policy")
mode = str(section.get("mode") or "inherit").strip().lower()
- path = _profile_config_path(plan.profile_id, tool_policy.PLUGIN_NAME)
+ path = _profile_config_path(
+ plan.profile_id,
+ tool_policy.PLUGIN_NAME,
+ plan.project_name,
+ )
data = _read_mapping_strict(path, "tool policy configuration")
if mode == "inherit":
@@ -840,7 +872,11 @@ def _plan_tool_policy(plan: ChangePlan, value: Any) -> None:
def _plan_skill_policy(plan: ChangePlan, value: Any) -> None:
section = _mapping(value, "skill_policy")
mode = str(section.get("mode") or "inherit").strip().lower()
- path = _profile_config_path(plan.profile_id, skills.ACTIVE_SKILLS_PLUGIN_NAME)
+ path = _profile_config_path(
+ plan.profile_id,
+ skills.ACTIVE_SKILLS_PLUGIN_NAME,
+ plan.project_name,
+ )
data = _read_mapping_strict(path, "skill policy configuration")
if mode == "inherit":
@@ -878,7 +914,9 @@ def _normalize_avatar(plan: ChangePlan, value: Any) -> dict[str, str]:
if not source.is_file():
raise ValueError("The staged avatar has expired. Upload it again.")
plan.write(
- USER_AGENTS_ROOT / plan.profile_id / "assets" / "avatar.webp",
+ _profile_root(plan.profile_id, plan.project_name)
+ / "assets"
+ / "avatar.webp",
source.read_bytes(),
)
plan.staged_tokens.add(token)
@@ -949,7 +987,15 @@ def _editor_image_avatar(value: Any) -> bool:
def apply_change_plan(plan: ChangePlan) -> dict[str, Any]:
- root = USER_AGENTS_ROOT / validate_profile_id(plan.profile_id)
+ project_name = (
+ projects.validate_project_name(plan.project_name) if plan.project_name else ""
+ )
+ if project_name and not Path(projects.get_project_folder(project_name)).is_dir():
+ raise ValueError("Project not found.")
+ root = _profile_root(
+ validate_profile_id(plan.profile_id),
+ project_name,
+ )
changes = sorted(plan.changes.values(), key=lambda item: str(item.path))
_validate_plan_paths(root, changes)
receipt = plan.response()
@@ -1011,7 +1057,7 @@ def plan_remove_changes(
if not profile_exists(profile_id, context):
raise ValueError(f'Agent profile "{profile_id}" does not exist.')
if destructive:
- return _full_delete_plan(profile_id)
+ return _full_delete_plan(profile_id, context)
catalog = prompt_catalog(EditorAgent(profile_id, context))
prompt_resets = [
@@ -1036,21 +1082,22 @@ def plan_remove_changes(
def plan_delete_custom(profile_id: str, context: Any | None = None) -> ChangePlan:
profile_id = validate_profile_id(profile_id)
state = metadata_state(profile_id, context)
- if state["origin"] != "Custom":
- raise ValueError("Built-in and plugin-provided agents cannot be deleted.")
- return _full_delete_plan(profile_id)
+ if not state["deletable"]:
+ raise ValueError("Only custom agents created in this scope can be deleted.")
+ return _full_delete_plan(profile_id, context)
def delete_impact(profile_id: str, context: Any | None = None) -> dict[str, Any]:
profile_id = validate_profile_id(profile_id)
state = metadata_state(profile_id, context)
- root = USER_AGENTS_ROOT / profile_id
+ project_name = _context_project_name(context)
+ root = _profile_root(profile_id, project_name)
file_paths = [
_relative_source(path)
for path in sorted(root.rglob("*"))
if path.is_file() or path.is_symlink()
] if root.is_dir() else []
- references = _profile_reference_paths(profile_id)
+ references = _profile_reference_paths(profile_id, project_name)
sessions: list[str] = []
try:
from agent import AgentContext
@@ -1060,15 +1107,22 @@ def delete_impact(profile_id: str, context: Any | None = None) -> dict[str, Any]
for item in AgentContext.all()
if str(getattr(getattr(item.agent0, "config", None), "profile", ""))
== profile_id
+ and (
+ not project_name
+ or projects.get_context_project_name(item) == project_name
+ )
]
except Exception:
pass
- model_config = _read_mapping(_profile_config_path(profile_id, "_model_config"))
+ model_config = _read_mapping(
+ _profile_config_path(profile_id, "_model_config", project_name)
+ )
return {
"profile_id": profile_id,
- "deletable": state["origin"] == "Custom",
+ "deletable": state["deletable"],
"origin": state["origin"],
+ "project_name": project_name,
"files": file_paths,
"project_references": references,
"active_sessions": sessions,
@@ -1128,9 +1182,17 @@ def staged_avatar_path(token: str) -> Path:
return STAGED_AVATAR_ROOT / f"{token}.webp"
-def _full_delete_plan(profile_id: str) -> ChangePlan:
- root = USER_AGENTS_ROOT / profile_id
- plan = ChangePlan(profile_id=profile_id, remove_empty_root=True)
+def _full_delete_plan(
+ profile_id: str,
+ context: Any | None = None,
+) -> ChangePlan:
+ project_name = _context_project_name(context)
+ root = _profile_root(profile_id, project_name)
+ plan = ChangePlan(
+ profile_id=profile_id,
+ project_name=project_name,
+ remove_empty_root=True,
+ )
if not root.is_dir():
return plan
for path in sorted(root.rglob("*")):
@@ -1150,7 +1212,7 @@ def _validate_plan_paths(root: Path, changes: list[FileChange]) -> None:
raise ValueError("Invalid change-plan action.")
resolved = change.path.resolve(strict=False)
if not files.is_in_dir(str(resolved), str(intended_root)):
- raise ValueError("A planned path is outside the user profile directory.")
+ raise ValueError("A planned path is outside the selected profile directory.")
cursor = change.path.parent
while files.is_in_dir(str(cursor), str(intended_root)):
if cursor.is_symlink():
@@ -1248,13 +1310,18 @@ def _cleanup_staged_avatars() -> None:
pass
-def _profile_reference_paths(profile_id: str) -> list[str]:
- roots = Path(files.get_abs_path("usr", "projects"))
- if not roots.is_dir():
+def _profile_reference_paths(profile_id: str, project_name: str = "") -> list[str]:
+ root = (
+ Path(projects.get_project_meta(project_name))
+ if project_name
+ else Path(files.get_abs_path("usr", "projects"))
+ )
+ if not root.is_dir():
return []
references: list[str] = []
for suffix in ("*.json", "*.yaml", "*.yml"):
- for path in roots.glob(f"*/.a0proj/**/{suffix}"):
+ pattern = f"**/{suffix}" if project_name else f"*/.a0proj/**/{suffix}"
+ for path in root.glob(pattern):
try:
if profile_id in path.read_text(encoding="utf-8"):
references.append(_relative_source(path))
diff --git a/plugins/_agent_editor/webui/agent-editor-store.js b/plugins/_agent_editor/webui/agent-editor-store.js
index 9307d11e8..4959c29c8 100644
--- a/plugins/_agent_editor/webui/agent-editor-store.js
+++ b/plugins/_agent_editor/webui/agent-editor-store.js
@@ -42,12 +42,24 @@ function policyFromState(value, hasOverride) {
}
function policyAllows(policy, id) {
- if (policy.mode !== "custom") return true;
+ if (!policy || policy.mode !== "custom") return true;
if (policy.blocked.includes(id)) return false;
if (policy.allowed.includes(id)) return true;
return policy.default === "allow";
}
+function policyBehavior(policy) {
+ const value = policy || {};
+ if (value.mode !== "custom") {
+ return { default: "allow", allowed: [], blocked: [] };
+ }
+ return {
+ default: value.default === "block" ? "block" : "allow",
+ allowed: unique(value.allowed).sort(),
+ blocked: unique(value.blocked).sort(),
+ };
+}
+
function movePolicyItem(policy, id, allow) {
policy.allowed = policy.allowed.filter((item) => item !== id);
policy.blocked = policy.blocked.filter((item) => item !== id);
@@ -63,7 +75,7 @@ function escapeHtml(value) {
}
const model = {
- intent: { view: "create", profileId: "", contextId: "" },
+ intent: { view: "create", profileId: "", contextId: "", projectName: "" },
view: "editor",
mode: "easy",
section: "1",
@@ -72,6 +84,8 @@ const model = {
avatarUploading: false,
error: "",
state: null,
+ projects: [],
+ projectName: "",
profiles: [],
draft: null,
initialDraft: null,
@@ -107,10 +121,17 @@ const model = {
},
async open(options = {}) {
+ const contextProject = chatsStore.selectedContext?.project;
+ const currentProjectName = typeof contextProject === "object"
+ ? String(contextProject?.name || "")
+ : String(contextProject || "");
this.intent = {
view: options.view || (options.profileId ? "edit" : "create"),
profileId: String(options.profileId || ""),
contextId: String(options.contextId || chatsStore.selected || ""),
+ projectName: options.projectName === undefined
+ ? currentProjectName
+ : String(options.projectName || ""),
};
this.suppressClosePrompt = false;
return await openModal(MODAL, () => this.beforeClose());
@@ -128,6 +149,7 @@ const model = {
this.plan = { written: [], deleted: [], warnings: [] };
this.planStatus = "idle";
this.view = this.intent.view === "manage" ? "manage" : "editor";
+ this.projectName = this.intent.projectName || "";
const modalTitle =
this.view === "manage"
? "Manage agents"
@@ -145,6 +167,12 @@ const model = {
this.mode = "easy";
this.section = this.savedSection();
this.syncSurface();
+ await this.loadProjects();
+ if (this.projectName && this.projects.length
+ && !this.projects.some((project) => project.key === this.projectName)) {
+ this.projectName = "";
+ this.intent = { ...this.intent, projectName: "" };
+ }
await this.loadProfiles();
if (this.view === "manage") {
this.loading = false;
@@ -161,7 +189,7 @@ const model = {
try {
const data = await callJsonApi(API, {
action: "list",
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.profiles = data.profiles || [];
} catch (error) {
@@ -170,6 +198,40 @@ const model = {
}
},
+ async loadProjects() {
+ try {
+ const data = await callJsonApi("/projects", { action: "list_options" });
+ this.projects = data.ok ? (data.data || []) : [];
+ } catch {
+ this.projects = [];
+ }
+ },
+
+ scopeInput() {
+ return { project_name: this.projectName || "" };
+ },
+
+ get scopeLabel() {
+ if (!this.projectName) return "Global";
+ return this.projects.find((project) => project.key === this.projectName)?.label
+ || this.projectName;
+ },
+
+ get inheritedLabel() {
+ return this.projectName ? "Inherited" : "Default";
+ },
+
+ async onScopeChanged() {
+ this.intent = { ...this.intent, projectName: this.projectName || "" };
+ this.loading = true;
+ this.error = "";
+ try {
+ await this.loadProfiles();
+ } finally {
+ this.loading = false;
+ }
+ },
+
async loadEditor(profileId, creating = false) {
this.loading = true;
this.error = "";
@@ -177,7 +239,7 @@ const model = {
const data = await callJsonApi(API, {
action: "load",
profile_id: profileId,
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.state = data.state;
this.intent = { ...this.intent, view: creating ? "create" : "edit", profileId };
@@ -468,6 +530,7 @@ const model = {
metadataProvenance(key) {
const metadata = this.state?.profile?.metadata?.[key] || {};
if (metadata.has_override && !this.metadataResetPending(key)) return "Customized by you";
+ if (this.projectName) return "Inherited from Global";
const match = String(metadata.inherited_source || metadata.source || "")
.match(/(?:^|\/)agents\/([^/]+)/);
const sourceId = match?.[1] || "";
@@ -536,13 +599,15 @@ const model = {
},
promptDisplayState(prompt) {
- if (prompt?.reset) return "Will use the default";
+ if (prompt?.reset) return this.projectName ? "Will use inherited" : "Will use the default";
if (prompt?.has_override || this.promptDirty(prompt)) return "Customized by you";
- return prompt?.state === "Unavailable" ? "Unavailable" : "Default";
+ if (prompt?.state === "Unavailable") return "Unavailable";
+ return this.projectName ? "Inherited" : "Default";
},
promptSourceChain(prompt) {
if (!prompt?.reset && (prompt?.has_override || this.promptDirty(prompt))) return "Customized by you";
+ if (this.projectName) return "Inherited from Global";
const source = [...(prompt?.source_chain || [])]
.filter((item) => item !== "Your override")
.at(-1);
@@ -596,7 +661,10 @@ const model = {
},
copyPromptPath() {
- const path = `usr/agents/${this.draft.profileId}/prompts/${this.selectedPrompt}`;
+ const root = this.projectName
+ ? `usr/projects/${this.projectName}/.a0proj/agents`
+ : "usr/agents";
+ const path = `${root}/${this.draft.profileId}/prompts/${this.selectedPrompt}`;
navigator.clipboard?.writeText(path);
globalThis.justToast?.("Path copied", "success", 1200, "agent-editor-copy");
},
@@ -607,21 +675,26 @@ const model = {
this.selectedBlockedTools = [];
},
+ customizePolicy(kind) {
+ const key = kind === "tool" ? "toolPolicy" : "skillPolicy";
+ if (this.draft[key].mode === "custom") return;
+ const state = kind === "tool" ? this.state.tools : this.state.skills;
+ this.draft[key] = { mode: "custom", ...policyBehavior(state.effective_policy) };
+ },
+
chooseTools() {
- if (this.draft.toolPolicy.mode !== "custom") {
- this.draft.toolPolicy = { mode: "custom", default: "allow", allowed: [], blocked: [] };
- }
+ this.customizePolicy("tool");
this.setMode("advanced", "3");
},
setEasyToolAllowed(id, allow) {
- if (this.draft.toolPolicy.mode !== "custom") {
- this.draft.toolPolicy = { mode: "custom", default: "allow", allowed: [], blocked: [] };
- }
+ this.customizePolicy("tool");
this.moveTools([id], allow);
const policy = this.draft.toolPolicy;
- if (this.initialDraft?.toolPolicy.mode !== "custom" && policy.default === "allow"
- && !policy.allowed.length && !policy.blocked.length) this.useStandardTools();
+ if (this.initialDraft?.toolPolicy.mode !== "custom"
+ && same(policyBehavior(policy), policyBehavior(this.state.tools.effective_policy))) {
+ this.useStandardTools();
+ }
},
useStandardSkills() {
@@ -631,9 +704,7 @@ const model = {
},
chooseSkills() {
- if (this.draft.skillPolicy.mode !== "custom") {
- this.draft.skillPolicy = { mode: "custom", default: "allow", allowed: [], blocked: [] };
- }
+ this.customizePolicy("skill");
},
setPolicyDefault(kind, nextDefault) {
@@ -650,11 +721,17 @@ const model = {
},
isToolAllowed(item) {
- return policyAllows(this.draft.toolPolicy, item.id);
+ const policy = this.draft.toolPolicy.mode === "custom"
+ ? this.draft.toolPolicy
+ : this.state?.tools?.effective_policy;
+ return policyAllows(policy, item.id);
},
isSkillAllowed(item) {
- return policyAllows(this.draft.skillPolicy, item.name);
+ const policy = this.draft.skillPolicy.mode === "custom"
+ ? this.draft.skillPolicy
+ : this.state?.skills?.effective_policy;
+ return policyAllows(policy, item.name);
},
filteredTools(allowed) {
@@ -739,7 +816,7 @@ const model = {
const data = await callJsonApi(API, {
action: "load",
profile_id: this.draft.profileId || "new-agent",
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.state.model_presets = data.state.model_presets;
} catch (error) {
@@ -854,7 +931,7 @@ const model = {
const data = await callJsonApi(API, {
action: "plan",
patch: this.buildPatch(),
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.plan = data;
this.planStatus = "ready";
@@ -883,7 +960,7 @@ const model = {
const data = await callJsonApi(API, {
action: "save",
patch: this.buildPatch(),
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.plan = data;
this.initialDraft = clone(this.draft);
@@ -913,6 +990,11 @@ const model = {
const created = await callJsonApi("/chat_create", {
current_context: this.intent.contextId || chatsStore.selected || "",
});
+ await callJsonApi("/projects", {
+ action: this.projectName ? "activate" : "deactivate",
+ context_id: created.ctxid,
+ ...(this.projectName ? { name: this.projectName } : {}),
+ });
await callJsonApi("/agent_profile_set", {
context_id: created.ctxid,
agent_profile: profileId,
@@ -951,7 +1033,7 @@ const model = {
action: "plan_remove_changes",
profile_id: this.draft.profileId,
destructive,
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.plan = data;
this.planStatus = "ready";
@@ -985,7 +1067,7 @@ const model = {
action: "remove_changes",
profile_id: this.draft.profileId,
destructive: this.pendingMutation.destructive,
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
this.pendingMutation = null;
await this.loadEditor(this.draft.profileId);
@@ -1000,11 +1082,11 @@ const model = {
const data = await callJsonApi(API, {
action: "plan_delete",
profile_id: profileId,
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
const confirmed = await showConfirmDialog({
title: `Delete ${escapeHtml(profileId)}?`,
- message: `${this.deletionImpactHtml(data)}<p>This permanently removes this custom agent.</p>`,
+ message: `${this.deletionImpactHtml(data)}<p>This permanently removes this custom agent from ${escapeHtml(this.scopeLabel)}.</p>`,
confirmText: "Delete agent",
type: "danger",
});
@@ -1013,13 +1095,13 @@ const model = {
action: "delete",
profile_id: profileId,
confirm: true,
- context_id: this.intent.contextId,
+ ...this.scopeInput(),
});
await this.loadProfiles();
await modelConfigStore.loadAgentProfiles(true);
this.view = "manage";
this.setModalTitle("Manage agents");
- globalThis.justToast?.("Agent deleted.", "success", 1800);
+ globalThis.justToast?.(`Agent deleted from ${this.scopeLabel}.`, "success", 1800);
} catch (error) {
this.error = error.message || String(error);
}
diff --git a/plugins/_agent_editor/webui/main.html b/plugins/_agent_editor/webui/main.html
index 062bf1694..fc547c516 100644
--- a/plugins/_agent_editor/webui/main.html
+++ b/plugins/_agent_editor/webui/main.html
@@ -26,7 +26,28 @@
<template x-if="!$store.agentEditor.loading && $store.agentEditor.view === 'manage'">
<section class="agent-manager" aria-label="Manage agents">
- <p class="agent-manager-intro">Edits to built-in agents are saved as your own changes — originals are never modified.</p>
+ <div class="agent-scope-selector">
+ <div class="agent-scope-header">
+ <div class="agent-scope-copy">
+ <strong>Agent scope</strong>
+ <p>Choose whether agents and customizations apply globally or only to one project.</p>
+ </div>
+ </div>
+ <div class="agent-scope-toolbar">
+ <label class="agent-scope-field">
+ <span>Project</span>
+ <select x-model="$store.agentEditor.projectName"
+ x-init="$nextTick(() => $el.value = $store.agentEditor.projectName)"
+ @change="$store.agentEditor.onScopeChanged()">
+ <option value="">Global</option>
+ <template x-for="project in $store.agentEditor.projects" :key="project.key">
+ <option :value="project.key" x-text="project.label"></option>
+ </template>
+ </select>
+ </label>
+ </div>
+ </div>
+ <p class="agent-manager-intro" x-text="$store.agentEditor.projectName ? `Create agents and customize inherited profiles only for ${$store.agentEditor.scopeLabel}. Global and original files are never modified.` : 'Create agents and customize inherited profiles for every project. Originals are never modified.'"></p>
<div class="agent-manager-list">
<template x-for="profile in $store.agentEditor.profiles" :key="profile.id">
<article class="agent-manager-card">
@@ -38,17 +59,16 @@
<div class="agent-manager-name">
<strong x-text="profile.title || profile.id"></strong>
<span class="agent-origin" x-text="profile.origin"></span>
- <span class="agent-status-badge is-customized" x-show="profile.has_user_overrides">
+ <span class="agent-status-badge is-customized" x-show="profile.scope_has_overrides">
<x-icon name="edit_note"></x-icon><span>Customized by you</span>
</span>
</div>
<p x-text="profile.description || 'No description'"></p>
<code x-text="profile.id"></code>
- <div class="agent-project-notice" x-show="profile.project_override_active">This project’s customization takes priority here.</div>
</div>
<div class="agent-manager-actions">
<button type="button" class="button" @click="$store.agentEditor.loadEditor(profile.id, false)"><x-icon name="edit"></x-icon>Edit</button>
- <button type="button" class="button danger" x-show="profile.origin === 'Custom'" @click="$store.agentEditor.deleteProfile(profile.id)"><x-icon name="delete"></x-icon>Delete</button>
+ <button type="button" class="button danger" x-show="profile.deletable" @click="$store.agentEditor.deleteProfile(profile.id)"><x-icon name="delete"></x-icon>Delete</button>
</div>
</article>
</template>
@@ -59,8 +79,9 @@
<template x-if="!$store.agentEditor.loading && $store.agentEditor.view === 'editor' && $store.agentEditor.draft">
<div class="agent-editor-workspace">
<header class="agent-editor-topbar">
- <div class="agent-editor-heading" x-show="$store.agentEditor.intent.view === 'manage' || (!$store.agentEditor.draft.creating && $store.agentEditor.dirty)">
+ <div class="agent-editor-heading">
<button type="button" class="button icon" x-show="$store.agentEditor.intent.view === 'manage'" aria-label="Back to agents" @click="$store.agentEditor.showManager()"><x-icon name="arrow_back"></x-icon></button>
+ <span class="agent-scope-indicator"><x-icon :name="$store.agentEditor.projectName ? 'folder' : 'public'"></x-icon><span>Scope:</span><strong x-text="$store.agentEditor.scopeLabel"></strong></span>
<div class="agent-editor-subtitle" x-show="$store.agentEditor.dirty">
<span class="agent-status-badge is-unsaved"><x-icon name="edit_note"></x-icon><span>Unsaved changes</span></span>
</div>
@@ -102,7 +123,7 @@
<div>
<textarea id="agent-editor-instructions" rows="9" x-model="$store.agentEditor.instructions.value" @input="$store.agentEditor.markPromptSet('agent.system.main.specifics.md')" placeholder="Research technical topics, verify important claims with reliable sources, and return concise reports with links." :aria-invalid="$store.agentEditor.fieldIssue('instructions') ? 'true' : null" :aria-describedby="$store.agentEditor.fieldIssue('instructions') ? 'agent-editor-instructions-error' : null"></textarea>
<span id="agent-editor-instructions-error" class="field-error" role="alert" x-show="$store.agentEditor.fieldIssue('instructions')" x-text="$store.agentEditor.fieldIssue('instructions')?.message"></span>
- <button type="button" class="text-button restore-action" x-show="$store.agentEditor.instructions.has_override && !$store.agentEditor.instructions.reset" @click="$store.agentEditor.restoreInstructions()"><x-icon name="restart_alt"></x-icon>Use default instructions</button>
+ <button type="button" class="text-button restore-action" x-show="$store.agentEditor.instructions.has_override && !$store.agentEditor.instructions.reset" @click="$store.agentEditor.restoreInstructions()"><x-icon name="restart_alt"></x-icon><span x-text="$store.agentEditor.projectName ? 'Use inherited instructions' : 'Use default instructions'"></span></button>
</div>
</section>
@@ -117,7 +138,6 @@
<p class="policy-empty" x-show="!$store.agentEditor.toolCatalog.length">No configurable tools are available.</p>
</div>
<p class="easy-skills-hint">To enable or disable skills, click Advanced.</p>
- <div class="agent-project-notice" x-show="$store.agentEditor.state.tools.project_override_active">This project has different tool settings. Your changes apply wherever a project has not chosen its own settings.</div>
</section>
</main>
@@ -136,8 +156,7 @@
<header class="advanced-section-heading"><h3 id="agent-section-1-title">Identity & models</h3><p>Set the agent’s identity, delegation guidance, and model preset.</p></header>
<div class="origin-row">
<span class="agent-origin" x-text="$store.agentEditor.state.profile.origin"></span>
- <span class="agent-status-badge is-customized" x-show="$store.agentEditor.state.profile.has_user_overrides"><x-icon name="edit_note"></x-icon><span>Customized by you</span></span>
- <span class="agent-project-notice" x-show="$store.agentEditor.state.profile.project_override_active">This project’s customization takes priority here.</span>
+ <span class="agent-status-badge is-customized" x-show="$store.agentEditor.state.profile.scope_has_overrides"><x-icon name="edit_note"></x-icon><span>Customized by you</span></span>
</div>
<p class="built-in-note" x-show="$store.agentEditor.state.profile.built_in">Your changes override the built-in profile. The original files stay unchanged.</p>
<div class="advanced-identity-grid">
@@ -174,7 +193,7 @@
</section>
<section x-show="$store.agentEditor.section === '2'" data-agent-editor-section="2" tabindex="-1" aria-labelledby="agent-section-2-title">
- <header class="advanced-section-heading"><h3 id="agent-section-2-title">Prompt files</h3><p>Customize this agent’s prompt files. You always see the default next to your version.</p></header>
+ <header class="advanced-section-heading"><h3 id="agent-section-2-title">Prompt files</h3><p>Customize this agent’s prompt files. You always see the inherited version next to your version.</p></header>
<div class="prompt-workspace">
<aside class="prompt-browser">
<label class="compact-search"><span class="sr-only">Search prompt files</span><x-icon name="search"></x-icon><input type="search" x-model="$store.agentEditor.promptFileSearch" placeholder="Search files"></label>
@@ -198,21 +217,20 @@
<div class="prompt-actions">
<button type="button" class="btn btn-action-header cancel" x-show="$store.agentEditor.promptEditPending($store.agentEditor.selectedPromptDraft)" title="Discard current edit" aria-label="Discard current edit" @click="$store.agentEditor.discardPromptEdit($store.agentEditor.selectedPrompt)"><x-icon name="close"></x-icon></button>
<button type="button" class="btn btn-action-header confirm" x-show="$store.agentEditor.promptEditPending($store.agentEditor.selectedPromptDraft)" title="Accept current edit" aria-label="Accept current edit" @click="$store.agentEditor.acceptPromptEdit($store.agentEditor.selectedPrompt)"><x-icon name="check"></x-icon></button>
- <button type="button" class="button" x-show="$store.agentEditor.selectedPromptDraft.has_override || $store.agentEditor.promptDirty($store.agentEditor.selectedPromptDraft)" @click="$store.agentEditor.resetPrompt($store.agentEditor.selectedPrompt)">Use default</button>
+ <button type="button" class="button" x-show="$store.agentEditor.selectedPromptDraft.has_override || $store.agentEditor.promptDirty($store.agentEditor.selectedPromptDraft)" @click="$store.agentEditor.resetPrompt($store.agentEditor.selectedPrompt)" x-text="`Use ${$store.agentEditor.inheritedLabel.toLowerCase()}`"></button>
<button type="button" class="button icon" title="Copy customization path" aria-label="Copy customization path" @click="$store.agentEditor.copyPromptPath()"><x-icon name="content_copy"></x-icon></button>
</div>
</div>
- <div class="agent-project-notice" x-show="$store.agentEditor.selectedPromptDraft.project_override_active">This project has its own version of this file. Your customization applies wherever a project has not supplied one.</div>
- <div class="agent-project-notice" x-show="$store.agentEditor.selectedPromptDraft.dynamic_processor">This file is generated dynamically at runtime. Python processors are read-only and are not executed by the editor.</div>
+ <div class="agent-editor-note" x-show="$store.agentEditor.selectedPromptDraft.dynamic_processor">This file is generated dynamically at runtime. Python processors are read-only and are not executed by the editor.</div>
<div class="prompt-view-tabs" role="tablist" aria-label="Prompt view">
<button type="button" role="tab" :aria-selected="$store.agentEditor.comparePrompt === ''" :class="{ active: $store.agentEditor.comparePrompt === '' }" @click="$store.agentEditor.comparePrompt = ''">Your version</button>
- <button type="button" role="tab" :aria-selected="$store.agentEditor.comparePrompt === 'inherited'" :class="{ active: $store.agentEditor.comparePrompt === 'inherited' }" @click="$store.agentEditor.comparePrompt = 'inherited'">Default</button>
+ <button type="button" role="tab" :aria-selected="$store.agentEditor.comparePrompt === 'inherited'" :class="{ active: $store.agentEditor.comparePrompt === 'inherited' }" @click="$store.agentEditor.comparePrompt = 'inherited'" x-text="$store.agentEditor.inheritedLabel"></button>
<button type="button" role="tab" :aria-selected="$store.agentEditor.comparePrompt === 'compare'" :class="{ active: $store.agentEditor.comparePrompt === 'compare' }" @click="$store.agentEditor.comparePrompt = 'compare'">Compare</button>
</div>
<div class="prompt-find"><label><span class="sr-only">Search within prompt</span><input type="search" x-model="$store.agentEditor.promptTextSearch" placeholder="Find in file" @keydown.enter.prevent="$store.agentEditor.findInPrompt($event.shiftKey ? -1 : 1)"></label><span x-text="`${$store.agentEditor.promptMatchCount()} matches`"></span><button type="button" class="button icon" aria-label="Previous match" @click="$store.agentEditor.findInPrompt(-1)"><x-icon name="keyboard_arrow_up"></x-icon></button><button type="button" class="button icon" aria-label="Next match" @click="$store.agentEditor.findInPrompt(1)"><x-icon name="keyboard_arrow_down"></x-icon></button></div>
<div class="prompt-panes" :class="{ compare: $store.agentEditor.comparePrompt === 'compare' }">
<div class="prompt-pane" x-show="$store.agentEditor.comparePrompt !== 'inherited'"><label for="agent-editor-prompt-text">Your version</label><textarea id="agent-editor-prompt-text" spellcheck="false" x-model="$store.agentEditor.selectedPromptDraft.value" @input="$store.agentEditor.onPromptInput($store.agentEditor.selectedPrompt)" aria-label="Prompt Markdown" :aria-invalid="$store.agentEditor.selectedPrompt === 'agent.system.main.specifics.md' && $store.agentEditor.fieldIssue('instructions') ? 'true' : null" :aria-describedby="$store.agentEditor.selectedPrompt === 'agent.system.main.specifics.md' && $store.agentEditor.fieldIssue('instructions') ? 'agent-editor-prompt-error' : null"></textarea><span id="agent-editor-prompt-error" class="field-error" role="alert" x-show="$store.agentEditor.selectedPrompt === 'agent.system.main.specifics.md' && $store.agentEditor.fieldIssue('instructions')" x-text="$store.agentEditor.fieldIssue('instructions')?.message"></span></div>
- <div class="prompt-pane inherited" x-show="$store.agentEditor.comparePrompt"><div class="prompt-pane-title">Default</div><pre x-text="$store.agentEditor.selectedPromptDraft.inherited || '(empty)'" tabindex="0"></pre></div>
+ <div class="prompt-pane inherited" x-show="$store.agentEditor.comparePrompt"><div class="prompt-pane-title" x-text="$store.agentEditor.inheritedLabel"></div><pre x-text="$store.agentEditor.selectedPromptDraft.inherited || '(empty)'" tabindex="0"></pre></div>
</div>
<details class="effective-preview"><summary>Preview combined prompt</summary><p>Static preview only. Runtime variables, projects, skills, tools, secrets, time, and dynamic extensions can differ.</p><pre x-text="$store.agentEditor.selectedPromptDraft.preview || '(empty)'" tabindex="0"></pre></details>
</div>
@@ -221,8 +239,7 @@
<section x-show="$store.agentEditor.section === '3'" data-agent-editor-section="3" tabindex="-1" aria-labelledby="agent-section-3-title">
<header class="advanced-section-heading"><h3 id="agent-section-3-title">Tools</h3><p>Choose which tools this agent can use.</p></header>
- <div class="agent-project-notice" x-show="$store.agentEditor.state.tools.project_override_active">This project has different tool settings. Your changes apply wherever a project has not chosen its own settings.</div>
- <div class="policy-mode-row"><label><input type="radio" name="tool-policy-mode" :checked="$store.agentEditor.draft.toolPolicy.mode === 'inherit'" @change="$store.agentEditor.useStandardTools()"><span>Use standard tool access <small x-text="`(${$store.agentEditor.toolCatalog.length} tools)`"></small></span></label><label><input type="radio" name="tool-policy-mode" :checked="$store.agentEditor.draft.toolPolicy.mode === 'custom'" @change="$store.agentEditor.chooseTools()">Choose tools</label></div>
+ <div class="policy-mode-row"><label><input type="radio" name="tool-policy-mode" :checked="$store.agentEditor.draft.toolPolicy.mode === 'inherit'" @change="$store.agentEditor.useStandardTools()"><span><span x-text="$store.agentEditor.projectName ? 'Use inherited tool access' : 'Use standard tool access'"></span> <small x-text="`(${$store.agentEditor.toolCatalog.length} tools)`"></small></span></label><label><input type="radio" name="tool-policy-mode" :checked="$store.agentEditor.draft.toolPolicy.mode === 'custom'" @change="$store.agentEditor.chooseTools()">Choose tools</label></div>
<fieldset class="policy-editor" :disabled="$store.agentEditor.draft.toolPolicy.mode !== 'custom'">
<legend class="sr-only">Tool access selection</legend>
<div class="policy-filters tools"><label class="policy-search"><x-icon name="search"></x-icon><span class="sr-only">Search tools</span><input type="search" x-model="$store.agentEditor.toolSearch" placeholder="Search tools"></label><label>Category <select x-model="$store.agentEditor.toolCategory"><option value="all">All</option><option value="local">Local</option><option value="plugin">Plugin</option><option value="mcp">MCP</option></select></label><label>Origin <select x-model="$store.agentEditor.toolOrigin"><option value="all">All</option><template x-for="origin in $store.agentEditor.toolOrigins" :key="origin"><option :value="origin" x-text="origin"></option></template></select></label></div>
@@ -237,7 +254,7 @@
<section x-show="$store.agentEditor.section === '4'" data-agent-editor-section="4" tabindex="-1" aria-labelledby="agent-section-4-title">
<header class="advanced-section-heading"><h3 id="agent-section-4-title">Skills</h3><p>Choose which skills this agent can find and use.</p></header>
- <div class="policy-mode-row"><label><input type="radio" name="skill-policy-mode" :checked="$store.agentEditor.draft.skillPolicy.mode === 'inherit'" @change="$store.agentEditor.useStandardSkills()"><span>Use standard skill access <small x-text="`(${$store.agentEditor.skillCatalog.length} skills)`"></small></span></label><label><input type="radio" name="skill-policy-mode" :checked="$store.agentEditor.draft.skillPolicy.mode === 'custom'" @change="$store.agentEditor.chooseSkills()">Choose skills</label></div>
+ <div class="policy-mode-row"><label><input type="radio" name="skill-policy-mode" :checked="$store.agentEditor.draft.skillPolicy.mode === 'inherit'" @change="$store.agentEditor.useStandardSkills()"><span><span x-text="$store.agentEditor.projectName ? 'Use inherited skill access' : 'Use standard skill access'"></span> <small x-text="`(${$store.agentEditor.skillCatalog.length} skills)`"></small></span></label><label><input type="radio" name="skill-policy-mode" :checked="$store.agentEditor.draft.skillPolicy.mode === 'custom'" @change="$store.agentEditor.chooseSkills()">Choose skills</label></div>
<fieldset class="policy-editor" :disabled="$store.agentEditor.draft.skillPolicy.mode !== 'custom'">
<legend class="sr-only">Skill access selection</legend>
<div class="policy-filters skills"><label class="policy-search"><x-icon name="search"></x-icon><span class="sr-only">Search skills</span><input type="search" x-model="$store.agentEditor.skillSearch" placeholder="Search skills"></label><label>Origin <select x-model="$store.agentEditor.skillOrigin"><option value="all">All</option><template x-for="origin in $store.agentEditor.skillOrigins" :key="origin"><option :value="origin" x-text="origin"></option></template></select></label></div>
@@ -266,11 +283,11 @@
<template x-if="$store.agentEditor.plan.warnings?.length"><section><h4>Notices</h4><ul><template x-for="warning in $store.agentEditor.plan.warnings" :key="warning"><li x-text="warning"></li></template></ul></section></template>
</div>
<div class="review-actions" x-show="$store.agentEditor.pendingMutation"><button type="button" class="button danger" @click="$store.agentEditor.applyPendingMutation()"><x-icon name="delete"></x-icon>Apply removal plan</button><button type="button" class="text-button" @click="$store.agentEditor.pendingMutation = null; $store.agentEditor.previewPlan()">Cancel removal</button></div>
- <div class="profile-maintenance" x-show="!$store.agentEditor.draft.creating && $store.agentEditor.state.profile.origin !== 'Custom'">
- <h4>Built-in or plugin profile</h4><p>Remove only the customizations shown in this editor. Other files stay in place.</p><button type="button" class="button danger" @click="$store.agentEditor.planRemoval(false)"><x-icon name="delete_sweep"></x-icon>Remove my changes</button>
- <details><summary>Delete all customizations for this profile</summary><p>This removes every customization saved for this profile after showing each affected file. Agent Zero’s defaults remain untouched.</p><button type="button" class="button danger" @click="$store.agentEditor.planRemoval(true)"><x-icon name="delete_forever"></x-icon>Review files to delete</button></details>
+ <div class="profile-maintenance" x-show="!$store.agentEditor.draft.creating && $store.agentEditor.state.profile.scope_has_overrides && !$store.agentEditor.state.profile.deletable">
+ <h4>Customized by you</h4><p x-text="`Remove only the customizations shown in this editor from ${$store.agentEditor.scopeLabel}. Other files stay in place.`"></p><button type="button" class="button danger" @click="$store.agentEditor.planRemoval(false)"><x-icon name="delete_sweep"></x-icon>Remove my changes</button>
+ <details><summary x-text="`Delete all customizations in ${$store.agentEditor.scopeLabel}`"></summary><p>This removes every customization saved in this scope after showing each affected file. Inherited files remain untouched.</p><button type="button" class="button danger" @click="$store.agentEditor.planRemoval(true)"><x-icon name="delete_forever"></x-icon>Review files to delete</button></details>
</div>
- <div class="profile-maintenance" x-show="!$store.agentEditor.draft.creating && $store.agentEditor.state.profile.origin === 'Custom'"><h4>Delete custom agent</h4><p>Projects and open chats that use this agent are shown before confirmation, together with its files and settings.</p><button type="button" class="button danger" @click="$store.agentEditor.deleteProfile($store.agentEditor.draft.profileId)">Delete agent</button></div>
+ <div class="profile-maintenance" x-show="!$store.agentEditor.draft.creating && $store.agentEditor.state.profile.deletable"><h4>Delete custom agent</h4><p>Projects and open chats that use this agent are shown before confirmation, together with its files and settings.</p><button type="button" class="button danger" @click="$store.agentEditor.deleteProfile($store.agentEditor.draft.profileId)">Delete agent</button></div>
</section>
</div>
</div>
@@ -285,8 +302,8 @@
</div>
<div class="footer-actions">
<button type="button" class="btn btn-ok" x-show="$store.agentEditor.view === 'manage'" @click="$store.agentEditor.loadEditor('new-agent', true)">Create agent</button>
- <button type="button" class="btn agent-editor-secondary-action" x-show="$store.agentEditor.view === 'editor' && !$store.agentEditor.draft?.creating" @click="$store.agentEditor.save(true)" :disabled="$store.agentEditor.saving || $store.agentEditor.validationIssues().length">Save & test</button>
- <button type="button" class="btn btn-ok" x-show="$store.agentEditor.view === 'editor'" @click="$store.agentEditor.save(false)" :disabled="$store.agentEditor.saving || $store.agentEditor.avatarUploading || $store.agentEditor.validationIssues().length" :title="$store.agentEditor.validationIssues().length ? 'Fix the highlighted issues before saving' : ''"><span x-text="$store.agentEditor.saving ? 'Saving…' : $store.agentEditor.draft?.creating ? 'Create agent' : 'Save changes'"></span></button>
+ <button type="button" class="btn agent-editor-secondary-action" x-show="$store.agentEditor.view === 'editor' && !$store.agentEditor.draft?.creating" @click="$store.agentEditor.save(true)" :disabled="$store.agentEditor.saving || $store.agentEditor.validationIssues().length > 0">Save & test</button>
+ <button type="button" class="btn btn-ok" x-show="$store.agentEditor.view === 'editor'" @click="$store.agentEditor.save(false)" :disabled="$store.agentEditor.saving || $store.agentEditor.avatarUploading || $store.agentEditor.validationIssues().length > 0" :title="$store.agentEditor.validationIssues().length ? 'Fix the highlighted issues before saving' : ''"><span x-text="$store.agentEditor.saving ? 'Saving…' : $store.agentEditor.draft?.creating ? 'Create agent' : 'Save changes'"></span></button>
</div>
</div>
</div>
@@ -318,6 +335,9 @@
.agent-editor-loading { min-height:20rem; display:grid; place-content:center; justify-items:center; gap:.65rem; color:var(--color-text-secondary); }
.agent-editor-topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:1rem; }
.agent-editor-heading { display:flex; align-items:center; gap:.6rem; }
+ .agent-scope-indicator { display:inline-flex; align-items:center; gap:.3rem; min-width:0; color:var(--color-text-secondary); font-size:.78rem; }
+ .agent-scope-indicator strong { max-width:18rem; overflow:hidden; color:var(--color-text); text-overflow:ellipsis; white-space:nowrap; }
+ .agent-scope-indicator x-icon { font-size:1rem; }
.agent-editor-subtitle { margin-top:.2rem; font-size:.78rem; color:var(--color-text-secondary); }
.agent-status-badge { display:inline-flex; align-items:center; gap:.25rem; max-width:100%; padding:.2rem .45rem; border:1px solid var(--color-border); border-radius:999px; font-size:.7rem; font-weight:500; line-height:1.2; white-space:normal; }
.agent-status-badge x-icon { flex:0 0 auto; font-size:.85rem; }
@@ -367,7 +387,7 @@
.origin-row { display:flex; flex-wrap:wrap; align-items:center; gap:.6rem; }
.built-in-note,.field-provenance { color:var(--color-text-secondary); font-size:.76rem; }
.agent-origin { padding:.2rem .45rem; border:1px solid var(--color-border); border-radius:999px; font-size:.72rem; color:var(--color-text-secondary); }
- .agent-project-notice { padding:.55rem .7rem; border-left:3px solid var(--color-warning); background:color-mix(in srgb,var(--color-warning) 8%,transparent); color:var(--color-text-secondary); font-size:.8rem; }
+ .agent-editor-note { padding:.55rem .7rem; border-left:3px solid var(--color-warning); background:color-mix(in srgb,var(--color-warning) 8%,transparent); color:var(--color-text-secondary); font-size:.8rem; }
.advanced-identity-grid { display:grid; grid-template-columns:9rem minmax(0,1fr); gap:1.2rem; }
.advanced-avatar { align-self:start; }
.identity-fields { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:.9rem; }
@@ -462,6 +482,15 @@
.agent-editor .button.danger { display:inline-flex; align-items:center; gap:.35rem; border-color:color-mix(in srgb,var(--agent-editor-danger) 60%,var(--color-border)); color:var(--agent-editor-danger); background:color-mix(in srgb,var(--agent-editor-danger) 7%,var(--color-panel)); }
.agent-editor .button.danger:hover { background:color-mix(in srgb,var(--agent-editor-danger) 15%,var(--color-panel)); }
.agent-manager { display:flex; flex-direction:column; gap:1rem; }
+ .agent-scope-selector { overflow:hidden; border:1px solid var(--color-border); border-radius:4px; }
+ .agent-scope-header { padding:.75rem 1rem; border-bottom:1px solid var(--color-border); background:var(--color-bg-secondary); }
+ .agent-scope-copy { min-width:0; }
+ .agent-scope-copy strong { color:var(--color-text-primary); font-size:var(--font-size-normal); font-weight:600; }
+ .agent-scope-copy p { margin-top:.25rem; color:var(--color-text-secondary); font-size:var(--font-size-small); }
+ .agent-scope-toolbar { display:flex; padding:1rem; }
+ .agent-scope-field { display:flex; flex:1 1 0; align-items:center; gap:.5rem; min-width:12rem; margin:0; }
+ .agent-scope-field span { color:var(--color-text-secondary); font-weight:600; white-space:nowrap; }
+ .agent-scope-field select { flex:1 1 auto; min-width:0; }
.agent-manager-intro,.agent-manager-copy p { color:var(--color-text-secondary); font-size:.82rem; }
.agent-manager-list { display:flex; flex-direction:column; gap:.55rem; }
.agent-manager-card { display:grid; grid-template-columns:3rem minmax(0,1fr) auto; gap:.75rem; align-items:center; padding:.75rem; border:1px solid var(--color-border); border-radius:10px; }
@@ -499,6 +528,7 @@
.policy-list { min-height:20rem; }
.agent-manager-card { grid-template-columns:3rem minmax(0,1fr); }
.agent-manager-actions { grid-column:1/-1; justify-content:flex-end; }
+ .agent-scope-field { flex-basis:100%; min-width:0; }
.agent-editor-footer { flex-wrap:wrap; }
.footer-actions { width:100%; }
.footer-actions .btn { flex:1; }
diff --git a/tests/test_agent_editor.py b/tests/test_agent_editor.py
index 56b9f5327..a764bc775 100644
--- a/tests/test_agent_editor.py
+++ b/tests/test_agent_editor.py
@@ -10,6 +10,7 @@ from werkzeug.datastructures import FileStorage
from helpers import yaml as yaml_helper
from plugins._agent_editor.api.agent_editor import AgentEditor
+from plugins._agent_editor.api.agent_editor import _context as editor_context
from plugins._agent_editor.api.agent_editor_avatar import AgentEditorAvatar
from plugins._agent_editor.helpers import editor
@@ -46,6 +47,34 @@ def user_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
return root
+def project_scope(
+ user_root: Path,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> tuple[editor._EditorContext, Path]:
+ project_folder = tmp_path / "usr" / "projects" / "demo"
+ project_meta = project_folder / ".a0proj"
+ project_meta.mkdir(parents=True)
+ real_folder = editor.projects.get_project_folder
+ real_meta = editor.projects.get_project_meta
+ monkeypatch.setattr(
+ editor.projects,
+ "get_project_folder",
+ lambda name: str(project_folder) if name == "demo" else real_folder(name),
+ )
+ monkeypatch.setattr(
+ editor.projects,
+ "get_project_meta",
+ lambda name, *parts: (
+ str(project_meta.joinpath(*parts))
+ if name == "demo"
+ else real_meta(name, *parts)
+ ),
+ )
+ return editor._EditorContext("demo"), project_meta / "agents"
+
+
def _write_manual_files(root: Path) -> dict[Path, bytes]:
manual_files = {
root / "prompts" / "manual.md": b"prompt",
@@ -339,25 +368,20 @@ def test_model_and_off_tool_choices_write_only_their_json_contracts(
}
-def test_project_tool_policy_is_visible_but_editor_plan_stays_in_user_profile(
- user_root: Path,
+def test_project_tool_policy_reads_effective_access_and_writes_project_scope(
+ project_scope: tuple[editor._EditorContext, Path],
monkeypatch: pytest.MonkeyPatch,
) -> None:
- real_find = editor.plugins.find_plugin_asset
-
- def find_plugin_asset(plugin_name, *parts, **scope):
- if plugin_name == editor.tool_policy.PLUGIN_NAME:
- return {
- "path": "/project/.a0proj/plugins/_tool_access/config.json",
- "project_name": "demo",
- "agent_profile": "",
- }
- return real_find(plugin_name, *parts, **scope)
-
- monkeypatch.setattr(editor.plugins, "find_plugin_asset", find_plugin_asset)
monkeypatch.setattr(editor.tool_policy, "get_tool_catalog", lambda _agent: [])
+ effective_policy = {
+ "mode": "custom",
+ "default": "allow",
+ "allowed": [],
+ "blocked": ["local:shell"],
+ }
+ monkeypatch.setattr(editor.tool_policy, "get_policy", lambda _agent: effective_policy)
monkeypatch.setattr(editor.skills, "list_skill_catalog", lambda agent=None: [])
- context = editor._EditorContext("demo")
+ context, project_agents = project_scope
state = editor.build_editor_state("researcher", context)
plan = editor.build_change_plan(
@@ -368,12 +392,106 @@ def test_project_tool_policy_is_visible_but_editor_plan_stays_in_user_profile(
context,
)
- assert state["tools"]["project_override_active"] is True
+ assert state["tools"]["has_override"] is False
+ assert state["tools"]["effective_policy"] == effective_policy
assert list(plan.changes) == [
- user_root / "researcher" / "plugins" / "_tool_access" / "config.json"
+ project_agents
+ / "researcher"
+ / "plugins"
+ / "_tool_access"
+ / "config.json"
]
+def test_project_agents_are_scope_owned_and_never_leak_global_writes(
+ user_root: Path,
+ project_scope: tuple[editor._EditorContext, Path],
+) -> None:
+ context, project_agents = project_scope
+ profile_id = "project-helper"
+ plan = editor.build_change_plan(
+ {
+ "profile_id": profile_id,
+ "creating": True,
+ "editor_mode": "easy",
+ "metadata": {"set": {"title": "Project Helper"}, "reset": []},
+ "prompts": {
+ "set": {editor.SPECIFICS_FILE: "Help only this project."},
+ "reset": [],
+ },
+ },
+ context,
+ )
+
+ assert plan.project_name == "demo"
+ assert all(path.is_relative_to(project_agents / profile_id) for path in plan.changes)
+ assert not (user_root / profile_id).exists()
+ editor.apply_change_plan(plan)
+
+ state = editor.build_profile_state(profile_id, context)
+ assert state["scope_has_overrides"] is True
+ assert state["deletable"] is True
+ assert any(item["id"] == profile_id for item in editor.list_profiles(context))
+ assert all(item["id"] != profile_id for item in editor.list_profiles())
+
+ delete = editor.plan_delete_custom(profile_id, context)
+ assert delete.project_name == "demo"
+ editor.apply_change_plan(delete)
+ assert not (project_agents / profile_id).exists()
+
+
+def test_project_customizations_inherit_global_agent_and_remove_only_project_files(
+ user_root: Path,
+ project_scope: tuple[editor._EditorContext, Path],
+) -> None:
+ context, project_agents = project_scope
+ global_profile = user_root / "shared-helper"
+ global_profile.mkdir(parents=True)
+ (global_profile / "agent.yaml").write_text(
+ "title: Shared Helper\ndescription: Global description\n",
+ encoding="utf-8",
+ )
+
+ inherited = editor.build_profile_state("shared-helper", context)
+ assert inherited["metadata"]["description"]["effective"] == "Global description"
+ assert inherited["scope_has_overrides"] is False
+ assert inherited["deletable"] is False
+ with pytest.raises(ValueError, match="created in this scope"):
+ editor.plan_delete_custom("shared-helper", context)
+
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "shared-helper",
+ "metadata": {"set": {"description": "Project description"}, "reset": []},
+ },
+ context,
+ )
+ project_yaml = project_agents / "shared-helper" / "agent.yaml"
+ assert list(plan.changes) == [project_yaml]
+ editor.apply_change_plan(plan)
+ assert editor.build_profile_state("shared-helper", context)["deletable"] is False
+
+ reset = editor.plan_remove_changes("shared-helper", context)
+ assert list(reset.changes) == [project_yaml]
+ editor.apply_change_plan(reset)
+ assert yaml_helper.loads((global_profile / "agent.yaml").read_text())["description"] == "Global description"
+
+
+def test_project_scope_is_validated_at_api_and_apply_boundaries(
+ user_root: Path,
+ project_scope: tuple[editor._EditorContext, Path],
+) -> None:
+ context, _project_agents = project_scope
+ assert editor.projects.get_context_project_name(editor_context({"project_name": "demo"})) == "demo"
+ with pytest.raises(ValueError, match="Project not found"):
+ editor_context({"project_name": "missing-agent-editor-project"})
+
+ forged = editor.ChangePlan(profile_id="researcher", project_name="demo")
+ forged.write(user_root / "researcher" / "agent.yaml", "title: Wrong scope\n")
+ with pytest.raises(ValueError, match="outside the selected profile directory"):
+ editor.apply_change_plan(forged)
+
+
def test_unavailable_skill_policy_ids_are_retained_in_editor_state(
user_root: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -425,7 +543,7 @@ def test_unavailable_skill_policy_ids_are_retained_in_editor_state(
def test_display_title_change_keeps_profile_id_and_builtin_delete_is_rejected(
user_root: Path,
) -> None:
- with pytest.raises(ValueError, match="cannot be deleted"):
+ with pytest.raises(ValueError, match="created in this scope"):
editor.plan_delete_custom("researcher")
plan = editor.build_change_plan(
@@ -584,7 +702,7 @@ def test_mixed_save_matches_plan_preserves_every_unrelated_family_and_refreshes_
assert all(path.read_bytes() == payload for path, payload in manual_files.items())
-def test_empty_prompt_override_and_project_precedence_are_distinct(
+def test_empty_prompt_override_and_selected_project_scope_are_distinct(
user_root: Path,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -637,10 +755,9 @@ def test_empty_prompt_override_and_project_precedence_are_distinct(
assert empty["state"] == "Overridden here (empty)"
assert empty["has_override"] is True
assert empty["effective"] == ""
- assert project["state"] == "Project override active"
- assert project["project_override_active"] is True
+ assert project["state"] == "Overridden here"
assert project["effective"] == "project"
- assert project["source_chain"][-2:] == ["Your override", "Project · project"]
+ assert project["source_chain"][-2:] == ["Global", "Your override"]
reset = editor.build_change_plan(
{
diff --git a/tests/test_agent_editor_webui.py b/tests/test_agent_editor_webui.py
index 3223dc984..86215c2ec 100644
--- a/tests/test_agent_editor_webui.py
+++ b/tests/test_agent_editor_webui.py
@@ -93,7 +93,16 @@ def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls
assert tool_section.count('class="policy-item-description"') == 2
assert skill_section.count('class="policy-item-description"') == 2
assert "Your changes override the built-in profile. The original files stay unchanged." in modal
- assert "This project has different tool settings." in modal
+ assert 'x-model="$store.agentEditor.projectName"' in modal
+ assert 'x-init="$nextTick(() => $el.value = $store.agentEditor.projectName)"' in modal
+ assert '@change="$store.agentEditor.onScopeChanged()"' in modal
+ assert '<option value="">Global</option>' in modal
+ assert 'x-for="project in $store.agentEditor.projects"' in modal
+ assert 'x-show="profile.deletable"' in modal
+ assert 'x-show="profile.scope_has_overrides"' in modal
+ assert "project_override_active" not in modal
+ assert "profile.origin === 'Custom'" not in modal
+ assert "Scope:" in modal
assert "Unavailable — kept in your settings" in modal
assert "Customize this file" not in modal
assert 'role="tablist" aria-label="Prompt view"' in modal
@@ -118,11 +127,12 @@ def test_agent_editor_surface_has_normative_entry_points_and_accessible_controls
assert 'class="prompt-editor" role="region" aria-label="Selected prompt file" tabindex="0"' in modal
assert 'width:1.5rem; height:1.5rem' in modal
assert "moveAllVisibleTools(false)" in modal and "moveAllVisibleSkills(false)" in modal
- assert "!$store.agentEditor.draft.creating && $store.agentEditor.dirty" in modal
+ assert 'class="agent-editor-heading"' in modal
assert ':aria-invalid=' in modal
assert modal.count('role="alert"') >= 4
assert "Fix ${$store.agentEditor.validationIssues().length}" in modal
- assert "Delete all customizations for this profile" in modal
+ assert modal.count("$store.agentEditor.validationIssues().length > 0") == 2
+ assert "Delete all customizations in" in modal
assert 'input[type="checkbox"]' in modal and "appearance:none" in modal
assert 'promptDisplayState(prompt)' in modal
assert 'promptSourceChain($store.agentEditor.selectedPromptDraft)' in modal
@@ -240,8 +250,8 @@ store.state = {
{ filename: "agent.system.main.communication.md", group: "2.4", group_label: "Communication", effective: "Inherited comm", inherited: "Inherited comm", source_chain: ["Framework", "Researcher"], state: "Inherited", has_override: false },
],
model_preset: { has_override: false },
- tools: { policy: { mode: "inherit" }, has_override: false, catalog: [] },
- skills: { policy: { mode: "inherit" }, has_override: false, catalog: [] },
+ tools: { policy: { mode: "inherit" }, effective_policy: { mode: "inherit", default: "allow", allowed: [], blocked: [] }, has_override: false, catalog: [] },
+ skills: { policy: { mode: "inherit" }, effective_policy: { mode: "inherit", default: "allow", allowed: [], blocked: [] }, has_override: false, catalog: [] },
};
store.makeDraft(true);
if (await store.previewPlan()) throw new Error("invalid plan unexpectedly succeeded");
@@ -283,6 +293,20 @@ if (store.isToolAllowed(store.state.tools.catalog[0]) || store.draft.toolPolicy.
store.useStandardTools();
store.chooseTools();
if (store.draft.toolPolicy.mode !== "custom" || store.draft.toolPolicy.default !== "allow" || store.section !== "3") throw new Error("custom tool editor did not open");
+store.useStandardTools();
+store.state.tools.effective_policy = { mode: "inherit", default: "block", allowed: [], blocked: ["local:shell"] };
+store.chooseTools();
+if (store.draft.toolPolicy.default !== "allow" || store.draft.toolPolicy.blocked.length) throw new Error("inactive inherited exceptions leaked into custom policy");
+store.projectName = "demo";
+store.state.tools.effective_policy = { mode: "custom", default: "allow", allowed: [], blocked: ["local:shell"] };
+store.useStandardTools();
+if (store.isToolAllowed(store.state.tools.catalog[0])) throw new Error("project scope ignored inherited tool restriction");
+store.setEasyToolAllowed("local:shell", true);
+if (store.draft.toolPolicy.mode !== "custom" || !store.isToolAllowed(store.state.tools.catalog[0])) throw new Error("project scope did not customize inherited policy");
+store.setEasyToolAllowed("local:shell", false);
+if (store.draft.toolPolicy.mode !== "inherit" || store.isToolAllowed(store.state.tools.catalog[0])) throw new Error("project scope did not restore inherited policy");
+store.projectName = "";
+store.state.tools.effective_policy = { mode: "inherit", default: "allow", allowed: [], blocked: [] };
store.state.skills.catalog = [
{ name: "Research", path: "skills/research/SKILL.md", origin: "Agent Zero", description: "Research sources", available: true, tags: [], allowed_tools: [] },
{ name: "Gone", path: "skills/gone/SKILL.md", origin: "Unavailable", description: "Missing skill", available: false, tags: [], allowed_tools: [] },
@@ -338,14 +362,20 @@ calls.length = 0;
store.intent = { contextId: "source-chat" };
await store.openFreshChat("researcher", true);
const endpoints = calls.map((item) => item.endpoint);
-const expected = ["/chat_create", "/agent_profile_set", "/plugins/_model_config/model_override", "selectChat", "event"];
+const expected = ["/chat_create", "/projects", "/agent_profile_set", "/plugins/_model_config/model_override", "selectChat", "event"];
if (JSON.stringify(endpoints) !== JSON.stringify(expected)) throw new Error(JSON.stringify(calls));
-if (calls[1].payload.agent_profile !== "researcher") throw new Error("profile not selected");
-if (calls[2].payload.action !== "clear") throw new Error("chat preset override not cleared");
+if (calls[1].payload.action !== "deactivate") throw new Error("global test chat kept a project");
+if (calls[2].payload.agent_profile !== "researcher") throw new Error("profile not selected");
+if (calls[3].payload.action !== "clear") throw new Error("chat preset override not cleared");
if (store.readyNoteContext !== "fresh-chat") throw new Error("ready note missing");
+calls.length = 0;
+store.projectName = "demo";
+await store.openFreshChat("researcher", false);
+if (calls[1].endpoint !== "/projects" || calls[1].payload.action !== "activate" || calls[1].payload.name !== "demo") throw new Error("project test chat did not activate selected scope");
await store.planRemoval(true);
if (!store.pendingMutation?.destructive || store.section !== "5" || store.planStatus !== "ready") throw new Error("removal plan was replaced");
if (calls.at(-1).payload.action !== "plan_remove_changes") throw new Error("removal plan request missing");
+if (calls.at(-1).payload.project_name !== "demo") throw new Error("removal request lost selected scope");
store.plan = { written: ["usr/agents/researcher/agent.yaml"], deleted: ["usr/agents/researcher/prompts/old.md"], warnings: [] };
await store.applyPendingMutation();
if (confirmations.length !== 1 || confirmations[0].type !== "danger") throw new Error("danger confirmation missing");