forked from justlovemaki/openclaw-china-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.sh
More file actions
1642 lines (1387 loc) · 65.1 KB
/
init.sh
File metadata and controls
1642 lines (1387 loc) · 65.1 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
# =============================================================================
# OpenClaw Docker 容器初始化脚本
# =============================================================================
# 功能说明:
# 1. 检查和修复挂载目录权限
# 2. 创建基础配置文件
# 3. 根据环境变量同步配置(AI 模型、IM 渠道、插件等)
# 4. 启动 OpenClaw Gateway 服务
#
# 运行用户:root(自动降权为 node 用户运行网关)
# =============================================================================
set -e # 遇到错误立即退出
# -----------------------------------------------------------------------------
# 全局变量定义
# -----------------------------------------------------------------------------
OPENCLAW_HOME="/home/node/.openclaw" # OpenClaw 主目录(配置和数据存储)
OPENCLAW_WORKSPACE="${WORKSPACE:-/home/node/.openclaw/workspace}" # 工作空间目录(可通过 WORKSPACE 环境变量覆盖)
NODE_UID="$(id -u node)" # node 用户的 UID
NODE_GID="$(id -g node)" # node 用户的 GID
GATEWAY_PID="" # 用于存储 Gateway 进程 ID
# -----------------------------------------------------------------------------
# 日志输出函数:打印带分隔符的标题
# 参数:$1 - 标题内容
# -----------------------------------------------------------------------------
log_section() {
echo "=== $1 ==="
}
# -----------------------------------------------------------------------------
# 目录创建函数:确保必要的目录存在
# 创建 OpenClaw 主目录和工作空间目录
# -----------------------------------------------------------------------------
ensure_directories() {
mkdir -p "$OPENCLAW_HOME" "$OPENCLAW_WORKSPACE"
}
# -----------------------------------------------------------------------------
# 权限检查函数:判断当前是否以 root 用户运行
# 返回值:0 - 是 root;1 - 不是 root
# -----------------------------------------------------------------------------
is_root() {
[ "$(id -u)" -eq 0 ]
}
# -----------------------------------------------------------------------------
# 权限修复函数:检测并修复挂载目录的所有者权限
# 使用场景:当宿主机挂载目录的所有者与容器内 node 用户不一致时
# 修复步骤:
# 1. 检测当前目录所有者
# 2. 尝试自动修改为 node 用户所有
# 3. 验证写入权限
# 4. 如果失败,提供详细的解决建议
# -----------------------------------------------------------------------------
fix_permissions_if_needed() {
# 非 root 用户运行时跳过修复
if ! is_root; then
return
fi
local current_owner
# 获取挂载目录当前的所有者 (UID:GID)
current_owner="$(stat -c '%u:%g' "$OPENCLAW_HOME" 2>/dev/null || echo unknown:unknown)"
echo "挂载目录:$OPENCLAW_HOME"
echo "当前所有者 (UID:GID): $current_owner"
echo "目标所有者 (UID:GID): ${NODE_UID}:${NODE_GID}"
# 如果所有者不一致,尝试修复
if [ "$current_owner" != "${NODE_UID}:${NODE_GID}" ]; then
echo "检测到宿主机挂载目录所有者与容器运行用户不一致,尝试自动修复..."
chown -R node:node "$OPENCLAW_HOME" || true
fi
# 验证 node 用户是否有写入权限
if ! gosu node test -w "$OPENCLAW_HOME"; then
echo "❌ 权限检查失败:node 用户无法写入 $OPENCLAW_HOME"
echo "请在宿主机执行(Linux):"
echo " sudo chown -R ${NODE_UID}:${NODE_GID} <your-openclaw-data-dir>"
echo "或在启动时显式指定用户:"
echo " docker run --user \$(id -u):\$(id -g) ..."
echo "若宿主机启用了 SELinux,请在挂载卷后添加 :z 或 :Z"
exit 1
fi
}
# -----------------------------------------------------------------------------
# 基础配置创建函数:当 openclaw.json 不存在时创建默认配置
# 包含:浏览器设置、模型配置、Agent 默认值、工具配置、内存后端等
# -----------------------------------------------------------------------------
ensure_base_config() {
local config_file="$OPENCLAW_HOME/openclaw.json"
# 如果配置文件已存在,直接返回
if [ -f "$config_file" ]; then
return
fi
echo "配置文件不存在,创建基础骨架..."
cat > "$config_file" <<'EOF'
{
"meta": { "lastTouchedVersion": "2026.2.14" }, # 元数据:最后修改版本
"update": { "checkOnStart": false }, # 启动时不自动检查更新
"browser": { # 浏览器配置(用于网页自动化)
"headless": true, # 无头模式
"noSandbox": true, # 禁用沙盒(容器环境需要)
"defaultProfile": "openclaw", # 默认浏览器配置文件
"executablePath": "/usr/bin/chromium" # Chromium 路径
},
"models": { "mode": "merge", "providers": { "default": { "models": [] } } }, # 模型提供商配置
"agents": { # Agent 默认配置
"defaults": {
"compaction": { "mode": "safeguard" }, # 对话压缩模式
"sandbox": { "mode": "off" }, # 沙盒模式(关闭)
"elevatedDefault": "full", # 默认提权级别
"maxConcurrent": 4, # 最大并发 Agent 数
"subagents": { "maxConcurrent": 8 } # 子代理最大并发
}
},
"messages": { "ackReactionScope": "group-mentions", "tts": { "edge": { "voice": "zh-CN-XiaoxiaoNeural" } } }, # 消息和 TTS 配置
"commands": { "native": "auto", "nativeSkills": "auto" }, # 原生命令和技能
"tools": { # 工具配置
"profile": "full", # 完整工具集
"sessions": { "visibility": "all" }, # 会话可见性
"fs": { "workspaceOnly": true } # 文件系统访问限制在工作空间
},
"channels": {}, # IM 渠道配置(将由 sync_config_with_env 填充)
"plugins": { "entries": {}, "installs": {} }, # 插件配置
"memory": { # 记忆后端配置
"backend": "qmd", # 使用 QMD 作为记忆后端
"qmd": {
"command": "/usr/local/bin/qmd", # QMD 命令路径
"paths": [
{
"path": "/home/node/.openclaw/workspace", # 监控的工作空间路径
"name": "workspace", # 名称
"pattern": "**/*.md" # 匹配所有 Markdown 文件
}
]
}
}
}
EOF
}
# -----------------------------------------------------------------------------
# 配置同步函数:根据环境变量生成 openclaw.json 配置
# 核心功能:
# 1. 加载现有配置(兼容含注释的 JSON)
# 2. 同步 AI 模型配置(支持多提供商)
# 3. 同步 IM 渠道配置(飞书、钉钉、QQ、企业微信等)
# 4. 同步插件配置
# 5. 同步 Gateway 配置
# 6. 验证多账号配置冲突
# 使用方式:通过 CONFIG_FILE 环境变量指定配置文件路径
# -----------------------------------------------------------------------------
sync_config_with_env() {
local config_file="$OPENCLAW_HOME/openclaw.json"
# 确保基础配置存在
ensure_base_config
echo "正在根据当前环境变量同步配置状态..."
# 使用 Python 脚本处理复杂的 JSON 操作(深度合并、多账号管理等)
CONFIG_FILE="$config_file" python3 - <<'PYCODE'
# =============================================================================
# Python 配置处理脚本开始
# =============================================================================
# 导入必要的模块
import json
import os
import re
import sys
from copy import deepcopy
from datetime import datetime
# -----------------------------------------------------------------------------
# 常量定义:账号 ID 验证正则表达式和各平台字段集合
# -----------------------------------------------------------------------------
WECOM_ACCOUNT_ID_RE = re.compile(r'^[a-z0-9_-]+$') # 企业微信账号 ID 格式:仅小写字母、数字、下划线、中划线
# 飞书账号配置字段(用于判断哪些字段属于账号级别配置)
FEISHU_ACCOUNT_FIELDS = {
'appId', 'appSecret', 'botName', 'dmPolicy', 'allowFrom', 'groupPolicy',
'groupAllowFrom', 'domain', 'replyMode', 'threadSession', 'groups',
'footer', 'streaming', 'requireMention'
}
# 飞书保留字段(顶层字段,不属于特定账号)
FEISHU_RESERVED_FIELDS = {
'enabled', 'appId', 'appSecret', 'botName', 'dmPolicy', 'allowFrom', 'groupPolicy',
'groupAllowFrom', 'streaming', 'footer', 'requireMention', 'threadSession',
'replyMode', 'defaultAccount', 'accounts', 'groups'
}
# 企业微信账号配置字段
WECOM_ACCOUNT_FIELDS = {
'botId', 'secret', 'dmPolicy', 'allowFrom', 'groupPolicy', 'groupAllowFrom',
'welcomeMessage', 'sendThinkingMessage', 'agent', 'webhooks', 'network',
'groupChat', 'dm', 'workspaceTemplate'
}
# 企业微信保留字段
WECOM_RESERVED_FIELDS = {'enabled', 'defaultAccount', 'adminUsers', 'commands', 'dynamicAgents'}
# QQ 机器人账号配置字段
QQBOT_ACCOUNT_FIELDS = {'appId', 'clientSecret', 'enabled'}
# QQ 机器人保留字段
QQBOT_RESERVED_FIELDS = {'enabled', 'appId', 'clientSecret', 'dmPolicy', 'allowFrom', 'groupPolicy', 'accounts'}
# -----------------------------------------------------------------------------
# 各 IM 渠道插件的安装信息定义
# source: 安装来源 (npm/git/path)
# spec: 包名或 Git 地址
# installPath: 安装路径
# -----------------------------------------------------------------------------
CHANNEL_INSTALLS = {
'feishu': {'source': 'npm', 'spec': '@openclaw/feishu', 'installPath': '/home/node/.openclaw/extensions/feishu'}, # 飞书官方插件
'dingtalk': {'source': 'npm', 'spec': 'https://github.com/soimy/clawdbot-channel-dingtalk.git', 'installPath': '/home/node/.openclaw/extensions/dingtalk'}, # 钉钉插件
'qqbot': {'source': 'path', 'sourcePath': '/home/node/.openclaw/qqbot', 'installPath': '/home/node/.openclaw/extensions/qqbot'}, # QQ 机器人(本地路径)
'napcat': {'source': 'path', 'sourcePath': '/home/node/.openclaw/extensions/napcat', 'installPath': '/home/node/.openclaw/extensions/napcat'}, # NapCat(本地路径)
'wecom': {'source': 'npm', 'spec': '@sunnoy/wecom', 'installPath': '/home/node/.openclaw/extensions/wecom'}, # 企业微信插件
}
def strip_json_comments_and_trailing_commas(raw):
raw = re.sub(r'/\*.*?\*/', '', raw, flags=re.S)
raw = re.sub(r'(^|\s)//.*?$', '', raw, flags=re.M)
raw = re.sub(r'(^|\s)#.*?$', '', raw, flags=re.M)
raw = re.sub(r',(?=\s*[}\]])', '', raw)
return raw
def load_config_with_compat(path):
with open(path, 'r', encoding='utf-8') as f:
raw = f.read()
try:
return json.loads(raw)
except json.JSONDecodeError as original_error:
sanitized = strip_json_comments_and_trailing_commas(raw)
try:
config = json.loads(sanitized)
print('⚠️ 检测到 openclaw.json 含注释或尾随逗号,已按兼容模式自动解析并在保存时标准化为合法 JSON')
return config
except json.JSONDecodeError:
raise ValueError(f'openclaw.json 格式非法: {original_error}')
def ensure_path(cfg, keys):
curr = cfg
for key in keys:
if key not in curr or not isinstance(curr.get(key), dict):
curr[key] = {}
curr = curr[key]
return curr
def deep_merge(dst, src):
if not isinstance(dst, dict) or not isinstance(src, dict):
return src
for key, value in src.items():
if isinstance(value, dict) and isinstance(dst.get(key), dict):
dst[key] = deep_merge(dst[key], value)
else:
dst[key] = value
return dst
def parse_bool(value, default=False):
if value is None:
return default
if isinstance(value, bool):
return value
return str(value).strip().lower() in ('1', 'true', 'yes', 'on')
def parse_csv(value):
if value is None:
return []
if isinstance(value, list):
return value
return [item.strip() for item in str(value).split(',') if item.strip()]
def parse_json_object(raw, env_name):
raw = (raw or '').strip()
if not raw:
return None
try:
parsed = json.loads(raw)
except Exception as ex:
raise ValueError(f'{env_name} 不是合法 JSON: {ex}')
if not isinstance(parsed, dict):
raise ValueError(f'{env_name} 必须是 JSON 对象')
return parsed
def utc_now_iso():
return datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
def first_csv_item(raw, default=''):
values = parse_csv(raw)
return values[0] if values else default
def normalize_model_ref(raw, provider_names=None, default_provider='default'):
"""归一化模型引用,确保包含 provider 前缀。
规则:
1. 不含 / 时,补成 default/<model_id>
2. 含 / 且首段是已知 provider 名称时,视为完整 provider/model 引用,原样返回
3. 含 / 但首段不是已知 provider 名称时,视为 default provider 下的模型 ID,补成 default/<raw>
"""
val = str(raw or '').strip()
if not val:
return ''
provider_names = set(provider_names or [])
provider_names.add(default_provider)
if '/' not in val:
return f'{default_provider}/{val}'
provider_prefix = val.split('/', 1)[0].strip()
if provider_prefix in provider_names:
return val
return f'{default_provider}/{val}'
def resolve_primary_model(env, default_model_id, provider_names=None):
"""
解析主模型:
1. 优先使用 PRIMARY_MODEL。
2. 留空时,使用默认模型。
3. 归一化时仅当首段是已知 provider 名称时,才视为 provider/model;否则补 default/。
"""
raw = str(env.get('PRIMARY_MODEL') or '').strip()
if raw:
return normalize_model_ref(raw, provider_names=provider_names)
return normalize_model_ref(default_model_id, provider_names=provider_names)
def resolve_image_model(env, default_model_id, provider_names=None):
"""
解析图片模型:
1. 优先使用 IMAGE_MODEL_ID。
2. 留空时,回退到默认模型。
3. 归一化规则与主模型一致。
"""
raw = str(env.get('IMAGE_MODEL_ID') or '').strip()
if raw:
return normalize_model_ref(raw, provider_names=provider_names)
return normalize_model_ref(default_model_id, provider_names=provider_names)
def collect_extra_model_providers(env, start=2, end=6):
providers = []
for index in range(start, end + 1):
prefix = f'MODEL{index}'
raw_name = str(env.get(f'{prefix}_NAME') or '').strip()
provider_name = raw_name or f'model{index}'
model_ids = str(env.get(f'{prefix}_MODEL_ID') or '').strip()
base_url = str(env.get(f'{prefix}_BASE_URL') or '').strip()
api_key = str(env.get(f'{prefix}_API_KEY') or '').strip()
protocol = str(env.get(f'{prefix}_PROTOCOL') or '').strip()
context_window = str(env.get(f'{prefix}_CONTEXT_WINDOW') or '').strip()
max_tokens = str(env.get(f'{prefix}_MAX_TOKENS') or '').strip()
has_any = any([raw_name, model_ids, base_url, api_key, protocol, context_window, max_tokens])
if not has_any:
continue
providers.append({
'index': index,
'provider_name': provider_name,
'model_ids': model_ids,
'base_url': base_url,
'api_key': api_key,
'protocol': protocol,
'context_window': context_window,
'max_tokens': max_tokens,
})
return providers
def is_valid_account_id(account_id):
return WECOM_ACCOUNT_ID_RE.match(str(account_id)) is not None
def is_feishu_account_config(value):
return isinstance(value, dict) and any(key in value for key in FEISHU_ACCOUNT_FIELDS)
def is_wecom_account_config(value):
return isinstance(value, dict) and any(key in value for key in WECOM_ACCOUNT_FIELDS)
def is_qqbot_account_config(value):
return isinstance(value, dict) and any(key in value for key in QQBOT_ACCOUNT_FIELDS)
def get_feishu_accounts(feishu):
if not isinstance(feishu, dict):
return []
accounts = feishu.get('accounts')
if not isinstance(accounts, dict):
return []
result = []
for account_id, cfg in accounts.items():
if is_valid_account_id(account_id) and is_feishu_account_config(cfg):
result.append((account_id, cfg))
return result
def get_wecom_accounts(wecom):
if not isinstance(wecom, dict):
return []
accounts = []
for account_id, cfg in wecom.items():
if account_id in WECOM_RESERVED_FIELDS:
continue
if is_wecom_account_config(cfg):
accounts.append((account_id, cfg))
return accounts
def get_qqbot_accounts(qqbot):
if not isinstance(qqbot, dict):
return []
accounts = qqbot.get('accounts')
if not isinstance(accounts, dict):
return []
result = []
for account_id, cfg in accounts.items():
if is_valid_account_id(account_id) and is_qqbot_account_config(cfg):
result.append((account_id, cfg))
return result
def normalize_wecom_config(channels):
wecom = channels.get('wecom')
if not isinstance(wecom, dict):
return
normalized = {}
migrated = False
for key in WECOM_RESERVED_FIELDS:
if key in wecom:
normalized[key] = wecom[key]
for key, value in wecom.items():
if key in WECOM_RESERVED_FIELDS:
continue
if is_valid_account_id(key) and is_wecom_account_config(value):
normalized[key] = value
continue
if key in WECOM_ACCOUNT_FIELDS:
default_account_id = str(wecom.get('defaultAccount') or 'default').strip() or 'default'
default_cfg = normalized.get(default_account_id)
if not isinstance(default_cfg, dict):
default_cfg = {}
default_cfg.setdefault(key, value)
normalized[default_account_id] = default_cfg
migrated = True
if normalized and normalized != wecom:
channels['wecom'] = normalized
migrated = True
if migrated:
print('✅ 企业微信配置已标准化为当前多账号结构')
def normalize_qqbot_config(channels):
qqbot = channels.get('qqbot')
if not isinstance(qqbot, dict):
return
migrated = False
accounts = qqbot.get('accounts')
if not isinstance(accounts, dict):
accounts = {}
legacy_account = {key: qqbot[key] for key in ('appId', 'clientSecret') if key in qqbot}
if legacy_account:
default_cfg = accounts.get('default', {})
if not isinstance(default_cfg, dict):
default_cfg = {}
for key, value in legacy_account.items():
default_cfg.setdefault(key, value)
if 'enabled' not in default_cfg and isinstance(qqbot.get('enabled'), bool):
default_cfg['enabled'] = qqbot['enabled']
accounts['default'] = default_cfg
migrated = True
main_account = accounts.pop('main', None) if 'main' in accounts else None
if isinstance(main_account, dict):
default_cfg = accounts.get('default', {})
if not isinstance(default_cfg, dict):
default_cfg = {}
for key, value in main_account.items():
default_cfg.setdefault(key, value)
accounts['default'] = default_cfg
migrated = True
normalized_accounts = {}
for account_id, cfg in accounts.items():
if is_valid_account_id(account_id) and is_qqbot_account_config(cfg):
normalized_accounts[account_id] = cfg
if normalized_accounts:
qqbot['accounts'] = normalized_accounts
default_cfg = normalized_accounts.get('default')
if isinstance(default_cfg, dict):
if default_cfg.get('appId'):
qqbot['appId'] = default_cfg['appId']
if default_cfg.get('clientSecret'):
qqbot['clientSecret'] = default_cfg['clientSecret']
migrated = migrated or qqbot.get('accounts') != accounts
if migrated:
print('✅ QQ 机器人配置已标准化为多 Bot 结构')
def normalize_feishu_config(channels):
feishu = channels.get('feishu')
if not isinstance(feishu, dict):
return
migrated = False
accounts = feishu.get('accounts')
if not isinstance(accounts, dict):
accounts = {}
legacy_account = {key: feishu[key] for key in FEISHU_ACCOUNT_FIELDS if key in feishu}
if legacy_account:
default_account = accounts.get('default', {})
if not isinstance(default_account, dict):
default_account = {}
for key, value in legacy_account.items():
default_account.setdefault(key, value)
if 'botName' not in default_account:
default_account['botName'] = feishu.get('botName', 'OpenClaw Bot')
accounts['default'] = default_account
migrated = True
main_account = accounts.pop('main', None) if 'main' in accounts else None
if isinstance(main_account, dict):
default_account = accounts.get('default', {})
if not isinstance(default_account, dict):
default_account = {}
for key, value in main_account.items():
default_account.setdefault(key, value)
accounts['default'] = default_account
migrated = True
normalized_accounts = {}
for account_id, cfg in accounts.items():
if is_valid_account_id(account_id) and is_feishu_account_config(cfg):
normalized_accounts[account_id] = cfg
if normalized_accounts:
feishu['accounts'] = normalized_accounts
default_account_id = str(feishu.get('defaultAccount') or 'default').strip() or 'default'
if default_account_id not in normalized_accounts and 'default' in normalized_accounts:
default_account_id = 'default'
feishu['defaultAccount'] = default_account_id
default_account = normalized_accounts.get(default_account_id) or normalized_accounts.get('default')
if isinstance(default_account, dict):
if default_account.get('appId'):
feishu['appId'] = default_account['appId']
if default_account.get('appSecret'):
feishu['appSecret'] = default_account['appSecret']
if default_account.get('botName'):
feishu['botName'] = default_account['botName']
migrated = migrated or feishu.get('accounts') != accounts
if migrated:
print('✅ 飞书配置已标准化为多账号结构')
def migrate_feishu_config(channels_root):
feishu = channels_root.get('feishu', {})
if 'appId' in feishu and 'accounts' not in feishu:
print('检测到飞书旧版格式,执行迁移...')
feishu['accounts'] = {
'default': {
'appId': feishu.get('appId', ''),
'appSecret': feishu.get('appSecret', ''),
'botName': feishu.get('botName', 'OpenClaw Bot'),
}
}
accounts = feishu.get('accounts')
if isinstance(accounts, dict) and 'main' in accounts:
print('检测到飞书 accounts.main,迁移为 accounts.default...')
main_account = accounts.pop('main')
default_account = accounts.get('default')
if not isinstance(default_account, dict):
accounts['default'] = main_account if isinstance(main_account, dict) else {}
elif isinstance(main_account, dict):
for key, value in main_account.items():
default_account.setdefault(key, value)
default_account = accounts.get('default') if isinstance(accounts, dict) else None
if isinstance(default_account, dict):
if default_account.get('appId'):
feishu['appId'] = default_account['appId']
if default_account.get('appSecret'):
feishu['appSecret'] = default_account['appSecret']
normalize_feishu_config(channels_root)
def merge_wecom_accounts_from_env(channels, env):
raw = (env.get('WECOM_ACCOUNTS_JSON') or '').strip()
if not raw:
return False
try:
parsed = json.loads(raw)
except Exception as ex:
raise ValueError(f'WECOM_ACCOUNTS_JSON 不是合法 JSON: {ex}')
if not isinstance(parsed, dict):
raise ValueError('WECOM_ACCOUNTS_JSON 必须是对象,格式为 {"open": {...}, "support": {...}}')
if 'accounts' in parsed and isinstance(parsed.get('accounts'), dict):
parsed = parsed['accounts']
elif 'wecom' in parsed and isinstance(parsed.get('wecom'), dict):
parsed = {
key: value
for key, value in parsed['wecom'].items()
if key not in WECOM_RESERVED_FIELDS and is_valid_account_id(key)
}
wecom = channels.get('wecom')
if not isinstance(wecom, dict):
wecom = {}
channels['wecom'] = wecom
changed = False
for account_id, account_cfg in parsed.items():
if not is_valid_account_id(account_id):
raise ValueError(f'WECOM_ACCOUNTS_JSON 账号 ID 不合法: {account_id},仅支持小写字母、数字、-、_')
if not isinstance(account_cfg, dict) or not is_wecom_account_config(account_cfg):
raise ValueError(f'WECOM_ACCOUNTS_JSON 账号配置非法: {account_id},至少包含 botId/secret/agent/webhooks/dmPolicy 中的一项')
old_cfg = wecom.get(account_id)
if not isinstance(old_cfg, dict):
old_cfg = {}
wecom[account_id] = deep_merge(old_cfg, account_cfg)
changed = True
if changed:
wecom['enabled'] = True
print('✅ 已从企业微信多账号环境变量同步配置')
return changed
def merge_feishu_accounts_from_env(channels, env):
raw = (env.get('FEISHU_ACCOUNTS_JSON') or '').strip()
if not raw:
return False
try:
parsed = json.loads(raw)
except Exception as ex:
raise ValueError(f'FEISHU_ACCOUNTS_JSON 不是合法 JSON: {ex}')
if not isinstance(parsed, dict):
raise ValueError('FEISHU_ACCOUNTS_JSON 必须是对象,格式为 {"default": {...}, "work": {...}}')
if 'accounts' in parsed and isinstance(parsed.get('accounts'), dict):
parsed = parsed['accounts']
elif 'feishu' in parsed and isinstance(parsed.get('feishu'), dict):
feishu_payload = parsed['feishu']
if 'accounts' in feishu_payload and isinstance(feishu_payload.get('accounts'), dict):
parsed = feishu_payload['accounts']
else:
parsed = {key: value for key, value in feishu_payload.items() if key not in FEISHU_RESERVED_FIELDS}
feishu = channels.get('feishu')
if not isinstance(feishu, dict):
feishu = {}
channels['feishu'] = feishu
accounts = feishu.get('accounts')
if not isinstance(accounts, dict):
accounts = {}
feishu['accounts'] = accounts
changed = False
for account_id, account_cfg in parsed.items():
if not is_valid_account_id(account_id):
raise ValueError(f'FEISHU_ACCOUNTS_JSON 账号 ID 不合法: {account_id},仅支持小写字母、数字、-、_')
if not isinstance(account_cfg, dict) or not is_feishu_account_config(account_cfg):
raise ValueError(f'FEISHU_ACCOUNTS_JSON 账号配置非法: {account_id},至少包含 appId/appSecret/botName/dmPolicy/groupPolicy 中的一项')
old_cfg = accounts.get(account_id)
if not isinstance(old_cfg, dict):
old_cfg = {}
accounts[account_id] = deep_merge(old_cfg, account_cfg)
changed = True
if changed:
feishu['enabled'] = True
default_account_id = str(feishu.get('defaultAccount') or env.get('FEISHU_DEFAULT_ACCOUNT') or 'default').strip() or 'default'
if default_account_id not in accounts and 'default' in accounts:
default_account_id = 'default'
feishu['defaultAccount'] = default_account_id
default_cfg = accounts.get(default_account_id) or accounts.get('default')
if isinstance(default_cfg, dict):
if default_cfg.get('appId'):
feishu['appId'] = default_cfg['appId']
if default_cfg.get('appSecret'):
feishu['appSecret'] = default_cfg['appSecret']
if default_cfg.get('botName'):
feishu['botName'] = default_cfg['botName']
print('✅ 已从飞书多账号环境变量同步配置')
return changed
def merge_qqbot_bots_from_env(channels, env):
raw = (env.get('QQBOT_BOTS_JSON') or '').strip()
if not raw:
return False
try:
parsed = json.loads(raw)
except Exception as ex:
raise ValueError(f'QQBOT_BOTS_JSON 不是合法 JSON: {ex}')
if not isinstance(parsed, dict):
raise ValueError('QQBOT_BOTS_JSON 必须是对象,格式为 {"bot1": {...}, "bot2": {...}}')
if 'accounts' in parsed and isinstance(parsed.get('accounts'), dict):
parsed = parsed['accounts']
elif 'qqbot' in parsed and isinstance(parsed.get('qqbot'), dict):
qqbot_payload = parsed['qqbot']
if 'accounts' in qqbot_payload and isinstance(qqbot_payload.get('accounts'), dict):
parsed = qqbot_payload['accounts']
else:
parsed = {key: value for key, value in qqbot_payload.items() if key not in QQBOT_RESERVED_FIELDS}
qqbot = channels.get('qqbot')
if not isinstance(qqbot, dict):
qqbot = {}
channels['qqbot'] = qqbot
accounts = qqbot.get('accounts')
if not isinstance(accounts, dict):
accounts = {}
qqbot['accounts'] = accounts
changed = False
for account_id, account_cfg in parsed.items():
if not is_valid_account_id(account_id):
raise ValueError(f'QQBOT_BOTS_JSON 账号 ID 不合法: {account_id},仅支持小写字母、数字、-、_')
if not isinstance(account_cfg, dict) or not is_qqbot_account_config(account_cfg):
raise ValueError(f'QQBOT_BOTS_JSON 账号配置非法: {account_id},至少包含 appId/clientSecret/enabled 中的一项')
old_cfg = accounts.get(account_id)
if not isinstance(old_cfg, dict):
old_cfg = {}
accounts[account_id] = deep_merge(old_cfg, account_cfg)
changed = True
if changed:
qqbot['enabled'] = True
default_cfg = accounts.get('default')
if isinstance(default_cfg, dict):
if default_cfg.get('appId'):
qqbot['appId'] = default_cfg['appId']
if default_cfg.get('clientSecret'):
qqbot['clientSecret'] = default_cfg['clientSecret']
print('✅ 已从 QQ 机器人多 Bot 环境变量同步配置')
return changed
def validate_feishu_multi_accounts(channels):
feishu = channels.get('feishu')
if not isinstance(feishu, dict):
return
accounts = get_feishu_accounts(feishu)
if not accounts:
return
account_map = dict(accounts)
default_account = (feishu.get('defaultAccount') or '').strip() if isinstance(feishu.get('defaultAccount'), str) else ''
if default_account and default_account not in account_map:
raise ValueError(f'飞书 defaultAccount 不存在: {default_account}')
app_id_index = {}
for account_id, cfg in accounts:
if not is_valid_account_id(account_id):
raise ValueError(f'飞书账号 ID 不合法: {account_id},仅支持小写字母、数字、-、_')
app_id = str(cfg.get('appId') or '').strip()
if app_id:
app_id_index.setdefault(app_id, []).append(account_id)
duplicate_app_ids = {key: value for key, value in app_id_index.items() if len(value) > 1}
if duplicate_app_ids:
detail = '; '.join([f"{app_id}: {', '.join(ids)}" for app_id, ids in duplicate_app_ids.items()])
raise ValueError(f'飞书 App ID 冲突(可能导致消息路由错乱): {detail}')
def validate_wecom_multi_accounts(channels):
wecom = channels.get('wecom')
if not isinstance(wecom, dict):
return
accounts = get_wecom_accounts(wecom)
if not accounts:
return
account_map = dict(accounts)
default_account = (wecom.get('defaultAccount') or '').strip() if isinstance(wecom.get('defaultAccount'), str) else ''
if default_account and default_account not in account_map:
raise ValueError(f'企业微信 defaultAccount 不存在: {default_account}')
bot_id_index = {}
agent_id_index = {}
for account_id, cfg in accounts:
if not is_valid_account_id(account_id):
raise ValueError(f'企业微信账号 ID 不合法: {account_id},仅支持小写字母、数字、-、_')
bot_id = str(cfg.get('botId') or '').strip()
if bot_id:
bot_id_index.setdefault(bot_id, []).append(account_id)
agent = cfg.get('agent') if isinstance(cfg.get('agent'), dict) else None
if agent:
agent_id = agent.get('agentId')
if agent_id is not None and str(agent_id).strip() != '':
agent_id_index.setdefault(str(agent_id).strip(), []).append(account_id)
duplicate_bot_ids = {key: value for key, value in bot_id_index.items() if len(value) > 1}
if duplicate_bot_ids:
detail = '; '.join([f"{bot_id}: {', '.join(ids)}" for bot_id, ids in duplicate_bot_ids.items()])
raise ValueError(f'企业微信 botId 冲突(可能导致消息路由错乱): {detail}')
duplicate_agent_ids = {key: value for key, value in agent_id_index.items() if len(value) > 1}
if duplicate_agent_ids:
detail = '; '.join([f"{agent_id}: {', '.join(ids)}" for agent_id, ids in duplicate_agent_ids.items()])
raise ValueError(f'企业微信 Agent ID 冲突(可能导致消息路由错乱): {detail}')
def validate_qqbot_multi_accounts(channels):
qqbot = channels.get('qqbot')
if not isinstance(qqbot, dict):
return
accounts = get_qqbot_accounts(qqbot)
if not accounts:
return
app_id_index = {}
for account_id, cfg in accounts:
if not is_valid_account_id(account_id):
raise ValueError(f'QQ 机器人账号 ID 不合法: {account_id},仅支持小写字母、数字、-、_')
app_id = str(cfg.get('appId') or '').strip()
if app_id:
app_id_index.setdefault(app_id, []).append(account_id)
duplicate_app_ids = {key: value for key, value in app_id_index.items() if len(value) > 1}
if duplicate_app_ids:
detail = '; '.join([f"{app_id}: {', '.join(ids)}" for app_id, ids in duplicate_app_ids.items()])
raise ValueError(f'QQ 机器人 AppID 冲突(可能导致消息路由错乱): {detail}')
class SyncContext:
def __init__(self, config, env):
self.config = config
self.env = env
self.channels = ensure_path(config, ['channels'])
self.plugins = ensure_path(config, ['plugins'])
self.entries = ensure_path(self.plugins, ['entries'])
self.installs = ensure_path(self.plugins, ['installs'])
self.default_dm_policy = env.get('DM_POLICY') or 'open'
self.default_allow_from = parse_csv(env.get('ALLOW_FROM')) or ['*']
self.default_group_policy = env.get('GROUP_POLICY') or 'open'
self.multi_account_channels = {'feishu', 'wecom', 'qqbot'}
self.has_feishu_single_env = bool((env.get('FEISHU_APP_ID') or '').strip() and (env.get('FEISHU_APP_SECRET') or '').strip())
self.has_feishu_accounts_env = bool((env.get('FEISHU_ACCOUNTS_JSON') or '').strip())
self.has_feishu_any_env = self.has_feishu_single_env or self.has_feishu_accounts_env
self.has_wecom_single_env = bool((env.get('WECOM_BOT_ID') or '').strip() and (env.get('WECOM_SECRET') or '').strip())
self.has_wecom_accounts_env = bool((env.get('WECOM_ACCOUNTS_JSON') or '').strip())
self.has_wecom_any_env = self.has_wecom_single_env or self.has_wecom_accounts_env
self.has_qqbot_single_env = bool((env.get('QQBOT_APP_ID') or '').strip() and (env.get('QQBOT_CLIENT_SECRET') or '').strip())
self.has_qqbot_bots_env = bool((env.get('QQBOT_BOTS_JSON') or '').strip())
self.has_qqbot_any_env = self.has_qqbot_single_env or self.has_qqbot_bots_env
self.feishu_plugin_env = (env.get('FEISHU_OFFICIAL_PLUGIN_ENABLED') or '').strip().lower()
self.feishu_plugin_enabled = self.feishu_plugin_env in ('1', 'true', 'yes', 'on')
self.feishu_plugin_explicit = self.feishu_plugin_env in ('0', '1', 'false', 'true', 'no', 'yes', 'off', 'on')
def channel(self, channel_id):
return ensure_path(self.channels, [channel_id])
def entry(self, channel_id):
return ensure_path(self.entries, [channel_id])
def install(self, channel_id):
install_info = CHANNEL_INSTALLS.get(channel_id)
if install_info and channel_id not in self.installs:
payload = deepcopy(install_info)
payload['installedAt'] = utc_now_iso()
self.installs[channel_id] = payload
def enable_channel(self, channel_id, install=False):
self.entries[channel_id] = {'enabled': True}
if install:
self.install(channel_id)
def disable_channel(self, channel_id):
self.entries[channel_id] = {'enabled': False}
def is_channel_explicitly_disabled(self, channel_id):
entry = self.entries.get(channel_id)
return isinstance(entry, dict) and (entry.get('enabled') is False)
def sync_models(ctx):
sync_model = (ctx.env.get('SYNC_MODEL_CONFIG') or 'true').strip().lower()
if sync_model not in ('', 'true', '1', 'yes'):
return
def sync_provider(provider_name, api_key, base_url, protocol, model_ids_raw, context_window, max_tokens):
if not ((api_key and base_url) or model_ids_raw):
return None
provider = ensure_path(ctx.config, ['models', 'providers', provider_name])
if api_key:
provider['apiKey'] = api_key
if base_url:
provider['baseUrl'] = base_url
provider['api'] = protocol or 'openai-completions'
models = provider.get('models', [])
model_ids = parse_csv(model_ids_raw)
for model_id in model_ids:
model_obj = next((item for item in models if item.get('id') == model_id), None)
if not model_obj:
model_obj = {
'id': model_id,
'name': model_id,
'reasoning': False,
'input': ['text', 'image'],
'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0},
}
models.append(model_obj)
model_obj['contextWindow'] = int(context_window or 200000)
model_obj['maxTokens'] = int(max_tokens or 8192)
provider['models'] = models
return provider_name
primary_provider = sync_provider(
'default',
ctx.env.get('API_KEY'),
ctx.env.get('BASE_URL'),
ctx.env.get('API_PROTOCOL'),
ctx.env.get('MODEL_ID') or 'gpt-4o',
ctx.env.get('CONTEXT_WINDOW'),
ctx.env.get('MAX_TOKENS'),
)
enabled_extra_providers = []
for provider_cfg in collect_extra_model_providers(ctx.env):
synced_name = sync_provider(
provider_cfg['provider_name'],
provider_cfg['api_key'],
provider_cfg['base_url'],
provider_cfg['protocol'],
provider_cfg['model_ids'],
provider_cfg['context_window'],
provider_cfg['max_tokens'],
)
if synced_name:
enabled_extra_providers.append(synced_name)
# 提取默认模型 ID (MODEL_ID 的第一个)
default_model_id = first_csv_item(ctx.env.get('MODEL_ID') or 'gpt-4o', 'gpt-4o')
primary_model_raw = str(ctx.env.get('PRIMARY_MODEL') or '').strip()
image_model_raw = str(ctx.env.get('IMAGE_MODEL_ID') or '').strip()
provider_names = set(ensure_path(ctx.config, ['models', 'providers']).keys())
# 解析最终的主模型与图片模型引用
primary_model = resolve_primary_model(ctx.env, default_model_id, provider_names=provider_names)
primary_image_model = resolve_image_model(ctx.env, default_model_id, provider_names=provider_names)
ensure_path(ctx.config, ['agents', 'defaults', 'model'])['primary'] = primary_model
ensure_path(ctx.config, ['agents', 'defaults', 'imageModel'])['primary'] = primary_image_model
workspace = ctx.env.get('WORKSPACE') or '/home/node/.openclaw/workspace'
ctx.config['agents']['defaults']['workspace'] = workspace