Agent Zero AI framework
feat: add plugin installer with support for ZIP and Git installations
TerminallyLazy99e6c2b41908
diff --git a/plugins/plugin_installer/api/plugin_install.py b/plugins/plugin_installer/api/plugin_install.pynew file mode 100644index 000000000..294a36596--- /dev/null+++ b/plugins/plugin_installer/api/plugin_install.py@@ -0,0 +1,73 @@+from __future__ import annotations++import time+import uuid+from pathlib import Path++from python.helpers.api import ApiHandler, Input, Request, Output+from python.helpers import files+from werkzeug.datastructures import FileStorage+from werkzeug.utils import secure_filename+++class PluginInstall(ApiHandler):+ """Plugin installation API. Handles ZIP upload, Git clone, and index fetch."""++ async def process(self, input: Input, request: Request) -> Output:+ action = input.get("action", "") or request.form.get("action", "")++ try:+ if action == "install_zip":+ return self._install_zip(request)+ elif action == "install_git":+ return self._install_git(input)+ elif action == "fetch_index":+ return self._fetch_index(input)+ else:+ return {"success": False, "error": f"Unknown action: {action}"}+ except ValueError as e:+ return {"success": False, "error": str(e)}+ except Exception as e:+ return {"success": False, "error": f"Installation failed: {e}"}++ def _install_zip(self, request: Request) -> dict:+ if "plugin_file" not in request.files:+ return {"success": False, "error": "No file provided"}++ plugin_file: FileStorage = request.files["plugin_file"]+ 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)++ def _install_git(self, input: dict) -> dict:+ git_url = (input.get("git_url", "") or "").strip()+ git_token = (input.get("git_token", "") or "").strip() or None+ if not git_url:+ return {"success": False, "error": "Git URL is required"}++ from plugins.plugin_installer.helpers.install import install_from_git+ return 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 python.helpers.plugins import get_plugins_list+ index_data = fetch_plugin_index()+ installed = get_plugins_list()+ return {+ "success": True,+ "index": index_data,+ "installed_plugins": installed,+ }diff --git a/plugins/plugin_installer/extensions/webui/plugins-list-header-buttons/install-buttons.html b/plugins/plugin_installer/extensions/webui/plugins-list-header-buttons/install-buttons.htmlnew file mode 100644index 000000000..4b04f9984--- /dev/null+++ b/plugins/plugin_installer/extensions/webui/plugins-list-header-buttons/install-buttons.html@@ -0,0 +1,136 @@+<span x-data="{ open: false }">+ <script type="module">+ import { store } from "/plugins/plugin_installer/webui/pluginInstallStore.js";+ </script>++ <div class="pi-install-wrapper" @click.outside="open = false">+ <button type="button"+ class="button"+ @click="open = !open">+ <span class="icon material-symbols-outlined">add</span> Install+ <span class="material-symbols-outlined pi-chevron"+ :class="{ 'pi-chevron-open': open }">expand_more</span>+ </button>++ <div class="pi-dropdown" x-show="open" x-cloak x-transition.opacity.duration.150ms>+ <button type="button" class="pi-dropdown-item"+ @click="open = false; openModal('../plugins/plugin_installer/webui/install-index.html')">+ <span class="material-symbols-outlined">store</span>+ <span class="pi-item-text">+ <span class="pi-item-title">Browse Plugins</span>+ <span class="pi-item-desc">Explore the community index</span>+ </span>+ </button>+ <div class="pi-dropdown-sep"></div>+ <button type="button" class="pi-dropdown-item"+ @click="open = false; openModal('../plugins/plugin_installer/webui/install-git.html')">+ <span class="material-symbols-outlined">terminal</span>+ <span class="pi-item-text">+ <span class="pi-item-title">Clone from Git</span>+ <span class="pi-item-desc">Install from a repository URL</span>+ </span>+ </button>+ <button type="button" class="pi-dropdown-item"+ @click="open = false; openModal('../plugins/plugin_installer/webui/install-zip.html')">+ <span class="material-symbols-outlined">upload_file</span>+ <span class="pi-item-text">+ <span class="pi-item-title">Upload ZIP</span>+ <span class="pi-item-desc">Install from a local archive</span>+ </span>+ </button>+ </div>+ </div>++ <style>+ .plugins-toolbar-actions {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ }++ .pi-install-wrapper {+ position: relative;+ }++ .pi-install-wrapper > .button {+ gap: 0.25rem;+ }++ .pi-chevron {+ font-size: 1.1rem !important;+ transition: transform 0.2s ease;+ }++ .pi-chevron-open {+ transform: rotate(180deg);+ }++ .pi-dropdown {+ position: absolute;+ top: calc(100% + 0.35rem);+ right: 0;+ min-width: 230px;+ background: var(--color-panel);+ border: 1px solid var(--color-border);+ border-radius: 8px;+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35);+ z-index: 100;+ padding: 0.3rem;+ }++ .pi-dropdown-item {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ width: 100%;+ padding: 0.5rem 0.6rem;+ background: none;+ border: none;+ border-radius: 5px;+ color: var(--color-text);+ cursor: pointer;+ text-align: left;+ font-family: inherit;+ font-size: 0.875rem;+ transition: background 0.12s ease;+ }++ .pi-dropdown-item:hover {+ background: var(--color-background);+ }++ .pi-dropdown-item .material-symbols-outlined {+ font-size: 1.25rem;+ color: var(--color-text-secondary);+ flex-shrink: 0;+ }++ .pi-dropdown-item:hover .material-symbols-outlined {+ color: var(--color-highlight);+ }++ .pi-item-text {+ display: flex;+ flex-direction: column;+ }++ .pi-item-title {+ font-weight: 500;+ line-height: 1.3;+ }++ .pi-item-desc {+ font-size: 0.75rem;+ color: var(--color-text-secondary);+ line-height: 1.3;+ }++ .pi-dropdown-sep {+ height: 1px;+ background: var(--color-border);+ margin: 0.2rem 0.5rem;+ }++ [x-cloak] { display: none !important; }+ </style>+</span>diff --git a/plugins/plugin_installer/helpers/__init__.py b/plugins/plugin_installer/helpers/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/plugins/plugin_installer/helpers/install.py b/plugins/plugin_installer/helpers/install.pynew file mode 100644index 000000000..7e0043aea--- /dev/null+++ b/plugins/plugin_installer/helpers/install.py@@ -0,0 +1,176 @@+from __future__ import annotations++import os+import re+import shutil+import time+import zipfile+from pathlib import Path+from typing import Optional++from python.helpers import files+from python.helpers.plugins import (+ META_FILE_NAME,+ PluginMetadata,+ invalidate_plugin_cache,+)+from python.helpers import yaml as yaml_helper++_SAFE_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")+++def _get_user_plugins_dir() -> str:+ """Return absolute path to usr/plugins/."""+ 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.+ Raises ValueError if the name is unsafe for filesystem use."""+ name = name.strip().strip(".")+ 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, hyphens, underscores, or dots."+ )+ return 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."""+ meta_path = os.path.join(path, META_FILE_NAME)+ if not os.path.isfile(meta_path):+ raise ValueError(f"No {META_FILE_NAME} found in {os.path.basename(path)}")+ with open(meta_path, "r", encoding="utf-8") as f:+ content = f.read()+ data = yaml_helper.loads(content)+ return PluginMetadata.model_validate(data)+++def check_plugin_conflict(name: str) -> None:+ """Raise ValueError if a plugin with this name already exists in usr/plugins/."""+ dest = os.path.join(_get_user_plugins_dir(), name)+ if os.path.exists(dest):+ raise ValueError(f"Plugin '{name}' is already installed")+++def _find_plugin_root(extracted_dir: str) -> str:+ """Walk extracted directory to find the parent of plugin.yaml.+ Returns absolute path to the plugin root directory."""+ for root, dirs, dir_files in os.walk(extracted_dir):+ if META_FILE_NAME in dir_files:+ return root+ raise ValueError(f"No {META_FILE_NAME} found in the uploaded archive")+++def install_from_zip(zip_path: str) -> 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."""+ base_tmp = files.get_abs_path("tmp", "plugin_installs")+ os.makedirs(base_tmp, exist_ok=True)+ stamp = time.strftime("%Y%m%d_%H%M%S")+ extract_dir = os.path.join(base_tmp, f"extract_{stamp}")+ os.makedirs(extract_dir, exist_ok=True)++ try:+ # Extract with path traversal protection+ try:+ with zipfile.ZipFile(zip_path, "r") as z:+ real_extract = os.path.realpath(extract_dir)+ for member in z.namelist():+ member_path = os.path.realpath(os.path.join(extract_dir, member))+ if not member_path.startswith(real_extract + os.sep) and member_path != real_extract:+ raise ValueError(f"Unsafe path in archive: {member}")+ z.extractall(extract_dir)+ except zipfile.BadZipFile:+ raise ValueError("The uploaded file is not a valid ZIP archive")++ # Find plugin.yaml+ plugin_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 = _sanitize_plugin_name(plugin_name)+ check_plugin_conflict(plugin_name)++ # Move to usr/plugins/+ dest = os.path.join(_get_user_plugins_dir(), plugin_name)+ os.makedirs(os.path.dirname(dest), exist_ok=True)+ shutil.move(plugin_root, dest)+ invalidate_plugin_cache()++ return {+ "success": True,+ "plugin_name": plugin_name,+ "title": meta.title or plugin_name,+ "path": files.deabsolute_path(dest),+ }+ finally:+ # Cleanup: extracted files and the archive+ shutil.rmtree(extract_dir, ignore_errors=True)+ try:+ os.unlink(zip_path)+ except OSError:+ pass+++def install_from_git(url: str, token: Optional[str] = None) -> dict:+ """Clone git repo into usr/plugins/, validate plugin.yaml.+ Returns dict with plugin name and metadata."""+ from python.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 = _sanitize_plugin_name(repo_name)+ check_plugin_conflict(repo_name)++ dest = os.path.join(_get_user_plugins_dir(), repo_name)+ os.makedirs(os.path.dirname(dest), exist_ok=True)++ try:+ clone_repo(url, dest, token=token or None)+ except Exception as e:+ # Cleanup partial clone+ shutil.rmtree(dest, ignore_errors=True)+ raise ValueError(f"Git clone failed: {e}") from e++ try:+ meta = validate_plugin_dir(dest)+ except ValueError:+ # No plugin.yaml — remove cloned repo+ shutil.rmtree(dest, ignore_errors=True)+ raise++ invalidate_plugin_cache()++ return {+ "success": True,+ "plugin_name": repo_name,+ "title": meta.title or repo_name,+ "path": files.deabsolute_path(dest),+ }+++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:+ data = json.loads(resp.read().decode())+ return datadiff --git a/plugins/plugin_installer/plugin.yaml b/plugins/plugin_installer/plugin.yamlnew file mode 100644index 000000000..845fefef4--- /dev/null+++ b/plugins/plugin_installer/plugin.yaml@@ -0,0 +1,5 @@+title: Plugin Installer+description: Install plugins from ZIP files, Git repositories, or the community index.+version: 1.0.0+settings_sections: []+always_enabled: truediff --git a/plugins/plugin_installer/webui/install-detail.html b/plugins/plugin_installer/webui/install-detail.htmlnew file mode 100644index 000000000..27dc94bff--- /dev/null+++ b/plugins/plugin_installer/webui/install-detail.html@@ -0,0 +1,232 @@+<html>+<head>+ <title>Plugin Details</title>+ <script type="module">+ import { store } from "/plugins/plugin_installer/webui/pluginInstallStore.js";+ </script>+</head>+<body>+ <div x-data>+ <template x-if="$store.pluginInstallStore?.selectedPlugin">+ <div>+ <div class="pi-detail-header">+ <div class="pi-detail-thumb">+ <template x-if="$store.pluginInstallStore.selectedPlugin.thumbnail">+ <img :src="$store.pluginInstallStore.selectedPlugin.thumbnail"+ :alt="$store.pluginInstallStore.selectedPlugin.title">+ </template>+ <template x-if="!$store.pluginInstallStore.selectedPlugin.thumbnail">+ <span class="material-symbols-outlined pi-detail-placeholder">extension</span>+ </template>+ </div>+ <div class="pi-detail-info">+ <h3 class="pi-detail-title" x-text="$store.pluginInstallStore.selectedPlugin.title || $store.pluginInstallStore.selectedPlugin.key"></h3>+ <div class="pi-detail-stars">+ <span class="material-symbols-outlined" style="font-size:1rem">star</span>+ <span x-text="($store.pluginInstallStore.selectedPlugin.stars || 0) + ' stars'"></span>+ </div>+ <div class="pi-detail-tags" x-show="$store.pluginInstallStore.selectedPlugin.tags?.length">+ <template x-for="tag in $store.pluginInstallStore.selectedPlugin.tags || []" :key="tag">+ <span class="pi-tag" x-text="tag"></span>+ </template>+ </div>+ </div>+ </div>++ <div class="pi-detail-desc" x-text="$store.pluginInstallStore.selectedPlugin.description || 'No description available.'"></div>++ <div class="pi-detail-links">+ <template x-if="$store.pluginInstallStore.selectedPlugin.github">+ <a :href="$store.pluginInstallStore.selectedPlugin.github" target="_blank" class="pi-link">+ <span class="material-symbols-outlined">code</span> GitHub Repository+ </a>+ </template>+ <template x-if="$store.pluginInstallStore.selectedPlugin.discussion">+ <a :href="$store.pluginInstallStore.selectedPlugin.discussion" target="_blank" class="pi-link">+ <span class="material-symbols-outlined">forum</span> Discussion+ </a>+ </template>+ </div>++ <div class="pi-detail-actions">+ <template x-if="$store.pluginInstallStore.selectedPlugin.installed">+ <button class="button" disabled>+ <span class="icon material-symbols-outlined">check</span> Already Installed+ </button>+ </template>+ <template x-if="!$store.pluginInstallStore.selectedPlugin.installed">+ <button class="button confirm"+ @click="$store.pluginInstallStore.installFromIndex($store.pluginInstallStore.selectedPlugin)"+ :disabled="$store.pluginInstallStore.loading">+ <template x-if="$store.pluginInstallStore.loading">+ <span class="pi-button-loading">+ <span class="spinner"></span>+ <span x-text="$store.pluginInstallStore.loadingMessage || 'Installing...'"></span>+ </span>+ </template>+ <template x-if="!$store.pluginInstallStore.loading">+ <span>+ <span class="icon material-symbols-outlined">download</span> Install Plugin+ </span>+ </template>+ </button>+ </template>+ </div>++ <div x-show="$store.pluginInstallStore.error" class="pi-error">+ <span x-text="$store.pluginInstallStore.error"></span>+ </div>++ <div x-show="$store.pluginInstallStore.result" class="pi-result">+ <div class="pi-result-icon">+ <span class="material-symbols-outlined">check_circle</span>+ </div>+ <div class="pi-result-text">+ <strong>Plugin installed successfully!</strong>+ <div class="pi-result-path" x-text="$store.pluginInstallStore.result?.path || ''"></div>+ </div>+ </div>+ </div>+ </template>+ </div>++ <style>+ .pi-detail-header {+ display: flex;+ gap: 1rem;+ margin-bottom: 1rem;+ }++ .pi-detail-thumb {+ width: 100px;+ height: 100px;+ border-radius: 8px;+ overflow: hidden;+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--color-panel);+ }++ .pi-detail-thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }++ .pi-detail-placeholder {+ font-size: 3rem;+ color: var(--color-text-muted);+ }++ .pi-detail-info {+ flex: 1;+ }++ .pi-detail-title {+ margin: 0 0 0.3rem 0;+ font-size: 1.2rem;+ }++ .pi-detail-stars {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ font-size: 0.9rem;+ color: var(--color-text-secondary);+ margin-bottom: 0.4rem;+ }++ .pi-detail-tags {+ display: flex;+ flex-wrap: wrap;+ gap: 0.3rem;+ }++ .pi-tag {+ font-size: 0.75rem;+ padding: 0.15rem 0.5rem;+ border-radius: 3px;+ background: var(--color-panel);+ color: var(--color-text-secondary);+ border: 1px solid var(--color-border);+ }++ .pi-detail-desc {+ color: var(--color-text-primary);+ font-size: 0.95rem;+ line-height: 1.5;+ margin-bottom: 1rem;+ }++ .pi-detail-links {+ display: flex;+ gap: 1rem;+ margin-bottom: 1rem;+ }++ .pi-link {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ color: var(--color-highlight);+ text-decoration: none;+ font-size: 0.9rem;+ }++ .pi-link:hover {+ text-decoration: underline;+ }++ .pi-detail-actions {+ margin: 1rem 0;+ }++ .pi-button-loading {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ }++ .pi-error {+ color: var(--color-error);+ padding: 0.75rem;+ background: var(--color-error-bg, rgba(239,68,68,0.1));+ border-radius: 4px;+ margin-top: 0.75rem;+ }++ .pi-result {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.75rem;+ background: rgba(34,197,94,0.1);+ border: 1px solid rgba(34,197,94,0.3);+ border-radius: 4px;+ margin-top: 0.75rem;+ }++ .pi-result-icon .material-symbols-outlined {+ font-size: 2rem;+ color: #22c55e;+ }++ .pi-result-path {+ font-size: 0.85rem;+ color: var(--color-text-secondary);+ margin-top: 0.25rem;+ font-family: var(--font-family-code);+ }++ @media (max-width: 500px) {+ .pi-detail-header {+ flex-direction: column;+ align-items: center;+ text-align: center;+ }+ }+ </style>+</body>+</html>diff --git a/plugins/plugin_installer/webui/install-git.html b/plugins/plugin_installer/webui/install-git.htmlnew file mode 100644index 000000000..67fd8546e--- /dev/null+++ b/plugins/plugin_installer/webui/install-git.html@@ -0,0 +1,144 @@+<html>+<head>+ <title>Install Plugin from Git</title>+ <script type="module">+ import { store } from "/plugins/plugin_installer/webui/pluginInstallStore.js";+ </script>+</head>+<body>+ <div x-data>+ <template x-if="$store.pluginInstallStore">+ <div x-init="$store.pluginInstallStore.resetGit()">++ <div class="pi-form-group">+ <label class="pi-label">Git Repository URL</label>+ <input type="text" class="pi-input"+ x-model="$store.pluginInstallStore.gitUrl"+ :disabled="$store.pluginInstallStore.loading"+ placeholder="https://github.com/user/my-plugin.git">+ </div>++ <div class="pi-form-group">+ <label class="pi-label">Access Token <span class="pi-optional">(optional, for private repos)</span></label>+ <input type="password" class="pi-input"+ x-model="$store.pluginInstallStore.gitToken"+ :disabled="$store.pluginInstallStore.loading"+ placeholder="ghp_xxxx or glpat-xxxx">+ <div class="pi-hint">Token is used only for cloning and is not stored.</div>+ </div>++ <div class="pi-actions">+ <button class="button confirm"+ @click="$store.pluginInstallStore.installGit()"+ :disabled="$store.pluginInstallStore.loading || !$store.pluginInstallStore.gitUrl.trim()">+ <template x-if="$store.pluginInstallStore.loading">+ <span class="pi-button-loading">+ <span class="spinner"></span>+ <span x-text="$store.pluginInstallStore.loadingMessage || 'Cloning...'"></span>+ </span>+ </template>+ <template x-if="!$store.pluginInstallStore.loading">+ <span>+ <span class="icon material-symbols-outlined">terminal</span> Clone & Install+ </span>+ </template>+ </button>+ </div>++ <div x-show="$store.pluginInstallStore.error" class="pi-error">+ <span x-text="$store.pluginInstallStore.error"></span>+ </div>++ <div x-show="$store.pluginInstallStore.result" class="pi-result">+ <div class="pi-result-icon">+ <span class="material-symbols-outlined">check_circle</span>+ </div>+ <div class="pi-result-text">+ <strong x-text="'Plugin installed: ' + ($store.pluginInstallStore.result?.title || $store.pluginInstallStore.result?.plugin_name || '')"></strong>+ <div class="pi-result-path" x-text="$store.pluginInstallStore.result?.path || ''"></div>+ </div>+ </div>++ </div>+ </template>+ </div>++ <style>+ .pi-form-group {+ margin-bottom: 1rem;+ }++ .pi-label {+ display: block;+ font-weight: 600;+ margin-bottom: 0.35rem;+ }++ .pi-optional {+ font-weight: 400;+ color: var(--color-text-secondary);+ font-size: 0.85rem;+ }++ .pi-input {+ width: 100%;+ padding: 0.6rem 0.75rem;+ border: 1px solid var(--color-border);+ border-radius: 4px;+ background: var(--color-bg-primary);+ color: var(--color-text-primary);+ font-size: 0.95rem;+ box-sizing: border-box;+ }++ .pi-hint {+ margin-top: 0.35rem;+ font-size: 0.8rem;+ color: var(--color-text-secondary);+ }++ .pi-actions {+ display: flex;+ justify-content: flex-start;+ margin: 1rem 0;+ }++ .pi-button-loading {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ }++ .pi-error {+ color: var(--color-error);+ padding: 0.75rem;+ background: var(--color-error-bg, rgba(239,68,68,0.1));+ border-radius: 4px;+ margin-top: 0.75rem;+ }++ .pi-result {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.75rem;+ background: rgba(34,197,94,0.1);+ border: 1px solid rgba(34,197,94,0.3);+ border-radius: 4px;+ margin-top: 0.75rem;+ }++ .pi-result-icon .material-symbols-outlined {+ font-size: 2rem;+ color: #22c55e;+ }++ .pi-result-path {+ font-size: 0.85rem;+ color: var(--color-text-secondary);+ margin-top: 0.25rem;+ font-family: var(--font-family-code);+ }+ </style>+</body>+</html>diff --git a/plugins/plugin_installer/webui/install-index.html b/plugins/plugin_installer/webui/install-index.htmlnew file mode 100644index 000000000..2845de973--- /dev/null+++ b/plugins/plugin_installer/webui/install-index.html@@ -0,0 +1,246 @@+<html>+<head>+ <title>Browse Plugins</title>+ <script type="module">+ import { store } from "/plugins/plugin_installer/webui/pluginInstallStore.js";+ </script>+</head>+<body>+ <div x-data>+ <template x-if="$store.pluginInstallStore">+ <div x-init="$store.pluginInstallStore.resetIndex(); $store.pluginInstallStore.fetchIndex()">++ <!-- Search & Sort Bar -->+ <div class="pi-index-toolbar">+ <input type="text" class="pi-search-input"+ x-model="$store.pluginInstallStore.search"+ @input="$store.pluginInstallStore.page = 1"+ placeholder="Search plugins...">+ <select class="pi-sort-select"+ x-model="$store.pluginInstallStore.sortBy">+ <option value="stars">Sort by Stars</option>+ <option value="name">Sort by Name</option>+ </select>+ </div>++ <!-- Loading -->+ <div x-show="$store.pluginInstallStore.loading" class="pi-loading">+ <span x-text="$store.pluginInstallStore.loadingMessage || 'Loading...'"></span>+ </div>++ <!-- Error -->+ <div x-show="$store.pluginInstallStore.error && !$store.pluginInstallStore.loading" class="pi-error">+ <span x-text="$store.pluginInstallStore.error"></span>+ </div>++ <!-- Plugin Grid -->+ <div x-show="$store.pluginInstallStore.index && !$store.pluginInstallStore.loading" class="pi-grid">+ <template x-for="plugin in $store.pluginInstallStore.paginatedPlugins" :key="plugin.key">+ <div class="pi-card" @click="$store.pluginInstallStore.openDetail(plugin)">+ <div class="pi-card-thumb">+ <template x-if="plugin.thumbnail">+ <img :src="plugin.thumbnail" :alt="plugin.title" loading="lazy">+ </template>+ <template x-if="!plugin.thumbnail">+ <span class="material-symbols-outlined pi-card-placeholder">extension</span>+ </template>+ </div>+ <div class="pi-card-body">+ <div class="pi-card-title">+ <span x-text="plugin.title || plugin.key"></span>+ <template x-if="plugin.installed">+ <span class="pi-badge-installed">Installed</span>+ </template>+ </div>+ <div class="pi-card-desc" x-text="$store.pluginInstallStore.truncate(plugin.description, 100)"></div>+ </div>+ <div class="pi-card-footer">+ <span class="pi-stars">+ <span class="material-symbols-outlined" style="font-size:0.9rem">star</span>+ <span x-text="plugin.stars || 0"></span>+ </span>+ </div>+ </div>+ </template>+ </div>++ <!-- Empty state -->+ <div x-show="$store.pluginInstallStore.index && !$store.pluginInstallStore.loading && $store.pluginInstallStore.filteredPlugins.length === 0"+ class="pi-empty">+ No plugins found matching your search.+ </div>++ <!-- Pagination -->+ <div x-show="$store.pluginInstallStore.totalPages > 1" class="pi-pagination">+ <button class="button"+ :disabled="$store.pluginInstallStore.page <= 1"+ @click="$store.pluginInstallStore.setPage($store.pluginInstallStore.page - 1)">+ <span class="material-symbols-outlined">chevron_left</span>+ </button>+ <span class="pi-page-info"+ x-text="$store.pluginInstallStore.page + ' / ' + $store.pluginInstallStore.totalPages">+ </span>+ <button class="button"+ :disabled="$store.pluginInstallStore.page >= $store.pluginInstallStore.totalPages"+ @click="$store.pluginInstallStore.setPage($store.pluginInstallStore.page + 1)">+ <span class="material-symbols-outlined">chevron_right</span>+ </button>+ </div>++ </div>+ </template>+ </div>++ <style>+ .pi-index-toolbar {+ display: flex;+ gap: 0.5rem;+ margin-bottom: 1rem;+ }++ .pi-search-input {+ flex: 1;+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--color-border);+ border-radius: 4px;+ background: var(--color-bg-primary);+ color: var(--color-text-primary);+ font-size: 0.95rem;+ }++ .pi-sort-select {+ padding: 0.5rem;+ border: 1px solid var(--color-border);+ border-radius: 4px;+ background: var(--color-bg-primary);+ color: var(--color-text-primary);+ font-size: 0.9rem;+ }++ .pi-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: 0.75rem;+ }++ .pi-card {+ border: 1px solid var(--color-border);+ border-radius: 6px;+ background: var(--color-background);+ cursor: pointer;+ transition: border-color 0.15s, box-shadow 0.15s;+ display: flex;+ flex-direction: column;+ overflow: hidden;+ }++ .pi-card:hover {+ border-color: var(--color-highlight);+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);+ }++ .pi-card-thumb {+ width: 100%;+ height: 120px;+ overflow: hidden;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--color-panel);+ }++ .pi-card-thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }++ .pi-card-placeholder {+ font-size: 3rem;+ color: var(--color-text-muted);+ }++ .pi-card-body {+ padding: 0.6rem 0.75rem;+ flex: 1;+ }++ .pi-card-title {+ font-weight: 600;+ font-size: 0.95rem;+ display: flex;+ align-items: center;+ gap: 0.4rem;+ flex-wrap: wrap;+ }++ .pi-badge-installed {+ font-size: 0.7rem;+ font-weight: 600;+ padding: 0.1rem 0.4rem;+ border-radius: 3px;+ background: rgba(34,197,94,0.2);+ color: #22c55e;+ }++ .pi-card-desc {+ font-size: 0.8rem;+ color: var(--color-text-secondary);+ margin-top: 0.3rem;+ line-height: 1.3;+ }++ .pi-card-footer {+ padding: 0.4rem 0.75rem;+ border-top: 1px solid var(--color-border);+ font-size: 0.8rem;+ color: var(--color-text-secondary);+ }++ .pi-stars {+ display: inline-flex;+ align-items: center;+ gap: 0.2rem;+ }++ .pi-pagination {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.75rem;+ margin-top: 1rem;+ padding: 0.5rem 0;+ }++ .pi-page-info {+ font-size: 0.9rem;+ color: var(--color-text-secondary);+ }++ .pi-loading {+ text-align: center;+ padding: 2rem;+ color: var(--color-text-secondary);+ }++ .pi-error {+ color: var(--color-error);+ padding: 0.75rem;+ background: var(--color-error-bg, rgba(239,68,68,0.1));+ border-radius: 4px;+ }++ .pi-empty {+ text-align: center;+ padding: 2rem;+ color: var(--color-text-secondary);+ }++ @media (max-width: 500px) {+ .pi-grid {+ grid-template-columns: 1fr;+ }+ }+ </style>+</body>+</html>diff --git a/plugins/plugin_installer/webui/install-zip.html b/plugins/plugin_installer/webui/install-zip.htmlnew file mode 100644index 000000000..a75e14f54--- /dev/null+++ b/plugins/plugin_installer/webui/install-zip.html@@ -0,0 +1,129 @@+<html>+<head>+ <title>Install Plugin from ZIP</title>+ <script type="module">+ import { store } from "/plugins/plugin_installer/webui/pluginInstallStore.js";+ </script>+</head>+<body>+ <div x-data>+ <template x-if="$store.pluginInstallStore">+ <div x-init="$store.pluginInstallStore.resetZip()">++ <div class="pi-upload-section">+ <label for="plugin-zip-file" class="pi-upload-btn button confirm"+ :class="{ 'pi-has-file': $store.pluginInstallStore.zipFile }">+ <span class="icon material-symbols-outlined">upload_file</span>+ <span x-text="$store.pluginInstallStore.zipFileName || 'Select Plugin ZIP File'"></span>+ </label>+ <input type="file" id="plugin-zip-file" accept=".zip" style="display:none"+ @change="$store.pluginInstallStore.handleFileUpload($event)">+ <div class="pi-hint">+ The ZIP should contain a folder with a plugin.yaml file.+ </div>+ </div>++ <div x-show="$store.pluginInstallStore.zipFile" class="pi-actions">+ <button class="button confirm"+ @click="$store.pluginInstallStore.installZip()"+ :disabled="$store.pluginInstallStore.loading">+ <span class="icon material-symbols-outlined">download</span> Install Plugin+ </button>+ </div>++ <div x-show="$store.pluginInstallStore.loading" class="pi-loading">+ <span x-text="$store.pluginInstallStore.loadingMessage || 'Processing...'"></span>+ </div>++ <div x-show="$store.pluginInstallStore.error" class="pi-error">+ <span x-text="$store.pluginInstallStore.error"></span>+ </div>++ <div x-show="$store.pluginInstallStore.result" class="pi-result">+ <div class="pi-result-icon">+ <span class="material-symbols-outlined">check_circle</span>+ </div>+ <div class="pi-result-text">+ <strong x-text="'Plugin installed: ' + ($store.pluginInstallStore.result?.title || $store.pluginInstallStore.result?.plugin_name || '')"></strong>+ <div class="pi-result-path" x-text="$store.pluginInstallStore.result?.path || ''"></div>+ </div>+ </div>++ </div>+ </template>+ </div>++ <style>+ .pi-upload-section {+ text-align: center;+ padding: 2rem 1rem;+ border: 2px dashed var(--color-border);+ border-radius: 8px;+ margin-bottom: 1rem;+ }++ .pi-upload-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.75rem 1.5rem;+ font-size: 1rem;+ cursor: pointer;+ }++ .pi-upload-btn.pi-has-file {+ background: var(--color-panel);+ border-color: var(--color-highlight);+ }++ .pi-hint {+ margin-top: 0.75rem;+ font-size: 0.85rem;+ color: var(--color-text-secondary);+ }++ .pi-actions {+ display: flex;+ justify-content: center;+ margin: 1rem 0;+ }++ .pi-loading {+ text-align: center;+ padding: 1rem;+ color: var(--color-text-secondary);+ }++ .pi-error {+ color: var(--color-error);+ padding: 0.75rem;+ background: var(--color-error-bg, rgba(239,68,68,0.1));+ border-radius: 4px;+ margin-top: 0.75rem;+ }++ .pi-result {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.75rem;+ background: rgba(34,197,94,0.1);+ border: 1px solid rgba(34,197,94,0.3);+ border-radius: 4px;+ margin-top: 0.75rem;+ }++ .pi-result-icon .material-symbols-outlined {+ font-size: 2rem;+ color: #22c55e;+ }++ .pi-result-path {+ font-size: 0.85rem;+ color: var(--color-text-secondary);+ margin-top: 0.25rem;+ font-family: var(--font-family-code);+ }+ </style>+</body>+</html>diff --git a/plugins/plugin_installer/webui/pluginInstallStore.js b/plugins/plugin_installer/webui/pluginInstallStore.jsnew file mode 100644index 000000000..8208b6aae--- /dev/null+++ b/plugins/plugin_installer/webui/pluginInstallStore.js@@ -0,0 +1,311 @@+import { createStore } from "/js/AlpineStore.js";+import * as api from "/js/api.js";+import { showConfirmDialog } from "/js/confirmDialog.js";++const PLUGIN_API = "plugins/plugin_installer/plugin_install";+const PER_PAGE = 20;++const SECURITY_WARNING = {+ title: "Security Warning",+ message: `+ <p><strong>Installing plugins from untrusted sources may pose security risks:</strong></p>+ <ul style="margin: 0.75em 0; padding-left: 1.5em;">+ <li>Malicious code execution</li>+ <li>Exposure of sensitive data</li>+ <li>System compromise</li>+ </ul>+ <p style="margin-top: 0.75em;">Only install plugins from sources you trust.</p>+ `,+ type: "warning",+ confirmText: "Install Anyway",+ cancelText: "Cancel",+};++const model = {+ // ZIP install state+ zipFile: null,+ zipFileName: "",++ // Git install state+ gitUrl: "",+ gitToken: "",++ // Index state+ index: null,+ installedPlugins: [],+ search: "",+ page: 1,+ sortBy: "stars",+ selectedPlugin: null,++ // Shared state+ loading: false,+ loadingMessage: "",+ error: "",+ result: null,++ // ── ZIP Install ──────────────────────────────++ handleFileUpload(event) {+ const file = event.target.files[0];+ if (!file) return;+ this.zipFile = file;+ this.zipFileName = file.name;+ this.error = "";+ this.result = null;+ },++ async installZip() {+ if (!this.zipFile) {+ this.error = "Please select a ZIP file first";+ return;+ }++ const confirmed = await showConfirmDialog(SECURITY_WARNING);+ if (!confirmed) return;++ try {+ this.loading = true;+ this.loadingMessage = "Installing plugin from ZIP...";+ this.error = "";+ this.result = null;++ const formData = new FormData();+ formData.append("action", "install_zip");+ formData.append("plugin_file", this.zipFile);++ const response = await api.fetchApi(PLUGIN_API, {+ method: "POST",+ body: formData,+ });++ const data = await response.json();+ if (!data.success) {+ this.error = data.error || "Installation failed";+ return;+ }++ this.result = data;+ if (window.toastFrontendSuccess) {+ window.toastFrontendSuccess(+ `Plugin "${data.title || data.plugin_name}" installed`,+ "Plugin Installer"+ );+ }+ this._refreshPluginList();+ } catch (e) {+ this.error = `Installation error: ${e.message}`;+ } finally {+ this.loading = false;+ this.loadingMessage = "";+ }+ },++ // ── Git Install ──────────────────────────────++ async installGit() {+ const url = (this.gitUrl || "").trim();+ if (!url) {+ this.error = "Please enter a Git URL";+ return;+ }++ const confirmed = await showConfirmDialog(SECURITY_WARNING);+ if (!confirmed) return;++ try {+ this.loading = true;+ this.loadingMessage = "Cloning repository...";+ this.error = "";+ this.result = null;++ const data = await api.callJsonApi(PLUGIN_API, {+ action: "install_git",+ git_url: url,+ git_token: this.gitToken || "",+ });++ if (!data.success) {+ this.error = data.error || "Clone failed";+ return;+ }++ this.result = data;+ if (window.toastFrontendSuccess) {+ window.toastFrontendSuccess(+ `Plugin "${data.title || data.plugin_name}" installed`,+ "Plugin Installer"+ );+ }+ this._refreshPluginList();+ } catch (e) {+ this.error = `Clone error: ${e.message}`;+ } finally {+ this.loading = false;+ this.loadingMessage = "";+ }+ },++ // ── Index Browse ─────────────────────────────++ async fetchIndex() {+ try {+ this.loading = true;+ this.loadingMessage = "Loading plugin index...";+ this.error = "";+ this.index = null;++ const data = await api.callJsonApi(PLUGIN_API, {+ action: "fetch_index",+ });++ if (!data.success) {+ this.error = data.error || "Failed to load index";+ return;+ }++ this.index = data.index;+ this.installedPlugins = data.installed_plugins || [];+ this.page = 1;+ } catch (e) {+ this.error = `Failed to load plugin index: ${e.message}`;+ } finally {+ this.loading = false;+ this.loadingMessage = "";+ }+ },++ get pluginsList() {+ if (!this.index?.plugins) return [];+ return Object.entries(this.index.plugins).map(([key, val]) => ({+ key,+ ...val,+ installed: this.installedPlugins.includes(key),+ }));+ },++ get filteredPlugins() {+ let list = this.pluginsList;+ const q = (this.search || "").toLowerCase().trim();+ if (q) {+ list = list.filter(+ (p) =>+ (p.title || "").toLowerCase().includes(q) ||+ (p.description || "").toLowerCase().includes(q) ||+ (p.key || "").toLowerCase().includes(q) ||+ (p.tags || []).some((t) => t.toLowerCase().includes(q))+ );+ }+ if (this.sortBy === "stars") {+ list.sort((a, b) => (b.stars || 0) - (a.stars || 0));+ } else {+ list.sort((a, b) =>+ (a.title || a.key).localeCompare(b.title || b.key)+ );+ }+ return list;+ },++ get totalPages() {+ return Math.max(1, Math.ceil(this.filteredPlugins.length / PER_PAGE));+ },++ get paginatedPlugins() {+ const start = (this.page - 1) * PER_PAGE;+ return this.filteredPlugins.slice(start, start + PER_PAGE);+ },++ setPage(p) {+ this.page = Math.max(1, Math.min(p, this.totalPages));+ },++ openDetail(plugin) {+ this.selectedPlugin = plugin;+ this.error = "";+ this.result = null;+ window.openModal?.("../plugins/plugin_installer/webui/install-detail.html");+ },++ async installFromIndex(plugin) {+ if (!plugin?.github) {+ this.error = "No GitHub URL available for this plugin";+ return;+ }++ const confirmed = await showConfirmDialog(SECURITY_WARNING);+ if (!confirmed) return;++ try {+ this.loading = true;+ this.loadingMessage = `Installing ${plugin.title || plugin.key}...`;+ this.error = "";+ this.result = null;++ const data = await api.callJsonApi(PLUGIN_API, {+ action: "install_git",+ git_url: plugin.github,+ });++ if (!data.success) {+ this.error = data.error || "Installation failed";+ return;+ }++ this.result = data;+ if (!this.installedPlugins.includes(plugin.key)) {+ this.installedPlugins.push(plugin.key);+ }+ plugin.installed = true;++ if (window.toastFrontendSuccess) {+ window.toastFrontendSuccess(+ `Plugin "${data.title || data.plugin_name}" installed`,+ "Plugin Installer"+ );+ }+ this._refreshPluginList();+ } catch (e) {+ this.error = `Installation error: ${e.message}`;+ } finally {+ this.loading = false;+ this.loadingMessage = "";+ }+ },++ // ── Shared ───────────────────────────────────++ resetZip() {+ this.zipFile = null;+ this.zipFileName = "";+ this.error = "";+ this.result = null;+ },++ resetGit() {+ this.gitUrl = "";+ this.gitToken = "";+ this.error = "";+ this.result = null;+ },++ resetIndex() {+ this.search = "";+ this.page = 1;+ this.sortBy = "stars";+ this.error = "";+ this.result = null;+ this.selectedPlugin = null;+ },++ _refreshPluginList() {+ window.dispatchEvent(new CustomEvent("plugin-modal-closed"));+ },++ truncate(text, max) {+ if (!text || text.length <= max) return text || "";+ return text.substring(0, max) + "...";+ },+};++const store = createStore("pluginInstallStore", model);+export { store };