-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·2121 lines (1964 loc) · 72.6 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·2121 lines (1964 loc) · 72.6 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
#!/usr/bin/env bash
set -euo pipefail
# ── Argument parsing ────────────────────────────────────────────────────
# When called from sqrbx-setup wrapper: setup.sh --rerun [section ...]
# When called from .bashrc first-run: setup.sh (no args)
SB_RERUN=false
SB_RECONCILE_BOX=false
SB_SECTIONS=()
while [[ $# -gt 0 ]]; do
case "$1" in
--rerun) SB_RERUN=true; shift ;;
--reconcile-box)
SB_RECONCILE_BOX=true
SB_RERUN=true
SB_SECTIONS=(editors multiplexers shell)
shift
;;
*) SB_SECTIONS+=("$1"); shift ;;
esac
done
# If --rerun with no specific sections, run all sections
if $SB_RERUN && [ ${#SB_SECTIONS[@]} -eq 0 ]; then
SB_SECTIONS=(git github ai editors tuis multiplexers sdks shell)
fi
SB_FAILURES=0
record_failure() {
echo "ERROR: $*" >&2
SB_FAILURES=$((SB_FAILURES + 1))
}
cancel_setup() {
echo
echo "Setup cancelled; existing Selections were preserved."
exit 130
}
gum_confirm_or_cancel() {
local rc
if gum confirm "$@"; then
return 0
else
rc=$?
fi
[ "$rc" -eq 1 ] && return 1
cancel_setup
}
join_csv() {
local IFS=,
echo "$*"
}
# Effective global git identity. Once ~/.gitconfig exists (gh auth setup-git
# creates it holding only credential helpers), `git config --global <key>`
# reads that file alone and never consults the XDG file this script writes,
# so a configured identity would look unset. Fall back to the XDG file.
current_git_identity() {
git config --global "$1" 2>/dev/null \
|| git config --file "$HOME/.config/git/config" "$1" 2>/dev/null \
|| true
}
should_run() {
# In first-run mode (no --rerun), always run all sections
$SB_RERUN || return 0
local section="$1"
for s in "${SB_SECTIONS[@]}"; do
[ "$s" = "$section" ] && return 0
done
return 1
}
SB_TMPDIR=$(mktemp -d)
export SB_TMPDIR
trap 'rm -rf "$SB_TMPDIR"' EXIT
SB_STATE_DIR="${SQUAREBOX_STATE_DIR:-/workspace/.squarebox}"
SB_TOOL_LIB="${SQUAREBOX_TOOL_LIB:-/usr/local/lib/squarebox/tool-lib.sh}"
SB_SELECTION_STATE_FILES=(ai-tool editors editor-default nvim-lazyvim nvim-lazyvim-sha tuis multiplexer sdks shell)
# Selection state is host-owned input. Never follow a Workspace symlink while
# reading or writing it: a checkout could otherwise redirect setup into an
# unrelated host directory.
while [[ "$SB_STATE_DIR" == */ && "$SB_STATE_DIR" != / ]]; do SB_STATE_DIR="${SB_STATE_DIR%/}"; done
if [ -L "$SB_STATE_DIR" ]; then
echo "ERROR: Selection state directory must not be a symlink: $SB_STATE_DIR" >&2
exit 1
fi
if [ -e "$SB_STATE_DIR" ] && [ ! -d "$SB_STATE_DIR" ]; then
echo "ERROR: Selection state path is not a directory: $SB_STATE_DIR" >&2
exit 1
fi
# Fix /workspace ownership if volume mount left it owned by a different UID
if [ -d /workspace ] && ! [ -w /workspace ]; then
if ! command -v sudo >/dev/null 2>&1; then
echo "ERROR: /workspace is not writable and sudo is not available to fix ownership." >&2
echo "Please make /workspace writable for user 'dev' or rerun with appropriate privileges." >&2
exit 1
elif ! sudo -n chown dev:dev /workspace 2>/dev/null; then
echo "ERROR: Failed to change ownership of /workspace to dev:dev." >&2
echo "This can happen if passwordless sudo is not available for chown, or the volume type does not allow chown." >&2
echo "Please run 'sudo chown dev:dev /workspace' manually or adjust the mount configuration and try again." >&2
exit 1
fi
fi
mkdir -p -- "$SB_STATE_DIR"
if [ -L "$SB_STATE_DIR" ] || [ ! -d "$SB_STATE_DIR" ]; then
echo "ERROR: unable to create a safe Selection state directory: $SB_STATE_DIR" >&2
exit 1
fi
for _selection_file in "${SB_SELECTION_STATE_FILES[@]}"; do
_selection_path="$SB_STATE_DIR/$_selection_file"
if [ -L "$_selection_path" ]; then
echo "ERROR: Selection state file must not be a symlink: $_selection_path" >&2
exit 1
fi
if [ -e "$_selection_path" ] && [ ! -f "$_selection_path" ]; then
echo "ERROR: Selection state path is not a regular file: $_selection_path" >&2
exit 1
fi
done
# Source the shared installer. Setup-tier GitHub artifacts are accepted only
# when the exact release tag and asset name carry a valid SHA-256 digest in the
# GitHub release-asset metadata; the shared library verifies it before promote.
export SB_TOOLS_YAML="${SQUAREBOX_TOOLS_YAML:-/usr/local/lib/squarebox/tools.yaml}"
source "$SB_TOOL_LIB"
# Detect interactive terminal
INTERACTIVE=false
if ! $SB_RECONCILE_BOX && [ -t 0 ]; then
INTERACTIVE=true
fi
# Check for gum TUI tool
HAS_GUM=false
if $INTERACTIVE && command -v gum &>/dev/null; then
HAS_GUM=true
fi
section_header() {
if $HAS_GUM; then
gum style --foreground 212 --bold "$1"
else
echo "--- $1 ---"
fi
}
run_with_spinner() {
local title="$1"; shift
if $HAS_GUM; then
# Run command in background — gum spin can't invoke shell functions
# directly. Keep its output so a failure remains diagnosable.
local command_log="$SB_TMPDIR/spinner-${RANDOM}.log"
"$@" >"$command_log" 2>&1 &
local cmd_pid=$!
gum spin --spinner dot --title "$title" -- bash -c "tail --pid=$cmd_pid -f /dev/null"
local rc=0
wait "$cmd_pid" || rc=$?
if [ $rc -eq 0 ]; then
gum style --foreground 2 "✓ ${title%...}"
else
printf '%s\n' "${title%...} failed:" >&2
cat "$command_log" >&2
fi
return $rc
else
echo "$title"
"$@"
fi
}
# Install Ubuntu Box-tier packages with an explicit, non-interactive sudo
# contract. Build-only third-party sources are removed by the Dockerfile, so a
# failed update is authoritative rather than silently using stale indexes.
apt_install() {
# /etc/localtime is a read-only bind-mount in the running container (see
# docker-compose.yml), so tzdata's postinst can never rewrite it: any apt
# run that pulls a tzdata upgrade dies on a "device or resource busy" mv,
# wedges dpkg half-configured, and cascades to every dependent (python3,
# fish, …) — silently, since we discard output. Freeze tzdata (the host
# owns the timezone via the mount) and install non-interactively so no
# postinst can block on a debconf prompt in this tty-less context.
local _apt_log
if dpkg-query -W -f='${Status}' tzdata 2>/dev/null | grep -q 'ok installed'; then
if ! _apt_log=$(sudo -n apt-mark hold tzdata 2>&1); then
echo "apt_install: unable to hold tzdata under the read-only /etc/localtime contract" >&2
printf '%s\n' "$_apt_log" >&2
return 1
fi
fi
if ! _apt_log=$(sudo -n apt-get update -qq 2>&1); then
echo "apt_install: package index refresh failed" >&2
printf '%s\n' "$_apt_log" | tail -30 >&2
return 1
fi
if ! _apt_log=$(DEBIAN_FRONTEND=noninteractive sudo -n apt-get install -y -qq "$@" 2>&1); then
echo "apt_install: failed to install: $*" >&2
printf '%s\n' "$_apt_log" | tail -30 >&2
return 1
fi
}
if $SB_RERUN; then
_sb_banner="🟧📦 squarebox setup (reconfigure)"
else
_sb_banner="🟧📦 squarebox setup"
fi
if $HAS_GUM; then
gum style --border double --padding "0 2" --border-foreground 208 "$_sb_banner"
else
echo "=== $_sb_banner ==="
fi
echo
# Git identity
if should_run git; then
# git config --file won't create parent dirs; ensure it exists before writing.
# In the compose/GHCR pull path ~/.config/git is not bind-mounted, so it may
# be absent inside the squarebox-home volume (issue: setup fails with
# "could not lock config file .../.config/git/config: No such file or directory").
mkdir -p ~/.config/git
_current_name=$(current_git_identity user.name)
_current_email=$(current_git_identity user.email)
if $SB_RERUN && [ -n "$_current_name" ] && $INTERACTIVE; then
# Existing identity on re-run: present it pre-filled so you can edit
# inline or just accept it. Empty input (cleared gum value or a blank
# read — i.e. hitting Enter) keeps the current value unchanged.
if $HAS_GUM; then
if ! name=$(gum input --value "$_current_name" --header "Git name:" --width 40); then cancel_setup; fi
else
read -rp "Git name [$_current_name]: " name
fi
[ -z "$name" ] && name="$_current_name"
if $HAS_GUM; then
if ! email=$(gum input --value "$_current_email" --header "Git email:" --width 40); then cancel_setup; fi
else
read -rp "Git email [$_current_email]: " email
fi
[ -z "$email" ] && email="$_current_email"
else
if [ -z "$_current_name" ]; then
if $INTERACTIVE; then
while true; do
if $HAS_GUM; then
if ! name=$(gum input --placeholder "Your Name" --header "Git name:" --width 40); then cancel_setup; fi
else
read -rp "Git name: " name
fi
[ -n "$name" ] && break
echo "Name cannot be empty."
done
else
echo "Skipping git identity setup (non-interactive)"
fi
fi
if [ -z "$_current_email" ]; then
if $INTERACTIVE; then
while true; do
if $HAS_GUM; then
if ! email=$(gum input --placeholder "you@example.com" --header "Git email:" --width 40); then cancel_setup; fi
else
read -rp "Git email: " email
fi
[ -n "$email" ] && break
echo "Email cannot be empty."
done
fi
fi
fi
# Commit the identity only after every prompt completed; cancelling the
# email prompt cannot leave a partially changed name behind.
[ -n "${name:-}" ] && git config --file ~/.config/git/config user.name "$name"
[ -n "${email:-}" ] && git config --file ~/.config/git/config user.email "$email"
fi
# GitHub CLI config lives at ~/.config/gh (the gh default) and is preserved
# by the squarebox-home named volume. The legacy persistence path
# (/workspace/.squarebox/gh) is migrated once for users upgrading from a
# pre-named-volume install; new installs never touch it. The legacy paths
# are removed after a successful copy so the migration is self-healing and
# we don't leave stale credentials sitting in /workspace.
GH_PERSIST_LEGACY="/workspace/.squarebox/gh"
GH_SKIP_MARKER="$HOME/.squarebox-gh-skip"
GH_SKIP_MARKER_LEGACY="/workspace/.squarebox/gh-skip"
if [ -d "$GH_PERSIST_LEGACY" ] && [ ! -d ~/.config/gh ]; then
mkdir -p ~/.config
if cp -r "$GH_PERSIST_LEGACY" ~/.config/gh; then
rm -rf "$GH_PERSIST_LEGACY"
fi
fi
# Migrate legacy skip marker into $HOME so it persists with the rest of state.
if [ -f "$GH_SKIP_MARKER_LEGACY" ] && [ ! -f "$GH_SKIP_MARKER" ]; then
touch "$GH_SKIP_MARKER"
rm -f "$GH_SKIP_MARKER_LEGACY"
fi
# GitHub CLI (optional — users who don't use GitHub can skip this)
if should_run github; then
if gh auth status &>/dev/null; then
rm -f "$GH_SKIP_MARKER"
if $SB_RERUN && $INTERACTIVE; then
echo "GitHub CLI: already authenticated"
gh auth status 2>&1 | head -5 || true
if $HAS_GUM; then
gum_confirm_or_cancel "Re-authenticate?" --default=false && _do_reauth=true || _do_reauth=false
else
read -rp "Re-authenticate? [y/N]: " _reauth_reply
case "${_reauth_reply:-N}" in
[Yy]*) _do_reauth=true ;;
*) _do_reauth=false ;;
esac
fi
if $_do_reauth; then
BROWSER=echo gh auth login
fi
else
echo "GitHub CLI: already authenticated"
fi
elif [ -f "$GH_SKIP_MARKER" ]; then
if $SB_RERUN && $INTERACTIVE; then
echo "GitHub CLI: previously skipped"
if $HAS_GUM; then
gum_confirm_or_cancel "Sign in to GitHub?" --default=true && do_gh_login=true || do_gh_login=false
else
read -rp "Sign in to GitHub? [Y/n]: " gh_reply
case "${gh_reply:-Y}" in
[Nn]*) do_gh_login=false ;;
*) do_gh_login=true ;;
esac
fi
if $do_gh_login; then
echo "Logging into GitHub..."
BROWSER=echo gh auth login
if gh auth status &>/dev/null; then
rm -f "$GH_SKIP_MARKER"
else
echo "GitHub CLI auth was not completed — skipping"
fi
fi
else
echo "GitHub CLI: sign-in skipped (run 'gh auth login' to change)"
fi
elif $INTERACTIVE; then
echo
if $HAS_GUM; then
gum_confirm_or_cancel "Sign in to GitHub?" --default=true && do_gh_login=true || do_gh_login=false
else
read -rp "Sign in to GitHub? [Y/n]: " gh_reply
case "${gh_reply:-Y}" in
[Nn]*) do_gh_login=false ;;
*) do_gh_login=true ;;
esac
fi
if $do_gh_login; then
echo "Logging into GitHub..."
# BROWSER=echo makes gh print the auth URL instead of trying to open a browser
BROWSER=echo gh auth login
if gh auth status &>/dev/null; then
rm -f "$GH_SKIP_MARKER"
else
echo "GitHub CLI auth was not completed — skipping"
fi
else
touch "$GH_SKIP_MARKER"
echo "Skipping GitHub CLI sign-in (run 'gh auth login' later if you change your mind)"
fi
else
echo "Skipping GitHub CLI auth (non-interactive)"
fi
fi
# Shared infrastructure (needed by multiple sections)
mkdir -p ~/.local/bin
export PATH="$HOME/.local/bin:$PATH"
# Translate managed bash aliases into Fish syntax and keep the Fish selection
# snippet current even when only ai/editors/tuis is re-run.
_squarebox_bash_line_to_fish() {
local line="$1"
case "$line" in
"export PATH="*)
local val="${line#export PATH=}"
val="${val#\"}"; val="${val%\"}"
val="${val#\'}"; val="${val%\'}"
echo "set -x PATH ${val//:/ }"
;;
"export "*=*)
local rest="${line#export }"
local name="${rest%%=*}"
local val="${rest#*=}"
val="${val#\"}"; val="${val%\"}"
val="${val#\'}"; val="${val%\'}"
echo "set -x $name $val"
;;
"alias "*=*) echo "$line" ;;
esac
}
_refresh_fish_selections() {
local conf_dir="$HOME/.config/fish/conf.d"
[ -d "$conf_dir" ] || return 0
local sel_out="$conf_dir/squarebox-selections.fish"
{
echo "# Generated by setup.sh from ~/.squarebox-* bash files."
local src _sq_line
for src in \
"$HOME/.squarebox-ai-aliases" \
"$HOME/.squarebox-editor-aliases" \
"$HOME/.squarebox-tui-aliases"; do
[ -f "$src" ] || continue
echo "# --- from $(basename "$src") ---"
while IFS= read -r _sq_line; do
_squarebox_bash_line_to_fish "$_sq_line"
done < "$src"
done
} > "$sel_out"
}
# Optional tools install the latest upstream release at setup time.
# Pinned versions live only in the Dockerfile tier (checksums.txt).
#
# SDKs are managed by mise (jdx/mise) — a single polyglot version manager
# replaces the previous per-language grab-bag (nvm, uv, Go tarball, .NET
# script, rustup). mise itself is installed in the Dockerfile tier and
# activated by ~/.bashrc. We write tool selections to ~/.config/mise/config.toml
# via `mise use -g`, which both registers the tool and triggers install.
# Make mise-installed binaries visible in *this* shell. dotfiles/bashrc
# already runs `mise activate bash`, but setup.sh on first launch may execute
# in an environment where mise wasn't yet on PATH (or the shims dir is empty
# and gets repopulated mid-script). Re-eval is cheap and idempotent.
_squarebox_mise_activate() {
command -v mise >/dev/null 2>&1 || return 0
eval "$(mise activate bash --shims)"
export PATH="$HOME/.local/share/mise/shims:$PATH"
}
_install_mise_sdk_inner() {
mise use -g "$1@${2:-latest}"
}
_install_mise_sdk() {
local tool="$1" label="$2" version="${3:-latest}"
if ! command -v mise >/dev/null 2>&1; then
echo "Error: mise is not installed (expected at /usr/local/bin/mise)" >&2
return 1
fi
if mise which "$tool" >/dev/null 2>&1 && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then
echo "${label} already installed, skipping."
return 0
fi
run_with_spinner "Installing/updating ${label} (via mise)..." _install_mise_sdk_inner "$tool" "$version" || return 1
_squarebox_mise_activate
if ! mise which "$tool" >/dev/null 2>&1; then
echo "Error: ${label} not available after mise install" >&2
return 1
fi
}
install_node() { _install_mise_sdk node "Node.js"; }
install_python() { _install_mise_sdk python "Python"; }
install_go() { _install_mise_sdk go "Go"; }
install_dotnet() { _install_mise_sdk dotnet ".NET"; }
install_rust() { _install_mise_sdk rust "Rust"; }
# Ensure Node.js is available for npm-based AI tools
ensure_node_for_npm() {
_squarebox_mise_activate
if command -v node &>/dev/null; then return 0; fi
install_node || return 1
_squarebox_mise_activate
# Persist Node.js in SDK config so it survives rebuilds
local sdk_cfg="$SB_STATE_DIR/sdks"
if [ -f "$sdk_cfg" ]; then
local sdk_current
sdk_current=$(cat "$sdk_cfg")
if [[ ",$sdk_current," != *",node,"* ]] && [ "$sdk_current" != "node" ]; then
echo "${sdk_current:+$sdk_current,}node" > "$sdk_cfg"
fi
else
echo "node" > "$sdk_cfg"
fi
}
ensure_node_major_for_npm() {
local minimum="$1" major=""
_squarebox_mise_activate
if command -v node >/dev/null 2>&1; then
major=$(node -p 'Number(process.versions.node.split(".")[0])' 2>/dev/null || true)
fi
if [[ "$major" =~ ^[0-9]+$ ]] && [ "$major" -ge "$minimum" ]; then
return 0
fi
_install_mise_sdk node "Node.js ${minimum}+" "$minimum" || return 1
_squarebox_mise_activate
major=$(node -p 'Number(process.versions.node.split(".")[0])' 2>/dev/null || true)
if [[ ! "$major" =~ ^[0-9]+$ ]] || [ "$major" -lt "$minimum" ]; then
echo "Error: Node.js ${minimum}+ is required (observed '${major:-missing}')" >&2
return 1
fi
local sdk_cfg="$SB_STATE_DIR/sdks" sdk_current=""
[ -f "$sdk_cfg" ] && sdk_current=$(cat "$sdk_cfg")
if [[ ",$sdk_current," != *",node,"* ]]; then
printf '%s\n' "${sdk_current:+$sdk_current,}node" > "$sdk_cfg"
fi
}
# AI coding assistant
if should_run ai; then
AI_CONFIG="$SB_STATE_DIR/ai-tool"
ai_prev=""
ai_cancelled=false
if [ -f "$AI_CONFIG" ]; then
ai_prev=$(cat "$AI_CONFIG")
fi
if $INTERACTIVE; then
echo
section_header "AI Coding Assistants"
if $HAS_GUM; then
# Build --selected from previously saved AI tools
gum_selected=""
for ai in $(echo "$ai_prev" | tr ',' ' '); do
case "$ai" in
claude) gum_selected="${gum_selected:+$gum_selected,}Claude Code" ;;
copilot) gum_selected="${gum_selected:+$gum_selected,}GitHub Copilot CLI" ;;
gemini) gum_selected="${gum_selected:+$gum_selected,}Google Gemini CLI" ;;
codex) gum_selected="${gum_selected:+$gum_selected,}OpenAI Codex CLI" ;;
opencode) gum_selected="${gum_selected:+$gum_selected,}OpenCode" ;;
pi) gum_selected="${gum_selected:+$gum_selected,}Pi Coding Agent" ;;
esac
done
gum_args=(--no-limit --header "Select AI coding assistants (space=toggle, enter=confirm):")
[ -n "$gum_selected" ] && gum_args+=(--selected "$gum_selected")
if ! selected=$(gum choose "${gum_args[@]}" \
"Claude Code" "GitHub Copilot CLI" "Google Gemini CLI" \
"OpenAI Codex CLI" "OpenCode" "Pi Coding Agent"); then
cancel_setup
fi
ai_choice=""
while ! $ai_cancelled && IFS= read -r line; do
case "$line" in
"Claude Code") ai_choice="${ai_choice:+$ai_choice,}claude" ;;
"GitHub Copilot CLI") ai_choice="${ai_choice:+$ai_choice,}copilot" ;;
"Google Gemini CLI") ai_choice="${ai_choice:+$ai_choice,}gemini" ;;
"OpenAI Codex CLI") ai_choice="${ai_choice:+$ai_choice,}codex" ;;
"OpenCode") ai_choice="${ai_choice:+$ai_choice,}opencode" ;;
"Pi Coding Agent") ai_choice="${ai_choice:+$ai_choice,}pi" ;;
esac
done <<< "$selected"
else
echo "Select AI coding assistants (comma-separated, 'all', or press Enter to skip):"
for ai_item in "1:claude:Claude Code" "2:copilot:GitHub Copilot CLI" "3:gemini:Google Gemini CLI" "4:codex:OpenAI Codex CLI" "5:opencode:OpenCode" "6:pi:Pi Coding Agent"; do
num="${ai_item%%:*}"; rest="${ai_item#*:}"; key="${rest%%:*}"; label="${rest#*:}"
if [[ ",$ai_prev," == *",${key},"* ]]; then
echo " ${num}) ${label} [installed]"
else
echo " ${num}) ${label}"
fi
done
read -rp "Selection [1-6/all/skip]: " ai_selection
if [ -z "$ai_selection" ] && [ -n "$ai_prev" ]; then
ai_choice="$ai_prev"
else
ai_choice=""
if [ "$ai_selection" = "all" ]; then
ai_choice="claude,copilot,gemini,codex,opencode,pi"
elif [ -n "$ai_selection" ]; then
for item in $(echo "$ai_selection" | tr ',' ' '); do
case "$item" in
1) ai_choice="${ai_choice:+$ai_choice,}claude" ;;
2) ai_choice="${ai_choice:+$ai_choice,}copilot" ;;
3) ai_choice="${ai_choice:+$ai_choice,}gemini" ;;
4) ai_choice="${ai_choice:+$ai_choice,}codex" ;;
5) ai_choice="${ai_choice:+$ai_choice,}opencode" ;;
6) ai_choice="${ai_choice:+$ai_choice,}pi" ;;
esac
done
fi
fi
fi
elif [ -n "$ai_prev" ]; then
ai_choice="$ai_prev"
echo "Installing AI tools: $ai_choice (from previous selection)"
else
echo "Defaulting to Claude Code (non-interactive)"
ai_choice="claude"
fi
supported_ai=()
for ai_tool in $(echo "$ai_choice" | tr ',' ' '); do
case "$ai_tool" in
claude|copilot|gemini|codex|opencode|pi) supported_ai+=("$ai_tool") ;;
*) echo "Warning: removing unsupported AI assistant from Selection: $ai_tool" >&2 ;;
esac
done
ai_choice=$(join_csv "${supported_ai[@]}")
install_copilot() {
if command -v copilot &>/dev/null && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then echo "GitHub Copilot CLI already installed, skipping."; return 0; fi
ensure_node_major_for_npm 22 || return 1
run_with_spinner "Installing/updating GitHub Copilot CLI..." npm install -g --silent @github/copilot || return 1
command -v copilot >/dev/null 2>&1
}
install_gemini() {
if command -v gemini &>/dev/null && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then echo "Google Gemini CLI already installed, skipping."; return 0; fi
ensure_node_for_npm || return 1
run_with_spinner "Installing/updating Google Gemini CLI..." npm install -g --silent @google/gemini-cli || return 1
command -v gemini >/dev/null 2>&1
}
install_codex() {
if command -v codex &>/dev/null && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then echo "OpenAI Codex CLI already installed, skipping."; return 0; fi
ensure_node_for_npm || return 1
run_with_spinner "Installing/updating OpenAI Codex CLI..." npm install -g --silent @openai/codex || return 1
command -v codex >/dev/null 2>&1
}
install_pi() {
if command -v pi &>/dev/null && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then echo "Pi Coding Agent already installed, skipping."; return 0; fi
ensure_node_for_npm || return 1
# --ignore-scripts is the upstream-recommended install flag (see pi.dev).
run_with_spinner "Installing/updating Pi Coding Agent..." npm install -g --silent --ignore-scripts @earendil-works/pi-coding-agent || return 1
command -v pi >/dev/null 2>&1
}
install_claude() {
if command -v claude >/dev/null 2>&1 && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then
echo "Claude Code already installed, skipping."
return 0
fi
local installer="$SB_TMPDIR/claude-install.sh"
curl -fsSL https://claude.ai/install.sh -o "$installer" || return 1
bash "$installer" || return 1
command -v claude >/dev/null 2>&1
}
ai_command_present() {
case "$1" in
claude) command -v claude >/dev/null 2>&1 ;;
copilot) command -v copilot >/dev/null 2>&1 ;;
gemini) command -v gemini >/dev/null 2>&1 ;;
codex) command -v codex >/dev/null 2>&1 ;;
opencode) command -v opencode >/dev/null 2>&1 ;;
pi) command -v pi >/dev/null 2>&1 ;;
*) return 1 ;;
esac
}
if ! $ai_cancelled; then
installed_ai=()
committed_ai=()
for ai_tool in $(echo "$ai_choice" | tr ',' ' '); do
ai_ok=false
case "$ai_tool" in
claude)
# Trust boundary: the Claude Code install script manages its own binary
# fetching and verification. We rely on HTTPS for script integrity.
run_with_spinner "Installing/updating Claude Code..." install_claude && ai_ok=true
;;
opencode)
if command -v opencode &>/dev/null && { ! $SB_RERUN || $SB_RECONCILE_BOX; }; then
echo "OpenCode already installed, skipping."
ai_ok=true
else
run_with_spinner "Installing/updating OpenCode..." sb_install opencode latest \
&& command -v opencode >/dev/null 2>&1 && ai_ok=true
fi
;;
copilot) install_copilot && ai_ok=true ;;
gemini) install_gemini && ai_ok=true ;;
codex) install_codex && ai_ok=true ;;
pi) install_pi && ai_ok=true ;;
esac
if $ai_ok; then
installed_ai+=("$ai_tool")
committed_ai+=("$ai_tool")
else
record_failure "$ai_tool installation failed; new Selection was not committed"
ai_command_present "$ai_tool" && installed_ai+=("$ai_tool")
[[ ",$ai_prev," == *",$ai_tool,"* ]] && committed_ai+=("$ai_tool")
fi
done
ai_choice=$(join_csv "${committed_ai[@]}")
observed_ai=$(join_csv "${installed_ai[@]}")
printf '%s\n' "$ai_choice" > "$AI_CONFIG"
# Set aliases based on selection — c maps to first selected tool in priority order
{
c_target=""
for ai_tool in claude copilot gemini codex opencode pi; do
if [[ ",$observed_ai," == *",$ai_tool,"* ]]; then
[ -z "$c_target" ] && c_target="$ai_tool"
case "$ai_tool" in
claude) echo "alias claude-yolo='claude --dangerously-skip-permissions'" ;;
opencode) echo "alias opencode-yolo='opencode --dangerously-skip-permissions'" ;;
esac
fi
done
if [ -n "$c_target" ]; then
case "$c_target" in
copilot) echo "alias c='copilot'" ;;
*) echo "alias c='$c_target'" ;;
esac
fi
} > ~/.squarebox-ai-aliases
fi # ! ai_cancelled
fi # should_run ai
# Text editors
if should_run editors; then
EDITOR_CONFIG="$SB_STATE_DIR/editors"
EDITOR_DEFAULT_CONFIG="$SB_STATE_DIR/editor-default"
editor_prev=""
editor_default_prev=""
editor_cancelled=false
if [ -f "$EDITOR_CONFIG" ]; then
editor_prev=$(cat "$EDITOR_CONFIG")
fi
if [ -f "$EDITOR_DEFAULT_CONFIG" ]; then
editor_default_prev=$(cat "$EDITOR_DEFAULT_CONFIG")
case "$editor_default_prev" in
nano|micro|edit|fresh|hx|nvim) ;;
*) echo "Warning: ignoring invalid saved default editor '$editor_default_prev'." >&2; editor_default_prev="" ;;
esac
fi
if $INTERACTIVE; then
echo
section_header "Text Editors"
if $HAS_GUM; then
# Build --selected from previously saved editors
gum_selected=""
for ed in $(echo "$editor_prev" | tr ',' ' '); do
case "$ed" in
micro) gum_selected="${gum_selected:+$gum_selected,}micro" ;;
edit) gum_selected="${gum_selected:+$gum_selected,}edit" ;;
fresh) gum_selected="${gum_selected:+$gum_selected,}fresh" ;;
helix) gum_selected="${gum_selected:+$gum_selected,}helix" ;;
nvim) gum_selected="${gum_selected:+$gum_selected,}nvim" ;;
esac
done
echo "Nano is always available and remains the fallback default unless you choose an installed editor instead."
gum_args=(--no-limit --header "Select text editors to install:")
[ -n "$gum_selected" ] && gum_args+=(--selected "$gum_selected")
if ! selected=$(gum choose "${gum_args[@]}" \
"micro" "edit" "fresh" "helix" "nvim"); then
cancel_setup
fi
editor_list=""
while IFS= read -r line; do
[ -z "$line" ] && continue
editor_list="${editor_list:+$editor_list,}${line}"
done <<< "$selected"
else
echo "Select text editors to install (comma-separated, or 'all', or press Enter to skip):"
echo " Nano is always available and remains the fallback default unless you choose an installed editor instead."
for ed_item in "1:micro:micro" "2:edit:edit" "3:fresh:fresh" "4:helix:helix (hx)" "5:nvim:nvim"; do
num="${ed_item%%:*}"; rest="${ed_item#*:}"; key="${rest%%:*}"; label="${rest#*:}"
case "$key" in
micro) desc="modern, intuitive terminal editor" ;;
edit) desc="terminal text editor (Microsoft)" ;;
fresh) desc="modern terminal text editor" ;;
helix) desc="modal editor (Kakoune-inspired)" ;;
nvim) desc="Neovim" ;;
esac
if [[ ",$editor_prev," == *",${key},"* ]]; then
echo " ${num}) ${label} — ${desc} [installed]"
else
echo " ${num}) ${label} — ${desc}"
fi
done
read -rp "Selection [1,2,3,4,5/all/skip]: " editor_selection
if [ -z "$editor_selection" ] && [ -n "$editor_prev" ]; then
editor_list="$editor_prev"
else
editor_list=""
if [ "$editor_selection" = "all" ]; then
editor_list="micro,edit,fresh,helix,nvim"
elif [ -n "$editor_selection" ]; then
for item in $(echo "$editor_selection" | tr ',' ' '); do
case "$item" in
1) editor_list="${editor_list:+$editor_list,}micro" ;;
2) editor_list="${editor_list:+$editor_list,}edit" ;;
3) editor_list="${editor_list:+$editor_list,}fresh" ;;
4) editor_list="${editor_list:+$editor_list,}helix" ;;
5) editor_list="${editor_list:+$editor_list,}nvim" ;;
esac
done
fi
fi
fi
elif [ -n "$editor_prev" ]; then
editor_list="$editor_prev"
[ -n "$editor_list" ] && echo "Installing editors: $editor_list (from previous selection)"
else
echo "Skipping editor selection (non-interactive)"
editor_list=""
fi
if ! $editor_cancelled; then
# LazyVim starter — offered when Neovim is among the selected editors
LAZYVIM_CONFIG="$SB_STATE_DIR/nvim-lazyvim"
LAZYVIM_SHA_CONFIG="$SB_STATE_DIR/nvim-lazyvim-sha"
lazyvim_prev=""
[ -f "$LAZYVIM_CONFIG" ] && lazyvim_prev=$(cat "$LAZYVIM_CONFIG")
lazyvim_choice=false
if [[ ",$editor_list," == *",nvim,"* ]]; then
if $INTERACTIVE; then
lv_default=true
[ "$lazyvim_prev" = "false" ] && lv_default=false
echo
echo "LazyVim turns Neovim into a preconfigured IDE (needs a Nerd Font in your terminal for icons)."
if $HAS_GUM; then
if gum confirm "Install the LazyVim starter config for Neovim?" --default="$lv_default"; then
lazyvim_choice=true
else
confirm_rc=$?
[ "$confirm_rc" -gt 1 ] && cancel_setup
lazyvim_choice=false
fi
else
if $lv_default; then _lv_hint="Y/n"; else _lv_hint="y/N"; fi
read -rp "Install the LazyVim starter config for Neovim? [$_lv_hint]: " _lv_reply
if [ -z "$_lv_reply" ]; then
lazyvim_choice=$lv_default
else
case "$_lv_reply" in [Yy]*) lazyvim_choice=true ;; *) lazyvim_choice=false ;; esac
fi
fi
elif [ -n "$lazyvim_prev" ]; then
lazyvim_choice="$lazyvim_prev"
fi
fi
install_micro() {
if command -v micro &>/dev/null; then echo "Micro already installed, skipping."; return 0; fi
run_with_spinner "Installing Micro..." sb_install micro latest || return 1
command -v micro >/dev/null 2>&1
}
install_edit() {
if command -v edit &>/dev/null; then echo "Edit already installed, skipping."; return 0; fi
run_with_spinner "Installing Edit..." sb_install edit latest || return 1
command -v edit >/dev/null 2>&1
}
install_fresh() {
if command -v fresh &>/dev/null; then echo "Fresh already installed, skipping."; return 0; fi
run_with_spinner "Installing Fresh..." sb_install fresh latest || return 1
command -v fresh >/dev/null 2>&1
}
install_helix() {
if command -v hx &>/dev/null && [ -d "$HOME/.config/helix/runtime" ]; then
echo "Helix already installed, skipping."
return 0
fi
run_with_spinner "Installing Helix..." sb_install helix latest || return 1
command -v hx >/dev/null 2>&1 && [ -d "$HOME/.config/helix/runtime" ]
}
install_nvim() {
if command -v nvim &>/dev/null; then echo "Neovim already installed, skipping."; return 0; fi
run_with_spinner "Installing Neovim..." sb_install nvim latest || return 1
command -v nvim >/dev/null 2>&1
}
_lazyvim_default_sha() {
local repo=LazyVim/starter api_base repo_body branch encoded_branch commit_body sha rc
api_base="${SB_GITHUB_API_BASE:-https://api.github.com}"
repo_body=$(_sb_gh_api_get "${api_base}/repos/${repo}" "${repo} repository metadata") || {
rc=$?; return "$rc"
}
branch=$(printf '%s' "$repo_body" | jq -er \
'.default_branch | select(type == "string" and length > 0)' 2>/dev/null) || {
echo "Error: no valid default branch in GitHub metadata for $repo" >&2
return 1
}
[[ "$branch" =~ ^[A-Za-z0-9._/-]+$ ]] \
&& [[ "$branch" != /* ]] && [[ "$branch" != */ ]] \
&& [[ "$branch" != *..* ]] && [[ "$branch" != *//* ]] || {
echo "Error: unsafe default branch in GitHub metadata for $repo" >&2
return 1
}
encoded_branch=$(printf '%s' "$branch" | jq -sRr '@uri') || return 1
commit_body=$(_sb_gh_api_get \
"${api_base}/repos/${repo}/commits/${encoded_branch}" \
"${repo} default branch ${branch}") || {
rc=$?; return "$rc"
}
sha=$(printf '%s' "$commit_body" | jq -er \
'.sha | select(type == "string" and test("^[0-9a-f]{40}$"))' 2>/dev/null) || {
echo "Error: no valid commit SHA in GitHub metadata for $repo" >&2
return 1
}
printf '%s\n' "$sha"
}
install_lazyvim() {
local sha
# nvim-treesitter may compile parsers after a Box replacement. The starter
# config persists in the Managed home, but its compiler is Box-tier state.
if [ -L "$HOME/.config/nvim" ]; then
echo "Error: refusing symlinked LazyVim destination: $HOME/.config/nvim" >&2
return 1
fi
if [ -e "$HOME/.config/nvim" ]; then
echo "~/.config/nvim already exists, skipping LazyVim starter clone."
return 0
fi
# Resolve immutable source identity before installing a compiler or changing
# the Managed home. Metadata failure is authoritative.
sha=$(_lazyvim_default_sha) || return 1
if ! command -v cc &>/dev/null && ! command -v gcc &>/dev/null; then
apt_install build-essential || return 1
fi
run_with_spinner "Installing LazyVim starter..." _install_lazyvim_inner "$sha" || return 1
printf '%s\n' "$sha" > "$LAZYVIM_SHA_CONFIG"
}
_install_lazyvim_inner() {
local sha="$1" stage head rc=0
[[ "$sha" =~ ^[0-9a-f]{40}$ ]] || return 1
mkdir -p "$HOME/.config" || return 1
# Stage beside the destination so the final rename stays within the Managed
# home filesystem; /tmp may be a different mount and expose a partial copy.
stage=$(mktemp -d "$HOME/.config/.nvim.squarebox-stage.XXXXXX") || return 1
git init -q "$stage" >/dev/null 2>&1 || rc=$?
[ "$rc" -ne 0 ] || git -C "$stage" remote add origin https://github.com/LazyVim/starter.git >/dev/null 2>&1 || rc=$?
[ "$rc" -ne 0 ] || git -C "$stage" fetch --depth=1 --no-tags origin "$sha" >/dev/null 2>&1 || rc=$?
[ "$rc" -ne 0 ] || git -C "$stage" checkout --detach "$sha" >/dev/null 2>&1 || rc=$?
if [ "$rc" -eq 0 ]; then
head=$(git -C "$stage" rev-parse --verify HEAD 2>/dev/null) || rc=$?
fi
if [ "$rc" -eq 0 ] && [ "$head" != "$sha" ]; then
echo "Error: LazyVim starter HEAD verification failed" >&2
rc=1
fi
[ "$rc" -ne 0 ] || rm -rf -- "$stage/.git" || rc=$?
[ "$rc" -ne 0 ] || mv -T -- "$stage" "$HOME/.config/nvim" || rc=$?
if [ "$rc" -ne 0 ]; then
rm -rf -- "$stage"
return "$rc"
fi
}
installed_editors=()
committed_editors=()
for editor in $(echo "$editor_list" | tr ',' ' '); do
case "$editor" in
micro)
if install_micro; then installed_editors+=("micro"); committed_editors+=("micro")
else record_failure "Micro installation failed; new Selection was not committed"; [[ ",$editor_prev," == *",micro,"* ]] && committed_editors+=("micro"); fi ;;
edit)
if install_edit; then installed_editors+=("edit"); committed_editors+=("edit")
else record_failure "Edit installation failed; new Selection was not committed"; [[ ",$editor_prev," == *",edit,"* ]] && committed_editors+=("edit"); fi ;;
fresh)
if install_fresh; then installed_editors+=("fresh"); committed_editors+=("fresh")
else record_failure "Fresh installation failed; new Selection was not committed"; [[ ",$editor_prev," == *",fresh,"* ]] && committed_editors+=("fresh"); fi ;;
helix)
if install_helix; then installed_editors+=("hx"); committed_editors+=("helix")
else record_failure "Helix installation failed; new Selection was not committed"; [[ ",$editor_prev," == *",helix,"* ]] && committed_editors+=("helix"); fi ;;
nvim)
if install_nvim; then installed_editors+=("nvim"); committed_editors+=("nvim")
else record_failure "Neovim installation failed; new Selection was not committed"; [[ ",$editor_prev," == *",nvim,"* ]] && committed_editors+=("nvim"); fi ;;
esac
done
editor_list=$(join_csv "${committed_editors[@]}")
# Bootstrap LazyVim starter config when chosen and Neovim is available
if [ "$lazyvim_choice" = "true" ] && command -v nvim &>/dev/null; then
if install_lazyvim; then
printf 'true\n' > "$LAZYVIM_CONFIG"
else
record_failure "LazyVim starter setup failed; Selection was not committed"
printf 'false\n' > "$LAZYVIM_CONFIG"
fi
elif [[ ",$editor_list," == *",nvim,"* ]]; then
printf 'false\n' > "$LAZYVIM_CONFIG"
fi
# Prompt for the default editor if multiple were installed. Persist this
# separately from the editor set so noninteractive Box reconciliation cannot