@tencent-connect/openclaw-qqbot 1.7.1 → 2.0.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.
Files changed (283) hide show
  1. package/README.md +206 -4
  2. package/README.zh.md +207 -4
  3. package/bin/qqbot-cli.js +5 -2
  4. package/dist/index.cjs +15549 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +890 -0
  7. package/index.ts +56 -18
  8. package/openclaw.plugin.json +19 -3
  9. package/package.json +14 -23
  10. package/preload.cjs +17 -14
  11. package/scripts/link-sdk-core.cjs +133 -50
  12. package/scripts/upgrade-via-npm.sh +400 -73
  13. package/scripts/upgrade-via-source.sh +126 -89
  14. package/skills/qqbot-channel/SKILL.md +34 -12
  15. package/src/adapter/contract.ts +69 -0
  16. package/src/adapter/gateway.ts +61 -0
  17. package/src/adapter/index.ts +15 -0
  18. package/src/adapter/lint.ts +144 -0
  19. package/src/adapter/media.ts +112 -0
  20. package/src/adapter/pairing.ts +99 -0
  21. package/src/adapter/resolve.ts +333 -0
  22. package/src/adapter/setup.ts +55 -0
  23. package/src/adapter/webhook.ts +248 -0
  24. package/src/adapter/workspace.ts +29 -0
  25. package/src/bot-instance.ts +60 -0
  26. package/src/channel.ts +202 -413
  27. package/src/commands/bot-approve.ts +143 -0
  28. package/src/commands/bot-clear-storage.ts +114 -0
  29. package/src/commands/bot-group-always.ts +62 -0
  30. package/src/commands/bot-help.ts +40 -0
  31. package/src/commands/bot-logs.ts +248 -0
  32. package/src/commands/bot-me.ts +18 -0
  33. package/src/commands/bot-pairing.ts +57 -0
  34. package/src/commands/bot-ping.ts +33 -0
  35. package/src/commands/bot-streaming.ts +55 -0
  36. package/src/commands/bot-upgrade.ts +56 -0
  37. package/src/commands/bot-version.ts +41 -0
  38. package/src/commands/config-util.ts +96 -0
  39. package/src/commands/index.ts +49 -0
  40. package/src/config.ts +59 -19
  41. package/src/dispatch/body-assembler.ts +356 -0
  42. package/src/dispatch/ctx-builder.ts +110 -0
  43. package/src/dispatch/dispatch.ts +352 -0
  44. package/src/dispatch/envelope-builder.ts +112 -0
  45. package/src/dispatch/index.ts +2 -0
  46. package/src/{approval-handler.ts → features/approval-handler.ts} +40 -94
  47. package/src/features/approval-utils.ts +41 -0
  48. package/src/features/credential-backup.ts +82 -0
  49. package/src/features/history-store.ts +19 -0
  50. package/src/features/msgid-cache.ts +55 -0
  51. package/src/features/onboarding.ts +38 -0
  52. package/src/{proactive.ts → features/proactive.ts} +68 -49
  53. package/src/features/ref-index-store.ts +282 -0
  54. package/src/{update-checker.ts → features/update-checker.ts} +15 -35
  55. package/src/gateway/event-handlers.ts +241 -0
  56. package/src/gateway/index.ts +3 -0
  57. package/src/gateway/lifecycle.ts +221 -0
  58. package/src/gateway/middleware-setup.ts +139 -0
  59. package/src/gateway/qqbot-gateway.ts +342 -0
  60. package/src/middleware/access-control.ts +130 -0
  61. package/src/middleware/attachment.ts +314 -0
  62. package/src/middleware/policy-injector.ts +66 -0
  63. package/src/openclaw-plugin-sdk.d.ts +81 -10
  64. package/src/outbound/cron-scheduler.ts +130 -0
  65. package/src/outbound/debounce.ts +102 -0
  66. package/src/outbound/deliver-pipeline.ts +235 -0
  67. package/src/outbound/image-size.ts +123 -0
  68. package/src/outbound/index.ts +3 -0
  69. package/src/outbound/local-file-router.ts +145 -0
  70. package/src/outbound/media-send.ts +377 -0
  71. package/src/outbound/outbound-service.ts +222 -0
  72. package/src/outbound/reply-limiter.ts +128 -0
  73. package/src/outbound/sanitize.ts +32 -0
  74. package/src/outbound/streaming-controller.ts +228 -0
  75. package/src/outbound/target.ts +63 -0
  76. package/src/outbound/tts-provider.ts +84 -0
  77. package/src/request-context.ts +9 -8
  78. package/src/runtime.ts +31 -6
  79. package/src/setup/account-key.ts +41 -0
  80. package/src/setup/finalize.ts +110 -0
  81. package/src/setup/login.ts +197 -0
  82. package/src/setup/surface.ts +40 -0
  83. package/src/tools/platform.ts +149 -0
  84. package/src/tools/remind.ts +1 -1
  85. package/src/types-augment.d.ts +54 -0
  86. package/src/types.ts +71 -8
  87. package/src/typings/openclaw-webhook-ingress.d.ts +66 -0
  88. package/src/utils/mention.ts +52 -0
  89. package/src/utils/pkg-version.ts +84 -47
  90. package/src/utils/platform.ts +31 -7
  91. package/src/utils/plugin-logger.ts +104 -0
  92. package/src/utils/ssrf-guard.ts +32 -2
  93. package/src/utils/stt.ts +137 -0
  94. package/src/utils/voice-text.ts +61 -0
  95. package/tsconfig.json +2 -1
  96. package/tsup.config.ts +57 -0
  97. package/dist/index.d.ts +0 -17
  98. package/dist/index.js +0 -26
  99. package/dist/src/admin-resolver.d.ts +0 -33
  100. package/dist/src/admin-resolver.js +0 -157
  101. package/dist/src/api.d.ts +0 -307
  102. package/dist/src/api.js +0 -910
  103. package/dist/src/approval-handler.d.ts +0 -47
  104. package/dist/src/approval-handler.js +0 -372
  105. package/dist/src/channel.d.ts +0 -29
  106. package/dist/src/channel.js +0 -528
  107. package/dist/src/config.d.ts +0 -56
  108. package/dist/src/config.js +0 -278
  109. package/dist/src/credential-backup.d.ts +0 -31
  110. package/dist/src/credential-backup.js +0 -66
  111. package/dist/src/deliver-debounce.d.ts +0 -74
  112. package/dist/src/deliver-debounce.js +0 -174
  113. package/dist/src/gateway.d.ts +0 -18
  114. package/dist/src/gateway.js +0 -2063
  115. package/dist/src/group-history.d.ts +0 -136
  116. package/dist/src/group-history.js +0 -226
  117. package/dist/src/image-server.d.ts +0 -87
  118. package/dist/src/image-server.js +0 -570
  119. package/dist/src/inbound-attachments.d.ts +0 -60
  120. package/dist/src/inbound-attachments.js +0 -248
  121. package/dist/src/known-users.d.ts +0 -100
  122. package/dist/src/known-users.js +0 -263
  123. package/dist/src/message-gating.d.ts +0 -53
  124. package/dist/src/message-gating.js +0 -107
  125. package/dist/src/message-queue.d.ts +0 -91
  126. package/dist/src/message-queue.js +0 -257
  127. package/dist/src/onboarding.d.ts +0 -10
  128. package/dist/src/onboarding.js +0 -203
  129. package/dist/src/outbound-deliver.d.ts +0 -48
  130. package/dist/src/outbound-deliver.js +0 -392
  131. package/dist/src/outbound.d.ts +0 -220
  132. package/dist/src/outbound.js +0 -975
  133. package/dist/src/proactive.d.ts +0 -170
  134. package/dist/src/proactive.js +0 -399
  135. package/dist/src/ref-index-store.d.ts +0 -101
  136. package/dist/src/ref-index-store.js +0 -298
  137. package/dist/src/reply-dispatcher.d.ts +0 -35
  138. package/dist/src/reply-dispatcher.js +0 -311
  139. package/dist/src/request-context.d.ts +0 -25
  140. package/dist/src/request-context.js +0 -37
  141. package/dist/src/runtime.d.ts +0 -3
  142. package/dist/src/runtime.js +0 -13
  143. package/dist/src/session-store.d.ts +0 -52
  144. package/dist/src/session-store.js +0 -254
  145. package/dist/src/slash-commands.d.ts +0 -82
  146. package/dist/src/slash-commands.js +0 -2117
  147. package/dist/src/startup-greeting.d.ts +0 -30
  148. package/dist/src/startup-greeting.js +0 -97
  149. package/dist/src/streaming.d.ts +0 -247
  150. package/dist/src/streaming.js +0 -899
  151. package/dist/src/stt.d.ts +0 -21
  152. package/dist/src/stt.js +0 -70
  153. package/dist/src/tools/channel.d.ts +0 -16
  154. package/dist/src/tools/channel.js +0 -234
  155. package/dist/src/tools/remind.d.ts +0 -2
  156. package/dist/src/tools/remind.js +0 -256
  157. package/dist/src/types.d.ts +0 -443
  158. package/dist/src/types.js +0 -22
  159. package/dist/src/typing-keepalive.d.ts +0 -27
  160. package/dist/src/typing-keepalive.js +0 -64
  161. package/dist/src/update-checker.d.ts +0 -36
  162. package/dist/src/update-checker.js +0 -171
  163. package/dist/src/utils/audio-convert.d.ts +0 -98
  164. package/dist/src/utils/audio-convert.js +0 -755
  165. package/dist/src/utils/chunked-upload.d.ts +0 -68
  166. package/dist/src/utils/chunked-upload.js +0 -341
  167. package/dist/src/utils/file-utils.d.ts +0 -61
  168. package/dist/src/utils/file-utils.js +0 -172
  169. package/dist/src/utils/image-size.d.ts +0 -51
  170. package/dist/src/utils/image-size.js +0 -234
  171. package/dist/src/utils/media-send.d.ts +0 -158
  172. package/dist/src/utils/media-send.js +0 -502
  173. package/dist/src/utils/media-tags.d.ts +0 -14
  174. package/dist/src/utils/media-tags.js +0 -165
  175. package/dist/src/utils/payload.d.ts +0 -112
  176. package/dist/src/utils/payload.js +0 -186
  177. package/dist/src/utils/pkg-version.d.ts +0 -5
  178. package/dist/src/utils/pkg-version.js +0 -61
  179. package/dist/src/utils/platform.d.ts +0 -137
  180. package/dist/src/utils/platform.js +0 -390
  181. package/dist/src/utils/ssrf-guard.d.ts +0 -25
  182. package/dist/src/utils/ssrf-guard.js +0 -91
  183. package/dist/src/utils/text-parsing.d.ts +0 -31
  184. package/dist/src/utils/text-parsing.js +0 -74
  185. package/dist/src/utils/upload-cache.d.ts +0 -34
  186. package/dist/src/utils/upload-cache.js +0 -93
  187. package/node_modules/@eshaz/web-worker/LICENSE +0 -201
  188. package/node_modules/@eshaz/web-worker/README.md +0 -134
  189. package/node_modules/@eshaz/web-worker/browser.js +0 -17
  190. package/node_modules/@eshaz/web-worker/cjs/browser.js +0 -16
  191. package/node_modules/@eshaz/web-worker/cjs/node.js +0 -219
  192. package/node_modules/@eshaz/web-worker/index.d.ts +0 -4
  193. package/node_modules/@eshaz/web-worker/node.js +0 -223
  194. package/node_modules/@eshaz/web-worker/package.json +0 -54
  195. package/node_modules/@wasm-audio-decoders/common/index.js +0 -5
  196. package/node_modules/@wasm-audio-decoders/common/package.json +0 -36
  197. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderCommon.js +0 -231
  198. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderWorker.js +0 -129
  199. package/node_modules/@wasm-audio-decoders/common/src/puff/README +0 -67
  200. package/node_modules/@wasm-audio-decoders/common/src/puff/build_puff.js +0 -31
  201. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.c +0 -863
  202. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.h +0 -35
  203. package/node_modules/@wasm-audio-decoders/common/src/utilities.js +0 -3
  204. package/node_modules/@wasm-audio-decoders/common/types.d.ts +0 -7
  205. package/node_modules/mpg123-decoder/README.md +0 -265
  206. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js +0 -185
  207. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js.map +0 -1
  208. package/node_modules/mpg123-decoder/index.js +0 -8
  209. package/node_modules/mpg123-decoder/package.json +0 -58
  210. package/node_modules/mpg123-decoder/src/EmscriptenWasm.js +0 -464
  211. package/node_modules/mpg123-decoder/src/MPEGDecoder.js +0 -200
  212. package/node_modules/mpg123-decoder/src/MPEGDecoderWebWorker.js +0 -21
  213. package/node_modules/mpg123-decoder/types.d.ts +0 -30
  214. package/node_modules/silk-wasm/LICENSE +0 -21
  215. package/node_modules/silk-wasm/README.md +0 -85
  216. package/node_modules/silk-wasm/lib/index.cjs +0 -16
  217. package/node_modules/silk-wasm/lib/index.d.ts +0 -70
  218. package/node_modules/silk-wasm/lib/index.mjs +0 -16
  219. package/node_modules/silk-wasm/lib/silk.wasm +0 -0
  220. package/node_modules/silk-wasm/lib/utils.d.ts +0 -4
  221. package/node_modules/silk-wasm/package.json +0 -39
  222. package/node_modules/simple-yenc/.github/FUNDING.yml +0 -1
  223. package/node_modules/simple-yenc/.prettierignore +0 -1
  224. package/node_modules/simple-yenc/LICENSE +0 -7
  225. package/node_modules/simple-yenc/README.md +0 -163
  226. package/node_modules/simple-yenc/dist/esm.js +0 -1
  227. package/node_modules/simple-yenc/dist/index.js +0 -1
  228. package/node_modules/simple-yenc/package.json +0 -50
  229. package/node_modules/simple-yenc/rollup.config.js +0 -27
  230. package/node_modules/simple-yenc/src/simple-yenc.js +0 -302
  231. package/node_modules/ws/LICENSE +0 -20
  232. package/node_modules/ws/README.md +0 -548
  233. package/node_modules/ws/browser.js +0 -8
  234. package/node_modules/ws/index.js +0 -13
  235. package/node_modules/ws/lib/buffer-util.js +0 -131
  236. package/node_modules/ws/lib/constants.js +0 -19
  237. package/node_modules/ws/lib/event-target.js +0 -292
  238. package/node_modules/ws/lib/extension.js +0 -203
  239. package/node_modules/ws/lib/limiter.js +0 -55
  240. package/node_modules/ws/lib/permessage-deflate.js +0 -528
  241. package/node_modules/ws/lib/receiver.js +0 -706
  242. package/node_modules/ws/lib/sender.js +0 -602
  243. package/node_modules/ws/lib/stream.js +0 -161
  244. package/node_modules/ws/lib/subprotocol.js +0 -62
  245. package/node_modules/ws/lib/validation.js +0 -152
  246. package/node_modules/ws/lib/websocket-server.js +0 -554
  247. package/node_modules/ws/lib/websocket.js +0 -1393
  248. package/node_modules/ws/package.json +0 -69
  249. package/node_modules/ws/wrapper.mjs +0 -8
  250. package/scripts/postinstall-link-sdk.js +0 -126
  251. package/skills/qqbot-media/SKILL.md +0 -60
  252. package/src/admin-resolver.ts +0 -181
  253. package/src/api.ts +0 -1319
  254. package/src/credential-backup.ts +0 -72
  255. package/src/deliver-debounce.ts +0 -229
  256. package/src/gateway.ts +0 -2304
  257. package/src/group-history.ts +0 -328
  258. package/src/image-server.ts +0 -675
  259. package/src/inbound-attachments.ts +0 -321
  260. package/src/known-users.ts +0 -353
  261. package/src/message-gating.ts +0 -190
  262. package/src/message-queue.ts +0 -354
  263. package/src/onboarding.ts +0 -274
  264. package/src/outbound-deliver.ts +0 -486
  265. package/src/outbound.ts +0 -1179
  266. package/src/ref-index-store.ts +0 -412
  267. package/src/reply-dispatcher.ts +0 -334
  268. package/src/session-store.ts +0 -303
  269. package/src/slash-commands.ts +0 -2297
  270. package/src/startup-greeting.ts +0 -120
  271. package/src/streaming.ts +0 -1077
  272. package/src/stt.ts +0 -86
  273. package/src/tools/channel.ts +0 -281
  274. package/src/typing-keepalive.ts +0 -59
  275. package/src/utils/audio-convert.ts +0 -859
  276. package/src/utils/chunked-upload.ts +0 -483
  277. package/src/utils/file-utils.ts +0 -193
  278. package/src/utils/image-size.ts +0 -266
  279. package/src/utils/media-send.ts +0 -636
  280. package/src/utils/media-tags.ts +0 -183
  281. package/src/utils/payload.ts +0 -265
  282. package/src/utils/text-parsing.ts +0 -85
  283. package/src/utils/upload-cache.ts +0 -128
@@ -0,0 +1,84 @@
1
+ /**
2
+ * TTS(文字转语音)集成接口
3
+ *
4
+ * audioAsVoice 语音回复能力:
5
+ * text → TTS → audioPath → SILK 转换 → Base64 → sendVoice
6
+ *
7
+ * 本模块定义接口和桥接逻辑。实际 TTS 引擎由 openclaw 框架的
8
+ * tts-runtime 插件提供(通过 runtime 注入),本文件不内置 TTS 实现。
9
+ */
10
+ import { convertSilkToWav } from '@tencent-connect/qqbot-nodejs/protocol';
11
+
12
+ /**
13
+ * TTS Provider 接口(由框架注入或用户自定义)
14
+ */
15
+ export interface TTSProvider {
16
+ /** 文字转语音 → 返回本地音频文件路径(wav/mp3 等) */
17
+ textToSpeech(params: { text: string; cfg?: unknown; channel?: string; accountId?: string }): Promise<string | null>;
18
+ /** 音频文件 → SILK Base64(用于 QQ 发送) */
19
+ audioFileToSilkBase64?(audioPath: string): Promise<string | null>;
20
+ }
21
+
22
+ /**
23
+ * 从 runtime 尝试获取 TTS provider
24
+ *
25
+ * openclaw 框架通过 `runtime.channel.runtimeContexts` 或直接挂载 `runtime.tts`
26
+ * 提供 TTS 能力。本函数做兼容性探测。
27
+ */
28
+ export function resolveTTSProvider(runtime: any): TTSProvider | undefined {
29
+ // 方式 1: runtime.tts (直接挂载)
30
+ if (runtime?.tts?.textToSpeech) {
31
+ return runtime.tts;
32
+ }
33
+ // 方式 2: channel runtime context 注册
34
+ const tts = runtime?.channel?.runtimeContexts?.get?.('tts'); // @adapter-bypass: TTS 扩展点探测,非核心 channel API
35
+ if (tts?.textToSpeech) {
36
+ return tts;
37
+ }
38
+ return undefined;
39
+ }
40
+
41
+ /**
42
+ * 将音频文件转换为 SILK Base64(QQ 语音消息格式)
43
+ *
44
+ * 如果 TTS provider 提供了 audioFileToSilkBase64,使用它;
45
+ * 否则尝试直接读取文件返回 Base64(假设已经是 SILK 格式)。
46
+ */
47
+ export async function audioToSilkBase64(
48
+ audioPath: string,
49
+ provider?: TTSProvider,
50
+ ): Promise<string | null> {
51
+ // 优先使用 provider 的转换方法
52
+ if (provider?.audioFileToSilkBase64) {
53
+ return provider.audioFileToSilkBase64(audioPath);
54
+ }
55
+
56
+ // Fallback:尝试 SDK 内置的 SILK 转换
57
+ try {
58
+ const { default: fs } = await import('node:fs');
59
+ const buffer = fs.readFileSync(audioPath);
60
+ return buffer.toString('base64');
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * 完整的 TTS → SILK → Base64 流程
68
+ *
69
+ * 返回可以直接传给 sendVoice({ base64 }) 的 Base64 字符串。
70
+ */
71
+ export async function textToVoiceBase64(
72
+ text: string,
73
+ provider: TTSProvider,
74
+ opts?: { cfg?: unknown; accountId?: string },
75
+ ): Promise<string | null> {
76
+ const audioPath = await provider.textToSpeech({
77
+ text,
78
+ cfg: opts?.cfg,
79
+ channel: 'qqbot',
80
+ accountId: opts?.accountId,
81
+ });
82
+ if (!audioPath) return null;
83
+ return audioToSilkBase64(audioPath, provider);
84
+ }
@@ -6,43 +6,44 @@
6
6
  * 作用域内的所有异步代码(包括 AI agent 调用、tool execute)
7
7
  * 都能通过 getRequestContext() 安全地拿到当前请求的上下文。
8
8
  */
9
- import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { AsyncLocalStorage } from 'node:async_hooks';
10
10
 
11
11
  export interface RequestContext {
12
12
  /** 投递目标地址,如 qqbot:c2c:xxx 或 qqbot:group:xxx */
13
13
  target: string;
14
14
  /** 当前请求的 QQBot 账户 ID(多账户场景) */
15
15
  accountId?: string;
16
+ /** 当前消息 ID */
17
+ messageId?: string;
18
+ /** 发送者 open_id */
19
+ openId?: string;
16
20
  }
17
21
 
18
22
  const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();
19
23
 
20
24
  /**
21
- * 在请求级作用域中执行回调。
22
- * 作用域内所有同步/异步代码都能通过 getRequestContext() 获取上下文。
25
+ * 在请求级作用域中执行回调
23
26
  */
24
27
  export function runWithRequestContext<T>(ctx: RequestContext, fn: () => T): T {
25
28
  return asyncLocalStorage.run(ctx, fn);
26
29
  }
27
30
 
28
31
  /**
29
- * 获取当前请求的上下文,不存在时返回 undefined。
32
+ * 获取当前请求的上下文
30
33
  */
31
34
  export function getRequestContext(): RequestContext | undefined {
32
35
  return asyncLocalStorage.getStore();
33
36
  }
34
37
 
35
38
  /**
36
- * 获取当前请求的投递目标地址。
37
- * 便捷方法,等价于 getRequestContext()?.target。
39
+ * 获取当前请求的投递目标地址
38
40
  */
39
41
  export function getRequestTarget(): string | undefined {
40
42
  return asyncLocalStorage.getStore()?.target;
41
43
  }
42
44
 
43
45
  /**
44
- * 获取当前请求的账户 ID
45
- * 便捷方法,等价于 getRequestContext()?.accountId。
46
+ * 获取当前请求的账户 ID
46
47
  */
47
48
  export function getRequestAccountId(): string | undefined {
48
49
  return asyncLocalStorage.getStore()?.accountId;
package/src/runtime.ts CHANGED
@@ -1,17 +1,42 @@
1
+ /**
2
+ * QQBot 插件运行时管理。
3
+ *
4
+ * 日志统一由 `utils/plugin-logger.ts` 提供,此处只管理 runtime 实例。
5
+ */
6
+
1
7
  import type { PluginRuntime } from "openclaw/plugin-sdk";
2
- import { setOpenClawVersion } from "./api.js";
8
+ import { setOpenClawVersion } from "./bot-instance.js";
9
+ import { flushAllRefIndexStores } from "./features/ref-index-store.js";
10
+ import { getOpenclawVersion } from "./utils/pkg-version.js";
3
11
 
4
12
  let runtime: PluginRuntime | null = null;
13
+ let exitHooksInstalled = false;
5
14
 
6
15
  export function setQQBotRuntime(next: PluginRuntime) {
7
16
  runtime = next;
8
- // 将框架版本注入 User-Agent(runtime 注入后才能拿到准确版本)
9
- setOpenClawVersion(next.version);
17
+ const version = getOpenclawVersion(next.version);
18
+ setOpenClawVersion(version);
19
+ installExitHooksOnce();
20
+ }
21
+
22
+ function installExitHooksOnce(): void {
23
+ if (exitHooksInstalled) return;
24
+ exitHooksInstalled = true;
25
+
26
+ const flush = () => {
27
+ try { flushAllRefIndexStores(); } catch {}
28
+ };
29
+
30
+ process.on('beforeExit', flush);
31
+ process.on('SIGINT', () => { flush(); process.exit(0); });
32
+ process.on('SIGTERM', () => { flush(); process.exit(0); });
10
33
  }
11
34
 
12
35
  export function getQQBotRuntime(): PluginRuntime {
13
- if (!runtime) {
14
- throw new Error("QQBot runtime not initialized");
15
- }
36
+ if (!runtime) throw new Error("QQBot runtime not initialized");
37
+ return runtime;
38
+ }
39
+
40
+ export function tryGetQQBotRuntime(): PluginRuntime | null {
16
41
  return runtime;
17
42
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * 账户键解析 — setup / login 共用
3
+ *
4
+ * 统一确定扫码/绑定凭据应写入哪个账户键。
5
+ */
6
+
7
+ import type { OpenClawConfig } from 'openclaw/plugin-sdk';
8
+ import { listQQBotAccountIds, resolveQQBotAccount } from '../config.js';
9
+
10
+ /**
11
+ * 解析凭据写入的目标账户键。
12
+ *
13
+ * @param cfg 当前配置
14
+ * @param appId 扫码或输入的 AppID
15
+ * @param resolvedId 用户显式指定的账户名(如 --account / setup wizard),可选
16
+ * @returns 账户键
17
+ *
18
+ * 优先级:
19
+ * 1. resolvedId 指定 → 直接使用
20
+ * 2. 已有同 appId 的账户 → 刷新凭据(复用该账户键)
21
+ * 3. 零账户 → 'default'(首次配置)
22
+ * 4. 已有其他账户 → appId(新增独立账户)
23
+ */
24
+ export function resolveAccountKey(
25
+ cfg: OpenClawConfig,
26
+ appId: string,
27
+ resolvedId?: string | null,
28
+ ): string {
29
+ if (resolvedId) return resolvedId;
30
+
31
+ // 同 appId → 刷新
32
+ for (const id of listQQBotAccountIds(cfg)) {
33
+ if (resolveQQBotAccount(cfg, id).appId === appId) return id;
34
+ }
35
+
36
+ // 零账户 → default
37
+ if (listQQBotAccountIds(cfg).length === 0) return 'default';
38
+
39
+ // 新增账户
40
+ return appId;
41
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * openclaw setup 引导 — QQ Bot 扫码/手动绑定
3
+ */
4
+ import type { OpenClawConfig } from 'openclaw/plugin-sdk';
5
+ import { DEFAULT_ACCOUNT_ID, formatDocsLink } from '../adapter/setup.js';
6
+ import { qrConnect } from '@tencent-connect/qqbot-connector';
7
+ import { applyQQBotAccountConfig, resolveQQBotAccount } from '../config.js';
8
+ import { resolveAccountKey } from './account-key.js';
9
+
10
+ type Prompter = {
11
+ select: (opts: { message: string; options: Array<{ value: string; label: string; hint?: string }> }) => Promise<string>;
12
+ text: (opts: { message: string; validate?: (v: string) => string | undefined }) => Promise<string>;
13
+ note: (msg: string, title?: string) => Promise<void>;
14
+ };
15
+
16
+ type Runtime = {
17
+ log: (msg: string) => void;
18
+ error: (msg: string) => void;
19
+ };
20
+
21
+ function isConfigured(cfg: OpenClawConfig, accountId: string): boolean {
22
+ const account = resolveQQBotAccount(cfg, accountId);
23
+ return Boolean(account.appId && account.clientSecret);
24
+ }
25
+
26
+ async function linkViaQrCode(cfg: OpenClawConfig, _accountId: string, prompter: Prompter, rt: Runtime): Promise<OpenClawConfig> {
27
+ try {
28
+ const accounts: Array<{ appId: string; appSecret: string; userOpenid?: string }> = await qrConnect({ source: 'openclaw' });
29
+
30
+ if (accounts.length === 0) {
31
+ await prompter.note('未获取到任何 QQ Bot 账号信息。', 'QQ Bot');
32
+ return cfg;
33
+ }
34
+
35
+ let next = cfg;
36
+ for (const { appId, appSecret, userOpenid } of accounts) {
37
+ // 同 appId 刷新;零账户 default;已有账户新增 appId
38
+ const key = resolveAccountKey(cfg, appId);
39
+ next = applyQQBotAccountConfig(next, key, { appId, clientSecret: appSecret });
40
+ next = applyAccountDefaults(next, key, userOpenid);
41
+ rt.log(`绑定成功!账户: ${key} (AppID: ${appId})`);
42
+ }
43
+
44
+ return next;
45
+ } catch (err) {
46
+ rt.error(`QQ Bot 绑定失败: ${String(err)}`);
47
+ await prompter.note(`绑定失败,您可以稍后手动配置。\n文档: ${formatDocsLink('/channels/qqbot', 'qqbot')}`, 'QQ Bot');
48
+ return cfg;
49
+ }
50
+ }
51
+
52
+ async function linkViaManual(cfg: OpenClawConfig, _accountId: string, prompter: Prompter): Promise<OpenClawConfig> {
53
+ const appIdInput = await prompter.text({ message: '请输入 QQ Bot AppID', validate: (v) => v.trim() ? undefined : 'AppID 不能为空' });
54
+ const secret = await prompter.text({ message: '请输入 QQ Bot AppSecret', validate: (v) => v.trim() ? undefined : 'AppSecret 不能为空' });
55
+ const appId = appIdInput.trim();
56
+ const key = resolveAccountKey(cfg, appId);
57
+ let next = applyQQBotAccountConfig(cfg, key, { appId, clientSecret: secret.trim() });
58
+ next = applyAccountDefaults(next, key);
59
+ await prompter.note('✔ QQ Bot 配置完成!', 'QQ Bot');
60
+ return next;
61
+ }
62
+
63
+ export async function finalizeQQBotSetup(params: {
64
+ cfg: OpenClawConfig;
65
+ accountId: string;
66
+ prompter: Prompter;
67
+ runtime: Runtime;
68
+ }): Promise<{ cfg: OpenClawConfig }> {
69
+ const accountId = params.accountId.trim() || DEFAULT_ACCOUNT_ID;
70
+ const configured = isConfigured(params.cfg, accountId);
71
+
72
+ const mode = await params.prompter.select({
73
+ message: configured ? 'QQ 已绑定,选择操作' : '选择 QQ 绑定方式',
74
+ options: [
75
+ { value: 'qr', label: '扫码绑定(推荐)', hint: '使用 QQ 扫描二维码自动完成绑定' },
76
+ { value: 'manual', label: '手动输入 QQ Bot AppID 和 AppSecret', hint: '需到 QQ 开放平台 q.qq.com 查看' },
77
+ { value: 'skip', label: configured ? '保持当前配置' : '稍后配置' },
78
+ ],
79
+ });
80
+
81
+ let next = params.cfg;
82
+ if (mode === 'qr') {
83
+ next = await linkViaQrCode(next, accountId, params.prompter, params.runtime);
84
+ } else if (mode === 'manual') {
85
+ next = await linkViaManual(next, accountId, params.prompter);
86
+ } else if (!configured) {
87
+ await params.prompter.note('您可以稍后运行以下命令重新配置:\n openclaw channels add', 'QQ Bot');
88
+ }
89
+
90
+ return { cfg: next };
91
+ }
92
+
93
+ export function applyAccountDefaults(cfg: OpenClawConfig, accountId: string, userOpenid?: string): OpenClawConfig {
94
+ const next = { ...cfg, channels: { ...cfg.channels } };
95
+ const qqbot = { ...(next.channels?.qqbot as Record<string, unknown> ?? {}) } as Record<string, unknown>;
96
+
97
+ const defaults: Record<string, unknown> = { streaming: { mode: 'partial' }, dmPolicy: 'allowlist', mediaMaxMb: 200 };
98
+ if (userOpenid) defaults.allowFrom = [userOpenid];
99
+
100
+ if (accountId === DEFAULT_ACCOUNT_ID) {
101
+ Object.assign(qqbot, defaults);
102
+ } else {
103
+ const accounts = { ...(qqbot.accounts as Record<string, unknown> ?? {}) };
104
+ accounts[accountId] = { ...(accounts[accountId] as Record<string, unknown> ?? {}), ...defaults };
105
+ qqbot.accounts = accounts;
106
+ }
107
+
108
+ next.channels = { ...next.channels, qqbot };
109
+ return next;
110
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * QQ Bot QR 登录 — 两阶段接口适配
3
+ *
4
+ * 使用 @tencent-connect/qqbot-connector 的 startQrConnect 回调 API,
5
+ * 将扫码绑定流程拆分为 start / wait 两个阶段,对接 ChannelPlugin 的
6
+ * gateway.loginWithQrStart / loginWithQrWait。
7
+ */
8
+ import { startQrConnect, type QrConnectCredentials } from '@tencent-connect/qqbot-connector';
9
+
10
+ // ── 类型 ──
11
+
12
+ export interface QrLoginStartResult {
13
+ qrDataUrl?: string;
14
+ message: string;
15
+ }
16
+
17
+ export interface QrLoginWaitResult {
18
+ connected: boolean;
19
+ message: string;
20
+ credentials?: QrConnectCredentials[];
21
+ }
22
+
23
+ // ── 挂起的登录会话 ──
24
+
25
+ interface PendingSession {
26
+ /** 等待扫码结果的 Promise(onSuccess resolve, onFailure reject) */
27
+ credentialsPromise: Promise<QrConnectCredentials[]>;
28
+ /** 取消当前流程 */
29
+ dispose: () => void;
30
+ }
31
+
32
+ const pendingSessions = new Map<string, PendingSession>();
33
+
34
+ // ── 启动 QR 登录 ──
35
+
36
+ export function startQrLogin(accountId?: string, source = 'openclaw'): Promise<QrLoginStartResult> {
37
+ const key = accountId ?? 'default';
38
+
39
+ // 清理旧会话
40
+ pendingSessions.get(key)?.dispose();
41
+ pendingSessions.delete(key);
42
+
43
+ return new Promise((resolve) => {
44
+ let credentialsResolve: (creds: QrConnectCredentials[]) => void;
45
+ let credentialsReject: (err: Error) => void;
46
+
47
+ // 凭据 Promise — 在 onSuccess/onFailure 中 settle
48
+ const credentialsPromise = new Promise<QrConnectCredentials[]>((res, rej) => {
49
+ credentialsResolve = res;
50
+ credentialsReject = rej;
51
+ });
52
+
53
+ const dispose = startQrConnect(
54
+ {
55
+ onQrDisplayed(url) {
56
+ resolve({
57
+ qrDataUrl: url,
58
+ message: '请使用手机 QQ 扫描二维码完成绑定',
59
+ });
60
+ },
61
+ onSuccess: (creds) => credentialsResolve!(creds),
62
+ onFailure: (err) => credentialsReject!(err),
63
+ },
64
+ { displayQrCodeToConsole: true, source },
65
+ );
66
+
67
+ pendingSessions.set(key, { dispose, credentialsPromise });
68
+ });
69
+ }
70
+
71
+ // ── 等待扫码结果 ──
72
+
73
+ export async function waitQrLogin(accountId?: string): Promise<QrLoginWaitResult> {
74
+ const key = accountId ?? 'default';
75
+ const session = pendingSessions.get(key);
76
+
77
+ if (!session) {
78
+ return { connected: false, message: '没有正在进行的登录会话,请先运行 login 命令。' };
79
+ }
80
+
81
+ try {
82
+ const credentials = await session.credentialsPromise;
83
+ pendingSessions.delete(key);
84
+
85
+ if (credentials.length === 0) {
86
+ return { connected: false, message: '未获取到 QQ Bot 凭据。' };
87
+ }
88
+
89
+ return {
90
+ connected: true,
91
+ message: `绑定成功!AppID: ${credentials.map((c) => c.appId).join(', ')}`,
92
+ credentials,
93
+ };
94
+ } catch (err) {
95
+ pendingSessions.delete(key);
96
+ return {
97
+ connected: false,
98
+ message: `绑定失败: ${err instanceof Error ? err.message : String(err)}`,
99
+ };
100
+ }
101
+ }
102
+
103
+ // ── 主动取消 ──
104
+
105
+ export function cancelQrLogin(accountId?: string): void {
106
+ const key = accountId ?? 'default';
107
+ pendingSessions.get(key)?.dispose();
108
+ pendingSessions.delete(key);
109
+ }
110
+
111
+ // ── 解析 channelInput (appId:clientSecret) ──
112
+
113
+ export function parseChannelInput(channelInput?: string | null): { appId: string; clientSecret: string } | null {
114
+ if (!channelInput) return null;
115
+ const parts = channelInput.trim().split(':');
116
+ if (parts.length === 2 && parts[0] && parts[1]) {
117
+ return { appId: parts[0], clientSecret: parts[1] };
118
+ }
119
+ return null;
120
+ }
121
+
122
+ // ── auth.login 入口 ──
123
+
124
+ export interface QqbotLoginParams {
125
+ cfg: Record<string, unknown>;
126
+ accountId?: string | null;
127
+ channelInput?: string | null;
128
+ verbose?: boolean;
129
+ /** 框架注入的 runtime(含 config 持久化 API) */
130
+ [key: string]: unknown;
131
+ }
132
+
133
+ /**
134
+ * auth.login 完整实现。
135
+ *
136
+ * 账号策略:
137
+ * --account <id> → 写入指定账户
138
+ * channelInput → 用 appId 作为账户键
139
+ * QR 扫码 → 用扫码返回的 appId 作为新账户键
140
+ */
141
+ export async function qqbotLogin({
142
+ cfg,
143
+ accountId,
144
+ channelInput,
145
+ verbose,
146
+ ...rest
147
+ }: QqbotLoginParams): Promise<void> {
148
+ // 延迟导入,避免循环依赖
149
+ const { applyQQBotAccountConfig } = await import('../config.js');
150
+ const { persistAuthConfig } = await import('../adapter/resolve.js');
151
+ const { applyAccountDefaults } = await import('./finalize.js');
152
+ const { resolveAccountKey } = await import('./account-key.js');
153
+
154
+ const runtime: Record<string, unknown> = rest as any;
155
+ const resolvedId = accountId ? accountId.trim().toLowerCase() : null;
156
+
157
+ // 如果传了 appId:clientSecret,直接写入配置
158
+ const parsed = parseChannelInput(channelInput);
159
+ if (parsed) {
160
+ const key = resolveAccountKey(cfg as any, parsed.appId, resolvedId);
161
+ const result = applyQQBotAccountConfig(cfg as any, key, {
162
+ appId: parsed.appId,
163
+ clientSecret: parsed.clientSecret,
164
+ });
165
+ Object.assign(cfg, result);
166
+ // 对齐 setup:写入默认 streaming/dmPolicy
167
+ const withDefaults = applyAccountDefaults(cfg as any, key);
168
+ Object.assign(cfg, withDefaults);
169
+ await persistAuthConfig(runtime, cfg, 'restart');
170
+ if (verbose) console.log(`QQ Bot 已配置 (${key}) AppID: ${parsed.appId}`);
171
+ return;
172
+ }
173
+
174
+ // QR 扫码登录
175
+ const { qrDataUrl, message } = await startQrLogin(resolvedId || 'pending');
176
+ console.log(`\n${message}`);
177
+ if (qrDataUrl) console.log(`QR 链接: ${qrDataUrl}`);
178
+
179
+ const result = await waitQrLogin(resolvedId || 'pending');
180
+ if (!result.connected || !result.credentials) {
181
+ throw new Error(result.message);
182
+ }
183
+
184
+ for (const cred of result.credentials) {
185
+ const key = resolveAccountKey(cfg as any, cred.appId, resolvedId);
186
+ const next = applyQQBotAccountConfig(cfg as any, key, {
187
+ appId: cred.appId,
188
+ clientSecret: cred.appSecret,
189
+ });
190
+ Object.assign(cfg, next);
191
+ // 对齐 setup:写入默认 streaming/dmPolicy,扫码用户加入白名单
192
+ const withDefaults = applyAccountDefaults(cfg as any, key, cred.userOpenid);
193
+ Object.assign(cfg, withDefaults);
194
+ }
195
+ await persistAuthConfig(runtime, cfg, 'restart');
196
+ console.log(`QQ Bot 登录成功!`);
197
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * OpenClaw setup 向导 — QQ Bot 配置界面
3
+ */
4
+ import type { ChannelSetupWizard } from '../adapter/setup.js';
5
+ import { createStandardChannelSetupStatus, setSetupChannelEnabled } from '../adapter/setup.js';
6
+ import { listQQBotAccountIds, resolveQQBotAccount, resolveDefaultQQBotAccountId } from '../config.js';
7
+ import { finalizeQQBotSetup } from './finalize.js';
8
+
9
+ const CHANNEL = 'qqbot' as const;
10
+
11
+ export const qqbotSetupWizard: ChannelSetupWizard = {
12
+ channel: CHANNEL,
13
+ status: createStandardChannelSetupStatus({
14
+ channelLabel: 'QQ Bot',
15
+ configuredLabel: 'configured',
16
+ unconfiguredLabel: 'needs AppID + AppSecret',
17
+ configuredHint: 'configured',
18
+ unconfiguredHint: 'needs AppID + AppSecret',
19
+ configuredScore: 1,
20
+ unconfiguredScore: 6,
21
+ resolveConfigured: ({ cfg, accountId }) =>
22
+ (accountId ? [accountId] : listQQBotAccountIds(cfg as any)).some((id) => {
23
+ const account = resolveQQBotAccount(cfg as any, id);
24
+ return Boolean(account.appId && account.clientSecret);
25
+ }),
26
+ }),
27
+ // 未配置时默认使用 default 账号,有账户时框架会提示选择
28
+ resolveAccountIdForConfigure: async ({ cfg, shouldPromptAccountIds, accountOverride, defaultAccountId }) => {
29
+ if (accountOverride) return accountOverride;
30
+ const ids = listQQBotAccountIds(cfg as any);
31
+ if (ids.length === 0) return 'default';
32
+ if (!shouldPromptAccountIds) return ids[0];
33
+ return defaultAccountId || resolveDefaultQQBotAccountId(cfg as any);
34
+ },
35
+ credentials: [],
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ finalize: (async ({ cfg, accountId, prompter, runtime }: any) =>
38
+ finalizeQQBotSetup({ cfg, accountId, prompter: prompter as any, runtime: runtime as any })) as any,
39
+ disable: (cfg) => { setSetupChannelEnabled(cfg, CHANNEL, false); return cfg; },
40
+ };