mvp-ai's picture
download
raw
21.5 kB
"""Validate the local Codex plugin package and repo marketplace offline."""
from __future__ import annotations
import argparse
import json
import re
import urllib.parse
from pathlib import Path
from typing import Any, Mapping, Sequence
PLUGIN_NAME_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
SEMVER_PATTERN = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
SKILL_NAME_PATTERN = re.compile(r"(?m)^name:\s*([^\s]+)\s*$")
SKILL_DESCRIPTION_PATTERN = re.compile(r"(?m)^description:\s*(.+?)\s*$")
REQUIRED_MANIFEST_FIELDS = {"name", "version", "description", "skills"}
REQUIRED_INTERFACE_FIELDS = {
"displayName",
"shortDescription",
"longDescription",
"developerName",
"category",
"capabilities",
"websiteURL",
"defaultPrompt",
"brandColor",
"composerIcon",
"logo",
}
ALLOWED_INTERFACE_FIELDS = REQUIRED_INTERFACE_FIELDS | {
"privacyPolicyURL",
"termsOfServiceURL",
}
PUBLIC_INTERFACE_URL_FIELDS = (
"privacyPolicyURL",
"termsOfServiceURL",
)
REQUIRED_MARKETPLACE_POLICY_FIELDS = {"installation", "authentication"}
HOSTED_MCP_NAME = "ai_open_source_intelligence"
HOSTED_MCP_URL = "https://mcp.aiworkstation.cn/mcp"
HOSTED_MCP_FIELDS = {
"type",
"url",
}
UNIFIED_SKILL_NAME = "ai-open-source-intelligence"
SKILL_AGENT_RELATIVE_PATH = Path("skills") / UNIFIED_SKILL_NAME / "agents" / "openai.yaml"
def _load_object(path: Path, errors: list[str]) -> Mapping[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
errors.append(f"missing file: {path}")
return {}
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
errors.append(f"invalid JSON file {path}: {exc}")
return {}
if not isinstance(value, Mapping):
errors.append(f"{path} must contain a JSON object")
return {}
return value
def _resolve_relative_path(root: Path, raw_path: Any, label: str, errors: list[str]) -> Path | None:
if not isinstance(raw_path, str) or not raw_path.startswith("./"):
errors.append(f"{label} must be a ./-prefixed path relative to the plugin root")
return None
candidate = (root / raw_path[2:]).resolve()
try:
candidate.relative_to(root.resolve())
except ValueError:
errors.append(f"{label} escapes the plugin root")
return None
return candidate
def _frontmatter(content: str, path: Path, errors: list[str]) -> tuple[str, str]:
if not content.startswith("---\n"):
errors.append(f"{path}: SKILL.md must start with YAML frontmatter")
return "", ""
name = SKILL_NAME_PATTERN.search(content)
description = SKILL_DESCRIPTION_PATTERN.search(content)
if not name:
errors.append(f"{path}: frontmatter name is missing")
if not description or not description.group(1).strip():
errors.append(f"{path}: frontmatter description is missing")
return (
name.group(1).strip() if name else "",
description.group(1).strip() if description else "",
)
def _validate_component_path(
root: Path,
manifest: Mapping[str, Any],
field: str,
expected_name: str,
errors: list[str],
) -> None:
if field not in manifest:
return
path = _resolve_relative_path(root, manifest[field], field, errors)
if path is None:
return
if path != (root / expected_name).resolve():
errors.append(f"{field} must point to {expected_name}")
if not path.is_file():
errors.append(f"{field} target does not exist: {path}")
def _public_https_url(value: Any) -> bool:
text = str(value or "").strip()
if not text:
return False
try:
parsed = urllib.parse.urlparse(text)
except ValueError:
return False
return (
parsed.scheme == "https"
and bool(parsed.netloc)
and parsed.hostname not in {"localhost", "127.0.0.1", "::1"}
and parsed.username is None
and parsed.password is None
)
def _validate_square_svg_asset(
root: Path,
raw_path: Any,
label: str,
errors: list[str],
) -> None:
path = _resolve_relative_path(root, raw_path, label, errors)
if path is None:
return
if not path.is_file():
errors.append(f"{label} target does not exist: {path}")
return
if path.suffix.lower() != ".svg":
errors.append(f"{label} must use the reviewed square SVG asset")
return
try:
content = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as exc:
errors.append(f"{label} SVG is unreadable: {exc}")
return
match = re.search(r'\bviewBox="([^"]+)"', content)
if not match:
errors.append(f"{label} SVG must declare a numeric square viewBox")
return
try:
_x, _y, width, height = (float(value) for value in match.group(1).split())
except (TypeError, ValueError):
errors.append(f"{label} SVG viewBox is invalid")
return
if width != height or not 48 <= width <= 4096:
errors.append(f"{label} SVG must be square and between 48 and 4096 pixels")
def _validate_hosted_mcp_config(root: Path, errors: list[str]) -> bool:
initial_error_count = len(errors)
payload = _load_object(root / ".mcp.json", errors)
if not payload:
return False
if set(payload) != {"mcpServers"}:
errors.append(".mcp.json must contain only the mcpServers object")
servers = payload.get("mcpServers")
if not isinstance(servers, Mapping):
errors.append(".mcp.json must contain an mcpServers object")
return False
if set(servers) != {HOSTED_MCP_NAME}:
errors.append(
".mcp.json must declare exactly the ai_open_source_intelligence server"
)
return False
server = servers.get(HOSTED_MCP_NAME)
if not isinstance(server, Mapping):
errors.append("Hosted MCP configuration must be an object")
return False
if set(server) != HOSTED_MCP_FIELDS:
errors.append("Hosted MCP configuration fields do not match the reviewed surface")
if server.get("type") != "http":
errors.append("Hosted MCP type must be http")
if server.get("url") != HOSTED_MCP_URL:
errors.append(f"Hosted MCP URL must be {HOSTED_MCP_URL}")
forbidden = {"command", "args", "env", "headers", "bearer_token_env_var"}
if forbidden.intersection(server):
errors.append("public Hosted MCP configuration must not carry commands or credentials")
return len(errors) == initial_error_count
def _validate_skill_agent_config(root: Path, errors: list[str]) -> bool:
"""Validate the intentionally narrow Skill-to-MCP dependency contract.
The release carries one canonical Skill and one canonical Hosted MCP. Keeping
this YAML subset exact avoids adding a general YAML parser to the runtime
package while still failing closed on missing, duplicated or drifted fields.
"""
initial_error_count = len(errors)
path = root / SKILL_AGENT_RELATIVE_PATH
try:
content = path.read_text(encoding="utf-8")
except FileNotFoundError:
errors.append(f"missing file: {path}")
return False
except (OSError, UnicodeDecodeError) as exc:
errors.append(f"invalid Skill agent config {path}: {exc}")
return False
if "\t" in content:
errors.append("Skill agents/openai.yaml must use spaces, not tabs")
return False
lines = [line.rstrip() for line in content.splitlines() if line.strip()]
structural_lines = {
0: "interface:",
4: "dependencies:",
5: " tools:",
6: ' - type: "mcp"',
7: f' value: "{HOSTED_MCP_NAME}"',
9: ' transport: "streamable_http"',
10: f' url: "{HOSTED_MCP_URL}"',
11: "policy:",
12: " allow_implicit_invocation: true",
}
if len(lines) != 13 or any(
index >= len(lines) or lines[index] != expected
for index, expected in structural_lines.items()
):
errors.append(
"Skill agents/openai.yaml must declare the canonical implicit Skill and Hosted MCP dependency"
)
return False
display_match = re.fullmatch(r' display_name: "([^"\n]+)"', lines[1])
short_match = re.fullmatch(r' short_description: "([^"\n]+)"', lines[2])
prompt_match = re.fullmatch(r' default_prompt: "([^"\n]+)"', lines[3])
dependency_description = re.fullmatch(
r' description: "([^"\n]+)"', lines[8]
)
if not all((display_match, short_match, prompt_match, dependency_description)):
errors.append("Skill agents/openai.yaml UI and dependency strings must be quoted and non-empty")
return False
assert display_match is not None
assert short_match is not None
assert prompt_match is not None
if len(display_match.group(1)) > 64:
errors.append("Skill display_name must be at most 64 characters")
if not 25 <= len(short_match.group(1)) <= 64:
errors.append("Skill short_description must be 25 to 64 characters")
if f"${UNIFIED_SKILL_NAME}" not in prompt_match.group(1):
errors.append("Skill default_prompt must explicitly invoke the unified Skill")
return len(errors) == initial_error_count
def validate_plugin_package(root: Path) -> dict[str, Any]:
"""Return local-install and public-submission metadata readiness for one plugin root."""
plugin_root = Path(root).resolve()
errors: list[str] = []
warnings: list[str] = []
public_blockers: list[str] = []
manifest_path = plugin_root / ".codex-plugin" / "plugin.json"
marketplace_path = plugin_root / ".agents" / "plugins" / "marketplace.json"
manifest = _load_object(manifest_path, errors)
marketplace = _load_object(marketplace_path, errors)
skill_agent_dependency_ready = _validate_skill_agent_config(plugin_root, errors)
manifest_directory = manifest_path.parent
if manifest_directory.exists():
extra_entries = sorted(
path.name for path in manifest_directory.iterdir() if path.name != "plugin.json"
)
if extra_entries:
errors.append(
".codex-plugin must contain only plugin.json; found: " + ", ".join(extra_entries)
)
if manifest:
missing = sorted(REQUIRED_MANIFEST_FIELDS - set(manifest))
if missing:
errors.append(f"plugin manifest is missing required fields: {missing}")
name = str(manifest.get("name") or "")
version = str(manifest.get("version") or "")
description = str(manifest.get("description") or "").strip()
if not PLUGIN_NAME_PATTERN.fullmatch(name):
errors.append("plugin name must be stable kebab-case")
if not SEMVER_PATTERN.fullmatch(version):
errors.append("plugin version must be semantic x.y.z")
if not description:
errors.append("plugin description must be non-empty")
skills_root = _resolve_relative_path(plugin_root, manifest.get("skills"), "skills", errors)
skill_names: set[str] = set()
if skills_root is not None:
if not skills_root.is_dir():
errors.append(f"skills directory does not exist: {skills_root}")
else:
skill_files = sorted(skills_root.glob("*/SKILL.md"))
if not skill_files:
errors.append("skills directory contains no */SKILL.md files")
for skill_file in skill_files:
content = skill_file.read_text(encoding="utf-8")
skill_name, _description = _frontmatter(content, skill_file, errors)
if skill_name and skill_name != skill_file.parent.name:
errors.append(
f"{skill_file}: frontmatter name must match directory {skill_file.parent.name}"
)
if skill_name in skill_names:
errors.append(f"duplicate skill name: {skill_name}")
if skill_name:
skill_names.add(skill_name)
_validate_component_path(plugin_root, manifest, "mcpServers", ".mcp.json", errors)
_validate_component_path(plugin_root, manifest, "apps", ".app.json", errors)
mcp_configuration_bundled = False
if manifest.get("mcpServers") == "./.mcp.json":
mcp_configuration_bundled = _validate_hosted_mcp_config(plugin_root, errors)
interface = manifest.get("interface")
if not isinstance(interface, Mapping):
errors.append("plugin manifest interface must be an object")
interface_mapping: Mapping[str, Any] = {}
else:
interface_mapping = interface
unsupported_interface_fields = sorted(
set(interface_mapping) - ALLOWED_INTERFACE_FIELDS
)
if unsupported_interface_fields:
errors.append(
"plugin interface contains unsupported fields: "
+ ", ".join(unsupported_interface_fields)
)
missing_interface = sorted(REQUIRED_INTERFACE_FIELDS - set(interface))
if missing_interface:
errors.append(f"plugin interface is missing fields: {missing_interface}")
display_name = str(interface.get("displayName") or "")
short_description = str(interface.get("shortDescription") or "")
developer_name = str(interface.get("developerName") or "")
if not display_name or len(display_name) > 30 or "\n" in display_name:
errors.append("plugin displayName must fit the 30-character directory limit")
if (
not short_description
or len(short_description) > 30
or "\n" in short_description
):
errors.append(
"plugin shortDescription must fit the 30-character directory limit"
)
if not developer_name or len(developer_name) > 80 or "\n" in developer_name:
errors.append("plugin developerName must fit the 80-character directory limit")
prompts = interface.get("defaultPrompt")
if (
not isinstance(prompts, Sequence)
or isinstance(prompts, (str, bytes, bytearray))
or not 1 <= len(prompts) <= 3
or any(
not isinstance(prompt, str)
or not prompt.strip()
or len(prompt) > 128
or "\n" in prompt
for prompt in prompts
)
):
errors.append(
"plugin interface must provide one to three single-line default prompts of at most 128 characters"
)
capabilities = interface.get("capabilities")
if not isinstance(capabilities, Sequence) or isinstance(
capabilities, (str, bytes, bytearray)
):
errors.append("plugin capabilities must be an array")
else:
if "Read" not in capabilities:
errors.append("read-only product must declare the Read capability")
if "Write" in capabilities:
errors.append("read-only product must not declare the Write capability")
brand_color = str(interface.get("brandColor") or "")
if not re.fullmatch(r"#[0-9A-Fa-f]{6}", brand_color):
errors.append("brandColor must be a six-digit hexadecimal color")
_validate_square_svg_asset(
plugin_root,
interface.get("composerIcon"),
"interface.composerIcon",
errors,
)
_validate_square_svg_asset(
plugin_root,
interface.get("logo"),
"interface.logo",
errors,
)
license_id = str(manifest.get("license") or "").strip()
if not license_id:
public_blockers.append("software license is missing")
elif license_id != "Apache-2.0":
public_blockers.append("public Skills release expects license=Apache-2.0")
elif not (plugin_root / "LICENSE").is_file():
public_blockers.append("Apache-2.0 LICENSE file is missing")
for field in PUBLIC_INTERFACE_URL_FIELDS:
value = interface_mapping.get(field)
if not value:
public_blockers.append(f"{field} is missing")
elif not _public_https_url(value):
public_blockers.append(f"{field} must be a public credential-free HTTPS URL")
if not _public_https_url(interface_mapping.get("websiteURL")):
public_blockers.append("websiteURL must be a public credential-free HTTPS URL")
if "mcpServers" not in manifest and "apps" not in manifest:
warnings.append(
"current package is Skills-only; MCP server setup remains a separate local workflow"
)
else:
mcp_configuration_bundled = False
if marketplace:
if not str(marketplace.get("name") or "").strip():
errors.append("marketplace name is required")
interface = marketplace.get("interface")
if not isinstance(interface, Mapping) or not str(interface.get("displayName") or "").strip():
errors.append("marketplace interface.displayName is required")
plugins = marketplace.get("plugins")
if not isinstance(plugins, Sequence) or isinstance(plugins, (str, bytes, bytearray)):
errors.append("marketplace plugins must be an array")
else:
matching_entries = [
entry
for entry in plugins
if isinstance(entry, Mapping) and entry.get("name") == manifest.get("name")
]
if len(matching_entries) != 1:
errors.append("marketplace must contain exactly one entry for this plugin")
else:
entry = matching_entries[0]
source = entry.get("source")
if not isinstance(source, Mapping):
errors.append("marketplace source must be an object")
else:
if source.get("source") != "local":
errors.append("repo-scoped marketplace source must be local")
source_path = _resolve_relative_path(
plugin_root,
source.get("path"),
"marketplace source.path",
errors,
)
if source_path is not None and source_path != plugin_root:
errors.append("repo marketplace must point to the repository-root plugin")
policy = entry.get("policy")
if not isinstance(policy, Mapping):
errors.append("marketplace policy must be an object")
else:
missing_policy = sorted(REQUIRED_MARKETPLACE_POLICY_FIELDS - set(policy))
if missing_policy:
errors.append(f"marketplace policy is missing fields: {missing_policy}")
if policy.get("installation") not in {
"AVAILABLE",
"INSTALLED_BY_DEFAULT",
"NOT_AVAILABLE",
}:
errors.append("marketplace installation policy is invalid")
if policy.get("authentication") not in {"ON_INSTALL", "ON_USE"}:
errors.append("marketplace authentication policy is invalid")
if not str(entry.get("category") or "").strip():
errors.append("marketplace category is required")
for blocker in public_blockers:
warnings.append("public submission is blocked: " + blocker)
local_ready = not errors
public_ready = local_ready and not public_blockers
return {
"schema_version": "osi.plugin-validation.v1",
"readiness_scope": "offline_metadata_only",
"plugin_root": str(plugin_root),
"plugin_name": manifest.get("name") if manifest else None,
"plugin_version": manifest.get("version") if manifest else None,
"local_skills_ready": local_ready,
"mcp_configuration_bundled": mcp_configuration_bundled,
"skill_agent_dependency_ready": skill_agent_dependency_ready,
"public_submission_metadata_ready": public_ready,
"external_checks_performed": False,
"public_submission_ready": public_ready,
"summary": {"errors": len(errors), "warnings": len(warnings)},
"errors": errors,
"warnings": warnings,
"public_submission_blockers": public_blockers,
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="osi-validate-plugin")
parser.add_argument("--root", type=Path, default=Path.cwd())
return parser
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
report = validate_plugin_package(args.root)
print(json.dumps(report, ensure_ascii=False, indent=2))
return 0 if report["local_skills_ready"] else 1
if __name__ == "__main__":
raise SystemExit(main())

Xet Storage Details

Size:
21.5 kB
·
Xet hash:
7d260ffffbfd80eeb34b647e6320e9ef118e081f03c0778e798f8a422d6b5f42

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.