From e9dd5685da66549ab849c8dea1c4c8c2b56a9021 Mon Sep 17 00:00:00 2001 From: alt-glitch Date: Wed, 25 Mar 2026 07:01:05 +0530 Subject: [PATCH] feat(nix): persistent /home/hermes and MESSAGING_CWD in container mode Container mode now bind-mounts ${stateDir}/home to /home/hermes so the agent's home directory survives container recreation. Previously it lived in the writable layer and was lost on image/volume/options changes. Also passes MESSAGING_CWD to the container so the agent finds its workspace and documents, matching native mode behavior. Other changes: - Extract containerDataDir/containerHomeDir bindings (no more magic strings) - Fix entrypoint chown to run unconditionally (volume mounts always exist) - Add schema field to container identity hash for auto-recreation - Add idempotency test (Scenario G) to config-roundtrip check --- docs/nixos-setup.md | 211 ++++++++++++++++++++++++++--- nix/checks.nix | 277 +++++++++++++++++++++++++++++++++++++- nix/config-keys.json | 127 +++++++++++++++++ nix/configMergeScript.nix | 33 +++++ nix/nixosModules.nix | 132 +++++++++++++++--- 5 files changed, 746 insertions(+), 34 deletions(-) create mode 100644 nix/config-keys.json create mode 100644 nix/configMergeScript.nix diff --git a/docs/nixos-setup.md b/docs/nixos-setup.md index 596ceea78c69..a72dc8dfbc6f 100644 --- a/docs/nixos-setup.md +++ b/docs/nixos-setup.md @@ -171,6 +171,10 @@ directory setup, config generation, secrets, documents, and service lifecycle. command = "npx"; args = [ "-y" "@modelcontextprotocol/server-filesystem" "/data/workspace" ]; }; + mcpServers.remote-tools = { + url = "https://mcp.example.com/mcp"; + auth = "oauth"; + }; # ── Container options ────────────────────────────────────────────── container = { @@ -281,14 +285,16 @@ Host Container │ ├── config.yaml (Nix-generated, copied by activation) │ ├── .managed (marker file) │ ├── state.db + │ ├── mcp-tokens/ (OAuth tokens for MCP servers) │ ├── sessions/ │ ├── memories/ │ └── ... + ├── home/ ──► /home/hermes (rw) └── workspace/ (MESSAGING_CWD) ├── SOUL.md (from documents option) └── (agent-created files) -Container writable layer (apt/pip/npm): /usr, /home/hermes, /tmp +Container writable layer (apt/pip/npm): /usr, /tmp ``` The container entrypoint is `/data/current-package/bin/hermes gateway run --replace`, @@ -296,18 +302,18 @@ which resolves through the symlink to the current Nix store path. ### What Persists Across What -| Event | Container recreated? | `/data` (state) | Writable layer (`apt`/`pip`/`npm`) | -|---|---|---|---| -| `systemctl restart hermes-agent` | No | Persists | Persists | -| `nixos-rebuild switch` (code change) | No (symlink updated) | Persists | Persists | -| Host reboot | No | Persists | Persists | -| `nix-collect-garbage` | No (GC root) | Persists | Persists | -| Image change (`container.image`) | **Yes** | Persists | **Lost** | -| Volume/options change | **Yes** | Persists | **Lost** | -| `environment`/`environmentFiles` change | No | Persists | Persists | +| Event | Container recreated? | `/data` (state) | `/home/hermes` | Writable layer (`apt`/`pip`/`npm`) | +|---|---|---|---|---| +| `systemctl restart hermes-agent` | No | Persists | Persists | Persists | +| `nixos-rebuild switch` (code change) | No (symlink updated) | Persists | Persists | Persists | +| Host reboot | No | Persists | Persists | Persists | +| `nix-collect-garbage` | No (GC root) | Persists | Persists | Persists | +| Image change (`container.image`) | **Yes** | Persists | Persists | **Lost** | +| Volume/options change | **Yes** | Persists | Persists | **Lost** | +| `environment`/`environmentFiles` change | No | Persists | Persists | Persists | The container is only recreated when its **identity hash** changes. The hash -covers: `image`, `extraVolumes`, `extraOptions`. Changes to `environment`, +covers: `schema` version, `image`, `extraVolumes`, `extraOptions`. Changes to `environment`, `environmentFiles`, `settings`, `documents`, or the hermes package itself do **not** trigger recreation — environment variables are written to `$HERMES_HOME/.env` by the activation script and read by hermes at startup. @@ -350,6 +356,172 @@ If you need to change configuration, edit your `configuration.nix` and run --- +## MCP Servers + +The `mcpServers` option lets you declaratively configure +[MCP (Model Context Protocol)](https://modelcontextprotocol.io) servers. +Each server uses either **stdio** (local command) or **HTTP** (remote URL) +transport. + +### Stdio Transport (Local Servers) + +For MCP servers that run as local subprocesses: + +```nix +{ + services.hermes-agent.mcpServers = { + filesystem = { + command = "npx"; + args = [ "-y" "@modelcontextprotocol/server-filesystem" "/data/workspace" ]; + }; + + github = { + command = "npx"; + args = [ "-y" "@modelcontextprotocol/server-github" ]; + env.GITHUB_PERSONAL_ACCESS_TOKEN = "\${GITHUB_TOKEN}"; # resolved from .env + }; + }; +} +``` + +Environment variables in `env` values are resolved from `$HERMES_HOME/.env` +at runtime. Use `environmentFiles` (with sops-nix or agenix) to inject +secrets — never put tokens directly in Nix config. + +### HTTP Transport (Remote Servers) + +For remote MCP servers accessible via HTTP/StreamableHTTP: + +```nix +{ + services.hermes-agent.mcpServers = { + remote-api = { + url = "https://mcp.example.com/v1/mcp"; + headers.Authorization = "Bearer \${MCP_REMOTE_API_KEY}"; + timeout = 180; + }; + }; +} +``` + +### HTTP Transport with OAuth + +For remote MCP servers that use OAuth 2.1 for authentication, set +`auth = "oauth"`. Hermes implements the full OAuth 2.1 PKCE flow via the +MCP SDK — including metadata discovery, dynamic client registration, token +exchange, and automatic refresh. + +```nix +{ + services.hermes-agent.mcpServers = { + my-oauth-server = { + url = "https://mcp.example.com/mcp"; + auth = "oauth"; + }; + }; +} +``` + +Tokens are stored in `$HERMES_HOME/mcp-tokens/.json` and +persist across restarts and rebuilds. Token refresh is automatic. + +#### Initial Authorization (Headless / Container) + +The first OAuth authorization requires completing a browser-based consent +flow. In a headless NixOS deployment (native or container), Hermes detects +the absence of a display and prints the authorization URL to stdout/logs +instead of opening a browser. + +**Option A: Interactive bootstrap** — run the OAuth flow once via `docker exec` +(container mode) or `sudo -u hermes` (native mode): + +```bash +# Container mode +docker exec -it hermes-agent \ + hermes mcp add my-oauth-server --url https://mcp.example.com/mcp --auth oauth + +# Native mode +sudo -u hermes HERMES_HOME=/var/lib/hermes/.hermes \ + hermes mcp add my-oauth-server --url https://mcp.example.com/mcp --auth oauth +``` + +Since the container uses `--network=host`, the OAuth callback listener on +`127.0.0.1` is reachable from the host. Open the printed URL in your +browser, complete consent, and the callback is received by Hermes inside +the container. Tokens are saved and reused automatically from then on. + +**Option B: Pre-seed tokens** — complete the OAuth flow on a workstation +first, then copy the token files to the server: + +```bash +# On your workstation +hermes mcp add my-oauth-server --url https://mcp.example.com/mcp --auth oauth + +# Copy tokens to the server +scp ~/.hermes/mcp-tokens/my-oauth-server.json \ + server:/var/lib/hermes/.hermes/mcp-tokens/ +scp ~/.hermes/mcp-tokens/my-oauth-server.client.json \ + server:/var/lib/hermes/.hermes/mcp-tokens/ +``` + +Ensure the files are owned by the hermes user (`chown hermes:hermes`) +and have mode `0600`. + +### Sampling (Server-Initiated LLM Requests) + +Some MCP servers can request LLM completions from the agent. Configure +this per-server with the `sampling` option: + +```nix +{ + services.hermes-agent.mcpServers.analysis = { + command = "npx"; + args = [ "-y" "analysis-server" ]; + sampling = { + enabled = true; + model = "google/gemini-3-flash"; + max_tokens_cap = 4096; + timeout = 30; + max_rpm = 10; + }; + }; +} +``` + +### Mixed Example + +```nix +{ + services.hermes-agent = { + environmentFiles = [ config.sops.secrets."hermes/env".path ]; + + mcpServers = { + # Local stdio server + filesystem = { + command = "npx"; + args = [ "-y" "@modelcontextprotocol/server-filesystem" "/data/workspace" ]; + }; + + # Remote server with API key auth + ink = { + url = "https://mcp.ml.ink/mcp"; + headers.Authorization = "Bearer \${INK_API_KEY}"; + }; + + # Remote server with OAuth + cloud-tools = { + url = "https://tools.example.com/mcp"; + auth = "oauth"; + timeout = 300; + connect_timeout = 30; + }; + }; + }; +} +``` + +--- + ## Options Reference ### Core @@ -392,10 +564,15 @@ If you need to change configuration, edit your `configuration.nix` and run | Option | Type | Default | Description | |---|---|---|---| | `mcpServers` | `attrsOf submodule` | `{}` | MCP server definitions, merged into `settings.mcp_servers` | -| `mcpServers..command` | `str` | — | Server command | -| `mcpServers..args` | `listOf str` | `[]` | Command arguments | -| `mcpServers..env` | `attrsOf str` | `{}` | Server environment | -| `mcpServers..timeout` | `null` or `int` | `null` | Timeout in seconds | +| `mcpServers..command` | `null` or `str` | `null` | Server command (stdio transport) | +| `mcpServers..args` | `listOf str` | `[]` | Command arguments (stdio transport) | +| `mcpServers..env` | `attrsOf str` | `{}` | Environment variables for the server process (stdio transport) | +| `mcpServers..url` | `null` or `str` | `null` | Server endpoint URL (HTTP/StreamableHTTP transport) | +| `mcpServers..headers` | `attrsOf str` | `{}` | HTTP headers, e.g. `Authorization` (HTTP transport) | +| `mcpServers..auth` | `null` or `"oauth"` | `null` | Authentication method. `"oauth"` enables OAuth 2.1 PKCE | +| `mcpServers..timeout` | `null` or `int` | `null` | Tool call timeout in seconds (default: 120) | +| `mcpServers..connect_timeout` | `null` or `int` | `null` | Initial connection timeout in seconds (default: 60) | +| `mcpServers..sampling` | `null` or `submodule` | `null` | Sampling configuration for server-initiated LLM requests | ### Service Behavior @@ -431,11 +608,13 @@ If you need to change configuration, edit your `configuration.nix` and run │ ├── auth.json # OAuth credentials (seeded, then self-managed) │ ├── gateway.pid │ ├── state.db +│ ├── mcp-tokens/ # OAuth tokens for MCP servers │ ├── sessions/ │ ├── memories/ │ ├── skills/ │ ├── cron/ │ └── logs/ +├── home/ # Agent HOME (container mode: /home/hermes) └── workspace/ # MESSAGING_CWD ├── SOUL.md # From documents option └── (agent-created files) @@ -449,7 +628,7 @@ Same layout, but mounted into the container as `/data`: |---|---|---|---| | `/nix/store` | `/nix/store` | `ro` | Hermes binary + all Nix deps | | `/data` | `/var/lib/hermes` | `rw` | All state, config, workspace | -| `/home/hermes` | (container layer) | `rw` | Persists — agent home, `pip install --user` | +| `/home/hermes` | `${stateDir}/home` | `rw` | Persistent — agent home, `pip install --user`, tool caches | | `/usr`, `/usr/local` | (container layer) | `rw` | Persists — `apt`/`pip`/`npm` installs | | `/tmp` | (container layer) | `rw` | Persists across restarts (lost on recreation) | diff --git a/nix/checks.nix b/nix/checks.nix index abb2f10bf2d2..d3afe3a058ff 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -3,6 +3,11 @@ perSystem = { pkgs, system, ... }: let hermes-agent = inputs.self.packages.${system}.default; + hermesVenv = pkgs.callPackage ./python.nix { + inherit (inputs) uv2nix pyproject-nix pyproject-build-systems; + }; + + configMergeScript = pkgs.callPackage ./configMergeScript.nix { }; in { checks = { # Verify binaries exist and are executable @@ -26,7 +31,6 @@ entry-points-sync = pkgs.runCommand "hermes-entry-points-sync" { } '' set -e echo "=== Checking entry points match pyproject.toml [project.scripts] ===" - # These must match [project.scripts] in pyproject.toml for bin in hermes hermes-agent hermes-acp; do test -x ${hermes-agent}/bin/$bin || (echo "FAIL: $bin binary missing from Nix package"; exit 1) echo "PASS: $bin present" @@ -92,6 +96,277 @@ mkdir -p $out echo "ok" > $out/result ''; + + # ── Config drift detection ──────────────────────────────────────── + # Extracts leaf key paths from Python's DEFAULT_CONFIG and compares + # against the committed reference in nix/config-keys.json. + config-drift = pkgs.runCommand "hermes-config-drift" { + nativeBuildInputs = [ pkgs.jq ]; + referenceKeys = ./config-keys.json; + } '' + set -e + export HOME=$(mktemp -d) + + echo "=== Extracting DEFAULT_CONFIG leaf keys from Python ===" + ${hermesVenv}/bin/python3 -c ' +import json, sys +from hermes_cli.config import DEFAULT_CONFIG + +def leaf_paths(d, prefix=""): + paths = [] + for k, v in sorted(d.items()): + path = f"{prefix}.{k}" if prefix else k + if isinstance(v, dict) and v: + paths.extend(leaf_paths(v, path)) + else: + paths.append(path) + return paths + +json.dump(sorted(leaf_paths(DEFAULT_CONFIG)), sys.stdout) +' > /tmp/actual-keys.json + + echo "=== Comparing against reference ===" + jq -r '.[]' $referenceKeys | sort > /tmp/reference.txt + jq -r '.[]' /tmp/actual-keys.json | sort > /tmp/actual.txt + + ADDED=$(comm -23 /tmp/actual.txt /tmp/reference.txt || true) + REMOVED=$(comm -13 /tmp/actual.txt /tmp/reference.txt || true) + FAILED=false + + if [ -n "$ADDED" ]; then + echo "FAIL: New keys in DEFAULT_CONFIG not in nix/config-keys.json:" + echo "$ADDED" | sed 's/^/ + /' + FAILED=true + fi + if [ -n "$REMOVED" ]; then + echo "FAIL: Keys in nix/config-keys.json missing from DEFAULT_CONFIG:" + echo "$REMOVED" | sed 's/^/ - /' + FAILED=true + fi + + if [ "$FAILED" = "true" ]; then + exit 1 + fi + + ACTUAL_COUNT=$(wc -l < /tmp/actual.txt) + echo "PASS: All $ACTUAL_COUNT config keys match reference" + mkdir -p $out + echo "ok" > $out/result + ''; + + # ── Config merge + round-trip test ──────────────────────────────── + # Tests the merge script (Nix activation behavior) across 7 + # scenarios, then verifies Python's load_config() reads correctly. + config-roundtrip = let + # Nix settings used across scenarios + nixSettings = pkgs.writeText "nix-settings.json" (builtins.toJSON { + model = "test/nix-model"; + toolsets = ["nix-toolset"]; + terminal = { backend = "docker"; timeout = 999; }; + mcp_servers = { + nix-server = { command = "echo"; args = ["nix"]; }; + }; + }); + + # Pre-built YAML fixtures for each scenario + fixtureB = pkgs.writeText "fixture-b.yaml" '' + model: "old-model" + mcp_servers: + old-server: + url: "http://old" + ''; + fixtureC = pkgs.writeText "fixture-c.yaml" '' + skills: + disabled: + - skill-a + - skill-b + session_reset: + mode: idle + idle_minutes: 30 + streaming: + enabled: true + fallback_model: + provider: openrouter + model: test-fallback + ''; + fixtureD = pkgs.writeText "fixture-d.yaml" '' + model: "user-model" + skills: + disabled: + - skill-x + streaming: + enabled: true + transport: edit + ''; + fixtureE = pkgs.writeText "fixture-e.yaml" '' + mcp_servers: + user-server: + url: "http://user-mcp" + nix-server: + command: "old-cmd" + args: ["old"] + ''; + fixtureF = pkgs.writeText "fixture-f.yaml" '' + terminal: + cwd: "/user/path" + custom_key: "preserved" + env_passthrough: + - USER_VAR + ''; + + in pkgs.runCommand "hermes-config-roundtrip" { + nativeBuildInputs = [ pkgs.jq ]; + } '' + set -e + export HOME=$(mktemp -d) + ERRORS="" + + fail() { ERRORS="$ERRORS\nFAIL: $1"; } + + # Helper: run merge then load with Python, output merged JSON + merge_and_load() { + local hermes_home="$1" + export HERMES_HOME="$hermes_home" + ${configMergeScript} ${nixSettings} "$hermes_home/config.yaml" + ${hermesVenv}/bin/python3 -c ' +import json, sys +from hermes_cli.config import load_config +json.dump(load_config(), sys.stdout, default=str) +' + } + + # ═══════════════════════════════════════════════════════════════ + # Scenario A: Fresh install — no existing config.yaml + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario A: Fresh install ===" + A_HOME=$(mktemp -d) + A_CONFIG=$(merge_and_load "$A_HOME") + + echo "$A_CONFIG" | jq -e '.model == "test/nix-model"' > /dev/null \ + || fail "A: model not set from Nix" + echo "$A_CONFIG" | jq -e '.mcp_servers."nix-server".command == "echo"' > /dev/null \ + || fail "A: MCP nix-server missing" + echo "PASS: Scenario A" + + # ═══════════════════════════════════════════════════════════════ + # Scenario B: Nix keys override existing values + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario B: Nix overrides ===" + B_HOME=$(mktemp -d) + install -m 0644 ${fixtureB} "$B_HOME/config.yaml" + B_CONFIG=$(merge_and_load "$B_HOME") + + echo "$B_CONFIG" | jq -e '.model == "test/nix-model"' > /dev/null \ + || fail "B: Nix model did not override" + echo "PASS: Scenario B" + + # ═══════════════════════════════════════════════════════════════ + # Scenario C: User-only keys preserved + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario C: User keys preserved ===" + C_HOME=$(mktemp -d) + install -m 0644 ${fixtureC} "$C_HOME/config.yaml" + C_CONFIG=$(merge_and_load "$C_HOME") + + echo "$C_CONFIG" | jq -e '.skills.disabled == ["skill-a", "skill-b"]' > /dev/null \ + || fail "C: skills.disabled not preserved" + echo "$C_CONFIG" | jq -e '.session_reset.mode == "idle"' > /dev/null \ + || fail "C: session_reset.mode not preserved" + echo "$C_CONFIG" | jq -e '.session_reset.idle_minutes == 30' > /dev/null \ + || fail "C: session_reset.idle_minutes not preserved" + echo "$C_CONFIG" | jq -e '.streaming.enabled == true' > /dev/null \ + || fail "C: streaming.enabled not preserved" + echo "$C_CONFIG" | jq -e '.fallback_model.provider == "openrouter"' > /dev/null \ + || fail "C: fallback_model not preserved" + echo "PASS: Scenario C" + + # ═══════════════════════════════════════════════════════════════ + # Scenario D: Mixed — Nix wins for its keys, user keys preserved + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario D: Mixed merge ===" + D_HOME=$(mktemp -d) + install -m 0644 ${fixtureD} "$D_HOME/config.yaml" + D_CONFIG=$(merge_and_load "$D_HOME") + + echo "$D_CONFIG" | jq -e '.model == "test/nix-model"' > /dev/null \ + || fail "D: Nix model did not override user model" + echo "$D_CONFIG" | jq -e '.skills.disabled == ["skill-x"]' > /dev/null \ + || fail "D: user skills not preserved" + echo "$D_CONFIG" | jq -e '.streaming.enabled == true' > /dev/null \ + || fail "D: user streaming not preserved" + echo "PASS: Scenario D" + + # ═══════════════════════════════════════════════════════════════ + # Scenario E: MCP additive merge + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario E: MCP additive merge ===" + E_HOME=$(mktemp -d) + install -m 0644 ${fixtureE} "$E_HOME/config.yaml" + E_CONFIG=$(merge_and_load "$E_HOME") + + echo "$E_CONFIG" | jq -e '.mcp_servers."user-server".url == "http://user-mcp"' > /dev/null \ + || fail "E: user MCP server not preserved" + echo "$E_CONFIG" | jq -e '.mcp_servers."nix-server".command == "echo"' > /dev/null \ + || fail "E: Nix MCP server did not override same-name user server" + echo "$E_CONFIG" | jq -e '.mcp_servers."nix-server".args == ["nix"]' > /dev/null \ + || fail "E: Nix MCP server args wrong" + echo "PASS: Scenario E" + + # ═══════════════════════════════════════════════════════════════ + # Scenario F: Nested deep merge + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario F: Nested deep merge ===" + F_HOME=$(mktemp -d) + install -m 0644 ${fixtureF} "$F_HOME/config.yaml" + F_CONFIG=$(merge_and_load "$F_HOME") + + echo "$F_CONFIG" | jq -e '.terminal.backend == "docker"' > /dev/null \ + || fail "F: Nix terminal.backend did not override" + echo "$F_CONFIG" | jq -e '.terminal.timeout == 999' > /dev/null \ + || fail "F: Nix terminal.timeout did not override" + echo "$F_CONFIG" | jq -e '.terminal.custom_key == "preserved"' > /dev/null \ + || fail "F: terminal.custom_key not preserved" + echo "$F_CONFIG" | jq -e '.terminal.cwd == "/user/path"' > /dev/null \ + || fail "F: user terminal.cwd not preserved when Nix does not set it" + echo "$F_CONFIG" | jq -e '.terminal.env_passthrough == ["USER_VAR"]' > /dev/null \ + || fail "F: user terminal.env_passthrough not preserved" + echo "PASS: Scenario F" + + # ═══════════════════════════════════════════════════════════════ + # Scenario G: Idempotency — merging twice yields the same result + # ═══════════════════════════════════════════════════════════════ + echo "=== Scenario G: Idempotency ===" + G_HOME=$(mktemp -d) + install -m 0644 ${fixtureD} "$G_HOME/config.yaml" + ${configMergeScript} ${nixSettings} "$G_HOME/config.yaml" + FIRST=$(cat "$G_HOME/config.yaml") + ${configMergeScript} ${nixSettings} "$G_HOME/config.yaml" + SECOND=$(cat "$G_HOME/config.yaml") + + if [ "$FIRST" != "$SECOND" ]; then + fail "G: second merge produced different output" + echo "--- first ---" + echo "$FIRST" + echo "--- second ---" + echo "$SECOND" + fi + echo "PASS: Scenario G" + + # ═══════════════════════════════════════════════════════════════ + # Report + # ═══════════════════════════════════════════════════════════════ + if [ -n "$ERRORS" ]; then + echo "" + echo "FAILURES:" + echo -e "$ERRORS" + exit 1 + fi + + echo "" + echo "=== All 7 merge scenarios passed ===" + mkdir -p $out + echo "ok" > $out/result + ''; }; }; } diff --git a/nix/config-keys.json b/nix/config-keys.json new file mode 100644 index 000000000000..bc91f854bd26 --- /dev/null +++ b/nix/config-keys.json @@ -0,0 +1,127 @@ +[ + "_config_version", + "agent.max_turns", + "approvals.mode", + "auxiliary.approval.api_key", + "auxiliary.approval.base_url", + "auxiliary.approval.model", + "auxiliary.approval.provider", + "auxiliary.compression.api_key", + "auxiliary.compression.base_url", + "auxiliary.compression.model", + "auxiliary.compression.provider", + "auxiliary.flush_memories.api_key", + "auxiliary.flush_memories.base_url", + "auxiliary.flush_memories.model", + "auxiliary.flush_memories.provider", + "auxiliary.mcp.api_key", + "auxiliary.mcp.base_url", + "auxiliary.mcp.model", + "auxiliary.mcp.provider", + "auxiliary.session_search.api_key", + "auxiliary.session_search.base_url", + "auxiliary.session_search.model", + "auxiliary.session_search.provider", + "auxiliary.skills_hub.api_key", + "auxiliary.skills_hub.base_url", + "auxiliary.skills_hub.model", + "auxiliary.skills_hub.provider", + "auxiliary.vision.api_key", + "auxiliary.vision.base_url", + "auxiliary.vision.model", + "auxiliary.vision.provider", + "auxiliary.vision.timeout", + "auxiliary.web_extract.api_key", + "auxiliary.web_extract.base_url", + "auxiliary.web_extract.model", + "auxiliary.web_extract.provider", + "browser.command_timeout", + "browser.inactivity_timeout", + "browser.record_sessions", + "checkpoints.enabled", + "checkpoints.max_snapshots", + "command_allowlist", + "compression.enabled", + "compression.summary_base_url", + "compression.summary_model", + "compression.summary_provider", + "compression.threshold", + "delegation.api_key", + "delegation.base_url", + "delegation.model", + "delegation.provider", + "discord.auto_thread", + "discord.free_response_channels", + "discord.require_mention", + "display.bell_on_complete", + "display.compact", + "display.personality", + "display.resume_display", + "display.show_cost", + "display.show_reasoning", + "display.skin", + "display.streaming", + "honcho", + "human_delay.max_ms", + "human_delay.min_ms", + "human_delay.mode", + "memory.memory_char_limit", + "memory.memory_enabled", + "memory.user_char_limit", + "memory.user_profile_enabled", + "model", + "personalities", + "prefill_messages_file", + "privacy.redact_pii", + "quick_commands", + "security.redact_secrets", + "security.tirith_enabled", + "security.tirith_fail_open", + "security.tirith_path", + "security.tirith_timeout", + "security.website_blocklist.domains", + "security.website_blocklist.enabled", + "security.website_blocklist.shared_files", + "smart_model_routing.cheap_model", + "smart_model_routing.enabled", + "smart_model_routing.max_simple_chars", + "smart_model_routing.max_simple_words", + "stt.enabled", + "stt.local.model", + "stt.openai.model", + "stt.provider", + "terminal.backend", + "terminal.container_cpu", + "terminal.container_disk", + "terminal.container_memory", + "terminal.container_persistent", + "terminal.cwd", + "terminal.daytona_image", + "terminal.docker_forward_env", + "terminal.docker_image", + "terminal.docker_mount_cwd_to_workspace", + "terminal.docker_volumes", + "terminal.env_passthrough", + "terminal.modal_image", + "terminal.persistent_shell", + "terminal.singularity_image", + "terminal.timeout", + "timezone", + "toolsets", + "tts.edge.voice", + "tts.elevenlabs.model_id", + "tts.elevenlabs.voice_id", + "tts.neutts.device", + "tts.neutts.model", + "tts.neutts.ref_audio", + "tts.neutts.ref_text", + "tts.openai.model", + "tts.openai.voice", + "tts.provider", + "voice.auto_tts", + "voice.max_recording_seconds", + "voice.record_key", + "voice.silence_duration", + "voice.silence_threshold", + "whatsapp" +] diff --git a/nix/configMergeScript.nix b/nix/configMergeScript.nix new file mode 100644 index 000000000000..bea2d61611bf --- /dev/null +++ b/nix/configMergeScript.nix @@ -0,0 +1,33 @@ +# nix/configMergeScript.nix — Deep-merge Nix settings into existing config.yaml +# +# Used by the NixOS module activation script and by checks.nix tests. +# Nix keys override; user-added keys (skills, streaming, etc.) are preserved. +{ pkgs }: +pkgs.writeScript "hermes-config-merge" '' + #!${pkgs.python3.withPackages (ps: [ ps.pyyaml ])}/bin/python3 + import json, yaml, sys + from pathlib import Path + + nix_json, config_path = sys.argv[1], Path(sys.argv[2]) + + with open(nix_json) as f: + nix = json.load(f) + + existing = {} + if config_path.exists(): + with open(config_path) as f: + existing = yaml.safe_load(f) or {} + + def deep_merge(base, override): + result = dict(base) + for k, v in override.items(): + if k in result and isinstance(result[k], dict) and isinstance(v, dict): + result[k] = deep_merge(result[k], v) + else: + result[k] = v + return result + + merged = deep_merge(existing, nix) + with open(config_path, "w") as f: + yaml.dump(merged, f, default_flow_style=False, sort_keys=False) +'' diff --git a/nix/nixosModules.nix b/nix/nixosModules.nix index ea8e3a80e4aa..78d927e122f5 100644 --- a/nix/nixosModules.nix +++ b/nix/nixosModules.nix @@ -37,6 +37,8 @@ generatedConfigFile = pkgs.writeText "hermes-config.yaml" configJson; configFile = if cfg.configFile != null then cfg.configFile else generatedConfigFile; + configMergeScript = pkgs.callPackage ./configMergeScript.nix { }; + # Generate .env from non-secret environment attrset envFileContent = lib.concatStringsSep "\n" ( lib.mapAttrsToList (k: v: "${k}=${v}") cfg.environment @@ -55,6 +57,8 @@ ); containerName = "hermes-agent"; + containerDataDir = "/data"; # stateDir mount point inside container + containerHomeDir = "/home/hermes"; # ── Container mode helpers ────────────────────────────────────────── containerBin = if cfg.container.backend == "docker" @@ -86,10 +90,10 @@ fi # ── User: ensure a user with UID=$HERMES_UID exists ── - EXISTING_USER=$(getent passwd "$HERMES_UID" 2>/dev/null | cut -d: -f1 || true) - if [ -n "$EXISTING_USER" ]; then - TARGET_USER="$EXISTING_USER" - TARGET_HOME=$(getent passwd "$HERMES_UID" | cut -d: -f6) + PASSWD_ENTRY=$(getent passwd "$HERMES_UID" 2>/dev/null || true) + if [ -n "$PASSWD_ENTRY" ]; then + TARGET_USER=$(echo "$PASSWD_ENTRY" | cut -d: -f1) + TARGET_HOME=$(echo "$PASSWD_ENTRY" | cut -d: -f6) else TARGET_USER="hermes" TARGET_HOME="/home/hermes" @@ -99,9 +103,12 @@ adduser -u "$HERMES_UID" -D -h "$TARGET_HOME" -s /bin/sh -G "$GROUP_NAME" "$TARGET_USER" 2>/dev/null || true fi fi - if [ ! -d "$TARGET_HOME" ]; then - mkdir -p "$TARGET_HOME" - chown "$HERMES_UID:$HERMES_GID" "$TARGET_HOME" + mkdir -p "$TARGET_HOME" + chown "$HERMES_UID:$HERMES_GID" "$TARGET_HOME" + + # Ensure HERMES_HOME is owned by the target user + if [ -n "''${HERMES_HOME:-}" ] && [ -d "$HERMES_HOME" ]; then + chown -R "$HERMES_UID:$HERMES_GID" "$HERMES_HOME" fi # Install sudo on Debian/Ubuntu if missing (first boot only, cached in writable layer) @@ -117,7 +124,7 @@ if command -v setpriv >/dev/null 2>&1; then exec setpriv --reuid="$HERMES_UID" --regid="$HERMES_GID" --init-groups "$@" elif command -v su >/dev/null 2>&1; then - exec su -s /bin/sh "$TARGET_USER" -c 'exec "$@"' -- "$@" + exec su -s /bin/sh "$TARGET_USER" -c 'exec "$0" "$@"' -- "$@" else echo "WARNING: no privilege-drop tool (setpriv/su), running as root" >&2 exec "$@" @@ -128,6 +135,7 @@ # Environment variables are handled via $HERMES_HOME/.env (read by # load_hermes_dotenv at Python startup), so they don't need container recreation. containerIdentity = builtins.hashString "sha256" (builtins.toJSON { + schema = 2; # bump when hardcoded volumes/env vars change image = cfg.container.image; extraVolumes = cfg.container.extraVolumes; extraOptions = cfg.container.extraOptions; @@ -136,6 +144,13 @@ identityFile = "${cfg.stateDir}/.container-identity"; + # Default: /var/lib/hermes/workspace → /data/workspace. + # Custom paths outside stateDir pass through unchanged (user must add extraVolumes). + containerWorkDir = + if lib.hasPrefix "${cfg.stateDir}/" cfg.workingDirectory + then "${containerDataDir}/${lib.removePrefix "${cfg.stateDir}/" cfg.workingDirectory}" + else cfg.workingDirectory; + in { options.services.hermes-agent = with lib; { enable = mkEnableOption "Hermes Agent gateway service"; @@ -291,6 +306,23 @@ description = "HTTP headers, e.g. for authentication (HTTP transport)."; }; + # Authentication + auth = mkOption { + type = types.nullOr (types.enum [ "oauth" ]); + default = null; + description = '' + Authentication method. Set to "oauth" for OAuth 2.1 PKCE flow + (remote MCP servers). Tokens are stored in $HERMES_HOME/mcp-tokens/. + ''; + }; + + # Enable/disable + enabled = mkOption { + type = types.bool; + default = true; + description = "Enable or disable this MCP server."; + }; + # Common options timeout = mkOption { type = types.nullOr types.int; @@ -303,15 +335,42 @@ description = "Initial connection timeout in seconds (default: 60)."; }; + # Tool filtering + tools = mkOption { + type = types.nullOr (types.submodule { + options = { + include = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "Tool allowlist — only these tools are registered."; + }; + exclude = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "Tool blocklist — these tools are hidden."; + }; + }; + }); + default = null; + description = "Filter which tools are exposed by this server."; + }; + # Sampling (server-initiated LLM requests) sampling = mkOption { type = types.nullOr (types.submodule { options = { enabled = mkOption { type = types.bool; default = true; description = "Enable sampling."; }; - model = mkOption { type = types.str; default = ""; description = "Override model for sampling requests."; }; + model = mkOption { type = types.nullOr types.str; default = null; description = "Override model for sampling requests."; }; max_tokens_cap = mkOption { type = types.nullOr types.int; default = null; description = "Max tokens per request."; }; timeout = mkOption { type = types.nullOr types.int; default = null; description = "LLM call timeout in seconds."; }; max_rpm = mkOption { type = types.nullOr types.int; default = null; description = "Max requests per minute."; }; + max_tool_rounds = mkOption { type = types.nullOr types.int; default = null; description = "Max tool-use rounds per sampling request."; }; + allowed_models = mkOption { type = types.listOf types.str; default = [ ]; description = "Models the server is allowed to request."; }; + log_level = mkOption { + type = types.nullOr (types.enum [ "debug" "info" "warning" ]); + default = null; + description = "Audit log level for sampling requests."; + }; }; }); default = null; @@ -334,6 +393,10 @@ url = "http://my-server:8080/v0/mcp"; headers = { Authorization = "Bearer ..."; }; }; + remote-oauth = { + url = "https://mcp.example.com/mcp"; + auth = "oauth"; + }; } ''; }; @@ -405,9 +468,32 @@ # ── Merge MCP servers into settings ──────────────────────────────── (lib.mkIf (cfg.mcpServers != { }) { services.hermes-agent.settings.mcp_servers = lib.mapAttrs (_name: srv: - { inherit (srv) command args; } + # Stdio transport + lib.optionalAttrs (srv.command != null) { inherit (srv) command args; } // lib.optionalAttrs (srv.env != { }) { inherit (srv) env; } + # HTTP transport + // lib.optionalAttrs (srv.url != null) { inherit (srv) url; } + // lib.optionalAttrs (srv.headers != { }) { inherit (srv) headers; } + # Auth + // lib.optionalAttrs (srv.auth != null) { inherit (srv) auth; } + # Enable/disable + // { inherit (srv) enabled; } + # Common options // lib.optionalAttrs (srv.timeout != null) { inherit (srv) timeout; } + // lib.optionalAttrs (srv.connect_timeout != null) { inherit (srv) connect_timeout; } + # Tool filtering + // lib.optionalAttrs (srv.tools != null) { + tools = lib.filterAttrs (_: v: v != [ ]) { + inherit (srv.tools) include exclude; + }; + } + # Sampling + // lib.optionalAttrs (srv.sampling != null) { + sampling = lib.filterAttrs (_: v: v != null && v != [ ]) { + inherit (srv.sampling) enabled model max_tokens_cap timeout max_rpm + max_tool_rounds allowed_models log_level; + }; + } ) cfg.mcpServers; }) @@ -434,6 +520,7 @@ systemd.tmpfiles.rules = [ "d ${cfg.stateDir} 0755 ${cfg.user} ${cfg.group} - -" "d ${cfg.stateDir}/.hermes 0755 ${cfg.user} ${cfg.group} - -" + "d ${cfg.stateDir}/home 0750 ${cfg.user} ${cfg.group} - -" "d ${cfg.workingDirectory} 0750 ${cfg.user} ${cfg.group} - -" ]; } @@ -443,11 +530,20 @@ system.activationScripts."hermes-agent-setup" = lib.stringAfter [ "users" ] '' # Ensure directories exist (activation runs before tmpfiles) mkdir -p ${cfg.stateDir}/.hermes + mkdir -p ${cfg.stateDir}/home mkdir -p ${cfg.workingDirectory} - chown ${cfg.user}:${cfg.group} ${cfg.stateDir} ${cfg.stateDir}/.hermes ${cfg.workingDirectory} + chown ${cfg.user}:${cfg.group} ${cfg.stateDir} ${cfg.stateDir}/.hermes ${cfg.stateDir}/home ${cfg.workingDirectory} - # Link config file - install -o ${cfg.user} -g ${cfg.group} -m 0644 -D ${configFile} ${cfg.stateDir}/.hermes/config.yaml + # Merge Nix settings into existing config.yaml. + # Preserves user-added keys (skills, streaming, etc.); Nix keys win. + # If configFile is user-provided (not generated), overwrite instead of merge. + ${if cfg.configFile != null then '' + install -o ${cfg.user} -g ${cfg.group} -m 0644 -D ${configFile} ${cfg.stateDir}/.hermes/config.yaml + '' else '' + ${configMergeScript} ${generatedConfigFile} ${cfg.stateDir}/.hermes/config.yaml + chown ${cfg.user}:${cfg.group} ${cfg.stateDir}/.hermes/config.yaml + chmod 0644 ${cfg.stateDir}/.hermes/config.yaml + ''} # Managed mode marker (so interactive shells also detect NixOS management) touch ${cfg.stateDir}/.hermes/.managed @@ -582,16 +678,18 @@ HERMES_NIX_ENV_EOF --network=host \ --entrypoint ${containerEntrypoint} \ --volume /nix/store:/nix/store:ro \ - --volume ${cfg.stateDir}:/data \ + --volume ${cfg.stateDir}:${containerDataDir} \ + --volume ${cfg.stateDir}/home:${containerHomeDir} \ ${lib.concatStringsSep " " (map (v: "--volume ${v}") cfg.container.extraVolumes)} \ --env HERMES_UID="$HERMES_UID" \ --env HERMES_GID="$HERMES_GID" \ - --env HERMES_HOME=/data/.hermes \ + --env HERMES_HOME=${containerDataDir}/.hermes \ --env HERMES_MANAGED=true \ - --env HOME=/home/hermes \ + --env HOME=${containerHomeDir} \ + --env MESSAGING_CWD=${containerWorkDir} \ ${lib.concatStringsSep " " cfg.container.extraOptions} \ ${cfg.container.image} \ - /data/current-package/bin/hermes gateway run --replace ${lib.concatStringsSep " " cfg.extraArgs} + ${containerDataDir}/current-package/bin/hermes gateway run --replace ${lib.concatStringsSep " " cfg.extraArgs} echo "${containerIdentity}" > ${identityFile} fi