-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoc
More file actions
executable file
·1917 lines (1739 loc) · 66.8 KB
/
Copy pathoc
File metadata and controls
executable file
·1917 lines (1739 loc) · 66.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
# oc — opencode (LeXwDeX fork) version manager TUI
# 升级渠道:https://github.com/LeXwDeX/opencode/releases
# 依赖:bash, curl, tar/unzip, fzf(必需);gh(可选,无 token 走 curl)
set -euo pipefail
REPO="LeXwDeX/opencode"
RELEASES_URL="https://github.com/${REPO}/releases"
INSTALL_DIR="${OC_INSTALL_DIR:-/usr/local/bin}"
INSTALL_NAME="${OC_OPENCODE_NAME:-opencode}"
OC_VERSION="1.3.11"
# ---------- 插件管理配置 ----------
# 动态解析:OPENCODE_CONFIG_DIR 优先,其次 .jsonc > .json,最终回退默认路径
_resolve_oc_config() {
local conf_dir="${OPENCODE_CONFIG_DIR:-${HOME}/.config/opencode}"
[ -f "${conf_dir}/opencode.json" ] && echo "${conf_dir}/opencode.json" && return
if [ -f "${conf_dir}/opencode.jsonc" ]; then
warn "仅存在 opencode.jsonc;脚本会用 json.dump 写回,可能丢失 JSONC 注释"
echo "${conf_dir}/opencode.jsonc"
return
fi
echo "${conf_dir}/opencode.json"
}
OC_CONFIG_FILE=$(_resolve_oc_config)
THINK_PKG="think-mcp-tool"
DCP_PKG="@lexwdex-org/opencode-dcp"
OC_RAW_URL="https://raw.githubusercontent.com/${REPO}/stable/oc"
# ---------- 系统配置管理 ----------
AGENTS_REPO_SSH="git@github.com:LeXwDeX/opencode-agents.git"
AGENTS_REPO_HTTPS="https://github.com/LeXwDeX/opencode-agents.git"
AGENTS_DIR="${HOME}/.config/opencode/agents-repo"
AGENTS_TARGET="${HOME}/.config/opencode/agents"
SKILLS_TARGET="${HOME}/.config/opencode/skills"
OC_ENV_VARS=(
"OPENCODE_EXPERIMENTAL_SANDBOX=true"
"OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true"
"OPENCODE_EXPERIMENTAL_SCOUT=true"
)
_resolve_oc_script_dir() {
local src="${BASH_SOURCE[0]:-$0}"
while [ -L "$src" ]; do
local dir link
dir=$(cd -P "$(dirname "$src")" && pwd)
link=$(readlink "$src")
case "$link" in
/*) src="$link" ;;
*) src="$dir/$link" ;;
esac
done
cd -P "$(dirname "$src")" && pwd
}
# 本地包目录候选(按顺序尝试):
# 1) $OC_LOCAL_DIR 显式指定
# 2) oc 脚本所在目录(仓内 packages/opencode/ 直接执行场景)
# 3) ~/.cache/oc 在线下载产物缓存
# 目录里需含 VERSION 文件(BUNDLED_VERSION + SHA256_*)和对应平台压缩包
OC_SCRIPT_DIR="$(_resolve_oc_script_dir)"
LOCAL_DIR_CANDIDATES=(
"${OC_LOCAL_DIR:-}"
"$OC_SCRIPT_DIR"
"$HOME/.cache/oc"
)
C_RESET=$'\033[0m'; C_DIM=$'\033[2m'; C_BOLD=$'\033[1m'
C_GREEN=$'\033[32m'; C_YELLOW=$'\033[33m'; C_RED=$'\033[31m'; C_CYAN=$'\033[36m'
die() { printf "%s[err]%s %s\n" "$C_RED" "$C_RESET" "$*" >&2; exit 1; }
info() { printf "%s[oc]%s %s\n" "$C_CYAN" "$C_RESET" "$*"; }
warn() { printf "%s[warn]%s %s\n" "$C_YELLOW" "$C_RESET" "$*" >&2; }
ok() { printf "%s[ok]%s %s\n" "$C_GREEN" "$C_RESET" "$*"; }
# _run_with_timeout <seconds> <command...>
# 跨平台超时:优先用系统 timeout (Linux GNU coreutils / macOS brew coreutils),
# 不存在则降级为纯 bash 实现(& sleep kill)。
_run_with_timeout() {
local secs="$1"; shift
if command -v timeout >/dev/null 2>&1; then
# Linux (GNU coreutils) 或 macOS brew install coreutils (gtimeout 软链到 timeout)
timeout "$secs" "$@"
elif command -v gtimeout >/dev/null 2>&1; then
# macOS brew install coreutils 但无 PATH 别名
gtimeout "$secs" "$@"
else
# 纯 bash 降级:后台执行 + sleep + kill
"$@" &
local _tid=$!
(sleep "$secs"; kill "$_tid" 2>/dev/null) &
local _killer=$!
wait "$_tid" 2>/dev/null
local _rc=$?
kill "$_killer" 2>/dev/null || true
wait "$_killer" 2>/dev/null || true
return "$_rc"
fi
}
_version_gt() {
local a="${1#v}" b="${2#v}"
local IFS=.
local -a av bv
read -r -a av <<< "$a"
read -r -a bv <<< "$b"
local i ai bi
for i in 0 1 2; do
ai=${av[$i]:-0}
bi=${bv[$i]:-0}
ai=${ai%%[^0-9]*}
bi=${bi%%[^0-9]*}
ai=${ai:-0}
bi=${bi:-0}
if [ "$ai" -gt "$bi" ]; then return 0; fi
if [ "$ai" -lt "$bi" ]; then return 1; fi
done
return 1
}
_find_bun_cache_package() {
local bare_name="$1"
local cache_dir="${HOME}/.bun/install/cache"
[ -d "$cache_dir" ] || return 1
local pattern="${bare_name}@*"
case "$bare_name" in
*/*) pattern="$(basename "$bare_name")@*" ;;
esac
find "$cache_dir" -type d -name "$pattern" 2>/dev/null | sort | tail -1
}
need() { command -v "$1" >/dev/null 2>&1 || die "缺少依赖:$1"; }
need curl
need fzf
# shasum 或 sha256sum 至少有一个
command -v shasum >/dev/null 2>&1 || command -v sha256sum >/dev/null 2>&1 \
|| die "缺少依赖:shasum 或 sha256sum"
# ---------- 平台检测 ----------
detect_asset() {
local os arch
os=$(uname -s); arch=$(uname -m)
case "$os" in
Linux)
case "$arch" in
x86_64|amd64) echo "opencode-linux-x64.tar.gz" ;;
*) die "不支持的 Linux 架构:$arch(fork 当前仅发布 linux-x64)" ;;
esac ;;
Darwin)
case "$arch" in
arm64|aarch64) echo "opencode-darwin-arm64.zip" ;;
*) die "不支持的 macOS 架构:$arch(fork 当前仅发布 darwin-arm64)" ;;
esac ;;
MINGW*|MSYS*|CYGWIN*) echo "opencode-windows-x64.zip" ;;
*) die "未知操作系统:$os" ;;
esac
}
# ---------- 当前版本 ----------
current_version() {
local bin
bin=$(command -v "$INSTALL_NAME" 2>/dev/null || true)
[ -z "$bin" ] && { echo "(未安装)"; return; }
# 穿透 tmux shim + wrapper,找到真实 opencode 二进制
local real="$bin"
if head -n5 "$bin" 2>/dev/null | grep -q "opencode-tmux"; then
# shim 里 exec 的是 wrapper.sh,wrapper.sh 里有 OPENCODE_REAL_BIN=
local wrapper
wrapper=$(grep -m1 'exec ' "$bin" 2>/dev/null | sed 's/exec //' | tr -d '"' | awk '{print $1}' || true)
if [ -n "$wrapper" ] && [ -f "$wrapper" ]; then
local extracted
extracted=$(printf '%s\n' "$wrapper" | grep -oE 'OPENCODE_REAL_BIN="[^"]*"|OPENCODE_REAL_BIN='\''[^'\'']*'\''' | head -1 | cut -d= -f2- | tr -d '"' | tr -d "'")
[ -n "$extracted" ] && [ -x "$extracted" ] && real="$extracted"
fi
fi
"$real" --version 2>/dev/null | head -n1 || echo "(无法读取)"
}
# ---------- GitHub API ----------
gh_api() {
# 调用方式:gh_api "latest" 或 gh_api "?per_page=100"
# 自动拼接到 .../releases 后面(path 以 ? 开头时无分隔符,否则加 /)
local path="$1"
local sep="/"
[[ "$path" == \?* ]] && sep=""
local relpath="repos/${REPO}/releases${sep}${path}"
if command -v gh >/dev/null 2>&1; then
local gh_out
if gh_out=$(gh api "$relpath" 2>/dev/null); then
printf '%s' "$gh_out"
return 0
fi
fi
local hdr=()
[ -n "${GITHUB_TOKEN:-}" ] && hdr+=(-H "Authorization: Bearer $GITHUB_TOKEN")
curl -fsSL --connect-timeout 5 --max-time 20 "${hdr[@]}" -H "Accept: application/vnd.github+json" \
"https://api.github.com/${relpath}"
}
list_releases() {
# 输出 TSV:tag<TAB>name<TAB>publishedAt<TAB>prerelease
gh_api "?per_page=100" \
| python3 -c '
import json, sys
for r in json.load(sys.stdin):
tag = r.get("tag_name","")
name = r.get("name","") or tag
pub = (r.get("published_at","") or "")[:10]
pre = "pre" if r.get("prerelease") else "stable"
print(f"{tag}\t{name}\t{pub}\t{pre}")
'
}
latest_tag() {
gh_api "latest" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("tag_name",""))'
}
# ---------- 下载与校验 ----------
download_asset() {
local tag="$1" asset="$2" out="$3"
local url="${RELEASES_URL}/download/${tag}/${asset}"
info "下载 $url"
curl -fL --progress-bar -o "$out" "$url" || die "下载失败:$url"
}
try_verify_sha256() {
# 尝试拉取 SHA256SUMS / *.sha256,存在则校验,不存在跳过并 warn
local tag="$1" asset="$2" file="$3" tmpdir="$4"
local sums_url="${RELEASES_URL}/download/${tag}/SHA256SUMS"
local sums="$tmpdir/SHA256SUMS"
if curl -fsSL -o "$sums" "$sums_url" 2>/dev/null && [ -s "$sums" ]; then
local expect actual
expect=$(awk -v a="$asset" '$2==a || $2=="*"a {print $1; exit}' "$sums")
if [ -n "$expect" ]; then
actual=$(file_sha256 "$file")
[ "$expect" = "$actual" ] || die "SHA256 不匹配:期望 $expect,实际 $actual"
ok "SHA256 校验通过"
return
fi
fi
warn "上游未提供 SHA256SUMS,跳过校验(仍依赖 GitHub HTTPS 安全传输)"
}
# ---------- 本地包发现 ----------
file_sha256() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | awk '{print $1}'
else
shasum -a 256 "$1" | awk '{print $1}'
fi
}
# 当前平台对应 VERSION 里的 SHA256_* 字段名
asset_hash_key() {
case "$(detect_asset)" in
opencode-linux-x64.tar.gz) echo "SHA256_LINUX_X64" ;;
opencode-darwin-arm64.zip) echo "SHA256_DARWIN_ARM64" ;;
opencode-windows-x64.zip) echo "SHA256_WINDOWS_X64" ;;
esac
}
# 在候选目录里找一个同时具备 VERSION + 当前平台压缩包的目录;返回路径或空
find_local_dir() {
local asset key dir
asset=$(detect_asset)
for dir in "${LOCAL_DIR_CANDIDATES[@]}"; do
[ -z "$dir" ] && continue
[ -f "$dir/VERSION" ] && [ -f "$dir/$asset" ] || continue
echo "$dir"
return 0
done
return 1
}
# 从 VERSION 读 key=value(key 形如 BUNDLED_VERSION / SHA256_LINUX_X64)
read_version_field() {
local file="$1" key="$2"
[ -f "$file" ] || return 1
awk -F= -v k="$key" '$1==k {print $2; exit}' "$file" | tr -d '[:space:]'
}
# 用本地包安装;前置:local_dir 已找到,且本地包 hash 与 VERSION 自洽
install_from_local() {
local local_dir="$1" asset
asset=$(detect_asset)
local file="$local_dir/$asset"
local key actual expect
key=$(asset_hash_key)
expect=$(read_version_field "$local_dir/VERSION" "$key" || true)
actual=$(file_sha256 "$file")
if [ -n "$expect" ] && [ "$expect" != "$actual" ]; then
die "本地包 hash 与 VERSION 不一致($asset):VERSION=$expect 实际=$actual"
fi
info "使用本地包:$file"
ok "本地 SHA256 自洽"
local tmpdir; tmpdir=$(mktemp -d); trap "rm -rf '$tmpdir'" EXIT
extract_and_install "$file" "$tmpdir"
ok "安装完成:$(${INSTALL_DIR}/${INSTALL_NAME} --version 2>/dev/null || echo "(版本未知)")"
check_brew_shadow
}
extract_and_install() {
local file="$1" tmpdir="$2"
local extract_dir="$tmpdir/extract"
mkdir -p "$extract_dir"
case "$file" in
*.tar.gz) tar -xzf "$file" -C "$extract_dir" ;;
*.zip)
command -v unzip >/dev/null 2>&1 || die "需要 unzip 命令"
unzip -q "$file" -d "$extract_dir" ;;
*) die "未知压缩格式:$file" ;;
esac
local bin
bin=$(find "$extract_dir" -type f -name "opencode*" ! -name "*.zip" ! -name "*.tar.gz" \
-perm -u+x 2>/dev/null | head -n1 || true)
[ -z "$bin" ] && bin=$(find "$extract_dir" -type f -name "opencode*" 2>/dev/null | head -n1 || true)
[ -z "$bin" ] && die "解包后未找到 opencode 二进制"
local target="${INSTALL_DIR}/${INSTALL_NAME}"
info "安装到 $target"
if [ -d "$INSTALL_DIR" ] && [ -w "$INSTALL_DIR" ]; then
mkdir -p "$INSTALL_DIR"
cp -f "$bin" "$target" && chmod +x "$target"
else
sudo mkdir -p "$INSTALL_DIR"
sudo cp -f "$bin" "$target" && sudo chmod +x "$target"
fi
# macOS: 清除 quarantine 属性 + ad-hoc 重签名(否则 Gatekeeper SIGKILL)
if [ "$(uname -s)" = "Darwin" ]; then
if [ -w "$target" ]; then
xattr -cr "$target" 2>/dev/null || true
codesign -fs - "$target" 2>/dev/null || warn "ad-hoc 签名失败,可能需要 sudo codesign -fs - $target"
else
sudo xattr -cr "$target" 2>/dev/null || true
sudo codesign -fs - "$target" 2>/dev/null || warn "ad-hoc 签名失败"
fi
fi
}
# ---------- TUI ----------
# 计算居中左边距
_center_pad() {
local content_width="$1"
local term_width
term_width=$(tput cols 2>/dev/null || echo 80)
local pad=$(( (term_width - content_width) / 2 ))
[ "$pad" -lt 0 ] && pad=0
printf '%*s' "$pad" ''
}
# 装饰横线(固定宽度,居中)
_divider() {
local pad
pad=$(_center_pad 64)
echo "${pad}${C_CYAN}╭─────────────────────── ✦ ───────────────────────╮${C_RESET}"
}
_divider_bottom() {
local pad
pad=$(_center_pad 64)
echo "${pad}${C_CYAN}╰──────────────────────────────────────────────────╯${C_RESET}"
}
_panel_title() {
local title="$1" subtitle="${2:-}"
local pad
pad=$(_center_pad 64)
_divider
echo "${pad}${C_CYAN}│${C_RESET} ${C_BOLD}${title}${C_RESET}"
[ -n "$subtitle" ] && echo "${pad}${C_CYAN}│${C_RESET} ${C_DIM}${subtitle}${C_RESET}"
_divider_bottom
}
_status_row() {
local icon="$1" label="$2" value="$3" color="${4:-$C_CYAN}"
local pad
pad=$(_center_pad 64)
printf '%s %b%-2s%b %-16s %b%s%b\n' "$pad" "$color" "$icon" "$C_RESET" "$label" "$color" "$value" "$C_RESET"
}
__OC_FZF_HELP_CACHE=""
_fzf_help_cache() {
if [ -z "$__OC_FZF_HELP_CACHE" ]; then
__OC_FZF_HELP_CACHE=$(fzf --help 2>/dev/null || true)
fi
printf '%s' "$__OC_FZF_HELP_CACHE"
}
_fzf_supports() {
local opt="$1"
_fzf_help_cache | awk -v opt="$opt" '
{
pos = index($0, opt)
if (pos == 0) next
next_char = substr($0, pos + length(opt), 1)
if (next_char == "" || next_char ~ /[[:space:]=\[,]/) { found = 1; exit }
}
END { exit found ? 0 : 1 }
'
}
_fzf_supports_border_style() {
_fzf_help_cache | awk '
{
pos = index($0, "--border")
if (pos == 0) next
next_char = substr($0, pos + length("--border"), 1)
if (next_char != "" && next_char !~ /[[:space:]=\[]/) next
if ($0 ~ /--border\[[^]]*=/ || $0 ~ /--border=[^[:space:]]*STYLE/ || $0 ~ /\[[^]]*rounded[^]]*\]/) {
found = 1
exit
}
}
END { exit found ? 0 : 1 }
'
}
_fzf_run() {
local label="" prompt="" header="" preview="" height="" border="rounded" margin="" pointer="▶" marker="◆"
while [ "$#" -gt 0 ]; do
case "$1" in
--label) label="$2"; shift 2 ;;
--prompt) prompt="$2"; shift 2 ;;
--header) header="$2"; shift 2 ;;
--preview) preview="$2"; shift 2 ;;
--height) height="$2"; shift 2 ;;
--border) border="$2"; shift 2 ;;
--margin) margin="$2"; shift 2 ;;
--pointer) pointer="$2"; shift 2 ;;
--marker) marker="$2"; shift 2 ;;
*) shift ;;
esac
done
local args=()
_fzf_supports "--ansi" && args+=(--ansi)
[ -n "$height" ] && _fzf_supports "--height" && args+=("--height=$height")
[ -n "$prompt" ] && _fzf_supports "--prompt" && args+=("--prompt=$prompt")
[ -n "$pointer" ] && _fzf_supports "--pointer" && args+=("--pointer=$pointer")
[ -n "$marker" ] && _fzf_supports "--marker" && args+=("--marker=$marker")
_fzf_supports "--no-info" && args+=(--no-info)
[ -n "$header" ] && _fzf_supports "--header" && args+=("--header=$header")
if [ -n "$border" ] && _fzf_supports "--border"; then
if _fzf_supports_border_style; then
args+=(--border "$border")
else
args+=(--border)
fi
fi
[ -n "$label" ] && _fzf_supports "--border-label" && args+=("--border-label=$label")
[ -n "$label" ] && _fzf_supports "--border-label-pos" && args+=(--border-label-pos=center)
[ -n "$margin" ] && _fzf_supports "--margin" && args+=("--margin=$margin")
[ -n "$preview" ] && _fzf_supports "--preview" && args+=("--preview=$preview")
fzf "${args[@]}"
}
banner() {
local cur="$1" latest="$2" oc_ver="$3"
clear
echo
_panel_title "OPENCODE CONTROL // oc v${oc_ver}" "LeXwDeX fork release manager"
echo
_status_row "◆" "Current" "$cur" "$C_CYAN"
_status_row "▲" "Latest" "$latest" "$C_GREEN"
_status_row "●" "Channel" "$RELEASES_URL" "$C_DIM"
echo
}
choose_action() {
local latest="$1"
local options
options=$(printf '%s\n' \
"🚀 升级到最新版本 (${latest})" \
"📋 手工选择具体版本号..." \
"👁 仅查看已发布版本(不安装)" \
"🔌 插件管理 (MCP / plugin / NPM 工具)" \
"⚙️ 系统配置 (AGENTS / config / 环境变量)" \
"🔄 自更新 oc 脚本" \
"❌ 退出")
printf '%s' "$options" | _fzf_run --height "55%" --prompt "oc ▸ " \
--header " ↑/↓ navigate Enter run Esc quit " \
--border "rounded" --label " COMMANDS " --margin "1,18"
}
choose_release() {
# 输入 list_releases 输出,列出全部 release 给用户选
local picked
picked=$(list_releases | \
awk -F'\t' '{
mark = ($4=="pre") ? "[预] " : " ";
printf "%s%-30s %s %s\n", mark, $1, $3, $2
}' | \
_fzf_run --height "70%" --prompt "选择版本 > " \
--header "标 [预] 为预发布;↑/↓ 移动,Enter 确认,Esc 取消" \
--preview "echo '查看详情:${RELEASES_URL}/tag/'\$(echo {} | sed -E 's/^\[预\] +//' | awk '{print \$1}')")
[ -z "$picked" ] && return 1
# 取第一列(去掉 [预] 前缀)
echo "$picked" | sed -E 's/^\[预\] +//' | awk '{print $1}'
}
# ---------- Homebrew 遮蔽检测 ----------
check_brew_shadow() {
# 安装后检测 PATH 中实际解析到的 opencode 是否为 Homebrew 管理的版本
local resolved
resolved=$(command -v "$INSTALL_NAME" 2>/dev/null || true)
[ -z "$resolved" ] && return 0
local target="${INSTALL_DIR}/${INSTALL_NAME}"
# 如果 PATH 解析到的就是我们刚装的,没问题
[ "$resolved" = "$target" ] && return 0
# 检测是否是 Homebrew 路径
if echo "$resolved" | grep -qE '/(opt/homebrew|Cellar|Homebrew)/'; then
echo
warn "检测到 Homebrew 的 opencode 正在遮蔽 fork 版本:"
warn " PATH 解析到:$resolved (Homebrew)"
warn " fork 已装到:$target"
warn ""
warn "解决方法(任选其一):"
warn " brew unlink opencode # 取消 Homebrew 的 PATH 链接"
warn " brew uninstall opencode # 完全卸载 Homebrew 版本"
echo
fi
}
# ---------- 自更新 ----------
self_update() {
info "检查脚本更新..."
local tmp_file
tmp_file=$(mktemp)
if ! curl -fsSL --connect-timeout 5 --max-time 15 -o "$tmp_file" "$OC_RAW_URL" 2>/dev/null; then
rm -f "$tmp_file"
warn "下载失败(网络不通或超时),请检查网络连接"
return 1
fi
if ! head -1 "$tmp_file" | grep -q "^#!/usr/bin/env bash"; then
rm -f "$tmp_file"
warn "下载内容不是有效的 bash 脚本"
return 1
fi
local remote_version
remote_version=$(grep '^OC_VERSION=' "$tmp_file" | head -1 | cut -d'"' -f2)
if [ -z "$remote_version" ]; then
rm -f "$tmp_file"
warn "远程脚本缺少 OC_VERSION,可能版本过旧"
return 1
fi
info "当前版本: v${OC_VERSION}"
info "远程版本: v${remote_version}"
if [ "$OC_VERSION" = "$remote_version" ]; then
rm -f "$tmp_file"
ok "已是最新版 (v${OC_VERSION})"
return 0
fi
if _version_gt "$OC_VERSION" "$remote_version"; then
rm -f "$tmp_file"
ok "本地版本 (v${OC_VERSION}) 比远程 (v${remote_version}) 更新,无需更新"
return 0
fi
info "发现新版本: v${OC_VERSION} → v${remote_version}"
local self_path
self_path="$(_resolve_oc_script_dir)/$(basename "${BASH_SOURCE[0]}")"
if [ ! -w "$self_path" ]; then
rm -f "$tmp_file"
warn "当前脚本无写入权限: $self_path"
warn "请手动更新: sudo cp <新脚本> $self_path"
return 1
fi
local backup_path="${self_path}.bak.${OC_VERSION}"
cp "$self_path" "$backup_path"
info "已备份: $(basename "$backup_path")"
cp "$tmp_file" "$self_path"
chmod +x "$self_path"
rm -f "$tmp_file"
ok "已更新到 v${remote_version}"
return 2 # 特殊返回值:需要重启
}
# ---------- AGENTS 管理 ----------
# _agents_sync — 把仓库里的 agents (md) 和 skills 同步到 opencode 实际加载目录
# opencode 自动扫描:
# <global_config>/agent/*.md and <global_config>/agents/**/*.md
# <global_config>/skill/**/SKILL.md and <global_config>/skills/**/SKILL.md
_agents_sync() {
local src="$AGENTS_DIR"
local ok_sync=0
# agents
local agents_src=""
for d in agents agent; do
if [ -d "${src}/${d}" ]; then
agents_src="${src}/${d}"
break
fi
done
if [ -n "$agents_src" ]; then
mkdir -p "$AGENTS_TARGET"
if command -v rsync >/dev/null 2>&1; then
rsync -av --delete --quiet "$agents_src/" "$AGENTS_TARGET/" >/dev/null
else
cp -R "$agents_src/." "$AGENTS_TARGET/"
fi
ok_sync=$((ok_sync + 1))
else
warn "仓库内未找到 agent/ 或 agents/ 目录,跳过 agents 同步"
fi
# skills (SKILL.md 可能在根目录或 skills/ subdirectory)
local skills_src=""
if [ -d "${src}/skills" ]; then
skills_src="${src}/skills"
elif [ -f "${src}/SKILL.md" ]; then
skills_src="${src}"
fi
if [ -n "$skills_src" ]; then
mkdir -p "$SKILLS_TARGET"
if command -v rsync >/dev/null 2>&1; then
rsync -av --delete --quiet "$skills_src/" "$SKILLS_TARGET/" >/dev/null
else
cp -R "$skills_src/." "$SKILLS_TARGET/"
fi
ok_sync=$((ok_sync + 1))
else
warn "仓库内未找到 skills/ 目录或 SKILL.md,跳过 skills 同步"
fi
if [ "$ok_sync" -gt 0 ]; then
ok "已同步到 opencode 生效目录(agents: $AGENTS_TARGET, skills: $SKILLS_TARGET)"
fi
}
# agents_check — 检查 agents 仓库状态,输出 TSV:
# installed|<branch>|<short_hash>|<date>|<path>
# 或
# missing|||
agents_check() {
if [ -d "$AGENTS_DIR/.git" ]; then
local branch hash date
branch=$(git -C "$AGENTS_DIR" branch --show-current 2>/dev/null || echo "unknown")
hash=$(git -C "$AGENTS_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown")
date=$(git -C "$AGENTS_DIR" log -1 --format=%ci 2>/dev/null | head -c10 || echo "unknown")
echo "installed|${branch}|${hash}|${date}|${AGENTS_DIR}"
else
echo "missing|||"
fi
}
agents_install_or_update() {
need git
if [ -d "$AGENTS_DIR/.git" ]; then
info "已存在:$AGENTS_DIR,执行 git pull..."
if git -C "$AGENTS_DIR" pull --ff-only 2>&1; then
ok "AGENTS 已更新"
local hash
hash=$(git -C "$AGENTS_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown")
info "当前 commit: $hash"
_agents_sync
else
warn "git pull 失败,可能需要手动解决冲突"
fi
elif [ -e "$AGENTS_DIR" ]; then
warn "$AGENTS_DIR 已存在但不是 git 仓库"
local backup="${AGENTS_DIR}.bak.$(date +%Y%m%d%H%M%S)"
info "已备份到 $backup"
mv "$AGENTS_DIR" "$backup"
_agents_clone
else
_agents_clone
fi
}
_agents_clone() {
info "克隆 AGENTS 仓库到 $AGENTS_DIR..."
mkdir -p "$(dirname "$AGENTS_DIR")"
if git clone "$AGENTS_REPO_SSH" "$AGENTS_DIR" 2>&1; then
ok "AGENTS 已安装(SSH)"
elif git clone "$AGENTS_REPO_HTTPS" "$AGENTS_DIR" 2>&1; then
warn "SSH 克隆失败,已使用 HTTPS"
ok "AGENTS 已安装(HTTPS)"
else
die "克隆失败,请检查 SSH 密钥、HTTPS 访问或网络连接"
fi
local hash
hash=$(git -C "$AGENTS_DIR" rev-parse --short HEAD 2>/dev/null || echo "unknown")
info "当前 commit: $hash"
_agents_sync
}
# ---------- Config 管理 ----------
# _config_apply <mode> — 应用 opencode.json 配置
# mode=all: 执行 1-5 步骤(基础配置 + small_model + compaction + 模型纠错 + 体检)
# mode=models-only: 仅执行 4-5 步骤(模型纠错 + 体检)
# 逻辑:
# 1. 确保 lsp=true, autoupdate=false, default_agent="main"
# 2. small_model: 未配置时,仅从已存在的 OpenAI-compatible deepseek 模型中选择
# 3. Compaction: 未配置时,仅从已存在的 OpenAI-compatible deepseek 模型中选择
# 已有 compaction 则不覆盖
# 4. 模型属性纠错:按模板纠正已存在模型(不新增/删除/改名 model key,不碰 URL/API Key)
# 5. 模型体检:对坏类型 / 引用缺失等只 warning,不自动修改
_config_apply() {
local mode="${1:-all}"
if ! command -v python3 &>/dev/null; then
die "python3 未安装"
fi
python3 - "$OC_CONFIG_FILE" "$mode" <<'PYEOF'
import copy, json, sys
config_file = sys.argv[1]
mode = sys.argv[2] if len(sys.argv) > 2 else "all"
try:
with open(config_file, encoding="utf-8") as f:
cfg = json.load(f)
except FileNotFoundError:
print(f"[err] 配置文件不存在: {config_file}")
sys.exit(1)
except json.JSONDecodeError as e:
print(f"[err] JSON 解析失败: {e}")
sys.exit(1)
changes = []
warnings = []
providers = cfg.get("provider", {})
if not isinstance(providers, dict):
warnings.append(" ! provider: provider 配置不是 object")
providers = {}
agent_missing = "agent" not in cfg
agent_cfg = cfg.get("agent", {})
agent_bad_type = False
if not isinstance(agent_cfg, dict):
warnings.append(" ! agent: agent 配置不是 object")
agent_bad_type = True
agent_cfg = {}
if mode == "all":
# 1. 基础配置
defaults = {
"lsp": True,
"autoupdate": False,
"default_agent": "main",
}
for key, val in defaults.items():
if key not in cfg:
cfg[key] = val
changes.append(f" + {key}: {json.dumps(val)}")
elif cfg[key] != val:
old = cfg[key]
cfg[key] = val
changes.append(f" ~ {key}: {json.dumps(old)} → {json.dumps(val)}")
def find_openai_compatible_deepseek(prefer):
fallback = None
for pname, prov in providers.items():
if not isinstance(prov, dict):
continue
if prov.get("npm") != "@ai-sdk/openai-compatible":
continue
models = prov.get("models", {})
if not isinstance(models, dict):
continue
for key in prefer:
if key in models:
return pname, key
for key in models:
if "deepseek" in key:
fallback = (pname, key)
return fallback
if mode == "all":
# 2. small_model 配置:仅 key 缺失时补;key 已存在则不覆盖。
if "small_model" not in cfg:
found = find_openai_compatible_deepseek(["deepseek-v4-pro", "deepseek-v4-flash"])
if found:
cfg["small_model"] = f"{found[0]}/{found[1]}"
changes.append(f" + small_model: {cfg['small_model']}")
else:
print(" (跳过 small_model: 未找到 OpenAI-compatible deepseek model)")
else:
print(f" (small_model 已配置: {cfg.get('small_model')})")
if not isinstance(cfg.get("small_model"), str) or not cfg.get("small_model"):
warnings.append(" ! small_model: 已存在但不是有效 model string,未自动覆盖")
if mode == "all":
# 3. Compaction 配置
compaction_missing = "compaction" not in agent_cfg
compaction_cfg = agent_cfg.get("compaction", {})
compaction_bad_type = False
if not isinstance(compaction_cfg, dict):
warnings.append(" ! agent.compaction: compaction 配置不是 object")
compaction_bad_type = True
compaction_cfg = {}
compaction_model = compaction_cfg.get("model", None)
if agent_bad_type or compaction_bad_type:
print(" (跳过 compaction: agent/compaction 配置类型异常,未自动覆盖)")
elif compaction_missing:
found = find_openai_compatible_deepseek(["deepseek-v4-pro", "deepseek-v4-flash"])
if found:
compaction_model = f"{found[0]}/{found[1]}"
if agent_missing:
cfg["agent"] = {}
cfg["agent"]["compaction"] = {
"model": compaction_model,
"temperature": 0,
"variant": "disabled"
}
changes.append(f" + agent.compaction.model: {compaction_model}")
else:
print(" (跳过 compaction: 未找到 OpenAI-compatible deepseek model)")
else:
print(f" (compaction 已配置: {compaction_model})")
if not compaction_model:
warnings.append(" ! agent.compaction.model: compaction 已存在但缺少 model,未自动覆盖")
# 4. 模型属性纠错:只纠正已存在模型的内部字段(limit/cost/modalities/variants 等);
# 不新增/删除/改名 model key;不新增 provider;不触碰 URL/API Key。
# 通道范围:
# - API 原厂模式:@ai-sdk/openai、@ai-sdk/anthropic、@ai-sdk/openai-compatible
# - GitHub Copilot:provider id 以 github-copilot 开头,或 npm=@ai-sdk/github-copilot
API_NATIVE_MODEL_TEMPLATES = {
"@ai-sdk/openai": {
"gpt-5.5": {
"name": "GPT-5.5",
"reasoning": True,
"tool_call": True,
"attachment": True,
"limit": {"context": 1000000, "output": 128000},
"cost": {"input": 5, "output": 30, "cache_read": 0.5},
"modalities": {"input": ["text", "image"], "output": ["text"]},
"interleaved": {"field": "reasoning_content"},
"variants": {
"none": {"reasoningEffort": "none"},
"low": {"reasoningEffort": "low"},
"medium": {"reasoningEffort": "medium"},
"high": {"reasoningEffort": "high"},
"xhigh": {"reasoningEffort": "xhigh"},
},
},
},
"@ai-sdk/anthropic": {
# Source: D:\yc_agents_orchestration\agents_multi-orchestration\config\opencode.json
"claude-opus-4-6": {
"name": "Claude Opus 4.6",
"limit": {"context": 1000000, "output": 128000},
"cost": {"input": 5, "output": 25, "cache_read": 0.5},
"modalities": {"input": ["text", "image"], "output": ["text"]},
"variants": {
"low": {"reasoningEffort": "low"},
"medium": {"reasoningEffort": "medium"},
"high": {"reasoningEffort": "high"},
},
},
"claude-opus-4-8": {
"name": "Claude Opus 4.8",
"limit": {"context": 1000000, "output": 128000},
"cost": {"input": 5, "output": 25, "cache_read": 0.5},
"modalities": {"input": ["text", "image"], "output": ["text"]},
"variants": {
"low": {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "low"}},
"medium": {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "medium"}},
"high": {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "high"}},
"xhigh": {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "xhigh"}},
"max": {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "max"}},
},
"reasoning": False,
},
},
"@ai-sdk/openai-compatible": {
# Source: D:\yc_agents_orchestration\agents_multi-orchestration\config\opencode.json
"qwen3.7-max": {
"name": "Qwen3.7 Max",
"status": "active",
"reasoning": True,
"tool_call": True,
"attachment": True,
"temperature": False,
"limit": {"context": 1000000, "input": 936000, "output": 64000},
"cost": {"input": 12, "output": 36, "cache_read": 1.2, "cache_write": 12},
"modalities": {"input": ["text"], "output": ["text"]},
"interleaved": {"field": "reasoning_content"},
"variants": {
"enabled": {"thinking": {"type": "enabled"}},
"disabled": {"thinking": {"type": "disabled"}},
},
},
"glm-5.1": {
"name": "GLM-5.1",
"status": "active",
"reasoning": True,
"tool_call": True,
"attachment": True,
"temperature": False,
"limit": {"context": 1000000, "input": 936000, "output": 64000},
"cost": {"input": 12, "output": 36, "cache_read": 1.2, "cache_write": 12},
"modalities": {"input": ["text"], "output": ["text"]},
"interleaved": {"field": "reasoning_content"},
"variants": {
"enabled": {"thinking": {"type": "enabled"}},
"disabled": {"thinking": {"type": "disabled"}},
},
},
"deepseek-v4-pro": {
"name": "DeepSeek V4 Pro",
"status": "active",
"reasoning": True,
"tool_call": True,
"attachment": True,
"limit": {"context": 1000000, "input": 936000, "output": 64000},
"cost": {"input": 12, "output": 36, "cache_read": 1.2, "cache_write": 12},
"modalities": {"input": ["text"], "output": ["text"]},
"interleaved": {"field": "reasoning_content"},
"variants": {
"enabled": {"thinking": {"type": "enabled"}},
"disabled": {"thinking": {"type": "disabled"}},
},
},
"minimax-m3": {
"name": "MiniMax M3",
"reasoning": True,
"tool_call": True,
"attachment": True,
"limit": {"context": 1000000, "output": 128000},
"cost": {"input": 2.1, "output": 8.4, "cache_read": 0.42},
"modalities": {"input": ["text", "image"], "output": ["text"]},
"interleaved": {"field": "reasoning_content"},
},
"step-3.7-flash": {
"name": "Step 3.7 Flash",
"reasoning": True,
"tool_call": True,
"attachment": True,
"limit": {"context": 262144, "input": 262144, "output": 262144},
"cost": {"input": 1.35, "output": 8.1, "cache_read": 0.27},
"modalities": {"input": ["text", "image"], "output": ["text"]},
"interleaved": {"field": "reasoning_content"},
"options": {"reasoning_format": "deepseek-style"},
"variants": {
"low": {"reasoningEffort": "low"},
"medium": {"reasoningEffort": "medium"},
"high": {"reasoningEffort": "high"},
},
},
},
}
COPILOT_MODEL_TEMPLATES = {
"claude-opus-4.6": {
"name": "Claude Opus 4.6",
"reasoning": True,
"tool_call": True,
"attachment": True,
"limit": {"context": 264000, "input": 200000, "output": 64000},
"cost": {"input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25},
"status": "active",
"modalities": {"input": ["text", "image"], "output": ["text"]},
"variants": {
"low": {"reasoningEffort": "low"},
"medium": {"reasoningEffort": "medium"},
"high": {"reasoningEffort": "high"},
"max": {"reasoningEffort": "max"},
},
},
"claude-opus-4.8": {
"name": "Claude Opus 4.8",
"reasoning": True,
"tool_call": True,
"attachment": True,
"limit": {"context": 264000, "input": 200000, "output": 64000},
"cost": {"input": 5, "output": 25, "cache_read": 0.5, "cache_write": 6.25},
"status": "active",
"modalities": {"input": ["text", "image"], "output": ["text"]},
"variants": {
"low": {"reasoningEffort": "low"},
"medium": {"reasoningEffort": "medium"},
"high": {"reasoningEffort": "high"},
"xhigh": {"reasoningEffort": "xhigh"},
"max": {"reasoningEffort": "max"},
},
},
"gemini-3.5-flash": {
"name": "Gemini 3.5 Flash",
"reasoning": True,
"tool_call": True,
"attachment": True,