Skip to content

The agent that grows with you

Plugins: apps are found wherever they are installed on Windows, macOS and Linux (#134050)

Siddharth Balyan3aaae8c5371a
diff --git a/hermes_platform/declaration.py b/hermes_platform/declaration.py
index 197be7bb6de..e6e962a3e7d 100644
--- a/hermes_platform/declaration.py
+++ b/hermes_platform/declaration.py
@@ -7,7 +7,7 @@ import threading
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Mapping, Optional
-from hermes_platform.resolver.app import AppDef
+from hermes_platform.resolver.app import LOCATION_KINDS, AppDef, AppLocation
__all__ = [
"AppSpec",
@@ -104,17 +104,56 @@ def _location_is_rooted(location: str, osf: str) -> bool:
return location.startswith("/")
+def _is_relative_name(value: Any, *, allow_dirs: bool) -> bool:
+ """Checks the stripped value, the one later joined: an empty part rejects a leading / or \\, a colon rejects a drive."""
+ if not isinstance(value, str) or not value.strip() or "://" in value:
+ return False
+ parts = value.strip().replace("\\", "/").split("/")
+ return ".." not in parts and "" not in parts and (allow_dirs or len(parts) == 1) and ":" not in parts[0]
+
+
+def _parse_location(where: str, osf: str, presence: str, label: str, raw: Any) -> AppLocation:
+ """A string is a path, where `*` may stand for a versioned folder; a mapping names a location kind."""
+ if isinstance(raw, str):
+ path = raw.strip()
+ if not path:
+ raise DeclarationError(f"{where}: {label} is required")
+ if not _location_is_rooted(path, osf) or "**" in path:
+ raise DeclarationError(
+ f"{where}: {label} must be absolute or start with ~ / %VAR% / $VAR, without '..', '**' or a URL scheme")
+ return AppLocation("path", path)
+ if not isinstance(raw, dict) or not isinstance(raw.get("kind"), str) or raw["kind"] not in LOCATION_KINDS:
+ raise DeclarationError(f"{where}: {label} must be a path or a mapping with kind one of {sorted(LOCATION_KINDS)}")
+ kind = raw["kind"]
+ spec = LOCATION_KINDS[kind]
+ if spec.only_on and spec.only_on != osf:
+ raise DeclarationError(f"{where}: {label} kind {kind!r} is only valid under app.{spec.only_on}")
+ if spec.yields != presence:
+ raise DeclarationError(f"{where}: {label} kind {kind!r} needs app.{osf}.presence {spec.yields}")
+ value = raw.get(spec.key)
+ if not _is_relative_name(value, allow_dirs=False):
+ raise DeclarationError(f"{where}: {label}.{spec.key} must be a bare name")
+ file = raw.get("file", "")
+ if spec.needs_file and not _is_relative_name(file, allow_dirs=True):
+ raise DeclarationError(f"{where}: {label}.file must be a relative path inside the install folder")
+ return AppLocation(kind, value.strip(), str(file).strip())
+
+
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():
+ if isinstance(location, list):
+ if not location:
+ raise DeclarationError(f"{where}: app.{osf}.location is required")
+ locations = tuple(_parse_location(where, osf, presence, f"app.{osf}.location[{i}]", item)
+ for i, item in enumerate(location))
+ elif isinstance(location, str):
+ locations = (_parse_location(where, osf, presence, f"app.{osf}.location", location),)
+ else:
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")
@@ -135,7 +174,7 @@ def _parse_app_os(where: str, name: str, osf: str, raw: Any) -> AppDef:
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(),
+ app_id=name, os_family=osf, presence=presence, locations=locations,
version_kind=vkind, version_arg=varg,
liveness_kind=lkind, liveness_path=lpath,
liveness_pid_key=str(liveness.get("pid_key") or "pid"),
@@ -181,7 +220,10 @@ def parse_requires(raw: Any, app: Optional[AppSpec], *, where: str) -> RequiresS
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")
+ # Linux has no version source, so a Linux block is gated on presence only; Windows and macOS must read
+ # one, and a Linux-only declaration has nothing to compare.
+ unversioned = [osf for osf in sorted(app.per_os) if app.per_os[osf].version_kind == "none"
+ and (osf != "linux" or len(app.per_os) == 1)]
if unversioned:
raise DeclarationError(
f"{where}: requires.min_version needs a version source under app.{unversioned[0]} (kind is none)")
diff --git a/hermes_platform/resolver/app.py b/hermes_platform/resolver/app.py
index 2e567b474b6..da32d627c4c 100644
--- a/hermes_platform/resolver/app.py
+++ b/hermes_platform/resolver/app.py
@@ -1,28 +1,35 @@
"""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.
+`locate` stats every declared location in order (fixed paths, PATH, uninstall entries, the flatpak,
+snap and Applications directories) and lists directories for a `*` path segment; the first present
+one wins. `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 glob
import json
import os
import plistlib
+import re
import sys
import time
from dataclasses import dataclass
-from typing import Literal
+from typing import Any, Callable, Iterator, Literal
from urllib.parse import urlsplit
+from hermes_platform.resolver import known_dirs
from hermes_platform.resolver.base import Effort, Inspection, Probe
from hermes_platform.resolver.core import (
Candidate,
CheckState,
+ Kind,
LookupContext,
Observation,
Resolution,
+ locate_command,
)
PresenceKind = Literal["executable", "bundle"]
@@ -32,6 +39,16 @@ LivenessKind = Literal["server_json", "none"]
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})
+@dataclass(frozen=True)
+class AppLocation:
+ """One place to look. `kind` is `path` or a key of `LOCATION_KINDS`. `value` is the path, or the
+ value of that kind's `key`. `file` is joined onto an uninstall entry's `InstallLocation`."""
+
+ kind: str
+ value: str
+ file: str = ""
+
+
@dataclass(frozen=True)
class AppDef:
"""One application on one OS. Paths use `%VAR%` and `~`; expansion happens at lookup."""
@@ -39,7 +56,7 @@ class AppDef:
app_id: str
os_family: str
presence: PresenceKind
- location: str
+ locations: tuple[AppLocation, ...]
version_kind: VersionKind = "none"
version_arg: str = ""
liveness_kind: LivenessKind = "none"
@@ -75,15 +92,9 @@ class AppResolver:
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,))
+ found = [hit for loc in d.locations for hit in _locator(loc.kind)(d, loc, ctx)]
+ kind: Kind = next((k for c, k in found if c.present), "missing")
+ return Resolution(kind, tuple(c for c, _ in found))
# ---- inspect: bounded file reads and in-process OS APIs -----------------------------
@@ -139,6 +150,87 @@ class AppResolver:
return Probe(running=running, answering=answering, endpoint=endpoint_obs)
+# ---- locations: each yields (candidate, resolution kind) in probe order -----------------
+
+_Hit = tuple[Candidate, Kind]
+_Locator = Callable[[AppDef, AppLocation, LookupContext | None], list[_Hit]]
+
+
+def _present(presence: PresenceKind, path: str) -> bool:
+ if presence == "bundle":
+ return os.path.isdir(path) and os.path.isfile(os.path.join(path, "Contents", "Info.plist"))
+ return os.path.isfile(path)
+
+
+def _hit(d: AppDef, source: str, path: str) -> _Hit:
+ present = os.path.isabs(path) and _present(d.presence, path)
+ return Candidate(path, source, present), "known_path"
+
+
+def _version_order(path: str) -> list:
+ return [(1, int(part)) if part.isdigit() else (0, part) for part in re.split(r"(\d+)", path)]
+
+
+def _path_hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
+ target, source = _expand(loc.value), f"app:{d.app_id}"
+ not_found: list[_Hit] = [(Candidate(target, source, False), "known_path")]
+ if not os.path.isabs(target) or "%" in target or "$" in target:
+ return not_found
+ if "*" not in target:
+ return [_hit(d, source, target)]
+ # A `*` segment stands for a versioned folder (`Blender 5.2`); the highest version is tried first.
+ pattern = "*".join(glob.escape(part) for part in target.split("*"))
+ matches = sorted(glob.glob(pattern), key=_version_order, reverse=True)
+ return [_hit(d, source, match) for match in matches] or not_found
+
+
+def _command_hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
+ res = locate_command(loc.value, ctx)
+ return [(Candidate(c.value, f"app:{d.app_id}:{loc.kind}", c.present), "path_executable") for c in res.candidates]
+
+
+def _uninstall_hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
+ if sys.platform != "win32":
+ return []
+ # A UNC InstallLocation is skipped so a presence check never touches the network.
+ return [_hit(d, f"app:{d.app_id}:{loc.kind}", os.path.join(entry["InstallLocation"], loc.file))
+ for entry in _uninstall_entries(loc.value)
+ if entry.get("InstallLocation") and not entry["InstallLocation"].startswith(("\\\\", "//"))]
+
+
+def _in_dirs(dirs: Callable[[], tuple[str, ...]]) -> _Locator:
+ def hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
+ return [_hit(d, f"app:{d.app_id}:{loc.kind}", os.path.join(_expand(root), loc.value)) for root in dirs()]
+ return hits
+
+
+@dataclass(frozen=True)
+class LocationSpec:
+ """A location kind a declaration names in a mapping. `only_on` is the one OS family it is valid
+ under (None: any), `key` names the mapping field holding what to find, `yields` is the presence
+ it finds, and `needs_file` says the mapping also carries a relative `file`."""
+
+ only_on: str | None
+ key: str
+ yields: PresenceKind
+ locate: _Locator
+ needs_file: bool = False
+
+
+LOCATION_KINDS: dict[str, LocationSpec] = {
+ "command": LocationSpec(None, "name", "executable", _command_hits),
+ "uninstall_registry": LocationSpec("win32", "display_name_prefix", "executable", _uninstall_hits, needs_file=True),
+ "app_bundle": LocationSpec("darwin", "name", "bundle", _in_dirs(known_dirs.mac_application_dirs)),
+ "flatpak": LocationSpec("linux", "app_id", "executable", _in_dirs(known_dirs.flatpak_export_dirs)),
+ "snap": LocationSpec("linux", "name", "executable", _in_dirs(known_dirs.snap_bin_dirs)),
+}
+
+
+def _locator(kind: str) -> _Locator:
+ """A plain string location is a `path`; every other kind comes from `LOCATION_KINDS`."""
+ return _path_hits if kind == "path" else LOCATION_KINDS[kind].locate
+
+
# ---- version sources -------------------------------------------------------------------
@@ -180,9 +272,32 @@ def _pe_version(path: str) -> Observation[str]:
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")
+def _uninstall_values(entry: Any) -> dict[str, str]:
+ """The uninstall entry's values that exist; any of them may be missing."""
+ import winreg
+
+ values: dict[str, str] = {}
+ for value_name in ("DisplayName", "DisplayVersion", "InstallLocation"):
+ try:
+ values[value_name] = str(winreg.QueryValueEx(entry, value_name)[0])
+ except OSError:
+ continue
+ return values
+
+
+def _uninstall_entry(key: Any, index: int) -> dict[str, str]:
+ """One child entry's values; an entry can vanish between EnumKey and OpenKey, which reads as no values."""
+ import winreg
+
+ try:
+ with winreg.OpenKey(key, winreg.EnumKey(key, index)) as entry:
+ return _uninstall_values(entry)
+ except OSError:
+ return {}
+
+
+def _uninstall_entries(display_name_prefix: str) -> Iterator[dict[str, str]]:
+ """Each uninstall entry whose `DisplayName` starts with the prefix, machine-wide before per-user."""
import winreg
roots = (
@@ -195,21 +310,22 @@ def _uninstall_registry_version(display_name_prefix: str) -> Observation[str]:
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))
+ values = _uninstall_entry(key, i)
+ if values.get("DisplayName", "").startswith(display_name_prefix):
+ yield values
except OSError:
continue
- return Observation(CheckState.ABSENT, detail="no uninstall entry")
+
+
+def _uninstall_registry_version(display_name_prefix: str) -> Observation[str]:
+ if sys.platform != "win32":
+ return Observation(CheckState.UNAVAILABLE, detail="uninstall_registry needs Windows")
+ entry = next(_uninstall_entries(display_name_prefix), None)
+ if entry is None:
+ return Observation(CheckState.ABSENT, detail="no uninstall entry")
+ if "DisplayVersion" not in entry:
+ return Observation(CheckState.UNAVAILABLE, detail="entry has no DisplayVersion")
+ return Observation(CheckState.PRESENT, entry["DisplayVersion"])
# ---- liveness: the token stays inside this section -------------------------------------
diff --git a/hermes_platform/resolver/availability.py b/hermes_platform/resolver/availability.py
index 09acd5ee732..d7c77d98d20 100644
--- a/hermes_platform/resolver/availability.py
+++ b/hermes_platform/resolver/availability.py
@@ -12,7 +12,7 @@ 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
+from hermes_platform.resolver.core import Candidate, CheckState, Resolution
AvailabilityState = Literal[
"available",
@@ -60,15 +60,15 @@ class Availability:
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 _version_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(".")]
- 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)
+def version_at_least(found: str, minimum: str) -> bool:
+ """Compare dot-separated decimal components, failing closed on invalid input."""
+ a, b = _version_parts(found), _version_parts(minimum)
if a is None or b is None:
return False
width = max(len(a), len(b))
@@ -96,10 +96,22 @@ def availability(entry: _HasRequirements, *, os_family: str | None = None) -> Av
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)
+ if definition.version_kind == "none":
+ return Availability("available", path=looked_at, min_version=entry.min_version)
+
+ def version_of(copy: Candidate) -> str | None:
+ obs = resolver.inspect(Resolution(res.kind, (copy,))).version
+ return obs.value if obs.state is CheckState.PRESENT else None
+
+ if not entry.min_version:
+ return Availability("available", version=version_of(res.present[0]), path=looked_at)
+ # Every present copy is read, so an old copy found first does not hide a newer one found later;
+ # location order only breaks ties among copies that qualify.
+ copies = [(copy.value, version_of(copy)) for copy in res.present]
+ for path, version in copies:
+ if version is not None and version_at_least(version, entry.min_version):
+ return Availability("available", version=version, path=path, min_version=entry.min_version)
+ readable = [(parts, path, version) for path, version in copies
+ if version is not None and (parts := _version_parts(version)) is not None]
+ _, path, version = max(readable, key=lambda item: item[0]) if readable else (None, looked_at, None)
+ return Availability("version_too_old", version=version, path=path, min_version=entry.min_version)
diff --git a/hermes_platform/resolver/known_dirs.py b/hermes_platform/resolver/known_dirs.py
index d22fe0ac13e..3225a6ca144 100644
--- a/hermes_platform/resolver/known_dirs.py
+++ b/hermes_platform/resolver/known_dirs.py
@@ -41,3 +41,16 @@ def windows_user_program_dirs() -> tuple[str, ...]:
"%USERPROFILE%/scoop/shims",
"%LOCALAPPDATA%/Microsoft/WinGet/Links",
)
+
+
+def mac_application_dirs() -> tuple[str, ...]:
+ return ("/Applications", "~/Applications") if sys.platform == "darwin" else ()
+
+
+def flatpak_export_dirs() -> tuple[str, ...]:
+ """Where flatpak links each installed app's launcher, named by its app id (system, then per-user)."""
+ return ("/var/lib/flatpak/exports/bin", "~/.local/share/flatpak/exports/bin") if sys.platform.startswith("linux") else ()
+
+
+def snap_bin_dirs() -> tuple[str, ...]:
+ return ("/snap/bin",) if sys.platform.startswith("linux") else ()
diff --git a/tests/hermes_platform/test_declaration.py b/tests/hermes_platform/test_declaration.py
index cbdc7ca0f8a..3e7b185804a 100644
--- a/tests/hermes_platform/test_declaration.py
+++ b/tests/hermes_platform/test_declaration.py
@@ -13,7 +13,7 @@ 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.app import AppDef, AppLocation, AppResolver
from hermes_platform.resolver.availability import Availability, availability, version_at_least
WHERE = "test-plugin/plugin.yaml"
@@ -64,6 +64,20 @@ def test_app_block_parses_into_one_appdef_per_os():
({"darwin": {"presence": "bundle", "location": "https://example.test/Thing.app"}}, None, "must be absolute"),
({"win32": {"presence": "executable", "location": "Thing/thing.exe"}}, None, "must be absolute"),
(None, {"gpu": "amd"}, "requires.gpu must be one of"),
+ ({"darwin": {"presence": "bundle", "location": "/Applications/Thing */**/Thing.app"}}, None, "must be absolute"),
+ ({"linux": {"presence": "executable", "location": []}}, None, "location is required"),
+ ({"linux": {"presence": "executable", "location": [{"kind": "registry", "name": "thing"}]}}, None,
+ "must be a path or a mapping with kind one of"),
+ ({"linux": {"presence": "executable", "location": [{"kind": "app_bundle", "name": "Thing.app"}]}}, None,
+ "only valid under app.darwin"),
+ ({"darwin": {"presence": "bundle", "location": [{"kind": "command", "name": "thing"}]}}, None,
+ "needs app.darwin.presence executable"),
+ ({"linux": {"presence": "executable", "location": [{"kind": "snap", "name": "../thing"}]}}, None,
+ "location\\[0\\].name must be a bare name"),
+ ({"win32": {"presence": "executable", "location": [{"kind": "uninstall_registry", "display_name_prefix": "Thing"}]}},
+ None, "location\\[0\\].file must be a relative path"),
+ ({"linux": {"presence": "executable", "location": "/usr/bin/thing"}}, {"app": True, "min_version": "1.0"},
+ "needs a version source under app.linux"),
])
def test_invalid_blocks_name_the_rule(raw_app, raw_requires, message):
with pytest.raises(DeclarationError, match=message):
@@ -129,6 +143,50 @@ def test_availability_missing_then_present_then_version_gate(tmp_path):
assert availability(decl, os_family="darwin").state == "version_too_old"
+def test_location_list_parses_each_kind_in_order():
+ decl = parse_declaration("thing-mcp", {
+ "win32": {"presence": "executable", "location": [
+ {"kind": "uninstall_registry", "display_name_prefix": "Thing", "file": "bin/thing.exe"},
+ "%ProgramFiles%/Thing */thing.exe",
+ ]},
+ "linux": {"presence": "executable", "location": [
+ {"kind": "command", "name": "thing"}, {"kind": "flatpak", "app_id": "org.thing.Thing"},
+ ]},
+ }, None, where=WHERE)
+ win, linux = decl.app_for("win32"), decl.app_for("linux")
+ assert win is not None and linux is not None
+ assert win.locations == (AppLocation("uninstall_registry", "Thing", "bin/thing.exe"),
+ AppLocation("path", "%ProgramFiles%/Thing */thing.exe"))
+ assert linux.locations == (AppLocation("command", "thing"), AppLocation("flatpak", "org.thing.Thing"))
+
+
+def test_min_version_lets_a_linux_block_go_without_a_version_source():
+ decl = parse_declaration("thing-mcp", {
+ "darwin": {"presence": "bundle", "location": "/Applications/Thing.app", "version": {"kind": "plist"}},
+ "linux": {"presence": "executable", "location": [{"kind": "command", "name": "thing"}]},
+ }, {"app": True, "min_version": "2.0"}, where=WHERE)
+ linux = decl.app_for("linux")
+ assert decl.min_version == "2.0" and linux is not None and linux.version_kind == "none"
+
+
+def test_min_version_picks_a_newer_copy_found_after_an_old_one(tmp_path, monkeypatch):
+ monkeypatch.setenv("THINGROOT", str(tmp_path))
+ _bundle(tmp_path / "old", "1.0")
+ _bundle(tmp_path / "new", "2.4")
+ decl = parse_declaration("thing-mcp", {"darwin": {
+ "presence": "bundle",
+ "location": ["$THINGROOT/old/Applications/Thing.app", "$THINGROOT/new/Applications/Thing.app"],
+ "version": {"kind": "plist"},
+ }}, {"app": True, "min_version": "2.0"}, where=WHERE)
+ ok = availability(decl, os_family="darwin")
+ assert ok.state == "available" and ok.version == "2.4" and str(tmp_path / "new") in (ok.path or "")
+ too_old = parse_declaration("thing-mcp", {"darwin": {
+ "presence": "bundle", "location": "$THINGROOT/old/Applications/Thing.app", "version": {"kind": "plist"},
+ }}, {"app": True, "min_version": "2.0"}, where=WHERE)
+ assert availability(too_old, os_family="darwin").version == "1.0"
+
+
def test_availability_is_not_a_boolean():
with pytest.raises(TypeError):
bool(Availability("available"))
@@ -152,7 +210,7 @@ def test_unexpanded_locations_are_missing_even_when_cwd_contains_them(tmp_path,
path = tmp_path / location
path.parent.mkdir(exist_ok=True)
path.write_text("fixture", encoding="utf-8")
- definition = AppDef("thing", sys.platform, "executable", location)
+ definition = AppDef("thing", sys.platform, "executable", (AppLocation("path", location),))
assert AppResolver(definition).locate().kind == "missing"
diff --git a/tests/hermes_platform/test_resolver_app.py b/tests/hermes_platform/test_resolver_app.py
index 0e41a2a8227..9c1173640e6 100644
--- a/tests/hermes_platform/test_resolver_app.py
+++ b/tests/hermes_platform/test_resolver_app.py
@@ -12,7 +12,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
import pytest
from hermes_platform.resolver import CheckState, Effort
-from hermes_platform.resolver.app import AppDef, AppResolver, Endpoint
+from hermes_platform.resolver.app import AppDef, AppLocation, AppResolver, Endpoint
TOKEN = "tok-3e1f9c-unique-fixture-value"
@@ -33,7 +33,7 @@ def _server_json(tmp_path, *, url, pid=None):
def _resolver(tmp_path, exe, server_json=None):
return AppResolver(AppDef(
- "thing", sys.platform, "executable", str(exe),
+ "thing", sys.platform, "executable", (AppLocation("path", str(exe)),),
liveness_kind="server_json" if server_json else "none",
liveness_path=str(server_json) if server_json else "",
))
@@ -43,7 +43,7 @@ def _resolver(tmp_path, exe, server_json=None):
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"))
+ r = AppResolver(AppDef("thing", sys.platform, "executable", (AppLocation("path", "$THINGROOT/bin/thing"),)))
res = r.locate()
assert res.kind == "missing"
assert res.candidates[0].value == str(tmp_path / "bin" / "thing")
@@ -51,7 +51,7 @@ def test_locate_reports_expanded_path_when_missing(tmp_path, monkeypatch):
def test_bundle_presence_and_plist_version(tmp_path):
app = _bundle(tmp_path)
- r = AppResolver(AppDef("thing", "darwin", "bundle", str(app), version_kind="plist"))
+ r = AppResolver(AppDef("thing", "darwin", "bundle", (AppLocation("path", str(app)),), version_kind="plist"))
res = r.locate()
assert res.kind == "known_path" and res.command == (str(app),)
insp = r.inspect(res)
@@ -59,8 +59,29 @@ def test_bundle_presence_and_plist_version(tmp_path):
assert insp.signer.state is CheckState.NOT_CHECKED
+def test_star_segment_tries_the_highest_version_first(tmp_path):
+ for version in ("2.9", "2.10", "10.0b"):
+ folder = tmp_path / f"Thing {version}"
+ folder.mkdir()
+ (folder / "thing").write_text("", encoding="utf-8")
+ location = AppLocation("path", str(tmp_path / "Thing *" / "thing"))
+ res = AppResolver(AppDef("thing", sys.platform, "executable", (location,))).locate()
+ assert res.kind == "known_path"
+ assert [os.path.basename(os.path.dirname(c.value)) for c in res.candidates] == ["Thing 10.0b", "Thing 2.10", "Thing 2.9"]
+
+
+def test_first_present_location_sets_the_resolution(tmp_path):
+ exe = tmp_path / "later" / "thing"
+ exe.parent.mkdir()
+ exe.write_text("", encoding="utf-8")
+ locations = (AppLocation("path", str(tmp_path / "absent" / "thing")), AppLocation("path", str(exe)))
+ res = AppResolver(AppDef("thing", sys.platform, "executable", locations)).locate()
+ assert res.kind == "known_path" and res.command == (str(exe),)
+ assert [c.present for c in res.candidates] == [False, True]
+
+
def test_inspect_on_missing_is_not_checked(tmp_path):
- r = AppResolver(AppDef("thing", sys.platform, "executable", str(tmp_path / "none"), version_kind="plist"))
+ r = AppResolver(AppDef("thing", sys.platform, "executable", (AppLocation("path", str(tmp_path / "none")),), version_kind="plist"))
insp = r.inspect(r.locate())
assert insp.version.state is CheckState.NOT_CHECKED
diff --git a/website/docs/developer-guide/plugins/application-declarations.md b/website/docs/developer-guide/plugins/application-declarations.md
index 93e5e147d57..d5130f27aff 100644
--- a/website/docs/developer-guide/plugins/application-declarations.md
+++ b/website/docs/developer-guide/plugins/application-declarations.md
@@ -41,11 +41,44 @@ app:
version: { kind: plist }
```
+`location` is one path or an ordered list of places to look; the first present one wins, except that with `requires.min_version` every present copy's version is read and the first copy that qualifies wins. A list item is a path or a mapping that names a location kind:
+
+```yaml
+app:
+ win32:
+ presence: executable
+ location:
+ - { kind: uninstall_registry, display_name_prefix: "Vendor App", file: vendor.exe }
+ - "%ProgramFiles%/Vendor/Vendor App */vendor.exe"
+ version: { kind: pe_resource }
+ darwin:
+ presence: bundle
+ location: [{ kind: app_bundle, name: Vendor.app }]
+ version: { kind: plist }
+ linux:
+ presence: executable
+ location:
+ - { kind: command, name: vendor }
+ - { kind: flatpak, app_id: com.vendor.App }
+ - { kind: snap, name: vendor }
+```
+
+| location kind | OS | key | where it looks |
+|---|---|---|---|
+| (a path string) | any | — | that path; a `*` stands for a versioned folder, highest version first |
+| `command` | any | `name` | `PATH` (`executable` only) |
+| `uninstall_registry` | `win32` | `display_name_prefix`, `file` | `InstallLocation` of each matching uninstall entry, joined with `file` |
+| `app_bundle` | `darwin` | `name` | `/Applications`, then `~/Applications` (`bundle` only) |
+| `flatpak` | `linux` | `app_id` | the system, then the per-user flatpak `exports/bin` |
+| `snap` | `linux` | `name` | `/snap/bin` |
+
+Each kind's OS, key, presence and locator are one `LOCATION_KINDS` entry in `hermes_platform/resolver/app.py`; the parser validates against that table, so a new kind is one entry there. The directories behind each kind live in `hermes_platform/resolver/known_dirs.py`.
+
| 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` |
+| `location` | str \| list | required; a path is drive-rooted (`C:\\...`) on Windows, or starts with `~` / `%VAR%` / `$VAR`; UNC paths are rejected so a presence check never touches the network; no `..` segment, `**` or URL scheme; expansion at lookup. A list holds paths and location-kind mappings (above) | `.locations` |
| `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` |
@@ -66,7 +99,7 @@ requires:
| 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) |
+| `min_version` | str | requires `app: true`; dotted numeric; every `app.win32` and `app.darwin` must declare a real `version.kind`; `app.linux` may omit it (Linux has no version source) and is then gated on presence only, but a Linux-only declaration cannot set a minimum; compared numerically per segment, non-numeric characters in a segment are dropped (`2.3.0.12594` ≥ `2.3.0`; prerelease suffixes are not ordered) |
| `gpu` | str | `nvidia`; the server is offered only on a host where `hermes_platform.host.facts.gpu_class()` reports that vendor. Independent of `app`: a server with no `app:` block can require a GPU. |
`requires.app: true` with no `app:` block is a `DeclarationError`.
@@ -90,7 +123,7 @@ Availability(
- `no_requirements`: no `requires.app`, and `requires.gpu` (if any) is met; the application gate passes, but the connection check still applies.
- `unsupported_os`: `requires.app` and no `app.<this os>` block. Zero I/O.
- `unsupported_gpu`: `requires.gpu` names a vendor this host's GPU is not. The install is refused (`… is unavailable: unsupported_gpu, needs an NVIDIA GPU.`), and a registered server's status sentence is "`<app>` needs an NVIDIA GPU; none was found on this machine. Use `<app>` on a machine with an NVIDIA GPU."
-- `missing_app`: `locate` found nothing at `location`.
+- `missing_app`: `locate` found nothing at any `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.