luckytri 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.github/SECURITY.md +71 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +250 -0
  4. package/README.md +250 -0
  5. package/bin/luckytri.js +107 -0
  6. package/docs/brand/banner.png +0 -0
  7. package/docs/brand/palette.png +0 -0
  8. package/docs/brand/portrait.png +0 -0
  9. package/docs/en/CHANGELOG.md +113 -0
  10. package/docs/en/architecture.md +152 -0
  11. package/docs/en/chat-style.md +62 -0
  12. package/docs/en/connect.md +63 -0
  13. package/docs/en/guide.md +216 -0
  14. package/docs/en/her-life.md +189 -0
  15. package/docs/en/npm-release.md +25 -0
  16. package/docs/en/plugins.md +82 -0
  17. package/docs/en/recovery.md +28 -0
  18. package/docs/en/time.md +71 -0
  19. package/docs/en/webui.md +73 -0
  20. package/docs/zh/CHANGELOG.md +113 -0
  21. package/docs/zh/architecture.md +152 -0
  22. package/docs/zh/chat-style.md +62 -0
  23. package/docs/zh/connect.md +63 -0
  24. package/docs/zh/guide.md +216 -0
  25. package/docs/zh/her-life.md +189 -0
  26. package/docs/zh/npm-release.md +33 -0
  27. package/docs/zh/plugins.md +82 -0
  28. package/docs/zh/recovery.md +28 -0
  29. package/docs/zh/time.md +71 -0
  30. package/docs/zh/webui.md +73 -0
  31. package/package.json +108 -0
  32. package/plugins/sdk/index.d.ts +155 -0
  33. package/plugins/sdk/testing.js +58 -0
  34. package/plugins/weather/index.js +82 -0
  35. package/plugins/weather/luckytri-plugin.json +29 -0
  36. package/public/app/assets/ChatsPage-C-FcRapR.js +3 -0
  37. package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
  38. package/public/app/assets/Empty-CpP5kQHH.js +2 -0
  39. package/public/app/assets/Empty-DmUB2-Bk.css +1 -0
  40. package/public/app/assets/Field-D4gY-INU.js +1 -0
  41. package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
  42. package/public/app/assets/HeartPage-CPy_thQd.js +1 -0
  43. package/public/app/assets/LifePage-BUi5euBF.css +1 -0
  44. package/public/app/assets/LifePage-CxWvwmSf.js +1 -0
  45. package/public/app/assets/MemoryPage-DC4rhQ68.js +1 -0
  46. package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
  47. package/public/app/assets/NaturePage-CTXHCE2D.css +1 -0
  48. package/public/app/assets/NaturePage-IvYw04Zq.js +3 -0
  49. package/public/app/assets/PeoplePage-BmUxkrOU.css +1 -0
  50. package/public/app/assets/PeoplePage-Cqefm9-q.js +1 -0
  51. package/public/app/assets/PluginsPage-DKSaKvXb.js +2 -0
  52. package/public/app/assets/PluginsPage-HyBe5D8w.css +1 -0
  53. package/public/app/assets/SystemPage-CAMPoYqM.css +1 -0
  54. package/public/app/assets/SystemPage-CJmtJkrK.js +1 -0
  55. package/public/app/assets/TimePage-BOms_n4I.css +1 -0
  56. package/public/app/assets/TimePage-Cw44inM4.js +3 -0
  57. package/public/app/assets/formatters-ZmW_xFHw.js +1 -0
  58. package/public/app/assets/index-BheRW-1t.js +4 -0
  59. package/public/app/assets/index-YDz1ree1.css +1 -0
  60. package/public/app/assets/knowledge-DG0e0uKw.js +1 -0
  61. package/public/app/assets/liquid-garden-IMoHBwzc.png +0 -0
  62. package/public/app/assets/luckytri-home-95QKeMtc.png +0 -0
  63. package/public/app/assets/media-BzPDBm7e.js +1 -0
  64. package/public/app/index.html +27 -0
  65. package/public/guide.en.html +1053 -0
  66. package/public/guide.html +893 -0
  67. package/public/plugin-kit/v1/bridge.js +30 -0
  68. package/public/plugin-kit/v1/kit.css +14 -0
  69. package/public/tutorial.en.md +214 -0
  70. package/public/tutorial.md +214 -0
  71. package/scripts/backup.js +311 -0
  72. package/scripts/browser.js +41 -0
  73. package/scripts/launch.js +94 -0
  74. package/scripts/plugin.js +150 -0
  75. package/scripts/proxy-config.js +167 -0
  76. package/scripts/recover.js +26 -0
  77. package/scripts/runtime.js +25 -0
  78. package/scripts/service.js +47 -0
  79. package/scripts/setup.js +50 -0
  80. package/scripts/start-server.js +41 -0
  81. package/scripts/stop.js +36 -0
  82. package/server/app.js +96 -0
  83. package/server/channels/adapters.js +27 -0
  84. package/server/channels/contract.js +57 -0
  85. package/server/channels/hub.js +165 -0
  86. package/server/channels/index.js +25 -0
  87. package/server/channels/onebot/adapter.js +288 -0
  88. package/server/channels/onebot/index.js +336 -0
  89. package/server/channels/onebot/token.js +3 -0
  90. package/server/channels/qqbot/adapter.js +253 -0
  91. package/server/channels/qqbot/api.js +199 -0
  92. package/server/channels/qqbot/credentials.js +11 -0
  93. package/server/channels/qqbot/gateway.js +274 -0
  94. package/server/channels/qqbot/index.js +389 -0
  95. package/server/channels/segments.js +40 -0
  96. package/server/channels/session-key.js +153 -0
  97. package/server/channels/state.js +42 -0
  98. package/server/core/api.js +564 -0
  99. package/server/core/capabilities.js +208 -0
  100. package/server/core/context-builder.js +288 -0
  101. package/server/core/context-compactor.js +454 -0
  102. package/server/core/conversation-cues.js +325 -0
  103. package/server/core/conversation-manager.js +87 -0
  104. package/server/core/events.js +60 -0
  105. package/server/core/feedback.js +8 -0
  106. package/server/core/group-style.js +72 -0
  107. package/server/core/image-preprocessor.js +208 -0
  108. package/server/core/initiative-context.js +66 -0
  109. package/server/core/input-budget.js +32 -0
  110. package/server/core/local-demo.js +98 -0
  111. package/server/core/message-manager.js +118 -0
  112. package/server/core/message-scheduler.js +78 -0
  113. package/server/core/model-json.js +190 -0
  114. package/server/core/model-manager.js +1213 -0
  115. package/server/core/model-presets.js +900 -0
  116. package/server/core/name-call.js +29 -0
  117. package/server/core/net-guard.js +49 -0
  118. package/server/core/network.js +157 -0
  119. package/server/core/orchestrator.js +569 -0
  120. package/server/core/perceivers.js +91 -0
  121. package/server/core/person-name.js +22 -0
  122. package/server/core/persona-manager.js +243 -0
  123. package/server/core/reply-delivery.js +393 -0
  124. package/server/core/reply-target-resolver.js +50 -0
  125. package/server/core/repository.js +293 -0
  126. package/server/core/response-generator.js +50 -0
  127. package/server/core/response-validator.js +508 -0
  128. package/server/core/retired-prompts.js +51 -0
  129. package/server/core/sessions.js +109 -0
  130. package/server/core/speaker-names.js +92 -0
  131. package/server/core/topic-tracker.js +65 -0
  132. package/server/core/turn-processor.js +630 -0
  133. package/server/core/turn.js +236 -0
  134. package/server/core/vision-manager.js +633 -0
  135. package/server/http.js +18 -0
  136. package/server/i18n/decisions.js +206 -0
  137. package/server/i18n/errors.js +497 -0
  138. package/server/i18n/index.js +144 -0
  139. package/server/i18n/labels.js +653 -0
  140. package/server/i18n/models.js +111 -0
  141. package/server/index.js +102 -0
  142. package/server/knowledge/api.js +342 -0
  143. package/server/knowledge/embedding-profile.js +114 -0
  144. package/server/knowledge/index.js +13 -0
  145. package/server/knowledge/manager.js +386 -0
  146. package/server/knowledge/retrieval.js +93 -0
  147. package/server/knowledge/schema.js +154 -0
  148. package/server/knowledge/vector-index.js +90 -0
  149. package/server/mind/affect.js +265 -0
  150. package/server/mind/anticipations.js +507 -0
  151. package/server/mind/api.js +703 -0
  152. package/server/mind/attention.js +200 -0
  153. package/server/mind/bonds.js +558 -0
  154. package/server/mind/budget.js +152 -0
  155. package/server/mind/clock.js +83 -0
  156. package/server/mind/context-selection.js +61 -0
  157. package/server/mind/continuity.js +562 -0
  158. package/server/mind/conversation-origin.js +175 -0
  159. package/server/mind/day-planner.js +324 -0
  160. package/server/mind/days.js +210 -0
  161. package/server/mind/evidence-read.js +45 -0
  162. package/server/mind/evidence.js +148 -0
  163. package/server/mind/faces.js +138 -0
  164. package/server/mind/guard.js +60 -0
  165. package/server/mind/index.js +445 -0
  166. package/server/mind/initiative.js +333 -0
  167. package/server/mind/life/activities.js +21 -0
  168. package/server/mind/life/context.js +309 -0
  169. package/server/mind/life/diary.js +786 -0
  170. package/server/mind/life/growth.js +252 -0
  171. package/server/mind/life/index.js +1049 -0
  172. package/server/mind/life/presence.js +305 -0
  173. package/server/mind/meetings.js +1069 -0
  174. package/server/mind/memory-policy.js +48 -0
  175. package/server/mind/memory.js +888 -0
  176. package/server/mind/nature.js +262 -0
  177. package/server/mind/novelty.js +19 -0
  178. package/server/mind/observations.js +84 -0
  179. package/server/mind/own-day.js +324 -0
  180. package/server/mind/own-voice.js +318 -0
  181. package/server/mind/periods.js +118 -0
  182. package/server/mind/reading.js +120 -0
  183. package/server/mind/salience.js +201 -0
  184. package/server/mind/schema.js +562 -0
  185. package/server/mind/self.js +484 -0
  186. package/server/mind/senses.js +53 -0
  187. package/server/mind/thoughts.js +274 -0
  188. package/server/mind/time/activity-clock.js +196 -0
  189. package/server/mind/time/agenda.js +242 -0
  190. package/server/mind/time/api.js +200 -0
  191. package/server/mind/time/attention.js +34 -0
  192. package/server/mind/time/availability.js +69 -0
  193. package/server/mind/time/commitment-review.js +198 -0
  194. package/server/mind/time/delivery-links.js +130 -0
  195. package/server/mind/time/executor.js +512 -0
  196. package/server/mind/time/experiences.js +128 -0
  197. package/server/mind/time/games.js +562 -0
  198. package/server/mind/time/index.js +739 -0
  199. package/server/mind/time/intent.js +166 -0
  200. package/server/mind/time/kinds.js +171 -0
  201. package/server/mind/time/model-material.js +77 -0
  202. package/server/mind/time/plugin-activity.js +207 -0
  203. package/server/mind/time/presentation.js +51 -0
  204. package/server/mind/time/schedule.js +83 -0
  205. package/server/mind/time/schema.js +84 -0
  206. package/server/mind/time/search.js +383 -0
  207. package/server/mind/time/sharing.js +472 -0
  208. package/server/mind/time/task-links.js +311 -0
  209. package/server/mind/time/tasks.js +587 -0
  210. package/server/mind/time/works.js +432 -0
  211. package/server/mind/traits.js +191 -0
  212. package/server/mind/util.js +110 -0
  213. package/server/mind/view.js +273 -0
  214. package/server/paths.js +102 -0
  215. package/server/plugins/api.js +204 -0
  216. package/server/plugins/host.js +967 -0
  217. package/server/plugins/install.js +295 -0
  218. package/server/plugins/manifest.js +201 -0
  219. package/server/plugins/permissions.js +42 -0
  220. package/server/plugins/runner/guard.mjs +36 -0
  221. package/server/plugins/runner/worker.mjs +250 -0
  222. package/server/plugins/schema.js +91 -0
  223. package/server/plugins/zip.js +112 -0
  224. package/server/startup-lock.js +118 -0
  225. package/server/storage/archive.js +241 -0
  226. package/server/storage/backup-cleanup-worker.js +8 -0
  227. package/server/storage/backup-cleanup.js +414 -0
  228. package/server/storage/backup-lock.js +76 -0
  229. package/server/storage/backup-scheduler.js +131 -0
  230. package/server/storage/store.js +199 -0
  231. package/server/studio/display-names.js +138 -0
  232. package/server/studio/management.js +102 -0
  233. package/server/studio/readiness.js +190 -0
  234. package/server/studio/settings.js +236 -0
  235. package/server/version.js +10 -0
@@ -0,0 +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
+ }
@@ -0,0 +1,40 @@
1
+ // What a list of OneBot-style message segments says: who is mentioned, which
2
+ // message is quoted, and which attachments came along. The OneBot adapter uses
3
+ // it to fill the neutral message; `messageEnvelope` falls back to it for events
4
+ // that were saved before adapters filled those fields themselves.
5
+ const ATTACHMENT_TYPES = new Set([
6
+ "image",
7
+ "mface",
8
+ "market_face",
9
+ "sticker",
10
+ "file",
11
+ "video",
12
+ "record",
13
+ "face",
14
+ ]);
15
+
16
+ export function segmentFacts(segments = []) {
17
+ const list = Array.isArray(segments) ? segments : [];
18
+ return {
19
+ mentions: list
20
+ .filter((s) => String(s?.type || "").toLowerCase() === "at")
21
+ .map((s) => {
22
+ const id = s.data?.qq ?? s.data?.user_id;
23
+ return id == null || id === "" ? "" : String(id);
24
+ })
25
+ .filter(Boolean),
26
+ replyId: String(list.find((s) => s?.type === "reply")?.data?.id || ""),
27
+ attachments: list
28
+ .filter((s) => ATTACHMENT_TYPES.has(s?.type))
29
+ .map((s) => ({
30
+ type: s.type,
31
+ ...s.data,
32
+ // QQ's built-in faces carry their readable name inside raw. Keep it
33
+ // alongside the placeholder so a reaction is not reduced to [表情].
34
+ summary: String(s.data?.summary || s.data?.raw?.faceText || "").slice(
35
+ 0,
36
+ 80,
37
+ ),
38
+ })),
39
+ };
40
+ }
@@ -0,0 +1,153 @@
1
+ const KINDS = new Set(["group", "private"]);
2
+
3
+ export function formatSessionKey({
4
+ channel = "onebot",
5
+ accountId = "_",
6
+ kind,
7
+ nativeId,
8
+ }) {
9
+ if (!KINDS.has(kind) || nativeId == null || String(nativeId) === "")
10
+ throw Error("会话身份不完整");
11
+ return `${channel}:${accountId || "_"}:${kind}:${nativeId}`;
12
+ }
13
+
14
+ export function parseSessionKey(id) {
15
+ const raw = String(id || "");
16
+ const parts = raw.split(":");
17
+ if (parts.length === 2 && KINDS.has(parts[0]) && parts[1])
18
+ return {
19
+ channel: "onebot",
20
+ accountId: "_",
21
+ kind: parts[0],
22
+ nativeId: parts[1],
23
+ legacy: true,
24
+ id: raw,
25
+ };
26
+ if (parts.length >= 4 && KINDS.has(parts[2]) && parts[3])
27
+ return {
28
+ channel: parts[0],
29
+ accountId: parts[1] || "_",
30
+ kind: parts[2],
31
+ nativeId: parts.slice(3).join(":"),
32
+ legacy: false,
33
+ id: raw,
34
+ };
35
+ throw Error("会话 ID 无效");
36
+ }
37
+
38
+ export function sessionKind(id) {
39
+ return parseSessionKey(id).kind;
40
+ }
41
+
42
+ export function sessionNativeId(id) {
43
+ return parseSessionKey(id).nativeId;
44
+ }
45
+
46
+ export function sessionAliases(id) {
47
+ const parsed = parseSessionKey(id);
48
+ // The short `group:<id>` forms are how OneBot rooms were keyed before keys
49
+ // carried a channel; no other channel ever used them.
50
+ if (parsed.channel !== "onebot")
51
+ return [...new Set([id, formatSessionKey(parsed)])];
52
+ return [
53
+ ...new Set([
54
+ id,
55
+ formatSessionKey(parsed),
56
+ `${parsed.kind}:${parsed.nativeId}`,
57
+ formatSessionKey({ ...parsed, accountId: "_" }),
58
+ ]),
59
+ ];
60
+ }
61
+
62
+ export function scopedSessionAliases(db, id) {
63
+ const aliases = sessionAliases(id);
64
+ try {
65
+ const parsed = parseSessionKey(id);
66
+ if (
67
+ parsed.legacy ||
68
+ parsed.channel !== "onebot" ||
69
+ parsed.accountId === "_" ||
70
+ parsed.kind !== "group"
71
+ )
72
+ return aliases;
73
+ const legacy = `${parsed.kind}:${parsed.nativeId}`;
74
+ const accounts = db
75
+ .prepare(
76
+ "SELECT DISTINCT account_id FROM core_events WHERE session_id=? AND account_id IS NOT NULL AND account_id!=''",
77
+ )
78
+ .all(legacy)
79
+ .map((row) => String(row.account_id));
80
+ if (
81
+ accounts.length &&
82
+ accounts.some((account) => account !== parsed.accountId)
83
+ )
84
+ return aliases.filter(
85
+ (alias) =>
86
+ alias !== legacy &&
87
+ alias !== formatSessionKey({ ...parsed, accountId: "_" }),
88
+ );
89
+ } catch {
90
+ /* Keep the broad legacy aliases for malformed or pre-core databases. */
91
+ }
92
+ return aliases;
93
+ }
94
+
95
+ export function isGroupSession(id) {
96
+ try {
97
+ return parseSessionKey(id).kind === "group";
98
+ } catch {
99
+ return String(id).startsWith("group:");
100
+ }
101
+ }
102
+
103
+ export function bindSessionId(db, sessionId) {
104
+ const parsed = parseSessionKey(sessionId);
105
+ const aliases = sessionAliases(sessionId);
106
+ const placeholders = aliases.map(() => "?").join(",");
107
+ const requested = parsed.accountId;
108
+ const keepAccountScope = (id) => {
109
+ // Legacy `group:<id>` rows predate account-qualified channels. Reuse one
110
+ // only for the account that already owns its events; a second bot account
111
+ // gets its own canonical session instead of silently sharing memory.
112
+ if (
113
+ parsed.channel !== "onebot" ||
114
+ parsed.legacy ||
115
+ id !== `${parsed.kind}:${parsed.nativeId}`
116
+ )
117
+ return id;
118
+ const accounts = db
119
+ .prepare(
120
+ "SELECT DISTINCT account_id FROM core_events WHERE session_id=? AND account_id IS NOT NULL AND account_id!=''",
121
+ )
122
+ .all(id)
123
+ .map((row) => String(row.account_id));
124
+ return accounts.length && !accounts.includes(requested)
125
+ ? formatSessionKey(parsed)
126
+ : id;
127
+ };
128
+ const session = db
129
+ .prepare(`SELECT id FROM sessions WHERE id IN (${placeholders}) LIMIT 1`)
130
+ .get(...aliases);
131
+ if (session) return keepAccountScope(session.id);
132
+ const event = db
133
+ .prepare(
134
+ `SELECT session_id AS id FROM core_events WHERE session_id IN (${placeholders}) LIMIT 1`,
135
+ )
136
+ .get(...aliases);
137
+ if (event) return keepAccountScope(event.id);
138
+ const message = db
139
+ .prepare(
140
+ `SELECT session_id AS id FROM messages WHERE session_id IN (${placeholders}) LIMIT 1`,
141
+ )
142
+ .get(...aliases);
143
+ if (message) return keepAccountScope(message.id);
144
+ return parsed.legacy ? parsed.id : formatSessionKey(parsed);
145
+ }
146
+
147
+ export function publicSession(row) {
148
+ try {
149
+ return { ...row, ...parseSessionKey(row.id) };
150
+ } catch {
151
+ return { ...row, channel: "onebot", accountId: "_", nativeId: row.id };
152
+ }
153
+ }
@@ -0,0 +1,42 @@
1
+ // Small durable memory for a channel: which rooms switched proactive messages
2
+ // off, which openid belongs to which person. It lives in the same database as
3
+ // everything else, so backups and recovery carry it along.
4
+ export function channelState(db) {
5
+ db.exec(
6
+ "CREATE TABLE IF NOT EXISTS channel_state (key TEXT PRIMARY KEY, value TEXT NOT NULL, time INTEGER NOT NULL)",
7
+ );
8
+ const read = db.prepare("SELECT value FROM channel_state WHERE key=?");
9
+ const write = db.prepare(
10
+ "INSERT INTO channel_state(key,value,time) VALUES (?,?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value,time=excluded.time",
11
+ );
12
+ const remove = db.prepare("DELETE FROM channel_state WHERE key=?");
13
+ const cache = new Map();
14
+ return {
15
+ get(key, fallback = null) {
16
+ if (cache.has(key)) return cache.get(key) ?? fallback;
17
+ const row = read.get(key);
18
+ const value = row ? row.value : null;
19
+ cache.set(key, value);
20
+ return value ?? fallback;
21
+ },
22
+ set(key, value, now = Date.now()) {
23
+ const text = String(value);
24
+ if (cache.get(key) === text) return false;
25
+ write.run(key, text, now);
26
+ cache.set(key, text);
27
+ return true;
28
+ },
29
+ delete(key) {
30
+ cache.delete(key);
31
+ remove.run(key);
32
+ },
33
+ // Rows whose key starts with `prefix`, for rebuilding in-memory sets.
34
+ list(prefix) {
35
+ return db
36
+ .prepare(
37
+ "SELECT key,value,time FROM channel_state WHERE substr(key,1,?)=?",
38
+ )
39
+ .all(prefix.length, prefix);
40
+ },
41
+ };
42
+ }