|
| 1 | +# Copyright (C) 2026 Marco Fortina |
| 2 | +# SPDX-License-Identifier: AGPL-3.0-or-later |
| 3 | + |
| 4 | +"""External plugin SDK helpers.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import json |
| 9 | +import re |
| 10 | +import zipfile |
| 11 | +from pathlib import Path |
| 12 | +from typing import Any, Dict |
| 13 | + |
| 14 | +from automax.plugins.registry import PluginRegistry, PluginRegistryError |
| 15 | + |
| 16 | +PLUGIN_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$") |
| 17 | + |
| 18 | + |
| 19 | +def plugin_module_name(plugin_name: str) -> str: |
| 20 | + """Return a safe module stem for a canonical plugin name.""" |
| 21 | + return plugin_name.replace(".", "_").replace("-", "_") |
| 22 | + |
| 23 | + |
| 24 | +def plugin_class_name(plugin_name: str) -> str: |
| 25 | + """Return a readable plugin class name for a canonical plugin name.""" |
| 26 | + parts = re.split(r"[._-]+", plugin_name) |
| 27 | + return "".join(part[:1].upper() + part[1:] for part in parts if part) + "Plugin" |
| 28 | + |
| 29 | + |
| 30 | +def resolve_plugin_output_path(output_path: str, plugin_name: str) -> Path: |
| 31 | + """Resolve the file path used by the plugin skeleton generator.""" |
| 32 | + output = Path(output_path).expanduser() |
| 33 | + if output.suffix == ".py": |
| 34 | + return output |
| 35 | + return output / f"{plugin_module_name(plugin_name)}.py" |
| 36 | + |
| 37 | + |
| 38 | +def render_plugin_skeleton(plugin_name: str) -> str: |
| 39 | + """Render a minimal external plugin implementation.""" |
| 40 | + class_name = plugin_class_name(plugin_name) |
| 41 | + return f'''# Copyright (C) 2026 Marco Fortina |
| 42 | +# SPDX-License-Identifier: AGPL-3.0-or-later |
| 43 | +
|
| 44 | +"""External Automax plugin: {plugin_name}.""" |
| 45 | +
|
| 46 | +from __future__ import annotations |
| 47 | +
|
| 48 | +from typing import Dict |
| 49 | +
|
| 50 | +from automax.core.models import ExecutionContext, PluginResult |
| 51 | +from automax.plugins.base import BasePlugin |
| 52 | +
|
| 53 | +
|
| 54 | +class {class_name}(BasePlugin): |
| 55 | + """Example external plugin implementation.""" |
| 56 | +
|
| 57 | + name = "{plugin_name}" |
| 58 | + description = "Render a deterministic external plugin response." |
| 59 | + category = "{plugin_name.split('.', 1)[0]}" |
| 60 | + required_params = ("message",) |
| 61 | + optional_params = ("changed",) |
| 62 | + parameter_schema = {{ |
| 63 | + "message": {{ |
| 64 | + "type": "string", |
| 65 | + "description": "Message returned by the plugin.", |
| 66 | + "non_empty": True, |
| 67 | + }}, |
| 68 | + "changed": {{ |
| 69 | + "type": "boolean", |
| 70 | + "default": False, |
| 71 | + "description": "Whether the plugin should report a change.", |
| 72 | + }}, |
| 73 | + }} |
| 74 | + examples = ( |
| 75 | + """- id: external\n use: {plugin_name}\n with:\n message: hello""", |
| 76 | + ) |
| 77 | + result_fields = {{ |
| 78 | + "message": "Rendered message.", |
| 79 | + "changed": "Whether the plugin reported a change.", |
| 80 | + }} |
| 81 | + supports_dry_run = True |
| 82 | + supports_check_mode = True |
| 83 | +
|
| 84 | + def execute(self, params: Dict[str, object], context: ExecutionContext) -> PluginResult: |
| 85 | + message = str(params["message"]) |
| 86 | + changed = bool(params.get("changed", False)) |
| 87 | + return PluginResult.success( |
| 88 | + changed=changed, |
| 89 | + message=message, |
| 90 | + data={{"message": message, "changed": changed}}, |
| 91 | + ) |
| 92 | +''' |
| 93 | + |
| 94 | + |
| 95 | +def create_plugin_skeleton(plugin_name: str, output_path: str, *, force: bool = False) -> Path: |
| 96 | + """Create one external plugin skeleton file.""" |
| 97 | + if not PLUGIN_NAME_RE.match(plugin_name): |
| 98 | + raise PluginRegistryError( |
| 99 | + "plugin name must be canonical, for example vendor.category.action" |
| 100 | + ) |
| 101 | + output = resolve_plugin_output_path(output_path, plugin_name) |
| 102 | + if output.exists() and not force: |
| 103 | + raise PluginRegistryError(f"plugin file already exists: {output}") |
| 104 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 105 | + output.write_text(render_plugin_skeleton(plugin_name), encoding="utf-8") |
| 106 | + return output |
| 107 | + |
| 108 | + |
| 109 | +def load_external_plugins(path: str) -> PluginRegistry: |
| 110 | + """Load external plugins only from one file or directory.""" |
| 111 | + registry = PluginRegistry() |
| 112 | + registry.load_from_paths([path]) |
| 113 | + return registry |
| 114 | + |
| 115 | + |
| 116 | +def check_external_plugin_path(path: str) -> Dict[str, Any]: |
| 117 | + """Validate external plugin loading and metadata completeness.""" |
| 118 | + registry = load_external_plugins(path) |
| 119 | + plugins = registry.describe_all() |
| 120 | + failures: list[str] = [] |
| 121 | + |
| 122 | + for plugin in plugins: |
| 123 | + name = str(plugin["name"]) |
| 124 | + if not PLUGIN_NAME_RE.match(name): |
| 125 | + failures.append(f"{name}: name must be canonical") |
| 126 | + if not plugin.get("description"): |
| 127 | + failures.append(f"{name}: description is required") |
| 128 | + if not plugin.get("category"): |
| 129 | + failures.append(f"{name}: category is required") |
| 130 | + |
| 131 | + required = list(plugin.get("required_params") or []) |
| 132 | + optional = list(plugin.get("optional_params") or []) |
| 133 | + if len(set(required)) != len(required): |
| 134 | + failures.append(f"{name}: duplicate required params") |
| 135 | + if len(set(optional)) != len(optional): |
| 136 | + failures.append(f"{name}: duplicate optional params") |
| 137 | + overlap = sorted(set(required) & set(optional)) |
| 138 | + if overlap: |
| 139 | + failures.append(f"{name}: params cannot be both required and optional: {', '.join(overlap)}") |
| 140 | + |
| 141 | + parameters = {str(item["name"]): item for item in plugin.get("parameters", [])} |
| 142 | + for param in required + optional: |
| 143 | + details = parameters.get(param) or {} |
| 144 | + if not details.get("type") or details.get("type") == "any": |
| 145 | + failures.append(f"{name}: param {param} must declare a type") |
| 146 | + if not details.get("description"): |
| 147 | + failures.append(f"{name}: param {param} must declare a description") |
| 148 | + |
| 149 | + if not plugin.get("examples"): |
| 150 | + failures.append(f"{name}: at least one example is required") |
| 151 | + if not plugin.get("result_fields"): |
| 152 | + failures.append(f"{name}: result_fields are required") |
| 153 | + |
| 154 | + return { |
| 155 | + "ok": not failures, |
| 156 | + "checked": len(plugins), |
| 157 | + "failure_count": len(failures), |
| 158 | + "failures": failures, |
| 159 | + "plugins": plugins, |
| 160 | + } |
| 161 | + |
| 162 | + |
| 163 | +def render_plugin_check_text(payload: Dict[str, Any]) -> str: |
| 164 | + """Render external plugin check results as text.""" |
| 165 | + lines = ["External plugin check:"] |
| 166 | + lines.append(f" checked: {payload['checked']}") |
| 167 | + lines.append(f" failures: {payload['failure_count']}") |
| 168 | + if payload["plugins"]: |
| 169 | + lines.append("Plugins:") |
| 170 | + for plugin in payload["plugins"]: |
| 171 | + lines.append(f" - {plugin['name']}") |
| 172 | + if payload["failures"]: |
| 173 | + lines.append("Failures:") |
| 174 | + for failure in payload["failures"]: |
| 175 | + lines.append(f" - {failure}") |
| 176 | + lines.append(f"Result: {'OK' if payload['ok'] else 'FAILED'}") |
| 177 | + return "\n".join(lines) |
| 178 | + |
| 179 | + |
| 180 | +def package_external_plugin_path(path: str, output_path: str, *, force: bool = False) -> Path: |
| 181 | + """Package external plugin sources and metadata into a ZIP archive.""" |
| 182 | + source = Path(path).expanduser().resolve() |
| 183 | + output = Path(output_path).expanduser().resolve() |
| 184 | + if output.exists() and not force: |
| 185 | + raise PluginRegistryError(f"package already exists: {output}") |
| 186 | + |
| 187 | + payload = check_external_plugin_path(str(source)) |
| 188 | + if not payload["ok"]: |
| 189 | + failures = "; ".join(str(item) for item in payload["failures"]) |
| 190 | + raise PluginRegistryError(f"external plugin check failed: {failures}") |
| 191 | + |
| 192 | + if source.is_file(): |
| 193 | + files = [source] |
| 194 | + root = source.parent |
| 195 | + elif source.is_dir(): |
| 196 | + root = source |
| 197 | + files = sorted( |
| 198 | + item for item in source.rglob("*") |
| 199 | + if item.is_file() |
| 200 | + and "__pycache__" not in item.parts |
| 201 | + and not item.name.endswith((".pyc", ".pyo")) |
| 202 | + ) |
| 203 | + else: |
| 204 | + raise PluginRegistryError(f"plugin path not found: {source}") |
| 205 | + |
| 206 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 207 | + manifest = { |
| 208 | + "format": "automax-external-plugin-package-v1", |
| 209 | + "source": str(source), |
| 210 | + "plugin_count": payload["checked"], |
| 211 | + "plugins": [plugin["name"] for plugin in payload["plugins"]], |
| 212 | + } |
| 213 | + with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive: |
| 214 | + archive.writestr("automax-plugin.json", json.dumps(manifest, indent=2, sort_keys=True) + "\n") |
| 215 | + for item in files: |
| 216 | + archive.write(item, item.relative_to(root).as_posix()) |
| 217 | + return output |
0 commit comments