Agent Zero AI framework
pipx, subagent paths, alpine directives, CSRF allowed origins autoset
frdeldd018d66a49e
diff --git a/agent.py b/agent.pyindex f5e0602f8..f6001098c 100644--- a/agent.py+++ b/agent.py@@ -619,14 +619,14 @@ class Agent:return system_promptdef parse_prompt(self, _prompt_file: str, **kwargs):- dirs = subagents.get_agent_paths_chain(self, "prompts")+ dirs = subagents.get_paths(self, "prompts")prompt = files.parse_file(_prompt_file, _directories=dirs, _agent=self, **kwargs)return promptdef read_prompt(self, file: str, **kwargs) -> str:- dirs = subagents.get_agent_paths_chain(self, "prompts")+ dirs = subagents.get_paths(self, "prompts")prompt = files.read_prompt_file(file, _directories=dirs, _agent=self, **kwargs)prompt = files.remove_code_fences(prompt)return prompt@@ -958,7 +958,7 @@ class Agent:classes = []# search for tools in agent's folder hierarchy- paths = subagents.get_agent_paths_chain(self, "tools", name + ".py", default_root="python")+ paths = subagents.get_paths(self, "tools", name + ".py", default_root="python")for path in paths:try:classes = extract_tools.load_classes_from_file(path, Tool) # type: ignore[arg-type]diff --git a/docker/base/fs/ins/install_python.sh b/docker/base/fs/ins/install_python.shindex 82f2fc383..417395ebc 100644--- a/docker/base/fs/ins/install_python.sh+++ b/docker/base/fs/ins/install_python.sh@@ -20,7 +20,7 @@ python3.13 -m venv /opt/venvsource /opt/venv/bin/activate# upgrade pip and install static packages-pip install --no-cache-dir --upgrade pip ipython requests+pip install --no-cache-dir --upgrade pip pipx ipython requestsecho "====================PYTHON PYVENV===================="diff --git a/python/api/csrf_token.py b/python/api/csrf_token.pyindex 0e46a4d46..f4d1d63c0 100644--- a/python/api/csrf_token.py+++ b/python/api/csrf_token.py@@ -11,6 +11,8 @@ from python.helpers.api import (from python.helpers import runtime, dotenv, loginimport fnmatch+ALLOWED_ORIGINS_KEY = "ALLOWED_ORIGINS"+class GetCsrfToken(ApiHandler):@@ -44,9 +46,11 @@ class GetCsrfToken(ApiHandler):}async def check_allowed_origin(self, request: Request):- # if login is required, this che+ # if login is required, this check is unnecessaryif login.is_login_required():return {"ok": True, "origin": "", "allowed_origins": ""}+ # initialize allowed origins if not yet set+ self.initialize_allowed_origins(request)# otherwise, check if the origin is allowedreturn await self.is_allowed_origin(request)@@ -66,6 +70,7 @@ class GetCsrfToken(ApiHandler):)return {"ok": match, "origin": origin, "allowed_origins": allowed_origins}+def get_origin_from_request(self, request: Request):# get from originr = request.headers.get("Origin") or request.environ.get("HTTP_ORIGIN")@@ -88,7 +93,7 @@ class GetCsrfToken(ApiHandler):# get the allowed origins from the environmentallowed_origins = [origin.strip()- for origin in (dotenv.get_dotenv_value("ALLOWED_ORIGINS") or "").split(",")+ for origin in (dotenv.get_dotenv_value(ALLOWED_ORIGINS_KEY) or "").split(",")if origin.strip()]@@ -110,3 +115,34 @@ class GetCsrfToken(ApiHandler):def get_default_allowed_origins(self) -> list[str]:return ["*://localhost:*", "*://127.0.0.1:*", "*://0.0.0.0:*"]++ def initialize_allowed_origins(self, request: Request):+ """+ If A0 is hosted on a server, add the first visit origin to ALLOWED_ORIGINS.+ This simplifies deployment process as users can access their new instance without+ additional setup while keeping it secure.+ """+ # dotenv value is already set, do nothing+ denv = dotenv.get_dotenv_value(ALLOWED_ORIGINS_KEY)+ if denv:+ return++ # get the origin from the request+ req_origin = self.get_origin_from_request(request)+ if not req_origin:+ return++ # check if the origin is allowed by default+ allowed_origins = self.get_default_allowed_origins()+ match = any(+ fnmatch.fnmatch(req_origin, allowed_origin)+ for allowed_origin in allowed_origins+ )+ if match:+ return++ # if not, add it to the allowed origins+ allowed_origins.append(req_origin)+ dotenv.save_dotenv_value(ALLOWED_ORIGINS_KEY, ",".join(allowed_origins))++\ No newline at end of filediff --git a/python/extensions/agent_init/_15_load_profile_settings.py b/python/extensions/agent_init/_15_load_profile_settings.pyindex d4261d7b9..d4c9b5ab4 100644--- a/python/extensions/agent_init/_15_load_profile_settings.py+++ b/python/extensions/agent_init/_15_load_profile_settings.py@@ -10,7 +10,7 @@ class LoadProfileSettings(Extension):if not self.agent or not self.agent.config.profile:return- config_files = subagents.get_agent_paths_chain(self.agent, "settings.json", include_default=False)+ config_files = subagents.get_paths(self.agent, "settings.json", include_default=False)settings_override = {}for settings_path in config_files:diff --git a/python/helpers/extension.py b/python/helpers/extension.pyindex d28e86c4e..186099cc0 100644--- a/python/helpers/extension.py+++ b/python/helpers/extension.py@@ -30,7 +30,7 @@ async def call_extensions(from python.helpers import projects, subagents# search for extension folders in all agent's paths- paths = subagents.get_agent_paths_chain(agent, "extensions", extension_point, default_root="python")+ paths = subagents.get_paths(agent, "extensions", extension_point, default_root="python")all_exts = [cls for path in paths for cls in _get_extensions(path)]# merge: first ocurrence of file name is the overridediff --git a/python/helpers/subagents.py b/python/helpers/subagents.pyindex fb8886a4a..66f320f00 100644--- a/python/helpers/subagents.py+++ b/python/helpers/subagents.py@@ -246,84 +246,63 @@ def get_available_agents_dict(return filtered_agents-def get_agent_paths(- agent: "Agent", *subpaths, must_exist_completely: bool = True-) -> list[str]:- """Returns list of possible paths for the given agent and subpaths. Order is from lowest priority (global)."""-- if not agent or not agent.config.profile:- return []- from python.helpers import projects-- project_name = projects.get_context_project_name(agent.context)- return get_agent_profile_paths(- agent.config.profile,- project_name,- *subpaths,- must_exist_completely=must_exist_completely,- )---def get_agent_paths_chain(+def get_paths(agent: "Agent|None",*subpaths,- must_exist_completely: bool = True,+ must_exist_completely: bool = True,include_project: bool = True,include_user: bool = True,include_default: bool = True,default_root: str = "",) -> list[str]:"""Returns list of file paths for the given agent and subpaths, searched in order of priority:- project/agents/, usr/agents/, agents/, project/, usr/, default."""- from python.helpers import projects+ project/agents/, project/, usr/agents/, agents/, usr/, default."""+ paths: list[str] = []+ check_subpaths = subpaths if must_exist_completely else []+ profile_name = agent.config.profile if agent and agent.config.profile else ""+ project_name = ""- if agent and agent.config.profile:- project_name = projects.get_context_project_name(agent.context)- paths = get_agent_profile_paths(- agent.config.profile,- project_name,- *subpaths,- must_exist_completely=must_exist_completely,- )- list.reverse(paths) # reverse for proper priority- else:- paths = []- project_name = ""+ if include_project and agent:+ from python.helpers import projects- if include_project and project_name:- path = projects.get_project_meta_folder(project_name, *subpaths)- if (not must_exist_completely) or files.exists(path):+ project_name = projects.get_context_project_name(agent.context) or ""++ if project_name and profile_name:+ # project/agents/<profile>/...+ project_agent_dir = projects.get_project_meta_folder(+ project_name, "agents", profile_name+ )+ if files.exists(files.get_abs_path(project_agent_dir, *check_subpaths)):+ paths.append(files.get_abs_path(project_agent_dir, *subpaths))++ if project_name:+ # project/.a0proj/...+ path = projects.get_project_meta_folder(project_name, *subpaths)+ if (not must_exist_completely) or files.exists(path):+ paths.append(path)++ if profile_name:++ # usr/agents/<profile>/...+ path = files.get_abs_path(USER_AGENTS_DIR, profile_name, *subpaths)+ if (not must_exist_completely) or files.exists(files.get_abs_path(USER_AGENTS_DIR, profile_name, *check_subpaths)):paths.append(path)++ # agents/<profile>/...+ path = files.get_abs_path(DEFAULT_AGENTS_DIR, profile_name, *subpaths)+ if (not must_exist_completely) or files.exists(files.get_abs_path(DEFAULT_AGENTS_DIR, profile_name, *check_subpaths)):+ paths.append(path)+if include_user:+ # usr/...path = files.get_abs_path(USER_DIR, *subpaths)if (not must_exist_completely) or files.exists(path):paths.append(path)+if include_default:+ # default_root/...path = files.get_abs_path(default_root, *subpaths)if (not must_exist_completely) or files.exists(path):paths.append(path)- return paths--def get_agent_profile_paths(- name: str,- project_name: str | None = None,- *subpaths,- must_exist_completely: bool = True,-) -> list[str]:- result = []- check_subpaths = subpaths if must_exist_completely else []-- if files.exists(files.get_abs_path(DEFAULT_AGENTS_DIR, name, *check_subpaths)):- result.append(files.get_abs_path(DEFAULT_AGENTS_DIR, name, *subpaths))- if files.exists(files.get_abs_path(USER_AGENTS_DIR, name, *check_subpaths)):- result.append(files.get_abs_path(USER_AGENTS_DIR, name, *subpaths))- if project_name:- from python.helpers import projects-- project_agent_dir = projects.get_project_meta_folder(- project_name, "agents", name- )- if files.exists(files.get_abs_path(project_agent_dir, *check_subpaths)):- result.append(files.get_abs_path(project_agent_dir, *subpaths))- return result+ return pathsdiff --git a/webui/js/initFw.js b/webui/js/initFw.jsindex 69abde220..c758b6d6c 100644--- a/webui/js/initFw.js+++ b/webui/js/initFw.js@@ -10,15 +10,48 @@ await import("../vendor/alpine/alpine.min.js");// add x-destroy directive to alpineAlpine.directive(- "destroy",- (el, { expression }, { evaluateLater, cleanup }) => {- const onDestroy = evaluateLater(expression);- cleanup(() => onDestroy());- }-);+ "destroy",+ (_el, { expression }, { evaluateLater, cleanup }) => {+ const onDestroy = evaluateLater(expression);+ cleanup(() => onDestroy());+ }+ );-// add x-create directive to alpine-Alpine.directive("create", (_el, { expression }, { evaluateLater }) => {- const onCreate = evaluateLater(expression);- onCreate();-});+ // add x-create directive to alpine+ Alpine.directive(+ "create",+ (_el, { expression }, { evaluateLater }) => {+ const onCreate = evaluateLater(expression);+ onCreate();+ }+ );++ // run every second if the component is active+ Alpine.directive(+ "every-second",+ (_el, { expression }, { evaluateLater, cleanup }) => {+ const onTick = evaluateLater(expression);+ const intervalId = setInterval(() => onTick(), 1000);+ cleanup(() => clearInterval(intervalId));+ }+ );++ // run every minute if the component is active+ Alpine.directive(+ "every-minute",+ (_el, { expression }, { evaluateLater, cleanup }) => {+ const onTick = evaluateLater(expression);+ const intervalId = setInterval(() => onTick(), 60_000);+ cleanup(() => clearInterval(intervalId));+ }+ );++ // run every hour if the component is active+ Alpine.directive(+ "every-hour",+ (_el, { expression }, { evaluateLater, cleanup }) => {+ const onTick = evaluateLater(expression);+ const intervalId = setInterval(() => onTick(), 3_600_000);+ cleanup(() => clearInterval(intervalId));+ }+ );