-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbridge_simple.py
More file actions
1811 lines (1502 loc) · 64.7 KB
/
bridge_simple.py
File metadata and controls
1811 lines (1502 loc) · 64.7 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 python3
"""
IMClaw 连接 Agent
职责:
1. 保持 WebSocket 连接到 IMClaw Hub
2. 收到消息 → 写入队列 → hooks/wake 唤醒主会话
3. 不处理任何逻辑,只做转发
环境变量:
- OPENCLAW_GATEWAY_URL: OpenClaw Gateway 地址(默认 http://127.0.0.1:18789)
- OPENCLAW_HOOKS_TOKEN: OpenClaw hooks token(必需,需与 openclaw.json 中配置一致)
"""
import sys
import os
# exec 工具在 shell 退出后会清理进程组,必须在重量级 import 之前脱离
if sys.platform != "win32":
try:
if not os.isatty(sys.stdin.fileno()):
os.setsid()
except (OSError, ValueError, AttributeError):
pass
import json
import time
import base64
import signal
import atexit
import logging
import threading
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
try:
import yaml
from typing import Optional
except ImportError:
yaml = None # type: ignore
# 配置 logging(线程安全,替代 print)
logging.basicConfig(
level=logging.INFO,
format='%(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)
class PIDManager:
"""PID 文件管理器 - 确保 PID 文件的准确性,防止重复启动"""
def __init__(self, pid_file: Path, process_name: str = "bridge_simple.py"):
self.pid_file = pid_file
self.process_name = process_name
self.pid = os.getpid()
self._registered = False
self._shutdown_requested = False
self._exit_signal = 0
@staticmethod
def _is_pid_alive(pid: int) -> bool:
"""检测进程是否存活(跨平台)"""
if sys.platform == "win32":
import ctypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(0x1000, 0, pid)
if handle:
kernel32.CloseHandle(handle)
return True
return False
else:
try:
os.kill(pid, 0)
return True
except (ProcessLookupError, PermissionError):
return False
def _find_other_instances(self) -> list[int]:
"""查找其他同名进程(排除自己)"""
other_pids = []
try:
import subprocess
if sys.platform == "win32":
result = subprocess.run(
["wmic", "process", "where",
f"CommandLine like '%{self.process_name}%'",
"get", "ProcessId"],
capture_output=True, text=True
)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
line = line.strip()
if line.isdigit():
pid = int(line)
if pid != self.pid:
other_pids.append(pid)
else:
result = subprocess.run(
["pgrep", "-f", self.process_name],
capture_output=True, text=True
)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
if line:
pid = int(line)
if pid != self.pid:
other_pids.append(pid)
except Exception:
pass
return other_pids
def is_running(self) -> tuple[bool, list[int]]:
"""检查是否有其他实例正在运行"""
running_pids = []
if self.pid_file.exists():
try:
old_pid = int(self.pid_file.read_text().strip())
if old_pid != self.pid and self._is_pid_alive(old_pid):
running_pids.append(old_pid)
except (ValueError, OSError):
pass
other_pids = self._find_other_instances()
for pid in other_pids:
if pid not in running_pids:
running_pids.append(pid)
return len(running_pids) > 0, running_pids
def acquire(self, force: bool = False) -> bool:
"""获取 PID 锁,写入当前进程的 PID"""
running, running_pids = self.is_running()
if running and not force:
logger.warning(f"⚠️ 已有 {len(running_pids)} 个实例运行中: {running_pids}")
if sys.platform == "win32":
logger.info(f" 请先停止旧进程: taskkill /F /PID {running_pids[0]}")
else:
logger.info(f" 请先停止旧进程: pkill -f {self.process_name}")
logger.info(f" 或使用 --force 参数强制启动")
return False
if running and force:
logger.warning(f"⚠️ 强制启动,已有实例: {running_pids}")
self.pid_file.write_text(str(self.pid))
if not self._registered:
atexit.register(self.release)
signal.signal(signal.SIGINT, self._signal_handler)
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, self._signal_handler)
self._registered = True
return True
def release(self):
"""释放 PID 锁,删除 PID 文件"""
try:
if self.pid_file.exists():
current_pid = int(self.pid_file.read_text().strip())
if current_pid == self.pid:
self.pid_file.unlink()
except Exception:
pass
def _signal_handler(self, signum, frame):
"""信号处理器 — 设置标志位 + 抛 SystemExit,让 finally 统一清理。"""
if self._shutdown_requested:
return
self._shutdown_requested = True
self._exit_signal = signum
stop_group_refresh_timer()
raise SystemExit(128 + signum)
class MessageDedup:
"""滑动窗口消息去重,防止 WebSocket 重连/网络抖动导致的重复处理"""
def __init__(self, max_size=1000):
self._seen = OrderedDict()
self._max_size = max_size
def is_duplicate(self, msg_id: str) -> bool:
if not msg_id:
return False
if msg_id in self._seen:
return True
self._seen[msg_id] = time.time()
while len(self._seen) > self._max_size:
self._seen.popitem(last=False)
return False
class TTLCache:
"""带过期时间的内存缓存,减少高频 API 调用"""
def __init__(self, ttl_seconds=60):
self._cache = {}
self._ttl = ttl_seconds
def get(self, key):
if key in self._cache:
value, expire_at = self._cache[key]
if time.time() < expire_at:
return value
del self._cache[key]
return None
def set(self, key, value):
self._cache[key] = (value, time.time() + self._ttl)
def invalidate(self, key):
self._cache.pop(key, None)
_msg_dedup = MessageDedup()
_members_cache = TTLCache(ttl_seconds=60)
_history_cache = TTLCache(ttl_seconds=10)
_tasks_cache = TTLCache(ttl_seconds=30)
# 路径设置 - 自动检测,支持多种部署方式
def get_skill_dir() -> Path:
"""自动检测 skill 目录路径"""
# 优先使用环境变量
if os.environ.get("IMCLAW_SKILL_DIR"):
return Path(os.environ["IMCLAW_SKILL_DIR"])
# 其次使用脚本所在目录(通过 scripts/ 子目录判断是否为 skill 目录)
script_dir = Path(__file__).parent.resolve()
if (script_dir / "scripts" / "imclaw_skill").is_dir():
return script_dir
# 最后使用默认路径
default_dir = Path.home() / ".openclaw" / "workspace" / "skills" / "im-skill"
return default_dir
SKILL_DIR = get_skill_dir()
ASSETS_DIR = SKILL_DIR / "assets"
QUEUE_DIR = SKILL_DIR / "imclaw_queue"
PROCESSED_DIR = SKILL_DIR / "imclaw_processed"
SESSIONS_DIR = SKILL_DIR / "sessions"
GROUP_SETTINGS_FILE = ASSETS_DIR / "group_settings.yaml"
STATUS_FILE = SKILL_DIR / "bridge_status.json"
sys.path.insert(0, str(SKILL_DIR / "scripts"))
def write_status(status: str, **extra):
"""写入 bridge_status.json,供外部脚本轮询连接状态"""
data = {"status": status, "updated_at": datetime.now().isoformat(), "pid": os.getpid()}
data.update(extra)
try:
STATUS_FILE.write_text(json.dumps(data, ensure_ascii=False))
except Exception:
pass
# 从 gateway.env 加载环境变量(bridge 作为独立进程需要自行加载)
def _load_gateway_env():
env_file = Path.home() / ".openclaw" / "gateway.env"
if not env_file.exists():
return
for line in env_file.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, _, value = line.partition("=")
os.environ.setdefault(key.strip(), value.strip())
_load_gateway_env()
# 确保队列目录存在
QUEUE_DIR.mkdir(exist_ok=True)
# ─── 群聊响应配置管理 ───
def load_group_settings() -> dict:
"""加载群聊响应配置"""
if not GROUP_SETTINGS_FILE.exists():
return {"default": {"response_mode": "smart"}, "groups": {}}
try:
import yaml
with open(GROUP_SETTINGS_FILE, 'r', encoding='utf-8') as f:
settings = yaml.safe_load(f) or {}
return {
"default": settings.get("default", {"response_mode": "smart"}),
"groups": settings.get("groups", {})
}
except Exception as e:
logger.warning(f"⚠️ 加载群聊配置失败: {e}")
return {"default": {"response_mode": "smart"}, "groups": {}}
def get_response_mode(group_id: str) -> str:
"""获取指定群聊的响应模式(silent/smart),优先读 sessions 下该群 session 文件"""
session_file = SESSIONS_DIR / f"session_{group_id}.json"
if session_file.exists():
try:
data = json.loads(session_file.read_text(encoding="utf-8"))
mode = data.get("response_mode")
if mode in ("silent", "smart"):
return mode
except Exception as e:
logger.debug(f"读取 session 响应模式失败: {e}")
settings = load_group_settings()
group_config = settings.get("groups", {}).get(group_id, {})
return group_config.get("response_mode", settings["default"].get("response_mode", "smart"))
def get_response_language() -> str:
"""获取 Agent 的回复语言(从环境变量读取)"""
from imclaw_skill import resolve_env
return resolve_env("IMCLAW_DEFAULT_LANGUAGE", "zh-CN")
def check_if_mentioned(msg: dict, my_agent_id: str) -> bool:
"""检查消息是否 @ 了当前 Agent"""
metadata = msg.get("metadata")
if not metadata:
return False
try:
if isinstance(metadata, str):
parsed = json.loads(metadata)
else:
parsed = metadata
if not isinstance(parsed, dict):
return False
mentions = parsed.get("mentions", [])
return any(m.get("id") == my_agent_id for m in mentions)
except (json.JSONDecodeError, TypeError):
return False
def get_identity_from_token() -> tuple[str, str]:
"""从环境变量中的 token 解析 Agent ID 和 Owner ID
Returns:
tuple: (agent_id, owner_id) - 如果解析失败返回 (None, None)
"""
try:
from imclaw_skill import resolve_env
token = resolve_env("IMCLAW_TOKEN")
if not token or token == 'your-agent-token-here':
return None, None
parts = token.split('.')
if len(parts) != 3:
return None, None
payload = parts[1]
payload += '=' * (4 - len(payload) % 4)
decoded = base64.urlsafe_b64decode(payload)
data = json.loads(decoded)
agent_id = data.get('sub') or data.get('agent_id')
owner_id = data.get('user_id')
return agent_id, owner_id
except Exception as e:
logger.warning(f"⚠️ 无法从 token 解析身份信息: {e}")
return None, None
# 从配置中动态获取 Agent ID 和 Owner ID
MY_AGENT_ID, MY_OWNER_ID = get_identity_from_token()
logger.info("=" * 50)
logger.info("🦞 IMClaw 连接 Agent")
logger.info("=" * 50)
logger.info(f"📁 Skill 目录: {SKILL_DIR}")
logger.info(f"📁 队列目录: {QUEUE_DIR}")
if MY_AGENT_ID:
logger.info(f"🆔 我的 Agent ID: {MY_AGENT_ID}")
else:
logger.warning("⚠️ 无法获取 Agent ID,将无法过滤自己的消息")
if MY_OWNER_ID:
logger.info(f"👤 我的 Owner ID: {MY_OWNER_ID}")
else:
logger.warning("⚠️ 无法获取 Owner ID,将无法识别主人消息")
def get_hooks_token() -> str:
"""获取 OpenClaw hooks token(优先环境变量,其次配置文件)"""
# 优先使用环境变量
token = os.environ.get("OPENCLAW_HOOKS_TOKEN", "")
if token:
return token
# 从 openclaw.json 读取
try:
openclaw_config = Path.home() / ".openclaw" / "openclaw.json"
if openclaw_config.exists():
config = json.loads(openclaw_config.read_text())
token = config.get("hooks", {}).get("token", "")
if token:
return token
except Exception as e:
logger.warning(f"⚠️ 读取 openclaw.json 失败: {e}")
return ""
# 获取 hooks token
HOOKS_TOKEN = get_hooks_token()
if not HOOKS_TOKEN:
logger.warning("⚠️ 警告: OPENCLAW_HOOKS_TOKEN 未设置")
logger.info(" 请设置环境变量或在 ~/.openclaw/openclaw.json 中配置 hooks")
else:
logger.info(f"✅ OPENCLAW_HOOKS_TOKEN: {'*' * 8}{HOOKS_TOKEN[-4:]}")
# 导入模块
try:
from imclaw_skill import IMClawSkill
from reply import archive_history_messages
logger.info("✅ 模块导入成功")
except Exception as e:
logger.error(f"❌ 模块导入失败: {e}")
sys.exit(1)
# 读取 skill 版本
def _read_skill_version() -> str:
meta_file = SKILL_DIR / "_meta.json"
if meta_file.exists():
try:
return json.loads(meta_file.read_text()).get("version", "")
except Exception:
pass
return ""
SKILL_VERSION = _read_skill_version()
_notification_file_lock = threading.Lock()
_NOTIFICATION_DEFAULT_EVENTS = [
"task_claimed",
"task_completed",
"task_blocked",
"exception",
"progress_report",
"authorization_request",
"status_change",
"mentioned",
]
def _notification_yaml_path() -> Path:
return ASSETS_DIR / "notification_settings.yaml"
def _load_openclaw_channel_names() -> list[str]:
"""扫描 ~/.openclaw/openclaw.json 的 channels 键名作为可选通知渠道。"""
try:
p = Path.home() / ".openclaw" / "openclaw.json"
if not p.exists():
return []
cfg = json.loads(p.read_text(encoding="utf-8"))
ch = cfg.get("channels")
if isinstance(ch, dict):
return sorted(ch.keys())
return []
except Exception as e:
logger.warning(f"⚠️ 读取 openclaw.json channels 失败: {e}")
return []
def _read_notification_settings() -> tuple[bool, list[str]]:
path = _notification_yaml_path()
enabled = False
events = list(_NOTIFICATION_DEFAULT_EVENTS)
if not path.exists():
return enabled, events
if yaml is None:
logger.warning("⚠️ PyYAML 未安装,无法读取 notification_settings.yaml")
return enabled, events
try:
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
if not isinstance(raw, dict):
return enabled, events
enabled = bool(raw.get("enabled", False))
ev = raw.get("events")
if isinstance(ev, list):
events = [str(x) for x in ev if x is not None]
else:
events = list(_NOTIFICATION_DEFAULT_EVENTS)
return enabled, events
except Exception as e:
logger.warning(f"⚠️ 读取通知配置失败: {e}")
return False, list(_NOTIFICATION_DEFAULT_EVENTS)
def _write_notification_settings(enabled: bool, events: list[str]) -> None:
if yaml is None:
raise RuntimeError("PyYAML is required to write notification_settings.yaml")
path = _notification_yaml_path()
data: dict = {}
if path.exists():
prev = yaml.safe_load(path.read_text(encoding="utf-8"))
if isinstance(prev, dict):
data = dict(prev)
data["enabled"] = bool(enabled)
data["events"] = list(events)
text = yaml.safe_dump(
data, allow_unicode=True, default_flow_style=False, sort_keys=False
)
path.write_text(text, encoding="utf-8")
def _read_channel_binding() -> Optional[dict]:
path = _notification_yaml_path()
if not path.exists() or yaml is None:
return None
try:
raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
binding = raw.get("channel_binding")
if isinstance(binding, dict) and binding.get("channel") and binding.get("target"):
return binding
return None
except Exception:
return None
def _on_hub_config_query(data: dict):
req_id = data.get("request_id") or ""
key = data.get("key", "")
channels = _load_openclaw_channel_names()
if key != "notification":
payload = {"enabled": False, "events": [], "available_channels": channels, "channel_binding": None}
else:
with _notification_file_lock:
en, ev = _read_notification_settings()
binding = _read_channel_binding()
payload = {"enabled": en, "events": ev, "available_channels": channels, "channel_binding": binding}
try:
skill.client.send_ws_json(
{"type": "config_response", "request_id": req_id, "payload": payload}
)
except Exception as e:
logger.warning(f"⚠️ 发送 config_response 失败: {e}")
def _on_hub_config_update(data: dict):
req_id = data.get("request_id") or ""
key = data.get("key", "")
ack: dict = {"success": False, "error": ""}
try:
if key != "notification":
ack["error"] = "unsupported key"
else:
inner = data.get("payload")
if isinstance(inner, str):
inner = json.loads(inner)
if not isinstance(inner, dict):
ack["error"] = "invalid payload"
else:
en = bool(inner.get("enabled", False))
ev = inner.get("events")
if not isinstance(ev, list):
ack["error"] = "invalid events"
else:
ev_clean = [str(x) for x in ev]
with _notification_file_lock:
_write_notification_settings(en, ev_clean)
ack["success"] = True
ack.pop("error", None)
except Exception as e:
logger.warning(f"⚠️ config_update 处理失败: {e}")
ack["success"] = False
ack["error"] = "write failed"
try:
skill.client.send_ws_json(
{"type": "config_update_ack", "request_id": req_id, "payload": ack}
)
except Exception as e:
logger.warning(f"⚠️ 发送 config_update_ack 失败: {e}")
# 加载配置
try:
skill = IMClawSkill.from_env(skill_version=SKILL_VERSION)
logger.info(f"✅ 配置加载成功")
logger.info(f" Hub: {skill.config.hub_url}")
if SKILL_VERSION:
logger.info(f" Skill 版本: v{SKILL_VERSION}")
skill.client.on("config_query", _on_hub_config_query)
skill.client.on("config_update", _on_hub_config_update)
except Exception as e:
logger.error(f"❌ 配置加载失败: {e}")
sys.exit(1)
# ─── 上下文获取函数(需要 skill 对象)───
MY_PROFILE = {} # 稀后在连接成功时从 API 获取完整信息
GROUP_NAME_CACHE = {} # 群名缓存 {group_id: group_name}
def fetch_my_profile():
"""获取当前 Agent 的完整信息(从 IMClaw Hub API)"""
global MY_PROFILE
try:
MY_PROFILE = skill.client.get_profile()
name = MY_PROFILE.get("display_name", "")
desc = MY_PROFILE.get("description", "")
logger.info(f"📛 我是: {name}")
if desc:
logger.info(f" 描述: {desc[:50]}")
except Exception as e:
logger.warning(f"⚠️ 获取个人信息失败: {e}")
MY_PROFILE = {}
def get_group_members(group_id: str) -> list[dict]:
"""获取群聊成员列表,403 时主动取消订阅"""
try:
members = skill.client._get(f"/api/v1/groups/{group_id}/members")
return members if isinstance(members, list) else []
except Exception as e:
_handle_api_error(e, group_id, "获取群成员")
return []
def get_recent_history(group_id: str, limit: int = 10) -> list[dict]:
"""获取最近的历史消息,403 时主动取消订阅"""
try:
result = skill.client.get_history(group_id, limit=limit)
messages = result.get("messages", []) if isinstance(result, dict) else result
return messages if isinstance(messages, list) else []
except Exception as e:
_handle_api_error(e, group_id, "获取历史消息")
return []
def _handle_api_error(e: Exception, group_id: str, action: str):
"""统一处理 API 错误,403 时主动取消订阅(已被移除的兜底防护)"""
import requests as _requests
if isinstance(e, _requests.exceptions.HTTPError) and e.response is not None:
if e.response.status_code == 403:
logger.warning(f"⚠️ {action}失败: 403 无权访问群 {group_id[:8]}(可能已被移除),取消订阅")
skill.unsubscribe(group_id)
return
logger.warning(f"⚠️ {action}失败: {e}")
def format_members_for_prompt(members: list[dict]) -> str:
"""格式化成员列表供 prompt 使用,显示 名字(类型/id)"""
names = []
for m in members:
name = m.get("display_name") or m.get("agent_name") or m.get("username") or m.get("id", "")[:8]
mtype = m.get("member_type") or m.get("type", "unknown")
mid = (m.get("member_id") or m.get("id") or "")
mid_short = mid[:8] if mid else "unknown"
names.append(f"{name}({mtype}/{mid_short})")
return ", ".join(names) if names else "无法获取"
def _extract_mentions(msg: dict) -> list[dict]:
"""从消息 metadata 中提取 @mention 列表,每项含 type/id/display_name"""
metadata = msg.get("metadata")
if not metadata:
return []
try:
parsed = json.loads(metadata) if isinstance(metadata, str) else metadata
if not isinstance(parsed, dict):
return []
return parsed.get("mentions", [])
except (json.JSONDecodeError, TypeError):
return []
def _format_mentions_for_prompt(mentions: list[dict]) -> str:
"""格式化 @mention 列表供 prompt 使用,用 display_name(type/id前缀) 区分重名"""
if not mentions:
return ""
parts = []
for m in mentions:
name = m.get("display_name", "?")
mtype = m.get("type", "?")
mid = m.get("id", "")[:8]
parts.append(f"@{name}({mtype}/{mid})")
return ", ".join(parts)
def _extract_attachments(msg: dict) -> list[dict]:
"""从消息 metadata 中提取附件列表"""
metadata = msg.get("metadata")
if not metadata:
return []
try:
parsed = json.loads(metadata) if isinstance(metadata, str) else metadata
if not isinstance(parsed, dict):
return []
return parsed.get("attachments", [])
except (json.JSONDecodeError, TypeError):
return []
def _format_attachments(attachments: list[dict]) -> str:
"""将附件列表格式化为可读字符串"""
if not attachments:
return ""
parts = []
for att in attachments:
filename = att.get("filename") or att.get("object_path", "").split("/")[-1] or "未知文件"
url = att.get("url") or att.get("access_url") or ""
att_type = att.get("type", "file")
size = att.get("size")
size_str = f" ({size // 1024}KB)" if size and size >= 1024 else (f" ({size}B)" if size else "")
if url:
parts.append(f"[{att_type}]{size_str} {filename} → {url}")
else:
parts.append(f"[{att_type}]{size_str} {filename}")
return " | ".join(parts)
def format_history_for_prompt(history: list[dict], limit: int = 30) -> str:
"""格式化历史消息供 prompt 使用(渐进式截断:旧消息短,新消息长)
发送者格式: name(id前缀) — 用 ID 区分重名成员
"""
if not history:
return "无历史记录"
recent = history[-limit:]
lines = []
threshold = max(len(recent) - 5, 0)
for i, msg in enumerate(recent):
sender_name = msg.get("sender_name") or ""
sender_id = msg.get("sender_id") or ""
if sender_name and sender_id:
sender = f"{sender_name}({sender_id[:8]})"
else:
sender = sender_name or sender_id[:8] or "未知"
content = msg.get("content", "")
if msg.get("type") == "system":
content = content[:80]
elif i < threshold:
content = content[:150]
else:
content = content[:500]
attachments = _extract_attachments(msg)
if attachments:
att_str = _format_attachments(attachments)
content = f"{content} 📎 {att_str}" if content and content not in ("[file]", "[image]", "[video]", "[audio]") else f"📎 {att_str}"
lines.append(f" {sender}: {content}")
return "\n".join(lines)
def get_group_tasks(group_id: str) -> list[dict]:
"""获取群聊的任务列表,403 时主动取消订阅"""
try:
tasks = skill.client.list_tasks(group_id)
return tasks if isinstance(tasks, list) else []
except Exception as e:
_handle_api_error(e, group_id, "获取任务列表")
return []
def format_tasks_for_prompt(tasks: list[dict], members: list[dict]) -> str:
"""格式化任务列表为树形结构供 prompt 使用
展示层级:主任务 → 子任务,含状态/认领者/指派者/依赖。
只展示活跃任务(open/claimed/in_progress),done/cancelled 只统计数量。
"""
if not tasks:
return "📋 暂无任务"
member_names = {}
for m in members:
mid = m.get("member_id") or m.get("id", "")
name = m.get("display_name") or m.get("agent_name") or mid[:8]
if mid:
member_names[mid] = name
def _agent_name(agent_id):
if not agent_id:
return ""
return member_names.get(agent_id, agent_id[:8])
active_statuses = {"open", "claimed", "in_progress"}
top_tasks = [t for t in tasks if not t.get("parent_task_id")]
child_map = {}
for t in tasks:
parent = t.get("parent_task_id")
if parent:
child_map.setdefault(parent, []).append(t)
status_icons = {
"open": "⬜", "claimed": "🔒", "in_progress": "🔄",
"done": "✅", "cancelled": "❌",
}
priority_tags = {1: " 🔥", 2: " 🚨"}
lines = []
done_count = sum(1 for t in tasks if t.get("status") == "done")
cancelled_count = sum(1 for t in tasks if t.get("status") == "cancelled")
active_count = sum(1 for t in tasks if t.get("status") in active_statuses)
def _format_task(t, indent=""):
s = t.get("status", "open")
icon = status_icons.get(s, "❓")
tid = t.get("id", "")[:8]
title = t.get("title", "?")
prio = priority_tags.get(t.get("priority", 0), "")
parts = [f"{indent}{icon} [{tid}] {title}{prio}"]
claimer = t.get("claimed_by_id")
assignee = t.get("assigned_to_id")
if claimer:
parts.append(f"认领: {_agent_name(claimer)}")
elif assignee:
parts.append(f"指派: {_agent_name(assignee)}")
elif s == "open":
parts.append("无人认领")
return " (".join(parts[:1]) if len(parts) == 1 else f"{parts[0]} ({', '.join(parts[1:])})"
for t in top_tasks:
s = t.get("status", "open")
if s not in active_statuses:
continue
lines.append(_format_task(t))
children = child_map.get(t.get("id"), [])
for child in children:
if child.get("status") in active_statuses:
lines.append(_format_task(child, indent=" └─ "))
summary_parts = [f"📋 {active_count} 个活跃"]
if done_count:
summary_parts.append(f"{done_count} 个已完成")
if cancelled_count:
summary_parts.append(f"{cancelled_count} 个已取消")
header = " | ".join(summary_parts)
if not lines:
return f"{header}\n(所有任务已完成或取消)"
return f"{header}\n" + "\n".join(lines)
def archive_message(msg: dict):
"""立即归档消息到 年/月/日/group_id.jsonl(所有消息都记录)"""
now = datetime.now()
day_dir = PROCESSED_DIR / now.strftime("%Y") / now.strftime("%m") / now.strftime("%d")
day_dir.mkdir(parents=True, exist_ok=True)
group_id = msg.get('group_id', 'unknown')
archive_file = day_dir / f"{group_id}.jsonl"
archive_record = msg.copy()
archive_record['_archived_at'] = now.isoformat()
with open(archive_file, 'a', encoding='utf-8') as f:
f.write(json.dumps(archive_record, ensure_ascii=False) + '\n')
logger.info(f" 📦 已归档: {archive_file.name}")
def write_to_queue(msg: dict):
"""写入消息队列(按 group_id 分目录存储)"""
group_id = msg.get('group_id', 'unknown')
group_queue_dir = QUEUE_DIR / group_id
group_queue_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
queue_file = group_queue_dir / f"{timestamp}.json"
with open(queue_file, 'w', encoding='utf-8') as f:
json.dump(msg, f, ensure_ascii=False, indent=2)
logger.info(f" 📝 已写入: {group_id[:8]}/{queue_file.name}")
def get_queue_count(group_id: str = None) -> int:
"""获取队列中待处理消息数量
Args:
group_id: 指定群聊 ID,为 None 时统计所有群聊
"""
try:
if group_id:
group_dir = QUEUE_DIR / group_id
return len(list(group_dir.glob("*.json"))) if group_dir.exists() else 0
else:
return len(list(QUEUE_DIR.glob("*/*.json")))
except:
return 0
_warm_sessions = {} # {session_key: {"last_wake": float, "count": int}}
_WARM_THRESHOLD = 3600 # 1小时内视为热 Session
_WARM_REFRESH_INTERVAL = 20 # 每 N 条消息发一次冷模板刷新上下文
if sys.platform == "win32":
_SKILL_DIR_STR = "%USERPROFILE%\\.openclaw\\workspace\\skills\\imclaw"
_VENV_PY = "venv\\Scripts\\python.exe"
_CMD_SEP = " && "
else:
_SKILL_DIR_STR = "~/.openclaw/workspace/skills/imclaw"
_VENV_PY = "venv/bin/python3"
_CMD_SEP = " && "
_PY_CMD = f"cd {_SKILL_DIR_STR}{_CMD_SEP}{_VENV_PY}"
_RULES_PATH = f"{_SKILL_DIR_STR}/references/session_rules.md"
_RULES_REF_PATH = f"{_SKILL_DIR_STR}/references/session_rules_ref.md"
def _build_auth_block(trust_level: str, msg: dict) -> str:
"""根据信任等级构建授权提示块"""
if trust_level == "T0":
return ""
group_id = msg.get('group_id', '')
sender_id = msg.get('sender_id', '')
sender_type = msg.get('sender_type', 'user')
if trust_level == "T2":
return f"""
⚠️ 信任: T2(其他人) | L0-L2 ✅ | L3/L4 🔒需授权 | L5 ❌拒绝
授权: PY reply.py --auth-request "任务描述" --risk-level L3 --requester-type {sender_type} --requester-id {sender_id} --group {group_id}
🔒 流程: 先回复"需等主人确认" → 发授权请求 → 等批准再执行
"""
if trust_level == "T1":
return "\n信任: T1(主人的龙虾) | 仅 L5 敏感操作需授权,其余 ✅\n"
return ""
def _extract_common_context(msg: dict) -> dict:
"""提取消息的通用上下文字段,供冷/热模板共用"""
ctx = msg.get('_context', {})
group_members = ctx.get('group_members', [])
mentions = _extract_mentions(msg)
mentions_str = _format_mentions_for_prompt(mentions)
other_members = [m for m in group_members
if (m.get('member_id') or m.get('id', '')) != MY_AGENT_ID]
trust_level = get_trust_level(msg)
trust_labels = {"T0": "T0(主人)", "T1": "T1(主人的龙虾)", "T2": "T2(其他人)"}
attachments = _extract_attachments(msg)
attachment_block = ""
if attachments:
att_lines = []
for att in attachments:
filename = att.get("filename") or att.get("object_path", "").split("/")[-1] or "未知文件"
url = att.get("url") or att.get("access_url") or ""
att_type = att.get("type", "file")
size = att.get("size")
size_str = f" ({size // 1024}KB)" if size and size >= 1024 else (f" ({size}B)" if size else "")
if url:
att_lines.append(f" - [{att_type}]{size_str} {filename}\n URL: {url}")
else:
att_lines.append(f" - [{att_type}]{size_str} {filename}")
attachment_block = "\n附件:\n" + "\n".join(att_lines)
notify_enabled = False
notify_events: list[str] = []
try:
with _notification_file_lock:
notify_enabled, notify_events = _read_notification_settings()
except Exception:
pass
return {
"content": msg.get('content', '')[:2000],
"sender": msg.get('sender_name', msg.get('sender_id', '未知')[:8]),
"group_name": msg.get('group_name', '群聊'),
"group_id": msg.get('group_id', ''),
"from_owner": msg.get('_from_owner', False),
"response_mode": ctx.get('response_mode', 'smart'),
"is_mentioned": ctx.get('is_mentioned', False),
"group_members": group_members,
"recent_history": ctx.get('recent_history', []),
"group_tasks": ctx.get('group_tasks', []),
"trust_level": trust_level,
"trust_display": trust_labels.get(trust_level, trust_level),
"mentions_str": mentions_str,
"mention_detail": f" → {mentions_str}" if mentions_str else "",
"is_one_on_one": len(other_members) == 1,
"attachment_block": attachment_block,
"auth_block": _build_auth_block(trust_level, msg),
"language": get_response_language(),
"notify_enabled": notify_enabled,
"notify_events": notify_events,
}
def _build_dynamic_section(msg: dict, is_cold: bool = True) -> str:
"""构建 wake_text 的动态部分
Args:
is_cold: True=冷启动完整模板, False=热Session精简模板
"""
c = _extract_common_context(msg)
if is_cold: