declaration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. """Parse and register application requirements shared by MCP and skill offer-time gates."""
  2. from __future__ import annotations
  3. import re
  4. import threading
  5. from dataclasses import dataclass, field
  6. from typing import Any, Callable, Dict, Mapping, Optional
  7. from hermes_platform.resolver.app import LOCATION_KINDS, AppDef, AppLocation
  8. __all__ = [
  9. "AppSpec",
  10. "Declaration",
  11. "DeclarationError",
  12. "RequiresSpec",
  13. "clear",
  14. "gpu_label",
  15. "lookup",
  16. "parse_app",
  17. "parse_declaration",
  18. "parse_requires",
  19. "register",
  20. "unregister",
  21. ]
  22. class DeclarationError(ValueError):
  23. """Declaration parse/validation failure."""
  24. @dataclass(frozen=True)
  25. class AppSpec:
  26. """Where the application lives, one ``AppDef`` per OS it is detectable on."""
  27. per_os: Mapping[str, AppDef] = field(default_factory=dict)
  28. def for_os(self, os_family: str) -> Optional[AppDef]:
  29. return self.per_os.get(os_family)
  30. @dataclass(frozen=True)
  31. class RequiresSpec:
  32. """What the server needs before it is offered. Separate from ``app`` on purpose: one is data, one is policy."""
  33. app: bool = False
  34. min_version: Optional[str] = None
  35. gpu: Optional[str] = None
  36. @dataclass(frozen=True)
  37. class Declaration:
  38. """A parsed declaration; satisfies ``hermes_platform.resolver.availability._HasRequirements``."""
  39. name: str
  40. app: Optional[AppSpec]
  41. requires: RequiresSpec = RequiresSpec()
  42. @property
  43. def requires_app(self) -> bool:
  44. return self.requires.app
  45. @property
  46. def min_version(self) -> Optional[str]:
  47. return self.requires.min_version
  48. @property
  49. def required_gpu(self) -> Optional[str]:
  50. return self.requires.gpu
  51. def app_for(self, os_family: str) -> Optional[AppDef]:
  52. return self.app.for_os(os_family) if self.app else None
  53. _APP_OS_FAMILIES = ("win32", "darwin", "linux")
  54. _APP_PRESENCE = ("executable", "bundle")
  55. _APP_VERSION_KINDS = {"pe_resource": "win32", "uninstall_registry": "win32", "plist": "darwin", "none": None}
  56. _APP_LIVENESS_KINDS = ("server_json", "none")
  57. _VERSION_RE = re.compile(r"^\d+(\.\d+)*$")
  58. # `requires.gpu` values and how a sentence names them. Only NVIDIA: `facts.gpu_class()` reports the
  59. # highest-priority vendor present, which answers "is an NVIDIA GPU here" exactly and would not answer
  60. # it for AMD or Intel on a machine that also has an NVIDIA GPU.
  61. GPU_LABELS = {"nvidia": "an NVIDIA GPU"}
  62. def gpu_label(gpu: Optional[str]) -> str:
  63. """How a user-facing sentence names a ``requires.gpu`` value."""
  64. return GPU_LABELS.get(gpu or "", "a supported GPU")
  65. def _require_mapping(where: str, key: str, raw: Any) -> dict:
  66. if not isinstance(raw, dict):
  67. raise DeclarationError(f"{where}: '{key}' must be a mapping")
  68. return raw
  69. def _location_is_rooted(location: str, osf: str) -> bool:
  70. if ".." in location.replace("\\", "/").split("/") or "://" in location:
  71. return False
  72. if location.startswith(("~", "%", "$")):
  73. return True
  74. if osf == "win32":
  75. return bool(re.match(r"^[A-Za-z]:[\\/]", location))
  76. return location.startswith("/")
  77. def _is_relative_name(value: Any, *, allow_dirs: bool) -> bool:
  78. """Checks the stripped value, the one later joined: an empty part rejects a leading / or \\, a colon rejects a drive."""
  79. if not isinstance(value, str) or not value.strip() or "://" in value:
  80. return False
  81. parts = value.strip().replace("\\", "/").split("/")
  82. return ".." not in parts and "" not in parts and (allow_dirs or len(parts) == 1) and ":" not in parts[0]
  83. def _parse_location(where: str, osf: str, presence: str, label: str, raw: Any) -> AppLocation:
  84. """A string is a path, where `*` may stand for a versioned folder; a mapping names a location kind."""
  85. if isinstance(raw, str):
  86. path = raw.strip()
  87. if not path:
  88. raise DeclarationError(f"{where}: {label} is required")
  89. if not _location_is_rooted(path, osf) or "**" in path:
  90. raise DeclarationError(
  91. f"{where}: {label} must be absolute or start with ~ / %VAR% / $VAR, without '..', '**' or a URL scheme")
  92. return AppLocation("path", path)
  93. if not isinstance(raw, dict) or not isinstance(raw.get("kind"), str) or raw["kind"] not in LOCATION_KINDS:
  94. raise DeclarationError(f"{where}: {label} must be a path or a mapping with kind one of {sorted(LOCATION_KINDS)}")
  95. kind = raw["kind"]
  96. spec = LOCATION_KINDS[kind]
  97. if spec.only_on and spec.only_on != osf:
  98. raise DeclarationError(f"{where}: {label} kind {kind!r} is only valid under app.{spec.only_on}")
  99. if spec.yields != presence:
  100. raise DeclarationError(f"{where}: {label} kind {kind!r} needs app.{osf}.presence {spec.yields}")
  101. value = raw.get(spec.key)
  102. if not _is_relative_name(value, allow_dirs=False):
  103. raise DeclarationError(f"{where}: {label}.{spec.key} must be a bare name")
  104. file = raw.get("file", "")
  105. if spec.needs_file and not _is_relative_name(file, allow_dirs=True):
  106. raise DeclarationError(f"{where}: {label}.file must be a relative path inside the install folder")
  107. return AppLocation(kind, value.strip(), str(file).strip())
  108. def _parse_app_os(where: str, name: str, osf: str, raw: Any) -> AppDef:
  109. _require_mapping(where, f"app.{osf}", raw)
  110. presence = raw.get("presence")
  111. if presence not in _APP_PRESENCE:
  112. raise DeclarationError(f"{where}: app.{osf}.presence must be one of {_APP_PRESENCE}")
  113. location = raw.get("location")
  114. if isinstance(location, list):
  115. if not location:
  116. raise DeclarationError(f"{where}: app.{osf}.location is required")
  117. locations = tuple(_parse_location(where, osf, presence, f"app.{osf}.location[{i}]", item)
  118. for i, item in enumerate(location))
  119. elif isinstance(location, str):
  120. locations = (_parse_location(where, osf, presence, f"app.{osf}.location", location),)
  121. else:
  122. raise DeclarationError(f"{where}: app.{osf}.location is required")
  123. version = raw.get("version") or {"kind": "none"}
  124. _require_mapping(where, f"app.{osf}.version", version)
  125. vkind = version.get("kind", "none")
  126. if vkind not in _APP_VERSION_KINDS:
  127. raise DeclarationError(f"{where}: app.{osf}.version.kind must be one of {sorted(_APP_VERSION_KINDS)}")
  128. only_on = _APP_VERSION_KINDS[vkind]
  129. if only_on and only_on != osf:
  130. raise DeclarationError(f"{where}: app.{osf}.version.kind {vkind!r} is only valid under app.{only_on}")
  131. varg = str(version.get("display_name_prefix") or "")
  132. if vkind == "uninstall_registry" and not varg:
  133. raise DeclarationError(f"{where}: app.{osf}.version.display_name_prefix is required for uninstall_registry")
  134. liveness = raw.get("liveness") or {"kind": "none"}
  135. _require_mapping(where, f"app.{osf}.liveness", liveness)
  136. lkind = liveness.get("kind", "none")
  137. if lkind not in _APP_LIVENESS_KINDS:
  138. raise DeclarationError(f"{where}: app.{osf}.liveness.kind must be one of {_APP_LIVENESS_KINDS}")
  139. lpath = str(liveness.get("path") or "")
  140. if lkind == "server_json" and not lpath:
  141. raise DeclarationError(f"{where}: app.{osf}.liveness.path is required for server_json")
  142. return AppDef(
  143. app_id=name, os_family=osf, presence=presence, locations=locations,
  144. version_kind=vkind, version_arg=varg,
  145. liveness_kind=lkind, liveness_path=lpath,
  146. liveness_pid_key=str(liveness.get("pid_key") or "pid"),
  147. liveness_url_key=str(liveness.get("url_key") or "http"),
  148. liveness_token_key=str(liveness.get("token_key") or "token"),
  149. endpoint_path=str(liveness.get("endpoint_path") or "/mcp"),
  150. )
  151. def parse_app(raw: Any, *, name: str, where: str) -> Optional[AppSpec]:
  152. """Parse the ``app:`` block (already-decoded mapping, not YAML text) into an ``AppSpec``."""
  153. if raw is None:
  154. return None
  155. _require_mapping(where, "app", raw)
  156. unknown = set(raw) - set(_APP_OS_FAMILIES)
  157. if unknown:
  158. raise DeclarationError(f"{where}: app has unknown OS keys {sorted(unknown)}; use {_APP_OS_FAMILIES}")
  159. if not raw:
  160. raise DeclarationError(f"{where}: app needs at least one OS block")
  161. return AppSpec(per_os={osf: _parse_app_os(where, name, osf, raw[osf]) for osf in raw})
  162. def parse_requires(raw: Any, app: Optional[AppSpec], *, where: str) -> RequiresSpec:
  163. """Parse the ``requires:`` block; needs the parsed ``app`` to cross-check version policy."""
  164. if raw is None:
  165. return RequiresSpec()
  166. _require_mapping(where, "requires", raw)
  167. unknown = set(raw) - {"app", "min_version", "gpu"}
  168. if unknown:
  169. raise DeclarationError(f"{where}: requires has unknown keys {sorted(unknown)}")
  170. gpu = raw.get("gpu")
  171. if gpu is not None and (not isinstance(gpu, str) or gpu not in GPU_LABELS):
  172. raise DeclarationError(f"{where}: requires.gpu must be one of {sorted(GPU_LABELS)}")
  173. needs_app = raw.get("app", False)
  174. if not isinstance(needs_app, bool):
  175. raise DeclarationError(f"{where}: requires.app must be a boolean")
  176. if needs_app and app is None:
  177. raise DeclarationError(f"{where}: requires.app is true but the declaration has no 'app' block")
  178. min_version = raw.get("min_version")
  179. if min_version is not None:
  180. if not isinstance(min_version, str) or not _VERSION_RE.fullmatch(min_version):
  181. raise DeclarationError(f"{where}: requires.min_version must be a dotted numeric string")
  182. if not needs_app:
  183. raise DeclarationError(f"{where}: requires.min_version needs requires.app: true")
  184. assert app is not None
  185. # Linux has no version source, so a Linux block is gated on presence only; Windows and macOS must read
  186. # one, and a Linux-only declaration has nothing to compare.
  187. unversioned = [osf for osf in sorted(app.per_os) if app.per_os[osf].version_kind == "none"
  188. and (osf != "linux" or len(app.per_os) == 1)]
  189. if unversioned:
  190. raise DeclarationError(
  191. f"{where}: requires.min_version needs a version source under app.{unversioned[0]} (kind is none)")
  192. return RequiresSpec(app=needs_app, min_version=min_version, gpu=gpu)
  193. def parse_declaration(name: str, raw_app: Any, raw_requires: Any, *, where: str) -> Declaration:
  194. """Parse both blocks of one declaration. ``where`` is the human label in error messages."""
  195. app = parse_app(raw_app, name=name, where=where)
  196. return Declaration(name=name, app=app, requires=parse_requires(raw_requires, app, where=where))
  197. _REGISTRY: dict[str, Declaration] = {}
  198. _REGISTRY_LOCK = threading.Lock()
  199. on_change: Optional[Callable[[], None]] = None
  200. def _changed() -> None:
  201. if on_change is not None:
  202. on_change()
  203. def register(server_name: str, decl: Declaration) -> None:
  204. """Record which application declaration gates *server_name*."""
  205. with _REGISTRY_LOCK:
  206. _REGISTRY[server_name] = decl
  207. _changed()
  208. def unregister(server_name: str) -> None:
  209. """Remove the declaration registered for *server_name*."""
  210. with _REGISTRY_LOCK:
  211. _REGISTRY.pop(server_name, None)
  212. _changed()
  213. def lookup(server_name: str) -> Optional[Declaration]:
  214. """Return the declaration registered for *server_name*, if any."""
  215. with _REGISTRY_LOCK:
  216. return _REGISTRY.get(server_name)
  217. def clear() -> None:
  218. """Drop every registration."""
  219. with _REGISTRY_LOCK:
  220. _REGISTRY.clear()
  221. _changed()