summaryrefslogtreecommitdiffstats
path: root/configs/hermes.nix
blob: 93fea1c030af2b6bc39dfd3a7b06cc2a313668ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# Hermes Agent (Nous Research), with its own NixOS module, fitted to this
# guest.  hermes runs as hermes in a tmux, which root opens with
# hermes-attach.  Two ways to Claude, selectable with /model or hermes
# model: the Claude API (provider anthropic, the default), with the API key
# from the secret hermes.env (see environmentFiles), and the Claude subscription
# through the claude CLI (provider claude-subscription-directsdk-experimental):
# log in once with claude auth login, in a new window there (C-b c).  The
# state is in /home/hermes, i.e. on the run script's --home drive, which is
# required.
{ config, lib, pkgs, hostPkgs, ... }:
let
  tmux = "${pkgs.tmux}/bin/tmux -S /run/hermes/tmux";
  # The provider plugin, installed by hermes-agent-setup, see there.
  claude-subscription-directsdk = pkgs.runCommand "claude-subscription-directsdk" { } ''
    cp -r ${pkgs.fetchFromGitHub {
      owner = "NousResearch";
      repo = "hermes-official-plugins";
      rev = "80025332933bf84fb3c7b68f369d9fe59a771e98";
      hash = "sha256-eI0XGxwrM9D9a6Vdoj+yAGDGJalaUgLE1fw+aLHjb8c=";
    }}/claude-subscription-directsdk $out
  '';

  # The home drive, for hermes' services, see there.
  homeMount = {
    RequiresMountsFor = config.services.hermes-agent.stateDir;
    AssertPathIsMountPoint = "/home";
  };

  # Root's way into hermes' tmux; attaching starts it (see hermes-tmux).
  hermes-attach = pkgs.writeShellScriptBin "hermes-attach" ''
    exec ${tmux} attach -t hermes
  '';

  # Fetched with the host's pkgs (see default.nix), as imports need it.
  # Bump rev and hash together.
  src = hostPkgs.applyPatches {
    name = "hermes-agent-source";
    src = hostPkgs.fetchFromGitHub {
      owner = "NousResearch";
      repo = "hermes-agent";
      rev = "9f47677483d1b4de4d1a88d37b3b7ca18b18b215";
      hash = "sha256-4fRnt5Dh7bbuNR6XODpuhoXP/XOrZP0Fc5XqYuvj+/Y=";
    };
    # The gateway's log lines on stderr get a timestamp of their own, which
    # journald adds anyway: leave it out when stderr is the journal.
    postPatch = ''
      substituteInPlace gateway/run.py --replace-fail \
        'RedactingFormatter("%(asctime)s %(levelname)s %(name)s: %(message)s")' \
        'RedactingFormatter(("" if os.environ.get("JOURNAL_STREAM") else "%(asctime)s ") + "%(levelname)s %(name)s: %(message)s")'

      # Bundled and optional skills get copied out of the store with the
      # store's modes, i.e. read-only, so skill_manage can neither patch
      # them nor write its temporary files next to them: make the copies
      # writable (and the categories' DESCRIPTION.md, without its mode).
      # The manifest's hashes are of contents only, so that doesn't make
      # them count as user-modified.
      substituteInPlace tools/skills_sync.py \
        --replace-fail 'shutil.copytree(src, dest, ignore=_ignore_runtime_cache)' \
          '_copytree_writable(src, dest, ignore=_ignore_runtime_cache)' \
        --replace-fail 'shutil.copytree(skill_src, dest, ignore=_ignore_runtime_cache)' \
          '_copytree_writable(skill_src, dest, ignore=_ignore_runtime_cache)' \
        --replace-fail 'shutil.copy2(desc_md, dest_desc)' \
          'shutil.copyfile(desc_md, dest_desc)'
      substituteInPlace tools/skills_sync_bundled_ops.py \
        --replace-fail 'shutil.copytree(src, dest, ignore=_ignore_runtime_cache, dirs_exist_ok=True,' \
          'ss._copytree_writable(src, dest, ignore=_ignore_runtime_cache, dirs_exist_ok=True,'
      cat >> tools/skills_sync.py <<'EOF'


      def _copytree_writable(src, dst, **kwargs):
          result = shutil.copytree(src, dst, **kwargs)
          for root, _dirs, files in os.walk(dst):
              for path in [root, *(os.path.join(root, name) for name in files)]:
                  st = os.lstat(path)
                  if not stat.S_ISLNK(st.st_mode):
                      os.chmod(path, st.st_mode | stat.S_IWUSR)
          return result
      EOF
    '';
  };

  # hermes-agent's flake without flakes, like flake-compat, but with this
  # system's pkgs as nixpkgs, which all of the flake's inputs follow.  The
  # other inputs are fetched as locked in its flake.lock; home-manager is
  # left out, as only the flake's checks use it.
  callFlake = src: inputs:
    let
      self = { _type = "flake"; outPath = src; inherit inputs; }
        // (import (src + "/flake.nix")).outputs (inputs // { inherit self; });
    in
    self;
  input = name:
    let locked = (builtins.fromJSON (builtins.readFile (src + "/flake.lock"))).nodes.${name}.locked;
    in hostPkgs.fetchFromGitHub {
      inherit (locked) owner repo rev;
      hash = locked.narHash;
    };
  nixpkgs = {
    _type = "flake";
    outPath = pkgs.path;
    inherit (pkgs) lib;
    # For nixos-26.05, which hermes-agent doesn't target.
    legacyPackages.${pkgs.stdenv.hostPlatform.system} = pkgs.extend (_: prev: {
      # Its fetchPnpmDeps overrides nodejs-slim in a pnpm >= 11, but
      # hermes-agent's pnpm 12 is a plain attrset with that.
      fetchPnpmDeps = args: prev.fetchPnpmDeps (args // {
        pnpm = args.pnpm // { override = attrs: args.pnpm // attrs; };
      });
      # hermes-agent patches a bug of patchelf 0.19 that its 0.15 doesn't
      # have, and the patch doesn't apply to it.
      patchelf =
        if lib.versionOlder prev.patchelf.version "0.19"
        then prev.patchelf // { overrideAttrs = _: prev.patchelf; }
        else prev.patchelf;
    });
  };
  pyproject-nix = callFlake (input "pyproject-nix") { inherit nixpkgs; };
  uv2nix = callFlake (input "uv2nix") { inherit nixpkgs pyproject-nix; };
  hermes-agent = callFlake src {
    inherit nixpkgs pyproject-nix uv2nix;
    flake-parts = callFlake (input "flake-parts") { nixpkgs-lib = nixpkgs; };
    pyproject-build-systems = callFlake (input "pyproject-build-systems") { inherit nixpkgs pyproject-nix uv2nix; };
  };
in
{
  # Straight from the file, as the flake's nixosModules.default needs pkgs,
  # which imports can't use.
  imports = [
    (import (src + "/nix/nixosModules.nix") { inputs.self = hermes-agent; }).flake.nixosModules.default
    ../modules/claude-code.nix
  ];

  services.hermes-agent = {
    enable = true;
    # Without perl, as profiles/perlless forbids it in the closure: git
    # without send-email & co., and no wl-clipboard, whose xdg-utils needs
    # perl, and which is no use here anyway.
    package = hermes-agent.packages.${pkgs.stdenv.hostPlatform.system}.default.override {
      git = pkgs.gitMinimal;
      wl-clipboard = pkgs.emptyDirectory;
    };
    # hermes' home, as the module makes it, on the --home drive.
    stateDir = "/home/hermes";
    # The anthropic provider uses ANTHROPIC_API_KEY from hermes.env, see below.
    # Don't put ANTHROPIC_TOKEN or CLAUDE_CODE_OAUTH_TOKEN otherwise hermes
    # disguises itself as claude code.
    settings.model = {
      provider = "anthropic";
      default = "claude-opus-5-5";
    };
    # Prevent anthropic provider from using ~/.claude/.credentials.json
    # claude-subscription-directsdk-experimental is unaffected as it's going
    # via the claude CLI.
    settings.auth.adopt_external_logins = false;
    # The Webapp (Hermes Desktop in a browser), served by the gateway, for
    # the host at http://GUEST:9120.  Off loopback, it needs a sign-in:
    # put HERMES_DASHBOARD_BASIC_AUTH_USERNAME, ..._PASSWORD (or
    # ..._PASSWORD_HASH) and ..._SECRET (32+ random bytes) into hermes.env
    # (the secret, see environmentFiles).
    settings.webapp = {
      enabled = true;
      host = "0.0.0.0";
      port = 9120;
    };
    # A secret (rig.secrets), from the run script: --secret
    # hermes.env=FILE, which it requires.  The module copies it into
    # ~/.hermes/.env, i.e. onto the home drive.
    environmentFiles = [ config.rig.secrets."hermes.env".path ];
    # The login is in ~/.claude, i.e. in stateDir.
    extraPackages = [ pkgs.claude-code ];
  };
  # hermes for hermes' shells, too, like in a new window of the tmux.
  users.users.hermes.packages = [
    config.services.hermes-agent.package
    pkgs.gitMinimal
  ];

  rig.home.required = true;
  # The API key and the Webapp's sign-in, see environmentFiles.
  rig.secrets."hermes.env" = { };
  # A normal user, with a home like any other.  /home is mounted after
  # users get created, see tmpfiles below.
  users.users.hermes = {
    isSystemUser = lib.mkForce false;
    isNormalUser = true;
    # Fixed, for the files on the home drive: users get created anew at
    # every boot, and their uids would depend on the other users there.
    # Not claude's (configs/claude.nix).
    uid = 1001;
    createHome = lib.mkForce false;
  };
  users.groups.hermes.gid = 1001;
  # 0700 rather than the module's 2770 (setgid, for its hostUsers, which
  # aren't used here): before it, so it's the one systemd-tmpfiles takes
  # (it ignores later lines for the same path, with a warning).
  systemd.tmpfiles.rules = lib.mkBefore [
    "d ${config.services.hermes-agent.stateDir} 0700 hermes hermes -"
  ];
  # Without the drive, there's no mount to require, and /home is on the
  # tmpfs: fail rather than keep the state there.
  systemd.services.hermes-agent-setup.unitConfig = homeMount;
  systemd.services.hermes-agent.unitConfig = homeMount;
  systemd.services.hermes-tmux.unitConfig = homeMount;

  # hermes' home is stateDir, so this uses the service's state at ~/.hermes.
  # tmux lets root attach to it.  Socket-activated: the first client
  # starts the server, whose config starts hermes, and quitting hermes
  # ends the session and the server (exit-empty), until the next client.
  systemd.sockets.hermes-tmux = {
    wantedBy = [ "sockets.target" ];
    socketConfig = {
      ListenStream = "/run/hermes/tmux";
      SocketUser = "hermes";
      SocketMode = "0600";
    };
  };
  systemd.services.hermes-tmux = {
    requires = [ "hermes-agent-setup.service" ];
    after = [ "hermes-agent-setup.service" ];
    serviceConfig = {
      User = "hermes";
      # -D: in the foreground, on the socket from systemd.
      ExecStart = "${pkgs.tmux}/bin/tmux -D -f ${pkgs.writeText "hermes-tmux.conf" ''
        set -s exit-empty on
        new-session -d -s hermes ${lib.getExe config.services.hermes-agent.package} --tui
      ''}";
    };
    inherit (config.systemd.services.hermes-agent) path;
  };
  environment.systemPackages = [ hermes-attach ];

  # The module adds pkgs.git, which needs perl; the package has gitMinimal.
  systemd.services.hermes-agent.path = lib.mkForce ([
    config.services.hermes-agent.package
    pkgs.bash
    pkgs.coreutils
  ] ++ config.services.hermes-agent.extraPackages);

  # nixos-init doesn't run activation scripts, and that's where the module
  # creates the state and installs config.yaml and .env.
  systemd.services.hermes-agent-setup = {
    requiredBy = [ "hermes-agent.service" ];
    before = [ "hermes-agent.service" ];
    serviceConfig.Type = "oneshot";
    serviceConfig.RemainAfterExit = true;
    script = config.system.activationScripts.hermes-agent-setup.text + ''

      # Not with extraPlugins, which links to the store: Hermes stages a
      # provider plugin by copying it, mode included, and renaming the
      # copy into another directory, which needs a writable directory to
      # update its "..", and fails as hermes with the store's read-only
      # one.  So a writable copy instead.
      p=${config.services.hermes-agent.stateDir}/.hermes/plugins/claude-subscription-directsdk
      rm -rf "$p"
      cp -r --no-preserve=mode ${claude-subscription-directsdk} "$p"
      chown -R hermes:hermes "$p"

      # Hermes imports provider plugins from copies under runtime, one set
      # per process, reclaimed by later processes when nothing holds them.
      # Copies of a read-only plugin couldn't be removed, and a crash
      # leaves its own; no Hermes runs yet, so none is in use.
      rm -rf ${config.services.hermes-agent.stateDir}/.hermes/runtime/provider-plugins

      # Writable for hermes, too, see HERMES_MANAGED below.
      chmod 0660 ${config.services.hermes-agent.stateDir}/.hermes/config.yaml

      # The module's script makes it 2770, see tmpfiles above.
      chmod 0700 ${config.services.hermes-agent.stateDir}
    '';
  };

  # Not managed, as far as Hermes is concerned: managed, it refuses to
  # save config.yaml at all, which takes interactive model changes that
  # last (/model --global, hermes model).  HERMES_MANAGED wins over the
  # module's .managed marker.  At boot, the settings here still replace
  # the same keys in config.yaml (model.provider, model.default, ...),
  # which keeps the rest.
  environment.variables.HERMES_MANAGED = "false";
  systemd.services.hermes-agent.environment.HERMES_MANAGED = lib.mkForce "false";
  systemd.services.hermes-tmux.environment.HERMES_MANAGED = "false";

  # users.manageLingering is off here.  Without a user manager, hermes'
  # cron can't run jobs; nothing else needs one.
  users.users.hermes.linger = null;
}