The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
hermes_platform.resolver: locate/inspect/probe tiers, AppResolver, gh lookup migrated (NS-921) (#118065)
Siddharth Balyan4094ab610dc7
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 8ddbeb89030..5f330639129 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -24,7 +24,7 @@ from agent.runtime_cwd import resolve_agent_cwdfrom agent.skill_utils import (EXCLUDED_SKILL_DIRS, ORG_ACTIVE_MARKER, ORG_MIRROR_DIR_NAME, ORG_PROVENANCE_FILE, SKILL_SUPPORT_DIRS,extract_skill_conditions, extract_skill_description, get_all_skills_dirs, get_disabled_skill_names,- iter_skill_index_files, parse_frontmatter, read_active_org_id, skill_matches_environment,+ iter_skill_index_files, parse_frontmatter, read_active_org_id, skill_matches_apps, skill_matches_environment,skill_matches_platform, skill_matches_platform_list,)from tools.threat_patterns import scan_for_threats as _scan_for_threats@@ -1116,7 +1116,7 @@ _SKILLS_PROMPT_CACHE_MAX = 32_SKILLS_PROMPT_CACHE: OrderedDict[tuple, str] = OrderedDict()_SKILLS_PROMPT_CACHE_LOCK = threading.Lock()# v2 added org provenance fields (org_id/org_author); older snapshots are rebuilt.-_SKILLS_SNAPSHOT_VERSION = 2+_SKILLS_SNAPSHOT_VERSION = 3def _skills_prompt_snapshot_path() -> Path:@@ -1177,6 +1177,12 @@ def _load_skills_snapshot(skills_dir: Path) -> Optional[dict]:return None+def _requires_apps_list(frontmatter: dict) -> list[str]:+ raw = frontmatter.get("requires_apps")+ items = raw if isinstance(raw, list) else [raw] if raw else []+ return [str(a).strip() for a in items if str(a).strip()]++def _build_snapshot_entry(skill_file: Path, skills_dir: Path, frontmatter: dict, description: str) -> dict:"""Serialisable metadata dict for one skill."""parts = skill_file.relative_to(skills_dir).parts@@ -1192,6 +1198,7 @@ def _build_snapshot_entry(skill_file: Path, skills_dir: Path, frontmatter: dict,"skill_name": skill_name, "category": category, "frontmatter_name": str(frontmatter.get("name", skill_name)),"description": description, "platforms": [str(p).strip() for p in platforms if str(p).strip()],"conditions": extract_skill_conditions(frontmatter),+ "requires_apps": _requires_apps_list(frontmatter),}if org_id:entry["org_id"] = org_id@@ -1208,8 +1215,8 @@ def _parse_skill_file(skill_file: Path) -> tuple[bool, dict, str]:try:frontmatter, _ = parse_frontmatter(skill_file.read_text(encoding="utf-8"))# Host-platform / runtime-environment gates are offer-time only; explicit loads bypass them.- if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter):- return False, frontmatter, ""+ if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter) or not skill_matches_apps(frontmatter):+ return False, frontmatter, extract_skill_description(frontmatter)return True, frontmatter, extract_skill_description(frontmatter)except Exception as e:logger.warning("Failed to parse skill file %s: %s", skill_file, e)@@ -1414,9 +1421,13 @@ def _build_skills_system_prompt_inner(_platform_hint, tuple(sorted(disabled)), tuple(sorted(compact_categories or ())),_oneshot_prompt_variant(),)+ snapshot = _load_skills_snapshot(skills_dir)+ app_gated = snapshot is not None and any(+ entry.get("requires_apps") for entry in snapshot.get("skills", []) if isinstance(entry, dict)+ )with _SKILLS_PROMPT_CACHE_LOCK:cached = _SKILLS_PROMPT_CACHE.get(cache_key)- if cached is not None:+ if cached is not None and not app_gated:_SKILLS_PROMPT_CACHE.move_to_end(cache_key)return cached@@ -1428,9 +1439,10 @@ def _build_skills_system_prompt_inner(skills_by_category: dict[str, list[tuple[str, str]]] = {}category_descriptions: dict[str, str] = {}# Disk snapshot (fast path) vs. full scan: both yield (entry, is_compatible) pairs so labeling runs identically.- snapshot = _load_skills_snapshot(skills_dir)if snapshot is not None:- candidates = [(entry, skill_matches_platform_list(entry.get("platforms") or []))+ # Platforms and app presence are host facts that change without SKILL.md changing: re-evaluate both.+ candidates = [(entry, skill_matches_platform_list(entry.get("platforms") or [])+ and skill_matches_apps({"requires_apps": entry.get("requires_apps") or []}))for entry in snapshot.get("skills", []) if isinstance(entry, dict)]category_descriptions = {str(k): str(v) for k, v in (snapshot.get("category_descriptions") or {}).items()}else:diff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex ec17a02d9a1..7f3de811485 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -353,12 +353,12 @@ def skill_command_collision_note(name: str) -> Optional[str]:def _scan_skill_md(skill_md: Path, disabled: set, seen_names: set, commands: Dict[str, Dict[str, Any]]) -> None:"""Register one SKILL.md in *commands* (no-op when filtered or colliding)."""- from tools.skills_tool import _parse_frontmatter, skill_matches_platform, skill_matches_environment+ from tools.skills_tool import _parse_frontmatter, skill_matches_apps, skill_matches_platform, skill_matches_environmentif any(part in _SCAN_SKIP_PARTS for part in skill_md.parts):returnfrontmatter, body = _parse_frontmatter(skill_md.read_text(encoding='utf-8'))# OS gate is hard; environment gate (kanban/docker/s6) is offer-time only.- if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter):+ if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter) or not skill_matches_apps(frontmatter):returnname = frontmatter.get('name', skill_md.parent.name)if name in seen_names or name in disabled:diff --git a/agent/skill_utils.py b/agent/skill_utils.pyindex e9677cae302..ad0eaebe9c3 100644--- a/agent/skill_utils.py+++ b/agent/skill_utils.py@@ -208,6 +208,28 @@ def skill_matches_environment(frontmatter: Dict[str, Any]) -> bool:return any(_detect_environment(tag) for tag in tags if tag)+def skill_matches_apps(frontmatter: Dict[str, Any]) -> bool:+ """True when every app named in ``requires_apps:`` has a registered declaration this host satisfies.++ Names resolve through ``hermes_platform.declaration`` (registered by whoever owns the server,+ e.g. the plugin loader); the check is the same ``availability()`` the MCP check_fn uses. An+ unknown name hides the skill (fail closed). Offer-time filter, like ``environments:``.+ """+ names = frontmatter.get("requires_apps")+ if not names:+ return True+ from hermes_platform import declaration+ from hermes_platform.resolver.availability import availability++ for name in names if isinstance(names, list) else [names]:+ decl = declaration.lookup(str(name).strip())+ if decl is None or decl.app is None:+ return False+ if not availability(decl).offerable:+ return False+ return True++_RAW_CONFIG_CACHE: Dict[Tuple[str, int, int, int, int], Dict[str, Any]] = {}diff --git a/hermes_cli/copilot_auth.py b/hermes_cli/copilot_auth.pyindex 1f7009fb3e1..53c9bc6dfc4 100644--- a/hermes_cli/copilot_auth.py+++ b/hermes_cli/copilot_auth.py@@ -87,12 +87,16 @@ def resolve_copilot_token() -> tuple[str, str]:def _gh_cli_candidates() -> list[str]:- """Candidate ``gh`` binary paths, including common Homebrew installs."""- candidates: list[str] = [c for c in (shutil.which("gh"),) if c]- candidates += [- c for c in ("/opt/homebrew/bin/gh", "/usr/local/bin/gh", str(Path.home() / ".local/bin/gh"))- if c not in candidates and os.path.isfile(c) and os.access(c, os.X_OK)]- return candidates+ """Every present ``gh`` in probe order: PATH first, then Homebrew and ``~/.local/bin``."""+ from hermes_platform.resolver import locate_command+ from hermes_platform.resolver.known_dirs import homebrew_dirs, user_local_bin++ res = locate_command("gh", known_dirs=(*homebrew_dirs(), *user_local_bin()))+ seen: list[str] = []+ for cand in res.present:+ if cand.value not in seen:+ seen.append(cand.value)+ return seen# ``gh auth token`` cache (misses too). With no credential store the probe blocks its full 5s ondiff --git a/hermes_platform/catalog/__init__.py b/hermes_platform/catalog/__init__.pydeleted file mode 100644index 0e82da6a07c..00000000000--- a/hermes_platform/catalog/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Declarative application catalog and loader."""diff --git a/hermes_platform/declaration.py b/hermes_platform/declaration.pynew file mode 100644index 00000000000..cc2ef5b2cff--- /dev/null+++ b/hermes_platform/declaration.py@@ -0,0 +1,213 @@+"""Parse and register application requirements shared by MCP and skill offer-time gates."""++from __future__ import annotations++import re+import threading+from dataclasses import dataclass, field+from typing import Any, Callable, Dict, Mapping, Optional++from hermes_platform.resolver.app import AppDef++__all__ = [+ "AppSpec",+ "RequiresSpec",+ "Declaration",+ "DeclarationError",+ "parse_app",+ "parse_requires",+ "parse_declaration",+ "register",+ "unregister",+ "lookup",+ "clear",+]+++class DeclarationError(ValueError):+ """Declaration parse/validation failure."""+++@dataclass(frozen=True)+class AppSpec:+ """Where the application lives, one ``AppDef`` per OS it is detectable on."""++ per_os: Mapping[str, AppDef] = field(default_factory=dict)++ def for_os(self, os_family: str) -> Optional[AppDef]:+ return self.per_os.get(os_family)+++@dataclass(frozen=True)+class RequiresSpec:+ """What the server needs before it is offered. Separate from ``app`` on purpose: one is data, one is policy."""++ app: bool = False+ min_version: Optional[str] = None+++@dataclass(frozen=True)+class Declaration:+ """A parsed declaration; satisfies ``hermes_platform.resolver.availability._HasRequirements``."""++ name: str+ app: Optional[AppSpec]+ requires: RequiresSpec = RequiresSpec()++ @property+ def requires_app(self) -> bool:+ return self.requires.app++ @property+ def min_version(self) -> Optional[str]:+ return self.requires.min_version++ def app_for(self, os_family: str) -> Optional[AppDef]:+ return self.app.for_os(os_family) if self.app else None+++_APP_OS_FAMILIES = ("win32", "darwin", "linux")+_APP_PRESENCE = ("executable", "bundle")+_APP_VERSION_KINDS = {"pe_resource": "win32", "uninstall_registry": "win32", "plist": "darwin", "none": None}+_APP_LIVENESS_KINDS = ("server_json", "none")+_VERSION_RE = re.compile(r"^\d+(\.\d+)*$")+++def _require_mapping(where: str, key: str, raw: Any) -> dict:+ if not isinstance(raw, dict):+ raise DeclarationError(f"{where}: '{key}' must be a mapping")+ return raw+++def _location_is_rooted(location: str, osf: str) -> bool:+ if ".." in location.replace("\\", "/").split("/") or "://" in location:+ return False+ if location.startswith(("~", "%", "$")):+ return True+ if osf == "win32":+ return bool(re.match(r"^[A-Za-z]:[\\/]", location))+ return location.startswith("/")+++def _parse_app_os(where: str, name: str, osf: str, raw: Any) -> AppDef:+ _require_mapping(where, f"app.{osf}", raw)+ presence = raw.get("presence")+ if presence not in _APP_PRESENCE:+ raise DeclarationError(f"{where}: app.{osf}.presence must be one of {_APP_PRESENCE}")+ location = raw.get("location")+ if not isinstance(location, str) or not location.strip():+ raise DeclarationError(f"{where}: app.{osf}.location is required")+ if not _location_is_rooted(location.strip(), osf):+ raise DeclarationError(+ f"{where}: app.{osf}.location must be absolute or start with ~ / %VAR% / $VAR, without '..' or a URL scheme")+ version = raw.get("version") or {"kind": "none"}+ _require_mapping(where, f"app.{osf}.version", version)+ vkind = version.get("kind", "none")+ if vkind not in _APP_VERSION_KINDS:+ raise DeclarationError(f"{where}: app.{osf}.version.kind must be one of {sorted(_APP_VERSION_KINDS)}")+ only_on = _APP_VERSION_KINDS[vkind]+ if only_on and only_on != osf:+ raise DeclarationError(f"{where}: app.{osf}.version.kind {vkind!r} is only valid under app.{only_on}")+ varg = str(version.get("display_name_prefix") or "")+ if vkind == "uninstall_registry" and not varg:+ raise DeclarationError(f"{where}: app.{osf}.version.display_name_prefix is required for uninstall_registry")+ liveness = raw.get("liveness") or {"kind": "none"}+ _require_mapping(where, f"app.{osf}.liveness", liveness)+ lkind = liveness.get("kind", "none")+ if lkind not in _APP_LIVENESS_KINDS:+ raise DeclarationError(f"{where}: app.{osf}.liveness.kind must be one of {_APP_LIVENESS_KINDS}")+ lpath = str(liveness.get("path") or "")+ if lkind == "server_json" and not lpath:+ raise DeclarationError(f"{where}: app.{osf}.liveness.path is required for server_json")+ return AppDef(+ app_id=name, os_family=osf, presence=presence, location=location.strip(),+ version_kind=vkind, version_arg=varg,+ liveness_kind=lkind, liveness_path=lpath,+ liveness_pid_key=str(liveness.get("pid_key") or "pid"),+ liveness_url_key=str(liveness.get("url_key") or "http"),+ liveness_token_key=str(liveness.get("token_key") or "token"),+ endpoint_path=str(liveness.get("endpoint_path") or "/mcp"),+ )+++def parse_app(raw: Any, *, name: str, where: str) -> Optional[AppSpec]:+ """Parse the ``app:`` block (already-decoded mapping, not YAML text) into an ``AppSpec``."""+ if raw is None:+ return None+ _require_mapping(where, "app", raw)+ unknown = set(raw) - set(_APP_OS_FAMILIES)+ if unknown:+ raise DeclarationError(f"{where}: app has unknown OS keys {sorted(unknown)}; use {_APP_OS_FAMILIES}")+ if not raw:+ raise DeclarationError(f"{where}: app needs at least one OS block")+ return AppSpec(per_os={osf: _parse_app_os(where, name, osf, raw[osf]) for osf in raw})+++def parse_requires(raw: Any, app: Optional[AppSpec], *, where: str) -> RequiresSpec:+ """Parse the ``requires:`` block; needs the parsed ``app`` to cross-check version policy."""+ if raw is None:+ return RequiresSpec()+ _require_mapping(where, "requires", raw)+ unknown = set(raw) - {"app", "min_version"}+ if unknown:+ raise DeclarationError(f"{where}: requires has unknown keys {sorted(unknown)}")+ needs_app = raw.get("app", False)+ if not isinstance(needs_app, bool):+ raise DeclarationError(f"{where}: requires.app must be a boolean")+ if needs_app and app is None:+ raise DeclarationError(f"{where}: requires.app is true but the declaration has no 'app' block")+ min_version = raw.get("min_version")+ if min_version is not None:+ if not isinstance(min_version, str) or not _VERSION_RE.fullmatch(min_version):+ raise DeclarationError(f"{where}: requires.min_version must be a dotted numeric string")+ if not needs_app:+ raise DeclarationError(f"{where}: requires.min_version needs requires.app: true")+ assert app is not None+ unversioned = sorted(osf for osf, d in app.per_os.items() if d.version_kind == "none")+ if unversioned:+ raise DeclarationError(+ f"{where}: requires.min_version needs a version source under app.{unversioned[0]} (kind is none)")+ return RequiresSpec(app=needs_app, min_version=min_version)+++def parse_declaration(name: str, raw_app: Any, raw_requires: Any, *, where: str) -> Declaration:+ """Parse both blocks of one declaration. ``where`` is the human label in error messages."""+ app = parse_app(raw_app, name=name, where=where)+ return Declaration(name=name, app=app, requires=parse_requires(raw_requires, app, where=where))+++_REGISTRY: Dict[str, Declaration] = {}+_REGISTRY_LOCK = threading.Lock()+on_change: Optional[Callable[[], None]] = None+++def _changed() -> None:+ if on_change is not None:+ on_change()+++def register(server_name: str, decl: Declaration) -> None:+ """Record which application declaration gates *server_name*."""+ with _REGISTRY_LOCK:+ _REGISTRY[server_name] = decl+ _changed()+++def unregister(server_name: str) -> None:+ """Remove the declaration registered for *server_name*."""+ with _REGISTRY_LOCK:+ _REGISTRY.pop(server_name, None)+ _changed()+++def lookup(server_name: str) -> Optional[Declaration]:+ """Return the declaration registered for *server_name*, if any."""+ with _REGISTRY_LOCK:+ return _REGISTRY.get(server_name)+++def clear() -> None:+ """Drop every registration."""+ with _REGISTRY_LOCK:+ _REGISTRY.clear()+ _changed()diff --git a/hermes_platform/resolver/__init__.py b/hermes_platform/resolver/__init__.pyindex e3c34bf9d24..cd1b39abdd6 100644--- a/hermes_platform/resolver/__init__.py+++ b/hermes_platform/resolver/__init__.py@@ -1 +1,17 @@-"""Resource owners and resolution helpers."""+"""Resource resolution: where a tool or application is, and what state it is in."""++from hermes_platform.resolver.base import Effort, Inspection, Probe, Probeable, Resolver+from hermes_platform.resolver.core import (+ ABSENT,+ Candidate,+ CheckState,+ LookupContext,+ Observation,+ Resolution,+ locate_command,+)++__all__ = [+ "ABSENT", "Candidate", "CheckState", "Effort", "Inspection", "LookupContext",+ "Observation", "Probe", "Probeable", "Resolution", "Resolver", "locate_command",+]diff --git a/hermes_platform/resolver/app.py b/hermes_platform/resolver/app.pynew file mode 100644index 00000000000..82549ee5b7a--- /dev/null+++ b/hermes_platform/resolver/app.py@@ -0,0 +1,301 @@+"""Desktop-application resolver over an `AppDef` (parsed from an MCP manifest's `app:` block).++`locate` stats the executable or bundle. `inspect` reads the version source in-process.+`probe` re-reads the vendor's runtime file on every call; the bearer token in it never+leaves this module.+"""++from __future__ import annotations++import json+import os+import plistlib+import sys+import time+from dataclasses import dataclass+from typing import Literal+from urllib.parse import urlsplit++from hermes_platform.resolver.base import Effort, Inspection, Probe+from hermes_platform.resolver.core import (+ Candidate,+ CheckState,+ LookupContext,+ Observation,+ Resolution,+)++PresenceKind = Literal["executable", "bundle"]+VersionKind = Literal["pe_resource", "plist", "uninstall_registry", "none"]+LivenessKind = Literal["server_json", "none"]++_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})+++@dataclass(frozen=True)+class AppDef:+ """One application on one OS. Paths use `%VAR%` and `~`; expansion happens at lookup."""++ app_id: str+ os_family: str+ presence: PresenceKind+ location: str+ version_kind: VersionKind = "none"+ version_arg: str = ""+ liveness_kind: LivenessKind = "none"+ liveness_path: str = ""+ liveness_pid_key: str = "pid"+ liveness_url_key: str = "http"+ liveness_token_key: str = "token"+ endpoint_path: str = "/mcp"+++def _expand(path: str) -> str:+ return os.path.expandvars(os.path.expanduser(path))+++@dataclass(frozen=True)+class AppResolver:+ definition: AppDef++ @property+ def name(self) -> str:+ return self.definition.app_id++ # ---- locate: stat only -------------------------------------------------------------++ def locate(self, ctx: LookupContext | None = None) -> Resolution:+ d = self.definition+ target = _expand(d.location)+ if not os.path.isabs(target) or "%" in target or "$" in target:+ return Resolution("missing", (Candidate(target, f"app:{d.app_id}", False),))+ if d.presence == "bundle":+ present = os.path.isdir(target) and os.path.isfile(os.path.join(target, "Contents", "Info.plist"))+ else:+ present = os.path.isfile(target)+ cand = Candidate(target, f"app:{d.app_id}", present)+ return Resolution("known_path" if present else "missing", (cand,))++ # ---- inspect: bounded file reads and in-process OS APIs -----------------------------++ def inspect(self, res: Resolution, ctx: LookupContext | None = None) -> Inspection:+ if not res.found:+ return Inspection(Observation.not_checked(), Observation.not_checked())+ return Inspection(version=self._version(res.command[0]), signer=Observation.not_checked())++ def _version(self, path: str) -> Observation[str]:+ kind = self.definition.version_kind+ try:+ if kind == "none":+ return Observation.not_checked()+ if kind == "plist":+ return _plist_version(path)+ if kind == "pe_resource":+ return _pe_version(path)+ if kind == "uninstall_registry":+ return _uninstall_registry_version(self.definition.version_arg)+ except Exception as exc: # a vendor's plist/PE/registry entry is untrusted input; never abort the caller+ return Observation(CheckState.ERROR, detail=exc.__class__.__name__)+ return Observation(CheckState.UNAVAILABLE, detail=f"unknown version kind {kind}")++ # ---- probe: fresh, never cached ------------------------------------------------------++ def probe(self, res: Resolution, *, effort: Effort, deadline_s: float = 3.0) -> Probe:+ d = self.definition+ nc: Observation = Observation.not_checked()+ if d.liveness_kind != "server_json":+ return Probe(running=nc, answering=nc, endpoint=nc)+ session = _read_server_json(_expand(d.liveness_path), d)+ if session is None:+ absent = Observation(CheckState.ABSENT, False, "runtime file missing or unreadable")+ return Probe(running=absent, answering=nc, endpoint=Observation(CheckState.ABSENT))+ running = _pid_alive(session.pid)+ endpoint_obs = _endpoint_observation(session.url, d.endpoint_path)+ if effort is Effort.LOCAL or running.value is not True or endpoint_obs.state is not CheckState.PRESENT:+ return Probe(running=running, answering=nc, endpoint=endpoint_obs)+ answering = _mcp_initialize(session, endpoint_obs.value or "", deadline_s)+ return Probe(running=running, answering=answering, endpoint=endpoint_obs)+++# ---- version sources -------------------------------------------------------------------+++def _plist_version(bundle: str) -> Observation[str]:+ with open(os.path.join(bundle, "Contents", "Info.plist"), "rb") as fh: # windows-footgun: ok — binary mode+ info = plistlib.load(fh)+ value = info.get("CFBundleShortVersionString") or info.get("CFBundleVersion")+ if not value:+ return Observation(CheckState.UNAVAILABLE, detail="no version key in Info.plist")+ return Observation(CheckState.PRESENT, str(value))+++def _pe_version(path: str) -> Observation[str]:+ if sys.platform != "win32":+ return Observation(CheckState.UNAVAILABLE, detail="pe_resource needs Windows")+ import ctypes+ from ctypes import wintypes++ ver = ctypes.windll.version # type: ignore[attr-defined]+ ver.GetFileVersionInfoSizeW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.DWORD)]+ ver.GetFileVersionInfoSizeW.restype = wintypes.DWORD+ size = ver.GetFileVersionInfoSizeW(path, None)+ if not size:+ return Observation(CheckState.UNAVAILABLE, detail="no version resource")+ buf = ctypes.create_string_buffer(size)+ ver.GetFileVersionInfoW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]+ ver.GetFileVersionInfoW.restype = wintypes.BOOL+ if not ver.GetFileVersionInfoW(path, 0, size, buf):+ return Observation(CheckState.ERROR, detail="GetFileVersionInfoW failed")+ ptr = ctypes.c_void_p()+ length = wintypes.UINT()+ ver.VerQueryValueW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.UINT)]+ ver.VerQueryValueW.restype = wintypes.BOOL+ if not ver.VerQueryValueW(buf, "\\", ctypes.byref(ptr), ctypes.byref(length)) or not ptr.value:+ return Observation(CheckState.UNAVAILABLE, detail="no fixed file info")+ # VS_FIXEDFILEINFO: dwFileVersionMS at offset 8, dwFileVersionLS at offset 12.+ ms = ctypes.cast(ptr.value + 8, ctypes.POINTER(wintypes.DWORD)).contents.value+ ls = ctypes.cast(ptr.value + 12, ctypes.POINTER(wintypes.DWORD)).contents.value+ return Observation(CheckState.PRESENT, f"{ms >> 16}.{ms & 0xFFFF}.{ls >> 16}.{ls & 0xFFFF}")+++def _uninstall_registry_version(display_name_prefix: str) -> Observation[str]:+ if sys.platform != "win32":+ return Observation(CheckState.UNAVAILABLE, detail="uninstall_registry needs Windows")+ import winreg++ roots = (+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"),+ (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"),+ (winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"),+ )+ for hive, root in roots:+ try:+ with winreg.OpenKey(hive, root) as key:+ count = winreg.QueryInfoKey(key)[0]+ for i in range(count):+ sub = winreg.EnumKey(key, i)+ with winreg.OpenKey(key, sub) as entry:+ try:+ name, _ = winreg.QueryValueEx(entry, "DisplayName")+ except OSError:+ continue+ if str(name).startswith(display_name_prefix):+ try:+ version, _ = winreg.QueryValueEx(entry, "DisplayVersion")+ except OSError:+ return Observation(CheckState.UNAVAILABLE, detail="entry has no DisplayVersion")+ return Observation(CheckState.PRESENT, str(version))+ except OSError:+ continue+ return Observation(CheckState.ABSENT, detail="no uninstall entry")+++# ---- liveness: the token stays inside this section -------------------------------------+++@dataclass(frozen=True)+class _Session:+ pid: int | None+ url: str+ token: str++ def __repr__(self) -> str:+ return f"_Session(pid={self.pid}, url={self.url!r}, token=<redacted>)"+++def _read_server_json(path: str, d: AppDef) -> _Session | None:+ try:+ with open(path, encoding="utf-8") as fh:+ data = json.load(fh)+ except (OSError, ValueError):+ return None+ if not isinstance(data, dict):+ return None+ pid = data.get(d.liveness_pid_key)+ url = data.get(d.liveness_url_key)+ token = data.get(d.liveness_token_key)+ return _Session(+ pid=pid if isinstance(pid, int) else None,+ url=url if isinstance(url, str) else "",+ token=token if isinstance(token, str) else "",+ )+++def _pid_alive(pid: int | None) -> Observation[bool]:+ if pid is None or pid <= 0:+ return Observation(CheckState.UNAVAILABLE, detail="no pid in runtime file")+ if sys.platform == "win32":+ import ctypes+ from ctypes import wintypes++ k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]+ k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ k32.OpenProcess.restype = wintypes.HANDLE+ handle = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION+ if not handle:+ return Observation(CheckState.ABSENT, False)+ k32.CloseHandle.argtypes = [wintypes.HANDLE]+ k32.CloseHandle(handle)+ return Observation(CheckState.PRESENT, True)+ try:+ os.kill(pid, 0) # windows-footgun: ok — POSIX only, the win32 branch returned above+ except ProcessLookupError:+ return Observation(CheckState.ABSENT, False)+ except PermissionError:+ return Observation(CheckState.PRESENT, True)+ return Observation(CheckState.PRESENT, True)+++def _endpoint_observation(raw_url: str, fixed_path: str) -> Observation[str]:+ """Accept only a loopback http URL with a numeric port and no userinfo; the path is ours."""+ if not raw_url:+ return Observation(CheckState.UNAVAILABLE, detail="no url in runtime file")+ try:+ parts = urlsplit(raw_url)+ hostname, port, username, password = parts.hostname, parts.port, parts.username, parts.password+ except ValueError:+ return Observation(CheckState.UNAVAILABLE, detail="malformed endpoint")+ if parts.scheme != "http" or username or password:+ return Observation(CheckState.UNAVAILABLE, detail="endpoint must be plain http without userinfo")+ if hostname not in _LOOPBACK_HOSTS:+ return Observation(CheckState.UNAVAILABLE, detail="endpoint must be loopback")+ if port is None or not (1 <= port <= 65535):+ return Observation(CheckState.UNAVAILABLE, detail="endpoint needs a numeric port")+ return Observation(CheckState.PRESENT, f"http://{hostname}:{port}{fixed_path}")+++def _mcp_initialize(session: _Session, endpoint: str, deadline_s: float) -> Observation[bool]:+ """One MCP `initialize` POST under one absolute deadline covering connect, headers, and body."""+ import http.client++ parts = urlsplit(endpoint)+ body = json.dumps({+ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {"protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "hermes", "version": "probe"}},+ }).encode()+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}+ if session.token:+ headers["Authorization"] = f"Bearer {session.token}"+ deadline = time.monotonic() + max(0.1, deadline_s)++ def remaining() -> float:+ left = deadline - time.monotonic()+ if left <= 0:+ raise TimeoutError+ return left++ conn = http.client.HTTPConnection(parts.hostname or "127.0.0.1", parts.port or 80, timeout=remaining())+ try:+ conn.request("POST", parts.path or "/", body=body, headers=headers)+ conn.sock.settimeout(remaining())+ status = conn.getresponse().status+ except TimeoutError:+ return Observation(CheckState.ABSENT, False, f"no answer within {deadline_s:g} s")+ except (OSError, http.client.HTTPException):+ return Observation(CheckState.ABSENT, False, "connection refused or timed out")+ finally:+ conn.close()+ if status in (200, 401, 403):+ return Observation(CheckState.PRESENT, True, f"http {status}")+ return Observation(CheckState.ABSENT, False, f"http {status}")diff --git a/hermes_platform/resolver/availability.py b/hermes_platform/resolver/availability.pynew file mode 100644index 00000000000..1827160e31a--- /dev/null+++ b/hermes_platform/resolver/availability.py@@ -0,0 +1,94 @@+"""Whether a catalog entry can be offered on this host, from its `app` and `requires` blocks.++`availability` runs `locate` and `inspect` only. It never probes, never spawns, never connects, and holds+no cache: the callers that need a TTL (the tool registry) already have one.+"""++from __future__ import annotations++from dataclasses import dataclass+import re+from typing import Literal, Protocol++from hermes_platform.host import facts+from hermes_platform.resolver.app import AppDef, AppResolver+from hermes_platform.resolver.core import CheckState++AvailabilityState = Literal[+ "available",+ "installed_not_running",+ "missing_app",+ "version_too_old",+ "unsupported_os",+ "no_requirements",+]++OFFERABLE: frozenset[str] = frozenset({"available", "no_requirements"})+++class _HasRequirements(Protocol):+ """The slice of a catalog entry `availability` reads; keeps this module free of `hermes_cli` imports."""++ @property+ def requires_app(self) -> bool: ...++ @property+ def min_version(self) -> str | None: ...++ def app_for(self, os_family: str) -> AppDef | None: ...+++@dataclass(frozen=True)+class Availability:+ state: AvailabilityState+ version: str | None = None+ path: str | None = None+ min_version: str | None = None++ @property+ def offerable(self) -> bool:+ return self.state in OFFERABLE++ def __bool__(self) -> bool:+ raise TypeError("Availability is not a boolean; read .offerable or .state")++ def as_dict(self) -> dict:+ return {"state": self.state, "version": self.version, "path": self.path, "min_version": self.min_version}+++def version_at_least(found: str, minimum: str) -> bool:+ """Compare dot-separated decimal components, failing closed on invalid input."""++ def parts(version: str) -> list[int] | None:+ if not re.fullmatch(r"[0-9]{1,9}(?:\.[0-9]{1,9})*", version):+ return None+ return [int(component) for component in version.split(".")]++ a, b = parts(found), parts(minimum)+ if a is None or b is None:+ return False+ width = max(len(a), len(b))+ a += [0] * (width - len(a))+ b += [0] * (width - len(b))+ return a >= b+++def availability(entry: _HasRequirements, *, os_family: str | None = None) -> Availability:+ if not entry.requires_app:+ return Availability("no_requirements")+ osf = os_family or facts.os_family()+ definition = entry.app_for(osf)+ if definition is None:+ return Availability("unsupported_os", min_version=entry.min_version)+ resolver = AppResolver(definition)+ res = resolver.locate()+ looked_at = res.command[0] if res.command else (res.candidates[0].value if res.candidates else None)+ if not res.found:+ return Availability("missing_app", path=looked_at, min_version=entry.min_version)+ version = None+ if entry.min_version or definition.version_kind != "none":+ obs = resolver.inspect(res).version+ version = obs.value if obs.state is CheckState.PRESENT else None+ if entry.min_version and (version is None or not version_at_least(version, entry.min_version)):+ return Availability("version_too_old", version=version, path=looked_at, min_version=entry.min_version)+ return Availability("available", version=version, path=looked_at, min_version=entry.min_version)diff --git a/hermes_platform/resolver/base.py b/hermes_platform/resolver/base.pynew file mode 100644index 00000000000..72197f875dd--- /dev/null+++ b/hermes_platform/resolver/base.py@@ -0,0 +1,55 @@+"""Resolver protocols and the results of the two non-passive tiers.++`locate` reads file metadata only. `inspect` may open files and call OS APIs in-process.+`probe` is fresh, never cached, and the only tier that may open a socket or spawn.+"""++from __future__ import annotations++from dataclasses import dataclass+from enum import Enum+from typing import Protocol, runtime_checkable++from hermes_platform.resolver.core import LookupContext, Observation, Resolution+++class Effort(Enum):+ """What `probe` may do. `NETWORK` never implies subprocess; `DIAGNOSTIC` alone may spawn."""++ LOCAL = "local"+ NETWORK = "network"+ DIAGNOSTIC = "diagnostic"+++@dataclass(frozen=True)+class Inspection:+ version: Observation[str]+ signer: Observation[str]++ @property+ def ok(self) -> bool:+ return self.version.state.value != "error" and self.signer.state.value != "error"+++@dataclass(frozen=True)+class Probe:+ running: Observation[bool]+ answering: Observation[bool]+ endpoint: Observation[str]++ def __bool__(self) -> bool: # pragma: no cover - the raise is the behavior+ raise TypeError("Probe is not a boolean; read .running/.answering")+++@runtime_checkable+class Resolver(Protocol):+ name: str++ def locate(self, ctx: LookupContext | None = None) -> Resolution: ...++ def inspect(self, res: Resolution, ctx: LookupContext | None = None) -> Inspection: ...+++@runtime_checkable+class Probeable(Resolver, Protocol):+ def probe(self, res: Resolution, *, effort: Effort, deadline_s: float = 3.0) -> Probe: ...diff --git a/hermes_platform/resolver/core.py b/hermes_platform/resolver/core.pynew file mode 100644index 00000000000..8b27e84a549--- /dev/null+++ b/hermes_platform/resolver/core.py@@ -0,0 +1,148 @@+"""Result and context types shared by every resolver, plus passive command location.++`locate_command` reads only file metadata. It never opens a file, spawns, or connects.+"""++from __future__ import annotations++import os+import shutil+from dataclasses import dataclass, field+from enum import Enum+from typing import Generic, Literal, TypeVar++Kind = Literal["explicit_path", "path_executable", "known_path", "package_runner", "missing"]++T = TypeVar("T")+++class _Absent:+ __slots__ = ()++ def __repr__(self) -> str:+ return "ABSENT"+++ABSENT = _Absent()+++class CheckState(Enum):+ NOT_CHECKED = "not_checked"+ PRESENT = "present"+ ABSENT = "absent"+ UNAVAILABLE = "unavailable"+ ERROR = "error"+++@dataclass(frozen=True)+class Observation(Generic[T]):+ """One checked fact. Consumers branch on `state`; `detail` is never parsed."""++ state: CheckState+ value: T | None = None+ detail: str = ""++ @classmethod+ def not_checked(cls) -> "Observation[T]":+ return cls(CheckState.NOT_CHECKED)+++@dataclass(frozen=True)+class Candidate:+ value: str+ source: str+ present: bool+++@dataclass(frozen=True)+class LookupContext:+ """`path`: ABSENT = caller did not say (ambient), None = ambient, "" = search nothing."""++ path: str | None | _Absent = ABSENT+ pathext: str | None = None++ def effective_path(self) -> str | None:+ if isinstance(self.path, str):+ return self.path+ return None+++@dataclass(frozen=True)+class Resolution:+ kind: Kind+ candidates: tuple[Candidate, ...] = field(default_factory=tuple)++ @property+ def command(self) -> tuple[str, ...]:+ first = next((c for c in self.candidates if c.present), None)+ return (first.value,) if first else ()++ @property+ def source(self) -> str:+ first = next((c for c in self.candidates if c.present), None)+ return first.source if first else "none"++ @property+ def present(self) -> tuple[Candidate, ...]:+ return tuple(c for c in self.candidates if c.present)++ @property+ def found(self) -> bool:+ return self.kind != "missing"+++def _which(name: str, ctx: LookupContext) -> str | None:+ if ctx.path == "":+ return None+ if ctx.pathext is not None and os.name == "nt":+ # shutil.which reads PATHEXT from os.environ; an explicit pathext is honored without mutating it.+ exts = [e for e in ctx.pathext.split(os.pathsep) if e]+ for ext in ["", *exts]:+ hit = shutil.which(name + ext, path=ctx.effective_path())+ if hit:+ return hit+ return None+ return shutil.which(name, path=ctx.effective_path())+++def _is_executable_file(path: str) -> bool:+ return os.path.isfile(path) and os.access(path, os.X_OK)+++def _expand(path: str) -> str:+ return os.path.expandvars(os.path.expanduser(path))+++def locate_command(name: str, ctx: LookupContext | None = None, *, known_dirs: tuple[str, ...] = ()) -> Resolution:+ """Find `name` on PATH, then in `known_dirs`, recording every candidate in probe order."""+ ctx = ctx or LookupContext()+ name = name.strip()+ if os.sep in name or (os.altsep and os.altsep in name):+ expanded = _expand(name)+ # A relative explicit path would resolve against the ambient cwd; only absolute paths are trusted.+ present = os.path.isabs(expanded) and _is_executable_file(expanded)+ cand = Candidate(expanded, "explicit", present)+ return Resolution("explicit_path" if present else "missing", (cand,))++ candidates: list[Candidate] = []+ hit = _which(name, ctx)+ candidates.append(Candidate(hit or name, "PATH", hit is not None))+ for d in known_dirs:+ base = os.path.join(_expand(d), name)+ found = next((v for v in _known_dir_variants(base) if _is_executable_file(v)), None)+ candidates.append(Candidate(found or base, f"known_dir:{d}", found is not None))++ kind: Kind = "missing"+ for c in candidates:+ if c.present:+ kind = "path_executable" if c.source == "PATH" else "known_path"+ break+ return Resolution(kind, tuple(candidates))+++def _known_dir_variants(base: str) -> tuple[str, ...]:+ """On Windows a bare name in a known dir may carry any PATHEXT suffix; one candidate is recorded per dir."""+ if os.name != "nt":+ return (base,)+ exts = [e for e in os.environ.get("PATHEXT", ".EXE;.CMD;.BAT").split(os.pathsep) if e]+ return (base, *[base + e for e in exts])diff --git a/hermes_platform/resolver/known_dirs.py b/hermes_platform/resolver/known_dirs.pynew file mode 100644index 00000000000..d22fe0ac13e--- /dev/null+++ b/hermes_platform/resolver/known_dirs.py@@ -0,0 +1,43 @@+"""Directories where tools install outside PATH, grouped by the ecosystem that owns them.++Every table in Hermes lives here. A directory literal outside this module fails the ratchet in+`tests/test_managed_runtime_resolution.py`. Each table is empty on an OS where the ecosystem+does not install there, so callers compose tables without OS branches.+"""++from __future__ import annotations++import sys++_POSIX = sys.platform != "win32"+_WIN = sys.platform == "win32"+++def homebrew_dirs() -> tuple[str, ...]:+ return ("/opt/homebrew/bin", "/usr/local/bin") if sys.platform == "darwin" else ()+++def user_local_bin() -> tuple[str, ...]:+ return ("~/.local/bin",) if _POSIX else ("%USERPROFILE%/.local/bin",)+++def rust_tool_dirs() -> tuple[str, ...]:+ return ("~/.cargo/bin",) if _POSIX else ("%USERPROFILE%/.cargo/bin",)+++def node_tool_dirs() -> tuple[str, ...]:+ return ("~/.npm-global/bin", "~/.bun/bin", "~/.volta/bin") if _POSIX else ("%APPDATA%/npm", "%USERPROFILE%/.bun/bin", "%LOCALAPPDATA%/Volta/bin")+++def hermes_vendored_dirs() -> tuple[str, ...]:+ return ("~/.hermes/bin",) if _POSIX else ("%USERPROFILE%/.hermes/bin",)+++def windows_user_program_dirs() -> tuple[str, ...]:+ if not _WIN:+ return ()+ return (+ "%LOCALAPPDATA%/Programs",+ "%USERPROFILE%/scoop/shims",+ "%LOCALAPPDATA%/Microsoft/WinGet/Links",+ )diff --git a/pyproject.toml b/pyproject.tomlindex feb61e94802..55caa670b05 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -609,8 +609,6 @@ youtube-transcript-api = falseinclude = ["agent", "agent.*", "tools", "tools.*", "hermes_cli", "hermes_cli.*", "gateway", "gateway.*", "tui_gateway", "tui_gateway.*", "cron", "cron.*", "acp_adapter", "plugins", "plugins.*", "providers", "providers.*", "hermes_platform", "hermes_platform.*"][tool.setuptools.package-data]-# hermes_platform/catalog ships apps.yaml (PR2); declared now so the wheel picks it up on arrival.-hermes_platform = ["catalog/*.yaml"]hermes_cli = ["observability/schemas/*.json", "data/*.json", "local_runtime/*.json"]# gateway/assets/ ships status_phrases.yaml and the Telegram BotFather# screenshot. Without this, sealed venvs (uv2nix) silently lose both —diff --git a/tests/agent/test_skill_app_snapshot.py b/tests/agent/test_skill_app_snapshot.pynew file mode 100644index 00000000000..c72a4a47f81--- /dev/null+++ b/tests/agent/test_skill_app_snapshot.py@@ -0,0 +1,42 @@+"""Application requirements survive disk and in-process skill-index reuse."""++import sys++from hermes_platform import declaration+++def test_application_gate_rechecks_snapshot_without_losing_description(tmp_path, monkeypatch):+ from agent import prompt_builder as pb++ monkeypatch.setattr(declaration, "_REGISTRY", {})+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(pb, "get_disabled_skill_names", lambda *_: set())+ skills = tmp_path / "skills"+ skill = skills / "app-guide" / "SKILL.md"+ skill.parent.mkdir(parents=True)+ skill.write_text(+ "---\nname: app-guide\ndescription: Application instructions.\n"+ "requires_apps: [thing]\n---\nHelp with the application.\n", encoding="utf-8",+ )+ app = tmp_path / "application.exe"+ declaration.register("thing", declaration.parse_declaration(+ "thing", {sys.platform: {"presence": "executable", "location": str(app)}},+ {"app": True}, where="test-plugin/plugin.yaml",+ ))+ pb.clear_skills_system_prompt_cache(clear_snapshot=True)+ try:+ def build():+ return pb._build_skills_system_prompt_inner(skills, [], None, None, None)++ assert "app-guide" not in build()+ snapshot = pb._load_skills_snapshot(skills)+ assert snapshot is not None+ assert snapshot["skills"][0]["requires_apps"] == ["thing"]+ app.write_text("presence fixture", encoding="utf-8")+ assert "app-guide: Application instructions." in build()+ app.unlink()+ assert "app-guide" not in build()+ pb.clear_skills_system_prompt_cache()+ assert "app-guide" not in build()+ finally:+ pb.clear_skills_system_prompt_cache(clear_snapshot=True)diff --git a/tests/fixtures/resolution_allowlist.json b/tests/fixtures/resolution_allowlist.jsonindex 0403a012df6..250e66da05f 100644--- a/tests/fixtures/resolution_allowlist.json+++ b/tests/fixtures/resolution_allowlist.json@@ -144,11 +144,6 @@"symbol": "edit_config","kind": "bare_which"},- {- "path": "hermes_cli/copilot_auth.py",- "symbol": "_gh_cli_candidates",- "kind": "bare_which"- },{"path": "hermes_cli/dep_ensure.py","symbol": "<module>",@@ -704,11 +699,6 @@"symbol": "_find_uv_binary","kind": "known_path_table"},- {- "path": "hermes_cli/copilot_auth.py",- "symbol": "_gh_cli_candidates",- "kind": "known_path_table"- },{"path": "tools/computer_use/cua_backend_driver.py","symbol": "_candidate_cua_driver_commands",diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.pyindex 480bf0681cb..70043cd8f6a 100644--- a/tests/hermes_cli/test_api_key_providers.py+++ b/tests/hermes_cli/test_api_key_providers.py@@ -358,19 +358,19 @@ class TestResolveApiKeyProviderCredentials:- def test_try_gh_cli_token_uses_homebrew_path_when_not_on_path(self, monkeypatch):+ def test_try_gh_cli_token_uses_homebrew_path_when_not_on_path(self, monkeypatch, tmp_path):from hermes_cli.copilot_auth import _invalidate_gh_cli_token_cache+ from hermes_platform.resolver import known_dirs_invalidate_gh_cli_token_cache()- monkeypatch.setattr("hermes_cli.copilot_auth.shutil.which", lambda command: None)- monkeypatch.setattr(- "hermes_cli.copilot_auth.os.path.isfile",- lambda path: path == "/opt/homebrew/bin/gh",- )- monkeypatch.setattr(- "hermes_cli.copilot_auth.os.access",- lambda path, mode: path == "/opt/homebrew/bin/gh" and mode == os.X_OK,- )+ brew = tmp_path / "homebrew" / "bin"+ brew.mkdir(parents=True)+ gh = brew / "gh"+ gh.write_text("#!/bin/sh\n", encoding="utf-8")+ gh.chmod(0o755)+ monkeypatch.setenv("PATH", str(tmp_path / "empty"))+ monkeypatch.setattr(known_dirs, "homebrew_dirs", lambda: (str(brew),))+ monkeypatch.setattr(known_dirs, "user_local_bin", lambda: ())calls = []@@ -385,7 +385,7 @@ class TestResolveApiKeyProviderCredentials:monkeypatch.setattr("hermes_cli.copilot_auth.subprocess.run", _fake_run)assert _try_gh_cli_token() == "gh-cli-secret"- assert calls == [["/opt/homebrew/bin/gh", "auth", "token"]]+ assert calls == [[str(gh), "auth", "token"]]diff --git a/tests/hermes_platform/test_declaration.py b/tests/hermes_platform/test_declaration.pynew file mode 100644index 00000000000..26084a21a5e--- /dev/null+++ b/tests/hermes_platform/test_declaration.py@@ -0,0 +1,172 @@+"""Declaration parser, availability, and skill-gate contracts.++Fixtures are dicts passed to ``parse_declaration`` (never YAML files); fixture paths satisfy the+OS rule they test under (`C:/x/y.exe` for win32, `/x` elsewhere).+"""++from __future__ import annotations++import plistlib+import sys+from pathlib import Path++import pytest++from hermes_platform.declaration import DeclarationError, parse_declaration+from hermes_platform.resolver.app import AppDef, AppResolver+from hermes_platform.resolver.availability import Availability, availability, version_at_least++WHERE = "test-plugin/plugin.yaml"+++def _bundle(tmp_path: Path, version: str) -> Path:+ app = tmp_path / "Applications" / "Thing.app"+ (app / "Contents").mkdir(parents=True, exist_ok=True)+ with open(app / "Contents" / "Info.plist", "wb") as fh:+ plistlib.dump({"CFBundleShortVersionString": version}, fh)+ return app+++def test_app_block_parses_into_one_appdef_per_os():+ decl = parse_declaration("thing-mcp", {+ "darwin": {"presence": "bundle", "location": "/Applications/Thing.app", "version": {"kind": "plist"}},+ "win32": {+ "presence": "executable",+ "location": "%ProgramFiles%/Thing/thing.exe",+ "version": {"kind": "uninstall_registry", "display_name_prefix": "Thing"},+ "liveness": {"kind": "server_json", "path": "%LOCALAPPDATA%/Thing/server.json", "endpoint_path": "/rpc"},+ },+ }, {"app": True, "min_version": "2.3.0"}, where=WHERE)+ assert decl.app is not None and set(decl.app.per_os) == {"darwin", "win32"}+ mac, win = decl.app_for("darwin"), decl.app_for("win32")+ assert mac is not None and win is not None+ assert mac.presence == "bundle" and mac.version_kind == "plist" and mac.liveness_kind == "none"+ assert win.version_arg == "Thing" and win.endpoint_path == "/rpc" and win.liveness_pid_key == "pid"+ assert decl.requires_app is True and decl.min_version == "2.3.0"++[email protected]("raw_app, raw_requires, message", [+ (None, {"app": True}, "no 'app' block"),+ (None, {"min_version": "1.0\n"}, "dotted numeric"),+ ({"linux": {"presence": "executable", "location": "/x/y", "version": {"kind": "plist"}}}, None,+ "only valid under app.darwin"),+ ({"win32": {"presence": "executable", "location": "C:/x/y.exe", "version": {"kind": "uninstall_registry"}}}, None,+ "display_name_prefix"),+ ({"freebsd": {"presence": "executable", "location": "/x"}}, None, "unknown OS keys"),+ ({"win32": {"presence": "executable", "location": "C:/x/y.exe"}}, {"min_version": "1.0"},+ "needs requires.app"),+ ({"win32": {"presence": "executable", "location": "C:/x/y.exe"}}, {"app": True, "min_version": "latest"},+ "dotted numeric"),+ ({"win32": {"presence": "executable", "location": "C:/x/y.exe"}}, {"app": True, "min_version": "1.0"},+ "needs a version source"),+ ({"darwin": {"presence": "bundle", "location": "../Up/Thing.app"}}, None, "must be absolute"),+ ({"darwin": {"presence": "bundle", "location": "Relative/Thing.app"}}, None, "must be absolute"),+ ({"darwin": {"presence": "bundle", "location": "https://example.test/Thing.app"}}, None, "must be absolute"),+ ({"win32": {"presence": "executable", "location": "Thing/thing.exe"}}, None, "must be absolute"),+])+def test_invalid_blocks_name_the_rule(raw_app, raw_requires, message):+ with pytest.raises(DeclarationError, match=message):+ parse_declaration("thing-mcp", raw_app, raw_requires, where=WHERE)+++def test_availability_no_requirements_does_no_io():+ decl = parse_declaration("thing-mcp", None, None, where=WHERE)+ result = availability(decl, os_family="freebsd")+ assert result.state == "no_requirements" and result.offerable+++def test_availability_unsupported_os_when_no_block_for_host():+ decl = parse_declaration(+ "thing-mcp",+ {"win32": {"presence": "executable", "location": "C:/x/y.exe"}},+ {"app": True},+ where=WHERE,+ )+ assert availability(decl, os_family="darwin").state == "unsupported_os"++[email protected]_only+def test_availability_missing_then_present_then_version_gate(tmp_path):+ location = tmp_path / "Applications" / "Thing.app"+ decl = parse_declaration(+ "thing-mcp",+ {"darwin": {"presence": "bundle", "location": str(location), "version": {"kind": "plist"}}},+ {"app": True, "min_version": "2.3.0"},+ where=WHERE,+ )+ missing = availability(decl, os_family="darwin")+ assert missing.state == "missing_app" and str(tmp_path) in (missing.path or "")+ _bundle(tmp_path, "2.2.9")+ old = availability(decl, os_family="darwin")+ assert old.state == "version_too_old" and old.version == "2.2.9" and old.min_version == "2.3.0"+ _bundle(tmp_path, "2.3.0")+ ok = availability(decl, os_family="darwin")+ assert ok.state == "available" and ok.version == "2.3.0" and ok.offerable+ (location / "Contents" / "Info.plist").write_bytes(b"invalid plist")+ assert availability(decl, os_family="darwin").state == "version_too_old"+++def test_availability_is_not_a_boolean():+ with pytest.raises(TypeError):+ bool(Availability("available"))++[email protected]("found, minimum, expected", [+ ("2.3.0", "2.3.0", True),+ ("2.3.0-beta", "2.3.0", False),+ ("11.0.9.509", "11.0.9", True),+ ("11.0.9", "11.0.9.509", False),+ ("2.\u0663.0", "2.3.0", False),+ ("1234567890", "2.3.0", False),+])+def test_version_at_least_accepts_only_bounded_ascii_components(found, minimum, expected):+ assert version_at_least(found, minimum) is expected+++def test_unexpanded_locations_are_missing_even_when_cwd_contains_them(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ for location in ("%HERMES_TEST_UNSET_VAR%/x.exe", "$HERMES_TEST_UNSET_VAR/x"):+ path = tmp_path / location+ path.parent.mkdir(exist_ok=True)+ path.write_text("fixture", encoding="utf-8")+ definition = AppDef("thing", sys.platform, "executable", location)+ assert AppResolver(definition).locate().kind == "missing"+++def test_registry_mutations_are_visible_and_notify_once(monkeypatch):+ from hermes_platform import declaration++ decl = parse_declaration("thing-mcp", None, None, where=WHERE)+ changes = []+ monkeypatch.setattr(declaration, "on_change", lambda: changes.append(None))+ declaration.register("thing-mcp", decl)+ assert declaration.lookup("thing-mcp") is decl+ declaration.unregister("thing-mcp")+ assert declaration.lookup("thing-mcp") is None+ declaration.register("other", decl)+ declaration.clear()+ assert declaration.lookup("other") is None+ assert len(changes) == 4+++def test_skill_requires_apps_gate(tmp_path, monkeypatch):+ from agent import skill_utils+ from hermes_platform import declaration++ monkeypatch.setattr(declaration, "_REGISTRY", {})+ decl = parse_declaration(+ "thing-mcp",+ {sys.platform: {"presence": "executable", "location": str(tmp_path / "thing")}},+ {"app": True},+ where=WHERE,+ )+ declaration.clear()+ try:+ assert skill_utils.skill_matches_apps({}) is True+ assert skill_utils.skill_matches_apps({"requires_apps": ["unknown"]}) is False+ declaration.register("thing-mcp", decl)+ assert skill_utils.skill_matches_apps({"requires_apps": ["thing-mcp"]}) is False+ (tmp_path / "thing").write_text("fixture", encoding="utf-8")+ assert skill_utils.skill_matches_apps({"requires_apps": ["thing-mcp"]}) is True+ finally:+ declaration.clear()diff --git a/tests/hermes_platform/test_import_hygiene.py b/tests/hermes_platform/test_import_hygiene.pyindex 50160c96ecb..3cbf732f71f 100644--- a/tests/hermes_platform/test_import_hygiene.py+++ b/tests/hermes_platform/test_import_hygiene.py@@ -6,7 +6,7 @@ import subprocessimport sys-def test_host_modules_only_import_stdlib_and_hermes_platform() -> None:+def test_platform_modules_only_import_stdlib_and_hermes_platform() -> None:root = Path(__file__).resolve().parents[2]code = """import sys@@ -14,6 +14,11 @@ before = set(sys.modules)import hermes_platform.host.factsimport hermes_platform.host.runtimeimport hermes_platform.host.products+import hermes_platform.declaration+import hermes_platform.resolver+import hermes_platform.resolver.app+import hermes_platform.resolver.availability+import hermes_platform.resolver.known_dirsnew_top_levels = {name.partition('.')[0] for name in set(sys.modules) - before}unexpected = sorted(namediff --git a/tests/hermes_platform/test_resolver_app.py b/tests/hermes_platform/test_resolver_app.pynew file mode 100644index 00000000000..fca388a5d75--- /dev/null+++ b/tests/hermes_platform/test_resolver_app.py@@ -0,0 +1,218 @@+from __future__ import annotations++import dataclasses+import json+import os+import plistlib+import socket+import sys+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer++import pytest++from hermes_platform.resolver import CheckState, Effort, Probeable, Resolver+from hermes_platform.resolver.app import AppDef, AppResolver++TOKEN = "tok-3e1f9c-unique-fixture-value"+++def _bundle(tmp_path, version="9.8.7"):+ app = tmp_path / "Applications" / "Thing.app"+ (app / "Contents").mkdir(parents=True)+ with open(app / "Contents" / "Info.plist", "wb") as fh:+ plistlib.dump({"CFBundleShortVersionString": version}, fh)+ return app+++def _server_json(tmp_path, *, url, pid=None):+ p = tmp_path / "server.json"+ p.write_text(json.dumps({"pid": os.getpid() if pid is None else pid, "http": url, "token": TOKEN}), encoding="utf-8")+ return p+++def _resolver(tmp_path, exe, server_json=None):+ return AppResolver(AppDef(+ "thing", sys.platform, "executable", str(exe),+ liveness_kind="server_json" if server_json else "none",+ liveness_path=str(server_json) if server_json else "",+ ))+++def test_app_resolver_satisfies_both_protocols(tmp_path):+ r = AppResolver(AppDef("x", sys.platform, "executable", str(tmp_path / "x")))+ assert isinstance(r, Resolver) and isinstance(r, Probeable)+++def test_locate_reports_expanded_path_when_missing(tmp_path, monkeypatch):+ monkeypatch.setenv("THINGROOT", str(tmp_path))+ r = AppResolver(AppDef("thing", sys.platform, "executable", "$THINGROOT/bin/thing"))+ res = r.locate()+ assert res.kind == "missing"+ assert res.candidates[0].value == str(tmp_path / "bin" / "thing")+++def test_bundle_presence_and_plist_version(tmp_path):+ app = _bundle(tmp_path)+ r = AppResolver(AppDef("thing", "darwin", "bundle", str(app), version_kind="plist"))+ res = r.locate()+ assert res.kind == "known_path" and res.command == (str(app),)+ insp = r.inspect(res)+ assert insp.version.state is CheckState.PRESENT and insp.version.value == "9.8.7"+ assert insp.signer.state is CheckState.NOT_CHECKED+++def test_inspect_on_missing_is_not_checked(tmp_path):+ r = AppResolver(AppDef("thing", sys.platform, "executable", str(tmp_path / "none"), version_kind="plist"))+ insp = r.inspect(r.locate())+ assert insp.version.state is CheckState.NOT_CHECKED+++def test_probe_without_liveness_source_is_all_not_checked(tmp_path):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ r = _resolver(tmp_path, exe)+ pr = r.probe(r.locate(), effort=Effort.NETWORK)+ assert pr.running.state is pr.answering.state is pr.endpoint.state is CheckState.NOT_CHECKED+++def test_probe_local_reads_pid_and_endpoint_but_never_connects(tmp_path):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ sj = _server_json(tmp_path, url="http://127.0.0.1:1/mcp")+ r = _resolver(tmp_path, exe, sj)+ pr = r.probe(r.locate(), effort=Effort.LOCAL)+ assert pr.running.state is CheckState.PRESENT and pr.running.value is True+ assert pr.endpoint.value == "http://127.0.0.1:1/mcp"+ assert pr.answering.state is CheckState.NOT_CHECKED+++def test_probe_is_not_a_boolean(tmp_path):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ pr = _resolver(tmp_path, exe).probe(_resolver(tmp_path, exe).locate(), effort=Effort.LOCAL)+ with pytest.raises(TypeError):+ bool(pr)+++def test_token_never_appears_in_any_public_result(tmp_path):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ sj = _server_json(tmp_path, url="http://127.0.0.1:1/mcp")+ r = _resolver(tmp_path, exe, sj)+ res = r.locate()+ pr = r.probe(res, effort=Effort.LOCAL)+ for obj in (res, r.inspect(res), pr):+ assert TOKEN not in repr(obj)+ assert TOKEN not in json.dumps(dataclasses.asdict(obj), default=str)+ assert "token" not in {f.name for f in dataclasses.fields(obj)}++[email protected]("url", [+ "http://[::1",+ "https://127.0.0.1:1234/mcp",+ "http://user:[email protected]:1234/mcp",+ "http://example.com:1234/mcp",+ "http://127.0.0.1/mcp",+ "http://127.0.0.1:99999/mcp",+])+def test_non_loopback_or_malformed_endpoint_is_unavailable_and_never_contacted(tmp_path, url, monkeypatch):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ sj = _server_json(tmp_path, url=url)+ r = _resolver(tmp_path, exe, sj)+ monkeypatch.setattr(socket, "create_connection", lambda *a, **k: pytest.fail("no socket allowed"))+ pr = r.probe(r.locate(), effort=Effort.NETWORK)+ assert pr.endpoint.state is CheckState.UNAVAILABLE+ assert pr.answering.state is CheckState.NOT_CHECKED+++def test_dead_pid_is_absent_and_skips_network(tmp_path, monkeypatch):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ sj = _server_json(tmp_path, url="http://127.0.0.1:1/mcp", pid=2**22 + 12345)+ r = _resolver(tmp_path, exe, sj)+ monkeypatch.setattr(socket, "create_connection", lambda *a, **k: pytest.fail("no socket allowed"))+ pr = r.probe(r.locate(), effort=Effort.NETWORK)+ assert pr.running.state is CheckState.ABSENT+ assert pr.answering.state is CheckState.NOT_CHECKED+++class _Handler(BaseHTTPRequestHandler):+ seen: list[tuple[str, str]] = []++ def do_POST(self):+ length = int(self.headers.get("Content-Length", "0"))+ body = json.loads(self.rfile.read(length) or b"{}")+ _Handler.seen.append((self.path, self.headers.get("Authorization", "")))+ self.send_response(200 if body.get("method") == "initialize" else 400)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(b'{"jsonrpc":"2.0","id":1,"result":{}}')++ def log_message(self, format, *args): # noqa: A002+ pass+++def loopback_mcp():+ srv = HTTPServer(("127.0.0.1", 0), _Handler)+ t = threading.Thread(target=srv.serve_forever, daemon=True)+ t.start()+ _Handler.seen.clear()+ yield srv.server_address[1]+ srv.shutdown()+++def test_network_probe_reads_server_json_every_call_and_answers(tmp_path, loopback_mcp):+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ sj = _server_json(tmp_path, url=f"http://127.0.0.1:{loopback_mcp}/ignored")+ r = _resolver(tmp_path, exe, sj)+ res = r.locate()+ first = r.probe(res, effort=Effort.NETWORK)+ assert first.answering.state is CheckState.PRESENT and first.answering.value is True+ assert _Handler.seen[-1] == ("/mcp", f"Bearer {TOKEN}")+ # the vendor moves the port: the next probe must follow without any caller action+ sj.write_text(json.dumps({"pid": os.getpid(), "http": "http://127.0.0.1:1/x", "token": TOKEN}), encoding="utf-8")+ second = r.probe(res, effort=Effort.NETWORK)+ assert second.endpoint.value == "http://127.0.0.1:1/mcp"+ assert second.answering.state is CheckState.ABSENT+++class _SlowDrip(BaseHTTPRequestHandler):+ """Fast 200 and headers, then one body byte every 0.3 s: each receive is under any per-socket timeout."""++ def do_POST(self):+ import time as _t+ self.send_response(200)+ self.send_header("Content-Length", "64")+ self.end_headers()+ for _ in range(64):+ try:+ self.wfile.write(b"x")+ self.wfile.flush()+ except OSError:+ return+ _t.sleep(0.3)++ def log_message(self, format, *args): # noqa: A002+ pass+++def test_network_probe_honors_one_absolute_deadline(tmp_path):+ import time as _t+ srv = HTTPServer(("127.0.0.1", 0), _SlowDrip)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ try:+ exe = tmp_path / "thing"+ exe.write_text("", encoding="utf-8")+ sj = _server_json(tmp_path, url=f"http://127.0.0.1:{srv.server_address[1]}/x")+ r = _resolver(tmp_path, exe, sj)+ t0 = _t.monotonic()+ pr = r.probe(r.locate(), effort=Effort.NETWORK, deadline_s=0.5)+ elapsed = _t.monotonic() - t0+ assert elapsed < 2.0, elapsed+ assert pr.answering.state is CheckState.PRESENT+ finally:+ srv.shutdown()diff --git a/tests/hermes_platform/test_resolver_core.py b/tests/hermes_platform/test_resolver_core.pynew file mode 100644index 00000000000..1049945e674--- /dev/null+++ b/tests/hermes_platform/test_resolver_core.py@@ -0,0 +1,115 @@+from __future__ import annotations++import os+import stat+import sys++import pytest++from hermes_platform.resolver import ABSENT, CheckState, LookupContext, Observation, locate_command+++def _make_exe(path):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("#!/bin/sh\n", encoding="utf-8")+ path.chmod(path.stat().st_mode | stat.S_IXUSR)+ return path++[email protected](sys.platform == "win32", reason="POSIX executable bits")+def test_path_hit_comes_first_and_known_dirs_are_still_recorded(tmp_path):+ on_path = _make_exe(tmp_path / "pathbin" / "tool")+ in_known = _make_exe(tmp_path / "known" / "tool")+ res = locate_command("tool", LookupContext(path=str(on_path.parent)), known_dirs=(str(in_known.parent),))+ assert res.kind == "path_executable"+ assert res.command == (str(on_path),)+ assert [c.present for c in res.candidates] == [True, True]+ assert [c.value for c in res.present] == [str(on_path), str(in_known)]++[email protected](sys.platform == "win32", reason="POSIX executable bits")+def test_known_dir_hit_when_path_misses(tmp_path):+ in_known = _make_exe(tmp_path / "known" / "tool")+ res = locate_command("tool", LookupContext(path=""), known_dirs=(str(in_known.parent),))+ assert res.kind == "known_path"+ assert res.source == f"known_dir:{in_known.parent}"+ assert res.candidates[0].present is False+++def test_empty_path_is_a_miss_not_ambient(tmp_path):+ res = locate_command("python3", LookupContext(path=""))+ assert res.kind == "missing"+ assert res.command == ()+ assert res.present == ()+++def test_absent_and_none_both_mean_ambient():+ assert LookupContext().path is ABSENT+ assert LookupContext().effective_path() is None+ assert LookupContext(path=None).effective_path() is None+ assert LookupContext(path="/x").effective_path() == "/x"++[email protected](sys.platform == "win32", reason="POSIX executable bits")+def test_explicit_path_bypasses_search(tmp_path):+ exe = _make_exe(tmp_path / "bin" / "tool")+ res = locate_command(str(exe), LookupContext(path=""))+ assert res.kind == "explicit_path"+ assert res.command == (str(exe),)+ missing = locate_command(str(tmp_path / "nope" / "tool"), LookupContext(path=""))+ assert missing.kind == "missing" and missing.candidates[0].source == "explicit"++[email protected](sys.platform == "win32", reason="POSIX executable bits")+def test_locate_never_searches_the_working_directory(tmp_path, monkeypatch):+ _make_exe(tmp_path / "tool")+ monkeypatch.chdir(tmp_path)+ assert locate_command("tool", LookupContext(path="")).kind == "missing"+ relative = locate_command("./tool", LookupContext(path=""))+ assert relative.kind == "missing" and relative.candidates[0].present is False++[email protected](sys.platform == "win32", reason="POSIX executable bits")+def test_known_dir_expands_home_and_env(tmp_path, monkeypatch):+ exe = _make_exe(tmp_path / "home" / ".local" / "bin" / "tool")+ monkeypatch.setenv("HOME", str(tmp_path / "home"))+ monkeypatch.setenv("TOOLROOT", str(tmp_path / "home" / ".local"))+ for spec in ("~/.local/bin", "$TOOLROOT/bin"):+ res = locate_command("tool", LookupContext(path=""), known_dirs=(spec,))+ assert res.command == (str(exe),), spec++[email protected]_only+def test_windows_pathext_is_honored_without_mutating_environ(tmp_path, monkeypatch):+ exe = tmp_path / "bin" / "tool.cmd"+ exe.parent.mkdir()+ exe.write_text("@echo off\r\n", encoding="utf-8")+ before = os.environ.get("PATHEXT")+ res = locate_command("tool", LookupContext(path=str(exe.parent), pathext=".CMD"))+ assert res.kind == "path_executable"+ assert res.command[0].lower() == str(exe).lower()+ assert os.environ.get("PATHEXT") == before+++def test_observation_not_checked_is_distinct_from_absent():+ assert Observation.not_checked().state is CheckState.NOT_CHECKED+ assert Observation(CheckState.ABSENT, False).state is not CheckState.NOT_CHECKED+ assert Observation(CheckState.ABSENT, False).value is False+++def test_one_candidate_per_known_dir_regardless_of_pathext(tmp_path):+ res = locate_command("nothing-here", LookupContext(path=""), known_dirs=(str(tmp_path / "a"), str(tmp_path / "b")))+ assert [c.source for c in res.candidates] == ["PATH", f"known_dir:{tmp_path / 'a'}", f"known_dir:{tmp_path / 'b'}"]+++def test_known_dir_tables_match_the_host_os():+ from hermes_platform.resolver import known_dirs as kd++ every = (*kd.homebrew_dirs(), *kd.user_local_bin(), *kd.rust_tool_dirs(),+ *kd.node_tool_dirs(), *kd.hermes_vendored_dirs(), *kd.windows_user_program_dirs())+ assert every, "at least one table applies on every host"+ if sys.platform == "win32":+ assert not any(d.startswith("/") for d in every)+ else:+ assert not any("%" in d for d in every)+ assert bool(kd.homebrew_dirs()) == (sys.platform == "darwin")diff --git a/tests/tools/test_mcp_app_gate.py b/tests/tools/test_mcp_app_gate.pynew file mode 100644index 00000000000..b55d82fc83b--- /dev/null+++ b/tests/tools/test_mcp_app_gate.py@@ -0,0 +1,48 @@+"""Application requirements compose with live, recycled, and lazy MCP connections."""++from __future__ import annotations++import sys+from types import SimpleNamespace++import pytest++from hermes_platform import declaration++[email protected]("connection", ["live", "recycled", "lazy", "absent"])+def test_check_fn_composes_connection_and_registered_requirement(tmp_path, monkeypatch, connection):+ from tools import mcp_tool, mcp_tool_handlers+ from tools.mcp_tool_scope import _resolve_server_key++ monkeypatch.setattr(declaration, "_REGISTRY", {})+ core = mcp_tool+ monkeypatch.setattr(core, "_servers", {})+ monkeypatch.setattr(core, "_lazy_server_configs", {})+ monkeypatch.setattr(core, "_server_tool_scopes", {})+ name = "declaration-test-server"+ key = _resolve_server_key(name)+ if connection == "lazy":+ core._lazy_server_configs[key] = {}+ elif connection != "absent":+ core._servers[key] = SimpleNamespace(+ session=object() if connection == "live" else None,+ _is_recycled_stdio=lambda: connection == "recycled",+ )+ check = mcp_tool_handlers._make_check_fn(name)+ connected = connection != "absent"+ assert check() is connected++ location = tmp_path / "application.exe"+ decl = declaration.parse_declaration(+ name, {sys.platform: {"presence": "executable", "location": str(location)}},+ {"app": True}, where="test-plugin/plugin.yaml",+ )+ declaration.register(name, decl)+ assert check() is False+ location.write_text("presence fixture", encoding="utf-8")+ assert check() is connected+ location.unlink()+ assert check() is False+ declaration.clear()+ assert check() is connecteddiff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.pyindex b94122d62fd..fb7b724bc22 100644--- a/tools/mcp_tool_handlers.py+++ b/tools/mcp_tool_handlers.py@@ -11,7 +11,9 @@ from contextlib import asynccontextmanagerfrom functools import partialfrom types import SimpleNamespacefrom typing import Any, Callable, Dict, List, Optional, Tuple-from tools.registry import tool_error++from hermes_platform import declaration+from tools.registry import invalidate_check_fn_cache, tool_errorfrom tools.ansi_strip import strip_unicode_tagsfrom tools.mcp_tool_common import _exc_str, _sanitize_error, mcp_field, _corefrom tools import mcp_tool_loop as _loop@@ -24,6 +26,8 @@ from tools.mcp_tool_errors import _is_auth_error, _is_session_expired_errorlogger = logging.getLogger("tools.mcp_tool")_MISSING = object()+declaration.on_change = invalidate_check_fn_cache+_NEEDS_REAUTH_MSG = ("MCP server '{s}' requires re-authentication. Run `hermes mcp login {s}` (or delete the tokens file under ""~/.hermes/mcp-tokens/ and restart). Do NOT retry this tool — ask the user to re-authenticate.")@@ -667,13 +671,35 @@ _make_get_prompt_handler = _make_utility_handler(def _make_check_fn(server_name: str):- """Connection-alive check; lazy (schema-cache registered) servers count as available."""+ """Connection-alive check; lazy (schema-cache registered) servers count as available.++ When the server's owner registered an application declaration (`requires.app`), the+ application must also be present on this host, or the tools are not offered even while a+ stale connection lingers. With no declaration registered the check is the connection check+ alone. Returns a plain bool: the registry caches ``bool(fn())``.+ """from tools.mcp_tool_scope import _resolve_server_key- def _check() -> bool:+ def _connected() -> bool:with _core._lock:key = _resolve_server_key(server_name)server = _core._servers.get(key)return ((server is not None and (server.session is not None or server._is_recycled_stdio()))or key in _core._lazy_server_configs)++ def _check() -> bool:+ if not _connected():+ return False+ return _declared_app_offerable(server_name)return _check+++def _declared_app_offerable(server_name: str) -> bool:+ """True unless a declaration registered for this server requires an application this host lacks."""+ from hermes_platform import declaration+ from hermes_platform.resolver.availability import availability++ decl = declaration.lookup(server_name)+ if decl is None or not decl.requires_app:+ return True+ return availability(decl).offerablediff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 456bc1ea8c6..b1e60f5d223 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -114,6 +114,7 @@ def _skill_utils_delegate(attr: str):skill_matches_platform = _skill_utils_delegate("skill_matches_platform")# Offer-time relevance gate (kanban/docker/s6), NOT hard compatibility; explicit loads bypass it.skill_matches_environment = _skill_utils_delegate("skill_matches_environment")+skill_matches_apps = _skill_utils_delegate("skill_matches_apps")_parse_frontmatter = _skill_utils_delegate("parse_frontmatter")_get_disabled_skill_names = _skill_utils_delegate("get_disabled_skill_names")@@ -203,7 +204,7 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:continuetry:frontmatter, body = _parse_frontmatter(_read_skill_text(skill_md)[:4000])- if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter):+ if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter) or not skill_matches_apps(frontmatter):continuename = frontmatter.get("name", skill_md.parent.name)[:MAX_NAME_LENGTH]if name in seen_names or name in disabled:diff --git a/website/docs/developer-guide/plugins/application-declarations.md b/website/docs/developer-guide/plugins/application-declarations.mdnew file mode 100644index 00000000000..20c465be6e3--- /dev/null+++ b/website/docs/developer-guide/plugins/application-declarations.md@@ -0,0 +1,99 @@+# Application declarations++A plugin whose MCP server fronts a desktop application declares which application that is and what the server needs of it. The core evaluates the declaration on the host and gates the server's tools, and any skill that names the application, on the answer. The parser imports only the standard library and `hermes_platform`.++The vocabulary lives in `hermes_platform/declaration.py`. A declaration is data plus policy, parsed from plain mappings (already-decoded YAML, JSON, a dict literal — the parser never touches a file):++```python+from hermes_platform import declaration++decl = declaration.parse_declaration(+ "my-server",+ raw_app={"linux": {"presence": "executable", "location": "/opt/my-app/server"}},+ raw_requires={"app": True},+ where="my-plugin/plugin.yaml", # human label used in error messages+)+declaration.register("my-server", decl)+```++`register(server_name, decl)` stores one declaration under the configured server name in a process-local registry. Loader integration is separate work; core does not read plugin YAML automatically.++An unregistered MCP server keeps its connection-only check. A skill that explicitly names an unregistered server is hidden. `clear()` removes every registration and is not a per-plugin unload operation. Registrations are process-wide, not profile-scoped.++## `app` — how to find the application on each OS++```yaml+app:+ win32:+ presence: executable+ location: "%ProgramFiles%/Vendor/Vendor App/McpServer/Server.exe"+ version: { kind: uninstall_registry, display_name_prefix: "Vendor App" }+ liveness:+ kind: server_json+ path: "%LOCALAPPDATA%/Vendor/Vendor App/McpServer/server.json"+ pid_key: pid+ url_key: http+ token_key: token+ endpoint_path: /mcp+ darwin:+ presence: bundle+ location: /Applications/Vendor.app+ version: { kind: plist }+```++| field | type | rule | maps to `AppDef` |+|---|---|---|---|+| `<os>` | `win32` \| `darwin` \| `linux` | at least one; unknown key is an error | `AppDef.os_family` |+| `presence` | `executable` \| `bundle` | required per OS | `.presence` |+| `location` | str | required; drive-rooted (`C:\\...`) on Windows, or starting with `~` / `%VAR%` / `$VAR`; UNC paths are rejected so a presence check never touches the network; no `..` segment or URL scheme; expansion at lookup | `.location` |+| `version.kind` | `pe_resource` \| `plist` \| `uninstall_registry` \| `none` | default `none`; `pe_resource`/`uninstall_registry` only under `win32`, `plist` only under `darwin` | `.version_kind` |+| `version.display_name_prefix` | str | required when `uninstall_registry` | `.version_arg` |+| `liveness.kind` | `server_json` \| `none` | default `none` | `.liveness_kind` |+| `liveness.path` | str | required when `server_json` | `.liveness_path` |+| `liveness.pid_key` / `url_key` / `token_key` | str | defaults `pid` / `http` / `token` | `.liveness_*_key` |+| `liveness.endpoint_path` | str | default `/mcp`; the path used for `initialize`, never the one in the file | `.endpoint_path` |++When `requires.app` is true, an OS missing from `app:` gives `unsupported_os`.++## `requires` — what the server needs before it is offered++```yaml+requires:+ app: true+ min_version: "2.3.0"+```++| field | type | rule |+|---|---|---|+| `app` | bool | when true, `app:` must exist and the server is gated on presence |+| `min_version` | str | requires `app: true`; dotted numeric; every applicable `app.<os>` must declare a real `version.kind`; compared numerically per segment, non-numeric characters in a segment are dropped (`2.3.0.12594` ≥ `2.3.0`; prerelease suffixes are not ordered) |++`requires.app: true` with no `app:` block is a `DeclarationError`.++## Availability: the one evaluation every reader uses++`hermes_platform/resolver/availability.py::availability(decl) -> Availability`++```+Availability(+ state: available | installed_not_running | missing_app | version_too_old+ | unsupported_os | no_requirements,+ version: str | None, # inspected, when present+ path: str | None, # where the app was found or looked for+ min_version: str | None, # from requires+)+```++- `no_requirements`: no `requires.app`; the application gate passes, but the connection check still applies.+- `unsupported_os`: `requires.app` and no `app.<this os>` block. Zero I/O.+- `missing_app`: `locate` found nothing at `location`.+- `version_too_old`: the version is below the minimum or cannot be read.+- `available`: present, version acceptable or not required.+- `installed_not_running`: reserved vocabulary; this evaluator never produces it.++Evaluation uses `locate` and optional version inspection. It never probes a server, launches an application, or connects. The tool registry retains its existing availability cache.++## The two gates++- **MCP `check_fn`** (`tools/mcp_tool_handlers.py::_make_check_fn`): connection alive AND, when a declaration with `requires.app` is registered for the server, `availability(decl).offerable`. Returns a plain `bool` because the registry caches `bool(fn())`.+- **Skill `requires_apps:` frontmatter** (`agent/skill_utils.py::skill_matches_apps`): each name resolves through `declaration.lookup`; an unknown name hides the skill (fail closed). Offer-time filter, like `environments:`.diff --git a/website/sidebars.ts b/website/sidebars.tsindex 548d5ecf070..3021b2abf48 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -829,6 +829,7 @@ const sidebars: SidebarsConfig = {'developer-guide/web-search-provider-plugin','developer-guide/browser-provider-plugin','developer-guide/terminal-environment-plugin',+ 'developer-guide/plugins/application-declarations',],},'developer-guide/creating-skills',