Agent Zero AI framework
plugin installer flow cleanup
Alessandro64aff8423b81
diff --git a/plugins/plugin_installer/api/plugin_install.py b/plugins/plugin_installer/api/plugin_install.pyindex bbb3355f9..7de86446c 100644--- a/plugins/plugin_installer/api/plugin_install.py+++ b/plugins/plugin_installer/api/plugin_install.py@@ -1,13 +1,13 @@from __future__ import annotations-import time-import uuid-from pathlib import Path--from helpers.api import ApiHandler, Input, Request, Output-from helpers import files+from helpers.api import ApiHandler, Input, Output, Requestfrom werkzeug.datastructures import FileStorage-from werkzeug.utils import secure_filename++from plugins.plugin_installer.helpers.install import (+ get_marketplace_index,+ install_from_git,+ install_uploaded_zip,+)class PluginInstall(ApiHandler):"""Plugin installation API. Handles ZIP upload, Git clone, and index fetch."""@@ -37,19 +37,7 @@ class PluginInstall(ApiHandler):if not plugin_file.filename:return {"success": False, "error": "No file selected"}- # Save upload to temp- tmp_dir = Path(files.get_abs_path("tmp", "plugin_uploads"))- tmp_dir.mkdir(parents=True, exist_ok=True)- base = secure_filename(plugin_file.filename)- if not base.lower().endswith(".zip"):- base = f"{base}.zip"- unique = uuid.uuid4().hex[:8]- stamp = time.strftime("%Y%m%d_%H%M%S")- tmp_path = str(tmp_dir / f"plugin_{stamp}_{unique}_{base}")- plugin_file.save(tmp_path)-- from plugins.plugin_installer.helpers.install import install_from_zip- return install_from_zip(tmp_path)+ return install_uploaded_zip(plugin_file)def _install_git(self, input: dict) -> dict:git_url = (input.get("git_url", "") or "").strip()@@ -57,24 +45,7 @@ class PluginInstall(ApiHandler):if not git_url:return {"success": False, "error": "Git URL is required"}- from plugins.plugin_installer.helpers.install import install_from_gitreturn install_from_git(git_url, git_token)def _fetch_index(self, input: dict) -> dict:- from plugins.plugin_installer.helpers.install import fetch_plugin_index- from helpers.plugins import get_plugins_list-- index_data = fetch_plugin_index()- plugins = index_data.get("plugins", {})- installed_dirs = set(get_plugins_list())-- def _dir_name(github: str) -> str:- seg = (github or "").rstrip("/").split("/")[-1]- return seg[:-4] if seg.endswith(".git") else seg-- installed_keys = [- key for key, p in plugins.items()- if _dir_name(p.get("github", "")) in installed_dirs- ]-- return {"success": True, "index": index_data, "installed_plugins": installed_keys}+ return {"success": True, **get_marketplace_index()}diff --git a/plugins/plugin_installer/helpers/install.py b/plugins/plugin_installer/helpers/install.pyindex 4360175de..8d90e6ee7 100644--- a/plugins/plugin_installer/helpers/install.py+++ b/plugins/plugin_installer/helpers/install.py@@ -1,25 +1,55 @@from __future__ import annotations+import jsonimport osimport shutilimport time+import urllib.request+import uuidimport zipfilefrom pathlib import Path-from typing import Optional+from typing import Any, Optionalfrom helpers import files+from helpers import yaml as yaml_helperfrom helpers.plugins import (META_FILE_NAME,PluginMetadata,+ get_plugins_list,invalidate_plugin_cache,)-from helpers import yaml as yaml_helper+from werkzeug.datastructures import FileStorage+from werkzeug.utils import secure_filenamedef _get_user_plugins_dir() -> str:"""Return absolute path to usr/plugins/."""return files.get_abs_path(files.USER_DIR, files.PLUGINS_DIR)+def _derive_git_plugin_name(url: str) -> str:+ """Derive the canonical plugin ID from a Git repository URL."""+ repo_name = url.rstrip("/").split("/")[-1]+ if repo_name.endswith(".git"):+ repo_name = repo_name[:-4]+ 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_name++def validate_plugin_dir(path: str) -> PluginMetadata:"""Check directory contains plugin.yaml and return parsed metadata.Raises ValueError if plugin.yaml is missing or invalid."""@@ -48,7 +78,28 @@ def _find_plugin_root(extracted_dir: str) -> str:raise ValueError(f"No {META_FILE_NAME} found in the uploaded archive")-def install_from_zip(zip_path: str) -> dict:+def install_uploaded_zip(plugin_file: FileStorage) -> dict:+ """Persist an uploaded ZIP temporarily and install it."""+ original_filename = Path((plugin_file.filename or "").strip()).name+ if not original_filename:+ raise ValueError("No file selected")++ tmp_dir = Path(files.get_abs_path("tmp", "plugin_uploads"))+ tmp_dir.mkdir(parents=True, exist_ok=True)++ temp_name = secure_filename(original_filename) or "plugin.zip"+ if not temp_name.lower().endswith(".zip"):+ temp_name = f"{temp_name}.zip"++ unique = uuid.uuid4().hex[:8]+ stamp = time.strftime("%Y%m%d_%H%M%S")+ tmp_path = str(tmp_dir / f"plugin_{stamp}_{unique}_{temp_name}")+ plugin_file.save(tmp_path)++ return install_from_zip(tmp_path, original_filename=original_filename)+++def install_from_zip(zip_path: str, original_filename: str | None = None) -> dict:"""Extract ZIP, find plugin.yaml, move its parent to usr/plugins/.Returns dict with plugin name and metadata.Cleans up tmp files regardless of outcome."""@@ -74,13 +125,7 @@ def install_from_zip(zip_path: str) -> dict:# Find plugin.yamlplugin_root = _find_plugin_root(extract_dir)meta = validate_plugin_dir(plugin_root)- plugin_name = os.path.basename(plugin_root)-- # If the zip only has one top-level dir that IS the plugin root,- # use that dir's name. Otherwise use the zip's stem.- if plugin_root == extract_dir:- # plugin.yaml at root of extraction — use zip filename stem- plugin_name = Path(zip_path).stem+ plugin_name = _derive_zip_plugin_name(plugin_root, extract_dir, original_filename)check_plugin_conflict(plugin_name)@@ -110,12 +155,7 @@ def install_from_git(url: str, token: Optional[str] = None) -> dict:Returns dict with plugin name and metadata."""from helpers.git import clone_repo- # Derive plugin name from URL- repo_name = url.rstrip("/").split("/")[-1]- if repo_name.endswith(".git"):- repo_name = repo_name[:-4]- if not repo_name:- raise ValueError("Could not derive plugin name from URL")+ repo_name = _derive_git_plugin_name(url)check_plugin_conflict(repo_name)@@ -146,11 +186,34 @@ def install_from_git(url: str, token: Optional[str] = None) -> dict:}+def get_marketplace_index() -> dict[str, Any]:+ """Return the plugin index plus installed marketplace keys."""+ index_data = fetch_plugin_index()+ if not isinstance(index_data, dict):+ raise ValueError("Plugin index response was not a JSON object")++ plugins = index_data.get("plugins")+ if not isinstance(plugins, dict):+ raise ValueError("Plugin index payload is missing a valid 'plugins' map")++ installed_dirs = set(get_plugins_list())+ installed_keys: list[str] = []+ for key, plugin_data in plugins.items():+ if not isinstance(plugin_data, dict):+ continue+ github_url = plugin_data.get("github", "")+ try:+ plugin_name = _derive_git_plugin_name(github_url)+ except ValueError:+ continue+ if plugin_name in installed_dirs:+ installed_keys.append(key)++ return {"index": index_data, "installed_plugins": installed_keys}++def fetch_plugin_index() -> dict:"""Download the plugin index from GitHub releases."""- import urllib.request- import json-index_url = "https://github.com/agent0ai/a0-plugins/releases/download/generated-index/index.json"req = urllib.request.Request(index_url, headers={"User-Agent": "AgentZero"})with urllib.request.urlopen(req, timeout=30) as resp:diff --git a/plugins/plugin_installer/webui/install-detail.html b/plugins/plugin_installer/webui/install-detail.htmlindex 75061deb8..7a2e1c13c 100644--- a/plugins/plugin_installer/webui/install-detail.html+++ b/plugins/plugin_installer/webui/install-detail.html@@ -28,41 +28,35 @@<div class="pi-hero-manage"><template x-if="$store.pluginInstallStore.installedPluginInfo.has_main_screen"><button type="button" class="button"- title="Open"@click="$store.pluginInstallStore.manageOpenPlugin()"><span class="icon material-symbols-outlined">dashboard</span> Open</button></template><template x-if="$store.pluginInstallStore.installedPluginInfo.has_config_screen"><button type="button" class="button"- title="Config"@click="$store.pluginInstallStore.manageOpenConfig()"><span class="icon material-symbols-outlined">settings</span> Config</button></template><template x-if="$store.pluginInstallStore.installedPluginInfo.has_readme"><button type="button" class="button"- title="README"@click="$store.pluginInstallStore.manageOpenDoc('readme')"><span class="icon material-symbols-outlined">description</span> README</button></template><template x-if="$store.pluginInstallStore.installedPluginInfo.has_license"><button type="button" class="button"- title="LICENSE"@click="$store.pluginInstallStore.manageOpenDoc('license')"><span class="icon material-symbols-outlined">gavel</span> License</button></template><template x-if="$store.pluginInstallStore.installedPluginInfo.has_init_script"><button type="button" class="button"- title="Run initializer script"@click="$store.pluginInstallStore.manageOpenInit()"><span class="icon material-symbols-outlined">terminal</span> Init</button></template><button type="button" class="button"- title="Info"@click="$store.pluginInstallStore.manageOpenInfo()"><span class="icon material-symbols-outlined">info</span> Info</button>@@ -323,12 +317,8 @@}.pi-tag {- display: flex;- flex-wrap: wrap;- gap: 0.4rem;- }-- .pi-tag {+ display: inline-flex;+ align-items: center;font-size: 0.8rem;padding: 0.25rem 0.6rem;border-radius: 4px;diff --git a/plugins/plugin_installer/webui/pluginInstallStore.js b/plugins/plugin_installer/webui/pluginInstallStore.jsindex a7b63c84e..de76574dd 100644--- a/plugins/plugin_installer/webui/pluginInstallStore.js+++ b/plugins/plugin_installer/webui/pluginInstallStore.js@@ -157,7 +157,8 @@ const model = {"Plugin Installer");} catch (e) {- this.error = `Installation error: ${e.message}`;+ const message = e instanceof Error ? e.message : String(e);+ this.error = `Installation error: ${message}`;} finally {this.loading = false;this.loadingMessage = "";@@ -197,7 +198,8 @@ const model = {"Plugin Installer");} catch (e) {- this.error = `Clone error: ${e.message}`;+ const message = e instanceof Error ? e.message : String(e);+ this.error = `Clone error: ${message}`;} finally {this.loading = false;this.loadingMessage = "";@@ -226,7 +228,8 @@ const model = {this.installedPlugins = data.installed_plugins || [];this.page = 1;} catch (e) {- this.error = `Failed to load plugin index: ${e.message}`;+ const message = e instanceof Error ? e.message : String(e);+ this.error = `Failed to load plugin index: ${message}`;} finally {this.loading = false;this.loadingMessage = "";@@ -339,17 +342,18 @@ const model = {},openDetail(plugin) {- this.selectedPlugin = plugin;+ const detailPlugin = plugin ? { ...plugin } : null;+ this.selectedPlugin = detailPlugin;this.error = "";this.installedPluginInfo = null;this.readmeContent = null;- this.detailPluginName = this._pluginName(plugin);- this.detailThumbnailSources = this.getDetailThumbnailSources(plugin);+ this.detailPluginName = this._pluginName(detailPlugin);+ this.detailThumbnailSources = this.getDetailThumbnailSources(detailPlugin);this.detailThumbnailIndex = 0;- if (plugin.installed) {+ if (detailPlugin?.installed) {this.fetchInstalledPluginInfo(this.detailPluginName);}- this.fetchReadme(plugin);+ this.fetchReadme(detailPlugin);openModal("/plugins/plugin_installer/webui/install-detail.html");},@@ -360,14 +364,24 @@ const model = {try {this.readmeLoading = true;this.readmeContent = null;+ let lastError = null;++ for (const branch of ["main", "master"]) {+ try {+ const response = await fetch(`${rawBase}/${branch}/README.md`);+ if (!response.ok) continue;++ const readme = await response.text();+ this.readmeContent = marked.parse(readme, { breaks: true });+ return;+ } catch (error) {+ lastError = error;+ }+ }- const response = await fetch(`${rawBase}/main/README.md`);- if (response.ok) {- const readme = await response.text();- this.readmeContent = marked.parse(readme, { breaks: true });+ if (lastError) {+ console.warn("Failed to fetch readme:", lastError);}- } catch (e) {- console.warn("Failed to fetch readme:", e);} finally {this.readmeLoading = false;}@@ -406,11 +420,15 @@ const model = {return;}- if (!this.installedPlugins.includes(plugin.key)) {- this.installedPlugins.push(plugin.key);+ const installedKey = plugin.key || data.plugin_name;+ if (installedKey && !this.installedPlugins.includes(installedKey)) {+ this.installedPlugins = [...this.installedPlugins, installedKey];}- plugin.installed = true;- this.selectedPlugin = { ...this.selectedPlugin, installed: true };+ this.selectedPlugin = {+ ...plugin,+ ...(this.selectedPlugin || {}),+ installed: true,+ };this.detailPluginName = data.plugin_name;this.detailThumbnailSources = this.getDetailThumbnailSources(this.selectedPlugin);this.detailThumbnailIndex = 0;@@ -421,7 +439,8 @@ const model = {"Plugin Installer");} catch (e) {- this.error = `Installation error: ${e.message}`;+ const message = e instanceof Error ? e.message : String(e);+ this.error = `Installation error: ${message}`;} finally {this.loading = false;this.loadingMessage = "";@@ -438,7 +457,7 @@ const model = {});const plugins = Array.isArray(response.plugins) ? response.plugins : [];this.installedPluginInfo = plugins.find((p) => p.name === pluginName) || null;- } catch (e) {+ } catch (_error) {this.installedPluginInfo = null;}},@@ -453,7 +472,7 @@ const model = {manageOpenPlugin() {const info = this.installedPluginInfo;- if (!info?.name || !info?.has_main_screen) return;+ if (!info || !info.name || !info.has_main_screen) return;openModal(`/plugins/${info.name}/webui/main.html`);},@@ -489,10 +508,12 @@ const model = {const pls = this._pluginListStore();if (pls?.deletePlugin && this.installedPluginInfo) {await pls.deletePlugin(this.installedPluginInfo);- if (this.selectedPlugin) {- this.selectedPlugin.installed = false;- const idx = this.installedPlugins.indexOf(this.selectedPlugin.key);- if (idx !== -1) this.installedPlugins.splice(idx, 1);+ const currentPlugin = this.selectedPlugin;+ if (currentPlugin) {+ this.selectedPlugin = { ...currentPlugin, installed: false };+ this.installedPlugins = this.installedPlugins.filter(+ (key) => key !== currentPlugin.key+ );}this.installedPluginInfo = null;}@@ -523,13 +544,20 @@ const model = {*/getDetailThumbnailSources(plugin) {const currentPlugin = plugin || this.selectedPlugin;- const sources = [+ const rawSources = [this.getThumbnailUrl(currentPlugin),this.getLocalThumbnailUrl(),];- return sources.filter(- (url, index) => typeof url === "string" && sources.indexOf(url) === index- );+ const uniqueSources = [];+ const seen = new Set();++ for (const url of rawSources) {+ if (typeof url !== "string" || seen.has(url)) continue;+ seen.add(url);+ uniqueSources.push(url);+ }++ return uniqueSources;},getDetailThumbnailUrl() {