@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,346 @@
1
+ /**
2
+ * Multi-account JSON-file session persistence for the WebSocket gateway.
3
+ *
4
+ * QQ Open Platform allows a bot to RESUME after a brief disconnect by
5
+ * replaying the last `(session_id, lastSeq)` it observed. This module
6
+ * persists that pair plus `intentLevelIndex` (so the auto-fallback logic
7
+ * can resume at the right intent level on restart) into per-account JSON
8
+ * files, with throttled writes and automatic expiry of stale sessions.
9
+ *
10
+ * Path resolution is delegated to the embedder via the constructor — the
11
+ * SDK does not assume any particular directory layout.
12
+ */
13
+
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { formatErrorMessage } from "./format.js";
17
+
18
+ /** Persisted gateway session state. */
19
+ export interface SessionState {
20
+ sessionId: string | null;
21
+ lastSeq: number | null;
22
+ lastConnectedAt: number;
23
+ intentLevelIndex: number;
24
+ accountId: string;
25
+ savedAt: number;
26
+ appId?: string;
27
+ }
28
+
29
+ /** Optional logger contract used for diagnostic messages. */
30
+ export interface SessionStoreLogger {
31
+ log?: (msg: string) => void;
32
+ error?: (msg: string) => void;
33
+ }
34
+
35
+ /** Configuration for {@link FileSessionStore}. */
36
+ export interface FileSessionStoreOptions {
37
+ /** Resolve the directory that holds session JSON files. */
38
+ getDir: () => string;
39
+ /** Ensure the directory exists. Called before writing. */
40
+ ensureDir: () => void;
41
+ /** Session expiry, in milliseconds. Defaults to 5 minutes. */
42
+ expireMs?: number;
43
+ /** Save throttle window, in milliseconds. Defaults to 1 second. */
44
+ saveThrottleMs?: number;
45
+ /** Optional logger. */
46
+ logger?: SessionStoreLogger;
47
+ }
48
+
49
+ const NOOP_LOGGER: Required<SessionStoreLogger> = {
50
+ log: () => {},
51
+ error: () => {},
52
+ };
53
+
54
+ const DEFAULT_EXPIRE_MS = 5 * 60 * 1000;
55
+ const DEFAULT_SAVE_THROTTLE_MS = 1000;
56
+
57
+ /**
58
+ * Multi-account file-backed gateway session store.
59
+ *
60
+ * One instance handles all accounts owned by a single QQ Bot deployment —
61
+ * the per-account file path is derived deterministically from
62
+ * `accountId`. The on-disk filename uses base64url(accountId) so any
63
+ * Unicode/special-character account id is safe.
64
+ */
65
+ export class FileSessionStore {
66
+ private readonly options: Required<Omit<FileSessionStoreOptions, "logger">> & {
67
+ logger: Required<SessionStoreLogger>;
68
+ };
69
+
70
+ private readonly throttleState = new Map<
71
+ string,
72
+ {
73
+ pendingState: SessionState | null;
74
+ lastSaveTime: number;
75
+ throttleTimer: ReturnType<typeof setTimeout> | null;
76
+ }
77
+ >();
78
+
79
+ constructor(options: FileSessionStoreOptions) {
80
+ this.options = {
81
+ getDir: options.getDir,
82
+ ensureDir: options.ensureDir,
83
+ expireMs: options.expireMs ?? DEFAULT_EXPIRE_MS,
84
+ saveThrottleMs: options.saveThrottleMs ?? DEFAULT_SAVE_THROTTLE_MS,
85
+ logger: {
86
+ log: options.logger?.log ?? NOOP_LOGGER.log,
87
+ error: options.logger?.error ?? NOOP_LOGGER.error,
88
+ },
89
+ };
90
+ }
91
+
92
+ /** Load a saved session, rejecting expired or mismatched-appId entries. */
93
+ load(accountId: string, expectedAppId?: string): SessionState | null {
94
+ try {
95
+ let filePath: string | null = null;
96
+ for (const candidatePath of this.getCandidateSessionPaths(accountId)) {
97
+ if (fs.existsSync(candidatePath)) {
98
+ filePath = candidatePath;
99
+ break;
100
+ }
101
+ }
102
+ if (!filePath) {
103
+ return null;
104
+ }
105
+
106
+ const data = fs.readFileSync(filePath, "utf-8");
107
+ const state = JSON.parse(data) as SessionState;
108
+ const now = Date.now();
109
+
110
+ if (now - state.savedAt > this.options.expireMs) {
111
+ this.options.logger.log(
112
+ `[session-store] Session expired for ${accountId}, age: ${Math.round((now - state.savedAt) / 1000)}s`,
113
+ );
114
+ try {
115
+ fs.unlinkSync(filePath);
116
+ } catch {
117
+ // Best-effort cleanup; ignore errors.
118
+ }
119
+ return null;
120
+ }
121
+
122
+ if (expectedAppId && state.appId && state.appId !== expectedAppId) {
123
+ this.options.logger.log(
124
+ `[session-store] appId mismatch for ${accountId}: saved=${state.appId}, current=${expectedAppId}. Discarding stale session.`,
125
+ );
126
+ try {
127
+ fs.unlinkSync(filePath);
128
+ } catch {
129
+ // Best-effort cleanup; ignore errors.
130
+ }
131
+ return null;
132
+ }
133
+
134
+ if (!state.sessionId || state.lastSeq === null || state.lastSeq === undefined) {
135
+ this.options.logger.log(`[session-store] Invalid session data for ${accountId}`);
136
+ return null;
137
+ }
138
+
139
+ this.options.logger.log(
140
+ `[session-store] Loaded session for ${accountId}: sessionId=${state.sessionId}, lastSeq=${state.lastSeq}, appId=${state.appId ?? "unknown"}, age=${Math.round((now - state.savedAt) / 1000)}s`,
141
+ );
142
+ return state;
143
+ } catch (err) {
144
+ this.options.logger.error(
145
+ `[session-store] Failed to load session for ${accountId}: ${formatErrorMessage(err)}`,
146
+ );
147
+ return null;
148
+ }
149
+ }
150
+
151
+ /** Save session state with throttling. */
152
+ save(state: SessionState): void {
153
+ const { accountId } = state;
154
+ let throttle = this.throttleState.get(accountId);
155
+ if (!throttle) {
156
+ throttle = { pendingState: null, lastSaveTime: 0, throttleTimer: null };
157
+ this.throttleState.set(accountId, throttle);
158
+ }
159
+
160
+ const now = Date.now();
161
+ const timeSinceLastSave = now - throttle.lastSaveTime;
162
+
163
+ if (timeSinceLastSave >= this.options.saveThrottleMs) {
164
+ this.doSaveSession(state);
165
+ throttle.lastSaveTime = now;
166
+ throttle.pendingState = null;
167
+ if (throttle.throttleTimer) {
168
+ clearTimeout(throttle.throttleTimer);
169
+ throttle.throttleTimer = null;
170
+ }
171
+ } else {
172
+ throttle.pendingState = state;
173
+ if (!throttle.throttleTimer) {
174
+ const delay = this.options.saveThrottleMs - timeSinceLastSave;
175
+ throttle.throttleTimer = setTimeout(() => {
176
+ const t = this.throttleState.get(accountId);
177
+ if (t?.pendingState) {
178
+ this.doSaveSession(t.pendingState);
179
+ t.lastSaveTime = Date.now();
180
+ t.pendingState = null;
181
+ }
182
+ if (t) {
183
+ t.throttleTimer = null;
184
+ }
185
+ }, delay);
186
+ }
187
+ }
188
+ }
189
+
190
+ /** Clear a saved session and any pending throttle state. */
191
+ clear(accountId: string): void {
192
+ const throttle = this.throttleState.get(accountId);
193
+ if (throttle) {
194
+ if (throttle.throttleTimer) {
195
+ clearTimeout(throttle.throttleTimer);
196
+ }
197
+ this.throttleState.delete(accountId);
198
+ }
199
+ try {
200
+ let cleared = false;
201
+ for (const filePath of this.getCandidateSessionPaths(accountId)) {
202
+ if (fs.existsSync(filePath)) {
203
+ fs.unlinkSync(filePath);
204
+ cleared = true;
205
+ }
206
+ }
207
+ if (cleared) {
208
+ this.options.logger.log(`[session-store] Cleared session for ${accountId}`);
209
+ }
210
+ } catch (err) {
211
+ this.options.logger.error(
212
+ `[session-store] Failed to clear session for ${accountId}: ${formatErrorMessage(err)}`,
213
+ );
214
+ }
215
+ }
216
+
217
+ /** Update only lastSeq on the persisted session. */
218
+ updateLastSeq(accountId: string, lastSeq: number): void {
219
+ const existing = this.load(accountId);
220
+ if (existing?.sessionId) {
221
+ this.save({ ...existing, lastSeq });
222
+ }
223
+ }
224
+
225
+ /** Load all saved sessions from disk. */
226
+ getAllSessions(): SessionState[] {
227
+ const sessions = new Map<string, SessionState>();
228
+ try {
229
+ const sessionDir = this.options.getDir();
230
+ if (!fs.existsSync(sessionDir)) {
231
+ return [];
232
+ }
233
+ const files = fs.readdirSync(sessionDir);
234
+
235
+ for (const file of files) {
236
+ if (this.isSessionFileName(file)) {
237
+ try {
238
+ const { state } = this.readSessionStateFile(file);
239
+ if (typeof state.accountId !== "string" || !state.accountId) {
240
+ continue;
241
+ }
242
+ const existing = sessions.get(state.accountId);
243
+ if (!existing || (state.savedAt ?? 0) >= (existing.savedAt ?? 0)) {
244
+ sessions.set(state.accountId, state);
245
+ }
246
+ } catch {
247
+ // Skip malformed files; cleanup is opportunistic.
248
+ }
249
+ }
250
+ }
251
+ } catch {
252
+ // Directory may not exist yet; return empty.
253
+ }
254
+ return [...sessions.values()];
255
+ }
256
+
257
+ /** Remove expired session files from disk. Returns number removed. */
258
+ cleanupExpiredSessions(): number {
259
+ let cleaned = 0;
260
+ try {
261
+ const sessionDir = this.options.getDir();
262
+ if (!fs.existsSync(sessionDir)) {
263
+ return 0;
264
+ }
265
+ const now = Date.now();
266
+ const files = fs.readdirSync(sessionDir);
267
+
268
+ for (const file of files) {
269
+ if (this.isSessionFileName(file)) {
270
+ const filePath = path.join(sessionDir, file);
271
+ try {
272
+ const { state } = this.readSessionStateFile(file);
273
+
274
+ if (now - state.savedAt > this.options.expireMs) {
275
+ fs.unlinkSync(filePath);
276
+ cleaned++;
277
+ this.options.logger.log(`[session-store] Cleaned expired session: ${file}`);
278
+ }
279
+ } catch {
280
+ try {
281
+ fs.unlinkSync(filePath);
282
+ cleaned++;
283
+ } catch {
284
+ // Best-effort cleanup; ignore errors.
285
+ }
286
+ }
287
+ }
288
+ }
289
+ } catch {
290
+ // Directory may not exist yet; nothing to do.
291
+ }
292
+ return cleaned;
293
+ }
294
+
295
+ // ============ Internal ============
296
+
297
+ private encodeAccountIdForFileName(accountId: string): string {
298
+ return Buffer.from(accountId, "utf8").toString("base64url");
299
+ }
300
+
301
+ private getLegacySessionPath(accountId: string): string {
302
+ const safeId = accountId.replace(/[^a-zA-Z0-9_-]/g, "_");
303
+ return path.join(this.options.getDir(), `session-${safeId}.json`);
304
+ }
305
+
306
+ private getSessionPath(accountId: string): string {
307
+ const encodedId = this.encodeAccountIdForFileName(accountId);
308
+ return path.join(this.options.getDir(), `session-${encodedId}.json`);
309
+ }
310
+
311
+ private getCandidateSessionPaths(accountId: string): string[] {
312
+ const primaryPath = this.getSessionPath(accountId);
313
+ const legacyPath = this.getLegacySessionPath(accountId);
314
+ return primaryPath === legacyPath ? [primaryPath] : [primaryPath, legacyPath];
315
+ }
316
+
317
+ private isSessionFileName(file: string): boolean {
318
+ return file.startsWith("session-") && file.endsWith(".json");
319
+ }
320
+
321
+ private readSessionStateFile(file: string): { filePath: string; state: SessionState } {
322
+ const filePath = path.join(this.options.getDir(), file);
323
+ const data = fs.readFileSync(filePath, "utf-8");
324
+ return { filePath, state: JSON.parse(data) as SessionState };
325
+ }
326
+
327
+ private doSaveSession(state: SessionState): void {
328
+ const filePath = this.getSessionPath(state.accountId);
329
+ const legacyPath = this.getLegacySessionPath(state.accountId);
330
+ try {
331
+ this.options.ensureDir();
332
+ const stateToSave: SessionState = { ...state, savedAt: Date.now() };
333
+ fs.writeFileSync(filePath, JSON.stringify(stateToSave, null, 2), "utf-8");
334
+ if (legacyPath !== filePath && fs.existsSync(legacyPath)) {
335
+ fs.unlinkSync(legacyPath);
336
+ }
337
+ this.options.logger.log(
338
+ `[session-store] Saved session for ${state.accountId}: sessionId=${state.sessionId}, lastSeq=${state.lastSeq}`,
339
+ );
340
+ } catch (err) {
341
+ this.options.logger.error(
342
+ `[session-store] Failed to save session for ${state.accountId}: ${formatErrorMessage(err)}`,
343
+ );
344
+ }
345
+ }
346
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * QQ Bot target address parser.
3
+ *
4
+ * QQ Bot conversations are addressed via strings of the form
5
+ * `qqbot:<scope>:<id>` where scope is `c2c | group | channel`. This
6
+ * module parses, validates, and canonicalizes those strings.
7
+ *
8
+ * All functions are pure (no I/O) and framework-agnostic.
9
+ */
10
+
11
+ /** Supported target types. */
12
+ export type TargetType = "c2c" | "group" | "channel";
13
+
14
+ /** Parsed delivery target. */
15
+ export interface ParsedTarget {
16
+ type: TargetType;
17
+ id: string;
18
+ }
19
+
20
+ /**
21
+ * Parse a qqbot target string into a structured delivery target.
22
+ *
23
+ * Supported formats:
24
+ * - `qqbot:c2c:openid` → C2C direct message
25
+ * - `qqbot:group:groupid` → Group message
26
+ * - `qqbot:channel:channelid` → Channel message
27
+ * - `c2c:openid` → C2C (without qqbot: prefix)
28
+ * - `group:groupid` → Group (without qqbot: prefix)
29
+ * - `channel:channelid` → Channel (without qqbot: prefix)
30
+ * - `openid` → C2C (bare openid, default)
31
+ *
32
+ * @param to - Raw target string.
33
+ * @returns Parsed target with type and id.
34
+ * @throws {Error} When the target format is invalid.
35
+ */
36
+ export function parseTarget(to: string): ParsedTarget {
37
+ const id = to.replace(/^qqbot:/i, "");
38
+
39
+ if (id.startsWith("c2c:")) {
40
+ const userId = id.slice(4);
41
+ if (!userId) {
42
+ throw new Error(`Invalid c2c target format: ${to} - missing user ID`);
43
+ }
44
+ return { type: "c2c", id: userId };
45
+ }
46
+
47
+ if (id.startsWith("group:")) {
48
+ const groupId = id.slice(6);
49
+ if (!groupId) {
50
+ throw new Error(`Invalid group target format: ${to} - missing group ID`);
51
+ }
52
+ return { type: "group", id: groupId };
53
+ }
54
+
55
+ if (id.startsWith("channel:")) {
56
+ const channelId = id.slice(8);
57
+ if (!channelId) {
58
+ throw new Error(`Invalid channel target format: ${to} - missing channel ID`);
59
+ }
60
+ return { type: "channel", id: channelId };
61
+ }
62
+
63
+ if (!id) {
64
+ throw new Error(`Invalid target format: ${to} - empty ID after removing qqbot: prefix`);
65
+ }
66
+
67
+ return { type: "c2c", id };
68
+ }
69
+
70
+ /**
71
+ * Map a parsed target type to a ChatScope for API calls.
72
+ *
73
+ * Channel and DM targets are not C2C/Group scoped and should be handled
74
+ * separately by the caller.
75
+ *
76
+ * @returns `'c2c'` or `'group'`, or `undefined` for channel targets.
77
+ */
78
+ export function targetToChatScope(target: ParsedTarget): "c2c" | "group" | undefined {
79
+ if (target.type === "c2c") {
80
+ return "c2c";
81
+ }
82
+ if (target.type === "group") {
83
+ return "group";
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ /**
89
+ * Normalize a QQ Bot target string into the canonical `qqbot:...` form.
90
+ *
91
+ * Returns `undefined` when the target does not look like a QQ Bot address.
92
+ */
93
+ export function normalizeTarget(target: string): string | undefined {
94
+ const id = target.replace(/^qqbot:/i, "");
95
+ if (id.startsWith("c2c:") || id.startsWith("group:") || id.startsWith("channel:")) {
96
+ return `qqbot:${id}`;
97
+ }
98
+ if (/^[0-9a-fA-F]{32}$/.test(id)) {
99
+ return `qqbot:c2c:${id}`;
100
+ }
101
+ if (/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) {
102
+ return `qqbot:c2c:${id}`;
103
+ }
104
+ return undefined;
105
+ }
106
+
107
+ /**
108
+ * Return true when the string looks like a QQ Bot target ID.
109
+ */
110
+ export function looksLikeQQBotTarget(id: string): boolean {
111
+ if (/^qqbot:(c2c|group|channel):/i.test(id)) {
112
+ return true;
113
+ }
114
+ if (/^(c2c|group|channel):/i.test(id)) {
115
+ return true;
116
+ }
117
+ if (/^[0-9a-fA-F]{32}$/.test(id)) {
118
+ return true;
119
+ }
120
+ return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id);
121
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * QQ Bot single-message text length limits and a naive fallback splitter.
3
+ *
4
+ * The QQ Open Platform caps a single text message at ~5000 characters.
5
+ * When richer markdown-aware chunking is unavailable (e.g. outside an
6
+ * outbound pipeline), this module provides a simple byte-window split
7
+ * so callers always have a safe fallback.
8
+ */
9
+
10
+ /** Maximum text length for a single QQ Bot message. */
11
+ export const TEXT_CHUNK_LIMIT = 5000;
12
+
13
+ /** Text chunker function signature. */
14
+ export type ChunkTextFn = (text: string, limit: number) => string[];
15
+
16
+ /**
17
+ * Naive text chunking fallback.
18
+ *
19
+ * Splits on a fixed character window — does not respect markdown
20
+ * structure. Use this only when the embedder cannot supply a
21
+ * smarter chunker.
22
+ */
23
+ export function chunkText(text: string, limit: number = TEXT_CHUNK_LIMIT): string[] {
24
+ const chunks: string[] = [];
25
+ for (let i = 0; i < text.length; i += limit) {
26
+ chunks.push(text.slice(i, i + limit));
27
+ }
28
+ return chunks.length > 0 ? chunks : [text];
29
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Text parsing utilities — zero external dependency.
3
+ *
4
+ * Contains pure functions for QQ Bot inbound message text processing:
5
+ * internal-marker stripping, ref-index extraction, face-tag rendering,
6
+ * and attachment-summary normalization.
7
+ */
8
+
9
+ import type { RefAttachmentSummary } from "./ref-attachments.js";
10
+
11
+ // ============ Internal markers ============
12
+
13
+ const INTERNAL_MARKER_RE = /\[internal:?\s*[^\]]*\]|\[debug:?\s*[^\]]*\]|\[system:?\s*[^\]]*\]/gi;
14
+
15
+ /** Remove internal markers like `[internal:...]`, `[debug:...]`, `[system:...]`. */
16
+ export function filterInternalMarkers(text: string | undefined | null): string {
17
+ if (!text) {
18
+ return "";
19
+ }
20
+ return text.replace(INTERNAL_MARKER_RE, "").trim();
21
+ }
22
+
23
+ // ============ Ref indices ============
24
+
25
+ /** QQ message type for quote-reply messages. */
26
+ export const MSG_TYPE_QUOTE = 103;
27
+
28
+ /**
29
+ * Parse message_scene.ext to extract refMsgIdx and msgIdx.
30
+ *
31
+ * Supports both ext prefix formats:
32
+ * - `ref_msg_idx=` / `msg_idx=` (platform native format)
33
+ * - `refMsgIdx:` / `msgIdx:` (legacy internal format)
34
+ *
35
+ * When `messageType` equals `MSG_TYPE_QUOTE` (103) and `msgElements` is
36
+ * provided, `msgElements[0].msg_idx` takes precedence over the ext-parsed
37
+ * `refMsgIdx` value — the element-level index is more authoritative for
38
+ * quote messages.
39
+ */
40
+ export function parseRefIndices(
41
+ ext?: string[],
42
+ messageType?: number,
43
+ msgElements?: Array<{ msg_idx?: string }>,
44
+ ): { refMsgIdx?: string; msgIdx?: string } {
45
+ let refMsgIdx: string | undefined;
46
+ let msgIdx: string | undefined;
47
+
48
+ if (ext && ext.length > 0) {
49
+ for (const item of ext) {
50
+ if (typeof item !== "string") {
51
+ continue;
52
+ }
53
+ if (item.startsWith("ref_msg_idx=")) {
54
+ refMsgIdx = item.slice("ref_msg_idx=".length).trim();
55
+ } else if (item.startsWith("msg_idx=")) {
56
+ msgIdx = item.slice("msg_idx=".length).trim();
57
+ } else if (item.startsWith("refMsgIdx:")) {
58
+ refMsgIdx = item.slice("refMsgIdx:".length).trim();
59
+ } else if (item.startsWith("msgIdx:")) {
60
+ msgIdx = item.slice("msgIdx:".length).trim();
61
+ }
62
+ }
63
+ }
64
+
65
+ if (messageType === MSG_TYPE_QUOTE) {
66
+ const refElement = msgElements?.[0];
67
+ if (refElement?.msg_idx) {
68
+ refMsgIdx = refElement.msg_idx;
69
+ }
70
+ }
71
+
72
+ return { refMsgIdx, msgIdx };
73
+ }
74
+
75
+ // ============ Face tags ============
76
+
77
+ const MAX_FACE_EXT_BYTES = 64 * 1024;
78
+
79
+ /** Estimate Base64 decoded byte size. */
80
+ function estimateBase64Size(base64: string): number {
81
+ const len = base64.length;
82
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
83
+ return Math.ceil((len * 3) / 4) - padding;
84
+ }
85
+
86
+ /** Replace QQ face tags with readable text labels. */
87
+ export function parseFaceTags(text: string | undefined | null): string {
88
+ if (!text) {
89
+ return "";
90
+ }
91
+
92
+ return text.replace(/<faceType=\d+,faceId="[^"]*",ext="([^"]*)">/g, (_match, ext: string) => {
93
+ try {
94
+ if (estimateBase64Size(ext) > MAX_FACE_EXT_BYTES) {
95
+ return "[Emoji: unknown emoji]";
96
+ }
97
+ const decoded = Buffer.from(ext, "base64").toString("utf-8");
98
+ const parsed = JSON.parse(decoded);
99
+ const faceName = parsed.text || "unknown emoji";
100
+ return `[Emoji: ${faceName}]`;
101
+ } catch {
102
+ return _match;
103
+ }
104
+ });
105
+ }
106
+
107
+ // ============ Attachment summaries ============
108
+
109
+ /** Lowercase a string safely. */
110
+ function lc(s: string | undefined | null): string {
111
+ return (s ?? "").toLowerCase();
112
+ }
113
+
114
+ /** Build attachment summaries for ref-index caching. */
115
+ export function buildAttachmentSummaries(
116
+ attachments?: Array<{
117
+ content_type: string;
118
+ url: string;
119
+ filename?: string;
120
+ voice_wav_url?: string;
121
+ }>,
122
+ localPaths?: Array<string | null>,
123
+ ): RefAttachmentSummary[] | undefined {
124
+ if (!attachments || attachments.length === 0) {
125
+ return undefined;
126
+ }
127
+
128
+ return attachments.map((att, idx) => {
129
+ const ct = lc(att.content_type);
130
+ let type: RefAttachmentSummary["type"] = "unknown";
131
+ if (ct.startsWith("image/")) {
132
+ type = "image";
133
+ } else if (
134
+ ct === "voice" ||
135
+ ct.startsWith("audio/") ||
136
+ ct.includes("silk") ||
137
+ ct.includes("amr")
138
+ ) {
139
+ type = "voice";
140
+ } else if (ct.startsWith("video/")) {
141
+ type = "video";
142
+ } else if (ct.startsWith("application/") || ct.startsWith("text/")) {
143
+ type = "file";
144
+ }
145
+
146
+ return {
147
+ type,
148
+ filename: att.filename,
149
+ contentType: att.content_type,
150
+ localPath: localPaths?.[idx] ?? undefined,
151
+ };
152
+ });
153
+ }