summaryrefslogtreecommitdiffstats
path: root/pkgs/claude-remote.nix
blob: ff491023ed39c666d7d16407af27d4e1bc5d98a6 (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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# claude-remote, root's tool for the remotes (claude-remote-control@NAME,
# see configs/claude.nix): list, inspect, start, stop, restart, attach,
# log, rename; with bash completion.
#
# Renaming a remote, OLD to NEW:
# 1. claude-remote rename OLD NEW, as root, from anywhere but OLD itself.
#    It checks first (OLD there and not static, nothing of NEW's there,
#    nothing but OLD's own unit using OLD), stops OLD if it runs (asking,
#    or with --stop), moves its directory, its Claude Code project (with
#    the link to its claude.ai session), its trust, its worktrees and its
#    branches (OLD/* to NEW/*), and starts NEW if OLD ran.  A static
#    remote, take out of the configuration first, and deploy.
# 2. Check NEW: claude-remote inspect NEW, and claude.ai, where its
#    sessions go on (named OLD-..., until new ones).  Update what
#    mentions OLD (it says where): ~claude/CLAUDE.md, NEW's own CLAUDE.md,
#    and a static one, the configuration.
# 3. If something's wrong: claude-remote rename NEW OLD.
# A rename is all or nothing: if a step fails, it takes back the ones
# done, and ends where it began.  Only if that fails, too, it keeps a
# copy of ~claude/.claude.json, as it was, which claude-remote list
# shows, until it's removed.
{ lib, runCommand, writeShellScript, writeText
, coreutils, findutils, gitMinimal, gnugrep, gnused, jq, systemd, tmux, util-linux
  # Where remotes started with systemctl are kept, see configs/claude.nix.
, stateDir
}:
let
  script = writeShellScript "claude-remote" ''
    set -eu
    export PATH=${lib.makeBinPath [ coreutils findutils gitMinimal gnugrep gnused jq systemd tmux util-linux ]}
    # The static remotes: those multi-user.target wants, as the running
    # system has it (so changing them doesn't change this script).
    static=($(systemctl show --value -p Wants multi-user.target 2>/dev/null |
      tr ' ' '\n' | sed -n 's/^claude-remote-control@\(.*\)\.service$/\1/p'))
    state=${lib.escapeShellArg stateDir}
    home=/home/claude
    remotes=$home/remotes

    usage() {
      cat <<'EOF'
    usage: claude-remote [COMMAND [NAME...]]

    The remotes: claude-remote-control@NAME, each a Claude Code Remote
    Control server, working in ~claude/remotes/NAME.

    Commands:
      list (the default)
          The remotes: name, kind, state, trusted; and copies of
          ~claude/.claude.json that a failed rename kept.
      inspect NAME
          A remote, in more detail: its unit, directory, trust, claude.ai
          session, and its terminal's last lines.
      start NAME
          Start a remote; a dynamic one lasts, across reboots, until stop.
      stop NAME
      restart NAME
      attach [NAME]
          Its terminal (tmux; default: main; C-b d to leave).
      log NAME [JOURNALCTL-OPTION...]
          Its unit's journal.
      rename OLD NEW [--stop]
          Check first, and change nothing unless all's well; stop OLD if
          it runs (asking first, or with --stop); move its directory,
          Claude Code project, trust, worktrees and branches (OLD/* to
          NEW/*); start NEW if OLD ran.  All or nothing: if a step
          fails, it takes back those done.  rename NEW OLD takes it back.
          As root, and not from OLD itself; not for static ones (take
          them out of the system's configuration first).
      help, -h, --help
          This.

    Kinds:
      static    started by the system's configuration
      dynamic   started here: lasts, across reboots, until stopped here
      -         neither: stopped, or not started yet
    EOF
    }
    # colors, if FD (1 or 2) is a terminal, as claude-inbox has them:
    # commands, options, names, and bold for headings; none with NO_COLOR,
    # or a dumb one
    colors() {
      C_CMD= C_OPT= C_NAME= C_HEAD= C_OFF=
      test -t "$1" && test -z "''${NO_COLOR-}" || return 0
      case ''${TERM-dumb} in dumb | "") return 0 ;; esac
      local n p
      case ''${COLORTERM-} in
        truecolor | 24bit) p="38;2;230;180;80 38;2;150;150;175 38;2;100;160;240" ;;
        *)
          case $TERM in
            *256color*) n=256 ;;
            *) n=$(tput colors 2>/dev/null) || n=8 ;;
          esac
          if test "''${n:-0}" -ge 256; then p="38;5;179 38;5;103 38;5;75"
          elif test "''${n:-0}" -ge 8; then p="33 35 34"
          else return 0
          fi ;;
      esac
      set -- $p
      C_CMD=$'\e['$1m C_OPT=$'\e['$2m C_NAME=$'\e['$3m C_OFF=$'\e[0m'
      C_HEAD=$'\e[1m'
    }
    # the headings (bold), commands (where they lead a line, or follow
    # claude-remote), options and names in a text (the help, an error), in
    # their colors, if any (a colored word follows an m, so each loop ends)
    paint() {
      if test -z "$C_OFF"; then cat; return; fi
      local x='[^-A-Za-z0-9_]' c='list|inspect|start|stop|restart|attach|log|rename|help'
      sed -E \
        -e "s/^([A-Z][A-Za-z ]*:)$/$C_HEAD\1$C_OFF/" \
        -e "s/^(  )($c)($x|$)/\1$C_CMD\2$C_OFF\3/" \
        -e ":a; s/(claude-remote |, |^usage: claude-remote \[)($c|COMMAND)($x|$)/\1$C_CMD\2$C_OFF\3/; ta" \
        -e ":b; s/(^|$x)(--stop|-h|--help|JOURNALCTL-OPTION)($x|$)/\1$C_OPT\2$C_OFF\3/; tb" \
        -e ":c; s/(^|$x)(NAME|OLD|NEW)($x|$)/\1$C_NAME\2$C_OFF\3/; tc"
    }
    die() {
      colors 2
      printf 'claude-remote: %s\n' "$*" | paint >&2
      exit 1
    }
    unit() {
      printf 'claude-remote-control@%s.service' "$1"
    }
    valid() {
      case $1 in "" | .* | */* | *[[:space:]]*) return 1 ;; esac
    }
    name_arg() {
      valid "''${1-}" || die "not a remote's name: ''${1-}"
    }
    is_static() {
      case " ''${static[*]} " in *" $1 "*) true ;; *) false ;; esac
    }
    kind() {
      if is_static "$1"; then echo static
      elif test -e "$state/$1"; then echo dynamic
      else echo -
      fi
    }
    active() {
      systemctl is-active "$(unit "$1")" 2>/dev/null || :
    }
    trusted() {
      jq -e --arg d "$remotes/$1" '.projects[$d].hasTrustDialogAccepted == true' \
        "$home/.claude.json" >/dev/null 2>&1
    }
    # Claude Code's project directory for a path: every / and . a -.
    project() {
      printf '%s/.claude/projects/%s' "$home" "$(printf %s "$remotes/$1" | tr '/.' '--')"
    }
    # Every remote there is: static, dynamic, with a unit loaded, or with a
    # directory.
    names() {
      {
        printf '%s\n' "''${static[@]}"
        find "$state" "$remotes" -mindepth 1 -maxdepth 1 -printf '%f\n' 2>/dev/null
        systemctl list-units --all --plain --no-legend 'claude-remote-control@*' 2>/dev/null |
          sed -n 's/^claude-remote-control@\([^ ]*\)\.service .*/\1/p'
      } | while read -r n; do valid "$n" && echo "$n"; done | sort -u
    }
    hint_attach() {
      if ! trusted "$1"; then
        echo "$1 hasn't trusted ~claude/remotes/$1 yet: claude-remote attach $1, and answer Remote Control's questions there (C-b d to leave)."
      fi
    }

    # Renaming: every step a rename of its own (directory, project,
    # trust, branches, mark), so that rename NEW OLD takes it all back; and
    # all or nothing: each step, once done, leaves how to take it back,
    # and if one fails, those get done, last first.
    as_claude() {
      runuser -u claude -- env HOME="$home" "$@"
    }
    # The repositories, in ~claude/src (third parties', by their links).
    repos() {
      local r
      for r in "$home"/src/*/; do
        r=''${r%/}
        if test -e "$r/.git"; then printf '%s\n' "$r"; fi
      done
    }
    # Processes using PATH... (cwd, root, open files), but a remote's own
    # (by its unit's cgroup), as "PID COMMAND: FILE".
    users_of() {
      local own=$1 a pid l
      shift
      local tests=()
      for a; do tests+=(-o -lname "$a" -o -lname "$a/*"); done
      find /proc/[0-9]*/cwd /proc/[0-9]*/root /proc/[0-9]*/fd -maxdepth 1 \
          \( -false "''${tests[@]}" \) -printf '%p %l\n' 2>/dev/null |
        while read -r pid l; do
          pid=''${pid#/proc/} pid=''${pid%%/*}
          if test -n "$own" && grep -qs "/$(unit "$own")" "/proc/$pid/cgroup"; then continue; fi
          echo "$pid $(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | cut -c1-50): $l"
        done | sort -u
    }
    # A JSON file of claude's through jq ARG..., atomically, as claude.
    jq_in_place() {
      as_claude "$BASH" -c 'f=$1; shift; jq "$@" "$f" > "$f.rename" && mv "$f.rename" "$f" || { rm -f "$f.rename"; exit 1; }' \
        jq-in-place "$@"
    }
    # The trust (and the rest of the project's entry in ~/.claude.json) of
    # remote FROM, for remote TO, replacing any TO had.
    move_trust() {
      jq_in_place "$home/.claude.json" --arg o "$remotes/$1" --arg n "$remotes/$2" \
        'if .projects | has($o) then .projects[$n] = .projects[$o] | del(.projects[$o]) else . end'
    }
    # The link to the claude.ai session, in remote NAME's project, for
    # the directory DIR.
    point() {
      local p
      p=$(project "$1")/bridge-pointer.json
      if test -f "$p"; then jq_in_place "$p" -c --arg d "$2" '.dir = $d'; fi
    }
    # The worktrees "REPO WORKTREE" on stdin, in remote FROM's directory,
    # repaired, now that it's TO's (but for git's "repair: gitdir
    # incorrect", what it says goes to stderr, errors included).
    repair_worktrees() {
      local r w
      while read -r r w; do
        test -n "$r" || continue
        as_claude git -C "$r" worktree repair "$remotes/$2''${w#"$remotes/$1"}" \
          2> >(grep -v '^repair: ' >&2)
      done
    }
    # Undos, for a step that may have gone through, or half, or not:
    # The directory of remote FROM back, as TO's, if it's FROM's, with the
    # worktrees in it that were repaired already (those recorded in
    # FROM's).
    move_dir_back() {
      test -e "$remotes/$1" && ! test -e "$remotes/$2" || return 0
      local wts
      wts=$(worktrees_below "$remotes/$1")
      as_claude mv "$remotes/$1" "$remotes/$2"
      repair_worktrees "$1" "$2" <<< "$wts"
    }
    # FROM back to TO, if FROM's there and TO isn't; as claude, with a
    # third argument, as_claude.
    move_back() {
      if test -e "$1" && ! test -e "$2"; then ''${3-} mv "$1" "$2"; fi
    }
    # In REPO, the branch FROM back to TO, if there's FROM, and no TO
    # (as git branch -m can rename it, and still fail, e.g. at a
    # worktree's HEAD, which renaming it back sets right again).
    branch_back() {
      if as_claude git -C "$1" rev-parse -q --verify "refs/heads/$2" >/dev/null &&
          ! as_claude git -C "$1" rev-parse -q --verify "refs/heads/$3" >/dev/null; then
        as_claude git -C "$1" branch -m "$2" "$3"
      fi
    }
    # the worktrees the repositories record below DIR, as "REPO WORKTREE"
    worktrees_below() {
      local r g w
      repos | while read -r r; do
        for g in "$r"/.git/worktrees/*/gitdir; do
          test -f "$g" || continue
          w=$(cat "$g") w=''${w%/.git}
          case $w in "$1"/*) echo "$r $w" ;; esac
        done
      done
    }
    # After a step: how to take it back (a command line).
    undoable() {
      undos+=("$(printf '%q ' "$@")")
    }
    # The steps done, taken back, last first, if the rename didn't finish.
    take_back() {
      test -z "$finished" || return 0
      set +e
      local i failed=
      echo "claude-remote: rename $old $new failed; taking back what's done" >&2
      for ((i = ''${#undos[@]} - 1; i >= 0; i--)); do
        eval "''${undos[i]}" || { failed=1; echo "claude-remote: couldn't take back: ''${undos[i]}" >&2; }
      done
      if test -n "$failed"; then
        echo "claude-remote: not all taken back (see above); ~claude/.claude.json as it was: $backup (claude-remote list shows it, until it's removed)" >&2
      else
        rm -f "$backup"
        echo "claude-remote: all taken back: $old is as it was" >&2
      fi
    }
    do_rename() {
      # (global, for take_back, which runs on exit)
      old=$1 new=$2 undos=() finished= backup=
      local stop=$3 errs=() r n w b sha users active= wts brs
      test "$(id -u)" = 0 || die "rename: as root"
      valid "$old" || die "not a remote's name: $old"
      valid "$new" || die "not a remote's name: $new"
      test "$old" != "$new" || die "rename: $old is $new already"
      # Everything first, nothing changed unless all's well.
      test -d "$remotes/$old" || errs+=("there's no remote $old ($remotes/$old)")
      if is_static "$old"; then
        errs+=("$old is static: take it out of the system's configuration first, and deploy")
      fi
      if test -e "$remotes/$new"; then errs+=("$remotes/$new is there already"); fi
      if test -e "$(project "$new")"; then errs+=("$(project "$new") is there already"); fi
      # (but not an entry in ~/.claude.json alone: a remote writing back
      # what it read before can bring one back)
      if is_static "$new"; then errs+=("$new is static (the system's configuration)"); fi
      if test -e "$state/$new"; then errs+=("$state/$new is there already"); fi
      case $(active "$new") in inactive | failed | "") ;; *) errs+=("$(unit "$new") is $(active "$new")") ;; esac
      while read -r r; do
        n=$(as_claude git -C "$r" for-each-ref --format=x "refs/heads/$new/" | wc -l)
        test "$n" = 0 || errs+=("$r has $n branches $new/* already")
      done < <(repos)
      if grep -qs "/$(unit "$old")" /proc/self/cgroup; then
        errs+=("this runs in $old: rename it from elsewhere (a root shell, another remote)")
      fi
      users=$(users_of "$old" "$remotes/$old" "$(project "$old")")
      if test -n "$users"; then
        errs+=("in use, by more than $old itself: $(printf '\n  %s' "$users")")
      fi
      exec 9> /run/claude-remote-rename.lock
      flock -n 9 || errs+=("another rename is running")
      if test ''${#errs[@]} -gt 0; then
        printf 'claude-remote: rename %s %s: no:\n' "$old" "$new" >&2
        printf -- '- %s\n' "''${errs[@]}" >&2
        exit 1
      fi
      case $(active "$old") in
        inactive | failed | "") ;;
        *)
          active=1
          if test -z "$stop"; then
            test -t 0 || die "rename: $old is running: stop it first, or --stop"
            read -r -p "$old is running: stop it (which ends its sessions)? [y/N] " n
            case $n in y | Y | yes) ;; *) die "rename: not stopping $old" ;; esac
          fi
      esac

      wts=$(worktrees_below "$remotes/$old")
      brs=$(repos | while read -r r; do
        as_claude git -C "$r" for-each-ref --format="$r %(refname:short)" "refs/heads/$old/"
      done)
      backup=$(mktemp "''${state%/*}"/rename-backup.XXXXXX.claude.json)
      cp -a "$home/.claude.json" "$backup"
      trap take_back EXIT

      # Each step's undo first, which looks at what's there, so that it
      # takes back a step that went through, or half of one, and leaves
      # alone what didn't happen.
      if test -n "$active"; then
        undoable systemctl start "$(unit "$old")"
        systemctl stop "$(unit "$old")"
        users=$(users_of "" "$remotes/$old" "$(project "$old")")
        test -z "$users" || die "rename: $old still in use, once stopped:$(printf '\n  %s' "$users")"
      fi
      # a dynamic remote's mark, if a stop didn't end well (else, at the
      # next boot, OLD would start again, anew)
      if test -e "$state/$old"; then
        undoable move_back "$state/$new" "$state/$old"
        mv "$state/$old" "$state/$new"
      fi
      if test -e "$(project "$old")"; then
        undoable move_back "$(project "$new")" "$(project "$old")" as_claude
        as_claude mv "$(project "$old")" "$(project "$new")"
      fi
      undoable move_dir_back "$new" "$old"
      as_claude mv "$remotes/$old" "$remotes/$new"
      repair_worktrees "$old" "$new" <<< "$wts"
      while read -r r b; do
        test -n "$r" || continue
        undoable branch_back "$r" "$new/''${b#"$old"/}" "$b"
        as_claude git -C "$r" branch -m "$b" "$new/''${b#"$old"/}"
      done <<< "$brs"
      undoable move_trust "$new" "$old"
      move_trust "$old" "$new"
      undoable point "$new" "$remotes/$old"
      point "$new" "$remotes/$new"
      if test -n "$active"; then
        # the trust again, in case a remote wrote .claude.json since, from
        # what it had read before
        move_trust "$old" "$new"
        undoable systemctl stop "$(unit "$new")"
        systemctl start "$(unit "$new")"
      fi
      finished=1
      rm -f "$backup"

      echo "renamed $old to $new: $(grep -c . <<< "$wts") worktrees, $(grep -c . <<< "$brs") branches$(test -z "$active" || echo ", and started it")."
      local mentions
      mentions=$(grep -lw -- "$old" "$home"/CLAUDE.md "$remotes/$new"/CLAUDE.md 2>/dev/null || :)
      if test -n "$mentions"; then
        echo "These mention $old still:"
        printf '  %s\n' $mentions
      fi
      echo "Check $new: claude-remote inspect $new, and claude.ai.  To take it back: claude-remote rename $new $old"
    }

    cmd=''${1-list}
    shift || :
    case $cmd in
      list)
        printf '%-20s %-8s %-12s %s\n' NAME KIND STATE TRUSTED
        names | while read -r n; do
          printf '%-20s %-8s %-12s %s\n' "$n" "$(kind "$n")" "$(active "$n")" "$(trusted "$n" && echo yes || echo no)"
        done
        # not to be forgotten: copies of ~claude/.claude.json, kept by a
        # rename that couldn't take back all it had done
        for n in "''${state%/*}"/rename-backup.*; do
          if test -e "$n"; then echo "(kept by a rename that failed: $n)"; fi
        done
        ;;
      rename)
        stop=
        args=()
        for a; do
          case $a in
            --stop) stop=1 ;;
            -*) die "rename: $a: no such option (claude-remote -h)" ;;
            *) args+=("$a")
          esac
        done
        test ''${#args[@]} = 2 || die "rename OLD NEW [--stop] (claude-remote -h)"
        do_rename "''${args[0]}" "''${args[1]}" "$stop"
        ;;
      inspect)
        name_arg "''${1-}"
        n=$1
        echo "remote:    $n ($(kind "$n"))"
        echo "unit:      $(unit "$n"): $(systemctl show --value -p ActiveState,SubState "$(unit "$n")" | paste -sd/), since $(systemctl show --value -p StateChangeTimestamp "$(unit "$n")")"
        echo "directory: $remotes/$n$(test -d "$remotes/$n" || echo ' (not there yet)')"
        echo "trusted:   $(trusted "$n" && echo yes || echo no)"
        p=$(project "$n")/bridge-pointer.json
        if test -f "$p"; then
          echo "claude.ai: $(jq -r '"session \(.sessionId), environment \(.environmentId)"' "$p")"
        fi
        if test -S /run/claude/"$n"/tmux; then
          echo "terminal (claude-remote attach $n):"
          tmux -S /run/claude/"$n"/tmux capture-pane -p -t claude -S -15 | sed '/^$/d; s/^/  /'
        fi
        hint_attach "$n"
        ;;
      start)
        name_arg "''${1-}"
        systemctl start "$(unit "$1")"
        if ! is_static "$1"; then
          echo "$1 is dynamic: it lasts, across reboots, until claude-remote stop $1."
        fi
        hint_attach "$1"
        ;;
      stop | restart)
        name_arg "''${1-}"
        systemctl "$cmd" "$(unit "$1")"
        ;;
      attach)
        n=''${1:-main}
        name_arg "$n"
        test -S /run/claude/"$n"/tmux || die "$n isn't running (claude-remote start $n)"
        exec tmux -S /run/claude/"$n"/tmux attach -t claude
        ;;
      log)
        name_arg "''${1-}"
        n=$1
        shift
        exec journalctl -u "$(unit "$n")" "$@"
        ;;
      names)  # for the completion
        names
        ;;
      help | -h | --help)
        colors 1
        usage | paint
        ;;
      *)
        die "$cmd: no such command (claude-remote -h)"
    esac
  '';

  completion = writeText "claude-remote-completion" ''
    _claude_remote() {
      local cur=''${COMP_WORDS[COMP_CWORD]}
      if [ "$COMP_CWORD" -eq 1 ]; then
        COMPREPLY=($(compgen -W "list inspect start stop restart attach log rename help" -- "$cur"))
      elif [ "$COMP_CWORD" -eq 2 ]; then
        case ''${COMP_WORDS[1]} in
          inspect | start | stop | restart | attach | log | rename)
            COMPREPLY=($(compgen -W "$(claude-remote names 2>/dev/null)" -- "$cur")) ;;
        esac
      elif [ "''${COMP_WORDS[1]}" = rename ]; then
        COMPREPLY=($(compgen -W "--stop" -- "$cur"))
      fi
    }
    complete -F _claude_remote claude-remote
  '';
in
runCommand "claude-remote" { meta.mainProgram = "claude-remote"; } ''
  install -D -m 755 ${script} $out/bin/claude-remote
  install -D -m 644 ${completion} $out/share/bash-completion/completions/claude-remote
''