Files
hermes-agent/hermes_cli/main_container.py
Jeffrey Quesnelle 02afb7489e fix(profiles): a marked profile's container-mode file is not used on the host (#160087)
* fix(profiles): a marked profile's container-mode file is not used on the host

A home may hold a .container-mode file that tells the CLI to hand every
command to a container runtime before it is parsed. Its backend= line
names that runtime, and a path works as well as a name. The backend a
plugin runs elsewhere writes the profile home, so with such a file in a
marked home every host command (hermes -p ops status, config, doctor)
started the program the file named, once to ask for the container and
once more with the command.

The entry point now asks hermes_cli.main_container.container_exec_info(),
which answers None for a home whose profile a plugin runs elsewhere. The
command then stays a host command and runs as it does for a home without
the file, so the commands a person needs for a marked profile (status,
config, a plugin's own command) keep working whatever the backend wrote.
A profile that runs here is handed to its container as before.

* fix(profiles): a marked profile's container-mode file is not opened

The entry point read <home>/.container-mode before it asked whether a
plugin runs the profile elsewhere. A backend that leaves bytes that are
not UTF-8 under that name, or a folder, made the read raise, and every
host command for the profile ended there (hermes -p ops config path
among them).

container_exec_info() now asks first, and only when something exists
under that name, so a home without the file is still not asked about.
For a marked profile the file is not opened. A profile that runs here
reads its file as before.

* fix(profiles): fast start-up paths ask before reading container-mode

The fast chat and serve start-up paths run before main()'s own container
check and called get_container_exec_info() themselves, so a marked
profile's .container-mode file was still opened at every start. A FIFO
under that name held every host command for the profile: hermes -p ops
status, config and doctor did not return.

Both paths now ask container_exec_info(). A home that runs here gets the
answer it got before, so container routing is unchanged. For a marked
home the fast path goes on, and the command is refused where it was
refused before: chat by the agent's start-up, serve with exit 78.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* test(profiles): the stand-in program helper drops an unused argument

_program()'s says argument had no caller, so the branch it added never
ran.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* fix(profiles): a container-mode file written during a start is not used

container_exec_info() looks for the file before it asks whether the
profile runs elsewhere, so that a home without the file is not asked
about at every start. The backend of a marked profile writes that folder
at any moment. A file that was not there at the look and was there at
the read came back as container routing, and the host started the
program its backend= line names.

What was read is now asked about once more, and for a marked profile it
is not used. A home that runs here pays for the second question only
when it has such a file.

---------

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-26 00:01:22 -05:00

122 lines
5.0 KiB
Python

"""NixOS container mode: route a ``hermes`` invocation into the managed container (``main()``)."""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
def _probe_container(cmd: list, backend: str, via_sudo: bool = False):
"""Run a container inspect probe, returning the CompletedProcess.
Catches TimeoutExpired specifically for a human-readable message;
all other exceptions propagate naturally.
"""
try:
return subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, check=False)
except subprocess.TimeoutExpired:
label = f"sudo {backend}" if via_sudo else backend
print(
f"Error: timed out waiting for {label} to respond.\n"
f"The {backend} daemon may be unresponsive or starting up.",
file=sys.stderr,
)
sys.exit(1)
def container_exec_info() -> dict | None:
"""``hermes_cli.config.get_container_exec_info()`` for the entry point, or None for a profile a plugin
runs elsewhere: that backend writes the file, and its ``backend=`` line names the program to start. The
file is not opened for such a profile, whatever the backend left under its name, and the command stays
a host command. A home with nothing under that name is not asked about; what its backend writes there
after that look is read and not used."""
from hermes_cli.config import get_container_exec_info
from hermes_cli.profiles_run_elsewhere import run_elsewhere_refusal
from hermes_constants import get_hermes_home
if os.path.lexists(get_hermes_home() / ".container-mode") and run_elsewhere_refusal() is not None:
return None
info = get_container_exec_info()
# The backend can write the file between the look above and this read, so the question is asked again.
return None if info and run_elsewhere_refusal() is not None else info
def exec_in_container(container_info: dict, cli_args: list):
"""Replace the current process with a command inside the managed container.
Probes whether sudo is needed (rootful containers), then os.execvp
into the container. On success the Python process is replaced entirely
and the container's exit code becomes the process exit code (OS semantics).
On failure, OSError propagates naturally.
Args:
container_info: dict with backend, container_name, exec_user, hermes_bin
cli_args: the original CLI arguments (everything after 'hermes')
"""
backend = container_info["backend"]
container_name = container_info["container_name"]
exec_user = container_info["exec_user"]
hermes_bin = container_info["hermes_bin"]
runtime = shutil.which(backend)
if not runtime:
print(
f"Error: {backend} not found on PATH. Cannot route to container.",
file=sys.stderr,
)
sys.exit(1)
# Rootful containers (NixOS systemd service) are invisible to unprivileged
# users — Podman uses per-user namespaces, Docker needs group access.
# Probe whether the runtime can see the container; if not, try via sudo.
inspect_cmd = [runtime, "inspect", "--format", "ok", container_name]
cmd_prefix = [runtime]
if _probe_container(inspect_cmd, backend).returncode != 0:
sudo_path = shutil.which("sudo")
if not sudo_path:
print(
f"Error: container '{container_name}' not found via {backend}.\n"
f"The container may be running under root. Try: sudo hermes {' '.join(cli_args)}",
file=sys.stderr,
)
sys.exit(1)
cmd_prefix = [sudo_path, "-n", runtime]
if _probe_container(cmd_prefix[:2] + inspect_cmd, backend, via_sudo=True).returncode != 0:
print(
f"Error: container '{container_name}' not found via {backend}.\n"
f"\n"
f"The container is likely running as root. Your user cannot see it\n"
f"because {backend} uses per-user namespaces. Grant passwordless\n"
f"sudo for {backend} — the -n (non-interactive) flag is required\n"
f"because a password prompt would hang or break piped commands.\n"
f"\n"
f"On NixOS:\n"
f"\n"
f" security.sudo.extraRules = [{{\n"
f' users = [ "{os.getenv("USER", "your-user")}" ];\n'
f' commands = [{{ command = "{runtime}"; options = [ "NOPASSWD" ]; }}];\n'
f" }}];\n"
f"\n"
f"Or run: sudo hermes {' '.join(cli_args)}",
file=sys.stderr,
)
sys.exit(1)
env_flags = []
for var in ("TERM", "COLORTERM", "LANG", "LC_ALL"):
val = os.environ.get(var)
if val:
env_flags.extend(["-e", f"{var}={val}"])
exec_cmd = (
cmd_prefix
+ ["exec", "-it" if sys.stdin.isatty() else "-i", "-u", exec_user]
+ env_flags
+ [container_name, hermes_bin]
+ cli_args
)
os.execvp(exec_cmd[0], exec_cmd)