plugin_catalog_presence.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """Whether the desktop app a catalog plugin drives is on this machine, before the plugin is installed.
  2. A portable plugin declares its app in ``plugin.json`` (``extensions.com.nousresearch.hermes.servers``).
  3. The catalog pins the commit, so the declaration is read once per pin from the repo at that commit and
  4. judged by the same ``hermes_platform`` resolver the installer and the Plugins-tab pill use. Nothing is
  5. installed, spawned or connected. Any failure to read the declaration is ``unknown``, never a guess.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import logging
  10. import re
  11. from dataclasses import dataclass
  12. from typing import Any, Dict, Optional, Tuple
  13. logger = logging.getLogger(__name__)
  14. _GITHUB = re.compile(r"^https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+?)(?:\.git)?/?$")
  15. _TIMEOUT = 5.0
  16. _MAX_BYTES = 256 * 1024
  17. _DISCLOSURE = re.compile(r"\bDisclosure\s*[:\u2014]\s*(.+)")
  18. # (repo, sha, subdir) -> manifest dict, or None when the pin has no readable plugin.json. A pin is
  19. # immutable, so the process keeps the answer.
  20. _manifests: dict[tuple[str, str, str], Optional[dict[str, Any]]] = {}
  21. @dataclass(frozen=True)
  22. class Presence:
  23. """``state`` uses the card's vocabulary (``CatalogAppState``); ``sentence`` is empty when present or unknown."""
  24. state: str
  25. sentence: str = ""
  26. UNKNOWN = Presence("unknown")
  27. def _raw_manifest_url(repo: str, sha: str, subdir: str) -> Optional[str]:
  28. match = _GITHUB.match(repo.strip())
  29. if not match:
  30. return None
  31. path = "/".join(p for p in (subdir.strip("/"), "plugin.json") if p)
  32. return f"https://raw.githubusercontent.com/{match.group(1)}/{match.group(2)}/{sha}/{path}"
  33. def _pinned_manifest(repo: str, sha: str, subdir: str) -> Optional[dict[str, Any]]:
  34. key = (repo, sha, subdir)
  35. if key in _manifests:
  36. return _manifests[key]
  37. url = _raw_manifest_url(repo, sha, subdir)
  38. manifest: Optional[dict[str, Any]] = None
  39. if url:
  40. try:
  41. import httpx
  42. resp = httpx.get(url, timeout=_TIMEOUT, follow_redirects=True)
  43. if resp.status_code == 200 and len(resp.content) <= _MAX_BYTES:
  44. data = json.loads(resp.content)
  45. manifest = data if isinstance(data, dict) else None
  46. elif resp.status_code != 404:
  47. return None # transient: do not remember
  48. except Exception as exc:
  49. logger.debug("plugin catalog presence: %s unreadable: %s", url, exc)
  50. return None
  51. _manifests[key] = manifest
  52. return manifest
  53. def _server_presence(decl: Any, liveness_raw: Any, title: str) -> Presence:
  54. from hermes_platform.declaration import gpu_label
  55. from hermes_platform.host import facts
  56. from hermes_platform.resolver.app import AppResolver
  57. from hermes_platform.resolver.availability import availability
  58. from hermes_platform.resolver.base import Effort
  59. from tools.mcp_liveness import parse_liveness
  60. available = availability(decl)
  61. if available.state == "no_requirements":
  62. return UNKNOWN
  63. if available.state in ("missing_app", "unsupported_os"):
  64. return Presence("missing_app", f"needs {title}")
  65. if available.state == "unsupported_gpu":
  66. return Presence("missing_app", f"needs {gpu_label(decl.required_gpu)}")
  67. if available.state == "version_too_old":
  68. found = f" (found {available.version})" if available.version else ""
  69. return Presence("missing_app", f"needs {title} {available.min_version} or newer{found}")
  70. try:
  71. live = parse_liveness(liveness_raw) if liveness_raw is not None else None
  72. except ValueError:
  73. live = None
  74. if live is None or live.kind == "static":
  75. return Presence("present")
  76. if live.kind == "interactive_session":
  77. return Presence("present") if facts.interactive_session() else Presence(
  78. "app_not_running", f"{title} needs an interactive desktop session")
  79. definition = decl.app_for(facts.os_family())
  80. if definition is None:
  81. return Presence("missing_app", f"needs {title}")
  82. resolver = AppResolver(live.app_definition(definition))
  83. probe = resolver.probe(resolver.locate(), effort=Effort.LOCAL)
  84. return Presence("present") if probe.running.value is True else Presence(
  85. "app_not_running", f"{title} is not running")
  86. def presence(entry: Any) -> Presence:
  87. """The app state of one catalog entry on this host. The worst server wins (missing, then not running)."""
  88. from hermes_cli.agent_plugins import _server_declarations
  89. manifest = _pinned_manifest(entry.repo, entry.sha, entry.subdir)
  90. if not manifest:
  91. return UNKNOWN
  92. raw_servers = (manifest.get("extensions") or {}).get("com.nousresearch.hermes", {}).get("servers") or {}
  93. if not isinstance(raw_servers, dict) or not raw_servers:
  94. return UNKNOWN
  95. try:
  96. declarations = _server_declarations(manifest, {name: {} for name in raw_servers})
  97. except Exception as exc:
  98. logger.debug("plugin catalog presence: %s declaration invalid: %s", entry.name, exc)
  99. return UNKNOWN
  100. title = getattr(entry, "title", "") or entry.name
  101. rank = {"missing_app": 0, "app_not_running": 1, "present": 2, "unknown": 3}
  102. found = [_server_presence(d.declaration, d.liveness, title) for d in declarations.values()]
  103. return min(found, key=lambda p: rank[p.state]) if found else UNKNOWN
  104. def _onboarding_catalog() -> list:
  105. """Catalog entries curated for onboarding (``onboarding: true``) that this OS can run."""
  106. from hermes_cli.plugin_catalog import load_catalog_live
  107. from hermes_cli.plugins_cmd_catalog import normalized_platforms
  108. from hermes_platform.host.facts import os_family
  109. here = os_family()
  110. return [entry for entry in load_catalog_live()
  111. if entry.onboarding and (not entry.platforms or here in normalized_platforms(entry.platforms))]
  112. def onboarding_names() -> list[str]:
  113. """The onboarding plugins this OS runs, by catalog name; no presence probe."""
  114. return [entry.name for entry in _onboarding_catalog()]
  115. def onboarding_entries() -> list[dict[str, Any]]:
  116. """Catalog entries curated for the onboarding card (``onboarding: true``) that this OS can run,
  117. each with its app state. Platform mismatch is the only exclusion; a missing app is reported."""
  118. rows = []
  119. for entry in _onboarding_catalog():
  120. found = presence(entry)
  121. rows.append({
  122. "name": entry.name,
  123. "title": entry.title or entry.name,
  124. "description": _first_sentence(entry.description),
  125. "tier": entry.tier,
  126. "platforms": list(entry.platforms),
  127. "app_state": found.state,
  128. "sentence": found.sentence,
  129. })
  130. return rows
  131. def presence_for(names: list[str]) -> list[dict[str, Any]]:
  132. """The named catalog plugins this OS runs, in the order asked, each with its app state and the
  133. catalog description's disclosure. A name the live catalog does not carry (unknown or removed) is dropped."""
  134. from concurrent.futures import ThreadPoolExecutor
  135. from hermes_cli.plugin_catalog import load_catalog_live
  136. from hermes_cli.plugins_cmd_catalog import normalized_platforms
  137. from hermes_platform.host.facts import os_family
  138. here = os_family()
  139. by_name = {entry.name: entry for entry in load_catalog_live()}
  140. entries = [by_name[name] for name in dict.fromkeys(names) if name in by_name
  141. and (not by_name[name].platforms or here in normalized_platforms(by_name[name].platforms))]
  142. if not entries:
  143. return []
  144. # Each manifest read is bounded by _TIMEOUT; in parallel the whole answer waits one timeout, not one per name.
  145. with ThreadPoolExecutor(max_workers=len(entries)) as pool:
  146. found = list(pool.map(presence, entries))
  147. return [{"name": entry.name, "title": entry.title or entry.name, "state": state.state,
  148. "sentence": state.sentence, "disclosure": _disclosure(entry.description)}
  149. for entry, state in zip(entries, found)]
  150. def _disclosure(text: str) -> str:
  151. """The sentence after the description's ``Disclosure:`` (or ``Disclosure —``) marker; empty when absent."""
  152. match = _DISCLOSURE.search(" ".join(str(text or "").split()))
  153. return _first_sentence(match.group(1)) if match else ""
  154. def _first_sentence(text: str) -> str:
  155. text = " ".join(str(text or "").split())
  156. head, dot, _rest = text.partition(". ")
  157. return f"{head}." if dot else text