@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,190 @@
1
+ /**
2
+ * Quoted-message reference index types and rendering helpers.
3
+ *
4
+ * These types describe the per-message metadata captured for QQ Bot
5
+ * "quote / reply" features. The SDK is the single source of truth so
6
+ * platform consumers (history replay, current-turn rendering, ref-index
7
+ * cache) can share one vocabulary.
8
+ *
9
+ * Zero external dependencies — pure type + string formatting.
10
+ */
11
+
12
+ // ============ Types ============
13
+
14
+ /** Summary stored for one quoted message. */
15
+ export interface RefIndexEntry {
16
+ content: string;
17
+ senderId: string;
18
+ senderName?: string;
19
+ timestamp: number;
20
+ isBot?: boolean;
21
+ attachments?: RefAttachmentSummary[];
22
+ }
23
+
24
+ /** Attachment summary persisted alongside a ref index entry. */
25
+ export interface RefAttachmentSummary {
26
+ type: "image" | "voice" | "video" | "file" | "unknown";
27
+ filename?: string;
28
+ contentType?: string;
29
+ transcript?: string;
30
+ transcriptSource?: "stt" | "asr" | "tts" | "fallback";
31
+ localPath?: string;
32
+ url?: string;
33
+ }
34
+
35
+ /** Canonical attachment shape shared by history entries and ref entries. */
36
+ export type AttachmentSummary = RefAttachmentSummary;
37
+
38
+ /**
39
+ * Rendering mode.
40
+ *
41
+ * - `"inline"`: current turn + history replay. No transcript-source tag.
42
+ * Tags are separated by newlines.
43
+ * - `"ref"`: quoted-message block. Appends `[source: …]` to voice
44
+ * transcripts when `transcriptSource` is present. Tags are separated
45
+ * by spaces so the block fits on one line.
46
+ */
47
+ export type RenderMode = "inline" | "ref";
48
+
49
+ /** Human-readable labels for transcript provenance (prompt contract). */
50
+ export const TRANSCRIPT_SOURCE_LABELS: Record<
51
+ NonNullable<RefAttachmentSummary["transcriptSource"]>,
52
+ string
53
+ > = {
54
+ stt: "local STT",
55
+ asr: "platform ASR",
56
+ tts: "TTS source",
57
+ fallback: "fallback text",
58
+ };
59
+
60
+ /** Options controlling how the tag list is rendered. */
61
+ export interface RenderOptions {
62
+ mode: RenderMode;
63
+ /** Separator between tags. Defaults per mode: inline=`\n`, ref=` `. */
64
+ separator?: string;
65
+ /** Returned when `attachments` is empty/undefined. Defaults to `""`. */
66
+ emptyFallback?: string;
67
+ }
68
+
69
+ // ============ Public API ============
70
+
71
+ /**
72
+ * Render a list of attachments into an LLM-facing tag string.
73
+ *
74
+ * Shared grammar (both modes):
75
+ *
76
+ * ```
77
+ * attachment_with_source := "MEDIA:" SOURCE [voice_suffix]
78
+ * voice_suffix := ' (transcript: "' TEXT '")' [source_suffix]
79
+ * attachment_no_source := "[" TYPE_LABEL [": " FILENAME] [voice_suffix_bare] "]" [source_suffix_bare]
80
+ * voice_suffix_bare := ' (transcript: "' TEXT '")'
81
+ * source_suffix := " [source: " LABEL "]" ← ref mode only
82
+ * source_suffix_bare := " [source: " LABEL "]" ← ref mode only
83
+ * TYPE_LABEL := "image" | "voice" | "video" | "file" | "attachment"
84
+ * ```
85
+ *
86
+ * The **only** mode-dependent decoration is the `source_suffix` (present
87
+ * in `ref`, absent in `inline`). Every other token is identical.
88
+ */
89
+ export function renderAttachmentTags(
90
+ attachments: readonly AttachmentSummary[] | undefined,
91
+ options: RenderOptions,
92
+ ): string {
93
+ if (!attachments?.length) {
94
+ return options.emptyFallback ?? "";
95
+ }
96
+
97
+ const parts: string[] = [];
98
+ for (const att of attachments) {
99
+ parts.push(renderOne(att, options.mode));
100
+ }
101
+
102
+ const separator = options.separator ?? (options.mode === "ref" ? " " : "\n");
103
+ return parts.join(separator);
104
+ }
105
+
106
+ /**
107
+ * Shorthand for `renderAttachmentTags(attachments, { mode: "inline" })`.
108
+ *
109
+ * Kept as the primary entry point for group history / current-turn
110
+ * rendering where the terse inline form is always wanted.
111
+ */
112
+ export function formatAttachmentTags(attachments?: readonly AttachmentSummary[]): string {
113
+ return renderAttachmentTags(attachments, { mode: "inline" });
114
+ }
115
+
116
+ /** Format a ref-index entry into text suitable for model context. */
117
+ export function formatRefEntryForAgent(entry: RefIndexEntry): string {
118
+ const parts: string[] = [];
119
+
120
+ if (entry.content.trim()) {
121
+ parts.push(entry.content);
122
+ }
123
+
124
+ const attachmentTags = renderAttachmentTags(entry.attachments, { mode: "ref" });
125
+ if (attachmentTags) {
126
+ parts.push(attachmentTags);
127
+ }
128
+
129
+ return parts.join(" ") || "[empty message]";
130
+ }
131
+
132
+ // ============ Internal ============
133
+
134
+ /**
135
+ * Render a single attachment.
136
+ *
137
+ * The function is split into two orthogonal concerns:
138
+ * - `renderBody`: the shared "MEDIA:{source}…" or "[type…]" string.
139
+ * - `renderSourceSuffix`: ref-mode-only `" [source: …]"` tail.
140
+ *
141
+ * Both consumers produce the same body; only the suffix differs.
142
+ */
143
+ function renderOne(att: AttachmentSummary, mode: RenderMode): string {
144
+ const body = renderBody(att);
145
+ const suffix = mode === "ref" ? renderSourceSuffix(att) : "";
146
+ return body + suffix;
147
+ }
148
+
149
+ /** Shared, mode-agnostic body of the tag. */
150
+ function renderBody(att: AttachmentSummary): string {
151
+ const source = att.localPath || att.url;
152
+ const voiceSuffix =
153
+ att.type === "voice" && att.transcript ? ` (transcript: "${att.transcript}")` : "";
154
+
155
+ if (source) {
156
+ return `MEDIA:${source}${voiceSuffix}`;
157
+ }
158
+
159
+ const label = labelForType(att.type);
160
+ const namePart = att.filename ? `: ${att.filename}` : "";
161
+ return `[${label}${namePart}${voiceSuffix}]`;
162
+ }
163
+
164
+ /**
165
+ * Ref-mode-only tail that records where a voice transcript came from.
166
+ * Empty string when the attachment isn't a transcribed voice message.
167
+ */
168
+ function renderSourceSuffix(att: AttachmentSummary): string {
169
+ if (att.type !== "voice" || !att.transcript || !att.transcriptSource) {
170
+ return "";
171
+ }
172
+ const label = TRANSCRIPT_SOURCE_LABELS[att.transcriptSource] ?? att.transcriptSource;
173
+ return ` [source: ${label}]`;
174
+ }
175
+
176
+ /** Canonical single-word label for each attachment type. */
177
+ function labelForType(type: AttachmentSummary["type"]): string {
178
+ switch (type) {
179
+ case "image":
180
+ return "image";
181
+ case "voice":
182
+ return "voice";
183
+ case "video":
184
+ return "video";
185
+ case "file":
186
+ return "file";
187
+ default:
188
+ return "attachment";
189
+ }
190
+ }
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Generic JSONL-backed ref-index store.
3
+ *
4
+ * QQ Bot quote / reply messages identify the quoted message via a
5
+ * `refMsgIdx` string. To render the quoted-message preview the bot needs
6
+ * to remember the original sender + content + attachments associated
7
+ * with each `refMsgIdx`. This class implements the storage layer of that
8
+ * cache:
9
+ *
10
+ * - Append-only JSONL on disk (cheap writes, replay on startup).
11
+ * - Bounded in-memory map with TTL eviction.
12
+ * - Compaction when on-disk lines >> in-memory entries.
13
+ *
14
+ * Path resolution is **delegated to the embedder** via the constructor:
15
+ * the SDK itself does not know where the host application wants its data
16
+ * (`~/.openclaw/qqbot/data/ref-index.jsonl`, `/var/lib/qqbot/...`, etc).
17
+ */
18
+
19
+ import fs from "node:fs";
20
+ import { formatErrorMessage } from "./format.js";
21
+ import type { RefIndexEntry } from "./ref-attachments.js";
22
+
23
+ /** Optional logger contract used for diagnostic messages. */
24
+ export interface RefIndexStoreLogger {
25
+ log?: (msg: string) => void;
26
+ error?: (msg: string) => void;
27
+ }
28
+
29
+ /** Configuration for {@link JsonlRefIndexStore}. */
30
+ export interface JsonlRefIndexStoreOptions {
31
+ /** Resolve the on-disk JSONL file path. Called lazily on first I/O. */
32
+ filePath: () => string;
33
+ /** Ensure the parent directory exists. Called before each append. */
34
+ ensureDir: () => void;
35
+ /** Maximum number of in-memory entries before LRU-by-create-time eviction. */
36
+ maxEntries?: number;
37
+ /** Time-to-live for each entry, in milliseconds. */
38
+ ttlMs?: number;
39
+ /** Disk lines / cache entries ratio that triggers compaction. */
40
+ compactThresholdRatio?: number;
41
+ /** Optional logger for diagnostics. */
42
+ logger?: RefIndexStoreLogger;
43
+ }
44
+
45
+ interface RefIndexLine {
46
+ k: string;
47
+ v: RefIndexEntry;
48
+ t: number;
49
+ }
50
+
51
+ const NOOP_LOGGER: Required<RefIndexStoreLogger> = {
52
+ log: () => {},
53
+ error: () => {},
54
+ };
55
+
56
+ const DEFAULT_MAX_ENTRIES = 50_000;
57
+ const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
58
+ const DEFAULT_COMPACT_RATIO = 2;
59
+
60
+ /**
61
+ * Append-only JSONL store for QQ Bot ref-index entries.
62
+ *
63
+ * Each instance owns one file path and one in-memory map. Multi-account
64
+ * deployments should construct one store per logical scope.
65
+ */
66
+ export class JsonlRefIndexStore {
67
+ private readonly options: Required<Omit<JsonlRefIndexStoreOptions, "logger">> & {
68
+ logger: Required<RefIndexStoreLogger>;
69
+ };
70
+
71
+ private cache: Map<string, RefIndexEntry & { _createdAt: number }> | null = null;
72
+ private totalLinesOnDisk = 0;
73
+
74
+ constructor(options: JsonlRefIndexStoreOptions) {
75
+ this.options = {
76
+ filePath: options.filePath,
77
+ ensureDir: options.ensureDir,
78
+ maxEntries: options.maxEntries ?? DEFAULT_MAX_ENTRIES,
79
+ ttlMs: options.ttlMs ?? DEFAULT_TTL_MS,
80
+ compactThresholdRatio: options.compactThresholdRatio ?? DEFAULT_COMPACT_RATIO,
81
+ logger: {
82
+ log: options.logger?.log ?? NOOP_LOGGER.log,
83
+ error: options.logger?.error ?? NOOP_LOGGER.error,
84
+ },
85
+ };
86
+ }
87
+
88
+ /** Persist a refIdx mapping for one message. */
89
+ set(refIdx: string, entry: RefIndexEntry): void {
90
+ const store = this.loadFromFile();
91
+ this.evictIfNeeded();
92
+ const now = Date.now();
93
+ store.set(refIdx, { ...entry, _createdAt: now });
94
+ this.appendLine({
95
+ k: refIdx,
96
+ v: {
97
+ content: entry.content,
98
+ senderId: entry.senderId,
99
+ senderName: entry.senderName,
100
+ timestamp: entry.timestamp,
101
+ isBot: entry.isBot,
102
+ attachments: entry.attachments,
103
+ },
104
+ t: now,
105
+ });
106
+ if (this.shouldCompact()) {
107
+ this.compactFile();
108
+ }
109
+ }
110
+
111
+ /** Look up one quoted message by refIdx. */
112
+ get(refIdx: string): RefIndexEntry | null {
113
+ const store = this.loadFromFile();
114
+ const entry = store.get(refIdx);
115
+ if (!entry) {
116
+ return null;
117
+ }
118
+ if (Date.now() - entry._createdAt > this.options.ttlMs) {
119
+ store.delete(refIdx);
120
+ return null;
121
+ }
122
+ return {
123
+ content: entry.content,
124
+ senderId: entry.senderId,
125
+ senderName: entry.senderName,
126
+ timestamp: entry.timestamp,
127
+ isBot: entry.isBot,
128
+ attachments: entry.attachments,
129
+ };
130
+ }
131
+
132
+ /** Compact the store before process exit when needed. */
133
+ flush(): void {
134
+ if (this.cache && this.shouldCompact()) {
135
+ this.compactFile();
136
+ }
137
+ }
138
+
139
+ /** Return diagnostic stats. */
140
+ getStats(): { size: number; maxEntries: number; totalLinesOnDisk: number; filePath: string } {
141
+ const store = this.loadFromFile();
142
+ return {
143
+ size: store.size,
144
+ maxEntries: this.options.maxEntries,
145
+ totalLinesOnDisk: this.totalLinesOnDisk,
146
+ filePath: this.options.filePath(),
147
+ };
148
+ }
149
+
150
+ // ============ Internal ============
151
+
152
+ private loadFromFile(): Map<string, RefIndexEntry & { _createdAt: number }> {
153
+ if (this.cache !== null) {
154
+ return this.cache;
155
+ }
156
+ this.cache = new Map();
157
+ this.totalLinesOnDisk = 0;
158
+
159
+ try {
160
+ const file = this.options.filePath();
161
+ if (!fs.existsSync(file)) {
162
+ return this.cache;
163
+ }
164
+ const raw = fs.readFileSync(file, "utf-8");
165
+ const lines = raw.split("\n");
166
+ const now = Date.now();
167
+ let expired = 0;
168
+
169
+ for (const line of lines) {
170
+ const trimmed = line.trim();
171
+ if (!trimmed) {
172
+ continue;
173
+ }
174
+ this.totalLinesOnDisk++;
175
+ try {
176
+ const entry = JSON.parse(trimmed) as RefIndexLine;
177
+ if (!entry.k || !entry.v || !entry.t) {
178
+ continue;
179
+ }
180
+ if (now - entry.t > this.options.ttlMs) {
181
+ expired++;
182
+ continue;
183
+ }
184
+ this.cache.set(entry.k, { ...entry.v, _createdAt: entry.t });
185
+ } catch {
186
+ // Skip malformed lines; they will be dropped by the next compaction.
187
+ }
188
+ }
189
+ this.options.logger.log(
190
+ `[ref-index-store] Loaded ${this.cache.size} entries from ${this.totalLinesOnDisk} lines (${expired} expired)`,
191
+ );
192
+ if (this.shouldCompact()) {
193
+ this.compactFile();
194
+ }
195
+ } catch (err) {
196
+ this.options.logger.error(`[ref-index-store] Failed to load: ${formatErrorMessage(err)}`);
197
+ this.cache = new Map();
198
+ }
199
+ return this.cache;
200
+ }
201
+
202
+ private appendLine(line: RefIndexLine): void {
203
+ try {
204
+ this.options.ensureDir();
205
+ fs.appendFileSync(this.options.filePath(), JSON.stringify(line) + "\n", "utf-8");
206
+ this.totalLinesOnDisk++;
207
+ } catch (err) {
208
+ this.options.logger.error(`[ref-index-store] Failed to append: ${formatErrorMessage(err)}`);
209
+ }
210
+ }
211
+
212
+ private shouldCompact(): boolean {
213
+ if (!this.cache) {
214
+ return false;
215
+ }
216
+ return (
217
+ this.totalLinesOnDisk > this.cache.size * this.options.compactThresholdRatio &&
218
+ this.totalLinesOnDisk > 1000
219
+ );
220
+ }
221
+
222
+ private compactFile(): void {
223
+ if (!this.cache) {
224
+ return;
225
+ }
226
+ const before = this.totalLinesOnDisk;
227
+ try {
228
+ this.options.ensureDir();
229
+ const file = this.options.filePath();
230
+ const tmpPath = file + ".tmp";
231
+ const lines: string[] = [];
232
+ for (const [key, entry] of this.cache) {
233
+ lines.push(
234
+ JSON.stringify({
235
+ k: key,
236
+ v: {
237
+ content: entry.content,
238
+ senderId: entry.senderId,
239
+ senderName: entry.senderName,
240
+ timestamp: entry.timestamp,
241
+ isBot: entry.isBot,
242
+ attachments: entry.attachments,
243
+ },
244
+ t: entry._createdAt,
245
+ }),
246
+ );
247
+ }
248
+ fs.writeFileSync(tmpPath, lines.join("\n") + "\n", "utf-8");
249
+ fs.renameSync(tmpPath, file);
250
+ this.totalLinesOnDisk = this.cache.size;
251
+ this.options.logger.log(
252
+ `[ref-index-store] Compacted: ${before} lines → ${this.totalLinesOnDisk} lines`,
253
+ );
254
+ } catch (err) {
255
+ this.options.logger.error(`[ref-index-store] Compact failed: ${formatErrorMessage(err)}`);
256
+ }
257
+ }
258
+
259
+ private evictIfNeeded(): void {
260
+ if (!this.cache || this.cache.size < this.options.maxEntries) {
261
+ return;
262
+ }
263
+ const now = Date.now();
264
+ for (const [key, entry] of this.cache) {
265
+ if (now - entry._createdAt > this.options.ttlMs) {
266
+ this.cache.delete(key);
267
+ }
268
+ }
269
+ if (this.cache.size >= this.options.maxEntries) {
270
+ const entries = [...this.cache.entries()];
271
+ entries.sort((a, b) => a[1]._createdAt - b[1]._createdAt);
272
+ const toRemove = entries.slice(0, this.cache.size - this.options.maxEntries + 1000);
273
+ for (const [key] of toRemove) {
274
+ this.cache.delete(key);
275
+ }
276
+ this.options.logger.log(`[ref-index-store] Evicted ${toRemove.length} oldest entries`);
277
+ }
278
+ }
279
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Passive reply limiter — enforce per-message reply count and TTL limits.
3
+ *
4
+ * QQ Bot restricts how many passive replies can be sent in response to a
5
+ * single inbound message (4 per hour by default). This module tracks reply
6
+ * counts and determines whether the next reply should be passive or
7
+ * fall back to proactive mode.
8
+ *
9
+ * The module is a **class** with zero I/O dependencies, fully supporting
10
+ * multi-account concurrent operation via separate instances.
11
+ */
12
+
13
+ /** Configuration for the reply limiter. */
14
+ export interface ReplyLimiterConfig {
15
+ /** Maximum passive replies per message. Defaults to 4. */
16
+ limit?: number;
17
+ /** TTL in milliseconds for the passive reply window. Defaults to 1 hour. */
18
+ ttlMs?: number;
19
+ /** Maximum number of tracked messages before eviction. Defaults to 10000. */
20
+ maxTrackedMessages?: number;
21
+ }
22
+
23
+ /** Result of a passive-reply limit check. */
24
+ export interface ReplyLimitResult {
25
+ /** Whether a passive reply is still allowed. */
26
+ allowed: boolean;
27
+ /** Number of remaining passive replies. */
28
+ remaining: number;
29
+ /** Whether the caller should fall back to proactive mode. */
30
+ shouldFallbackToProactive: boolean;
31
+ /** Reason for the fallback. */
32
+ fallbackReason?: "expired" | "limit_exceeded";
33
+ /** Human-readable diagnostic message. */
34
+ message?: string;
35
+ }
36
+
37
+ interface ReplyRecord {
38
+ count: number;
39
+ firstReplyAt: number;
40
+ }
41
+
42
+ const DEFAULT_LIMIT = 4;
43
+ const DEFAULT_TTL_MS = 60 * 60 * 1000;
44
+ const DEFAULT_MAX_TRACKED = 10_000;
45
+
46
+ /**
47
+ * Per-account reply limiter with automatic eviction.
48
+ *
49
+ * Usage:
50
+ * ```ts
51
+ * const limiter = new ReplyLimiter({ limit: 4, ttlMs: 3600000 });
52
+ * const check = limiter.checkLimit(messageId);
53
+ * if (check.allowed) {
54
+ * await sendPassiveReply(...);
55
+ * limiter.record(messageId);
56
+ * } else if (check.shouldFallbackToProactive) {
57
+ * await sendProactiveMessage(...);
58
+ * }
59
+ * ```
60
+ */
61
+ export class ReplyLimiter {
62
+ private readonly limit: number;
63
+ private readonly ttlMs: number;
64
+ private readonly maxTracked: number;
65
+ private readonly tracker = new Map<string, ReplyRecord>();
66
+
67
+ constructor(config?: ReplyLimiterConfig) {
68
+ this.limit = config?.limit ?? DEFAULT_LIMIT;
69
+ this.ttlMs = config?.ttlMs ?? DEFAULT_TTL_MS;
70
+ this.maxTracked = config?.maxTrackedMessages ?? DEFAULT_MAX_TRACKED;
71
+ }
72
+
73
+ /** Check whether a passive reply is allowed for the given message. */
74
+ checkLimit(messageId: string): ReplyLimitResult {
75
+ const now = Date.now();
76
+ this.evictIfNeeded(now);
77
+
78
+ const record = this.tracker.get(messageId);
79
+
80
+ if (!record) {
81
+ return {
82
+ allowed: true,
83
+ remaining: this.limit,
84
+ shouldFallbackToProactive: false,
85
+ };
86
+ }
87
+
88
+ if (now - record.firstReplyAt > this.ttlMs) {
89
+ return {
90
+ allowed: false,
91
+ remaining: 0,
92
+ shouldFallbackToProactive: true,
93
+ fallbackReason: "expired",
94
+ message: `Message is older than ${this.ttlMs / (60 * 60 * 1000)}h; sending as a proactive message instead`,
95
+ };
96
+ }
97
+
98
+ const remaining = this.limit - record.count;
99
+ if (remaining <= 0) {
100
+ return {
101
+ allowed: false,
102
+ remaining: 0,
103
+ shouldFallbackToProactive: true,
104
+ fallbackReason: "limit_exceeded",
105
+ message: `Passive reply limit reached (${this.limit} per hour); sending proactively instead`,
106
+ };
107
+ }
108
+
109
+ return {
110
+ allowed: true,
111
+ remaining,
112
+ shouldFallbackToProactive: false,
113
+ };
114
+ }
115
+
116
+ /** Record one passive reply against a message. */
117
+ record(messageId: string): void {
118
+ const now = Date.now();
119
+ const existing = this.tracker.get(messageId);
120
+
121
+ if (!existing) {
122
+ this.tracker.set(messageId, { count: 1, firstReplyAt: now });
123
+ } else if (now - existing.firstReplyAt > this.ttlMs) {
124
+ this.tracker.set(messageId, { count: 1, firstReplyAt: now });
125
+ } else {
126
+ existing.count++;
127
+ }
128
+ }
129
+
130
+ /** Return diagnostic stats. */
131
+ getStats(): { trackedMessages: number; totalReplies: number } {
132
+ let totalReplies = 0;
133
+ for (const record of this.tracker.values()) {
134
+ totalReplies += record.count;
135
+ }
136
+ return { trackedMessages: this.tracker.size, totalReplies };
137
+ }
138
+
139
+ /** Return limiter configuration. */
140
+ getConfig(): { limit: number; ttlMs: number; ttlHours: number } {
141
+ return {
142
+ limit: this.limit,
143
+ ttlMs: this.ttlMs,
144
+ ttlHours: this.ttlMs / (60 * 60 * 1000),
145
+ };
146
+ }
147
+
148
+ /** Clear all tracked records. */
149
+ clear(): void {
150
+ this.tracker.clear();
151
+ }
152
+
153
+ /** Opportunistically evict expired records to keep the tracker bounded. */
154
+ private evictIfNeeded(now: number): void {
155
+ if (this.tracker.size <= this.maxTracked) {
156
+ return;
157
+ }
158
+ for (const [id, rec] of this.tracker) {
159
+ if (now - rec.firstReplyAt > this.ttlMs) {
160
+ this.tracker.delete(id);
161
+ }
162
+ }
163
+ }
164
+ }