Skip to content

The agent that grows with you

feat(platform): hermes_platform.host with machine facts, runtime predicates, SoC recognizer

alt-glitch48ed4e53646e
diff --git a/hermes_constants.py b/hermes_constants.py
index 6aaacef5eaf..7eb4c52dfa9 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -13,6 +13,8 @@ from collections.abc import MutableMapping
from contextvars import ContextVar, Token
from pathlib import Path
+from hermes_platform.host.runtime import _detect_container, is_container, is_termux, is_wsl # noqa: F401
+
_profile_fallback_warned: bool = False
_UNSET = object()
_HERMES_HOME_OVERRIDE: ContextVar[str | object] = ContextVar("_HERMES_HOME_OVERRIDE", default=_UNSET)
@@ -1387,27 +1389,6 @@ def resolve_reasoning_config(cfg: dict | None, model: str = "") -> dict | None:
return result
-def is_termux() -> bool:
- """True inside Termux (Android): ``TERMUX_VERSION`` or the Termux-specific ``PREFIX`` path."""
- prefix = os.getenv("PREFIX", "")
- return bool(os.getenv("TERMUX_VERSION") or "com.termux/files/usr" in prefix)
-
-
-_wsl_detected: bool | None = None
-
-
-def is_wsl() -> bool:
- """True inside WSL1/WSL2 (``microsoft`` marker in ``/proc/version``); cached per process."""
- global _wsl_detected
- if _wsl_detected is None:
- try:
- with open("/proc/version", "r", encoding="utf-8") as f:
- _wsl_detected = "microsoft" in f.read().lower()
- except Exception:
- _wsl_detected = False
- return _wsl_detected
-
-
def windows_path_to_wsl(path: str) -> str | None:
"""Convert a Windows drive path (``C:\\...``) to its ``/mnt/<drive>/...`` form."""
match = re.match(r"^([A-Za-z]):[\\/](.*)$", str(path or "").strip())
@@ -1435,54 +1416,6 @@ def translate_cwd_for_wsl_backend(cwd: str) -> str:
return cwd
-_container_detected: bool | None = None
-
-
-def is_container() -> bool:
- """True inside a container (Docker/Podman/LXC/Kubernetes markers); cached per process.
-
- See: NousResearch/hermes-agent#47111
- """
- global _container_detected
- if _container_detected is None:
- _container_detected = _detect_container()
- return _container_detected
-
-
-def _read_proc(path: str) -> str:
- try:
- with open(path, "r", encoding="utf-8") as f:
- return f.read()
- except OSError:
- return ""
-
-
-def _proc_file_has_marker(path: str, markers: tuple[str, ...]) -> bool:
- content = _read_proc(path)
- return any(marker in content for marker in markers)
-
-
-def _detect_container() -> bool:
- if (
- os.path.exists("/.dockerenv")
- or os.path.exists("/run/.containerenv")
- or os.environ.get("KUBERNETES_SERVICE_HOST")
- or _proc_file_has_marker("/proc/1/cgroup", ("docker", "podman", "/lxc/", "kubepods", "containerd", "crio"))
- ):
- return True
- # cgroup v2: /proc/1/cgroup is just "0::/"; the runtime still shows in mountinfo — but ONLY on
- # the root ("/") mount line. A host that merely *runs* containers exposes every container's
- # overlay lowerdir (``lowerdir=/var/lib/containerd/...``) at non-root mount points, which a
- # whole-file scan misread as "inside a container" and flipped subprocess HOME (#58135).
- return _root_mount_has_marker("/proc/self/mountinfo", ("kubepods", "containerd", "crio"))
-
-
-def _root_mount_has_marker(path: str, markers: tuple[str, ...]) -> bool:
- """mountinfo field 5 (index 4) is the mount point; only the root ("/") line is the process's own rootfs."""
- root_lines = [line for line in _read_proc(path).splitlines() if len(f := line.split()) >= 5 and f[4] == "/"]
- return any(marker in line for line in root_lines for marker in markers)
-
-
def get_config_path() -> Path:
"""Return the path to ``config.yaml`` under HERMES_HOME."""
return get_hermes_home() / "config.yaml"
diff --git a/hermes_platform/__init__.py b/hermes_platform/__init__.py
new file mode 100644
index 00000000000..8f018e6a090
--- /dev/null
+++ b/hermes_platform/__init__.py
@@ -0,0 +1,4 @@
+"""Machine facts and resource resolution for every Hermes surface.
+
+Host facts describe the machine running this interpreter; resolution has no side effects.
+"""
diff --git a/hermes_platform/catalog/__init__.py b/hermes_platform/catalog/__init__.py
new file mode 100644
index 00000000000..0e82da6a07c
--- /dev/null
+++ b/hermes_platform/catalog/__init__.py
@@ -0,0 +1 @@
+"""Declarative application catalog and loader."""
diff --git a/hermes_platform/host/__init__.py b/hermes_platform/host/__init__.py
new file mode 100644
index 00000000000..af8e0ed1e39
--- /dev/null
+++ b/hermes_platform/host/__init__.py
@@ -0,0 +1,4 @@
+"""Cached facts about the machine running this Python process.
+
+Facts use hardware sources without environment-variable input or subprocesses.
+"""
diff --git a/hermes_platform/host/facts.py b/hermes_platform/host/facts.py
new file mode 100644
index 00000000000..83dec275317
--- /dev/null
+++ b/hermes_platform/host/facts.py
@@ -0,0 +1,176 @@
+"""Cached OS, architecture, and CPU facts for the current machine.
+
+Native architecture remains accurate when the Python process is emulated.
+"""
+
+from __future__ import annotations
+
+import functools
+import os
+import platform
+import sys
+
+_ARCH_NAMES = {
+ "amd64": "amd64", "x86_64": "amd64", "x64": "amd64",
+ "arm64": "arm64", "aarch64": "arm64",
+ "x86": "x86", "i386": "x86", "i686": "x86",
+}
+IMAGE_FILE_MACHINE = {0x8664: "amd64", 0xAA64: "arm64", 0x014C: "x86"}
+
+
+def normalize_arch(raw: str | None) -> str:
+ """Return a canonical architecture name."""
+ return _ARCH_NAMES.get((raw or "").strip().lower(), "unknown")
+
+
+def os_family() -> str:
+ """Return the current platform identifier."""
+ return sys.platform
+
+
+def process_arch() -> str:
+ """Return the architecture of this Python process."""
+ return normalize_arch(platform.machine())
+
+
+def windows_native_arch(*, wow64_native: int | None, machine: str, env_arch: str | None) -> str:
+ """Return the native architecture from Windows observations.
+
+ Order matters: ``PROCESSOR_ARCHITECTURE`` reads ``AMD64`` inside an x64-emulated process
+ on ARM64 hardware, so the environment is consulted only when both APIs are unavailable.
+ """
+ name = IMAGE_FILE_MACHINE.get(wow64_native or 0)
+ if name:
+ return name
+ normalized = normalize_arch(machine)
+ if normalized != "unknown":
+ return normalized
+ return normalize_arch(env_arch)
+
+
+def _wow64_native_machine() -> int | None:
+ """Return the IsWow64Process2 native machine, or ``None`` when unavailable."""
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ probe = getattr(kernel32, "IsWow64Process2", None)
+ if probe is None:
+ return None
+ # ctypes otherwise truncates the HANDLE pseudo-handle to c_int.
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ kernel32.GetCurrentProcess.argtypes = []
+ probe.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.USHORT), ctypes.POINTER(wintypes.USHORT)]
+ probe.restype = wintypes.BOOL
+ process_machine = wintypes.USHORT(0)
+ native_machine = wintypes.USHORT(0)
+ if not probe(kernel32.GetCurrentProcess(), ctypes.byref(process_machine), ctypes.byref(native_machine)):
+ return None
+ return native_machine.value or None
+
+
+def _darwin_translated() -> bool:
+ """Return whether this process runs under Rosetta."""
+ return _sysctl_int(b"sysctl.proc_translated") == 1
+
+
+def native_arch() -> str:
+ """Return the machine architecture even when this process is emulated."""
+ if sys.platform == "win32":
+ try:
+ wow64 = _wow64_native_machine()
+ except (OSError, AttributeError, TypeError, ValueError):
+ wow64 = None
+ env_arch = os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get("PROCESSOR_ARCHITECTURE")
+ return windows_native_arch(wow64_native=wow64, machine=platform.machine(), env_arch=env_arch)
+ if sys.platform == "darwin" and process_arch() == "amd64" and _darwin_translated():
+ return "arm64"
+ return process_arch()
+
+
+_CPU_KEY = r"HARDWARE\DESCRIPTION\System\CentralProcessor\0"
+
+
+def parse_cpuinfo(text: str, *, device_tree_model: str = "") -> str:
+ """Return the first available CPU or device-tree model."""
+ for key in ("model name", "Hardware"):
+ for line in text.splitlines():
+ if line.lower().startswith(key.lower()) and ":" in line:
+ return line.split(":", 1)[1].strip()
+ return device_tree_model.replace("\0", "").replace("_", " ").strip()
+
+
+def _read_text(path: str, limit: int = 65536) -> str:
+ try:
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
+ return handle.read(limit)
+ except OSError:
+ return ""
+
+
+def _winreg_str(subkey: str, name: str) -> str:
+ import winreg
+
+ try:
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey) as key:
+ value = winreg.QueryValueEx(key, name)[0]
+ except OSError:
+ return ""
+ return str(value).strip()
+
+
+def _sysctl_int(name: bytes) -> int | None:
+ import ctypes
+ import ctypes.util
+
+ libc = ctypes.CDLL(ctypes.util.find_library("c"))
+ value = ctypes.c_int(0)
+ size = ctypes.c_size_t(ctypes.sizeof(ctypes.c_int))
+ if libc.sysctlbyname(name, ctypes.byref(value), ctypes.byref(size), None, 0) != 0:
+ return None
+ return value.value
+
+
+def _sysctl_str(name: bytes) -> str:
+ import ctypes
+ import ctypes.util
+
+ libc = ctypes.CDLL(ctypes.util.find_library("c"))
+ size = ctypes.c_size_t(0)
+ if libc.sysctlbyname(name, None, ctypes.byref(size), None, 0) != 0:
+ return ""
+ buffer = ctypes.create_string_buffer(size.value)
+ if libc.sysctlbyname(name, buffer, ctypes.byref(size), None, 0) != 0:
+ return ""
+ return buffer.value.decode(errors="replace").strip()
+
+
+def cpu_model() -> str:
+ """Return the CPU model, or an empty string when unavailable."""
+ if sys.platform == "win32":
+ return _winreg_str(_CPU_KEY, "ProcessorNameString")
+ if sys.platform == "darwin":
+ return _sysctl_str(b"machdep.cpu.brand_string")
+ return parse_cpuinfo(_read_text("/proc/cpuinfo"), device_tree_model=_read_text("/proc/device-tree/model", 512))
+
+
+def cpu_vendor() -> str:
+ """Return the CPU vendor, or an empty string when unavailable."""
+ if sys.platform == "win32":
+ return _winreg_str(_CPU_KEY, "VendorIdentifier")
+ if sys.platform.startswith("linux"):
+ for line in _read_text("/proc/cpuinfo").splitlines():
+ if line.lower().startswith("vendor_id") and ":" in line:
+ return line.split(":", 1)[1].strip()
+ return ""
+
+
+def clear_caches() -> None:
+ """Clear every cached host fact."""
+ for fact in (os_family, process_arch, native_arch, cpu_model, cpu_vendor):
+ fact.cache_clear()
diff --git a/hermes_platform/host/products.py b/hermes_platform/host/products.py
new file mode 100644
index 00000000000..273930ac68c
--- /dev/null
+++ b/hermes_platform/host/products.py
@@ -0,0 +1,27 @@
+"""Vendor SoC recognizers derived from host facts.
+
+Recognition uses OS-reported CPU identity without environment-variable input.
+"""
+
+from __future__ import annotations
+
+from hermes_platform.host import facts
+
+# Match the CPU string because the chassis vendor does not identify the SoC.
+_NVIDIA_SOC_VENDOR = "NVIDIA"
+_NVIDIA_SOC_MODEL_MARKERS = ("N1X", "SPARK")
+
+
+def looks_like_nvidia_arm_soc(*, native_arch: str, cpu_model: str, cpu_vendor: str) -> bool:
+ """Return whether the supplied facts identify an NVIDIA ARM SoC."""
+ if native_arch != "arm64":
+ return False
+ model = cpu_model.upper()
+ vendor_match = _NVIDIA_SOC_VENDOR in model or cpu_vendor.strip().upper() == _NVIDIA_SOC_VENDOR
+ return vendor_match and any(marker in model for marker in _NVIDIA_SOC_MODEL_MARKERS)
+
+
+def is_nvidia_arm_soc() -> bool:
+ """Return whether this host has an NVIDIA ARM SoC."""
+ return looks_like_nvidia_arm_soc(
+ native_arch=facts.native_arch(), cpu_model=facts.cpu_model(), cpu_vendor=facts.cpu_vendor())
diff --git a/hermes_platform/host/runtime.py b/hermes_platform/host/runtime.py
new file mode 100644
index 00000000000..bcc7edbdd35
--- /dev/null
+++ b/hermes_platform/host/runtime.py
@@ -0,0 +1,69 @@
+"""Cached runtime-environment predicates for WSL, containers, and Termux."""
+
+from __future__ import annotations
+
+import os
+
+
+def is_termux() -> bool:
+ """Return whether this process runs inside Termux."""
+ prefix = os.getenv("PREFIX", "")
+ return bool(os.getenv("TERMUX_VERSION") or "com.termux/files/usr" in prefix)
+
+
+_wsl_detected: bool | None = None
+
+
+def is_wsl() -> bool:
+ """Return whether this process runs inside WSL."""
+ global _wsl_detected
+ if _wsl_detected is None:
+ try:
+ with open("/proc/version", "r", encoding="utf-8") as f:
+ _wsl_detected = "microsoft" in f.read().lower()
+ except Exception:
+ _wsl_detected = False
+ return _wsl_detected
+
+
+_container_detected: bool | None = None
+
+
+def is_container() -> bool:
+ """Return whether this process runs inside a container."""
+ global _container_detected
+ if _container_detected is None:
+ _container_detected = _detect_container()
+ return _container_detected
+
+
+def _read_proc(path: str) -> str:
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ return f.read()
+ except OSError:
+ return ""
+
+
+def _proc_file_has_marker(path: str, markers: tuple[str, ...]) -> bool:
+ content = _read_proc(path)
+ return any(marker in content for marker in markers)
+
+
+def _detect_container() -> bool:
+ if (
+ os.path.exists("/.dockerenv")
+ or os.path.exists("/run/.containerenv")
+ or os.environ.get("KUBERNETES_SERVICE_HOST")
+ or _proc_file_has_marker("/proc/1/cgroup", ("docker", "podman", "/lxc/", "kubepods", "containerd", "crio"))
+ ):
+ return True
+ # Under cgroup v2, only the root mount identifies this process's container.
+ # Scanning all mountinfo lines misclassifies hosts that run containers (#58135).
+ return _root_mount_has_marker("/proc/self/mountinfo", ("kubepods", "containerd", "crio"))
+
+
+def _root_mount_has_marker(path: str, markers: tuple[str, ...]) -> bool:
+ """Return whether the root mount contains any marker."""
+ root_lines = [line for line in _read_proc(path).splitlines() if len(f := line.split()) >= 5 and f[4] == "/"]
+ return any(marker in line for line in root_lines for marker in markers)
diff --git a/hermes_platform/resolver/__init__.py b/hermes_platform/resolver/__init__.py
new file mode 100644
index 00000000000..e3c34bf9d24
--- /dev/null
+++ b/hermes_platform/resolver/__init__.py
@@ -0,0 +1 @@
+"""Resource owners and resolution helpers."""
diff --git a/pyproject.toml b/pyproject.toml
index e38e5a8349e..feb61e94802 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -606,9 +606,11 @@ youtube-transcript-api = false
# and the drift broke installed wheels. Do not add the list back.
[tool.setuptools.packages.find]
-include = ["agent", "agent.*", "tools", "tools.*", "hermes_cli", "hermes_cli.*", "gateway", "gateway.*", "tui_gateway", "tui_gateway.*", "cron", "cron.*", "acp_adapter", "plugins", "plugins.*", "providers", "providers.*"]
+include = ["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 —