summaryrefslogtreecommitdiffstats
path: root/pkgs/claude-remote.nix
blob: d0da6524c0bb1ae798605cdcbc8d74d119fbb3fe (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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# 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), of
    # either kind: Remote Control servers, and interactive sessions.
    wants=$(systemctl show --value -p Wants multi-user.target 2>/dev/null | tr ' ' '\n')
    static=($(sed -n 's/^claude-remote-control@\(.*\)\.service$/\1/p' <<< "$wants"))
    staticI=($(sed -n 's/^claude-interactive@\(.*\)\.service$/\1/p' <<< "$wants"))
    state=${lib.escapeShellArg stateDir}
    # interactive sessions: the dynamic ones, meant to run, and the ids of
    # their sessions (which make a remote interactive), see configs/claude.nix
    istate=''${state%/*}/interactive
    sessions=''${state%/*}/interactive-sessions
    home=/home/claude
    remotes=$home/remotes

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

    The remotes, working in ~claude/remotes/NAME, each a Claude Code Remote
    Control server (claude-remote-control@NAME), or an interactive session
    with Remote Control (claude-interactive@NAME), as their TYPE says.

    Commands:
      list (the default)
          The remotes: name, type, 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 [--type=server|interactive]
      restart NAME [--type=server|interactive]
          Start a remote (or restart it); a dynamic one lasts, across
          reboots, until stop.  --type: a Remote Control server (server),
          or an interactive session with Remote Control (interactive;
          --interactive for short), with more memory and CPU, and its
          session archived on claude.ai while it's stopped.  A new one is
          made so (default: server); an existing one of the other type
          changes (stopped, if it runs): to interactive, it resumes its
          latest session; to server, the session it had as one.  Without
          --type, a remote starts as the type it is.  Not for a static
          one, whose type is the system's configuration's.
      stop 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).
      reset NAME [-f|--force]
          Forget its claude.ai session (its link to it moved aside, or an
          interactive one's session id replaced), so that it starts with a
          new one: stopped, if it runs, and started again.  Then its old
          session and environment can go, on claude.ai (deleting them
          there first leaves it a link to a session that's gone, which it
          can't resume).
      remove NAME [-f|--force]
          Retire it: stop it, and move its directory and Claude Code
          project to ~claude/remotes/.removed/NAME-DATE (worktrees in it
          repaired); its branches and its trust stay.  Then its session
          and environment can go, on claude.ai.  Not for static ones.
          reset and remove ask first (y/N), unless -f; as root, and not
          from the remote itself; all or nothing, like rename.
      help, -h, --help
          This.

    Kinds:
      static    started by the system's configuration
      dynamic   started here, or static until taken out of the
                configuration: 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|reset|remove|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|--interactive|--type|-f|--force|-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
    }
    # interactive: static as such, or with a session id
    is_interactive() {
      case " ''${staticI[*]} " in *" $1 "*) return 0 ;; esac
      test -e "$sessions/$1"
    }
    # NAME's unit, of its kind
    unit() {
      if is_interactive "$1"; then
        printf 'claude-interactive@%s.service' "$1"
      else
        printf 'claude-remote-control@%s.service' "$1"
      fi
    }
    type_of() {
      if is_interactive "$1"; then echo interactive; else echo server; fi
    }
    valid() {
      case $1 in "" | .* | */* | *[[:space:]]*) return 1 ;; esac
    }
    name_arg() {
      valid "''${1-}" || die "not a remote's name: ''${1-}"
    }
    is_static() {
      case " ''${static[*]} ''${staticI[*]} " in *" $1 "*) true ;; *) false ;; esac
    }
    kind() {
      if is_static "$1"; then echo static
      elif test -e "$state/$1" || test -e "$istate/$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, of either kind.
    names() {
      {
        printf '%s\n' "''${static[@]}" "''${staticI[@]}"
        find "$state" "$istate" "$sessions" "$remotes" -mindepth 1 -maxdepth 1 -printf '%f\n' 2>/dev/null
        systemctl list-units --all --plain --no-legend 'claude-remote-control@*' 'claude-interactive@*' 2>/dev/null |
          sed -n 's/^claude-\(remote-control\|interactive\)@\([^ ]*\)\.service .*/\2/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 command (doing)
    # didn't finish.
    take_back() {
      test -z "$finished" || return 0
      set +e
      local i failed=
      echo "claude-remote: $doing 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)''${backup:+; ~claude/.claude.json as it was: $backup (claude-remote list shows it, until removed)}" >&2
      else
        if test -n "$backup"; then rm -f "$backup"; fi
        echo "claude-remote: all taken back: as it was" >&2
      fi
    }
    # QUESTION, answered y, on a terminal, unless with -f (force)
    confirm() {
      test -z "$force" || return 0
      test -t 0 || die "$1 (asks first, on a terminal, or -f)"
      local a
      read -r -p "$1 [y/N] " a
      case $a in y | Y | yes) ;; *) die "not done" ;; esac
    }
    # NAME, as a remote of TYPE (server, interactive) from now on: stopped,
    # if it runs, and left so.  To an interactive session, it resumes its
    # latest session (its latest transcript), or else starts a new one; to
    # a Remote Control server, its session id goes (kept, as a dot file,
    # which names() passes over), and it resumes the session its link
    # points to.  (On claude.ai, the session of the other type stays, or
    # gets archived, as Remote Control has it.)  Not for a static one,
    # whose type is the system's configuration's.
    change_type() {
      local name=$1 type=$2 t id
      test "$(id -u)" = 0 || die "--type: as root"
      if is_static "$name"; then
        die "$name is static, as $(type_of "$name"): its type is the system's configuration's"
      fi
      if grep -qs "/$(unit "$name")" /proc/self/cgroup; then
        die "this runs in $name: change its type from elsewhere (a root shell, another remote)"
      fi
      # (global, for take_back, which runs on exit)
      doing="$name, as $type" undos=() finished= backup=
      trap take_back EXIT
      case $(active "$name") in
        inactive | failed | "") ;;
        *)
          undoable systemctl start "$(unit "$name")"
          systemctl stop "$(unit "$name")"
      esac
      if test "$type" = interactive; then
        t=$(ls -t "$(project "$name")"/*.jsonl 2>/dev/null | head -n 1 || :)
        if test -n "$t"; then
          id=$(basename "$t" .jsonl)
        else
          id=$(cat /proc/sys/kernel/random/uuid)
        fi
        undoable rm -f "$sessions/$name"
        printf '%s\n' "$id" > "$sessions/$name"
      else
        undoable mv -f "$sessions/.$name.old" "$sessions/$name"
        mv -f "$sessions/$name" "$sessions/.$name.old"
      fi
      finished=1
      trap - EXIT
    }
    # Remote NAME's claude.ai session forgotten (its link to it in its
    # project moved aside, to bridge-pointer.json.old), so that it starts
    # with a new one: stopped, if it runs, and started again.
    do_reset() {
      local name=$1 p ids active=
      test "$(id -u)" = 0 || die "reset: as root"
      valid "$name" || die "not a remote's name: $name"
      test -d "$remotes/$name" || die "there's no remote $name ($remotes/$name)"
      if grep -qs "/$(unit "$name")" /proc/self/cgroup; then
        die "reset: this runs in $name: reset it from elsewhere (a root shell, another remote)"
      fi
      # what it has: an interactive one, its session id (and maybe a
      # link, too); a Remote Control server, the link to its session
      p=$(project "$name")/bridge-pointer.json
      if is_interactive "$name"; then
        test -s "$sessions/$name" || die "$name has no session id to forget ($sessions/$name)"
        ids="session $(cat "$sessions/$name")"
      else
        test -f "$p" || die "$name has no claude.ai session to forget ($p)"
        ids=$(jq -r '"session \(.sessionId), environment \(.environmentId)"' "$p")
      fi
      case $(active "$name") in inactive | failed | "") ;; *) active=1 ;; esac
      if test -n "$active"; then
        confirm "reset $name: stop it (which ends its sessions), forget its claude.ai $ids, and start it again, with a new one?"
      else
        confirm "reset $name: forget its claude.ai $ids, for a new one at its next start?"
      fi
      # (global, for take_back, which runs on exit)
      doing="reset $name" undos=() finished= backup=
      trap take_back EXIT
      if test -n "$active"; then
        undoable systemctl start "$(unit "$name")"
        systemctl stop "$(unit "$name")"
      fi
      if test -f "$p"; then
        undoable move_back "$p.old" "$p" as_claude
        as_claude mv -f "$p" "$p.old"
      fi
      # an interactive one, a new session id (the old one kept, as a dot
      # file, which names() passes over)
      if is_interactive "$name" && test -s "$sessions/$name"; then
        cp "$sessions/$name" "$sessions/.$name.old"
        undoable mv -f "$sessions/.$name.old" "$sessions/$name"
        cat /proc/sys/kernel/random/uuid > "$sessions/$name"
      fi
      if test -n "$active"; then
        undoable systemctl stop "$(unit "$name")"
        systemctl start "$(unit "$name")"
      fi
      finished=1
      echo "reset $name$(test -z "$active" || echo ", and started it again"): its old claude.ai $ids can go, on claude.ai."
    }
    # Remote NAME, retired: stopped, and its directory and Claude Code
    # project moved to ~/remotes/.removed/NAME-DATE (remote, project),
    # with the worktrees in it repaired; its branches and its trust stay.
    do_remove() {
      local name=$1 dest rel users active= wts p n ids=
      test "$(id -u)" = 0 || die "remove: as root"
      valid "$name" || die "not a remote's name: $name"
      test -d "$remotes/$name" || die "there's no remote $name ($remotes/$name)"
      if is_static "$name"; then
        die "$name is static: take it out of the system's configuration first, and deploy"
      fi
      if grep -qs "/$(unit "$name")" /proc/self/cgroup; then
        die "remove: this runs in $name: remove it from elsewhere (a root shell, another remote)"
      fi
      users=$(users_of "$name" "$remotes/$name" "$(project "$name")")
      test -z "$users" || die "remove: $name is in use, by more than itself:$(printf '\n  %s' "$users")"
      rel=.removed/$name-$(date -u +%Y%m%dT%H%M%SZ)
      dest=$remotes/$rel
      test ! -e "$dest" || die "remove: $dest is there already"
      case $(active "$name") in inactive | failed | "") ;; *) active=1 ;; esac
      p=$(project "$name")/bridge-pointer.json
      if test -f "$p"; then
        ids=$(jq -r '"session \(.sessionId), environment \(.environmentId)"' "$p")
      fi
      if test -s "$sessions/$name"; then ids="session $(cat "$sessions/$name")"; fi
      confirm "remove $name: $(test -z "$active" || echo "stop it (which ends its sessions), and ")move its directory and Claude Code project to $dest?"
      # (global, for take_back, which runs on exit)
      doing="remove $name" undos=() finished= backup=
      trap take_back EXIT
      if test -n "$active"; then
        undoable systemctl start "$(unit "$name")"
        systemctl stop "$(unit "$name")"
        users=$(users_of "" "$remotes/$name" "$(project "$name")")
        test -z "$users" || die "remove: $name still in use, once stopped:$(printf '\n  %s' "$users")"
      fi
      # its mark, if a stop didn't end well (else, at the next boot, it
      # would start again, anew)
      if test -e "$state/$name"; then
        undoable touch "$state/$name"
        rm -f "$state/$name"
      fi
      undoable as_claude rmdir --ignore-fail-on-non-empty "$dest" "$remotes/.removed"
      as_claude mkdir -p "$dest"
      # an interactive one's mark, and its session id, with the rest
      if test -e "$istate/$name"; then
        undoable touch "$istate/$name"
        rm -f "$istate/$name"
      fi
      if test -e "$sessions/$name"; then
        undoable move_back "$dest/interactive-session" "$sessions/$name"
        mv "$sessions/$name" "$dest/interactive-session"
      fi
      wts=$(worktrees_below "$remotes/$name")
      undoable move_dir_back "$rel/remote" "$name"
      as_claude mv "$remotes/$name" "$dest/remote"
      repair_worktrees "$name" "$rel/remote" <<< "$wts"
      if test -e "$(project "$name")"; then
        undoable move_back "$dest/project" "$(project "$name")" as_claude
        as_claude mv "$(project "$name")" "$dest/project"
      fi
      finished=1
      n=$(repos | while read -r r; do
        as_claude git -C "$r" for-each-ref --format=x "refs/heads/$name/"
      done | wc -l)
      echo "removed $name: in $dest, with $(grep -c . <<< "$wts") worktrees; its $n branches $name/* stay, and so does its trust."
      if test -n "$ids"; then echo "Its claude.ai $ids can go, on claude.ai."; fi
      echo "To bring it back: mv $dest/remote $remotes/$name, mv $dest/project $(project "$name")$(test ! -e "$dest/interactive-session" || echo ", mv $dest/interactive-session $sessions/$name"), git worktree repair in each of its worktrees, claude-remote reset -f $name (its old session, deleted, can't be resumed), and claude-remote start $name."
    }
    do_rename() {
      # (global, for take_back, which runs on exit)
      old=$1 new=$2 undos=() finished= backup= doing="rename $1 $2"
      local stop=$3 errs=() r n w b d 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
      for d in "$istate" "$sessions"; do
        if test -e "$d/$new"; then errs+=("$d/$new is there already"); fi
      done
      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
      # an interactive one's session id, and its mark
      for d in "$sessions" "$istate"; do
        if test -e "$d/$old"; then
          undoable move_back "$d/$new" "$d/$old"
          mv "$d/$old" "$d/$new"
        fi
      done
      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 %-12s %-8s %-12s %s\n' NAME TYPE KIND STATE TRUSTED
        names | while read -r n; do
          printf '%-20s %-12s %-8s %-12s %s\n' "$n" "$(type_of "$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"
        ;;
      reset | remove)
        force=
        args=()
        for a; do
          case $a in
            -f | --force) force=1 ;;
            -*) die "$cmd: $a: no such option (claude-remote -h)" ;;
            *) args+=("$a")
          esac
        done
        test ''${#args[@]} = 1 || die "$cmd NAME [-f|--force] (claude-remote -h)"
        "do_$cmd" "''${args[0]}"
        ;;
      inspect)
        name_arg "''${1-}"
        n=$1
        echo "remote:    $n ($(type_of "$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)"
        if test -s "$sessions/$n"; then
          echo "session:   $(cat "$sessions/$n") (resumed at each start)"
        fi
        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 | restart)
        type=
        args=()
        for a; do
          case $a in
            --interactive) type=interactive ;;
            --type=server | --type=interactive) type=''${a#--type=} ;;
            --type=*) die "$cmd: $a: the type is server or interactive" ;;
            -*) die "$cmd: $a: no such option (claude-remote -h)" ;;
            *) args+=("$a")
          esac
        done
        test ''${#args[@]} = 1 || die "$cmd NAME [--type=server|interactive] (claude-remote -h)"
        n=''${args[0]}
        name_arg "$n"
        # before the login, the unit would be skipped, and not come back
        test -e "$home/.claude/.credentials.json" ||
          die "there's no login yet: runuser -l claude -c 'claude auth login' (then the remotes start)"
        # of the type asked for: a new one, made so; an existing one of the
        # other type, changed (stopped, if it runs); without --type, of the
        # type it is (a new one, a server)
        if test -n "$type" && test "$(type_of "$n")" != "$type"; then
          if test -d "$remotes/$n" || test -d "$(project "$n")"; then
            change_type "$n" "$type"
            cmd=start
          else
            ! is_static "$n" || die "$n is static, as $(type_of "$n"): its type is the system's configuration's"
            test "$(id -u)" = 0 || die "--type=interactive: as root"
            cat /proc/sys/kernel/random/uuid > "$sessions/$n"
          fi
        fi
        systemctl "$cmd" "$(unit "$n")"
        if ! is_static "$n"; then
          echo "$n is dynamic: it lasts, across reboots, until claude-remote stop $n."
        fi
        if is_interactive "$n"; then
          echo "$n is an interactive session ($(cat "$sessions/$n" 2>/dev/null)): claude-remote attach $n for its terminal, or claude.ai while it runs."
        fi
        hint_attach "$n"
        ;;
      stop)
        name_arg "''${1-}"
        systemctl stop "$(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")" "$@"
        ;;
      type)  # for the completion
        name_arg "''${1-}"
        type_of "$1"
        ;;
      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 reset remove help" -- "$cur"))
      elif [ "$COMP_CWORD" -eq 2 ]; then
        case ''${COMP_WORDS[1]} in
          inspect | start | stop | restart | attach | log | rename | reset | remove)
            COMPREPLY=($(compgen -W "$(claude-remote names 2>/dev/null)" -- "$cur")) ;;
        esac
      elif [ "''${COMP_WORDS[1]}" = reset ] || [ "''${COMP_WORDS[1]}" = remove ]; then
        COMPREPLY=($(compgen -W "-f --force" -- "$cur"))
      elif [ "''${COMP_WORDS[1]}" = start ] || [ "''${COMP_WORDS[1]}" = restart ]; then
        # --type=TYPE (which bash splits into --type, =, TYPE): only the
        # type it isn't (a new one is a server)
        local prev=''${COMP_WORDS[COMP_CWORD-1]} other=interactive
        [ "$(claude-remote type "''${COMP_WORDS[2]}" 2>/dev/null)" != interactive ] || other=server
        if [ "$cur" = = ] && [ "$prev" = --type ]; then
          COMPREPLY=($other)
        elif [ "$prev" = = ] && [ "''${COMP_WORDS[COMP_CWORD-2]}" = --type ]; then
          COMPREPLY=($(compgen -W "$other" -- "$cur"))
        else
          COMPREPLY=($(compgen -W "--type= $([ $other = server ] || echo --interactive)" -- "$cur"))
          [ "''${COMPREPLY[*]}" != --type= ] || compopt -o nospace
        fi
      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
''