luckytri 1.0.4 → 1.0.6

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 (156) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +2 -0
  3. package/README.md +2 -0
  4. package/docs/en/CHANGELOG.md +20 -13
  5. package/docs/en/guide.md +7 -5
  6. package/docs/en/her-life.md +2 -2
  7. package/docs/en/webui.md +1 -1
  8. package/docs/zh/CHANGELOG.md +20 -13
  9. package/docs/zh/guide.md +7 -5
  10. package/docs/zh/her-life.md +2 -2
  11. package/docs/zh/webui.md +1 -1
  12. package/package.json +2 -1
  13. package/public/app/assets/ChatsPage-CFMVozoG.css +1 -0
  14. package/public/app/assets/{ChatsPage-CshdtTzV.js → ChatsPage-DCYMkJ91.js} +2 -2
  15. package/public/app/assets/{Empty-C7yzOBzy.js → Empty-CLyZkxR5.js} +1 -1
  16. package/public/app/assets/{Empty-DmUB2-Bk.css → Empty-DIobYG3x.css} +1 -1
  17. package/public/app/assets/{Field-BjFv4Rfn.js → Field-BpaRwLI_.js} +1 -1
  18. package/public/app/assets/{HeartPage-eqo6ru16.js → HeartPage-BIOMTiwr.js} +1 -1
  19. package/public/app/assets/HeartPage-C-2jvgzF.css +1 -0
  20. package/public/app/assets/{LifePage-CN8GE5NK.js → LifePage-BCgM4JkR.js} +1 -1
  21. package/public/app/assets/LifePage-CG1OHbRK.css +1 -0
  22. package/public/app/assets/MemoryPage-C_Bu4rfb.css +1 -0
  23. package/public/app/assets/{MemoryPage-CCpMN4Wg.js → MemoryPage-vShvRqMt.js} +1 -1
  24. package/public/app/assets/NaturePage-CPZlImT0.css +1 -0
  25. package/public/app/assets/{NaturePage-C0JqdBTR.js → NaturePage-Cy9ptr4G.js} +2 -2
  26. package/public/app/assets/PeoplePage-3RRUITDz.css +1 -0
  27. package/public/app/assets/{PeoplePage-BXGBbO4u.js → PeoplePage-CUZekB2E.js} +1 -1
  28. package/public/app/assets/{PluginsPage-Dksp5AV5.js → PluginsPage-1RM4rmJP.js} +1 -1
  29. package/public/app/assets/{SystemPage-BenIyTvk.css → SystemPage-BI2CB5Ig.css} +1 -1
  30. package/public/app/assets/{SystemPage-Cd7aa8eE.js → SystemPage-BeT5TmIV.js} +1 -1
  31. package/public/app/assets/TimePage-C-guwPk2.css +1 -0
  32. package/public/app/assets/{TimePage-Bs_zImb4.js → TimePage-taTmPMM8.js} +2 -2
  33. package/public/app/assets/{index-BHZcHUMh.css → index-DY5AM0Hz.css} +1 -1
  34. package/public/app/assets/{index-CyRtYxP3.js → index-DdYwC5ZU.js} +3 -3
  35. package/public/app/assets/{knowledge-BJOIyuJo.js → knowledge-DJmfu2KN.js} +1 -1
  36. package/public/app/assets/{media-Bwtx8blz.js → media-BEtnE0Gv.js} +1 -1
  37. package/public/app/assets/{mind-DtTVrW6Z.js → mind-Dtiw0-QK.js} +1 -1
  38. package/public/app/index.html +6 -5
  39. package/public/guide.en.html +11 -3
  40. package/public/guide.html +6 -3
  41. package/public/tutorial.en.md +2 -0
  42. package/public/tutorial.md +2 -0
  43. package/scripts/import-data.js +128 -128
  44. package/scripts/proxy-config.js +167 -167
  45. package/scripts/service-supervisor.js +50 -0
  46. package/scripts/start-server.js +71 -16
  47. package/scripts/update-instance.js +201 -201
  48. package/server/channels/adapters.js +27 -27
  49. package/server/channels/onebot/adapter.js +288 -288
  50. package/server/channels/qqbot/adapter.js +253 -253
  51. package/server/channels/qqbot/api.js +199 -199
  52. package/server/channels/qqbot/credentials.js +11 -11
  53. package/server/channels/qqbot/gateway.js +274 -274
  54. package/server/channels/qqbot/index.js +389 -389
  55. package/server/channels/segments.js +40 -40
  56. package/server/channels/session-key.js +153 -153
  57. package/server/channels/state.js +42 -42
  58. package/server/core/api.js +564 -564
  59. package/server/core/context-builder.js +288 -288
  60. package/server/core/context-compactor.js +454 -454
  61. package/server/core/conversation-cues.js +325 -325
  62. package/server/core/conversation-manager.js +87 -87
  63. package/server/core/feedback.js +8 -8
  64. package/server/core/group-style.js +72 -72
  65. package/server/core/initiative-context.js +66 -66
  66. package/server/core/input-budget.js +32 -32
  67. package/server/core/local-demo.js +98 -98
  68. package/server/core/message-manager.js +118 -118
  69. package/server/core/message-scheduler.js +78 -78
  70. package/server/core/model-json.js +190 -190
  71. package/server/core/model-presets.js +900 -900
  72. package/server/core/name-call.js +29 -29
  73. package/server/core/network.js +157 -157
  74. package/server/core/person-name.js +22 -22
  75. package/server/core/persona-manager.js +2 -1
  76. package/server/core/reply-delivery.js +404 -403
  77. package/server/core/reply-target-resolver.js +50 -50
  78. package/server/core/response-generator.js +50 -50
  79. package/server/core/response-validator.js +14 -2
  80. package/server/core/retired-prompts.js +51 -51
  81. package/server/core/sessions.js +109 -109
  82. package/server/core/speaker-names.js +92 -92
  83. package/server/core/topic-tracker.js +65 -65
  84. package/server/http.js +18 -18
  85. package/server/i18n/decisions.js +209 -206
  86. package/server/i18n/errors.js +4 -0
  87. package/server/i18n/index.js +144 -144
  88. package/server/i18n/models.js +111 -111
  89. package/server/knowledge/api.js +342 -342
  90. package/server/knowledge/embedding-profile.js +114 -114
  91. package/server/knowledge/index.js +13 -13
  92. package/server/knowledge/retrieval.js +93 -93
  93. package/server/knowledge/schema.js +158 -158
  94. package/server/knowledge/vector-index.js +90 -90
  95. package/server/mind/affect.js +265 -265
  96. package/server/mind/attention.js +200 -200
  97. package/server/mind/bonds.js +565 -565
  98. package/server/mind/clock.js +83 -83
  99. package/server/mind/continuity.js +562 -562
  100. package/server/mind/conversation-origin.js +175 -175
  101. package/server/mind/days.js +210 -210
  102. package/server/mind/evidence-read.js +45 -45
  103. package/server/mind/faces.js +373 -373
  104. package/server/mind/guard.js +60 -60
  105. package/server/mind/initiative.js +338 -338
  106. package/server/mind/life/activities.js +21 -21
  107. package/server/mind/life/context.js +330 -323
  108. package/server/mind/life/diary.js +20 -0
  109. package/server/mind/life/growth.js +261 -254
  110. package/server/mind/life/index.js +10 -2
  111. package/server/mind/life/presence.js +305 -305
  112. package/server/mind/meetings.js +1069 -1069
  113. package/server/mind/memory-policy.js +48 -48
  114. package/server/mind/memory.js +888 -888
  115. package/server/mind/nature.js +358 -358
  116. package/server/mind/novelty.js +19 -19
  117. package/server/mind/periods.js +118 -118
  118. package/server/mind/reading.js +120 -120
  119. package/server/mind/relationship-context.js +71 -0
  120. package/server/mind/relationships.js +390 -279
  121. package/server/mind/salience.js +201 -201
  122. package/server/mind/schema.js +567 -567
  123. package/server/mind/self.js +484 -484
  124. package/server/mind/thoughts.js +274 -274
  125. package/server/mind/time/agenda.js +242 -242
  126. package/server/mind/time/api.js +200 -200
  127. package/server/mind/time/attention.js +34 -34
  128. package/server/mind/time/delivery-links.js +130 -130
  129. package/server/mind/time/model-material.js +77 -77
  130. package/server/mind/time/presentation.js +51 -51
  131. package/server/mind/time/schedule.js +83 -83
  132. package/server/mind/time/schema.js +84 -84
  133. package/server/mind/time/search.js +383 -383
  134. package/server/mind/time/sharing.js +472 -472
  135. package/server/mind/time/task-links.js +311 -311
  136. package/server/mind/time/works.js +432 -432
  137. package/server/mind/traits.js +191 -191
  138. package/server/mind/view.js +9 -1
  139. package/server/runtime/installation.js +116 -116
  140. package/server/runtime/update-execution.js +2 -1
  141. package/server/runtime/update-manager.js +140 -140
  142. package/server/storage/data-package.js +298 -298
  143. package/server/storage/data-transfer-api.js +50 -50
  144. package/server/storage/data-transfer-worker.js +18 -18
  145. package/server/storage/data-transfer.js +416 -416
  146. package/server/studio/display-names.js +139 -139
  147. package/server/studio/management.js +102 -102
  148. package/server/studio/updates.js +144 -144
  149. package/server/version.js +10 -10
  150. package/public/app/assets/ChatsPage-DfyPCS9N.css +0 -1
  151. package/public/app/assets/HeartPage-Bft9wZp5.css +0 -1
  152. package/public/app/assets/LifePage-BUi5euBF.css +0 -1
  153. package/public/app/assets/MemoryPage-cZvXfkXb.css +0 -1
  154. package/public/app/assets/NaturePage-CHkpb5NK.css +0 -1
  155. package/public/app/assets/PeoplePage-BTU0H1pM.css +0 -1
  156. package/public/app/assets/TimePage-BOms_n4I.css +0 -1
@@ -1,389 +1,389 @@
1
- import { WebSocket } from "ws";
2
- import { defineChannel } from "../contract.js";
3
- import { parseSessionKey } from "../session-key.js";
4
- import { channelState } from "../state.js";
5
- import { QQBotApi, QQBotError } from "./api.js";
6
- import { qqbotCredentials } from "./credentials.js";
7
- import {
8
- isPlaceholderName,
9
- normalize,
10
- openidOf,
11
- qqbot,
12
- quotedElement,
13
- quotedMessage,
14
- } from "./adapter.js";
15
- import { QQBotGateway } from "./gateway.js";
16
-
17
- // The platform's windows for answering a message without it counting as a
18
- // proactive one. A little margin is kept off both so a late reply is sent as a
19
- // proactive message instead of being refused.
20
- const WINDOW = { group: 5 * 60000 - 15000, private: 60 * 60000 - 60000 };
21
- const REPLIES = { group: 5, private: 4 };
22
- const WAKEUP_EVERY = 30 * 86400000;
23
- const REMEMBER = 2000;
24
-
25
- // Answers that mean the message id cannot be used (any more) as a passive reply.
26
- const EXPIRED = new Set([304103, 40034005, 40034128, 40034024]);
27
- // The person or room has not allowed proactive messages.
28
- const NOT_ALLOWED = new Set([40034105]);
29
- const EXPLAIN = new Map([
30
- [40034100, "主动消息太频繁,平台暂时限制了发送"],
31
- [40034105, "对方或这个群没有开启机器人的主动消息"],
32
- [40034101, "机器人已不在这个群里"],
33
- [40054003, "机器人已不在这个群里"],
34
- [40054002, "机器人在这个群里被禁言"],
35
- [40054007, "消息太长,平台没有接收"],
36
- [40054010, "平台不允许发送链接"],
37
- [40034006, "消息内容没有通过平台审核"],
38
- [40054016, "机器人已下线,请检查机器人状态"],
39
- ]);
40
-
41
- function bounded(map, key, value, limit = REMEMBER) {
42
- map.set(key, value);
43
- while (map.size > limit) map.delete(map.keys().next().value);
44
- }
45
-
46
- // The QQ 开放平台 channel: she connects out to the platform's gateway with an
47
- // AppID and AppSecret, instead of waiting for a OneBot client to connect in.
48
- // Everything above the channel is shared with OneBot.
49
- export function createQqBotChannel(
50
- store,
51
- {
52
- fetch,
53
- WebSocketImpl = WebSocket,
54
- now = Date.now,
55
- apiBase,
56
- tokenUrls,
57
- backoff,
58
- timeoutMs,
59
- env = process.env,
60
- } = {},
61
- ) {
62
- const state = channelState(store.db);
63
- const seen = new Map();
64
- const passive = new Map();
65
- const latest = new Map();
66
- const quotes = new Map();
67
- const botRefs = new Set();
68
- const names = new Map();
69
- let chat = null;
70
- let api = null;
71
- let gateway = null;
72
- let creds = qqbotCredentials(store, env);
73
- let signature = "";
74
- let connection = { state: "idle", error: "" };
75
- let botId = "";
76
- let botName = "";
77
- let connectedAt = null;
78
- let lastEventAt = null;
79
- let lastDisconnectAt = null;
80
- let sawAllGroupMessages = false;
81
- let sawAtOnlyGroupMessages = false;
82
-
83
- const key = (kind, id) => `${kind}:${creds.appId}:${id}`;
84
-
85
- function knownName(person) {
86
- if (names.has(person)) return names.get(person);
87
- let name = "";
88
- try {
89
- const row = store.db
90
- .prepare(
91
- "SELECT json_extract(payload,'$.name') name FROM core_events WHERE role='user' AND json_extract(payload,'$.userId')=? ORDER BY seq DESC LIMIT 20",
92
- )
93
- .all(person)
94
- .find((item) => item.name && !isPlaceholderName(item.name));
95
- name = row?.name || "";
96
- } catch {
97
- /* The core tables may not exist yet. */
98
- }
99
- names.set(person, name);
100
- return name;
101
- }
102
-
103
- function roomOf(type, d) {
104
- if (type.startsWith("GROUP_") && d?.group_openid)
105
- return `qqbot:${creds.appId}:group:${d.group_openid}`;
106
- const openid = String(d?.openid || "");
107
- if (!openid) return "";
108
- const person = state.get(key("person", openid)) || openid;
109
- return `qqbot:${creds.appId}:private:${person}`;
110
- }
111
-
112
- function permission(type, d) {
113
- const room = roomOf(type, d);
114
- if (!room) return;
115
- if (/_(REJECT|DEL_ROBOT|DEL)$/.test(type))
116
- state.set(key("closed", room), type);
117
- else state.delete(key("closed", room));
118
- }
119
-
120
- function inbound(type, d) {
121
- const id = String(d?.id ?? "");
122
- if (!id || seen.has(id)) return;
123
- bounded(seen, id, true);
124
- const person = String(d?.author?.union_openid || "");
125
- const message = normalize(type, d, {
126
- appId: creds.appId,
127
- botId,
128
- botRefs,
129
- knownName,
130
- });
131
- if (!message) return;
132
- if (
133
- type === "GROUP_MESSAGE_CREATE" &&
134
- !(d.mentions || []).some((u) => u?.is_you)
135
- )
136
- sawAllGroupMessages = true;
137
- if (type === "GROUP_AT_MESSAGE_CREATE") sawAtOnlyGroupMessages = true;
138
- const openid = openidOf(type, d);
139
- if (message.kind === "private" && person && person !== openid) {
140
- state.set(key("openid", message.userId), openid);
141
- state.set(key("person", openid), message.userId);
142
- }
143
- if (d.author?.username && !isPlaceholderName(message.name))
144
- names.set(message.userId, message.name);
145
- const entry = {
146
- msgId: id,
147
- session: message.sessionId,
148
- kind: message.kind,
149
- at: now(),
150
- seq: 0,
151
- expired: false,
152
- };
153
- bounded(passive, message.platformId, entry);
154
- if (message.platformId !== id) bounded(passive, id, entry);
155
- latest.set(message.sessionId, entry);
156
- if (message.replyId) {
157
- const element = quotedElement(d, message.replyId);
158
- if (element) bounded(quotes, message.replyId, element);
159
- }
160
- chat?.receive(message);
161
- }
162
-
163
- function onDispatch(type, d) {
164
- lastEventAt = now();
165
- switch (type) {
166
- case "GROUP_AT_MESSAGE_CREATE":
167
- case "GROUP_MESSAGE_CREATE":
168
- case "C2C_MESSAGE_CREATE":
169
- return inbound(type, d);
170
- case "C2C_MSG_REJECT":
171
- case "C2C_MSG_RECEIVE":
172
- case "GROUP_MSG_REJECT":
173
- case "GROUP_MSG_RECEIVE":
174
- case "GROUP_ADD_ROBOT":
175
- case "GROUP_DEL_ROBOT":
176
- case "FRIEND_ADD":
177
- case "FRIEND_DEL":
178
- return permission(type, d);
179
- default:
180
- }
181
- }
182
-
183
- function onState(next) {
184
- if (next.state === "ready") {
185
- botId = String(next.user?.id || botId || "");
186
- botName = String(next.user?.username || botName || "");
187
- connectedAt = now();
188
- connection = { state: "ready", error: "" };
189
- } else if (next.state === "closed") {
190
- lastDisconnectAt = now();
191
- connection = { state: "closed", error: connection.error };
192
- } else if (next.state === "error") {
193
- connection = { state: "error", error: next.error || "" };
194
- if (next.fatal) lastDisconnectAt = now();
195
- } else connection = { state: next.state, error: "" };
196
- }
197
-
198
- function usable(entry, kind) {
199
- return (
200
- !!entry &&
201
- !entry.expired &&
202
- now() - entry.at < WINDOW[kind] &&
203
- entry.seq < REPLIES[kind]
204
- );
205
- }
206
-
207
- function passiveFor(message, kind) {
208
- const direct = passive.get(String(message.platformId || ""));
209
- if (direct?.session === message.sessionId && usable(direct, kind))
210
- return direct;
211
- const recent = latest.get(message.sessionId);
212
- return usable(recent, kind) ? recent : null;
213
- }
214
-
215
- function explain(error) {
216
- if (error instanceof QQBotError && EXPLAIN.has(error.code))
217
- error.message = EXPLAIN.get(error.code);
218
- return error;
219
- }
220
-
221
- async function sendActive(post, route, body, session) {
222
- try {
223
- return await post(body);
224
- } catch (error) {
225
- if (NOT_ALLOWED.has(error?.code)) {
226
- state.set(key("closed", session), "NOT_ALLOWED");
227
- // One recall message per person each cycle is the platform's own
228
- // way back to someone who has stopped hearing from her.
229
- const wakeKey = key("wakeup", route.nativeId);
230
- const last = Number(state.get(wakeKey, 0));
231
- if (route.kind === "private" && now() - last > WAKEUP_EVERY) {
232
- state.set(wakeKey, now());
233
- try {
234
- return await post({ ...body, is_wakeup: true });
235
- } catch (again) {
236
- throw explain(again);
237
- }
238
- }
239
- }
240
- throw explain(error);
241
- }
242
- }
243
-
244
- async function send(message, text) {
245
- if (message.simulated) return { message_id: "sim" };
246
- if (!gateway?.ready || !api) throw new Error("QQ 官方机器人尚未连接");
247
- const route = parseSessionKey(message.sessionId);
248
- if (route.channel !== "qqbot" || route.accountId !== creds.appId)
249
- throw new Error("这个会话不属于当前连接的 QQ 官方机器人");
250
- const to =
251
- route.kind === "group"
252
- ? route.nativeId
253
- : state.get(key("openid", route.nativeId)) || route.nativeId;
254
- const post = (body) =>
255
- route.kind === "group" ? api.sendGroup(to, body) : api.sendUser(to, body);
256
- const body = { msg_type: 0, content: text };
257
- let result = null;
258
- const anchor = passiveFor(message, route.kind);
259
- if (anchor) {
260
- // The sequence number is spent before the request: if the answer never
261
- // comes, the same number can never be sent twice.
262
- anchor.seq += 1;
263
- try {
264
- result = await post({
265
- ...body,
266
- msg_id: anchor.msgId,
267
- msg_seq: anchor.seq,
268
- });
269
- } catch (error) {
270
- if (!EXPIRED.has(error?.code)) throw explain(error);
271
- anchor.expired = true;
272
- }
273
- }
274
- result ||= await sendActive(post, route, body, message.sessionId);
275
- const ref = String(result?.ext_info?.ref_idx || "");
276
- if (ref) {
277
- botRefs.add(ref);
278
- while (botRefs.size > REMEMBER)
279
- botRefs.delete(botRefs.values().next().value);
280
- }
281
- return { message_id: ref || String(result?.id || ""), id: result?.id };
282
- }
283
-
284
- async function fetchQuoted(message) {
285
- const element = quotes.get(String(message.replyId || ""));
286
- return element ? quotedMessage(message, element, { botId, botRefs }) : null;
287
- }
288
-
289
- function canReach(sessionId) {
290
- if (!gateway?.ready) return false;
291
- let route;
292
- try {
293
- route = parseSessionKey(sessionId);
294
- } catch {
295
- return false;
296
- }
297
- if (route.channel !== "qqbot" || route.accountId !== creds.appId)
298
- return false;
299
- if (usable(latest.get(sessionId), route.kind)) return true;
300
- return !state.get(key("closed", sessionId));
301
- }
302
-
303
- function stopConnection() {
304
- gateway?.stop();
305
- gateway = null;
306
- api = null;
307
- signature = "";
308
- connection = { state: "idle", error: "" };
309
- }
310
-
311
- function start() {
312
- creds = qqbotCredentials(store, env);
313
- if (!creds.appId || !creds.secret) {
314
- stopConnection();
315
- connection = { state: "unconfigured", error: "" };
316
- return;
317
- }
318
- const next = `${creds.appId}\n${creds.secret}`;
319
- if (gateway && next === signature) return gateway.start();
320
- stopConnection();
321
- signature = next;
322
- botId = "";
323
- botName = "";
324
- api = new QQBotApi({
325
- appId: creds.appId,
326
- secret: creds.secret,
327
- fetch,
328
- apiBase,
329
- tokenUrls,
330
- now,
331
- timeoutMs,
332
- });
333
- gateway = new QQBotGateway({
334
- api,
335
- onDispatch,
336
- onState,
337
- WebSocketImpl,
338
- now,
339
- backoff,
340
- });
341
- gateway.start();
342
- }
343
-
344
- function status() {
345
- const current = qqbotCredentials(store, env);
346
- return {
347
- type: "qqbot",
348
- online: !!gateway?.ready,
349
- configured: !!(current.appId && current.secret),
350
- appId: current.appId,
351
- secretConfigured: !!current.secret,
352
- appIdFromEnv: current.appIdFromEnv,
353
- secretFromEnv: current.secretFromEnv,
354
- state: connection.state,
355
- error: connection.error,
356
- botName,
357
- connectedAt,
358
- lastEventAt,
359
- lastDisconnectAt,
360
- // What the platform has actually delivered. Without "receive all
361
- // messages" switched on in the platform's console, only messages that
362
- // mention her arrive.
363
- groupMessages: sawAllGroupMessages
364
- ? "all"
365
- : sawAtOnlyGroupMessages
366
- ? "mentions"
367
- : "unknown",
368
- closedRooms: state.list(`closed:${current.appId}:`).length,
369
- adminProtected: !!env.ADMIN_TOKEN,
370
- };
371
- }
372
-
373
- return defineChannel({
374
- type: "qqbot",
375
- capabilities: qqbot.capabilities,
376
- attach(_server, chatSystem) {
377
- chat = chatSystem;
378
- },
379
- start,
380
- stop: stopConnection,
381
- send,
382
- fetchQuoted,
383
- fetchImage: async () => null,
384
- refreshDirectory: async () => 0,
385
- canReach,
386
- status,
387
- close: stopConnection,
388
- });
389
- }
1
+ import { WebSocket } from "ws";
2
+ import { defineChannel } from "../contract.js";
3
+ import { parseSessionKey } from "../session-key.js";
4
+ import { channelState } from "../state.js";
5
+ import { QQBotApi, QQBotError } from "./api.js";
6
+ import { qqbotCredentials } from "./credentials.js";
7
+ import {
8
+ isPlaceholderName,
9
+ normalize,
10
+ openidOf,
11
+ qqbot,
12
+ quotedElement,
13
+ quotedMessage,
14
+ } from "./adapter.js";
15
+ import { QQBotGateway } from "./gateway.js";
16
+
17
+ // The platform's windows for answering a message without it counting as a
18
+ // proactive one. A little margin is kept off both so a late reply is sent as a
19
+ // proactive message instead of being refused.
20
+ const WINDOW = { group: 5 * 60000 - 15000, private: 60 * 60000 - 60000 };
21
+ const REPLIES = { group: 5, private: 4 };
22
+ const WAKEUP_EVERY = 30 * 86400000;
23
+ const REMEMBER = 2000;
24
+
25
+ // Answers that mean the message id cannot be used (any more) as a passive reply.
26
+ const EXPIRED = new Set([304103, 40034005, 40034128, 40034024]);
27
+ // The person or room has not allowed proactive messages.
28
+ const NOT_ALLOWED = new Set([40034105]);
29
+ const EXPLAIN = new Map([
30
+ [40034100, "主动消息太频繁,平台暂时限制了发送"],
31
+ [40034105, "对方或这个群没有开启机器人的主动消息"],
32
+ [40034101, "机器人已不在这个群里"],
33
+ [40054003, "机器人已不在这个群里"],
34
+ [40054002, "机器人在这个群里被禁言"],
35
+ [40054007, "消息太长,平台没有接收"],
36
+ [40054010, "平台不允许发送链接"],
37
+ [40034006, "消息内容没有通过平台审核"],
38
+ [40054016, "机器人已下线,请检查机器人状态"],
39
+ ]);
40
+
41
+ function bounded(map, key, value, limit = REMEMBER) {
42
+ map.set(key, value);
43
+ while (map.size > limit) map.delete(map.keys().next().value);
44
+ }
45
+
46
+ // The QQ 开放平台 channel: she connects out to the platform's gateway with an
47
+ // AppID and AppSecret, instead of waiting for a OneBot client to connect in.
48
+ // Everything above the channel is shared with OneBot.
49
+ export function createQqBotChannel(
50
+ store,
51
+ {
52
+ fetch,
53
+ WebSocketImpl = WebSocket,
54
+ now = Date.now,
55
+ apiBase,
56
+ tokenUrls,
57
+ backoff,
58
+ timeoutMs,
59
+ env = process.env,
60
+ } = {},
61
+ ) {
62
+ const state = channelState(store.db);
63
+ const seen = new Map();
64
+ const passive = new Map();
65
+ const latest = new Map();
66
+ const quotes = new Map();
67
+ const botRefs = new Set();
68
+ const names = new Map();
69
+ let chat = null;
70
+ let api = null;
71
+ let gateway = null;
72
+ let creds = qqbotCredentials(store, env);
73
+ let signature = "";
74
+ let connection = { state: "idle", error: "" };
75
+ let botId = "";
76
+ let botName = "";
77
+ let connectedAt = null;
78
+ let lastEventAt = null;
79
+ let lastDisconnectAt = null;
80
+ let sawAllGroupMessages = false;
81
+ let sawAtOnlyGroupMessages = false;
82
+
83
+ const key = (kind, id) => `${kind}:${creds.appId}:${id}`;
84
+
85
+ function knownName(person) {
86
+ if (names.has(person)) return names.get(person);
87
+ let name = "";
88
+ try {
89
+ const row = store.db
90
+ .prepare(
91
+ "SELECT json_extract(payload,'$.name') name FROM core_events WHERE role='user' AND json_extract(payload,'$.userId')=? ORDER BY seq DESC LIMIT 20",
92
+ )
93
+ .all(person)
94
+ .find((item) => item.name && !isPlaceholderName(item.name));
95
+ name = row?.name || "";
96
+ } catch {
97
+ /* The core tables may not exist yet. */
98
+ }
99
+ names.set(person, name);
100
+ return name;
101
+ }
102
+
103
+ function roomOf(type, d) {
104
+ if (type.startsWith("GROUP_") && d?.group_openid)
105
+ return `qqbot:${creds.appId}:group:${d.group_openid}`;
106
+ const openid = String(d?.openid || "");
107
+ if (!openid) return "";
108
+ const person = state.get(key("person", openid)) || openid;
109
+ return `qqbot:${creds.appId}:private:${person}`;
110
+ }
111
+
112
+ function permission(type, d) {
113
+ const room = roomOf(type, d);
114
+ if (!room) return;
115
+ if (/_(REJECT|DEL_ROBOT|DEL)$/.test(type))
116
+ state.set(key("closed", room), type);
117
+ else state.delete(key("closed", room));
118
+ }
119
+
120
+ function inbound(type, d) {
121
+ const id = String(d?.id ?? "");
122
+ if (!id || seen.has(id)) return;
123
+ bounded(seen, id, true);
124
+ const person = String(d?.author?.union_openid || "");
125
+ const message = normalize(type, d, {
126
+ appId: creds.appId,
127
+ botId,
128
+ botRefs,
129
+ knownName,
130
+ });
131
+ if (!message) return;
132
+ if (
133
+ type === "GROUP_MESSAGE_CREATE" &&
134
+ !(d.mentions || []).some((u) => u?.is_you)
135
+ )
136
+ sawAllGroupMessages = true;
137
+ if (type === "GROUP_AT_MESSAGE_CREATE") sawAtOnlyGroupMessages = true;
138
+ const openid = openidOf(type, d);
139
+ if (message.kind === "private" && person && person !== openid) {
140
+ state.set(key("openid", message.userId), openid);
141
+ state.set(key("person", openid), message.userId);
142
+ }
143
+ if (d.author?.username && !isPlaceholderName(message.name))
144
+ names.set(message.userId, message.name);
145
+ const entry = {
146
+ msgId: id,
147
+ session: message.sessionId,
148
+ kind: message.kind,
149
+ at: now(),
150
+ seq: 0,
151
+ expired: false,
152
+ };
153
+ bounded(passive, message.platformId, entry);
154
+ if (message.platformId !== id) bounded(passive, id, entry);
155
+ latest.set(message.sessionId, entry);
156
+ if (message.replyId) {
157
+ const element = quotedElement(d, message.replyId);
158
+ if (element) bounded(quotes, message.replyId, element);
159
+ }
160
+ chat?.receive(message);
161
+ }
162
+
163
+ function onDispatch(type, d) {
164
+ lastEventAt = now();
165
+ switch (type) {
166
+ case "GROUP_AT_MESSAGE_CREATE":
167
+ case "GROUP_MESSAGE_CREATE":
168
+ case "C2C_MESSAGE_CREATE":
169
+ return inbound(type, d);
170
+ case "C2C_MSG_REJECT":
171
+ case "C2C_MSG_RECEIVE":
172
+ case "GROUP_MSG_REJECT":
173
+ case "GROUP_MSG_RECEIVE":
174
+ case "GROUP_ADD_ROBOT":
175
+ case "GROUP_DEL_ROBOT":
176
+ case "FRIEND_ADD":
177
+ case "FRIEND_DEL":
178
+ return permission(type, d);
179
+ default:
180
+ }
181
+ }
182
+
183
+ function onState(next) {
184
+ if (next.state === "ready") {
185
+ botId = String(next.user?.id || botId || "");
186
+ botName = String(next.user?.username || botName || "");
187
+ connectedAt = now();
188
+ connection = { state: "ready", error: "" };
189
+ } else if (next.state === "closed") {
190
+ lastDisconnectAt = now();
191
+ connection = { state: "closed", error: connection.error };
192
+ } else if (next.state === "error") {
193
+ connection = { state: "error", error: next.error || "" };
194
+ if (next.fatal) lastDisconnectAt = now();
195
+ } else connection = { state: next.state, error: "" };
196
+ }
197
+
198
+ function usable(entry, kind) {
199
+ return (
200
+ !!entry &&
201
+ !entry.expired &&
202
+ now() - entry.at < WINDOW[kind] &&
203
+ entry.seq < REPLIES[kind]
204
+ );
205
+ }
206
+
207
+ function passiveFor(message, kind) {
208
+ const direct = passive.get(String(message.platformId || ""));
209
+ if (direct?.session === message.sessionId && usable(direct, kind))
210
+ return direct;
211
+ const recent = latest.get(message.sessionId);
212
+ return usable(recent, kind) ? recent : null;
213
+ }
214
+
215
+ function explain(error) {
216
+ if (error instanceof QQBotError && EXPLAIN.has(error.code))
217
+ error.message = EXPLAIN.get(error.code);
218
+ return error;
219
+ }
220
+
221
+ async function sendActive(post, route, body, session) {
222
+ try {
223
+ return await post(body);
224
+ } catch (error) {
225
+ if (NOT_ALLOWED.has(error?.code)) {
226
+ state.set(key("closed", session), "NOT_ALLOWED");
227
+ // One recall message per person each cycle is the platform's own
228
+ // way back to someone who has stopped hearing from her.
229
+ const wakeKey = key("wakeup", route.nativeId);
230
+ const last = Number(state.get(wakeKey, 0));
231
+ if (route.kind === "private" && now() - last > WAKEUP_EVERY) {
232
+ state.set(wakeKey, now());
233
+ try {
234
+ return await post({ ...body, is_wakeup: true });
235
+ } catch (again) {
236
+ throw explain(again);
237
+ }
238
+ }
239
+ }
240
+ throw explain(error);
241
+ }
242
+ }
243
+
244
+ async function send(message, text) {
245
+ if (message.simulated) return { message_id: "sim" };
246
+ if (!gateway?.ready || !api) throw new Error("QQ 官方机器人尚未连接");
247
+ const route = parseSessionKey(message.sessionId);
248
+ if (route.channel !== "qqbot" || route.accountId !== creds.appId)
249
+ throw new Error("这个会话不属于当前连接的 QQ 官方机器人");
250
+ const to =
251
+ route.kind === "group"
252
+ ? route.nativeId
253
+ : state.get(key("openid", route.nativeId)) || route.nativeId;
254
+ const post = (body) =>
255
+ route.kind === "group" ? api.sendGroup(to, body) : api.sendUser(to, body);
256
+ const body = { msg_type: 0, content: text };
257
+ let result = null;
258
+ const anchor = passiveFor(message, route.kind);
259
+ if (anchor) {
260
+ // The sequence number is spent before the request: if the answer never
261
+ // comes, the same number can never be sent twice.
262
+ anchor.seq += 1;
263
+ try {
264
+ result = await post({
265
+ ...body,
266
+ msg_id: anchor.msgId,
267
+ msg_seq: anchor.seq,
268
+ });
269
+ } catch (error) {
270
+ if (!EXPIRED.has(error?.code)) throw explain(error);
271
+ anchor.expired = true;
272
+ }
273
+ }
274
+ result ||= await sendActive(post, route, body, message.sessionId);
275
+ const ref = String(result?.ext_info?.ref_idx || "");
276
+ if (ref) {
277
+ botRefs.add(ref);
278
+ while (botRefs.size > REMEMBER)
279
+ botRefs.delete(botRefs.values().next().value);
280
+ }
281
+ return { message_id: ref || String(result?.id || ""), id: result?.id };
282
+ }
283
+
284
+ async function fetchQuoted(message) {
285
+ const element = quotes.get(String(message.replyId || ""));
286
+ return element ? quotedMessage(message, element, { botId, botRefs }) : null;
287
+ }
288
+
289
+ function canReach(sessionId) {
290
+ if (!gateway?.ready) return false;
291
+ let route;
292
+ try {
293
+ route = parseSessionKey(sessionId);
294
+ } catch {
295
+ return false;
296
+ }
297
+ if (route.channel !== "qqbot" || route.accountId !== creds.appId)
298
+ return false;
299
+ if (usable(latest.get(sessionId), route.kind)) return true;
300
+ return !state.get(key("closed", sessionId));
301
+ }
302
+
303
+ function stopConnection() {
304
+ gateway?.stop();
305
+ gateway = null;
306
+ api = null;
307
+ signature = "";
308
+ connection = { state: "idle", error: "" };
309
+ }
310
+
311
+ function start() {
312
+ creds = qqbotCredentials(store, env);
313
+ if (!creds.appId || !creds.secret) {
314
+ stopConnection();
315
+ connection = { state: "unconfigured", error: "" };
316
+ return;
317
+ }
318
+ const next = `${creds.appId}\n${creds.secret}`;
319
+ if (gateway && next === signature) return gateway.start();
320
+ stopConnection();
321
+ signature = next;
322
+ botId = "";
323
+ botName = "";
324
+ api = new QQBotApi({
325
+ appId: creds.appId,
326
+ secret: creds.secret,
327
+ fetch,
328
+ apiBase,
329
+ tokenUrls,
330
+ now,
331
+ timeoutMs,
332
+ });
333
+ gateway = new QQBotGateway({
334
+ api,
335
+ onDispatch,
336
+ onState,
337
+ WebSocketImpl,
338
+ now,
339
+ backoff,
340
+ });
341
+ gateway.start();
342
+ }
343
+
344
+ function status() {
345
+ const current = qqbotCredentials(store, env);
346
+ return {
347
+ type: "qqbot",
348
+ online: !!gateway?.ready,
349
+ configured: !!(current.appId && current.secret),
350
+ appId: current.appId,
351
+ secretConfigured: !!current.secret,
352
+ appIdFromEnv: current.appIdFromEnv,
353
+ secretFromEnv: current.secretFromEnv,
354
+ state: connection.state,
355
+ error: connection.error,
356
+ botName,
357
+ connectedAt,
358
+ lastEventAt,
359
+ lastDisconnectAt,
360
+ // What the platform has actually delivered. Without "receive all
361
+ // messages" switched on in the platform's console, only messages that
362
+ // mention her arrive.
363
+ groupMessages: sawAllGroupMessages
364
+ ? "all"
365
+ : sawAtOnlyGroupMessages
366
+ ? "mentions"
367
+ : "unknown",
368
+ closedRooms: state.list(`closed:${current.appId}:`).length,
369
+ adminProtected: !!env.ADMIN_TOKEN,
370
+ };
371
+ }
372
+
373
+ return defineChannel({
374
+ type: "qqbot",
375
+ capabilities: qqbot.capabilities,
376
+ attach(_server, chatSystem) {
377
+ chat = chatSystem;
378
+ },
379
+ start,
380
+ stop: stopConnection,
381
+ send,
382
+ fetchQuoted,
383
+ fetchImage: async () => null,
384
+ refreshDirectory: async () => 0,
385
+ canReach,
386
+ status,
387
+ close: stopConnection,
388
+ });
389
+ }