summaryrefslogtreecommitdiffstats
path: root/configs/claude.nix
blob: ebbf18600569c886d06a2a286957b520c27646bc (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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# Claude Code, on the Claude subscription, as Remote Control servers: their
# sessions run here and are driven from claude.ai/code or the Claude app.
# One per remote, claude-remote-control@NAME, main by default; more by
# adding them in a layer:
#   systemd.targets.multi-user.wants = [ "claude-remote-control@NAME.service" ];
# or with claude-remote --start NAME (root's tool for the remotes, see
# pkgs/claude-remote.nix), which lasts, across reboots, until
# claude-remote --stop NAME (see stateDir).  One taken out of the layers
# goes on like that, too, after the reboot (see staticFile).
# Or a remote can be an interactive session instead, claude-interactive@NAME
# (see istateDir): claude-remote --start NAME --interactive.
# A remote is a context: it works in ~/remotes/NAME, which is its project
# for Claude Code (sessions, memory, trust), on the repositories in ~/src,
# which all remotes share.  Each runs as claude in a tmux of its own,
# which root opens with claude-remote --attach [NAME].  Once, as root:
# runuser -l claude -c 'claude auth login', which the remotes wait for
# (see login).  Remote Control's questions (enable it, once per
# machine; trust ~/remotes/NAME) the unit answers.
# The state is in /home/claude, i.e. on the run script's --home drive,
# which is required.
{ config, lib, pkgs, ... }:
let
  # The tmux of claude-remote-control@NAME.
  tmux = name: "${pkgs.tmux}/bin/tmux -S /run/claude/${name}/tmux";

  # git, for the remotes and claude-remote, without gettext (25M, for
  # git's messages in other languages than English, which the guest has
  # none of): NO_GETTEXT, and git-sh-i18n not pointing at gettext.sh,
  # which nixpkgs' postPatch puts there regardless.  Not as an overlay of
  # gitMinimal, which would reach everything built with it.
  git = (pkgs.gitMinimal.override { nlsSupport = false; }).overrideAttrs (old: {
    postPatch = builtins.replaceStrings
      [ "--subst-var-by gettext ${pkgs.gettext}" ]
      [ "--subst-var-by gettext /no-gettext" ]
      old.postPatch;
  });

  # Root's tool for the remotes.
  claude-remote = pkgs.callPackage ../pkgs/claude-remote.nix {
    inherit stateDir;
    systemd = config.systemd.package;  # the guest's, which may be slimmer
    gitMinimal = git;
    inherit taskTimer;
  };

  # The login (runuser -l claude -c 'claude auth login'), which the
  # remotes wait for: Remote Control needs it, and ~/.claude.json, which
  # their units answer its questions in, may come before.
  login = "/home/claude/.claude/.credentials.json";
  # Remotes started with systemctl, rather than by multi-user.target's
  # wants (static), come back after a reboot: each has a file of its name
  # in stateDir while it's meant to run, i.e. from its start until it gets
  # stopped (not by a failure, after which it restarts, nor by a
  # shutdown).  Below /home/.var/lib/claude, the claude facet's part of
  # what would be in /var/lib (which is on the tmpfs), on the home drive:
  # root's, and readable for anyone.
  stateDir = "/home/.var/lib/claude/remote-control";
  # The remotes that were static at the last boot, so that the restore
  # service makes the ones that aren't anymore dynamic, and they go on;
  # and the interactive ones (staticI), likewise.
  staticFile = "/home/.var/lib/claude/static-remotes";
  staticFileI = "/home/.var/lib/claude/static-interactive";
  # The static ones, by the units multi-user.target wants.
  staticOf = prefix: map (u: lib.removeSuffix ".service" (lib.removePrefix prefix u))
    (lib.filter (lib.hasPrefix prefix) config.systemd.targets.multi-user.wants);
  static = staticOf "claude-remote-control@";
  systemctl = "${config.systemd.package}/bin/systemctl";
  isIn = list: name: ''case " ${toString list} " in *" ${name} "*) true ;; *) false ;; esac'';
  isStatic = isIn static;
  # NAME, meant to run (a file in DIR), from its start, but for a static
  # one, until it gets stopped (not by a failure, nor a shutdown).
  rememberIn = dir: list: pkgs.writeShellScript "claude-remember" ''
    if ! ${isIn list "$1"}; then
      touch ${dir}/"$1"
    fi
  '';
  forgetIn = dir: pkgs.writeShellScript "claude-forget" ''
    if test "''${SERVICE_RESULT-}" = success &&
        test "$(${systemctl} is-system-running || :)" != stopping; then
      rm -f ${dir}/"$1"
    fi
  '';
  remember = rememberIn stateDir static;
  forget = forgetIn stateDir;

  # Interactive sessions, claude-interactive@NAME: a remote, too, in
  # ~/remotes/NAME, but one claude, interactive (in its tmux), with Remote
  # Control, rather than a Remote Control server; a NAME is either.  Its
  # session has an id of its own, kept in sessionsDir/NAME (which is
  # what makes NAME interactive), made at its first start, and resumed
  # once there's a transcript; those started with systemctl come back
  # after a reboot, like the remotes, by istateDir.  More memory and CPU
  # than a Remote Control server, and its session is archived on
  # claude.ai while it's stopped, back once it runs again.
  istateDir = "/home/.var/lib/claude/interactive";
  sessionsDir = "/home/.var/lib/claude/interactive-sessions";
  staticI = staticOf "claude-interactive@";
  # (as root) NAME's session id, made at its first start
  sessionId = pkgs.writeShellScript "claude-interactive-session-id" ''
    f=${sessionsDir}/"$1"
    test -s "$f" || cat /proc/sys/kernel/random/uuid > "$f"
  '';
  # claude, interactive, with Remote Control, in NAME's session: by its
  # id, the first time, else resumed, once there's a transcript
  interactive = pkgs.writeShellScript "claude-interactive" ''
    id=$(cat ${sessionsDir}/"$1")
    key=$(printf %s /home/claude/remotes/"$1" | tr '/.' '--')
    if test -e /home/claude/.claude/projects/"$key"/"$id".jsonl; then
      exec claude --remote-control "$1" --resume "$id"
    else
      exec claude --remote-control "$1" --session-id "$id"
    fi
  '';
  # (as root) not NAME of the other kind, too, running (their tmux would
  # collide, and so would their sessions)
  notAlso = other: pkgs.writeShellScript "claude-not-also" ''
    if ${systemctl} is-active -q "${other}@$1.service"; then
      echo "$1 runs as ${other}@$1 already" >&2
      exit 1
    fi
  '';

  # A directory in ~/remotes: neither ~/remotes itself, nor anything
  # above, nor a dot file.
  remoteDir = pkgs.writeShellScript "claude-remote-dir" ''
    case $1 in
      "" | .* | */*) echo "$1: not a name for a directory in ~/remotes" >&2; exit 1
    esac
    mkdir -p /home/claude/remotes/"$1"
  '';
  # Remote Control's questions, answered, rather than asked in the
  # terminal: enable it (remoteDialogSeen, once per machine; that's what
  # the units are for), and trust ~/remotes/NAME, the remote's own
  # directory, just made.  In ~/.claude.json (once there is one, i.e.
  # after the login), atomically; if a remote writes back what it read
  # before, and an answer gets lost, Remote Control asks again, as before.
  answers = pkgs.writeShellScript "claude-remote-control-trust" ''
    f=/home/claude/.claude.json d=/home/claude/remotes/$1
    test -f "$f" || exit 0
    if ! ${pkgs.jq}/bin/jq -e --arg d "$d" '.remoteDialogSeen == true and .projects[$d].hasTrustDialogAccepted == true' "$f" >/dev/null; then
      ${pkgs.jq}/bin/jq --arg d "$d" '.remoteDialogSeen = true | .projects[$d].hasTrustDialogAccepted = true' "$f" > "$f.trust" &&
        mv "$f.trust" "$f" || rm -f "$f.trust"
    fi
  '';

  # What claude runs with, in the remotes and the tasks: their PATH, and
  # environment.
  claudePath = [
    pkgs.claude-code
    config.nix.package
    pkgs.bash
    pkgs.coreutils
    pkgs.diffutils
    pkgs.findutils
    pkgs.gawk
    git
    pkgs.gnugrep
    pkgs.gnused
    pkgs.ripgrep
    # And, after these, the system's, like rig-egress or claude-remote.
    "/run/current-system/sw"
  ];
  claudeEnv = {
    # Telemetry and error reports go to Datadog.  Unlike
    # CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC, these leave Remote Control
    # alone.
    DISABLE_TELEMETRY = "1";
    DISABLE_ERROR_REPORTING = "1";
    # The claude.ai account's connectors, via mcp-proxy.anthropic.com.
    ENABLE_CLAUDEAI_MCP_SERVERS = "false";
  };

  # Tasks, scheduled with claude-remote --schedule: a prompt for a remote,
  # claude -p in ~/remotes/NAME, at a time (once), or at a calendar event
  # (again and again), per systemd.time(7); each claude-task@NAME:ID, by a
  # transient timer.  Their definitions are in tasksDir/NAME:ID (remote,
  # kind: at or every, when: normalized, prompt, mode, and once it ran,
  # last and result), so that the restore service makes their timers
  # again, after a reboot (and that they're backed up).
  tasksDir = "/home/.var/lib/claude/tasks";
  # (as root) task NAME:ID's timer, from its definition: at its time; but a
  # one-time one that ran is done, and one missed (the VM was off then)
  # runs now
  taskTimer = pkgs.writeShellScript "claude-task-timer" ''
    set -eu
    d=${tasksDir}/$1 unit=claude-task@$1
    if ${systemctl} is-active -q "$unit.timer"; then exit 0; fi
    when=$(cat "$d/when")
    if test "$(cat "$d/kind")" = at; then
      test ! -e "$d/last" || exit 0
      if test "$(date -d "$when" +%s)" -le "$(date +%s)"; then
        ${systemctl} start --no-block "$unit.service"
        exit
      fi
    fi
    ${config.systemd.package}/bin/systemd-run --quiet --unit="$unit" \
      --on-calendar="$when" --timer-property=AccuracySec=1s \
      --description="claude task $1"
  '';
  # (as claude) task NAME:ID: its prompt, in its remote's directory
  claudeTask = pkgs.writeShellScript "claude-task" ''
    d=${tasksDir}/$1
    cd /home/claude/remotes/"$(cat "$d/remote")"
    exec claude -p "$(cat "$d/prompt")" --permission-mode "$(cat "$d/mode")"
  '';
  # (as root) task NAME:ID, run: when, and how it went
  taskDone = pkgs.writeShellScript "claude-task-done" ''
    d=${tasksDir}/$1
    test -d "$d" || exit 0
    date -Is > "$d/last"
    printf '%s\n' "''${SERVICE_RESULT-}" > "$d/result"
  '';

  # In a tmux, for a terminal: Remote Control asks its questions there, and
  # shows the session's URL; an interactive session is there, too.
  # Remote Control exits after about 10 minutes without network, which
  # ends the session and the server, and systemd starts it again, which
  # brings back the sessions it served.  Sessions start in ~/remotes/NAME,
  # which gets created if need be: a directory of its own, as Claude Code
  # never saves trust for the home directory itself, and without a
  # terminal to ask, it wouldn't start.  A tmux each, as a second tmux
  # new-session in the same server would exit without a process for
  # systemd to follow, and in a runtime directory each, as stopping one
  # removes its own.
  claudeUnit = { other, preStart ? [ ], remember, forget, command }: {
    wants = [ "network-online.target" ];
    after = [ "network-online.target" "systemd-tmpfiles-setup.service" ];
    unitConfig.RequiresMountsFor = "/home/claude";
    # Not before the login (skipped, rather than failed): the restore
    # service starts the remotes once there is one.
    unitConfig.ConditionPathExists = login;
    # Without the drive, there's no mount to require, and /home is on the
    # tmpfs: fail rather than keep the state there.
    unitConfig.AssertPathIsMountPoint = "/home";
    path = claudePath;
    environment = claudeEnv;
    serviceConfig = {
      Type = "forking";
      User = "claude";
      WorkingDirectory = "/home/claude";
      RuntimeDirectory = "claude/%i";
      ExecStartPre = [
        "+${notAlso other} %i"
        "${remoteDir} %i"
        "${answers} %i"
      ] ++ preStart ++ [
        # As root (+), the state being root's.
        "+${remember} %i"
      ];
      ExecStart = "${tmux "%i"} new-session -d -s claude -c /home/claude/remotes/%i ${command}";
      ExecStopPost = "+${forget} %i";
      Restart = "always";
      RestartSec = 10;
    };
  };
in
{
  imports = [ ../modules/claude-code.nix ];

  rig.home.required = true;

  # For Claude to build and try things with (nix-build, nix-shell), see
  # the service's path; with it, the run script requires --store.
  assertions = [{
    assertion = config.nix.enable;
    message = "configs/claude.nix needs nix: put rigs' layers/nix.nix into the layers, before it.";
  }];

  users.users.claude = {
    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.
    uid = 1000;
    home = "/home/claude";
    # /home is mounted after users get created, see tmpfiles below.
    createHome = false;
    packages = lib.filter lib.isDerivation config.systemd.services."claude-remote-control@".path;
  };
  systemd.tmpfiles.rules = [
    "d /home/claude 0700 claude users -"
    "d /home/claude/src 0755 claude users -"
    "d /home/claude/remotes 0755 claude users -"
    "d ${stateDir} 0755 root root -"
    "d ${istateDir} 0755 root root -"
    "d ${sessionsDir} 0755 root root -"
    "d ${tasksDir} 0755 root root -"
  ];

  # The repositories, for every remote (and every claude here, as managed
  # settings are the machine's, and win over anyone's own); and the
  # skills synced from the claude.ai account that are of no use here
  # (documents, browsers, desktop control), off: hidden from the model
  # and from /, each by its name and as the account's (anthropic-skills:).
  environment.etc."claude-code/managed-settings.json".text = builtins.toJSON {
    permissions.additionalDirectories = [ "/home/claude/src" ];
    skillOverrides = lib.listToAttrs (lib.concatMap (s: [
      (lib.nameValuePair s "off")
      (lib.nameValuePair "anthropic-skills:${s}" "off")
    ]) [
      "built-in-browser" "chrome-browser" "computer-use" "deep-research"
      "docs" "docx" "pdf" "pptx" "skill-creator" "xlsx"
    ]);
  };

  systemd.targets.multi-user.wants = [ "claude-remote-control@main.service" ];

  systemd.services."claude-remote-control@" = claudeUnit {
    other = "claude-interactive";
    inherit remember forget;
    # --name: its session named after the remote, rather than after the
    # host, which they all share.
    command = "${lib.getExe pkgs.claude-code} remote-control --name %i";
  };
  systemd.services."claude-interactive@" = claudeUnit {
    other = "claude-remote-control";
    preStart = [ "+${sessionId} %i" ];
    remember = rememberIn istateDir staticI;
    forget = forgetIn istateDir;
    command = "${interactive} %i";
  };

  # A task's run (see tasksDir), as its remote's would be, but once, and
  # not before the login.
  systemd.services."claude-task@" = {
    wants = [ "network-online.target" ];
    after = [ "network-online.target" ];
    unitConfig.RequiresMountsFor = "/home/claude";
    unitConfig.ConditionPathExists = login;
    path = claudePath;
    environment = claudeEnv;
    serviceConfig = {
      Type = "oneshot";
      User = "claude";
      ExecStart = "${claudeTask} %i";
      ExecStopPost = "+${taskDone} %i";
    };
  };
  # Starts the remotes in stateDir again, after a reboot, but for those
  # that are static now, which it forgets instead; and before that, makes
  # the ones that were static at the last boot, but aren't anymore (taken
  # out of the configuration), dynamic, so they go on running, as long as
  # they have a directory (to retire one: claude-remote --stop NAME); and
  # starts the static ones, too, which multi-user.target's start skipped
  # if there was no login yet.  Once per boot, by the path unit below,
  # once there's a login.  And the interactive sessions, likewise.
  systemd.services.claude-remote-control-restore = {
    after = [ "systemd-tmpfiles-setup.service" ];
    unitConfig.RequiresMountsFor = stateDir;
    unitConfig.AssertPathIsMountPoint = "/home";
    serviceConfig.Type = "oneshot";
    # active, once done, so that the path unit doesn't start it again
    serviceConfig.RemainAfterExit = true;
    script = ''
      # KIND STATIC-FILE STATE-DIR STATIC...: the remotes of KIND
      # (claude-KIND@NAME) that were static at the last boot (in
      # STATIC-FILE), but aren't anymore, made dynamic; the dynamic ones
      # (in STATE-DIR) started, but for those that are static now, which
      # get forgotten; and the static ones started.
      restore() {
        local kind=$1 file=$2 dir=$3 f name statics
        shift 3
        statics=" $* "
        if test -f "$file"; then
          for name in $(cat "$file"); do
            case $statics in *" $name "*) continue ;; esac
            if test -d /home/claude/remotes/"$name"; then
              touch "$dir/$name"
            fi
          done
        fi
        printf '%s\n' "$@" > "$file"
        for f in "$dir"/*; do
          test -f "$f" || continue
          name=''${f##*/}
          case $statics in
            *" $name "*) rm -f "$f" ;;
            *) ${systemctl} start --no-block "claude-$kind@$name.service"
          esac
        done
        for name; do
          ${systemctl} start --no-block "claude-$kind@$name.service"
        done
      }
      restore remote-control ${staticFile} ${stateDir} ${lib.escapeShellArgs static}
      restore interactive ${staticFileI} ${istateDir} ${lib.escapeShellArgs staticI}
      # and the tasks' timers
      for d in ${tasksDir}/*/; do
        test -d "$d" || continue
        d=''${d%/}
        ${taskTimer} "''${d##*/}" || :
      done
    '';
  };
  # The restore service, once there's a login: at boot, if there's one
  # already, or else as soon as there is.
  systemd.paths.claude-remote-control-restore = {
    wantedBy = [ "multi-user.target" ];
    unitConfig.RequiresMountsFor = "/home/claude";
    pathConfig.PathExists = login;
  };
  environment.systemPackages = [ claude-remote ];
}