@mcviseron/dsh-qq-bridge 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,14 @@ DeepSeek Harness Host 插件:把 QQ 会话映射成 DSH Session。
19
19
  | `approvalTimeoutMs` | 180000 | 审批等待上限,超时按 `approvalDefault` |
20
20
  | `approvalDefault` | reject | 超时结果 |
21
21
 
22
+ ## 一键装机器人环境
23
+
24
+ 设置页「机器人环境」里的 **下载 / 配置机器人** 会在 `<DSH_HOME>/qq-bridge/` 下把机器人装好:
25
+ 找系统 Python(3.10+)→ 建 `venv` → pip 装 aiohttp / Pillow / viseron-qqbotpy(直连失败自动换清华镜像)
26
+ → 复制随包的 `bot/` 源码(跳过 state/logs/`.env`/config.json)→ 写 `bot/config.json` 的
27
+ AppID / AppSecret / 分组根目录 → 拉起 `main.py --supervise`。
28
+ 装完落 `install.json`,之后自动启动优先用里面的 venv 解释器;重复点会复用已有 venv。
29
+
22
30
  ## HTTP 路由(全部要求 `x-bridge-token`,且只接受回环来源)
23
31
 
24
32
  | 方法与路径 | 请求 | 响应 |
@@ -0,0 +1,32 @@
1
+ # 复制为 .env 后填写;.env 不要提交仓库
2
+ BOTNAME=DSH
3
+ APPID=
4
+ APPSECRET=
5
+
6
+ # 主人 QQ 的 openid(留空则首次单聊自动认领并写回 bot/state.json)
7
+ OWNER_OPENID=
8
+
9
+ # DSH 插件 dsh-qq-bridge 的本地回环地址与令牌(令牌须与 profile 里 qq-bridge 条目的 token 一致)
10
+ BRIDGE_URL=http://127.0.0.1:39061
11
+ BRIDGE_TOKEN=
12
+
13
+ # 运行参数
14
+ QQ_SANDBOX=0
15
+ GROUP_ENABLED=1
16
+ # 群消息全量模式:能看到每条群消息(只做上下文,不逐条回),并低频插话
17
+ GROUP_FULL_MODE=1
18
+ GROUP_CHIME_MIN=8
19
+ GROUP_CHIME_COOLDOWN=240
20
+ # 群主身份走平台接口校验(内邀能力未开通时退回 /绑定)
21
+ OWNER_ROLE_CHECK=1
22
+ HTTP_TIMEOUT=60
23
+ MAX_CHARS=1600
24
+ PULL_WAIT_MS=25000
25
+ ACK_DELAY_S=12
26
+ ACK_TEXT=(还在处理,请稍等…)
27
+ # 连续消息合并:安静 1.8s 或最长 6s 后合成一条
28
+ DEBOUNCE_MS=1800
29
+ DEBOUNCE_MAX_MS=6000
30
+ # 回复里出现 Markdown 就用 msg_type=2 的 MD 消息发
31
+ MD_AUTO=1
32
+ IMAGE_MAX_MB=8
package/bot/bridge.py ADDED
@@ -0,0 +1,339 @@
1
+ """Loopback HTTP client for the dsh-qq-bridge DSH plugin.
2
+
3
+ The plugin owns the DSH Sessions; this module is only the transport between
4
+ the QQ gateway and that plugin, so nothing here knows about agents or tools.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import base64
10
+ import io
11
+ import json
12
+ import logging
13
+ from typing import Any, Dict, List, Optional, Tuple
14
+
15
+ import aiohttp
16
+
17
+ # QQ 侧只认这几种图片类型
18
+ IMAGE_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}
19
+
20
+ log = logging.getLogger("dsh.bot.bridge")
21
+
22
+
23
+ class BridgeError(RuntimeError):
24
+ """The bridge plugin is unreachable or answered with an error."""
25
+
26
+
27
+ class BridgeClient:
28
+ """Thin async client for the plugin's loopback routes."""
29
+
30
+ def __init__(self, base_url: str, token: str, *, timeout: float = 120.0) -> None:
31
+ self.base_url = base_url.rstrip("/")
32
+ self.token = token
33
+ self.timeout = timeout
34
+ self._session: Optional[aiohttp.ClientSession] = None
35
+
36
+ async def _session_or_create(self) -> aiohttp.ClientSession:
37
+ if self._session is None or self._session.closed:
38
+ self._session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout))
39
+ return self._session
40
+
41
+ async def close(self) -> None:
42
+ if self._session is not None and not self._session.closed:
43
+ await self._session.close()
44
+ self._session = None
45
+
46
+ async def _request(
47
+ self,
48
+ method: str,
49
+ path: str,
50
+ *,
51
+ params: Optional[Dict[str, Any]] = None,
52
+ payload: Optional[Dict[str, Any]] = None,
53
+ ) -> Dict[str, Any]:
54
+ session = await self._session_or_create()
55
+ headers = {"x-bridge-token": self.token} if self.token else {}
56
+ url = f"{self.base_url}{path}"
57
+ try:
58
+ async with session.request(method, url, params=params, json=payload, headers=headers) as response:
59
+ body = await response.text()
60
+ if response.status != 200:
61
+ raise BridgeError(f"{method} {path} -> {response.status}: {body[:300]}")
62
+ return json.loads(body) if body.strip() else {}
63
+ except aiohttp.ClientError as error:
64
+ raise BridgeError(f"{method} {path} failed: {error}") from error
65
+
66
+ async def health(self) -> Dict[str, Any]:
67
+ return await self._request("GET", "/health")
68
+
69
+ async def status(self) -> Dict[str, Any]:
70
+ return await self._request("GET", "/status")
71
+
72
+ async def inbound(
73
+ self,
74
+ *,
75
+ conv_key: str,
76
+ text: str,
77
+ sender_name: str = "",
78
+ is_owner: bool = False,
79
+ approval_target: str = "",
80
+ images: Optional[List[Dict[str, str]]] = None,
81
+ context_only: bool = False,
82
+ chime: bool = False,
83
+ quote: Optional[Dict[str, Any]] = None,
84
+ auto_group: Optional[bool] = None,
85
+ auto_group_root: Optional[str] = None,
86
+ persona: str = "",
87
+ ) -> Dict[str, Any]:
88
+ """Hand one QQ message to DSH; the answer arrives through :meth:`pull`.
89
+
90
+ `context_only` only feeds the plugin's rolling group transcript, so
91
+ background chatter costs no agent turn.
92
+ """
93
+ return await self._request(
94
+ "POST",
95
+ "/inbound",
96
+ payload={
97
+ "convKey": conv_key,
98
+ "text": text,
99
+ "senderName": sender_name,
100
+ "isOwner": bool(is_owner),
101
+ "approvalTarget": approval_target,
102
+ "images": images or [],
103
+ "contextOnly": bool(context_only),
104
+ "chime": bool(chime),
105
+ "quote": quote,
106
+ "autoGroup": auto_group,
107
+ "autoGroupRoot": auto_group_root,
108
+ "persona": persona,
109
+ },
110
+ )
111
+
112
+ async def judge(
113
+ self, conv_key: str, transcript: str, *, threshold: int = 2, hint: str = ""
114
+ ) -> Dict[str, Any]:
115
+ """Ask the plugin's independent judge session whether to answer."""
116
+ return await self._request(
117
+ "POST",
118
+ "/judge",
119
+ payload={"convKey": conv_key, "transcript": transcript, "threshold": int(threshold), "hint": hint},
120
+ )
121
+
122
+ async def answer_question(self, question_id: str, index: int) -> Dict[str, Any]:
123
+ """Deliver a picked option back to the plugin's pending user-questions/request."""
124
+ return await self._request("POST", "/answer", payload={"id": question_id, "index": int(index)})
125
+
126
+ async def commands(self, conv_key: str) -> Dict[str, Any]:
127
+ """List the DSH slash commands available to this conversation's session."""
128
+ return await self._request("POST", "/commands", payload={"convKey": conv_key})
129
+
130
+ async def run_command(self, conv_key: str, line: str) -> Dict[str, Any]:
131
+ """Execute one DSH slash command through the official command runtime."""
132
+ return await self._request("POST", "/command", payload={"convKey": conv_key, "line": line})
133
+
134
+ async def rebind(self, conv_key: str) -> Dict[str, Any]:
135
+ """Re-create the DSH session for one conversation (used by /分组)."""
136
+ return await self._request("POST", "/rebind", payload={"convKey": conv_key})
137
+
138
+ async def permission(self, conv_key: str, preset: Optional[str] = None) -> Dict[str, Any]:
139
+ """Read or switch the DSH permission preset for one conversation."""
140
+ return await self._request(
141
+ "POST",
142
+ "/permission",
143
+ payload={"convKey": conv_key, "preset": preset or ""},
144
+ )
145
+
146
+ async def pull(self, cursor: Optional[int], wait_ms: int) -> Dict[str, Any]:
147
+ """Long-poll the outbox; cursor=None starts from the current tail."""
148
+ params: Dict[str, Any] = {"wait": max(0, int(wait_ms))}
149
+ if cursor is not None:
150
+ params["since"] = int(cursor)
151
+ return await self._request("GET", "/pull", params=params)
152
+
153
+ async def approve(self, approval_id: str, decision: str) -> Dict[str, Any]:
154
+ """Answer one pending approval: allow / reject / cancel."""
155
+ return await self._request(
156
+ "POST",
157
+ "/approval",
158
+ payload={"approvalId": approval_id, "decision": decision},
159
+ )
160
+
161
+ async def switch_session(self, conv_key: str, session_id: str) -> Dict[str, Any]:
162
+ """Rebind one QQ conversation onto another existing Session ("" = go back)."""
163
+ return await self._request(
164
+ "POST",
165
+ "/switch",
166
+ payload={"convKey": conv_key, "sessionId": session_id},
167
+ )
168
+
169
+ async def sessions(self) -> Dict[str, Any]:
170
+ """Bindings this plugin knows plus the Host's own Session list."""
171
+ return await self._request("GET", "/sessions")
172
+
173
+ async def reset(self, conv_key: str) -> Dict[str, Any]:
174
+ """Forget the conversation's Session binding so the next message starts fresh."""
175
+ return await self._request("POST", "/reset", payload={"convKey": conv_key})
176
+
177
+
178
+ def normalize_image(data: bytes, *, max_side: int = 1280, budget: int = 400_000) -> Optional[Tuple[bytes, str]]:
179
+ """Re-encode any decodable image into a clean PNG/JPEG for DSH.
180
+
181
+ DSH decodes image bytes with sharp and rejects anything it cannot parse, so
182
+ the payload is normalized here instead of trusting the source format: this
183
+ also drops odd EXIF/ICC profiles and shrinks screenshots before upload.
184
+ """
185
+ try:
186
+ from PIL import Image, ImageFile
187
+ # QQ's CDN regularly cuts the tail of a transfer (measured: exactly 64 KiB
188
+ # dumps missing the JPEG EOI); Pillow refuses those unless truncation is
189
+ # tolerated. The re-encode below always emits a complete file.
190
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
191
+ except ImportError:
192
+ log.warning("Pillow is not installed; keeping the original image bytes")
193
+ return None
194
+ try:
195
+ with Image.open(io.BytesIO(data)) as image:
196
+ image.load()
197
+ image = image.convert("RGB")
198
+ if max(image.size) > max_side:
199
+ image.thumbnail((max_side, max_side))
200
+ buffer = io.BytesIO()
201
+ image.save(buffer, format="PNG", optimize=True)
202
+ png = buffer.getvalue()
203
+ if len(png) <= budget:
204
+ return png, "image/png"
205
+ # The bridge caps its JSON body at 1 MiB, so keep the encoded image
206
+ # small enough that base64 (+33%) always fits.
207
+ for quality in (85, 75, 65, 55):
208
+ buffer = io.BytesIO()
209
+ image.save(buffer, format="JPEG", quality=quality, optimize=True)
210
+ jpeg = buffer.getvalue()
211
+ if len(jpeg) <= budget:
212
+ return jpeg, "image/jpeg"
213
+ return jpeg, "image/jpeg"
214
+ except Exception as error: # noqa: BLE001 - retry once with truncated input allowed
215
+ try:
216
+ from PIL import Image, ImageFile
217
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
218
+ with Image.open(io.BytesIO(data)) as image:
219
+ image.load()
220
+ image = image.convert("RGB")
221
+ if max(image.size) > max_side:
222
+ image.thumbnail((max_side, max_side))
223
+ buffer = io.BytesIO()
224
+ image.save(buffer, format="JPEG", quality=80, optimize=True)
225
+ return buffer.getvalue(), "image/jpeg"
226
+ except Exception: # noqa: BLE001 - really not decodable
227
+ print(f"[image] re-encode failed: {error}", flush=True)
228
+ return None
229
+
230
+
231
+ def sniff_media_type(data: bytes) -> str:
232
+ """Detect the real image type from magic bytes (QQ often lies in Content-Type)."""
233
+ if data[:8] == b"\x89PNG\r\n\x1a\n":
234
+ return "image/png"
235
+ if data[:3] == b"\xff\xd8\xff":
236
+ return "image/jpeg"
237
+ if data[:6] in (b"GIF87a", b"GIF89a"):
238
+ return "image/gif"
239
+ if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
240
+ return "image/webp"
241
+ return ""
242
+
243
+
244
+ def normalize_media_type(content_type: str) -> str:
245
+ """Map the platform's MIME spelling onto the types DSH accepts."""
246
+ value = (content_type or "").split(";")[0].strip().lower()
247
+ if value in {"image/jpg", "image/pjpeg"}:
248
+ return "image/jpeg"
249
+ return value if value in IMAGE_TYPES else ""
250
+
251
+
252
+ async def download_image(
253
+ url: str,
254
+ *,
255
+ max_bytes: int,
256
+ dump_dir: Optional[str] = None,
257
+ ) -> Optional[Dict[str, str]]:
258
+ """Fetch one QQ attachment URL and return a base64 image part for DSH.
259
+
260
+ DSH decodes image bytes with sharp and rejects anything that is not a real
261
+ png/jpeg/webp/gif, so the type is sniffed from magic bytes here; a body that
262
+ is not a supported image is optionally dumped for diagnosis and skipped.
263
+ """
264
+ if not url:
265
+ return None
266
+
267
+ # QQ's CDN occasionally closes the connection early; a partial JPEG then
268
+ # decodes as garbage. Read the whole body, check it against Content-Length,
269
+ # and retry a couple of times before giving up.
270
+ timeout = aiohttp.ClientTimeout(total=60, sock_read=45)
271
+ header_type = ""
272
+ status = 0
273
+ expected = -1
274
+ raw = b""
275
+ for attempt in range(1, 4):
276
+ try:
277
+ async with aiohttp.ClientSession(timeout=timeout) as session:
278
+ async with session.get(url, headers={"Accept": "image/*,*/*"}) as response:
279
+ status = response.status
280
+ header_type = response.headers.get("content-type", "")
281
+ expected = response.content_length if response.content_length is not None else -1
282
+ if response.status != 200:
283
+ raw = b""
284
+ break
285
+ raw = await response.read()
286
+ except (aiohttp.ClientError, TimeoutError) as error:
287
+ print(f"[image] download attempt {attempt} failed: {error}", flush=True)
288
+ await asyncio.sleep(0.4 * attempt)
289
+ continue
290
+ if expected < 0 or len(raw) >= expected:
291
+ break
292
+ print(
293
+ f"[image] truncated download attempt {attempt}: {len(raw)}/{expected} bytes",
294
+ flush=True,
295
+ )
296
+ await asyncio.sleep(0.4 * attempt)
297
+
298
+ if not raw:
299
+ return None
300
+ if len(raw) > max_bytes:
301
+ print(f"[image] refusing {len(raw)} bytes (limit {max_bytes})", flush=True)
302
+ return None
303
+ sniffed = sniff_media_type(raw)
304
+ normalized = normalize_image(raw) if raw else None
305
+ if normalized is not None:
306
+ media_type, data = normalized[1], normalized[0]
307
+ elif sniffed and len(raw) <= max_bytes:
308
+ # Pillow missing or unable to decode: the magic bytes still describe a
309
+ # real png/jpeg/webp/gif, which DSH's sharp decoder accepts as-is.
310
+ media_type, data = sniffed, raw
311
+ else:
312
+ media_type = ""
313
+
314
+ if dump_dir and raw:
315
+ try:
316
+ import os as _os
317
+ import time as _time
318
+ _os.makedirs(dump_dir, exist_ok=True)
319
+ tag = "ok" if media_type else "bad"
320
+ path = _os.path.join(dump_dir, f"{tag}-{_time.strftime('%Y%m%d-%H%M%S')}.bin")
321
+ with open(path, "wb") as handle:
322
+ handle.write(raw[: 4 * 1024 * 1024])
323
+ log.info(
324
+ "[image] %s: status=%s header=%r sniffed=%s raw=%d normalized=%d head=%r dump=%s",
325
+ tag,
326
+ status,
327
+ header_type,
328
+ sniffed or "unknown",
329
+ len(raw),
330
+ len(data) if media_type else 0,
331
+ raw[:16],
332
+ path,
333
+ )
334
+ except OSError:
335
+ pass
336
+
337
+ if not media_type or len(data) > max_bytes:
338
+ return None
339
+ return {"mediaType": media_type, "data": base64.b64encode(data).decode("ascii")}
@@ -0,0 +1,31 @@
1
+ """Fail if a method that is not 'async def' is awaited anywhere in main.py."""
2
+ import ast
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ source = Path("main.py").read_text(encoding="utf-8")
7
+ tree = ast.parse(source)
8
+
9
+ sync_methods = set()
10
+ async_methods = set()
11
+ for node in ast.walk(tree):
12
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
13
+ (async_methods if isinstance(node, ast.AsyncFunctionDef) else sync_methods).add(node.name)
14
+
15
+ problems = []
16
+ for node in ast.walk(tree):
17
+ if isinstance(node, ast.Await) and isinstance(node.value, ast.Call):
18
+ call = node.value.func
19
+ name = None
20
+ if isinstance(call, ast.Attribute) and isinstance(call.value, ast.Name) and call.value.id == "self":
21
+ name = call.attr
22
+ elif isinstance(call, ast.Name):
23
+ name = call.id
24
+ if name and name in sync_methods and name not in async_methods:
25
+ problems.append((node.lineno, name))
26
+
27
+ if problems:
28
+ for line, name in problems:
29
+ print(f"AWAIT_OF_SYNC {name} at main.py:{line}")
30
+ sys.exit(1)
31
+ print(f"OK: no awaited sync function ({len(sync_methods)} sync / {len(async_methods)} async defined)")