summaryrefslogtreecommitdiffstats
path: root/configs/hermes.nix
blob: ab04b15ba268847808341bfa7b1133e4d8fd59b3 (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
# Hermes Agent (Nous Research), with its own NixOS module, fitted to this
# guest.  hermes runs as hermes in a tmux, which root's console opens.  It
# uses the Claude subscription through the claude CLI: log in once with
# claude auth login, in a new window there (C-b c).
{ 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 plugin's Claude models need claude 2.1.280 or newer; nixos-26.05
  # has 2.1.223.  From npm's platform package, which has the plain binary
  # and an integrity hash; x86_64-linux only, like the package.
  claude-code = pkgs.claude-code.overrideAttrs (_: rec {
    version = "2.1.329";
    src = pkgs.fetchurl {
      url = "https://registry.npmjs.org/@anthropic-ai/claude-code-linux-x64/-/claude-code-linux-x64-${version}.tgz";
      hash = "sha512-+n4lu1ubYAp02Y0X/MAUnxw9yY6SHHZ77F+IoW+V0wVoFuiI9opdH6gofjf14gXJCEYMTNpks7Gn1i8XZTKAWA==";
    };
    # installPhase installs $src as is.
    preInstall = ''
      tar -xzf $src package/claude
      src=$PWD/package/claude
    '';
  });

  # Root's way (back) into 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")'
    '';
  };

  # 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 ];

  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;
    };
    # /var is a tmpfs.  This is on the only drive that can outlive a boot,
    # like nix's database, see /nix/var.
    stateDir = "/nix/.rw-store/hermes";
    settings.model = {
      provider = "claude-subscription-directsdk-experimental";
      default = "opus";
    };
    # 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
    # in the host's xchg, which is read at boot.
    settings.webapp = {
      enabled = true;
      host = "0.0.0.0";
      port = 9120;
    };
    environmentFiles = [ "/xchg/hermes.env" ];
    # The login is in ~/.claude, i.e. in stateDir.
    extraPackages = [ claude-code ];
  };
  # hermes for hermes' shells, too, like in a new window of the tmux.
  users.users.hermes.packages = [ config.services.hermes-agent.package ];
  nixpkgs.config.allowUnfreePredicate = pkg: lib.getName pkg == "claude-code";

  # hermes' home is stateDir, so this uses the service's state at ~/.hermes.
  # tmux lets root attach to it.  Quitting hermes ends the session, and
  # systemd starts a new one.
  systemd.services.hermes-tmux = {
    wantedBy = [ "multi-user.target" ];
    requires = [ "hermes-agent-setup.service" ];
    after = [ "hermes-agent-setup.service" ];
    before = [ "serial-getty@ttyS0.service" ];
    serviceConfig = {
      Type = "forking";
      User = "hermes";
      RuntimeDirectory = "hermes";
      ExecStart = "${tmux} new-session -d -s hermes ${lib.getExe config.services.hermes-agent.package} --tui";
      Restart = "always";
    };
    inherit (config.systemd.services.hermes-agent) path;
  };
  # Detaching gets root's shell back, and hermes-attach goes back in.
  environment.systemPackages = [ hermes-attach ];
  programs.bash.loginShellInit = ''
    if [ "$USER" = root ] && [ -z "$TMUX" ]; then ${lib.getExe hermes-attach}; fi
  '';

  # 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"

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

  # 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;
}