Repository navigation
Expand file tree
/
Copy pathstart.sh
More file actions
executable file
·1093 lines (949 loc) · 42 KB
/
Copy pathstart.sh
File metadata and controls
executable file
·1093 lines (949 loc) · 42 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
# ─── Lumiverse Launcher (macOS / Linux) ───────────────────────────────────────
# Usage:
# ./start.sh Start backend, serve pre-built frontend (default)
# ./start.sh -b|--build Rebuild frontend before starting backend
# ./start.sh -a|--auto-open Open the default browser after the backend starts
# ./start.sh --build-only Build frontend only, don't start backend
# ./start.sh --backend-only Start backend only, skip frontend serving
# ./start.sh --dev Start backend in watch mode (no frontend build)
# ./start.sh --setup Run setup wizard only
# ./start.sh --reset-password Reset owner account password
# ./start.sh --edit-env Edit the .env configuration file in a terminal editor
# ./start.sh -m|--migrate-st Run SillyTavern migration helper
# ./start.sh -k|--kill-pkgs Nuke lockfiles + node_modules, reinstall backend deps
# ./start.sh --install-desktop Build/install Tauri desktop app and create launcher shortcuts
# ./start.sh --no-runner Start without the visual runner
# ./start.sh --safe-theme Suppress custom CSS/component overrides for recovery
# ./start.sh --upgrade-bun Upgrade Bun to the latest stable release before running
# ./start.sh --upgrade-bun-canary Upgrade Bun to the latest canary build before running
#
# Bun versions older than 1.4.4 are automatically upgraded to latest stable.
#
# Environment overrides:
# FRONTEND_PATH Path to frontend directory (default: ./frontend)
# ──────────────────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
info() { echo -e "${CYAN}[info]${NC} $*"; }
ok() { echo -e "${GREEN}[ok]${NC} $*"; }
warn() { echo -e "${YELLOW}[warn]${NC} $*"; }
err() { echo -e "${RED}[error]${NC} $*" >&2; }
# ─── Platform detection ─────────────────────────────────────────────────────
IS_TERMUX=false
IS_PROOT=false
TERMUX_BUN_METHOD="" # "direct" | "grun" | "proot" — how to invoke bun on Termux
TERMUX_BUN_PATH="" # Full resolved path to bun binary (needed for grun/proot)
# Detect native Termux: $PREFIX is always set in Termux shell sessions
if [[ -n "${PREFIX:-}" && -d "/data/data/com.termux" ]]; then
IS_TERMUX=true
# Detect proot-distro inside Termux (running a full Linux distro)
elif [[ -f "/etc/os-release" && -d "/data/data/com.termux" ]] 2>/dev/null; then
IS_PROOT=true
fi
# ─── Bun execution wrapper ─────────────────────────────────────────────────
# On Termux, the raw bun binary can't execute natively (glibc vs bionic libc).
# _bun routes through the best available method. _proot_bun always wraps in
# proot for operations that need syscall interception (e.g. bun install).
_bun() {
if [[ "$IS_TERMUX" == true && -n "$TERMUX_BUN_PATH" ]]; then
case "$TERMUX_BUN_METHOD" in
direct)
# bun-termux wrapper handles linker + /proc/self/exe
"$TERMUX_BUN_PATH" "$@" ;;
grun)
# glibc-runner invokes ld.so explicitly (must use full path)
grun "$TERMUX_BUN_PATH" "$@" ;;
proot)
# proot intercepts syscalls + explicit glibc linker invocation
proot --link2symlink -0 \
"${PREFIX}/glibc/lib/ld-linux-aarch64.so.1" \
--library-path "${PREFIX}/glibc/lib" \
"$TERMUX_BUN_PATH" "$@" ;;
*)
"$TERMUX_BUN_PATH" "$@" ;;
esac
else
bun "$@"
fi
}
# Like _bun but guarantees proot wrapping — used for bun install where
# Android's seccomp filter blocks syscalls even when grun works otherwise.
_proot_bun() {
local bun_path="${TERMUX_BUN_PATH:-$(command -v bun 2>/dev/null || echo "$HOME/.bun/bin/bun")}"
local glibc_ld="${PREFIX:-/data/data/com.termux/files/usr}/glibc/lib/ld-linux-aarch64.so.1"
if [[ "$TERMUX_BUN_METHOD" == "direct" ]]; then
# bun-termux wrapper handles linker; proot adds syscall interception
proot --link2symlink -0 "$bun_path" "$@"
elif [[ "$TERMUX_BUN_METHOD" == "grun" ]]; then
# Keep using grun inside proot. Reconstructing ld.so manually can drift
# from the user's installed glibc-runner layout and pass `--version`
# probes while still failing the real `bun install` path.
proot --link2symlink -0 grun "$bun_path" "$@"
elif [[ -x "$glibc_ld" ]]; then
# Explicit glibc linker + proot for full coverage
proot --link2symlink -0 "$glibc_ld" --library-path "${PREFIX}/glibc/lib" "$bun_path" "$@"
else
# Last resort — hope proot alone handles it
proot --link2symlink -0 "$bun_path" "$@"
fi
}
update_bun_termux_components() {
local component="$1"
local repo="$HOME/.bun-termux"
if [[ -d "$repo" ]]; then
if [[ -d "$repo/.git" ]] && ! (cd "$repo" && git pull --ff-only); then
warn "Could not update bun-termux checkout — using the existing copy"
fi
else
info "Installing bun-termux..."
git clone https://github.com/Happ1ness-dev/bun-termux.git "$repo" || return 1
fi
local manager="$repo/helper_scripts/bun-termux-manager"
if [[ ! -f "$manager" ]]; then
err "The bun-termux checkout does not contain its update manager."
err "Remove $repo and retry so Lumiverse can install a current checkout."
return 1
fi
case "$component" in
bun)
bash "$manager" update bun
;;
wrapper)
bash "$manager" update wrapper --source "$repo"
;;
all)
bash "$manager" update all --source "$repo"
;;
*)
err "Unknown bun-termux update component: $component"
return 1
;;
esac
}
rebuild_bun_termux_wrapper() {
info "Rebuilding bun-termux wrapper..."
update_bun_termux_components wrapper
}
upgrade_bun_termux() {
local before="$1"
info "Updating the Bun runtime..."
update_bun_termux_components bun || return 1
_resolve_bun || true
local after
after="$(_bun --version 2>/dev/null || echo unknown)"
if [[ "$after" == "$before" ]]; then
info "Termux wrapper unchanged because the Bun version did not change"
return 0
fi
info "Bun changed: $before -> $after; rebuilding bun-termux wrapper..."
update_bun_termux_components wrapper
}
verify_termux_bun_install_path() {
[[ "$IS_TERMUX" == true ]] || return 0
# Native Termux always installs packages through _proot_bun, so validate the
# exact wrapper chain we will later use for `bun install`.
if (_proot_bun --version) &>/dev/null 2>&1; then
return 0
fi
warn "Native Termux Bun probe failed for the proot-wrapped install path"
warn "grun/direct version checks may pass even when bun install will not"
if rebuild_bun_termux_wrapper && _resolve_bun && (_proot_bun --version) &>/dev/null 2>&1; then
ok "Recovered a working native Termux Bun install path"
return 0
fi
err "Native Termux Bun is not install-capable in the current shell."
err "Lumiverse needs a Bun path that survives the proot-wrapped install probe."
err "This usually means bun-termux or glibc-runner is stale or partially installed."
err "Repair it on native Termux, then retry:"
err " ./start.sh --upgrade-bun"
err " pkg reinstall glibc-runner proot"
exit 1
}
# ─── Parse arguments ─────────────────────────────────────────────────────────
MODE="all" # all | build-only | backend-only | dev | setup | reset-password | edit-env | migrate-st | kill-pkgs | install-desktop
USE_RUNNER=true
FORCE_BUILD=false
AUTO_OPEN=false
SAFE_THEME=false
BUN_UPGRADE_CHANNEL="" # "" | "stable" | "canary"
MINIMUM_BUN_VERSION="1.4.4"
for arg in "$@"; do
case "$arg" in
--build|-b) FORCE_BUILD=true ;;
--auto-open|-a) AUTO_OPEN=true ;;
--build-only) MODE="build-only" ;;
--backend-only) MODE="backend-only" ;;
--dev) MODE="dev" ;;
--setup) MODE="setup" ;;
--reset-password) MODE="reset-password" ;;
--edit-env) MODE="edit-env" ;;
--migrate-st|-m) MODE="migrate-st" ;;
--kill-pkgs|-k) MODE="kill-pkgs" ;;
--install-desktop|--desktop) MODE="install-desktop" ;;
--no-runner) USE_RUNNER=false ;;
--safe-theme) SAFE_THEME=true ;;
--upgrade-bun) BUN_UPGRADE_CHANNEL="stable" ;;
--upgrade-bun-canary) BUN_UPGRADE_CHANNEL="canary" ;;
--help|-h)
sed -n '3,21p' "$0" | sed 's/^# *//'
exit 0
;;
*) err "Unknown argument: $arg"; exit 1 ;;
esac
done
# ─── Resolve paths ───────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKEND_DIR="$SCRIPT_DIR"
FRONTEND_DIR="${FRONTEND_PATH:-$SCRIPT_DIR/frontend}"
# Keep these aligned with frontend/package.json overrides and optionalDependencies.
# Rolldown 1.2.4 includes the Android ARMv8.0 SIGILL fix.
TERMUX_FRONTEND_NATIVE_DEPS=(
"@rolldown/binding-android-arm64@1.2.4"
"lightningcss-android-arm64@1.33.0"
)
# ─── Ensure Bun is installed ────────────────────────────────────────────────
# Try to find bun in PATH or common install locations.
# Called at the start and after install attempts.
_resolve_bun() {
# Load Bun env early — catches cases where Bun was previously installed
# but the current shell session hasn't sourced the profile yet.
export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
export PATH="$BUN_INSTALL/bin:$PATH"
[[ -f "$BUN_INSTALL/env" ]] && source "$BUN_INSTALL/env"
if [[ "$IS_TERMUX" == true ]]; then
TERMUX_BUN_METHOD=""
TERMUX_BUN_PATH=""
fi
# Build list of candidate paths
local candidates=()
local found
found="$(command -v bun 2>/dev/null || true)"
[[ -n "$found" ]] && candidates+=("$found")
candidates+=(
"$BUN_INSTALL/bin/bun"
"$HOME/.bun/bin/bun"
"/root/.bun/bin/bun"
)
for try in "${candidates[@]}"; do
[[ -x "$try" ]] || continue
# On Termux, the binary may exist with +x but fail to execute due to
# missing glibc linker or seccomp restrictions. Verify it actually runs.
if [[ "$IS_TERMUX" == true ]]; then
# Tier 1: direct execution (bun-termux wrapper or native)
# Subshell suppresses shell-level signal diagnostics (e.g. "Bad system call")
if ("$try" --version) &>/dev/null 2>&1; then
TERMUX_BUN_METHOD="direct"
TERMUX_BUN_PATH="$try"
# Only add raw bun to PATH when it can execute natively
export PATH="$(dirname "$try"):$PATH"
return 0
fi
# Tier 2: grun (glibc-runner) — invokes glibc's ld.so explicitly
# Don't add raw bun to PATH — it can't execute without grun
if command -v grun &>/dev/null && (grun "$try" --version) &>/dev/null 2>&1; then
TERMUX_BUN_METHOD="grun"
TERMUX_BUN_PATH="$try"
return 0
fi
# Tier 3: proot + explicit glibc linker (slower but most compatible)
# Don't add raw bun to PATH — it can't execute without proot
local glibc_ld="${PREFIX:-}/glibc/lib/ld-linux-aarch64.so.1"
if [[ -x "$glibc_ld" ]] && command -v proot &>/dev/null \
&& (proot --link2symlink -0 "$glibc_ld" --library-path "${PREFIX}/glibc/lib" "$try" --version) &>/dev/null 2>&1; then
TERMUX_BUN_METHOD="proot"
TERMUX_BUN_PATH="$try"
return 0
fi
continue # Binary exists but can't execute — try next candidate
fi
export PATH="$(dirname "$try"):$PATH"
return 0
done
return 1
}
# Install the standard Termux autobuild signing key when the current Termux
# channel does not package glibc-repo (notably the Google Play channel).
_install_termux_autobuild_key() {
local key_dir="${PREFIX}/etc/apt/trusted.gpg.d"
local key_file="${key_dir}/lumiverse-termux-autobuilds.gpg"
local key_url="https://raw.githubusercontent.com/termux/termux-packages/fc8cedb2e0a6ac296133631390823bf70d349281/packages/termux-keyring/termux-autobuilds.gpg"
local key_sha256="21c385d5a30107453bd60582d64e2f6e5f5ce11e340ac05e57f943f9c0235420"
local temp_key
if [[ -f "$key_file" ]] \
&& printf '%s %s\n' "$key_sha256" "$key_file" | sha256sum -c - &>/dev/null; then
return 0
fi
mkdir -p "$key_dir"
temp_key="$(mktemp "${TMPDIR:-${PREFIX}/tmp}/lumiverse-termux-key.XXXXXX")"
if ! curl --retry 3 -fsSL "$key_url" -o "$temp_key"; then
rm -f "$temp_key"
return 1
fi
if ! printf '%s %s\n' "$key_sha256" "$temp_key" | sha256sum -c - &>/dev/null; then
err "Downloaded Termux repository signing key failed verification."
rm -f "$temp_key"
return 1
fi
install -m 600 "$temp_key" "$key_file"
rm -f "$temp_key"
ok "Installed verified Termux autobuild repository signing key"
}
# Install Termux prerequisites for running glibc-linked Bun binaries.
# Bun is compiled against glibc, but Termux uses Android's bionic libc.
# We need glibc-runner to bridge the gap, plus bun-termux for a proper
# wrapper that handles /proc/self/exe, hardlink stubs, and path remapping.
_install_bun_termux() {
info "Termux detected — installing Bun with glibc compatibility layer..."
if ! command -v pkg &>/dev/null; then
err "Termux 'pkg' package manager not found."
exit 1
fi
local glibc_sources_dir="${PREFIX}/etc/apt/sources.list.d"
local glibc_source_file="${glibc_sources_dir}/glibc.list"
local glibc_repo_entry="deb https://packages-cf.termux.dev/apt/termux-glibc/ glibc stable"
local saved_glibc_source=""
local restore_glibc_source=false
local migrate_glibc_source=false
# Resume cleanly if an earlier setup attempt stopped while this source was
# temporarily disabled (for example, because the network dropped).
if [[ -f "$glibc_source_file" ]]; then
sed -i -E 's/^# Lumiverse setup: temporarily disabled: (deb[[:space:]].*termux-glibc.*)$/\1/' "$glibc_source_file"
fi
# Keep an existing glibc source out of the first package refresh. Older
# launchers wrote an invalid suite, while Google Play Termux installations
# may not have the official repository signing key linked yet. Re-enable the
# source after refreshing termux-keyring from the main repository, preserving
# any valid custom mirror the user already configured.
if [[ -f "$glibc_source_file" ]] \
&& grep -Eq '^[[:space:]]*deb[[:space:]].*termux-glibc' "$glibc_source_file"; then
saved_glibc_source="$(cat "$glibc_source_file")"
restore_glibc_source=true
if grep -Eq 'packages(-cf)?\.termux\.dev/apt/termux-glibc/?[[:space:]]+stable[[:space:]]+main' "$glibc_source_file"; then
migrate_glibc_source=true
restore_glibc_source=false
fi
warn "Temporarily disabling the Termux glibc repository while refreshing its signing key..."
sed -i -E '/^[[:space:]]*deb[[:space:]].*termux-glibc/s/^/# Lumiverse setup: temporarily disabled: /' "$glibc_source_file"
fi
# ── Step 1: Base packages ────────────────────────────────────────────────
info "Installing base Termux prerequisites..."
pkg update -y
info "Refreshing Termux repository signing keys..."
pkg reinstall -y termux-keyring
pkg install -y git curl build-essential proot
# ── Step 2: Set up the glibc repository ──────────────────────────────────
# glibc-runner lives in a separate repo (termux-glibc), NOT the default
# termux-main repo. The glibc-repo package registers this repo source.
info "Setting up glibc package repository..."
local glibc_runner_installed=false
# Try installing glibc-repo (the repo enabler package)
if pkg install -y glibc-repo 2>/dev/null; then
info "glibc repository registered, refreshing package lists..."
else
warn "glibc-repo package not available — adding glibc repository manually..."
if command -v apt-get &>/dev/null && ! _install_termux_autobuild_key; then
err "Could not install the verified signing key for the Termux glibc repository."
exit 1
fi
fi
# Restore a valid custom mirror, migrate only the known-broken legacy entry,
# or add the canonical source if glibc-repo did not create one.
mkdir -p "$glibc_sources_dir"
if [[ "$restore_glibc_source" == true ]]; then
printf '%s\n' "$saved_glibc_source" > "$glibc_source_file"
elif [[ "$migrate_glibc_source" == true ]] \
|| ! grep -Eq '^[[:space:]]*deb[[:space:]].*termux-glibc' "$glibc_source_file" 2>/dev/null; then
echo "$glibc_repo_entry" > "$glibc_source_file"
fi
# Refresh package lists to pick up the glibc repo
pkg update -y
# ── Step 3: Install glibc-runner ─────────────────────────────────────────
if pkg install -y glibc-runner 2>/dev/null; then
glibc_runner_installed=true
ok "glibc-runner installed via apt"
else
warn "glibc-runner not found — refreshing package lists and retrying..."
if pkg update -y 2>/dev/null && pkg install -y glibc-runner 2>/dev/null; then
glibc_runner_installed=true
ok "glibc-runner installed after refreshing package lists"
fi
fi
# ── Step 4: Pacman fallback ──────────────────────────────────────────────
if [[ "$glibc_runner_installed" != true ]]; then
warn "apt-based glibc-runner install failed — trying pacman fallback..."
if pkg install -y pacman 2>/dev/null; then
pacman-key --init 2>/dev/null || true
pacman-key --populate 2>/dev/null || true
if pacman -Sy --noconfirm glibc-runner 2>/dev/null; then
glibc_runner_installed=true
ok "glibc-runner installed via pacman"
fi
fi
fi
if [[ "$glibc_runner_installed" != true ]]; then
warn "Could not install glibc-runner through any method."
warn "Bun may still work via proot fallback, or consider using proot-distro:"
warn " pkg install proot-distro && proot-distro install ubuntu"
warn " proot-distro login ubuntu"
warn " # Then re-run this script inside the Ubuntu environment"
fi
# The official Bun installer downloads the linux-aarch64 glibc binary,
# which is exactly what we need — glibc-runner will execute it.
touch "$HOME/.bashrc" 2>/dev/null || true
curl -fsSL https://bun.sh/install | bash
source "$HOME/.bashrc" 2>/dev/null || true
export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
export PATH="$BUN_INSTALL/bin:$PATH"
[[ -f "$BUN_INSTALL/env" ]] && source "$BUN_INSTALL/env"
# Install bun-termux wrapper (userland-exec + LD_PRELOAD shim). Use the
# upstream manager instead of `make install`: the latter copies directly
# over the live wrapper and Android rejects that with ETXTBSY.
# This replaces the raw bun binary with a wrapper that:
# - Loads glibc's ld-linux via userland exec (fixes /proc/self/exe)
# - Intercepts syscalls for Android filesystem compatibility
# - Remaps shebang paths to Termux prefix
if rebuild_bun_termux_wrapper; then
ok "bun-termux wrapper installed"
else
warn "bun-termux wrapper build failed — will use grun (glibc-runner) fallback"
fi
# Determine which execution method works (same 3-tier detection as _resolve_bun)
local bun_bin="${BUN_INSTALL}/bin/bun"
local glibc_ld="${PREFIX}/glibc/lib/ld-linux-aarch64.so.1"
if [[ -x "$bun_bin" ]] && ("$bun_bin" --version) &>/dev/null 2>&1; then
TERMUX_BUN_METHOD="direct"
TERMUX_BUN_PATH="$bun_bin"
elif command -v grun &>/dev/null && (grun "$bun_bin" --version) &>/dev/null 2>&1; then
TERMUX_BUN_METHOD="grun"
TERMUX_BUN_PATH="$bun_bin"
warn "Using grun (glibc-runner) to execute Bun — bun-termux wrapper not functional"
elif [[ -x "$glibc_ld" ]] && command -v proot &>/dev/null \
&& (proot --link2symlink -0 "$glibc_ld" --library-path "${PREFIX}/glibc/lib" "$bun_bin" --version) &>/dev/null 2>&1; then
TERMUX_BUN_METHOD="proot"
TERMUX_BUN_PATH="$bun_bin"
warn "Using proot + glibc linker to execute Bun (slower — bun-termux and grun both failed)"
fi
}
# Set up convenience aliases in Termux's ~/.bashrc when proot-distro is available.
# This lets users type 'p' to enter proot or 'l' to launch Lumiverse directly.
setup_proot_aliases() {
if [[ "$IS_TERMUX" != true ]]; then return; fi
if ! command -v proot-distro &>/dev/null; then return; fi
local bashrc="$HOME/.bashrc"
# Skip if aliases already exist (ours or user-defined) to avoid duplicates
if [[ -f "$bashrc" ]] && grep -qE "^alias [pl]=" "$bashrc"; then
return
fi
info "proot-distro detected — adding convenience aliases to ~/.bashrc..."
touch "$bashrc" 2>/dev/null || true
cat >> "$bashrc" <<'ALIASES'
# Lumiverse proot-distro aliases
alias p='proot-distro login ubuntu'
alias l='proot-distro login ubuntu -- bash -lc "export BUN_INSTALL=/root/.bun; export PATH=\$BUN_INSTALL/bin:\$PATH; echo Using bun at: /root/.bun/bin/bun; /root/.bun/bin/bun --version; cd /root/Lumiverse && ./start.sh"'
ALIASES
ok "Added aliases to ~/.bashrc: 'p' (proot login), 'l' (launch Lumiverse in proot)"
# Refresh environment so aliases and env vars take effect in this session
source "$bashrc" 2>/dev/null || true
}
ensure_bun() {
# ── Try to resolve an existing Bun installation ──────────────────────────
if _resolve_bun; then
verify_termux_bun_install_path
# Capture only the first line — bun may dump its full help text to stdout
# through some execution methods, and we don't want that in the status line
local ver
ver="$(_bun --version 2>/dev/null | head -1 || echo 'unknown')"
case "$TERMUX_BUN_METHOD" in
grun) ok "Bun $ver found (via glibc-runner)" ;;
proot) ok "Bun $ver found (via proot + glibc linker)" ;;
*) ok "Bun $ver found" ;;
esac
return
fi
# ── No Bun found — install it ───────────────────────────────────────────
warn "Bun not found. Installing..."
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then
err "On Windows, please run start.ps1 instead, or install Bun manually:"
err " powershell -c \"irm bun.sh/install.ps1 | iex\""
exit 1
fi
if [[ "$IS_TERMUX" == true ]]; then
_install_bun_termux
else
curl -fsSL https://bun.sh/install | bash
fi
# ── Make bun available in this session ──────────────────────────────────
if _resolve_bun; then
verify_termux_bun_install_path
local ver
ver="$(_bun --version 2>/dev/null | head -1 || echo 'unknown')"
case "$TERMUX_BUN_METHOD" in
grun) ok "Bun $ver installed (via glibc-runner)" ;;
proot) ok "Bun $ver installed (via proot + glibc linker)" ;;
*) ok "Bun $ver installed successfully" ;;
esac
return
fi
# ── Installation failed ─────────────────────────────────────────────────
if [[ "$IS_TERMUX" == true ]]; then
err "Bun installation failed on Termux."
err "You can also try running inside proot-distro:"
err " pkg install proot-distro && proot-distro install ubuntu"
err " proot-distro login ubuntu"
err " # Then re-run this script inside the Ubuntu environment"
else
err "Bun installation failed. Please install manually: https://bun.sh"
fi
exit 1
}
# ─── Bun channel upgrades and minimum-version recovery ──────────────────────
# Honors --upgrade-bun / --upgrade-bun-canary and also upgrades versions below
# MINIMUM_BUN_VERSION to latest stable. Runs after ensure_bun so the binary
# exists; `bun upgrade [--canary|--stable]` swaps the binary in-place
# at $BUN_INSTALL/bin/bun. On native Termux we cannot use `bun upgrade` —
# Bun's built-in updater probes for `ld` and aborts ("unsupported on systems
# without ld") because Termux uses bionic, not glibc. Instead we use the
# bun-termux manager, which atomically replaces the underlying `buno` runtime.
# The wrapper is rebuilt only when that update changes the Bun version; a no-op
# stable update leaves the already-working wrapper alone. Atomic replacement is
# required because Android will not allow `cp` to truncate an executable that is
# currently mapped.
upgrade_bun_channel() {
local channel="$1"
local before
before="$(_bun --version 2>/dev/null || echo unknown)"
# ── Native Termux path ────────────────────────────────────────────────────
# proot-distro (IS_PROOT) is a real glibc env, so it falls through to the
# standard `bun upgrade` path below.
if [[ "$IS_TERMUX" == true ]]; then
if [[ "$channel" == "canary" ]]; then
warn "Bun canary upgrades are not supported by Lumiverse's native Termux path."
warn "The bun-termux manager downloads official stable Bun releases."
warn "Skipping this upgrade; keeping the existing $before binary."
warn "If you specifically need canary, run inside a proot-distro Linux instead."
return 0
fi
info "Updating Bun to official stable through bun-termux (current: $before)..."
if ! upgrade_bun_termux "$before"; then
err "bun-termux upgrade failed. Continuing with the available Bun runtime."
return 0
fi
_resolve_bun
verify_termux_bun_install_path
local after
after="$(_bun --version 2>/dev/null || echo unknown)"
if [[ "$after" == "$before" ]]; then
ok "Bun $after is already up to date"
else
ok "Bun upgraded via bun-termux: $before -> $after"
fi
return 0
fi
# ── Standard path (macOS, Linux, proot-distro, WSL, etc.) ─────────────────
if [[ "$channel" == "canary" ]]; then
info "Upgrading Bun to latest canary (current: $before)..."
if ! _bun upgrade --canary; then
err "Bun canary upgrade failed. Continuing with the existing $before binary."
return 0
fi
else
info "Upgrading Bun to latest stable (current: $before)..."
# `--stable` is a no-op for users already on stable but forces a switch
# back from canary for anyone who previously opted in.
if ! _bun upgrade --stable; then
err "Bun stable upgrade failed. Continuing with the existing $before binary."
return 0
fi
fi
local after
after="$(_bun --version 2>/dev/null || echo unknown)"
ok "Bun upgraded: $before -> $after"
}
upgrade_bun_if_requested() {
[[ -z "$BUN_UPGRADE_CHANNEL" ]] && return 0
upgrade_bun_channel "$BUN_UPGRADE_CHANNEL"
}
bun_version_at_least() {
local current="${1%%-*}"
local required="${2%%-*}"
local current_major=0 current_minor=0 current_patch=0
local required_major=0 required_minor=0 required_patch=0
IFS=. read -r current_major current_minor current_patch <<< "$current"
IFS=. read -r required_major required_minor required_patch <<< "$required"
[[ "$current_major" =~ ^[0-9]+$ ]] || return 1
[[ "$current_minor" =~ ^[0-9]+$ ]] || return 1
[[ "$current_patch" =~ ^[0-9]+$ ]] || return 1
if (( current_major != required_major )); then
(( current_major > required_major ))
elif (( current_minor != required_minor )); then
(( current_minor > required_minor ))
else
(( current_patch >= required_patch ))
fi
}
ensure_minimum_bun_version() {
local current
current="$(_bun --version 2>/dev/null | head -1 || echo unknown)"
if bun_version_at_least "$current" "$MINIMUM_BUN_VERSION"; then
return 0
fi
warn "Bun $current is below Lumiverse's minimum $MINIMUM_BUN_VERSION."
info "Automatically upgrading Bun to the latest stable release..."
upgrade_bun_channel "stable"
_resolve_bun || true
current="$(_bun --version 2>/dev/null | head -1 || echo unknown)"
if bun_version_at_least "$current" "$MINIMUM_BUN_VERSION"; then
verify_termux_bun_install_path
ok "Bun $current satisfies the minimum supported version"
return 0
fi
err "Bun $current is still below the required $MINIMUM_BUN_VERSION."
if [[ "$IS_TERMUX" == true ]]; then
err "Retry ./start.sh --upgrade-bun when the official Bun download is reachable."
err "Runtime source: https://github.com/oven-sh/bun/releases (Bun >= $MINIMUM_BUN_VERSION)."
err "Wrapper source: https://github.com/Happ1ness-dev/bun-termux."
else
err "Install the latest stable Bun release from https://bun.sh, then retry."
fi
exit 1
}
# ─── First-run setup wizard ─────────────────────────────────────────────────
run_setup_if_needed() {
local identity_file="$BACKEND_DIR/data/lumiverse.identity"
local credentials_file="$BACKEND_DIR/data/owner.credentials"
# A migrated data folder is already set up even if .env was not copied.
# The backend can fall back to defaults for missing .env values.
if [[ ! -f "$identity_file" || ! -f "$credentials_file" ]]; then
info "First run detected — launching setup wizard..."
echo ""
install_deps "$BACKEND_DIR" "backend"
(cd "$BACKEND_DIR" && _bun run scripts/setup-wizard.ts)
# Verify the wizard actually created the critical data files.
# On some platforms (Termux) the interactive prompts can fail silently.
if [[ ! -f "$identity_file" || ! -f "$credentials_file" ]]; then
err "Setup wizard did not create the required identity and owner credentials."
err "Files expected at: $identity_file and $credentials_file"
err "Try running the wizard manually: ./start.sh --setup"
exit 1
fi
fi
}
run_setup() {
install_deps "$BACKEND_DIR" "backend"
(cd "$BACKEND_DIR" && _bun run scripts/setup-wizard.ts)
}
run_reset_password() {
install_deps "$BACKEND_DIR" "backend"
info "Launching password reset..."
(cd "$BACKEND_DIR" && _bun run scripts/reset-password.ts)
}
run_migrate_st() {
install_deps "$BACKEND_DIR" "backend"
info "Launching SillyTavern migration helper..."
(cd "$BACKEND_DIR" && _bun run scripts/migrate-sillytavern.ts)
}
run_edit_env() {
# No dep install — edit-env.ts only uses Bun built-ins + local ui/input
# helpers, so it's a quick hop to the editor (handy before first setup).
(cd "$BACKEND_DIR" && _bun run scripts/edit-env.ts)
}
open_browser() {
local url="$1"
if [[ "$OSTYPE" == "darwin"* ]] && command -v open &>/dev/null; then
open "$url" &>/dev/null &
elif command -v xdg-open &>/dev/null; then
xdg-open "$url" &>/dev/null &
elif command -v termux-open-url &>/dev/null; then
termux-open-url "$url" &>/dev/null &
elif [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then
cmd /c start "" "$url" &>/dev/null &
else
warn "Could not find a browser opener for $url"
fi
}
# ─── Kill packages (nuke + reinstall) ──────────────────────────────────────
kill_pkgs() {
warn "Removing lockfiles and node_modules..."
rm -f "$BACKEND_DIR/bun.lock"
rm -f "$FRONTEND_DIR/bun.lock"
rm -rf "$BACKEND_DIR/node_modules"
rm -rf "$FRONTEND_DIR/node_modules"
ok "Cleaned lockfiles and node_modules from backend and frontend"
install_deps "$BACKEND_DIR" "backend"
ok "Backend dependencies reinstalled (frontend deps will install on next build)"
}
# ─── Install dependencies ───────────────────────────────────────────────────
repair_termux_frontend_native_deps() {
local dir="$1"
[[ "$IS_TERMUX" == true || "$IS_PROOT" == true ]] || return 0
info "Repairing Termux frontend native bindings with npm..."
(cd "$dir" && npm cache clean --force)
(cd "$dir" && npm install --force --no-save --no-package-lock --include=optional --no-audit --no-fund "${TERMUX_FRONTEND_NATIVE_DEPS[@]}")
ok "Termux frontend native bindings repaired"
}
run_bun_dependency_install() {
local dir="$1"
if [[ "$IS_TERMUX" == true ]]; then
# Android doesn't support hardlinks — use file copy backend instead.
# Clear Bun's install cache first — filesystem emulation can corrupt
# cached packages, causing random "Cannot find package" errors.
if [[ -d "$HOME/.bun/install/cache" ]]; then
rm -rf "$HOME/.bun/install/cache"
fi
# Always wrap bun install in proot on Termux — Android's seccomp filter
# blocks certain syscalls that bun install needs, causing "Bad system call"
# (SIGSYS) errors. _proot_bun handles both linker and syscall issues.
# --ignore-scripts avoids proot getcwd() failures in dependency lifecycle
# scripts; affected packages have pure-JS fallbacks.
(cd "$dir" && _proot_bun install --backend=copyfile --ignore-scripts)
elif [[ "$IS_PROOT" == true ]]; then
if [[ -d "$HOME/.bun/install/cache" ]]; then
rm -rf "$HOME/.bun/install/cache"
fi
(cd "$dir" && bun install --backend=copyfile --ignore-scripts)
else
(cd "$dir" && bun install)
fi
}
verify_backend_dependencies() {
local dir="$1"
# glibc-runner/grun currently word-splits argv containing spaces on Termux.
# Keep eval probes whitespace-free so fallback runtimes receive one intact -e arg.
(cd "$dir" && _bun -e "await(import('better-auth'));await(import('@better-auth/oauth-provider'))")
}
verify_frontend_dependencies() {
local dir="$1"
# Exercise the browser-facing import that reaches Better Auth's transitive
# core files. Direct-package checks do not catch a partially extracted core.
(cd "$dir" && _bun -e "await(import('@better-auth/oauth-provider/client'))")
}
verify_dependencies() {
local dir="$1"
local name="$2"
if [[ "$name" == "backend" ]]; then
verify_backend_dependencies "$dir"
elif [[ "$name" == "frontend" ]]; then
verify_frontend_dependencies "$dir"
fi
}
install_deps() {
local dir="$1"
local name="$2"
# Stamp written only after `bun install` exits 0. Its absence next to an
# existing node_modules means a previous install was interrupted (crash,
# kill, OOM, proot path-translation error mid-stream) — tree can't be
# trusted, so nuke node_modules and reinstall from scratch.
local stamp="$dir/node_modules/.lumiverse-install-complete"
if [[ -d "$dir/node_modules" && ! -f "$stamp" ]]; then
warn "Detected interrupted $name install — removing node_modules and retrying..."
rm -rf "$dir/node_modules"
fi
info "Installing $name dependencies..."
local install_status=0
run_bun_dependency_install "$dir" || install_status=$?
if [[ $install_status -ne 0 ]]; then
err "$name install failed (exit $install_status) — node_modules will be cleaned on next launch"
return $install_status
fi
if [[ "$name" == "backend" || "$name" == "frontend" ]] && ! verify_dependencies "$dir" "$name"; then
warn "$name dependency validation failed; clearing the package cache and reinstalling from a clean tree..."
_bun pm cache rm >/dev/null 2>&1 || true
rm -rf "$dir/node_modules"
install_status=0
run_bun_dependency_install "$dir" || install_status=$?
if [[ $install_status -ne 0 ]]; then
err "$name clean reinstall failed (exit $install_status)"
return $install_status
fi
if ! verify_dependencies "$dir" "$name"; then
err "$name dependencies are still unreadable after a clean reinstall"
return 1
fi
ok "$name dependency tree repaired"
fi
if [[ "$name" == "frontend" ]]; then
repair_termux_frontend_native_deps "$dir"
fi
# Stamp success so next launch knows this tree is complete.
touch "$stamp" 2>/dev/null || true
ok "$name dependencies installed"
}
# ─── Build frontend ─────────────────────────────────────────────────────────
build_frontend() {
if [[ ! -d "$FRONTEND_DIR" ]]; then
err "Frontend directory not found at: $FRONTEND_DIR"
err "Set FRONTEND_PATH to the correct location."
exit 1
fi
install_deps "$FRONTEND_DIR" "frontend"
info "Building frontend..."
(
cd "$FRONTEND_DIR"
# Keep every Bun hop behind _bun on Termux. Package-script aliases such as
# `bun run build` recurse through a shell and can resolve the raw glibc Bun
# binary, bypassing grun/proot and failing with "required file not found".
_bun run scripts/extract-props.ts
_bun run scripts/extract-css-vars.ts
_bun run scripts/build-frontend.ts
)
ok "Frontend built -> $FRONTEND_DIR/dist"
}
# ─── Start backend ──────────────────────────────────────────────────────────
start_backend() {
local frontend_dist=""
# Point to frontend dist if it exists (skip in dev mode — Vite proxies)
if [[ "$MODE" != "dev" && -d "$FRONTEND_DIR/dist" ]]; then
frontend_dist="$FRONTEND_DIR/dist"
info "Serving frontend from: $frontend_dist"
elif [[ "$MODE" != "dev" ]]; then
warn "No frontend build found. Backend will start without serving frontend."
warn "Run './start.sh --build-only' first, or use './start.sh --build' to build + start."
fi
install_deps "$BACKEND_DIR" "backend"
# Clear Bun install cache to avoid stale tarballs after updates
_bun pm cache rm >/dev/null 2>&1 || true
# Export FRONTEND_DIR for the backend process
export FRONTEND_DIR="$frontend_dist"
# Load .env for PORT and other vars
if [[ -f "$BACKEND_DIR/.env" ]]; then
set -a
source "$BACKEND_DIR/.env"
set +a
fi
if [[ "$SAFE_THEME" == true ]]; then
export LUMIVERSE_SAFE_THEME=true
warn "Safe theme mode enabled: custom CSS and component overrides are suppressed"
fi
# smol (low-memory GC mode) defaults on; operators disable it persistently
# via LUMIVERSE_SMOL=false in .env (survives auto-updates, unlike bunfig.toml).
# The visual runner applies this itself in scripts/runner/server-manager.ts;
# this only covers the plain (no-runner) launch below. Use a scalar (not an
# array) so the empty case expands cleanly under macOS bash 3.2 + `set -u`.
local smol_flag="--smol"
case "$(printf '%s' "${LUMIVERSE_SMOL:-}" | tr '[:upper:]' '[:lower:]')" in
false|0|off|no) smol_flag="" ;;
esac
# Decide: visual runner or plain process
if [[ "$USE_RUNNER" == true ]] && [[ -t 1 ]]; then
# Interactive terminal — use the visual runner (fall back to plain if it crashes)
local runner_args=()
local runner_status=0
if [[ "$MODE" == "dev" || "$AUTO_OPEN" == true ]]; then
runner_args+=("--")
fi
if [[ "$MODE" == "dev" ]]; then
runner_args+=("--dev")
fi
if [[ "$AUTO_OPEN" == true ]]; then
runner_args+=("--auto-open")
fi
# macOS ships Bash 3.2; under `set -u`, "${runner_args[@]}" errors if empty.
if ((${#runner_args[@]})); then
(cd "$BACKEND_DIR" && _bun run scripts/runner.ts "${runner_args[@]}") || runner_status=$?
else
(cd "$BACKEND_DIR" && _bun run scripts/runner.ts) || runner_status=$?
fi
if [[ "$runner_status" -ne 0 ]]; then
warn "Visual runner failed — falling back to plain mode..."
USE_RUNNER=false
fi
fi
if [[ "$USE_RUNNER" != true ]]; then
# Non-interactive (piped, CI, --no-runner) — plain process
echo ""
echo -e "${BOLD}Starting Lumiverse Backend on port ${PORT:-7860}...${NC}"
echo ""
if [[ "$AUTO_OPEN" == true ]]; then
if [[ -n "${LUMIVERSE_TLS_CERT_FILE:-}${LUMIVERSE_TLS_CONFIG_FILE:-}" ]]; then