@mcviseron/dsh-qq-bridge 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bot/main.py ADDED
@@ -0,0 +1,4335 @@
1
+ """DSH QQ bot: the QQ face of DeepSeek Harness.
2
+
3
+ Every QQ message is forwarded to the local dsh-qq-bridge DSH plugin, which owns
4
+ one DSH Session per conversation; the agent's answer comes back through the same
5
+ channel. Tool approvals are relayed to the bot owner's private chat, and only
6
+ that owner may answer them.
7
+
8
+ The viseron_qqbotpy SDK is used read-only: nothing in this file modifies it.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import aiohttp
13
+ import argparse
14
+ import asyncio
15
+ import json
16
+ import os
17
+ import re
18
+ import shutil
19
+ import signal
20
+ import subprocess
21
+ import sys
22
+ import threading
23
+ import time
24
+ import uuid
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+ from typing import Any, Dict, List, Optional, Tuple
28
+
29
+ from viseron_qqbotpy import C2CMessage, Client, GroupMessage, Intents, Interaction
30
+ from viseron_qqbotpy import configure_logging, load_env, get_logger, load_panels
31
+
32
+ from bridge import BridgeClient, BridgeError, download_image
33
+
34
+ ROOT = Path(__file__).resolve().parent
35
+ SG_GROUP_BASE_URL = "https://api.sgroup.qq.com"
36
+ STATE_FILE = ROOT / "state.json"
37
+ CURSOR_FILE = ROOT / "state" / "cursor.txt"
38
+
39
+ # One QQ passive reply slot expires after 5 minutes, and one user message may be
40
+ # answered at most 5 times; both limits are enforced locally before the API call.
41
+ PASSIVE_WINDOW_S = 240.0
42
+ MAX_PASSIVE_PER_MESSAGE = 5
43
+
44
+ # 消息池:缓存最近 10 分钟的收发消息,供 /撤回 挑一条撤销
45
+ MSG_POOL_TTL_S = 1800.0
46
+ MSG_POOL_MAX = 100
47
+
48
+ ALLOW_WORDS = {"允许", "同意", "可以", "批准", "y", "yes", "ok", "allow", "approve"}
49
+ DENY_WORDS = {"拒绝", "不行", "不允许", "驳回", "n", "no", "deny", "reject"}
50
+ RESET_COMMANDS = {"/reset", "reset", "/新会话", "新会话", "/重置", "重置", "清空上下文", "/清空"}
51
+ HELP_COMMANDS = {"/help", "help", "/帮助", "帮助", "/dsh"}
52
+ BIND_COMMANDS = {"/绑定", "/绑定主人", "绑定主人"}
53
+ STATE_COMMANDS = {"/状态", "/status", "状态"}
54
+ LINK_COMMANDS = {"/链接", "/邀请", "/invite", "邀请链接"}
55
+ SHOT_COMMANDS = {"/截图", "/screenshot", "/shot", "截图"}
56
+ WINDOW_COMMANDS = {"/窗口", "/windows", "窗口"}
57
+ SESSION_COMMANDS = {"/会话", "/sessions", "会话", "/当前会话"}
58
+ SWITCH_COMMANDS = {"/切会话", "/切换", "/switch", "切会话"}
59
+ BACK_COMMANDS = {"/切回", "/返回", "/back", "切回"}
60
+ USAGE_COMMANDS = {"/花费", "/用量", "/token", "/usage", "/cost", "花费", "用量"}
61
+ MENU_COMMANDS = {"/菜单", "/指令", "/面板", "/menu", "/commands", "菜单", "指令"}
62
+ RECALL_COMMANDS = {"/撤回", "/recall", "撤回"}
63
+ POOL_COMMANDS = {"/消息池", "/池", "/pool", "消息池"}
64
+ URGENT_EVENTS = {"approval", "notice"}
65
+ # Commands that touch the host machine, cost accounting, or a Session binding:
66
+ # non-owners may not run them (checked inside handle_extra_command).
67
+ OWNER_ONLY_COMMANDS = (
68
+ SHOT_COMMANDS | WINDOW_COMMANDS | USAGE_COMMANDS | SESSION_COMMANDS
69
+ | SWITCH_COMMANDS | BACK_COMMANDS | STATE_COMMANDS | LINK_COMMANDS | POOL_COMMANDS
70
+ )
71
+
72
+ CAPTURE_SCRIPT = ROOT.parent / "tools" / "window-capture.ps1"
73
+ SHOT_DIR = ROOT.parent / "shots"
74
+ STICKER_DIR = ROOT.parent / "assets" / "stickers"
75
+ # 模型想发表情包时写 [[sticker: 名字]],机器人从 assets/stickers 里取图发出去
76
+ STICKER_MARK = re.compile(r"\[\[sticker\s*[::]\s*([^\]]+?)\]\]", re.IGNORECASE)
77
+ NO_REPLY_MARK = "[NO_REPLY]"
78
+ JOIN_MARK_RE = re.compile(r"\[\[\s*join\s*:\s*([0-3])\s*\]\]", re.IGNORECASE)
79
+
80
+ # 模型用这个标记把本地文件交回 QQ:[[send_file: D:\path\pic.png]]
81
+ SEND_FILE_MARK = re.compile(r"\[\[(?:send_file|send_image|发送文件|发图)\s*[::]\s*([^\]]+?)\]\]", re.IGNORECASE)
82
+ # 扩展名 → QQ 富媒体 file_type(1 图片 2 视频 3 语音 4 文件)
83
+ FILE_TYPES = {
84
+ ".png": 1, ".jpg": 1, ".jpeg": 1, ".gif": 1, ".webp": 1, ".bmp": 1,
85
+ ".mp4": 2, ".mov": 2,
86
+ ".silk": 3, ".amr": 3, ".mp3": 3, ".wav": 3,
87
+ }
88
+
89
+ CODE_FENCE = "\x60\x60\x60"
90
+ MD_LINE = re.compile(r"(^|\n)\s*(#{1,6} |[-*+] |\d+\. |\|\s*\S)")
91
+ MD_INLINE = re.compile(r"\*\*[^*\n]+\*\*")
92
+
93
+ log = get_logger()
94
+
95
+
96
+ # --------------------------------------------------------------------------- #
97
+ # configuration
98
+ # --------------------------------------------------------------------------- #
99
+ @dataclass(frozen=True)
100
+ class Config:
101
+ """Everything the transport needs; secrets come from .env only."""
102
+
103
+ appid: str
104
+ secret: str
105
+ botname: str
106
+ bridge_url: str
107
+ bridge_token: str
108
+ owner_openid: str
109
+ sandbox: bool
110
+ http_timeout: float
111
+ groups_enabled: bool
112
+ group_full_mode: bool
113
+ owner_role_check: bool
114
+ max_chars: int
115
+ pull_wait_ms: int
116
+ ack_delay_s: float
117
+ ack_text: str
118
+ debounce_s: float
119
+ debounce_max_s: float
120
+ chime_min: int
121
+ chime_cooldown_s: float
122
+ md_auto: bool
123
+ image_max_mb: float
124
+ send_file_roots: Tuple[str, ...]
125
+ bot_aliases: Tuple[str, ...]
126
+ stale_prompt_s: float
127
+ owner_window_s: float
128
+ group_chat_window_s: float
129
+ chatter_batch: int
130
+ chatter_max_s: float
131
+ chatter_cooldown_s: float
132
+ bot_say_memory_s: float
133
+ stuck_turn_s: float
134
+
135
+
136
+ def _env(name: str, default: str = "") -> str:
137
+ value = os.getenv(name)
138
+ return default if value is None or value.strip() == "" else value.strip()
139
+
140
+
141
+ def _env_flag(name: str, default: bool) -> bool:
142
+ raw = _env(name, "1" if default else "0").lower()
143
+ return raw in {"1", "true", "yes", "on"}
144
+
145
+
146
+ def load_config() -> Config:
147
+ """Read .env + environment; fail fast with an actionable message."""
148
+ load_env(ROOT / ".env")
149
+ appid = _env("APPID")
150
+ secret = _env("APPSECRET") or _env("APPSECERT")
151
+ if not appid or not secret:
152
+ raise SystemExit("APPID / APPSECRET missing: copy .env.example to .env and fill them in.")
153
+ return Config(
154
+ appid=appid,
155
+ secret=secret,
156
+ botname=_env("BOTNAME", "DSH"),
157
+ bridge_url=_env("BRIDGE_URL", "http://127.0.0.1:39061"),
158
+ bridge_token=_env("BRIDGE_TOKEN"),
159
+ owner_openid=_env("OWNER_OPENID"),
160
+ sandbox=_env_flag("QQ_SANDBOX", False),
161
+ http_timeout=float(_env("HTTP_TIMEOUT", "60")),
162
+ groups_enabled=_env_flag("GROUP_ENABLED", True),
163
+ group_full_mode=_env_flag("GROUP_FULL_MODE", False),
164
+ owner_role_check=_env_flag("OWNER_ROLE_CHECK", True),
165
+ max_chars=int(_env("MAX_CHARS", "1600")),
166
+ pull_wait_ms=int(_env("PULL_WAIT_MS", "25000")),
167
+ ack_delay_s=float(_env("ACK_DELAY_S", "12")),
168
+ ack_text=_env("ACK_TEXT", "(还在处理,请稍等…)"),
169
+ debounce_s=float(_env("DEBOUNCE_MS", "1800")) / 1000.0,
170
+ debounce_max_s=float(_env("DEBOUNCE_MAX_MS", "6000")) / 1000.0,
171
+ chime_min=int(_env("GROUP_CHIME_MIN", "8")),
172
+ chime_cooldown_s=float(_env("GROUP_CHIME_COOLDOWN", "240")),
173
+ md_auto=_env_flag("MD_AUTO", True),
174
+ image_max_mb=float(_env("IMAGE_MAX_MB", "8")),
175
+ send_file_roots=tuple(
176
+ part.strip() for part in _env("SEND_FILE_ROOTS", str(ROOT.parent)).split(";") if part.strip()
177
+ ),
178
+ bot_aliases=tuple(
179
+ part.strip()
180
+ for part in _env("BOT_ALIASES", "蓝色大肥鱼,大肥鱼,机器人,DSH,dsh").split(",")
181
+ if part.strip()
182
+ ),
183
+ stale_prompt_s=float(_env("STALE_PROMPT_S", "90")),
184
+ owner_window_s=float(_env("OWNER_WINDOW_S", "180")),
185
+ group_chat_window_s=float(_env("GROUP_CHAT_WINDOW_S", "300")),
186
+ chatter_batch=int(_env("GROUP_CHATTER_BATCH", "8")),
187
+ chatter_max_s=float(_env("GROUP_CHATTER_MAX_S", "120")),
188
+ chatter_cooldown_s=float(_env("GROUP_CHATTER_COOLDOWN_S", "45")),
189
+ bot_say_memory_s=float(_env("BOT_SAY_MEMORY_S", "300")),
190
+ stuck_turn_s=float(_env("STUCK_TURN_S", "180")),
191
+ )
192
+
193
+
194
+ # --------------------------------------------------------------------------- #
195
+ # small helpers
196
+ # --------------------------------------------------------------------------- #
197
+ # QQ 把表情/图片/按钮等编码成这种内联标签,喂给模型前先清掉
198
+ MENTION_RE = re.compile(r"<@!?([0-9A-Za-z_-]{8,})>")
199
+ QAT_USER_RE = re.compile(r"<qqbot-at-user[^>]*?\bid=\"([^\"]+)\"[^>]*>", re.IGNORECASE)
200
+ INLINE_TAG = re.compile(r"<(?:faceType|img|qqbot-cmd-enter|qqbot-at-user|emoji)[^>]*>", re.IGNORECASE)
201
+
202
+
203
+ def _author_nick(message: Any) -> str:
204
+ """The sender's nickname as the platform reports it (username, else group card)."""
205
+ author = getattr(message, "author", None)
206
+ for value in (
207
+ getattr(author, "username", "") if author is not None else "",
208
+ getattr(author, "member_nickname", "") if author is not None else "",
209
+ getattr(message, "member_nickname", "") or "",
210
+ ):
211
+ if isinstance(value, str) and value.strip():
212
+ return value.strip()
213
+ return ""
214
+
215
+
216
+ def clean_content(content: Optional[str]) -> str:
217
+ """Normalise inbound text: keep WHO was @-ed, drop only the noisy tags."""
218
+ text = (content or "").strip()
219
+ text = MENTION_RE.sub(lambda hit: "@群友" + short_id(hit.group(1)).upper(), text)
220
+ text = QAT_USER_RE.sub(lambda hit: "@群友" + short_id(hit.group(1)).upper(), text)
221
+ text = INLINE_TAG.sub("", text)
222
+ return " ".join(text.split()).strip()
223
+
224
+
225
+ def looks_like_openid(value: str) -> bool:
226
+ """Guard against answering synthetic ids such as the CLI smoke tests."""
227
+ return len(value) >= 16 and "-" not in value and value.isalnum()
228
+
229
+
230
+ def short_id(value: str) -> str:
231
+ """Stable short tag for an openid, so a name stays readable in chat."""
232
+ return value[-6:] if len(value) > 6 else value
233
+
234
+
235
+ def looks_like_markdown(text: str) -> bool:
236
+ """Whether a reply should go out as a QQ Markdown message (msg_type=2)."""
237
+ if CODE_FENCE in text:
238
+ return True
239
+ if MD_LINE.search(text) is not None:
240
+ return True
241
+ return MD_INLINE.search(text) is not None
242
+
243
+
244
+ def chunk_text(text: str, limit: int) -> List[str]:
245
+ """Split long answers on paragraph/line boundaries, then hard-cut."""
246
+ if limit <= 0 or len(text) <= limit:
247
+ return [text]
248
+ chunks: List[str] = []
249
+ buffer = ""
250
+ for line in text.splitlines(keepends=True):
251
+ while len(line) > limit:
252
+ if buffer:
253
+ chunks.append(buffer)
254
+ buffer = ""
255
+ chunks.append(line[:limit])
256
+ line = line[limit:]
257
+ if len(buffer) + len(line) > limit:
258
+ chunks.append(buffer)
259
+ buffer = line
260
+ else:
261
+ buffer += line
262
+ if buffer:
263
+ chunks.append(buffer)
264
+ return [chunk for chunk in (part.strip("\n") for part in chunks) if chunk != ""]
265
+
266
+
267
+ def parse_kick_confirm(text: str) -> Optional[Tuple[str, bool]]:
268
+ """'踢人确认 <id> yes|no' as sent by the confirmation buttons."""
269
+ match = re.search(r"踢人确认\s+(\S+)\s+(yes|no)", text or "", re.IGNORECASE)
270
+ if not match:
271
+ return None
272
+ return match.group(1), match.group(2).lower() == "yes"
273
+
274
+
275
+ def parse_decision(text: str) -> Tuple[Optional[str], Optional[str]]:
276
+ """Recognise an approval answer, optionally carrying the approval id."""
277
+ tokens = text.strip().split()
278
+ if not tokens:
279
+ return None, None
280
+ head = tokens[0].strip("::,,。.!!~~").lower()
281
+ approval_id = tokens[1] if len(tokens) > 1 else None
282
+ if head in ALLOW_WORDS:
283
+ return "allow", approval_id
284
+ if head in DENY_WORDS:
285
+ return "reject", approval_id
286
+ return None, None
287
+
288
+
289
+ COMMAND_PANEL_ROWS = [
290
+ [("/帮助", "帮助"), ("/状态", "状态"), ("/会话", "会话")],
291
+ [("/花费", "花费"), ("/花费 全部", "花费全部"), ("/新会话", "新会话")],
292
+ [("/截图", "截图"), ("/窗口", "窗口"), ("/菜单", "菜单")],
293
+ ]
294
+
295
+
296
+ def command_keyboard() -> Dict[str, Any]:
297
+ """Command panel: every button sends its command as a normal message."""
298
+ rows = []
299
+ for row in COMMAND_PANEL_ROWS:
300
+ buttons = []
301
+ for data, label in row:
302
+ buttons.append(
303
+ {
304
+ "id": data,
305
+ "render_data": {"label": label, "visited_label": label, "style": 1},
306
+ "action": {
307
+ "type": 2,
308
+ "permission": {"type": 2},
309
+ "data": data,
310
+ "unsupport_tips": f"请升级 QQ 后使用按钮,或直接回复「{data}」",
311
+ "enter": True,
312
+ },
313
+ }
314
+ )
315
+ rows.append({"buttons": buttons})
316
+ return {"content": {"rows": rows}}
317
+
318
+
319
+ def question_keyboard(question_id: str, options: list) -> Dict[str, Any]:
320
+ """One button per option; clicking answers the pending dsh question."""
321
+ buttons = []
322
+ for index, label in enumerate(options[:8]):
323
+ text = str(label)
324
+ buttons.append({
325
+ "id": f"{question_id}:{index}",
326
+ "render_data": {"label": text[:12], "visited_label": "✓ 已选", "style": 1},
327
+ "action": {
328
+ "type": 1,
329
+ "permission": {"type": 2},
330
+ "click_limit": 1,
331
+ "data": f"选择 {question_id} {index}",
332
+ "unsupport_tips": "请升级 QQ 后使用按钮,或直接回复选项序号",
333
+ },
334
+ })
335
+ rows = [{"buttons": buttons[i:i + 2]} for i in range(0, len(buttons), 2)]
336
+ return {"content": {"rows": rows}}
337
+
338
+
339
+ def kick_confirm_keyboard(request_id: str) -> Dict[str, Any]:
340
+ """Owner-only second confirmation for an irreversible kick."""
341
+ def button(label: str, style: int, data: str, visited: str) -> Dict[str, Any]:
342
+ return {
343
+ "id": data,
344
+ "render_data": {"label": label, "visited_label": visited, "style": style},
345
+ "action": {
346
+ "type": 1,
347
+ "permission": {"type": 2},
348
+ "data": data,
349
+ "unsupport_tips": "请升级 QQ 后使用按钮,或直接回复「确认踢人」/「取消踢人」",
350
+ },
351
+ }
352
+
353
+ return {
354
+ "content": {
355
+ "rows": [
356
+ {
357
+ "buttons": [
358
+ button("确认踢出", 3, f"踢人确认 {request_id} yes", "✓ 已踢出"),
359
+ button("取消", 0, f"踢人确认 {request_id} no", "✓ 已取消"),
360
+ ]
361
+ }
362
+ ]
363
+ }
364
+ }
365
+
366
+
367
+ def decided_keyboard(approval_id: str, label: str) -> Dict[str, Any]:
368
+ """Keyboard for an already-decided approval: one dead button that only toasts."""
369
+ return {
370
+ "content": {
371
+ "rows": [
372
+ {
373
+ "buttons": [
374
+ {
375
+ "id": "1",
376
+ "render_data": {"label": "已处理 ✅", "visited_label": "已处理 ✅", "style": 0},
377
+ "action": {
378
+ "type": 1,
379
+ "permission": {"type": 0},
380
+ "data": f"已处理 {approval_id}"[:40],
381
+ "unsupport_tips": "已处理",
382
+ },
383
+ }
384
+ ]
385
+ }
386
+ ]
387
+ }
388
+ }
389
+
390
+
391
+ def approval_keyboard(approval_id: str) -> Dict[str, Any]:
392
+ """Two-button keyboard: 允许 / 拒绝, clicked value carries the approval id."""
393
+
394
+ def button(label: str, style: int, data: str, visited: str) -> Dict[str, Any]:
395
+ return {
396
+ "id": data,
397
+ # visited_label:点完之后客户端把按钮就地改成这个文案(官方同款做法)
398
+ "render_data": {"label": label, "visited_label": visited, "style": style},
399
+ "action": {
400
+ # 官方 dsh-qqbot 的审批键盘用的就是 action.type=1 + permission.type=2
401
+ # (permission.type: 0 会被平台直接判成"无权限操作")
402
+ "type": 1,
403
+ "permission": {"type": 2},
404
+ "data": data,
405
+ "unsupport_tips": "请升级 QQ 后使用按钮,或直接回复「允许」/「拒绝」",
406
+ },
407
+ }
408
+
409
+ return {
410
+ "content": {
411
+ "rows": [
412
+ {
413
+ "buttons": [
414
+ button("允许", 1, f"允许 {approval_id}", "✓ 已允许"),
415
+ button("拒绝", 0, f"拒绝 {approval_id}", "✓ 已拒绝"),
416
+ ]
417
+ }
418
+ ]
419
+ }
420
+ }
421
+
422
+
423
+ # --------------------------------------------------------------------------- #
424
+ # local state (owner identity + bound group owners)
425
+ # --------------------------------------------------------------------------- #
426
+ class LocalState:
427
+ """Owner identity per bot appid, plus per-group owner bindings."""
428
+
429
+ def __init__(self, path: Path) -> None:
430
+ self.path = path
431
+ self.owner_openid = ""
432
+ self.group_owners: Dict[str, str] = {}
433
+
434
+ def load(self) -> "LocalState":
435
+ try:
436
+ data = json.loads(self.path.read_text(encoding="utf-8"))
437
+ except (FileNotFoundError, json.JSONDecodeError):
438
+ return self
439
+ if isinstance(data, dict):
440
+ owner = data.get("owner_openid")
441
+ if isinstance(owner, str):
442
+ self.owner_openid = owner
443
+ bound = data.get("group_owners")
444
+ if isinstance(bound, dict):
445
+ self.group_owners = {str(k): str(v) for k, v in bound.items()}
446
+ return self
447
+
448
+ def save(self) -> None:
449
+ payload = {"owner_openid": self.owner_openid, "group_owners": self.group_owners}
450
+ try:
451
+ self.path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
452
+ except OSError as error: # pragma: no cover - best effort
453
+ log.warning("could not persist %s: %s", self.path, error)
454
+
455
+
456
+ # --------------------------------------------------------------------------- #
457
+ # reply target bookkeeping
458
+ # --------------------------------------------------------------------------- #
459
+ @dataclass
460
+ class Target:
461
+ """Where latest messages of one conversation go, and the passive window."""
462
+
463
+ conv_key: str
464
+ kind: str
465
+ openid: str
466
+ last_msg_id: Optional[str] = None
467
+ last_msg_at: float = 0.0
468
+ passive_used: int = 0
469
+
470
+ def remember(self, message_id: Optional[str]) -> None:
471
+ if message_id:
472
+ self.last_msg_id = message_id
473
+ self.last_msg_at = time.time()
474
+ self.passive_used = 0
475
+
476
+ def passive_slot(self) -> Optional[str]:
477
+ """A msg_id we may still answer passively, if one is available."""
478
+ if not self.last_msg_id:
479
+ return None
480
+ if time.time() - self.last_msg_at > PASSIVE_WINDOW_S:
481
+ return None
482
+ if self.passive_used >= MAX_PASSIVE_PER_MESSAGE:
483
+ return None
484
+ self.passive_used += 1
485
+ return self.last_msg_id
486
+
487
+
488
+ @dataclass
489
+ class PooledMessage:
490
+ """One recent message (in or out) kept so /撤回 can reach it by index."""
491
+
492
+ message_id: str
493
+ conv_key: str
494
+ kind: str
495
+ openid: str
496
+ author: str
497
+ text: str
498
+ outbound: bool
499
+ at: float
500
+ idx: str = ""
501
+
502
+
503
+ @dataclass
504
+ class Chatter:
505
+ """Chatter buffered between judgments for one group."""
506
+
507
+ lines: List[str] = field(default_factory=list)
508
+ first_at: float = 0.0
509
+ last_judge_at: float = 0.0
510
+ timer: Optional[asyncio.Task] = None
511
+
512
+
513
+ @dataclass
514
+ class QueuedPrompt:
515
+ """Messages that piled up while a turn was still running for this chat."""
516
+
517
+ parts: List[str] = field(default_factory=list)
518
+ images: List[Dict[str, str]] = field(default_factory=list)
519
+ sender_name: str = ""
520
+ is_owner: bool = False
521
+ chime: bool = False
522
+ chat: bool = False
523
+ first_at: float = field(default_factory=time.time)
524
+
525
+
526
+ @dataclass
527
+ class Pending:
528
+ """Messages being debounced into one prompt for a conversation."""
529
+
530
+ parts: List[str] = field(default_factory=list)
531
+ images: List[Dict[str, str]] = field(default_factory=list)
532
+ sender_name: str = ""
533
+ is_owner: bool = False
534
+ chat: bool = False
535
+ started: float = field(default_factory=time.time)
536
+ job: Optional[asyncio.Task] = None
537
+
538
+
539
+ # --------------------------------------------------------------------------- #
540
+ # the bot
541
+ # --------------------------------------------------------------------------- #
542
+ class DSHBot(Client):
543
+ """QQ transport in front of the dsh-qq-bridge plugin."""
544
+
545
+ def __init__(self, intents: Intents, *, config: Config) -> None:
546
+ super().__init__(intents, timeout=config.http_timeout, is_sandbox=config.sandbox)
547
+ self.config = config
548
+ self.bridge = BridgeClient(config.bridge_url, config.bridge_token)
549
+ self.state = LocalState(STATE_FILE).load()
550
+ self.owner_openid = config.owner_openid or self.state.owner_openid
551
+ if config.owner_openid and config.owner_openid != self.state.owner_openid:
552
+ self.state.owner_openid = config.owner_openid
553
+ self.state.save()
554
+ self.targets: Dict[str, Target] = {}
555
+ self.pending_approvals: Dict[str, Dict[str, Any]] = {}
556
+ self._decided: Dict[str, str] = {}
557
+ self._streams: Dict[str, Dict[str, Any]] = {}
558
+ self._suppress_reply: set = set()
559
+ self._streamed_turns: Dict[str, float] = {}
560
+
561
+ self.pending: Dict[str, Pending] = {}
562
+ self.queued: Dict[str, QueuedPrompt] = {}
563
+ self.chatter: Dict[str, Chatter] = {}
564
+ self.recent_images: Dict[str, Tuple[List[Dict[str, str]], float]] = {}
565
+ self._addressed_at: Dict[str, float] = {}
566
+ self._bot_spoke_at: Dict[str, float] = {}
567
+ self._last_sent: Dict[str, Tuple[str, float]] = {}
568
+ self._last_bot_say: Dict[str, Tuple[str, float]] = {}
569
+ self._rate: Dict[str, Tuple[int, float]] = {}
570
+ self.rt = None # type: ignore[assignment]
571
+ self.group_state: Dict[str, Dict[str, Any]] = {}
572
+ self._role_probe_failed_at = 0.0
573
+ self._seen_ids: Dict[str, float] = {}
574
+ self._submitted_at: Dict[str, float] = {}
575
+ self._urgent_tasks: set = set()
576
+ self._inflight: Dict[str, int] = {}
577
+ self._inflight_at: Dict[str, float] = {}
578
+ self.chime: Dict[str, Dict[str, float]] = {}
579
+ self._msg_seq = 0
580
+ self._pull_task: Optional[asyncio.Task] = None
581
+ self._watchdog_task: Optional[asyncio.Task] = None
582
+ self._acks: Dict[str, asyncio.Task] = {}
583
+ self.pool: Dict[str, PooledMessage] = {}
584
+ self.pool_idx: Dict[str, str] = {}
585
+ self._pending_quotes: Dict[str, Dict[str, Any]] = {}
586
+ self._started_at = time.time()
587
+ self._chat_turns: Dict[str, bool] = {}
588
+ self._judge_silent_streak: Dict[str, int] = {}
589
+ self._judge_force_at: Dict[str, float] = {}
590
+ self._judge_threshold_used: Dict[str, int] = {}
591
+ self._bg_tasks: set = set()
592
+ self._owner_recent: Dict[str, float] = {}
593
+ self._last_group_at: Dict[str, float] = {}
594
+ self._stream_locks: Dict[str, asyncio.Lock] = {}
595
+ self._stream_holdoff: Dict[str, float] = {}
596
+ self._admin_confirm: Dict[str, Dict[str, Any]] = {}
597
+ self.member_index: Dict[str, Dict[str, str]] = {}
598
+ self._member_names: Dict[str, Dict[str, str]] = {}
599
+ self._token: Tuple[str, float] = ("", 0.0)
600
+
601
+ # -- lifecycle ---------------------------------------------------------- #
602
+ async def on_ready(self) -> None:
603
+ log.info("[%s] bot online (owner=%s)", self.config.botname, self.owner_openid or "unclaimed")
604
+ try:
605
+ health = await self.bridge.health()
606
+ log.info("[%s] bridge %s (%s)", self.config.botname, health.get("service"), self.config.bridge_url)
607
+ except BridgeError as error:
608
+ log.warning("[%s] bridge unreachable: %s", self.config.botname, error)
609
+ self._seed_members() # 成员索引跨重启保留:谁发过言就一直在
610
+ self._seed_metrics() # 计数跨重启累计,只有「运行时长」归零
611
+ self._bump("c2c_msgs", 0) # 初始化并落盘计数器,仪表盘开局就有数据
612
+ self._prune_metrics(time.time()) # 启动时清一次超过保留期的归档
613
+ await self._prefetch_group_profiles()
614
+ await self._sync_panels()
615
+ # 严格闭合:重启后先把上个进程遗留的流式会话关掉,再开始新回合
616
+ try:
617
+ await self._close_stale_streams()
618
+ except Exception as error: # noqa: BLE001 - must never block startup
619
+ log.warning("stale stream cleanup failed: %s", error)
620
+ _heartbeat()
621
+ if self._pull_task is None or self._pull_task.done():
622
+ self._pull_task = asyncio.create_task(self._pull_loop())
623
+ if getattr(self, "_watchdog_task", None) is None or self._watchdog_task.done():
624
+ self._watchdog_task = asyncio.create_task(self._pull_watchdog())
625
+ self._question_task = asyncio.create_task(self._question_loop())
626
+ self._admin_task = asyncio.create_task(self._admin_loop())
627
+
628
+ async def _sync_panels(self) -> None:
629
+ """Push bot/panels/panels.json to the QQ instruction panel."""
630
+ try:
631
+ store = await load_panels(self.api, root_dir=str(ROOT / "panels"))
632
+ await store.sync_from_config()
633
+ log.info("[%s] instruction panels synced", self.config.botname)
634
+ except Exception as error: # noqa: BLE001 - panel sync must never block startup
635
+ log.warning("[%s] panel sync failed: %s", self.config.botname, error)
636
+
637
+ # -- runtime settings (panel-editable, hot-reloaded) -------------------- #
638
+ def rt_bool(self, key: str, default: bool = True) -> bool:
639
+ return self.rt.get_bool(key) if self.rt is not None else default
640
+
641
+ def rt_int(self, key: str, default: int = 0) -> int:
642
+ return self.rt.get_int(key) if self.rt is not None else default
643
+
644
+ def rt_float(self, key: str, default: float = 0.0) -> float:
645
+ return self.rt.get_float(key) if self.rt is not None else default
646
+
647
+ def rt_str(self, key: str, default: str = "") -> str:
648
+ if self.rt is None:
649
+ return default
650
+ value = self.rt.get(key)
651
+ return default if value is None else str(value)
652
+
653
+ def _allowlisted(self, key: str, ident: str) -> bool:
654
+ raw = self.rt_str(key, "")
655
+ if raw.strip() == "":
656
+ return True
657
+ return any(part.strip() == ident for part in raw.split(",") if part.strip())
658
+
659
+ def _in_quiet_hours(self) -> bool:
660
+ if not self.rt_bool("quiet_enabled", True):
661
+ return False
662
+ raw = self.rt_str("quiet_hours", "").strip()
663
+ if not raw or "-" not in raw:
664
+ return False
665
+ try:
666
+ start_text, end_text = raw.split("-", 1)
667
+ now = time.strftime("%H:%M")
668
+ start, end = start_text.strip(), end_text.strip()
669
+ return (start <= now < end) if start <= end else (now >= start or now < end)
670
+ except Exception:
671
+ return False
672
+
673
+ def _rate_limited(self, conv_key: str) -> bool:
674
+ limit = self.rt_int("rate_limit_per_hour", 0)
675
+ if limit <= 0:
676
+ return False
677
+ count, window = self._rate.get(conv_key, (0, time.time()))
678
+ if time.time() - window > 3600:
679
+ count, window = 0, time.time()
680
+ self._rate[conv_key] = (count, window)
681
+ if count >= limit:
682
+ log.warning("rate limited %s (%d/h)", conv_key, limit)
683
+ return True
684
+ return False
685
+
686
+ def _count_send(self, conv_key: str) -> None:
687
+ count, window = self._rate.get(conv_key, (0, time.time()))
688
+ if time.time() - window > 3600:
689
+ count, window = 0, time.time()
690
+ self._rate[conv_key] = (count + 1, window)
691
+
692
+ # -- helpers ------------------------------------------------------------ #
693
+ @staticmethod
694
+ def _target_from_key(conv_key: str) -> Optional[Target]:
695
+ kind, _, openid = conv_key.partition(":")
696
+ if not openid or kind not in {"group", "c2c"}:
697
+ return None
698
+ return Target(conv_key=conv_key, kind=kind, openid=openid)
699
+
700
+ def _register(self, conv_key: str, kind: str, openid: str, message_id: Optional[str]) -> Target:
701
+ target = self.targets.get(conv_key)
702
+ if target is None:
703
+ target = Target(conv_key=conv_key, kind=kind, openid=openid)
704
+ self.targets[conv_key] = target
705
+ target.openid = openid or target.openid
706
+ target.remember(message_id)
707
+ return target
708
+
709
+ @staticmethod
710
+ def conv_label(conv_key: str) -> str:
711
+ """Human-facing name for a conversation key (approval cards, logs)."""
712
+ kind, _, openid = conv_key.partition(":")
713
+ if kind == "group":
714
+ return f"QQ 群 …{short_id(openid)}"
715
+ if kind == "c2c":
716
+ return f"QQ 私聊 …{short_id(openid)}"
717
+ return conv_key
718
+
719
+ def _owner_conv(self) -> str:
720
+ return f"c2c:{self.owner_openid}" if self.owner_openid else ""
721
+
722
+ def _is_owner_group(self, group_openid: str, member_openid: str) -> bool:
723
+ if member_openid == "":
724
+ return False
725
+ # The bot owner is the owner everywhere, even in a group nobody bound.
726
+ if self.owner_openid and member_openid == self.owner_openid:
727
+ return True
728
+ return self.state.group_owners.get(group_openid, "") == member_openid
729
+
730
+ async def _bind_group_owner_by_role(self, group_openid: str, member_openid: str) -> bool:
731
+ """Ask the platform whether this member owns the group, then remember it."""
732
+ if not self.config.owner_role_check or not member_openid:
733
+ return False
734
+ if self._is_owner_group(group_openid, member_openid):
735
+ return True
736
+ try:
737
+ if time.time() - self._role_probe_failed_at < 900:
738
+ return False
739
+ info = await self.api.get_group_member(group_openid=group_openid, member_openid=member_openid)
740
+ except Exception as error: # noqa: BLE001 - 11253 = capability not opened yet
741
+ self._role_probe_failed_at = time.time()
742
+ log.info("group member lookup unavailable (will retry in 15 min): %s", error)
743
+ return False
744
+ payload = info.get("member") if isinstance(info, dict) and isinstance(info.get("member"), dict) else info
745
+ role = str(payload.get("member_role") or "") if isinstance(payload, dict) else ""
746
+ if role != "owner":
747
+ return False
748
+ self.state.group_owners[group_openid] = member_openid
749
+ self.state.save()
750
+ log.info("group owner detected: %s -> %s", group_openid, short_id(member_openid))
751
+ return True
752
+
753
+ def _remember_id(self, message_id: Optional[str]) -> None:
754
+ """Track recently handled message ids so one message is answered once."""
755
+ if not message_id:
756
+ return
757
+ self._seen_ids[message_id] = time.time()
758
+ if len(self._seen_ids) > 500:
759
+ for key in sorted(self._seen_ids, key=self._seen_ids.get)[:250]:
760
+ self._seen_ids.pop(key, None)
761
+
762
+ # -- recent message pool (for /撤回) ------------------------------------ #
763
+ def _pool_ttl(self) -> float:
764
+ return max(60.0, self.rt_float("pool_ttl_s", MSG_POOL_TTL_S))
765
+
766
+ def _pool_limit(self) -> int:
767
+ return max(10, self.rt_int("pool_max", MSG_POOL_MAX))
768
+
769
+ def _pool_add(self, item: PooledMessage) -> None:
770
+ """Keep the last 10 minutes of traffic, oldest evicted first."""
771
+ self.pool[item.message_id] = item
772
+ if item.idx:
773
+ self.pool_idx[item.idx] = item.message_id
774
+ cutoff = time.time() - self._pool_ttl()
775
+ for key in [key for key, value in self.pool.items() if value.at < cutoff]:
776
+ self.pool.pop(key, None)
777
+ while len(self.pool) > self._pool_limit():
778
+ self.pool.pop(next(iter(self.pool)), None)
779
+ if self.pool_idx:
780
+ live = {item.message_id for item in self.pool.values()}
781
+ for idx, message_id in list(self.pool_idx.items()):
782
+ if message_id not in live:
783
+ self.pool_idx.pop(idx, None)
784
+
785
+ def _strip_self_mention(self, conv_key: str, text: str) -> str:
786
+ """群聊里 @ 自己那一次不进正文:'@蓝色大肥鱼 现在?' → '现在?'。"""
787
+ kind, _, group_openid = conv_key.partition(":")
788
+ if kind != "group":
789
+ return text
790
+ own_tail = short_id((getattr(self, "_bot_openids", {}) or {}).get(group_openid, "")).upper()
791
+ name = str(getattr(self.config, "botname", "") or "")
792
+ body = str(text or "").lstrip()
793
+ prefixes = []
794
+ if name:
795
+ prefixes.append("@" + name)
796
+ if own_tail:
797
+ prefixes.append("@群友" + own_tail)
798
+ for prefix in prefixes:
799
+ if body.startswith(prefix):
800
+ return body[len(prefix):].lstrip()
801
+ return body
802
+
803
+ def _roster_line(self, conv_key: str, limit: int = 12) -> str:
804
+ """短号 → 昵称对照,让转录里的 @群友XXXX 能被认出来。"""
805
+ index = getattr(self, "member_index", {}).get(conv_key) or {}
806
+ names = (getattr(self, "_member_names", {}) or {}).get(conv_key) or {}
807
+ rows = []
808
+ for tail, openid in list(index.items())[:limit]:
809
+ name = names.get(tail) or ""
810
+ if name:
811
+ rows.append(str(tail).upper() + "=" + name)
812
+ else:
813
+ rows.append(str(tail).upper() + "=" + self._display_name(conv_key, openid))
814
+ if not rows:
815
+ return ""
816
+ return "群友对照(短号=昵称):" + "、".join(rows)
817
+
818
+ def _humanize_mentions(self, conv_key: str, text: str) -> str:
819
+ """@群友622C23 → @真实昵称,让判断/转录看得出来这次在跟谁说话。"""
820
+ if "@群友" not in text:
821
+ return text
822
+ index = getattr(self, "member_index", {}).get(conv_key) or {}
823
+ by_tail = {str(tail).upper(): openid for tail, openid in index.items()}
824
+
825
+ kind, _, group_openid = conv_key.partition(":")
826
+ own_tail = short_id((getattr(self, "_bot_openids", {}) or {}).get(group_openid, "")).upper()
827
+ own_name = str(getattr(self.config, "botname", "") or "我")
828
+
829
+ def swap(hit: "re.Match[str]") -> str:
830
+ tail = hit.group(1).upper()
831
+ if own_tail and tail == own_tail:
832
+ # @ 的是机器人自己:写名字,别写成陌生群友
833
+ return "@" + own_name
834
+ openid = by_tail.get(tail, "")
835
+ if not openid:
836
+ return hit.group(0)
837
+ return "@" + self._display_name(conv_key, openid)
838
+
839
+ return re.sub(r"@群友([0-9A-F]{6})", swap, text)
840
+
841
+ def _pool_incoming(self, message: Any, kind: str, openid: str, conv_key: str, author: str) -> None:
842
+ message_id = str(getattr(message, "id", "") or "")
843
+ if not message_id:
844
+ return
845
+ raw = clean_content(getattr(message, "content", ""))
846
+ # 防御:任何时候都不要把我们自己的提示词当成群聊发言记进上下文
847
+ if raw.lstrip().startswith(("【闲聊模式】", "【群聊插话判断】")):
848
+ log.warning("dropped prompt-shaped text from the pool (%s)", kind)
849
+ return
850
+ self._pool_add(
851
+ PooledMessage(
852
+ message_id=message_id,
853
+ conv_key=conv_key,
854
+ kind=kind,
855
+ openid=openid,
856
+ author=author or "群友",
857
+ text=self._humanize_mentions(conv_key, clean_content(getattr(message, "content", "")))[:60],
858
+ outbound=False,
859
+ at=time.time(),
860
+ idx=self._message_idx(message),
861
+ )
862
+ )
863
+
864
+ def _note_bot_say(self, conv_key: str, text: str) -> None:
865
+ """记住机器人在这个会话里最后一次真正说出去的话(插话判断要用)。"""
866
+ body = str(text or "").strip()
867
+ if not body:
868
+ return
869
+ said = getattr(self, "_last_bot_say", None)
870
+ if said is None:
871
+ said = self._last_bot_say = {}
872
+ said[conv_key] = (body[:160], time.time())
873
+
874
+ def _last_bot_say_of(self, conv_key: str) -> Tuple[str, float]:
875
+ """最近说过什么:优先内存记录,其次回看消息池里自己发的那几条。"""
876
+ said = getattr(self, "_last_bot_say", {}) or {}
877
+ text, at = said.get(conv_key, ("", 0.0))
878
+ if text:
879
+ return text, at
880
+ try:
881
+ items = [item for item in self._pool_items(conv_key) if item.outbound]
882
+ except Exception: # noqa: BLE001 - 池不可用就当没说过
883
+ items = []
884
+ if not items:
885
+ return "", 0.0
886
+ last = items[-1]
887
+ return str(last.text or ""), float(last.at)
888
+
889
+ def _pool_sent(self, target: Target, result: Any, text: str) -> None:
890
+ if isinstance(result, dict):
891
+ message_id = str(result.get("id") or "")
892
+ else:
893
+ message_id = str(getattr(result, "id", "") or "")
894
+ if not message_id:
895
+ return
896
+ self._pool_add(
897
+ PooledMessage(
898
+ message_id=message_id,
899
+ conv_key=target.conv_key,
900
+ kind=target.kind,
901
+ openid=target.openid,
902
+ author=self.config.botname,
903
+ text=text[:60],
904
+ outbound=True,
905
+ idx=_sent_idx(result),
906
+ at=time.time(),
907
+ )
908
+ )
909
+
910
+ def _pool_items(self, conv_key: str) -> List[PooledMessage]:
911
+ cutoff = time.time() - self._pool_ttl()
912
+ items = [item for item in self.pool.values() if item.conv_key == conv_key and item.at >= cutoff]
913
+ return sorted(items, key=lambda item: item.at)
914
+
915
+ def _pool_text(self, conv_key: str) -> str:
916
+ items = self._pool_items(conv_key)
917
+ if not items:
918
+ return "消息池是空的(只缓存最近 10 分钟)。"
919
+ rows = [
920
+ f"{index}. [{int(time.time() - item.at)}s] {'我' if item.outbound else item.author}:"
921
+ f"{item.text.replace(chr(10), ' ')[:28] or '(图片/空)'}"
922
+ for index, item in enumerate(items, 1)
923
+ ]
924
+ head = f"最近 10 分钟 {len(items)} 条(/撤回 <序号> 撤指定,/撤回 n 撤我最近 n 条):"
925
+ return "\n".join([head, *rows[-20:]])
926
+
927
+ async def _access_token(self) -> str:
928
+ """App access token for raw platform calls (the SDK caches its own copy)."""
929
+ stored = self._token
930
+ # The SDK hands over a TokenManager until our own cache is primed.
931
+ token, expires_at = stored if isinstance(stored, tuple) else ("", 0.0)
932
+ if token and time.time() < expires_at - 60:
933
+ return token
934
+ appid = self.rt_str("appid", self.config.appid)
935
+ secret = self.rt_str("appsecret", self.config.secret)
936
+ timeout = aiohttp.ClientTimeout(total=20)
937
+ async with aiohttp.ClientSession(timeout=timeout) as session:
938
+ async with session.post(
939
+ "https://bots.qq.com/app/getAppAccessToken",
940
+ json={"appId": appid, "clientSecret": secret},
941
+ ) as response:
942
+ data = await response.json(content_type=None)
943
+ token = str((data or {}).get("access_token") or "")
944
+ if not token:
945
+ raise RuntimeError(f"取 token 失败:{data}")
946
+ self._token = (token, time.time() + float((data or {}).get("expires_in") or 7200))
947
+ return token
948
+
949
+ async def recall_message(self, item: PooledMessage) -> Tuple[bool, str]:
950
+ """DELETE one message: a bot admin may recall its own and members' messages."""
951
+ try:
952
+ token = await self._access_token()
953
+ except Exception as error: # noqa: BLE001 - surfaced to the caller as text
954
+ return False, f"鉴权失败:{error}"
955
+ appid = self.rt_str("appid", self.config.appid)
956
+ if item.kind == "group":
957
+ url = f"{SG_GROUP_BASE_URL}/v2/groups/{item.openid}/messages/{item.message_id}"
958
+ else:
959
+ url = f"{SG_GROUP_BASE_URL}/v2/users/{item.openid}/messages/{item.message_id}"
960
+ headers = {"Authorization": f"QQBot {token}", "X-Union-Appid": appid}
961
+ timeout = aiohttp.ClientTimeout(total=20)
962
+ try:
963
+ async with aiohttp.ClientSession(timeout=timeout) as session:
964
+ async with session.delete(url, headers=headers) as response:
965
+ body = await response.text()
966
+ ok = response.status == 200
967
+ log.info(
968
+ "recall %s/%s status=%s body=%s",
969
+ item.kind,
970
+ item.message_id[-8:],
971
+ response.status,
972
+ body[:160].replace("\n", " "),
973
+ )
974
+ except aiohttp.ClientError as error:
975
+ return False, f"请求失败:{error}"
976
+ if ok:
977
+ self.pool.pop(item.message_id, None)
978
+ return True, ""
979
+ hints = {
980
+ "40062003": "没权限(我还是群管理员吗?)",
981
+ "40064004": "已超撤回时限",
982
+ "40061001": "消息 id 无效",
983
+ "50065001": "平台撤回失败,稍后重试",
984
+ }
985
+ try:
986
+ code = str(json.loads(body).get("code") or "")
987
+ except (json.JSONDecodeError, AttributeError):
988
+ code = ""
989
+ return False, hints.get(code, body[:120] or "未知错误")
990
+
991
+ async def _recall_command(self, conv_key: str, text: str) -> None:
992
+ parts = text.split(maxsplit=1)
993
+ arg = parts[1].strip() if len(parts) > 1 else ""
994
+ items = self._pool_items(conv_key)
995
+ if not items:
996
+ await self.send_text(conv_key, "消息池是空的(只缓存最近 10 分钟)。")
997
+ return
998
+ outbound = [item for item in items if item.outbound]
999
+ if not arg:
1000
+ targets = outbound[-1:]
1001
+ elif arg.startswith("#") and arg[1:].isdigit():
1002
+ index = int(arg[1:])
1003
+ targets = [items[index - 1]] if 1 <= index <= len(items) else []
1004
+ elif arg.isdigit():
1005
+ targets = outbound[-max(1, min(int(arg), 10)):]
1006
+ else:
1007
+ targets = [item for item in items if item.message_id.startswith(arg)]
1008
+ if not targets:
1009
+ await self.send_text(conv_key, f"没找到要撤的消息({arg or '我最近没发过'})。")
1010
+ return
1011
+ done = 0
1012
+ failures: List[str] = []
1013
+ for item in targets:
1014
+ ok, detail = await self.recall_message(item)
1015
+ if ok:
1016
+ done += 1
1017
+ else:
1018
+ failures.append(detail)
1019
+ message = f"已撤回 {done} 条。" if done else "一条都没撤成。"
1020
+ if failures:
1021
+ message += "\n失败:" + ";".join(sorted(set(failures))[:3])
1022
+ await self.send_text(conv_key, message)
1023
+
1024
+ def _alias_list(self):
1025
+ raw = self.rt_str("bot_aliases", ",".join(self.config.bot_aliases))
1026
+ return ", ".join(part.strip() for part in raw.split(",") if part.strip())
1027
+
1028
+ def addresses_bot(self, text: str) -> bool:
1029
+ """Whether the text names the bot without an explicit @ mention."""
1030
+ lowered = text.lower()
1031
+ raw = self.rt_str("bot_aliases", ",".join(self.config.bot_aliases))
1032
+ aliases = [part.strip() for part in raw.split(",") if part.strip()]
1033
+ return any(alias.lower() in lowered for alias in aliases)
1034
+
1035
+ async def _mentions_bot(self, message: GroupMessage) -> bool:
1036
+ """Whether this message actually @s the bot (never "any mention")."""
1037
+ mentions = getattr(message, "mentions", None) or []
1038
+ if not mentions:
1039
+ return False
1040
+
1041
+ # Collect every string the platform gave us for each mention.
1042
+ candidates: List[str] = []
1043
+ flag_bot = False
1044
+ for mention in mentions:
1045
+ raw = getattr(mention, "raw", None) or {}
1046
+ for value in raw.values():
1047
+ if isinstance(value, str) and value:
1048
+ candidates.append(value)
1049
+ for attr in ("id", "member_openid", "user_openid", "union_openid", "username"):
1050
+ value = getattr(mention, attr, None)
1051
+ if isinstance(value, str) and value:
1052
+ candidates.append(value)
1053
+ if getattr(mention, "bot", False):
1054
+ flag_bot = True
1055
+
1056
+ state = await self.group_bot_state(message.group_openid or "")
1057
+ bot_ids = {str(state.get("member_openid") or "")} | {str(v) for v in (state.get("_bot_ids") or [])}
1058
+ bot_ids = {value for value in bot_ids if value != ""}
1059
+
1060
+ if bot_ids & set(candidates):
1061
+ return True
1062
+ if not bot_ids and flag_bot:
1063
+ # no id to compare against, but the mention is flagged as a bot
1064
+ return True
1065
+ log.info(
1066
+ "mention not for me (bot=%s seen=%s flags=%s)",
1067
+ ",".join(short_id(v) for v in list(bot_ids)[:3]) or "-",
1068
+ ",".join(short_id(v) for v in candidates[:5]) or "-",
1069
+ flag_bot,
1070
+ )
1071
+ return False
1072
+
1073
+ async def group_bot_state(self, group_openid: str, *, force: bool = False) -> Dict[str, Any]:
1074
+ """機器人在该群的状态:消息范围、是否允许主动发言(缓存 60s)。"""
1075
+ cached = self.group_state.get(group_openid)
1076
+ if cached is not None and not force and time.time() - float(cached.get("_at", 0.0)) < 60.0:
1077
+ return cached
1078
+ try:
1079
+ state = await self.api.get_group_bot_state(group_openid)
1080
+ except Exception as error: # noqa: BLE001 - capability may be gated
1081
+ log.info("group bot state unavailable: %s", error)
1082
+ return {}
1083
+ if not isinstance(state, dict):
1084
+ return {}
1085
+ state = dict(state)
1086
+ state["_at"] = time.time()
1087
+ self.group_state[group_openid] = state
1088
+ member = str(state.get("member_openid") or "")
1089
+ if member:
1090
+ bots = getattr(self, "_bot_openids", None)
1091
+ if bots is None:
1092
+ bots = self._bot_openids = {}
1093
+ bots[group_openid] = member
1094
+ return state
1095
+
1096
+ async def status_text(self, conv_key: str) -> str:
1097
+ """Human-facing summary of what the bot may do in this conversation."""
1098
+ kind, _, openid = conv_key.partition(":")
1099
+ lines = [f"**会话**:{self.conv_label(conv_key)}"]
1100
+ if kind == "group":
1101
+ state = await self.group_bot_state(openid)
1102
+ scope = str(state.get("recv_msg_setting") or "unknown")
1103
+ scope_text = {"all": "全量消息 ✅", "mention": "仅 @ 我", "unknown": "未知"}.get(scope, scope)
1104
+ proactive = state.get("allow_proactive_msg")
1105
+ proactive_text = "允许 ✅" if proactive is True else ("未开启" if proactive is False else "未知")
1106
+ lines.append(f"**消息范围**:{scope_text}")
1107
+ lines.append(f"**主动发言**:{proactive_text}")
1108
+ if state.get("joined_at"):
1109
+ lines.append(f"**入群时间**:{state['joined_at']}")
1110
+ bound = openid in self.state.group_owners
1111
+ lines.append(f"**群主绑定**:{'已绑定' if bound else '未绑定(群主可发 /绑定)'}")
1112
+ else:
1113
+ lines.append(f"**主人**:{'是' if openid == self.owner_openid else '不是'}")
1114
+ lines.append(f"**会话已绑定 DSH**:{'是' if conv_key in self.targets else '本次进程内未活动'}")
1115
+ return "\n".join(lines)
1116
+
1117
+ async def _session_usage(self, session_id: str) -> Dict[str, Any]:
1118
+ """Run the Node usage reader; the Session log is multi-frame zstd."""
1119
+ node = shutil.which("node") or "node"
1120
+ script = ROOT / "usage.mjs"
1121
+ try:
1122
+ process = await asyncio.create_subprocess_exec(
1123
+ node,
1124
+ str(script),
1125
+ session_id,
1126
+ stdout=asyncio.subprocess.PIPE,
1127
+ stderr=asyncio.subprocess.PIPE,
1128
+ )
1129
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=30)
1130
+ except (OSError, asyncio.TimeoutError) as error:
1131
+ return {"ok": False, "error": str(error)}
1132
+ text = stdout.decode("utf-8", "replace").strip()
1133
+ try:
1134
+ return json.loads(text or "{}")
1135
+ except json.JSONDecodeError:
1136
+ detail = stderr.decode("utf-8", "replace").strip() or text
1137
+ return {"ok": False, "error": detail[:120]}
1138
+
1139
+ @staticmethod
1140
+ def menu_text(help_body: str) -> str:
1141
+ """Short header for the command panel message."""
1142
+ return "**指令面板**\n点下面的按钮,或直接发指令。\n\n" + help_body
1143
+
1144
+ @staticmethod
1145
+ def _usage_cost(stats: Dict[str, Any]) -> float:
1146
+ """Rough CNY estimate from the token mix (¥2/¥0.2/¥3 per 1M)."""
1147
+ return (
1148
+ int(stats.get("inputTokens") or 0) / 1e6 * 2
1149
+ + int(stats.get("cacheReadTokens") or 0) / 1e6 * 0.2
1150
+ + int(stats.get("outputTokens") or 0) / 1e6 * 3
1151
+ )
1152
+
1153
+ async def usage_all_text(self, conv_key: str, bindings: Dict[str, Any]) -> str:
1154
+ """Recent Sessions, most expensive first, with the bound ones labelled."""
1155
+ stats = await self._session_usage("--all")
1156
+ if not stats.get("ok"):
1157
+ return f"读不到用量:{stats.get('error')}"
1158
+ sessions = stats.get("sessions") or []
1159
+ if not sessions:
1160
+ return "没有找到可统计的会话。"
1161
+ owners: Dict[str, str] = {}
1162
+ for key, value in bindings.get("bound") or []:
1163
+ owners[str(value)] = key
1164
+ sessions.sort(key=lambda row: int(row.get("totalTokens") or 0), reverse=True)
1165
+ lines = ["**最近会话 token 用量**", "| 会话 | 消息 | 合计 | 约¥ |", "|---|---|---|---|"]
1166
+ total_tokens = 0.0
1167
+ total_cost = 0.0
1168
+ for row in sessions[:10]:
1169
+ session_id = str(row.get("sessionId") or "")
1170
+ title = str(row.get("title") or session_id[:12]).strip() or session_id[:12]
1171
+ if len(title) > 14:
1172
+ title = title[:14] + "…"
1173
+ mark = "◆" if owners.get(session_id) == conv_key else ("·" if session_id in owners else " ")
1174
+ tokens = int(row.get("totalTokens") or 0)
1175
+ cost = self._usage_cost(row)
1176
+ total_tokens += tokens
1177
+ total_cost += cost
1178
+ lines.append(f"| {mark}{title} | {int(row.get('messages') or 0)} | {tokens:,} | {cost:.2f} |")
1179
+ lines.append(f"◆=本会话 · 共 {len(sessions)} 个会话,前 10 个合计 {int(total_tokens):,} token,约 ¥{total_cost:.2f}。")
1180
+ return "\n".join(lines)
1181
+
1182
+ async def usage_text(self, conv_key: str, scope: str = "") -> str:
1183
+ """Token usage of the DSH Session bound to this conversation."""
1184
+ try:
1185
+ bindings = await self.bridge.sessions()
1186
+ except BridgeError as error:
1187
+ return f"拿不到会话绑定:{error}"
1188
+ if scope in {"全部", "所有", "all", "-a", "全", "all-sessions"}:
1189
+ return await self.usage_all_text(conv_key, bindings)
1190
+ session_id = ""
1191
+ for key, value in bindings.get("bound") or []:
1192
+ if key == conv_key:
1193
+ session_id = str(value)
1194
+ break
1195
+ if session_id == "":
1196
+ return "这个会话还没绑定 DSH,说句话让我建一个再看用量。"
1197
+ stats = await self._session_usage(session_id)
1198
+ if not stats.get("ok"):
1199
+ return f"读不到用量:{stats.get('error')}"
1200
+ input_tokens = int(stats.get("inputTokens") or 0)
1201
+ cache_read = int(stats.get("cacheReadTokens") or 0)
1202
+ output_tokens = int(stats.get("outputTokens") or 0)
1203
+ rows = [
1204
+ ("消息数", f"{int(stats.get('messages') or 0)}"),
1205
+ ("输入(未命中)", f"{input_tokens:,}"),
1206
+ ("缓存命中输入", f"{cache_read:,}"),
1207
+ ("输出", f"{output_tokens:,}"),
1208
+ ("合计", f"{int(stats.get('totalTokens') or 0):,}"),
1209
+ ]
1210
+ lines = ["**本会话 token 用量**", "| 项 | 值 |", "|---|---|"]
1211
+ lines += [f"| {name} | {value} |" for name, value in rows]
1212
+ prompt = input_tokens + cache_read
1213
+ hit_rate = (cache_read / prompt * 100) if prompt > 0 else 0.0
1214
+ cost = self._usage_cost(stats)
1215
+ model = ",".join(stats.get("models") or []) or "unknown"
1216
+ span = 0.0
1217
+ if stats.get("firstAt") and stats.get("lastAt"):
1218
+ span = (int(stats["lastAt"]) - int(stats["firstAt"])) / 60000
1219
+ lines.append(
1220
+ f"缓存命中 {hit_rate:.1f}%,约 ¥{cost:.2f}(¥2/M 未命中 · ¥0.2/M 命中 · ¥3/M 输出);"
1221
+ f"模型 {model},跨度 {span:.0f} 分钟。"
1222
+ )
1223
+ return "\n".join(lines)
1224
+
1225
+ async def sessions_text(self, conv_key: str) -> str:
1226
+ """Human-readable view of the current binding and the switchable Sessions."""
1227
+ try:
1228
+ data = await self.bridge.sessions()
1229
+ except BridgeError as error:
1230
+ return f"取会话列表失败:{error}"
1231
+ lines: List[str] = ["**当前 QQ 会话绑定**"]
1232
+ for key, session_id in data.get("bound") or []:
1233
+ mark = "(本会话)" if key == conv_key else ""
1234
+ lines.append(f"· `{session_id}` ← {self.conv_label(key)}{mark}")
1235
+ for key, session_id in data.get("returns") or []:
1236
+ if key == conv_key:
1237
+ lines.append(f"**可切回**:`{session_id}`(发 /切回)")
1238
+ host = data.get("host") or {}
1239
+ rows = host.get("sessions") or []
1240
+ if rows:
1241
+ lines.append(f"**DSH 会话**(来源 {host.get('source')})")
1242
+ for row in rows[:12]:
1243
+ title = (row.get("title") or "").strip()
1244
+ lines.append(f"· `{row.get('id')}` {title}".rstrip())
1245
+ elif host.get("source") == "unavailable":
1246
+ lines.append("(该 DSH 版本未暴露会话列表 API,可直接 /切会话 <session-id> 指定)")
1247
+ if host.get("error"):
1248
+ lines.append(f"(列表接口报错:{host['error']})")
1249
+ lines.append("用法:/切会话 <session-id> 切过去,/切回 回到原来的会话。")
1250
+ return "\n".join(lines)
1251
+
1252
+ async def handle_extra_command(self, conv_key: str, text: str, lowered: str, *, is_owner: bool = False) -> bool:
1253
+ """Shared /状态 /链接 /窗口 /撤回 handling; True when the message was a command."""
1254
+ head = lowered.split(" ", 1)[0]
1255
+ if not is_owner and (lowered in OWNER_ONLY_COMMANDS or head in OWNER_ONLY_COMMANDS):
1256
+ await self.send_text(conv_key, "这条指令只有主人能用。")
1257
+ return True
1258
+ if lowered in STATE_COMMANDS:
1259
+ await self.send_text(conv_key, await self.status_text(conv_key))
1260
+ return True
1261
+ if lowered in LINK_COMMANDS:
1262
+ await self.send_text(conv_key, f"机器人邀请链接:{await self.share_link()}")
1263
+ return True
1264
+ if lowered in WINDOW_COMMANDS and self.rt_bool("capture_enabled", True):
1265
+ ok, listing = await self._run_capture(["-List"])
1266
+ rows: List[str] = []
1267
+ for raw in listing.splitlines():
1268
+ parts = raw.split("\t")
1269
+ if len(parts) < 2:
1270
+ continue
1271
+ title = parts[1].strip()
1272
+ if not title:
1273
+ continue
1274
+ if len(title) > 34:
1275
+ title = title[:34] + "…"
1276
+ rows.append(f"{len(rows) + 1}. {title}")
1277
+ if len(rows) >= 20:
1278
+ break
1279
+ if rows:
1280
+ await self.send_text(conv_key, "当前可见窗口:\n" + "\n".join(rows))
1281
+ else:
1282
+ await self.send_text(conv_key, "没取到窗口列表")
1283
+ return True
1284
+ if lowered in MENU_COMMANDS:
1285
+ await self.send_text(conv_key, self.menu_text(self.help_text()), keyboard=command_keyboard())
1286
+ return True
1287
+ if lowered.split(" ", 1)[0] in USAGE_COMMANDS:
1288
+ parts = text.split(maxsplit=1)
1289
+ scope = parts[1].strip().lower() if len(parts) > 1 else ""
1290
+ await self.send_text(conv_key, await self.usage_text(conv_key, scope))
1291
+ return True
1292
+ if lowered in SESSION_COMMANDS:
1293
+ await self.send_text(conv_key, await self.sessions_text(conv_key))
1294
+ return True
1295
+ if lowered in BACK_COMMANDS:
1296
+ try:
1297
+ result = await self.bridge.switch_session(conv_key, "")
1298
+ except BridgeError as error:
1299
+ await self.send_text(conv_key, f"切回失败:{error}")
1300
+ return True
1301
+ await self.send_text(conv_key, f"已切回 `{result.get('sessionId')}`,消息重新进原会话。")
1302
+ return True
1303
+ if lowered.split(" ", 1)[0] in SWITCH_COMMANDS:
1304
+ parts = text.split(maxsplit=1)
1305
+ target = parts[1].strip() if len(parts) > 1 else ""
1306
+ if not target:
1307
+ await self.send_text(conv_key, "用法:/切会话 <session-id>\n先发 /会话 看有哪些可选。")
1308
+ return True
1309
+ try:
1310
+ result = await self.bridge.switch_session(conv_key, target)
1311
+ except BridgeError as error:
1312
+ await self.send_text(conv_key, f"切换失败:{error}")
1313
+ return True
1314
+ await self.send_text(
1315
+ conv_key,
1316
+ f"已切到 `{result.get('sessionId')}`;从现在起消息都进这个会话,\n要继续原来的工作发 /切回。",
1317
+ )
1318
+ return True
1319
+ if lowered.split(" ", 1)[0] in RECALL_COMMANDS:
1320
+ if not is_owner:
1321
+ await self.send_text(conv_key, "撤回只有主人能用。")
1322
+ return True
1323
+ await self._recall_command(conv_key, text)
1324
+ return True
1325
+ if lowered.split(" ", 1)[0] in POOL_COMMANDS:
1326
+ await self.send_text(conv_key, self._pool_text(conv_key))
1327
+ return True
1328
+ if (lowered in SHOT_COMMANDS or lowered.split(" ", 1)[0] in SHOT_COMMANDS) and self.rt_bool("capture_enabled", True):
1329
+ parts = text.split(maxsplit=1)
1330
+ wanted = parts[1].strip() if len(parts) > 1 else ""
1331
+ ok, detail = await self.capture_shot(wanted)
1332
+ if ok:
1333
+ await self.send_shot(conv_key, detail, f"📸 {wanted or '全屏'} · {Path(detail).name}")
1334
+ else:
1335
+ await self.send_text(conv_key, f"截图失败:{detail}")
1336
+ return True
1337
+ return False
1338
+
1339
+ async def _run_capture(self, args: List[str], out: Optional[str] = None) -> Tuple[bool, str]:
1340
+ """Run tools/window-capture.ps1 and return (ok, captured path or message)."""
1341
+ command = [
1342
+ "powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass",
1343
+ "-File", str(CAPTURE_SCRIPT), *args,
1344
+ ]
1345
+ if out is not None:
1346
+ command += ["-Out", out]
1347
+ try:
1348
+ process = await asyncio.create_subprocess_exec(
1349
+ *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
1350
+ )
1351
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=45)
1352
+ except (OSError, asyncio.TimeoutError) as error:
1353
+ return False, f"截屏失败:{error}"
1354
+ text = (stdout or b"").decode("utf-8", "replace")
1355
+ detail = (stderr or b"").decode("utf-8", "replace").strip()
1356
+ for line in text.splitlines():
1357
+ if line.startswith("CAPTURED "):
1358
+ return True, line[len("CAPTURED "):].strip()
1359
+ return False, (detail or text).strip()[:300] or "截屏失败(没有输出)"
1360
+
1361
+ async def capture_shot(self, target: str) -> Tuple[bool, str]:
1362
+ """Capture the screen (or a window matching `target`) into shots/."""
1363
+ SHOT_DIR.mkdir(parents=True, exist_ok=True)
1364
+ name = f"shot-{time.strftime('%Y%m%d-%H%M%S')}.png"
1365
+ out = str(SHOT_DIR / name)
1366
+ wanted = target.strip()
1367
+ if wanted in {"", "全屏", "screen", "桌面"}:
1368
+ return await self._run_capture(["-FullScreen"], out)
1369
+ if wanted in {"前台", "foreground"}:
1370
+ return await self._run_capture(["-Foreground"], out)
1371
+ if wanted.isdigit():
1372
+ # /截图 9 = /窗口 列表里的第 9 个(用完整标题,不用展示用的截断标题)
1373
+ full = await self._window_title_by_index(int(wanted))
1374
+ if full is None:
1375
+ return False, f"没有第 {wanted} 个窗口(先发 /窗口 看列表)"
1376
+ wanted = full
1377
+ return await self._run_capture(["-Title", wanted], out)
1378
+
1379
+ async def _window_title_by_index(self, index: int) -> Optional[str]:
1380
+ """Full title of the index-th visible window (1-based), as listed by -List."""
1381
+ ok, listing = await self._run_capture(["-List"])
1382
+ if not ok:
1383
+ return None
1384
+ titles = []
1385
+ for raw in listing.splitlines():
1386
+ parts = raw.split("\t")
1387
+ if len(parts) < 2:
1388
+ continue
1389
+ title = parts[1].strip()
1390
+ if title:
1391
+ titles.append(title)
1392
+ if index < 1 or index > len(titles):
1393
+ return None
1394
+ return titles[index - 1]
1395
+
1396
+ async def send_shot(self, conv_key: str, path: str, caption: str = "") -> bool:
1397
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
1398
+ if target is None:
1399
+ return False
1400
+ self.targets.setdefault(conv_key, target)
1401
+ if caption:
1402
+ await self.send_text(conv_key, caption)
1403
+ return await self._send_file(target, path)
1404
+
1405
+ async def share_link(self) -> str:
1406
+ """平台生成的机器人分享/邀请链接(群主用它把机器人加进群)。"""
1407
+ try:
1408
+ payload = await self.api.create_url_link("qqbridge")
1409
+ except Exception as error: # noqa: BLE001
1410
+ log.warning("create_url_link failed: %s", error)
1411
+ return f"取链接失败:{error}"
1412
+ url = ""
1413
+ if isinstance(payload, dict):
1414
+ data = payload.get("data")
1415
+ if isinstance(data, dict):
1416
+ url = str(data.get("url") or "")
1417
+ url = url or str(payload.get("url") or "")
1418
+ return url or f"平台没返回链接:{json.dumps(payload, ensure_ascii=False)[:200]}"
1419
+
1420
+ async def _collect_images(
1421
+ self, attachments: Optional[List[Dict[str, Any]]]
1422
+ ) -> Tuple[List[Dict[str, str]], int]:
1423
+ """Download up to four QQ image attachments; returns (images, skipped)."""
1424
+ images: List[Dict[str, str]] = []
1425
+ skipped = 0
1426
+ for attachment in list(attachments or [])[:4]:
1427
+ url = attachment.get("url")
1428
+ if not url:
1429
+ skipped += 1
1430
+ continue
1431
+ image = await download_image(
1432
+ str(url),
1433
+ max_bytes=int(self.rt_float("image_max_mb", self.config.image_max_mb) * 1024 * 1024),
1434
+ dump_dir=str(SHOT_DIR / "incoming"),
1435
+ )
1436
+ if image is None:
1437
+ skipped += 1
1438
+ log.warning("image skipped (unreadable): %s", attachment.get("content_type"))
1439
+ continue
1440
+ images.append(image)
1441
+ return images, skipped
1442
+
1443
+ # -- sending ------------------------------------------------------------ #
1444
+ async def send_text(self, conv_key: str, text: str, *, keyboard: Optional[Dict[str, Any]] = None) -> None:
1445
+ """Send text to one conversation, chunked and within QQ's reply limits."""
1446
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
1447
+ if target is None:
1448
+ log.warning("cannot answer unknown conversation %r", conv_key)
1449
+ return
1450
+ if not looks_like_openid(target.openid):
1451
+ log.warning("skipping synthetic conversation %r", conv_key)
1452
+ return
1453
+ self.targets.setdefault(conv_key, target)
1454
+ if not self.rt_bool("enabled", True):
1455
+ log.info("master switch off; dropping reply to %s", conv_key)
1456
+ return
1457
+ if target.kind == "group" and not self.rt_bool("group_enabled", True):
1458
+ return
1459
+ if target.kind == "c2c" and not self.rt_bool("c2c_enabled", True):
1460
+ return
1461
+ if self._rate_limited(conv_key):
1462
+ return
1463
+ self._count_send(conv_key)
1464
+ now = time.time()
1465
+ last = self._last_sent.get(conv_key)
1466
+ if last is not None and last[0] == text and now - last[1] < 15:
1467
+ log.warning("skip duplicate send to %s (same text within %.0fs)", conv_key, now - last[1])
1468
+ return
1469
+ self._last_sent[conv_key] = (text, now)
1470
+ for index, chunk in enumerate(chunk_text(text, self.rt_int("max_chars", self.config.max_chars))):
1471
+ await self._send_chunk(target, chunk, keyboard=keyboard if index == 0 else None)
1472
+
1473
+ async def _post(
1474
+ self,
1475
+ target: Target,
1476
+ chunk: str,
1477
+ *,
1478
+ keyboard: Optional[Dict[str, Any]],
1479
+ msg_id: Optional[str],
1480
+ markdown: bool,
1481
+ ) -> Any:
1482
+ self._msg_seq += 1
1483
+ payload: Dict[str, Any] = {"msg_seq": self._msg_seq}
1484
+ if msg_id:
1485
+ payload["msg_id"] = msg_id
1486
+ if keyboard is not None:
1487
+ payload["keyboard"] = keyboard
1488
+ if markdown:
1489
+ payload["msg_type"] = 2
1490
+ payload["markdown"] = {"content": chunk}
1491
+ else:
1492
+ payload["msg_type"] = 0
1493
+ payload["content"] = chunk
1494
+ if target.kind == "group":
1495
+ result = await self.api.post_group_message(group_openid=target.openid, **payload)
1496
+ else:
1497
+ result = await self.api.post_c2c_message(openid=target.openid, **payload)
1498
+ self._pool_sent(target, result, chunk)
1499
+ self._note_bot_say(target.conv_key, chunk)
1500
+ return result
1501
+
1502
+ def _display_name(self, conv_key: str, member_openid: str) -> str:
1503
+ """How the model should see a group member: nickname when known, else 群友+短号."""
1504
+ tail = short_id(member_openid).upper()
1505
+ name = getattr(self, "_member_names", {}).get(conv_key, {}).get(tail, "")
1506
+ if name:
1507
+ return name
1508
+ try:
1509
+ saved = json.loads(MEMBERS_FILE.read_text(encoding="utf-8"))
1510
+ name = str(((saved.get(conv_key) or {}).get(tail) or {}).get("name") or "")
1511
+ except (OSError, ValueError):
1512
+ name = ""
1513
+ return name or ("群友" + tail)
1514
+
1515
+ def _seed_members(self) -> None:
1516
+ """Restore the member index from disk so a restart never forgets who spoke."""
1517
+ try:
1518
+ saved = json.loads(MEMBERS_FILE.read_text(encoding="utf-8"))
1519
+ except (OSError, ValueError):
1520
+ return
1521
+ if not isinstance(saved, dict):
1522
+ return
1523
+ names = getattr(self, "_member_names", None) or {}
1524
+ restored = 0
1525
+ for conv_key, items in saved.items():
1526
+ if not isinstance(items, dict):
1527
+ continue
1528
+ bucket = self.member_index.setdefault(str(conv_key), {})
1529
+ for tail, info in items.items():
1530
+ if not isinstance(info, dict):
1531
+ continue
1532
+ openid = str(info.get("openid") or "")
1533
+ if not re.fullmatch(r"[0-9A-Fa-f]{32}", openid):
1534
+ continue
1535
+ key = str(tail).upper()
1536
+ bucket[key] = openid
1537
+ name = str(info.get("name") or "")
1538
+ if name:
1539
+ names.setdefault(str(conv_key), {})[key] = name
1540
+ restored += 1
1541
+ self._member_names = names
1542
+ log.info("member index restored: %d members in %d conversation(s)", restored, len(self.member_index))
1543
+
1544
+ def _persist_members(self) -> None:
1545
+ """Merge the in-memory index into state/members.json — every conversation, never just one."""
1546
+ try:
1547
+ saved = json.loads(MEMBERS_FILE.read_text(encoding="utf-8")) if MEMBERS_FILE.exists() else {}
1548
+ except (OSError, ValueError):
1549
+ saved = {}
1550
+ payload: Dict[str, Dict[str, Any]] = {}
1551
+ if isinstance(saved, dict):
1552
+ for conv_key, items in saved.items():
1553
+ if isinstance(items, dict):
1554
+ payload[str(conv_key)] = {
1555
+ str(tail).upper(): dict(info)
1556
+ for tail, info in items.items()
1557
+ if isinstance(info, dict)
1558
+ }
1559
+ stamp = time.strftime("%Y-%m-%d %H:%M:%S")
1560
+ appid = getattr(self.config, "appid", "")
1561
+ for conv_key, items in self.member_index.items():
1562
+ bucket = payload.setdefault(conv_key, {})
1563
+ for tail, openid in items.items():
1564
+ old = bucket.get(tail) or {}
1565
+ name = (getattr(self, "_member_names", {}).get(conv_key, {}) or {}).get(tail) or old.get("name") or ""
1566
+ bucket[tail] = {
1567
+ "openid": openid,
1568
+ "name": name,
1569
+ "avatar": old.get("avatar")
1570
+ or (f"https://q.qlogo.cn/qqapp/{appid}/{openid}/640" if appid else ""),
1571
+ "last_seen": stamp,
1572
+ }
1573
+ try:
1574
+ MEMBERS_FILE.parent.mkdir(parents=True, exist_ok=True)
1575
+ MEMBERS_FILE.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
1576
+ except OSError as error:
1577
+ log.warning("member index persist failed: %s", error)
1578
+
1579
+ def _remember_member(self, conv_key: str, member_openid: str, nickname: str = "") -> None:
1580
+ """Index speakers (tail6 -> openid + nickname) and mirror the whole index to disk."""
1581
+ if not member_openid:
1582
+ return
1583
+ if not re.fullmatch(r"[0-9A-Fa-f]{32}", str(member_openid)):
1584
+ # 只认真实的 openid:测试桩/脏数据不允许污染 state/members.json
1585
+ return
1586
+ tail = short_id(member_openid).upper()
1587
+ self.member_index.setdefault(conv_key, {})[tail] = member_openid
1588
+ names = getattr(self, "_member_names", None)
1589
+ if names is None:
1590
+ names = self._member_names = {}
1591
+ bucket = names.setdefault(conv_key, {})
1592
+ if nickname:
1593
+ bucket[tail] = str(nickname)[:40]
1594
+ elif tail not in bucket:
1595
+ bucket[tail] = ""
1596
+ self._persist_members()
1597
+
1598
+ def _readable_at(self, text: str, target: Optional[Target] = None) -> str:
1599
+ """Per QQ docs: 群聊 @人用 <qqbot-at-user id="member_openid"/>,仅 markdown 消息支持。"""
1600
+ if not text:
1601
+ return text
1602
+ text = text.replace("@全体", AT_EVERYONE_TOKEN).replace("@everyone", AT_EVERYONE_TOKEN)
1603
+
1604
+ def alias(text_in: str) -> str:
1605
+ return OPENID_RE.sub(lambda match: "@群友" + match.group(1)[-6:].upper(), text_in)
1606
+
1607
+ if target is None or target.kind != "group":
1608
+ return alias(text)
1609
+ known = self.member_index.get(target.conv_key) or {}
1610
+ if not known:
1611
+ return alias(text)
1612
+
1613
+ def replace_guard(match: "_re.Match[str]") -> str:
1614
+ key = match.group(1).upper()
1615
+ openid = known.get(key)
1616
+ return f'<qqbot-at-user id="{openid}" />' if openid else match.group(0)
1617
+
1618
+ return _AT_ALIAS_RE.sub(replace_guard, alias(text))
1619
+
1620
+ async def _send_chunk(self, target: Target, chunk: str, *, keyboard: Optional[Dict[str, Any]]) -> None:
1621
+ # QQ renders 按钮 only under a Markdown message (msg_type=2) for group/
1622
+ # C2C chats, so a keyboard forces the markdown path.
1623
+ chunk = self._readable_at(chunk, target)
1624
+ md_auto = self.rt_bool("md_auto", self.config.md_auto)
1625
+ # @ 标签只有 markdown 消息支持(QQ 文档:文本交互 → 使用 @ 能力)
1626
+ wants_at = "<qqbot-at-" in chunk
1627
+ use_markdown = keyboard is not None or wants_at or (md_auto and looks_like_markdown(chunk))
1628
+ msg_id = target.passive_slot()
1629
+ try:
1630
+ await self._post(target, chunk, keyboard=keyboard, msg_id=msg_id, markdown=use_markdown)
1631
+ log.info(
1632
+ "sent %s (%d chars, %s) to %s",
1633
+ "markdown" if use_markdown else "text",
1634
+ len(chunk),
1635
+ "passive" if msg_id else "proactive",
1636
+ target.conv_key,
1637
+ )
1638
+ return
1639
+ except Exception as error: # noqa: BLE001 - platform rejects many optional fields
1640
+ log.warning("send failed (%s): %s", type(error).__name__, error)
1641
+ if target.kind == "group":
1642
+ state = self.group_state.get(target.openid) or {}
1643
+ if state.get("allow_proactive_msg") is False:
1644
+ log.warning("skip proactive message: group %s does not allow it", target.conv_key)
1645
+ return
1646
+ try:
1647
+ await self._post(target, chunk, keyboard=None, msg_id=None, markdown=False)
1648
+ except Exception as error: # noqa: BLE001 - nothing left to try
1649
+ log.error("proactive plain send failed (%s): %s", type(error).__name__, error)
1650
+
1651
+ # -- outbound files ----------------------------------------------------- #
1652
+ def _allowed_file(self, path: str) -> Optional[str]:
1653
+ """Absolute path when it exists inside an allowed root, else None."""
1654
+ try:
1655
+ resolved = Path(path).expanduser().resolve(strict=True)
1656
+ except (OSError, RuntimeError):
1657
+ return None
1658
+ if not resolved.is_file():
1659
+ # 目录被当成文件上传时会抛 Errno 13(Permission denied),这里提前挡住
1660
+ return None
1661
+ roots = list(self.config.send_file_roots)
1662
+ # 自动分区工作区默认在别的盘(如 D:\dsh-qqbot-temp),必须一并放行,
1663
+ # 否则模型写在那里的图/文件会被"outside SEND_FILE_ROOTS"挡掉。
1664
+ extra = self.rt_str("auto_group_root", "").strip()
1665
+ if extra:
1666
+ roots.append(extra)
1667
+ for root in roots:
1668
+ try:
1669
+ resolved.relative_to(Path(root).resolve())
1670
+ except (OSError, ValueError):
1671
+ continue
1672
+ return str(resolved)
1673
+ return None
1674
+
1675
+ def sticker_names(self) -> List[str]:
1676
+ """Available sticker file stems, for the prompt hint and lookup."""
1677
+ try:
1678
+ return sorted(
1679
+ path.stem
1680
+ for path in STICKER_DIR.iterdir()
1681
+ if path.suffix.lower() in {".png", ".gif", ".jpg", ".jpeg", ".webp"}
1682
+ )
1683
+ except OSError:
1684
+ return []
1685
+
1686
+ def resolve_sticker(self, name: str) -> Optional[str]:
1687
+ wanted = name.strip().lower()
1688
+ for suffix in (".png", ".gif", ".jpg", ".jpeg", ".webp"):
1689
+ if wanted.endswith(suffix):
1690
+ wanted = wanted[: -len(suffix)]
1691
+ break
1692
+ for stem in self.sticker_names():
1693
+ if stem.lower() == wanted:
1694
+ for suffix in (".png", ".gif", ".jpg", ".jpeg", ".webp"):
1695
+ candidate = STICKER_DIR / f"{stem}{suffix}"
1696
+ if candidate.exists():
1697
+ return str(candidate)
1698
+ return None
1699
+
1700
+ def _persist_streams(self) -> None:
1701
+ """Remember open streams across restarts so a new process can close them."""
1702
+ try:
1703
+ payload = {
1704
+ conv: {k: s.get(k) for k in ("index", "msg_seq", "event_id", "stream_msg_id", "text")}
1705
+ for conv, s in self._streams.items()
1706
+ if s.get("stream_msg_id")
1707
+ }
1708
+ STREAMS_FILE.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
1709
+ except OSError as error:
1710
+ log.debug("stream state persist failed: %s", error)
1711
+
1712
+ async def _close_stale_streams(self) -> None:
1713
+ """严格闭合:上个进程留下的流必须先关掉,否则新流会撞上“其它流式消息发送中”。"""
1714
+ try:
1715
+ stale = json.loads(STREAMS_FILE.read_text(encoding="utf-8")) if STREAMS_FILE.exists() else {}
1716
+ except (OSError, ValueError):
1717
+ stale = {}
1718
+ for conv_key, saved in list(stale.items()):
1719
+ if conv_key in self._streams or not saved.get("stream_msg_id"):
1720
+ continue
1721
+ self._streams[conv_key] = {**saved, "sent_text": saved.get("text", ""), "sent": 0, "last": 0.0, "turn_id": ""}
1722
+ log.info("closing stale stream left by a previous process (%s)", conv_key)
1723
+ await self._finish_stream(conv_key)
1724
+ if STREAMS_FILE.exists():
1725
+ try:
1726
+ STREAMS_FILE.unlink()
1727
+ except OSError:
1728
+ pass
1729
+
1730
+ async def _finish_stream(self, conv_key: str) -> None:
1731
+ """Close an open streaming message so media never truncates it mid-frame."""
1732
+ state = self._streams.pop(conv_key, None)
1733
+ self._persist_streams()
1734
+ if state is None or int(state.get("index", 0)) == 0:
1735
+ return
1736
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
1737
+ if target is None or not state.get("stream_msg_id"):
1738
+ return
1739
+ payload = {
1740
+ "input_mode": "replace",
1741
+ "input_state": 10,
1742
+ "content_type": "markdown",
1743
+ # 空内容收尾会被客户端显示成"该消息类型暂不支持查看",给个占位
1744
+ "content_raw": STICKER_MARK.sub("", SEND_FILE_MARK.sub("", str(state.get("text") or ""))).strip() or "📎 文件在下面",
1745
+ "event_id": state.get("event_id") or target.last_msg_id or "",
1746
+ "msg_seq": state.get("msg_seq", 1),
1747
+ "index": int(state.get("index", 0)),
1748
+ "stream_msg_id": state["stream_msg_id"],
1749
+ }
1750
+ http = getattr(self.api, "_http", None)
1751
+ previous = getattr(http, "base_url", None)
1752
+ try:
1753
+ if previous:
1754
+ http.base_url = SG_GROUP_BASE_URL
1755
+ await self.api.post_c2c_stream_message(openid=target.openid, **payload)
1756
+ except Exception as error: # noqa: BLE001 - never block media on a stream hiccup
1757
+ log.warning("stream finish failed (%s): %s", type(error).__name__, error)
1758
+ finally:
1759
+ if previous:
1760
+ http.base_url = previous
1761
+ self._persist_streams()
1762
+
1763
+ async def _send_file(self, target: Target, path: str) -> bool:
1764
+ """Upload one local file into the conversation as a QQ media message."""
1765
+ file_type = FILE_TYPES.get(Path(path).suffix.lower(), 4)
1766
+ try:
1767
+ if target.kind == "group":
1768
+ result = await self.api.upload_group_media(
1769
+ group_openid=target.openid, file_path=path, file_type=file_type, srv_send_msg=True
1770
+ )
1771
+ else:
1772
+ result = await self.api.upload_c2c_media(
1773
+ user_openid=target.openid, file_path=path, file_type=file_type, srv_send_msg=True
1774
+ )
1775
+ self._pool_sent(target, result, f"[文件] {Path(path).name}")
1776
+ except Exception as error: # noqa: BLE001 - platform rejects unsupported media
1777
+ log.warning("file send failed (%s, type=%s): %s", Path(path).name, file_type, error)
1778
+ return False
1779
+ self._bump("files_sent")
1780
+ self._bump("files_image" if file_type == 1 else "files_doc")
1781
+ self._timeline("file", Path(path).name)
1782
+ log.info("sent file %s (type=%s) to %s", Path(path).name, file_type, target.conv_key)
1783
+ return True
1784
+
1785
+ def _spawn_files(self, conv_key: str, text: str) -> None:
1786
+ """Send media off the pull loop.
1787
+
1788
+ The pull loop is the single reader of the bridge feed: a slow platform
1789
+ upload inside it froze every later event (DSH looked finished while QQ
1790
+ showed nothing). Uploads therefore run as background tasks.
1791
+ """
1792
+ if not (SEND_FILE_MARK.search(text) or STICKER_MARK.search(text)):
1793
+ return
1794
+
1795
+ async def runner() -> None:
1796
+ try:
1797
+ await self._dispatch_files(conv_key, text)
1798
+ except Exception as error: # noqa: BLE001 - never kill the loop
1799
+ log.exception("file dispatch failed: %s", error)
1800
+
1801
+ task = asyncio.create_task(runner())
1802
+ self._bg_tasks.add(task)
1803
+ task.add_done_callback(self._bg_tasks.discard)
1804
+
1805
+ async def _dispatch_files(self, conv_key: str, text: str) -> str:
1806
+ """Send [[send_file: path]] / [[sticker: name]] payloads, return the rest."""
1807
+ problems: List[str] = []
1808
+ stickers = [match.strip() for match in STICKER_MARK.findall(text)]
1809
+ if stickers:
1810
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
1811
+ for name in stickers:
1812
+ resolved = self.resolve_sticker(name)
1813
+ if resolved is None:
1814
+ log.warning("unknown sticker %r (have %s)", name, ",".join(self.sticker_names()))
1815
+ problems.append(f"表情包「{name}」不存在")
1816
+ continue
1817
+ if target is not None:
1818
+ await self._send_file(target, resolved)
1819
+ text = STICKER_MARK.sub("", text).strip()
1820
+ if not text:
1821
+ return ""
1822
+ paths = [match.strip() for match in SEND_FILE_MARK.findall(text)]
1823
+ if not paths:
1824
+ return text
1825
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
1826
+ if target is None:
1827
+ return SEND_FILE_MARK.sub("", text).strip()
1828
+ for path in paths:
1829
+ allowed = self._allowed_file(path)
1830
+ if allowed is None:
1831
+ # 不再静默:路径不存在或不在允许目录,都要让对话里的人知道
1832
+ log.warning("refusing to send %s (outside SEND_FILE_ROOTS)", path)
1833
+ candidate = Path(path).expanduser()
1834
+ if not candidate.exists():
1835
+ reason = "文件不存在"
1836
+ elif candidate.is_dir():
1837
+ reason = "这是个目录,不是文件"
1838
+ else:
1839
+ reason = "路径不在允许目录内"
1840
+ problems.append(f"{candidate.name}:{reason}")
1841
+ continue
1842
+ sent = await self._send_file(target, allowed)
1843
+ if not sent:
1844
+ problems.append(f"{Path(allowed).name}:平台拒绝发送")
1845
+ if problems:
1846
+ await self.send_text(conv_key, "⚠ 有文件没发出去:" + ";".join(problems[:4]))
1847
+ return SEND_FILE_MARK.sub("", text).strip()
1848
+
1849
+ # -- ack watchdog ------------------------------------------------------- #
1850
+ def _arm_ack(self, conv_key: str) -> None:
1851
+ if not self.rt_bool("ack_enabled", False):
1852
+ return
1853
+ self._cancel_ack(conv_key)
1854
+ ack_delay = self.rt_float("ack_delay_s", self.config.ack_delay_s)
1855
+ if ack_delay <= 0 or not self.config.ack_text:
1856
+ return
1857
+
1858
+ async def later() -> None:
1859
+ try:
1860
+ await asyncio.sleep(ack_delay)
1861
+ except asyncio.CancelledError:
1862
+ return
1863
+ await self.send_text(conv_key, self.config.ack_text)
1864
+
1865
+ self._acks[conv_key] = asyncio.create_task(later())
1866
+
1867
+ def _cancel_ack(self, conv_key: str) -> None:
1868
+ task = self._acks.pop(conv_key, None)
1869
+ if task is not None and not task.done():
1870
+ task.cancel()
1871
+
1872
+ # -- DSH ---------------------------------------------------------------- #
1873
+ def _release_if_stuck(self, conv_key: str, *, force: bool = False) -> None:
1874
+ """A turn that never returns must not silence the conversation forever.
1875
+
1876
+ Note: this must NOT depend on ack_enabled — the "还在处理" placeholder is
1877
+ optional, but the dead-man release is the only thing that unblocks a
1878
+ conversation whose turn/end event was lost (e.g. the bridge dropped).
1879
+ """
1880
+ if self._inflight.get(conv_key, 0) <= 0:
1881
+ return
1882
+ started = self._inflight_at.get(conv_key, 0.0)
1883
+ waited = time.time() - started if started > 0 else 0.0
1884
+ if not force and waited < self.rt_float("stuck_turn_s", self.config.stuck_turn_s):
1885
+ return
1886
+ log.warning("turn in %s stuck for %.0fs; releasing the queue", conv_key, waited)
1887
+ self._inflight[conv_key] = 0
1888
+ self._inflight_at.pop(conv_key, None)
1889
+ if conv_key in self.queued:
1890
+ asyncio.create_task(self._drain_queued(conv_key))
1891
+
1892
+ def _message_idx(self, message):
1893
+ """The msg_idx QQ assigned to this very message (needed to resolve quotes)."""
1894
+ raw = getattr(message, "raw", None) or {}
1895
+ scene = raw.get("message_scene") if isinstance(raw, dict) else None
1896
+ return _scene_ext(scene).get("msg_idx", "")
1897
+
1898
+ async def _quote_images(self, quote: Optional[Dict[str, Any]]) -> List[Dict[str, str]]:
1899
+ """Download the quoted image(s) so the model can actually see them."""
1900
+ if not quote or quote.get("kind") != "image":
1901
+ return []
1902
+ urls = [url for url in (quote.get("urls") or []) if isinstance(url, str) and url]
1903
+ if not urls:
1904
+ return []
1905
+ images, _skipped = await self._collect_images([{"url": url} for url in urls])
1906
+ return list(images)
1907
+
1908
+ def _quote_author(self, ref_idx):
1909
+ """Who wrote the quoted message: the bot itself, the owner, or a group member."""
1910
+ message_id = self.pool_idx.get(ref_idx, "")
1911
+ item = self.pool.get(message_id) if message_id else None
1912
+ if item is None or item.at < time.time() - self._pool_ttl():
1913
+ return "", False
1914
+ if item.outbound:
1915
+ return "你自己(机器人)", True
1916
+ return item.author or "群友", False
1917
+
1918
+ def _quote_of(self, message):
1919
+ """Body + author + kind of the quoted message.
1920
+
1921
+ QQ ships the quoted element in raw["msg_elements"] ({"content": ...,
1922
+ "message_type": 103, "msg_idx": ...}); the author is resolved from the
1923
+ recent pool by that msg_idx. Text is the only kind QQ always fills in,
1924
+ so media quotes degrade to a labelled placeholder instead of fiction.
1925
+ """
1926
+ if not self.rt_bool("quote_enabled", True):
1927
+ return None
1928
+ raw = getattr(message, "raw", None) or {}
1929
+ if not isinstance(raw, dict):
1930
+ return None
1931
+
1932
+ kind = "text"
1933
+ text = ""
1934
+ ref_idx = ""
1935
+ quote_urls = []
1936
+ elements = raw.get("msg_elements")
1937
+ if isinstance(elements, list):
1938
+ for element in elements:
1939
+ if not isinstance(element, dict):
1940
+ continue
1941
+ ref_idx = str(element.get("msg_idx") or "")
1942
+ content = element.get("content")
1943
+ if isinstance(content, str) and content.strip():
1944
+ text = content.strip()
1945
+ kind = "text"
1946
+ break
1947
+ name = element.get("file_name") or element.get("filename") or ""
1948
+ attachments = element.get("attachments")
1949
+ if isinstance(name, str) and name.strip():
1950
+ text = name.strip()
1951
+ kind = "file"
1952
+ break
1953
+ if isinstance(attachments, list) and attachments:
1954
+ text = ""
1955
+ kind = "image"
1956
+ urls = [_attachment_url(item) for item in attachments]
1957
+ quote_urls = [url for url in urls if url][:4]
1958
+ break
1959
+ single = _attachment_url(element)
1960
+ if single: # 有的版本把图片地址直接放在元素上
1961
+ text = ""
1962
+ kind = "image"
1963
+ quote_urls = [single]
1964
+ break
1965
+ if ref_idx:
1966
+ kind = "other"
1967
+ break
1968
+
1969
+ if self.rt_bool("quote_probe", False) and not text:
1970
+ reference = raw.get("message_reference")
1971
+ log.info("quote probe (c2c): keys=%s reference=%r",
1972
+ ",".join(sorted(raw.keys())) if isinstance(raw, dict) else "-",
1973
+ reference)
1974
+
1975
+ # Private chats carry the quote as message_reference instead of msg_elements.
1976
+ if kind == "text" and not text:
1977
+ reference = raw.get("message_reference")
1978
+ if isinstance(reference, dict):
1979
+ content = reference.get("content")
1980
+ ref_id = str(reference.get("message_id") or reference.get("id") or "")
1981
+ if isinstance(content, str) and content.strip():
1982
+ text = content.strip()
1983
+ if ref_id:
1984
+ item = self.pool.get(ref_id)
1985
+ if item is not None and item.at >= time.time() - self._pool_ttl():
1986
+ return {
1987
+ "ref_id": ref_id,
1988
+ "resolved": True,
1989
+ "author": "你自己(机器人)" if item.outbound else (item.author or "对方"),
1990
+ "text": text or item.text,
1991
+ "outbound": bool(item.outbound),
1992
+ "kind": "text",
1993
+ }
1994
+ if text:
1995
+ return {
1996
+ "ref_id": ref_id,
1997
+ "resolved": True,
1998
+ "author": "",
1999
+ "text": text,
2000
+ "outbound": False,
2001
+ "kind": "text",
2002
+ }
2003
+ elif text:
2004
+ return {"ref_id": "", "resolved": True, "author": "", "text": text, "outbound": False, "kind": "text"}
2005
+
2006
+ if kind == "text" and not text:
2007
+ flat = _scene_ext(raw.get("message_scene"))
2008
+ ref_idx = flat.get("ref_msg_idx", "") or ref_idx
2009
+ if not ref_idx:
2010
+ return None
2011
+ author, outbound = self._quote_author(ref_idx)
2012
+ message_id = self.pool_idx.get(ref_idx, "")
2013
+ item = self.pool.get(message_id) if message_id else None
2014
+ if item is None or item.at < time.time() - self._pool_ttl():
2015
+ return {"ref_id": ref_idx, "resolved": False, "author": author, "text": "", "kind": "text"}
2016
+ return {
2017
+ "ref_id": ref_idx,
2018
+ "resolved": True,
2019
+ "author": author,
2020
+ "text": item.text,
2021
+ "outbound": outbound,
2022
+ "kind": "text",
2023
+ }
2024
+
2025
+ if not ref_idx and kind == "text" and not text:
2026
+ return None
2027
+ if not ref_idx:
2028
+ return None
2029
+
2030
+ if self.rt_bool("quote_probe", False):
2031
+ log.info("quote element: kind=%s len=%d ref=%s", kind, len(text), short_id(ref_idx))
2032
+ author, outbound = self._quote_author(ref_idx)
2033
+ return {
2034
+ "ref_id": ref_idx,
2035
+ "resolved": True,
2036
+ "author": author,
2037
+ "text": text,
2038
+ "outbound": outbound,
2039
+ "kind": kind,
2040
+ "urls": list(quote_urls),
2041
+ }
2042
+
2043
+ def _merge_queued(self, conv_key: str, text: str, images: List[Dict[str, str]], sender_name: str, is_owner: bool, chime: bool, chat: bool = False) -> None:
2044
+ """One conversation runs one turn at a time; later messages wait here."""
2045
+ entry = self.queued.get(conv_key)
2046
+ if entry is None:
2047
+ entry = QueuedPrompt()
2048
+ self.queued[conv_key] = entry
2049
+ if text.strip():
2050
+ entry.parts.append(text)
2051
+ entry.images.extend(images)
2052
+ entry.sender_name = sender_name
2053
+ entry.is_owner = is_owner or entry.is_owner
2054
+ entry.chime = entry.chime and chime
2055
+ entry.chat = entry.chat and chat if entry.parts[:-1] else chat
2056
+ log.info("queued behind running turn in %s (%d part(s))", conv_key, len(entry.parts))
2057
+
2058
+ async def _drain_queued(self, conv_key: str) -> None:
2059
+ """Send the merged backlog once the running turn has finished."""
2060
+ entry = self.queued.pop(conv_key, None)
2061
+ if entry is None:
2062
+ return
2063
+ age = time.time() - entry.first_at
2064
+ if age > self.config.stale_prompt_s:
2065
+ log.info("dropping %.0fs-old backlog in %s to avoid a stale answer", age, conv_key)
2066
+ return
2067
+ text = "\n".join(part for part in entry.parts if part.strip())
2068
+ await self._submit(conv_key, text, entry.sender_name, entry.is_owner, entry.images, chime=entry.chime, chat=entry.chat)
2069
+
2070
+ async def _submit(
2071
+ self,
2072
+ conv_key: str,
2073
+ text: str,
2074
+ sender_name: str,
2075
+ is_owner: bool,
2076
+ images: Optional[List[Dict[str, str]]] = None,
2077
+ *,
2078
+ chime: bool = False,
2079
+ chat: bool = False,
2080
+ ) -> None:
2081
+ self._release_if_stuck(conv_key)
2082
+ if self._inflight.get(conv_key, 0) > 0 or conv_key in self.queued:
2083
+ self._merge_queued(conv_key, text, images or [], sender_name, is_owner, chime, chat)
2084
+ return
2085
+ quote = self._pending_quotes.pop(conv_key, None)
2086
+ recent = self.recent_images.pop(conv_key, None)
2087
+ if recent is not None and time.time() - recent[1] < self.rt_float("image_cache_s", 120) and not images:
2088
+ images = recent[0]
2089
+ stickers = self.sticker_names()
2090
+ if stickers and text.strip():
2091
+ # 全量列出:截断会让模型"看不见"新加的表情包,只能反复发它知道的那几个
2092
+ shown = stickers[:60]
2093
+ hint = ",".join(shown)
2094
+ if len(stickers) > len(shown):
2095
+ hint += f"…(共 {len(stickers)} 个)"
2096
+ text = text + "\n(想发个表情包时,单独一行写 [[sticker: 名字]],可选:" + hint + ")"
2097
+ if chat and text.strip():
2098
+ # 长度与"别复述过程"由插件侧的群聊指令负责,这里只补一条不重复的话
2099
+ text = "【闲聊模式】不要调用工具。" + chr(10) + text
2100
+ # 人设只在新会话的第一条消息里带一次,由插件按会话判断
2101
+ persona = ""
2102
+ if self.rt_bool("persona_enabled", False):
2103
+ slot = "persona_group" if conv_key.startswith("group:") else "persona_c2c"
2104
+ persona = self.rt_str(slot, "").strip()
2105
+ self._chat_turns[conv_key] = bool(chat)
2106
+ try:
2107
+ await self.bridge.inbound(
2108
+ conv_key=conv_key,
2109
+ text=text,
2110
+ sender_name=sender_name,
2111
+ is_owner=is_owner,
2112
+ approval_target=self._owner_conv(),
2113
+ images=images,
2114
+ chime=chime,
2115
+ quote=quote,
2116
+ auto_group=self.rt_bool("auto_group", True),
2117
+ auto_group_root=self.rt_str("auto_group_root", ""),
2118
+ persona=persona,
2119
+ )
2120
+ except BridgeError as error:
2121
+ log.error("inbound failed: %s", error)
2122
+ await self.send_text(conv_key, f"DSH 桥接不可用:{error}")
2123
+ return
2124
+ self._submitted_at[conv_key] = time.time()
2125
+ self._inflight[conv_key] = self._inflight.get(conv_key, 0) + 1
2126
+ self._inflight_at[conv_key] = time.time()
2127
+ if not chime:
2128
+ self._arm_ack(conv_key)
2129
+
2130
+ async def _buffer_context(self, conv_key: str, text: str, sender_name: str) -> None:
2131
+ """Disabled on purpose: replaying chatter into every prompt bloated the
2132
+ Session history until the model call 400'd. The judge batch carries the
2133
+ context instead, so nothing is forwarded here."""
2134
+ return
2135
+
2136
+ # -- debounce: several consecutive messages become one prompt ----------- #
2137
+ async def _queue_message(
2138
+ self,
2139
+ conv_key: str,
2140
+ text: str,
2141
+ sender_name: str,
2142
+ is_owner: bool,
2143
+ images: List[Dict[str, str]],
2144
+ *,
2145
+ chat: bool = False,
2146
+ quote: Optional[Dict[str, Any]] = None,
2147
+ ) -> None:
2148
+ if quote:
2149
+ self._pending_quotes[conv_key] = quote
2150
+ entry = self.pending.get(conv_key)
2151
+ if entry is None:
2152
+ entry = Pending()
2153
+ self.pending[conv_key] = entry
2154
+ if text.strip():
2155
+ entry.parts.append(text)
2156
+ entry.images.extend(images)
2157
+ entry.sender_name = sender_name
2158
+ entry.is_owner = is_owner
2159
+ entry.chat = entry.chat and chat if entry.parts[:-1] else chat
2160
+ if entry.job is not None and not entry.job.done():
2161
+ entry.job.cancel()
2162
+ entry.job = asyncio.create_task(self._flush(conv_key))
2163
+
2164
+ async def _flush(self, conv_key: str) -> None:
2165
+ entry = self.pending.get(conv_key)
2166
+ if entry is None:
2167
+ return
2168
+ wait = min(self.config.debounce_s, max(0.05, self.config.debounce_max_s - (time.time() - entry.started)))
2169
+ try:
2170
+ await asyncio.sleep(wait)
2171
+ except asyncio.CancelledError:
2172
+ return
2173
+ entry = self.pending.pop(conv_key, None)
2174
+ if entry is None:
2175
+ return
2176
+ text = "\n".join(part for part in entry.parts if part.strip())
2177
+ if not text and not entry.images:
2178
+ return
2179
+ await self._submit(conv_key, text, entry.sender_name, entry.is_owner, entry.images, chat=entry.chat)
2180
+
2181
+ # -- event feed --------------------------------------------------------- #
2182
+ def _load_cursor(self) -> Optional[int]:
2183
+ """Resume the bridge event feed where the previous process stopped.
2184
+
2185
+ Replies produced while the bot was restarting stay in the plugin's ring
2186
+ buffer, so reloading the cursor delivers them instead of dropping them.
2187
+ """
2188
+ try:
2189
+ return int(CURSOR_FILE.read_text(encoding="utf-8").strip())
2190
+ except (OSError, ValueError):
2191
+ return None
2192
+
2193
+ def _save_cursor(self, cursor: Optional[int]) -> None:
2194
+ if cursor is None:
2195
+ return
2196
+ try:
2197
+ CURSOR_FILE.parent.mkdir(parents=True, exist_ok=True)
2198
+ CURSOR_FILE.write_text(str(cursor), encoding="utf-8")
2199
+ except OSError:
2200
+ pass
2201
+
2202
+ METRIC_KEYS = (
2203
+ "c2c_msgs", "group_msgs", "group_at", "group_images", "quotes",
2204
+ "judge_calls", "judge_spoke", "judge_silent", "hook_skips",
2205
+ "judge_score0", "judge_score1", "judge_score2", "judge_score3",
2206
+ "streams", "stream_fallbacks", "files_image", "files_doc", "files_sent",
2207
+ "approvals", "approvals_allow", "approvals_deny",
2208
+ "questions", "questions_answered", "question_timeouts",
2209
+ "mutes", "unmutes", "kicks", "errors",
2210
+ )
2211
+
2212
+ def _bump(self, name: str, n: int = 1) -> None:
2213
+ """Cheap counters for the dashboard; never allowed to break a handler."""
2214
+ if not hasattr(self, "_metrics"):
2215
+ self._metrics = {key: 0 for key in self.METRIC_KEYS}
2216
+ self._metrics_at = 0.0
2217
+ self._metrics[name] = int(self._metrics.get(name, 0)) + n
2218
+ now = time.time()
2219
+ if n:
2220
+ bucket = int(now // 60) * 60
2221
+ series = getattr(self, "_series", None)
2222
+ if series is None:
2223
+ series = self._series = {}
2224
+ cell = series.setdefault(bucket, {})
2225
+ cell[name] = int(cell.get(name, 0)) + n
2226
+ cutoff = now - 180 * 60
2227
+ for stale in [key for key in series if key < cutoff]:
2228
+ series.pop(stale, None)
2229
+ self._archive_complete_minutes(now)
2230
+ if now - float(getattr(self, "_metrics_at", 0.0)) < 3.0:
2231
+ return
2232
+ self._metrics_at = now
2233
+ self._write_metrics()
2234
+
2235
+ def _write_metrics(self) -> None:
2236
+ """Persist counters/series/timeline; the file's started_at always tracks the live process."""
2237
+ try:
2238
+ METRICS_FILE.write_text(
2239
+ json.dumps(
2240
+ {
2241
+ "started_at": getattr(self, "_started_at", 0.0),
2242
+ **self._metrics,
2243
+ "series": getattr(self, "_series", {}),
2244
+ "events": getattr(self, "_events", []),
2245
+ "runtime": {
2246
+ "inflight": sum(int(v) for v in getattr(self, "_inflight", {}).values()),
2247
+ "queued": len(getattr(self, "queued", {}) or {}),
2248
+ "chatter": sum(len(getattr(entry, "lines", [])) for entry in (getattr(self, "chatter", {}) or {}).values()),
2249
+ },
2250
+ },
2251
+ ensure_ascii=False,
2252
+ ),
2253
+ encoding="utf-8",
2254
+ )
2255
+ except OSError:
2256
+ pass
2257
+
2258
+ def _read_recent_archive(self, now: float, window_s: float = 180 * 60) -> Dict[int, Dict[str, int]]:
2259
+ """Finished minutes from the per-day JSONL files inside the window."""
2260
+ rows: Dict[int, Dict[str, int]] = {}
2261
+ for offset in (0, 1): # 跨零点时补上前一天
2262
+ day = time.strftime("%Y-%m-%d", time.localtime(now - offset * 86400))
2263
+ path = METRICS_DIR / f"{day}.jsonl"
2264
+ if not path.exists():
2265
+ continue
2266
+ try:
2267
+ for line in path.read_text(encoding="utf-8").splitlines():
2268
+ if not line.strip():
2269
+ continue
2270
+ row = json.loads(line)
2271
+ bucket = int(row.pop("minute"))
2272
+ if now - bucket > window_s:
2273
+ continue
2274
+ rows[bucket] = {key: int(value) for key, value in row.items()}
2275
+ except (OSError, ValueError) as error:
2276
+ log.debug("metrics archive read failed (%s): %s", day, error)
2277
+ return rows
2278
+
2279
+ def _seed_metrics(self) -> None:
2280
+ """Everything except uptime is time-based: counters, per-minute series and the timeline all survive a restart."""
2281
+ try:
2282
+ saved = json.loads(METRICS_FILE.read_text(encoding="utf-8"))
2283
+ except (OSError, ValueError):
2284
+ saved = {}
2285
+ now = time.time()
2286
+ archived = self._read_recent_archive(now)
2287
+ totals: Dict[str, int] = {key: 0 for key in self.METRIC_KEYS}
2288
+ for cell in archived.values():
2289
+ for key, value in cell.items():
2290
+ if key in totals:
2291
+ totals[key] += value
2292
+ # metrics.json 是绝对总数,JSONL 是逐分钟明细;取较大值,免得被节流丢掉的最后几秒把总数拉低
2293
+ self._metrics = {
2294
+ key: max(int(saved.get(key, 0) or 0), totals.get(key, 0)) for key in self.METRIC_KEYS
2295
+ }
2296
+ self._metrics_at = 0.0
2297
+ series: Dict[int, Dict[str, int]] = dict(archived)
2298
+ saved_series = saved.get("series")
2299
+ if isinstance(saved_series, dict):
2300
+ for bucket, cell in saved_series.items():
2301
+ try:
2302
+ key = int(bucket)
2303
+ except (TypeError, ValueError):
2304
+ continue
2305
+ if now - key > 180 * 60 or not isinstance(cell, dict):
2306
+ continue
2307
+ series.setdefault(key, {name: int(value) for name, value in cell.items()})
2308
+ self._series = series
2309
+ self._archived = set(archived)
2310
+ events = saved.get("events")
2311
+ if isinstance(events, list):
2312
+ self._events = events[-20:]
2313
+ if saved.get("scale"):
2314
+ self._lifecycle = str(saved.get("scale"))
2315
+ self._write_metrics() # 启动即刷新 started_at,面板的运行时长不必等第一条消息
2316
+
2317
+ def _archive_complete_minutes(self, now: float) -> None:
2318
+ """Append each finished minute to a per-day JSONL so history outlives a restart."""
2319
+ series = getattr(self, "_series", None)
2320
+ if not series:
2321
+ return
2322
+ written = getattr(self, "_archived", None)
2323
+ if written is None:
2324
+ written = self._archived = set()
2325
+ current = int(now // 60) * 60
2326
+ try:
2327
+ METRICS_DIR.mkdir(parents=True, exist_ok=True)
2328
+ except OSError:
2329
+ return
2330
+ for bucket in sorted(series):
2331
+ if bucket >= current or bucket in written:
2332
+ continue
2333
+ cell = series[bucket]
2334
+ day = time.strftime("%Y-%m-%d", time.localtime(bucket))
2335
+ line = json.dumps({"minute": int(bucket), **{k: int(v) for k, v in cell.items()}}, ensure_ascii=False)
2336
+ try:
2337
+ with (METRICS_DIR / f"{day}.jsonl").open("a", encoding="utf-8") as handle:
2338
+ handle.write(line + chr(10))
2339
+ except OSError as error:
2340
+ log.debug("metrics archive failed: %s", error)
2341
+ continue
2342
+ written.add(bucket)
2343
+ if len(written) > 2000:
2344
+ self._archived = set(sorted(written)[-500:])
2345
+ self._prune_metrics(now)
2346
+
2347
+ def _prune_metrics(self, now: float) -> None:
2348
+ """Keep at most metrics_keep_days of archive; prune once per day."""
2349
+ keep_days = max(1, self.rt_int("metrics_keep_days", 30))
2350
+ last = float(getattr(self, "_pruned_at", 0.0))
2351
+ if now - last < 3600:
2352
+ return
2353
+ self._pruned_at = now
2354
+ cutoff = now - keep_days * 86400
2355
+ removed = 0
2356
+ try:
2357
+ for path in METRICS_DIR.glob("*.jsonl"):
2358
+ try:
2359
+ day_start = time.mktime(time.strptime(path.stem, "%Y-%m-%d"))
2360
+ except ValueError:
2361
+ continue
2362
+ if day_start < cutoff:
2363
+ path.unlink(missing_ok=True)
2364
+ removed += 1
2365
+ for path in LOG_DIR.glob("*.log.*"):
2366
+ try:
2367
+ if path.stat().st_mtime < cutoff:
2368
+ path.unlink(missing_ok=True)
2369
+ removed += 1
2370
+ except OSError:
2371
+ continue
2372
+ except OSError as error:
2373
+ log.debug("metrics prune failed: %s", error)
2374
+ return
2375
+ if removed:
2376
+ log.info("pruned %d old metric/log file(s) (keep %d days)", removed, keep_days)
2377
+
2378
+ def _timeline(self, kind: str, text: str) -> None:
2379
+ """Last few interesting things, for the dashboard timeline."""
2380
+ if not hasattr(self, "_events"):
2381
+ self._events = []
2382
+ self._events.append({"at": time.time(), "kind": kind, "text": str(text)[:120]})
2383
+ if len(self._events) > 20:
2384
+ self._events = self._events[-20:]
2385
+
2386
+ def _note_owner_activity(self, conv_key: str, is_owner: bool) -> None:
2387
+ """Group-admin tools are owner-only: remember who spoke last in this conversation."""
2388
+ if not hasattr(self, "_owner_recent"):
2389
+ self._owner_recent = {}
2390
+ self._owner_recent[conv_key] = time.time() if is_owner else 0.0
2391
+
2392
+ def _admin_allowed(self, payload: Dict[str, Any]) -> Tuple[bool, str]:
2393
+ """A tool call may act only when the owner is the one who just asked."""
2394
+ conv_key = str(payload.get("convKey") or "")
2395
+ group = str(payload.get("group") or "")
2396
+ if conv_key.startswith("c2c:"):
2397
+ return (conv_key == self._owner_conv(), "只有主人能使用群管理功能")
2398
+ if conv_key and conv_key != f"group:{group}":
2399
+ return (False, "会话与目标群不一致")
2400
+ last = getattr(self, "_owner_recent", {}).get(conv_key, 0.0)
2401
+ if last <= 0 or time.time() - last > self.rt_float("admin_owner_window_s", 300):
2402
+ return (False, "只有主人能使用群管理功能(最近没有主人的指令)")
2403
+ return (True, "")
2404
+
2405
+ async def _admin_loop(self) -> None:
2406
+ """Execute group-admin requests queued by the panel/tools (mute / kick / members)."""
2407
+ outbox = STATE_DIR / "admin"
2408
+ while True:
2409
+ try:
2410
+ if outbox.is_dir():
2411
+ for path in sorted(outbox.glob("*.json")):
2412
+ payload = {}
2413
+ try:
2414
+ payload = json.loads(path.read_text(encoding="utf-8"))
2415
+ except (OSError, ValueError):
2416
+ path.unlink(missing_ok=True)
2417
+ continue
2418
+ if payload.get("status") not in (None, "pending"):
2419
+ continue
2420
+ result = {"status": "done", "ok": False, "error": "unknown action"}
2421
+ try:
2422
+ action = str(payload.get("action") or "")
2423
+ if action in ("group", "muted", "member", "stats"):
2424
+ result = await self._info_action(action, payload)
2425
+ path.write_text(json.dumps({**payload, **result}, ensure_ascii=False), encoding="utf-8")
2426
+ continue
2427
+ allowed, why = self._admin_allowed(payload)
2428
+ if not allowed:
2429
+ log.warning("admin %s refused: %s", action, why)
2430
+ path.write_text(
2431
+ json.dumps({**payload, "status": "done", "ok": False, "error": why}, ensure_ascii=False),
2432
+ encoding="utf-8",
2433
+ )
2434
+ continue
2435
+ if (
2436
+ action == "kick"
2437
+ and not payload.get("confirmed")
2438
+ and self.rt_bool("kick_confirm", True)
2439
+ ):
2440
+ if not payload.get("id"):
2441
+ payload["id"] = uuid.uuid4().hex[:12]
2442
+ # 踢人不可逆:先到主人私聊要一次二次确认
2443
+ request_id = str(payload.get("id") or "")
2444
+ payload["_path"] = str(path)
2445
+ self._admin_confirm[request_id] = dict(payload)
2446
+ target_group = str(payload.get("group") or "")
2447
+ target_member = str(payload.get("member") or "")
2448
+ who = self._display_name(f"group:{target_group}", target_member)
2449
+ group_label = await self._group_name(target_group) or ("…" + target_group[-6:])
2450
+ await self.send_text(
2451
+ self._owner_conv(),
2452
+ "⚠ 请求踢人" + chr(10)
2453
+ + "群:" + group_label + chr(10)
2454
+ + "成员:" + who
2455
+ + ("" if not who.startswith("群友") else "(昵称未知,这是短号)") + chr(10)
2456
+ + "点下面的按钮确认,取消则不动。",
2457
+ keyboard=kick_confirm_keyboard(request_id),
2458
+ )
2459
+ path.write_text(
2460
+ json.dumps({**payload, "status": "waiting"}, ensure_ascii=False),
2461
+ encoding="utf-8",
2462
+ )
2463
+ continue
2464
+ group = str(payload.get("group") or "")
2465
+ member = str(payload.get("member") or "")
2466
+ if action == "mute" and group and member:
2467
+ raw_seconds = payload.get("seconds")
2468
+ # 注意:0 是「解禁」,不能被 or 600 吞成 10 分钟
2469
+ seconds = 600 if raw_seconds is None else int(raw_seconds)
2470
+ # 官方字段:op=add/del + mute_expire_at(RFC3339,带时区)
2471
+ entry: Dict[str, Any] = {"op": "add" if seconds > 0 else "del", "member_openid": member}
2472
+ if seconds > 0:
2473
+ expire = time.time() + seconds
2474
+ entry["mute_expire_at"] = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(expire)) + "+08:00"
2475
+ await self.api.set_group_restrict_chat_setting(group_openid=group, members=[entry])
2476
+ still_muted = None
2477
+ try:
2478
+ state_now = await self.api.get_group_restrict_chat_setting(group_openid=group)
2479
+ still_muted = any(
2480
+ str(item.get("member_openid")) == member
2481
+ for item in (state_now.get("members") or [])
2482
+ )
2483
+ except Exception as error: # noqa: BLE001 - state re-read is best effort
2484
+ log.warning("mute state re-read failed: %s", error)
2485
+ result = {
2486
+ "status": "done",
2487
+ "ok": True,
2488
+ "group_name": await self._group_name(group),
2489
+ "member_name": self._display_name(f"group:{group}", member),
2490
+ "seconds": seconds,
2491
+ "op": entry["op"],
2492
+ "still_muted": still_muted,
2493
+ }
2494
+ self._bump("unmutes" if entry["op"] == "del" else "mutes")
2495
+ self._timeline("admin", f'mute {entry["op"]} {seconds}s')
2496
+ elif action == "kick" and group and member:
2497
+ await self.api.batch_remove_group_members(
2498
+ group_openid=group,
2499
+ member_openids=[member],
2500
+ add_to_member_blacklist=bool(payload.get("blacklist")),
2501
+ )
2502
+ result = {"status": "done", "ok": True}
2503
+ self._bump("kicks")
2504
+ self._timeline("admin", "kick")
2505
+ elif action == "mute_state" and group:
2506
+ state = await self.api.get_group_restrict_chat_setting(group_openid=group)
2507
+ result = {"status": "done", "ok": True, "state": state}
2508
+ elif action == "members":
2509
+ result = {"status": "done", "ok": True, "members": payload.get("known") or {}}
2510
+ except Exception as error: # noqa: BLE001 - report the platform message verbatim
2511
+ self._bump("errors")
2512
+ result = {"status": "done", "ok": False, "error": str(error)}
2513
+ try:
2514
+ path.write_text(json.dumps({**payload, **result}, ensure_ascii=False), encoding="utf-8")
2515
+ except OSError:
2516
+ pass
2517
+ log.info("admin %s -> %s", payload.get("action"), "ok" if result.get("ok") else result.get("error"))
2518
+ except Exception as error: # noqa: BLE001
2519
+ log.warning("admin loop error: %s", error)
2520
+ await asyncio.sleep(0.8)
2521
+
2522
+ async def _question_loop(self) -> None:
2523
+ """Poll the file outbox the panel writes; render each dsh question as a keyboard."""
2524
+ outbox = STATE_DIR / "questions"
2525
+ while True:
2526
+ try:
2527
+ if outbox.is_dir():
2528
+ for path in sorted(outbox.glob("*.json")):
2529
+ try:
2530
+ payload = json.loads(path.read_text(encoding="utf-8"))
2531
+ except (OSError, ValueError):
2532
+ path.unlink(missing_ok=True)
2533
+ continue
2534
+ conv_key = str(payload.get("convKey") or "")
2535
+ question_id = str(payload.get("id") or "")
2536
+ text = str(payload.get("question") or "")
2537
+ options = [str(item) for item in (payload.get("options") or [])]
2538
+ if conv_key and question_id and options:
2539
+ body = "**需要你确认**" + chr(10) + chr(10) + text + chr(10) + chr(10)
2540
+ body += chr(10).join(f"{i + 1}. {label}" for i, label in enumerate(options))
2541
+ self._bump("questions")
2542
+ self._timeline("question", question_id[:8])
2543
+ await self.send_text(conv_key, body, keyboard=question_keyboard(question_id, options))
2544
+ log.info("question %s delivered to %s", short_id(question_id), conv_key)
2545
+ path.unlink(missing_ok=True)
2546
+ except Exception as error: # noqa: BLE001 - never let the watcher die
2547
+ log.warning("question loop error: %s", error)
2548
+ await asyncio.sleep(1.0)
2549
+
2550
+ async def _pull_loop(self) -> None:
2551
+ cursor = self._load_cursor()
2552
+ if cursor is not None:
2553
+ log.info("resuming bridge feed from cursor %s", cursor)
2554
+ while True:
2555
+ _heartbeat()
2556
+ try:
2557
+ result = await asyncio.wait_for(
2558
+ self.bridge.pull(cursor, self.config.pull_wait_ms),
2559
+ timeout=(self.config.pull_wait_ms / 1000.0) + 20,
2560
+ )
2561
+ head = result.get("cursor", cursor)
2562
+ events = result.get("events") or []
2563
+ if isinstance(head, int) and isinstance(cursor, int) and head < cursor:
2564
+ # The plugin reloaded and its sequence restarted: everything in
2565
+ # this response belongs to the old ring buffer, so jumping to
2566
+ # the new head avoids re-sending replies that already went out.
2567
+ log.warning("bridge sequence reset (%s -> %s); skipping backlog", cursor, head)
2568
+ cursor = head
2569
+ self._save_cursor(cursor)
2570
+ continue
2571
+ cursor = head
2572
+ self._save_cursor(cursor)
2573
+ _heartbeat()
2574
+ for event in events:
2575
+ if event.get("type") in URGENT_EVENTS:
2576
+ # Approvals must never queue behind a slow reply send: a
2577
+ # stuck turn used to swallow the whole approval card.
2578
+ task = asyncio.create_task(self._handle_urgent(event))
2579
+ self._urgent_tasks.add(task)
2580
+ task.add_done_callback(self._urgent_tasks.discard)
2581
+ continue
2582
+ self._pull_failures = 0
2583
+ await self._handle_event(event)
2584
+ except asyncio.CancelledError:
2585
+ log.warning("pull loop cancelled; watchdog will restart it")
2586
+ return
2587
+ except BridgeError as error:
2588
+ self._pull_failures = getattr(self, "_pull_failures", 0) + 1
2589
+ log.warning("bridge pull failed (%d in a row): %s", self._pull_failures, error)
2590
+ if self._pull_failures >= 3:
2591
+ # 桥接掉线期间丢掉的 turn/end 会让会话永远"忙",这里强制解锁
2592
+ for key in list(self._inflight):
2593
+ self._release_if_stuck(key, force=True)
2594
+ self._pull_failures = 0
2595
+ await asyncio.sleep(3)
2596
+ except Exception as error: # noqa: BLE001 - keep the feed alive
2597
+ self._bump("errors")
2598
+ log.exception("pull loop error: %s", error)
2599
+ await asyncio.sleep(3)
2600
+
2601
+ async def _pull_watchdog(self) -> None:
2602
+ """Keep the event feed alive: restart it whenever the task dies."""
2603
+ while True:
2604
+ await asyncio.sleep(10)
2605
+ task = getattr(self, "_pull_task", None)
2606
+ if task is None or task.done():
2607
+ reason = "missing" if task is None else ("cancelled" if task.cancelled() else str(task.exception()))
2608
+ log.warning("pull loop down (%s); restarting", reason)
2609
+ self._pull_task = asyncio.create_task(self._pull_loop())
2610
+
2611
+ async def _handle_urgent(self, event: Dict[str, Any]) -> None:
2612
+ """Deliver an approval/notice out of band; one failure must not kill the feed."""
2613
+ try:
2614
+ await self._handle_event(event)
2615
+ except Exception as error: # noqa: BLE001 - keep the pull loop alive
2616
+ log.exception("urgent event failed (%s): %s", event.get("type"), error)
2617
+
2618
+ async def _handle_event(self, event: Dict[str, Any]) -> None:
2619
+ kind = event.get("type")
2620
+ conv_key = str(event.get("convKey") or "")
2621
+ if kind == "reply":
2622
+ self._cancel_ack(conv_key)
2623
+ text = str(event.get("text") or "").strip()
2624
+ tools = event.get("tools") or []
2625
+ reason = reason_text(event.get("reason"))
2626
+ # Turn bookkeeping happens on every path: a suppressed reply used to
2627
+ # leak the in-flight counter, so later messages queued forever.
2628
+ self._inflight[conv_key] = max(0, self._inflight.get(conv_key, 1) - 1)
2629
+ if conv_key in self._streams:
2630
+ # 回合结束了但流还开着(final 事件丢失/异常路径):这里必须闭合,
2631
+ # 否则下一个回合会撞上"其它流式消息发送中"。
2632
+ try:
2633
+ await self._close_stream(conv_key)
2634
+ except Exception as error: # noqa: BLE001 - sealing is best effort
2635
+ log.warning("stream seal on turn end failed: %s", error)
2636
+ started = self._submitted_at.pop(conv_key, None)
2637
+ turn_id = str(event.get("turnId") or "")
2638
+ duplicated = False
2639
+ if turn_id:
2640
+ duplicated = self._streamed_turns.pop(turn_id, None) is not None
2641
+ else:
2642
+ duplicated = conv_key in self._suppress_reply
2643
+ self._suppress_reply.discard(conv_key)
2644
+ if duplicated:
2645
+ log.info("turn %s already streamed; dropping durable duplicate for %s", turn_id or "-", conv_key)
2646
+ await self._drain_queued(conv_key)
2647
+ return
2648
+ join_match = JOIN_MARK_RE.search(text)
2649
+ join_score = int(join_match.group(1)) if join_match else None
2650
+ if join_match:
2651
+ text = JOIN_MARK_RE.sub("", text).strip()
2652
+ self._bump("judge_score%d" % join_score)
2653
+ threshold = self._judge_thresholds().get(conv_key, self.rt_int("judge_join_threshold", 2))
2654
+ if self._chat_turns.get(conv_key) and join_score < threshold:
2655
+ self._judge_thresholds().pop(conv_key, None)
2656
+ self._chat_turns.pop(conv_key, None)
2657
+ self._judge_streaks()[conv_key] = self._judge_streaks().get(conv_key, 0) + 1
2658
+ self._bump("judge_silent")
2659
+ log.info(
2660
+ "chatter judge scored %d < threshold %d in %s; staying silent",
2661
+ join_score, threshold, conv_key,
2662
+ )
2663
+ await self._drain_queued(conv_key)
2664
+ return
2665
+ if self._chat_turns.get(conv_key) and not text.strip():
2666
+ self._chat_turns.pop(conv_key, None)
2667
+ self._judge_streaks()[conv_key] = self._judge_streaks().get(conv_key, 0) + 1
2668
+ self._bump("judge_silent")
2669
+ await self._drain_queued(conv_key)
2670
+ return
2671
+ if NO_REPLY_MARK in text:
2672
+ if self._chat_turns.pop(conv_key, False):
2673
+ self._judge_streaks()[conv_key] = self._judge_streaks().get(conv_key, 0) + 1
2674
+ self._bump("judge_silent")
2675
+ log.info("agent stayed silent in %s (chatter judge)", conv_key)
2676
+ await self._drain_queued(conv_key)
2677
+ return
2678
+ # A real question (@ or private chat) must never be answered with silence.
2679
+ log.warning("model tried to stay silent on a directed message in %s; answering instead", conv_key)
2680
+ text = text.replace(NO_REPLY_MARK, "").strip() or "在的,你说。"
2681
+ if self._chat_turns.pop(conv_key, False):
2682
+ self._judge_streaks()[conv_key] = 0
2683
+ self._bump("judge_spoke")
2684
+ had_media = bool(SEND_FILE_MARK.search(text) or STICKER_MARK.search(text))
2685
+ self._spawn_files(conv_key, text)
2686
+ text = STICKER_MARK.sub("", SEND_FILE_MARK.sub("", text)).strip()
2687
+ if had_media and not text:
2688
+ # 文件本身就是这轮的全部内容,不必再说"没有文字输出"
2689
+ await self._drain_queued(conv_key)
2690
+ return
2691
+ if not text:
2692
+ used = f"(调用了 {len(tools)} 个工具:{'、'.join(tools[:8])})" if tools else ""
2693
+ text = f"(本轮结束 {reason or 'done'},没有文字输出){used}"
2694
+ if started is not None:
2695
+ log.info(
2696
+ "reply latency %.2fs for %s (tools=%d, reason=%s)",
2697
+ time.time() - started,
2698
+ conv_key,
2699
+ len(tools),
2700
+ reason or "-",
2701
+ )
2702
+ await self.send_text(conv_key, text)
2703
+ self._bot_spoke_at[conv_key] = time.time()
2704
+ await self._drain_queued(conv_key)
2705
+
2706
+ if kind == "stream":
2707
+ await self._handle_stream(event)
2708
+ return
2709
+ if kind == "approval":
2710
+ await self._deliver_approval(event)
2711
+ return
2712
+ if kind == "notice":
2713
+ await self.send_text(str(event.get("target") or conv_key), str(event.get("text") or ""))
2714
+ return
2715
+
2716
+ def _stream_degraded(self, conv_key: str) -> bool:
2717
+ until = getattr(self, "_stream_holdoff", {}).get(conv_key, 0.0)
2718
+ return until > time.time()
2719
+
2720
+ def _hold_stream(self, conv_key: str, why: str) -> None:
2721
+ if not hasattr(self, "_stream_holdoff"):
2722
+ self._stream_holdoff = {}
2723
+ hold = self.rt_float("stream_retry_s", 120)
2724
+ self._stream_holdoff[conv_key] = time.time() + hold
2725
+ log.warning("streaming suspended in %s for %.0fs: %s", conv_key, hold, why)
2726
+
2727
+ def _new_stream_state(self, conv_key: str, target: Target, turn_id: str) -> Dict[str, Any]:
2728
+ self._msg_seq += 1
2729
+ return {
2730
+ "index": 0,
2731
+ "text": "",
2732
+ "sent_text": "",
2733
+ "last": 0.0,
2734
+ "msg_seq": self._msg_seq,
2735
+ "event_id": target.last_msg_id or "",
2736
+ "stream_msg_id": "",
2737
+ "turn_id": turn_id,
2738
+ }
2739
+
2740
+ async def _stream_post(self, target: Target, state: Dict[str, Any], done: bool) -> bool:
2741
+ """One frame. index is allocated strictly increasing, only after a success."""
2742
+ body = STICKER_MARK.sub("", SEND_FILE_MARK.sub("", str(state.get("text") or ""))).strip()
2743
+ if not body:
2744
+ return True
2745
+ payload: Dict[str, Any] = {
2746
+ "input_mode": "replace",
2747
+ "input_state": 10 if done else 1,
2748
+ "content_type": "markdown",
2749
+ "content_raw": body,
2750
+ "event_id": state["event_id"],
2751
+ "msg_seq": int(state["msg_seq"]),
2752
+ "index": int(state["index"]),
2753
+ }
2754
+ if target.last_msg_id:
2755
+ payload["msg_id"] = target.last_msg_id
2756
+ if state.get("stream_msg_id"):
2757
+ payload["stream_msg_id"] = state["stream_msg_id"]
2758
+ http = getattr(self.api, "_http", None)
2759
+ previous = getattr(http, "base_url", None)
2760
+ try:
2761
+ if previous:
2762
+ # stream_messages lives on the sgroup host; the SDK default
2763
+ # (api.bot.qq.com) answers 50015001 "系统繁忙" for it.
2764
+ http.base_url = SG_GROUP_BASE_URL
2765
+ response = await self.api.post_c2c_stream_message(openid=target.openid, **payload)
2766
+ except Exception as error: # noqa: BLE001 - a refused frame must never lose the answer
2767
+ message = str(error)
2768
+ log.warning("stream frame failed (%s): %s", type(error).__name__, message)
2769
+ if "其它流式消息发送中" in message or "引导已经结束" in message:
2770
+ self._hold_stream(target.conv_key, "platform reports another open stream")
2771
+ return False
2772
+ finally:
2773
+ if previous:
2774
+ http.base_url = previous
2775
+ if isinstance(response, dict) and response.get("id") and not state.get("stream_msg_id"):
2776
+ state["stream_msg_id"] = response["id"]
2777
+ state["index"] = int(state["index"]) + 1
2778
+ state["sent_text"] = state["text"]
2779
+ state["last"] = time.time()
2780
+ self._persist_streams()
2781
+ return True
2782
+
2783
+ async def _close_stream(self, conv_key: str) -> bool:
2784
+ """Strictly seal the open stream: exactly one final frame, then forget it."""
2785
+ state = self._streams.pop(conv_key, None)
2786
+ self._persist_streams()
2787
+ if state is None or not state.get("stream_msg_id"):
2788
+ return True
2789
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
2790
+ if target is None:
2791
+ return True
2792
+ return await self._stream_post(target, state, True)
2793
+
2794
+ async def _handle_stream(self, event: Dict[str, Any]) -> None:
2795
+ """Progressive C2C delivery with a strict one-open-stream contract.
2796
+
2797
+ The platform allows a single open stream per user, requires index to
2798
+ increase per frame, and refuses anything after input_state 10. So: one
2799
+ session per turn, frames serialised per conversation, a guaranteed seal
2800
+ on the final event, and a plain-message fallback when the platform
2801
+ refuses - never a silently lost answer.
2802
+ """
2803
+ conv_key = str(event.get("convKey") or "")
2804
+ target = self.targets.get(conv_key) or self._target_from_key(conv_key)
2805
+ if target is None or target.kind != "c2c":
2806
+ return
2807
+ if not self.rt_bool("stream_enabled", False):
2808
+ return
2809
+ final = bool(event.get("final"))
2810
+ delta = str(event.get("text") or "")
2811
+ turn_id = str(event.get("turnId") or "")
2812
+ if final and turn_id and turn_id in self._streamed_turns:
2813
+ # 同一回合的收尾事件重投:这条回答已经流式送出去了,别再开一个新气泡
2814
+ log.info("duplicate final stream event for turn %s ignored", turn_id)
2815
+ self._streams.pop(conv_key, None)
2816
+ self._persist_streams()
2817
+ return
2818
+ if not hasattr(self, "_stream_locks"):
2819
+ self._stream_locks = {}
2820
+ lock = self._stream_locks.setdefault(conv_key, asyncio.Lock())
2821
+ async with lock:
2822
+ if self._stream_degraded(conv_key):
2823
+ if final and delta.strip():
2824
+ await self.send_text(conv_key, STICKER_MARK.sub("", SEND_FILE_MARK.sub("", delta)).strip())
2825
+ self._spawn_files(conv_key, delta)
2826
+ return
2827
+ state = self._streams.get(conv_key)
2828
+ if state is None:
2829
+ self._bump("streams")
2830
+ state = self._new_stream_state(conv_key, target, str(event.get("turnId") or ""))
2831
+ self._streams[conv_key] = state
2832
+ if delta:
2833
+ if final:
2834
+ # 最终事件可能是「整段文本」(deltas 已经逐段流过),也可能只是最后一片。
2835
+ # 整段时必须以它替换,叠加会让同一段话在气泡里重复两三遍。
2836
+ streamed = str(state["text"]).rstrip()
2837
+ incoming = delta.rstrip()
2838
+ if not streamed or incoming.startswith(streamed) or streamed in incoming:
2839
+ state["text"] = delta
2840
+ elif streamed.endswith(incoming):
2841
+ state["text"] = streamed
2842
+ else:
2843
+ state["text"] = streamed + delta
2844
+ else:
2845
+ state["text"] += delta
2846
+ if not str(state["text"]).strip():
2847
+ if final:
2848
+ self._streams.pop(conv_key, None)
2849
+ self._persist_streams()
2850
+ return
2851
+ if final:
2852
+ ok = await self._close_stream(conv_key)
2853
+ fallback_sent = False
2854
+ if not ok:
2855
+ fallback = STICKER_MARK.sub("", SEND_FILE_MARK.sub("", str(state.get("text") or ""))).strip()
2856
+ if fallback and int(state.get("index", 0)) > 0:
2857
+ self._bump("stream_fallbacks")
2858
+ log.warning("stream unusable for %s; falling back to a plain message", conv_key)
2859
+ await self.send_text(conv_key, fallback)
2860
+ fallback_sent = True
2861
+ # delivered 决定要不要抑制 durable 回复:什么都没送出去时必须让它照常发,
2862
+ # 否则这条回答就凭空消失了。
2863
+ delivered = int(state.get("index", 0)) > 0 or fallback_sent
2864
+ if delivered:
2865
+ self._spawn_files(conv_key, str(state.get("text") or ""))
2866
+ if state.get("turn_id"):
2867
+ self._streamed_turns[str(state["turn_id"])] = time.time()
2868
+ if len(self._streamed_turns) > 50:
2869
+ for stale in sorted(self._streamed_turns, key=self._streamed_turns.get)[:10]:
2870
+ self._streamed_turns.pop(stale, None)
2871
+ else:
2872
+ self._suppress_reply.add(conv_key)
2873
+ if ok:
2874
+ log.info("stream finished (%d chars, %d frame(s)) for %s", len(state["text"]), state["index"], conv_key)
2875
+ return
2876
+ interval = self.rt_float("stream_interval_ms", 300) / 1000.0
2877
+ if time.time() - float(state["last"]) < interval:
2878
+ return
2879
+ if state["sent_text"] == state["text"]:
2880
+ return
2881
+ if not await self._stream_post(target, state, False):
2882
+ # A refused frame makes the session untrustworthy: drop it and let
2883
+ # the durable reply carry the answer as one plain message.
2884
+ self._streams.pop(conv_key, None)
2885
+ self._persist_streams()
2886
+ async def _deliver_approval(self, event: Dict[str, Any]) -> None:
2887
+ """Send the approval card (buttons + fallback text) to the owner chat."""
2888
+ approval_id = str(event.get("approvalId") or "")
2889
+ if not approval_id:
2890
+ return
2891
+ target_key = str(event.get("target") or event.get("convKey") or "")
2892
+ if target_key == "":
2893
+ return
2894
+ tool_name = str(event.get("toolName") or "unknown")
2895
+ reason = reason_text(event.get("reason")).strip()
2896
+ arguments = str(event.get("argumentPreview") or "").strip()
2897
+ self.pending_approvals[approval_id] = event
2898
+ self._cancel_ack(str(event.get("convKey") or ""))
2899
+ body = ["**⚠️ DSH 需要你授权一次操作**", "", f"> 工具:\u0060{tool_name}\u0060"]
2900
+ if arguments:
2901
+ body.append(f"> 参数:\u0060{arguments}\u0060")
2902
+ if reason:
2903
+ body.append(f"> 理由:{reason}")
2904
+ body.append(f"> 来源:{self.conv_label(str(event.get('convKey') or ''))}")
2905
+ body.append("")
2906
+ body.append("点下面的 **允许 / 拒绝** 按钮,或直接回复「允许」/「拒绝」;超时按拒绝。")
2907
+ self._bump("approvals")
2908
+ log.info("delivering approval %s (%s) to %s", approval_id[:8], tool_name, target_key)
2909
+ await self.send_text(target_key, "\n".join(body), keyboard=approval_keyboard(approval_id))
2910
+
2911
+ def _spawn_approval(self, conv_key: str, decision: str, approval_id: str) -> None:
2912
+ """Run the decision off the interaction handler, but never let it die silently."""
2913
+ async def runner() -> None:
2914
+ try:
2915
+ await self._resolve_approval(conv_key, decision, approval_id)
2916
+ except Exception as error: # noqa: BLE001 - the click must still be acked
2917
+ log.exception("approval resolve failed (%s): %s", decision, error)
2918
+
2919
+ task = asyncio.create_task(runner())
2920
+ self._bg_tasks.add(task)
2921
+ task.add_done_callback(self._bg_tasks.discard)
2922
+
2923
+ async def _resolve_kick_confirm(self, interaction: Interaction, request_id: str, approved: bool) -> None:
2924
+ """Owner-only second confirmation for an irreversible kick."""
2925
+ await self._interaction_result(interaction, 0)
2926
+ payload = self._admin_confirm.pop(request_id, None)
2927
+ if payload is None:
2928
+ await self.send_text(self._owner_conv(), "这条踢人请求已经处理过了")
2929
+ return
2930
+ group = str(payload.get("group") or "")
2931
+ member = str(payload.get("member") or "")
2932
+ who = self._display_name(f"group:{group}", member)
2933
+ result_path = str(payload.pop("_path", "") or "")
2934
+ ok, failure = False, None
2935
+ if not approved:
2936
+ await self.send_text(self._owner_conv(), "已取消:没有踢出 " + who)
2937
+ failure = "cancelled by owner"
2938
+ else:
2939
+ try:
2940
+ await self.api.batch_remove_group_members(
2941
+ group_openid=group, member_openids=[member], add_to_member_blacklist=bool(payload.get("blacklist"))
2942
+ )
2943
+ ok = True
2944
+ await self.send_text(self._owner_conv(), "✅ 已踢出 " + who)
2945
+ except Exception as error: # noqa: BLE001 - report platform refusal to the owner
2946
+ failure = str(error)
2947
+ await self.send_text(self._owner_conv(), f"❌ 踢人失败:{failure}")
2948
+ if result_path:
2949
+ try:
2950
+ Path(result_path).write_text(
2951
+ json.dumps({**payload, "status": "done", "ok": ok, "error": failure}, ensure_ascii=False),
2952
+ encoding="utf-8",
2953
+ )
2954
+ except OSError as error:
2955
+ log.warning("kick result write failed: %s", error)
2956
+
2957
+ async def _resolve_approval(self, conv_key: str, decision: str, approval_id: Optional[str]) -> None:
2958
+ if not self.owner_openid:
2959
+ await self.send_text(conv_key, "还没认领主人,无法审批。")
2960
+ return
2961
+ chosen = approval_id if approval_id in self.pending_approvals else None
2962
+ if chosen is None:
2963
+ chosen = next(reversed(self.pending_approvals), None) if self.pending_approvals else None
2964
+ if chosen is None:
2965
+ await self.send_text(conv_key, "现在没有待审批的操作。")
2966
+ return
2967
+ outcome = self.pending_approvals.pop(chosen, None) or {}
2968
+ tool_name = str(outcome.get("toolName") or "")
2969
+ try:
2970
+ await self.bridge.approve(chosen, decision)
2971
+ except BridgeError as error:
2972
+ await self.send_text(conv_key, f"审批没能送达 DSH:{error}")
2973
+ return
2974
+ self._decided[chosen] = decision
2975
+ self._bump("approvals_allow" if decision == "allow" else "approvals_deny")
2976
+ self._timeline("approval", f"{tool_name or 'tool'} -> {decision}")
2977
+ while len(self._decided) > 100:
2978
+ self._decided.pop(next(iter(self._decided)), None)
2979
+ label = ("✅ 已允许" if decision == "allow" else "⛔ 已拒绝") + (f"({tool_name})" if tool_name else "")
2980
+ tail = ",继续执行。" if decision == "allow" else ",本轮操作不会执行。"
2981
+ if not self.rt_bool("approval_inline_redraw", True):
2982
+ # 旧行为:结论文字 + 重发的「已处理」卡片(按钮已失效,再点只回 toast)
2983
+ await self.send_text(
2984
+ conv_key,
2985
+ label + tail,
2986
+ keyboard=decided_keyboard(chosen, label),
2987
+ )
2988
+ # 关闭时什么都不发:按钮已被 visited_label 就地重绘成「✓ 已允许 / ✓ 已拒绝」
2989
+
2990
+ async def _buffer_chatter(self, conv_key: str, sender: str, text: str) -> None:
2991
+ """Collect group chatter; a judge run decides later whether to join in."""
2992
+ entry = self.chatter.get(conv_key)
2993
+ if entry is None:
2994
+ entry = Chatter()
2995
+ self.chatter[conv_key] = entry
2996
+ if text.lstrip().startswith(("【闲聊模式】", "【群聊插话判断】")):
2997
+ log.warning("dropped prompt-shaped chatter line")
2998
+ return
2999
+ entry.lines.append(f"[{time.strftime('%H:%M')}] {sender}: {self._humanize_mentions(conv_key, text)}")
3000
+ if len(entry.lines) > 12:
3001
+ entry.lines = entry.lines[-12:]
3002
+ if entry.first_at == 0.0:
3003
+ entry.first_at = time.time()
3004
+ if entry.timer is None or entry.timer.done():
3005
+ entry.timer = asyncio.create_task(self._judge_later(conv_key))
3006
+
3007
+ async def _judge_later(self, conv_key: str) -> None:
3008
+ """Fire the judgment when the buffered window tops out, even if quiet."""
3009
+ entry = self.chatter.get(conv_key)
3010
+ if entry is None:
3011
+ return
3012
+ deadline = max(0.5, self.rt_float("chatter_max_s", self.config.chatter_max_s) - (time.time() - entry.first_at))
3013
+ try:
3014
+ await asyncio.sleep(deadline)
3015
+ except asyncio.CancelledError:
3016
+ return
3017
+ await self._maybe_judge(conv_key, force_timer=True)
3018
+
3019
+ async def _prefetch_group_profiles(self) -> None:
3020
+ """Warm the group profile cache so cards and the panel have names immediately."""
3021
+ known: set = set()
3022
+ try:
3023
+ saved = json.loads(GROUPS_FILE.read_text(encoding="utf-8")) if GROUPS_FILE.exists() else {}
3024
+ if isinstance(saved, dict):
3025
+ known.update(key for key in saved if len(key) >= 20)
3026
+ except (OSError, ValueError):
3027
+ pass
3028
+ try:
3029
+ members = json.loads(MEMBERS_FILE.read_text(encoding="utf-8"))
3030
+ if isinstance(members, dict):
3031
+ known.update(key[6:] for key in members if key.startswith("group:"))
3032
+ except (OSError, ValueError):
3033
+ pass
3034
+ for group_openid in list(known)[:10]:
3035
+ try:
3036
+ await self._group_name(group_openid)
3037
+ except Exception as error: # noqa: BLE001 - cosmetics only
3038
+ log.debug("group profile prefetch failed: %s", error)
3039
+
3040
+ async def _info_action(self, action: str, payload: Dict[str, Any]) -> Dict[str, Any]:
3041
+ """Read-only lookups for the model's tools (no owner gate needed)."""
3042
+ group = str(payload.get("group") or "")
3043
+ if action == "group":
3044
+ info: Dict[str, Any] = {}
3045
+ try:
3046
+ info = await self.api.get_group_info(group_openid=group)
3047
+ self._save_group_profile(group, info or {})
3048
+ except Exception as error: # noqa: BLE001 - fall back to the cached profile
3049
+ log.info("group info lookup failed: %s", error)
3050
+ mute_rule = {}
3051
+ try:
3052
+ mute_rule = await self.api.get_group_restrict_chat_setting(group_openid=group)
3053
+ except Exception as error: # noqa: BLE001 - optional detail
3054
+ log.info("group mute rule lookup failed: %s", error)
3055
+ saved = {}
3056
+ try:
3057
+ all_groups = json.loads(GROUPS_FILE.read_text(encoding="utf-8")) if GROUPS_FILE.exists() else {}
3058
+ saved = all_groups.get(group, {}) if isinstance(all_groups, dict) else {}
3059
+ except (OSError, ValueError):
3060
+ saved = {}
3061
+ return {
3062
+ "status": "done",
3063
+ "ok": bool(info or saved),
3064
+ "group": {
3065
+ "openid": group,
3066
+ "name": (info or {}).get("group_name") or saved.get("name") or "",
3067
+ "memo": (info or {}).get("group_finger_memo") or saved.get("memo") or "",
3068
+ "class": (info or {}).get("group_class_text") or saved.get("class") or "",
3069
+ "tags": (info or {}).get("group_tags") or saved.get("tags") or [],
3070
+ "members": (info or {}).get("group_member_num") or saved.get("members") or 0,
3071
+ },
3072
+ "mute_rule": mute_rule,
3073
+ "known_members": len(self.member_index.get(f"group:{group}", {})),
3074
+ }
3075
+ if action == "muted":
3076
+ try:
3077
+ state = await self.api.get_group_restrict_chat_setting(group_openid=group)
3078
+ except Exception as error: # noqa: BLE001 - report the platform message
3079
+ return {"status": "done", "ok": False, "error": str(error)}
3080
+ members = []
3081
+ for item in state.get("members") or []:
3082
+ openid = str(item.get("member_openid") or "")
3083
+ members.append({
3084
+ "name": item.get("username") or self._display_name(f"group:{group}", openid),
3085
+ "openid": openid,
3086
+ "short": short_id(openid).upper(),
3087
+ "expire_at": item.get("mute_expire_at") or "",
3088
+ })
3089
+ return {"status": "done", "ok": True, "muted": members, "count": len(members)}
3090
+ if action == "member":
3091
+ member = str(payload.get("member") or "")
3092
+ conv = f"group:{group}"
3093
+ name = self._display_name(conv, member)
3094
+ entry: Dict[str, Any] = {}
3095
+ try:
3096
+ known = json.loads(MEMBERS_FILE.read_text(encoding="utf-8")) if MEMBERS_FILE.exists() else {}
3097
+ entry = ((known or {}).get(conv) or {}).get(short_id(member).upper(), {})
3098
+ except (OSError, ValueError):
3099
+ entry = {}
3100
+ muted = None
3101
+ try:
3102
+ state = await self.api.get_group_restrict_chat_setting(group_openid=group)
3103
+ for item in state.get("members") or []:
3104
+ if str(item.get("member_openid")) == member:
3105
+ muted = item.get("mute_expire_at") or ""
3106
+ except Exception: # noqa: BLE001 - optional
3107
+ muted = None
3108
+ return {
3109
+ "status": "done",
3110
+ "ok": True,
3111
+ "member": {
3112
+ "name": name,
3113
+ "openid": member,
3114
+ "short": short_id(member).upper(),
3115
+ "avatar": entry.get("avatar") or f"https://q.qlogo.cn/qqapp/{self.config.appid}/{member}/640",
3116
+ "last_seen": entry.get("last_seen") or "",
3117
+ "muted_until": muted,
3118
+ },
3119
+ }
3120
+ if action == "stats":
3121
+ metrics = {}
3122
+ try:
3123
+ metrics = json.loads(METRICS_FILE.read_text(encoding="utf-8")) if METRICS_FILE.exists() else {}
3124
+ except (OSError, ValueError):
3125
+ metrics = {}
3126
+ counters = {key: int(metrics.get(key, 0) or 0) for key in self.METRIC_KEYS}
3127
+ return {"status": "done", "ok": True, "counters": counters, "events": (metrics.get("events") or [])[-5:]}
3128
+ return {"status": "done", "ok": False, "error": f"unknown info action: {action}"}
3129
+
3130
+ def _save_group_profile(self, group_openid: str, info: Dict[str, Any]) -> None:
3131
+ """Keep the last known profile per group so the panel needs no API call."""
3132
+ try:
3133
+ saved = json.loads(GROUPS_FILE.read_text(encoding="utf-8")) if GROUPS_FILE.exists() else {}
3134
+ except (OSError, ValueError):
3135
+ saved = {}
3136
+ if not isinstance(saved, dict):
3137
+ saved = {}
3138
+ saved[group_openid] = {
3139
+ "name": str(info.get("group_name") or ""),
3140
+ "memo": str(info.get("group_finger_memo") or ""),
3141
+ "class": str(info.get("group_class_text") or ""),
3142
+ "tags": list(info.get("group_tags") or []),
3143
+ "members": int(info.get("group_member_num") or 0),
3144
+ "fetched_at": int(time.time()),
3145
+ }
3146
+ try:
3147
+ GROUPS_FILE.parent.mkdir(parents=True, exist_ok=True)
3148
+ GROUPS_FILE.write_text(json.dumps(saved, ensure_ascii=False), encoding="utf-8")
3149
+ except OSError as error:
3150
+ log.debug("group profile save failed: %s", error)
3151
+
3152
+ async def _group_name(self, group_openid: str) -> str:
3153
+ """Group display name, cached for 5 minutes and mirrored to state/groups.json."""
3154
+ if not group_openid:
3155
+ return ""
3156
+ cached = getattr(self, "_group_cache", None)
3157
+ if cached is None:
3158
+ cached = self._group_cache = {}
3159
+ entry = cached.get(group_openid)
3160
+ if entry and time.time() - entry[0] < 300:
3161
+ return entry[1]
3162
+ try:
3163
+ info = await self.api.get_group_info(group_openid=group_openid)
3164
+ name = str((info or {}).get("group_name") or "")
3165
+ cached[group_openid] = (time.time(), name)
3166
+ self._save_group_profile(group_openid, info or {})
3167
+ return name
3168
+ except Exception as error: # noqa: BLE001 - naming is cosmetic
3169
+ log.debug("group info unavailable: %s", error)
3170
+ return entry[1] if entry else ""
3171
+
3172
+ def _owner_label(self, conv_key: str, member_openid: str) -> str:
3173
+ """Owner tag with the nickname attached when we know it: 主人(𝒟𝒶𝒾𝓈𝓎)."""
3174
+ nick = self._display_name(conv_key, member_openid) if member_openid else ""
3175
+ if nick and not nick.startswith("群友"):
3176
+ return f"主人({nick})"
3177
+ return "主人"
3178
+
3179
+ def _last_speaker_name(self, conv_key: str, lines: List[str]) -> str:
3180
+ """Resolve the newest buffered speaker ('[10:00] 名字: 内容') back to a nickname."""
3181
+ for line in reversed(lines or []):
3182
+ body = str(line)
3183
+ if "]" in body:
3184
+ body = body.split("]", 1)[1].strip()
3185
+ name = body.split(":", 1)[0].strip()
3186
+ if not name:
3187
+ continue
3188
+ tail = name.upper().replace("群友", "")
3189
+ openid = self.member_index.get(conv_key, {}).get(tail, "")
3190
+ return self._display_name(conv_key, openid) if openid else name
3191
+ return "群友"
3192
+
3193
+ def _interject_hook(self, conv_key: str, lines: List[str]) -> bool:
3194
+ """Cheap pre-check: is this batch worth one model call at all?"""
3195
+ if not lines:
3196
+ return False
3197
+ text = chr(10).join(lines)
3198
+ if self.addresses_bot(text):
3199
+ return True
3200
+ if "?" in text or "?" in text:
3201
+ return True
3202
+ lowered = text.lower()
3203
+ for name in ("大肥鱼", "机器人", "dsh", "鱼"):
3204
+ if name in lowered:
3205
+ return True
3206
+ last = getattr(self, "_last_group_at", {}).get(conv_key, 0.0)
3207
+ cold = self.rt_float("interject_cold_s", 1200)
3208
+ if last and time.time() - last > cold:
3209
+ return True
3210
+ return False
3211
+
3212
+ def _judge_streaks(self) -> Dict[str, int]:
3213
+ streak = getattr(self, "_judge_silent_streak", None)
3214
+ if streak is None:
3215
+ streak = self._judge_silent_streak = {}
3216
+ return streak
3217
+
3218
+ def _judge_forces(self) -> Dict[str, float]:
3219
+ forced = getattr(self, "_judge_force_at", None)
3220
+ if forced is None:
3221
+ forced = self._judge_force_at = {}
3222
+ return forced
3223
+
3224
+ def _judge_thresholds(self) -> Dict[str, int]:
3225
+ used = getattr(self, "_judge_threshold_used", None)
3226
+ if used is None:
3227
+ used = self._judge_threshold_used = {}
3228
+ return used
3229
+
3230
+ def _judge_threshold(self, conv_key: str) -> int:
3231
+ """开口阈值:基础值可配,连续沉默或长时间未开口时临时降一档。"""
3232
+ if not self.rt_bool("judge_score_output", True):
3233
+ return 0
3234
+ base = max(0, min(3, self.rt_int("judge_join_threshold", 2)))
3235
+ lowered = base
3236
+ streak = self._judge_streaks().get(conv_key, 0)
3237
+ if streak >= max(1, self.rt_int("judge_silent_streak", 3)):
3238
+ lowered = max(0, base - 1)
3239
+ spoke_at = self._last_bot_say_of(conv_key)[1]
3240
+ quiet = time.time() - spoke_at if spoke_at else float("inf")
3241
+ hourly = max(0, self.rt_int("judge_force_per_hour", 1))
3242
+ forced = self._judge_forces()
3243
+ if hourly and quiet > 3600 and time.time() - forced.get(conv_key, 0.0) > 3600:
3244
+ lowered = min(lowered, max(0, base - 1))
3245
+ forced[conv_key] = time.time()
3246
+ return lowered
3247
+
3248
+ def _judge_stats_line(self) -> str:
3249
+ metrics = getattr(self, "_metrics", None) or {}
3250
+ calls = int(metrics.get("judge_calls", 0) or 0)
3251
+ spoke = int(metrics.get("judge_spoke", 0) or 0)
3252
+ ratio = (spoke / calls) if calls else 0.0
3253
+ target = float(self.rt_float("judge_target_ratio", 0.3))
3254
+ return (
3255
+ f"今天你在这个群:判断 {calls} 次、开口 {spoke} 次({ratio:.0%})。"
3256
+ f"目标大概 {target:.0%};低于它的时候更大胆一点,轻接一句也行。"
3257
+ )
3258
+
3259
+ async def _maybe_judge(self, conv_key: str, *, force_timer: bool = False) -> None:
3260
+ """Ask the agent whether it wants to say something; it may stay silent."""
3261
+ entry = self.chatter.get(conv_key)
3262
+ if entry is None or not entry.lines:
3263
+ return
3264
+ if self._inflight.get(conv_key, 0) > 0 or conv_key in self.queued:
3265
+ return
3266
+ if self._in_quiet_hours():
3267
+ return
3268
+ now = time.time()
3269
+ if self.rt_bool("interject_hook_only", True) and not self._interject_hook(conv_key, entry.lines):
3270
+ # 没有钩子就不花一次模型调用;消息继续攒在缓冲里,等下一个钩子一起判
3271
+ entry.last_judge_at = now
3272
+ self._bump("hook_skips")
3273
+ log.info("chatter skipped (no hook) in %s", conv_key)
3274
+ return
3275
+ if now - entry.last_judge_at < self.rt_float("chatter_cooldown_s", self.config.chatter_cooldown_s):
3276
+ return
3277
+ if not force_timer and len(entry.lines) < self.rt_int("chatter_batch", self.config.chatter_batch):
3278
+ return
3279
+ lines = list(entry.lines)
3280
+
3281
+ # Someone naming the bot inside plain chatter must get a real answer:
3282
+ # the judge prompt offers [NO_REPLY], and a called bot must not take it.
3283
+ if any(self.addresses_bot(line) for line in lines):
3284
+ self.chatter.pop(conv_key, None)
3285
+ joined = chr(10).join(line.split(": ", 1)[-1] for line in lines)
3286
+ log.info("chatter named the bot; answering instead of judging (%d line(s))", len(lines))
3287
+ await self._submit(conv_key, joined, self._last_speaker_name(conv_key, lines), False, None, chat=False)
3288
+ return
3289
+
3290
+ entry.lines.clear()
3291
+ entry.first_at = 0.0
3292
+ entry.last_judge_at = now
3293
+ spoke_text, spoke_at = self._last_bot_say_of(conv_key)
3294
+ since = time.time() - spoke_at if spoke_text else float("inf")
3295
+ if spoke_text and since < self.rt_float("bot_say_memory_s", self.config.bot_say_memory_s):
3296
+ situation = (
3297
+ f"你在群里最近说过({max(0, int(since))} 秒前):\u201c{spoke_text[:160]}\u201d"
3298
+ f"(可参考的记录:最近 {int(self._pool_ttl() // 60)} 分钟 / 最近 {self._pool_limit()} 条)"
3299
+ )
3300
+ elif spoke_text:
3301
+ situation = (
3302
+ f"你在这群里已经安静了 {int(since // 60)} 分钟,最近没说话"
3303
+ f"(更早之前说过:\u201c{spoke_text[:80]}\u201d,只作背景,别重复它)。"
3304
+ )
3305
+ else:
3306
+ situation = (
3307
+ f"在最近 {int(self._pool_ttl() // 60)} 分钟 / 最近 {self._pool_limit()} 条消息的记录里,"
3308
+ "没看到你在群里说过话(不代表你从没说过,只是这些记录里没有)。"
3309
+ )
3310
+ speakers = [line.split(": ", 1)[0] for line in lines if ": " in line]
3311
+ last_speaker = speakers[-1] if speakers else "群友"
3312
+ prev_speaker = speakers[-2] if len(speakers) > 1 else ""
3313
+ last_text = lines[-1].split(": ", 1)[-1] if lines else ""
3314
+ called = self.addresses_bot(last_text)
3315
+ speakers = []
3316
+ for item in lines:
3317
+ # 行形如 "[14:11] 群友35DB11: 下午好啊"——先去时间戳,再取发言人
3318
+ body = str(item)
3319
+ if body.startswith("[") and "]" in body:
3320
+ body = body.split("]", 1)[1].strip()
3321
+ name = body.split(":", 1)[0].strip()
3322
+ if name and name not in speakers:
3323
+ speakers.append(name)
3324
+ recent = "、".join(speakers[:6]) or last_speaker
3325
+ if called:
3326
+ audience = f"最后一句来自 {last_speaker},里面叫了你的名字(别名:{self._alias_list()}),是在跟你说话。"
3327
+ else:
3328
+ audience = (
3329
+ f"最近 {len(lines)} 条里发言的人:{recent}。最后一句来自 {last_speaker}。"
3330
+ "(谁在跟谁说话、是不是在问你,你自己按上下文判断,不要只看最后两条。)"
3331
+ )
3332
+
3333
+ if self.rt_bool("judge_score_output", True):
3334
+ format_rules = [
3335
+ "输出格式:",
3336
+ "第一行只写 [[join: 0~3]](3=必须接,2=想接,1=可接可不接,0=不说)",
3337
+ "第二行起写你想说的话;不想说时整条只留 [[join: 0]]。",
3338
+ ]
3339
+ else:
3340
+ format_rules = ["不想说话时整条只回 [NO_REPLY],其余情况直接写你想说的话。"]
3341
+ self._judge_thresholds()[conv_key] = self._judge_threshold(conv_key)
3342
+
3343
+ roster = self._roster_line(conv_key)
3344
+ prompt = chr(10).join(
3345
+ [
3346
+ "【群聊插话判断】",
3347
+ situation,
3348
+ audience,
3349
+ *([roster] if roster else []),
3350
+ "",
3351
+ "这之后群里在聊:",
3352
+ *lines,
3353
+ "",
3354
+ self._judge_stats_line(),
3355
+ "",
3356
+ "像群里的一员那样:默认接一句(1~2 句口语),别总结、别复述、别客套、别写成报告。",
3357
+ "只有这三种情况才沉默:",
3358
+ "① 明显是两个人一对一搭话,既没提到你也没什么可加;",
3359
+ "② 你 2 分钟内刚说过同类的话;",
3360
+ "③ 这条只是表情/图片/链接/单字,没有可回应的内容。",
3361
+ "其余情况(抛观点、吐槽、聊到你熟的东西、问问题、接梗)都可以接一句;",
3362
+ "话题不熟也可以轻接一句(提问、帮腔、吐槽),不必等到“感兴趣”才开口。",
3363
+ "",
3364
+ *format_rules,
3365
+ ]
3366
+ )
3367
+ self._bump("judge_calls")
3368
+ self._timeline("judge", f"{len(lines)} 行")
3369
+ log.info("judging %d line(s) of chatter in %s", len(lines), conv_key)
3370
+ await self._submit(conv_key, prompt, "群友", False, None, chat=True)
3371
+
3372
+ def _pool_transcript(self, conv_key: str, limit: int = 12) -> str:
3373
+ """Recent messages of this conversation, verbatim, oldest first."""
3374
+ cutoff = time.time() - self._pool_ttl()
3375
+ items = [
3376
+ item
3377
+ for item in self.pool.values()
3378
+ if item.conv_key == conv_key and item.at >= cutoff
3379
+ ]
3380
+ items.sort(key=lambda item: item.at)
3381
+ lines = []
3382
+ for item in items[-limit:]:
3383
+ body = str(item.text)
3384
+ # 双保险:无论污染从哪条路径进来,提示词形状的文本都不许出现在聊天记录里
3385
+ if "【闲聊模式】" in body or "【群聊插话判断】" in body:
3386
+ continue
3387
+ if item.outbound:
3388
+ who = "你(机器人)"
3389
+ else:
3390
+ # 池里存的是短号,提示词里换成昵称(群友不知道自己的短号)
3391
+ tail = str(item.author or "").upper()
3392
+ openid = self.member_index.get(conv_key, {}).get(tail, "")
3393
+ who = self._display_name(conv_key, openid) if openid else item.author
3394
+ lines.append(f"[{time.strftime('%H:%M', time.localtime(item.at))}] {who}: {body}")
3395
+ return chr(10).join(lines)
3396
+
3397
+ async def _plan_b(self, conv_key: str, message: Any, member_openid: str) -> None:
3398
+ """Plan B: an independent judge decides, then the main model gets the verbatim pool."""
3399
+ # 只有"未被点名"的闲聊才会走到这里(被 @ 的走 _handle_group_at),
3400
+ # 所以静默时段在这里拦,@ 与私聊不受影响。
3401
+ if self._in_quiet_hours():
3402
+ log.info("plan B skipped: quiet hours (%s)", self.rt_str("quiet_hours", ""))
3403
+ return
3404
+ transcript = self._pool_transcript(conv_key)
3405
+ if transcript.strip() == "":
3406
+ transcript = f"{self._display_name(conv_key, member_openid)}: {clean_content(getattr(message, 'content', ''))}"
3407
+ try:
3408
+ verdict = await self.bridge.judge(
3409
+ conv_key,
3410
+ transcript,
3411
+ threshold=self._judge_threshold(conv_key),
3412
+ hint=self._judge_stats_line(),
3413
+ )
3414
+ except BridgeError as error:
3415
+ log.warning("plan B judge unavailable (%s); fallback to plain chatter", error)
3416
+ await self._buffer_chatter(conv_key, self._display_name(conv_key, member_openid), clean_content(getattr(message, "content", "")))
3417
+ await self._maybe_judge(conv_key)
3418
+ return
3419
+ need_reply = bool(verdict.get("needReply"))
3420
+ score = verdict.get("score")
3421
+ self._bump("judge_calls")
3422
+ if isinstance(score, int) and 0 <= score <= 3:
3423
+ self._bump("judge_score%d" % score)
3424
+ self._bump("judge_spoke" if need_reply else "judge_silent")
3425
+ self._judge_streaks()[conv_key] = 0 if need_reply else self._judge_streaks().get(conv_key, 0) + 1
3426
+ note = str(verdict.get("note") or "").strip()
3427
+ if not need_reply:
3428
+ log.info("plan B: judge stayed silent%s", f" ({note[:60]})" if note else "")
3429
+ try:
3430
+ await self.bridge.inbound(conv_key=conv_key, text=transcript, context_only=True)
3431
+ except BridgeError as error:
3432
+ log.debug("plan B context push failed: %s", error)
3433
+ return
3434
+ log.info("plan B: judge wants a reply%s", f" ({note[:60]})" if note else "")
3435
+ prompt = "【群里最近的原文】" + chr(10) + transcript
3436
+ if note:
3437
+ prompt += chr(10) + chr(10) + "【判断参考】" + note
3438
+ await self._queue_message(
3439
+ conv_key,
3440
+ prompt,
3441
+ self._display_name(conv_key, member_openid),
3442
+ False,
3443
+ [],
3444
+ chat=False,
3445
+ )
3446
+
3447
+ async def _handle_group_at(self, message: GroupMessage, *, chat: bool = False) -> None:
3448
+ self._remember_id(message.id)
3449
+ log.info(
3450
+ "group @ from %s: %r",
3451
+ short_id(((message.author.member_openid if message.author else "") or "")),
3452
+ clean_content(message.content)[:120],
3453
+ )
3454
+ if not self.config.groups_enabled or not self.rt_bool("group_enabled", True) or not self.rt_bool("enabled", True):
3455
+ return
3456
+ group_openid = message.group_openid or ""
3457
+ conv_key = f"group:{group_openid}"
3458
+ member_openid = ""
3459
+ if message.author is not None:
3460
+ member_openid = message.author.member_openid or message.author.user_openid or ""
3461
+ text = clean_content(message.content)
3462
+ self._bump("group_at")
3463
+ if member_openid:
3464
+ self._remember_member(conv_key, member_openid, _author_nick(message))
3465
+ # 先补名字,再去掉开头那次「@我」——闲聊转录里保留全部 @,这里只处理点名的这条
3466
+ text = self._strip_self_mention(conv_key, self._humanize_mentions(conv_key, text))
3467
+ if getattr(message, "attachments", None):
3468
+ self._bump("group_images")
3469
+ self._pool_incoming(message, "group", group_openid, conv_key, short_id(member_openid))
3470
+ if member_openid:
3471
+ self.member_index.setdefault(conv_key, {})[short_id(member_openid).upper()] = member_openid
3472
+ is_owner = self._is_owner_group(group_openid, member_openid)
3473
+ self._note_owner_activity(conv_key, is_owner)
3474
+ if not hasattr(self, "_last_group_at"):
3475
+ self._last_group_at = {}
3476
+ self._last_group_at[conv_key] = time.time()
3477
+ if not is_owner and member_openid:
3478
+ is_owner = await self._bind_group_owner_by_role(group_openid, member_openid)
3479
+ lowered = text.lower()
3480
+
3481
+ if text in BIND_COMMANDS:
3482
+ if not is_owner:
3483
+ await self.send_text(conv_key, "只有机器人主人才能绑定群主。")
3484
+ return
3485
+ self.state.group_owners[group_openid] = member_openid
3486
+ self.state.save()
3487
+ log.info("group owner bound: %s -> %s", group_openid, short_id(member_openid))
3488
+ await self.send_text(conv_key, "已把当前群里的你绑定为主人。")
3489
+ return
3490
+ if lowered in RESET_COMMANDS:
3491
+ if not is_owner:
3492
+ await self.send_text(conv_key, "这条指令只有主人能用。")
3493
+ return
3494
+ try:
3495
+ await self.bridge.reset(conv_key)
3496
+ except BridgeError as error:
3497
+ await self.send_text(conv_key, f"重置失败:{error}")
3498
+ return
3499
+ await self.send_text(conv_key, "已开新会话,上下文清空。")
3500
+ return
3501
+ if lowered in HELP_COMMANDS:
3502
+ await self.send_text(conv_key, self.help_text())
3503
+ return
3504
+ if lowered in ("/分组", "/workspace", "/ws"):
3505
+ try:
3506
+ result = await self.bridge.rebind(conv_key)
3507
+ except BridgeError as error:
3508
+ await self.send_text(conv_key, "创建分组失败:" + str(error))
3509
+ return
3510
+ if result.get("ok") and result.get("moved"):
3511
+ sandbox = result.get("sandbox")
3512
+ granted = ""
3513
+ if isinstance(sandbox, dict) and str(sandbox.get("granted") or "") == "failed":
3514
+ granted = chr(10) + "⚠ 沙箱预授权失败:" + str(sandbox.get("reason") or "未知原因")
3515
+ await self.send_text(conv_key, "已迁移到工作区(上下文保留):" + str(result.get("cwd")) + granted)
3516
+ elif result.get("ok"):
3517
+ reason = str(result.get("fallbackReason") or "")
3518
+ await self.send_text(conv_key, "已切到独立工作区:" + str(result.get("cwd")) + chr(10) + "方式:新建会话(上下文不继承)" + ((",原因:" + reason) if reason else ""))
3519
+ else:
3520
+ await self.send_text(conv_key, "创建分组失败:" + str(result.get("error")))
3521
+ return
3522
+ if lowered in ("/指令", "/commands"):
3523
+ try:
3524
+ result = await self.bridge.commands(conv_key)
3525
+ except BridgeError as error:
3526
+ await self.send_text(conv_key, "查询指令失败:" + str(error))
3527
+ return
3528
+ if not result.get("ok"):
3529
+ await self.send_text(conv_key, str(result.get("error") or "不可用"))
3530
+ return
3531
+ items = result.get("commands") or []
3532
+ lines = ["DSH 指令(实时," + str(len(items)) + " 条):"]
3533
+ for item in items[:40]:
3534
+ desc = str(item.get("description") or "")
3535
+ lines.append("- /" + str(item.get("name")) + ((" — " + desc) if desc else ""))
3536
+ if len(items) > 40:
3537
+ lines.append("… 还有 " + str(len(items) - 40) + " 条")
3538
+ lines.append("")
3539
+ lines.append("直接用 /<名字> 就能执行(转给 DSH 官方命令通道)")
3540
+ await self.send_text(conv_key, chr(10).join(lines))
3541
+ return
3542
+ if lowered.startswith("/") and lowered not in ("/pr", "/分组"):
3543
+ try:
3544
+ result = await self.bridge.run_command(conv_key, text.strip())
3545
+ except Exception: # noqa: BLE001 - unknown command must fall through, never crash
3546
+ result = {}
3547
+ if result.get("ok") and result.get("handled"):
3548
+ return
3549
+ if lowered == "/pr" or lowered.startswith("/pr "):
3550
+ preset = text[3:].strip()
3551
+ try:
3552
+ result = await self.bridge.permission(conv_key, preset or None)
3553
+ except BridgeError as error:
3554
+ await self.send_text(conv_key, "权限查询失败:" + str(error))
3555
+ return
3556
+ names = result.get("names") or []
3557
+ if preset:
3558
+ if result.get("ok"):
3559
+ await self.send_text(conv_key, "已切换权限:" + preset + "(以 DSH 的提示为准)")
3560
+ else:
3561
+ await self.send_text(conv_key, "切换失败:" + str(result.get("error")) + ";可用:" + ", ".join(names))
3562
+ return
3563
+ if not names:
3564
+ await self.send_text(conv_key, str(result.get("note") or result.get("error") or "权限预设不可用"))
3565
+ return
3566
+ current = str(result.get("current") or "")
3567
+ lines = ["当前权限:" + (current or "未知(会话未加载)")]
3568
+ lines.append("")
3569
+ lines.append("可选预设(实时,来自 DSH):")
3570
+ for name in names:
3571
+ lines.append("- " + name + ("(默认)" if name == result.get("current") else ""))
3572
+ lines.append("")
3573
+ lines.append("切换:/pr <名字>(转发官方 /permission,不扩大权限)")
3574
+ await self.send_text(conv_key, chr(10).join(lines))
3575
+ return
3576
+ if await self.handle_extra_command(conv_key, text, lowered, is_owner=is_owner):
3577
+ return
3578
+
3579
+ images, skipped = await self._collect_images(message.attachments)
3580
+ if skipped and not images:
3581
+ text = (text + "\n(对方发来图片,但我这边解不开:只支持 png/jpg/webp/gif,可能是 HEIF 或下载失败)").strip()
3582
+ if not text and not images:
3583
+ await self.send_text(conv_key, "在的,@我并说出你的问题就行。")
3584
+ return
3585
+
3586
+ self.chime[conv_key] = {"count": 0.0, "last": time.time()}
3587
+ quote = self._quote_of(message)
3588
+ if quote is not None:
3589
+ self._bump("quotes")
3590
+ quoted_images = await self._quote_images(quote)
3591
+ if quoted_images:
3592
+ images = list(images) + quoted_images
3593
+ await self._queue_message(
3594
+ conv_key,
3595
+ text,
3596
+ self._owner_label(conv_key, member_openid) if is_owner else self._display_name(conv_key, member_openid),
3597
+ is_owner,
3598
+ images,
3599
+ chat=chat,
3600
+ quote=quote,
3601
+ )
3602
+
3603
+ async def on_group_at_message_create(self, message: GroupMessage) -> None:
3604
+ try:
3605
+ await self._handle_group_at(message)
3606
+ except Exception as error: # noqa: BLE001 - one bad message must not kill dispatch
3607
+ log.exception("group @ handler failed: %s", error)
3608
+
3609
+ async def on_group_message_create(self, message: GroupMessage) -> None:
3610
+ """Full mode: @ commands work, plain chatter goes through the judge."""
3611
+ try:
3612
+ if (
3613
+ not self.config.group_full_mode
3614
+ or not self.config.groups_enabled
3615
+ or not self.rt_bool("group_enabled", True)
3616
+ or not self.rt_bool("enabled", True)
3617
+ ):
3618
+ return
3619
+ group_openid = message.group_openid or ""
3620
+ if not group_openid:
3621
+ return
3622
+ conv_key = f"group:{group_openid}"
3623
+ self._bump("group_msgs")
3624
+ member_openid = ""
3625
+ if message.author is not None:
3626
+ member_openid = message.author.member_openid or message.author.user_openid or ""
3627
+ text = clean_content(message.content)
3628
+ if message.id and message.id in self._seen_ids:
3629
+ return
3630
+ self._remember_id(message.id)
3631
+ self._pool_incoming(message, "group", group_openid, conv_key, short_id(member_openid))
3632
+ if member_openid:
3633
+ self._remember_member(conv_key, member_openid, _author_nick(message))
3634
+ log.info(
3635
+ "group message from %s: %r (keys=%s, mentions=%d)",
3636
+ short_id(member_openid),
3637
+ text[:80],
3638
+ ",".join(sorted((message.raw or {}).keys()))[:160],
3639
+ len(getattr(message, "mentions", None) or []),
3640
+ )
3641
+ mentioned = await self._mentions_bot(message)
3642
+ named = self.addresses_bot(text)
3643
+ commanded = text.startswith("/")
3644
+ at_only = self.rt_bool("group_at_only", False)
3645
+ if at_only is True and not mentioned:
3646
+ # at-only:别名/关键词、以及斜杠命令都不算被叫到,只有真 @ 才放行
3647
+ log.info("group chat ignored (at-only mode, named=%s cmd=%s)", named, commanded)
3648
+ return
3649
+ if mentioned or named or commanded:
3650
+ self._addressed_at[conv_key] = time.time()
3651
+ stale = self.chatter.pop(conv_key, None)
3652
+ if stale is not None and stale.timer is not None:
3653
+ stale.timer.cancel()
3654
+ log.info("treat as addressed (mention=%s name=%s cmd=%s)", mentioned, named, commanded)
3655
+ await self._handle_group_at(message, chat=False)
3656
+ return
3657
+ if self.rt_str("group_mode", "A").strip().upper() == "B":
3658
+ await self._plan_b(conv_key, message, member_openid)
3659
+ return
3660
+
3661
+ images, _skipped = await self._collect_images(message.attachments) if message.attachments else ([], 0)
3662
+ if images:
3663
+ self.recent_images[conv_key] = (images[-2:], time.time())
3664
+ if text:
3665
+ await self._buffer_chatter(conv_key, self._display_name(conv_key, member_openid), text)
3666
+ await self._maybe_judge(conv_key)
3667
+ except Exception as error: # noqa: BLE001
3668
+ self._bump("errors")
3669
+ log.exception("group handler failed: %s", error)
3670
+
3671
+ async def on_c2c_message_create(self, message: C2CMessage) -> None:
3672
+ try:
3673
+ await self._handle_c2c(message)
3674
+ except Exception as error: # noqa: BLE001
3675
+ log.exception("c2c handler failed: %s", error)
3676
+
3677
+ async def _handle_c2c(self, message: C2CMessage) -> None:
3678
+ # QQ 网关会在 ack 慢或重连时重投同一个事件;私聊必须先去重,否则一轮对话会被跑两次、回两条
3679
+ if message.id and message.id in self._seen_ids:
3680
+ log.info("duplicate c2c event ignored: %s", message.id)
3681
+ return
3682
+ self._remember_id(message.id)
3683
+ log.info(
3684
+ "c2c from %s: %r",
3685
+ short_id(((message.author.user_openid if message.author else "") or "")),
3686
+ clean_content(message.content)[:120],
3687
+ )
3688
+ if not self.rt_bool("enabled", True) or not self.rt_bool("c2c_enabled", True):
3689
+ return
3690
+ self._bump("c2c_msgs")
3691
+ user_openid = message.author.user_openid if message.author is not None else ""
3692
+ if not user_openid:
3693
+ return
3694
+ conv_key = f"c2c:{user_openid}"
3695
+ self._register(conv_key, "c2c", user_openid, message.id)
3696
+
3697
+ if not self.owner_openid:
3698
+ self.owner_openid = user_openid
3699
+ self.state.owner_openid = user_openid
3700
+ self.state.save()
3701
+ log.info("owner claimed by first private message: %s", short_id(user_openid))
3702
+ is_owner = user_openid == self.owner_openid
3703
+
3704
+ text = clean_content(message.content)
3705
+ self._pool_incoming(message, "c2c", user_openid, conv_key, f"用户{short_id(user_openid)}")
3706
+ lowered = text.lower()
3707
+ decision, approval_id = parse_decision(text)
3708
+ if decision is not None:
3709
+ if not is_owner:
3710
+ await self.send_text(conv_key, "只有主人可以审批。")
3711
+ return
3712
+ await self._resolve_approval(conv_key, decision, approval_id)
3713
+ return
3714
+ if lowered in RESET_COMMANDS:
3715
+ try:
3716
+ await self.bridge.reset(conv_key)
3717
+ except BridgeError as error:
3718
+ await self.send_text(conv_key, f"重置失败:{error}")
3719
+ return
3720
+ await self.send_text(conv_key, "已开新会话,上下文清空。")
3721
+ return
3722
+ if lowered in HELP_COMMANDS:
3723
+ await self.send_text(conv_key, self.help_text())
3724
+ return
3725
+ if lowered in ("/分组", "/workspace", "/ws"):
3726
+ try:
3727
+ result = await self.bridge.rebind(conv_key)
3728
+ except BridgeError as error:
3729
+ await self.send_text(conv_key, "创建分组失败:" + str(error))
3730
+ return
3731
+ if result.get("ok") and result.get("moved"):
3732
+ sandbox = result.get("sandbox")
3733
+ granted = ""
3734
+ if isinstance(sandbox, dict) and str(sandbox.get("granted") or "") == "failed":
3735
+ granted = chr(10) + "⚠ 沙箱预授权失败:" + str(sandbox.get("reason") or "未知原因")
3736
+ await self.send_text(conv_key, "已迁移到工作区(上下文保留):" + str(result.get("cwd")) + granted)
3737
+ elif result.get("ok"):
3738
+ reason = str(result.get("fallbackReason") or "")
3739
+ await self.send_text(conv_key, "已切到独立工作区:" + str(result.get("cwd")) + chr(10) + "方式:新建会话(上下文不继承)" + ((",原因:" + reason) if reason else ""))
3740
+ else:
3741
+ await self.send_text(conv_key, "创建分组失败:" + str(result.get("error")))
3742
+ return
3743
+ if lowered in ("/指令", "/commands"):
3744
+ try:
3745
+ result = await self.bridge.commands(conv_key)
3746
+ except BridgeError as error:
3747
+ await self.send_text(conv_key, "查询指令失败:" + str(error))
3748
+ return
3749
+ if not result.get("ok"):
3750
+ await self.send_text(conv_key, str(result.get("error") or "不可用"))
3751
+ return
3752
+ items = result.get("commands") or []
3753
+ lines = ["DSH 指令(实时," + str(len(items)) + " 条):"]
3754
+ for item in items[:40]:
3755
+ desc = str(item.get("description") or "")
3756
+ lines.append("- /" + str(item.get("name")) + ((" — " + desc) if desc else ""))
3757
+ if len(items) > 40:
3758
+ lines.append("… 还有 " + str(len(items) - 40) + " 条")
3759
+ lines.append("")
3760
+ lines.append("直接用 /<名字> 就能执行(转给 DSH 官方命令通道)")
3761
+ await self.send_text(conv_key, chr(10).join(lines))
3762
+ return
3763
+ if lowered.startswith("/") and lowered not in ("/pr", "/分组"):
3764
+ try:
3765
+ result = await self.bridge.run_command(conv_key, text.strip())
3766
+ except Exception: # noqa: BLE001 - unknown command must fall through, never crash
3767
+ result = {}
3768
+ if result.get("ok") and result.get("handled"):
3769
+ return
3770
+ if lowered == "/pr" or lowered.startswith("/pr "):
3771
+ preset = text[3:].strip()
3772
+ try:
3773
+ result = await self.bridge.permission(conv_key, preset or None)
3774
+ except BridgeError as error:
3775
+ await self.send_text(conv_key, "权限查询失败:" + str(error))
3776
+ return
3777
+ names = result.get("names") or []
3778
+ if preset:
3779
+ if result.get("ok"):
3780
+ await self.send_text(conv_key, "已切换权限:" + preset + "(以 DSH 的提示为准)")
3781
+ else:
3782
+ await self.send_text(conv_key, "切换失败:" + str(result.get("error")) + ";可用:" + ", ".join(names))
3783
+ return
3784
+ if not names:
3785
+ await self.send_text(conv_key, str(result.get("note") or result.get("error") or "权限预设不可用"))
3786
+ return
3787
+ current = str(result.get("current") or "")
3788
+ lines = ["当前权限:" + (current or "未知(会话未加载)")]
3789
+ lines.append("")
3790
+ lines.append("可选预设(实时,来自 DSH):")
3791
+ for name in names:
3792
+ lines.append("- " + name + ("(默认)" if name == result.get("current") else ""))
3793
+ lines.append("")
3794
+ lines.append("切换:/pr <名字>(转发官方 /permission,不扩大权限)")
3795
+ await self.send_text(conv_key, chr(10).join(lines))
3796
+ return
3797
+ if await self.handle_extra_command(conv_key, text, lowered, is_owner=is_owner):
3798
+ return
3799
+
3800
+ images, skipped = await self._collect_images(message.attachments)
3801
+ if skipped and not images:
3802
+ text = (text + "\n(对方发来图片,但我这边解不开:只支持 png/jpg/webp/gif,可能是 HEIF 或下载失败)").strip()
3803
+ if not text and not images:
3804
+ await self.send_text(conv_key, "说点什么,我转给 DSH。")
3805
+ return
3806
+
3807
+ quote = self._quote_of(message)
3808
+ if quote is not None:
3809
+ self._bump("quotes")
3810
+ quoted_images = await self._quote_images(quote)
3811
+ if quoted_images:
3812
+ images = list(images) + quoted_images
3813
+ await self._queue_message(
3814
+ conv_key,
3815
+ text,
3816
+ self._owner_label(conv_key, user_openid) if is_owner else f"用户{short_id(user_openid)}",
3817
+ is_owner,
3818
+ images,
3819
+ quote=quote,
3820
+ )
3821
+
3822
+ async def on_interaction_create(self, interaction: Interaction) -> None:
3823
+ """Handle 允许 / 拒绝 button clicks (only the owner may decide)."""
3824
+ data = interaction.data or {}
3825
+ resolved = data.get("resolved") or {}
3826
+ button_data = resolved.get("button_data") or data.get("button_data") or ""
3827
+ clicker = (interaction.user_openid or interaction.group_member_openid or "").strip()
3828
+ owner = (self.owner_openid or "").strip()
3829
+ if owner and clicker and clicker.upper() != owner.upper():
3830
+ # 点的人不是主人:QQ 会把这个 code 显示成「无权限操作」
3831
+ log.warning(
3832
+ "approval click rejected: clicker=%s owner=%s",
3833
+ short_id(clicker),
3834
+ short_id(owner),
3835
+ )
3836
+ await self._interaction_result(interaction, 4)
3837
+ return
3838
+ # 提问按钮必须在审批解析之前拦掉:它的 data 不是「允许/拒绝 <id>」
3839
+ picked = str(button_data).strip().split()
3840
+ if len(picked) == 3 and picked[0] == "选择":
3841
+ question_id, raw_index = picked[1], picked[2]
3842
+ conv_for_answer = f"c2c:{clicker}" if clicker else self._owner_conv()
3843
+ await self._interaction_result(interaction, 0)
3844
+ try:
3845
+ self._bump("questions_answered")
3846
+ await self.bridge.answer_question(question_id, int(raw_index))
3847
+ log.info("question %s answered with option %s", short_id(question_id), raw_index)
3848
+ except Exception as error: # noqa: BLE001 - the question may have expired
3849
+ log.warning("answer delivery failed: %s", error)
3850
+ await self.send_text(conv_for_answer, "这个提问已经失效了(或插件还没重启加载 /answer)。")
3851
+ return
3852
+ # 踢人二次确认:data 形如「踢人确认 <id> yes」/「踢人确认 <id> no」
3853
+ kick_hit = parse_kick_confirm(str(button_data))
3854
+ if kick_hit is not None:
3855
+ await self._resolve_kick_confirm(interaction, *kick_hit)
3856
+ return
3857
+ decision, approval_id = parse_decision(str(button_data))
3858
+ if decision is None:
3859
+ await self._interaction_result(interaction, 1)
3860
+ return
3861
+ if approval_id and approval_id in self._decided:
3862
+ log.info("approval %s already decided (%s); ignoring repeat click", short_id(approval_id), self._decided[approval_id])
3863
+ await self._interaction_result(interaction, 1)
3864
+ return
3865
+ conv_key = f"c2c:{clicker}" if clicker else self._owner_conv()
3866
+ # 先回执再干活:QQ 的交互回调有硬超时,超时后客户端会把按钮 data 当文本消息发出来
3867
+ # (表现就是群里多出一条「允许 <uuid>」)。
3868
+ await self._interaction_result(interaction, 0)
3869
+ self._spawn_approval(conv_key, decision, approval_id)
3870
+
3871
+ async def _interaction_result(self, interaction: Interaction, code: int) -> None:
3872
+ try:
3873
+ await self.api.on_interaction_result(interaction_id=interaction.id, code=code)
3874
+ except Exception as error: # noqa: BLE001 - best effort acknowledgement
3875
+ log.warning("interaction result failed: %s", error)
3876
+
3877
+ async def on_group_add_robot(self, event: Any) -> None:
3878
+ group_openid = getattr(event, "group_openid", "") or ""
3879
+ log.info("bot added to group %s", short_id(group_openid))
3880
+ self.group_state.pop(group_openid, None)
3881
+
3882
+ async def on_group_del_robot(self, event: Any) -> None:
3883
+ group_openid = getattr(event, "group_openid", "") or ""
3884
+ log.info("bot removed from group %s", short_id(group_openid))
3885
+ self.group_state.pop(group_openid, None)
3886
+ self.targets.pop(f"group:{group_openid}", None)
3887
+
3888
+ async def on_group_msg_receive(self, event: Any) -> None:
3889
+ group_openid = getattr(event, "group_openid", "") or ""
3890
+ log.info("group %s enabled proactive messages", short_id(group_openid))
3891
+ self.group_state.pop(group_openid, None)
3892
+
3893
+ async def on_group_msg_reject(self, event: Any) -> None:
3894
+ group_openid = getattr(event, "group_openid", "") or ""
3895
+ log.warning("group %s disabled proactive messages", short_id(group_openid))
3896
+ self.group_state.pop(group_openid, None)
3897
+
3898
+ def help_text(self) -> str:
3899
+ return "\n".join(
3900
+ [
3901
+ f"我是 {self.config.botname}:DeepSeek Harness 的 QQ 入口。",
3902
+ "· /状态 看授权、/窗口 列窗口、/截图 <关键字> 截图发你",
3903
+ "· 连续发几条会合并成一条再处理;发图我能看图",
3904
+ "· 群里 @ 我才干活,其它时候像群友一样听着、偶尔插一句",
3905
+ "· /新会话(/重置)清空上下文;群里 /绑定 把自己绑成群主",
3906
+ "· /会话 看绑定,/切会话 <id> 换会话,/切回 回到原会话",
3907
+ "· /花费 看本会话 token 用量(/花费 全部 看最近所有会话)",
3908
+ "· /菜单 弹出按钮面板,常用指令一点就走",
3909
+ "· /消息池 看最近 10 分钟收发(/池),/撤回 [n|#序号] 撤我发的或指定那条",
3910
+ "· 需要授权时审批发到主人单聊:点按钮或回「允许」/「拒绝」",
3911
+ ]
3912
+ )
3913
+
3914
+
3915
+ # --------------------------------------------------------------------------- #
3916
+ # process control: run / supervise (auto-restart + panel) / stop
3917
+ # --------------------------------------------------------------------------- #
3918
+ STATE_DIR = Path(os.environ.get("DSH_QQBOT_STATE_DIR") or (ROOT / "state"))
3919
+ LOG_DIR = ROOT / "logs"
3920
+ MEMBERS_FILE = STATE_DIR / "members.json"
3921
+ STREAMS_FILE = STATE_DIR / "streams.json"
3922
+ METRICS_FILE = STATE_DIR / "metrics.json"
3923
+ METRICS_DIR = STATE_DIR / "metrics"
3924
+ GROUPS_FILE = STATE_DIR / "groups.json"
3925
+ STOP_FLAG = STATE_DIR / "stop.flag"
3926
+ SUPERVISOR_PID = STATE_DIR / "supervisor.pid"
3927
+ CHILD_PID = STATE_DIR / "child.pid"
3928
+ CURSOR_FILE = ROOT / "state" / "cursor.txt"
3929
+ RESTART_DELAYS = (2, 5, 15, 30)
3930
+
3931
+
3932
+ def _write_pid(path: Path, pid: int) -> None:
3933
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
3934
+ path.write_text(str(pid), encoding="utf-8")
3935
+
3936
+
3937
+ def _read_pid(path: Path) -> Optional[int]:
3938
+ try:
3939
+ return int(path.read_text(encoding="utf-8").strip())
3940
+ except (OSError, ValueError):
3941
+ return None
3942
+
3943
+
3944
+ def _alive(pid: int) -> bool:
3945
+ """Whether the process still exists (Windows: tasklist, else signal 0)."""
3946
+ try:
3947
+ if os.name == "nt":
3948
+ result = subprocess.run(["tasklist", "/FI", f"PID eq {pid}"], capture_output=True, text=True)
3949
+ return str(pid) in (result.stdout or "")
3950
+ os.kill(pid, 0)
3951
+ return True
3952
+ except OSError:
3953
+ return False
3954
+
3955
+
3956
+ def _kill_tree(pid: int) -> None:
3957
+ """Terminate one process and its children (Windows taskkill, else SIGKILL)."""
3958
+ if pid <= 0:
3959
+ return
3960
+ try:
3961
+ if os.name == "nt":
3962
+ subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, check=False)
3963
+ else:
3964
+ os.kill(pid, signal.SIGKILL)
3965
+ except OSError as error:
3966
+ log.warning("could not stop pid %s: %s", pid, error)
3967
+
3968
+
3969
+
3970
+ def reason_text(value: Any) -> str:
3971
+ """Turn-end reason as a readable string (the host sends an object)."""
3972
+ if isinstance(value, str):
3973
+ # the host stringifies its turn-end object; treat that as "unknown"
3974
+ return '' if value.strip() in ('[object Object]', 'undefined', 'null') else value
3975
+ if isinstance(value, dict):
3976
+ for key in ('kind', 'type', 'reason', 'message'):
3977
+ if isinstance(value.get(key), str):
3978
+ return value[key]
3979
+ return ''
3980
+ return ''
3981
+
3982
+
3983
+ def _attachment_url(attachment):
3984
+ """Best-effort URL out of one quoted-media attachment."""
3985
+ if isinstance(attachment, str):
3986
+ return attachment.strip() or None
3987
+ if isinstance(attachment, dict):
3988
+ for key in ("url", "file_url", "remote_url", "src", "thumb_url"):
3989
+ value = attachment.get(key)
3990
+ if isinstance(value, str) and value.strip():
3991
+ return value.strip()
3992
+ return None
3993
+
3994
+
3995
+ def _sent_idx(result):
3996
+ """msg_idx of a message we just sent: QQ returns it as ext_info.ref_idx."""
3997
+ if isinstance(result, dict):
3998
+ ext = result.get("ext_info")
3999
+ if isinstance(ext, dict) and isinstance(ext.get("ref_idx"), str):
4000
+ return ext["ref_idx"]
4001
+ for key in ("msg_idx", "idx", "ref_idx"):
4002
+ if isinstance(result.get(key), str):
4003
+ return result[key]
4004
+ return ""
4005
+ for attr in ("msg_idx", "idx"):
4006
+ value = getattr(result, attr, "")
4007
+ if isinstance(value, str):
4008
+ return value
4009
+ return ""
4010
+
4011
+
4012
+ def _scene_ext(scene):
4013
+ """Flatten message_scene.ext into a dict of key -> value.
4014
+
4015
+ Real payloads carry a list like ["ref_msg_idx=REFIDX_...", "msg_idx=REFIDX_...",
4016
+ "auth_token=..."], so only explicit keys are trusted; anything else is noise.
4017
+ """
4018
+ if not isinstance(scene, dict):
4019
+ return {}
4020
+ flat = {}
4021
+ ext = scene.get("ext")
4022
+ if isinstance(ext, dict):
4023
+ flat.update({k: v for k, v in ext.items() if isinstance(v, str)})
4024
+ elif isinstance(ext, list):
4025
+ for entry in ext:
4026
+ if isinstance(entry, str) and "=" in entry:
4027
+ key, value = entry.split("=", 1)
4028
+ flat[key.strip()] = value.strip()
4029
+ elif isinstance(entry, dict):
4030
+ for key, value in entry.items():
4031
+ if isinstance(value, str):
4032
+ flat[str(key)] = value
4033
+ for key in ("ref_msg_idx", "msg_idx"):
4034
+ value = scene.get(key)
4035
+ if isinstance(value, str) and value.strip():
4036
+ flat.setdefault(key, value.strip())
4037
+ return flat
4038
+
4039
+
4040
+ AT_EVERYONE_TOKEN = "<qqbot-at-everyone />"
4041
+ OPENID_RE = re.compile(r"@?(?<!群友)(?<![0-9A-Za-z])([0-9A-Fa-f]{6,32})(?![0-9A-Za-z])")
4042
+ _AT_ALIAS_RE = re.compile(r"@群友([0-9A-Fa-f]{4,8})")
4043
+
4044
+
4045
+ def _decode_line(raw: bytes) -> str:
4046
+ """Child stdout may be UTF-8 or the legacy GBK console encoding."""
4047
+ for encoding in ("utf-8", "gbk"):
4048
+ try:
4049
+ return raw.decode(encoding)
4050
+ except UnicodeDecodeError:
4051
+ continue
4052
+ return raw.decode("utf-8", "replace")
4053
+
4054
+
4055
+ def _heartbeat() -> None:
4056
+ try:
4057
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
4058
+ (STATE_DIR / "alive.txt").write_text(str(time.time()), encoding="utf-8")
4059
+ except OSError:
4060
+ pass
4061
+
4062
+
4063
+ def run_bot() -> int:
4064
+ """One bot process, no supervision."""
4065
+ from dataclasses import replace as dataclass_replace
4066
+
4067
+ from runtime_config import RuntimeConfig
4068
+
4069
+ configure_logging(log_file=str(LOG_DIR / "viseron_qqbotpy.log"))
4070
+ config = load_config()
4071
+ runtime = RuntimeConfig()
4072
+ overrides = {}
4073
+ if runtime.get("appid"):
4074
+ overrides["appid"] = str(runtime.get("appid"))
4075
+ if runtime.get("appsecret"):
4076
+ overrides["secret"] = str(runtime.get("appsecret"))
4077
+ if runtime.get("bridge_url"):
4078
+ overrides["bridge_url"] = str(runtime.get("bridge_url"))
4079
+ if runtime.get("bridge_token"):
4080
+ overrides["bridge_token"] = str(runtime.get("bridge_token"))
4081
+ if overrides:
4082
+ config = dataclass_replace(config, **overrides)
4083
+ bot = DSHBot(intents=Intents.default(), config=config)
4084
+ bot.rt = runtime
4085
+ log.info("[%s] starting appid=%s bridge=%s", config.botname, config.appid, config.bridge_url)
4086
+ bot.run(appid=config.appid, secret=config.secret)
4087
+ return 0
4088
+
4089
+
4090
+ def supervise() -> int:
4091
+ """Own the bot process and the settings page (面板 + 日志 + 进程管理)."""
4092
+ from panel import start_panel
4093
+ from runtime_config import RuntimeConfig
4094
+ from viseron_qqbotpy import load_env
4095
+
4096
+ # 守护进程写自己的日志文件:两个进程同写一个文件会让轮转报 WinError 32,
4097
+ # 日志永远切不开(旧日志会一直涨并淹没真实错误)。
4098
+ try:
4099
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
4100
+ configure_logging(log_file=str(LOG_DIR / "supervisor.log"))
4101
+ except Exception as error: # noqa: BLE001 - logging must never block startup
4102
+ print(f"[supervisor] logging setup failed: {error}", flush=True)
4103
+
4104
+ load_env(ROOT / ".env")
4105
+ runtime = RuntimeConfig()
4106
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
4107
+
4108
+ # Single instance only: two supervisors share config.json and would fight
4109
+ # over desired_running (visible as a bot that starts and stops by itself).
4110
+ existing = _read_pid(SUPERVISOR_PID)
4111
+ if existing and existing != os.getpid() and _alive(existing):
4112
+ print(f"[supervisor] already running as pid={existing}; exiting", flush=True)
4113
+ return 0
4114
+
4115
+ STOP_FLAG.unlink(missing_ok=True)
4116
+ _write_pid(SUPERVISOR_PID, os.getpid())
4117
+
4118
+ state: Dict[str, Any] = {"child": None, "started_at": 0.0, "attempt": 0, "next_at": 0.0, "note": "starting", "log": []}
4119
+ lock = threading.Lock()
4120
+ log_path = STATE_DIR / "bot-output.log"
4121
+ no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if os.name == "nt" else 0
4122
+
4123
+ def pump(stream: Any) -> None:
4124
+ """Mirror the child's console output into a ring buffer and a file."""
4125
+ try:
4126
+ handle = open(log_path, "ab", buffering=0)
4127
+ except OSError:
4128
+ handle = None
4129
+ try:
4130
+ for raw in iter(stream.readline, b""):
4131
+ line = _decode_line(raw).rstrip("\r\n")
4132
+ line = re.sub(r"\x1b\[[0-9;]*m", "", line)
4133
+ if line.strip() == "":
4134
+ continue
4135
+ with lock:
4136
+ ring = state["log"]
4137
+ ring.append(line)
4138
+ if len(ring) > 600:
4139
+ del ring[: len(ring) - 600]
4140
+ if handle is not None:
4141
+ try:
4142
+ handle.write((line + "\n").encode("utf-8", "replace"))
4143
+ except OSError:
4144
+ pass
4145
+ finally:
4146
+ if handle is not None:
4147
+ handle.close()
4148
+
4149
+ def online() -> bool:
4150
+ try:
4151
+ return (time.time() - (STATE_DIR / "alive.txt").stat().st_mtime) < 45
4152
+ except OSError:
4153
+ return False
4154
+
4155
+ def bridge_state() -> str:
4156
+ import json as _json
4157
+ import urllib.request
4158
+ url = str(runtime.get("bridge_url") or "")
4159
+ token = str(runtime.get("bridge_token") or os.getenv("BRIDGE_TOKEN", ""))
4160
+ if not url:
4161
+ return "unset"
4162
+ try:
4163
+ request = urllib.request.Request(url.rstrip("/") + "/health", headers={"x-bridge-token": token})
4164
+ with urllib.request.urlopen(request, timeout=2) as response:
4165
+ payload = _json.loads(response.read().decode("utf-8"))
4166
+ return str(payload.get("service") or "unknown")
4167
+ except Exception:
4168
+ return "down"
4169
+
4170
+ def spawn() -> None:
4171
+ with lock:
4172
+ child = state["child"]
4173
+ if child is not None and child.poll() is None:
4174
+ return
4175
+ child_env = dict(os.environ)
4176
+ child_env["PYTHONIOENCODING"] = "utf-8"
4177
+ child_env["PYTHONUTF8"] = "1"
4178
+ process = subprocess.Popen(
4179
+ [sys.executable, "-u", str(Path(__file__).resolve()), "--run"],
4180
+ cwd=str(ROOT),
4181
+ stdout=subprocess.PIPE,
4182
+ stderr=subprocess.STDOUT,
4183
+ creationflags=no_window,
4184
+ env=child_env,
4185
+ )
4186
+ state["child"] = process
4187
+ state["started_at"] = time.time()
4188
+ state["note"] = f"bot pid={process.pid} up"
4189
+ _write_pid(CHILD_PID, process.pid)
4190
+ threading.Thread(target=pump, args=(process.stdout,), daemon=True).start()
4191
+ print(f"[supervisor] bot pid={process.pid} up", flush=True)
4192
+
4193
+ def kill_child() -> None:
4194
+ with lock:
4195
+ child = state["child"]
4196
+ if child is None:
4197
+ return
4198
+ if child.poll() is None:
4199
+ _kill_tree(child.pid)
4200
+ state["child"] = None
4201
+ CHILD_PID.unlink(missing_ok=True)
4202
+ print("[supervisor] bot stopped", flush=True)
4203
+
4204
+ async def perform(action: str) -> str:
4205
+ if action == "start":
4206
+ runtime.update({"desired_running": True})
4207
+ STOP_FLAG.unlink(missing_ok=True)
4208
+ state["attempt"] = 0
4209
+ state["next_at"] = 0.0
4210
+ spawn()
4211
+ state["note"] = "已启动"
4212
+ return "已启动"
4213
+ if action == "stop":
4214
+ runtime.update({"desired_running": False})
4215
+ kill_child()
4216
+ state["note"] = "已停止(不会自动拉起)"
4217
+ return "已停止(不会自动拉起)"
4218
+ runtime.update({"desired_running": True})
4219
+ STOP_FLAG.unlink(missing_ok=True)
4220
+ kill_child()
4221
+ state["attempt"] = 0
4222
+ state["next_at"] = 0.0
4223
+ time.sleep(0.6)
4224
+ spawn()
4225
+ state["note"] = "已重启(凭据等改动已生效)"
4226
+ return "已重启(凭据等改动已生效)"
4227
+
4228
+ def status() -> Dict[str, Any]:
4229
+ child = state["child"]
4230
+ running = child is not None and child.poll() is None
4231
+ note = state.get("note", "")
4232
+ if runtime.get_bool("desired_running") is False:
4233
+ note = "已停止(不会自动拉起)"
4234
+ return {
4235
+ "running": running,
4236
+ "pid": child.pid if running else 0,
4237
+ "online": running and online(),
4238
+ "desired": runtime.get_bool("desired_running"),
4239
+ "supervisor": os.getpid(),
4240
+ "uptime_s": int(time.time() - state["started_at"]) if running else 0,
4241
+ "note": note,
4242
+ }
4243
+
4244
+ def logs(limit: int = 300) -> List[str]:
4245
+ with lock:
4246
+ return list(state["log"])[-max(1, min(limit, 600)):]
4247
+
4248
+ control = type("Control", (), {
4249
+ "status": staticmethod(status),
4250
+ "perform": staticmethod(perform),
4251
+ "bridge_state": staticmethod(bridge_state),
4252
+ "logs": staticmethod(logs),
4253
+ })
4254
+
4255
+ host = str(runtime.get("panel_host") or "127.0.0.1")
4256
+ port = runtime.get_int("panel_port")
4257
+ token = str(runtime.get("bridge_token") or os.getenv("PANEL_TOKEN") or os.getenv("BRIDGE_TOKEN", ""))
4258
+ start_panel(control, runtime, host, port, token)
4259
+
4260
+ print(f"[supervisor] pid={os.getpid()} supervising (panel http://{host}:{port}/)", flush=True)
4261
+ try:
4262
+ while True:
4263
+ desired = runtime.get_bool("desired_running")
4264
+ child = state["child"]
4265
+ running = child is not None and child.poll() is None
4266
+
4267
+ if running and not desired:
4268
+ kill_child()
4269
+ elif desired and not running:
4270
+ if child is not None:
4271
+ code = child.returncode
4272
+ print(f"[supervisor] bot exited code={code}", flush=True)
4273
+ state["child"] = None
4274
+ CHILD_PID.unlink(missing_ok=True)
4275
+ uptime = time.time() - state["started_at"]
4276
+ state["attempt"] = 0 if uptime > 300 else state["attempt"] + 1
4277
+ delay = RESTART_DELAYS[min(state["attempt"] - 1, len(RESTART_DELAYS) - 1)] if state["attempt"] else 2
4278
+ state["next_at"] = time.time() + delay
4279
+ state["note"] = f"崩溃退出(code={code}),{delay}s 后重启"
4280
+ print(f"[supervisor] restarting in {delay}s", flush=True)
4281
+ if time.time() >= state["next_at"]:
4282
+ spawn()
4283
+
4284
+ time.sleep(1.0)
4285
+ except KeyboardInterrupt:
4286
+ print("[supervisor] interrupted", flush=True)
4287
+ kill_child()
4288
+ return 0
4289
+ finally:
4290
+ STOP_FLAG.unlink(missing_ok=True)
4291
+ for path in (CHILD_PID, SUPERVISOR_PID):
4292
+ path.unlink(missing_ok=True)
4293
+
4294
+
4295
+ def request_stop() -> int:
4296
+ """Stop everything: park the bot and end the supervisor process."""
4297
+ from runtime_config import RuntimeConfig
4298
+
4299
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
4300
+ RuntimeConfig().update({"desired_running": False})
4301
+ STOP_FLAG.write_text("stop", encoding="utf-8")
4302
+ supervisor = _read_pid(SUPERVISOR_PID)
4303
+ child = _read_pid(CHILD_PID)
4304
+ print(f"[stop] flag written (supervisor={supervisor}, bot={child})", flush=True)
4305
+ if child:
4306
+ _kill_tree(child)
4307
+ if supervisor:
4308
+ for _ in range(60):
4309
+ time.sleep(0.1)
4310
+ if not _alive(supervisor):
4311
+ break
4312
+ else:
4313
+ _kill_tree(supervisor)
4314
+ for path in (CHILD_PID, SUPERVISOR_PID):
4315
+ path.unlink(missing_ok=True)
4316
+ print("[stop] stopped; panel and auto-restart are off until the next start", flush=True)
4317
+ return 0
4318
+
4319
+
4320
+ def main() -> int:
4321
+ parser = argparse.ArgumentParser(description="DeepSeek Harness QQ bot")
4322
+ group = parser.add_mutually_exclusive_group()
4323
+ group.add_argument("--run", action="store_true", help="run the bot only (used by --supervise)")
4324
+ group.add_argument("--supervise", action="store_true", help="run with auto-restart and the settings panel")
4325
+ group.add_argument("--stop", action="store_true", help="stop a supervised bot and keep it stopped")
4326
+ args = parser.parse_args()
4327
+ if args.stop:
4328
+ return request_stop()
4329
+ if args.supervise:
4330
+ return supervise()
4331
+ return run_bot()
4332
+
4333
+
4334
+ if __name__ == "__main__":
4335
+ sys.exit(main())