plugin_declarations.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """Read plugin build declarations without importing CLI configuration or plugin code."""
  2. from __future__ import annotations
  3. from collections.abc import Mapping
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. import tomllib
  7. def native_manifest_file(plugin_dir: Path) -> Path | None:
  8. for path in (plugin_dir / "plugin.yaml", plugin_dir / "plugin.yml"):
  9. try:
  10. path.stat()
  11. except FileNotFoundError:
  12. continue
  13. except OSError as exc:
  14. raise ValueError(f"Could not inspect plugin manifest {path}: {exc}") from exc
  15. return path
  16. return None
  17. def read_native_manifest(path: Path) -> dict:
  18. import hermes_yaml as yaml
  19. try:
  20. data = yaml.safe_load(path.read_text(encoding="utf-8-sig"))
  21. except (OSError, UnicodeError, yaml.YAMLError) as exc:
  22. raise ValueError(f"Could not read plugin manifest {path}: {exc}") from exc
  23. if data is None:
  24. return {}
  25. if not isinstance(data, dict):
  26. raise ValueError(f"Plugin manifest must be a mapping: {path}")
  27. return data
  28. def manifest_version_error(manifest: dict, name: str) -> str | None:
  29. from hermes_cli.plugins_manifest import SUPPORTED_MANIFEST_VERSION, requires_hermes_error
  30. reason = requires_hermes_error(manifest)
  31. if reason:
  32. return f"Plugin '{name}' {reason}"
  33. version = manifest.get("manifest_version")
  34. if version is None:
  35. return None
  36. try:
  37. parsed = int(version)
  38. except (TypeError, ValueError):
  39. return f"Plugin '{name}' has invalid manifest_version '{version}' (expected an integer)."
  40. if parsed > SUPPORTED_MANIFEST_VERSION:
  41. return (f"Plugin '{name}' requires manifest_version {version}, "
  42. f"but this installer only supports up to {SUPPORTED_MANIFEST_VERSION}.")
  43. return None
  44. @dataclass(frozen=True)
  45. class PythonDeclaration:
  46. files: tuple[Path, ...]
  47. pyproject: Path | None
  48. requirements: tuple[str, ...]
  49. manifest: dict
  50. requires_python: str | None = None
  51. # The pyproject itself installs something: the plugin as a package, or extras/dependency groups
  52. # (``uv sync --all-packages`` installs a member's default groups as well as its dependencies).
  53. pyproject_installs: bool = False
  54. @property
  55. def external(self) -> bool:
  56. return str(self.manifest.get("python_runtime") or "").strip().lower() == "external"
  57. @property
  58. def install_requirements(self) -> tuple[str, ...]:
  59. return () if self.external else applicable_requirements(self.requirements)
  60. @property
  61. def installs_packages(self) -> bool:
  62. """Admission would put packages into the shared environment: what dependency consent asks
  63. about and what makes the plugin a workspace member. ``dependencies = []`` installs nothing,
  64. so like no pyproject it asks no consent and stays out of the environment stamp, which hashes
  65. a member's whole tree (each enable or update would build a generation for nothing)."""
  66. return not self.external and (bool(self.install_requirements) or self.pyproject_installs)
  67. def python_error(self, version: str) -> str | None:
  68. """Why this member cannot join a workspace built for *version*; uv intersects every
  69. member's requires-python, so one excluding member fails the whole lock."""
  70. from packaging.specifiers import SpecifierSet
  71. if not self.installs_packages or not self.requires_python:
  72. return None
  73. if SpecifierSet(self.requires_python).contains(version, prereleases=True):
  74. return None
  75. return f"requires Python {self.requires_python}, but Hermes runs on Python {version}"
  76. def __post_init__(self) -> None:
  77. if not self.external:
  78. applicable_requirements(self.requirements)
  79. def applicable_requirements(specs: tuple[str, ...] | list[str]) -> tuple[str, ...]:
  80. """Index requirements only; let uv evaluate markers for the target interpreter.
  81. The application checkout supplies Hermes itself. Installing it from an index
  82. would replace that checkout; direct URLs bypass the reviewed package source.
  83. Markers must survive snapshots built for a different Python or platform.
  84. """
  85. from packaging.requirements import Requirement
  86. from packaging.utils import canonicalize_name
  87. return tuple(spec for spec in specs
  88. if not (req := Requirement(spec)).url and canonicalize_name(req.name) != "hermes-agent")
  89. def unsupported_requirements(specs: tuple[str, ...] | list[str]) -> tuple[str, ...]:
  90. from packaging.requirements import Requirement
  91. return tuple(spec for spec in specs if Requirement(spec).url)
  92. def read_python_declaration(plugin_dir: Path) -> PythonDeclaration:
  93. """One effective surface for consent, membership, builds and currency.
  94. A pyproject with a ``[project]`` table owns packaging. Tooling-only
  95. pyprojects (for example, a plugin's Ruff configuration) remain legacy
  96. manifest plugins and must not become uv workspace members. Both YAML
  97. suffixes and both dependency aliases have identical semantics. Reading
  98. never initializes a home, discovers code, or depends on the caller's CLI
  99. import state.
  100. """
  101. native = native_manifest_file(plugin_dir)
  102. files = [native] if native is not None else []
  103. manifest = read_native_manifest(native) if native is not None else {}
  104. if native is None:
  105. portable = plugin_dir / "plugin.json"
  106. try:
  107. portable.lstat()
  108. except FileNotFoundError:
  109. pass
  110. else:
  111. from hermes_cli.agent_plugins import read_agent_plugin_manifest
  112. manifest, _diagnostics = read_agent_plugin_manifest(plugin_dir)
  113. files.append(portable)
  114. project = plugin_dir / "pyproject.toml"
  115. try:
  116. text = project.read_text(encoding="utf-8-sig")
  117. except FileNotFoundError:
  118. text = None
  119. if text is not None:
  120. files.append(project)
  121. if "GENERATED by pm" not in text:
  122. document = tomllib.loads(text)
  123. metadata = document.get("project")
  124. if isinstance(metadata, Mapping):
  125. specs = metadata.get("dependencies", [])
  126. if not isinstance(specs, list) or any(not isinstance(v, str) for v in specs):
  127. raise ValueError(f"invalid project.dependencies: {project}")
  128. requires_python = metadata.get("requires-python")
  129. if requires_python is not None and not isinstance(requires_python, str):
  130. raise ValueError(f"invalid project.requires-python: {project}")
  131. uv = document.get("tool", {}).get("uv", {})
  132. installs = ("build-system" in document or uv.get("package") is True
  133. or any(metadata.get("optional-dependencies", {}).values())
  134. or any(document.get("dependency-groups", {}).values())
  135. or bool(uv.get("dev-dependencies")))
  136. return PythonDeclaration(tuple(files), project, tuple(specs), manifest, requires_python, installs)
  137. specs = []
  138. for key in ("pip_dependencies", "python_dependencies"):
  139. values = manifest.get(key, [])
  140. if not isinstance(values, list) or any(not isinstance(v, str) for v in values):
  141. raise ValueError(f"invalid {key}: {native}")
  142. specs.extend(values)
  143. return PythonDeclaration(tuple(files), None, tuple(dict.fromkeys(specs)), manifest)