-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathopenclaw.sh
More file actions
executable file
·3466 lines (3033 loc) · 105 KB
/
Copy pathopenclaw.sh
File metadata and controls
executable file
·3466 lines (3033 loc) · 105 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
#
# ╔══════════════════════════════════════════════════════════════════╗
# ║ OpenClaw CTL / MoltBot 管理脚本 ║
# ╠══════════════════════════════════════════════════════════════════╣
# ║ 作者 GitHub : by Joey ║
# ║ YouTube : @joeyblog ║
# ║ Telegram: https://t.me/+ft-zI76oovgwNmRh ║
# ╠══════════════════════════════════════════════════════════════════╣
# ║ 致谢 / 引用 ║
# ║ · 原始脚本基础来自 kejilion(@kejilion) ║
# ║ · CLIProxyAPI 安装器来自 cliproxyapi-installer ║
# ║ github.com/brokechubb/cliproxyapi-installer ║
# ╚══════════════════════════════════════════════════════════════════╝
#
: "${gl_hui:='\e[37m'}"
: "${gl_hong:='\033[31m'}"
: "${gl_lv:='\033[32m'}"
: "${gl_huang:='\033[33m'}"
: "${gl_lan:='\033[34m'}"
: "${gl_bai:='\033[0m'}"
: "${gl_zi:='\033[35m'}"
: "${gl_kjlan:='\033[96m'}"
if ! declare -f break_end > /dev/null 2>&1; then
break_end() {
if command -v gum >/dev/null 2>&1; then
echo
gum style --foreground 240 " ─────────────────────────────────────── "
gum input --placeholder "» 按回车继续 «" --prompt " " > /dev/null
else
echo " ─── 按任意键继续 ───"
read -n 1 -s -r -p ""
echo
fi
clear
}
fi
if ! declare -f install > /dev/null 2>&1; then
install() {
if [[ $# -eq 0 ]]; then
echo "未提供软件包参数"
return 1
fi
for package in "$@"; do
if ! command -v "$package" &>/dev/null; then
echo -e "${gl_kjlan}正在安装 $package...${gl_bai}"
if [[ "$(uname -s)" == "Darwin" ]]; then
_ensure_brew &>/dev/null
command -v brew &>/dev/null && brew install "$package" &>/dev/null
elif command -v dnf &>/dev/null; then
dnf install -y "$package" &>/dev/null
elif command -v yum &>/dev/null; then
yum install -y "$package" &>/dev/null
elif command -v apt &>/dev/null; then
DEBIAN_FRONTEND=noninteractive apt install -y "$package" &>/dev/null
elif command -v apk &>/dev/null; then
apk add "$package" &>/dev/null
elif command -v pacman &>/dev/null; then
pacman -S --noconfirm "$package" &>/dev/null
elif command -v zypper &>/dev/null; then
zypper install -y "$package" &>/dev/null
elif command -v opkg &>/dev/null; then
opkg install "$package" &>/dev/null
elif command -v pkg &>/dev/null; then
pkg install -y "$package" &>/dev/null
else
echo "未知的包管理器,无法安装 $package"
return 1
fi
fi
done
}
fi
is_macos() { [[ "$(uname -s)" == "Darwin" ]]; }
_ensure_brew() {
if ! command -v brew &>/dev/null; then
if [[ -f /opt/homebrew/bin/brew ]]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [[ -f /usr/local/bin/brew ]]; then
eval "$(/usr/local/bin/brew shellenv)"
fi
fi
if ! command -v brew &>/dev/null; then
echo "正在安装 Homebrew..."
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
if [[ -f /opt/homebrew/bin/brew ]]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [[ -f /usr/local/bin/brew ]]; then
eval "$(/usr/local/bin/brew shellenv)"
fi
fi
command -v brew &>/dev/null || { echo "Homebrew 安装失败,请手动安装:https://brew.sh"; return 1; }
}
_sed_i() {
if is_macos; then
sed -i '' "$@"
else
sed -i "$@"
fi
}
install_base_deps() {
if is_macos; then
_ensure_brew || return 1
local missing_brew=()
for cmd in curl git nano jq python3 gpg; do
command -v "$cmd" &>/dev/null || missing_brew+=("$cmd")
done
for i in "${!missing_brew[@]}"; do
[[ "${missing_brew[$i]}" == "gpg" ]] && missing_brew[$i]="gnupg"
done
[[ ${#missing_brew[@]} -eq 0 ]] && return 0
echo "正在安装缺失依赖:${missing_brew[*]}..."
brew install "${missing_brew[@]}" &>/dev/null
return 0
fi
local -a dep_map=(
"curl:curl:curl:curl:curl:curl"
"git:git:git:git:git:git"
"nano:nano:nano:nano:nano:nano"
"jq:jq:jq:jq:jq:jq"
"python3:python3:python3:python3:python:python3"
"tar:tar:tar:tar:tar:tar"
"gpg:gnupg:gnupg2:gnupg:gnupg:gpg2"
)
local missing_apt=() missing_dnf=() missing_apk=() missing_pacman=() missing_zypper=()
for entry in "${dep_map[@]}"; do
IFS=: read -r cmd pkg_apt pkg_dnf pkg_apk pkg_pacman pkg_zypper <<< "$entry"
command -v "$cmd" &>/dev/null && continue
missing_apt+=("$pkg_apt")
missing_dnf+=("$pkg_dnf")
missing_apk+=("$pkg_apk")
missing_pacman+=("$pkg_pacman")
missing_zypper+=("$pkg_zypper")
done
[[ ${#missing_apt[@]} -eq 0 ]] && return 0
echo "正在安装缺失依赖:${missing_apt[*]}..."
if command -v apt &>/dev/null; then
apt update -y &>/dev/null
DEBIAN_FRONTEND=noninteractive apt install -y "${missing_apt[@]}" &>/dev/null
elif command -v dnf &>/dev/null; then
dnf install -y epel-release &>/dev/null || true
dnf install -y "${missing_dnf[@]}" &>/dev/null
elif command -v yum &>/dev/null; then
yum install -y epel-release &>/dev/null || true
yum install -y "${missing_dnf[@]}" &>/dev/null
elif command -v apk &>/dev/null; then
apk update &>/dev/null
apk add "${missing_apk[@]}" &>/dev/null
elif command -v pacman &>/dev/null; then
pacman -Sy --noconfirm --needed "${missing_pacman[@]}" &>/dev/null
elif command -v zypper &>/dev/null; then
zypper install -y "${missing_zypper[@]}" &>/dev/null
fi
if ! command -v python3 &>/dev/null; then
local py
py=$(compgen -c 2>/dev/null | grep -E '^python3\.[0-9]+$' | sort -V | tail -1)
if [[ -n "$py" ]]; then
ln -sf "$(command -v "$py")" /usr/local/bin/python3 2>/dev/null || true
fi
fi
if ! command -v python3 &>/dev/null; then
echo "正在安装 python3..."
if command -v apt &>/dev/null; then
DEBIAN_FRONTEND=noninteractive apt install -y python3 &>/dev/null
elif command -v dnf &>/dev/null; then
dnf install -y python3 &>/dev/null
elif command -v yum &>/dev/null; then
yum install -y python3 &>/dev/null
elif command -v apk &>/dev/null; then
apk add python3 &>/dev/null
elif command -v pacman &>/dev/null; then
pacman -S --noconfirm python &>/dev/null
elif command -v zypper &>/dev/null; then
zypper install -y python3 &>/dev/null
fi
hash -r 2>/dev/null || true
fi
}
_install_gum_binary() {
local arch
case "$(uname -m)" in
x86_64) arch="amd64" ;;
aarch64) arch="arm64" ;;
armv7l) arch="armv7" ;;
*) echo "不支持的架构: $(uname -m)"; return 1 ;;
esac
local latest
latest=$(curl -fsSL https://api.github.com/repos/charmbracelet/gum/releases/latest \
| grep '"tag_name"' | sed 's/.*"v\([^"]*\)".*/\1/')
[[ -z "$latest" ]] && { echo "获取 gum 版本失败"; return 1; }
local url="https://github.com/charmbracelet/gum/releases/download/v${latest}/gum_${latest}_linux_${arch}.tar.gz"
local tmp
tmp=$(mktemp -d)
curl -fsSL "$url" -o "$tmp/gum.tar.gz" \
&& tar -xzf "$tmp/gum.tar.gz" -C "$tmp" \
&& install -m 755 "$tmp/gum" /usr/local/bin/gum
rm -rf "$tmp"
command -v gum >/dev/null 2>&1
}
install_gum() {
command -v gum >/dev/null 2>&1 && return 0
echo "正在安装 gum..."
if command -v brew >/dev/null 2>&1; then
brew install gum
elif command -v apt >/dev/null 2>&1; then
command -v gpg >/dev/null 2>&1 || apt install -y gnupg 2>/dev/null
mkdir -p /etc/apt/keyrings
if curl -fsSL https://repo.charm.sh/apt/gpg.key \
| gpg --dearmor -o /etc/apt/keyrings/charm.gpg 2>/dev/null; then
echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" \
| tee /etc/apt/sources.list.d/charm.list >/dev/null
apt update -y 2>/dev/null && apt install -y gum 2>/dev/null
fi
command -v gum >/dev/null 2>&1 || _install_gum_binary
elif command -v dnf &>/dev/null; then
cat > /etc/yum.repos.d/charm.repo <<'REPO'
[charm]
name=Charm
baseurl=https://repo.charm.sh/yum/
enabled=1
gpgcheck=1
gpgkey=https://repo.charm.sh/yum/gpg.key
REPO
dnf install -y gum
elif command -v yum &>/dev/null; then
cat > /etc/yum.repos.d/charm.repo <<'REPO'
[charm]
name=Charm
baseurl=https://repo.charm.sh/yum/
enabled=1
gpgcheck=1
gpgkey=https://repo.charm.sh/yum/gpg.key
REPO
yum install -y gum
elif command -v apk &>/dev/null; then
apk add gum 2>/dev/null || _install_gum_binary
elif command -v pacman &>/dev/null; then
pacman -S --noconfirm gum 2>/dev/null || _install_gum_binary
elif command -v zypper &>/dev/null; then
zypper install -y gum 2>/dev/null || _install_gum_binary
else
_install_gum_binary
fi
command -v gum >/dev/null 2>&1 || { echo "gum 安装失败,请手动安装: https://github.com/charmbracelet/gum"; return 1; }
}
install_fzf() {
command -v fzf >/dev/null 2>&1 && return 0
echo "正在安装 fzf..."
if command -v brew >/dev/null 2>&1; then
brew install fzf
elif command -v apt >/dev/null 2>&1; then
apt install -y fzf
elif command -v dnf &>/dev/null; then
dnf install -y fzf
elif command -v yum &>/dev/null; then
yum install -y fzf
elif command -v apk &>/dev/null; then
apk add fzf
elif command -v pacman &>/dev/null; then
pacman -S --noconfirm fzf
elif command -v zypper &>/dev/null; then
zypper install -y fzf
else
echo "无法自动安装 fzf,请手动安装: https://github.com/junegunn/fzf"
return 1
fi
}
_install_shortcut() {
local store_dir shortcut_dir shortcut
store_dir="$HOME/.local/bin"
mkdir -p "$store_dir"
local _candidate_dirs=("/opt/homebrew/bin" "/usr/local/bin")
shortcut_dir=""
for _d in "${_candidate_dirs[@]}"; do
if [[ -d "$_d" && -w "$_d" ]]; then
shortcut_dir="$_d"
break
fi
done
if [[ -z "$shortcut_dir" ]]; then
shortcut_dir="$store_dir"
local rc_file=""
[[ -f "$HOME/.zshrc" ]] && rc_file="$HOME/.zshrc"
[[ -f "$HOME/.bashrc" ]] && rc_file="${rc_file:-$HOME/.bashrc}"
if [[ -n "$rc_file" ]] && ! grep -q "$store_dir" "$rc_file" 2>/dev/null; then
printf '\nexport PATH="%s:$PATH"\n' "$store_dir" >> "$rc_file"
fi
export PATH="$store_dir:$PATH"
fi
shortcut="$shortcut_dir/oc"
cat > "$shortcut" <<EOF
#!/usr/bin/env bash
curl -fsSL https://raw.githubusercontent.com/byJoey/openclawctl/main/openclaw.sh \\
-o "$store_dir/openclawctl.sh" 2>/dev/null && chmod +x "$store_dir/openclawctl.sh"
exec bash "$store_dir/openclawctl.sh" "\$@"
EOF
chmod +x "$shortcut"
}
moltbot_menu() {
is_macos && _ensure_brew
_install_shortcut
install_base_deps
install_gum || { echo "gum 安装失败,无法继续"; return 1; }
install_fzf || { echo "fzf 安装失败,无法继续"; return 1; }
ui_header() {
gum style \
--bold --foreground 51 \
--border rounded --border-foreground 51 \
--padding "0 2" "$*"
echo
}
_fallback_input() {
local prompt="${1:-输入}" placeholder="${2:-}"
local val
[[ -n "$placeholder" ]] && echo -e " \033[90m($placeholder)\033[0m"
read -rp " $prompt: " val
echo "$val"
}
_fallback_confirm() {
local msg="${1:-确认?}"
local yn
read -rp " $msg [y/N]: " yn
[[ "$yn" == "y" || "$yn" == "Y" ]]
}
_fallback_spin() {
local title="$1"; shift
echo -e " \033[90m$title\033[0m"
"$@"
}
ui_ok() { gum style --foreground 46 " ◉ $*"; }
ui_err() { gum style --foreground 196 " ✗ $*"; }
ui_warn() { gum style --foreground 208 " ⚡ $*"; }
ui_info() { gum style --foreground 51 " ◈ $*"; }
ui_step() { echo; gum style --bold --foreground 201 " ▶ $*"; echo; }
if _has_gum; then
ui_header() {
gum style \
--bold --foreground 51 \
--border rounded --border-foreground 51 \
--padding "0 2" "$*"
echo
}
ui_ok() { gum style --foreground 46 " ◉ $*"; }
ui_err() { gum style --foreground 196 " ✗ $*"; }
ui_warn() { gum style --foreground 208 " ⚡ $*"; }
ui_info() { gum style --foreground 51 " ◈ $*"; }
ui_step() { echo; gum style --bold --foreground 201 " ▶ $*"; echo; }
else
ui_header() { echo -e "\n \033[1;36m══ $* ══\033[0m\n"; }
ui_ok() { echo -e " \033[32m[OK]\033[0m $*"; }
ui_err() { echo -e " \033[31m[ERR]\033[0m $*"; }
ui_warn() { echo -e " \033[33m[WARN]\033[0m $*"; }
ui_info() { echo -e " \033[36m[i]\033[0m $*"; }
ui_step() { echo -e "\n \033[35m>>\033[0m $*\n"; }
fi
check_openclaw_update() {
if ! command -v npm >/dev/null 2>&1; then
return 1
fi
local local_version remote_version
local_version=$(npm list -g openclaw --depth=0 --no-update-notifier 2>/dev/null \
| grep openclaw | awk '{print $NF}' | sed 's/^.*@//')
[[ -z "$local_version" ]] && return 1
remote_version=$(npm view openclaw version --no-update-notifier 2>/dev/null)
[[ -z "$remote_version" ]] && return 1
if [[ "$local_version" != "$remote_version" ]]; then
echo -e "\033[38;5;208m⚡ UPDATE AVAILABLE $remote_version\033[0m"
else
echo -e "\033[90m✦ v$local_version\033[0m"
fi
}
get_install_status() {
if command -v openclaw >/dev/null 2>&1; then
echo -e "\033[38;5;46m◉ INSTALLED\033[0m"
else
echo -e "\033[90m○ NOT FOUND\033[0m"
fi
}
get_running_status() {
if pgrep -f "openclaw.*gatewa" >/dev/null 2>&1; then
echo -e "\033[38;5;46m▶ RUNNING\033[0m"
else
echo -e "\033[90m■ STOPPED\033[0m"
fi
}
start_gateway() {
if is_macos; then
local plist="$HOME/Library/LaunchAgents/ai.openclaw.gateway.plist"
openclaw gateway stop >/dev/null 2>&1
launchctl unload "$plist" >/dev/null 2>&1 || true
if [[ -f "$plist" ]]; then
gum spin --spinner pulse --title "正在启动网关..." -- \
bash -c "launchctl load '$plist' 2>/dev/null; sleep 2"
else
gum spin --spinner pulse --title "正在安装并启动网关..." -- \
bash -c "openclaw gateway install 2>/dev/null; sleep 2"
fi
else
openclaw gateway stop >/dev/null 2>&1
gum spin --spinner pulse --title "正在启动网关..." -- openclaw gateway start
sleep 1
fi
}
install_node_and_tools() {
if command -v node &>/dev/null && command -v npm &>/dev/null; then
return 0
fi
echo "正在安装 Node.js..."
if is_macos; then
_ensure_brew || return 1
brew install node &>/dev/null
elif command -v dnf &>/dev/null; then
curl -fsSL https://rpm.nodesource.com/setup_24.x | bash - &>/dev/null
dnf install -y cmake libatomic nodejs &>/dev/null
elif command -v apt &>/dev/null; then
curl -fsSL https://deb.nodesource.com/setup_24.x | bash - &>/dev/null
DEBIAN_FRONTEND=noninteractive apt install -y build-essential python3 libatomic1 nodejs &>/dev/null
fi
hash -r 2>/dev/null || true
}
configure_openclaw_session_policy() {
local config_file="${HOME}/.openclaw/openclaw.json"
[[ ! -f "$config_file" ]] && return 1
command -v python3 &>/dev/null || install_base_deps
python3 - "$config_file" <<'PY'
import json, sys
path = sys.argv[1]
with open(path, 'r', encoding='utf-8') as f:
obj = json.load(f)
session = obj.setdefault('session', {})
session['dmScope'] = session.get('dmScope', 'per-channel-peer')
session['resetTriggers'] = ['/new', '/reset']
session['reset'] = {
'mode': 'idle',
'idleMinutes': 10080
}
session['resetByType'] = {
'direct': {'mode': 'idle', 'idleMinutes': 10080},
'thread': {'mode': 'idle', 'idleMinutes': 1440},
'group': {'mode': 'idle', 'idleMinutes': 120}
}
with open(path, 'w', encoding='utf-8') as f:
json.dump(obj, f, ensure_ascii=False, indent=2)
f.write('\n')
PY
}
sync_openclaw_api_models() {
local config_file="${HOME}/.openclaw/openclaw.json"
[[ ! -f "$config_file" ]] && return 0
command -v python3 &>/dev/null || install_base_deps
python3 - "$config_file" <<'PY'
import copy
import json
import sys
import time
import urllib.request
path = sys.argv[1]
with open(path, 'r', encoding='utf-8') as f:
obj = json.load(f)
work = copy.deepcopy(obj)
models_cfg = work.setdefault('models', {})
providers = models_cfg.get('providers', {})
if not isinstance(providers, dict) or not providers:
print('未检测到 API providers,跳过模型同步')
raise SystemExit(0)
agents = work.setdefault('agents', {})
defaults = agents.setdefault('defaults', {})
defaults_models_raw = defaults.get('models')
if isinstance(defaults_models_raw, dict):
defaults_models = defaults_models_raw
elif isinstance(defaults_models_raw, list):
defaults_models = {str(x): {} for x in defaults_models_raw if isinstance(x, str)}
else:
defaults_models = {}
defaults['models'] = defaults_models
SUPPORTED_APIS = {'openai-completions', 'openai-responses', 'openai-chat-completions'}
changed = False
fatal_errors = []
summary = []
def model_ref(provider_name, model_id):
return f"{provider_name}/{model_id}"
def get_primary_ref(defaults_obj):
model_obj = defaults_obj.get('model')
if isinstance(model_obj, str):
return model_obj
if isinstance(model_obj, dict):
primary = model_obj.get('primary')
if isinstance(primary, str):
return primary
return None
def set_primary_ref(defaults_obj, new_ref):
model_obj = defaults_obj.get('model')
if isinstance(model_obj, str):
defaults_obj['model'] = new_ref
elif isinstance(model_obj, dict):
model_obj['primary'] = new_ref
else:
defaults_obj['model'] = {'primary': new_ref}
def ref_provider(ref):
if not isinstance(ref, str) or '/' not in ref:
return None
return ref.split('/', 1)[0]
def collect_available_refs(exclude_provider=None):
refs = []
if not isinstance(providers, dict):
return refs
for pname, p in providers.items():
if exclude_provider and pname == exclude_provider:
continue
if not isinstance(p, dict):
continue
for m in p.get('models', []) or []:
if isinstance(m, dict) and m.get('id'):
refs.append(model_ref(pname, str(m['id'])))
return refs
def prompt_delete_provider(name):
prompt = f"{name} /models 探测连续失败 3 次。是否删除该 API 供应商及其全部相关模型?[y/N]: "
try:
ans = input(prompt).strip().lower()
except EOFError:
return False
return ans in ('y', 'yes')
def rebind_defaults_before_delete(name):
global changed
replacement = None
def get_replacement():
nonlocal replacement
if replacement is None:
candidates = collect_available_refs(exclude_provider=name)
replacement = candidates[0] if candidates else None
return replacement
primary_ref = get_primary_ref(defaults)
if ref_provider(primary_ref) == name:
repl = get_replacement()
if not repl:
summary.append(f'错误 - {name}: 默认主模型指向该 provider,但无可用替代模型,已中止删除')
return False
set_primary_ref(defaults, repl)
changed = True
summary.append(f'已切换默认主模型: {primary_ref} -> {repl}')
for fk in ('modelFallback', 'imageModelFallback'):
val = defaults.get(fk)
if ref_provider(val) == name:
repl = get_replacement()
if not repl:
summary.append(f'错误 - {name}: {fk} 指向该 provider,但无可用替代模型,已中止删除')
return False
defaults[fk] = repl
changed = True
summary.append(f'已切换 {fk}: {val} -> {repl}')
return True
def delete_provider_and_refs(name):
global changed
if not rebind_defaults_before_delete(name):
return False
removed_refs = [r for r in list(defaults_models.keys()) if r.startswith(name + '/')]
for r in removed_refs:
defaults_models.pop(r, None)
if removed_refs:
changed = True
if name in providers:
providers.pop(name, None)
changed = True
summary.append(f'已删除 provider {name},并移除 defaults.models 下 {len(removed_refs)} 个模型引用')
return True
def fetch_remote_models_with_retry(name, base_url, api_key, retries=3):
last_error = None
for attempt in range(1, retries + 1):
req = urllib.request.Request(
base_url.rstrip('/') + '/models',
headers={
'Authorization': f'Bearer {api_key}',
'User-Agent': 'Mozilla/5.0',
},
)
try:
with urllib.request.urlopen(req, timeout=12) as resp:
payload = resp.read().decode('utf-8', 'ignore')
data = json.loads(payload)
return data, None, attempt
except Exception as e:
last_error = e
if attempt < retries:
time.sleep(1)
return None, last_error, retries
for name, provider in list(providers.items()):
if not isinstance(provider, dict):
summary.append(f'跳过 {name}: provider 结构非法')
continue
api = provider.get('api', '')
base_url = provider.get('baseUrl')
api_key = provider.get('apiKey')
model_list = provider.get('models', [])
if not base_url or not api_key or not isinstance(model_list, list) or not model_list:
summary.append(f'跳过 {name}: 无 baseUrl/apiKey/models')
continue
if api not in SUPPORTED_APIS:
summary.append(f'跳过 {name}: 不支持直接 /models 校验 (api={api})')
continue
data, err, attempts = fetch_remote_models_with_retry(name, base_url, api_key, retries=3)
if err is not None:
summary.append(f'警告 - {name}: /models 探测失败,已重试 {attempts} 次 ({type(err).__name__}: {err})')
if prompt_delete_provider(name):
deleted = delete_provider_and_refs(name)
if deleted:
summary.append(f'{name}: 用户已确认删除该 provider 及全部相关模型引用')
else:
summary.append(f'{name}: 用户未确认删除,保留现有 provider 配置')
continue
if attempts > 1:
summary.append(f'{name}: /models 第 {attempts} 次重试后成功')
if not (isinstance(data, dict) and isinstance(data.get('data'), list)):
summary.append(f'警告 - 跳过 {name}: /models 返回结构不可识别')
continue
remote_ids = []
for item in data['data']:
if isinstance(item, dict) and item.get('id'):
remote_ids.append(str(item['id']))
remote_set = set(remote_ids)
if not remote_set:
fatal_errors.append(f'错误 - {name} 上游 /models 为空,无法为该 provider 提供兜底模型')
continue
local_models = [m for m in model_list if isinstance(m, dict) and m.get('id')]
local_ids = [str(m['id']) for m in local_models]
local_set = set(local_ids)
template = None
for m in local_models:
template = copy.deepcopy(m)
break
if template is None:
summary.append(f'警告 - 跳过 {name}: 本地 models 无有效模板模型')
continue
removed_ids = [mid for mid in local_ids if mid not in remote_set]
added_ids = [mid for mid in remote_ids if mid not in local_set]
kept_models = [copy.deepcopy(m) for m in local_models if str(m['id']) in remote_set]
new_models = kept_models[:]
for mid in added_ids:
nm = copy.deepcopy(template)
nm['id'] = mid
if isinstance(nm.get('name'), str):
nm['name'] = f'{name} / {mid}'
new_models.append(nm)
if not new_models:
fatal_errors.append(f'错误 - {name} 同步后无可用模型,无法保障默认模型/回退模型兜底')
continue
expected_refs = {model_ref(name, str(m['id'])) for m in new_models if isinstance(m, dict) and m.get('id')}
local_refs = {model_ref(name, mid) for mid in local_ids}
first_ref = model_ref(name, str(new_models[0]['id']))
primary_ref = get_primary_ref(defaults)
if isinstance(primary_ref, str) and primary_ref in (local_refs - expected_refs):
set_primary_ref(defaults, first_ref)
changed = True
summary.append(f'默认模型已兜底替换: {primary_ref} -> {first_ref}')
for fk in ('modelFallback', 'imageModelFallback'):
val = defaults.get(fk)
if isinstance(val, str) and val in (local_refs - expected_refs):
defaults[fk] = first_ref
changed = True
summary.append(f'{fk} 已兜底替换: {val} -> {first_ref}')
stale_refs = [r for r in list(defaults_models.keys()) if r.startswith(name + '/') and r not in expected_refs]
for r in stale_refs:
defaults_models.pop(r, None)
changed = True
for r in sorted(expected_refs):
if r not in defaults_models:
defaults_models[r] = {}
changed = True
if removed_ids or added_ids or len(local_models) != len(new_models):
provider['models'] = new_models
changed = True
summary.append(f'{name}: 删除 {len(removed_ids)} 个,新增 {len(added_ids)} 个,当前 {len(new_models)} 个')
if fatal_errors:
for line in summary:
print(line)
for err in fatal_errors:
print(err)
print('模型同步失败:存在 provider 同步后无可用模型,已中止写入')
raise SystemExit(2)
if changed:
with open(path, 'w', encoding='utf-8') as f:
json.dump(work, f, ensure_ascii=False, indent=2)
f.write('\n')
for line in summary:
print(line)
print('OpenClaw API 模型一致性同步完成')
else:
for line in summary:
print(line)
print('无需同步:配置已与上游 /models 保持一致')
PY
}
_install_openclaw_core() {
install_node_and_tools
git config --global url."${gh_https_url}github.com/".insteadOf ssh://git@github.com/
git config --global url."${gh_https_url}github.com/".insteadOf git@github.com:
if is_macos; then
gum spin --spinner globe --title "正在安装 OpenClaw..." -- \
env SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install -g openclaw@latest
else
gum spin --spinner globe --title "正在安装 OpenClaw..." -- npm install -g openclaw@latest
fi
hash -r 2>/dev/null || true
local npm_prefix npm_bin
npm_prefix=$(npm prefix -g 2>/dev/null)
npm_bin="${npm_prefix}/bin"
if [[ -n "$npm_bin" ]]; then
export PATH="$npm_bin:$PATH"
for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile"; do
[[ -f "$rc" ]] || continue
grep -qF "$npm_bin" "$rc" 2>/dev/null && continue
echo "export PATH=\"${npm_bin}:\$PATH\"" >> "$rc"
done
fi
openclaw onboard --install-daemon
_sed_i 's|"profile": "messaging"|"profile": "full"|g' ~/.openclaw/openclaw.json
configure_openclaw_session_policy
if ! is_macos; then
systemctl --user enable openclaw-gateway.service 2>/dev/null || true
fi
start_gateway
}
install_moltbot() {
_install_openclaw_core
break_end
}
_cliproxy_dir() {
if is_macos; then
echo "$(brew --prefix 2>/dev/null || echo /usr/local)/etc"
else
echo "$HOME/cliproxyapi"
fi
}
_cliproxy_conf() {
if is_macos; then
echo "$(_cliproxy_dir)/cliproxyapi.conf"
else
echo "$(_cliproxy_dir)/config.yaml"
fi
}
_cliproxy_bin() {
if is_macos; then
command -v cliproxyapi 2>/dev/null || echo "cliproxyapi"
else
echo "$HOME/cliproxyapi/cli-proxy-api"
fi
}
_cliproxy_running() {
if is_macos; then
pgrep -f "cliproxyapi" >/dev/null 2>&1
else
pgrep -f "cli-proxy-api" >/dev/null 2>&1
fi
}
_cliproxy_start_service() {
if is_macos; then
gum spin --spinner pulse --title "正在启动 CLIProxyAPI..." -- \
bash -c "brew services start cliproxyapi 2>/dev/null; sleep 2"
else
systemctl --user enable cliproxyapi.service >/dev/null 2>&1 || true
gum spin --spinner pulse --title "正在启动 CLIProxyAPI..." -- \
bash -c "systemctl --user start cliproxyapi.service 2>/dev/null; sleep 3"
if ! _cliproxy_running; then
ui_warn "systemd 启动失败,改用后台直接运行..."
local cliproxy_dir; cliproxy_dir=$(_cliproxy_dir)
(cd "$cliproxy_dir" && nohup ./cli-proxy-api > /tmp/cliproxyapi.log 2>&1 &)
sleep 3
fi
fi
if _cliproxy_running; then
ui_ok "CLIProxyAPI 已启动"
return 0
else
ui_err "CLIProxyAPI 启动失败,请检查 $(_cliproxy_conf) 后手动启动"
return 1
fi
}
_cliproxy_stop_service() {
if is_macos; then
gum spin --spinner pulse --title "正在停止 CLIProxyAPI..." -- \
bash -c "brew services stop cliproxyapi 2>/dev/null; sleep 2"
else
if systemctl --user is-active --quiet cliproxyapi.service 2>/dev/null; then
gum spin --spinner pulse --title "正在停止 CLIProxyAPI..." -- \
bash -c "systemctl --user stop cliproxyapi.service 2>/dev/null; sleep 2"
fi
fi
local _pat; _pat=$(is_macos && echo "cliproxyapi" || echo "cli-proxy-api")
local pids; pids=$(pgrep -f "$_pat" 2>/dev/null || true)
if [[ -n "$pids" ]]; then
echo "$pids" | xargs kill 2>/dev/null || true
sleep 2
pids=$(pgrep -f "$_pat" 2>/dev/null || true)
[[ -n "$pids" ]] && echo "$pids" | xargs kill -9 2>/dev/null || true
fi
if ! _cliproxy_running; then
ui_ok "CLIProxyAPI 已停止"
else
ui_err "停止失败,仍有进程残留"
fi
}
_cliproxy_oauth_login() {
local cliproxy_bin; cliproxy_bin=$(_cliproxy_bin)
if ! command -v "$cliproxy_bin" &>/dev/null && [[ ! -x "$cliproxy_bin" ]]; then
ui_err "CLIProxyAPI 未安装:$cliproxy_bin"
return 1
fi
local provider_choice
provider_choice=$(gum choose --cursor "❯ " \
--header $' 选择要登录的 AI 提供商\n ↑↓ 移动 · Enter 确认 · q 取消' \
"Claude (Anthropic)" \
"Gemini (Google)" \
"OpenAI / Codex" \
"Qwen (通义千问)" \
"iFlow" \
"取消") || return 0
local login_cmd="" login_port=""
case "$provider_choice" in
"Claude (Anthropic)") login_cmd="--claude-login"; login_port="54545" ;;
"Gemini (Google)") login_cmd="--login"; login_port="8085" ;;
"OpenAI / Codex") login_cmd="--codex-login"; login_port="1455" ;;
"Qwen (通义千问)") login_cmd="--qwen-login"; login_port="" ;;
"iFlow") login_cmd="--iflow-login"; login_port="11451" ;;
"取消"|*) return 0 ;;
esac
echo
local cliproxy_dir; cliproxy_dir=$(_cliproxy_dir)
local mode_input="" proj_input=""
if [[ "$login_cmd" == "--login" ]]; then
local mode_choice
mode_choice=$(gum choose --cursor "❯ " \
--header $' 选择 Gemini 登录模式\n ↑↓ 移动 · Enter 确认(默认:Google One)' \
"Google One(个人账号,自动发现项目)" \
"Code Assist(GCP 项目,手动选择)") || return 0
[[ "$mode_choice" == "Code Assist"* ]] && mode_input="1" || mode_input="2"
if [[ "$mode_input" == "1" ]]; then
echo
local proj_list proj_choice proj_num="1"
if command -v gcloud &>/dev/null; then
proj_list=$(gcloud projects list --format="value(projectId,name)" 2>/dev/null)
fi
if [[ -n "$proj_list" ]]; then
proj_choice=$(printf "%s\n" "$proj_list" | \
gum choose --cursor "❯ " \
--header $' 选择 GCP 项目\n ↑↓ 移动 · Enter 确认') || return 0
proj_num=$(printf "%s\n" "$proj_list" | \
awk -v sel="$proj_choice" 'NR==sel_line || $0==sel {print NR; exit}' \
sel="$proj_choice" 2>/dev/null || echo "1")
[[ -z "$proj_num" || "$proj_num" == "0" ]] && proj_num="1"
else
local proj_raw
proj_raw=$(gum input \
--placeholder "项目编号或直接按 Enter 使用默认(1)" \
--prompt " ❯ " --width 60) || return 0
proj_num="${proj_raw:-1}"
fi
proj_input="$proj_num"
fi
fi
if [[ -n "$login_port" ]]; then
if is_macos; then
gum style \
--border rounded --border-foreground 51 \
--foreground 51 --bold --padding "0 2" \
"◈ 本地浏览器登录流程"
echo
gum style --bold --foreground 240 \
" 浏览器将自动打开,完成授权后自动返回,请稍候..."
echo
if [[ -n "$mode_input" ]]; then
printf "%s\n%s\n" "$mode_input" "$proj_input" | "$cliproxy_bin" "$login_cmd"
else
"$cliproxy_bin" "$login_cmd"
fi