Skip to content

Agent Zero AI framework

Refactor plugin discovery and asset serving

frdel07c128130b38
diff --git a/plugins/example_agent/plugin.json b/plugins/example_agent/plugin.json
new file mode 100644
index 000000000..e69de29bb
diff --git a/plugins/memory/plugin.json b/plugins/memory/plugin.json
new file mode 100644
index 000000000..e69de29bb
diff --git a/python/helpers/files.py b/python/helpers/files.py
index 5a7b9362e..f0d63381e 100644
--- a/python/helpers/files.py
+++ b/python/helpers/files.py
@@ -17,6 +17,11 @@ import glob
import mimetypes
from simpleeval import simple_eval
+AGENTS_DIR = "agents"
+PLUGINS_DIR = "plugins"
+PROJECTS_DIR = "projects"
+USER_DIR = "usr"
+
class VariablesPlugin(ABC):
@abstractmethod
@@ -246,11 +251,7 @@ def is_probably_binary_bytes(data: bytes, threshold: float = 0.3) -> bool:
# Count suspicious control bytes
allowed = {8, 9, 10, 12, 13} # \b \t \n \f \r
- suspicious = sum(
- 1
- for b in data
- if ((b < 32 and b not in allowed) or b == 127)
- )
+ suspicious = sum(1 for b in data if ((b < 32 and b not in allowed) or b == 127))
return (suspicious / len(data)) > threshold
@@ -352,7 +353,11 @@ def find_file_in_dirs(_filename: str, _directories: list[str]):
)
-def get_unique_filenames_in_dirs(dir_paths: list[str], pattern: str = "*", type: Literal["file", "dir", "any"] = "file"):
+def get_unique_filenames_in_dirs(
+ dir_paths: list[str],
+ pattern: str = "*",
+ type: Literal["file", "dir", "any"] = "file",
+):
# returns absolute paths for unique filenames, priority by order in dir_paths
seen = set()
result = []
@@ -360,7 +365,11 @@ def get_unique_filenames_in_dirs(dir_paths: list[str], pattern: str = "*", type:
full_dir = get_abs_path(dir_path)
for file_path in glob.glob(os.path.join(full_dir, pattern)):
fname = os.path.basename(file_path)
- if fname not in seen and (type == "any" or (type == "file" and os.path.isfile(file_path)) or (type == "dir" and os.path.isdir(file_path))):
+ if fname not in seen and (
+ type == "any"
+ or (type == "file" and os.path.isfile(file_path))
+ or (type == "dir" and os.path.isdir(file_path))
+ ):
seen.add(fname)
result.append(get_abs_path(file_path))
# sort by filename (basename), not the full path
@@ -456,10 +465,10 @@ def move_dir(old_path: str, new_path: str):
abs_new = get_abs_path(new_path)
if not os.path.isdir(abs_old):
return # nothing to rename
-
+
# ensure parent directory exists
os.makedirs(os.path.dirname(abs_new), exist_ok=True)
-
+
try:
os.rename(abs_old, abs_new)
except Exception:
@@ -509,14 +518,17 @@ def get_abs_path(*relative_paths):
"Convert relative paths to absolute paths based on the base directory."
return os.path.join(get_base_dir(), *relative_paths)
+
def get_abs_path_dockerized(*relative_paths):
"Ensures the abs path is dockerized (i.e. /a0/... path)"
abs = get_abs_path(*relative_paths)
from python.helpers import runtime
+
if runtime.is_dockerized():
return abs
return normalize_a0_path(abs)
+
def get_abs_path_development(*relative_paths):
"Ensures the abs path is relevant for dev environment"
abs = get_abs_path(*relative_paths)
@@ -551,6 +563,16 @@ def exists(*relative_paths):
return os.path.exists(path)
+def is_file(*relative_paths):
+ path = get_abs_path(*relative_paths)
+ return os.path.isfile(path)
+
+
+def is_dir(*relative_paths):
+ path = get_abs_path(*relative_paths)
+ return os.path.isdir(path)
+
+
def get_base_dir():
# Get the base directory from the current file path
base_dir = os.path.dirname(os.path.abspath(os.path.join(__file__, "../../")))
@@ -568,10 +590,10 @@ def dirname(path: str):
def is_in_base_dir(path: str):
- return is_in_dir(path,get_base_dir())
+ return is_in_dir(path, get_base_dir())
-def is_in_dir(path:str,dir:str):
+def is_in_dir(path: str, dir: str):
# check if the given path is within the directory
abs_path = os.path.abspath(path)
abs_dir = os.path.abspath(dir)
@@ -621,6 +643,7 @@ def move_file(relative_path: str, new_path: str):
except OSError:
# fallback to copy and delete
import shutil
+
shutil.copy2(abs_path, new_abs_path)
try:
os.unlink(abs_path)
@@ -659,6 +682,7 @@ def read_text_files_in_dir(
continue
return result
+
def list_files_in_dir_recursively(relative_path: str) -> list[str]:
abs_path = get_abs_path(relative_path)
if not os.path.exists(abs_path):
@@ -671,4 +695,3 @@ def list_files_in_dir_recursively(relative_path: str) -> list[str]:
rel_path = os.path.relpath(file_path, abs_path)
result.append(rel_path)
return result
-
\ No newline at end of file
diff --git a/python/helpers/plugins.py b/python/helpers/plugins.py
index aa3c3e339..e980a964b 100644
--- a/python/helpers/plugins.py
+++ b/python/helpers/plugins.py
@@ -1,22 +1,26 @@
from __future__ import annotations
-import re
+import re, json
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, TYPE_CHECKING
from python.helpers import files, print_style
+if TYPE_CHECKING:
+ from agent import Agent
+
# Extracts target selector from <meta name="plugin-target" content="...">
_META_TARGET_RE = re.compile(
r'<meta\s+name=["\']plugin-target["\']\s+content=["\']([^"\']+)["\']',
re.IGNORECASE,
)
+META_FILE_NAME = "plugin.json"
+SETTINGS_FILE_NAME = "settings.json"
@dataclass(slots=True)
-class Plugin:
- id: str
+class PluginListItem:
name: str
path: Path
@@ -27,14 +31,14 @@ def get_plugin_roots() -> List[str]:
# projects = files.find_existing_paths_by_pattern("usr/projects/*/.a0proj/plugins")
return [
# *projects,
- files.get_abs_path("usr/plugins"),
- files.get_abs_path("plugins"),
+ files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR),
+ files.get_abs_path(files.PLUGINS_DIR),
]
-def list_plugins() -> List[Plugin]:
+def list_plugins() -> List[PluginListItem]:
"""Discover plugins by directory convention. First root wins on ID conflict."""
- by_id: Dict[str, Plugin] = {}
+ by_id: Dict[str, PluginListItem] = {}
for root in get_plugin_roots():
root_path = Path(root)
if not root_path.exists():
@@ -43,17 +47,25 @@ def list_plugins() -> List[Plugin]:
if not d.is_dir() or d.name.startswith("."):
continue
if d.name not in by_id:
- by_id[d.name] = Plugin(id=d.name, name=d.name, path=d)
+ by_id[d.name] = PluginListItem(name=d.name, path=d)
return list(by_id.values())
-def find_plugin(plugin_id: str) -> Optional[Plugin]:
+def find_plugin_dir(plugin_name: str):
"""Find a single plugin by ID."""
- if not plugin_id:
+ if not plugin_name:
return None
- for p in list_plugins():
- if p.id == plugin_id:
- return p
+
+ # check if the plugin is in the user directory
+ user_plugin_path = files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR, plugin_name, META_FILE_NAME)
+ if files.exists(user_plugin_path):
+ return files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR, plugin_name)
+
+ # check if the plugin is in the default directory
+ default_plugin_path = files.get_abs_path(files.PLUGINS_DIR, plugin_name, META_FILE_NAME)
+ if files.exists(default_plugin_path):
+ return files.get_abs_path(files.PLUGINS_DIR, plugin_name)
+
return None
@@ -97,10 +109,79 @@ def get_webui_extensions(extension_point:str, filters:List[str]|None=None) -> Li
try:
rel_path = files.deabsolute_path(str(ext_file))
entry: Dict[str, Any] = {
- "plugin_id": plugin.id,
+ "plugin_name": plugin.name,
"path": rel_path,
}
entries.append(entry)
except Exception:
print_style.PrintStyle.error(f"Failed to load frontend extension file {ext_file}")
return entries
+
+def get_plugin_settings(plugin_name:str, agent:Agent|None):
+ file_path = find_plugin_file(plugin_name, SETTINGS_FILE_NAME, agent=agent)
+ if file_path:
+ return json.loads(files.read_file(file_path))
+ return None
+
+def save_plugin_settings(plugin_name:str, project_name:str, agent_profile:str, settings:dict):
+ file_path = determine_plugin_save_file_path(plugin_name, project_name, agent_profile, SETTINGS_FILE_NAME)
+ if file_path:
+ files.write_file(file_path, json.dumps(settings))
+
+def find_plugin_file(plugin_name:str, *subpaths:str, agent:Agent|None=None):
+ profile_name = agent.config.profile if agent and agent.config.profile else ""
+ project_name = ""
+
+ if agent:
+ from python.helpers import projects
+ project_name = projects.get_context_project_name(agent.context) or ""
+
+ if project_name and profile_name:
+ # project/.a0proj/agents/<profile>/plugins/<plugin_name>/...
+ project_agent_file = projects.get_project_meta_folder(
+ project_name, files.AGENTS_DIR, profile_name, files.PLUGINS_DIR, plugin_name, *subpaths
+ )
+ if files.exists(project_agent_file):
+ return project_agent_file
+
+ if project_name:
+ # project/.a0proj/plugins/<plugin_name>/...
+ project_file = projects.get_project_meta_folder(project_name, files.PLUGINS_DIR, plugin_name, *subpaths)
+ if files.exists(project_file):
+ return project_file
+
+ if profile_name:
+ from python.helpers import subagents
+ # usr/agents/<profile>/plugins/<plugin_name>/...
+ path = files.get_abs_path(subagents.USER_AGENTS_DIR, profile_name, files.PLUGINS_DIR, plugin_name, *subpaths)
+ if files.exists(path):
+ return path
+
+ # agents/<profile>/plugins/<plugin_name>/...
+ path = files.get_abs_path(subagents.DEFAULT_AGENTS_DIR, profile_name, files.PLUGINS_DIR, plugin_name, *subpaths)
+ if files.exists(path):
+ return path
+
+ # usr/plugins/<plugin_name>/...
+ path = files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR, plugin_name, *subpaths)
+ if files.exists(path):
+ return path
+
+ # plugins/<plugin_name>/...
+ path = files.get_abs_path(files.PLUGINS_DIR, plugin_name, *subpaths)
+ if files.exists(path):
+ return path
+
+ return None
+
+def determine_plugin_save_file_path(plugin_name:str, project_name:str, agent_profile:str, *subpaths:str):
+ base_path = files.get_abs_path(files.USER_DIR)
+
+ if project_name:
+ from python.helpers import projects
+ base_path = projects.get_project_meta_folder(project_name)
+
+ if agent_profile:
+ base_path = files.get_abs_path(base_path, files.AGENTS_DIR, agent_profile)
+
+ return files.get_abs_path(base_path, files.PLUGINS_DIR, plugin_name, *subpaths)
\ No newline at end of file
diff --git a/run_ui.py b/run_ui.py
index a9bf51111..1f702bd26 100644
--- a/run_ui.py
+++ b/run_ui.py
@@ -238,9 +238,9 @@ async def serve_index():
# Serve plugin assets
[email protected]("/plugins/<plugin_id>/<path:asset_path>", methods=["GET"])
[email protected]("/plugins/<plugin_name>/<path:asset_path>", methods=["GET"])
@requires_auth
-async def serve_plugin_asset(plugin_id, asset_path):
+async def serve_plugin_asset(plugin_name, asset_path):
"""
Serve static assets from plugin directories.
Resolves using the plugin system (with overrides).
@@ -249,21 +249,21 @@ async def serve_plugin_asset(plugin_id, asset_path):
from flask import send_file
# Use the new find_plugin helper
- plugin = plugins.find_plugin(plugin_id)
- if not plugin:
+ plugin_dir = plugins.find_plugin_dir(plugin_name)
+ if not plugin_dir:
return Response("Plugin not found", 404)
# Resolve the plugin asset path with security checks
try:
# Construct path using plugin root
- asset_file = (plugin.path / asset_path).resolve()
- plugin_root = plugin.path.resolve()
+ asset_file = files.get_abs_path(plugin_dir, asset_path)
+ plugin_root = plugin_dir
# Security: ensure the resolved path is within the plugin directory
if not files.is_in_dir(str(asset_file), str(plugin_root)):
return Response("Access denied", 403)
- if not asset_file.is_file():
+ if not files.is_file(asset_file):
return Response("Asset not found", 404)
return send_file(str(asset_file))
@@ -507,7 +507,7 @@ def run():
plugin_handlers = load_classes_from_folder(str(api_path), "*.py", ApiHandler)
for handler in plugin_handlers:
# prefixed route for explicit namespacing
- register_api_handler(webapp, handler, url_prefix=f"/api/plugins/{plugin.id}")
+ register_api_handler(webapp, handler, url_prefix=f"/api/plugins/{plugin.name}")
handlers_by_namespace = _build_websocket_handlers_by_namespace(socketio_server, lock)
configure_websocket_namespaces(