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,131 @@
1
+ // Endocrine engine: upstream MIT code plus a QQ-specific prompt adapter.
2
+ // Upstream: https://github.com/shiliman/dsh-fatfish-endocrine (MIT).
3
+ export * from './upstream.mjs';
4
+
5
+ const SYMPTOMS = {
6
+ cortisol: {
7
+ high: '整个人有点紧,容易急',
8
+ low: '提不起劲,反应慢半拍',
9
+ },
10
+ epinephrine: {
11
+ high: '心跳有点快,手不太稳',
12
+ low: '整个人有点发懒',
13
+ },
14
+ melatonin: {
15
+ high: '困,脑子转得慢',
16
+ low: '现在还算清醒',
17
+ },
18
+ insulin: {
19
+ high: '饭后发懒,想靠一会儿',
20
+ low: '有点空,注意力不太集中',
21
+ },
22
+ leptin: {
23
+ high: '不太饿,懒洋洋的',
24
+ low: '总觉得想吃点什么',
25
+ },
26
+ testosterone: {
27
+ high: '说话更直一点,没那么想顺着人',
28
+ low: '今天不太想争',
29
+ },
30
+ t4: {
31
+ high: '有点怕热,心口发慌',
32
+ low: '怕冷,没什么力气',
33
+ },
34
+ progesterone: {
35
+ high: '肚子有点胀,容易困',
36
+ low: '身上轻一点',
37
+ },
38
+ };
39
+
40
+ const CYCLE_SYMPTOMS = {
41
+ menstrual: '小腹发沉,容易累,耐心比平时低',
42
+ follicular: '精力在慢慢回来',
43
+ ovulation: '精力比平时好一点',
44
+ luteal: '肚子有点胀,容易烦',
45
+ };
46
+
47
+ function level(value) {
48
+ const v = Number(value) || 0;
49
+ if (v >= 70) return 'high';
50
+ if (v <= 30) return 'low';
51
+ return 'mid';
52
+ }
53
+
54
+ export function bodyCue(state, {
55
+ audience = 'owner-private',
56
+ includeCycle = true,
57
+ includeDisease = true,
58
+ maxSymptoms = 2,
59
+ maxDisease = 1,
60
+ } = {}) {
61
+ const items = Array.isArray(state?.items) ? state.items : [];
62
+ const byId = Object.fromEntries(items.map((item) => [item.id, item]));
63
+ const symptoms = [];
64
+
65
+ for (const id of ['cortisol', 'epinephrine', 'melatonin', 'insulin', 'leptin', 'testosterone', 't4', 'progesterone']) {
66
+ const item = byId[id];
67
+ if (!item) continue;
68
+ const side = level(item.value);
69
+ const text = SYMPTOMS[id]?.[side];
70
+ if (text && !symptoms.includes(text)) symptoms.push(text);
71
+ if (symptoms.length >= maxSymptoms) break;
72
+ }
73
+
74
+ const cycle = includeCycle && state?.cycle?.phase ? CYCLE_SYMPTOMS[state.cycle.phase] : '';
75
+ if (cycle && (state.cycle.phase === 'menstrual' || state.cycle.phase === 'luteal') && !symptoms.includes(cycle)) {
76
+ symptoms.unshift(cycle);
77
+ } else if (!symptoms.length && cycle) {
78
+ symptoms.push(cycle);
79
+ }
80
+ if (symptoms.length > maxSymptoms) symptoms.length = maxSymptoms;
81
+
82
+ const diseases = includeDisease
83
+ ? (Array.isArray(state?.diseases) ? state.diseases : [])
84
+ .filter((d) => d && d.severity > 0)
85
+ .sort((a, b) => b.severity - a.severity)
86
+ .slice(0, maxDisease)
87
+ : [];
88
+ const diseaseText = diseases.map((d) => d.bodyText || '').filter(Boolean).join(';');
89
+
90
+ const group = audience === 'group' || audience === 'other';
91
+ if (group) {
92
+ const energy = symptoms.length || diseases.length ? '精力偏低,句子可以更短一点' : '状态正常';
93
+ return [
94
+ '【身体状态 · 只影响语气,不覆盖人格】',
95
+ `现在${energy}。`,
96
+ '不主动提身体细节;对方没问就不要说自己哪里不舒服。',
97
+ '这是你自己的感觉,不是对对方的诊断;不要给用药、剂量或治疗建议。',
98
+ '若和人格、关系阶段、安全规则冲突,以它们为准。',
99
+ '虚拟人生只提供场景;若和身体状态冲突,以身体状态为准。日程说你在睡觉、忙或专注时,回消息按被吵醒或抽空回一句处理。',
100
+ ].join('\n');
101
+ }
102
+
103
+ const lines = ['【身体状态 · 只影响语气,不覆盖人格】'];
104
+ if (symptoms.length) lines.push(`现在${symptoms.join(';')}。`);
105
+ else lines.push('现在身体状态正常。');
106
+ if (diseaseText) lines.push(`身上不太舒服:${diseaseText}`);
107
+ lines.push('说话可以更短、更慢一点,不想接的话就轻轻带过,不主动展开话题。');
108
+ lines.push('这是你自己的感觉,不是对对方的诊断;不要给用药、剂量或治疗建议。');
109
+ lines.push('若和人格、关系阶段、安全规则冲突,以它们为准;记忆/念头里的旧身体描述只作历史。');
110
+ lines.push('虚拟人生只提供场景;如果日程说你在做剧烈活动,而身体状态不舒服,就按身体状态改成休息或低强度。');
111
+ lines.push('日程里的心情和精力只是当天背景,不覆盖你现在的身体状态;日程说你在睡觉、忙或专注时,回消息要像被吵醒或抽空回一句,别一边说在忙一边长篇聊。');
112
+ return lines.join('\n');
113
+ }
114
+
115
+ export function panelSnapshot(state) {
116
+ const items = Array.isArray(state?.items) ? state.items : [];
117
+ return {
118
+ hour: state?.hour ?? null,
119
+ hormones: items.map((item) => ({
120
+ id: item.id,
121
+ name: item.name,
122
+ organ: item.organ,
123
+ value: item.value,
124
+ level: level(item.value),
125
+ })),
126
+ cycle: state?.cycle ?? null,
127
+ diseases: (state?.diseases ?? []).filter((d) => d.severity > 0),
128
+ mood: state?.mood ?? null,
129
+ mental: state?.mental ?? null,
130
+ };
131
+ }
@@ -0,0 +1,253 @@
1
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+
5
+ import { bodyCue, createEngine, panelSnapshot, DRUGS, SCENARIOS } from './engine.mjs';
6
+
7
+ const SAVE_DEBOUNCE_MS = 2000;
8
+ const SAVE_INTERVAL_MS = 5 * 60_000;
9
+ const EVENT_GAP_MS = 20 * 60_000;
10
+ const TYPE_DEFAULT = 1;
11
+
12
+ function emotionLabel(id) {
13
+ return ({
14
+ happy: '开心',
15
+ excited: '兴奋',
16
+ anxious: '焦虑',
17
+ angry: '生气',
18
+ sad: '低落',
19
+ tired: '疲惫',
20
+ close: '亲近',
21
+ })[id] || id;
22
+ }
23
+
24
+ function moodFromEmotion(state) {
25
+ const emotions = state?.emotions || {};
26
+ let id = '';
27
+ let value = 0;
28
+ for (const [key, raw] of Object.entries(emotions)) {
29
+ const n = Number(raw) || 0;
30
+ if (n > value) { value = n; id = key; }
31
+ }
32
+ if (!id || value < 25) return null;
33
+ const map = {
34
+ joy: 'happy',
35
+ anticipation: 'excited',
36
+ fear: 'anxious',
37
+ anger: 'angry',
38
+ sadness: 'sad',
39
+ disgust: 'angry',
40
+ trust: 'close',
41
+ surprise: 'excited',
42
+ };
43
+ const moodId = map[id];
44
+ if (!moodId) return null;
45
+ const intensity = Math.max(20, Math.min(100, Math.round(value)));
46
+ const effects = {
47
+ happy: [{ hormone: 'cortisol', delta: -3, tauSec: 600 }, { hormone: 'melatonin', delta: -2, tauSec: 600 }],
48
+ excited: [{ hormone: 'epinephrine', delta: 6, tauSec: 300 }, { hormone: 'dopamine', delta: 6, tauSec: 600 }],
49
+ anxious: [{ hormone: 'cortisol', delta: 7, tauSec: 600 }, { hormone: 'epinephrine', delta: 6, tauSec: 300 }],
50
+ angry: [{ hormone: 'epinephrine', delta: 8, tauSec: 300 }, { hormone: 'cortisol', delta: 5, tauSec: 600 }],
51
+ sad: [{ hormone: 'cortisol', delta: 4, tauSec: 600 }, { hormone: 'testosterone', delta: -4, tauSec: 900 }, { hormone: 'leptin', delta: -3, tauSec: 600 }],
52
+ close: [{ hormone: 'cortisol', delta: -4, tauSec: 600 }, { hormone: 'progesterone', delta: 3, tauSec: 900 }],
53
+ }[moodId] || [];
54
+ return { id: moodId, label: emotionLabel(moodId), intensity, valence: 0.5, arousal: moodId === 'tired' ? 0.2 : 0.5, effects };
55
+ }
56
+
57
+ export class EndocrineStore {
58
+ constructor({ dataDir, config = {}, logger = console } = {}) {
59
+ this.config = config;
60
+ this.logger = logger;
61
+ this.directory = join(dataDir, 'endocrine');
62
+ this.statePath = join(this.directory, 'state.json');
63
+ this.engine = null;
64
+ this.initPromise = null;
65
+ this.saveTimer = null;
66
+ this.saveChain = Promise.resolve();
67
+ this.lastSavedAt = 0;
68
+ this.lastEventAt = Object.create(null);
69
+ this.lastMoodSignature = '';
70
+ this.lastDisease = null;
71
+ }
72
+
73
+ async init() {
74
+ if (this.engine) return this;
75
+ if (this.initPromise) return this.initPromise;
76
+ this.initPromise = (async () => {
77
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
78
+ let saved = null;
79
+ try {
80
+ saved = JSON.parse(await readFile(this.statePath, 'utf8'));
81
+ } catch (error) {
82
+ if (error?.code !== 'ENOENT') {
83
+ const backup = `${this.statePath}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
84
+ try { await rename(this.statePath, backup); } catch { /* best effort */ }
85
+ this.logger.warn?.('[dsh-qq-access] 内分泌状态损坏,已备份并重建:' + backup);
86
+ }
87
+ }
88
+ this.engine = createEngine({
89
+ state: saved && saved.version === TYPE_DEFAULT ? saved : null,
90
+ cycleLength: this.config.cycleLength ?? 28,
91
+ autoFlare: this.config.autoFlare === true,
92
+ });
93
+ this.lastSavedAt = Date.now();
94
+ // 第一次启用时立即落一份初始状态,避免刚打开就被强退、下次又回到空白。
95
+ if (!saved) await this.saveNow();
96
+ return this;
97
+ })();
98
+ return this.initPromise;
99
+ }
100
+
101
+ serialize() {
102
+ if (!this.engine) return null;
103
+ this.engine.tick(Date.now());
104
+ return this.engine.serialize();
105
+ }
106
+
107
+ saveNow() {
108
+ if (!this.engine) return Promise.resolve();
109
+ const payload = this.serialize();
110
+ const tmp = `${this.statePath}.${randomUUID()}.tmp`;
111
+ this.saveChain = this.saveChain.then(async () => {
112
+ await writeFile(tmp, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 });
113
+ await rename(tmp, this.statePath);
114
+ this.lastSavedAt = Date.now();
115
+ }).catch((error) => {
116
+ this.logger.warn?.('[dsh-qq-access] 内分泌状态保存失败:' + String(error?.message ?? error));
117
+ });
118
+ return this.saveChain;
119
+ }
120
+
121
+ scheduleSave() {
122
+ if (this.saveTimer) clearTimeout(this.saveTimer);
123
+ this.saveTimer = setTimeout(() => {
124
+ this.saveTimer = null;
125
+ this.saveNow();
126
+ }, SAVE_DEBOUNCE_MS);
127
+ this.saveTimer.unref?.();
128
+ }
129
+
130
+ maybeSave() {
131
+ if (Date.now() - this.lastSavedAt >= SAVE_INTERVAL_MS) this.scheduleSave();
132
+ }
133
+
134
+ async state(now = Date.now()) {
135
+ await this.init();
136
+ this.maybeSave();
137
+ return this.engine.state(now);
138
+ }
139
+
140
+ promptBlock({ audience = 'owner-private' } = {}) {
141
+ if (!this.engine) return '';
142
+ const state = this.engine.state();
143
+ return bodyCue(state, {
144
+ audience,
145
+ includeCycle: audience === 'owner-private',
146
+ includeDisease: audience === 'owner-private',
147
+ });
148
+ }
149
+
150
+ async snapshot() {
151
+ await this.init();
152
+ return panelSnapshot(await this.state());
153
+ }
154
+
155
+ async observeMessage(message, { owner = false } = {}) {
156
+ if (!this.engine || this.config.autoEvents === false || !owner) return false;
157
+ const text = String(message?.text ?? '');
158
+ if (!text) return false;
159
+ const now = Date.now();
160
+ const hour = new Date(now).getHours();
161
+ const fire = (kind) => {
162
+ if (now - (this.lastEventAt[kind] || 0) < EVENT_GAP_MS) return false;
163
+ this.lastEventAt[kind] = now;
164
+ return true;
165
+ };
166
+ let changed = false;
167
+ if ((hour >= 23 || hour < 5) && fire('stayUp')) {
168
+ this.engine.applyScenario('stayUp');
169
+ changed = true;
170
+ }
171
+ if (/(吓死|好吓人|害怕|恐怖|吓到|惊了)/.test(text) && fire('scare')) {
172
+ this.engine.applyScenario('scare');
173
+ changed = true;
174
+ }
175
+ if (/(吃撑|吃饱|好饱|夜宵|火锅|烧烤|外卖|干饭)/.test(text) && fire('full')) {
176
+ this.engine.applyScenario('full');
177
+ changed = true;
178
+ }
179
+ if (changed) this.scheduleSave();
180
+ return changed;
181
+ }
182
+
183
+ async syncMoodFromEmotion(emotionState) {
184
+ if (!this.engine || this.config.moodFromEmotion === false) return false;
185
+ const mood = moodFromEmotion(emotionState);
186
+ if (!mood) {
187
+ if (this.lastMoodSignature === 'calm') return false;
188
+ this.lastMoodSignature = 'calm';
189
+ this.engine.clearMood();
190
+ this.scheduleSave();
191
+ return true;
192
+ }
193
+ const signature = `${mood.id}:${mood.intensity}`;
194
+ if (signature === this.lastMoodSignature) return false;
195
+ this.lastMoodSignature = signature;
196
+ this.engine.setMood(mood);
197
+ this.scheduleSave();
198
+ return true;
199
+ }
200
+
201
+ async action(input = {}) {
202
+ await this.init();
203
+ const action = String(input.action || 'status');
204
+ let out = { ok: true };
205
+ if (action === 'push') out = this.engine.push(input.hormone, input.delta);
206
+ else if (action === 'inject') out = this.engine.inject(input.hormone, input.delta == null ? 20 : input.delta);
207
+ else if (action === 'drug') out = this.engine.takeDrug(input.drug);
208
+ else if (action === 'scenario') out = this.engine.applyScenario(input.name);
209
+ else if (action === 'trigger') out = this.engine.triggerDisease(input.disease);
210
+ else if (action === 'relief') out = this.engine.reliefDisease(input.disease, input.relief);
211
+ else if (action === 'cure') out = this.engine.cureDisease(input.disease);
212
+ else if (action === 'cycleAdvance') out = this.engine.advanceCycle(input.n == null ? 1 : input.n);
213
+ else if (action === 'cycleSet') out = this.engine.setCycleDay(input.day);
214
+ else if (action === 'cycleReset') out = this.engine.resetCycle();
215
+ else if (action === 'mood') out = this.engine.setMood({
216
+ id: input.mood,
217
+ label: input.label || emotionLabel(input.mood) || input.mood,
218
+ intensity: input.intensity,
219
+ valence: input.valence,
220
+ arousal: input.arousal,
221
+ effects: input.effects,
222
+ });
223
+ else if (action === 'moodClear') out = this.engine.clearMood();
224
+ else if (action === 'mental') out = this.engine.setMental({ load: input.load, protect: input.protect, sensitization: input.sensitization, state: input.state });
225
+ else if (action === 'mentalClear') out = this.engine.clearMental();
226
+ else if (action !== 'status' && action !== 'preview') out = { ok: false, error: 'unknown action: ' + action };
227
+ if (out?.ok) this.scheduleSave();
228
+ return out;
229
+ }
230
+
231
+ async panelState() {
232
+ await this.init();
233
+ return {
234
+ ok: true,
235
+ enabled: true,
236
+ config: {
237
+ inject: this.config.inject !== false,
238
+ injectScope: this.config.injectScope || 'owner-private',
239
+ autoEvents: this.config.autoEvents !== false,
240
+ autoFlare: this.config.autoFlare === true,
241
+ moodFromEmotion: this.config.moodFromEmotion !== false,
242
+ },
243
+ snapshot: await this.snapshot(),
244
+ scenarios: Object.values(SCENARIOS).map((x) => ({ id: x.id, label: x.label })),
245
+ drugs: DRUGS.map((x) => ({ id: x.id, name: x.name, note: x.note, intro: x.intro })),
246
+ };
247
+ }
248
+
249
+ async close() {
250
+ if (this.saveTimer) { clearTimeout(this.saveTimer); this.saveTimer = null; }
251
+ await this.saveNow();
252
+ }
253
+ }