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
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Persistence for the emotional state, plus the model-facing analysis call.
3
+ *
4
+ * Split from emotion.mjs on purpose: emotion.mjs is pure arithmetic and can be
5
+ * unit-tested without touching disk or a model. This file owns the two things that
6
+ * are genuinely stateful — where the numbers live, and who decides how they move.
7
+ *
8
+ * Two decisions worth stating:
9
+ *
10
+ * - STATE IS KEYED BY QQ NUMBER, NOT BY SESSION. EmotionAI-Pro defaults to
11
+ * per-session (`session_based: false` means shared, despite the name). For a
12
+ * persona with one owner and a few group friends, per-QQ is the honest model:
13
+ * the same person talking in two groups is the same relationship. The config
14
+ * still exposes `perSession` for people who want the other behaviour.
15
+ *
16
+ * - THE MODEL PROPOSES, THIS FILE DISPOSES. The analyser returns deltas; caps,
17
+ * clamping, stage maths and persistence all happen here. Letting a model write
18
+ * the score directly is how a "好感度" system ends up at 100 in one evening.
19
+ */
20
+ import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
21
+ import { join } from 'node:path';
22
+ import {
23
+ applyDeltas, createEmotionState, evaluateStage, isSignificant,
24
+ normalizeEmotionState, EMOTION_DIMENSIONS,
25
+ } from './emotion.mjs';
26
+
27
+ const VERSION = 1;
28
+ const MAX_USERS = 2000;
29
+
30
+ /**
31
+ * Keyword scoring, used when the auxiliary model is unavailable.
32
+ *
33
+ * Ported from SmartUpdateManager._analyze_emotional_keywords. Negative and
34
+ * conflict words weigh more than positive ones (3 vs 2) because a bad turn moves a
35
+ * relationship more than a good one — that asymmetry is in the original and it is
36
+ * also how people actually work.
37
+ */
38
+ export const KEYWORD_GROUPS = {
39
+ // 单字(爱/棒/烦/滚/恨/傻/笨/蠢)必须去掉:
40
+ // 匹配是 includes ——「爱好」会给好感 +1,「麻烦」会 -2,「真棒」和「棒槌」同分。
41
+ // 模型分析失败时会静默退回这套启发式,所以坏样本会真的写进 state.json。
42
+ positive: ['喜欢', '爱你', '开心', '高兴', '谢谢', '感谢', '感动', '温暖', '真棒', '很棒', '不错', '可爱', '漂亮', '美丽', '想你'],
43
+ negative: ['讨厌', '恨你', '生气', '愤怒', '伤心', '难过', '失望', '好烦', '真烦', '麻烦', '滚开', '傻子', '笨蛋', '愚蠢', '垃圾', '别烦我'],
44
+ intimate: ['想你', '想念', '关心', '担心', '在乎', '重要', '宝贝', '亲爱的', '抱抱', '拥抱', '亲亲'],
45
+ conflict: ['吵架', '争执', '不满', '抱怨', '批评', '指责', '反对', '不同意', '分手'],
46
+ };
47
+
48
+ const INTENSIFIERS = ['非常', '特别', '极其', '太', '真的', '超级'];
49
+
50
+ /**
51
+ * Cheap heuristic analysis. Returns the same shape as the model analyser so the
52
+ * caller does not care which one produced it.
53
+ */
54
+ export function analyzeKeywords(userMessage, aiResponse = '') {
55
+ const message = String(userMessage ?? '').toLowerCase();
56
+ const detected = new Set();
57
+ let score = 0;
58
+ for (const [category, words] of Object.entries(KEYWORD_GROUPS)) {
59
+ for (const word of words) {
60
+ if (!message.includes(word)) continue;
61
+ detected.add(category);
62
+ score += category === 'negative' || category === 'conflict' ? 3 : 2;
63
+ break; // one hit per category is enough; repeating a word is not a stronger feeling
64
+ }
65
+ }
66
+ // Intensifiers and punctuation nudge the magnitude without changing the category.
67
+ if (INTENSIFIERS.some((w) => message.includes(w))) score += 2;
68
+ if (/[!!]/.test(message)) score += 1;
69
+ if (/[??]/.test(message)) score += 0.5;
70
+
71
+ const deltas = {};
72
+ if (!detected.size) return { deltas, category: 'neutral', reason: '', intensity: 0 };
73
+ const positive = detected.has('positive') || detected.has('intimate');
74
+ const negative = detected.has('negative') || detected.has('conflict');
75
+ if (positive && !negative) {
76
+ deltas.favor = score >= 4 ? 2 : 1;
77
+ deltas.joy = 2;
78
+ deltas.trust = 1;
79
+ if (detected.has('intimate')) { deltas.intimacy = 2; deltas.anticipation = 1; }
80
+ } else if (negative && !positive) {
81
+ // Negative turns move favor more than positive ones at the same intensity:
82
+ // a single insult should not weigh the same as a single thank-you. -2 is the
83
+ // floor for a detected negative word, -3 once it is also intensified.
84
+ deltas.favor = score >= 5 ? -3 : -2;
85
+ deltas.joy = -1;
86
+ deltas.anger = detected.has('conflict') ? 2 : 1;
87
+ deltas.trust = -1;
88
+ if (detected.has('conflict')) deltas.intimacy = -1;
89
+ } else {
90
+ // 正负同时出现(「喜欢你但你好烦」):按命中词数算净值,给一点变化。
91
+ // 以前这里 deltas 是空对象,这一轮照样计入 totalTurns,好感却一动不动 ——
92
+ // 用户在面板上看到「聊了很多轮,好感没变」。
93
+ // 负面词权重更高:一句同时有好有坏的抱怨,整体偏负才符合直觉。
94
+ const posCount = Object.entries(KEYWORD_GROUPS)
95
+ .filter(([k]) => k === 'positive' || k === 'intimate')
96
+ .reduce((sum, [, words]) => sum + words.filter((w) => message.includes(w)).length, 0);
97
+ const negCount = Object.entries(KEYWORD_GROUPS)
98
+ .filter(([k]) => k === 'negative' || k === 'conflict')
99
+ .reduce((sum, [, words]) => sum + words.filter((w) => message.includes(w)).length, 0);
100
+ const net = posCount - negCount * 1.5;
101
+ if (net !== 0) {
102
+ deltas.favor = net > 0 ? 1 : -1;
103
+ deltas.joy = net > 0 ? 1 : -1;
104
+ deltas.trust = net > 0 ? 1 : -1;
105
+ }
106
+ }
107
+ const category = positive && negative ? 'mixed'
108
+ : negative ? (detected.has('conflict') ? 'negative_conflict' : 'negative')
109
+ : detected.has('intimate') ? 'positive_intimate' : 'positive';
110
+ return {
111
+ deltas,
112
+ category,
113
+ reason: category === 'mixed' ? '对话同时包含正负情感' : '对话包含情感关键词',
114
+ intensity: Math.min(5, Math.round(score)),
115
+ };
116
+ }
117
+
118
+ export class EmotionStore {
119
+ constructor({ dataDir, logger = console, perSession = false, significanceThreshold = 5, privacyLevel = 1 } = {}) {
120
+ this.root = join(dataDir, 'emotion');
121
+ this.file = join(this.root, 'state.json');
122
+ this.logger = logger;
123
+ this.perSession = perSession === true;
124
+ this.significanceThreshold = significanceThreshold;
125
+ this.privacyLevel = privacyLevel;
126
+ this.users = {};
127
+ this.loaded = false;
128
+ this.writeChain = Promise.resolve();
129
+ // Coalesce concurrent turns: the analyser is async and two replies can land
130
+ // at once, which would otherwise read-modify-write the same key and lose one.
131
+ this.locks = new Map();
132
+ }
133
+
134
+ async init() {
135
+ if (this.loaded) return this;
136
+ await mkdir(this.root, { recursive: true });
137
+ try {
138
+ const raw = JSON.parse(await readFile(this.file, 'utf8'));
139
+ if (raw?.version === VERSION && raw.users && typeof raw.users === 'object') this.users = raw.users;
140
+ } catch { /* missing or corrupt starts empty */ }
141
+ this.loaded = true;
142
+ return this;
143
+ }
144
+
145
+ #save() {
146
+ this.writeChain = this.writeChain.then(async () => {
147
+ await mkdir(this.root, { recursive: true });
148
+ const tmp = this.file + '.tmp';
149
+ await writeFile(tmp, JSON.stringify({ version: VERSION, users: this.users }, null, 2) + '\n');
150
+ await rename(tmp, this.file);
151
+ }).catch((error) => this.logger.warn?.('情感状态写入失败:' + error.message));
152
+ return this.writeChain;
153
+ }
154
+
155
+ /** Serialise work per user key. */
156
+ async #withLock(key, fn) {
157
+ const prior = this.locks.get(key) ?? Promise.resolve();
158
+ const run = prior.then(fn, fn);
159
+ // Store a swallowed variant so a rejected turn cannot poison the next one,
160
+ // and compare against THAT object (calling .catch() again would make a new
161
+ // promise every time, so the equality test would never be true and the entry
162
+ // would leak forever).
163
+ const settled = run.catch(() => {});
164
+ this.locks.set(key, settled);
165
+ try { return await run; } finally {
166
+ if (this.locks.get(key) === settled) this.locks.delete(key);
167
+ }
168
+ }
169
+
170
+ /** Storage key for a QQ number (or conversation, when perSession is on). */
171
+ keyFor({ peerId, kind = 'private', sessionId = '' } = {}) {
172
+ const id = String(peerId ?? '').trim();
173
+ if (!id) return '';
174
+ return this.perSession ? `${kind}:${sessionId || id}` : id;
175
+ }
176
+
177
+ get(userKey) {
178
+ const raw = this.users[userKey];
179
+ if (!raw) return createEmotionState(userKey);
180
+ return normalizeEmotionState(raw, userKey);
181
+ }
182
+
183
+ /** Current state plus derived stage info, for prompts and the panel. */
184
+ describe(userKey) {
185
+ const state = this.get(userKey);
186
+ return { state, stage: evaluateStage(state) };
187
+ }
188
+
189
+ /**
190
+ * Record one turn.
191
+ *
192
+ * `deltas` may come from a model or from `analyzeKeywords`; either way the caps
193
+ * and clamping in emotion.mjs apply. Returns the new state and whether this turn
194
+ * was significant enough to remember.
195
+ */
196
+ async record(userKey, { deltas = {}, attitude = '', relationship = '', note = '', category = 'neutral', at = Date.now() } = {}) {
197
+ if (!userKey) return null;
198
+ return this.#withLock(userKey, async () => {
199
+ const before = this.get(userKey);
200
+ let next = applyDeltas(before, deltas);
201
+ // Let the model rewrite the free-text labels, but never let it blank them.
202
+ if (attitude) next.attitude = String(attitude).slice(0, 40) || before.attitude;
203
+ if (relationship) next.relationship = String(relationship).slice(0, 60) || before.relationship;
204
+ next.totalTurns = before.totalTurns + 1;
205
+ if (category === 'positive' || category === 'positive_intimate') next.positiveTurns = before.positiveTurns + 1;
206
+ if (category === 'negative' || category === 'negative_conflict') next.negativeTurns = before.negativeTurns + 1;
207
+ next.lastInteractionAt = at;
208
+ next.lastUpdatedAt = at;
209
+
210
+ const stage = evaluateStage(next);
211
+ next = stage.state;
212
+
213
+ const significant = isSignificant(deltas, this.significanceThreshold);
214
+ if (significant && note) {
215
+ next.memories = [...(next.memories ?? []), { at, note: String(note).slice(0, 160), category, stage: stage.stageName }].slice(-40);
216
+ }
217
+
218
+ this.users[userKey] = next;
219
+ this.#trim();
220
+ await this.#save();
221
+ return { state: next, stage, significant };
222
+ });
223
+ }
224
+
225
+ /** Manual override, used by the panel and the tools. */
226
+ async set(userKey, patch = {}) {
227
+ if (!userKey) return null;
228
+ return this.#withLock(userKey, async () => {
229
+ const before = this.get(userKey);
230
+ const next = normalizeEmotionState({ ...before, ...patch }, userKey);
231
+ const stage = evaluateStage(next);
232
+ this.users[userKey] = stage.state;
233
+ await this.#save();
234
+ return { state: stage.state, stage };
235
+ });
236
+ }
237
+
238
+ async reset(userKey) {
239
+ if (!userKey) return null;
240
+ return this.#withLock(userKey, async () => {
241
+ const fresh = createEmotionState(userKey);
242
+ this.users[userKey] = fresh;
243
+ await this.#save();
244
+ return { state: fresh, stage: evaluateStage(fresh) };
245
+ });
246
+ }
247
+
248
+ /** Newest-first list for the panel. */
249
+ list({ limit = 50 } = {}) {
250
+ const rows = Object.keys(this.users).map((key) => {
251
+ const state = this.get(key);
252
+ const stage = evaluateStage(state);
253
+ return {
254
+ userKey: key,
255
+ favor: state.favor,
256
+ intimacy: state.intimacy,
257
+ stage: stage.stageName,
258
+ attitude: state.attitude,
259
+ relationship: state.relationship,
260
+ totalTurns: state.totalTurns,
261
+ lastInteractionAt: state.lastInteractionAt,
262
+ dominant: Object.entries(state.emotions).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null,
263
+ };
264
+ }).sort((a, b) => (b.lastInteractionAt ?? 0) - (a.lastInteractionAt ?? 0));
265
+ return rows.slice(0, Math.min(200, Math.max(1, limit)));
266
+ }
267
+
268
+ stats() {
269
+ const keys = Object.keys(this.users);
270
+ let total = 0;
271
+ let positive = 0;
272
+ let negative = 0;
273
+ for (const key of keys) {
274
+ const s = this.get(key);
275
+ total += s.totalTurns;
276
+ positive += s.positiveTurns;
277
+ negative += s.negativeTurns;
278
+ }
279
+ return { users: keys.length, totalTurns: total, positiveTurns: positive, negativeTurns: negative, perSession: this.perSession };
280
+ }
281
+
282
+ /** Drop the least recently seen entries so the file cannot grow without bound. */
283
+ #trim() {
284
+ const keys = Object.keys(this.users);
285
+ if (keys.length <= MAX_USERS) return;
286
+ keys.sort((a, b) => (Number(this.users[a]?.lastInteractionAt) || 0) - (Number(this.users[b]?.lastInteractionAt) || 0));
287
+ for (const key of keys.slice(0, keys.length - MAX_USERS)) delete this.users[key];
288
+ }
289
+
290
+ async flush() { await this.writeChain; }
291
+ }
292
+
293
+ /**
294
+ * Prompt for the auxiliary emotion analyser.
295
+ *
296
+ * Ported from EmotionAnalysisExpert._build_emotion_analysis_prompt, with the
297
+ * delta range narrowed to ±3 and the output restricted to the fields we consume.
298
+ * Asking for a narrative instead of JSON is what makes this call cheap to parse.
299
+ */
300
+ export function buildAnalysisPrompt({ userMessage, aiResponse, state, history = [] }) {
301
+ const recent = history.slice(-3).map((h) => `${h.role === 'user' ? '对方' : '你'}:${h.text}`).join('\n');
302
+ return [
303
+ '你在分析一段 QQ 聊天里「对方」对「你」的情感影响,只输出 JSON。',
304
+ '',
305
+ '最近对话:',
306
+ recent || '(无)',
307
+ '',
308
+ `本轮对方说:「${String(userMessage ?? '').slice(0, 500)}」`,
309
+ `你回:「${String(aiResponse ?? '').slice(0, 500)}」`,
310
+ '',
311
+ '当前关系状态:',
312
+ `- 好感度 ${state.favor}(-100 到 100)`,
313
+ `- 亲密度 ${state.intimacy}(0 到 100)`,
314
+ `- 累计互动 ${state.totalTurns} 次`,
315
+ '',
316
+ '请给出这一轮带来的变化,每项是 -3 到 3 的整数(没有变化就写 0):',
317
+ 'favor(好感)、intimacy(亲密)、joy(喜悦)、trust(信任)、fear(恐惧)、',
318
+ 'surprise(惊讶)、sadness(悲伤)、disgust(厌恶)、anger(愤怒)、anticipation(期待)',
319
+ '',
320
+ '另外给出两个很短的描述:',
321
+ '- attitude:你此刻对他的态度,2-8 个字(例如「有点在意」「保持距离」)',
322
+ '- relationship:你们现在的关系,2-10 个字(例如「刚认识」「很熟的朋友」)',
323
+ '',
324
+ '只输出这个 JSON,不要解释:',
325
+ '{"deltas":{"favor":0,"intimacy":0,"joy":0,"trust":0,"fear":0,"surprise":0,"sadness":0,"disgust":0,"anger":0,"anticipation":0},"attitude":"","relationship":"","note":"一句话记下这轮发生了什么"}',
326
+ ].join('\n');
327
+ }
328
+
329
+ /** Pull the JSON object out of a model reply, tolerating fences and prose. */
330
+ export function extractAnalysis(text) {
331
+ const body = String(text ?? '');
332
+ const fenced = body.match(/```(?:json)?\s*([\s\S]*?)```/i);
333
+ const candidate = fenced ? fenced[1] : body;
334
+ const start = candidate.indexOf('{');
335
+ const end = candidate.lastIndexOf('}');
336
+ if (start < 0 || end <= start) return null;
337
+ try {
338
+ const data = JSON.parse(candidate.slice(start, end + 1));
339
+ if (!data || typeof data !== 'object') return null;
340
+ const deltas = {};
341
+ for (const key of ['favor', 'intimacy', ...EMOTION_DIMENSIONS]) {
342
+ const value = Number(data.deltas?.[key] ?? data[key] ?? 0);
343
+ if (Number.isFinite(value)) deltas[key] = Math.max(-3, Math.min(3, Math.round(value)));
344
+ }
345
+ return {
346
+ deltas,
347
+ attitude: typeof data.attitude === 'string' ? data.attitude.slice(0, 40) : '',
348
+ relationship: typeof data.relationship === 'string' ? data.relationship.slice(0, 60) : '',
349
+ note: typeof data.note === 'string' ? data.note.slice(0, 160) : '',
350
+ };
351
+ } catch { return null; }
352
+ }