-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·2389 lines (2105 loc) · 90.3 KB
/
setup.sh
File metadata and controls
executable file
·2389 lines (2105 loc) · 90.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
# ============================================================================
# OnClick-Claw: One-Click Setup for Claude Code + OpenClaw on Mac
# ============================================================================
# Usage: curl -fsSL https://raw.githubusercontent.com/cncoder/oneclaw/main/setup.sh | bash
# or: bash setup.sh
#
# What it does:
# 1. Install Claude Code (no dependencies — your AI assistant for troubleshooting)
# 2. Collect AWS credentials + configure Claude Code for Bedrock
# 3. Install fnm (Fast Node Manager) + Node.js
# 4. Install pnpm, uv/uvx, AWS CLI
# 5. Install OpenClaw
# 6. Configure OpenClaw (Bedrock, browser, agents)
# 7. Set up Guardian watchdog + LaunchAgents (auto-start on boot)
# 8. Generate a CLAUDE.md for OpenClaw initialization
#
# Requirements: macOS, internet connection
# ============================================================================
set -euo pipefail
# --- Colors ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
# --- Helpers ---
info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[OK]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }
step() { echo -e "\n${CYAN}${BOLD}=== Step $1: $2 ===${NC}\n"; }
# --- launchctl modern API helpers (bootstrap/bootout for macOS 13+, fallback to load/unload) ---
_launchctl_has_bootstrap() {
# macOS 13+ (Ventura) supports bootstrap/bootout
local major
major=$(sw_vers -productVersion 2>/dev/null | cut -d. -f1)
[ "${major:-0}" -ge 13 ]
}
GUI_UID=$(id -u)
la_load() {
local plist="$1"
local label
label=$(basename "$plist" .plist)
if _launchctl_has_bootstrap; then
launchctl bootstrap "gui/${GUI_UID}" "$plist" 2>/dev/null || \
launchctl kickstart -k "gui/${GUI_UID}/${label}" 2>/dev/null || true
else
launchctl load "$plist" 2>/dev/null || true
fi
}
la_unload() {
local plist="$1"
local label
label=$(basename "$plist" .plist)
if _launchctl_has_bootstrap; then
launchctl bootout "gui/${GUI_UID}/${label}" 2>/dev/null || true
else
launchctl unload "$plist" 2>/dev/null || true
fi
}
ask_secret() {
local prompt="$1" var_name="$2" hide="${3:-false}"
local value=""
while [ -z "$value" ]; do
echo -en "${YELLOW}$prompt: ${NC}"
if [ "$hide" = "true" ]; then
read -rs value </dev/tty
echo ""
else
read -r value </dev/tty
fi
[ -z "$value" ] && warn "必填项,请输入内容。"
done
printf -v "$var_name" '%s' "$value"
}
ask_optional() {
local prompt="$1" var_name="$2" default="$3"
echo -en "${YELLOW}$prompt [${default}]: ${NC}"
read -r value </dev/tty
value="${value:-$default}"
printf -v "$var_name" '%s' "$value"
}
check_command() {
command -v "$1" >/dev/null 2>&1
}
# Validate AWS Access Key ID format (AKIA/ASIA prefix, 20 chars, alphanumeric)
validate_aws_ak() {
local ak="$1"
if [[ ! "$ak" =~ ^(AKIA|ASIA)[A-Z0-9]{16}$ ]]; then
return 1
fi
return 0
}
# Validate AWS Secret Access Key format (40 chars, Base64 charset: A-Za-z0-9+/)
validate_aws_sk() {
local sk="$1"
if [[ ${#sk} -ne 40 ]]; then
return 1
fi
if [[ ! "$sk" =~ ^[A-Za-z0-9+/]{40}$ ]]; then
return 1
fi
return 0
}
# Ask for AWS Access Key ID with format validation
ask_aws_ak() {
local var_name="$1"
local value=""
while true; do
echo -en "${YELLOW}请输入 AWS Access Key ID: ${NC}"
read -r value </dev/tty
if [ -z "$value" ]; then
warn "必填项,请输入内容。"
continue
fi
if ! validate_aws_ak "$value"; then
warn "格式不正确。AWS Access Key ID 应以 AKIA 或 ASIA 开头,共 20 个大写字母和数字。"
echo -e " 示例: ${GREEN}AKIAIOSFODNN7EXAMPLE${NC}"
echo -en "${YELLOW}重新输入?(Y/n): ${NC}"
read -r retry </dev/tty
[[ "$retry" =~ ^[Nn]$ ]] && break # User insists, accept as-is
continue
fi
break
done
printf -v "$var_name" '%s' "$value"
}
# Ask for AWS Secret Access Key with format validation
ask_aws_sk() {
local var_name="$1"
local value=""
while true; do
echo -en "${YELLOW}请输入 AWS Secret Access Key(输入时不会显示): ${NC}"
read -rs value </dev/tty
echo ""
if [ -z "$value" ]; then
warn "必填项,请输入内容。"
continue
fi
if ! validate_aws_sk "$value"; then
warn "格式不正确。AWS Secret Access Key 应为 40 个字符(A-Z、a-z、0-9、+、/)。你输入了 ${#value} 个字符。"
echo -en "${YELLOW}重新输入?(Y/n): ${NC}"
read -r retry </dev/tty
[[ "$retry" =~ ^[Nn]$ ]] && break # User insists, accept as-is
continue
fi
break
done
printf -v "$var_name" '%s' "$value"
}
# ============================================================================
# Pre-flight checks
# ============================================================================
echo -e "\n${CYAN}${BOLD}"
echo " ╔══════════════════════════════════════════════════╗"
echo " ║ OnClick-Claw: One-Click Setup Script ║"
echo " ║ Claude Code + OpenClaw + AWS on macOS ║"
echo " ╚══════════════════════════════════════════════════╝"
echo -e "${NC}"
# Check macOS
[[ "$(uname)" == "Darwin" ]] || error "This script only runs on macOS."
info "Detected: macOS $(sw_vers -productVersion) ($(uname -m))"
# ============================================================================
# Optional components — interactive toggle menu
# ============================================================================
# Defaults: all optional components OFF
INSTALL_GHOSTTY=false
# Each optional component: (variable_name label default)
OPTIONAL_COMPONENTS=(
"INSTALL_GHOSTTY|Ghostty 终端配置(为 Claude Code 优化的字体/主题/快捷键)|false"
)
# Interactive menu: space to toggle, enter to confirm
show_optional_menu() {
local num=${#OPTIONAL_COMPONENTS[@]}
# Parse into arrays
local -a vars=() labels=() states=()
for entry in "${OPTIONAL_COMPONENTS[@]}"; do
IFS='|' read -r var label default <<< "$entry"
vars+=("$var")
labels+=("$label")
states+=("$default")
done
echo ""
echo -e "${BOLD}可选组件(空格切换选择,回车确认):${NC}"
echo ""
local current=0
# Hide cursor
tput civis 2>/dev/null || true
# Draw menu
draw_menu() {
# Move cursor up to redraw
for ((i=0; i<num; i++)); do
[ "$i" -gt 0 ] && printf "\033[A"
done
printf "\r"
for ((i=0; i<num; i++)); do
local marker=" "
[ "$current" -eq "$i" ] && marker="> "
local check="[ ]"
[ "${states[$i]}" = "true" ] && check="[✓]"
if [ "$current" -eq "$i" ]; then
printf "\033[K${CYAN}${marker}${check} ${labels[$i]}${NC}\n"
else
printf "\033[K${marker}${check} ${labels[$i]}\n"
fi
done
}
# Initial draw
for ((i=0; i<num; i++)); do
echo ""
done
draw_menu
# Read keys
while true; do
IFS= read -rsn1 key </dev/tty || true
case "$key" in
' ') # Space: toggle
if [ "${states[$current]}" = "true" ]; then
states[$current]="false"
else
states[$current]="true"
fi
draw_menu
;;
'') # Enter: confirm
break
;;
$'\x1b') # Arrow keys (escape sequence)
read -rsn2 arrow </dev/tty
case "$arrow" in
'[A') # Up
((current > 0)) && ((current--)) || true
draw_menu
;;
'[B') # Down
((current < num-1)) && ((current++)) || true
draw_menu
;;
esac
;;
esac
done
# Restore cursor
tput cnorm 2>/dev/null || true
# Apply selections
for ((i=0; i<num; i++)); do
eval "${vars[$i]}=${states[$i]}"
done
echo ""
}
show_optional_menu
echo ""
echo -e "${YELLOW}${BOLD}提示:${NC}安装过程需要管理员权限(sudo),请先输入你的 Mac 登录密码。"
echo -e " 密码输入时屏幕不会显示任何字符,输完按回车就行。"
echo ""
# Pre-flight sudo check — acquire sudo before anything else
if ! sudo -n true 2>/dev/null; then
sudo -v || error "无法获取管理员权限。请确认你的账户是管理员,并输入正确的密码。"
fi
# Keep sudo alive throughout the script
(while true; do sudo -n true; sleep 50; done) 2>/dev/null &
SUDO_KEEPALIVE_PID=$!
trap 'kill $SUDO_KEEPALIVE_PID 2>/dev/null' EXIT
success "管理员权限已获取"
# ============================================================================
# Step 0.5: Xcode Command Line Tools (required for compilation tools)
# ============================================================================
if ! xcode-select -p >/dev/null 2>&1; then
info "Installing Xcode Command Line Tools (may take a few minutes)..."
xcode-select --install 2>/dev/null || true
# Wait for installation to complete
echo -e "${YELLOW}请在弹出的对话框中点击「安装」,等待安装完成后按回车继续...${NC}"
read -r </dev/tty
if ! xcode-select -p >/dev/null 2>&1; then
echo ""
echo -e "${RED}${BOLD}Xcode Command Line Tools 安装失败。${NC}"
echo -e "${YELLOW}请手动执行以下命令,安装完成后重新运行本脚本:${NC}"
echo ""
echo -e " ${CYAN}xcode-select --install${NC}"
echo ""
echo -e " 如果弹窗没出现,可以从 Apple 开发者网站下载:"
echo -e " ${CYAN}https://developer.apple.com/download/more/${NC}"
echo -e " 搜索 \"Command Line Tools\",下载对应 macOS 版本的安装包。"
echo ""
exit 1
fi
success "Xcode Command Line Tools installed"
else
success "Xcode Command Line Tools already installed"
fi
# ============================================================================
# Step 1: Install Claude Code (NO dependencies — install first as safety net)
# ============================================================================
step 1 "Install Claude Code"
# Claude Code install puts binary in ~/.claude/local/bin/ and updates ~/.zshrc
# We need to check multiple possible locations
CLAUDE_SEARCH_PATHS=(
"$HOME/.claude/local/bin"
"$HOME/.local/bin"
"/usr/local/bin"
"/opt/homebrew/bin"
)
find_claude() {
for p in "${CLAUDE_SEARCH_PATHS[@]}"; do
if [ -x "$p/claude" ]; then
echo "$p"
return 0
fi
done
return 1
}
# Helper: ensure a PATH dir is in ~/.zshrc so new terminals can find claude
ensure_path_in_zshrc() {
local dir="$1"
local zshrc="$HOME/.zshrc"
touch "$zshrc"
# Check if this exact export already exists
if ! grep -qF "export PATH=\"$dir:\$PATH\"" "$zshrc" 2>/dev/null && \
! grep -qF "export PATH=\"$dir:" "$zshrc" 2>/dev/null && \
! grep -qF "PATH=\"$dir:" "$zshrc" 2>/dev/null; then
echo "" >> "$zshrc"
echo "# Claude Code" >> "$zshrc"
echo "export PATH=\"$dir:\$PATH\"" >> "$zshrc"
info "已将 ${dir} 写入 ~/.zshrc(新终端窗口自动生效)"
fi
}
if check_command claude; then
success "Claude Code already installed: $(claude --version 2>/dev/null || echo 'installed')"
elif CLAUDE_BIN_DIR=$(find_claude); then
export PATH="$CLAUDE_BIN_DIR:$PATH"
ensure_path_in_zshrc "$CLAUDE_BIN_DIR"
success "Claude Code already installed (found in $CLAUDE_BIN_DIR): $(claude --version 2>/dev/null || echo 'installed')"
else
echo -e "${BOLD}Claude Code 是 AI 编程助手,无额外依赖,优先安装。${NC}"
echo -e "后续步骤如果遇到问题,你可以随时${BOLD}打开新终端${NC}输入 ${GREEN}claude${NC} 让它帮你修复。\n"
# Pre-flight: check if claude.ai is accessible from this region
info "检测 claude.ai 网络可达性..."
CLAUDE_PREFLIGHT=$(curl -fsSL -o /dev/null -w "%{http_code}" -m 10 "https://claude.ai/install.sh" 2>/dev/null || echo "000")
if [ "$CLAUDE_PREFLIGHT" != "200" ]; then
# Double-check: fetch a small chunk and look for region block signature
CLAUDE_BODY=$(curl -fsSL -m 10 "https://claude.ai/install.sh" 2>/dev/null | head -c 2000 || true)
if echo "$CLAUDE_BODY" | grep -qi "unavailable in region\|unavailable here\|isn.*t available"; then
echo ""
echo -e "${RED}${BOLD}Claude.ai 在当前网络环境下不可用(IP 属地受限)。${NC}"
echo ""
echo -e " 检测到 claude.ai 返回 ${YELLOW}\"App unavailable in region\"${NC},"
echo -e " 说明你的网络出口 IP 不在 Claude 服务的可用区域内。"
echo ""
echo -e " ${BOLD}解决方法:${NC}"
echo -e " 配置终端代理,确保出口 IP 在支持的区域(如美国、日本等),然后重新运行本脚本。"
echo ""
# Auto-detect local proxy: scan localhost LISTEN ports, test which can reach Google
PROXY_FOUND=false
SUGGESTED_PORT=""
info "正在探测本地代理端口(可能需要几秒)..."
# Collect unique localhost LISTEN ports (skip well-known non-proxy: 22,53,80,443,3000,3306,5432,8443,9222,18789...)
LOCAL_PORTS=$(lsof -i -sTCP:LISTEN -P -n 2>/dev/null \
| awk '$5=="IPv4" || $5=="IPv6" {print $9}' \
| grep -E '127\.0\.0\.1:|localhost:|\*:' \
| grep -oE '[0-9]+$' \
| sort -un \
| grep -vE '^(22|53|80|443|3000|3306|5432|5900|8443|9222|18789)$' \
|| true)
for port in $LOCAL_PORTS; do
# Try using this port as HTTP proxy to reach Google (2s timeout)
if curl -s -o /dev/null -m 2 -w "%{http_code}" --proxy "http://127.0.0.1:${port}" "https://www.google.com" 2>/dev/null | grep -qE "^(200|301|302)"; then
PROXY_FOUND=true
SUGGESTED_PORT="$port"
success "发现可用代理端口: ${port}"
break
fi
done
if [ "$PROXY_FOUND" = true ]; then
echo ""
echo -e " ${BOLD}在终端执行以下命令设置代理,然后重新运行本脚本:${NC}"
echo ""
echo -e " ${CYAN}export http_proxy=http://127.0.0.1:${SUGGESTED_PORT}${NC}"
echo -e " ${CYAN}export https_proxy=http://127.0.0.1:${SUGGESTED_PORT}${NC}"
else
echo -e " ${YELLOW}未检测到可用的本地代理。请先打开代理软件,然后执行:${NC}"
echo ""
echo -e " ${CYAN}export http_proxy=http://127.0.0.1:<代理端口>${NC}"
echo -e " ${CYAN}export https_proxy=http://127.0.0.1:<代理端口>${NC}"
fi
echo ""
echo -e " ${YELLOW}提示:可以先用浏览器打开 ${CYAN}https://claude.ai${YELLOW} 测试是否能正常访问。${NC}"
echo ""
exit 1
fi
# Not a region block, might be a transient network issue
warn "claude.ai 返回 HTTP ${CLAUDE_PREFLIGHT},可能是临时网络问题,尝试继续安装..."
fi
info "Installing Claude Code..."
if curl -fsSL https://claude.ai/install.sh | bash; then
# Reload PATH: source shell profile to pick up changes made by `claude install`
if [ -f "$HOME/.zshrc" ]; then
source "$HOME/.zshrc" 2>/dev/null || true
fi
# Also explicitly add known locations
for p in "${CLAUDE_SEARCH_PATHS[@]}"; do
[[ ":$PATH:" != *":$p:"* ]] && export PATH="$p:$PATH"
done
if check_command claude; then
success "Claude Code installed: $(claude --version 2>/dev/null || echo 'installed')"
elif CLAUDE_BIN_DIR=$(find_claude); then
export PATH="$CLAUDE_BIN_DIR:$PATH"
success "Claude Code installed (at $CLAUDE_BIN_DIR): $(claude --version 2>/dev/null || echo 'installed')"
else
echo ""
echo -e "${YELLOW}${BOLD}Claude Code 安装可能已成功,但当前终端找不到 claude 命令。${NC}"
echo -e "请${BOLD}关闭终端,重新打开一个新终端${NC},然后重新运行本脚本。"
echo -e "如果仍然找不到,请手动运行:"
echo -e " ${CYAN}curl -fsSL https://claude.ai/install.sh | bash${NC}"
echo -e " 然后关闭终端重新打开,输入 ${GREEN}claude --version${NC} 验证。"
exit 1
fi
else
echo -e "${RED}Claude Code 安装失败。${NC}"
echo -e "请手动运行: ${CYAN}curl -fsSL https://claude.ai/install.sh | bash${NC}"
echo -e "安装完成后${BOLD}关闭终端重新打开${NC},再重新运行本脚本。"
exit 1
fi
fi
# Create symlink in /usr/local/bin so `claude` works in ANY shell without PATH config
CLAUDE_REAL=$(command -v claude 2>/dev/null)
if [ -z "$CLAUDE_REAL" ]; then
CLAUDE_DIR=$(find_claude 2>/dev/null) && CLAUDE_REAL="$CLAUDE_DIR/claude"
fi
if [ -n "$CLAUDE_REAL" ] && [ -x "$CLAUDE_REAL" ] && [ ! -e "/usr/local/bin/claude" ]; then
mkdir -p /usr/local/bin 2>/dev/null || true
if ln -sf "$CLAUDE_REAL" /usr/local/bin/claude 2>/dev/null; then
info "已创建 /usr/local/bin/claude → $CLAUDE_REAL(任何终端直接可用)"
fi
fi
# --- Gate: Claude Code MUST be working before proceeding ---
if ! claude --version >/dev/null 2>&1; then
echo ""
echo -e "${RED}${BOLD}Claude Code 未能正常运行,安装无法继续。${NC}"
echo ""
echo -e " Claude Code 是整个系统的基础,后续所有组件都依赖它。"
echo -e " 请先确保 Claude Code 安装成功后再重新运行本脚本。"
echo ""
echo -e " ${BOLD}排查步骤:${NC}"
echo -e " 1. 关闭当前终端,打开新终端"
echo -e " 2. 输入 ${GREEN}claude --version${NC} 检查是否能正常输出版本号"
echo -e " 3. 如果提示找不到命令,手动运行:"
echo -e " ${CYAN}curl -fsSL https://claude.ai/install.sh | bash${NC}"
echo -e " 4. 安装成功后,关闭终端重新打开,再运行本脚本"
echo ""
exit 1
fi
CLAUDE_VERSION=$(claude --version 2>/dev/null || echo "unknown")
success "Claude Code 已就绪: ${CLAUDE_VERSION}"
# --- Immediately create rescue scripts (only depends on Claude Code) ---
info "创建快捷脚本到 ~/Documents/OneClaw/ ..."
mkdir -p "$HOME/Documents/OneClaw"
# open-claude.command — one-click open Claude Code interactive mode
cat > "$HOME/Documents/OneClaw/open-claude.command" <<'ASKCLAUDE_EOF'
#!/bin/bash
# open-claude.command — Open Claude Code in interactive mode
export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$HOME/Library/pnpm:/usr/local/bin:$PATH"
eval "$(fnm env 2>/dev/null)" || true
if ! command -v claude >/dev/null 2>&1; then
echo "Claude Code not found. Please run: source ~/.zshrc"
exit 1
fi
echo ""
echo " 正在启动 Claude Code..."
echo " 用中文描述你的问题,例如:"
echo " 「帮我检查 AWS 凭证是否正确」"
echo " 「OpenClaw 报错了,帮我看看日志」"
echo " 「Chrome 连不上」"
echo ""
mkdir -p ~/Downloads
cd ~/Downloads
claude
ASKCLAUDE_EOF
chmod +x "$HOME/Documents/OneClaw/open-claude.command"
# ai-repair.command — Full-stack OneClaw AI diagnostic + repair
cat > "$HOME/Documents/OneClaw/ai-repair.command" <<'AIREPAIR_EOF'
#!/bin/bash
# ai-repair.command — OneClaw 全栈 AI 诊断+修复
# 覆盖:OpenClaw / Claude Code / AWS Bedrock / Chrome CDP / Skills / Agents / MCP / 代理 / LaunchAgents
set -euo pipefail
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$HOME/Library/pnpm:/opt/homebrew/bin:/usr/local/bin:$PATH"
eval "$(fnm env 2>/dev/null)" || true
# Run from ~/Downloads so Claude Code doesn't prompt to trust root dir every time
mkdir -p ~/Downloads
cd ~/Downloads
echo -e "\n${CYAN}${BOLD}=== OneClaw 全栈 AI 诊断+修复 ===${NC}"
echo -e "${YELLOW}覆盖 OpenClaw / Claude Code / AWS / Chrome / Skills / MCP 的所有环节${NC}"
echo -e "${YELLOW}预计 2-5 分钟(视问题严重程度)${NC}\n"
if ! command -v claude >/dev/null 2>&1; then
echo -e "${RED}找不到 claude 命令。${NC}"
echo -e "请新开一个终端窗口重试,或先执行: ${CYAN}source ~/.zshrc${NC}"
echo -e "仍无效就重新装: ${CYAN}curl -fsSL https://claude.ai/install.sh | bash${NC}"
exit 1
fi
REPAIR_PROMPT='你是 OneClaw 全栈诊断修复 agent(覆盖 OpenClaw + Claude Code + AWS Bedrock + Chrome CDP + Skills + MCP + 代理)。
铁律(不遵守直接中止):
- 不确定根因就停下来告诉用户,绝不瞎改
- 任何删文件用 `mv ~/.Trash/`,不用 `rm`
- 改 openclaw.json 前先 `cp ~/.openclaw/openclaw.json ~/.openclaw/openclaw.json.bak.$(date +%s)`
- 改 plist 后必须 `launchctl bootout` + `bootstrap`(`kickstart -k` 不重读 env)
- 只报告事实 + 做的事,不编造
- **不检测 Discord/Telegram/Feishu 网络可达性**(用户可能根本没启用这些 channel)。只在 openclaw.json 里配置了对应 channel 且日志有 ETIMEDOUT/reconnect 时才排查
# ===== Step 1: 全栈采集(只读,全跑完再分析)=====
## 1a. 基础环境
```
sw_vers
uname -m
which claude node pnpm aws openclaw 2>&1
claude --version
openclaw --version 2>&1 || echo "openclaw MISSING"
node -v
pnpm -v
aws --version 2>&1
echo "PNPM_HOME=${PNPM_HOME:-unset}"
echo "https_proxy=${https_proxy:-unset}"
```
## 1b. OpenClaw 运行态
```
openclaw daemon status 2>&1
openclaw doctor 2>&1
launchctl list | grep openclaw
pgrep -fl openclaw
lsof -nP -i :18789 -i :9222 -i :8880 2>/dev/null
```
## 1c. OpenClaw 配置与日志
```
test -f ~/.openclaw/openclaw.json && python3 -c "import json; json.load(open(\"$HOME/.openclaw/openclaw.json\"))" 2>&1 || echo "JSON INVALID"
ls -la ~/Library/LaunchAgents/ai.openclaw.*.plist 2>/dev/null
tail -80 ~/.openclaw/logs/gateway.err.log 2>/dev/null
tail -80 ~/.openclaw/logs/node.err.log 2>/dev/null
tail -40 ~/.openclaw/logs/gateway.log 2>/dev/null | grep -iE "error|fatal|reconnect|proxy|econn|etimedout|reason=auth|no api key"
# 兜底:查最近 1 天内任何 log 文件
find ~/.openclaw -name "*.log" -mtime -1 2>/dev/null | head -20
```
## 1d. Claude Code 状态
```
ls -la ~/.claude/settings.json ~/.mcp.json 2>&1
test -f ~/.claude/settings.json && python3 -m json.tool ~/.claude/settings.json > /dev/null 2>&1 && echo "settings.json OK" || echo "settings.json BROKEN"
ls ~/.claude/skills/ 2>&1 | head -20
ls ~/.claude/agents/ 2>&1 | head -20
```
## 1e. AWS / Bedrock
```
test -f ~/.aws/credentials && echo "~/.aws/credentials exists" || echo "~/.aws/credentials MISSING"
aws sts get-caller-identity 2>&1
aws bedrock list-inference-profiles --region us-west-2 --output text 2>&1 | grep -E "opus-4-7|sonnet-4-6|haiku-4-5" | head -5
# 检查 plist 是否注入了 AWS 环境变量(pi-ai 必需)
grep -A1 "AWS_ACCESS_KEY_ID\|AWS_REGION\|AWS_SECRET" ~/Library/LaunchAgents/ai.openclaw.gateway.plist 2>/dev/null | head -20
```
## 1f. Chrome CDP
```
curl -s -m 3 http://127.0.0.1:9222/json/version 2>&1 | head -5
ls -d ~/.openclaw/browser/abel-chrome ~/.openclaw/chrome-profile 2>/dev/null
```
## 1g. 网络 / 代理
```
curl -s -o /dev/null -m 5 -w "github %{http_code} %{time_total}s\n" https://github.com
curl -s -o /dev/null -m 5 -w "bedrock %{http_code} %{time_total}s\n" https://bedrock.us-west-2.amazonaws.com
# 检测本地代理(用户可能用 Clash/Stash/V2ray 任一端口)
for port in 7897 7890 1087 8080 8888 10808; do
curl -s -o /dev/null -m 2 --proxy http://127.0.0.1:$port https://www.google.com -w "proxy $port: %{http_code}\n" 2>/dev/null || true
done
```
## 1h. pnpm / Node 健康
```
ls "$HOME/Library/pnpm/global/"*"/.pnpm/" 2>/dev/null | grep openclaw | head -5
ls "$HOME/Library/pnpm/global/"*"/node_modules/openclaw/" 2>/dev/null | head -5
```
# ===== Step 2: 根因 → 修复映射(严格按症状判断)=====
## OpenClaw 层
| 症状 | 根因 | 修复 |
|-----|-----|------|
| `ERR_MODULE_NOT_FOUND: tslog` / bundled plugins 缺文件 | pnpm store 污染 | `pnpm store prune` → `mv $HOME/Library/pnpm/global/5/.pnpm/openclaw@<坏版本>* ~/.Trash/` → 重装 |
| `No API key found for amazon-bedrock` | gateway plist 没注入 AWS env(pi-ai 只读进程 env,不读 openclaw.json.env.vars) | 给 plist 的 `EnvironmentVariables` 加 AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_REGION;bootout+bootstrap 重载 |
| `reason=auth candidate=...claude-opus-4-6-v1` | 旧 inference profile 下线 | openclaw.json 里所有 `model.primary` / `imageModel.primary` / 子 agent `model` 更新到 `global.anthropic.claude-opus-4-7` / `global.anthropic.claude-sonnet-4-6` / `global.anthropic.claude-haiku-4-5-20251001-v1:0` |
| `Invalid config ... Unrecognized key` | 升级后字段被移除 | `openclaw doctor --fix`,仍报则手动删 cliBackends / talk.voiceId / feishu 旧 streaming 标量等 |
| `discord: Max reconnect attempts` + ETIMEDOUT/ECONNRESET(若用户启用了 Discord) | 防火墙/fake-ip,ws 不读 env 代理 | openclaw.json 里设 `channels.discord.proxy: "http://127.0.0.1:<Step 1g 实测可达端口>"`,`channels.telegram.proxy` 同理,重启 gateway |
| Gateway plist 里写着 `openclaw@旧版本` | 升级后没重注册 | `openclaw daemon install --force` + `openclaw node install --force` |
| `Invalid JSON` | openclaw.json 手改坏了 | 从 `openclaw.json.bak*` 或 git 恢复;没备份就报告不要瞎改 |
| LaunchAgent 非 0 退出 | 具体 bug | 先看对应 .err.log 定位 |
| 端口 18789/9222 被占 | 孤儿进程 | `pkill -f openclaw-gateway; pkill -f openclaw-node; pkill -f "remote-debugging-port=9222"` 后 bootstrap |
| `better_sqlite3 NODE_MODULE_VERSION mismatch` | Node 升级后 native 模块失效 | `cd $(brew --prefix)/lib/node_modules/@tobilu/qmd && npm rebuild better-sqlite3` |
## Claude Code 层
| 症状 | 根因 | 修复 |
|-----|-----|------|
| `claude` 命令找不到 | PATH 未加载 | `source ~/.zshrc`;仍无效重装:`curl -fsSL https://claude.ai/install.sh \| bash` |
| `~/.claude/settings.json` 损坏 | JSON 语法错 | 贴出错误行让用户确认,或从 git/备份恢复 |
| `~/.claude/skills/` 为空 | setup.sh 没跑完 | `git clone --depth 1 https://github.com/cncoder/oneclaw.git /tmp/oneclaw-skills && cp -r /tmp/oneclaw-skills/skills/* ~/.claude/skills/` |
| `~/.claude/agents/` 为空 | 同上 | `cp -r /tmp/oneclaw-skills/agents/*.md ~/.claude/agents/`(跳过 README.md) |
| MCP 连不上(chrome-devtools/aws-documentation) | `~/.mcp.json` 配置错 | 贴出错误,向用户确认是否需要重建 |
## AWS 层
| 症状 | 根因 | 修复 |
|-----|-----|------|
| `aws sts get-caller-identity` 失败 `InvalidClientTokenId` | Access Key 错或已失效 | 让用户到 AWS Console → IAM → 用户 → Security credentials 重发一对新的 |
| `list-inference-profiles` 无 opus-4-7 | 账号没开通模型访问 | 让用户去 Bedrock Console → Model access 申请 Anthropic Claude 全家桶 |
| 返回 403 `bedrock:InvokeModel` | IAM 策略不够 | 需要 `AmazonBedrockFullAccess` 或等价自定义策略 |
## Chrome CDP 层
| 症状 | 根因 | 修复 |
|-----|-----|------|
| `curl :9222/json/version` 连不上 | Chrome LaunchAgent 未启动 | `pkill -f "remote-debugging-port=9222"` → `launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/ai.openclaw.chrome.plist` |
| profile 路径不存在 | 新装或被清理 | `mkdir -p ~/.openclaw/browser/abel-chrome`(或 chrome-profile,看 plist 配的是哪个)|
## 网络层
| 症状 | 根因 | 修复 |
|-----|-----|------|
| 所有 curl 都超时/reset 但代理端口可达 | 直连被拦,需走代理 | 环境变量只对 axios/undici 生效,Discord ws 需要 openclaw.json 里 `channels.*.proxy` |
| 访问解析到 198.18.x.x 被 reset | Clash fake-ip 污染 | 对应 channel 配 `proxy` 字段让 ws 走代理,或 DoH 兜底 |
# ===== Step 3: 服务重启顺序(只在需要时执行)=====
```
launchctl bootout gui/$(id -u)/ai.openclaw.node 2>/dev/null || true
launchctl bootout gui/$(id -u)/ai.openclaw.gateway 2>/dev/null || true
pkill -f openclaw-gateway 2>/dev/null || true
pkill -f openclaw-node 2>/dev/null || true
sleep 1
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/ai.openclaw.gateway.plist
# 等 gateway ready(最多 15 秒)
for i in $(seq 1 15); do
curl -s -o /dev/null -m 1 http://127.0.0.1:18789/ && break
sleep 1
done
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/ai.openclaw.node.plist
sleep 2
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18789/
```
期望返回 200 或 401(401 = 正常,需要 token 登录)。
# ===== Step 4: 最终验证(必须跑)=====
```
openclaw daemon status # Runtime: running, RPC probe: ok
# 取第一个 agent 名跑 smoke test(用户可能改过名字)
AGENT=$(openclaw agent list 2>/dev/null | awk "NR==2{print \$1}")
AGENT=${AGENT:-main}
openclaw agent --agent "$AGENT" -m "say hi in 3 words" --timeout 60
```
`doctor ok ≠ agent ok`。agent 测试失败就继续回到 Step 2 找下一个根因。
# ===== 输出格式(中文)=====
## 发现的问题
- 列出命中的症状 + 贴关键日志(带行号/时间戳)
- 按严重度排序(P0: 服务挂了 / P1: 功能残缺 / P2: 告警)
## 执行的修复
- 每一步:做了什么 + 为什么 + 命令
- 改了配置的,贴 diff
## 验证结果
- `daemon status` 输出
- `agent` smoke test 输出
- 仍异常的日志尾部
## 未解决 / 需用户决策
- 凭证类问题(AWS Key 失效、Discord token 错)只提示不自动改
- 破坏性变更(删配置、回滚版本)先问用户
- 若完全定位不到,列出已收集的证据交回给用户
开始执行。'
claude --dangerously-skip-permissions --max-turns 50 -p "$REPAIR_PROMPT" --output-format text 2>&1 || true
echo -e "\n${GREEN}${BOLD}AI 诊断完成${NC}"
echo -e "如仍有问题请提 issue 附上本次输出: ${CYAN}https://github.com/cncoder/oneclaw/issues${NC}\n"
AIREPAIR_EOF
chmod +x "$HOME/Documents/OneClaw/ai-repair.command"
# Chinese symlinks
ln -sf "open-claude.command" "$HOME/Documents/OneClaw/打开Claude对话.command"
ln -sf "ai-repair.command" "$HOME/Documents/OneClaw/AI修复.command"
success "快捷脚本已创建: ~/Documents/OneClaw/"
echo -e " 📁 ${GREEN}open-claude.command${NC} (打开Claude对话) — 双击打开 Claude Code 交互模式"
echo -e " 📁 ${GREEN}ai-repair.command${NC} (AI修复) — 双击让 AI 自动诊断修复"
echo ""
echo -e "${GREEN}${BOLD}后续步骤如果遇到任何问题,${NC}可以:"
echo -e " 1. 打开新终端输入 ${GREEN}claude${NC}"
echo -e " 2. 或双击 ${GREEN}~/Documents/OneClaw/打开Claude对话.command${NC}"
echo ""
# ============================================================================
# Step 2: Collect AWS credentials + Configure Claude Code for Bedrock
# ============================================================================
step 2 "配置 AWS 凭证 + Claude Code"
echo -e "${BOLD}接下来检查 AWS 凭证配置...${NC}"
echo -e "所有信息只保存在你的电脑上,不会上传到任何地方。\n"
# Check if AWS credentials already exist and work
AWS_CREDS_EXIST=false
if [ -f "$HOME/.aws/credentials" ] && grep -q "aws_access_key_id" "$HOME/.aws/credentials" 2>/dev/null; then
# Extract existing values for later use
AWS_AK=$(grep -m1 "aws_access_key_id" "$HOME/.aws/credentials" | sed 's/.*=[ ]*//')
AWS_SK=$(grep -m1 "aws_secret_access_key" "$HOME/.aws/credentials" | sed 's/.*=[ ]*//')
# Try to validate credentials with a lightweight API call
if check_command aws && aws sts get-caller-identity >/dev/null 2>&1; then
AWS_CREDS_EXIST=true
AWS_IDENTITY=$(aws sts get-caller-identity --output text --query 'Arn' 2>/dev/null || echo "unknown")
success "已检测到有效的 AWS 凭证: ${AWS_IDENTITY}"
echo -e " ${YELLOW}如需更换凭证,请手动编辑 ~/.aws/credentials${NC}"
else
warn "~/.aws/credentials 存在但凭证无效或 AWS CLI 未安装,稍后验证"
# Still use existing values — they may work once AWS CLI is installed
AWS_CREDS_EXIST=true
fi
fi
if [ "$AWS_CREDS_EXIST" = false ]; then
# AWS credentials
echo -e "${CYAN}--- AWS 凭证(用于访问 Bedrock Claude 模型) ---${NC}"
echo -e " ${BOLD}没有 AWS 账号?${NC}找帮你装机的人要一组 Access Key 和 Secret Key。"
echo -e " ${BOLD}已有账号但没有密钥?${NC}登录 AWS Console → IAM → Users → 你的用户 → Security credentials → Create access key"
echo ""
echo -e " ${BOLD}${YELLOW}IAM 用户需要以下权限(缺一不可):${NC}"
echo -e " ${GREEN}bedrock:InvokeModel${NC} — 调用模型(Claude Code + OpenClaw 核心)"
echo -e " ${GREEN}bedrock:InvokeModelWithResponseStream${NC} — 流式调用(实时对话)"
echo -e " ${GREEN}bedrock:ListFoundationModels${NC} — 列出可用模型"
echo -e " ${GREEN}bedrock:GetFoundationModel${NC} — 查询模型详情"
echo -e ""
echo -e " ${BOLD}最简方式:${NC}给 IAM 用户附加 AWS 托管策略 ${GREEN}AmazonBedrockFullAccess${NC}"
echo -e " ${BOLD}最小权限:${NC}只需上面 4 个 Action,Resource 设为 ${GREEN}arn:aws:bedrock:*::foundation-model/*${NC}"
echo -e ""
echo -e " ${YELLOW}还需要在 Bedrock 控制台开启模型访问:${NC}"
echo -e " AWS Console → Bedrock → Model access → 勾选 Anthropic Claude 全系列 → Save"
echo ""
ask_aws_ak AWS_AK
ask_aws_sk AWS_SK
fi
# Region: read from existing config or ask
if [ -f "$HOME/.aws/config" ] && grep -q "region" "$HOME/.aws/config" 2>/dev/null; then
AWS_BEDROCK_REGION=$(grep -m1 "region" "$HOME/.aws/config" | sed 's/.*=[ ]*//')
success "已检测到 AWS 区域: ${AWS_BEDROCK_REGION}"
else
echo ""
echo -e "${CYAN}--- AWS 区域配置 ---${NC}"
echo -e " 默认使用 ${GREEN}us-west-2${NC}(美国西部-俄勒冈),直接按回车即可"
echo -e " 其他常用区域:us-east-1(美东)、eu-west-1(欧洲)、ap-northeast-1(东京)"
ask_optional "AWS Bedrock 区域" AWS_BEDROCK_REGION "us-west-2"
fi
# Claude Code uses the same region — derive inference profile prefix
CC_BEDROCK_REGION="$AWS_BEDROCK_REGION"
# Discord (optional)
echo -e "\n${CYAN}--- Discord 机器人(可选,按回车跳过) ---${NC}"
echo -e " OpenClaw 可以连接 Discord,让你在 Discord 里和 AI 对话、接收告警通知。"
echo -e " 如果暂时不需要,两项都直接按回车跳过,以后可以再配。\n"
echo -e " ${BOLD}如何获取 Discord Bot Token:${NC}"
echo -e " 1. 打开 ${CYAN}https://discord.com/developers/applications${NC}"
echo -e " 2. 点右上角 ${GREEN}New Application${NC} → 输入名字(如 OpenClaw)→ Create"
echo -e " 3. 左侧点 ${GREEN}机器人(Bot)${NC} → 点 ${GREEN}重置令牌(Reset Token)${NC} → 复制 Token"
echo -e " 4. 在同一页面往下找到 ${GREEN}特权网关意图(Privileged Gateway Intents)${NC}"
echo -e " 打开 ${GREEN}消息内容意图(Message Content Intent)${NC} 开关 → 点 ${GREEN}保存(Save)${NC}"
echo -e ""
echo -e " ${BOLD}如何邀请 Bot 到你的 Discord 服务器:${NC}"
echo -e " 5. 左侧点 ${GREEN}OAuth2${NC} → 往下找到 ${GREEN}OAuth2 URL 生成器${NC}"
echo -e " 范围(Scopes)勾选: ${GREEN}bot${NC}"
echo -e " 勾选后下方出现 ${GREEN}机器人权限(Bot Permissions)${NC},勾选:"
echo -e " ${GREEN}Send Messages${NC} / ${GREEN}Read Message History${NC} / ${GREEN}View Channels${NC}"
echo -e " 6. 页面最下方会生成一个 URL → 点 ${GREEN}Copy${NC} → 浏览器打开"
echo -e " 选择你的服务器 → 点 ${GREEN}授权(Authorize)${NC}\n"
echo -en "${YELLOW}Discord Bot Token(没有就直接回车): ${NC}"
read -r DISCORD_BOT_TOKEN </dev/tty
DISCORD_BOT_TOKEN="${DISCORD_BOT_TOKEN:-}"
echo -e "\n ${BOLD}如何获取 Discord Webhook URL:${NC}"
echo -e " 1. 打开 Discord → 进入你想收通知的频道"
echo -e " 2. 点频道名旁的 ⚙️ 设置 → 左侧 ${GREEN}Integrations${NC} → ${GREEN}Webhooks${NC}"
echo -e " 3. 点 ${GREEN}New Webhook${NC} → 取名(如 OpenClaw Alert)→ ${GREEN}Copy Webhook URL${NC}\n"
echo -en "${YELLOW}Discord Webhook URL(用于异常告警,没有就直接回车): ${NC}"
read -r DISCORD_WEBHOOK_URL </dev/tty
DISCORD_WEBHOOK_URL="${DISCORD_WEBHOOK_URL:-}"
# OpenClaw gateway token — auto-generate, user doesn't need to know
GATEWAY_TOKEN=$(openssl rand -hex 24)
info "已自动生成 Gateway 安全令牌"
# --- Write AWS credentials ---
info "Writing AWS credentials..."
mkdir -p "$HOME/.aws"
if command -v aws >/dev/null 2>&1; then
aws configure set aws_access_key_id "$AWS_AK" --profile default
aws configure set aws_secret_access_key "$AWS_SK" --profile default
aws configure set region "$AWS_BEDROCK_REGION" --profile default
aws configure set output json --profile default
success "AWS credentials set via 'aws configure set' (default profile only, other profiles untouched)"
else
# aws cli not yet installed — write files directly (only [default] section)
if [ ! -f "$HOME/.aws/credentials" ] || ! grep -q "\[default\]" "$HOME/.aws/credentials" 2>/dev/null; then
cat > "$HOME/.aws/credentials" <<EOF
[default]
aws_access_key_id = ${AWS_AK}
aws_secret_access_key = ${AWS_SK}
EOF
success "AWS credentials written to ~/.aws/credentials"
else
warn "~/.aws/credentials [default] already exists, not overwriting (aws cli not available for safe merge)"
fi
if [ ! -f "$HOME/.aws/config" ] || ! grep -q "\[default\]" "$HOME/.aws/config" 2>/dev/null; then
cat > "$HOME/.aws/config" <<EOF
[default]
region = ${AWS_BEDROCK_REGION}
output = json
EOF
success "AWS config written to ~/.aws/config"
else
warn "~/.aws/config [default] already exists, not overwriting (aws cli not available for safe merge)"
fi
fi
# --- Verify Bedrock access ---
if check_command aws; then
info "验证 Bedrock 模型访问权限..."
if aws bedrock list-foundation-models --region "$AWS_BEDROCK_REGION" --query 'modelSummaries[?starts_with(modelId, `anthropic.claude`)].[modelId]' --output text >/dev/null 2>&1; then
success "Bedrock 权限验证通过"
else
warn "无法访问 Bedrock 模型。可能的原因:"
echo -e " 1. IAM 用户缺少 ${GREEN}bedrock:ListFoundationModels${NC} 权限"
echo -e " 2. 区域 ${GREEN}${AWS_BEDROCK_REGION}${NC} 未开启 Bedrock 模型访问"
echo -e " 3. 请在 AWS Console → Bedrock → Model access 中勾选 Anthropic Claude 系列"
echo ""
echo -en "${YELLOW}是否重新输入 AWS Access Key?(y/N): ${NC}"
read -r RETRY_CREDS </dev/tty
if [[ "$RETRY_CREDS" =~ ^[Yy]$ ]]; then
ask_aws_ak AWS_AK
ask_aws_sk AWS_SK
aws configure set aws_access_key_id "$AWS_AK" --profile default
aws configure set aws_secret_access_key "$AWS_SK" --profile default
if aws bedrock list-foundation-models --region "$AWS_BEDROCK_REGION" --query 'modelSummaries[?starts_with(modelId, `anthropic.claude`)].[modelId]' --output text >/dev/null 2>&1; then
success "Bedrock 权限验证通过(新凭证)"
else
warn "新凭证仍无法访问 Bedrock,安装将继续。"
echo -e " ${YELLOW}安装完成后可以打开新终端输入 ${GREEN}claude${YELLOW} 让它帮你排查权限问题。${NC}"
fi
else
echo -e " ${YELLOW}安装将继续。完成后可以打开新终端输入 ${GREEN}claude${YELLOW} 让它帮你排查。${NC}"
fi
fi
else
info "AWS CLI 尚未安装,Bedrock 权限将在后续步骤验证"
fi
# --- Configure Claude Code for Bedrock ---
info "Configuring Claude Code for Bedrock..."
CLAUDE_DIR="$HOME/.claude"
mkdir -p "$CLAUDE_DIR"
PROFILE_PREFIX="us"
case "$CC_BEDROCK_REGION" in
eu-*) PROFILE_PREFIX="eu" ;;
ap-*) PROFILE_PREFIX="ap" ;;
esac
if [ -f "$CLAUDE_DIR/settings.json" ]; then
cp "$CLAUDE_DIR/settings.json" "$CLAUDE_DIR/settings.json.bak.$(date +%s)"
warn "已有 settings.json 已备份为 settings.json.bak.*"
fi
cat > "$CLAUDE_DIR/settings.json" <<SETTINGS_EOF
{
"\$schema": "https://json.schemastore.org/claude-code-settings.json",
"respectGitignore": true,
"cleanupPeriodDays": 30,
"env": {
"CLAUDE_CODE_USE_BEDROCK": "1",
"AWS_REGION": "${CC_BEDROCK_REGION}",
"ANTHROPIC_MODEL": "${PROFILE_PREFIX}.anthropic.claude-opus-4-6-v1",
"CLAUDE_CODE_SUBAGENT_MODEL": "${PROFILE_PREFIX}.anthropic.claude-sonnet-4-6",
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "128000",
"CLAUDE_CODE_EFFORT_LEVEL": "medium",
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "50",
"CLAUDE_PACKAGE_MANAGER": "pnpm",
"CLAUDE_CODE_ENABLE_TELEMETRY": "1"
},
"model": "${PROFILE_PREFIX}.anthropic.claude-opus-4-6-v1",
"permissions": {
"allow": [
"Bash",
"mcp__plugin_context7_context7__*",
"mcp__chrome-devtools__*",
"mcp__aws-documentation__*",
"WebFetch",
"Write",
"Edit"
],
"deny": [
"Bash(rm -rf /*)",
"Bash(rm -rf /)",
"Bash(rm -rf ~/*)",
"Bash(rm -rf ~)",
"Bash(sudo rm *)",
"Bash(git push --force *)",
"Bash(git reset --hard *)",
"Bash(git clean -f*)",
"Bash(mkfs*)",
"Bash(dd if=*)"
]
},
"outputStyle": "Concise",
"language": "chinese",
"sandbox": {
"enabled": false,
"autoAllowBashIfSandboxed": true
},
"enabledPlugins": {
"context7@claude-plugins-official": true
}
}
SETTINGS_EOF