Repository navigation
Expand file tree
/
Copy pathsetup-claude-code.sh
More file actions
2324 lines (2043 loc) · 82.8 KB
/
Copy pathsetup-claude-code.sh
File metadata and controls
2324 lines (2043 loc) · 82.8 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
# =============================================================================
# Claude Code One-Click Deployment Script for Offline/Online System
# =============================================================================
# Purpose: Set up Claude Code for a team member using offline packages or
# automatic download with automatic mirror source detection.
#
# Usage: bash setup-claude-code.sh [--offline-path PATH] [--auto-download]
#
# Author: DeepTrial (Enhanced)
# Version: 2.3 - Native binary support, offline resilience, non-interactive mode
# =============================================================================
set -euo pipefail
# ---------------------------------------------------------------------------
# Configuration & Constants
# ---------------------------------------------------------------------------
# Get absolute path of script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Convert to absolute path in case it's relative
SCRIPT_DIR="$(cd "$SCRIPT_DIR" && pwd)"
# Source common utilities (if available)
if [ -f "${SCRIPT_DIR}/skills/lib/common.sh" ]; then
source "${SCRIPT_DIR}/skills/lib/common.sh"
fi
# Fallback definitions if common.sh was not sourced
if ! type log_info >/dev/null 2>&1; then
log_info() { echo "[INFO] $1"; }
log_ok() { echo " [OK] $1"; }
log_warn() { echo " [WARN] $1"; }
log_error(){ echo " [ERROR] $1" >&2; }
fi
if ! type command_exists >/dev/null 2>&1; then
command_exists() { command -v "$1" >/dev/null 2>&1; }
fi
if ! type test_url_accessible >/dev/null 2>&1; then
test_url_accessible() {
local url="$1" timeout="${2:-10}"
if command_exists curl; then
curl -fsSL --max-time "$timeout" --retry 2 -I "$url" >/dev/null 2>&1
elif command_exists wget; then
wget --timeout="$timeout" --tries=2 -q --spider "$url" 2>/dev/null
else
return 1
fi
}
fi
if ! type download_with_mirrors >/dev/null 2>&1; then
download_with_mirrors() {
local output_file="$1"; shift; local mirrors=("$@"); local success=false
for mirror in "${mirrors[@]}"; do
log_info "Trying mirror: $mirror"
if command_exists curl; then
curl -fsSL --max-time 10 --retry 2 -o "$output_file" "$mirror" 2>/dev/null && { success=true; log_ok "Downloaded from: $mirror"; break; }
elif command_exists wget; then
wget --timeout=10 --tries=2 -q -O "$output_file" "$mirror" 2>/dev/null && { success=true; log_ok "Downloaded from: $mirror"; break; }
fi
log_warn "Failed to download from: $mirror"
done
[ "$success" = true ]
}
fi
USER_CLAUDE_DIR="$HOME/.claude"
USER_TMPDIR="$HOME/.claude/tmp"
BASHRC="$HOME/.bashrc"
# GitHub Release Configuration
GITHUB_REPO="DeepTrial/claude-code-offline"
GITHUB_API_URL="https://api.github.com/repos/${GITHUB_REPO}/releases/latest"
# Default offline package path (relative to script location)
DEFAULT_OFFLINE_PATH="${SCRIPT_DIR}/claude-offline-packages"
# Sentinel markers for shell config
SETUP_START="# >>> CLAUDE_CODE_SETUP >>>"
SETUP_END="# <<< CLAUDE_CODE_SETUP <<<"
NODE_START="# >>> CLAUDE_CODE_NODE >>>"
NODE_END="# <<< CLAUDE_CODE_NODE <<<"
# Network timeout settings (seconds)
NETWORK_TIMEOUT=10
CURL_RETRY=2
# Non-interactive mode flags (set by argument parsing)
ASSUME_YES=false
NON_INTERACTIVE=false
# Network status: unknown / true / false (set by check_network_status)
NETWORK_AVAILABLE="unknown"
# ---------------------------------------------------------------------------
# Mirror Source Configuration
# ---------------------------------------------------------------------------
# Node.js binary mirror sources
NODE_MIRRORS=(
"https://nodejs.org/dist/"
"https://npmmirror.com/mirrors/node/"
"http://mirrors.cloud.tencent.com/nodejs-release/"
)
# npm registry mirror sources
NPM_MIRRORS=(
"https://registry.npmjs.org/"
"https://registry.npmmirror.com"
)
# nvm install script mirror sources
NVM_INSTALL_MIRRORS=(
"https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh"
"https://cdn.jsdelivr.net/gh/nvm-sh/nvm@v0.39.7/install.sh"
"https://raw.gitmirror.com/nvm-sh/nvm/v0.39.7/install.sh"
)
# GitHub API/Release mirror sources (for fetching download URLs)
GITHUB_MIRRORS=(
"https://api.github.com"
"https://hub.gitmirror.com/https://api.github.com"
"https://ghproxy.com/https://api.github.com"
"https://ghps.cc/https://api.github.com"
)
# ---------------------------------------------------------------------------
# Uninstall Functions
# ---------------------------------------------------------------------------
# Detect if Claude Code is already installed
detect_existing_installation() {
local found=false
local install_paths=""
# Check if claude exists in PATH (use type instead of command -v for speed)
if type claude >/dev/null 2>&1; then
found=true
install_paths=" - Claude binary: $(type -P claude 2>/dev/null || echo 'in PATH')"
fi
# Check for npm global installation - use only direct path checks, no npm commands
# Get home directory for path construction
local home_dir="$HOME"
# Check common npm global paths
if [ -d "$home_dir/.local/lib/node_modules/@anthropic-ai/claude-code" ]; then
found=true
install_paths="$install_paths
- npm global: $home_dir/.local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/local/lib/node_modules/@anthropic-ai/claude-code" ]; then
found=true
install_paths="$install_paths
- npm global: /usr/local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/lib/node_modules/@anthropic-ai/claude-code" ]; then
found=true
install_paths="$install_paths
- npm global: /usr/lib/node_modules/@anthropic-ai/claude-code"
fi
# Check WSL Windows npm path
if [ -f /proc/version ] && grep -q Microsoft /proc/version 2>/dev/null; then
# Extract username from Windows path
local win_user="${USER:-$(whoami)}"
local win_npm_path="/mnt/c/Users/$win_user/AppData/Roaming/npm/node_modules/@anthropic-ai/claude-code"
if [ -d "$win_npm_path" ]; then
found=true
install_paths="$install_paths
- Windows npm: $win_npm_path"
fi
fi
# Check ~/.claude directory
if [ -d "$home_dir/.claude" ]; then
found=true
install_paths="$install_paths
- Config directory: $home_dir/.claude"
fi
# Check ~/.claude.json
if [ -f "$home_dir/.claude.json" ]; then
found=true
install_paths="$install_paths
- Config file: $home_dir/.claude.json"
fi
# Check .bashrc for configuration
if [ -f "$BASHRC" ] && grep -q "$SETUP_START" "$BASHRC" 2>/dev/null; then
found=true
install_paths="$install_paths
- Shell configuration: $BASHRC"
fi
if [ "$found" = true ]; then
echo "$install_paths"
return 0
else
return 1
fi
}
# Uninstall Claude Code
uninstall_claude_code() {
echo "============================================================================="
echo " Claude Code Uninstaller"
echo "============================================================================="
echo ""
# Detect existing installation
local existing
existing=$(detect_existing_installation)
# Also check for npm global installation (avoid all npm commands which can hang on WSL)
local npm_global_claude=""
# Check common npm global paths directly
if [ -d "$HOME/.local/lib/node_modules/@anthropic-ai/claude-code" ]; then
npm_global_claude="npm: $HOME/.local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/local/lib/node_modules/@anthropic-ai/claude-code" ]; then
npm_global_claude="npm: /usr/local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/lib/node_modules/@anthropic-ai/claude-code" ]; then
npm_global_claude="npm: /usr/lib/node_modules/@anthropic-ai/claude-code"
fi
if [ -z "$existing" ] && [ -z "$npm_global_claude" ]; then
log_warn "No existing Claude Code installation detected."
return 0
fi
if [ -n "$existing" ]; then
echo "Detected existing installation at:"
echo "$existing"
echo ""
fi
if [ -n "$npm_global_claude" ]; then
echo "Detected npm global installation:"
echo " $npm_global_claude"
echo ""
fi
if ! confirm_uninstall; then
log_info "Uninstall cancelled."
return 0
fi
echo ""
log_info "Starting uninstallation..."
# 1. Backup configuration (ask user)
if [ -d "$HOME/.claude" ] || [ -f "$HOME/.claude.json" ]; then
if confirm "Do you want to backup configuration files before uninstalling?" y; then
local backup_dir="$HOME/.claude-backup-$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir"
if [ -d "$HOME/.claude" ]; then
cp -r "$HOME/.claude" "$backup_dir/"
log_ok "Configuration backed up to: $backup_dir"
fi
if [ -f "$HOME/.claude.json" ]; then
cp "$HOME/.claude.json" "$backup_dir/"
fi
fi
fi
# 2. Remove npm global installation if exists (Linux side)
if [ -n "$npm_global_claude" ]; then
log_info "Removing npm global installation of Claude Code..."
# Check if npm is available and not pointing to Windows
if type npm >/dev/null 2>&1 && ! which npm | grep -q "/mnt/c"; then
npm uninstall -g @anthropic-ai/claude-code 2>/dev/null || {
log_warn "Failed to remove npm global installation automatically"
log_info "You may need to run manually: npm uninstall -g @anthropic-ai/claude-code"
}
else
log_warn "npm not available or using Windows npm, skipping npm uninstall"
log_info "You may need to manually remove: $npm_global_claude"
fi
fi
# 2.5 Special handling for WSL Windows npm installations
if [ -f /proc/version ] && grep -q "Microsoft" /proc/version 2>/dev/null; then
# Check for Windows npm claude
local windows_npm_claude="/mnt/c/Users/$USER/AppData/Roaming/npm/claude"
if [ -f "$windows_npm_claude" ] || [ -L "$windows_npm_claude" ]; then
log_warn "Detected Windows npm installation at: $windows_npm_claude"
log_info "Attempting to remove Windows npm installation..."
# Try to use Windows npm to uninstall (with timeout to prevent hanging)
if type cmd.exe >/dev/null 2>&1; then
log_info "Running: cmd.exe /C npm uninstall -g @anthropic-ai/claude-code"
timeout 10 cmd.exe /C "npm uninstall -g @anthropic-ai/claude-code" 2>/dev/null || {
log_warn "Failed to uninstall via Windows npm (timed out or failed)"
}
fi
# Directly remove the files if npm uninstall failed
if [ -f "$windows_npm_claude" ] || [ -L "$windows_npm_claude" ]; then
log_info "Manually removing Windows npm files..."
rm -f "$windows_npm_claude" 2>/dev/null || true
rm -f "/mnt/c/Users/$USER/AppData/Roaming/npm/claude.cmd" 2>/dev/null || true
rm -rf "/mnt/c/Users/$USER/AppData/Roaming/npm/node_modules/@anthropic-ai" 2>/dev/null || true
fi
log_ok "Windows npm installation removed"
fi
# Also check for other common Windows npm paths
for win_path in "/mnt/c/Program Files/nodejs/claude" "/mnt/c/ProgramData/npm/claude"; do
if [ -f "$win_path" ] 2>/dev/null; then
log_warn "Found additional Windows installation at: $win_path"
rm -f "$win_path" 2>/dev/null || true
fi
done
fi
# 3. Remove wrapper alias from .bashrc
if [ -f "$BASHRC" ]; then
# Remove claude wrapper alias
if grep -q "claude-wrapper" "$BASHRC" 2>/dev/null; then
log_info "Removing claude wrapper alias from .bashrc..."
sed -i '/# Claude Code wrapper/d' "$BASHRC"
sed -i "/alias claude='bash/d" "$BASHRC" 2>/dev/null || true
log_ok "Removed wrapper alias"
fi
if grep -q "$SETUP_START" "$BASHRC" 2>/dev/null; then
log_info "Removing PATH/TMPDIR configuration from .bashrc..."
sed -i "/$SETUP_START/,/$SETUP_END/d" "$BASHRC"
log_ok "Removed PATH/TMPDIR configuration"
fi
if grep -q "$NODE_START" "$BASHRC" 2>/dev/null; then
log_info "Removing Node.js configuration from .bashrc..."
sed -i "/$NODE_START/,/$NODE_END/d" "$BASHRC"
log_ok "Removed Node.js configuration"
fi
# Remove NVM configuration (if added by this script)
if grep -q "NVM CONFIGURATION" "$BASHRC" 2>/dev/null; then
if confirm "Remove NVM configuration from .bashrc? (Select 'n' if you use nvm for other projects)" n; then
sed -i '/# >>> NVM CONFIGURATION >>>/,/# <<< NVM CONFIGURATION <<</d' "$BASHRC"
log_ok "Removed NVM configuration"
fi
fi
# Remove Node.js PATH (if installed to ~/.local/node)
if grep -q "/.local/node/bin" "$BASHRC" 2>/dev/null; then
if confirm "Remove Node.js PATH from .bashrc? (Select 'n' if you use this Node.js for other projects)" n; then
sed -i '/\/\.local\/node\/bin/d' "$BASHRC"
log_ok "Removed Node.js PATH"
fi
fi
fi
# 4. Delete configuration files
if [ -f "$HOME/.claude.json" ]; then
log_info "Removing ~/.claude.json..."
rm -f "$HOME/.claude.json"
log_ok "Removed ~/.claude.json"
fi
# 5. Delete ~/.claude directory
if [ -d "$HOME/.claude" ]; then
log_info "Removing ~/.claude directory..."
rm -rf "$HOME/.claude"
log_ok "Removed ~/.claude directory"
fi
# 6. Ask if user wants to remove offline packages
if [ -d "$USER_CLAUDE_DIR/offline-packages" ]; then
if confirm "Remove downloaded offline packages?" n; then
rm -rf "$USER_CLAUDE_DIR/offline-packages"
log_ok "Removed offline packages"
fi
fi
# 7. Ask if user wants to remove Node.js
if [ -d "$HOME/.local/node" ]; then
echo ""
log_warn "Detected Node.js installation at: $HOME/.local/node"
if confirm "Remove this Node.js installation? (Select 'n' if you use it for other projects)" n; then
rm -rf "$HOME/.local/node"
log_ok "Removed Node.js from $HOME/.local/node"
fi
fi
# 8. Ask if user wants to remove nvm
if [ -d "$HOME/.nvm" ]; then
echo ""
log_warn "Detected nvm installation at: $HOME/.nvm"
if confirm "Remove nvm? (Select 'n' if you use it for other projects)" n; then
rm -rf "$HOME/.nvm"
log_ok "Removed nvm from $HOME/.nvm"
fi
fi
echo ""
echo "============================================================================="
echo " Uninstallation Complete"
echo "============================================================================="
echo ""
echo "Claude Code has been uninstalled."
echo ""
echo "IMPORTANT: To complete the uninstallation, please:"
echo " 1. Close and reopen your terminal (NOT just source ~/.bashrc)"
echo " This ensures all environment variables are cleared"
echo " 2. Or run: exec bash -l"
echo " 3. Verify: which claude (should return nothing)"
echo ""
# 9. For WSL: optionally fix PATH to remove Windows npm
if [ -f /proc/version ] && grep -q "Microsoft" /proc/version 2>/dev/null; then
if echo "$PATH" | grep -q "/mnt/c.*npm"; then
echo ""
if confirm "Detected Windows npm in WSL PATH. Add automatic fix to .bashrc?" y; then
log_info "Adding PATH fix to .bashrc..."
cat >> "$BASHRC" << 'WSLFIX'
# >>> WSL PATH FIX >>>
# Remove Windows npm from PATH to avoid conflicts
export PATH=$(echo "$PATH" | tr ':' '\n' | grep -v '/mnt/c.*npm' | tr '\n' ':')
# <<< WSL PATH FIX <<<
WSLFIX
log_ok "PATH fix added to .bashrc"
fi
fi
fi
# WSL specific warning
if [ -f /proc/version ] && grep -q "Microsoft" /proc/version 2>/dev/null; then
echo "============================================================================="
echo " WSL Environment Detected"
echo "============================================================================="
echo ""
echo "You appear to be running in WSL (Windows Subsystem for Linux)."
echo ""
echo "IF YOU STILL SEE 'Permission denied' ERRORS:"
echo ""
echo "1. Remove Windows npm from your WSL PATH:"
echo " Add this line to your ~/.bashrc:"
echo ""
echo " export PATH=\$(echo \$PATH | tr ':' '\\n' | grep -v '/mnt/c.*npm' | tr '\\n' ':')"
echo ""
echo "2. Or manually remove Windows npm files:"
echo " rm -f /mnt/c/Users/\$USER/AppData/Roaming/npm/claude"
echo " rm -f /mnt/c/Users/\$USER/AppData/Roaming/npm/claude.cmd"
echo ""
echo "3. Alternative - Open Windows PowerShell and run:"
echo " npm uninstall -g @anthropic-ai/claude-code"
echo ""
echo "4. Then restart your terminal completely"
echo "============================================================================="
fi
echo ""
return 0
}
# ---------------------------------------------------------------------------
# Helper Functions
# ---------------------------------------------------------------------------
# Common utilities (log_*, command_exists, test_url_accessible, download_with_mirrors)
# are sourced from skills/lib/common.sh above.
# ---------------------------------------------------------------------------
# Interactivity helpers (--yes / --non-interactive support)
# ---------------------------------------------------------------------------
# Unified confirmation helper.
# Usage: confirm "Prompt text" [y|n] (second arg = default answer, default n)
# Returns 0 for yes, 1 for no.
# When ASSUME_YES/NON_INTERACTIVE is set or stdin is not a TTY, the default
# answer is chosen automatically and the choice is printed.
confirm() {
local prompt="$1"
local default="${2:-n}"
local yn_hint answer
if [ "$default" = y ]; then yn_hint="[Y/n]"; else yn_hint="[y/N]"; fi
if [ "$ASSUME_YES" = true ] || [ "$NON_INTERACTIVE" = true ] || [ ! -t 0 ]; then
echo "$prompt $yn_hint: $default (auto)"
[ "$default" = y ] && return 0 || return 1
fi
read -p "$prompt $yn_hint: " -n 1 -r answer || answer=""
echo
[ -z "$answer" ] && answer="$default"
[[ "$answer" =~ ^[Yy]$ ]]
}
# Uninstall confirmation: always requires an explicit yes interactively,
# but --yes (ASSUME_YES) auto-confirms.
confirm_uninstall() {
if [ "$ASSUME_YES" = true ]; then
echo "Are you sure you want to uninstall Claude Code? [y/N]: y (auto, --yes)"
return 0
fi
confirm "Are you sure you want to uninstall Claude Code?" n
}
# ---------------------------------------------------------------------------
# Network resilience helpers
# ---------------------------------------------------------------------------
# Probe npm registry and GitHub with a 5 second timeout each.
# Sets NETWORK_AVAILABLE=true/false and prints a clear conclusion.
check_network_status() {
local npm_ok=false gh_ok=false
local npm_probe="${NPM_MIRRORS[0]}"
local gh_probe="${GITHUB_MIRRORS[0]}"
log_info "Checking network connectivity (5s timeout per probe)..."
if test_url_accessible "$npm_probe" 5; then
npm_ok=true
log_ok "npm registry reachable: $npm_probe"
else
log_warn "npm registry UNREACHABLE: $npm_probe"
fi
if test_url_accessible "$gh_probe" 5; then
gh_ok=true
log_ok "GitHub reachable: $gh_probe"
else
log_warn "GitHub UNREACHABLE: $gh_probe"
fi
if [ "$npm_ok" = true ] || [ "$gh_ok" = true ]; then
NETWORK_AVAILABLE=true
log_ok "Network available"
else
NETWORK_AVAILABLE=false
log_warn "Network appears UNAVAILABLE (npm registry and GitHub both unreachable)"
fi
return 0
}
# Fail-fast guard for steps that require network access.
# Usage: require_network_or_fail "download offline packages"
require_network_or_fail() {
local what="$1"
if [ "$NETWORK_AVAILABLE" = "unknown" ]; then
check_network_status
fi
if [ "$NETWORK_AVAILABLE" != true ]; then
log_error "Cannot $what: network is unreachable."
echo ""
echo "Troubleshooting suggestions:"
echo " - Check your internet connection / proxy / firewall settings"
echo " - Behind a proxy? export HTTPS_PROXY=http://proxy-host:port"
echo " - Use a mirror, e.g.: NPM_MIRROR=https://registry.npmmirror.com bash $0 --auto-download"
echo " - Fully offline? use a pre-downloaded package: bash $0 --offline-path /path/to/claude-offline-packages"
return 1
fi
return 0
}
# Run npm with a timeout and clear diagnostics.
# Usage: run_npm_with_timeout <seconds> <npm args...>
run_npm_with_timeout() {
local seconds="$1"; shift
echo "Running: npm $* (timeout ${seconds}s)"
if timeout "$seconds" npm "$@"; then
return 0
fi
local rc=$?
if [ $rc -eq 124 ]; then
log_error "'npm $*' timed out after ${seconds}s"
else
log_error "'npm $*' failed (exit code $rc)"
fi
echo ""
echo "Possible causes:"
echo " - npm registry unreachable (check network / proxy / firewall)"
echo " - the configured registry is down or blocked"
echo "Try specifying a mirror, e.g.:"
echo " NPM_MIRROR=https://registry.npmmirror.com bash $0"
return $rc
}
# ---------------------------------------------------------------------------
# Native binary / launcher helpers (claude-code 2.x standalone binaries)
# ---------------------------------------------------------------------------
# Print the platform package binary path for this machine, if present.
# Usage: platform_native_binary <packages_dir>
platform_native_binary() {
local pkg_dir="$1"
local os arch suffix=""
os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
Linux*)
case "$arch" in
x86_64|amd64) suffix="linux-x64" ;;
aarch64|arm64) suffix="linux-arm64" ;;
esac
;;
Darwin*)
case "$arch" in
x86_64|amd64) suffix="darwin-x64" ;;
arm64) suffix="darwin-arm64" ;;
esac
;;
CYGWIN*|MINGW*|MSYS*)
case "$arch" in
x86_64|amd64) suffix="win32-x64" ;;
arm64|aarch64) suffix="win32-arm64" ;;
esac
;;
esac
[ -z "$suffix" ] && return 1
local candidate="$pkg_dir/node_modules/@anthropic-ai/claude-code-${suffix}/claude"
case "$suffix" in
win32-*) candidate="${candidate}.exe" ;;
esac
if [ -f "$candidate" ]; then
echo "$candidate"
return 0
fi
return 1
}
# File size that works on both GNU (Linux) and BSD (macOS) stat
file_size() {
stat -c%s "$1" 2>/dev/null || stat -f%z "$1" 2>/dev/null || echo 0
}
# Test whether a native binary actually runs (--version within 30s)
native_binary_runs() {
local bin="$1"
[ -f "$bin" ] || return 1
chmod +x "$bin" 2>/dev/null || true
timeout 30 "$bin" --version >/dev/null 2>&1
}
# Detect how this package can run:
# "native" -> bin/claude.exe is a real, runnable native binary (no Node.js needed)
# "platform" -> bin/claude.exe is a stub but the platform package binary runs
# "node" -> no usable native binary; Node.js wrapper fallback required
detect_runtime_mode() {
local pkg_dir="$1"
local main_bin="$pkg_dir/node_modules/@anthropic-ai/claude-code/bin/claude.exe"
local size plat_bin
size=$(file_size "$main_bin")
if [ "$size" -gt 100000 ] && native_binary_runs "$main_bin"; then
echo "native"
return 0
fi
plat_bin=$(platform_native_binary "$pkg_dir" || true)
if [ -n "$plat_bin" ] && native_binary_runs "$plat_bin"; then
echo "platform"
return 0
fi
echo "node"
}
# Always (re)build node_modules/.bin/claude as a REAL launcher script
# (plain text file, never a symlink). This repairs packages whose symlinks
# were lost when the tar.gz was extracted with Windows tools (Explorer/7z).
# Returns: 0 = launcher execs native binary, 2 = Node.js wrapper fallback,
# 1 = fatal (no entry point found)
rebuild_claude_launcher() {
local pkg_dir="$1"
local bin_dir="$pkg_dir/node_modules/.bin"
local launcher="$bin_dir/claude"
local main_bin="$pkg_dir/node_modules/@anthropic-ai/claude-code/bin/claude.exe"
local size target_rel=""
size=$(file_size "$main_bin")
mkdir -p "$bin_dir"
if [ "$size" -gt 100000 ]; then
target_rel="../@anthropic-ai/claude-code/bin/claude.exe"
else
# bin/claude.exe is missing or a stub (<100KB): exec the platform
# package binary instead (chosen by uname -s/-m)
local plat_bin plat_name
plat_bin=$(platform_native_binary "$pkg_dir" || true)
if [ -n "$plat_bin" ]; then
plat_name=$(basename "$(dirname "$plat_bin")")
target_rel="../@anthropic-ai/${plat_name}/$(basename "$plat_bin")"
log_warn "bin/claude.exe is a stub (${size} bytes); launcher will use ${plat_name} binary"
fi
fi
rm -f "$launcher" 2>/dev/null || true
if [ -n "$target_rel" ]; then
cat > "$launcher" <<LAUNCHER
#!/usr/bin/env bash
# Claude Code launcher (generated by setup-claude-code.sh)
# Real file (NOT a symlink) so it survives Windows extraction tools.
# Locates its own directory via BASH_SOURCE, then execs the native binary.
SELF_DIR="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd)"
exec "\$SELF_DIR/${target_rel}" "\$@"
LAUNCHER
chmod +x "$launcher"
log_ok "Rebuilt launcher as real file (execs native binary): $launcher"
return 0
fi
# Fallback: Node.js wrapper (requires Node.js at runtime)
if [ -f "$pkg_dir/node_modules/@anthropic-ai/claude-code/cli-wrapper.cjs" ]; then
cat > "$launcher" << 'WRAPPER'
#!/usr/bin/env node
require('../@anthropic-ai/claude-code/cli-wrapper.cjs');
WRAPPER
chmod +x "$launcher"
log_warn "No usable native binary; launcher uses cli-wrapper.cjs (Node.js required at runtime)"
return 2
elif [ -f "$pkg_dir/node_modules/@anthropic-ai/claude-code/cli.js" ]; then
cat > "$launcher" << 'LAUNCHER'
#!/usr/bin/env node
require('../@anthropic-ai/claude-code/cli.js');
LAUNCHER
chmod +x "$launcher"
log_warn "No usable native binary; launcher uses cli.js (Node.js required at runtime)"
return 2
fi
log_error "Could not create claude launcher: no native binary or Node.js wrapper found in package"
return 1
}
# ---------------------------------------------------------------------------
# jq helper for the skills installer (system -> bundled -> package manager)
# ---------------------------------------------------------------------------
ensure_jq_for_skills() {
local pkg_dir="$1"
if command -v jq &>/dev/null; then
return 0
fi
log_warn "jq is required for skills installation"
log_info "Attempting to use bundled jq from offline package..."
# Try bundled jq first (no sudo required)
local bundled_jq=""
local os_jq arch_jq
os_jq="$(uname -s)"
arch_jq="$(uname -m)"
case "$os_jq" in
Linux*)
case "$arch_jq" in
x86_64|amd64) bundled_jq="linux-amd64/jq" ;;
aarch64|arm64) bundled_jq="linux-arm64/jq" ;;
esac
;;
Darwin*)
case "$arch_jq" in
x86_64|amd64) bundled_jq="macos-amd64/jq" ;;
arm64) bundled_jq="macos-arm64/jq" ;;
esac
;;
CYGWIN*|MINGW*|MSYS*)
bundled_jq="windows-amd64/jq.exe"
;;
esac
# Search both known layouts: tools/jq/<platform> (legacy) and
# skills/bin/<platform> (current packages)
local candidate=""
if [ -n "$bundled_jq" ]; then
local base
for base in "${pkg_dir}/tools/jq" "${pkg_dir}/skills/bin"; do
if [ -x "${base}/${bundled_jq}" ]; then
candidate="${base}/${bundled_jq}"
break
fi
done
fi
if [ -n "$candidate" ]; then
# Create a temporary jq in PATH so `command -v jq` succeeds
local tmp_jq_dir
tmp_jq_dir=$(mktemp -d)
ln -sf "$candidate" "$tmp_jq_dir/jq"
export PATH="$tmp_jq_dir:$PATH"
log_ok "Using bundled jq from offline package (no sudo required): $candidate"
return 0
fi
# Fallback: try to install system jq (requires sudo and network)
log_info "No bundled jq found for ${os_jq}/${arch_jq}, attempting system install..."
if ! require_network_or_fail "install jq"; then
return 1
fi
if command -v apt-get &>/dev/null; then
sudo apt-get update && sudo apt-get install -y jq
elif command -v yum &>/dev/null; then
sudo yum install -y jq
elif command -v brew &>/dev/null; then
brew install jq
else
log_error "Could not install jq automatically"
return 1
fi
}
# ---------------------------------------------------------------------------
# Direct npm installation of Claude Code (requires network)
# ---------------------------------------------------------------------------
install_via_npm_direct() {
local target_dir="$1"
mkdir -p "$target_dir"
cd "$target_dir"
if ! require_network_or_fail "install Claude Code via npm"; then
return 1
fi
# Select the fastest npm mirror (or the default when skipping tests)
local npm_mirror
if [ "$SKIP_MIRROR_TEST" = true ]; then
npm_mirror="${NPM_MIRRORS[0]}"
else
npm_mirror=$(select_fastest_npm_mirror)
fi
npm config set registry "$npm_mirror"
log_info "Installing Claude Code via npm..."
if ! run_npm_with_timeout 180 install @anthropic-ai/claude-code --production; then
return 1
fi
mkdir -p node_modules/.bin
if [ -f "node_modules/@anthropic-ai/claude-code/cli.js" ]; then
ln -sf ../@anthropic-ai/claude-code/cli.js node_modules/.bin/claude
chmod +x node_modules/.bin/claude
fi
log_ok "Claude Code installed"
}
# ---------------------------------------------------------------------------
# Config File Generators (used by both --config-only and normal mode)
# ---------------------------------------------------------------------------
generate_settings_json() {
local settings_file="$USER_CLAUDE_DIR/settings.json"
if [ -f "$settings_file" ]; then
local backup_name="settings.json.backup.$(date +%Y%m%d_%H%M%S)"
cp "$settings_file" "$USER_CLAUDE_DIR/backups/$backup_name"
log_warn "settings.json already exists. Backed up to backups/$backup_name"
else
cat > "$settings_file" << 'SETTINGSJSON'
{
"env": {
"ANTHROPIC_BASE_URL": "YOUR_BASE_URL_HERE",
"ANTHROPIC_API_KEY": "YOUR_API_KEY_HERE",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "YOUR_MODEL_HERE",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "YOUR_MODEL_HERE",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "YOUR_MODEL_HERE",
"DISABLE_AUTOUPDATER": "1",
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1",
"CLAUDE_CODE_SKIP_FIRST_RUN": "1",
"CLAUDE_CODE_TELEMETRY": "0",
"DISABLE_TELEMETRY": "1",
"CLAUDE_CODE_WEB_FETCH_SKIP_SAFETY_CHECK": "1"
},
"autoUpdate": { "enabled": false },
"hasCompletedOnboarding": true,
"skipOnboarding": true,
"telemetry": { "enabled": false }
}
SETTINGSJSON
log_ok "Created settings.json with placeholder values"
fi
}
generate_config_json() {
local config_file="$USER_CLAUDE_DIR/config.json"
if [ -f "$config_file" ]; then
log_ok "config.json already exists"
else
cat > "$config_file" << 'CONFIGJSON'
{ "primaryApiKey": "mimo" }
CONFIGJSON
log_ok "Created config.json"
fi
}
generate_claude_json() {
local claude_json="$HOME/.claude.json"
local first_start
first_start=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")
if [ -f "$claude_json" ]; then
local backup_name=".claude.json.backup.$(date +%Y%m%d_%H%M%S)"
cp "$claude_json" "$USER_CLAUDE_DIR/backups/$backup_name"
if command_exists python3; then
python3 -c "
import json, sys
try:
with open('$claude_json', 'r') as f:
data = json.load(f)
data['hasCompletedOnboarding'] = True
with open('$claude_json', 'w') as f:
json.dump(data, f, indent=2)
except Exception as e:
pass
" 2>/dev/null || true
elif command_exists jq; then
jq '.hasCompletedOnboarding = true' "$claude_json" > "$claude_json.tmp" && mv "$claude_json.tmp" "$claude_json" 2>/dev/null || true
fi
log_ok "Updated .claude.json (backed up to backups/$backup_name)"
else
cat > "$claude_json" << CLAUDEJSON
{
"hasCompletedOnboarding": true,
"firstStartTime": "$first_start",
"skipOnboarding": true,
"onboardingCompleted": true,
"hasSeenInitialMessage": true,
"hasAcceptedTerms": true,
"telemetry": {
"enabled": false,
"consentGiven": false
},
"regionCheck": {
"bypassed": true,
"checkedAt": "$first_start"
}
}
CLAUDEJSON
log_ok "Created .claude.json"
fi
}
generate_claude_wrapper() {
local wrapper="$USER_CLAUDE_DIR/claude-wrapper.sh"
cat > "$wrapper" << 'WRAPPER'
#!/usr/bin/env bash
# Claude Code Wrapper Script
# This script sets up necessary environment variables to bypass region checks
# 禁用自动更新
export DISABLE_AUTOUPDATER=1
# 禁用遥测
export CLAUDE_CODE_TELEMETRY=0
export DISABLE_TELEMETRY=1
# 跳过首次运行检查
export CLAUDE_CODE_SKIP_FIRST_RUN=1
# 跳过引导流程
export CLAUDE_CODE_SKIP_ONBOARDING=1
# 禁用 Web Tool 的域名安全检查(离线环境下无法连接 claude.ai 验证)
# 这样 Web Tool 会直接获取网页内容而不需要安全检查
export CLAUDE_CODE_WEB_FETCH_SKIP_SAFETY_CHECK=1
# 设置 API 配置(如果用户已配置)
if [ -f "$HOME/.claude/settings.json" ]; then
# Try to read API configuration from settings.json
if command -v jq >/dev/null 2>&1; then
BASE_URL=$(jq -r '.env.ANTHROPIC_BASE_URL // empty' "$HOME/.claude/settings.json" 2>/dev/null)
API_KEY=$(jq -r '.env.ANTHROPIC_API_KEY // empty' "$HOME/.claude/settings.json" 2>/dev/null)
[ -n "$BASE_URL" ] && export ANTHROPIC_BASE_URL="$BASE_URL"
[ -n "$API_KEY" ] && export ANTHROPIC_API_KEY="$API_KEY"
fi
fi
# Execute original claude command
exec claude "$@"
WRAPPER
chmod +x "$wrapper"
log_ok "Created claude-wrapper.sh"
}
generate_clean_tmp() {
local script="$USER_CLAUDE_DIR/clean-tmp.sh"
cat > "$script" << 'CLEANTMP'
#!/usr/bin/env bash
# Clean Claude Code tmp directory
TMPDIR="$HOME/.claude/tmp"
echo "Claude Code TMP Directory Cleaner"
echo "=================================="
echo ""
if [ ! -d "$TMPDIR" ]; then
echo "TMP directory does not exist: $TMPDIR"
exit 0
fi
# Show current size
SIZE=$(du -sh "$TMPDIR" 2>/dev/null | cut -f1)
echo "Current TMP directory size: $SIZE"
echo ""
# Count files
FILE_COUNT=$(find "$TMPDIR" -type f 2>/dev/null | wc -l)