Agent Zero AI framework
Derive plugin names; refactor API helpers
frdel6dde8c2e74be
diff --git a/helpers/git.py b/helpers/git.pyindex 5a8872f51..4e7049055 100644--- a/helpers/git.py+++ b/helpers/git.py@@ -1,4 +1,5 @@from git import Repo+from giturlparse import parsefrom datetime import datetimeimport osimport subprocess@@ -20,6 +21,19 @@ def strip_auth_from_url(url: str) -> str:return urlunparse((parsed.scheme, clean_netloc, parsed.path, '', '', ''))+def extract_author_repo(url: str) -> tuple[str, str]:+ parsed = parse(strip_auth_from_url(url.strip()))+ author = (parsed.owner or "").strip()+ repo = (parsed.repo or parsed.name or "").strip()+ if not parsed.valid or not author or not repo:+ raise ValueError("Could not derive plugin name from URL")+ if repo.endswith(".git"):+ repo = repo[:-4]+ if not author or not repo:+ raise ValueError("Could not derive plugin name from URL")+ return author, repo++def get_git_info():# Get the current working directory (assuming the repo is in the same folder as the script)repo_path = files.get_base_dir()diff --git a/plugins/plugin_installer/helpers/install.py b/plugins/plugin_installer/helpers/install.pyindex 0c2233342..70a4fc65c 100644--- a/plugins/plugin_installer/helpers/install.py+++ b/plugins/plugin_installer/helpers/install.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport os+import reimport shutilimport timeimport urllib.request@@ -11,12 +12,13 @@ from pathlib import Pathfrom typing import Any, Optionalfrom helpers import files+from helpers.git import extract_author_repofrom helpers import yaml as yaml_helperfrom helpers.plugins import (META_FILE_NAME,PluginMetadata,get_plugins_list,- invalidate_plugin_cache,+ clear_plugin_cache,)from werkzeug.datastructures import FileStoragefrom werkzeug.utils import secure_filename@@ -26,18 +28,31 @@ def _get_user_plugins_dir() -> str:return files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR)- def _sanitize_plugin_name(name: str) -> str:- """Validate and sanitize a plugin directory name.- Converts dots and dashes to underscores for Python import compatibility.- Raises ValueError if the name is unsafe for filesystem use."""- name = name.strip().strip(".")- name = re.sub(r"[-.]", "_", name)- if not name or not _SAFE_NAME_RE.match(name):- raise ValueError(- f"Invalid plugin name: '{name}'. "- "Names must start with a letter or digit and contain only letters, digits, or underscores."- )- return name+def _derive_git_plugin_name(url: str) -> str:+ """Derive the canonical plugin ID from a Git repository URL."""+ parts = extract_author_repo(url)+ repo_name = "__".join(+ cleaned+ for part in parts+ if (cleaned := re.sub(r"_+", "_", re.sub(r"[^0-9A-Za-z]+", "_", part)).strip("_"))+ )+ if not repo_name:+ raise ValueError("Could not derive plugin name from URL")+ return repo_name+++def _derive_zip_plugin_name(+ plugin_root: str, extract_dir: str, original_filename: str | None+) -> str:+ """Resolve the plugin ID for an uploaded ZIP archive."""+ if plugin_root != extract_dir:+ return os.path.basename(plugin_root)++ upload_name = Path((original_filename or "").strip()).name+ plugin_name = Path(upload_name).stem+ if not plugin_name:+ raise ValueError("Could not derive plugin name from uploaded filename")+ return plugin_namedef validate_plugin_dir(path: str) -> PluginMetadata:@@ -157,7 +172,6 @@ def install_from_git(url: str, token: Optional[str] = None) -> dict:except Exception as e:# Cleanup partial cloneshutil.rmtree(dest, ignore_errors=True)- clear_plugin_cache()raise ValueError(f"Git clone failed: {e}") from etry:@@ -165,7 +179,6 @@ def install_from_git(url: str, token: Optional[str] = None) -> dict:except ValueError:# No plugin.yaml — remove cloned reposhutil.rmtree(dest, ignore_errors=True)- clear_plugin_cache()raiseclear_plugin_cache()@@ -210,4 +223,4 @@ def fetch_plugin_index() -> dict:req = urllib.request.Request(index_url, headers={"User-Agent": "AgentZero"})with urllib.request.urlopen(req, timeout=30) as resp:data = json.loads(resp.read().decode())- return data+ return data\ No newline at end of filediff --git a/requirements.txt b/requirements.txtindex 527d9c6ef..f6b19eca9 100644--- a/requirements.txt+++ b/requirements.txt@@ -10,6 +10,7 @@ flask[async]==3.0.3flask-basicauth==0.2.0flaredantic==0.1.5GitPython==3.1.43+giturlparse==0.14.0inputimeout==1.0.4kokoro>=0.9.2simpleeval==1.0.3diff --git a/webui/js/api.js b/webui/js/api.jsindex 56e85fc6d..f79e9e834 100644--- a/webui/js/api.js+++ b/webui/js/api.js@@ -1,22 +1,3 @@-let _extensionsModule = null;--async function _getExtensions() {- if (!_extensionsModule) _extensionsModule = await import("./extensions.js");- return _extensionsModule;-}--async function _shouldCallApiExtensions(apiUrl) {- const extensions = await _getExtensions();- const excluded = extensions.API_EXTENSION_EXCLUDED_ENDPOINTS;- return !(excluded instanceof Set && excluded.has(apiUrl));-}--function _normalizeApiUrl(url) {- return url.startsWith("/api/") || url.startsWith("api/")- ? `/${url.replace(/^\/+/, "")}`- : `/api/${url.replace(/^\/+/, "")}`;-}-/*** Call a JSON-in JSON-out API endpoint* Data is automatically serialized@@ -61,7 +42,7 @@ export async function callJsonApi(endpoint, data) {}if (ctx.error) throw ctx.error;-+return ctx.result;}@@ -128,15 +109,10 @@ export async function fetchApi(url, request) {// retry the request with new tokencsrfToken = null;return await _wrap(false);- } else if (finalResponse.redirected && finalResponse.url.endsWith("/login")) {- // redirect to login (origin check prevents open redirect)- const _redirectUrl = new URL(finalResponse.url);- if (_redirectUrl.origin === window.location.origin) {- window.location.href = finalResponse.url;- }- return;}+ if (redirect(finalResponse)) return;+// return the responsereturn finalResponse;}@@ -220,14 +196,8 @@ export async function getCsrfToken() {}}- if (response.redirected && response.url.endsWith("/login")) {- // redirect to login (origin check prevents open redirect)- const _redirectUrl = new URL(response.url);- if (_redirectUrl.origin === window.location.origin) {- window.location.href = response.url;- }- return;- }+ if (redirect(response)) return;+const json = await response.json();if (json.ok) {const runtimeId =@@ -247,13 +217,17 @@ export async function getCsrfToken() {: null;const cookieRuntimeId = runtimeId || injectedRuntimeId;if (cookieRuntimeId) {- const _secureFlag = window.location.protocol === 'https:' ? '; Secure' : '';+ const _secureFlag =+ window.location.protocol === "https:" ? "; Secure" : "";document.cookie = `csrf_token_${cookieRuntimeId}=${csrfToken}; SameSite=Strict; Path=/${_secureFlag}`;} else {console.warn("CSRF runtime id missing; skipping cookie name binding.");}const elapsedMs = Date.now() - startedAt;- if (elapsedMs > CSRF_SLOW_WARN_MS && globalThis.runtimeInfo?.isDevelopment) {+ if (+ elapsedMs > CSRF_SLOW_WARN_MS &&+ globalThis.runtimeInfo?.isDevelopment+ ) {console.warn(`CSRF token request took ${elapsedMs}ms`);}return csrfToken;@@ -269,3 +243,33 @@ export async function getCsrfToken() {csrfTokenPromise = null;}}++++let _extensionsModule = null;++async function _getExtensions() {+ if (!_extensionsModule) _extensionsModule = await import("./extensions.js");+ return _extensionsModule;+}++async function _shouldCallApiExtensions(apiUrl) {+ const extensions = await _getExtensions();+ const excluded = extensions.API_EXTENSION_EXCLUDED_ENDPOINTS;+ return !(excluded instanceof Set && excluded.has(apiUrl));+}++function _normalizeApiUrl(url) {+ return url.startsWith("/api/") || url.startsWith("api/")+ ? `/${url.replace(/^\/+/, "")}`+ : `/api/${url.replace(/^\/+/, "")}`;+}++function redirect(response) {+ if (!(response.redirected && response.url.endsWith("/login"))) return false;+ const _redirectUrl = new URL(response.url);+ if (_redirectUrl.origin === window.location.origin) {+ window.location.href = response.url;+ }+ return true;+}\ No newline at end of file