dsh-wechat-access 0.0.0-stage → 0.0.2

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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +675 -0
  3. package/README.md +278 -2
  4. package/cordis.patch.yml +5 -0
  5. package/examples/config.example.json +98 -0
  6. package/index.mjs +123 -0
  7. package/lib/access.mjs +131 -0
  8. package/lib/anysearch.mjs +143 -0
  9. package/lib/capabilities.mjs +312 -0
  10. package/lib/client.js +2532 -0
  11. package/lib/config.mjs +509 -0
  12. package/lib/emotion-store.mjs +352 -0
  13. package/lib/emotion.mjs +428 -0
  14. package/lib/endocrine/LICENSE +21 -0
  15. package/lib/endocrine/README.md +39 -0
  16. package/lib/endocrine/diseases.js +791 -0
  17. package/lib/endocrine/engine.mjs +131 -0
  18. package/lib/endocrine/store.mjs +253 -0
  19. package/lib/endocrine/upstream.mjs +1230 -0
  20. package/lib/group-gate.mjs +305 -0
  21. package/lib/imagegen.mjs +360 -0
  22. package/lib/lock.mjs +204 -0
  23. package/lib/meme-classify.mjs +190 -0
  24. package/lib/memes.mjs +442 -0
  25. package/lib/memory.mjs +437 -0
  26. package/lib/normalize.mjs +230 -0
  27. package/lib/parser.mjs +602 -0
  28. package/lib/reply-settled.mjs +130 -0
  29. package/lib/runtime.mjs +3367 -0
  30. package/lib/startup.mjs +70 -0
  31. package/lib/steam-binding.mjs +144 -0
  32. package/lib/steam.mjs +334 -0
  33. package/lib/store.mjs +259 -0
  34. package/lib/thoughts.mjs +149 -0
  35. package/lib/time-context.mjs +182 -0
  36. package/lib/tools.mjs +583 -0
  37. package/lib/ui.mjs +997 -0
  38. package/lib/util.mjs +489 -0
  39. package/lib/virtual-life-generate.mjs +421 -0
  40. package/lib/virtual-life.mjs +971 -0
  41. package/lib/weather.mjs +172 -0
  42. package/lib/wechat-client.mjs +476 -0
  43. package/lib/wechat-events.mjs +269 -0
  44. package/locale/zh.json +6 -0
  45. package/package.json +77 -4
package/lib/memes.mjs ADDED
@@ -0,0 +1,442 @@
1
+ /**
2
+ * Sticker (meme) library: storage, retrieval and selection.
3
+ *
4
+ * Distilled from astrbot_plugin_meme_manager and astrbot_plugin_stealer, both of
5
+ * which are Python. What survives the port is the part that actually earns its
6
+ * keep: keep a folder of images, know what each one means, and pick a fitting one
7
+ * quickly. What is deliberately left behind is the WebUI back office, the image-host
8
+ * syncing and faiss -- the first is a second frontend nobody asked for here, the
9
+ * second has nothing to do with QQ, and the third has no Node equivalent worth a
10
+ * native dependency.
11
+ *
12
+ * Retrieval is BM25 over the text the library already holds (tags, emotions,
13
+ * description). That replaces faiss cosine search: it needs no embedding service,
14
+ * costs nothing per query, and for a few thousand stickers with hand-written or
15
+ * VLM-written labels it ranks better than embeddings would, because the labels are
16
+ * exactly the vocabulary a message is likely to share.
17
+ */
18
+ import { createHash } from 'node:crypto';
19
+ import {mkdir, readFile, writeFile, readdir, stat, unlink, copyFile, rename, rm } from 'node:fs/promises';
20
+ import {join, extname, basename, resolve, dirname, sep } from 'node:path';
21
+
22
+ const INDEX_VERSION = 1;
23
+
24
+ /** Extensions accepted when importing a folder. */
25
+ const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp']);
26
+
27
+ const MEDIA_BY_EXTENSION = {
28
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
29
+ '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp',
30
+ };
31
+
32
+ /**
33
+ * Read pixel dimensions from an image header.
34
+ *
35
+ * Used to reject things that are not stickers: a 20x20 emoji or a 4000x3000 photo
36
+ * both make a poor addition to a sticker library. Handles the four formats QQ
37
+ * actually delivers; returns null rather than guessing when the bytes do not match
38
+ * a known container.
39
+ */
40
+ export function imageSize(bytes) {
41
+ if (!bytes || bytes.length < 24) return null;
42
+ // PNG: IHDR is always the first chunk.
43
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
44
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), mediaType: 'image/png' };
45
+ }
46
+ // GIF: logical screen descriptor.
47
+ if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) {
48
+ return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8), mediaType: 'image/gif' };
49
+ }
50
+ // WEBP: VP8 / VP8L / VP8X each store the size differently.
51
+ if (bytes.slice(0, 4).toString('ascii') === 'RIFF' && bytes.slice(8, 12).toString('ascii') === 'WEBP') {
52
+ const kind = bytes.slice(12, 16).toString('ascii');
53
+ if (kind === 'VP8 ') return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff, mediaType: 'image/webp' };
54
+ if (kind === 'VP8L') {
55
+ const bits = bytes.readUInt32LE(21);
56
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1, mediaType: 'image/webp' };
57
+ }
58
+ if (kind === 'VP8X') {
59
+ return { width: (bytes.readUIntLE(24, 3)) + 1, height: (bytes.readUIntLE(27, 3)) + 1, mediaType: 'image/webp' };
60
+ }
61
+ return null;
62
+ }
63
+ // JPEG: walk the marker chain to the SOF segment.
64
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) {
65
+ let offset = 2;
66
+ while (offset + 9 < bytes.length) {
67
+ if (bytes[offset] !== 0xff) { offset++; continue; }
68
+ const marker = bytes[offset + 1];
69
+ const length = bytes.readUInt16BE(offset + 2);
70
+ // SOF0..SOF15 minus the non-frame markers.
71
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
72
+ return { width: bytes.readUInt16BE(offset + 7), height: bytes.readUInt16BE(offset + 5), mediaType: 'image/jpeg' };
73
+ }
74
+ offset += 2 + length;
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+
80
+ /**
81
+ * Tokenise text for BM25.
82
+ *
83
+ * Latin runs become whole words; CJK runs become overlapping bigrams, which is the
84
+ * cheapest scheme that still matches "好开心" against "开心" without a dictionary.
85
+ */
86
+ export function tokenize(text) {
87
+ const out = [];
88
+ const source = String(text ?? '').toLowerCase();
89
+ for (const match of source.matchAll(/[a-z0-9]+|[\u4e00-\u9fff]+/g)) {
90
+ const run = match[0];
91
+ if (/^[a-z0-9]+$/.test(run)) { out.push(run); continue; }
92
+ if (run.length === 1) { out.push(run); continue; }
93
+ for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2));
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /**
99
+ * BM25 ranking over an in-memory document set.
100
+ *
101
+ * k1/b are the usual defaults. Documents are the library entries' searchable text;
102
+ * the corpus statistics are recomputed per query because the library is small and
103
+ * changes rarely, and a stale index is a worse bug than a few microseconds.
104
+ */
105
+ export function bm25(queryTokens, documents, { k1 = 1.5, b = 0.75 } = {}) {
106
+ const N = documents.length;
107
+ if (N === 0 || queryTokens.length === 0) return documents.map(() => 0);
108
+ const avgLength = documents.reduce((sum, d) => sum + d.tokens.length, 0) / N || 1;
109
+ const df = new Map();
110
+ for (const doc of documents) {
111
+ for (const term of new Set(doc.tokens)) df.set(term, (df.get(term) ?? 0) + 1);
112
+ }
113
+ const scores = new Array(N).fill(0);
114
+ for (const term of new Set(queryTokens)) {
115
+ const freq = df.get(term);
116
+ if (!freq) continue;
117
+ const idf = Math.log(1 + (N - freq + 0.5) / (freq + 0.5));
118
+ for (let i = 0; i < N; i++) {
119
+ const doc = documents[i];
120
+ const tf = doc.terms.get(term) ?? 0;
121
+ if (tf === 0) continue;
122
+ const norm = tf * (k1 + 1) / (tf + k1 * (1 - b + b * (doc.tokens.length / avgLength)));
123
+ scores[i] += idf * norm;
124
+ }
125
+ }
126
+ return scores;
127
+ }
128
+
129
+ /** Deterministic id from content, so re-importing the same file cannot duplicate it. */
130
+ function contentId(buffer) {
131
+ return createHash('sha256').update(buffer).digest('hex');
132
+ }
133
+
134
+ export class MemeLibrary {
135
+ constructor({ dataDir, maxEntries = 5000, minPixels = 48, maxPixels = 4096, logger = console } = {}) {
136
+ this.root = join(dataDir, 'memes');
137
+ this.imagesDir = join(this.root, 'images');
138
+ this.pendingDir = join(this.root, 'pending');
139
+ this.indexPath = join(this.root, 'index.json');
140
+ this.maxEntries = maxEntries;
141
+ this.minPixels = minPixels;
142
+ this.maxPixels = maxPixels;
143
+ this.logger = logger;
144
+ this.entries = [];
145
+ this.pending = [];
146
+ this.loaded = false;
147
+ this.writeChain = Promise.resolve();
148
+ }
149
+
150
+ async init() {
151
+ if (this.loaded) return this;
152
+ await mkdir(this.imagesDir, { recursive: true });
153
+ await mkdir(this.pendingDir, { recursive: true });
154
+ try {
155
+ const raw = JSON.parse(await readFile(this.indexPath, 'utf8'));
156
+ if (raw?.version === INDEX_VERSION) {
157
+ this.entries = Array.isArray(raw.entries) ? raw.entries : [];
158
+ this.pending = Array.isArray(raw.pending) ? raw.pending : [];
159
+ }
160
+ } catch { /* a missing or corrupt index starts an empty library */ }
161
+ this.loaded = true;
162
+ return this;
163
+ }
164
+
165
+ /** Serialise writes: two concurrent imports must not interleave into one file. */
166
+ #save() {
167
+ this.writeChain = this.writeChain.then(async () => {
168
+ const payload = JSON.stringify({ version: INDEX_VERSION, entries: this.entries, pending: this.pending }, null, 2);
169
+ // 原子写:writeFile 先截断再写,进程中途被杀会留下半截 JSON,
170
+ // 下次 init 解析失败后按空库启动 —— 图片文件还在,索引不认。
171
+ const tmp = `${this.indexPath}.${Date.now()}.tmp`;
172
+ try {
173
+ await writeFile(tmp, payload + '\n');
174
+ await rename(tmp, this.indexPath);
175
+ } catch (error) {
176
+ try { await rm(tmp, { force: true }); } catch {}
177
+ throw error;
178
+ }
179
+ }).catch((error) => { this.logger.warn?.('表情包索引写入失败:' + error.message); });
180
+ return this.writeChain;
181
+ }
182
+
183
+ stats() {
184
+ const byEmotion = {};
185
+ for (const entry of this.entries) {
186
+ for (const emotion of entry.emotions ?? []) byEmotion[emotion] = (byEmotion[emotion] ?? 0) + 1;
187
+ }
188
+ return {
189
+ total: this.entries.length,
190
+ pending: this.pending.length,
191
+ classified: this.entries.filter((e) => e.classifiedAt).length,
192
+ unclassified: this.entries.filter((e) => !e.classifiedAt).length,
193
+ byEmotion,
194
+ root: this.root,
195
+ };
196
+ }
197
+
198
+ /** Whether these bytes are worth keeping as a sticker. */
199
+ #accept(bytes) {
200
+ const size = imageSize(bytes);
201
+ if (!size) return { ok: false, reason: '无法识别图片格式' };
202
+ const { width, height } = size;
203
+ if (width < this.minPixels || height < this.minPixels) {
204
+ return { ok: false, reason: `图片太小(${width}x${height})` };
205
+ }
206
+ if (width > this.maxPixels || height > this.maxPixels) {
207
+ return { ok: false, reason: `图片太大(${width}x${height})` };
208
+ }
209
+ // A sticker is roughly square; a 4000x400 banner is not one.
210
+ const ratio = width / height;
211
+ if (ratio > 3 || ratio < 1 / 3) return { ok: false, reason: `长宽比不合适(${width}x${height})` };
212
+ return { ok: true, size };
213
+ }
214
+
215
+ /**
216
+ * Add one image from bytes.
217
+ *
218
+ * \`source\` records where it came from so the panel can explain the library.
219
+ * Collected images land in the pending pool and wait for approval; manual imports
220
+ * go straight in, because a person already chose them.
221
+ */
222
+ async addBuffer(bytes, { source = 'manual', note = '', groupId = '', senderId = '', requireApproval = false } = {}) {
223
+ await this.init();
224
+ if (!bytes || !bytes.length) return { ok: false, reason: '空文件' };
225
+ const verdict = this.#accept(bytes);
226
+ if (!verdict.ok) return verdict;
227
+
228
+ const hash = contentId(bytes);
229
+ // `already: 'library' | 'pending'` lets the caller stay quiet instead of
230
+ // logging the same picture as a failure every time it is seen again.
231
+ if (this.entries.some((e) => e.hash === hash)) return { ok: false, reason: '已存在', duplicate: true, already: 'library' };
232
+ if (this.pending.some((e) => e.hash === hash)) return { ok: false, reason: '已在待审核池', duplicate: true, already: 'pending' };
233
+ if (this.entries.length + this.pending.length >= this.maxEntries) return { ok: false, reason: `图库已达上限(${this.maxEntries})` };
234
+
235
+ const extension = Object.entries(MEDIA_BY_EXTENSION).find(([, type]) => type === verdict.size.mediaType)?.[0] ?? '.png';
236
+ const name = hash.slice(0, 24) + extension;
237
+ const record = {
238
+ id: hash.slice(0, 16),
239
+ hash,
240
+ file: name,
241
+ mediaType: verdict.size.mediaType,
242
+ width: verdict.size.width,
243
+ height: verdict.size.height,
244
+ source,
245
+ note,
246
+ groupId: groupId ? String(groupId) : '',
247
+ senderId: senderId ? String(senderId) : '',
248
+ tags: [],
249
+ emotions: [],
250
+ description: '',
251
+ addedAt: Date.now(),
252
+ classifiedAt: null,
253
+ uses: 0,
254
+ enabled: true,
255
+ };
256
+
257
+ if (requireApproval) {
258
+ await writeFile(join(this.pendingDir, name), bytes);
259
+ this.pending.push(record);
260
+ await this.#save();
261
+ return { ok: true, record, pending: true };
262
+ }
263
+ await writeFile(join(this.imagesDir, name), bytes);
264
+ this.entries.push(record);
265
+ await this.#save();
266
+ return { ok: true, record, pending: false };
267
+ }
268
+
269
+ /**
270
+ * Import every image in a folder.
271
+ *
272
+ * Recursive, because sticker packs arrive as nested directories far more often
273
+ * than flat ones. Returns a tally instead of throwing on the first bad file.
274
+ */
275
+ async importFolder(folder, { recursive = true, note = '' } = {}) {
276
+ await this.init();
277
+ const target = resolve(String(folder ?? ''));
278
+ let info;
279
+ try { info = await stat(target); } catch { return { ok: false, reason: '目录不存在:' + target }; }
280
+ if (!info.isDirectory()) return { ok: false, reason: '不是目录:' + target };
281
+
282
+ const files = [];
283
+ const walk = async (dir) => {
284
+ for (const item of await readdir(dir, { withFileTypes: true })) {
285
+ const full = join(dir, item.name);
286
+ if (item.isDirectory()) { if (recursive) await walk(full); continue; }
287
+ if (IMAGE_EXTENSIONS.has(extname(item.name).toLowerCase())) files.push(full);
288
+ }
289
+ };
290
+ await walk(target);
291
+
292
+ let added = 0;
293
+ const skipped = [];
294
+ for (const file of files) {
295
+ try {
296
+ const bytes = await readFile(file);
297
+ // The folder name is a useful default label: sticker packs are usually
298
+ // organised as "开心/", "无语/" and so on.
299
+ const folderNote = note || basename(dirname(file)) || '';
300
+ const result = await this.addBuffer(bytes, { source: 'folder', note: folderNote });
301
+ if (result.ok) added++;
302
+ else skipped.push({ file: basename(file), reason: result.reason });
303
+ } catch (error) {
304
+ skipped.push({ file: basename(file), reason: error.message });
305
+ }
306
+ }
307
+ return { ok: true, scanned: files.length, added, skipped: skipped.slice(0, 20), skippedTotal: skipped.length, folder: target };
308
+ }
309
+
310
+ /** Move a pending record into the library. */
311
+ async approve(id) {
312
+ await this.init();
313
+ const index = this.pending.findIndex((e) => e.id === id);
314
+ if (index < 0) return { ok: false, reason: '待审核池中没有这条' };
315
+ const record = this.pending[index];
316
+ try {
317
+ await copyFile(join(this.pendingDir, record.file), join(this.imagesDir, record.file));
318
+ await unlink(join(this.pendingDir, record.file));
319
+ } catch (error) {
320
+ return { ok: false, reason: '移动文件失败:' + error.message };
321
+ }
322
+ this.pending.splice(index, 1);
323
+ this.entries.push(record);
324
+ await this.#save();
325
+ return { ok: true, record };
326
+ }
327
+
328
+ /** Drop a pending record and its file. */
329
+ async reject(id) {
330
+ await this.init();
331
+ const index = this.pending.findIndex((e) => e.id === id);
332
+ if (index < 0) return { ok: false, reason: '待审核池中没有这条' };
333
+ const [record] = this.pending.splice(index, 1);
334
+ try { await unlink(join(this.pendingDir, record.file)); } catch { /* already gone */ }
335
+ await this.#save();
336
+ return { ok: true };
337
+ }
338
+
339
+ /** Remove a library entry and its file. */
340
+ async remove(id) {
341
+ await this.init();
342
+ const index = this.entries.findIndex((e) => e.id === id);
343
+ if (index < 0) return { ok: false, reason: '图库中没有这条' };
344
+ const [record] = this.entries.splice(index, 1);
345
+ try { await unlink(join(this.imagesDir, record.file)); } catch { /* already gone */ }
346
+ await this.#save();
347
+ return { ok: true };
348
+ }
349
+
350
+ /** Absolute path of an entry's image, for sending. */
351
+ pathOf(entry) {
352
+ // 文件名只由哈希生成,正常写入是安全的;但 index.json 被改过时
353
+ // 可以让发送/读图走到图库之外的路径。这里校验一次解析结果。
354
+ const target = join(this.imagesDir, String(entry?.file ?? ''));
355
+ const root = resolve(this.imagesDir);
356
+ const full = resolve(target);
357
+ if (full !== root && !full.startsWith(root + sep)) {
358
+ throw new Error('表情包路径越界:' + String(entry?.file ?? ''));
359
+ }
360
+ return full;
361
+ }
362
+
363
+ /** Absolute path of a pending entry's image. */
364
+ pendingPathOf(entry) {
365
+ return join(this.pendingDir, entry.file);
366
+ }
367
+
368
+ /** Store what the vision pass learned about one entry. */
369
+ async annotate(id, { tags = [], emotions = [], description = '' } = {}) {
370
+ await this.init();
371
+ const record = this.entries.find((e) => e.id === id) ?? this.pending.find((e) => e.id === id);
372
+ if (!record) return { ok: false, reason: '找不到这条' };
373
+ record.tags = [...new Set([...(record.tags ?? []), ...tags.map(String).filter(Boolean)])].slice(0, 12);
374
+ record.emotions = [...new Set([...(record.emotions ?? []), ...emotions.map(String).filter(Boolean)])].slice(0, 8);
375
+ if (description) record.description = String(description).slice(0, 300);
376
+ record.classifiedAt = Date.now();
377
+ await this.#save();
378
+ return { ok: true, record };
379
+ }
380
+
381
+ /** The text BM25 indexes for one entry. */
382
+ #searchText(entry) {
383
+ return [entry.description, ...(entry.tags ?? []), ...(entry.emotions ?? []), entry.note].filter(Boolean).join(' ');
384
+ }
385
+
386
+ /**
387
+ * Rank library entries against a query.
388
+ *
389
+ * @returns entries with a \`score\`, best first. An empty query returns nothing
390
+ * rather than the whole library, because "no signal" is not "any sticker".
391
+ */
392
+ search(query, { limit = 5, minScore = 0.1, emotions = [] } = {}) {
393
+ const pool = this.entries.filter((e) => e.enabled !== false);
394
+ if (pool.length === 0) return [];
395
+ let candidates = pool;
396
+ if (emotions.length) {
397
+ const wanted = new Set(emotions.map((x) => String(x).toLowerCase()));
398
+ const filtered = pool.filter((e) => (e.emotions ?? []).some((x) => wanted.has(String(x).toLowerCase())));
399
+ // An emotion filter that matches nothing must not empty the result: fall back
400
+ // to the full pool so a rare mood still gets an answer.
401
+ if (filtered.length) candidates = filtered;
402
+ }
403
+ const queryTokens = tokenize(query);
404
+ if (!queryTokens.length) return [];
405
+ const documents = candidates.map((entry) => {
406
+ const tokens = tokenize(this.#searchText(entry));
407
+ const terms = new Map();
408
+ for (const token of tokens) terms.set(token, (terms.get(token) ?? 0) + 1);
409
+ return { tokens, terms };
410
+ });
411
+ const scores = bm25(queryTokens, documents);
412
+ return candidates
413
+ .map((entry, i) => ({ entry, score: scores[i] }))
414
+ .filter((row) => row.score >= minScore)
415
+ .sort((a, b) => b.score - a.score)
416
+ .slice(0, limit);
417
+ }
418
+
419
+ /** Record that an entry was sent, so the panel can show what gets used. */
420
+ async markUsed(id) {
421
+ const record = this.entries.find((e) => e.id === id);
422
+ if (!record) return;
423
+ record.uses = (record.uses ?? 0) + 1;
424
+ record.lastUsedAt = Date.now();
425
+ await this.#save();
426
+ }
427
+
428
+ /** Entries the vision pass has not seen yet, oldest first. */
429
+ unclassified(limit = 5) {
430
+ return this.entries.filter((e) => !e.classifiedAt).slice(0, limit);
431
+ }
432
+
433
+ /** Read one entry's bytes, for classification or sending. */
434
+ async bytesOf(entry, { pending = false } = {}) {
435
+ return readFile(pending ? this.pendingPathOf(entry) : this.pathOf(entry));
436
+ }
437
+ }
438
+
439
+ /** Small helper so callers do not import path just to build a display name. */
440
+ export function displayName(entry) {
441
+ return entry.note || (entry.tags ?? [])[0] || entry.id;
442
+ }