Skip to content

Agent Zero AI framework

Add deterministic sparse Agent Editor backend

Alessandro32bf5889b022
diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md
index 540b87d85..d6b95d751 100644
--- a/plugins/AGENTS.md
+++ b/plugins/AGENTS.md
@@ -69,6 +69,7 @@ Direct child DOX files:
| Child | Scope |
| --- | --- |
| [_a0_connector/AGENTS.md](_a0_connector/AGENTS.md) | HTTP and WebSocket connector integration with remote tools and runtime bridges. |
+| [_agent_editor/AGENTS.md](_agent_editor/AGENTS.md) | Deterministic sparse agent-profile editor API, helpers, and WebUI. |
| [_browser/AGENTS.md](_browser/AGENTS.md) | Playwright browser tool, helpers, viewer, and browser panel UI. |
| [_chat_branching/AGENTS.md](_chat_branching/AGENTS.md) | Chat branching from an existing message. |
| [_chat_compaction/AGENTS.md](_chat_compaction/AGENTS.md) | Full-chat compaction into a summary message. |
diff --git a/plugins/_agent_editor/AGENTS.md b/plugins/_agent_editor/AGENTS.md
new file mode 100644
index 000000000..f0aabc42b
--- /dev/null
+++ b/plugins/_agent_editor/AGENTS.md
@@ -0,0 +1,38 @@
+# Agent Editor Plugin DOX
+
+## Purpose
+
+- Own the deterministic Easy and Advanced Agent Editor API and WebUI workflow.
+
+## Ownership
+
+- `helpers/editor.py` composes existing profile, prompt, model, tool, and skill
+ owners into editor state and sparse change plans.
+- `api/` owns authenticated/CSRF-protected state, save, and avatar routes.
+- `webui/` owns the Alpine store, modal surface, styling, and client-side draft.
+- `extensions/webui/` owns lifecycle registration on the shared modal stack and
+ the global entry points used by existing WebUI surfaces.
+
+## 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.
+- 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.
+- Bundled `agents/` files are read-only.
+
+## Verification
+
+- Run Agent Editor, profile merge, tool policy, skill policy, API security, and
+ WebUI tests, then verify the explicitly named bind-mounted runtime.
+
+## Child DOX Index
+
+No child DOX files.
diff --git a/plugins/_agent_editor/README.md b/plugins/_agent_editor/README.md
new file mode 100644
index 000000000..fd9570689
--- /dev/null
+++ b/plugins/_agent_editor/README.md
@@ -0,0 +1,9 @@
+# Agent Editor
+
+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>`.
+
+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.
diff --git a/plugins/_agent_editor/api/agent_editor.py b/plugins/_agent_editor/api/agent_editor.py
new file mode 100644
index 000000000..9a2cacb6b
--- /dev/null
+++ b/plugins/_agent_editor/api/agent_editor.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+from typing import Any
+
+from agent import AgentContext
+from helpers import projects
+from helpers.api import ApiHandler, Request, Response
+from plugins._agent_editor.helpers import editor
+
+
+class AgentEditor(ApiHandler):
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ try:
+ action = str(input.get("action") or "list").strip().lower()
+ context = _context(input)
+
+ if action == "list":
+ return {"ok": True, "profiles": editor.list_profiles(context)}
+ if action == "load":
+ profile_id = editor.validate_profile_id(input.get("profile_id"))
+ return {
+ "ok": True,
+ "state": editor.build_editor_state(profile_id, context),
+ }
+ if action in {"plan", "save"}:
+ patch = input.get("patch")
+ plan = editor.build_change_plan(patch, context)
+ if action == "plan":
+ return {"ok": True, **plan.response()}
+ receipt = editor.apply_change_plan(plan)
+ profile_id = editor.validate_profile_id(patch.get("profile_id"))
+ return {
+ "ok": True,
+ **receipt,
+ "effective_profile": editor.build_profile_state(profile_id, context),
+ }
+ if action in {"plan_remove_changes", "remove_changes"}:
+ profile_id = editor.validate_profile_id(input.get("profile_id"))
+ plan = editor.plan_remove_changes(
+ profile_id,
+ context,
+ destructive=bool(input.get("destructive")),
+ )
+ if action == "plan_remove_changes":
+ return {"ok": True, **plan.response()}
+ return {"ok": True, **editor.apply_change_plan(plan)}
+ if action == "delete_impact":
+ return {
+ "ok": True,
+ "impact": editor.delete_impact(input.get("profile_id"), context),
+ }
+ if action in {"plan_delete", "delete"}:
+ profile_id = editor.validate_profile_id(input.get("profile_id"))
+ plan = editor.plan_delete_custom(profile_id, context)
+ if action == "plan_delete":
+ return {
+ "ok": True,
+ **plan.response(),
+ "impact": editor.delete_impact(profile_id, context),
+ }
+ if input.get("confirm") is not True:
+ raise ValueError("Deleting a custom agent requires confirmation.")
+ return {"ok": True, **editor.apply_change_plan(plan)}
+ raise ValueError(f"Unknown Agent Editor action: {action}")
+ except ValueError as exc:
+ return Response(status=400, response=str(exc), mimetype="text/plain")
+
+
+def _context(input: dict[str, Any]) -> Any:
+ context_id = str(input.get("context_id") or "").strip()
+ if context_id:
+ context = AgentContext.get(context_id)
+ if not context:
+ raise ValueError("Chat context not found.")
+ return context
+ project_name = str(input.get("project_name") or "").strip()
+ if project_name:
+ project_name = projects.validate_project_name(project_name)
+ return editor._EditorContext(project_name)
diff --git a/plugins/_agent_editor/api/agent_editor_avatar.py b/plugins/_agent_editor/api/agent_editor_avatar.py
new file mode 100644
index 000000000..331fbc08d
--- /dev/null
+++ b/plugins/_agent_editor/api/agent_editor_avatar.py
@@ -0,0 +1,36 @@
+from __future__ import annotations
+
+from flask import send_file
+
+from helpers.api import ApiHandler, Request, Response
+from plugins._agent_editor.helpers import editor
+
+
+class AgentEditorAvatar(ApiHandler):
+ @classmethod
+ def get_methods(cls) -> list[str]:
+ return ["GET", "POST"]
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ try:
+ if request.method == "POST":
+ return {
+ "ok": True,
+ **editor.stage_avatar(request.files.get("avatar")),
+ }
+
+ profile_id = editor.validate_profile_id(request.args.get("profile_id"))
+ project_name = str(request.args.get("project_name") or "").strip()
+ if project_name:
+ project_name = editor.projects.validate_project_name(project_name)
+ path = editor.effective_avatar_path(
+ profile_id,
+ editor._EditorContext(project_name),
+ )
+ if not path or not path.is_file():
+ return Response(status=404, response="Avatar not found.")
+ response = send_file(path, mimetype="image/webp", conditional=True)
+ response.headers["Cache-Control"] = "private, no-cache"
+ return response
+ except ValueError as exc:
+ return Response(status=400, response=str(exc), mimetype="text/plain")
diff --git a/plugins/_agent_editor/helpers/__init__.py b/plugins/_agent_editor/helpers/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/plugins/_agent_editor/helpers/editor.py b/plugins/_agent_editor/helpers/editor.py
new file mode 100644
index 000000000..a3f5a3519
--- /dev/null
+++ b/plugins/_agent_editor/helpers/editor.py
@@ -0,0 +1,1263 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from io import BytesIO
+import json
+import os
+from pathlib import Path
+import re
+import tempfile
+import threading
+import time
+from types import SimpleNamespace
+from typing import Any
+from urllib.parse import urlencode
+from uuid import uuid4
+
+from helpers import cache, files, plugins, projects, skills, subagents, tool_policy
+from helpers import yaml as yaml_helper
+
+
+PROFILE_ID_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$")
+COLOR_PATTERN = re.compile(r"^#[0-9A-Fa-f]{6}$")
+SPECIFICS_FILE = "agent.system.main.specifics.md"
+METADATA_KEYS = ("title", "description", "context", "avatar")
+MAX_PROMPT_BYTES = 512 * 1024
+MAX_PROMPTS_BYTES = 2 * 1024 * 1024
+MAX_AVATAR_BYTES = 8 * 1024 * 1024
+MAX_AVATAR_DIMENSION = 4096
+AVATAR_SIZE = 512
+RESERVED_PROFILE_IDS = {"_example"}
+NON_PROMPT_MARKDOWN = {"AGENTS.md"}
+USER_AGENTS_ROOT = Path(files.get_abs_path(subagents.USER_AGENTS_DIR))
+STAGED_AVATAR_ROOT = Path(files.get_abs_path("tmp", "agent-editor"))
+_POLICY_KEYS = ("mode", "default", "allowed", "blocked")
+_MUTATION_LOCK = threading.RLock()
+
+
+class _EditorContext:
+ def __init__(self, project_name: str = "") -> None:
+ self.project_name = project_name
+
+ def get_data(self, key: str, recursive: bool = True):
+ return self.project_name if key == projects.CONTEXT_DATA_KEY_PROJECT else None
+
+
+class EditorAgent:
+ def __init__(self, profile_id: str, context: Any | None = None) -> None:
+ self.config = SimpleNamespace(profile=profile_id)
+ self.context = context or _EditorContext()
+ self.data: dict[str, Any] = {}
+
+ def get_data(self, key: str):
+ return self.data.get(key)
+
+ def read_prompt(self, filename: str, **kwargs: Any) -> str:
+ path = files.find_file_in_dirs(filename, subagents.get_paths(self, "prompts"))
+ return Path(path).read_text(encoding="utf-8")
+
+
+@dataclass(frozen=True)
+class ProfileLayer:
+ kind: str
+ metadata_path: Path | None
+ data: dict[str, Any]
+
+
+@dataclass(frozen=True)
+class FileChange:
+ action: str
+ path: Path
+ content: bytes | None = None
+
+ @property
+ def relative_path(self) -> str:
+ return files.deabsolute_path(str(self.path)).replace(os.sep, "/")
+
+
+@dataclass
+class ChangePlan:
+ changes: dict[Path, FileChange] = field(default_factory=dict)
+ warnings: list[str] = field(default_factory=list)
+ staged_tokens: set[str] = field(default_factory=set)
+ profile_id: str = ""
+ remove_empty_root: bool = False
+
+ def write(self, path: Path, content: str | bytes) -> None:
+ payload = content.encode("utf-8") if isinstance(content, str) else content
+ if path.is_file() and path.read_bytes() == payload:
+ self.changes.pop(path, None)
+ return
+ self.changes[path] = FileChange("write", path, payload)
+
+ def delete(self, path: Path) -> None:
+ if path.exists():
+ self.changes[path] = FileChange("delete", path)
+ else:
+ self.changes.pop(path, None)
+
+ def response(self) -> dict[str, Any]:
+ ordered = sorted(self.changes.values(), key=lambda change: change.relative_path)
+ return {
+ "written": [
+ change.relative_path for change in ordered if change.action == "write"
+ ],
+ "deleted": [
+ change.relative_path for change in ordered if change.action == "delete"
+ ],
+ "warnings": list(self.warnings),
+ }
+
+
+def validate_profile_id(profile_id: Any) -> str:
+ value = str(profile_id or "").strip()
+ if value in RESERVED_PROFILE_IDS or not PROFILE_ID_PATTERN.fullmatch(value):
+ raise ValueError(
+ "Profile ID must be 1–64 lowercase letters, numbers, hyphens, or underscores."
+ )
+ return value
+
+
+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():
+ return True
+ if (USER_AGENTS_ROOT / profile_id).is_dir():
+ 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 ""
+ return bool(
+ project_name
+ and Path(projects.get_project_meta(project_name, "agents", profile_id)).is_dir()
+ )
+
+
+def list_profiles(context: Any | None = None) -> list[dict[str, Any]]:
+ project_name = projects.get_context_project_name(context) if context else None
+ resolved = subagents.get_agents_dict(project_name)
+ names = set(resolved)
+ for root in (Path(files.get_abs_path("agents")), USER_AGENTS_ROOT):
+ if root.is_dir():
+ names.update(path.name for path in root.iterdir() if path.is_dir())
+
+ result: list[dict[str, Any]] = []
+ for profile_id in sorted(names):
+ if profile_id in RESERVED_PROFILE_IDS:
+ continue
+ state = metadata_state(profile_id, context)
+ result.append(
+ {
+ "id": profile_id,
+ "title": state["title"]["effective"] or profile_id,
+ "description": state["description"]["effective"] or "",
+ "origin": state["origin"],
+ "origin_chain": state["origin_chain"],
+ "built_in": state["built_in"],
+ "has_user_overrides": state["has_user_overrides"],
+ "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),
+ }
+ )
+ return result
+
+
+def build_editor_state(
+ profile_id: str,
+ context: Any | None = None,
+) -> dict[str, Any]:
+ profile_id = validate_profile_id(profile_id)
+ agent = EditorAgent(profile_id, context)
+ prompt_files = prompt_catalog(agent)
+ tool_catalog = tool_policy.get_tool_catalog(agent)
+ from plugins._model_config.helpers import model_config
+
+ presets: list[dict[str, Any]] = []
+ for preset in model_config.get_presets():
+ name = str(preset.get("name") or "").strip()
+ if not name:
+ continue
+ resolved = model_config.resolve_config_settings(
+ {model_config.MODEL_PRESET_CONFIG_KEY: name}
+ )
+ presets.append(
+ {
+ "name": name,
+ "main": _model_identity(resolved.get("chat_model")),
+ "utility": _model_identity(resolved.get("utility_model")),
+ "embedding": _model_identity(resolved.get("embedding_model")),
+ }
+ )
+ model_path = _profile_config_path(profile_id, "_model_config")
+ model_user = _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
+ )
+ skill_user = _read_mapping(skill_path)
+ skill_policy = skills.normalize_visibility_policy(
+ skill_user.get("visibility_policy")
+ )
+ effective_skill_policy = skills.get_visibility_policy(agent)
+ skill_catalog = [
+ {**item, "available": True}
+ for item in skills.list_skill_catalog(agent=agent)
+ ]
+ known_skill_ids = {
+ value.casefold()
+ for item in skill_catalog
+ for value in (
+ str(item.get("name") or ""),
+ str(item.get("path") or ""),
+ Path(str(item.get("path") or "")).name,
+ )
+ if value
+ }
+ for skill_id in [*skill_policy["allowed"], *skill_policy["blocked"]]:
+ if skill_id.casefold() in known_skill_ids:
+ continue
+ known_skill_ids.add(skill_id.casefold())
+ allowed = skills.is_skill_allowed(effective_skill_policy, skill_id)
+ skill_catalog.append(
+ {
+ "name": skill_id,
+ "description": "",
+ "path": skill_id,
+ "origin": "Unavailable",
+ "hidden": not allowed,
+ "tags": [],
+ "allowed_tools": [],
+ "available": False,
+ }
+ )
+ skill_catalog.sort(
+ key=lambda item: (
+ str(item.get("name") or "").casefold(),
+ str(item.get("path") or ""),
+ )
+ )
+ return {
+ "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")
+ ),
+ "catalog": tool_catalog,
+ },
+ "skills": {
+ "policy": skill_policy,
+ "has_override": "visibility_policy" in skill_user,
+ "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,
+ },
+ }
+
+
+def build_profile_state(
+ profile_id: str,
+ context: Any | None = None,
+) -> dict[str, Any]:
+ profile_id = validate_profile_id(profile_id)
+ metadata = metadata_state(profile_id, context)
+ return {
+ "id": profile_id,
+ "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"),
+ "metadata": metadata,
+ "avatar_url": effective_avatar_url(profile_id, context),
+ }
+
+
+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"}
+ ]
+ state: dict[str, Any] = {}
+ for key in METADATA_KEYS:
+ effective, source, source_kind = _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
+ else None
+ ),
+ "has_override": bool(user_layer and key in user_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
+ built_in = (Path(files.get_abs_path("agents")) / profile_id).is_dir()
+ plugin_origin = any(layer.kind == "plugin" for layer in layers)
+ state.update(
+ {
+ "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
+ ),
+ }
+ )
+ return state
+
+
+def prompt_catalog(agent: EditorAgent) -> list[dict[str, Any]]:
+ roots = [Path(path) for path in subagents.get_paths(agent, "prompts")]
+ names = {
+ path.name
+ for root in roots
+ if root.is_dir()
+ for path in root.glob("*.md")
+ 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_root = (
+ Path(projects.get_project_meta(project_name)) if project_name else None
+ )
+ result: list[dict[str, Any]] = []
+ for name in sorted(names, key=lambda value: (_prompt_group(value)[0], value)):
+ occurrences: list[tuple[Path, str, str]] = []
+ for root in roots:
+ path = root / name
+ if path.is_file():
+ kind, label = _prompt_source(root, user_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)
+ inherited = next(
+ (
+ item
+ for item in occurrences
+ if item[1] not in {"user", "project"}
+ ),
+ 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)
+ 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:
+ state = "Conflict"
+ elif source_kind == "project":
+ state = "Project override active"
+ elif user:
+ state = (
+ "Overridden here (empty)"
+ if user_text == ""
+ else "Overridden here"
+ )
+ elif source_kind == "plugin":
+ state = "Plugin-provided"
+ elif effective:
+ state = "Inherited"
+ else:
+ state = "Unavailable"
+
+ preview = _expand_static_prompt(name, roots, 0, set())
+
+ result.append(
+ {
+ "filename": name,
+ "group": group_number,
+ "group_label": group_label,
+ "state": state,
+ "effective": effective_text,
+ "override": user_text if user else None,
+ "has_override": bool(user),
+ "inherited": inherited_text,
+ "source": _relative_source(effective[0] if effective else None),
+ "inherited_source": _relative_source(
+ inherited[0] if inherited else None
+ ),
+ "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,
+ "dynamic_processor": any(
+ (root / f"{Path(name).stem}.py").is_file() for root in roots
+ ),
+ }
+ )
+ return result
+
+
+def effective_avatar_path(profile_id: str, context: Any | None = None) -> Path | None:
+ layers = _metadata_layers(profile_id, context)
+ value, source, _ = _layer_value(layers, "avatar")
+ if not isinstance(value, dict) or value.get("kind") != "image" or not source:
+ return None
+ relative = str(value.get("value") or "")
+ candidate = (source.parent / relative).resolve()
+ if not files.is_in_dir(str(candidate), str(source.parent)) or not candidate.is_file():
+ return None
+ return candidate
+
+
+def effective_avatar_url(profile_id: str, context: Any | None = None) -> str:
+ path = effective_avatar_path(profile_id, context)
+ if not path:
+ return ""
+ query = {
+ "profile_id": profile_id,
+ "v": str(path.stat().st_mtime_ns),
+ }
+ project_name = projects.get_context_project_name(context) if context else ""
+ if project_name:
+ query["project_name"] = project_name
+ return "/api/plugins/_agent_editor/agent_editor_avatar?" + urlencode(query)
+
+
+def _metadata_layers(profile_id: str, context: Any | None) -> list[ProfileLayer]:
+ agent = EditorAgent(profile_id, context)
+ directories: list[tuple[str, Path]] = [
+ (
+ "profile",
+ Path(files.get_abs_path("agents", profile_id)),
+ )
+ ]
+ for directory in plugins.get_enabled_plugin_paths(agent, "agents", profile_id):
+ directories.append(("plugin", Path(directory)))
+ directories.append(("user", USER_AGENTS_ROOT / profile_id))
+
+ project_name = projects.get_context_project_name(agent.context) or ""
+ if project_name:
+ directories.append(
+ (
+ "project",
+ Path(projects.get_project_meta(project_name, "agents", profile_id)),
+ )
+ )
+
+ return [
+ layer
+ for kind, directory in directories
+ if (layer := _load_profile_layer(kind, directory)) is not None
+ ]
+
+
+def _load_profile_layer(kind: str, directory: Path) -> ProfileLayer | None:
+ if not directory.is_dir():
+ return None
+ yaml_path = directory / "agent.yaml"
+ json_path = directory / "agent.json"
+ path = yaml_path if yaml_path.is_file() else json_path if json_path.is_file() else None
+ data = _read_mapping(path) if path else {}
+ return ProfileLayer(kind, path, data)
+
+
+def _read_mapping(path: Path | None) -> dict[str, Any]:
+ if not path or not path.is_file():
+ return {}
+ try:
+ value = (
+ json.loads(path.read_text(encoding="utf-8"))
+ if path.suffix.lower() == ".json"
+ else yaml_helper.loads(path.read_text(encoding="utf-8"))
+ )
+ except Exception:
+ return {}
+ return dict(value) if isinstance(value, dict) else {}
+
+
+def _layer_value(
+ layers: list[ProfileLayer], key: str
+) -> tuple[Any, Path | None, str]:
+ for layer in reversed(layers):
+ if key in layer.data:
+ return layer.data[key], layer.metadata_path, layer.kind
+ return None, None, ""
+
+
+def _prompt_source(
+ root: Path, user_prompt_dir: Path, project_root: Path | None
+) -> tuple[str, str]:
+ if root.resolve() == user_prompt_dir.resolve():
+ return "user", "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)
+ if plugin:
+ return "plugin", f"Plugin · {plugin}"
+ bundled_agents = Path(files.get_abs_path("agents"))
+ if files.is_in_dir(str(root), str(bundled_agents)):
+ return "profile", root.parent.name.replace("-", " ").title()
+ if root.resolve() == Path(files.get_abs_path("prompts")).resolve():
+ return "framework", "Framework"
+ return "global", "Global"
+
+
+def _prompt_group(filename: str) -> tuple[str, str]:
+ if filename == SPECIFICS_FILE:
+ return "2.1", "Agent instructions"
+ if filename == "agent.system.main.role.md":
+ return "2.2", "Role"
+ if filename == "agent.system.main.environment.md":
+ return "2.3", "Environment"
+ if filename.startswith("agent.system.main.communication"):
+ return "2.4", "Communication"
+ if filename == "agent.system.main.solving.md":
+ return "2.5", "Problem solving"
+ if filename == "agent.system.main.tips.md":
+ return "2.6", "Tips"
+ if filename.startswith("fw."):
+ return "2.7", "Framework messages"
+ if filename.startswith("agent.system.tool.") or "tool" in filename:
+ return "2.8", "Tool instructions"
+ if filename.startswith(("agent.context.", "agent.system.projects.", "agent.system.skills")):
+ return "2.9", "Context, projects & skills"
+ return "2.10", "Other"
+
+
+def _model_identity(value: Any) -> dict[str, str]:
+ item = value if isinstance(value, dict) else {}
+ return {
+ "provider": str(item.get("provider") or ""),
+ "name": str(item.get("name") or ""),
+ }
+
+
+def _profile_config_path(profile_id: str, plugin_name: str) -> Path:
+ return Path(
+ plugins.determine_plugin_asset_path(
+ plugin_name,
+ "",
+ profile_id,
+ plugins.CONFIG_FILE_NAME,
+ )
+ )
+
+
+def _relative_source(path: Path | None) -> str:
+ return files.deabsolute_path(str(path)).replace(os.sep, "/") if path else ""
+
+
+def _prompt_text(path: Path | None) -> tuple[str, str]:
+ if not path:
+ return "", ""
+ try:
+ return path.read_text(encoding="utf-8"), ""
+ except (OSError, UnicodeError) as exc:
+ return "", f"Prompt is not readable UTF-8: {exc}"
+
+
+_NAMED_INCLUDE = re.compile(r"{{\s*include\s*['\"](.*?)['\"]\s*}}")
+_ORIGINAL_INCLUDE = re.compile(r"{{\s*include\s+original\s*}}")
+
+
+def _expand_static_prompt(
+ filename: str,
+ roots: list[Path],
+ start_index: int,
+ seen: set[Path],
+) -> str:
+ relative = Path(filename)
+ if relative.is_absolute() or ".." in relative.parts:
+ return ""
+ match = next(
+ (
+ (index, root / relative)
+ for index, root in enumerate(roots[start_index:], start=start_index)
+ if (root / relative).is_file()
+ ),
+ None,
+ )
+ if not match:
+ return ""
+ index, path = match
+ resolved = path.resolve()
+ if resolved in seen:
+ return "{{ include cycle }}"
+ text, error = _prompt_text(path)
+ if error:
+ return ""
+ branch_seen = {*seen, resolved}
+ text = _ORIGINAL_INCLUDE.sub(
+ lambda _match: _expand_static_prompt(
+ filename,
+ roots,
+ index + 1,
+ branch_seen,
+ ),
+ text,
+ )
+ return _NAMED_INCLUDE.sub(
+ lambda include: _expand_static_prompt(
+ include.group(1),
+ roots,
+ 0,
+ branch_seen,
+ ) or include.group(0),
+ text,
+ )
+def build_change_plan(
+ patch: dict[str, Any],
+ context: Any | None = None,
+) -> ChangePlan:
+ if not isinstance(patch, dict):
+ raise ValueError("The save patch must be an object.")
+
+ profile_id = validate_profile_id(patch.get("profile_id"))
+ creating = bool(patch.get("creating"))
+ easy = str(patch.get("editor_mode") or "advanced").lower() == "easy"
+ exists = profile_exists(profile_id, context)
+ if creating and exists:
+ raise ValueError(
+ f"An agent with the profile ID `{profile_id}` already exists. "
+ "Open it to edit its user overrides or choose another name."
+ )
+ if not creating and not exists:
+ raise ValueError(f'Agent profile "{profile_id}" does not exist.')
+
+ plan = ChangePlan(profile_id=profile_id)
+ if "metadata" in patch:
+ _plan_metadata(plan, patch["metadata"], context, creating=creating)
+ if "prompts" in patch:
+ _plan_prompts(
+ plan,
+ patch["prompts"],
+ context,
+ creating=creating,
+ easy=easy,
+ )
+ if "model_preset" in patch:
+ _plan_model_preset(plan, patch["model_preset"])
+ if "tool_policy" in patch:
+ _plan_tool_policy(plan, patch["tool_policy"])
+ if "skill_policy" in patch:
+ _plan_skill_policy(plan, patch["skill_policy"])
+
+ if creating:
+ metadata = _planned_mapping(plan, USER_AGENTS_ROOT / profile_id / "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
+ 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.")
+
+ return plan
+
+
+def _plan_metadata(
+ plan: ChangePlan,
+ value: Any,
+ context: Any | None,
+ *,
+ creating: bool,
+) -> None:
+ section = _mapping(value, "metadata")
+ set_values = _mapping(section.get("set", {}), "metadata.set")
+ reset_values = _string_list(section.get("reset", []), "metadata.reset")
+ unknown = (set(set_values) | set(reset_values)) - set(METADATA_KEYS)
+ if unknown:
+ raise ValueError(f"Unknown metadata field: {sorted(unknown)[0]}")
+ if set(set_values).intersection(reset_values):
+ 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"
+ data = _read_mapping_strict(
+ yaml_path if yaml_path.is_file() else legacy_path,
+ "profile metadata",
+ )
+ state = metadata_state(profile_id, context)
+ current_user_avatar = data.get("avatar")
+
+ 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")
+
+ for key, raw in set_values.items():
+ if key in {"title", "description", "context"}:
+ if not isinstance(raw, str):
+ raise ValueError(f"Metadata field {key} must be text.")
+ normalized: Any = raw
+ if key == "title" and not raw.strip():
+ raise ValueError("Agent name is required.")
+ else:
+ normalized = _normalize_avatar(plan, raw)
+ if normalized.get("kind") == "color" and _editor_image_avatar(
+ current_user_avatar
+ ):
+ plan.delete(USER_AGENTS_ROOT / profile_id / "assets" / "avatar.webp")
+
+ inherited = state[key]["inherited"]
+ if not creating and normalized == inherited:
+ data.pop(key, None)
+ else:
+ data[key] = normalized
+
+ if data:
+ plan.write(yaml_path, yaml_helper.dumps(data))
+ else:
+ plan.delete(yaml_path)
+
+
+def _plan_prompts(
+ plan: ChangePlan,
+ value: Any,
+ context: Any | None,
+ *,
+ creating: bool,
+ easy: bool,
+) -> None:
+ section = _mapping(value, "prompts")
+ set_values = _mapping(section.get("set", {}), "prompts.set")
+ reset_values = _string_list(section.get("reset", []), "prompts.reset")
+ if set(set_values).intersection(reset_values):
+ raise ValueError("A prompt cannot be set and reset in one save.")
+
+ agent = EditorAgent(plan.profile_id, context)
+ catalog = {item["filename"]: item for item in prompt_catalog(agent)}
+ for filename in [*set_values, *reset_values]:
+ if filename not in catalog:
+ raise ValueError(f'Prompt file "{filename}" is not in the editor catalog.')
+
+ total = 0
+ for filename, content in set_values.items():
+ if not isinstance(content, str):
+ raise ValueError(f'Prompt file "{filename}" must contain UTF-8 text.')
+ if "\x00" in content:
+ raise ValueError(f'Prompt file "{filename}" contains a NUL character.')
+ payload_size = len(content.encode("utf-8"))
+ if payload_size > MAX_PROMPT_BYTES:
+ raise ValueError(f'Prompt file "{filename}" is too large.')
+ total += payload_size
+ if easy and filename == SPECIFICS_FILE and not content.strip():
+ raise ValueError(
+ "Instructions can’t be empty. To remove your changes, use "
+ "Restore original instructions."
+ )
+ item = catalog[filename]
+ path = USER_AGENTS_ROOT / plan.profile_id / "prompts" / filename
+ if (
+ not creating
+ and item.get("inherited_source")
+ and content == item.get("inherited", "")
+ ):
+ plan.delete(path)
+ else:
+ plan.write(path, content)
+
+ 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)
+
+
+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")
+ data = _read_mapping_strict(path, "model preset configuration")
+
+ from plugins._model_config.helpers import model_config
+
+ if mode == "inherit":
+ data.pop(model_config.MODEL_PRESET_CONFIG_KEY, None)
+ elif mode == "preset":
+ requested = str(section.get("name") or "").strip()
+ preset = model_config.resolve_preset(requested)
+ if not preset:
+ raise ValueError(f'Model preset "{requested}" does not exist.')
+ data[model_config.MODEL_PRESET_CONFIG_KEY] = str(preset.get("name") or requested)
+ else:
+ raise ValueError("Model preset mode must be inherit or preset.")
+ _plan_json_mapping(plan, path, data)
+
+
+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)
+ data = _read_mapping_strict(path, "tool policy configuration")
+
+ if mode == "inherit":
+ for key in _POLICY_KEYS:
+ data.pop(key, None)
+ else:
+ if mode == "off":
+ policy = {"mode": "custom", "default": "block", "allowed": [], "blocked": []}
+ elif mode == "custom":
+ policy = tool_policy.normalize_policy(section)
+ allowed = set(policy["allowed"])
+ blocked = set(policy["blocked"])
+ if allowed.intersection(blocked):
+ raise ValueError("A tool cannot be both allowed and blocked.")
+ for tool_id in [*policy["allowed"], *policy["blocked"]]:
+ if not _valid_tool_id(tool_id):
+ raise ValueError(f'Invalid canonical tool ID "{tool_id}".')
+ else:
+ raise ValueError("Tool policy mode must be inherit, off, or custom.")
+ data.update({key: policy[key] for key in _POLICY_KEYS})
+ _plan_json_mapping(plan, path, data)
+
+
+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)
+ data = _read_mapping_strict(path, "skill policy configuration")
+
+ if mode == "inherit":
+ data.pop("visibility_policy", None)
+ else:
+ raw = (
+ {"mode": "custom", "default": "block", "allowed": [], "blocked": []}
+ if mode == "off"
+ else section
+ )
+ if mode not in {"off", "custom"}:
+ raise ValueError("Skill policy mode must be inherit, off, or custom.")
+ policy = skills.normalize_visibility_policy(raw)
+ if set(policy["allowed"]).intersection(policy["blocked"]):
+ raise ValueError("A skill cannot be both allowed and blocked.")
+ for skill_id in [*policy["allowed"], *policy["blocked"]]:
+ if not skill_id or len(skill_id) > 512 or "\x00" in skill_id:
+ raise ValueError("Invalid skill ID.")
+ data["visibility_policy"] = policy
+ _plan_json_mapping(plan, path, data)
+
+
+def _normalize_avatar(plan: ChangePlan, value: Any) -> dict[str, str]:
+ avatar = _mapping(value, "metadata.set.avatar")
+ kind = str(avatar.get("kind") or "").strip().lower()
+ if kind == "color":
+ color = str(avatar.get("value") or "").strip().upper()
+ if not COLOR_PATTERN.fullmatch(color):
+ raise ValueError("Avatar color must be a six-digit hex color.")
+ return {"kind": "color", "value": color}
+ if kind == "image":
+ token = str(avatar.get("token") or "").strip()
+ if token:
+ source = staged_avatar_path(token)
+ 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",
+ source.read_bytes(),
+ )
+ plan.staged_tokens.add(token)
+ return {"kind": "image", "value": "assets/avatar.webp"}
+ raise ValueError("Avatar must be a color or a staged image.")
+
+
+def _plan_json_mapping(plan: ChangePlan, path: Path, data: dict[str, Any]) -> None:
+ if data:
+ plan.write(path, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
+ else:
+ plan.delete(path)
+
+
+def _planned_mapping(plan: ChangePlan, path: Path) -> dict[str, Any]:
+ change = plan.changes.get(path)
+ if change and change.action == "delete":
+ return {}
+ if change and change.content is not None:
+ value = yaml_helper.loads(change.content.decode("utf-8"))
+ return dict(value) if isinstance(value, dict) else {}
+ return _read_mapping(path)
+
+
+def _read_mapping_strict(path: Path, label: str) -> dict[str, Any]:
+ if not path.is_file():
+ return {}
+ try:
+ value = (
+ json.loads(path.read_text(encoding="utf-8"))
+ if path.suffix.lower() == ".json"
+ else yaml_helper.loads(path.read_text(encoding="utf-8"))
+ )
+ except Exception as exc:
+ raise ValueError(f"Existing {label} is invalid and was not changed: {exc}") from exc
+ if not isinstance(value, dict):
+ raise ValueError(f"Existing {label} must be an object and was not changed.")
+ return dict(value)
+
+
+def _mapping(value: Any, label: str) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise ValueError(f"{label} must be an object.")
+ return dict(value)
+
+
+def _string_list(value: Any, label: str) -> list[str]:
+ if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
+ raise ValueError(f"{label} must be an array of strings.")
+ return list(dict.fromkeys(value))
+
+
+def _valid_tool_id(value: str) -> bool:
+ return bool(
+ re.fullmatch(
+ r"(?:local:[^\s/:]+|(?:mcp|plugin):[^\s/:]+:[^\s/:]+)",
+ value,
+ )
+ )
+
+
+def _editor_image_avatar(value: Any) -> bool:
+ return (
+ isinstance(value, dict)
+ and value.get("kind") == "image"
+ and value.get("value") == "assets/avatar.webp"
+ )
+
+
+def apply_change_plan(plan: ChangePlan) -> dict[str, Any]:
+ root = USER_AGENTS_ROOT / validate_profile_id(plan.profile_id)
+ changes = sorted(plan.changes.values(), key=lambda item: str(item.path))
+ _validate_plan_paths(root, changes)
+ receipt = plan.response()
+
+ with _MUTATION_LOCK:
+ snapshots = {
+ change.path: change.path.read_bytes() if change.path.is_file() else None
+ for change in changes
+ }
+ staged: dict[Path, Path] = {}
+ created_dirs: set[Path] = set()
+ try:
+ for change in changes:
+ if change.action != "write":
+ continue
+ _ensure_parent(change.path.parent, created_dirs)
+ staged[change.path] = _stage_bytes(
+ change.path.parent,
+ change.path.name,
+ change.content or b"",
+ )
+
+ for change in changes:
+ if change.action == "write":
+ os.replace(staged.pop(change.path), change.path)
+ _fsync_directory(change.path.parent)
+ elif change.path.is_file() or change.path.is_symlink():
+ change.path.unlink()
+ _fsync_directory(change.path.parent)
+
+ if plan.remove_empty_root:
+ _prune_empty_directories(root)
+ if root.is_dir() and not any(root.iterdir()):
+ root.rmdir()
+ except Exception:
+ for temporary in staged.values():
+ temporary.unlink(missing_ok=True)
+ _restore_snapshots(snapshots, root)
+ for directory in sorted(created_dirs, key=lambda path: len(path.parts), reverse=True):
+ try:
+ directory.rmdir()
+ except OSError:
+ pass
+ raise
+
+ for token in plan.staged_tokens:
+ staged_avatar_path(token).unlink(missing_ok=True)
+ _invalidate_profile_caches()
+ return receipt
+
+
+def plan_remove_changes(
+ profile_id: str,
+ context: Any | None = None,
+ *,
+ destructive: bool = False,
+) -> ChangePlan:
+ profile_id = validate_profile_id(profile_id)
+ 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)
+
+ catalog = prompt_catalog(EditorAgent(profile_id, context))
+ prompt_resets = [
+ item["filename"]
+ for item in catalog
+ if item.get("has_override") and item.get("inherited_source")
+ ]
+ plan = build_change_plan(
+ {
+ "profile_id": profile_id,
+ "metadata": {"set": {}, "reset": list(METADATA_KEYS)},
+ "prompts": {"set": {}, "reset": prompt_resets},
+ "model_preset": {"mode": "inherit"},
+ "tool_policy": {"mode": "inherit"},
+ "skill_policy": {"mode": "inherit"},
+ },
+ context,
+ )
+ return plan
+
+
+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)
+
+
+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
+ 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)
+ sessions: list[str] = []
+ try:
+ from agent import AgentContext
+
+ sessions = [
+ str(item.id)
+ for item in AgentContext.all()
+ if str(getattr(getattr(item.agent0, "config", None), "profile", ""))
+ == profile_id
+ ]
+ except Exception:
+ pass
+
+ model_config = _read_mapping(_profile_config_path(profile_id, "_model_config"))
+ return {
+ "profile_id": profile_id,
+ "deletable": state["origin"] == "Custom",
+ "origin": state["origin"],
+ "files": file_paths,
+ "project_references": references,
+ "active_sessions": sessions,
+ "model_preset": str(model_config.get("model_preset") or ""),
+ "contains": {
+ name: (root / name).is_dir()
+ for name in ("tools", "extensions", "skills", "assets", "plugins")
+ },
+ }
+
+
+def stage_avatar(upload: Any) -> dict[str, Any]:
+ if upload is None:
+ raise ValueError("Choose an image to upload.")
+ payload = upload.stream.read(MAX_AVATAR_BYTES + 1)
+ if len(payload) > MAX_AVATAR_BYTES:
+ raise ValueError("Avatar images must be 8 MB or smaller.")
+ if not payload:
+ raise ValueError("The uploaded image is empty.")
+
+ from PIL import Image, ImageOps, UnidentifiedImageError
+
+ try:
+ with Image.open(BytesIO(payload)) as source:
+ source_format = str(source.format or "").upper()
+ if source_format not in {"PNG", "JPEG", "WEBP"}:
+ raise ValueError("Avatar must be a PNG, JPEG, or WebP image.")
+ if max(source.size) > MAX_AVATAR_DIMENSION:
+ raise ValueError("Avatar dimensions must not exceed 4096 pixels.")
+ source.load()
+ normalized = ImageOps.exif_transpose(source)
+ mode = "RGBA" if "A" in normalized.getbands() else "RGB"
+ square = ImageOps.fit(
+ normalized.convert(mode),
+ (AVATAR_SIZE, AVATAR_SIZE),
+ method=Image.Resampling.LANCZOS,
+ )
+ output = BytesIO()
+ square.save(output, format="WEBP", quality=88, method=6)
+ except UnidentifiedImageError as exc:
+ raise ValueError("Avatar must be a valid PNG, JPEG, or WebP image.") from exc
+ except Image.DecompressionBombError as exc:
+ raise ValueError("Avatar dimensions are too large.") from exc
+
+ _cleanup_staged_avatars()
+ STAGED_AVATAR_ROOT.mkdir(parents=True, exist_ok=True)
+ token = uuid4().hex
+ path = staged_avatar_path(token)
+ temporary = _stage_bytes(path.parent, path.name, output.getvalue())
+ os.replace(temporary, path)
+ return {"token": token}
+
+
+def staged_avatar_path(token: str) -> Path:
+ if not re.fullmatch(r"[0-9a-f]{32}", str(token or "")):
+ raise ValueError("Invalid staged avatar token.")
+ 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)
+ if not root.is_dir():
+ return plan
+ for path in sorted(root.rglob("*")):
+ if path.is_symlink():
+ raise ValueError("Profile symlinks must be removed manually before deletion.")
+ if path.is_file():
+ plan.delete(path)
+ return plan
+
+
+def _validate_plan_paths(root: Path, changes: list[FileChange]) -> None:
+ intended_root = root.absolute()
+ if root.is_symlink():
+ raise ValueError("The profile directory cannot be a symlink.")
+ for change in changes:
+ if change.action not in {"write", "delete"}:
+ 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.")
+ cursor = change.path.parent
+ while files.is_in_dir(str(cursor), str(intended_root)):
+ if cursor.is_symlink():
+ raise ValueError("Profile paths cannot traverse symlinks.")
+ if cursor == root:
+ break
+ cursor = cursor.parent
+ if change.action == "delete" and change.path.exists() and not (
+ change.path.is_file() or change.path.is_symlink()
+ ):
+ raise ValueError("Change plans delete files, not directories.")
+
+
+def _ensure_parent(parent: Path, created: set[Path]) -> None:
+ missing: list[Path] = []
+ cursor = parent
+ while not cursor.exists():
+ missing.append(cursor)
+ cursor = cursor.parent
+ for directory in reversed(missing):
+ directory.mkdir(exist_ok=True)
+ created.add(directory)
+
+
+def _stage_bytes(directory: Path, name: str, content: bytes) -> Path:
+ target = directory / name
+ descriptor, temporary = tempfile.mkstemp(
+ prefix=f".{name}.", suffix=".tmp", dir=directory
+ )
+ path = Path(temporary)
+ try:
+ os.fchmod(
+ descriptor,
+ target.stat().st_mode & 0o777 if target.exists() else 0o644,
+ )
+ with os.fdopen(descriptor, "wb") as handle:
+ handle.write(content)
+ handle.flush()
+ os.fsync(handle.fileno())
+ return path
+ except Exception:
+ path.unlink(missing_ok=True)
+ raise
+
+
+def _restore_snapshots(snapshots: dict[Path, bytes | None], root: Path) -> None:
+ for path, content in snapshots.items():
+ if content is None:
+ if path.is_file() or path.is_symlink():
+ path.unlink()
+ continue
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = _stage_bytes(path.parent, path.name, content)
+ os.replace(temporary, path)
+
+
+def _prune_empty_directories(root: Path) -> None:
+ if not root.is_dir():
+ return
+ for directory in sorted(
+ (path for path in root.rglob("*") if path.is_dir()),
+ key=lambda path: len(path.parts),
+ reverse=True,
+ ):
+ try:
+ directory.rmdir()
+ except OSError:
+ pass
+
+
+def _fsync_directory(path: Path) -> None:
+ descriptor = os.open(path, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+def _invalidate_profile_caches() -> None:
+ cache.clear(subagents.PATHS_CACHE_AREA)
+ plugins.clear_plugin_cache(
+ ["_agent_editor", "_model_config", tool_policy.PLUGIN_NAME, skills.ACTIVE_SKILLS_PLUGIN_NAME]
+ )
+
+
+def _cleanup_staged_avatars() -> None:
+ if not STAGED_AVATAR_ROOT.is_dir():
+ return
+ cutoff = time.time() - 3600
+ for path in STAGED_AVATAR_ROOT.glob("*.webp"):
+ try:
+ if path.stat().st_mtime < cutoff:
+ path.unlink()
+ except OSError:
+ pass
+
+
+def _profile_reference_paths(profile_id: str) -> list[str]:
+ roots = Path(files.get_abs_path("usr", "projects"))
+ if not roots.is_dir():
+ return []
+ references: list[str] = []
+ for suffix in ("*.json", "*.yaml", "*.yml"):
+ for path in roots.glob(f"*/.a0proj/**/{suffix}"):
+ try:
+ if profile_id in path.read_text(encoding="utf-8"):
+ references.append(_relative_source(path))
+ except (OSError, UnicodeError):
+ pass
+ return sorted(set(references))
diff --git a/plugins/_agent_editor/plugin.yaml b/plugins/_agent_editor/plugin.yaml
new file mode 100644
index 000000000..0e29c997c
--- /dev/null
+++ b/plugins/_agent_editor/plugin.yaml
@@ -0,0 +1,5 @@
+name: _agent_editor
+title: Agent Editor
+description: Deterministic sparse editor for Agent Zero profiles.
+version: 1.0.0
+always_enabled: true
diff --git a/tests/test_agent_editor.py b/tests/test_agent_editor.py
new file mode 100644
index 000000000..2ed68f09f
--- /dev/null
+++ b/tests/test_agent_editor.py
@@ -0,0 +1,750 @@
+from __future__ import annotations
+
+from io import BytesIO
+import json
+from pathlib import Path
+import stat
+
+import pytest
+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_avatar import AgentEditorAvatar
+from plugins._agent_editor.helpers import editor
+
+
+def user_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ root = tmp_path / "usr" / "agents"
+ real_determine_path = editor.plugins.determine_plugin_asset_path
+
+ def determine_plugin_asset_path(
+ plugin_name: str,
+ project_name: str,
+ profile_id: str,
+ *parts: str,
+ ) -> str:
+ if profile_id and not project_name:
+ return str(
+ root
+ / profile_id
+ / editor.files.PLUGINS_DIR
+ / plugin_name
+ / Path(*parts)
+ )
+ return real_determine_path(plugin_name, project_name, profile_id, *parts)
+
+ monkeypatch.setattr(editor, "USER_AGENTS_ROOT", root)
+ monkeypatch.setattr(editor, "STAGED_AVATAR_ROOT", tmp_path / "staged")
+ monkeypatch.setattr(
+ editor.plugins,
+ "determine_plugin_asset_path",
+ determine_plugin_asset_path,
+ )
+ monkeypatch.setattr(editor.plugins, "clear_plugin_cache", lambda _names: None)
+ return root
+
+
+def _write_manual_files(root: Path) -> dict[Path, bytes]:
+ manual_files = {
+ root / "prompts" / "manual.md": b"prompt",
+ root / "tools" / "manual.py": b"tool",
+ root / "extensions" / "manual.py": b"extension",
+ root / "skills" / "manual" / "SKILL.md": b"skill",
+ root / "assets" / "manual.bin": b"asset",
+ root / "plugins" / "manual" / "config.json": b"{}",
+ root / "unknown.bin": b"unknown",
+ }
+ for path, payload in manual_files.items():
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(payload)
+ return manual_files
+
+
+def test_new_easy_profile_writes_only_minimum_exact_files(user_root: Path) -> None:
+ instructions = "Keep this exact. \n\nNo rewrite."
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "legal-research",
+ "creating": True,
+ "editor_mode": "easy",
+ "metadata": {"set": {"title": "Legal Research"}, "reset": []},
+ "prompts": {
+ "set": {editor.SPECIFICS_FILE: instructions},
+ "reset": [],
+ },
+ "tool_policy": {"mode": "inherit"},
+ }
+ )
+
+ assert {path.relative_to(user_root).as_posix() for path in plan.changes} == {
+ "legal-research/agent.yaml",
+ f"legal-research/prompts/{editor.SPECIFICS_FILE}",
+ }
+ editor.apply_change_plan(plan)
+
+ profile = user_root / "legal-research"
+ assert yaml_helper.loads((profile / "agent.yaml").read_text()) == {
+ "title": "Legal Research"
+ }
+ assert (profile / "prompts" / editor.SPECIFICS_FILE).read_text() == instructions
+ assert not list(profile.rglob("*.json"))
+ assert stat.S_IMODE((profile / "agent.yaml").stat().st_mode) == 0o644
+ assert (
+ stat.S_IMODE((profile / "prompts" / editor.SPECIFICS_FILE).stat().st_mode)
+ == 0o644
+ )
+
+
+def test_editor_lifecycle_needs_no_model_or_utility_configuration(
+ user_root: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import litellm
+ from plugins._model_config.helpers import model_config
+
+ def forbidden(*_args, **_kwargs):
+ raise AssertionError("the Agent Editor attempted a model request")
+
+ for name in ("completion", "acompletion", "embedding", "aembedding"):
+ monkeypatch.setattr(litellm, name, forbidden, raising=False)
+ monkeypatch.setattr(model_config, "get_presets", lambda: [{"name": "No utility"}])
+ monkeypatch.setattr(
+ model_config,
+ "resolve_config_settings",
+ lambda _settings: {
+ "chat_model": {"provider": "offline", "name": "main"},
+ "utility_model": {},
+ "embedding_model": {},
+ },
+ )
+ monkeypatch.setattr(
+ model_config,
+ "get_configured_preset_name",
+ lambda **_kwargs: "No utility",
+ )
+ monkeypatch.setattr(editor.tool_policy, "get_tool_catalog", lambda _agent: [])
+ monkeypatch.setattr(editor.skills, "list_skill_catalog", lambda agent=None: [])
+
+ state = editor.build_editor_state("offline-editor")
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "offline-editor",
+ "creating": True,
+ "editor_mode": "easy",
+ "metadata": {"set": {"title": "Offline Editor"}, "reset": []},
+ "prompts": {"set": {editor.SPECIFICS_FILE: "Exact text."}, "reset": []},
+ }
+ )
+ receipt = plan.response()
+
+ assert state["model_presets"][0]["utility"] == {"provider": "", "name": ""}
+ assert editor.apply_change_plan(plan) == receipt
+
+
+def test_state_catalog_is_complete_truthful_and_omits_internal_tools() -> None:
+ state = editor.build_editor_state("researcher")
+
+ assert all(
+ preset[slot]["provider"] and preset[slot]["name"]
+ for preset in state["model_presets"]
+ for slot in ("main", "utility", "embedding")
+ )
+ assert {prompt["group"] for prompt in state["prompts"]} == {
+ f"2.{index}" for index in range(1, 11)
+ }
+ assert all(
+ {
+ "effective",
+ "override",
+ "has_override",
+ "source",
+ "source_chain",
+ "state",
+ }.issubset(prompt)
+ for prompt in state["prompts"]
+ )
+ assert "AGENTS.md" not in {prompt["filename"] for prompt in state["prompts"]}
+ specifics = next(
+ prompt for prompt in state["prompts"]
+ if prompt["filename"] == editor.SPECIFICS_FILE
+ )
+ assert specifics["source_chain"] == ["Framework", "Researcher"]
+ assert any(
+ any(source.startswith("Plugin ·") for source in prompt["source_chain"])
+ for prompt in state["prompts"]
+ )
+ assert not {
+ item["name"] for item in state["tools"]["catalog"]
+ }.intersection({"response", "vision_load"})
+
+
+def test_builtin_prompt_override_never_touches_bundled_profile(user_root: Path) -> None:
+ bundled = Path("agents/researcher")
+ before = {path: path.read_bytes() for path in bundled.rglob("*") if path.is_file()}
+ content = "Only the user-layer instructions change."
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "prompts": {
+ "set": {editor.SPECIFICS_FILE: content},
+ "reset": [],
+ },
+ }
+ )
+
+ assert list(plan.changes) == [
+ user_root / "researcher" / "prompts" / editor.SPECIFICS_FILE
+ ]
+ editor.apply_change_plan(plan)
+ assert all(path.read_bytes() == payload for path, payload in before.items())
+
+ reset = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "prompts": {"set": {}, "reset": [editor.SPECIFICS_FILE]},
+ }
+ )
+ editor.apply_change_plan(reset)
+ assert not (user_root / "researcher" / "prompts" / editor.SPECIFICS_FILE).exists()
+
+
+def test_unrelated_empty_user_directory_survives_save(user_root: Path) -> None:
+ manual = user_root / "researcher" / "tools" / "reserved-for-manual-use"
+ manual.mkdir(parents=True)
+
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "prompts": {
+ "set": {editor.SPECIFICS_FILE: "Sparse change only."},
+ "reset": [],
+ },
+ }
+ )
+ editor.apply_change_plan(plan)
+
+ assert manual.is_dir()
+
+
+def test_profile_collision_includes_disabled_plugin_profiles(
+ user_root: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ plugin_profile = tmp_path / "disabled-plugin" / "agents" / "reserved-agent"
+ plugin_profile.mkdir(parents=True)
+ monkeypatch.setattr(
+ editor.plugins,
+ "get_plugin_paths",
+ lambda *parts: [str(plugin_profile)] if parts == ("agents", "reserved-agent") else [],
+ )
+
+ assert editor.profile_exists("reserved-agent") is True
+
+
+def test_metadata_empty_values_and_unknown_keys_survive(user_root: Path) -> None:
+ profile = user_root / "researcher"
+ profile.mkdir(parents=True)
+ metadata = profile / "agent.yaml"
+ metadata.write_text("custom_key: keep\ndescription: old\n", encoding="utf-8")
+
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "metadata": {
+ "set": {"description": "", "context": ""},
+ "reset": [],
+ },
+ }
+ )
+ editor.apply_change_plan(plan)
+
+ saved = yaml_helper.loads(metadata.read_text())
+ assert saved == {"custom_key": "keep", "description": "", "context": ""}
+
+
+def test_plugin_configs_preserve_unowned_keys_and_use_json(user_root: Path) -> None:
+ profile = user_root / "researcher" / "plugins"
+ model = profile / "_model_config" / "config.json"
+ tools = profile / "_tool_access" / "config.json"
+ skill = profile / "_skills" / "config.json"
+ for path, value in (
+ (model, {"manual": 1}),
+ (tools, {"manual": 2}),
+ (skill, {"active_skills": [{"name": "existing"}]}),
+ ):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(value), encoding="utf-8")
+
+ preset = editor.build_editor_state("researcher")["model_presets"][0]["name"]
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "model_preset": {"mode": "preset", "name": preset},
+ "tool_policy": {
+ "mode": "custom",
+ "default": "block",
+ "allowed": ["local:search_engine"],
+ "blocked": ["local:shell"],
+ },
+ "skill_policy": {
+ "mode": "custom",
+ "default": "block",
+ "allowed": ["a0-development"],
+ "blocked": [],
+ },
+ }
+ )
+ editor.apply_change_plan(plan)
+
+ assert json.loads(model.read_text())["manual"] == 1
+ assert set(json.loads(tools.read_text())) >= {
+ "manual", "mode", "default", "allowed", "blocked"
+ }
+ skill_data = json.loads(skill.read_text())
+ assert skill_data["active_skills"] == [{"name": "existing"}]
+ assert skill_data["visibility_policy"]["default"] == "block"
+
+
+def test_model_and_off_tool_choices_write_only_their_json_contracts(
+ user_root: Path,
+) -> None:
+ preset = editor.build_editor_state("researcher")["model_presets"][1]["name"]
+ model_path = user_root / "researcher" / "plugins" / "_model_config" / "config.json"
+ tool_path = user_root / "researcher" / "plugins" / "_tool_access" / "config.json"
+
+ inherit = editor.build_change_plan(
+ {"profile_id": "researcher", "model_preset": {"mode": "inherit"}}
+ )
+ assert inherit.changes == {}
+
+ selected = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "model_preset": {"mode": "preset", "name": preset},
+ }
+ )
+ assert list(selected.changes) == [model_path]
+ assert json.loads(selected.changes[model_path].content) == {"model_preset": preset}
+
+ off = editor.build_change_plan(
+ {"profile_id": "researcher", "tool_policy": {"mode": "off"}}
+ )
+ assert list(off.changes) == [tool_path]
+ assert json.loads(off.changes[tool_path].content) == {
+ "mode": "custom",
+ "default": "block",
+ "allowed": [],
+ "blocked": [],
+ }
+
+
+def test_project_tool_policy_is_visible_but_editor_plan_stays_in_user_profile(
+ user_root: 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: [])
+ monkeypatch.setattr(editor.skills, "list_skill_catalog", lambda agent=None: [])
+ context = editor._EditorContext("demo")
+
+ state = editor.build_editor_state("researcher", context)
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "tool_policy": {"mode": "off"},
+ },
+ context,
+ )
+
+ assert state["tools"]["project_override_active"] is True
+ assert list(plan.changes) == [
+ user_root / "researcher" / "plugins" / "_tool_access" / "config.json"
+ ]
+
+
+def test_unavailable_skill_policy_ids_are_retained_in_editor_state(
+ user_root: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ config = user_root / "researcher" / "plugins" / "_skills" / "config.json"
+ config.parent.mkdir(parents=True)
+ config.write_text(
+ json.dumps(
+ {
+ "visibility_policy": {
+ "mode": "custom",
+ "default": "allow",
+ "allowed": [],
+ "blocked": ["removed-skill"],
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(editor.skills, "list_skill_catalog", lambda agent=None: [])
+ monkeypatch.setattr(
+ editor.skills,
+ "get_visibility_policy",
+ lambda _agent: {
+ "mode": "custom",
+ "default": "allow",
+ "allowed": [],
+ "blocked": ["removed-skill"],
+ },
+ )
+
+ state = editor.build_editor_state("researcher")
+
+ assert state["skills"]["policy"]["blocked"] == ["removed-skill"]
+ assert state["skills"]["catalog"] == [
+ {
+ "name": "removed-skill",
+ "description": "",
+ "path": "removed-skill",
+ "origin": "Unavailable",
+ "hidden": True,
+ "tags": [],
+ "allowed_tools": [],
+ "available": False,
+ }
+ ]
+
+
+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"):
+ editor.plan_delete_custom("researcher")
+
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "metadata": {"set": {"title": "Renamed Display"}, "reset": []},
+ }
+ )
+ assert list(plan.changes) == [user_root / "researcher" / "agent.yaml"]
+ editor.apply_change_plan(plan)
+
+ assert (user_root / "researcher" / "agent.yaml").is_file()
+ assert not (user_root / "renamed-display").exists()
+
+
+def test_save_rolls_back_every_file_after_commit_failure(
+ user_root: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ root = user_root / "rollback-agent"
+ first = root / "agent.yaml"
+ second = root / "prompts" / editor.SPECIFICS_FILE
+ second.parent.mkdir(parents=True)
+ first.write_bytes(b"title: Before\n")
+ second.write_bytes(b"before")
+ plan = editor.ChangePlan(profile_id="rollback-agent")
+ plan.write(first, b"title: After\n")
+ plan.write(second, b"after")
+
+ original_replace = editor.os.replace
+ calls = 0
+ invalidations: list[bool] = []
+ monkeypatch.setattr(
+ editor,
+ "_invalidate_profile_caches",
+ lambda: invalidations.append(True),
+ )
+
+ def fail_second(source, destination):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise OSError("simulated commit failure")
+ return original_replace(source, destination)
+
+ monkeypatch.setattr(editor.os, "replace", fail_second)
+ with pytest.raises(OSError, match="simulated"):
+ editor.apply_change_plan(plan)
+
+ assert first.read_bytes() == b"title: Before\n"
+ assert second.read_bytes() == b"before"
+ assert invalidations == []
+
+
+def test_remove_my_changes_preserves_manual_and_unknown_files(
+ user_root: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ root = user_root / "researcher"
+ prompt = root / "prompts" / editor.SPECIFICS_FILE
+ manual_files = _write_manual_files(root)
+ prompt.parent.mkdir(parents=True, exist_ok=True)
+ prompt.write_text("override", encoding="utf-8")
+ (root / "agent.yaml").write_text(
+ "title: Mine\nunknown_key: keep\n", encoding="utf-8"
+ )
+ tool_config = root / "plugins" / "_tool_access" / "config.json"
+ tool_config.parent.mkdir(parents=True)
+ tool_config.write_text(
+ json.dumps({"mode": "custom", "default": "block", "manual": True}),
+ encoding="utf-8",
+ )
+
+ real_catalog = editor.prompt_catalog
+
+ def catalog(agent):
+ items = real_catalog(agent)
+ for item in items:
+ if item["filename"] == editor.SPECIFICS_FILE:
+ item.update({"has_override": True, "inherited_source": "agents/researcher"})
+ return items
+
+ monkeypatch.setattr(editor, "prompt_catalog", catalog)
+ plan = editor.plan_remove_changes("researcher")
+ assert set(manual_files).isdisjoint(plan.changes)
+ editor.apply_change_plan(plan)
+
+ assert all(path.read_bytes() == payload for path, payload in manual_files.items())
+ assert yaml_helper.loads((root / "agent.yaml").read_text()) == {
+ "unknown_key": "keep"
+ }
+ assert json.loads(tool_config.read_text()) == {"manual": True}
+
+
+def test_mixed_save_matches_plan_preserves_every_unrelated_family_and_refreshes_cache(
+ user_root: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ root = user_root / "researcher"
+ manual_files = _write_manual_files(root)
+ preset = editor.build_editor_state("researcher")["model_presets"][1]["name"]
+ cleared: list[object] = []
+ monkeypatch.setattr(editor.cache, "clear", lambda area: cleared.append(area))
+ monkeypatch.setattr(
+ editor.plugins,
+ "clear_plugin_cache",
+ lambda names: cleared.append(tuple(names)),
+ )
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "metadata": {"set": {"description": "Scoped"}, "reset": []},
+ "prompts": {
+ "set": {editor.SPECIFICS_FILE: "Only this prompt."},
+ "reset": [],
+ },
+ "model_preset": {"mode": "preset", "name": preset},
+ }
+ )
+ expected = plan.response()
+
+ assert {
+ path.relative_to(user_root).as_posix()
+ for path, change in plan.changes.items()
+ if change.action == "write"
+ } == {
+ "researcher/agent.yaml",
+ f"researcher/prompts/{editor.SPECIFICS_FILE}",
+ "researcher/plugins/_model_config/config.json",
+ }
+ assert editor.apply_change_plan(plan) == expected
+ assert cleared == [
+ editor.subagents.PATHS_CACHE_AREA,
+ ("_agent_editor", "_model_config", "_tool_access", "_skills"),
+ ]
+ assert all(path.read_bytes() == payload for path, payload in manual_files.items())
+
+
+def test_empty_prompt_override_and_project_precedence_are_distinct(
+ user_root: Path,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ framework = tmp_path / "framework"
+ user_prompts = user_root / "researcher" / "prompts"
+ project_meta = tmp_path / "project" / ".a0proj"
+ project_prompts = project_meta / "agents" / "researcher" / "prompts"
+ for path, text in (
+ (framework / editor.SPECIFICS_FILE, "framework"),
+ (user_prompts / editor.SPECIFICS_FILE, ""),
+ (project_prompts / editor.SPECIFICS_FILE, "project"),
+ ):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ monkeypatch.setattr(
+ editor.subagents,
+ "get_paths",
+ lambda _agent, *parts: (
+ [str(user_prompts), str(framework)]
+ if not editor.projects.get_context_project_name(_agent.context)
+ else [str(project_prompts), str(user_prompts), str(framework)]
+ ),
+ )
+ original_meta = editor.projects.get_project_meta
+ monkeypatch.setattr(
+ editor.projects,
+ "get_project_meta",
+ lambda name, *parts: str(project_meta.joinpath(*parts))
+ if name == "acceptance-project"
+ else original_meta(name, *parts),
+ )
+
+ empty = next(
+ item
+ for item in editor.prompt_catalog(editor.EditorAgent("researcher"))
+ if item["filename"] == editor.SPECIFICS_FILE
+ )
+ project = next(
+ item
+ for item in editor.prompt_catalog(
+ editor.EditorAgent(
+ "researcher",
+ editor._EditorContext("acceptance-project"),
+ )
+ )
+ if item["filename"] == editor.SPECIFICS_FILE
+ )
+
+ 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["effective"] == "project"
+ assert project["source_chain"][-2:] == ["Your override", "Project · project"]
+
+ reset = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "prompts": {"set": {}, "reset": [editor.SPECIFICS_FILE]},
+ }
+ )
+ assert list(reset.changes) == [user_prompts / editor.SPECIFICS_FILE]
+ assert next(iter(reset.changes.values())).action == "delete"
+
+
+def test_avatar_is_normalized_and_avatar_only_edit_is_sparse(user_root: Path) -> None:
+ from PIL import Image
+
+ source = BytesIO()
+ Image.new("RGB", (800, 400), "red").save(source, format="PNG")
+ upload = FileStorage(stream=BytesIO(source.getvalue()), filename="avatar.png")
+ staged = editor.stage_avatar(upload)
+ plan = editor.build_change_plan(
+ {
+ "profile_id": "researcher",
+ "metadata": {
+ "set": {"avatar": {"kind": "image", "token": staged["token"]}},
+ "reset": [],
+ },
+ }
+ )
+
+ assert {path.relative_to(user_root).as_posix() for path in plan.changes} == {
+ "researcher/agent.yaml",
+ "researcher/assets/avatar.webp",
+ }
+ editor.apply_change_plan(plan)
+ avatar = user_root / "researcher" / "assets" / "avatar.webp"
+ with Image.open(avatar) as normalized:
+ assert normalized.format == "WEBP"
+ assert normalized.size == (editor.AVATAR_SIZE, editor.AVATAR_SIZE)
+ assert not normalized.getexif()
+
+
+ ("relative_path", "patch", "label"),
+ (
+ (
+ "agent.yaml",
+ {"metadata": {"set": {"description": "new"}, "reset": []}},
+ "profile metadata",
+ ),
+ (
+ "plugins/_tool_access/config.json",
+ {"tool_policy": {"mode": "off"}},
+ "tool policy configuration",
+ ),
+ ),
+)
+def test_invalid_existing_authored_files_are_never_overwritten(
+ user_root: Path,
+ relative_path: str,
+ patch: dict,
+ label: str,
+) -> None:
+ path = user_root / "researcher" / relative_path
+ path.parent.mkdir(parents=True, exist_ok=True)
+ original = b"{ definitely not valid\n"
+ path.write_bytes(original)
+
+ with pytest.raises(ValueError, match=label):
+ editor.build_change_plan({"profile_id": "researcher", **patch})
+
+ assert path.read_bytes() == original
+
+
+def test_editor_preview_raw_reads_markdown_without_running_dynamic_processor(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ prompt_root = tmp_path / "prompts"
+ prompt_root.mkdir()
+ (prompt_root / editor.SPECIFICS_FILE).write_text(
+ "Raw {{value}}", encoding="utf-8"
+ )
+ (prompt_root / "agent.system.main.specifics.py").write_text(
+ "raise RuntimeError('must not run')\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ editor.subagents,
+ "get_paths",
+ lambda *_args, **_kwargs: [str(prompt_root)],
+ )
+ monkeypatch.setattr(
+ editor.files,
+ "read_prompt_file",
+ lambda *_args, **_kwargs: pytest.fail("dynamic prompt loader ran"),
+ )
+
+ item = next(
+ item
+ for item in editor.prompt_catalog(editor.EditorAgent("researcher"))
+ if item["filename"] == editor.SPECIFICS_FILE
+ )
+
+ assert item["effective"] == "Raw {{value}}"
+ assert item["preview"] == "Raw {{value}}"
+ assert item["dynamic_processor"] is True
+
+
+def test_editor_api_keeps_default_auth_and_csrf_protection() -> None:
+ for handler in (AgentEditor, AgentEditorAvatar):
+ assert handler.requires_auth() is True
+ assert handler.requires_csrf() is True
+
+
+def test_backend_has_no_legacy_save_or_model_request_path() -> None:
+ sources = "\n".join(
+ path.read_text(encoding="utf-8")
+ for path in (
+ Path(editor.__file__),
+ Path("plugins/_agent_editor/api/agent_editor.py"),
+ Path("plugins/_agent_editor/api/agent_editor_avatar.py"),
+ )
+ )
+
+ assert "save_agent_data" not in sources
+ assert "call_llm" not in sources
+ assert "call_utility_model" not in sources
+ assert "litellm" not in sources