-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathrun.sh
More file actions
executable file
·1284 lines (1175 loc) · 42.3 KB
/
Copy pathrun.sh
File metadata and controls
executable file
·1284 lines (1175 loc) · 42.3 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/bash
# Better Agent — prod-mode launcher.
#
# Backend runs WITHOUT uvicorn --reload (no code hot-reload).
# Frontend is served as built static files from the backend port
# (no Vite dev server, no HMR).
#
# To pick up frontend OR backend code changes from a browser, the user
# clicks the "Refresh" button in the UI — it POSTs /api/admin/restart,
# which sets a flag file and SIGTERMs uvicorn. The loop below detects
# the flag, starts the new backend, then rebuilds the frontend while the
# backend serves the previous build. The page reloads after the atomic
# frontend swap completes.
#
# Ctrl+C terminates the loop (uvicorn exits without the flag set).
#
# The restart flag lives at ba_home()/restart_requested — same path the
# backend writes via `paths.ba_home()`.
#
# Auth credentials (username + argon2 hash + session secret) live in
# the macOS login keychain under service "better-agent", with legacy
# "better-claude" entries still read and reset.
set -e
set -o pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
BA_HOME="${BETTER_AGENT_HOME:-${BETTER_CLAUDE_HOME:-$HOME/.better-claude}}"
case "${1:-}" in
--install-service|--uninstall-service|--service-status)
case "$1" in
--install-service) SERVICE_ACTION=install ;;
--uninstall-service) SERVICE_ACTION=uninstall ;;
--service-status) SERVICE_ACTION=status ;;
esac
exec python3 "$DIR/scripts/run_service.py" "$SERVICE_ACTION" --checkout "$DIR" --home "$BA_HOME"
;;
--service-child)
export BETTER_AGENT_RUN_SH_SERVICE_CHILD=1
shift
;;
esac
bas_available() {
if [ "${BETTER_AGENT_RUN_SH_ASSUME_NO_BAS:-0}" = "1" ]; then
return 1
fi
command -v bas >/dev/null 2>&1 || [ -x "$HOME/ba-switch/bas" ]
}
bas_executable() {
if command -v bas >/dev/null 2>&1; then
command -v bas
return
fi
if [ -x "$HOME/ba-switch/bas" ]; then
printf '%s\n' "$HOME/ba-switch/bas"
return
fi
return 1
}
current_checkout_is_main_line() {
case "$(basename "$DIR")" in
*-main)
return 0
;;
esac
if command -v git >/dev/null 2>&1; then
local branch
branch="$(git -C "$DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
[ "$branch" = "main" ] || [ "$branch" = "master" ]
return
fi
return 1
}
main_checkout_for_current_line() {
local name parent candidate
name="$(basename "$DIR")"
parent="$(dirname "$DIR")"
case "$name" in
*-qa)
candidate="$parent/${name%-qa}-main"
;;
*)
candidate="$DIR-main"
;;
esac
if [ -x "$candidate/run.sh" ]; then
printf '%s\n' "$candidate"
return 0
fi
return 1
}
if [ "${BETTER_AGENT_RUN_SH_SERVICE_CHILD:-0}" != "1" ]; then
BAS_BIN="$(bas_executable || true)"
if [ -n "$BAS_BIN" ]; then
BAS_LINE="$("$BAS_BIN" resolve-line "$DIR" 2>/dev/null || true)"
if [[ "$BAS_LINE" =~ ^[a-z0-9][a-z0-9_.-]{0,31}$ ]]; then
echo "BAS owns this checkout as line $BAS_LINE; delegating startup"
exec "$BAS_BIN" exec-line "$BAS_LINE"
fi
fi
fi
if [ "${BETTER_AGENT_RUN_SH_SERVICE_CHILD:-0}" != "1" ] && ! bas_available && ! current_checkout_is_main_line; then
MAIN_CHECKOUT="$(main_checkout_for_current_line || true)"
if [ -n "$MAIN_CHECKOUT" ]; then
echo "bas is not installed; launching main checkout at $MAIN_CHECKOUT"
exec "$MAIN_CHECKOUT/run.sh" "$@"
fi
echo "bas is not installed and no sibling main checkout is available; launching current checkout at $DIR"
fi
export BETTER_AGENT_HOME="${BETTER_AGENT_HOME:-$BA_HOME}"
export BETTER_CLAUDE_HOME="${BETTER_CLAUDE_HOME:-$BA_HOME}"
FLAG="$BA_HOME/restart_requested"
RESULT="$BA_HOME/refresh_result.json"
BACKEND_LOG="$BA_HOME/backend-run.log"
KC_SVC="better-agent"
KC_LEGACY_SVC="better-claude"
export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$PATH"
PY=""
CREDENTIAL_AUTHORITY="$DIR/desktop/dist/BetterAgentCredentialAuthority/BetterAgentCredentialAuthority"
DEFAULT_BACKEND_PORT=18765
BACKEND_PORT="${BETTER_AGENT_BACKEND_PORT:-${BETTER_CLAUDE_BACKEND_PORT:-$DEFAULT_BACKEND_PORT}}"
GRACEFUL_RESTART_TIMEOUT_SECONDS="${BETTER_AGENT_GRACEFUL_RESTART_TIMEOUT_SECONDS:-8}"
if ! [[ "$GRACEFUL_RESTART_TIMEOUT_SECONDS" =~ ^[0-9]+$ ]] || [ "$GRACEFUL_RESTART_TIMEOUT_SECONDS" -lt 1 ]; then
GRACEFUL_RESTART_TIMEOUT_SECONDS=8
fi
# The venv is created by `uv`, which does not install `pip` into it. Drive
# dependency installs through `uv pip` against the venv's interpreter.
UV="$(command -v uv || echo "$HOME/.local/bin/uv")"
mkdir -p "$BA_HOME"
# Default topology path to $BA_HOME/topology.yaml when unset, so the
# multi-machine `nodes` infrastructure (node_store, /api/nodes,
# RemoteProviderProxy) loads if the file is present. Backend tolerates
# the file being absent — it just logs the load failure and runs in
# single-machine mode. Explicit env var overrides the default.
TOPOLOGY_PATH="${BETTER_AGENT_TOPOLOGY_PATH:-${BETTER_CLAUDE_TOPOLOGY_PATH:-$BA_HOME/topology.yaml}}"
export BETTER_AGENT_TOPOLOGY_PATH="$TOPOLOGY_PATH"
export BETTER_CLAUDE_TOPOLOGY_PATH="$TOPOLOGY_PATH"
# Lets /api/admin/restart reject unsafe self-termination when uvicorn was
# launched directly and no outer process exists to rebuild and respawn it.
export BETTER_AGENT_RUN_SH_SUPERVISOR=1
export BETTER_CLAUDE_RUN_SH_SUPERVISOR=1
# --- Keychain helpers ------------------------------------------------
# All calls shell out to /usr/bin/security so the ACL on every stored
# entry is owned by `security` itself — no GUI permission prompt when
# the backend later reads them. See backend/auth_secrets.py for the
# matching invariant.
kc_has() {
# Check existence only. Do NOT use `-g`: `-g` attempts to READ the
# stored password, which on some macOS versions returns non-zero
# when the binary doesn't have read-ACL access yet (chicken-and-
# egg on the very first read after add-generic-password). Without
# `-g` we just probe attributes — always permitted, no GUI prompt.
/usr/bin/security find-generic-password -s "$KC_SVC" -a "$1" >/dev/null 2>&1 \
|| /usr/bin/security find-generic-password -s "$KC_LEGACY_SVC" -a "$1" >/dev/null 2>&1
}
kc_set() {
/usr/bin/security add-generic-password -U -s "$KC_SVC" -a "$1" -w "$2"
/usr/bin/security add-generic-password -U -s "$KC_LEGACY_SVC" -a "$1" -w "$2"
}
kc_del() {
/usr/bin/security delete-generic-password -s "$KC_SVC" -a "$1" >/dev/null 2>&1 || true
/usr/bin/security delete-generic-password -s "$KC_LEGACY_SVC" -a "$1" >/dev/null 2>&1 || true
}
# --- --reset-auth ----------------------------------------------------
if [ "${1:-}" = "--reset-auth" ]; then
echo "This will WIPE the stored Better Agent credentials from the"
echo "macOS keychain (username, password hash, session secret)."
read -p "Type 'yes' to confirm: " ans
if [ "$ans" != "yes" ]; then
echo "Aborted."
exit 1
fi
kc_del username
kc_del password_hash
kc_del session_secret
rm -f "$BA_HOME/qr_auth_state.json"
echo "Wiped. Run ./run.sh to bootstrap new credentials."
exit 0
fi
bootstrap_hint() {
if [ "$(uname -s)" = "Darwin" ]; then
echo "Run ./scripts/install-macos.sh, then run ./run.sh again." >&2
return 0
fi
echo "Install the missing prerequisites listed above, then run ./run.sh again." >&2
}
ensure_base_prereqs() {
local missing=""
local cmd=""
for cmd in git npm node curl; do
if ! command -v "$cmd" >/dev/null 2>&1; then
missing="${missing}${missing:+ }$cmd"
fi
done
if [ ! -x "$UV" ]; then
missing="${missing}${missing:+ }uv"
fi
if [ -z "$missing" ]; then
return 0
fi
echo "Missing required startup tool(s): $missing" >&2
bootstrap_hint
exit 1
}
kill_port_listeners() {
local port="$1"
local pids=""
local attempts=0
if ! command -v lsof >/dev/null 2>&1; then
echo "Cannot kill listeners on :$port because lsof is not installed." >&2
return 1
fi
stop_known_better_agent_port_users "$port"
pids="$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | sort -u || true)"
if [ -n "$pids" ]; then
echo "$pids" | xargs kill -15 2>/dev/null || true
fi
while [ "$attempts" -lt 20 ]; do
pids="$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | sort -u || true)"
if [ -z "$pids" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 0.25
done
if [ -n "$pids" ]; then
echo "Force killing remaining PIDs on :$port..."
echo "$pids" | xargs kill -9 2>/dev/null || true
fi
sleep 0.5
pids="$(lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | sort -u || true)"
if [ -n "$pids" ]; then
echo "Port :$port is still occupied by listener PID(s):"
lsof -nP -iTCP:"$port" -sTCP:LISTEN || true
return 1
fi
return 0
}
port_in_use() {
local port="$1"
if command -v lsof >/dev/null 2>&1; then
lsof -tiTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1
return $?
fi
(echo >"/dev/tcp/127.0.0.1/$port") >/dev/null 2>&1
}
resolve_port_conflict() {
local port="$1"
local label="$2"
local answer=""
local new_port=""
while true; do
if ! port_in_use "$port"; then
echo "$port"
return 0
fi
echo >&2
if command -v lsof >/dev/null 2>&1; then
echo "$label port :$port is already in use by:" >&2
lsof -nP -iTCP:"$port" -sTCP:LISTEN >&2 || true
else
echo "$label port :$port is already in use; listener details are unavailable because lsof is not installed." >&2
fi
echo >&2
if command -v lsof >/dev/null 2>&1; then
read -r -p "Kill those process(es), use a different port, or abort? [k/p/a]: " answer >&2
else
read -r -p "Use a different port or abort? [p/a]: " answer >&2
fi
case "$answer" in
k|K)
if ! command -v lsof >/dev/null 2>&1; then
echo "Kill requires lsof. Choose p or a." >&2
continue
fi
kill_port_listeners "$port" || return 1
;;
p|P)
read -r -p "New $label port: " new_port >&2
if ! [[ "$new_port" =~ ^[0-9]+$ ]] || [ "$new_port" -lt 1 ] || [ "$new_port" -gt 65535 ]; then
echo "Port must be a number between 1 and 65535." >&2
continue
fi
port="$new_port"
;;
a|A)
return 1
;;
*)
if command -v lsof >/dev/null 2>&1; then
echo "Choose k, p, or a." >&2
else
echo "Choose p or a." >&2
fi
;;
esac
done
}
bootout_launchctl_job() {
local label="$1"
local domain="gui/$(id -u)"
if launchctl print "$domain/$label" >/dev/null 2>&1; then
echo "Stopping launchctl job $label..."
launchctl bootout "$domain/$label" >/dev/null 2>&1 || true
fi
}
kill_matching_processes() {
local label="$1"
local pattern="$2"
local pids=""
local attempts=0
local pid=""
for pid in $(pgrep -f "$pattern" 2>/dev/null || true); do
if [ "$pid" != "$$" ]; then
pids="${pids}${pids:+ }$pid"
fi
done
if [ -z "$pids" ]; then
return 0
fi
echo "Stopping previous $label process(es): $pids"
echo "$pids" | xargs kill -15 2>/dev/null || true
while [ "$attempts" -lt 20 ]; do
pids=""
for pid in $(pgrep -f "$pattern" 2>/dev/null || true); do
if [ "$pid" != "$$" ]; then
pids="${pids}${pids:+ }$pid"
fi
done
if [ -z "$pids" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 0.25
done
echo "Force killing previous $label process(es): $pids"
echo "$pids" | xargs kill -9 2>/dev/null || true
}
process_is_running() {
local pid="$1"
local stat=""
if ! kill -0 "$pid" 2>/dev/null; then
return 1
fi
stat="$(ps -p "$pid" -o stat= 2>/dev/null || true)"
case "$stat" in
*Z*) return 1 ;;
*) return 0 ;;
esac
}
FRONTEND_BUILD_PID=""
BACKEND_PID=""
BACKEND_GENERATION_ID=""
BACKEND_GENERATION_STARTED_AT=""
BACKEND_EXIT_CODE=0
BACKEND_EXIT_PID=""
ZAI_STARTUP_CHECK_PID=""
DAEMON_HOST_PID=""
CREDENTIAL_BACKEND_SUPERVISOR_PID=""
CREDENTIAL_BACKEND_CONTROL_DIR=""
CREDENTIAL_BACKEND_CONTROL=""
tracked_child_is_running() {
local pid="$1"
local ppid=""
if [ -z "$pid" ] || ! process_is_running "$pid"; then
return 1
fi
ppid="$(ps -p "$pid" -o ppid= 2>/dev/null | tr -d ' ' || true)"
[ "$ppid" = "$$" ]
}
collect_descendants() {
local pid="$1"
local child=""
for child in $(pgrep -P "$pid" 2>/dev/null || true); do
collect_descendants "$child"
echo "$child"
done
}
reap_completed_children() {
if [ -n "$FRONTEND_BUILD_PID" ] && ! tracked_child_is_running "$FRONTEND_BUILD_PID"; then
FRONTEND_BUILD_PID=""
fi
if [ -n "$ZAI_STARTUP_CHECK_PID" ] && ! tracked_child_is_running "$ZAI_STARTUP_CHECK_PID"; then
ZAI_STARTUP_CHECK_PID=""
fi
}
stop_child_process() {
local label="$1"
local pid="$2"
local attempts=0
local pids=""
if ! tracked_child_is_running "$pid"; then
return 0
fi
echo "Stopping $label (PID $pid)..."
pids="$(collect_descendants "$pid"; echo "$pid")"
echo "$pids" | xargs kill -15 2>/dev/null || true
while [ "$attempts" -lt 20 ]; do
pids="$(echo "$pids" | while read -r child_pid; do
if [ -n "$child_pid" ] && process_is_running "$child_pid"; then
echo "$child_pid"
fi
done)"
if [ -z "$pids" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 0.25
done
echo "Force killing $label (PID $pid)..."
echo "$pids" | xargs kill -9 2>/dev/null || true
}
credential_backend_control() {
PYTHONPATH="$DIR:$DIR/backend:$DIR/desktop:$DIR/sdk" "$PY" \
-m desktop.browser_backend_control --control "$CREDENTIAL_BACKEND_CONTROL" "$@"
}
STATUS_TERMINAL=""
STATUS_PID=""
STATUS_GENERATION_ID=""
STATUS_RETURNCODE=""
STATUS_STARTED_AT=""
read_backend_status() {
local status_file="$CREDENTIAL_BACKEND_CONTROL_DIR/status.json"
local parsed=""
if ! credential_backend_control status > "$status_file"; then
rm -f "$status_file"
return 1
fi
if ! parsed="$("$PY" - "$status_file" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as handle:
status = json.load(handle)
fields = (
"1" if status.get("terminal") is True else "0",
str(status.get("pid") if isinstance(status.get("pid"), int) else "-"),
str(status.get("generation_id") or "-"),
str(status.get("returncode") if isinstance(status.get("returncode"), int) else "-"),
str(status.get("started_at") if isinstance(status.get("started_at"), (int, float)) else "-"),
)
print("|".join(fields))
PY
)"; then
rm -f "$status_file"
return 1
fi
rm -f "$status_file"
IFS='|' read -r STATUS_TERMINAL STATUS_PID STATUS_GENERATION_ID \
STATUS_RETURNCODE STATUS_STARTED_AT <<EOF
$parsed
EOF
}
start_credential_backend_supervisor() {
local attempts=0
CREDENTIAL_BACKEND_CONTROL_DIR="$(mktemp -d "/tmp/ba-bs.XXXXXX")"
chmod 700 "$CREDENTIAL_BACKEND_CONTROL_DIR"
CREDENTIAL_BACKEND_CONTROL="$CREDENTIAL_BACKEND_CONTROL_DIR/control.sock"
if [ "$(uname -s)" = "Darwin" ]; then
"$DIR/desktop/build_credential_authority.sh" >/dev/null
"$CREDENTIAL_AUTHORITY" \
--control "$CREDENTIAL_BACKEND_CONTROL" \
--launcher-root "$DIR" \
--controller-pid "$$" &
else
PYTHONPATH="$DIR:$DIR/backend:$DIR/desktop:$DIR/sdk" "$PY" \
-m desktop.browser_backend_supervisor \
--control "$CREDENTIAL_BACKEND_CONTROL" \
--launcher-root "$DIR" \
--controller-pid "$$" &
fi
CREDENTIAL_BACKEND_SUPERVISOR_PID=$!
while [ ! -S "$CREDENTIAL_BACKEND_CONTROL" ]; do
if ! tracked_child_is_running "$CREDENTIAL_BACKEND_SUPERVISOR_PID"; then
echo "Credential backend supervisor failed to start." >&2
return 1
fi
if [ "$attempts" -ge 40 ]; then
echo "Credential backend supervisor startup timed out." >&2
return 1
fi
attempts=$((attempts + 1))
sleep 0.05
done
}
stop_credential_backend_supervisor() {
if [ -n "$CREDENTIAL_BACKEND_CONTROL" ] && [ -S "$CREDENTIAL_BACKEND_CONTROL" ]; then
credential_backend_control shutdown >/dev/null 2>&1 || true
fi
stop_child_process "credential backend supervisor" "$CREDENTIAL_BACKEND_SUPERVISOR_PID"
[ -n "$CREDENTIAL_BACKEND_CONTROL" ] && rm -f "$CREDENTIAL_BACKEND_CONTROL"
[ -n "$CREDENTIAL_BACKEND_CONTROL_DIR" ] && rmdir "$CREDENTIAL_BACKEND_CONTROL_DIR" 2>/dev/null || true
CREDENTIAL_BACKEND_SUPERVISOR_PID=""
CREDENTIAL_BACKEND_CONTROL=""
CREDENTIAL_BACKEND_CONTROL_DIR=""
}
shutdown_children() {
local signal="${1:-TERM}"
local exit_code=143
trap - INT TERM
if [ "$signal" = "INT" ]; then
exit_code=130
fi
echo
echo "Stopping Better Agent..."
reap_completed_children
stop_child_process "startup checker" "$ZAI_STARTUP_CHECK_PID"
stop_child_process "frontend build" "$FRONTEND_BUILD_PID"
stop_child_process "daemon host" "$DAEMON_HOST_PID"
if [ -n "$CREDENTIAL_BACKEND_SUPERVISOR_PID" ]; then
stop_credential_backend_supervisor
else
stop_child_process "backend" "$BACKEND_PID"
fi
exit "$exit_code"
}
trap 'shutdown_children INT' INT
trap 'shutdown_children TERM' TERM
if [ "${BETTER_AGENT_RUN_SH_TEST_SIGNAL_CLEANUP:-0}" = "1" ]; then
((sleep 30 & wait) & wait) &
BACKEND_PID=$!
(sleep 30 & wait) &
FRONTEND_BUILD_PID=$!
(sleep 30 & wait) >/dev/null 2>&1 &
ZAI_STARTUP_CHECK_PID=$!
echo "Signal cleanup test ready: backend=$BACKEND_PID frontend=$FRONTEND_BUILD_PID checker=$ZAI_STARTUP_CHECK_PID"
while true; do
sleep 1
done
fi
kill_backend_lock_holder() {
local lock_path="$BA_HOME/backend.lock"
local pid=""
local cmd=""
local ppid=""
local cwd=""
local foreign_checkout=""
local attempts=0
if [ ! -f "$lock_path" ]; then
return 0
fi
pid="$(sed -n 's/^pid=//p' "$lock_path" | head -n 1)"
if ! [[ "$pid" =~ ^[0-9]+$ ]] || ! process_is_running "$pid"; then
return 0
fi
cmd="$(ps -p "$pid" -o command= 2>/dev/null || true)"
cwd="$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n 's/^n//p' | head -n1 || true)"
looks_like_ours=0
case "$cmd" in
*"$DIR/backend"*uvicorn*"main:app"*|*"$DIR/backend/app_entry.py"*"--serve"*)
looks_like_ours=1
;;
*uvicorn*"main:app"*)
# The launcher runs `(cd "$DIR/backend" && source .venv/bin/activate &&
# exec uvicorn main:app ...)`, so argv shows a relative
# `.venv/bin/uvicorn` without the absolute checkout path. Accept it when
# the process cwd is this checkout's backend dir. Also accept a sibling
# checkout: backend.lock is keyed on BA_HOME (the shared state home),
# not on the checkout directory, so a previous backend launched from
# another worktree can legitimately hold the lock and must be replaced
# here -- otherwise this relaunch can never win the lock and crashes.
looks_like_ours=1
if [ -n "$cwd" ] && [ "$cwd" != "$DIR/backend" ]; then
foreign_checkout="$cwd"
fi
;;
esac
if [ "$looks_like_ours" -ne 1 ]; then
echo "Backend lock is held by PID $pid, but it does not look like this checkout's backend:"
echo "$cmd"
return 0
fi
if [ -n "$foreign_checkout" ]; then
echo "Stopping previous Better Agent backend lock holder from a sibling checkout ($foreign_checkout): $pid"
else
echo "Stopping previous Better Agent backend lock holder: $pid"
fi
# Escalate TERM -> KILL and VERIFY death each round instead of a single
# best-effort SIGTERM+SIGKILL fire-and-forget. A lock holder that survived
# one round previously left the lock held indefinitely: the caller had no
# idea the kill failed, so it proceeded straight into a doomed backend
# start (fails the Python-side 15s lock retry) which burns a full,
# expensive startup-checker AI-agent cycle just to hit the same wall
# again on the next `run.sh` invocation.
local round=0
while [ "$round" -lt 3 ]; do
round=$((round + 1))
if [ "$round" -eq 1 ]; then
kill -15 "$pid" 2>/dev/null || true
else
echo "Lock holder $pid still alive after round $((round - 1)); escalating to SIGKILL (round $round)..."
kill -9 "$pid" 2>/dev/null || true
fi
attempts=0
while [ "$attempts" -lt 20 ]; do
if ! process_is_running "$pid"; then
ppid="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ' || true)"
if [ -n "$ppid" ] && [ "$ppid" != "1" ]; then
kill -15 "$ppid" 2>/dev/null || true
fi
echo "Lock holder $pid stopped (round $round)."
return 0
fi
attempts=$((attempts + 1))
sleep 0.25
done
done
echo "FATAL: backend lock holder $pid ($cmd) would not die after repeated SIGTERM/SIGKILL — refusing to start a new backend against a lock we cannot free." >&2
exit 1
}
stop_known_better_agent_port_users() {
local port="$1"
if [ "$port" != "$BACKEND_PORT" ]; then
return 0
fi
bootout_launchctl_job "better-claude"
kill_matching_processes \
"Better Agent backend wrapper" \
"cd $DIR/backend && .*uvicorn main:app.*--port $port"
kill_matching_processes \
"Better Agent backend" \
"$DIR/backend.*uvicorn main:app.*--port $port"
}
ensure_base_prereqs
echo "Checking startup ports..."
kill_backend_lock_holder
BACKEND_PORT="$(resolve_port_conflict "$BACKEND_PORT" "backend")"
export BETTER_CLAUDE_BACKEND_PORT="$BACKEND_PORT"
export BETTER_CLAUDE_BACKEND_URL="http://127.0.0.1:$BACKEND_PORT"
export BETTER_AGENT_BACKEND_PORT="$BACKEND_PORT"
export BETTER_AGENT_BACKEND_URL="http://127.0.0.1:$BACKEND_PORT"
export BA_BACKEND_PORT="$BACKEND_PORT"
npm_project_hash() {
local project_dir="$1"
shift
(cd "$project_dir" && node - "$@" <<'NODE'
const { createHash } = require("node:crypto");
const { readFileSync } = require("node:fs");
const outer = createHash("sha256");
for (const path of process.argv.slice(2)) {
const inner = createHash("sha256").update(readFileSync(path)).digest("hex");
outer.update(`${inner} ${path}\n`);
}
process.stdout.write(outer.digest("hex"));
NODE
)
}
sync_npm_project_deps() {
local project_dir="$1"
local label="$2"
local install_mode="$3"
local dependency_files=(package.json package-lock.json)
local lock_file="package-lock.json"
local stamp="$project_dir/node_modules/.better-agent-deps.stamp"
local current=""
local stamped=""
if [ "$install_mode" = "mobile" ]; then
dependency_files=(package.json mobile-dependencies.json package-lock.mobile.json)
lock_file="package-lock.mobile.json"
fi
if [ ! -f "$project_dir/$lock_file" ]; then
echo "$label dependency lock is missing; cannot install reproducibly." >&2
exit 1
fi
current="$(npm_project_hash "$project_dir" "${dependency_files[@]}"):$install_mode"
if [ -f "$stamp" ]; then
stamped="$(cat "$stamp" 2>/dev/null || true)"
fi
if [ -d "$project_dir/node_modules" ] && [ "$stamped" = "$current" ]; then
echo "$label npm deps unchanged — skipping install."
return 0
fi
echo "Installing $label npm deps..."
if [ "$install_mode" = "mobile" ]; then
(cd "$project_dir" && npm run install:mobile-deps)
elif [ "$install_mode" = "desktop" ]; then
(cd "$project_dir" && npm run install:desktop-deps)
else
(cd "$project_dir" && npm ci)
fi
printf '%s' "$current" > "$stamp"
}
BOOTSTRAP_PYTHON="$(command -v python3 || command -v python || true)"
if [ -z "$BOOTSTRAP_PYTHON" ]; then
echo "Python is required to resolve installation dependencies." >&2
exit 1
fi
# A state home with no installation profile has nothing to serve. Adopt an
# already-installed provider CLI so a fresh home boots usable; never install a
# CLI here — that stays an explicit `scripts/install.py` run.
if ! PYTHONPATH="$DIR/backend" "$BOOTSTRAP_PYTHON" -c \
'import installation_profile; raise SystemExit(0 if installation_profile.load()["status"] == "active" else 1)'; then
ADOPT_PROVIDER="$(PYTHONPATH="$DIR/backend" "$BOOTSTRAP_PYTHON" -c \
'import installation_bootstrap; print(installation_bootstrap.adoptable_provider_kind() or "")')"
if [ -n "$ADOPT_PROVIDER" ]; then
ADOPT_MODE="${BETTER_AGENT_INSTALL_MODE:-default}"
echo "No installation profile in this state home — adopting installed provider '$ADOPT_PROVIDER' with mode '$ADOPT_MODE'."
"$BOOTSTRAP_PYTHON" "$DIR/scripts/install.py" \
--mode "$ADOPT_MODE" --provider "$ADOPT_PROVIDER" --yes --adopt \
|| echo "Installation profile adoption failed; finish setup from the app." >&2
else
echo "No installation profile and no provider CLI found — finish setup from the app." >&2
fi
fi
# Provisioning follows the capability the user asked for, not what this
# bootstrap interpreter happens to have importable.
if PYTHONPATH="$DIR/backend" "$BOOTSTRAP_PYTHON" -c \
'import installation_profile as p; raise SystemExit(0 if p.capability_requested(p.MOBILE) else 1)'; then
FRONTEND_NPM_MODE="mobile"
else
FRONTEND_NPM_MODE="desktop"
fi
sync_npm_project_deps "$DIR/frontend" "frontend" "$FRONTEND_NPM_MODE"
# --- Sync backend dependencies before anything that imports them ----
# Idempotent; cheap when deps are cached. Required so the argon2 import
# in the keychain-bootstrap block below works on a fresh checkout.
sync_backend_deps() {
local bootstrap_python=""
local active_env=""
bootstrap_python="$BOOTSTRAP_PYTHON"
if [ -z "$bootstrap_python" ]; then
echo "Python is required to resolve backend dependencies." >&2
exit 1
fi
echo "Activating backend dependency plan..."
active_env="$("$bootstrap_python" "$DIR/backend/dependency_plan.py" activate --uv "$UV")"
if [ "$(uname -s)" = "MINGW64_NT" ] || [ "$(uname -s)" = "MSYS_NT" ]; then
PY="$active_env/Scripts/python.exe"
else
PY="$active_env/bin/python"
fi
if [ ! -x "$PY" ]; then
echo "Activated backend environment is not runnable." >&2
exit 1
fi
export BETTER_AGENT_BACKEND_PYTHON="$PY"
}
sync_backend_deps
# --- Install the `bagent` CLI command onto PATH (idempotent) --------
# Other tools (e.g. TestApe locator healing) shell out to `bagent`.
bash "$DIR/scripts/install-bagent.sh" || echo "bagent install failed (non-fatal)"
# --- First-time keychain bootstrap ----------------------------------
# A cleartext password is NEVER echoed (terminal scrollback, tmux/CI logs
# would leak a full-access credential). Three modes, none of which print a
# secret:
# - BA_PASSWORD set → use it silently (headless / scripted).
# - interactive TTY → prompt the operator to choose one.
# - no TTY and no env → mint a random one, do NOT print it; onboard via
# the login-screen QR, or `--reset-auth` to set a
# known password.
# Override the username via BA_USERNAME (defaults to a random ba-XXXX).
FIRST_RUN_AUTH_BOOTSTRAPPED=0
FIRST_RUN_BROWSER_OPENED=0
if [ "$(uname -s)" = "Darwin" ] && { ! kc_has username || ! kc_has password_hash || ! kc_has session_secret; }; then
FIRST_RUN_AUTH_BOOTSTRAPPED=1
echo
echo "Better Agent — first-time auth setup (credentials live in your OS keychain only)."
UNAME="${BA_USERNAME:-$("$PY" -c "import secrets; print('ba-'+secrets.token_hex(4))")}"
PW=""
if [ -n "${BA_PASSWORD:-}" ]; then
PW="$BA_PASSWORD"
echo "Using credentials from BA_USERNAME / BA_PASSWORD."
elif [ -t 0 ]; then
read -p "Username [$UNAME]: " _u; [ -n "$_u" ] && UNAME="$_u"
while true; do
read -s -p "Password: " PW1; echo
read -s -p "Confirm: " PW2; echo
if [ -z "$PW1" ]; then echo "Empty password — try again."; continue; fi
if [ "$PW1" != "$PW2" ]; then echo "Mismatch — try again."; continue; fi
PW="$PW1"; break
done
else
PW="$("$PY" -c "import secrets; print(secrets.token_urlsafe(18))")"
echo "No TTY and no BA_PASSWORD — set a RANDOM password (not shown)."
echo "Onboard devices via the QR on the login screen, or run ./run.sh --reset-auth to choose one."
fi
# Password reaches python via stdin (NOT argv) so it stays out of `ps`.
HASH=$(printf '%s' "$PW" | "$PY" -c "import sys, argon2; print(argon2.PasswordHasher().hash(sys.stdin.read()))")
SECRET=$("$PY" -c "import secrets; print(secrets.token_hex(32))")
kc_set username "$UNAME"
kc_set password_hash "$HASH"
kc_set session_secret "$SECRET"
unset PW PW1 PW2 _u HASH SECRET
echo
echo "Stored for user '$UNAME'. Starting backend..."
echo
unset UNAME
fi
rm -f "$FLAG"
build_frontend() {
local request_id="${1:-}"
local build_log="$BA_HOME/frontend_build.log"
local status="failed"
# `npm run build` (scripts/build-atomic.mjs) builds into a temp dir, swaps
# it into dist/ atomically, and keeps the previous build's content-hashed
# assets so live tabs don't lose their lazy chunks mid-rebuild.
echo "Building frontend..."
if (cd "${ACTIVE_DIR:-$DIR}/frontend" && npm run build 2>&1 | tee "$build_log"); then
status="succeeded"
else
echo "Frontend build failed — serving previous build"
fi
if [ -n "$request_id" ]; then
"$PY" - "$RESULT" "$request_id" "$status" "$build_log" <<'PY'
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
result_path = Path(sys.argv[1])
request_id = sys.argv[2]
status = sys.argv[3]
log_path = Path(sys.argv[4])
error = None
if status == "failed":
try:
error = log_path.read_text(encoding="utf-8", errors="replace")[-4000:]
except OSError:
error = "Frontend build failed; build log was unavailable."
payload = {
"request_id": request_id,
"status": status,
"completed_at": datetime.now(timezone.utc).isoformat(),
"error": error,
}
tmp_path = result_path.with_suffix(".tmp")
tmp_path.write_text(json.dumps(payload), encoding="utf-8")
os.replace(tmp_path, result_path)
PY
fi
}
start_frontend_build() {
local request_id="${1:-}"
reap_completed_children
if tracked_child_is_running "$FRONTEND_BUILD_PID"; then
if [ -n "$request_id" ]; then
local previous_pid="$FRONTEND_BUILD_PID"
(wait "$previous_pid" 2>/dev/null || true; build_frontend "$request_id") &
FRONTEND_BUILD_PID=$!
fi
return 0
fi
build_frontend "$request_id" &
FRONTEND_BUILD_PID=$!
}
app_url() {
echo "http://127.0.0.1:$BACKEND_PORT/"
}
open_first_run_browser() {
local url="$1"
if [ "${BETTER_AGENT_NO_BROWSER:-${BETTER_CLAUDE_NO_BROWSER:-0}}" = "1" ]; then
return 0
fi
if [ "$FIRST_RUN_AUTH_BOOTSTRAPPED" -ne 1 ]; then
return 0
fi
if [ "$FIRST_RUN_BROWSER_OPENED" -eq 1 ]; then
return 0
fi
if [ ! -t 0 ]; then
return 0
fi
FIRST_RUN_BROWSER_OPENED=1
case "$(uname -s)" in
Darwin)
open "$url" >/dev/null 2>&1 || true
;;
Linux)
if command -v xdg-open >/dev/null 2>&1; then
xdg-open "$url" >/dev/null 2>&1 || true
fi
;;
MINGW*|MSYS*|CYGWIN*)
cmd.exe /c start "" "$url" >/dev/null 2>&1 || true
;;
esac
}
start_backend() {
local bind_host
local pid_file="$CREDENTIAL_BACKEND_CONTROL_DIR/backend.pid"
if ! PYTHONPATH="$DIR:$DIR/backend" "$PY" -m restart_request "$FLAG" --clear; then
echo "Could not clear stale restart intent before backend generation." >&2
return 1
fi
bind_host=$("$PY" - "$BA_HOME/user_prefs.json" <<'PY'
import json
import sys
from pathlib import Path
try:
prefs = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
prefs = {}
host = prefs.get("network_bind_address", "127.0.0.1")
if host not in ("127.0.0.1", "0.0.0.0"):
host = "127.0.0.1"
print(host)
PY
)
# ACTIVE_DIR / BETTER_AGENT_ACTIVE_CHECKOUT are resolved once per loop
# iteration by the caller before the frontend build, so the built frontend and
# the backend always target the same checkout. The pointer is written by the
# switch-control extension; this launcher honors it and reverts on failed
# starts.
echo "Starting backend (no --reload) on $bind_host:$BACKEND_PORT..."
kill_backend_lock_holder
BACKEND_PORT="$(resolve_port_conflict "$BACKEND_PORT" "backend")"
export BETTER_CLAUDE_BACKEND_PORT="$BACKEND_PORT"
export BETTER_CLAUDE_BACKEND_URL="http://127.0.0.1:$BACKEND_PORT"
export BETTER_AGENT_BACKEND_PORT="$BACKEND_PORT"
export BETTER_AGENT_BACKEND_URL="http://127.0.0.1:$BACKEND_PORT"
export BA_BACKEND_PORT="$BACKEND_PORT"
# The Python supervisor owns uvicorn and its private credential channel. It
# forwards output to this terminal and the backend log.
: > "$BACKEND_LOG"