@tencent-connect/qqbot-nodejs 1.0.3

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 (293) hide show
  1. package/README.md +205 -0
  2. package/USAGE.md +804 -0
  3. package/dist/QQBot.d.ts +536 -0
  4. package/dist/QQBot.d.ts.map +1 -0
  5. package/dist/QQBot.js +752 -0
  6. package/dist/QQBot.js.map +1 -0
  7. package/dist/index.d.ts +49 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +66 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/middleware/access-policy.d.ts +54 -0
  12. package/dist/middleware/access-policy.d.ts.map +1 -0
  13. package/dist/middleware/access-policy.js +93 -0
  14. package/dist/middleware/access-policy.js.map +1 -0
  15. package/dist/middleware/concurrency-guard.d.ts +105 -0
  16. package/dist/middleware/concurrency-guard.d.ts.map +1 -0
  17. package/dist/middleware/concurrency-guard.js +325 -0
  18. package/dist/middleware/concurrency-guard.js.map +1 -0
  19. package/dist/middleware/content-sanitizer.d.ts +47 -0
  20. package/dist/middleware/content-sanitizer.d.ts.map +1 -0
  21. package/dist/middleware/content-sanitizer.js +85 -0
  22. package/dist/middleware/content-sanitizer.js.map +1 -0
  23. package/dist/middleware/envelope-formatter.d.ts +51 -0
  24. package/dist/middleware/envelope-formatter.d.ts.map +1 -0
  25. package/dist/middleware/envelope-formatter.js +97 -0
  26. package/dist/middleware/envelope-formatter.js.map +1 -0
  27. package/dist/middleware/error-handler.d.ts +36 -0
  28. package/dist/middleware/error-handler.d.ts.map +1 -0
  29. package/dist/middleware/error-handler.js +59 -0
  30. package/dist/middleware/error-handler.js.map +1 -0
  31. package/dist/middleware/history-buffer.d.ts +84 -0
  32. package/dist/middleware/history-buffer.d.ts.map +1 -0
  33. package/dist/middleware/history-buffer.js +113 -0
  34. package/dist/middleware/history-buffer.js.map +1 -0
  35. package/dist/middleware/index.d.ts +71 -0
  36. package/dist/middleware/index.d.ts.map +1 -0
  37. package/dist/middleware/index.js +48 -0
  38. package/dist/middleware/index.js.map +1 -0
  39. package/dist/middleware/mention-gate.d.ts +99 -0
  40. package/dist/middleware/mention-gate.d.ts.map +1 -0
  41. package/dist/middleware/mention-gate.js +117 -0
  42. package/dist/middleware/mention-gate.js.map +1 -0
  43. package/dist/middleware/message-filter.d.ts +38 -0
  44. package/dist/middleware/message-filter.d.ts.map +1 -0
  45. package/dist/middleware/message-filter.js +60 -0
  46. package/dist/middleware/message-filter.js.map +1 -0
  47. package/dist/middleware/quote-ref.d.ts +106 -0
  48. package/dist/middleware/quote-ref.d.ts.map +1 -0
  49. package/dist/middleware/quote-ref.js +168 -0
  50. package/dist/middleware/quote-ref.js.map +1 -0
  51. package/dist/middleware/rate-limiter.d.ts +43 -0
  52. package/dist/middleware/rate-limiter.d.ts.map +1 -0
  53. package/dist/middleware/rate-limiter.js +77 -0
  54. package/dist/middleware/rate-limiter.js.map +1 -0
  55. package/dist/middleware/slash-command.d.ts +112 -0
  56. package/dist/middleware/slash-command.d.ts.map +1 -0
  57. package/dist/middleware/slash-command.js +203 -0
  58. package/dist/middleware/slash-command.js.map +1 -0
  59. package/dist/middleware/types.d.ts +175 -0
  60. package/dist/middleware/types.d.ts.map +1 -0
  61. package/dist/middleware/types.js +138 -0
  62. package/dist/middleware/types.js.map +1 -0
  63. package/dist/middleware/typing-indicator.d.ts +54 -0
  64. package/dist/middleware/typing-indicator.d.ts.map +1 -0
  65. package/dist/middleware/typing-indicator.js +68 -0
  66. package/dist/middleware/typing-indicator.js.map +1 -0
  67. package/dist/protocol/api/api-client.d.ts +27 -0
  68. package/dist/protocol/api/api-client.d.ts.map +1 -0
  69. package/dist/protocol/api/api-client.js +119 -0
  70. package/dist/protocol/api/api-client.js.map +1 -0
  71. package/dist/protocol/api/media-chunked.d.ts +68 -0
  72. package/dist/protocol/api/media-chunked.d.ts.map +1 -0
  73. package/dist/protocol/api/media-chunked.js +298 -0
  74. package/dist/protocol/api/media-chunked.js.map +1 -0
  75. package/dist/protocol/api/media.d.ts +46 -0
  76. package/dist/protocol/api/media.d.ts.map +1 -0
  77. package/dist/protocol/api/media.js +101 -0
  78. package/dist/protocol/api/media.js.map +1 -0
  79. package/dist/protocol/api/messages.d.ts +86 -0
  80. package/dist/protocol/api/messages.d.ts.map +1 -0
  81. package/dist/protocol/api/messages.js +200 -0
  82. package/dist/protocol/api/messages.js.map +1 -0
  83. package/dist/protocol/api/retry.d.ts +23 -0
  84. package/dist/protocol/api/retry.d.ts.map +1 -0
  85. package/dist/protocol/api/retry.js +102 -0
  86. package/dist/protocol/api/retry.js.map +1 -0
  87. package/dist/protocol/api/routes.d.ts +23 -0
  88. package/dist/protocol/api/routes.d.ts.map +1 -0
  89. package/dist/protocol/api/routes.js +50 -0
  90. package/dist/protocol/api/routes.js.map +1 -0
  91. package/dist/protocol/api/token.d.ts +38 -0
  92. package/dist/protocol/api/token.d.ts.map +1 -0
  93. package/dist/protocol/api/token.js +191 -0
  94. package/dist/protocol/api/token.js.map +1 -0
  95. package/dist/protocol/gateway/codec.d.ts +9 -0
  96. package/dist/protocol/gateway/codec.d.ts.map +1 -0
  97. package/dist/protocol/gateway/codec.js +32 -0
  98. package/dist/protocol/gateway/codec.js.map +1 -0
  99. package/dist/protocol/gateway/constants.d.ts +71 -0
  100. package/dist/protocol/gateway/constants.d.ts.map +1 -0
  101. package/dist/protocol/gateway/constants.js +91 -0
  102. package/dist/protocol/gateway/constants.js.map +1 -0
  103. package/dist/protocol/gateway/event-dispatcher.d.ts +97 -0
  104. package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -0
  105. package/dist/protocol/gateway/event-dispatcher.js +155 -0
  106. package/dist/protocol/gateway/event-dispatcher.js.map +1 -0
  107. package/dist/protocol/gateway/gateway-connection.d.ts +73 -0
  108. package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -0
  109. package/dist/protocol/gateway/gateway-connection.js +293 -0
  110. package/dist/protocol/gateway/gateway-connection.js.map +1 -0
  111. package/dist/protocol/gateway/reconnect.d.ts +25 -0
  112. package/dist/protocol/gateway/reconnect.d.ts.map +1 -0
  113. package/dist/protocol/gateway/reconnect.js +118 -0
  114. package/dist/protocol/gateway/reconnect.js.map +1 -0
  115. package/dist/protocol/index.d.ts +41 -0
  116. package/dist/protocol/index.d.ts.map +1 -0
  117. package/dist/protocol/index.js +46 -0
  118. package/dist/protocol/index.js.map +1 -0
  119. package/dist/protocol/transport/index.d.ts +8 -0
  120. package/dist/protocol/transport/index.d.ts.map +1 -0
  121. package/dist/protocol/transport/index.js +4 -0
  122. package/dist/protocol/transport/index.js.map +1 -0
  123. package/dist/protocol/transport/types.d.ts +109 -0
  124. package/dist/protocol/transport/types.d.ts.map +1 -0
  125. package/dist/protocol/transport/types.js +15 -0
  126. package/dist/protocol/transport/types.js.map +1 -0
  127. package/dist/protocol/transport/webhook-server-node.d.ts +14 -0
  128. package/dist/protocol/transport/webhook-server-node.d.ts.map +1 -0
  129. package/dist/protocol/transport/webhook-server-node.js +57 -0
  130. package/dist/protocol/transport/webhook-server-node.js.map +1 -0
  131. package/dist/protocol/transport/webhook-verify.d.ts +49 -0
  132. package/dist/protocol/transport/webhook-verify.d.ts.map +1 -0
  133. package/dist/protocol/transport/webhook-verify.js +98 -0
  134. package/dist/protocol/transport/webhook-verify.js.map +1 -0
  135. package/dist/protocol/transport/webhook.d.ts +37 -0
  136. package/dist/protocol/transport/webhook.d.ts.map +1 -0
  137. package/dist/protocol/transport/webhook.js +183 -0
  138. package/dist/protocol/transport/webhook.js.map +1 -0
  139. package/dist/protocol/types.d.ts +270 -0
  140. package/dist/protocol/types.d.ts.map +1 -0
  141. package/dist/protocol/types.js +59 -0
  142. package/dist/protocol/types.js.map +1 -0
  143. package/dist/protocol/utils/audio.d.ts +79 -0
  144. package/dist/protocol/utils/audio.d.ts.map +1 -0
  145. package/dist/protocol/utils/audio.js +501 -0
  146. package/dist/protocol/utils/audio.js.map +1 -0
  147. package/dist/protocol/utils/decode-media-path.d.ts +26 -0
  148. package/dist/protocol/utils/decode-media-path.d.ts.map +1 -0
  149. package/dist/protocol/utils/decode-media-path.js +79 -0
  150. package/dist/protocol/utils/decode-media-path.js.map +1 -0
  151. package/dist/protocol/utils/ffmpeg.d.ts +38 -0
  152. package/dist/protocol/utils/ffmpeg.d.ts.map +1 -0
  153. package/dist/protocol/utils/ffmpeg.js +119 -0
  154. package/dist/protocol/utils/ffmpeg.js.map +1 -0
  155. package/dist/protocol/utils/file-utils.d.ts +42 -0
  156. package/dist/protocol/utils/file-utils.d.ts.map +1 -0
  157. package/dist/protocol/utils/file-utils.js +108 -0
  158. package/dist/protocol/utils/file-utils.js.map +1 -0
  159. package/dist/protocol/utils/format.d.ts +10 -0
  160. package/dist/protocol/utils/format.d.ts.map +1 -0
  161. package/dist/protocol/utils/format.js +68 -0
  162. package/dist/protocol/utils/format.js.map +1 -0
  163. package/dist/protocol/utils/image-size.d.ts +56 -0
  164. package/dist/protocol/utils/image-size.d.ts.map +1 -0
  165. package/dist/protocol/utils/image-size.js +185 -0
  166. package/dist/protocol/utils/image-size.js.map +1 -0
  167. package/dist/protocol/utils/media-source.d.ts +145 -0
  168. package/dist/protocol/utils/media-source.d.ts.map +1 -0
  169. package/dist/protocol/utils/media-source.js +175 -0
  170. package/dist/protocol/utils/media-source.js.map +1 -0
  171. package/dist/protocol/utils/media-tags.d.ts +15 -0
  172. package/dist/protocol/utils/media-tags.d.ts.map +1 -0
  173. package/dist/protocol/utils/media-tags.js +150 -0
  174. package/dist/protocol/utils/media-tags.js.map +1 -0
  175. package/dist/protocol/utils/media-type.d.ts +41 -0
  176. package/dist/protocol/utils/media-type.d.ts.map +1 -0
  177. package/dist/protocol/utils/media-type.js +89 -0
  178. package/dist/protocol/utils/media-type.js.map +1 -0
  179. package/dist/protocol/utils/payload.d.ts +52 -0
  180. package/dist/protocol/utils/payload.d.ts.map +1 -0
  181. package/dist/protocol/utils/payload.js +100 -0
  182. package/dist/protocol/utils/payload.js.map +1 -0
  183. package/dist/protocol/utils/ref-attachments.d.ts +80 -0
  184. package/dist/protocol/utils/ref-attachments.d.ts.map +1 -0
  185. package/dist/protocol/utils/ref-attachments.js +121 -0
  186. package/dist/protocol/utils/ref-attachments.js.map +1 -0
  187. package/dist/protocol/utils/ref-index-store.d.ts +69 -0
  188. package/dist/protocol/utils/ref-index-store.d.ts.map +1 -0
  189. package/dist/protocol/utils/ref-index-store.js +227 -0
  190. package/dist/protocol/utils/ref-index-store.js.map +1 -0
  191. package/dist/protocol/utils/reply-limiter.d.ts +75 -0
  192. package/dist/protocol/utils/reply-limiter.d.ts.map +1 -0
  193. package/dist/protocol/utils/reply-limiter.js +123 -0
  194. package/dist/protocol/utils/reply-limiter.js.map +1 -0
  195. package/dist/protocol/utils/session-store.d.ts +73 -0
  196. package/dist/protocol/utils/session-store.d.ts.map +1 -0
  197. package/dist/protocol/utils/session-store.js +274 -0
  198. package/dist/protocol/utils/session-store.js.map +1 -0
  199. package/dist/protocol/utils/target.d.ts +53 -0
  200. package/dist/protocol/utils/target.d.ts.map +1 -0
  201. package/dist/protocol/utils/target.js +104 -0
  202. package/dist/protocol/utils/target.js.map +1 -0
  203. package/dist/protocol/utils/text-chunk.d.ts +21 -0
  204. package/dist/protocol/utils/text-chunk.d.ts.map +1 -0
  205. package/dist/protocol/utils/text-chunk.js +25 -0
  206. package/dist/protocol/utils/text-chunk.js.map +1 -0
  207. package/dist/protocol/utils/text-parsing.d.ts +40 -0
  208. package/dist/protocol/utils/text-parsing.d.ts.map +1 -0
  209. package/dist/protocol/utils/text-parsing.js +126 -0
  210. package/dist/protocol/utils/text-parsing.js.map +1 -0
  211. package/dist/protocol/utils/upload-cache.d.ts +27 -0
  212. package/dist/protocol/utils/upload-cache.d.ts.map +1 -0
  213. package/dist/protocol/utils/upload-cache.js +73 -0
  214. package/dist/protocol/utils/upload-cache.js.map +1 -0
  215. package/dist/protocol/utils/voice-text.d.ts +9 -0
  216. package/dist/protocol/utils/voice-text.d.ts.map +1 -0
  217. package/dist/protocol/utils/voice-text.js +16 -0
  218. package/dist/protocol/utils/voice-text.js.map +1 -0
  219. package/dist/storage/index.d.ts +23 -0
  220. package/dist/storage/index.d.ts.map +1 -0
  221. package/dist/storage/index.js +21 -0
  222. package/dist/storage/index.js.map +1 -0
  223. package/dist/storage/kv-store.d.ts +85 -0
  224. package/dist/storage/kv-store.d.ts.map +1 -0
  225. package/dist/storage/kv-store.js +184 -0
  226. package/dist/storage/kv-store.js.map +1 -0
  227. package/dist/storage/session-adapter.d.ts +35 -0
  228. package/dist/storage/session-adapter.d.ts.map +1 -0
  229. package/dist/storage/session-adapter.js +48 -0
  230. package/dist/storage/session-adapter.js.map +1 -0
  231. package/dist/streaming.d.ts +67 -0
  232. package/dist/streaming.d.ts.map +1 -0
  233. package/dist/streaming.js +207 -0
  234. package/dist/streaming.js.map +1 -0
  235. package/package.json +90 -0
  236. package/src/QQBot.ts +1123 -0
  237. package/src/index.ts +175 -0
  238. package/src/middleware/access-policy.ts +139 -0
  239. package/src/middleware/concurrency-guard.ts +450 -0
  240. package/src/middleware/content-sanitizer.ts +125 -0
  241. package/src/middleware/envelope-formatter.ts +140 -0
  242. package/src/middleware/error-handler.ts +77 -0
  243. package/src/middleware/history-buffer.ts +169 -0
  244. package/src/middleware/index.ts +129 -0
  245. package/src/middleware/mention-gate.ts +227 -0
  246. package/src/middleware/message-filter.ts +82 -0
  247. package/src/middleware/quote-ref.ts +237 -0
  248. package/src/middleware/rate-limiter.ts +112 -0
  249. package/src/middleware/slash-command.ts +307 -0
  250. package/src/middleware/types.ts +273 -0
  251. package/src/middleware/typing-indicator.ts +107 -0
  252. package/src/protocol/api/api-client.ts +170 -0
  253. package/src/protocol/api/media-chunked.ts +517 -0
  254. package/src/protocol/api/media.ts +188 -0
  255. package/src/protocol/api/messages.ts +345 -0
  256. package/src/protocol/api/retry.ts +157 -0
  257. package/src/protocol/api/routes.ts +62 -0
  258. package/src/protocol/api/token.ts +250 -0
  259. package/src/protocol/gateway/codec.ts +33 -0
  260. package/src/protocol/gateway/constants.ts +98 -0
  261. package/src/protocol/gateway/event-dispatcher.ts +275 -0
  262. package/src/protocol/gateway/gateway-connection.ts +375 -0
  263. package/src/protocol/gateway/reconnect.ts +155 -0
  264. package/src/protocol/index.ts +238 -0
  265. package/src/protocol/transport/index.ts +17 -0
  266. package/src/protocol/transport/types.ts +121 -0
  267. package/src/protocol/transport/webhook-server-node.ts +64 -0
  268. package/src/protocol/transport/webhook-verify.ts +118 -0
  269. package/src/protocol/transport/webhook.ts +237 -0
  270. package/src/protocol/types.ts +305 -0
  271. package/src/protocol/utils/audio.ts +663 -0
  272. package/src/protocol/utils/decode-media-path.ts +88 -0
  273. package/src/protocol/utils/ffmpeg.ts +131 -0
  274. package/src/protocol/utils/file-utils.ts +121 -0
  275. package/src/protocol/utils/format.ts +69 -0
  276. package/src/protocol/utils/image-size.ts +236 -0
  277. package/src/protocol/utils/media-source.ts +243 -0
  278. package/src/protocol/utils/media-tags.ts +177 -0
  279. package/src/protocol/utils/media-type.ts +102 -0
  280. package/src/protocol/utils/payload.ts +157 -0
  281. package/src/protocol/utils/ref-attachments.ts +190 -0
  282. package/src/protocol/utils/ref-index-store.ts +279 -0
  283. package/src/protocol/utils/reply-limiter.ts +164 -0
  284. package/src/protocol/utils/session-store.ts +346 -0
  285. package/src/protocol/utils/target.ts +121 -0
  286. package/src/protocol/utils/text-chunk.ts +29 -0
  287. package/src/protocol/utils/text-parsing.ts +153 -0
  288. package/src/protocol/utils/upload-cache.ts +107 -0
  289. package/src/protocol/utils/voice-text.ts +16 -0
  290. package/src/storage/index.ts +24 -0
  291. package/src/storage/kv-store.ts +243 -0
  292. package/src/storage/session-adapter.ts +66 -0
  293. package/src/streaming.ts +255 -0
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Decode QQ Bot media-tag path strings.
3
+ *
4
+ * Media tags emitted by the model carry paths in a `MEDIA:<path>` form;
5
+ * the path itself may be tilde-prefixed and may contain octal escape
6
+ * sequences or UTF-8 byte sequences (a quirk of how some agents encode
7
+ * non-ASCII paths). This module strips the prefix and unescapes those
8
+ * encodings.
9
+ *
10
+ * Pure string transform — no I/O, framework-agnostic.
11
+ */
12
+
13
+ /** Optional logger for decode diagnostics. */
14
+ export interface MediaPathDecodeLogger {
15
+ debug?: (msg: string) => void;
16
+ error: (msg: string) => void;
17
+ }
18
+
19
+ /**
20
+ * Minimal tilde expansion using process env.
21
+ *
22
+ * Kept self-contained so this module is portable and testable without
23
+ * pulling in path/platform helpers.
24
+ */
25
+ function expandTildeInline(p: string): string {
26
+ let result = p.trim();
27
+ if (result.startsWith("~/") || result === "~") {
28
+ const home =
29
+ typeof process !== "undefined" ? (process.env.HOME ?? process.env.USERPROFILE) : undefined;
30
+ if (home) {
31
+ result = result === "~" ? home : `${home}${result.slice(1)}`;
32
+ }
33
+ }
34
+ return result;
35
+ }
36
+
37
+ /**
38
+ * Decode a media-tag path by stripping `MEDIA:`, expanding `~`, and
39
+ * unescaping octal/UTF-8 byte sequences.
40
+ *
41
+ * @param raw - Raw path string from a media tag.
42
+ * @param log - Optional logger for decode diagnostics.
43
+ * @returns The decoded, normalized media path.
44
+ */
45
+ export function decodeMediaPath(raw: string, log?: MediaPathDecodeLogger): string {
46
+ let mediaPath = raw;
47
+ if (mediaPath.startsWith("MEDIA:")) {
48
+ mediaPath = mediaPath.slice("MEDIA:".length);
49
+ }
50
+ mediaPath = expandTildeInline(mediaPath);
51
+ mediaPath = mediaPath.replace(/\\\\/g, "\\");
52
+
53
+ // Skip octal escape decoding for Windows local paths (e.g. C:\Users\1\file.txt)
54
+ // where backslash-digit sequences like \1, \2 ... \7 are directory separators,
55
+ // not octal escape sequences.
56
+ const isWinLocal = /^[a-zA-Z]:[\\/]/.test(mediaPath) || mediaPath.startsWith("\\\\");
57
+ try {
58
+ const hasOctal = /\\[0-7]{1,3}/.test(mediaPath);
59
+ const hasNonASCII = /[\u0080-\u00FF]/.test(mediaPath);
60
+
61
+ if (!isWinLocal && (hasOctal || hasNonASCII)) {
62
+ log?.debug?.(`Decoding path with mixed encoding: ${mediaPath}`);
63
+ const decoded = mediaPath.replace(/\\([0-7]{1,3})/g, (_: string, octal: string) => {
64
+ return String.fromCharCode(Number.parseInt(octal, 8));
65
+ });
66
+ const bytes: number[] = [];
67
+ for (let i = 0; i < decoded.length; i++) {
68
+ const code = decoded.charCodeAt(i);
69
+ if (code <= 0xff) {
70
+ bytes.push(code);
71
+ } else {
72
+ const charBytes = Buffer.from(decoded[i], "utf8");
73
+ bytes.push(...charBytes);
74
+ }
75
+ }
76
+ const buffer = Buffer.from(bytes);
77
+ const utf8Decoded = buffer.toString("utf8");
78
+ if (!utf8Decoded.includes("\uFFFD") || utf8Decoded.length < decoded.length) {
79
+ mediaPath = utf8Decoded;
80
+ log?.debug?.(`Successfully decoded path: ${mediaPath}`);
81
+ }
82
+ }
83
+ } catch (decodeErr) {
84
+ log?.error(`Path decode error: ${String(decodeErr)}`);
85
+ }
86
+
87
+ return mediaPath;
88
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * ffmpeg / silk-wasm runtime detection helpers.
3
+ *
4
+ * QQ voice messaging requires SILK-encoded audio. Two transcoding paths
5
+ * are supported:
6
+ * - **ffmpeg** (preferred): native decoder for any input format.
7
+ * - **silk-wasm + mpg123-decoder** (fallback): WASM decoders for SILK
8
+ * and MP3 respectively, used when ffmpeg is not installed on the host.
9
+ *
10
+ * Both paths are loaded **lazily** so SDK consumers that never send voice
11
+ * messages don't pay the detection cost.
12
+ */
13
+
14
+ import { execFile } from "node:child_process";
15
+ import * as fs from "node:fs";
16
+ import * as path from "node:path";
17
+
18
+ /** Return true when running on Windows. */
19
+ export function isWindows(): boolean {
20
+ return process.platform === "win32";
21
+ }
22
+
23
+ let _ffmpegPath: string | null | undefined;
24
+ let _ffmpegCheckPromise: Promise<string | null> | null = null;
25
+
26
+ /**
27
+ * Detect ffmpeg and return an executable path when available.
28
+ *
29
+ * The result is cached for the lifetime of the process; call
30
+ * {@link resetFfmpegCache} between tests to force re-detection.
31
+ *
32
+ * Detection order:
33
+ * 1. `FFMPEG_PATH` environment variable
34
+ * 2. Plain `ffmpeg` (or `ffmpeg.exe`) on PATH
35
+ * 3. Common install locations (Homebrew, apt, snap, choco, scoop)
36
+ */
37
+ export function detectFfmpeg(): Promise<string | null> {
38
+ if (_ffmpegPath !== undefined) {
39
+ return Promise.resolve(_ffmpegPath);
40
+ }
41
+ if (_ffmpegCheckPromise) {
42
+ return _ffmpegCheckPromise;
43
+ }
44
+
45
+ _ffmpegCheckPromise = (async () => {
46
+ const envPath = process.env.FFMPEG_PATH;
47
+ if (envPath) {
48
+ const ok = await testExecutable(envPath, ["-version"]);
49
+ if (ok) {
50
+ _ffmpegPath = envPath;
51
+ return _ffmpegPath;
52
+ }
53
+ }
54
+
55
+ const cmd = isWindows() ? "ffmpeg.exe" : "ffmpeg";
56
+ const ok = await testExecutable(cmd, ["-version"]);
57
+ if (ok) {
58
+ _ffmpegPath = cmd;
59
+ return _ffmpegPath;
60
+ }
61
+
62
+ const commonPaths = isWindows()
63
+ ? [
64
+ "C:\\ffmpeg\\bin\\ffmpeg.exe",
65
+ path.join(process.env.LOCALAPPDATA || "", "Programs", "ffmpeg", "bin", "ffmpeg.exe"),
66
+ path.join(process.env.ProgramFiles || "", "ffmpeg", "bin", "ffmpeg.exe"),
67
+ ]
68
+ : [
69
+ "/usr/local/bin/ffmpeg",
70
+ "/opt/homebrew/bin/ffmpeg",
71
+ "/usr/bin/ffmpeg",
72
+ "/snap/bin/ffmpeg",
73
+ ];
74
+
75
+ for (const p of commonPaths) {
76
+ if (p && fs.existsSync(p)) {
77
+ const works = await testExecutable(p, ["-version"]);
78
+ if (works) {
79
+ _ffmpegPath = p;
80
+ return _ffmpegPath;
81
+ }
82
+ }
83
+ }
84
+
85
+ _ffmpegPath = null;
86
+ return null;
87
+ })().finally(() => {
88
+ _ffmpegCheckPromise = null;
89
+ });
90
+
91
+ return _ffmpegCheckPromise;
92
+ }
93
+
94
+ /** Return true when the executable responds successfully to the given args. */
95
+ function testExecutable(cmd: string, args: string[]): Promise<boolean> {
96
+ return new Promise((resolve) => {
97
+ execFile(cmd, args, { timeout: 5000 }, (err) => {
98
+ resolve(!err);
99
+ });
100
+ });
101
+ }
102
+
103
+ /** Reset ffmpeg detection state, mainly for tests. */
104
+ export function resetFfmpegCache(): void {
105
+ _ffmpegPath = undefined;
106
+ _ffmpegCheckPromise = null;
107
+ }
108
+
109
+ let _silkWasmAvailable: boolean | null = null;
110
+
111
+ /**
112
+ * Check whether silk-wasm can run in the current environment.
113
+ *
114
+ * The SDK does NOT bundle `silk-wasm` as a hard dependency; this probe
115
+ * dynamically imports it and falls back gracefully when the package is
116
+ * not installed. Add `silk-wasm` to your dependencies (or peer
117
+ * dependencies) when you need voice-message support.
118
+ */
119
+ export async function checkSilkWasmAvailable(): Promise<boolean> {
120
+ if (_silkWasmAvailable !== null) {
121
+ return _silkWasmAvailable;
122
+ }
123
+ try {
124
+ const { isSilk } = (await import("silk-wasm")) as { isSilk: (data: Uint8Array) => boolean };
125
+ isSilk(new Uint8Array(0));
126
+ _silkWasmAvailable = true;
127
+ } catch {
128
+ _silkWasmAvailable = false;
129
+ }
130
+ return _silkWasmAvailable;
131
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * File-related helpers for the QQ Open Platform SDK.
3
+ *
4
+ * Pure helpers: filename sanitization, size constants, file size formatting.
5
+ * The SDK does NOT bundle SSRF / remote-fetch logic — those are concerns
6
+ * of the host application (e.g. an OpenClaw plugin) and should be
7
+ * implemented at the integration layer.
8
+ */
9
+
10
+ import { MediaFileType } from "../types.js";
11
+
12
+ /** Maximum file size accepted by the QQ Bot one-shot upload API (base64 direct). */
13
+ export const MAX_UPLOAD_SIZE = 20 * 1024 * 1024;
14
+
15
+ /** Absolute upper bound enforced on the chunked upload path. */
16
+ export const CHUNKED_UPLOAD_MAX_SIZE = 100 * 1024 * 1024;
17
+
18
+ /** Threshold above which uploads are dispatched to the chunked path. */
19
+ export const LARGE_FILE_THRESHOLD = 5 * 1024 * 1024;
20
+
21
+ /** Per-{@link MediaFileType} upload metadata. */
22
+ export const MEDIA_FILE_TYPE_INFO: Record<MediaFileType, { maxSize: number; name: string }> = {
23
+ [MediaFileType.IMAGE]: { maxSize: 30 * 1024 * 1024, name: "image" },
24
+ [MediaFileType.VIDEO]: { maxSize: 100 * 1024 * 1024, name: "video" },
25
+ [MediaFileType.VOICE]: { maxSize: 20 * 1024 * 1024, name: "voice" },
26
+ [MediaFileType.FILE]: { maxSize: 100 * 1024 * 1024, name: "file" },
27
+ };
28
+
29
+ export function getFileTypeName(fileType: number): string {
30
+ return MEDIA_FILE_TYPE_INFO[fileType as MediaFileType]?.name ?? "file";
31
+ }
32
+
33
+ export function getMaxUploadSize(fileType: number): number {
34
+ return MEDIA_FILE_TYPE_INFO[fileType as MediaFileType]?.maxSize ?? CHUNKED_UPLOAD_MAX_SIZE;
35
+ }
36
+
37
+ /** Canonical ext → MIME table. Single source of truth. */
38
+ const MIME_TYPES: Record<string, string> = {
39
+ ".jpg": "image/jpeg",
40
+ ".jpeg": "image/jpeg",
41
+ ".png": "image/png",
42
+ ".gif": "image/gif",
43
+ ".webp": "image/webp",
44
+ ".bmp": "image/bmp",
45
+ ".mp4": "video/mp4",
46
+ ".mov": "video/quicktime",
47
+ ".avi": "video/x-msvideo",
48
+ ".mkv": "video/x-matroska",
49
+ ".webm": "video/webm",
50
+ ".pdf": "application/pdf",
51
+ ".doc": "application/msword",
52
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
53
+ ".xls": "application/vnd.ms-excel",
54
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
55
+ ".zip": "application/zip",
56
+ ".tar": "application/x-tar",
57
+ ".gz": "application/gzip",
58
+ ".txt": "text/plain",
59
+ };
60
+
61
+ /** Extensions accepted as image uploads by the QQ Bot media pipeline. */
62
+ const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
63
+
64
+ /**
65
+ * Extract the lowercase extension (`".png"`) from a path-like string.
66
+ *
67
+ * Inlined from the lookup helpers so this module stays free of `node:path`
68
+ * imports — works the same for `/abs/foo.PNG`, `relative/foo.PNG`,
69
+ * `bare.PNG`, and accepts both forward and backward slashes.
70
+ */
71
+ function lowercaseExt(filePath: string): string {
72
+ const sepIdx = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
73
+ const base = sepIdx === -1 ? filePath : filePath.slice(sepIdx + 1);
74
+ const dotIdx = base.lastIndexOf(".");
75
+ if (dotIdx <= 0) {
76
+ return "";
77
+ }
78
+ return base.slice(dotIdx).toLowerCase();
79
+ }
80
+
81
+ /** Infer a MIME type from a file path's extension. */
82
+ export function getMimeType(filePath: string): string {
83
+ return MIME_TYPES[lowercaseExt(filePath)] ?? "application/octet-stream";
84
+ }
85
+
86
+ /**
87
+ * Return the image MIME type for a local file path, or `null` if the
88
+ * extension is not in the supported image whitelist.
89
+ *
90
+ * Use this instead of {@link getMimeType} when the caller must enforce
91
+ * "image formats only" as a business rule (e.g. constructing a
92
+ * `data:image/...;base64,` URL).
93
+ */
94
+ export function getImageMimeType(filePath: string): string | null {
95
+ const ext = lowercaseExt(filePath);
96
+ if (!IMAGE_EXTENSIONS.has(ext)) {
97
+ return null;
98
+ }
99
+ return MIME_TYPES[ext] ?? null;
100
+ }
101
+
102
+ /**
103
+ * Sanitize a filename for safe transmission to the QQ Open Platform.
104
+ *
105
+ * - Strips path separators / control characters.
106
+ * - Collapses repeated whitespace.
107
+ * - Falls back to `"file"` when the result is empty.
108
+ */
109
+ export function sanitizeFileName(name: string): string {
110
+ if (!name) {
111
+ return "file";
112
+ }
113
+
114
+ const cleaned = name
115
+ .replace(/[\\/:*?"<>|]/g, "_")
116
+ // eslint-disable-next-line no-control-regex
117
+ .replace(/[\u0000-\u001f\u007f]/g, "")
118
+ .replace(/\s+/g, " ")
119
+ .trim();
120
+ return cleaned || "file";
121
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * General formatting utilities. Pure helpers with zero external dependencies.
3
+ */
4
+
5
+ /** Format any error object into a readable string, traversing the `.cause` chain. */
6
+ export function formatErrorMessage(err: unknown): string {
7
+ if (err instanceof Error) {
8
+ let formatted = err.message || err.name || "Error";
9
+ let cause: unknown = err.cause;
10
+ const seen = new Set<unknown>([err]);
11
+ while (cause && !seen.has(cause)) {
12
+ seen.add(cause);
13
+ if (cause instanceof Error) {
14
+ if (cause.message) {
15
+ formatted += ` | ${cause.message}`;
16
+ }
17
+ cause = cause.cause;
18
+ } else if (typeof cause === "string") {
19
+ formatted += ` | ${cause}`;
20
+ break;
21
+ } else {
22
+ break;
23
+ }
24
+ }
25
+ return formatted;
26
+ }
27
+ if (typeof err === "string") {
28
+ return err;
29
+ }
30
+ if (
31
+ err === null ||
32
+ err === undefined ||
33
+ typeof err === "number" ||
34
+ typeof err === "boolean" ||
35
+ typeof err === "bigint"
36
+ ) {
37
+ return String(err);
38
+ }
39
+ try {
40
+ return JSON.stringify(err);
41
+ } catch {
42
+ return Object.prototype.toString.call(err);
43
+ }
44
+ }
45
+
46
+ /** Format a millisecond duration into a human-readable string (e.g. "5m 30s"). */
47
+ export function formatDuration(durationMs: number): string {
48
+ const seconds = Math.round(durationMs / 1000);
49
+ if (seconds < 60) {
50
+ return `${seconds}s`;
51
+ }
52
+ const minutes = Math.floor(seconds / 60);
53
+ const remainSeconds = seconds % 60;
54
+ return remainSeconds > 0 ? `${minutes}m ${remainSeconds}s` : `${minutes}m`;
55
+ }
56
+
57
+ /** Format a byte count into a human-readable string (e.g. "1.23 MB"). */
58
+ export function formatFileSize(bytes: number): string {
59
+ if (bytes < 1024) {
60
+ return `${bytes} B`;
61
+ }
62
+ if (bytes < 1024 * 1024) {
63
+ return `${(bytes / 1024).toFixed(2)} KB`;
64
+ }
65
+ if (bytes < 1024 * 1024 * 1024) {
66
+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
67
+ }
68
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
69
+ }
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Image dimension helpers for QQ Bot markdown image syntax.
3
+ *
4
+ * QQ Bot markdown images use `![#widthpx #heightpx](url)`.
5
+ *
6
+ * The header parsers are all pure functions. URL probing requires a
7
+ * caller-provided {@link ImageBytesFetcher} so this module stays free of
8
+ * networking / SSRF concerns — the OpenClaw plugin (or any embedder) is
9
+ * responsible for enforcing public-network-only / hostname-allowlist
10
+ * policies before any byte hits this code.
11
+ */
12
+
13
+ import { Buffer } from "node:buffer";
14
+ import { formatErrorMessage } from "./format.js";
15
+
16
+ export interface ImageSize {
17
+ width: number;
18
+ height: number;
19
+ }
20
+
21
+ /** Default dimensions used when probing fails. */
22
+ export const DEFAULT_IMAGE_SIZE: ImageSize = { width: 512, height: 512 };
23
+
24
+ // ============ Header parsers ============
25
+
26
+ /** Parse image dimensions from the PNG header. */
27
+ function parsePngSize(buffer: Buffer): ImageSize | null {
28
+ // PNG signature: 89 50 4E 47 0D 0A 1A 0A
29
+ if (buffer.length < 24) {
30
+ return null;
31
+ }
32
+ if (buffer[0] !== 0x89 || buffer[1] !== 0x50 || buffer[2] !== 0x4e || buffer[3] !== 0x47) {
33
+ return null;
34
+ }
35
+ // The IHDR chunk begins at byte 8, with width/height at 16..23.
36
+ const width = buffer.readUInt32BE(16);
37
+ const height = buffer.readUInt32BE(20);
38
+ return { width, height };
39
+ }
40
+
41
+ /** Parse image dimensions from JPEG SOF0/SOF2 markers. */
42
+ function parseJpegSize(buffer: Buffer): ImageSize | null {
43
+ // JPEG signature: FF D8 FF
44
+ if (buffer.length < 4) {
45
+ return null;
46
+ }
47
+ if (buffer[0] !== 0xff || buffer[1] !== 0xd8) {
48
+ return null;
49
+ }
50
+
51
+ let offset = 2;
52
+ while (offset < buffer.length - 9) {
53
+ if (buffer[offset] !== 0xff) {
54
+ offset++;
55
+ continue;
56
+ }
57
+
58
+ const marker = buffer[offset + 1];
59
+ // SOF0 (0xC0) and SOF2 (0xC2) contain dimensions.
60
+ if (marker === 0xc0 || marker === 0xc2) {
61
+ // Layout: FF C0 length(2) precision(1) height(2) width(2)
62
+ if (offset + 9 <= buffer.length) {
63
+ const height = buffer.readUInt16BE(offset + 5);
64
+ const width = buffer.readUInt16BE(offset + 7);
65
+ return { width, height };
66
+ }
67
+ }
68
+
69
+ if (offset + 3 < buffer.length) {
70
+ const blockLength = buffer.readUInt16BE(offset + 2);
71
+ offset += 2 + blockLength;
72
+ } else {
73
+ break;
74
+ }
75
+ }
76
+
77
+ return null;
78
+ }
79
+
80
+ /** Parse image dimensions from the GIF header. */
81
+ function parseGifSize(buffer: Buffer): ImageSize | null {
82
+ if (buffer.length < 10) {
83
+ return null;
84
+ }
85
+ const signature = buffer.toString("ascii", 0, 6);
86
+ if (signature !== "GIF87a" && signature !== "GIF89a") {
87
+ return null;
88
+ }
89
+ const width = buffer.readUInt16LE(6);
90
+ const height = buffer.readUInt16LE(8);
91
+ return { width, height };
92
+ }
93
+
94
+ /** Parse image dimensions from WebP headers. */
95
+ function parseWebpSize(buffer: Buffer): ImageSize | null {
96
+ if (buffer.length < 30) {
97
+ return null;
98
+ }
99
+
100
+ const riff = buffer.toString("ascii", 0, 4);
101
+ const webp = buffer.toString("ascii", 8, 12);
102
+ if (riff !== "RIFF" || webp !== "WEBP") {
103
+ return null;
104
+ }
105
+
106
+ const chunkType = buffer.toString("ascii", 12, 16);
107
+
108
+ // VP8 (lossy)
109
+ if (chunkType === "VP8 ") {
110
+ if (buffer.length >= 30 && buffer[23] === 0x9d && buffer[24] === 0x01 && buffer[25] === 0x2a) {
111
+ const width = buffer.readUInt16LE(26) & 0x3fff;
112
+ const height = buffer.readUInt16LE(28) & 0x3fff;
113
+ return { width, height };
114
+ }
115
+ }
116
+
117
+ // VP8L (lossless)
118
+ if (chunkType === "VP8L") {
119
+ if (buffer.length >= 25 && buffer[20] === 0x2f) {
120
+ const bits = buffer.readUInt32LE(21);
121
+ const width = (bits & 0x3fff) + 1;
122
+ const height = ((bits >> 14) & 0x3fff) + 1;
123
+ return { width, height };
124
+ }
125
+ }
126
+
127
+ // VP8X (extended format)
128
+ if (chunkType === "VP8X") {
129
+ if (buffer.length >= 30) {
130
+ const width = (buffer[24] | (buffer[25] << 8) | (buffer[26] << 16)) + 1;
131
+ const height = (buffer[27] | (buffer[28] << 8) | (buffer[29] << 16)) + 1;
132
+ return { width, height };
133
+ }
134
+ }
135
+
136
+ return null;
137
+ }
138
+
139
+ /** Parse image dimensions from raw image bytes (PNG / JPEG / GIF / WebP). */
140
+ export function parseImageSize(buffer: Buffer): ImageSize | null {
141
+ return (
142
+ parsePngSize(buffer) ?? parseJpegSize(buffer) ?? parseGifSize(buffer) ?? parseWebpSize(buffer)
143
+ );
144
+ }
145
+
146
+ // ============ URL / data-URL probing ============
147
+
148
+ /**
149
+ * Bytes fetcher contract used by {@link getImageSizeFromUrl}.
150
+ *
151
+ * Embedders inject their own implementation so SSRF policy, hostname
152
+ * allowlists, and other transport concerns stay outside the SDK.
153
+ */
154
+ export type ImageBytesFetcher = (url: string, opts: { maxBytes: number }) => Promise<Buffer>;
155
+
156
+ /**
157
+ * Fetch image dimensions from a URL using only the first 64 KB of bytes.
158
+ *
159
+ * The caller is responsible for SSRF safety: the {@link ImageBytesFetcher}
160
+ * implementation should reject private/reserved/loopback/link-local/metadata
161
+ * destinations before any byte is read.
162
+ *
163
+ * Returns `null` when the fetch fails or the bytes don't match any
164
+ * supported image header.
165
+ */
166
+ export async function getImageSizeFromUrl(
167
+ url: string,
168
+ fetchBytes: ImageBytesFetcher,
169
+ opts: { maxBytes?: number; logger?: { debug?: (msg: string) => void } } = {},
170
+ ): Promise<ImageSize | null> {
171
+ const maxBytes = opts.maxBytes ?? 65_536;
172
+ try {
173
+ const buffer = await fetchBytes(url, { maxBytes });
174
+ const size = parseImageSize(buffer);
175
+ if (size) {
176
+ opts.logger?.debug?.(
177
+ `[image-size] Got size from URL: ${size.width}x${size.height} - ${url.slice(0, 60)}...`,
178
+ );
179
+ }
180
+ return size;
181
+ } catch (err) {
182
+ opts.logger?.debug?.(
183
+ `[image-size] Error fetching ${url.slice(0, 60)}...: ${formatErrorMessage(err)}`,
184
+ );
185
+ return null;
186
+ }
187
+ }
188
+
189
+ /** Parse image dimensions from a Base64 data URL. */
190
+ export function getImageSizeFromDataUrl(
191
+ dataUrl: string,
192
+ logger?: { debug?: (msg: string) => void },
193
+ ): ImageSize | null {
194
+ try {
195
+ // Format: data:image/png;base64,xxxxx
196
+ const matches = dataUrl.match(/^data:image\/[^;]+;base64,(.+)$/);
197
+ if (!matches) {
198
+ return null;
199
+ }
200
+
201
+ const base64Data = matches[1];
202
+ const buffer = Buffer.from(base64Data, "base64");
203
+
204
+ const size = parseImageSize(buffer);
205
+ if (size) {
206
+ logger?.debug?.(`[image-size] Got size from Base64: ${size.width}x${size.height}`);
207
+ }
208
+
209
+ return size;
210
+ } catch (err) {
211
+ logger?.debug?.(`[image-size] Error parsing Base64: ${formatErrorMessage(err)}`);
212
+ return null;
213
+ }
214
+ }
215
+
216
+ // ============ QQ Bot markdown image syntax ============
217
+
218
+ /** Format a markdown image with QQ Bot width/height annotations. */
219
+ export function formatQQBotMarkdownImage(url: string, size: ImageSize | null): string {
220
+ const { width, height } = size ?? DEFAULT_IMAGE_SIZE;
221
+ return `![#${width}px #${height}px](${url})`;
222
+ }
223
+
224
+ /** Return true when markdown already contains QQ Bot size annotations. */
225
+ export function hasQQBotImageSize(markdownImage: string): boolean {
226
+ return /!\[#\d+px\s+#\d+px\]/.test(markdownImage);
227
+ }
228
+
229
+ /** Extract width and height from QQBot markdown image syntax: `![#Wpx #Hpx](url)`. */
230
+ export function extractQQBotImageSize(markdownImage: string): ImageSize | null {
231
+ const match = markdownImage.match(/!\[#(\d+)px\s+#(\d+)px\]/);
232
+ if (match) {
233
+ return { width: Number.parseInt(match[1], 10), height: Number.parseInt(match[2], 10) };
234
+ }
235
+ return null;
236
+ }