Skip to content

The agent that grows with you

P07: find Blender on Windows, macOS and Linux; offer its task only when present (#129246)

Siddharth Balyan1954a86e128c
diff --git a/agent/initiate_setup_prompt.py b/agent/initiate_setup_prompt.py
index 8022c5690df..569db962045 100644
--- a/agent/initiate_setup_prompt.py
+++ b/agent/initiate_setup_prompt.py
@@ -4,6 +4,7 @@ import importlib.util
import json
import re
import threading
+from functools import partial
from pathlib import Path
from typing import NamedTuple
@@ -71,7 +72,7 @@ def build_initiate_setup_prompt(surface: str, tools, primary_profile: str) -> st
}
host_facts = _host_facts_module(skill_dir)
# Waits on the scan the setup profile started at creation instead of scanning a second time.
- scanned = host_facts.scan_outcome(*start_user_scan())
+ scanned = partial(host_facts.scan_outcome, *start_user_scan())
# Same bytes the hook prints when the skill loads through inline shell.
host = json.dumps(host_facts.collect(scanned), ensure_ascii=False, separators=(",", ":"))
skill = (skill_dir / "SKILL.md").read_text(encoding="utf-8-sig").strip()
diff --git a/hermes_platform/declaration.py b/hermes_platform/declaration.py
index cc2ef5b2cff..4864c94c1a3 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 AppDef, AppLocation
__all__ = [
"AppSpec",
@@ -70,6 +70,14 @@ _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")
+# location kind -> (only valid under this OS, the key naming what to find, the presence it yields)
+_APP_LOCATION_KINDS = {
+ "command": (None, "name", "executable"),
+ "uninstall_registry": ("win32", "display_name_prefix", "executable"),
+ "app_bundle": ("darwin", "name", "bundle"),
+ "flatpak": ("linux", "app_id", "executable"),
+ "snap": ("linux", "name", "executable"),
+}
_VERSION_RE = re.compile(r"^\d+(\.\d+)*$")
@@ -89,17 +97,55 @@ def _location_is_rooted(location: str, osf: str) -> bool:
return location.startswith("/")
+def _is_relative_name(value: Any, *, allow_dirs: bool) -> bool:
+ if not isinstance(value, str) or not value.strip() or "://" in value:
+ return False
+ parts = value.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 raw.get("kind") not in _APP_LOCATION_KINDS:
+ raise DeclarationError(f"{where}: {label} must be a path or a mapping with kind one of {sorted(_APP_LOCATION_KINDS)}")
+ kind = raw["kind"]
+ only_on, key, yields = _APP_LOCATION_KINDS[kind]
+ if only_on and only_on != osf:
+ raise DeclarationError(f"{where}: {label} kind {kind!r} is only valid under app.{only_on}")
+ if yields != presence:
+ raise DeclarationError(f"{where}: {label} kind {kind!r} needs app.{osf}.presence {yields}")
+ value = raw.get(key)
+ if not _is_relative_name(value, allow_dirs=False):
+ raise DeclarationError(f"{where}: {label}.{key} must be a bare name")
+ file = raw.get("file", "")
+ if kind == "uninstall_registry" 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")
@@ -120,7 +166,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"),
@@ -163,7 +209,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..386c7e8f942 100644
--- a/hermes_platform/resolver/app.py
+++ b/hermes_platform/resolver/app.py
@@ -1,37 +1,56 @@
"""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 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"]
+LocationKind = Literal["path", "command", "uninstall_registry", "app_bundle", "flatpak", "snap"]
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 AppLocation:
+ """One place to look. `value` is the path (`path`), the command or snap name, the uninstall
+ entry's `DisplayName` prefix, the bundle name, or the flatpak app id. `file` is joined onto an
+ uninstall entry's `InstallLocation`."""
+
+ kind: LocationKind
+ value: str
+ file: str = ""
+
+
@dataclass(frozen=True)
class AppDef:
"""One application on one OS. Paths use `%VAR%` and `~`; expansion happens at lookup."""
@@ -39,7 +58,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 +94,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 _LOCATORS[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 +152,70 @@ 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}:command", 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}:uninstall_registry", 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, ...]], kind: str) -> _Locator:
+ def hits(d: AppDef, loc: AppLocation, ctx: LookupContext | None) -> list[_Hit]:
+ return [_hit(d, f"app:{d.app_id}:{kind}", os.path.join(_expand(root), loc.value)) for root in dirs()]
+ return hits
+
+
+_LOCATORS: dict[str, _Locator] = {
+ "path": _path_hits,
+ "command": _command_hits,
+ "uninstall_registry": _uninstall_hits,
+ "app_bundle": _in_dirs(known_dirs.mac_application_dirs, "app_bundle"),
+ "flatpak": _in_dirs(known_dirs.flatpak_export_dirs, "flatpak"),
+ "snap": _in_dirs(known_dirs.snap_bin_dirs, "snap"),
+}
+
+
# ---- version sources -------------------------------------------------------------------
@@ -180,9 +257,8 @@ 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_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 = (
@@ -197,19 +273,27 @@ def _uninstall_registry_version(display_name_prefix: str) -> Observation[str]:
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):
+ values: dict[str, str] = {}
+ for value_name in ("DisplayName", "DisplayVersion", "InstallLocation"):
try:
- version, _ = winreg.QueryValueEx(entry, "DisplayVersion")
+ values[value_name] = str(winreg.QueryValueEx(entry, value_name)[0])
except OSError:
- return Observation(CheckState.UNAVAILABLE, detail="entry has no DisplayVersion")
- return Observation(CheckState.PRESENT, str(version))
+ continue
+ 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 1827160e31a..931db71001f 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",
@@ -56,15 +56,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))
@@ -85,10 +85,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/optional-skills/productivity/initiate-setup/scripts/host_facts.py b/optional-skills/productivity/initiate-setup/scripts/host_facts.py
index 8692c7b91e7..52cc88951c9 100644
--- a/optional-skills/productivity/initiate-setup/scripts/host_facts.py
+++ b/optional-skills/productivity/initiate-setup/scripts/host_facts.py
@@ -18,6 +18,7 @@ builder may also import ``collect()`` and embed its result.
from __future__ import annotations
import argparse
+import contextvars
import json
import os
import platform
@@ -27,7 +28,9 @@ import threading
import time
from contextlib import suppress
from datetime import datetime, timezone
+from functools import partial
from pathlib import Path
+from typing import Any, Callable
from hermes_platform.host import facts, products, runtime
@@ -418,19 +421,42 @@ def scan_into(box: dict) -> None:
box["error"] = type(exc).__name__
-def scan_outcome(worker: threading.Thread, box: dict) -> tuple[dict | None, str]:
- """Wait up to the deadline for ``worker`` running :func:`scan_into` on ``box``."""
- worker.join(SCAN_DEADLINE_S)
+def scan_outcome(worker: threading.Thread, box: dict, deadline: float) -> tuple[dict | None, str]:
+ """Wait up to the deadline (``time.monotonic``) for ``worker`` running :func:`scan_into` on ``box``."""
+ worker.join(max(0.0, deadline - time.monotonic()))
if "result" in box:
return box["result"]
return None, box.get("error", "timeout")
-def _scan() -> tuple[dict | None, str]:
+def _in_background(work: Callable[[], Any]) -> Callable[[float], tuple[Any, str]]:
+ """Start ``work`` on a daemon thread under the caller's contextvars (its profile scope). The returned
+ join waits until ``deadline`` (``time.monotonic``) and gives ``(result, "")``, or ``(None, reason)``
+ when the work failed or is still running."""
+ box: dict = {}
+ context = contextvars.copy_context()
+
+ def run() -> None:
+ try:
+ box["result"] = context.run(work)
+ except Exception as exc:
+ box["error"] = type(exc).__name__
+
+ worker = threading.Thread(target=run, daemon=True)
+ worker.start()
+
+ def join(deadline: float) -> tuple[Any, str]:
+ worker.join(max(0.0, deadline - time.monotonic()))
+ return (box["result"], "") if "result" in box else (None, box.get("error", "timeout"))
+
+ return join
+
+
+def _scan() -> Callable[[float], tuple[dict | None, str]]:
box: dict = {}
worker = threading.Thread(target=scan_into, args=(box,), daemon=True)
worker.start()
- return scan_outcome(worker, box)
+ return partial(scan_outcome, worker, box)
def _value(profile: dict, fid: str) -> dict | None:
@@ -612,6 +638,28 @@ def interpret(profile: dict, source: str) -> dict:
return block
+def _blender_declared_state() -> str:
+ """Blender's state as the plugins card and the installer judge it: the resolver over the Blender
+ plugin's pinned ``app:`` declaration. Reading that declaration takes the network, so ``collect``
+ runs this beside the scan and under the same deadline."""
+ from hermes_cli.plugin_catalog import get_live_catalog_entry
+ from hermes_cli.plugin_catalog_presence import presence
+
+ entry = get_live_catalog_entry("blender")
+ return presence(entry).state if entry else "unknown"
+
+
+def _blender_present(declared: str | None, profile: dict | None) -> bool:
+ """Only proof of absence hides the Blender task: the declaration says ``missing_app``, or, when the
+ declaration gave no answer, the scan's app inventory ran and has no Blender. No evidence keeps it."""
+ if declared not in (None, "unknown"):
+ return declared != "missing_app"
+ if not profile or _value(profile, "apps.taxonomy") is None:
+ return True
+ used, unused, _ = _scan_apps(profile)
+ return "Blender" in used + unused
+
+
def _machine_state(scan: dict | None, age: int | None) -> tuple[str, int | None]:
if scan and scan.get("machine_state") in ("fresh", "settling", "established"):
owned = scan.get("owned_days")
@@ -621,10 +669,13 @@ def _machine_state(scan: dict | None, age: int | None) -> tuple[str, int | None]
return ("fresh" if age <= NEW_MACHINE_DAYS else "settling" if age < SETTLING_DAYS else "established"), age
-def collect(scanned: tuple[dict | None, str] | None = None) -> dict:
- """Return the fact block the ``/initiate-setup`` first turn embeds. ``scanned`` is a
- ``(profile, source)`` pair from a scan already run; without it this scans now."""
- profile, source = scanned if scanned is not None else _scan()
+def collect(scanned: Callable[[float], tuple[dict | None, str]] | None = None) -> dict:
+ """Return the fact block the ``/initiate-setup`` first turn embeds. ``scanned`` waits until the
+ deadline it is given for the ``(profile, source)`` pair of a scan already started; without it
+ this scans now. The Blender declaration is read beside the scan, under the same deadline."""
+ deadline = time.monotonic() + SCAN_DEADLINE_S
+ blender = _in_background(_blender_declared_state)
+ profile, source = (scanned or _scan())(deadline)
scan = interpret(profile, source) if profile else {"source": "unavailable", "reason": source}
os_family = facts.os_family()
@@ -643,7 +694,9 @@ def collect(scanned: tuple[dict | None, str] | None = None) -> dict:
spark = _is_spark(os_family, arch, gpu, cpu)
leads = spark or looks_new
kind = _machine_kind(os_family, spark)
- plugin_tasks = [_NVIDIA_TASK, _BLENDER_TASK] if os_family == "win32" and gpu == "nvidia" else [_BLENDER_TASK]
+ plugin_tasks = [_NVIDIA_TASK] if os_family == "win32" and gpu == "nvidia" else []
+ if _blender_present(blender(deadline)[0], profile):
+ plugin_tasks.append(_BLENDER_TASK)
return {
"schema_version": SCHEMA_VERSION,
@@ -685,7 +738,7 @@ def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--from-json", type=Path, help="interpret this saved scan instead of scanning")
args = parser.parse_args()
- scanned = (_read_json(args.from_json), "file") if args.from_json else None
+ scanned = (lambda _deadline: (_read_json(args.from_json), "file")) if args.from_json else None
print(json.dumps(collect(scanned), ensure_ascii=False, separators=(",", ":")))
diff --git a/tests/hermes_platform/test_declaration.py b/tests/hermes_platform/test_declaration.py
index 54c823d0c77..200f95d2d04 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"
@@ -129,7 +129,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..2fe083fa93f 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)
@@ -60,7 +60,7 @@ def test_bundle_presence_and_plist_version(tmp_path):
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 20c465be6e3..735a4fdc463 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` |
+
+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) |
`requires.app: true` with no `app:` block is a `DeclarationError`.
@@ -86,7 +119,7 @@ Availability(
- `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`.
+- `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.