modify template
This commit is contained in:
@@ -0,0 +1,324 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scaffold a plugin directory and optionally update marketplace.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
MAX_PLUGIN_NAME_LENGTH = 64
|
||||
DEFAULT_INSTALL_POLICY = "AVAILABLE"
|
||||
DEFAULT_AUTH_POLICY = "ON_INSTALL"
|
||||
DEFAULT_CATEGORY = "Productivity"
|
||||
DEFAULT_MARKETPLACE_NAME = "personal"
|
||||
VALID_INSTALL_POLICIES = {"NOT_AVAILABLE", "AVAILABLE", "INSTALLED_BY_DEFAULT"}
|
||||
VALID_AUTH_POLICIES = {"ON_INSTALL", "ON_USE"}
|
||||
DEFAULT_PLUGIN_PARENT = Path.home() / "plugins"
|
||||
DEFAULT_MARKETPLACE_PATH = Path.home() / ".agents" / "plugins" / "marketplace.json"
|
||||
|
||||
|
||||
def normalize_plugin_name(plugin_name: str) -> str:
|
||||
"""Normalize a plugin name to lowercase hyphen-case."""
|
||||
normalized = plugin_name.strip().lower()
|
||||
normalized = re.sub(r"[^a-z0-9]+", "-", normalized)
|
||||
normalized = normalized.strip("-")
|
||||
normalized = re.sub(r"-{2,}", "-", normalized)
|
||||
return normalized
|
||||
|
||||
|
||||
def validate_plugin_name(plugin_name: str) -> None:
|
||||
if not plugin_name:
|
||||
raise ValueError("Plugin name must include at least one letter or digit.")
|
||||
if len(plugin_name) > MAX_PLUGIN_NAME_LENGTH:
|
||||
raise ValueError(
|
||||
f"Plugin name '{plugin_name}' is too long ({len(plugin_name)} characters). "
|
||||
f"Maximum is {MAX_PLUGIN_NAME_LENGTH} characters."
|
||||
)
|
||||
|
||||
|
||||
def validate_marketplace_name(marketplace_name: str) -> None:
|
||||
if not marketplace_name:
|
||||
raise ValueError("Marketplace name must include at least one letter or digit.")
|
||||
if re.fullmatch(r"[A-Za-z0-9_-]+", marketplace_name) is None:
|
||||
raise ValueError(
|
||||
"Marketplace name may only contain ASCII letters, digits, `_`, and `-`."
|
||||
)
|
||||
|
||||
|
||||
def display_name_from_plugin_name(plugin_name: str) -> str:
|
||||
return " ".join(part.capitalize() for part in re.split(r"[-_]+", plugin_name))
|
||||
|
||||
|
||||
def build_plugin_json(plugin_name: str, *, with_mcp: bool, with_apps: bool) -> dict[str, Any]:
|
||||
display_name = display_name_from_plugin_name(plugin_name)
|
||||
payload: dict[str, Any] = {
|
||||
"name": plugin_name,
|
||||
"version": "0.1.0",
|
||||
"description": f"{display_name} plugin",
|
||||
"author": {
|
||||
"name": "Local developer",
|
||||
},
|
||||
"skills": "./skills/",
|
||||
"interface": {
|
||||
"displayName": display_name,
|
||||
"shortDescription": f"Use {display_name} in Codex.",
|
||||
"longDescription": f"{display_name} adds a local Codex plugin scaffold.",
|
||||
"developerName": "Local developer",
|
||||
"category": DEFAULT_CATEGORY,
|
||||
"capabilities": [],
|
||||
"defaultPrompt": f"Help me use {display_name}.",
|
||||
},
|
||||
}
|
||||
if with_mcp:
|
||||
payload["mcpServers"] = "./.mcp.json"
|
||||
if with_apps:
|
||||
payload["apps"] = "./.app.json"
|
||||
return payload
|
||||
|
||||
|
||||
def build_marketplace_entry(
|
||||
plugin_name: str,
|
||||
install_policy: str,
|
||||
auth_policy: str,
|
||||
category: str,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"name": plugin_name,
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": f"./plugins/{plugin_name}",
|
||||
},
|
||||
"policy": {
|
||||
"installation": install_policy,
|
||||
"authentication": auth_policy,
|
||||
},
|
||||
"category": category,
|
||||
}
|
||||
|
||||
|
||||
def load_json(path: Path) -> dict[str, Any]:
|
||||
with path.open() as handle:
|
||||
return json.load(handle)
|
||||
|
||||
|
||||
def build_default_marketplace(marketplace_name: str) -> dict[str, Any]:
|
||||
return {
|
||||
"name": marketplace_name,
|
||||
"interface": {
|
||||
"displayName": display_name_from_plugin_name(marketplace_name),
|
||||
},
|
||||
"plugins": [],
|
||||
}
|
||||
|
||||
|
||||
def validate_marketplace_interface(payload: dict[str, Any]) -> None:
|
||||
interface = payload.get("interface")
|
||||
if interface is not None and not isinstance(interface, dict):
|
||||
raise ValueError("marketplace.json field 'interface' must be an object.")
|
||||
|
||||
|
||||
def update_marketplace_json(
|
||||
marketplace_path: Path,
|
||||
marketplace_name: str | None,
|
||||
plugin_name: str,
|
||||
install_policy: str,
|
||||
auth_policy: str,
|
||||
category: str,
|
||||
force: bool,
|
||||
) -> None:
|
||||
if marketplace_path.exists():
|
||||
payload = load_json(marketplace_path)
|
||||
else:
|
||||
payload = build_default_marketplace(marketplace_name or DEFAULT_MARKETPLACE_NAME)
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError(f"{marketplace_path} must contain a JSON object.")
|
||||
|
||||
validate_marketplace_interface(payload)
|
||||
|
||||
existing_marketplace_name = payload.get("name")
|
||||
if marketplace_name is not None:
|
||||
if not isinstance(existing_marketplace_name, str) or not existing_marketplace_name.strip():
|
||||
raise ValueError(f"{marketplace_path} must contain a non-empty string 'name'.")
|
||||
if existing_marketplace_name != marketplace_name:
|
||||
raise ValueError(
|
||||
f"{marketplace_path} already uses marketplace name "
|
||||
f"'{existing_marketplace_name}'. Create a new marketplace file to use "
|
||||
f"'{marketplace_name}' instead."
|
||||
)
|
||||
|
||||
plugins = payload.setdefault("plugins", [])
|
||||
if not isinstance(plugins, list):
|
||||
raise ValueError(f"{marketplace_path} field 'plugins' must be an array.")
|
||||
|
||||
new_entry = build_marketplace_entry(plugin_name, install_policy, auth_policy, category)
|
||||
|
||||
for index, entry in enumerate(plugins):
|
||||
if isinstance(entry, dict) and entry.get("name") == plugin_name:
|
||||
if not force:
|
||||
raise FileExistsError(
|
||||
f"Marketplace entry '{plugin_name}' already exists in {marketplace_path}. "
|
||||
"Use --force to overwrite that entry."
|
||||
)
|
||||
plugins[index] = new_entry
|
||||
break
|
||||
else:
|
||||
plugins.append(new_entry)
|
||||
|
||||
write_json(marketplace_path, payload, force=True)
|
||||
|
||||
|
||||
def write_json(path: Path, data: dict, force: bool) -> None:
|
||||
if path.exists() and not force:
|
||||
raise FileExistsError(f"{path} already exists. Use --force to overwrite.")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w") as handle:
|
||||
json.dump(data, handle, indent=2)
|
||||
handle.write("\n")
|
||||
|
||||
|
||||
def create_stub_file(path: Path, payload: dict, force: bool) -> None:
|
||||
if path.exists() and not force:
|
||||
return
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w") as handle:
|
||||
json.dump(payload, handle, indent=2)
|
||||
handle.write("\n")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Create a plugin skeleton with a validation-ready plugin.json."
|
||||
)
|
||||
parser.add_argument("plugin_name")
|
||||
parser.add_argument(
|
||||
"--path",
|
||||
default=str(DEFAULT_PLUGIN_PARENT),
|
||||
help=(
|
||||
"Parent directory for plugin creation (defaults to <home>/plugins). "
|
||||
"Pass an explicit repo path only when a repo/team plugin is intended."
|
||||
),
|
||||
)
|
||||
parser.add_argument("--with-skills", action="store_true", help="Create skills/ directory")
|
||||
parser.add_argument("--with-hooks", action="store_true", help="Create hooks/ directory")
|
||||
parser.add_argument("--with-scripts", action="store_true", help="Create scripts/ directory")
|
||||
parser.add_argument("--with-assets", action="store_true", help="Create assets/ directory")
|
||||
parser.add_argument("--with-mcp", action="store_true", help="Create .mcp.json placeholder")
|
||||
parser.add_argument("--with-apps", action="store_true", help="Create .app.json placeholder")
|
||||
parser.add_argument(
|
||||
"--with-marketplace",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Create or update <home>/.agents/plugins/marketplace.json by default. "
|
||||
"Marketplace entries always point to ./plugins/<plugin-name> relative to the "
|
||||
"marketplace root."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--marketplace-path",
|
||||
default=str(DEFAULT_MARKETPLACE_PATH),
|
||||
help=(
|
||||
"Path to marketplace.json (defaults to <home>/.agents/plugins/marketplace.json). "
|
||||
"Pass a repo-rooted marketplace path only when a repo/team plugin is intended."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--marketplace-name",
|
||||
help=(
|
||||
"Marketplace name to seed into a new marketplace.json. Use this only when the default "
|
||||
"'personal' marketplace name is already taken and you need a different new marketplace."
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--install-policy",
|
||||
default=DEFAULT_INSTALL_POLICY,
|
||||
choices=sorted(VALID_INSTALL_POLICIES),
|
||||
help="Marketplace policy.installation value",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--auth-policy",
|
||||
default=DEFAULT_AUTH_POLICY,
|
||||
choices=sorted(VALID_AUTH_POLICIES),
|
||||
help="Marketplace policy.authentication value",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--category",
|
||||
default=DEFAULT_CATEGORY,
|
||||
help="Marketplace category value",
|
||||
)
|
||||
parser.add_argument("--force", action="store_true", help="Overwrite existing files")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
raw_plugin_name = args.plugin_name
|
||||
plugin_name = normalize_plugin_name(raw_plugin_name)
|
||||
if plugin_name != raw_plugin_name:
|
||||
print(f"Note: Normalized plugin name from '{raw_plugin_name}' to '{plugin_name}'.")
|
||||
validate_plugin_name(plugin_name)
|
||||
marketplace_name = None
|
||||
if args.marketplace_name is not None:
|
||||
marketplace_name = args.marketplace_name.strip()
|
||||
validate_marketplace_name(marketplace_name)
|
||||
|
||||
plugin_root = (Path(args.path).expanduser().resolve() / plugin_name)
|
||||
plugin_root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
plugin_json_path = plugin_root / ".codex-plugin" / "plugin.json"
|
||||
write_json(
|
||||
plugin_json_path,
|
||||
build_plugin_json(plugin_name, with_mcp=args.with_mcp, with_apps=args.with_apps),
|
||||
args.force,
|
||||
)
|
||||
|
||||
optional_directories = {
|
||||
"skills": args.with_skills,
|
||||
"hooks": args.with_hooks,
|
||||
"scripts": args.with_scripts,
|
||||
"assets": args.with_assets,
|
||||
}
|
||||
for folder, enabled in optional_directories.items():
|
||||
if enabled:
|
||||
(plugin_root / folder).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if args.with_mcp:
|
||||
create_stub_file(
|
||||
plugin_root / ".mcp.json",
|
||||
{"mcpServers": {}},
|
||||
args.force,
|
||||
)
|
||||
|
||||
if args.with_apps:
|
||||
create_stub_file(
|
||||
plugin_root / ".app.json",
|
||||
{
|
||||
"apps": {},
|
||||
},
|
||||
args.force,
|
||||
)
|
||||
|
||||
if args.with_marketplace:
|
||||
marketplace_path = Path(args.marketplace_path).expanduser().resolve()
|
||||
update_marketplace_json(
|
||||
marketplace_path,
|
||||
marketplace_name,
|
||||
plugin_name,
|
||||
args.install_policy,
|
||||
args.auth_policy,
|
||||
args.category,
|
||||
args.force,
|
||||
)
|
||||
|
||||
print(f"Created plugin scaffold: {plugin_root}")
|
||||
print(f"plugin manifest: {plugin_json_path}")
|
||||
if args.with_marketplace:
|
||||
print(f"marketplace manifest: {marketplace_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print the top-level marketplace name from any marketplace.json file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def default_marketplace_path() -> Path:
|
||||
return Path.home() / ".agents" / "plugins" / "marketplace.json"
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Print the top-level marketplace name from marketplace.json. Defaults to the personal "
|
||||
"marketplace path under the current home directory."
|
||||
)
|
||||
)
|
||||
parser.add_argument(
|
||||
"--marketplace-path",
|
||||
default=str(default_marketplace_path()),
|
||||
help="Path to marketplace.json",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
marketplace_path = Path(args.marketplace_path).expanduser().resolve()
|
||||
payload = json.loads(marketplace_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError(f"{marketplace_path} must contain a JSON object.")
|
||||
name = payload.get("name")
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
raise ValueError(f"{marketplace_path} must contain a non-empty string 'name'.")
|
||||
print(name.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as err: # noqa: BLE001 - CLI should surface a single clear message.
|
||||
print(str(err), file=sys.stderr)
|
||||
raise SystemExit(1) from err
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rewrite a local plugin version to a single Codex cachebuster suffix."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
CACHEBUSTER_PREFIX = "codex"
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Rewrite a local plugin's version so it preserves everything before '+' and uses "
|
||||
"a single +codex.<cachebuster> suffix."
|
||||
)
|
||||
)
|
||||
parser.add_argument("plugin_path", help="Path to the plugin root directory")
|
||||
parser.add_argument(
|
||||
"--cachebuster",
|
||||
help="Optional cachebuster token to embed in the plugin version",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
plugin_root = Path(args.plugin_path).expanduser().resolve()
|
||||
manifest_path = plugin_root / ".codex-plugin" / "plugin.json"
|
||||
manifest = load_manifest(manifest_path)
|
||||
|
||||
version = manifest.get("version")
|
||||
if not isinstance(version, str) or not version.strip():
|
||||
raise ValueError(f"{manifest_path} must contain a non-empty string 'version'.")
|
||||
cachebuster = sanitize_cachebuster(args.cachebuster or default_cachebuster())
|
||||
next_version = with_cachebuster(version, cachebuster)
|
||||
manifest["version"] = next_version
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
print(f"Updated plugin version: {version} -> {next_version}")
|
||||
|
||||
|
||||
def load_manifest(manifest_path: Path) -> dict[str, object]:
|
||||
if not manifest_path.is_file():
|
||||
raise FileNotFoundError(f"missing manifest: {manifest_path}")
|
||||
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError(f"{manifest_path} must contain a JSON object.")
|
||||
return payload
|
||||
def sanitize_cachebuster(value: str) -> str:
|
||||
sanitized = re.sub(r"[^a-z0-9-]+", "-", value.strip().lower())
|
||||
sanitized = re.sub(r"-{2,}", "-", sanitized).strip("-")
|
||||
if not sanitized:
|
||||
raise ValueError("Cachebuster must contain at least one letter or digit.")
|
||||
return sanitized
|
||||
|
||||
|
||||
def default_cachebuster() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")
|
||||
|
||||
|
||||
def with_cachebuster(version: str, cachebuster: str) -> str:
|
||||
version_prefix = version.split("+", 1)[0]
|
||||
return f"{version_prefix}+{CACHEBUSTER_PREFIX}.{cachebuster}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as err: # noqa: BLE001 - CLI should surface a single clear message.
|
||||
print(str(err), file=sys.stderr)
|
||||
raise SystemExit(1) from err
|
||||
@@ -0,0 +1,586 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate a generated plugin against the plugin ingestion contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
TODO_MARKER = "[TODO:"
|
||||
SEMVER_RE = re.compile(
|
||||
r"^(0|[1-9]\d*)\."
|
||||
r"(0|[1-9]\d*)\."
|
||||
r"(0|[1-9]\d*)"
|
||||
r"(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\."
|
||||
r"(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?"
|
||||
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
|
||||
)
|
||||
HEX_COLOR_RE = re.compile(r"^#[0-9A-F]{6}$", re.IGNORECASE)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Validate a local Codex plugin.")
|
||||
parser.add_argument("plugin_path", help="Path to the plugin root directory")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
plugin_root = Path(args.plugin_path).expanduser().resolve()
|
||||
errors = validate_plugin(plugin_root)
|
||||
if errors:
|
||||
print("Plugin validation failed:")
|
||||
for error in errors:
|
||||
print(f"- {error}")
|
||||
raise SystemExit(1)
|
||||
print(f"Plugin validation passed: {plugin_root}")
|
||||
|
||||
|
||||
def validate_plugin(plugin_root: Path) -> list[str]:
|
||||
errors: list[str] = []
|
||||
manifest_path = plugin_root / ".codex-plugin" / "plugin.json"
|
||||
manifest = load_json_object(manifest_path, errors)
|
||||
if manifest is None:
|
||||
return errors
|
||||
|
||||
reject_todo_markers(manifest, "$", errors)
|
||||
validate_manifest_shape(plugin_root, manifest, errors)
|
||||
return errors
|
||||
|
||||
|
||||
def load_json_object(path: Path, errors: list[str]) -> dict[str, Any] | None:
|
||||
if not path.is_file():
|
||||
errors.append("missing `.codex-plugin/plugin.json`")
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except OSError:
|
||||
errors.append("unable to read `.codex-plugin/plugin.json`")
|
||||
return None
|
||||
except json.JSONDecodeError:
|
||||
errors.append("`.codex-plugin/plugin.json` must be valid JSON")
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
errors.append("`.codex-plugin/plugin.json` must contain a JSON object")
|
||||
return None
|
||||
return payload
|
||||
|
||||
|
||||
def reject_todo_markers(value: Any, path: str, errors: list[str]) -> None:
|
||||
if isinstance(value, str):
|
||||
if TODO_MARKER in value:
|
||||
errors.append(f"{path} still contains a `[TODO: ...]` placeholder")
|
||||
return
|
||||
if isinstance(value, list):
|
||||
for index, item in enumerate(value):
|
||||
reject_todo_markers(item, f"{path}[{index}]", errors)
|
||||
return
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
reject_todo_markers(item, f"{path}.{key}", errors)
|
||||
|
||||
|
||||
def validate_manifest_shape(
|
||||
plugin_root: Path,
|
||||
manifest: dict[str, Any],
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
allowed_keys = {
|
||||
"id",
|
||||
"name",
|
||||
"version",
|
||||
"description",
|
||||
"skills",
|
||||
"apps",
|
||||
"mcpServers",
|
||||
"interface",
|
||||
"author",
|
||||
"homepage",
|
||||
"repository",
|
||||
"license",
|
||||
"keywords",
|
||||
}
|
||||
for key in sorted(set(manifest) - allowed_keys):
|
||||
errors.append(f"plugin.json field `{key}` is not accepted by plugin validation")
|
||||
|
||||
validate_optional_non_empty_string(manifest, "id", errors)
|
||||
require_non_empty_string(manifest, "name", errors)
|
||||
version = require_non_empty_string(manifest, "version", errors)
|
||||
if version is not None and SEMVER_RE.fullmatch(version) is None:
|
||||
errors.append("plugin.json field `version` must be strict semver")
|
||||
require_non_empty_string(manifest, "description", errors)
|
||||
|
||||
author = require_object(manifest, "author", errors)
|
||||
if author is not None:
|
||||
reject_unknown_fields(author, {"name", "email", "url"}, "author", errors)
|
||||
require_non_empty_string(author, "name", errors, prefix="author")
|
||||
validate_optional_non_empty_string(author, "email", errors, prefix="author")
|
||||
validate_optional_https_url(author, "url", errors, prefix="author")
|
||||
|
||||
validate_optional_contract_path(manifest, "skills", "skills", errors)
|
||||
validate_optional_contract_path(manifest, "apps", ".app.json", errors)
|
||||
validate_optional_contract_path(manifest, "mcpServers", ".mcp.json", errors)
|
||||
|
||||
if manifest.get("apps") is not None:
|
||||
validate_app_manifest(
|
||||
plugin_root / ".app.json",
|
||||
errors,
|
||||
)
|
||||
if manifest.get("mcpServers") is not None:
|
||||
validate_mcp_manifest(
|
||||
plugin_root / ".mcp.json",
|
||||
errors,
|
||||
)
|
||||
validate_skill_manifests(plugin_root, errors)
|
||||
|
||||
interface = require_object(manifest, "interface", errors)
|
||||
if interface is None:
|
||||
return
|
||||
reject_unknown_fields(
|
||||
interface,
|
||||
{
|
||||
"displayName",
|
||||
"shortDescription",
|
||||
"longDescription",
|
||||
"developerName",
|
||||
"category",
|
||||
"capabilities",
|
||||
"websiteURL",
|
||||
"privacyPolicyURL",
|
||||
"termsOfServiceURL",
|
||||
"brandColor",
|
||||
"composerIcon",
|
||||
"logo",
|
||||
"screenshots",
|
||||
"defaultPrompt",
|
||||
"default_prompt",
|
||||
},
|
||||
"interface",
|
||||
errors,
|
||||
)
|
||||
for field in (
|
||||
"displayName",
|
||||
"shortDescription",
|
||||
"longDescription",
|
||||
"developerName",
|
||||
"category",
|
||||
):
|
||||
require_non_empty_string(interface, field, errors, prefix="interface")
|
||||
if "defaultPrompt" not in interface and "default_prompt" not in interface:
|
||||
errors.append(
|
||||
"plugin.json field `interface.defaultPrompt` or `interface.default_prompt` is required"
|
||||
)
|
||||
capabilities = interface.get("capabilities")
|
||||
if not isinstance(capabilities, list) or not all(
|
||||
isinstance(value, str) and value.strip() for value in capabilities
|
||||
):
|
||||
errors.append("plugin.json field `interface.capabilities` must be an array of strings")
|
||||
for field in ("websiteURL", "privacyPolicyURL", "termsOfServiceURL"):
|
||||
validate_optional_https_url(interface, field, errors, prefix="interface")
|
||||
brand_color = interface.get("brandColor")
|
||||
if brand_color is not None and (
|
||||
not isinstance(brand_color, str) or HEX_COLOR_RE.fullmatch(brand_color) is None
|
||||
):
|
||||
errors.append("plugin.json field `interface.brandColor` must use `#RRGGBB`")
|
||||
for field in ("composerIcon", "logo"):
|
||||
validate_optional_asset_path(plugin_root, plugin_root, interface, field, errors)
|
||||
screenshots = interface.get("screenshots", [])
|
||||
if not isinstance(screenshots, list):
|
||||
errors.append("plugin.json field `interface.screenshots` must be an array")
|
||||
else:
|
||||
for index, raw_path in enumerate(screenshots):
|
||||
validate_asset_path(
|
||||
plugin_root,
|
||||
plugin_root,
|
||||
raw_path,
|
||||
f"interface.screenshots[{index}]",
|
||||
errors,
|
||||
)
|
||||
|
||||
|
||||
def require_object(
|
||||
payload: dict[str, Any],
|
||||
key: str,
|
||||
errors: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
value = payload.get(key)
|
||||
if not isinstance(value, dict):
|
||||
errors.append(f"plugin.json field `{key}` must be an object")
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def require_non_empty_string(
|
||||
payload: dict[str, Any],
|
||||
key: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
prefix: str | None = None,
|
||||
) -> str | None:
|
||||
value = payload.get(key)
|
||||
field = f"{prefix}.{key}" if prefix is not None else key
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"plugin.json field `{field}` must be a non-empty string")
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def validate_optional_non_empty_string(
|
||||
payload: dict[str, Any],
|
||||
key: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
prefix: str | None = None,
|
||||
) -> None:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return
|
||||
field = f"{prefix}.{key}" if prefix is not None else key
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"plugin.json field `{field}` must be a non-empty string")
|
||||
|
||||
|
||||
def reject_unknown_fields(
|
||||
payload: dict[str, Any],
|
||||
allowed_keys: set[str],
|
||||
prefix: str,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
for key in sorted(set(payload) - allowed_keys):
|
||||
errors.append(f"plugin.json field `{prefix}.{key}` is not accepted by plugin validation")
|
||||
|
||||
|
||||
def validate_optional_https_url(
|
||||
payload: dict[str, Any],
|
||||
key: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
prefix: str,
|
||||
) -> None:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return
|
||||
parsed = urlparse(value) if isinstance(value, str) else None
|
||||
if parsed is None or parsed.scheme != "https" or not parsed.netloc:
|
||||
errors.append(f"plugin.json field `{prefix}.{key}` must be an absolute `https://` URL")
|
||||
|
||||
|
||||
def validate_optional_contract_path(
|
||||
payload: dict[str, Any],
|
||||
key: str,
|
||||
expected: str,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
return
|
||||
normalized = normalize_contract_path(value) if isinstance(value, str) else None
|
||||
if normalized != expected:
|
||||
errors.append(f"plugin.json field `{key}` must resolve to `{expected}`")
|
||||
|
||||
|
||||
def normalize_contract_path(raw_path: str) -> str | None:
|
||||
path = Path(raw_path)
|
||||
if path.is_absolute():
|
||||
return None
|
||||
normalized = path.as_posix().rstrip("/")
|
||||
return normalized or None
|
||||
|
||||
|
||||
def validate_app_manifest(path: Path, errors: list[str]) -> None:
|
||||
payload = load_companion_json_object(path, "`.app.json`", errors)
|
||||
if payload is None:
|
||||
return
|
||||
reject_companion_unknown_fields(payload, {"apps"}, "`.app.json`", errors)
|
||||
apps = payload.get("apps")
|
||||
if not isinstance(apps, dict):
|
||||
errors.append("`.app.json` field `apps` must be an object")
|
||||
return
|
||||
for key, value in apps.items():
|
||||
if not isinstance(value, dict):
|
||||
errors.append(f"`.app.json` app `{key}` must be an object")
|
||||
continue
|
||||
reject_companion_unknown_fields(value, {"id"}, f"`.app.json` app `{key}`", errors)
|
||||
app_id = value.get("id")
|
||||
if not isinstance(app_id, str) or not app_id.strip():
|
||||
errors.append(f"`.app.json` app `{key}` field `id` must be a non-empty string")
|
||||
|
||||
|
||||
def validate_mcp_manifest(path: Path, errors: list[str]) -> None:
|
||||
payload = load_companion_json_object(path, "`.mcp.json`", errors)
|
||||
if payload is None:
|
||||
return
|
||||
reject_companion_unknown_fields(payload, {"mcpServers"}, "`.mcp.json`", errors)
|
||||
servers = payload.get("mcpServers")
|
||||
if not isinstance(servers, dict):
|
||||
errors.append("`.mcp.json` field `mcpServers` must be an object")
|
||||
return
|
||||
for key, value in servers.items():
|
||||
if not isinstance(key, str) or not key.strip():
|
||||
errors.append("`.mcp.json` server names must be non-empty strings")
|
||||
if not isinstance(value, dict):
|
||||
errors.append(f"`.mcp.json` server `{key}` must be an object")
|
||||
|
||||
|
||||
def load_companion_json_object(
|
||||
path: Path,
|
||||
label: str,
|
||||
errors: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
if not path.is_file():
|
||||
errors.append(f"{label} is required when its plugin.json field is present")
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
errors.append(f"{label} must contain valid JSON")
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
errors.append(f"{label} must contain a JSON object")
|
||||
return None
|
||||
return payload
|
||||
|
||||
|
||||
def reject_companion_unknown_fields(
|
||||
payload: dict[str, Any],
|
||||
allowed_keys: set[str],
|
||||
prefix: str,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
for key in sorted(set(payload) - allowed_keys):
|
||||
errors.append(f"{prefix} field `{key}` is not accepted by plugin validation")
|
||||
|
||||
|
||||
def validate_skill_manifests(plugin_root: Path, errors: list[str]) -> None:
|
||||
skills_root = plugin_root / "skills"
|
||||
if not skills_root.is_dir():
|
||||
return
|
||||
for skill_root in sorted(skills_root.iterdir(), key=lambda path: path.name):
|
||||
if skill_root.name.startswith(".") or not skill_root.is_dir():
|
||||
continue
|
||||
validate_skill_manifest(skill_root, errors)
|
||||
|
||||
|
||||
def validate_skill_manifest(skill_root: Path, errors: list[str]) -> None:
|
||||
skill_md_path = skill_root / "SKILL.md"
|
||||
if not skill_md_path.is_file():
|
||||
errors.append(f"skill `{skill_root.name}` is missing `SKILL.md`")
|
||||
return
|
||||
try:
|
||||
contents = skill_md_path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
errors.append(f"unable to read skill `{skill_root.name}`")
|
||||
return
|
||||
if not contents.startswith("---\n"):
|
||||
errors.append(f"skill `{skill_root.name}` must start with YAML frontmatter")
|
||||
return
|
||||
frontmatter_end = contents.find("\n---", 4)
|
||||
if frontmatter_end == -1:
|
||||
errors.append(f"skill `{skill_root.name}` frontmatter is not closed")
|
||||
return
|
||||
try:
|
||||
frontmatter = yaml.safe_load(contents[4:frontmatter_end])
|
||||
except yaml.YAMLError:
|
||||
errors.append(f"skill `{skill_root.name}` frontmatter must be valid YAML")
|
||||
return
|
||||
if not isinstance(frontmatter, dict):
|
||||
errors.append(f"skill `{skill_root.name}` frontmatter must be an object")
|
||||
return
|
||||
skill_name = frontmatter.get("name")
|
||||
if not isinstance(skill_name, str) or not skill_name.strip():
|
||||
errors.append(f"skill `{skill_root.name}` frontmatter field `name` must be non-empty")
|
||||
description = frontmatter.get("description")
|
||||
if not isinstance(description, str) or not description.strip():
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` frontmatter field `description` must be non-empty"
|
||||
)
|
||||
disable_model_invocation = frontmatter.get("disable-model-invocation")
|
||||
if disable_model_invocation is None:
|
||||
disable_model_invocation = frontmatter.get("disable_model_invocation")
|
||||
if disable_model_invocation not in (None, False):
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` frontmatter field `disable-model-invocation` must be false"
|
||||
)
|
||||
agent_yaml_path = skill_root / "agents" / "openai.yaml"
|
||||
if agent_yaml_path.is_file():
|
||||
validate_skill_agent_manifest(
|
||||
plugin_root=skill_root.parent.parent,
|
||||
skill_root=skill_root,
|
||||
agent_yaml_path=agent_yaml_path,
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
|
||||
def validate_skill_agent_manifest(
|
||||
*,
|
||||
plugin_root: Path,
|
||||
skill_root: Path,
|
||||
agent_yaml_path: Path,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
try:
|
||||
payload = yaml.safe_load(agent_yaml_path.read_text(encoding="utf-8"))
|
||||
except OSError:
|
||||
errors.append(f"unable to read skill `{skill_root.name}` agent YAML")
|
||||
return
|
||||
except yaml.YAMLError:
|
||||
errors.append(f"skill `{skill_root.name}` agent YAML must be valid YAML")
|
||||
return
|
||||
if not isinstance(payload, dict):
|
||||
errors.append(f"skill `{skill_root.name}` agent YAML must be an object")
|
||||
return
|
||||
|
||||
reject_skill_agent_unknown_fields(
|
||||
payload,
|
||||
{"interface", "policy", "dependencies"},
|
||||
skill_root,
|
||||
errors,
|
||||
)
|
||||
interface = payload.get("interface")
|
||||
if not isinstance(interface, dict):
|
||||
errors.append(f"skill `{skill_root.name}` agent field `interface` must be an object")
|
||||
return
|
||||
reject_skill_agent_unknown_fields(
|
||||
interface,
|
||||
{
|
||||
"display_name",
|
||||
"short_description",
|
||||
"icon_small",
|
||||
"icon_large",
|
||||
"brand_color",
|
||||
"default_prompt",
|
||||
},
|
||||
skill_root,
|
||||
errors,
|
||||
prefix="interface",
|
||||
)
|
||||
for field in ("display_name", "short_description"):
|
||||
value = interface.get(field)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` agent field `interface.{field}` must be non-empty"
|
||||
)
|
||||
for field in ("icon_small", "icon_large"):
|
||||
validate_optional_asset_path(
|
||||
skill_root,
|
||||
plugin_root,
|
||||
interface,
|
||||
field,
|
||||
errors,
|
||||
prefix=f"skill `{skill_root.name}` agent field `interface",
|
||||
)
|
||||
brand_color = interface.get("brand_color")
|
||||
if brand_color is not None and (
|
||||
not isinstance(brand_color, str) or HEX_COLOR_RE.fullmatch(brand_color) is None
|
||||
):
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` agent field `interface.brand_color` must use `#RRGGBB`"
|
||||
)
|
||||
default_prompt = interface.get("default_prompt")
|
||||
if default_prompt is not None and (
|
||||
not isinstance(default_prompt, str) or not default_prompt.strip()
|
||||
):
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` agent field `interface.default_prompt` must be non-empty"
|
||||
)
|
||||
|
||||
policy = payload.get("policy")
|
||||
if policy is not None:
|
||||
if not isinstance(policy, dict):
|
||||
errors.append(f"skill `{skill_root.name}` agent field `policy` must be an object")
|
||||
else:
|
||||
reject_skill_agent_unknown_fields(
|
||||
policy,
|
||||
{"allow_implicit_invocation"},
|
||||
skill_root,
|
||||
errors,
|
||||
prefix="policy",
|
||||
)
|
||||
allow_implicit_invocation = policy.get("allow_implicit_invocation")
|
||||
if allow_implicit_invocation is not None and not isinstance(
|
||||
allow_implicit_invocation,
|
||||
bool,
|
||||
):
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` agent field "
|
||||
"`policy.allow_implicit_invocation` must be a boolean"
|
||||
)
|
||||
|
||||
dependencies = payload.get("dependencies")
|
||||
if dependencies is not None:
|
||||
if not isinstance(dependencies, dict):
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` agent field `dependencies` must be an object"
|
||||
)
|
||||
else:
|
||||
reject_skill_agent_unknown_fields(
|
||||
dependencies,
|
||||
{"tools"},
|
||||
skill_root,
|
||||
errors,
|
||||
prefix="dependencies",
|
||||
)
|
||||
|
||||
|
||||
def reject_skill_agent_unknown_fields(
|
||||
payload: dict[str, Any],
|
||||
allowed_keys: set[str],
|
||||
skill_root: Path,
|
||||
errors: list[str],
|
||||
*,
|
||||
prefix: str | None = None,
|
||||
) -> None:
|
||||
for key in sorted(set(payload) - allowed_keys):
|
||||
field = f"{prefix}.{key}" if prefix is not None else key
|
||||
errors.append(
|
||||
f"skill `{skill_root.name}` agent field `{field}` is not accepted by plugin validation"
|
||||
)
|
||||
|
||||
|
||||
def validate_optional_asset_path(
|
||||
base_dir: Path,
|
||||
allowed_root: Path,
|
||||
payload: dict[str, Any],
|
||||
key: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
prefix: str = "interface",
|
||||
) -> None:
|
||||
raw_path = payload.get(key)
|
||||
if raw_path is None:
|
||||
return
|
||||
validate_asset_path(base_dir, allowed_root, raw_path, f"{prefix}.{key}", errors)
|
||||
|
||||
|
||||
def validate_asset_path(
|
||||
base_dir: Path,
|
||||
allowed_root: Path,
|
||||
raw_path: Any,
|
||||
field: str,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
label = field if field.startswith("skill `") else f"plugin.json field `{field}`"
|
||||
if not isinstance(raw_path, str) or not raw_path.strip():
|
||||
errors.append(f"{label} must be a non-empty relative path")
|
||||
return
|
||||
candidate = PurePosixPath(raw_path.replace("\\", "/"))
|
||||
if candidate.is_absolute() or any(part in {"", ".", ".."} for part in candidate.parts):
|
||||
errors.append(f"{label} must stay inside the plugin archive")
|
||||
return
|
||||
resolved_path = (base_dir / candidate.as_posix()).resolve()
|
||||
if not resolved_path.is_relative_to(allowed_root.resolve()):
|
||||
errors.append(f"{label} must stay inside the plugin archive")
|
||||
return
|
||||
if not resolved_path.is_file():
|
||||
errors.append(f"{label} points to a missing file")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user