@mcviseron/dsh-qq-bridge 0.2.1 → 0.3.1

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