Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,68 @@ def managed_error(action: str = "modify configuration"):
print(format_managed_message(action), file=sys.stderr)


# =============================================================================
# Container-aware CLI (NixOS container mode)
# =============================================================================

def _is_inside_container() -> bool:
"""Detect if we're already running inside a Docker/Podman container."""
# Standard Docker/Podman indicators
if os.path.exists("/.dockerenv"):
return True
# Podman uses /run/.containerenv
if os.path.exists("/run/.containerenv"):
return True
# Check cgroup for container runtime evidence (works for both Docker & Podman)
try:
with open("/proc/1/cgroup", "r") as f:
cgroup = f.read()
if "docker" in cgroup or "podman" in cgroup or "/lxc/" in cgroup:
return True
except (OSError, IOError):
pass
return False


def get_container_exec_info() -> Optional[dict]:
"""Read container mode metadata from HERMES_HOME/.container-mode.

Returns a dict with keys: backend, container_name, hermes_bin
or None if container mode is not active or we're already inside the container.

The .container-mode file is written by the NixOS activation script when
container.enable = true. It tells the host CLI to exec into the container
instead of running locally.
"""
if _is_inside_container():
return None

container_mode_file = get_hermes_home() / ".container-mode"
if not container_mode_file.exists():
return None

try:
info = {}
with open(container_mode_file, "r") as f:
for line in f:
line = line.strip()
if "=" in line and not line.startswith("#"):
key, _, value = line.partition("=")
info[key.strip()] = value.strip()

backend = info.get("backend", "docker")
container_name = info.get("container_name", "hermes-agent")
hermes_bin = info.get("hermes_bin", "/data/current-package/bin/hermes")

return {
"backend": backend,
"container_name": container_name,
"hermes_bin": hermes_bin,
}
except (OSError, IOError):
return None


# =============================================================================
# Config paths
# =============================================================================
Expand Down
71 changes: 71 additions & 0 deletions hermes_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,56 @@ def _resolve_last_cli_session() -> Optional[str]:
return None


def _exec_in_container(container_info: dict, cli_args: list):
"""Replace the current process with a command inside the managed container.
Uses os.execvp to hand off to docker/podman exec, preserving the TTY
so the interactive CLI works seamlessly inside the container.
Args:
container_info: dict with backend, container_name, hermes_bin
cli_args: the original CLI arguments (everything after 'hermes')
"""
import shutil
import subprocess

backend = container_info["backend"]
container_name = container_info["container_name"]
hermes_bin = container_info["hermes_bin"]

# Find the container runtime on PATH
runtime = shutil.which(backend)
if not runtime:
print(f"Warning: {backend} not found on PATH, falling back to host CLI.",
file=sys.stderr)
return # Fall through to normal CLI

# Check if the container is actually running
try:
result = subprocess.run(
[runtime, "inspect", "--format", "{{.State.Running}}", container_name],
capture_output=True, text=True, timeout=5
)
if result.returncode != 0 or result.stdout.strip().lower() != "true":
print(f"Warning: container '{container_name}' is not running, falling back to host CLI.",
file=sys.stderr)
return
except (subprocess.TimeoutExpired, OSError):
return # Fall through on any error

# Filter out --host flag from forwarded args (it's not meaningful inside)
forwarded_args = [a for a in cli_args if a != "--host"]

# Build the exec command
exec_cmd = [runtime, "exec", "-it", container_name, hermes_bin] + forwarded_args

print(f"Routing to container '{container_name}' via {backend}...",
file=sys.stderr)

# Replace the current process — this never returns on success
os.execvp(runtime, exec_cmd)


def _resolve_session_by_name_or_id(name_or_id: str) -> Optional[str]:
"""Resolve a session name (title) or ID to a session ID.
Expand Down Expand Up @@ -556,6 +606,21 @@ def _resolve_session_by_name_or_id(name_or_id: str) -> Optional[str]:

def cmd_chat(args):
"""Run interactive chat CLI."""
# ── Container-aware routing ──────────────────────────────────────────
# When NixOS container mode is active and we're on the host, exec into
# the managed container instead of running locally. --host bypasses this.
if not getattr(args, "host", False):
try:
from hermes_cli.config import get_container_exec_info
container_info = get_container_exec_info()
if container_info:
_exec_in_container(container_info, sys.argv[1:])
# _exec_in_container calls os.execvp which replaces the process.
# If we get here, the exec failed.
sys.exit(1)
except Exception:
pass # Fall through to normal CLI on any detection error

# Resolve --continue into --resume with the latest CLI session or by name
continue_val = getattr(args, "continue_last", None)
if continue_val and not getattr(args, "resume", None):
Expand Down Expand Up @@ -4386,6 +4451,12 @@ def main():
default=None,
help="Session source tag for filtering (default: cli). Use 'tool' for third-party integrations that should not appear in user session lists."
)
chat_parser.add_argument(
"--host",
action="store_true",
default=False,
help="Run on the host even when NixOS container mode is active (bypass container exec)"
)
chat_parser.set_defaults(func=cmd_chat)

# =========================================================================
Expand Down
16 changes: 16 additions & 0 deletions nix/nixosModules.nix
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,22 @@
chown ${cfg.user}:${cfg.group} ${cfg.stateDir}/.hermes/.managed
chmod 0644 ${cfg.stateDir}/.hermes/.managed

# Container mode metadata — tells the host CLI to exec into the
# container instead of running locally. Removed when container mode
# is disabled so the host CLI falls back to native execution.
${if cfg.container.enable then ''
cat > ${cfg.stateDir}/.hermes/.container-mode <<'HERMES_CONTAINER_MODE_EOF'
# Written by NixOS activation script. Do not edit manually.
backend=${cfg.container.backend}
container_name=${containerName}
hermes_bin=${containerDataDir}/current-package/bin/hermes
HERMES_CONTAINER_MODE_EOF
chown ${cfg.user}:${cfg.group} ${cfg.stateDir}/.hermes/.container-mode
chmod 0644 ${cfg.stateDir}/.hermes/.container-mode
'' else ''
rm -f ${cfg.stateDir}/.hermes/.container-mode
''}

# Seed auth file if provided
${lib.optionalString (cfg.authFile != null) ''
${if cfg.authFileForceOverwrite then ''
Expand Down
Loading
Loading