plugins_manifest.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. """Plugin manifest model and parsing (``plugin.yaml`` v1/v2, portable ``plugin.json``).
  2. Split out of :mod:`hermes_cli.plugins`; validation warns and never fails a load.
  3. """
  4. from __future__ import annotations
  5. import hashlib
  6. import importlib.util
  7. import logging
  8. import re
  9. from contextlib import suppress
  10. from dataclasses import dataclass, field
  11. from pathlib import Path
  12. from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Tuple, Union
  13. from utils import fast_safe_load
  14. from hermes_cli.plugin_capabilities import parse_declared_capabilities as _parse_declared_capabilities
  15. try:
  16. import hermes_yaml as yaml
  17. except ImportError: # pragma: no cover – yaml is optional at import time
  18. yaml = None # type: ignore[assignment]
  19. logger = logging.getLogger("hermes_cli.plugins")
  20. _VALID_PLUGIN_KINDS: set[str] = {"standalone", "backend", "exclusive", "platform", "model-provider"}
  21. # Unknown plugin.yaml fields are forward-compat surface: warn (debug for v1 files, warning for v2+)
  22. # and continue loading. ``capabilities``/``emits``/``listens``/``hermes``/``depends`` are reserved.
  23. # ── Manifest v2 (#64165) parsing helpers ──────────────────────────────────
  24. _KNOWN_MANIFEST_FIELDS: set[str] = {
  25. "name", "version", "description", "author", "requires_env", "provides_tools", "provides_hooks",
  26. "kind", "hooks", "label", "optional_env", "platforms", "external_dependencies",
  27. "pip_dependencies", "provides_browser_providers", "provides_web_providers",
  28. "manifest_version", "api_version", "requires_plugins", "python_dependencies", "config_schema",
  29. "license", "homepage", "tags", "capabilities", "emits", "listens", "hermes", "depends",
  30. "requires_hermes", "python_runtime", "provides_locales", "requires_auth", "oauth", "config_keys",
  31. }
  32. # Highest manifest schema version this Hermes understands.
  33. SUPPORTED_MANIFEST_VERSION = 2
  34. _CONFIG_SCHEMA_TYPES: dict[str, tuple] = {
  35. "str": (str,), "string": (str,), "int": (int,), "integer": (int,), "float": (int, float),
  36. "number": (int, float), "bool": (bool,), "boolean": (bool,), "list": (list,), "array": (list,),
  37. "dict": (dict,), "object": (dict,),
  38. # ``secret`` values live in ``.env`` (see hermes_cli.plugins_settings), so a config.yaml copy is
  39. # only ever a stray string.
  40. "secret": (str,),
  41. }
  42. def _plugins_debug() -> bool:
  43. from hermes_cli import plugins as _origin
  44. return _origin._PLUGINS_DEBUG
  45. def _portable_data_namespace(key: str) -> str:
  46. """Return a readable, collision-resistant ``plugin-data`` directory name for a portable plugin."""
  47. slug = _portable_slug(key)
  48. digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:8]
  49. return f"agent-plugin-{slug}-{digest}"
  50. def _portable_slug(key: str) -> str:
  51. slug = "".join(ch if ch.isascii() and (ch.isalnum() or ch in "_-") else "-" for ch in key.lower())
  52. return slug.strip("-_") or "plugin"
  53. def portable_mcp_server_name(key: str, server: str) -> str:
  54. """Internal name of a portable plugin's MCP server: exactly the name its ``mcp.json`` gives it, the same
  55. rule a user's own ``mcp_servers`` block in config.yaml follows. The plugin's data namespace
  56. (``agent-plugin-<slug>-<digest>``) is NOT prepended: it keeps plugin-data dirs collision-free
  57. without coordination, but here it cost ~40 chars of every ``mcp__<server>__<tool>`` name, which providers
  58. cap at 64, so the tool verb was hash-clamped away. A duplicate is refused at load (native config first,
  59. then first-loaded plugin) with a warning naming both owners; that beats hiding it behind a digest."""
  60. del key # one signature for loader and card; the plugin identity is deliberately not part of the name
  61. return _portable_slug(server)
  62. def _display_author(value: object) -> str:
  63. """Normalize a manifest author value for the string PluginManifest field."""
  64. if isinstance(value, Mapping):
  65. return ", ".join(str(value[f]) for f in ("name", "email", "url") if value.get(f))
  66. return "" if value is None else str(value)
  67. def _manifest_field_of_type(data: Mapping, key: str, field_name: str, typ, what: str):
  68. """Return ``data[field_name]`` when absent or of ``typ``; warn and return None otherwise."""
  69. raw = data.get(field_name)
  70. if raw is not None and not isinstance(raw, typ):
  71. logger.warning("Plugin %s: %s must be %s; ignoring", key, field_name, what)
  72. return None
  73. return raw
  74. def _manifest_list(data: Mapping, key: str, field_name: str, what: str, coerce: Callable, warn: str) -> list:
  75. """Coerce each item of list field ``field_name``; ``coerce`` returning None warns ``warn`` and skips."""
  76. out = []
  77. for item in _manifest_field_of_type(data, key, field_name, list, what) or []:
  78. coerced = coerce(item)
  79. if coerced is None:
  80. logger.warning(warn, key, item)
  81. else:
  82. out.append(coerced)
  83. return out
  84. def _config_key_path(item: object) -> Optional[str]:
  85. """A ``config_keys`` entry: a dotted path at least two segments deep (``memory.retaindb``), else None.
  86. A bare section (``agent``) would silence typo notices for the whole section."""
  87. parts = item.strip().split(".") if isinstance(item, str) else []
  88. return ".".join(parts) if len(parts) >= 2 and all(parts) else None
  89. def manifest_config_keys(data: Mapping, key: str) -> list[str]:
  90. """Validated ``config_keys`` of a manifest mapping (malformed entries warn and are skipped)."""
  91. return _manifest_list(data, key, "config_keys", "a list of dotted config paths", _config_key_path,
  92. "Plugin %s: config_keys entry %r must be a dotted path at least two levels deep; skipping")
  93. def _dependency_entry(item: object) -> Optional[dict[str, Any]]:
  94. """``{id, version_range}`` from a requires_plugins item (str shorthand ok); None when malformed."""
  95. if isinstance(item, str):
  96. return {"id": item, "version_range": None}
  97. if isinstance(item, Mapping) and isinstance(item.get("id"), str) and item["id"]:
  98. vr = item.get("version_range")
  99. return {"id": item["id"], "version_range": str(vr) if vr is not None else None}
  100. return None
  101. def _manifest_int(raw: object, key: str, warn: str, fallback: Optional[int]) -> Optional[int]:
  102. """``int(raw)``; a non-integer warns ``warn`` (formatted with key, raw) and yields ``fallback``."""
  103. try:
  104. return int(raw) # type: ignore[call-overload]
  105. except (TypeError, ValueError):
  106. logger.warning(warn, key, raw)
  107. return fallback
  108. def _config_schema_entries(key: str, raw: Any) -> dict[str, Any]:
  109. """``config_schema`` (key -> {type?, default?, description?, ...}) keeping only mapping entries;
  110. warns on what it drops or cannot type-check. Shared by ``plugin.yaml`` and ``plugin.json``."""
  111. schema: dict[str, Any] = {}
  112. for skey, spec in (raw if isinstance(raw, Mapping) else {}).items():
  113. if not isinstance(spec, Mapping):
  114. logger.warning(
  115. "Plugin %s: config_schema entry %r must be a mapping (e.g. {type: str}); skipping", key, skey)
  116. continue
  117. stype = spec.get("type")
  118. if stype is not None and str(stype).lower() not in _CONFIG_SCHEMA_TYPES:
  119. logger.warning(
  120. "Plugin %s: config_schema key %r declares unknown type %r "
  121. "(known: %s); type check will be skipped for it",
  122. key, skey, stype, ", ".join(sorted(_CONFIG_SCHEMA_TYPES)),
  123. )
  124. schema[str(skey)] = dict(spec)
  125. return schema
  126. def _parse_manifest_v2_fields(data: Mapping, key: str) -> dict[str, Any]:
  127. """Validate/normalize manifest v2 fields into PluginManifest kwargs (warnings, never failures).
  128. See #64165.
  129. """
  130. # manifest_version — absent means v1 (supported forever); api_version is the independent API generation.
  131. mv = _manifest_int(data.get("manifest_version", 1), key,
  132. "Plugin %s: manifest_version %r is not an integer; treating as 1", 1)
  133. if mv > SUPPORTED_MANIFEST_VERSION:
  134. logger.warning(
  135. "Plugin %s: manifest_version %d is newer than this Hermes "
  136. "supports (%d); loading anyway and ignoring unknown fields", key, mv, SUPPORTED_MANIFEST_VERSION,
  137. )
  138. raw_api = data.get("api_version")
  139. api = None if raw_api is None else _manifest_int(
  140. raw_api, key, "Plugin %s: api_version %r is not an integer; ignoring", None)
  141. deps = _manifest_list(
  142. data, key, "requires_plugins", "a list", _dependency_entry,
  143. "Plugin %s: requires_plugins entry %r must be a plugin id "
  144. "string or a {id, version_range} mapping; skipping",
  145. )
  146. # python_dependencies — validated and surfaced ONLY; never auto-installed.
  147. pydeps = _manifest_list(
  148. data, key, "python_dependencies", "a list of requirement strings",
  149. lambda item: item.strip() if isinstance(item, str) and item.strip() else None,
  150. "Plugin %s: python_dependencies entry %r must be a non-empty requirement string; skipping",
  151. )
  152. schema = _config_schema_entries(key, _manifest_field_of_type(data, key, "config_schema", Mapping, "a mapping"))
  153. tags = [str(t) for t in (_manifest_field_of_type(data, key, "tags", list, "a list") or [])]
  154. config_keys = manifest_config_keys(data, key)
  155. # Forward compat: unknown fields warn (never fail); v1 manifests only at debug.
  156. unknown = sorted(set(data.keys()) - _KNOWN_MANIFEST_FIELDS)
  157. if unknown:
  158. (logger.warning if mv >= 2 else logger.debug)(
  159. "Plugin %s: unknown manifest field(s) ignored: %s "
  160. "(newer manifest schema or typo; plugin still loads)", key, ", ".join(unknown),
  161. )
  162. return {
  163. "manifest_version": mv, "api_version": api, "requires_plugins": deps, "python_dependencies": pydeps,
  164. "config_schema": schema, "license": str(data.get("license") or ""),
  165. "homepage": str(data.get("homepage") or ""), "tags": tags, "config_keys": config_keys,
  166. }
  167. def validate_config_schema(plugin_id: str, schema: Mapping, settings: Mapping) -> list[str]:
  168. """Return actionable warning strings for settings vs config_schema mismatches (never raises).
  169. Never raises; schema mismatches must not block plugin load (#64165).
  170. """
  171. warnings: list[str] = []
  172. if not isinstance(schema, Mapping) or not isinstance(settings, Mapping):
  173. return warnings
  174. for skey, spec in schema.items():
  175. if not isinstance(spec, Mapping):
  176. continue
  177. if skey not in settings:
  178. if spec.get("required") and "default" not in spec:
  179. warnings.append(
  180. f"plugins.entries.{plugin_id}.settings.{skey} is required "
  181. "by the plugin's config_schema but is not set"
  182. )
  183. continue
  184. stype = spec.get("type")
  185. expected = _CONFIG_SCHEMA_TYPES.get(str(stype).lower()) if stype else None
  186. if expected is None:
  187. continue
  188. value = settings[skey]
  189. # bool is an int subclass — don't let True satisfy int/float.
  190. if not isinstance(value, expected) or (isinstance(value, bool) and bool not in expected):
  191. warnings.append(
  192. f"plugins.entries.{plugin_id}.settings.{skey} should be "
  193. f"{stype} (got {type(value).__name__})"
  194. )
  195. return warnings
  196. def resolve_plugin_load_order(manifests: Mapping[str, PluginManifest]) -> list[str]:
  197. """Return plugin keys in dependency order: B before A when A requires B; alphabetical ties. A cycle warns
  198. and falls back to alphabetical order for all; a missing dependency warns once but never removes the
  199. dependent plugin (loads never hard-fail on advisory deps).
  200. See #64165.
  201. """
  202. import graphlib
  203. keys = sorted(manifests.keys())
  204. by_name: dict[str, str] = {}
  205. for k in keys:
  206. if manifests[k].name:
  207. by_name.setdefault(manifests[k].name, k)
  208. edges: dict[str, set[str]] = {k: set() for k in keys}
  209. for k in keys:
  210. for dep in manifests[k].requires_plugins:
  211. dep_id = dep.get("id") if isinstance(dep, Mapping) else None
  212. if not dep_id:
  213. continue
  214. resolved = dep_id if dep_id in manifests else by_name.get(dep_id)
  215. if resolved is None:
  216. logger.warning(
  217. "Plugin %s requires plugin '%s' which is not enabled/"
  218. "installed; loading anyway (probe availability at runtime "
  219. "via ctx.has_plugin). Run `hermes plugins enable %s` if it is installed.",
  220. k, dep_id, dep_id,
  221. )
  222. elif resolved == k:
  223. logger.warning("Plugin %s declares a dependency on itself; ignoring", k)
  224. else:
  225. edges[k].add(resolved)
  226. sorter = graphlib.TopologicalSorter(edges)
  227. try:
  228. sorter.prepare()
  229. except graphlib.CycleError as exc:
  230. cycle = exc.args[1] if len(exc.args) > 1 else []
  231. logger.warning(
  232. "Plugin dependency cycle detected (%s); falling back to "
  233. "alphabetical load order for all plugins", " -> ".join(str(c) for c in cycle),
  234. )
  235. return keys
  236. ordered: list[str] = []
  237. while sorter.is_active():
  238. ready = sorted(sorter.get_ready())
  239. ordered.extend(ready)
  240. sorter.done(*ready)
  241. return ordered
  242. def _detect_kind_from_source(source_text: str) -> Optional[str]:
  243. """Kind implied by source markers (mirrors plugins/memory ``_is_memory_provider_dir`` and
  244. plugins/cron_providers ``_is_cron_provider_dir``): memory-, cron- or computer-use-provider markers -> ``exclusive``;
  245. ``register_provider`` + ``ProviderProfile`` -> ``model-provider``; else ``None``. Keeps these kinds out
  246. of the general manager's eager import (its PluginContext has no ``register_cron_scheduler``, #62951)."""
  247. if any(marker in source_text for marker in (
  248. "register_memory_provider", "MemoryProvider", "register_cron_scheduler", "CronScheduler",
  249. "register_computer_use_provider", "ComputerUseProvider")):
  250. return "exclusive"
  251. if "register_provider" in source_text and "ProviderProfile" in source_text:
  252. return "model-provider"
  253. return None
  254. def _read_source_from_origin(origin: Optional[str], limit: int = 8192) -> str:
  255. """First ``limit`` chars of a module's source (``.pyc`` mapped back to ``.py``); "" on failure."""
  256. try:
  257. if origin and origin.endswith((".pyc", ".pyo")):
  258. origin = importlib.util.source_from_cache(origin)
  259. if not origin or not origin.endswith(".py"):
  260. return ""
  261. return Path(origin).read_text(encoding="utf-8-sig", errors="replace")[:limit]
  262. except Exception:
  263. return ""
  264. def resolve_module_origin(module_name: str) -> Optional[str]:
  265. """Return a module's source path WITHOUT importing it, or ``None``. ``find_spec`` on a dotted name imports
  266. the parent package, so only the top-level name uses it; remaining segments are walked through
  267. ``submodule_search_locations`` by hand. Namespace/zipped/extension modules return ``None``. Shared with
  268. ``plugins/memory/__init__.py``."""
  269. parts = [p for p in module_name.split(".") if p]
  270. if not parts:
  271. return None
  272. try:
  273. spec = importlib.util.find_spec(parts[0])
  274. if spec is None or not spec.origin:
  275. return None
  276. if len(parts) == 1:
  277. return spec.origin
  278. search_paths = spec.submodule_search_locations
  279. if not search_paths:
  280. return None
  281. for i, part in enumerate(parts[1:], start=2):
  282. found_origin = next_paths = None
  283. for base in map(Path, search_paths):
  284. pkg_init, mod_file = base / part / "__init__.py", base / (part + ".py")
  285. if pkg_init.is_file():
  286. found_origin, next_paths = str(pkg_init), [base / part]
  287. break
  288. if mod_file.is_file():
  289. found_origin = str(mod_file)
  290. break
  291. if found_origin is None:
  292. return None
  293. if i == len(parts) or next_paths is None:
  294. return found_origin
  295. search_paths = next_paths
  296. return None
  297. except Exception:
  298. return None
  299. def _resolve_module_source(module_name: str, limit: int = 8192) -> str:
  300. """First ``limit`` chars of a module's source without importing it ("" when unresolvable)."""
  301. return _read_source_from_origin(resolve_module_origin(module_name), limit)
  302. def manifest_key(manifest: PluginManifest) -> str:
  303. """Registry id of a manifest: the path-derived ``key`` when set, else the bare ``name``."""
  304. return manifest.key or manifest.name
  305. @dataclass
  306. class PluginManifest:
  307. """Parsed representation of a plugin.yaml manifest."""
  308. name: str
  309. version: str = ""
  310. description: str = ""
  311. author: str = ""
  312. requires_env: list[str | dict[str, Any]] = field(default_factory=list)
  313. provides_tools: list[str] = field(default_factory=list)
  314. provides_hooks: list[str] = field(default_factory=list)
  315. source: str = "" # "bundled", "user", "project", or "entrypoint"
  316. path: Optional[str] = None
  317. # ``standalone`` (default; opt-in via plugins.enabled) | ``backend`` (pluggable backend for a core tool;
  318. # bundled auto-load, user-installed gated) | ``exclusive`` (one active provider, selected via
  319. # <category>.provider; own discovery, general scanner skips) | ``platform`` (gateway adapter; bundled
  320. # auto-load, user-installed gated as untrusted code).
  321. kind: str = "standalone"
  322. # Path-derived registry key used by plugins.enabled/disabled and `hermes plugins list`: ``disk-cleanup``
  323. # for a flat plugin, ``image_gen/openai`` for a category plugin. Empty -> name.
  324. key: str = ""
  325. # Hermes version requirement (``">=0.19"``, comma-separated clauses allowed). Unsatisfied plugins are
  326. # recorded with an error and skipped before import — see ``requires_hermes_error``.
  327. requires_hermes: str = ""
  328. portable: bool = False
  329. # ``plugin-data/<data_namespace>`` for a portable plugin; its skills are named after the plugin
  330. # itself (``<name>:<skill>``), like every native plugin's.
  331. data_namespace: str = ""
  332. # Declared capability ids, normalized to KNOWN ids. Declaration is consent metadata, NOT a grant: live
  333. # only via plugins.entries.<id>.granted_capabilities or the legacy allow_* key.
  334. # See #64228.
  335. capabilities: list[str] = field(default_factory=list)
  336. # Manifest v2 fields — all optional and additive. manifest_version versions the FILE FORMAT (v1 supported
  337. # forever); api_version is the runtime plugin API generation (None = current).
  338. # Absent (v1) manifests are fully supported forever. See #64165.
  339. manifest_version: int = 1
  340. api_version: Optional[int] = None
  341. # Advisory deps [{"id", "version_range"}]: missing ones warn but load; they order the load.
  342. requires_plugins: list[dict[str, Any]] = field(default_factory=list)
  343. # Declared pip deps — VALIDATED AND SURFACED ONLY, never auto-installed.
  344. # VALIDATED AND SURFACED ONLY — Hermes never auto-installs these (isolation design for the install seam
  345. # is a deferred follow-up; see #64165 round-2 review and #15220).
  346. python_dependencies: list[str] = field(default_factory=list)
  347. # Schema for plugins.entries.<id>.settings; mismatches warn, never fail.
  348. config_schema: dict[str, Any] = field(default_factory=dict)
  349. license: str = ""
  350. homepage: str = ""
  351. tags: list[str] = field(default_factory=list)
  352. # Event-bus declarations, advisory (discoverability only): ``emits`` bare names published under
  353. # ``<key>:``; ``listens`` fully-qualified ``<plugin>:<event>`` names.
  354. emits: list[str] = field(default_factory=list)
  355. listens: list[str] = field(default_factory=list)
  356. # Language pack declaration: ids whose ``locales/<id>[.tui|.desktop].yaml`` the loader registers
  357. # automatically (no Python needed). ``locale_metadata`` carries the optional per-id
  358. # ``{endonym, rtl}`` from the mapping form of a ``provides_locales`` entry.
  359. provides_locales: list[str] = field(default_factory=list)
  360. locale_metadata: dict[str, dict[str, Any]] = field(default_factory=dict)
  361. # Dotted paths in Hermes' own config sections the plugin reads (``memory.retaindb``), so
  362. # ``hermes config get/set`` recognizes them while the plugin is active (hermes_cli/config_runtime_keys.py).
  363. config_keys: list[str] = field(default_factory=list)
  364. def parse_provides_locales(raw: Any, key: str = "") -> tuple[list[str], dict[str, dict[str, Any]]]:
  365. """``provides_locales`` -> (ids, metadata). Entries are ``"pl"`` or ``{id: pl, endonym: Polski, rtl: false}``;
  366. ids are canonicalised (lowercase, ``_`` -> ``-``), invalid or duplicate ones are dropped with a warning."""
  367. from agent.i18n_layers import is_language_id, normalize_language_id
  368. ids: list[str] = []
  369. metadata: dict[str, dict[str, Any]] = {}
  370. if raw is None:
  371. return ids, metadata
  372. if isinstance(raw, (str, Mapping)):
  373. raw = [raw]
  374. if not isinstance(raw, list):
  375. logger.warning("Plugin %s: provides_locales must be a list of language ids, got %s", key, type(raw).__name__)
  376. return ids, metadata
  377. for item in raw:
  378. entry_meta: dict[str, Any] = {}
  379. if isinstance(item, Mapping):
  380. lang_id = normalize_language_id(item.get("id", ""))
  381. if isinstance(item.get("endonym"), str) and item["endonym"].strip():
  382. entry_meta["endonym"] = item["endonym"].strip()
  383. if "rtl" in item:
  384. entry_meta["rtl"] = bool(item["rtl"])
  385. else:
  386. lang_id = normalize_language_id(item)
  387. if not is_language_id(lang_id):
  388. logger.warning("Plugin %s: ignoring invalid provides_locales entry %r", key, item)
  389. continue
  390. if lang_id in ids:
  391. logger.warning("Plugin %s: duplicate provides_locales entry %r", key, lang_id)
  392. continue
  393. ids.append(lang_id)
  394. if entry_meta:
  395. metadata[lang_id] = entry_meta
  396. return ids, metadata
  397. # ── requires_hermes version gate ─────────────────────────────────────────────
  398. _VERSION_COMPARATOR_RE = re.compile(r"^\s*(>=|<=|==|!=|>|<)\s*(.+?)\s*$")
  399. def running_hermes_version() -> str:
  400. """Base release version of the Hermes code that is running."""
  401. from hermes_cli.version_info import get_version_info
  402. return get_version_info().base_version
  403. _VERSION_SEGMENT_RE = re.compile(r"^\d+")
  404. def _version_tuple(v: str) -> Optional[tuple]:
  405. """``v1.2.3-rc1`` / ``1.2.3rc1`` / ``1.2.3.post1`` → ``(1, 2, 3)``; ``None`` when a segment has no
  406. leading digits. PEP 440 pre/post/dev suffixes glued to a segment (``0rc1``) are dropped so an rc
  407. *target* still gates and an rc *running* version does not disable every gate."""
  408. parts = re.split(r"[-+]", str(v).strip().lstrip("v"), 1)[0].split(".")
  409. parts += ["0"] * (3 - len(parts))
  410. out = []
  411. for x in parts[:3]:
  412. m = _VERSION_SEGMENT_RE.match(x.strip())
  413. if m is None:
  414. return None
  415. out.append(int(m.group(0)))
  416. return tuple(out)
  417. def version_satisfies(spec: str, current: str) -> bool:
  418. """``>=``/``>``/``<=``/``<``/``==``/``!=`` clauses (comma = AND; bare version = ``>=``). Unparseable
  419. versions are permissive — no PEP 440 dependency for a one-field manifest gate."""
  420. cur = _version_tuple(current)
  421. if cur is None:
  422. return True
  423. ops = {">=": cur.__ge__, "<=": cur.__le__, "==": cur.__eq__, "!=": cur.__ne__, ">": cur.__gt__, "<": cur.__lt__}
  424. for clause in filter(None, (c.strip() for c in spec.split(","))):
  425. m = _VERSION_COMPARATOR_RE.match(clause)
  426. op, target = (m.group(1), m.group(2)) if m else (">=", clause)
  427. tgt = _version_tuple(target)
  428. if tgt is not None and not ops[op](tgt):
  429. return False
  430. return True
  431. def requires_hermes_error(manifest: PluginManifest | Mapping[str, Any]) -> Optional[str]:
  432. """Load-blocking reason when the manifest's ``requires_hermes`` rejects the running version."""
  433. spec = manifest.get("requires_hermes", "") if isinstance(manifest, Mapping) else manifest.requires_hermes
  434. if not spec:
  435. return None
  436. current = running_hermes_version()
  437. if version_satisfies(spec, current):
  438. return None
  439. return f"requires hermes {spec}, running {current}"
  440. def portable_plugin_manifest(child: Path, source: str, prefix: str) -> PluginManifest:
  441. """Build the manifest for a portable Agent Plugin directory (``plugin.json``); diagnostics warn."""
  442. from hermes_cli.agent_plugins import manifest_config_schema, manifest_hermes_extension, read_agent_plugin_manifest
  443. data, diagnostics = read_agent_plugin_manifest(child)
  444. for diagnostic in diagnostics:
  445. logger.warning("Agent Plugin '%s': %s", child, diagnostic.message)
  446. key = f"{prefix}/{child.name}" if prefix else data["name"]
  447. return PluginManifest(
  448. name=data["name"], version=data.get("version", ""), description=data.get("description", ""),
  449. author=_display_author(data.get("author", "")), source=source, path=str(child), key=key,
  450. portable=True, data_namespace=_portable_data_namespace(key),
  451. config_schema=_config_schema_entries(key, manifest_config_schema(data)),
  452. config_keys=manifest_config_keys(manifest_hermes_extension(data), key),
  453. )
  454. def _manifest_kind(data: Mapping, key: str, plugin_dir: Path) -> str:
  455. """Normalize ``kind``; undeclared memory/model providers are auto-detected from ``__init__.py`` so they
  456. route to their own discovery instead of the general manager."""
  457. raw_kind = data.get("kind", "standalone")
  458. kind = raw_kind.strip().lower() if isinstance(raw_kind, str) else "standalone"
  459. if kind not in _VALID_PLUGIN_KINDS:
  460. logger.warning(
  461. "Plugin %s: unknown kind '%s' (valid: %s); treating as 'standalone'",
  462. key, raw_kind, ", ".join(sorted(_VALID_PLUGIN_KINDS)),
  463. )
  464. kind = "standalone"
  465. init_file = plugin_dir / "__init__.py"
  466. if kind == "standalone" and "kind" not in data and init_file.exists():
  467. with suppress(Exception):
  468. source_text = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]
  469. detected = _detect_kind_from_source(source_text)
  470. if detected:
  471. kind = detected
  472. logger.debug("Plugin %s: detected %s, treating as kind='%s'", key, detected, detected)
  473. return kind
  474. def parse_manifest_file(
  475. manifest_file: Path, plugin_dir: Path, source: str, prefix: str
  476. ) -> Optional[PluginManifest]:
  477. """Parse one ``plugin.yaml`` into a :class:`PluginManifest`; ``None`` (warned) on failure."""
  478. try:
  479. if yaml is None:
  480. logger.warning("ruamel.yaml not installed – cannot load %s", manifest_file)
  481. return None
  482. data = fast_safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}
  483. if not isinstance(data, Mapping):
  484. logger.warning("Failed to parse %s: top level must be a mapping, got %s (#14066)",
  485. manifest_file, type(data).__name__)
  486. return None
  487. name = data.get("name", plugin_dir.name)
  488. key = f"{prefix}/{plugin_dir.name}" if prefix else name
  489. kind = _manifest_kind(data, key, plugin_dir)
  490. logger.debug(
  491. "Parsed manifest: key=%s name=%s kind=%s source=%s path=%s", key, name, kind, source, plugin_dir)
  492. provides_locales, locale_metadata = parse_provides_locales(data.get("provides_locales"), key)
  493. return PluginManifest(
  494. name=name, version=str(data.get("version", "")),
  495. description=data.get("description", ""), author=_display_author(data.get("author", "")),
  496. requires_env=data.get("requires_env", []),
  497. provides_tools=data.get("provides_tools", []),
  498. # ``hooks:`` is the spelling the bundled manifests carried for months; external copies of it
  499. # must keep declaring the same thing (#108371).
  500. provides_hooks=data.get("provides_hooks", data.get("hooks", [])), source=source, path=str(plugin_dir),
  501. kind=kind, key=key, requires_hermes=str(data.get("requires_hermes") or "").strip(),
  502. capabilities=_parse_declared_capabilities(data.get("capabilities"), name),
  503. **_parse_manifest_v2_fields(data, key), emits=data.get("emits") or [],
  504. listens=data.get("listens") or [],
  505. provides_locales=provides_locales, locale_metadata=locale_metadata,
  506. )
  507. except Exception as exc:
  508. logger.warning("Failed to parse %s: %s", manifest_file, exc, exc_info=_plugins_debug())
  509. return None