app.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. """Desktop-application resolver over an `AppDef` (parsed from an MCP manifest's `app:` block).
  2. `locate` stats every declared location in order (fixed paths, PATH, uninstall entries, the flatpak,
  3. snap and Applications directories) and lists directories for a `*` path segment; the first present
  4. one wins. `inspect` reads the version source in-process.
  5. `probe` re-reads the vendor's runtime file on every call; the bearer token in it never
  6. leaves this module.
  7. """
  8. from __future__ import annotations
  9. import glob
  10. import json
  11. import os
  12. import plistlib
  13. import re
  14. import sys
  15. import time
  16. from dataclasses import dataclass
  17. from typing import Any, Callable, Iterator, Literal
  18. from urllib.parse import urlsplit
  19. from hermes_platform.resolver import known_dirs
  20. from hermes_platform.resolver.base import Effort, Inspection, Probe
  21. from hermes_platform.resolver.core import (
  22. Candidate,
  23. CheckState,
  24. Kind,
  25. LookupContext,
  26. Observation,
  27. Resolution,
  28. locate_command,
  29. )
  30. PresenceKind = Literal["executable", "bundle"]
  31. VersionKind = Literal["pe_resource", "plist", "uninstall_registry", "none"]
  32. LivenessKind = Literal["server_json", "none"]
  33. _LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})
  34. @dataclass(frozen=True)
  35. class AppLocation:
  36. """One place to look. `kind` is `path` or a key of `LOCATION_KINDS`. `value` is the path, or the
  37. value of that kind's `key`. `file` is joined onto an uninstall entry's `InstallLocation`."""
  38. kind: str
  39. value: str
  40. file: str = ""
  41. @dataclass(frozen=True)
  42. class AppDef:
  43. """One application on one OS. Paths use `%VAR%` and `~`; expansion happens at lookup."""
  44. app_id: str
  45. os_family: str
  46. presence: PresenceKind
  47. locations: tuple[AppLocation, ...]
  48. version_kind: VersionKind = "none"
  49. version_arg: str = ""
  50. liveness_kind: LivenessKind = "none"
  51. liveness_path: str = ""
  52. liveness_pid_key: str = "pid"
  53. liveness_url_key: str = "http"
  54. liveness_token_key: str = "token"
  55. endpoint_path: str = "/mcp"
  56. def _expand(path: str) -> str:
  57. return os.path.expandvars(os.path.expanduser(path))
  58. @dataclass(frozen=True)
  59. class Endpoint:
  60. url: str
  61. token: str = ""
  62. def __repr__(self) -> str:
  63. return f"Endpoint(url={self.url!r}, token=<redacted>)"
  64. @dataclass(frozen=True)
  65. class AppResolver:
  66. definition: AppDef
  67. @property
  68. def name(self) -> str:
  69. return self.definition.app_id
  70. # ---- locate: stat only -------------------------------------------------------------
  71. def locate(self, ctx: LookupContext | None = None) -> Resolution:
  72. d = self.definition
  73. found = [hit for loc in d.locations for hit in _locator(loc.kind)(d, loc, ctx)]
  74. kind: Kind = next((k for c, k in found if c.present), "missing")
  75. return Resolution(kind, tuple(c for c, _ in found))
  76. # ---- inspect: bounded file reads and in-process OS APIs -----------------------------
  77. def inspect(self, res: Resolution, ctx: LookupContext | None = None) -> Inspection:
  78. if not res.found:
  79. return Inspection(Observation.not_checked(), Observation.not_checked())
  80. return Inspection(version=self._version(res.command[0]), signer=Observation.not_checked())
  81. def _version(self, path: str) -> Observation[str]:
  82. kind = self.definition.version_kind
  83. try:
  84. if kind == "none":
  85. return Observation.not_checked()
  86. if kind == "plist":
  87. return _plist_version(path)
  88. if kind == "pe_resource":
  89. return _pe_version(path)
  90. if kind == "uninstall_registry":
  91. return _uninstall_registry_version(self.definition.version_arg)
  92. except Exception as exc: # a vendor's plist/PE/registry entry is untrusted input; never abort the caller
  93. return Observation(CheckState.ERROR, detail=exc.__class__.__name__)
  94. return Observation(CheckState.UNAVAILABLE, detail=f"unknown version kind {kind}")
  95. # ---- probe: fresh, never cached ------------------------------------------------------
  96. def endpoint(self) -> Endpoint | None:
  97. """Read and validate the current runtime endpoint."""
  98. d = self.definition
  99. if d.liveness_kind != "server_json":
  100. return None
  101. session = _read_server_json(_expand(d.liveness_path), d)
  102. if session is None or _pid_alive(session.pid).value is not True:
  103. return None
  104. endpoint = _endpoint_observation(session.url, d.endpoint_path)
  105. if endpoint.state is not CheckState.PRESENT or not endpoint.value:
  106. return None
  107. return Endpoint(endpoint.value, session.token)
  108. def probe(self, res: Resolution, *, effort: Effort, deadline_s: float = 3.0) -> Probe:
  109. d = self.definition
  110. nc: Observation = Observation.not_checked()
  111. if d.liveness_kind != "server_json":
  112. return Probe(running=nc, answering=nc, endpoint=nc)
  113. session = _read_server_json(_expand(d.liveness_path), d)
  114. if session is None:
  115. absent = Observation(CheckState.ABSENT, False, "runtime file missing or unreadable")
  116. return Probe(running=absent, answering=nc, endpoint=Observation(CheckState.ABSENT))
  117. running = _pid_alive(session.pid)
  118. endpoint_obs = _endpoint_observation(session.url, d.endpoint_path)
  119. if effort is Effort.LOCAL or running.value is not True or endpoint_obs.state is not CheckState.PRESENT:
  120. return Probe(running=running, answering=nc, endpoint=endpoint_obs)
  121. answering = _mcp_initialize(session, endpoint_obs.value or "", deadline_s)
  122. return Probe(running=running, answering=answering, endpoint=endpoint_obs)
  123. # ---- locations: each yields (candidate, resolution kind) in probe order -----------------
  124. _Hit = tuple[Candidate, Kind]
  125. _Locator = Callable[[AppDef, AppLocation, LookupContext | None], list[_Hit]]
  126. def _present(presence: PresenceKind, path: str) -> bool:
  127. if presence == "bundle":
  128. return os.path.isdir(path) and os.path.isfile(os.path.join(path, "Contents", "Info.plist"))
  129. return os.path.isfile(path)
  130. def _hit(d: AppDef, source: str, path: str) -> _Hit:
  131. present = os.path.isabs(path) and _present(d.presence, path)
  132. return Candidate(path, source, present), "known_path"
  133. def _version_order(path: str) -> list:
  134. return [(1, int(part)) if part.isdigit() else (0, part) for part in re.split(r"(\d+)", path)]
  135. def _path_hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
  136. target, source = _expand(loc.value), f"app:{d.app_id}"
  137. not_found: list[_Hit] = [(Candidate(target, source, False), "known_path")]
  138. if not os.path.isabs(target) or "%" in target or "$" in target:
  139. return not_found
  140. if "*" not in target:
  141. return [_hit(d, source, target)]
  142. # A `*` segment stands for a versioned folder (`Blender 5.2`); the highest version is tried first.
  143. pattern = "*".join(glob.escape(part) for part in target.split("*"))
  144. matches = sorted(glob.glob(pattern), key=_version_order, reverse=True)
  145. return [_hit(d, source, match) for match in matches] or not_found
  146. def _command_hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
  147. res = locate_command(loc.value, ctx)
  148. return [(Candidate(c.value, f"app:{d.app_id}:{loc.kind}", c.present), "path_executable") for c in res.candidates]
  149. def _uninstall_hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
  150. if sys.platform != "win32":
  151. return []
  152. # A UNC InstallLocation is skipped so a presence check never touches the network.
  153. return [_hit(d, f"app:{d.app_id}:{loc.kind}", os.path.join(entry["InstallLocation"], loc.file))
  154. for entry in _uninstall_entries(loc.value)
  155. if entry.get("InstallLocation") and not entry["InstallLocation"].startswith(("\\\\", "//"))]
  156. def _in_dirs(dirs: Callable[[], tuple[str, ...]]) -> _Locator:
  157. def hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
  158. return [_hit(d, f"app:{d.app_id}:{loc.kind}", os.path.join(_expand(root), loc.value)) for root in dirs()]
  159. return hits
  160. @dataclass(frozen=True)
  161. class LocationSpec:
  162. """A location kind a declaration names in a mapping. `only_on` is the one OS family it is valid
  163. under (None: any), `key` names the mapping field holding what to find, `yields` is the presence
  164. it finds, and `needs_file` says the mapping also carries a relative `file`."""
  165. only_on: str | None
  166. key: str
  167. yields: PresenceKind
  168. locate: _Locator
  169. needs_file: bool = False
  170. LOCATION_KINDS: dict[str, LocationSpec] = {
  171. "command": LocationSpec(None, "name", "executable", _command_hits),
  172. "uninstall_registry": LocationSpec("win32", "display_name_prefix", "executable", _uninstall_hits, needs_file=True),
  173. "app_bundle": LocationSpec("darwin", "name", "bundle", _in_dirs(known_dirs.mac_application_dirs)),
  174. "flatpak": LocationSpec("linux", "app_id", "executable", _in_dirs(known_dirs.flatpak_export_dirs)),
  175. "snap": LocationSpec("linux", "name", "executable", _in_dirs(known_dirs.snap_bin_dirs)),
  176. }
  177. def _locator(kind: str) -> _Locator:
  178. """A plain string location is a `path`; every other kind comes from `LOCATION_KINDS`."""
  179. return _path_hits if kind == "path" else LOCATION_KINDS[kind].locate
  180. # ---- version sources -------------------------------------------------------------------
  181. def _plist_version(bundle: str) -> Observation[str]:
  182. with open(os.path.join(bundle, "Contents", "Info.plist"), "rb") as fh: # windows-footgun: ok — binary mode
  183. info = plistlib.load(fh)
  184. value = info.get("CFBundleShortVersionString") or info.get("CFBundleVersion")
  185. if not value:
  186. return Observation(CheckState.UNAVAILABLE, detail="no version key in Info.plist")
  187. return Observation(CheckState.PRESENT, str(value))
  188. def _pe_version(path: str) -> Observation[str]:
  189. if sys.platform != "win32":
  190. return Observation(CheckState.UNAVAILABLE, detail="pe_resource needs Windows")
  191. import ctypes
  192. from ctypes import wintypes
  193. ver = ctypes.windll.version # type: ignore[attr-defined]
  194. ver.GetFileVersionInfoSizeW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.DWORD)]
  195. ver.GetFileVersionInfoSizeW.restype = wintypes.DWORD
  196. size = ver.GetFileVersionInfoSizeW(path, None)
  197. if not size:
  198. return Observation(CheckState.UNAVAILABLE, detail="no version resource")
  199. buf = ctypes.create_string_buffer(size)
  200. ver.GetFileVersionInfoW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]
  201. ver.GetFileVersionInfoW.restype = wintypes.BOOL
  202. if not ver.GetFileVersionInfoW(path, 0, size, buf):
  203. return Observation(CheckState.ERROR, detail="GetFileVersionInfoW failed")
  204. ptr = ctypes.c_void_p()
  205. length = wintypes.UINT()
  206. ver.VerQueryValueW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.UINT)]
  207. ver.VerQueryValueW.restype = wintypes.BOOL
  208. if not ver.VerQueryValueW(buf, "\\", ctypes.byref(ptr), ctypes.byref(length)) or not ptr.value:
  209. return Observation(CheckState.UNAVAILABLE, detail="no fixed file info")
  210. # VS_FIXEDFILEINFO: dwFileVersionMS at offset 8, dwFileVersionLS at offset 12.
  211. ms = ctypes.cast(ptr.value + 8, ctypes.POINTER(wintypes.DWORD)).contents.value
  212. ls = ctypes.cast(ptr.value + 12, ctypes.POINTER(wintypes.DWORD)).contents.value
  213. return Observation(CheckState.PRESENT, f"{ms >> 16}.{ms & 0xFFFF}.{ls >> 16}.{ls & 0xFFFF}")
  214. def _uninstall_values(entry: Any) -> dict[str, str]:
  215. """The uninstall entry's values that exist; any of them may be missing."""
  216. import winreg
  217. values: dict[str, str] = {}
  218. for value_name in ("DisplayName", "DisplayVersion", "InstallLocation"):
  219. try:
  220. values[value_name] = str(winreg.QueryValueEx(entry, value_name)[0])
  221. except OSError:
  222. continue
  223. return values
  224. def _uninstall_entry(key: Any, index: int) -> dict[str, str]:
  225. """One child entry's values; an entry can vanish between EnumKey and OpenKey, which reads as no values."""
  226. import winreg
  227. try:
  228. with winreg.OpenKey(key, winreg.EnumKey(key, index)) as entry:
  229. return _uninstall_values(entry)
  230. except OSError:
  231. return {}
  232. def _uninstall_entries(display_name_prefix: str) -> Iterator[dict[str, str]]:
  233. """Each uninstall entry whose `DisplayName` starts with the prefix, machine-wide before per-user."""
  234. import winreg
  235. roots = (
  236. (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"),
  237. (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"),
  238. (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"),
  239. )
  240. for hive, root in roots:
  241. try:
  242. with winreg.OpenKey(hive, root) as key:
  243. count = winreg.QueryInfoKey(key)[0]
  244. for i in range(count):
  245. values = _uninstall_entry(key, i)
  246. if values.get("DisplayName", "").startswith(display_name_prefix):
  247. yield values
  248. except OSError:
  249. continue
  250. def _uninstall_registry_version(display_name_prefix: str) -> Observation[str]:
  251. if sys.platform != "win32":
  252. return Observation(CheckState.UNAVAILABLE, detail="uninstall_registry needs Windows")
  253. entry = next(_uninstall_entries(display_name_prefix), None)
  254. if entry is None:
  255. return Observation(CheckState.ABSENT, detail="no uninstall entry")
  256. if "DisplayVersion" not in entry:
  257. return Observation(CheckState.UNAVAILABLE, detail="entry has no DisplayVersion")
  258. return Observation(CheckState.PRESENT, entry["DisplayVersion"])
  259. # ---- liveness: the token stays inside this section -------------------------------------
  260. @dataclass(frozen=True)
  261. class _Session:
  262. pid: int | None
  263. url: str
  264. token: str
  265. def __repr__(self) -> str:
  266. return f"_Session(pid={self.pid}, url={self.url!r}, token=<redacted>)"
  267. def _read_server_json(path: str, d: AppDef) -> _Session | None:
  268. try:
  269. with open(path, encoding="utf-8") as fh:
  270. data = json.load(fh)
  271. except (OSError, ValueError):
  272. return None
  273. if not isinstance(data, dict):
  274. return None
  275. pid = data.get(d.liveness_pid_key)
  276. url = data.get(d.liveness_url_key)
  277. token = data.get(d.liveness_token_key)
  278. return _Session(
  279. pid=pid if isinstance(pid, int) else None,
  280. url=url if isinstance(url, str) else "",
  281. token=token if isinstance(token, str) else "",
  282. )
  283. def _pid_alive(pid: int | None) -> Observation[bool]:
  284. if pid is None or pid <= 0:
  285. return Observation(CheckState.UNAVAILABLE, detail="no pid in runtime file")
  286. if sys.platform == "win32":
  287. import ctypes
  288. from ctypes import wintypes
  289. k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
  290. k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
  291. k32.OpenProcess.restype = wintypes.HANDLE
  292. handle = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
  293. if not handle:
  294. return Observation(CheckState.ABSENT, False)
  295. k32.CloseHandle.argtypes = [wintypes.HANDLE]
  296. k32.CloseHandle(handle)
  297. return Observation(CheckState.PRESENT, True)
  298. try:
  299. os.kill(pid, 0) # windows-footgun: ok — POSIX only, the win32 branch returned above
  300. except ProcessLookupError:
  301. return Observation(CheckState.ABSENT, False)
  302. except PermissionError:
  303. return Observation(CheckState.PRESENT, True)
  304. return Observation(CheckState.PRESENT, True)
  305. def _endpoint_observation(raw_url: str, fixed_path: str) -> Observation[str]:
  306. """Accept only a loopback http URL with a numeric port and no userinfo; the path is ours."""
  307. if not raw_url:
  308. return Observation(CheckState.UNAVAILABLE, detail="no url in runtime file")
  309. try:
  310. parts = urlsplit(raw_url)
  311. hostname, port, username, password = parts.hostname, parts.port, parts.username, parts.password
  312. except ValueError:
  313. return Observation(CheckState.UNAVAILABLE, detail="malformed endpoint")
  314. if parts.scheme != "http" or username or password:
  315. return Observation(CheckState.UNAVAILABLE, detail="endpoint must be plain http without userinfo")
  316. if hostname not in _LOOPBACK_HOSTS:
  317. return Observation(CheckState.UNAVAILABLE, detail="endpoint must be loopback")
  318. if port is None or not (1 <= port <= 65535):
  319. return Observation(CheckState.UNAVAILABLE, detail="endpoint needs a numeric port")
  320. return Observation(CheckState.PRESENT, f"http://{hostname}:{port}{fixed_path}")
  321. def _mcp_initialize(session: _Session, endpoint: str, deadline_s: float) -> Observation[bool]:
  322. """One MCP `initialize` POST under one absolute deadline covering connect, headers, and body."""
  323. import http.client
  324. parts = urlsplit(endpoint)
  325. body = json.dumps({
  326. "jsonrpc": "2.0", "id": 1, "method": "initialize",
  327. "params": {"protocolVersion": "2025-06-18", "capabilities": {},
  328. "clientInfo": {"name": "hermes", "version": "probe"}},
  329. }).encode()
  330. headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
  331. if session.token:
  332. headers["Authorization"] = f"Bearer {session.token}"
  333. deadline = time.monotonic() + max(0.1, deadline_s)
  334. def remaining() -> float:
  335. left = deadline - time.monotonic()
  336. if left <= 0:
  337. raise TimeoutError
  338. return left
  339. conn = http.client.HTTPConnection(parts.hostname or "127.0.0.1", parts.port or 80, timeout=remaining())
  340. try:
  341. conn.request("POST", parts.path or "/", body=body, headers=headers)
  342. conn.sock.settimeout(remaining())
  343. status = conn.getresponse().status
  344. except TimeoutError:
  345. return Observation(CheckState.ABSENT, False, f"no answer within {deadline_s:g} s")
  346. except (OSError, http.client.HTTPException):
  347. return Observation(CheckState.ABSENT, False, "connection refused or timed out")
  348. finally:
  349. conn.close()
  350. if status in (200, 401, 403):
  351. return Observation(CheckState.PRESENT, True, f"http {status}")
  352. return Observation(CheckState.ABSENT, False, f"http {status}")