forked from Dicklesworthstone/mcp_agent_mail_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·3468 lines (3102 loc) · 111 KB
/
install.sh
File metadata and controls
executable file
·3468 lines (3102 loc) · 111 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
#
# mcp-agent-mail installer
#
# One-liner install (with cache buster):
# curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/mcp_agent_mail_rust/main/install.sh?$(date +%s)" | bash
#
# Or without cache buster:
# curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/mcp_agent_mail_rust/main/install.sh | bash
#
# Options:
# --version vX.Y.Z Install specific version (default: latest)
# --dest DIR Install to DIR (default: ~/.local/bin)
# --system Install to /usr/local/bin (requires sudo)
# --easy-mode Auto-update PATH in shell rc files
# --no-easy Do not auto-update PATH, even for piped installs
# --verify Run self-test after install
# --from-source Build from source instead of downloading binary
# --quiet Suppress non-error output
# --verbose Enable detailed installer diagnostics
# --no-gum Disable gum formatting even if available
# --no-verify Skip checksum + signature verification (for testing only)
# --offline Skip network preflight checks
# --force Force reinstall even if already at version
# --migrate Force Python->Rust migration/displacement when Python install detected
# --no-migrate Skip Python->Rust migration/displacement even when detected
# --uninstall Remove installed binaries/configuration helpers
# --yes Non-interactive mode (skip all confirmations)
# --purge With --uninstall, also delete data directories/database
# --dry-run Preview what the installer would do without making changes
# --preview Alias for --dry-run
#
set -Eeuo pipefail
umask 022
shopt -s lastpipe 2>/dev/null || true
VERSION="${VERSION:-}"
OWNER="${OWNER:-Dicklesworthstone}"
REPO="${REPO:-mcp_agent_mail_rust}"
ISSUES_URL="${ISSUES_URL:-https://github.com/${OWNER}/${REPO}/issues}"
INSTALL_SCRIPT_URL="${INSTALL_SCRIPT_URL:-https://raw.githubusercontent.com/${OWNER}/${REPO}/main/install.sh}"
DEST_DEFAULT="$HOME/.local/bin"
DEST="${DEST:-$DEST_DEFAULT}"
EASY=0
QUIET=0
VERBOSE=0
VERIFY=0
FROM_SOURCE=0
CHECKSUM="${CHECKSUM:-}"
CHECKSUM_URL="${CHECKSUM_URL:-}"
SIGSTORE_BUNDLE_URL="${SIGSTORE_BUNDLE_URL:-}"
COSIGN_IDENTITY_RE="${COSIGN_IDENTITY_RE:-^https://github.com/${OWNER}/${REPO}/.github/workflows/dist.yml@refs/tags/.*$}"
COSIGN_OIDC_ISSUER="${COSIGN_OIDC_ISSUER:-https://token.actions.githubusercontent.com}"
ARTIFACT_URL="${ARTIFACT_URL:-}"
LOCK_FILE="/tmp/mcp-agent-mail-install.lock"
SYSTEM=0
NO_GUM=0
NO_CHECKSUM=0
FORCE_INSTALL=0
FORCE_MIGRATE=0
FORCE_NO_MIGRATE=0
UNINSTALL=0
ASSUME_YES=0
PURGE=0
DRY_RUN=0
OFFLINE="${AM_OFFLINE:-0}"
VERBOSE_DUMP_LINES=20
LOG_FILE="${LOG_FILE:-/tmp/am-install-$(date -u +%Y%m%dT%H%M%SZ)-$$.log}"
LOG_INITIALIZED=0
ERROR_TAIL_EMITTED=0
ORIGINAL_ARGS=("$@")
UNINSTALL_SUMMARY=()
# T2.1: Auto-enable easy-mode for pipe installs (stdin is not a terminal)
# Also auto-enable in CI environments.
if [ ! -t 0 ] || [ "${CI:-}" = "true" ] || [ -n "${GITHUB_ACTIONS:-}" ] || [ -n "${GITLAB_CI:-}" ] || [ -n "${JENKINS_URL:-}" ]; then
EASY=1
fi
# Binary names in this project
BIN_SERVER="mcp-agent-mail"
BIN_CLI="am"
# Detect gum for fancy output (https://github.com/charmbracelet/gum)
HAS_GUM=0
if command -v gum &> /dev/null && [ -t 1 ]; then
HAS_GUM=1
fi
# Logging functions with optional gum formatting
log() { [ "$QUIET" -eq 1 ] && return 0; echo -e "$@"; }
info() {
[ "$QUIET" -eq 1 ] && return 0
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 39 -- "-> $*"
else
echo -e "\033[0;34m->\033[0m $*"
fi
}
ok() {
[ "$QUIET" -eq 1 ] && return 0
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 42 "ok $*"
else
echo -e "\033[0;32mok\033[0m $*"
fi
}
warn() {
[ "$QUIET" -eq 1 ] && return 0
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 214 "!! $*"
else
echo -e "\033[1;33m!!\033[0m $*"
fi
}
err() {
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ]; then
gum style --foreground 196 "ERR $*"
else
echo -e "\033[0;31mERR\033[0m $*"
fi
}
error_usage_hint() {
err "Run './install.sh --help' for full option details."
}
error_support_hint() {
err "Try re-running with --verbose for detailed diagnostics."
err "If this persists, report at ${ISSUES_URL} and include log: ${LOG_FILE}"
}
init_verbose_log() {
[ "$LOG_INITIALIZED" -eq 1 ] && return 0
local log_dir
log_dir=$(dirname "$LOG_FILE")
mkdir -p "$log_dir" 2>/dev/null || true
if ! : > "$LOG_FILE" 2>/dev/null; then
LOG_FILE="/tmp/am-install-$(date -u +%Y%m%dT%H%M%SZ)-$$.log"
: > "$LOG_FILE" 2>/dev/null || return 0
fi
LOG_INITIALIZED=1
printf '%s [VERBOSE] initialized pid=%s shell=%s\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
"$$" \
"${SHELL:-unknown}" >> "$LOG_FILE" || true
}
verbose() {
init_verbose_log
local ts msg
ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
msg="$*"
if [ "$LOG_INITIALIZED" -eq 1 ]; then
printf '%s [VERBOSE] %s\n' "$ts" "$msg" >> "$LOG_FILE" || true
fi
if [ "$VERBOSE" -eq 1 ] && [ "$QUIET" -eq 0 ]; then
echo "[VERBOSE] $msg"
fi
}
dump_verbose_tail() {
[ "$ERROR_TAIL_EMITTED" -eq 1 ] && return 0
ERROR_TAIL_EMITTED=1
[ "$LOG_INITIALIZED" -eq 1 ] || return 0
[ -f "$LOG_FILE" ] || return 0
err "Verbose log: $LOG_FILE"
if [ "$VERBOSE" -eq 0 ]; then
err "Last ${VERBOSE_DUMP_LINES} verbose log lines:"
tail -n "$VERBOSE_DUMP_LINES" "$LOG_FILE" >&2 || true
fi
}
on_error() {
local exit_code=$?
local line_no="${1:-unknown}"
trap - ERR
if [ "$exit_code" -ne 0 ]; then
err "Installer failed (exit ${exit_code}) at line ${line_no}"
err "Unexpected installer error."
error_support_hint
dump_verbose_tail
fi
exit "$exit_code"
}
early_exit_dump() {
local rc=$?
if [ "$rc" -ne 0 ]; then
dump_verbose_tail
fi
}
download_to_file() {
local url="$1"
local out="$2"
local label="${3:-download}"
local start_ts end_ts duration_s size_bytes rc=0
start_ts=$(date +%s)
verbose "${label}:start url=${url} out=${out}"
if [ "$VERBOSE" -eq 1 ] && [ "$QUIET" -eq 0 ]; then
curl -fL --progress-bar "$url" -o "$out" || rc=$?
else
curl -fsSL "$url" -o "$out" || rc=$?
fi
end_ts=$(date +%s)
duration_s=$((end_ts - start_ts))
if [ "$rc" -ne 0 ]; then
# curl may leave behind an empty/partial file on failure — clean it up
rm -f "$out" 2>/dev/null || true
verbose "${label}:failed rc=${rc} duration_s=${duration_s}"
return "$rc"
fi
size_bytes=$(wc -c < "$out" 2>/dev/null || echo 0)
verbose "${label}:done bytes=${size_bytes} duration_s=${duration_s} out=${out}"
}
# Spinner wrapper for long operations
run_with_spinner() {
local title="$1"
shift
if [ "$HAS_GUM" -eq 1 ] && [ "$NO_GUM" -eq 0 ] && [ "$QUIET" -eq 0 ]; then
gum spin --spinner dot --title "$title" -- "$@"
else
info "$title"
"$@"
fi
}
# Draw a box around text with automatic width calculation
draw_box() {
local color="$1"
shift
local lines=("$@")
local max_width=0
local esc
esc=$(printf '\033')
local strip_ansi_sed="s/${esc}\\[[0-9;]*m//g"
for line in "${lines[@]}"; do
local stripped
stripped=$(printf '%b' "$line" | LC_ALL=C sed "$strip_ansi_sed")
local len=${#stripped}
if [ "$len" -gt "$max_width" ]; then
max_width=$len
fi
done
local inner_width=$((max_width + 4))
local border=""
for ((i=0; i<inner_width; i++)); do
border+="="
done
printf "\033[%sm+%s+\033[0m\n" "$color" "$border"
for line in "${lines[@]}"; do
local stripped
stripped=$(printf '%b' "$line" | LC_ALL=C sed "$strip_ansi_sed")
local len=${#stripped}
local padding=$((max_width - len))
local pad_str=""
for ((i=0; i<padding; i++)); do
pad_str+=" "
done
printf "\033[%sm|\033[0m %b%s \033[%sm|\033[0m\n" "$color" "$line" "$pad_str" "$color"
done
printf "\033[%sm+%s+\033[0m\n" "$color" "$border"
}
resolve_version() {
verbose "resolve_version:start preset=${VERSION:-<unset>}"
if [ -n "$VERSION" ]; then return 0; fi
info "Resolving latest version..."
local latest_url="https://api.github.com/repos/${OWNER}/${REPO}/releases/latest"
local tag
if ! tag=$(curl -fsSL -H "Accept: application/vnd.github.v3+json" "$latest_url" 2>/dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/'); then
tag=""
fi
if [ -n "$tag" ]; then
VERSION="$tag"
verbose "resolve_version:github_latest tag=${VERSION}"
info "Resolved latest version: $VERSION"
else
# Try redirect-based resolution as fallback
local redirect_url="https://github.com/${OWNER}/${REPO}/releases/latest"
if tag=$(curl -fsSL -o /dev/null -w '%{url_effective}' "$redirect_url" 2>/dev/null | sed -E 's|.*/tag/||'); then
if [ -n "$tag" ] && [[ "$tag" =~ ^v[0-9] ]] && [[ "$tag" != *"/"* ]]; then
VERSION="$tag"
verbose "resolve_version:redirect_latest tag=${VERSION}"
info "Resolved latest version via redirect: $VERSION"
return 0
fi
fi
# Try git tags API as last resort (works even without releases)
local tags_url="https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=10"
if tag=$(curl -fsSL -H "Accept: application/vnd.github.v3+json" "$tags_url" 2>/dev/null \
| grep '"name":' | head -1 | sed -E 's/.*"([^"]+)".*/\1/'); then
if [ -n "$tag" ] && [[ "$tag" =~ ^v[0-9] ]]; then
VERSION="$tag"
verbose "resolve_version:tags_api tag=${VERSION}"
info "Resolved latest version via tags: $VERSION"
return 0
fi
fi
VERSION="v0.1.0"
verbose "resolve_version:fallback_default tag=${VERSION}"
warn "Could not resolve latest version; defaulting to $VERSION"
fi
verbose "resolve_version:done resolved=${VERSION}"
}
detect_platform() {
OS=$(uname -s | tr 'A-Z' 'a-z')
ARCH=$(uname -m)
verbose "detect_platform:raw os=${OS} arch=${ARCH}"
case "$ARCH" in
x86_64|amd64) ARCH="x86_64" ;;
arm64|aarch64) ARCH="aarch64" ;;
*) warn "Unknown arch $ARCH, using as-is" ;;
esac
TARGET=""
case "${OS}-${ARCH}" in
linux-x86_64) TARGET="x86_64-unknown-linux-gnu" ;;
linux-aarch64) TARGET="aarch64-unknown-linux-gnu" ;;
darwin-x86_64) TARGET="x86_64-apple-darwin" ;;
darwin-aarch64) TARGET="aarch64-apple-darwin" ;;
*) :;;
esac
if [ -z "$TARGET" ] && [ "$FROM_SOURCE" -eq 0 ] && [ -z "$ARTIFACT_URL" ]; then
warn "No prebuilt artifact for ${OS}/${ARCH}; falling back to build-from-source"
FROM_SOURCE=1
fi
verbose "detect_platform:normalized os=${OS} arch=${ARCH} target=${TARGET:-<none>} from_source=${FROM_SOURCE}"
}
set_artifact_url() {
TAR=""
URL=""
verbose "set_artifact_url:start artifact_url=${ARTIFACT_URL:-<unset>} target=${TARGET:-<none>} from_source=${FROM_SOURCE}"
if [ "$FROM_SOURCE" -eq 0 ]; then
if [ -n "$ARTIFACT_URL" ]; then
TAR=$(basename "$ARTIFACT_URL")
URL="$ARTIFACT_URL"
elif [ -n "$TARGET" ]; then
TAR="mcp-agent-mail-${TARGET}.tar.xz"
URL="https://github.com/${OWNER}/${REPO}/releases/download/${VERSION}/${TAR}"
else
warn "No prebuilt artifact for ${OS}/${ARCH}; falling back to build-from-source"
FROM_SOURCE=1
fi
fi
verbose "set_artifact_url:done tar=${TAR:-<none>} url=${URL:-<none>} from_source=${FROM_SOURCE}"
}
check_disk_space() {
local min_kb=20480 # 20MB for two binaries
local path="$DEST"
if [ ! -d "$path" ]; then
path=$(dirname "$path")
fi
if command -v df >/dev/null 2>&1; then
local avail_kb
avail_kb=$(df -Pk "$path" | awk 'NR==2 {print $4}')
if [ -n "$avail_kb" ] && [ "$avail_kb" -lt "$min_kb" ]; then
err "Insufficient disk space in $path (need at least 20MB)"
err "Free disk space or choose a different install directory with --dest."
exit 1
fi
else
warn "df not found; skipping disk space check"
fi
}
check_write_permissions() {
if [ ! -d "$DEST" ]; then
if ! mkdir -p "$DEST" 2>/dev/null; then
err "Cannot create $DEST (insufficient permissions)"
err "Try running with sudo or choose a writable --dest"
exit 1
fi
fi
if [ ! -w "$DEST" ]; then
err "No write permission to $DEST"
err "Try running with sudo or choose a writable --dest"
exit 1
fi
}
check_existing_install() {
verbose "check_existing_install:start dest=${DEST}"
if [ -x "$DEST/$BIN_CLI" ]; then
local current
current=$("$DEST/$BIN_CLI" --version 2>/dev/null | head -1 || echo "")
if [ -n "$current" ]; then
info "Existing am detected: $current"
verbose "check_existing_install:am version=${current}"
fi
fi
if [ -x "$DEST/$BIN_SERVER" ]; then
local current
current=$("$DEST/$BIN_SERVER" --version 2>/dev/null | head -1 || echo "")
if [ -n "$current" ]; then
info "Existing mcp-agent-mail detected: $current"
verbose "check_existing_install:mcp-agent-mail version=${current}"
fi
fi
verbose "check_existing_install:done"
}
check_network() {
if [ "$OFFLINE" -eq 1 ]; then
info "Offline mode enabled; skipping network preflight"
return 0
fi
if [ "$FROM_SOURCE" -eq 1 ]; then
return 0
fi
if [ -z "$URL" ]; then
return 0
fi
if ! command -v curl >/dev/null 2>&1; then
warn "curl not found; skipping network check"
return 0
fi
if ! curl -fsSI --connect-timeout 3 --max-time 5 -o /dev/null "$URL" 2>/dev/null; then
warn "Network check failed for $URL"
warn "Continuing; download may fail"
fi
}
# ── Python installation detection (T1.1, T1.2, T1.3) ──────────────────────
# Result variables set by detect_python_*
PYTHON_ALIAS_FOUND=0
PYTHON_ALIAS_FILE=""
PYTHON_ALIAS_LINE=0
PYTHON_ALIAS_CONTENT=""
PYTHON_ALIAS_KIND=""
PYTHON_ALIAS_HAS_MARKERS=0
PYTHON_BINARY_FOUND=0
PYTHON_BINARY_PATH=""
PYTHON_CLONE_FOUND=0
PYTHON_CLONE_PATH=""
PYTHON_VENV_PATH=""
PYTHON_PID=""
PYTHON_DETECTED=0
PYTHON_DB_FOUND=0
PYTHON_DB_PATH=""
PYTHON_DB_MIGRATED_PATH=""
MIGRATED_BEARER_TOKEN=""
RUST_DB_PATH=""
PYTHON_ALIAS_DISPLACED_COUNT=0
# T1.1: Detect Python am alias in shell rc files
detect_python_alias() {
PYTHON_ALIAS_FOUND=0
PYTHON_ALIAS_FILE=""
PYTHON_ALIAS_LINE=0
PYTHON_ALIAS_CONTENT=""
PYTHON_ALIAS_KIND=""
PYTHON_ALIAS_HAS_MARKERS=0
local rc_files=(
"$HOME/.zshrc"
"$HOME/.zprofile"
"$HOME/.zshenv"
"$HOME/.zlogin"
"$HOME/.bashrc"
"$HOME/.bash_profile"
"$HOME/.profile"
"$HOME/.aliases"
"$HOME/.zsh_aliases"
"$HOME/.config/zsh/.zshrc"
"$HOME/.config/zsh/aliases.zsh"
)
# Fish uses different syntax; check config.fish too
local fish_config="$HOME/.config/fish/config.fish"
if [ -f "$fish_config" ]; then
rc_files+=("$fish_config")
fi
if [ -d "$HOME/.config/fish/conf.d" ]; then
while IFS= read -r fish_file; do
[ -n "$fish_file" ] && rc_files+=("$fish_file")
done < <(find "$HOME/.config/fish/conf.d" -maxdepth 1 -type f -name "*.fish" 2>/dev/null | sort || true)
fi
for rc in "${rc_files[@]}"; do
[ -f "$rc" ] || continue
# Check for marker block: "# >>> MCP Agent Mail alias" ... "# <<< MCP Agent Mail alias"
# Only treat as active if the block still contains a live alias/function line.
if grep -q '# >>> MCP Agent Mail' "$rc" 2>/dev/null; then
local marker_line
marker_line=$(grep -n '# >>> MCP Agent Mail' "$rc" | head -1 | cut -d: -f1)
local marker_payload
marker_payload=$(sed -n '/# >>> MCP Agent Mail/,/# <<< MCP Agent Mail/p' "$rc")
local active_entry
active_entry=$(printf '%s\n' "$marker_payload" | grep -E "^[[:space:]]*(alias am=|alias am |function am[[:space:](]|am[[:space:]]*\\(\\))" | head -1 || true)
if [ -n "$active_entry" ]; then
PYTHON_ALIAS_FOUND=1
PYTHON_ALIAS_FILE="$rc"
PYTHON_ALIAS_HAS_MARKERS=1
PYTHON_ALIAS_LINE="$marker_line"
PYTHON_ALIAS_CONTENT="$active_entry"
if echo "$active_entry" | grep -qE "^[[:space:]]*(function am[[:space:](]|am[[:space:]]*\\(\\))"; then
PYTHON_ALIAS_KIND="function"
else
PYTHON_ALIAS_KIND="alias"
fi
verbose "detect_python_alias:found file=${PYTHON_ALIAS_FILE} line=${PYTHON_ALIAS_LINE} kind=${PYTHON_ALIAS_KIND} markers=1"
return 0
fi
fi
# Check for bare "alias am=" (bash/zsh) or "alias am " (fish) outside markers
local alias_line=""
alias_line=$(grep -n -E "^[[:space:]]*(alias am=|alias am )" "$rc" 2>/dev/null | grep -iv "disabled\|#.*alias am" | head -1 || true)
if [ -n "$alias_line" ]; then
# Skip commented-out aliases
local line_content
line_content=$(echo "$alias_line" | cut -d: -f2-)
if echo "$line_content" | grep -q "^[[:space:]]*#"; then
continue
fi
PYTHON_ALIAS_FOUND=1
PYTHON_ALIAS_FILE="$rc"
PYTHON_ALIAS_LINE=$(echo "$alias_line" | cut -d: -f1)
PYTHON_ALIAS_CONTENT="$line_content"
PYTHON_ALIAS_KIND="alias"
PYTHON_ALIAS_HAS_MARKERS=0
verbose "detect_python_alias:found file=${PYTHON_ALIAS_FILE} line=${PYTHON_ALIAS_LINE} kind=${PYTHON_ALIAS_KIND} markers=0"
return 0
fi
# Check for function definition: "function am()" or "am()" (bash/zsh)
# Or "function am" (fish)
local func_line=""
func_line=$(grep -n -E "^[[:space:]]*(function am[[:space:](]|am[[:space:]]*\(\))" "$rc" 2>/dev/null | grep -v "^[[:space:]]*#" | head -1 || true)
if [ -n "$func_line" ]; then
local line_content
line_content=$(echo "$func_line" | cut -d: -f2-)
if ! echo "$line_content" | grep -q "^[[:space:]]*#"; then
PYTHON_ALIAS_FOUND=1
PYTHON_ALIAS_FILE="$rc"
PYTHON_ALIAS_LINE=$(echo "$func_line" | cut -d: -f1)
PYTHON_ALIAS_CONTENT="$line_content"
PYTHON_ALIAS_KIND="function"
PYTHON_ALIAS_HAS_MARKERS=0
verbose "detect_python_alias:found file=${PYTHON_ALIAS_FILE} line=${PYTHON_ALIAS_LINE} kind=${PYTHON_ALIAS_KIND} markers=0"
return 0
fi
fi
done
verbose "detect_python_alias:not_found"
}
# T1.2: Detect Python am binary/script in PATH
detect_python_binary() {
PYTHON_BINARY_FOUND=0
PYTHON_BINARY_PATH=""
# Check for am binaries/scripts in PATH that are NOT the Rust binary
local all_am
all_am=$(which -a am 2>/dev/null || true)
[ -z "$all_am" ] && return 0
while IFS= read -r am_path; do
[ -z "$am_path" ] && continue
# Skip our own install destination
[ "$am_path" = "$DEST/$BIN_CLI" ] && continue
[ "$am_path" = "$DEST/am" ] && continue
# Check if it's a Python-related am
if [ -L "$am_path" ]; then
local link_target
link_target=$(readlink -f "$am_path" 2>/dev/null || readlink "$am_path" 2>/dev/null || true)
if echo "$link_target" | grep -qiE "python|venv|site-packages|mcp.agent.mail"; then
PYTHON_BINARY_FOUND=1
PYTHON_BINARY_PATH="$am_path"
verbose "detect_python_binary:found symlink_path=${PYTHON_BINARY_PATH}"
return 0
fi
fi
# Check shebang/content for Python references, but only for text files.
# Reading compiled binaries into command substitution can emit warnings
# like "ignored null byte in input" on macOS bash.
if [ -f "$am_path" ] && [ -r "$am_path" ]; then
if LC_ALL=C grep -Iq . "$am_path" 2>/dev/null; then
if head -5 "$am_path" 2>/dev/null | LC_ALL=C grep -qiE "python|#!/.*python"; then
PYTHON_BINARY_FOUND=1
PYTHON_BINARY_PATH="$am_path"
verbose "detect_python_binary:found script_path=${PYTHON_BINARY_PATH}"
return 0
fi
else
verbose "detect_python_binary:skip_binary path=${am_path}"
fi
fi
# Check if it's in a Python virtualenv or site-packages directory
if echo "$am_path" | grep -qiE "venv|virtualenv|site-packages|\.local/lib/python"; then
PYTHON_BINARY_FOUND=1
PYTHON_BINARY_PATH="$am_path"
verbose "detect_python_binary:found pythonish_path=${PYTHON_BINARY_PATH}"
return 0
fi
done <<< "$all_am"
# Also check for python -m mcp_agent_mail availability
if command -v python3 >/dev/null 2>&1 && python3 -c "import mcp_agent_mail" 2>/dev/null; then
PYTHON_BINARY_FOUND=1
PYTHON_BINARY_PATH="python3 -m mcp_agent_mail"
verbose "detect_python_binary:found importable=${PYTHON_BINARY_PATH}"
elif command -v python >/dev/null 2>&1 && python -c "import mcp_agent_mail" 2>/dev/null; then
PYTHON_BINARY_FOUND=1
PYTHON_BINARY_PATH="python -m mcp_agent_mail"
verbose "detect_python_binary:found importable=${PYTHON_BINARY_PATH}"
fi
if [ "$PYTHON_BINARY_FOUND" -eq 0 ]; then verbose "detect_python_binary:not_found"; fi
}
# Copy a SQLite database as a consistent snapshot.
# Prefer sqlite3 .backup to safely include WAL content and avoid torn copies.
copy_sqlite_snapshot() {
local src_db="$1"
local dest_db="$2"
rm -f "$dest_db" "${dest_db}-wal" "${dest_db}-shm" 2>/dev/null || true
if command -v sqlite3 >/dev/null 2>&1; then
local tmp_db escaped_tmp
tmp_db="${dest_db}.tmp.$$"
escaped_tmp=$(printf "%s" "$tmp_db" | sed "s/'/''/g")
rm -f "$tmp_db" 2>/dev/null || true
if sqlite3 "$src_db" ".timeout 5000" ".backup '$escaped_tmp'" >/dev/null 2>&1; then
mv -f "$tmp_db" "$dest_db"
return 0
fi
verbose "copy_sqlite_snapshot:fallback_copy reason=sqlite3_backup_failed src=${src_db} dest=${dest_db}"
rm -f "$tmp_db" 2>/dev/null || true
fi
if command -v sqlite3 >/dev/null 2>&1; then
sqlite3 "$src_db" "PRAGMA busy_timeout = 5000; PRAGMA wal_checkpoint(TRUNCATE);" >/dev/null 2>&1 || true
fi
# Sidecars are intentionally omitted to avoid propagating stale WAL/SHM state.
cp -p "$src_db" "$dest_db"
rm -f "${dest_db}-wal" "${dest_db}-shm" 2>/dev/null || true
}
# T1.3: Detect Python virtualenv and git clone
detect_python_installation() {
verbose "detect_python_installation:start"
PYTHON_CLONE_FOUND=0
PYTHON_CLONE_PATH=""
PYTHON_VENV_PATH=""
PYTHON_PID=""
# Check common clone locations
local candidates=(
"$HOME/mcp_agent_mail"
"$HOME/mcp-agent-mail"
"$HOME/projects/mcp_agent_mail"
"$HOME/code/mcp_agent_mail"
)
# If we found an alias, extract the path from it
if [ "$PYTHON_ALIAS_FOUND" -eq 1 ] && [ -n "$PYTHON_ALIAS_CONTENT" ]; then
local alias_path
# Extract path from patterns like: alias am='cd "/path/to/dir" && ...'
alias_path=$(echo "$PYTHON_ALIAS_CONTENT" | sed -n "s/.*cd [\"']*\([^\"'&]*\)[\"']*.*/\1/p")
[ -n "$alias_path" ] && candidates+=("$alias_path")
# Also try: alias am='cd /path/to/dir && ...'
alias_path=$(echo "$PYTHON_ALIAS_CONTENT" | sed -n 's/.*cd \([^ &"'"'"']*\).*/\1/p')
[ -n "$alias_path" ] && candidates+=("$alias_path")
fi
for dir in "${candidates[@]}"; do
# Expand ~ if present
dir="${dir/#\~/$HOME}"
[ -d "$dir" ] || continue
# Check for Python mcp_agent_mail markers
if [ -f "$dir/pyproject.toml" ] && grep -q "mcp.agent.mail\|mcp_agent_mail" "$dir/pyproject.toml" 2>/dev/null; then
PYTHON_CLONE_FOUND=1
PYTHON_CLONE_PATH="$dir"
# Check for virtualenv
if [ -d "$dir/.venv" ]; then
PYTHON_VENV_PATH="$dir/.venv"
elif [ -d "$dir/venv" ]; then
PYTHON_VENV_PATH="$dir/venv"
fi
break
fi
# Also check for src/mcp_agent_mail/ (source package layout)
if [ -d "$dir/src/mcp_agent_mail" ]; then
PYTHON_CLONE_FOUND=1
PYTHON_CLONE_PATH="$dir"
[ -d "$dir/.venv" ] && PYTHON_VENV_PATH="$dir/.venv"
[ -d "$dir/venv" ] && PYTHON_VENV_PATH="$dir/venv"
break
fi
done
# Check for running Python server processes
local pids
pids=$(pgrep -f "mcp_agent_mail\|mcp.agent.mail" 2>/dev/null | head -5 || true)
if [ -n "$pids" ]; then
# Filter to actual Python processes
while IFS= read -r pid; do
[ -z "$pid" ] && continue
local cmdline
cmdline=$(ps -p "$pid" -o command= 2>/dev/null || true)
if echo "$cmdline" | grep -qiE "python|uvicorn"; then
PYTHON_PID="$pid"
break
fi
done <<< "$pids"
fi
# Set overall detection flag
if [ "$PYTHON_ALIAS_FOUND" -eq 1 ] || [ "$PYTHON_BINARY_FOUND" -eq 1 ] || [ "$PYTHON_CLONE_FOUND" -eq 1 ]; then
PYTHON_DETECTED=1
fi
verbose "detect_python_installation:done clone_found=${PYTHON_CLONE_FOUND} clone=${PYTHON_CLONE_PATH:-<none>} venv=${PYTHON_VENV_PATH:-<none>} pid=${PYTHON_PID:-<none>}"
}
# Run all Python detection in sequence
detect_python() {
verbose "detect_python:start"
detect_python_alias
detect_python_binary
detect_python_installation
if [ "$PYTHON_DETECTED" -eq 1 ]; then
info "Existing Python mcp-agent-mail detected"
[ "$PYTHON_ALIAS_FOUND" -eq 1 ] && info " Alias: $PYTHON_ALIAS_FILE:$PYTHON_ALIAS_LINE"
[ "$PYTHON_BINARY_FOUND" -eq 1 ] && info " Binary: $PYTHON_BINARY_PATH"
[ "$PYTHON_CLONE_FOUND" -eq 1 ] && info " Clone: $PYTHON_CLONE_PATH"
[ -n "$PYTHON_VENV_PATH" ] && info " Venv: $PYTHON_VENV_PATH"
[ -n "$PYTHON_PID" ] && info " Running PID: $PYTHON_PID"
fi
verbose "detect_python:done detected=${PYTHON_DETECTED} alias=${PYTHON_ALIAS_FOUND} binary=${PYTHON_BINARY_FOUND} clone=${PYTHON_CLONE_FOUND} pid=${PYTHON_PID:-<none>}"
}
# T1.4: Displace Python alias (comment out with backup)
displace_single_python_alias() {
[ "$PYTHON_ALIAS_FOUND" -eq 0 ] && return 0
local rc="$PYTHON_ALIAS_FILE"
[ -z "$rc" ] && return 0
[ -f "$rc" ] || return 0
if [ ! -r "$rc" ]; then
warn "Cannot read shell config file: $rc"
return 1
fi
if [ ! -w "$rc" ]; then
warn "Cannot modify shell config file (not writable): $rc"
return 1
fi
local rc_dir
rc_dir=$(dirname "$rc")
if [ ! -w "$rc_dir" ]; then
warn "Cannot write alongside shell config file (directory not writable): $rc_dir"
return 1
fi
# Create timestamped backup
local timestamp
timestamp=$(date +%Y%m%d_%H%M%S)
local backup="${rc}.bak.mcp-agent-mail-${timestamp}-${RANDOM}"
if ! cp -p "$rc" "$backup"; then
warn "Failed to create backup before modifying alias file: $backup"
return 1
fi
verbose "displace_python_alias:backup rc=${rc} backup=${backup}"
info "Backed up $rc -> $backup"
# Write to a temp file, then atomic rename
local tmpfile="${rc}.tmp.mcp-agent-mail.$$"
if [ "$PYTHON_ALIAS_HAS_MARKERS" -eq 1 ]; then
# Replace the marker block with a commented-out version
awk -v dest="$DEST" -v date="$(date -u +%Y-%m-%dT%H:%M:%SZ)" '
/# >>> MCP Agent Mail/ { in_block=1; print "# >>> MCP Agent Mail alias (DISABLED by Rust installer on " date ")"; next }
/# <<< MCP Agent Mail/ { in_block=0; print "# Rust binary installed at: " dest "/am"; print "# To restore Python version: uncomment the alias line(s) above"; print "# <<< MCP Agent Mail alias (DISABLED)"; next }
in_block && /^[^#]/ { print "# " $0; next }
{ print }
' "$rc" > "$tmpfile"
else
# Comment out the bare alias line or function block
local line_num="$PYTHON_ALIAS_LINE"
if [ "${PYTHON_ALIAS_KIND:-alias}" = "function" ]; then
awk -v line="$line_num" -v dest="$DEST" '
function brace_delta(str, opens, closes, tmp) {
tmp=str
opens=gsub(/\{/, "{", tmp)
tmp=str
closes=gsub(/\}/, "}", tmp)
return opens - closes
}
NR < line { print; next }
NR == line {
print "# Disabled by mcp-agent-mail Rust installer: " $0
print "# Rust binary at: " dest "/am"
in_block=1
is_fish = ($0 ~ /^[[:space:]]*function am([[:space:]]|$)/ && $0 !~ /\(/ && $0 !~ /\{/)
if (!is_fish) {
saw_open = ($0 ~ /\{/)
depth = brace_delta($0)
if (saw_open && depth <= 0) {
in_block=0
}
}
next
}
in_block {
print "# Disabled by mcp-agent-mail Rust installer: " $0
if (is_fish) {
if ($0 ~ /^[[:space:]]*end([[:space:]]|$)/) {
in_block=0
}
} else {
if ($0 ~ /\{/) {
saw_open=1
}
depth += brace_delta($0)
if (saw_open && depth <= 0) {
in_block=0
}
}
next
}
{ print }
' "$rc" > "$tmpfile"
else
awk -v line="$line_num" -v dest="$DEST" '
NR == line { print "# Disabled by mcp-agent-mail Rust installer: " $0; print "# Rust binary at: " dest "/am"; next }
{ print }
' "$rc" > "$tmpfile"
fi
fi
# Verify the temp file is valid (non-empty, at least as many lines as original)
local orig_lines new_lines
orig_lines=$(wc -l < "$rc")
new_lines=$(wc -l < "$tmpfile")
if [ "$new_lines" -lt "$orig_lines" ]; then
warn "Displacement produced fewer lines ($new_lines < $orig_lines); aborting rc modification"
rm -f "$tmpfile"
return 1
fi
# Preserve original permissions
chmod --reference="$rc" "$tmpfile" 2>/dev/null || chmod "$(stat -f '%A' "$rc" 2>/dev/null || echo 644)" "$tmpfile" 2>/dev/null || true
# Atomic rename
if ! mv "$tmpfile" "$rc"; then
warn "Failed to atomically replace shell config file: $rc"
rm -f "$tmpfile" 2>/dev/null || true
return 1
fi
if command -v diff >/dev/null 2>&1; then
local diff_out
diff_out=$(diff -u "$backup" "$rc" 2>/dev/null || true)
if [ -n "$diff_out" ]; then
while IFS= read -r line; do
verbose "displace_python_alias:diff ${line}"
done <<< "$diff_out"
fi
fi
ok "Python alias disabled in $rc"
ok "Backup at $backup"
}
displace_python_alias() {
local pass=0
local max_passes=32
local displaced=0
PYTHON_ALIAS_DISPLACED_COUNT=0
while [ "$pass" -lt "$max_passes" ]; do
detect_python_alias
[ "$PYTHON_ALIAS_FOUND" -eq 1 ] || break
if ! displace_single_python_alias; then
warn "Failed to disable one of the detected 'am' alias/function entries."
break
fi
displaced=$((displaced + 1))
pass=$((pass + 1))
done
PYTHON_ALIAS_DISPLACED_COUNT="$displaced"
detect_python_alias
if [ "$PYTHON_ALIAS_FOUND" -eq 1 ]; then
warn "Could not fully disable all 'am' alias/function definitions."
warn "Remaining entry: ${PYTHON_ALIAS_FILE}:${PYTHON_ALIAS_LINE}"
return 1
fi
if [ "$PYTHON_ALIAS_DISPLACED_COUNT" -gt 0 ]; then
warn "If this shell already loaded an old 'am' alias/function, clear it now:"
warn " unalias am 2>/dev/null || true"
warn " unset -f am 2>/dev/null || true"
warn " hash -r 2>/dev/null || true"
fi
return 0
}
# Displace a legacy am launcher binary/script that appears earlier in PATH
# than the freshly installed Rust binary. This is especially important when a
# Python virtualenv prepends its own `am` script.
displace_python_binary() {
local candidates=()
local seen=""
local displaced_count=0
if [ "$PYTHON_BINARY_FOUND" -eq 1 ] && [ -n "$PYTHON_BINARY_PATH" ]; then
case "$PYTHON_BINARY_PATH" in
python\ *|python3\ *|*"-m mcp_agent_mail"*)
verbose "displace_python_binary:skip non-file launcher=${PYTHON_BINARY_PATH}"
;;
*)
candidates+=("$PYTHON_BINARY_PATH")
;;
esac
fi
if [ -n "${PYTHON_VENV_PATH:-}" ]; then
candidates+=("$PYTHON_VENV_PATH/bin/am")
fi
if [ "$PYTHON_CLONE_FOUND" -eq 1 ] && [ -n "${PYTHON_CLONE_PATH:-}" ]; then
candidates+=("$PYTHON_CLONE_PATH/.venv/bin/am")
candidates+=("$PYTHON_CLONE_PATH/venv/bin/am")
fi
local bin_path
for bin_path in "${candidates[@]}"; do
[ -n "$bin_path" ] || continue
case "$seen" in
*"|$bin_path|"*) continue;;
esac
seen="${seen}|${bin_path}|"
[ "$bin_path" = "$DEST/$BIN_CLI" ] && continue
[ "$bin_path" = "$DEST/am" ] && continue
[ -e "$bin_path" ] || continue
local bin_dir
bin_dir=$(dirname "$bin_path")
if [ ! -w "$bin_dir" ] || [ ! -w "$bin_path" ]; then
warn "Cannot displace legacy am launcher (not writable): $bin_path"
return 1
fi
local timestamp backup tmpfile
timestamp=$(date +%Y%m%d_%H%M%S)
backup="${bin_path}.bak.mcp-agent-mail-${timestamp}-${RANDOM}"
if ! cp -p "$bin_path" "$backup"; then
warn "Failed to backup legacy am launcher before displacement: $bin_path"
return 1
fi
tmpfile="${bin_path}.tmp.mcp-agent-mail.$$"
cat > "$tmpfile" <<EOF
#!/usr/bin/env bash
exec "$DEST/$BIN_CLI" "\$@"
EOF
chmod 0755 "$tmpfile"
if ! mv "$tmpfile" "$bin_path"; then
warn "Failed to replace legacy am launcher at: $bin_path"
rm -f "$tmpfile" 2>/dev/null || true
return 1
fi
ok "Legacy am launcher displaced at $bin_path"
ok "Backup at $backup"
displaced_count=$((displaced_count + 1))
done