Repository navigation
Expand file tree
/
Copy pathmin-zed
More file actions
executable file
·1704 lines (1607 loc) · 80 KB
/
Copy pathmin-zed
File metadata and controls
executable file
·1704 lines (1607 loc) · 80 KB
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# min-zed — Minimal sessions as Zed remote projects.
#
# min names a session, and it is reached as `min-zed.NAME`: stock ssh whose
# ProxyCommand runs an OpenSSH sshd *inside* the box through
# `min session exec`. `open` makes the session, writes its ssh stanza and
# Zed's ssh_connections entry, then runs `zed ssh://min-zed.NAME/workbench`.
#
# Layout: tool constants, then transport, ssh and session plumbing, then the
# Zed layer, whose first block holds every editor-specific value.
set -eu
# ---- tool constants ------------------------------------------------------------
TOOL=min-zed
LOADOUT=zed
HOST_PREFIX=min-zed.
ENV_PREFIX=MIN_ZED
STATE=${MIN_ZED_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/min-zed}
# The Zed layer below may define the hooks client_linked NAME (0: its UI
# holds the session), client_on_connect NAME and client_on_destroy NAME;
# undefined ones do nothing.
eval "DEBUG=\${${ENV_PREFIX}_DEBUG:-}"
SSH_KEYGEN=${SSH_KEYGEN_BIN:-ssh-keygen}
SELF=$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")
# GUI apps and hooks run us with a bare system PATH (tests turn this off).
[ "${MIN_NO_PATH_EXTEND:-}" = 1 ] || PATH=$PATH:/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin
SSH_DIR=$HOME/.ssh
SSH_CONF=$SSH_DIR/$TOOL.conf # one `Host <prefix>NAME` stanza per session; ours
SSH_MAIN=$SSH_DIR/config # the user's; gets a marked Include at the top
SSH_MARK1="# $TOOL ssh-config (remove with: $TOOL ssh-config --remove)"
SSH_MARK2="Include ~/.ssh/$TOOL.conf"
# What the first min-<client> ssh-config created under ~/.ssh (`dir`,
# `config`), one word per line; shared by every tool, so whichever removes
# the last Include deletes them.
SSH_CREATED=${XDG_STATE_HOME:-$HOME/.local/state}/min-clients/ssh-config-created
SSH_LOCK=${SSH_CREATED%/*}/ssh-config.lock # held by any tool rewriting ~/.ssh/config
die() { printf '%s: %s\n' "$TOOL" "$*" >&2; exit 1; }
log() { printf '[%s] %s\n' "$TOOL" "$*" >&2; }
dbg() { [ -n "$DEBUG" ] && log "$@"; return 0; }
# hook NAME ARGS...: the client layer's NAME when it defines one. Undefined,
# client_linked says "not linked" and the others do nothing.
hook() {
if command -v "$1" >/dev/null 2>&1; then "$@"; return; fi
[ "$1" != client_linked ]
}
# ---- transport -------------------------------------------------------------
# Absolute path of the min binary: it becomes the ssh ProxyCommand, which
# /usr/bin/ssh runs without the user's shell functions or PATH.
resolve_min() {
m=${MIN_BIN:-min}
case $m in
/*) ;;
*) m=$(command -v "$m" 2>/dev/null) || die "min not found on PATH (set MIN_BIN)" ;;
esac
[ -x "$m" ] || die "min is not executable: $m"
printf '%s' "$m"
}
# Quote one word for `sh -c` (ssh runs ProxyCommand through the shell) and
# double every % so ssh's own token expansion leaves it alone.
shq() {
case $1 in
'') printf "''" ;;
*[!A-Za-z0-9/._+:@,=-]*) printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" ;;
*) printf '%s' "$1" ;;
esac
}
pct() { printf '%s' "$1" | sed 's/%/%%/g'; }
mn() { "$MIN" "$@"; }
# min_ls: min ls --json, printed only when it is one session list (one JSON
# value whose .sessions is an array of objects): anything else (a warning
# line, a log line before it, nothing at all) fails like a failed min ls, so
# no caller reads it as "no box".
min_ls() {
ml_j=$(mn ls --json </dev/null) || return 1
printf '%s' "$ml_j" | jq -se 'length == 1 and (.[0].sessions | type == "array")
and all(.[0].sessions[]; type == "object")' >/dev/null 2>&1 || return 1
printf '%s\n' "$ml_j"
}
# ---- box ids ---------------------------------------------------------------
# Since min 0.8 (gominimal/minimal#2756) a session name is an alias several
# boxes may share: a stopped box keeps its name and a new box may take it,
# and min resolves a name to the running box, else the latest. min resolves
# a full session id before a name, so every min call aimed at one of our
# boxes passes the id min-zed recorded for it in sessions/NAME/id; NAME stays
# the handle (the ssh alias, the key dir, the ssh_connections entry, the
# CLI's arguments).
ID_ERE='[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
# stored_id NAME: the id in sessions/NAME/id, re-checked on read (it reaches
# min's command line and the stanzas); status 1 when there is none (or NAME
# is no session name: no path outside sessions/), 2 when it is no session id.
stored_id() {
valid_name "$1" || return 1
si_f=$(sess_dir "$1")/id
[ -e "$si_f" ] || return 1
si=$(cat "$si_f" 2>/dev/null) && fact_ok "$ID_ERE" "$si" || return 2
printf '%s' "$si"
}
# pick_id NAME LS: the id of NAME's box in LS (min ls --json), printed.
# Status 0: own: the recorded id, listed as NAME; or, for a key dir with no
# id (made before ids were recorded), the one box named NAME, whose id is
# then recorded. 4: not own, the one box named NAME, and no id recorded
# for NAME (only an explicit NAME may reach it). 1: no box for NAME. 2:
# several boxes named NAME, no id recorded. 3: sessions/NAME/id is no
# session id. 7: the one box named NAME, no id recorded, and min lists it
# with no session id (null, or not a UUID): nothing to reach it by. 8: LS
# could not be read (never "none"). A NAME that is no session name is 1.
# A recorded id is never traded for a box found by name: 5, ours is gone
# (min ls lists the id nowhere; prints how many boxes now have the name);
# 6, ours was renamed outside min-zed (min lists the id under another
# name, or none: prints it, or "(no name)").
# PICK_NOADOPT=1: a key dir from before ids still counts as own, but its id
# is not written. own_filter always sets it, so no list adopts; open and
# destroy set it too (open's prepare records the id once the box checks
# out; destroy never records one). attach, ssh and _proxy adopt the one box
# they act on (box_id/need_box), and prepare writes its id.
PICK_NOADOPT=
pick_id() {
valid_name "$1" || return 1
pi_s=0; pi_r=$(stored_id "$1") || pi_s=$?
[ "$pi_s" != 2 ] || return 3
# listed at all is asked apart from the name: min's name may be null
pi_l=$(printf '%s' "$2" | jq -r --arg n "$1" --arg r "$pi_r" '
($r != "" and any(.sessions[]?; .id == $r)) as $listed
| ([.sessions[]? | select(.id == $r) | .name][0]) as $rn
| [.sessions[]? | select(.name == $n) | .id // ""]
| if $listed and $rn == $n then "own \($r)" elif $listed then "renamed \($rn // "(no name)")"
elif $r != "" then "gone \(length)"
elif length == 1 then "one \(.[0])" elif length == 0 then "none" else "several" end' 2>/dev/null) || return 8
case $pi_l in
"own "*) printf '%s' "${pi_l#own }"; return 0 ;;
"renamed "*) printf '%s' "${pi_l#renamed }"; return 6 ;;
"gone "*) printf '%s' "${pi_l#gone }"; return 5 ;;
"one "*) pi_i=${pi_l#one } ;;
several) return 2 ;;
*) return 1 ;;
esac
fact_ok "$ID_ERE" "$pi_i" || return 7 # min gave it no id to reach it by
printf '%s' "$pi_i"
[ "$pi_s" = 1 ] && [ -d "$(sess_dir "$1")" ] || return 4
[ "$PICK_NOADOPT" = 1 ] || put "$(sess_dir "$1")/id" "$pi_i" || : # a key dir from before ids: adopted
}
# box_id NAME LS [own]: BID = pick_id's id for NAME. Its statuses (not
# pick_id's): 0 found (with own, only an own box counts); 1 none (BID
# empty; ours, if any, is gone and no box has the name); 2 no id to trust
# (several boxes named NAME, a bad id file, ours renamed outside min-zed,
# a box min lists without an id, a min ls it could not read, a NAME that is
# no session name):
# BWHY says why, never let min pick one by name; 5 ours is gone and
# another box has the name now (BWHY): never that one.
box_id() {
BID='' BWHY=''
if ! valid_name "$1"; then
BWHY="session name is not lowercase letters, digits and dashes; not using it: $(printf '%s' "$1" | LC_ALL=C tr -c '[:print:]' '?')"
return 2
fi
bi_s=0; BID=$(pick_id "$1" "$2") || bi_s=$?
case $bi_s in
0) return 0 ;;
4) [ "${3:-}" = own ] || return 0 ;;
2) if [ -d "$(sess_dir "$1")" ]; then
BWHY="several boxes are named $1, and $TOOL cannot tell which is its own: give the others new names (min ls --json shows their ids; min session rename ID NEW), or remove $(sess_dir "$1") to let go of it"
else
BWHY="Several boxes are named $1, and none is $TOOL's. Give the others new names with: min session rename ID NEW (min ls --json lists their ids)."
fi ;;
8) BWHY="could not read min ls; not looking up $1 in it" ;;
7) BWHY="min lists box $1 with no session id, so $TOOL cannot reach it by one and leaves it alone" ;;
3) BWHY="$(sess_dir "$1")/id is not a session id; not using it (write the box's id from min ls --json into it, or remove $(sess_dir "$1") if the box is gone)" ;;
5) if [ "$BID" != 0 ]; then
BID=; BWHY="your box $1 is gone; another box now has the name (remove $(sess_dir "$1") to reach it)"; return 5
fi ;;
6) bi_r=$(stored_id "$1" || :)
if [ "$BID" = "(no name)" ]; then BWHY="min lists box $1 with no name now, so $TOOL leaves it alone. To use it here again: min session rename $bi_r $1."
else BWHY="$1 was renamed outside $TOOL, to $BID. To use it here again: min session rename $bi_r $1."; fi ;;
esac
BID=
[ -z "$BWHY" ] || return 2
return 1
}
# need_box NAME [own]: BID for NAME (box_id) from a fresh min ls, kept in
# BLS; dies when min ls fails or there is none to trust.
need_box() {
BLS=$(min_ls) || die "min ls failed"
nb_s=0; box_id "$1" "$BLS" "${2:-}" || nb_s=$?
case $nb_s in
0) ;;
1) die "no session named $1" ;;
*) die "$BWHY" ;;
esac
}
# own_filter: min ls --json on stdin, narrowed to the sessions this tool has
# prepared: a key dir under $STATE/sessions whose recorded id min lists under
# the dir's name (pick_id: a box renamed outside min-zed, or another tool's
# box of the same name, is not own). gc, orphan reminders, open's reuse,
# new's offer, destroy's cwd lookup, the pickers, completions, the ssh
# stanzas and the ssh_connections entries use only these: other tools' boxes
# are theirs. Fails with its jq, so a failure never passes as an empty list.
# Never adopts: a list is no box acted on (box_id on the chosen NAME adopts).
# own_ls: the same from min ls.
own_filter() {
of_j=$(cat)
of_k=$(for s in "$STATE"/sessions/*/; do
[ -d "$s" ] || continue
s=${s%/}; s=${s##*/}
valid_name "$s" || continue
if of_i=$(PICK_NOADOPT=1; pick_id "$s" "$of_j"); then printf '%s\n' "$of_i"; fi
done)
printf '%s' "$of_j" | jq --arg k "$of_k" '($k | split("\n")) as $k | .sessions |= map(select(.id as $i | $k | index([$i])))'
}
own_ls() { ol_j=$(min_ls) || return 1; printf '%s' "$ol_j" | own_filter; }
# own_names LS: the names own_filter keeps in LS, one per line; fails with it.
own_names() { on_j=$(printf '%s' "$1" | own_filter) || return 1; printf '%s' "$on_j" | jq -r '.sessions[].name'; }
# id_field ID FIELD [LS]: FIELD (id | name | project_path | status | branch)
# of the session with id ID, in LS or a fresh min ls; empty when none.
id_field() {
if [ $# -ge 3 ]; then if_j=$3; else if_j=$(min_ls) || return 0; fi
printf '%s' "$if_j" | jq -r --arg i "$1" --arg f "$2" '[.sessions[] | select(.id == $i)
| if $f == "branch" then (.git.branch // empty) else (.[$f] // empty) end][0] // empty'
}
# live_box PATH: an own list (own_filter) on stdin; the name of its live
# session for PATH, if any, when the name is a hostname: what open reuses and
# new offers.
live_box() {
jq -r --arg p "$1" '[.sessions[] | select(.status == "active" and .project_path == $p
and (.name | test("^[a-z0-9][a-z0-9-]*$"))) | .name][0] // empty'
}
# ---- keys and facts --------------------------------------------------------
sess_dir() { printf '%s/sessions/%s' "$STATE" "$1"; }
ensure_keypair() {
d=$(sess_dir "$1")
mkdir -p "$d" && chmod 700 "$d"
[ -s "$d/id_ed25519" ] && return 0
"$SSH_KEYGEN" -q -t ed25519 -N '' -C "$TOOL:$1" -f "$d/id_ed25519" </dev/null \
|| die "ssh-keygen failed for $1"
chmod 600 "$d/id_ed25519"
}
# put FILE LINE: FILE becomes LINE (newline-terminated) in one rename, so a
# concurrent reader never sees it half written.
put() {
t=$(mktemp "$(dirname "$1")/.tmp.XXXXXX") && printf '%s\n' "$2" > "$t" && mv -f "$t" "$1"
}
# Runs inside the box via `min session exec NAME sh -c PREP TOOL PUBKEY`.
# Prints key=value facts on stdout; anything else is an error.
# The box's host key and authorized_keys live in ~/.ssh/TOOL.
# Host key: while either half of the pair is missing, the PREP that makes the
# .keygen dir generates into a temp name, drops any leftover half, and renames
# the new pair into place; everyone else waits for both files. Only that PREP
# removes the dir. Waiters give up after 5s (MIN_KEYGEN_WAIT: a test knob,
# min does not forward host env) leaving the dir alone. A dir over a minute
# old (owner died) is broken by one waiter at a time, under .keygen.break,
# which is itself cleared when over a minute old; without `find -mmin`
# neither is ever broken.
# The environment is dumped with awk's ENVIRON, not `env`: the box's env
# (coreutils 9.12) shell-quotes values (X='a b'), and sshd would read the
# quotes literally. A multi-line value is dropped whole (its later lines
# could pass as NAME=value). Without awk, env it is.
# The rc line moves interactive shells that start in $HOME to /workbench.
# A box with Minimal's claude package (`min add claude`: /usr/bin/claude, a
# wrapper loading Minimal's Claude plugin) gets CLAUDE_CODE_EXECUTABLE in
# the sshd environment, so Zed's Claude Agent (its ACP adapter honours the
# variable) runs that claude instead of the SDK's own; a value already set
# in the box wins. MIN_BOX_CLAUDE is a test knob, like MIN_KEYGEN_WAIT.
# shellcheck disable=SC2016
PREP='set -eu
umask 077
case $0 in ""|*[!a-z0-9-]*) echo "bad tool name: $0" >&2; exit 3 ;; esac
s="$HOME/.ssh"; a="$s/$0"; d="$a"; k="$d/host_ed25519"; l="$d/.keygen"
mkdir -p "$s" "$a"
command -v ssh-keygen >/dev/null 2>&1 || { echo "openssh is not installed in this session; activate it with --loadout zed" >&2; exit 3; }
unlock() { rm -f "$t" "$t.pub"; rmdir "$l" 2>/dev/null || true; }
old() { [ -n "$(find "$1" -prune -mmin +1 2>/dev/null)" ]; }
i=0
while [ ! -s "$k" ] || [ ! -s "$k.pub" ]; do
if mkdir "$l" 2>/dev/null; then
t="$d/.new.$$"; trap unlock EXIT; trap "exit 1" HUP INT TERM
if [ ! -s "$k" ] || [ ! -s "$k.pub" ]; then
rm -f "$t" "$t.pub"
ssh-keygen -q -t ed25519 -N "" -C "min host" -f "$t" </dev/null >&2
rm -f "$k" "$k.pub"
mv -f "$t" "$k"; mv -f "$t.pub" "$k.pub"
fi
trap - EXIT HUP INT TERM; unlock
break
fi
if old "$l.break"; then rmdir "$l.break" 2>/dev/null || true; fi
if old "$l" && mkdir "$l.break" 2>/dev/null; then
! old "$l" || rm -rf "$l"
rmdir "$l.break"; continue
fi
[ "$i" -lt "${MIN_KEYGEN_WAIT:-5}" ] || { echo "host key generation did not finish in $d ($l is held)" >&2; exit 3; }
sleep 1; i=$((i + 1))
done
printf "%s\n" "$1" > "$a/authorized_keys.$$" && mv -f "$a/authorized_keys.$$" "$a/authorized_keys"
if command -v awk >/dev/null 2>&1; then awk "BEGIN { for (k in ENVIRON) if (index(ENVIRON[k], \"\n\") == 0) print k \"=\" ENVIRON[k] }"; else env; fi | grep -E "^[A-Za-z_][A-Za-z0-9_]*=" | grep -Ev "^(TERM|PWD|OLDPWD|SHLVL|_|HOME|USER|LOGNAME|PATH|SSH_[A-Z_]*|PROMPT_COMMAND|MINIMAL_MOTD)=" > "$s/environment.$$" || true
c=${MIN_BOX_CLAUDE:-/usr/bin/claude}
if [ -x "$c" ] && [ -z "${CLAUDE_CODE_EXECUTABLE:-}" ]; then echo "CLAUDE_CODE_EXECUTABLE=$c" >> "$s/environment.$$"; fi
mv -f "$s/environment.$$" "$s/environment"
for rc in "$HOME/.bashrc" "$HOME/.zshrc"; do
grep -qs "min:workbench" "$rc" || printf "%s\n" "# min:workbench (managed by $0)" "case \$- in *i*) if [ \"\$PWD\" = \"\$HOME\" ] && [ -d /workbench ]; then cd /workbench; fi ;; esac" >> "$rc"
done
[ -e "$HOME/.bash_profile" ] || printf "%s\n" "[ -f \"\$HOME/.bashrc\" ] && . \"\$HOME/.bashrc\"" > "$HOME/.bash_profile"
echo "user=$(id -un)"
echo "home=$HOME"
echo "sshd=$(command -v sshd 2>/dev/null || echo /usr/sbin/sshd)"
echo "hostkey=$(cut -d" " -f1-2 "$k.pub")"'
# prepare NAME ID: key on the host, pubkey + host key in the box ID (NAME's:
# box_id), facts and ID on disk. Also the /workbench shell line for sessions
# activated before the loadout. Sets $F_USER $F_HOME $F_SSHD.
prepare() {
valid_name "$1" || die "session name is not lowercase letters, digits and dashes; not using it: $(printf '%s' "$1" | LC_ALL=C tr -c '[:print:]' '?')"
fact_ok "$ID_ERE" "${2:-}" || die "session $1: no session id to reach it by; not using it"
pr_s=0; pr_old=$(stored_id "$1") || pr_s=$?
[ "$pr_s" != 2 ] || die "session $1: $(sess_dir "$1")/id is not a session id; not using it"
if [ "$pr_s" = 0 ] && [ "$pr_old" != "$2" ]; then
die "session $1: $(sess_dir "$1")/id records box $pr_old, not $2; not using it"
fi
ensure_keypair "$1"
d=$(sess_dir "$1")
pub=$(cat "$d/id_ed25519.pub") || die "cannot read $d/id_ed25519.pub"
facts=$(mn session exec "$2" sh -c "$PREP" "$TOOL" "$pub" </dev/null) \
|| die "could not prepare session $1 (is it active, with openssh installed?)"
F_USER=$(printf '%s\n' "$facts" | sed -n 's/^user=//p' | head -1)
F_HOME=$(printf '%s\n' "$facts" | sed -n 's/^home=//p' | head -1)
F_SSHD=$(printf '%s\n' "$facts" | sed -n 's/^sshd=//p' | head -1)
hostkey=$(printf '%s\n' "$facts" | sed -n 's/^hostkey=//p' | head -1)
[ -n "$F_USER" ] && [ -n "$F_HOME" ] && [ -n "$hostkey" ] \
|| die "session $1 returned incomplete facts: $(printf '%s' "$facts" | LC_ALL=C tr -c '[:print:]\n' '?' | head -c 400)"
: "${F_SSHD:=/usr/sbin/sshd}"
# The box is untrusted: these land in ssh_config (User expands %tokens
# and ${ENV}) and in the ProxyCommand. Check all before writing any.
fact_ok "$USER_ERE" "$F_USER" || bad_fact "$1" user "$F_USER"
fact_ok 'ssh-ed25519 [A-Za-z0-9+/]+=*' "$hostkey" || bad_fact "$1" hostkey "$hostkey"
fact_ok "$PATH_ERE" "$F_HOME" || bad_fact "$1" home "$F_HOME"
fact_ok "$PATH_ERE" "$F_SSHD" || bad_fact "$1" sshd "$F_SSHD"
umask 077
# explicit: _proxy runs prepare under `||`, where set -e does not apply
if ! { put "$d/known_hosts" "$HOST_PREFIX$1 $hostkey" && put "$d/user" "$F_USER" \
&& put "$d/home" "$F_HOME" && put "$d/sshd" "$F_SSHD" && put "$d/id" "$2"; }; then
die "could not write the facts for $1 under $d"
fi
ssh_config_write
}
# What a box may report. Paths: no space (sshd's AuthorizedKeysFile splits on
# it), no quoting or %/$ expansion, no control bytes (proxy_command's
# \001/\002 sentinels among them).
USER_ERE='[A-Za-z_][A-Za-z0-9._-]{0,31}'
PATH_ERE='/[A-Za-z0-9._/+@-]*'
# fact_ok ERE VALUE: VALUE is one line matching ERE in full (C locale). The
# newline check matters for values read back from disk ($d/user).
fact_ok() {
case $2 in *"
"*) return 1 ;; esac
printf '%s\n' "$2" | LC_ALL=C grep -Eqx -- "$1"
}
# stored_path NAME FIELD: the path prepare stored in sessions/NAME/FIELD (home,
# sshd), re-checked on read; status 1 when it is missing or not a valid path.
stored_path() {
sp=$(cat "$(sess_dir "$1")/$2" 2>/dev/null) && fact_ok "$PATH_ERE" "$sp" || return 1
printf '%s' "$sp"
}
# bad_fact NAME FIELD VALUE: die naming the field; VALUE cut to 40 printable bytes.
bad_fact() {
v=$(printf '%s' "$3" | LC_ALL=C tr -c '[:print:]' '?' | cut -c1-40)
die "session $1 reported an invalid $2 ($v); not trusting it"
}
# sshd argv, one word per line. $1 sshd path, $2 box home.
sshd_argv() {
printf '%s\
10BC8
n' "$1" -i -e -f /dev/null -h "$2/.ssh/$TOOL/host_ed25519" \
-o LogLevel=ERROR -o PidFile=none -o StrictModes=no \
-o PubkeyAuthentication=yes -o PasswordAuthentication=no \
-o KbdInteractiveAuthentication=no \
-o "AuthorizedKeysFile $2/.ssh/$TOOL/authorized_keys" \
-o PermitUserEnvironment=yes -o AllowTcpForwarding=yes -o GatewayPorts=no \
-o AllowAgentForwarding=no -o X11Forwarding=no -o PrintMotd=no -o PrintLastLog=no -o UseDNS=no \
-o "Subsystem sftp internal-sftp"
}
# ---- ssh -------------------------------------------------------------------
# The ProxyCommand string for NAME (facts and id from disk).
proxy_command() {
d=$(sess_dir "$1")
sshd=$(stored_path "$1" sshd) || die "session $1: invalid sshd in $d/sshd; not using it"
home=$(stored_path "$1" home) || die "session $1: invalid home in $d/home; not using it"
pid_=$(stored_id "$1") || die "session $1: no valid session id in $d/id; not using it"
cmd="$(shq "$MIN") session exec $(shq "$pid_")"
set -f
for w in $(sshd_argv "$sshd" "$home" | tr '\n' '\001' | tr ' ' '\002' | tr '\001' ' '); do
w=$(printf '%s' "$w" | tr '\002' ' ')
cmd="$cmd $(shq "$w")"
done
set +f
pct "$cmd"
}
# ssh_common NAME FMT: the client options every path to NAME carries (the
# client's own ssh, `TOOL ssh`, the TOOL.conf stanza), as `FMT KEY VALUE
# [path]`. Forwarding is off here, not left to ~/.ssh/config: TOOL.conf is
# Included first, so a later `Host *` with `ForwardAgent yes` would otherwise
# hand the agent to the box.
ssh_common() {
d=$(sess_dir "$1")
$2 User "$(cat "$d/user")"
$2 IdentitiesOnly yes
$2 AddKeysToAgent no
$2 UserKnownHostsFile "$d/known_hosts" path
$2 StrictHostKeyChecking yes
$2 ForwardAgent no
$2 ForwardX11 no
$2 ForwardX11Trusted no
}
# KEY=VALUE for ssh -o; a path is quoted only when it has whitespace.
opt_kv() {
v=$2
if [ "${3:-}" = path ]; then
case $v in *[[:space:]]*) v="\"$v\"" ;; esac
v=$(pct "$v")
fi
printf '%s=%s\n' "$1" "$v"
}
# ssh -o options for NAME, one per line.
ssh_opts() {
d=$(sess_dir "$1")
fact_ok "$USER_ERE" "$(cat "$d/user")" || die "session $1: invalid user in $d/user; not using it"
pc=$(proxy_command "$1") || exit 1
printf '%s\n' "ProxyCommand=$pc"
ssh_common "$1" opt_kv
}
# The path baked into stanzas: ~/.local/bin/TOOL when that symlink is this
# file (a moved checkout then keeps working), else this file.
self_path() {
p=$HOME/.local/bin/$TOOL
if [ -L "$p" ]; then
l=$(readlink "$p"); case $l in /*) ;; *) l=$(dirname "$p")/$l ;; esac
if [ -f "$l" ] && [ "$(cd "$(dirname "$l")" && pwd -P)/$(basename "$l")" = "$(cd "$(dirname "$SELF")" && pwd -P)/$(basename "$SELF")" ]; then
printf '%s' "$p"; return 0
fi
fi
printf '%s' "$SELF"
}
# One stanza line; a path is always quoted and %-doubled.
stanza_kv() {
if [ "${3:-}" = path ]; then printf ' %s "%s"\n' "$1" "$(pct "$2")"
else printf ' %s %s\n' "$1" "$2"; fi
}
# ssh_stanza NAME: a `Host <prefix>NAME` block from the facts prepare wrote.
# Paths are quoted and %-doubled: ssh expands tokens in all three values.
ssh_stanza() {
d=$(sess_dir "$1")
mb=; [ -z "$MIN" ] || mb="MIN_BIN=$(shq "$MIN") "
printf '# %s\nHost %s%s\n' "$1" "$HOST_PREFIX" "$1"
ssh_common "$1" stanza_kv
stanza_kv IdentityFile "$d/id_ed25519" path
printf ' ProxyCommand %s\n' "$(pct "env ${mb}${ENV_PREFIX}_STATE_DIR=$(shq "$STATE") $(shq "$(self_path)") _proxy $(shq "$1")")"
}
# The whole TOOL.conf: header, a stanza per session on disk (only own ones
# min still lists, when min is around; else all but those with a bad id:
# _proxy decides at connect), then a catch-all that explains itself. A box
# whose id is not known (several boxes share its name) gets no stanza: ssh
# falls to the catch-all.
ssh_stanzas() {
printf '# managed by %s ssh-config; do not edit\n' "$TOOL"
# One min ls; when it fails the stanzas on disk are kept.
live=; filter=
if [ -n "$MIN" ] && ls_json=$(min_ls 2>/dev/null); then
if live=$(own_names "$ls_json"); then filter=1; else live=; fi
fi
for s in "$STATE"/sessions/*/; do
[ -f "${s}user" ] || continue
n=$(basename "$s")
valid_name "$n" || { log "skipping $n: not a valid stanza name"; continue; }
fact_ok "$USER_ERE" "$(cat "${s}user")" || { log "skipping $n: invalid user in ${s}user"; continue; }
if [ -n "$filter" ]; then printf '%s\n' "$live" | grep -qxF -- "$n" || continue
else ss_s=0; stored_id "$n" >/dev/null || ss_s=$?; [ "$ss_s" != 2 ] || continue; fi
printf '\n'; ssh_stanza "$n"
done
printf '\nHost %s* !%s*.*\n ProxyCommand %s\n' "$HOST_PREFIX" "$HOST_PREFIX" \
"$(pct "env ${ENV_PREFIX}_STATE_DIR=$(shq "$STATE") $(shq "$(self_path)") _proxy --missing")"
}
# stanza_names [FILE]: the session names of the stanzas in TOOL.conf (the
# catch-all is not one).
stanza_names() {
awk -v p="Host $HOST_PREFIX" 'index($0, p) == 1 && length($0) > length(p) && substr($0, length(p) + 1, 1) != "*" {
print substr($0, length(p) + 1) }' "${1:-$SSH_CONF}" 2>/dev/null || :
}
ssh_stanza_count() { stanza_names | grep -c . || :; }
# Refresh TOOL.conf. A no-op until `TOOL ssh-config` has created it (nothing
# under ~/.ssh is touched before that opt-in), and never fatal: it runs on
# the way to a connection, which matters more than a fresh stanza.
ssh_config_write() {
[ -e "$SSH_CONF" ] || return 0
case $STATE in *'"'*) log "state dir path contains a double quote; not writing $SSH_CONF"; return 0 ;; esac
ssh_config_put || log "could not write $SSH_CONF; leaving it as it was"
return 0
}
# TOOL.conf from ssh_stanzas: tmp + rename in place, mode 600; left alone
# (same inode, same mtime) when the content is unchanged.
ssh_config_put() {
tmp=$(mktemp "$SSH_CONF.XXXXXX") || return 1
ssh_stanzas > "$tmp" || { rm -f "$tmp"; return 1; }
if cmp -s "$tmp" "$SSH_CONF"; then rm -f "$tmp"; chmod 600 "$SSH_CONF"; return 0; fi
{ chmod 600 "$tmp" && mv -f "$tmp" "$SSH_CONF"; } || { rm -f "$tmp"; return 1; }
}
# lock_old PATH: PATH is over a minute old (without `find -mmin`, never).
lock_old() { [ -n "$(find "$1" -prune -mmin +1 2>/dev/null)" ]; }
# ssh_lock: hold SSH_LOCK (a dir, shared by every min-<client> tool) for a
# read-modify-write of ~/.ssh/config and the created record; released on
# exit. A lock over a minute old (its holder died) is broken by one waiter
# at a time, under .break, as in PREP. Gives up after MIN_LOCK_WAIT seconds.
ssh_lock() {
mkdir -p "${SSH_LOCK%/*}"
i=0
until mkdir "$SSH_LOCK" 2>/dev/null; do
if lock_old "$SSH_LOCK.break"; then rmdir "$SSH_LOCK.break" 2>/dev/null || :; fi
if lock_old "$SSH_LOCK" && mkdir "$SSH_LOCK.break" 2>/dev/null; then
! lock_old "$SSH_LOCK" || rm -rf "$SSH_LOCK"
rmdir "$SSH_LOCK.break"; continue
fi
[ "$i" -lt "${MIN_LOCK_WAIT:-10}" ] || die "$SSH_LOCK is held by another ssh-config run; try again (remove it if none is running)"
sleep 1; i=$((i + 1))
done
trap ssh_unlock EXIT
trap 'exit 1' HUP INT TERM
}
ssh_unlock() {
rmdir "$SSH_LOCK" 2>/dev/null || :
rmdir "${SSH_LOCK%/*}" 2>/dev/null || : # gone with the record, when it is
}
# Other tools' Include lines of the same shape in ~/.ssh/config: never touched.
ssh_other_includes() {
grep -Ex 'Include ~/\.ssh/min-[a-z0-9-]+\.conf' "$SSH_MAIN" 2>/dev/null | grep -vxF -- "$SSH_MARK2" || :
}
# ssh-config [--remove|--print]: create ~/.ssh/TOOL.conf and put a marked
# Include of it at the top of ~/.ssh/config. ~/.ssh/config is written
# through, never renamed: it is often a dotfiles symlink. What the first
# min-<client> install created (`dir` for ~/.ssh, `config` for
# ~/.ssh/config) is recorded in $SSH_CREATED; a tool installed beside
# another leaves the record alone, and the one removing the last Include
# deletes only those.
cmd_ssh_config() {
case ${1:-} in
'') ;;
--print) ssh_stanzas; return 0 ;;
--remove) ssh_config_remove; return 0 ;;
*) die "ssh-config: unknown option $1" ;;
esac
case $STATE in *'"'*) die "state dir path contains a double quote; not writing $SSH_CONF" ;; esac
mkdir -p "$STATE"
ssh_lock
created=
[ -d "$SSH_DIR" ] || { mkdir -p "$SSH_DIR" && chmod 700 "$SSH_DIR"; created=dir; }
[ -e "$SSH_CONF" ] || { : > "$SSH_CONF"; chmod 600 "$SSH_CONF"; }
if ! grep -qxF -- "$SSH_MARK2" "$SSH_MAIN" 2>/dev/null; then
[ -e "$SSH_MAIN" ] || { : > "$SSH_MAIN"; chmod 600 "$SSH_MAIN"; created="$created config"; }
if [ -z "$(ssh_other_includes)" ]; then
# the first tool in: the record says what this install created, nothing older
mkdir -p "$(dirname "$SSH_CREATED")"
rm -f "$SSH_CREATED"
for w in $created; do printf '%s\n' "$w" >> "$SSH_CREATED"; done
fi
tmp=$(mktemp "$SSH_MAIN.XXXXXX") || die "cannot write $SSH_MAIN"
{ printf '%s\n' "$SSH_MARK1" "$SSH_MARK2"; cat "$SSH_MAIN"; } > "$tmp"
ssh_main_write "$tmp" || { rm -f "$tmp"; die "cannot write $SSH_MAIN"; }
rm -f "$tmp"
log "added \`$SSH_MARK2\` to the top of $SSH_MAIN"
fi
ssh_config_put || die "cannot write $SSH_CONF"
log "$SSH_CONF: $(ssh_stanza_count) stanza(s); ssh ${HOST_PREFIX}NAME reaches a session"
}
# ssh_main_write FILE: ~/.ssh/config becomes FILE's content, written
# through, after a dated copy of its old content under $STATE/backups.
ssh_main_write() {
(umask 077; mkdir -p "$STATE/backups") && chmod 700 "$STATE/backups" || return 1
b=$STATE/backups/ssh_config.$(date +%Y%m%dT%H%M%S); i=1; bb=$b
while [ -e "$bb" ]; do bb=$b.$i; i=$((i + 1)); done
{ (umask 077; cat "$SSH_MAIN" > "$bb") && chmod 600 "$bb"; } || { log "cannot back up $SSH_MAIN to $bb"; return 1; }
log "backed up $SSH_MAIN to $bb"
cat "$1" > "$SSH_MAIN" && return 0
log "writing $SSH_MAIN failed; its previous content is in $bb"
if cat "$bb" > "$SSH_MAIN"; then log "restored $SSH_MAIN from $bb"
else log "could not restore $SSH_MAIN; copy $bb back by hand"; fi
return 1
}
# Drop every marker + Include pair of ours from ~/.ssh/config (the rest byte
# for byte, a last line without a newline included) in one write, delete
# TOOL.conf, and, when no other tool's Include is left, the config file and
# ~/.ssh too if the first install created them and they are now empty (a
# symlinked config never).
ssh_config_remove() {
ssh_lock
removed=
if grep -qxF -- "$SSH_MARK2" "$SSH_MAIN" 2>/dev/null; then
tmp=$(mktemp "$SSH_MAIN.XXXXXX") || die "cannot write $SSH_MAIN"
cat "$SSH_MAIN" > "$tmp"
while n=$(grep -nxF -- "$SSH_MARK2" "$tmp" | head -1 | cut -d: -f1) && [ -n "$n" ]; do
m=$n
[ "$n" -gt 1 ] && [ "$(sed -n "$((n - 1))p" "$tmp")" = "$SSH_MARK1" ] && m=$((n - 1))
{ { [ "$m" -le 1 ] || head -n $((m - 1)) "$tmp"; tail -n +$((n + 1)) "$tmp"; } > "$tmp.next" \
&& mv -f "$tmp.next" "$tmp"; } || { rm -f "$tmp" "$tmp.next"; die "cannot write $SSH_MAIN"; }
done
ssh_main_write "$tmp" || { rm -f "$tmp"; die "cannot write $SSH_MAIN"; }
rm -f "$tmp"
removed=1
fi
if [ -n "$removed" ]; then log "removed the $TOOL Include from $SSH_MAIN"
else log "no $TOOL Include found in $SSH_MAIN"; fi
rm -f "$SSH_CONF"
[ -z "$(ssh_other_includes)" ] || return 0
if grep -qx config "$SSH_CREATED" 2>/dev/null \
&& [ -f "$SSH_MAIN" ] && [ ! -L "$SSH_MAIN" ] && [ ! -s "$SSH_MAIN" ]; then
rm -f "$SSH_MAIN"; log "removed the now empty $SSH_MAIN"
fi
if grep -qx dir "$SSH_CREATED" 2>/dev/null && rmdir "$SSH_DIR" 2>/dev/null; then
log "removed the now empty $SSH_DIR"
fi
rm -f "$SSH_CREATED"
}
# _proxy NAME: the ProxyCommand behind a `Host <prefix>NAME` stanza. `_proxy
# --missing` is the catch-all's and takes no host, so no hostname reaches a
# shell; a trailing argument is ignored.
# Prepares the session (host key re-pinned, pubkey re-pushed), then becomes
# sshd in the box. Stdout is the ssh byte stream: nothing is printed before
# the exec; outcomes go to $STATE/proxy.log (and stderr, which ssh relays).
# The box is NAME's own one, by its recorded id; another box of that name
# only when min-zed holds nothing for NAME (no key dir): a box of ours that
# is gone never hands its stanza to whoever takes the name next.
cmd_proxy() {
if [ "${1:-}" = --missing ]; then
die "no $TOOL ssh stanza for this $HOST_PREFIX* host; run: $TOOL status, then $TOOL attach NAME (or $TOOL ssh-config)"
fi
name=${1:-}; [ -n "$name" ] || die "_proxy: NAME required"
pj=$(min_ls) || { proxy_log "$name" "fail: min ls"; die "min ls failed"; }
own=own; [ -d "$(sess_dir "$name")" ] || own=
pb=0; box_id "$name" "$pj" "$own" || pb=$?
case $pb in
0) ;;
1) proxy_log "$name" "fail: no session named $name"; die "no session named $name" ;;
*) proxy_log "$name" "fail: no id"; die "$BWHY" ;;
esac
id=$BID
(prepare "$name" "$id") || { proxy_log "$name" "fail: prepare"; exit 1; }
d=$(sess_dir "$name")
for f in sshd home; do
stored_path "$name" $f >/dev/null || {
proxy_log "$name" "fail: invalid $f in $d/$f"
die "session $name: invalid $f in $d/$f; not using it"
}
done
set --
while IFS= read -r w; do set -- "$@" "$w"; done <<EOT
$(sshd_argv "$(stored_path "$name" sshd)" "$(stored_path "$name" home)")
EOT
proxy_log "$name" ok
exec "$MIN" session exec "$id" "$@"
}
# proxy_log NAME WHAT: one dated line in $STATE/proxy.log (mode 600; past
# 1000 lines only the newest 500 are kept). Silent and never fails: stdout is
# the ssh byte stream in _proxy, and a log problem must not block a connect.
proxy_log() {
(
f=$STATE/proxy.log; umask 077
printf '%s %s %s\n' "$(date '+%FT%T')" "$1" "$2" >> "$f"
chmod 600 "$f"
[ "$(($(wc -l < "$f")))" -le 1000 ] || { tail -n 500 "$f" > "$f.$$" && mv -f "$f.$$" "$f"; } || rm -f "$f.$$"
) >/dev/null 2>&1 || true
}
# ssh NAME [-- ARGS...]: plain ssh into the session over the same transport.
cmd_ssh() {
name=${1:-}; [ -n "$name" ] || die "ssh: NAME required"
shift
[ "${1:-}" = "--" ] && shift
need_box "$name"
prepare "$name" "$BID"
d=$(sess_dir "$name")
tmp=$(mktemp) && ssh_opts "$name" > "$tmp"
set -- "$HOST_PREFIX$name" "$@"
while IFS= read -r o; do set -- -o "$o" "$@"; done < "$tmp"
rm -f "$tmp"
hook client_on_connect "$name" || :
exec ssh -i "$d/id_ed25519" "$@"
}
# ---- naming ----------------------------------------------------------------
# valid_name NAME: lowercase letters, digits and dashes, not starting with a
# dash: anything else breaks a `Host` pattern or a stanza comment.
valid_name() {
case $1 in ''|-*) return 1 ;; esac
[ "$(printf '%s.' "$1" | LC_ALL=C tr -d 'a-z0-9-')" = . ]
}
# pick_session CMD: numbered picker of own sessions on the terminal; prints the
# chosen name.
pick_session() {
[ -t 0 ] || die "$1: NAME required when stdin is not a terminal"
own_ls | jq -r '.sessions[] | [.name, .status, (.project_path // "")] | @tsv' \
| awk -F'\t' '{ printf "%2d) %-28s %-13s %s\n", NR, $1, $2, $3 }' >&2
printf 'session number: ' >&2
read -r n
case $n in ''|*[!0-9]*|0) die "no such entry" ;; esac
pn=$(own_ls | jq -r --argjson n "$n" '.sessions[$n - 1].name // empty') \
|| die "no such entry"
[ -n "$pn" ] || die "no such entry"
valid_name "$pn" || die "session name is not lowercase letters, digits and dashes; not using it: $(printf '%s' "$pn" | LC_ALL=C tr -c '[:print:]' '?')"
printf '%s\n' "$pn"
}
# default_loadouts: the names in min's default_loadouts (`[loadouts]` table
# or a top-level dotted `loadouts.default_loadouts`; "" or '' strings), one
# per line. Naming any --loadout makes min skip that list, so
# activate_session passes it on itself. What it cannot read, it says.
default_loadouts() {
f=${XDG_CONFIG_HOME:-$HOME/.config}/minimal/config.toml
[ -f "$f" ] || return 0
raw=$(awk '
/^[[:space:]]*\[/ && !on { hdr = 1; sec = ($0 ~ /^[[:space:]]*\[[[:space:]]*loadouts[[:space:]]*\][[:space:]]*(#.*)?$/); next }
!on && ((sec && /^[[:space:]]*default_loadouts[[:space:]]*=/) \
|| (!hdr && /^[[:space:]]*loadouts[[:space:]]*\.[[:space:]]*default_loadouts[[:space:]]*=/)) { on = 1; sub(/^[^=]*=/, "") }
on { sub(/#.*/, ""); print; if ($0 ~ /\]/) exit }' "$f")
[ -n "$raw" ] || return 0
dls=$(printf '%s\n' "$raw" | grep -oE "\"[^\"]*\"|'[^']*'" | sed "s/^.//; s/.\$//") || dls=
if [ -z "$dls" ]; then
[ -z "$(printf '%s' "$raw" | tr -d '[], \t\n')" ] || log "could not read default_loadouts in $f; activating with --loadout $LOADOUT only"
return 0
fi
printf '%s\n' "$dls" | while IFS= read -r dl; do
if printf '%s\n' "$dl" | grep -Eqx '[A-Za-z0-9._-]+'; then printf '%s\n' "$dl"
else log "ignoring default loadout '$dl' in $f: not a plain name"; fi
done
}
# activate_session NAME PATH [SYNC]: a new session for PATH with the user's
# default loadouts, then LOADOUT (last, so its settings win); SYNC is min's
# --sync mode (none: an empty /workbench). An empty NAME lets min name it
# (<dir>-<hex>). The new box is the one id min ls lists afterwards and not
# before (named NAME, or for PATH when min names it); its id goes in
# sessions/NAME/id. Prints the name; min's own output goes to stderr.
activate_session() {
an=$1 ap=$2 async=${3:-}
aj=$(min_ls) || die "min ls failed"
before=$(printf '%s' "$aj" | jq -r '.sessions[] | .id // empty') || die "min ls failed"
set --
for al in $(default_loadouts); do
case $al in
"$LOADOUT") ;;
*) set -- "$@" --loadout "$al" ;;
esac
done
[ -z "$async" ] || set -- "$@" --sync "$async"
set -- "$@" --loadout "$LOADOUT"
[ -z "$an" ] || set -- "$@" -n "$an"
mn session activate --no-prompt "$@" "$ap" >&2
aj=$(min_ls) || die "min ls failed"
anew=$(printf '%s' "$aj" | jq -r --arg n "$an" --arg p "$ap" --arg b "$before" '($b | split("\n")) as $o
| .sessions[] | select((.id // "") as $i | $i != "" and ($o | index([$i]) | not))
| select(if $n != "" then .name == $n else .project_path == $p end) | "\(.id) \(.name // "")"')
case $(printf '%s\n' "$anew" | grep -c .) in
1) ;;
0) if [ -n "$an" ]; then die "activate made no session $an"; fi
die "activate made no session for $ap" ;;
*) die "several new sessions for ${an:-$ap}: $(printf '%s' "$anew" | cut -d' ' -f2- | tr '\n' ' ')" ;;
esac
aid=${anew%% *} an=${anew#* }
valid_name "$an" || die "min named the session $(printf '%s' "$an" | LC_ALL=C tr -c '[:print:]' '?'), not a hostname; pass -n NAME"
fact_ok "$ID_ERE" "$aid" || die "min gave the new session $an no session id ($(printf '%s' "$aid" | LC_ALL=C tr -c '[:print:]' '?' | cut -c1-40)); not using it"
ad=$(sess_dir "$an")
{ mkdir -p "$ad" && chmod 700 "$ad" && put "$ad/id" "$aid"; } || die "could not record the id of $an under $ad"
printf '%s\n' "$an"
}
# ---- lifecycle -------------------------------------------------------------
# min destroys a session with no unsaved changes without asking, so ask here
# first (default No). min still shows its own warning and delta listing for a
# session that has changes. ask_destroy NAME ID CHOICES prints the answer.
ask_destroy() {
printf 'Destroy Minimal session %s (%s)? [%s] ' "$1" "$(id_field "$2" project_path)" "$3" >&2
IFS= read -r a || a=
printf '%s' "$a"
}
# destroy_one NAME ID ANSWER [force]: destroy box ID (NAME's) on y, else keep
# and snooze the tidy-up reminder for it (kept/NAME). force passes min's --force, which
# discards changes min has not saved. Returns min's exit status, or 4 when
# min refused for want of a terminal to confirm unsaved changes on (a
# client's call; on a terminal min asks itself).
# NAME counts as gone (keys and records dropped, client_on_destroy run) only
# when a min ls that succeeds lists its id no more (a key dir with no id:
# once no box is named NAME). A failed min ls is
# unknown: everything stays (ssh-config is not rewritten), with a warning,
# and after a y the status is non-zero (min's own, or 1 when it was 0); a
# later `destroy NAME` drops what was kept once min ls lists ID no more.
destroy_one() {
r=0
fact_ok "$ID_ERE" "$2" || { log "no session id for $1; not destroying it"; return 1; }
case $3 in
y|Y|yes|YES)
if [ -t 0 ]; then mn session destroy "$2" ${4:+--force} || r=$?
else
ef=$(mktemp "${TMPDIR:-/tmp}/$TOOL.XXXXXX") || die "mktemp failed"
mn session destroy "$2" ${4:+--force} 2>"$ef" || r=$?
cat "$ef" >&2
if [ "$r" != 0 ] && grep -q 'without confirmation' "$ef"; then
log "$1 has changes min has not saved; destroy -y --force $1 discards them"; r=4
fi
rm -f "$ef"
fi ;;
*) log "kept $1"; mkdir -p "$STATE/kept"; date +%s > "$STATE/kept/$1" ;;
esac
if ! listed=$(ls_lists "$2"); then
log "min ls failed, so whether $1 is gone is unknown; kept its keys"
case $3 in y|Y|yes|YES) [ "$r" != 0 ] || r=1 ;; esac
return "$r"
fi
[ "$listed" = true ] || drop_gone "$1"
ssh_config_write
return "$r"
}
# ls_lists ID: true or false (min lists box ID), from a min ls that succeeds;
# fails with it.
ls_lists() {
ll_j=$(min_ls 2>/dev/null) || return 1
printf '%s' "$ll_j" | jq -r --arg i "$1" 'any(.sessions[]; .id == $i)' 2>/dev/null
}
# drop_gone NAME: forget a box min no longer lists.
drop_gone() {
rm -rf "$(sess_dir "$1")" "$STATE/orphan/$1" "$STATE/kept/$1"
hook client_on_destroy "$1" || :
}
# Sessions whose box serves an ssh connection right now, one per line: any
# host process `min session exec X .../sshd` (_proxy, `ssh`, scp, any
# client's own ssh, whatever its Host prefix). X is a box's id or, from
# connections opened before ids or by other tools, a name: every check of
# an own box asks for both (track_orphans, gc, gc_still_idle, st_used).
# Read from ps, so a stopped box is never started to ask.
in_use_names() {
ps -xo pid=,ppid=,args= 2>/dev/null | awk '
{ k = split($0, w, /[ \t]+/)
for (i = 1; i + 3 <= k; i++) {
if (w[i] != "session" || w[i + 1] != "exec" || w[i + 2] !~ /^[a-z0-9][a-z0-9-]*$/) continue
m = split(w[i + 3], q, "/"); if (q[m] == "sshd") { print w[i + 2]; break }
} }' | sort -u
}
# gc_still_idle NAME [ID]: right before a gc asks about NAME, look again (the
# user may have connected while earlier questions were open): not in use
# (NAME, nor box ID: one not min-zed's), afresh, and not client_linked (the
# client must answer afresh too: clear any cache of its own before calling).
gc_still_idle() {
INUSE_DONE=
! box_in_use "$1" && { [ -z "${2:-}" ] || ! box_in_use "$2"; } && ! hook client_linked "$1"
}
# box_in_use NAME|ID: it is in in_use_names, read once per run (track_orphans
# and gc_still_idle read it afresh).
box_in_use() {
[ -n "${INUSE_DONE:-}" ] || { INUSE=$(in_use_names); INUSE_DONE=1; }
printf '%s\n' "$INUSE" | grep -qxF -- "$1"
}
# track_orphans LS_JSON NOW: orphan/NAME = epoch an active session was first
# seen neither held by this client (client_linked) nor in use (box_in_use);
# a session in use restarts its age, so it counts from the last use. Removed
# once linked or no longer active. kept/NAME goes with the session. Prints the orphans not in use now, one per line.
track_orphans() {
mkdir -p "$STATE/orphan" "$STATE/kept"
INUSE_DONE=
orphans=
# NAME/ID words: own names are hostnames, ids hex and dashes
for ni in $(printf '%s' "$1" | jq -r '.sessions[] | select(.status == "active") | "\(.name)/\(.id // "")"'); do
hook client_linked "${ni%%/*}" || orphans="$orphans$ni
"
done
all=$(printf '%s' "$1" | jq -r '.sessions[].name')
'%s' "$orphans" | sed 's,/.*,,')
for ni in $orphans; do
n=${ni%%/*} i=${ni#*/}
if box_in_use "$n" || { [ -n "$i" ] && box_in_use "$i"; }; then printf '%s' "$2" > "$STATE/orphan/$n"; continue; fi
[ -f "$STATE/orphan/$n" ] || printf '%s' "$2" > "$STATE/orphan/$n"
printf '%s\n' "$n"
done
for f in "$STATE"/orphan/* "$STATE"/kept/*; do
[ -f "$f" ] || continue
n=${f##*/}
case $f in
"$STATE"/orphan/*) printf '%s\n' "$onames" | grep -qxF -- "$n" || rm -f "$f" ;;
*) printf '%s\n' "$all" | grep -qxF -- "$n" || rm -f "$f" ;; # kept/
esac
done
}
# ---- report ----------------------------------------------------------------
# TSV on stdin -> space-aligned columns.
table() {
awk -F'\t' '{ for (i = 1; i <= NF; i++) { c[NR, i] = $i; if (length($i) > w[i]) w[i] = length($i) } nf[NR] = NF }
END { for (r = 1; r <= NR; r++) { s = ""
for (i = 1; i < nf[r]; i++) s = s sprintf("%-" w[i] "s ", c[r, i])
print s c[r, nf[r]] } }'
}
# row LEVEL CHECK MESSAGE [FIX]
row() {
printf '%-4s %-11s %s\n' "$1" "$2" "$3"
[ "$1" = ok ] || [ -z "${4:-}" ] || printf '%19s%s\n' '' "$4"
[ "$1" != FAIL ] || FAILS=$((FAILS + 1))
}
have() { command -v "$1" >/dev/null 2>&1; }
# 45m / 3h / 2d
humanise_age() {
if [ "$1" -ge 86400 ]; then echo "$(($1 / 86400))d"
elif [ "$1" -ge 3600 ]; then echo "$(($1 / 3600))h"
else echo "$(($1 / 60))m"; fi
}
# ---- client constants: every editor-specific value ---------------------------
EDITOR_NAME=Zed
EDITOR_BIN=${MIN_ZED_EDITOR_BIN:-zed} # host CLI that opens a window
EDITOR_APP=${MIN_ZED_EDITOR_APP:-/Applications/Zed.app}
# Without the zed command on PATH, the CLI inside the app.
if [ -z "${MIN_ZED_EDITOR_BIN:-}" ] && ! have "$EDITOR_BIN" && [ -x "$EDITOR_APP/Contents/MacOS/cli" ]; then
EDITOR_BIN=$EDITOR_APP/Contents/MacOS/cli
fi
EDITOR_TESTED=1.26.2 # the Zed release this tool was checked against
ZED_DIR=$HOME/.config/zed # Zed's config dir on the Mac
SETTINGS=${MIN_ZED_SETTINGS:-$ZED_DIR/settings.json} # ssh_connections: the Remote Projects list
TASKS=${MIN_ZED_TASKS:-$ZED_DIR/tasks.json} # global tasks: the Minimal tasks
KEYMAP=${MIN_ZED_KEYMAP:-$ZED_DIR/keymap.json} # the local-terminal key
WORKDIR=/workbench # folder the editor opens in the box
# ---- client settings ---------------------------------------------------------
MIN= # the min binary; main resolves it
usage() {
cat <<USAGE
usage: $TOOL <command> [args]
open [PATH] [-n NAME] [--no-window]
the session for PATH (default .): a live one of $TOOL's is reused, else
one is activated with --loadout $LOADOUT; then $EDITOR_NAME opens $WORKDIR in it
new [PATH | --empty] [-n NAME] [--no-window]
a new session for PATH, then $EDITOR_NAME; on a terminal, when one of
$TOOL's is live for PATH, asks to attach to it first (not with -n or
--empty); --empty: an empty $WORKDIR (min names it box-...)
attach [NAME] [--no-window]
an existing session in $EDITOR_NAME (no NAME: pick one of $TOOL's)
destroy [-y] [--if-idle] [--force] [NAME]
destroy a session after a y/N prompt (-y skips it; --if-idle refuses,
exit 3, while something is connected). No NAME: this directory's, else
pick one. Without a terminal, a session with unsaved changes exits 4;
-y --force discards them
gc [--older-than SECONDS] [--dry-run]
list active sessions no ssh client is using, then ask y/N/q for each
status [--json] table of sessions: status, project, in use, idle age
setup [--remove] install: link $TOOL into ~/.local/bin and the $LOADOUT loadout, copy
Minimal's skills, then ssh-config and config (--remove undoes only ours)
doctor health report (ok / warn / FAIL with a fix); exits 1 on any FAIL
config [--remove|--print]
opt in: ${HOST_PREFIX}* ssh_connections in $EDITOR_NAME's settings.json, the
Minimal tasks in tasks.json, the local-terminal key in keymap.json
(also: zed-config)
ssh NAME [-- ARGS...] plain ssh into the session with the same transport (debugging: -- -v)
ssh-config [--remove|--print]
opt in: Host ${HOST_PREFIX}NAME stanzas in ~/.ssh/$TOOL.conf ($EDITOR_NAME needs them)
completions <zsh|bash> print a completion script