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/config.mjs ADDED
@@ -0,0 +1,509 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { assert, decimal, integer, peerId as toPeerId } from './util.mjs';
6
+
7
+ /**
8
+ * `HH:MM` 校验,返回补零后的字符串。
9
+ *
10
+ * 只接受 00:00–24:00;24:00 单独放行是因为「到今天结束」比「23:59」更准确。
11
+ * 非法值在这里就报错,而不是等到调度时静默算出 NaN 时间。
12
+ */
13
+ function clock(value, fallback, label) {
14
+ if (value === undefined || value === null || value === '') return fallback;
15
+ const text = String(value).trim();
16
+ const m = text.match(/^(\d{1,2}):(\d{2})$/);
17
+ assert(m, `${label}必须是 HH:MM 格式`);
18
+ const h = Number(m[1]);
19
+ const min = Number(m[2]);
20
+ assert(h <= 24 && min <= 59, `${label}必须是 00:00–24:00 之间的时间`);
21
+ assert(h < 24 || min === 0, `${label}的 24 点只能写成 24:00`);
22
+ return String(h).padStart(2, '0') + ':' + String(min).padStart(2, '0');
23
+ }
24
+
25
+ /**
26
+ * 和风 API Key 的形状校验。
27
+ *
28
+ * 出过一次事故:面板把人格设定整段写进了 weather.apiKey,保存成功、
29
+ * 界面显示「已保存」,但那个字段根本不是 key。所以这里不只是 trim,
30
+ * 而是拒绝明显不像 key 的内容 —— 宁可当没填,也不要存一段垃圾进去。
31
+ */
32
+ function weatherApiKey(value) {
33
+ const text = String(value ?? '').trim();
34
+ if (!text) return '';
35
+ if (!/^[A-Za-z0-9._-]{8,128}$/.test(text)) return '';
36
+ return text;
37
+ }
38
+
39
+ export const defaultConfigPath = () => process.env.DSH_WECHAT_CONFIG || join(homedir(), '.dsh-wechat-access', 'config.json');
40
+
41
+ /**
42
+ * 一份能直接通过 normalizeConfig 的配置模板。
43
+ *
44
+ * cli.mjs setup 和面板的「首次配置」都用它,避免同一组默认值写两遍 ——
45
+ * 以前热应用、PATCHABLE、capabilities 这些手维护清单都因为两边不同步出过事。
46
+ * token / secret / webuiToken 每次调用都重新随机,绝不写死。
47
+ */
48
+ export function bootstrapConfig({ accountId = '', ownerIds = [], platform = process.platform, arch = process.arch } = {}) {
49
+ return {
50
+ accountId, ownerIds, dataDir: './data',
51
+ /**
52
+ * agent-wechat 守护进程地址与令牌。
53
+ *
54
+ * 和 QQ 版最大的不同:不需要我们自己拉起任何进程,也不需要
55
+ * 事件端口。`wx serve` 由用户(或桌面端)负责常驻,我们只是它的客户端。
56
+ * token 从 `wx tokens create` 取,只授予 read/send/media/read-state。
57
+ */
58
+ wechat: {
59
+ baseUrl: 'http://127.0.0.1:6174/v1',
60
+ token: '',
61
+ timeoutMs: 20000,
62
+ // 断线后是否用游标续传(默认开)。关掉等于「重连后从头再来」。
63
+ resumeEvents: true,
64
+ },
65
+ access: { privateMode: 'all', groupMode: 'all', privateIds: [], groupIds: [], blockedUsers: [], blockedGroups: [] },
66
+ reply: { private: true, group: 'off', smartThreshold: 3, selfNames: [], interests: [], learnInterests: true, maxChars: 2000, contextMessages: 20, concurrency: 4, maxLiveSessions: 64, commaSplit: true, sharedAgent: false },
67
+ retentionDays: 30, ownerHarnessTools: false,
68
+ rate: { globalGapMs: 1000, peerGapMs: 3000, maxPerMinute: 20 },
69
+ emotion: { enabled: false, perSession: false, useModel: true, inject: true, privacyLevel: 1, significanceThreshold: 5 },
70
+ life: { enabled: true, inject: true, autoRefresh: true, proactive: false },
71
+ memes: { enabled: true, autoCollect: false, requireApproval: true, visionClassify: true, autoSend: false },
72
+ thoughts: { enabled: true, inject: true, limit: 3, maxAgeHours: 48 },
73
+ search: { enabled: true, apiKey: '' },
74
+ steam: { enabled: false, apiKey: '', cacheTtlMs: 60000, withGames: true, inject: true, injectProactive: true, privateOnly: true },
75
+ image: { enabled: false, provider: 'doubao', model: 'image-gen', timeoutMs: 120000, maxPerTurn: 3 },
76
+ endocrine: { enabled: false, inject: true, injectScope: 'owner-private', autoEvents: true, autoFlare: false, moodFromEmotion: true, cycleLength: 28 },
77
+ persona: '你是一名友好自然的 AI 微信助手。使用中文简洁聊天,诚实说明自己是 AI;不发送思考过程、工具日志或其他人的私聊内容。',
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Turn the panel's model choice into a complete provider/model route.
83
+ *
84
+ * Absent or null means "follow the Host default" and yields {} -- the runtime then
85
+ * omits agentOptions and the Host's current selection is used. A partial selection
86
+ * is a mistake rather than an instruction, so it throws with a message the panel
87
+ * shows verbatim.
88
+ */
89
+ function modelRoute(model) {
90
+ if (model === undefined || model === null) return {};
91
+ if (typeof model !== 'object' || Array.isArray(model)) throw new Error('模型设置必须是对象或 null');
92
+ const provider = model.provider ? String(model.provider).trim() : '';
93
+ const id = model.model ? String(model.model).trim() : '';
94
+ if (!provider && !id) return {};
95
+ if (!provider) throw new Error('已选择模型但缺少服务商(provider)');
96
+ if (!id) throw new Error('已选择服务商但缺少模型(model)');
97
+ // 推理等级是同一个选择对象里的第三项。空串就是宿主的「服务商默认」,
98
+ // 落盘时干脆省掉这个键 —— 存一个空串只会让人以为设过什么。
99
+ const rawEffort = model.reasoningEffort;
100
+ const effort = rawEffort === undefined || rawEffort === null ? '' : String(rawEffort).trim();
101
+ assert(!effort || /^[A-Za-z0-9_.-]{1,40}$/.test(effort), '推理等级(reasoningEffort)取值不合法');
102
+ return { provider, model: id, ...(effort ? { reasoningEffort: effort } : {}) };
103
+ }
104
+
105
+ export function normalizeConfig(raw, filePath = defaultConfigPath()) {
106
+ assert(raw && typeof raw === 'object' && !Array.isArray(raw), '配置必须是 JSON 对象');
107
+ const base = dirname(resolve(filePath));
108
+ const absolute = value => isAbsolute(value) ? value : resolve(base, value);
109
+
110
+ // ── agent-wechat 守护进程 ─────────────────────────────────────────────
111
+ //
112
+ // 地址必须是本机回环。理由和 QQ 版一样:拿到 token 就等于能以这个微信
113
+ // 身份发消息、读全部聊天记录。把这样的接口暴露到网络上,风险远大于便利。
114
+ // 如果守护进程在别的机器上,正确做法是本机做 SSH 端口转发。
115
+ const wUrl = new URL(String(raw.wechat?.baseUrl ?? 'http://127.0.0.1:6174/v1'));
116
+ assert(['http:', 'https:'].includes(wUrl.protocol) && !wUrl.username && !wUrl.password && !wUrl.search && !wUrl.hash,
117
+ 'wechat.baseUrl 必须为无内嵌凭据的 HTTP(S) 地址');
118
+ assert(['127.0.0.1', 'localhost', '[::1]'].includes(wUrl.hostname),
119
+ 'wechat.baseUrl 请绑定本机 127.0.0.1 / localhost / ::1');
120
+ const rawToken = String(process.env.AGENT_WECHAT_TOKEN || raw.wechat?.token || '');
121
+ // 先验原文再 trim:反过来的话行尾换行会被 trim 掉,这条检查形同虚设。
122
+ // token 里混进换行通常是复制粘贴事故,带进去会让 Authorization 头非法。
123
+ assert(!/[\r\n]/.test(rawToken), 'wechat.token 不能包含换行或空白');
124
+ const wxToken = rawToken.trim();
125
+ assert(wxToken.length >= 16,
126
+ '请配置 agent-wechat 的 API token(wx tokens create 生成,至少 16 位)');
127
+
128
+ // accountId 允许留空:留空表示「用守护进程里当前在线的那个账号」。
129
+ // 首次安装时用户还没登录,不该逼他先填一个他看不到的 ID。
130
+ const rawAccount = String(raw.wechat?.accountId ?? raw.accountId ?? '').trim();
131
+ const accountId = rawAccount || '';
132
+ if (accountId) assert(/^account-\d{5,}$/.test(accountId), 'accountId 形如 account-12345678901234567890');
133
+
134
+ // 微信没有「自己的 wxid」这种先验知识:它由服务端给出。
135
+ // 这里保留 selfId 字段名以便下游复用,但允许为空,由 runtime 登录后填充。
136
+ const selfId = String(raw.selfId ?? '').trim();
137
+
138
+ const owners = (raw.ownerIds ?? []).map(x => toPeerId(x, '管理员微信号'));
139
+ const list = x => (x ?? []).map(y => toPeerId(y));
140
+ const access = {
141
+ privateMode: raw.access?.privateMode ?? 'all', groupMode: raw.access?.groupMode ?? 'all',
142
+ privateIds: list(raw.access?.privateIds), groupIds: list(raw.access?.groupIds),
143
+ blockedUsers: list(raw.access?.blockedUsers), blockedGroups: list(raw.access?.blockedGroups),
144
+ };
145
+ for (const mode of [access.privateMode, access.groupMode]) assert(['all', 'allowlist', 'disabled'].includes(mode), '访问模式必须为 all / allowlist / disabled');
146
+ const reply = {
147
+ private: raw.reply?.private ?? true,
148
+ // off = 只归档;mention = 仅被 @;smart = 感兴趣/与自己有关/被 @;all = 每条都回。
149
+ // 默认 off:群聊里默认不回。
150
+ // 群里消息又多又杂,默认「smart」会让新用户一装好就在一堆群里被认成话痨 ——
151
+ // 而且是拿她的身份在公开群里说话,风险比私聊大得多。要开自己开。
152
+ group: raw.reply?.group ?? 'off',
153
+ mentionSender: raw.reply?.mentionSender !== false,
154
+ // smart 模式的具体参数。放在 reply 段里,因为它们只影响「回不回」。
155
+ smartThreshold: integer(raw.reply?.smartThreshold, 3, 1, 10, '智能回复阈值'),
156
+ // 她的群昵称/别名,被叫到就回。微信号本身总是算在内。
157
+ selfNames: (Array.isArray(raw.reply?.selfNames) ? raw.reply.selfNames : [])
158
+ .map((x) => String(x ?? '').trim())
159
+ .filter((x) => x && x.length <= 20)
160
+ .slice(0, 10),
161
+ // 感兴趣的话题词;留空用内置默认表。
162
+ interests: (Array.isArray(raw.reply?.interests) ? raw.reply.interests : [])
163
+ .map((x) => String(x ?? '').trim())
164
+ .filter((x) => x && x.length <= 20)
165
+ .slice(0, 100),
166
+ // 是否让她从自己回过的话里学习话题。
167
+ learnInterests: raw.reply?.learnInterests !== false,
168
+ vision: raw.reply?.vision !== false,
169
+ maxImages: integer(raw.reply?.maxImages, 4, 0, 8, '单条消息最多图片数'),
170
+ maxChars: integer(raw.reply?.maxChars, 2000, 100, 4000, '回复字数'),
171
+ contextMessages: integer(raw.reply?.contextMessages, 20, 0, 100, '上下文条数'),
172
+ timeoutMs: integer(raw.reply?.timeoutMs, 180_000, 1000, 1_800_000, '回复超时'),
173
+ // 收到消息后等多久再合并回复。
174
+ // 默认 1200:推送到达就排一次短防抖,连发的几句合并成一轮。
175
+ // 设成 >= poll.intervalMs 等于关掉即时触发,回到「每轮轮询处理一次」。
176
+ debounceMs: integer(raw.reply?.debounceMs, 1200, 0, 600_000, '回复防抖'),
177
+ maxQueuePerConversation: integer(raw.reply?.maxQueuePerConversation, 20, 1, 100, '会话队列上限'),
178
+ maxQueuedTotal: integer(raw.reply?.maxQueuedTotal, 100, 1, 1000, '总队列上限'),
179
+ concurrency: integer(raw.reply?.concurrency, 4, 1, 16, '并发数'),
180
+ maxLiveSessions: integer(raw.reply?.maxLiveSessions, 64, 1, 1000, '活跃会话上限'),
181
+ // Link parsing. `linkParse` is a master switch: off means links are left as
182
+ // plain text and no network request is made for them.
183
+ linkParse: raw.reply?.linkParse !== false,
184
+ linkTimeoutMs: integer(raw.reply?.linkTimeoutMs, 20_000, 1000, 60_000, '链接解析超时'),
185
+ linkMaxImages: integer(raw.reply?.linkMaxImages, 9, 0, 20, '链接最多图片数'),
186
+ // 会话空闲多久后被回收(销毁 agent,释放内存)。
187
+ // 0 是「永不回收」的哨兵值:一直保留 agent,重启才清。
188
+ // 之前这里只允许 1 秒–24 小时,想永不回收就只能填 24 小时,
189
+ // 但那和「一直留着」是两回事 —— 隔一天照样会被销毁。
190
+ idleMs: integer(raw.reply?.idleMs, 1_800_000, 0, 86_400_000, '空闲会话清理时间'),
191
+ // 复读:她连续几轮说同一句话是很常见的问题。上下文里有她说过的原话,
192
+ // 但模型并不总会去比对,所以除了提示词约束外,这里再做一次机械检测。
193
+ // 命中就重问一次;重问后仍然重复就照发(宁可重复,也不能把回复吞掉)。
194
+ avoidRepeat: raw.reply?.avoidRepeat !== false,
195
+ // 是否按逗号分段。
196
+ //
197
+ // 默认开:真人聊天就是一句一发(「在呢,刚忙完,怎么了」)。
198
+ // 但代码、JSON、长英文句子里逗号很多,每个逗号切一刀会把内容切碎;
199
+ // 关掉之后只按换行分段,代价是逗号句会合并成一条 —— 这是用户要的效果。
200
+ commaSplit: raw.reply?.commaSplit !== false,
201
+ // 相似度阈值:2 字滑窗覆盖率达到这个值就算重复。
202
+ // 0.7 能抓住「加语气词 / 换标点 / 多一句尾巴」这类改写,同时不会把
203
+ // 「我在吃饭」和「我刚吃完饭」这种正常换说法误判成复读。
204
+ repeatThreshold: decimal(raw.reply?.repeatThreshold, 0.7, 0.5, 1, '复读判定阈值'),
205
+ // 共享会话模式:同对话复用同一 agent(固定 sessionId + resume),
206
+ // 她记住完整上下文,主动消息也共享聊天记忆。关闭则每次全新 agent。
207
+ // 与 emotion.perSession 联动:perSession=true 需要 sharedAgent 才能跨重启保持。
208
+ // 注意:必须放在这个对象字面量内部。曾经误放在 `};` 之后,语法合法但
209
+ // 变成了带标签的语句,reply.sharedAgent 永远是 undefined,功能整个失效。
210
+ sharedAgent: raw.reply?.sharedAgent === true,
211
+ };
212
+ assert(typeof reply.private === 'boolean' && ['off', 'mention', 'smart', 'all'].includes(reply.group), 'reply.private 必须为布尔值,reply.group 为 off / mention / smart / all');
213
+ const sections = raw.persona ?? '你是一名友好、自然的微信助手。用中文简洁聊天;诚实说明你是 AI。不要把思考过程、工具日志或其他人的私人信息发到聊天中。';
214
+ assert(typeof sections === 'string' && sections.length <= 12_000, 'persona 必须是最多 12000 字符的字符串');
215
+ return {
216
+ selfId, ownerIds: owners, dataDir: absolute(raw.dataDir ?? 'data'), configPath: resolve(filePath),
217
+ wechat: {
218
+ baseUrl: wUrl.href.replace(/\/$/, ''),
219
+ token: wxToken,
220
+ accountId,
221
+ timeoutMs: integer(raw.wechat?.timeoutMs, 20_000, 100, 120_000, 'API 超时'),
222
+ resumeEvents: raw.wechat?.resumeEvents !== false,
223
+ },
224
+ access, reply,
225
+ // 0 是显式哨兵值:永久保留,不按天清理,查询也不设时间下限。
226
+ retentionDays: integer(raw.retentionDays, 30, 0, 3650, '保留天数'),
227
+ // 不再需要轮询兜底:事件流带游标,断线重连会补齐漏掉的事件。
228
+ ownerHarnessTools: raw.ownerHarnessTools === true,
229
+ // A route is all-or-nothing: half of a selection would be handed to the Host as
230
+ // `agentOptions` and fail at request time, so an incomplete pair is rejected here
231
+ // while it is still a settings error the panel can report.
232
+ route: modelRoute(raw.model),
233
+ // 生图:走 DSH 的 provider 路由(默认 doubao/image-gen)。enabled 关掉时工具不注册。
234
+ image: {
235
+ enabled: raw.image?.enabled === true,
236
+ route: {
237
+ provider: String(raw.image?.provider ?? '').trim() || 'doubao',
238
+ model: String(raw.image?.model ?? '').trim() || 'image-gen',
239
+ },
240
+ timeoutMs: integer(raw.image?.timeoutMs, 120_000, 10_000, 600_000, '生图超时'),
241
+ maxPerTurn: integer(raw.image?.maxPerTurn, 3, 1, 6, '单轮最多生图数'),
242
+ },
243
+ persona: sections,
244
+ rate: {
245
+ // Per-segment pacing for multi-message replies.
246
+ segmentMinMs: integer(raw.rate?.segmentMinMs, 1000, 0, 30_000, '分段最小间隔'),
247
+ segmentMaxMs: integer(raw.rate?.segmentMaxMs, 10_000, 0, 60_000, '分段最大间隔'),
248
+ segmentPerCharMs: integer(raw.rate?.segmentPerCharMs, 60, 0, 500, '每字追加间隔'),
249
+ globalGapMs: integer(raw.rate?.globalGapMs, 1000, 0, 60_000, '全局发送间隔'),
250
+ peerGapMs: integer(raw.rate?.peerGapMs, 3000, 0, 60_000, '同会话发送间隔'),
251
+ maxPerMinute: integer(raw.rate?.maxPerMinute, 20, 1, 120, '每分钟发送上限'),
252
+ },
253
+ // Sticker library. `enabled` off means the tools are absent and nothing is
254
+ // collected; the folder on disk is left untouched either way.
255
+ // Realtime web search (Anysearch). Anonymous works; a key only raises quota.
256
+ // Virtual life: one generated week, reused until regenerated.
257
+ life: {
258
+ enabled: raw.life?.enabled !== false,
259
+ inject: raw.life?.inject !== false,
260
+ // 每周一自动生成新一周;关闭后只能从面板手动生成。
261
+ autoRefresh: raw.life?.autoRefresh !== false,
262
+ // Proactive messages ride the existing poll loop, so this is a switch and a
263
+ // cap rather than a schedule.
264
+ proactive: raw.life?.proactive === true,
265
+ proactivePrivate: raw.life?.proactivePrivate !== false,
266
+ proactiveGroup: raw.life?.proactiveGroup === true,
267
+ // 每天最多几次。实际次数按正态分布在 0..这个值之间抽,不是固定发满。
268
+ proactiveMaxPerDay: integer(raw.life?.proactiveMaxPerDay, 5, 0, 24, '每天最多几次主动消息'),
269
+ // 次数分布的离散程度,用「标准差 / 均值」表示。
270
+ // 0.1 很集中(几乎每天一样多),0.5 是标准钟形,1.0 接近均匀。
271
+ // 用比值而不是绝对值,换 maxPerDay 时松紧感觉保持一致。
272
+ proactiveSpread: decimal(raw.life?.proactiveSpread, 0.5, 0.05, 2, '主动消息次数离散度'),
273
+ // 两次主动消息之间至少隔多久。窗口数量由上面的最大值决定,
274
+ // 这个值保证它们不会挤在一起。
275
+ proactiveMinGapMinutes: integer(raw.life?.proactiveMinGapMinutes, 90, 10, 720, '主动消息最小间隔'),
276
+ // 时间随机化:窗口时间是模型按日程写的「大概这个点」,
277
+ // 如果每天都精确到同一分钟,几天就能被看出是程序发的。
278
+ // 偏移量由「日期 + 窗口 id」播种,当天固定、跨天不同、重启不变 ——
279
+ // 不能在轮询里现抽,否则 60 秒一次等于必然提前触发。
280
+ proactiveJitterMinutes: integer(raw.life?.proactiveJitterMinutes, 45, 0, 240, '主动消息时间随机幅度'),
281
+ // 到点后允许多久之内补发。随机化之后窗口是一个区间而不是一个点,
282
+ // 这个值决定区间的宽度。
283
+ proactiveGraceMinutes: integer(raw.life?.proactiveGraceMinutes, 30, 5, 180, '主动消息补发窗口'),
284
+ // 主动消息的内容方向。留空就完全按日程里的 intent 走。
285
+ // 非空时作为额外要求拼进提示词,用来长期约束她主动说话的主题 ——
286
+ // 比如「多聊生活小事,别总问我在干嘛」。
287
+ proactiveHint: String(raw.life?.proactiveHint ?? '').slice(0, 500),
288
+ // Per-conversation switches. An empty list means "no conversation", which is
289
+ // deliberate: the previous behaviour (most recently active chat) could message
290
+ // someone who never opted in.
291
+ proactiveTargets: (Array.isArray(raw.life?.proactiveTargets) ? raw.life.proactiveTargets : [])
292
+ .map((entry) => {
293
+ if (!entry || typeof entry !== 'object') return null;
294
+ const kind = entry.kind === 'group' ? 'group' : entry.kind === 'private' ? 'private' : '';
295
+ const peerId = String(entry.peerId ?? '').trim();
296
+ if (!kind || !/^\d{5,12}$/.test(peerId)) return null;
297
+ return { kind, peerId, enabled: entry.enabled !== false };
298
+ })
299
+ .filter(Boolean)
300
+ .slice(0, 200),
301
+ },
302
+ // 和风天气:给虚拟人生的穿搭和日程提供真实天气。
303
+ // 没配齐就当没启用,生成时退化成「按日期和季节猜」,不会因此失败。
304
+ // 内分泌是身体状态:只影响语气/精力,不参与人格、关系和安全规则的判定。
305
+ endocrine: {
306
+ enabled: raw.endocrine?.enabled === true,
307
+ inject: raw.endocrine?.inject !== false,
308
+ injectScope: ['owner-private', 'private', 'all'].includes(raw.endocrine?.injectScope)
309
+ ? raw.endocrine.injectScope : 'owner-private',
310
+ autoEvents: raw.endocrine?.autoEvents !== false,
311
+ autoFlare: raw.endocrine?.autoFlare === true,
312
+ moodFromEmotion: raw.endocrine?.moodFromEmotion !== false,
313
+ cycleLength: integer(raw.endocrine?.cycleLength, 28, 21, 45, '内分泌周期长度'),
314
+ },
315
+ weather: {
316
+ enabled: raw.weather?.enabled === true,
317
+ apiHost: String(raw.weather?.apiHost ?? '').trim(),
318
+ // 和风的 API Key 是短串,绝不该是一段文字。这里做形状校验,
319
+ // 因为出过一次事故:人格设定被当成 key 写进配置,面板还显示「已保存」。
320
+ apiKey: weatherApiKey(raw.weather?.apiKey ?? process.env.QWEATHER_API_KEY),
321
+ // 默认坐标刻意用美国白宫:公开地标,不代表任何真实用户的位置。
322
+ // 插件是公开分发的,默认值写成真实住址等于把位置随包发出去。
323
+ latitude: decimal(raw.weather?.latitude, 38.90, -90, 90, '纬度'),
324
+ longitude: decimal(raw.weather?.longitude, -77.04, -180, 180, '经度'),
325
+ city: String(raw.weather?.city ?? '华盛顿').slice(0, 40),
326
+ // 漏了这个字段会让 AbortSignal.timeout(undefined) 直接抛,
327
+ // 表现是「点生成就报错」,而且堆栈指向 weather.mjs 完全看不出是配置缺项。
328
+ timeoutMs: integer(raw.weather?.timeoutMs, 8000, 2000, 60_000, '天气超时'),
329
+ },
330
+ steam: {
331
+ // 默认关:没配 API Key 之前它什么也做不了,开着只会每轮多一次失败的网络请求。
332
+ enabled: raw.steam?.enabled === true,
333
+ // Steam Web API key 是 32 位十六进制。和 weatherApiKey 一样做形状校验:
334
+ // 把一整段说明文字粘贴进来是真实发生过的错误。
335
+ apiKey: (() => {
336
+ const v = String(process.env.STEAM_API_KEY || raw.steam?.apiKey || '').trim();
337
+ if (!v) return '';
338
+ // 接受 32 位十六进制;不符合就丢掉,不要带着一个注定 401 的值去请求。
339
+ return /^[0-9A-Fa-f]{32}$/.test(v) ? v : '';
340
+ })(),
341
+ // 没有「默认 SteamID」了:绑定只能在面板里做,查谁完全看绑定表。
342
+ // 留着这个字段会让「没绑定的人查到你」变成默认行为,那是隐私问题。
343
+ // 缓存时间可调。0 = 每次都查;上限 1 天,避免填个天文数字后状态永远不变。
344
+ cacheTtlMs: integer(raw.steam?.cacheTtlMs, 60_000, 0, 86_400_000, 'Steam 缓存时间'),
345
+ // 是否连游戏时长一起拉。关掉可以少一个请求,也少一点隐私暴露。
346
+ withGames: raw.steam?.withGames !== false,
347
+ // 是否注入到聊天上下文(她自己就知道你在玩什么)。
348
+ inject: raw.steam?.inject !== false,
349
+ // 主动消息时也注入,但提示词里明确要求「不要每次都提」。
350
+ injectProactive: raw.steam?.injectProactive !== false,
351
+ // 只在私聊注入。群里有别人,把「你老板在玩文明6」说出去很难收场。
352
+ privateOnly: raw.steam?.privateOnly !== false,
353
+ timeoutMs: integer(raw.steam?.timeoutMs, 6000, 2000, 30_000, 'Steam 超时'),
354
+ },
355
+
356
+ search: {
357
+ enabled: raw.search?.enabled !== false,
358
+ apiKey: String(process.env.ANYSEARCH_API_KEY || raw.search?.apiKey || ''),
359
+ timeoutMs: integer(raw.search?.timeoutMs, 30_000, 3000, 120_000, '搜索超时'),
360
+ },
361
+ memes: {
362
+ enabled: raw.memes?.enabled !== false,
363
+ maxEntries: integer(raw.memes?.maxEntries, 5000, 10, 100000, '表情包上限'),
364
+ autoCollect: raw.memes?.autoCollect === true,
365
+ autoCollectChance: Number.isFinite(Number(raw.memes?.autoCollectChance)) ? Math.min(1, Math.max(0, Number(raw.memes.autoCollectChance))) : 0.2,
366
+ requireApproval: raw.memes?.requireApproval !== false,
367
+ visionClassify: raw.memes?.visionClassify !== false,
368
+ autoSend: raw.memes?.autoSend === true,
369
+ autoSendChance: Number.isFinite(Number(raw.memes?.autoSendChance)) ? Math.min(1, Math.max(0, Number(raw.memes.autoSendChance))) : 0.15,
370
+ },
371
+ // 情感与关系:好感/亲密度双核 + 8 维情感 + 四阶段演进。
372
+ // 移植自 asakiyoshi/EmotionAI-Pro,去掉了只为命令界面存在的部分。
373
+ emotion: {
374
+ enabled: raw.emotion?.enabled === true,
375
+ // 默认按人累积:同一个人在两个群里还是同一个人。
376
+ // perSession=true 时改为按会话隔离。
377
+ perSession: raw.emotion?.perSession === true,
378
+ // 用模型判断这一轮的情感变化;关闭时退回关键词启发式(免费但粗糙)。
379
+ useModel: raw.emotion?.useModel !== false,
380
+ // 独立的情感分析模型;留空沿用主模型。
381
+ provider: String(raw.emotion?.provider ?? '').trim(),
382
+ model: String(raw.emotion?.model ?? '').trim(),
383
+ // 变化多大才值得记进长期记忆。
384
+ significanceThreshold: integer(raw.emotion?.significanceThreshold, 5, 1, 30, '情感记忆阈值'),
385
+ // 0=不注入 1=只给阶段 2=连数值一起给
386
+ privacyLevel: integer(raw.emotion?.privacyLevel, 1, 0, 2, '情感隐私级别'),
387
+ // 注入到人格提示里的情感描述开关。
388
+ inject: raw.emotion?.inject !== false,
389
+ // 面板显示最近多少条档案。
390
+ maxProfiles: integer(raw.emotion?.maxProfiles, 50, 1, 200, '情感档案上限'),
391
+ },
392
+
393
+ // 早先基于 Playwright 的字段(headless / channel / profileDir / 各种 selector)
394
+ // 已经没有任何代码读取,留着只会让人以为还要配浏览器。
395
+ // 念头:她自己想过、但没发出去的内容。
396
+ // 和记忆分开:记忆是「对方告诉我的事」,念头是「我自己在想什么」。
397
+ // 混在一起会让提示词分不清「他说过」和「我想过」。
398
+ thoughts: {
399
+ // 默认开:这个功能零额外模型调用(reasoning 本来就在事件里)。
400
+ enabled: raw.thoughts?.enabled !== false,
401
+ inject: raw.thoughts?.inject !== false,
402
+ // 每轮注入几条。太多会把人格层挤满。
403
+ limit: integer(raw.thoughts?.limit, 3, 0, 10, '念头注入条数'),
404
+ // 超过这个小时数的念头不再注入:三天前想的事和现在无关。
405
+ maxAgeHours: integer(raw.thoughts?.maxAgeHours, 48, 1, 720, '念头有效期(小时)'),
406
+ },
407
+
408
+ // 长期记忆:按「人」存,不按会话存。
409
+ // 同一个人在群里和私聊里是同一份记忆,这是这个功能的核心。
410
+ memory: {
411
+ enabled: raw.memory?.enabled === true,
412
+ // 半衰期:越久越难想起来,但不删除。
413
+ halfLifeDays: integer(raw.memory?.halfLifeDays, 30, 1, 3650, '记忆半衰期'),
414
+ // 每轮最多注入几条「事件」(事实不占这个额度)。
415
+ recallLimit: integer(raw.memory?.recallLimit, 4, 0, 20, '记忆召回条数'),
416
+ // 常驻事实条数。
417
+ factLimit: integer(raw.memory?.factLimit, 6, 0, 20, '常驻事实条数'),
418
+ // 命中阈值:越高越少提旧事。
419
+ minScore: (() => {
420
+ const n = Number(raw.memory?.minScore);
421
+ return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0.12;
422
+ })(),
423
+ // 每人每天最多记几条,防止把上下文塞满。
424
+ dailyQuota: integer(raw.memory?.dailyQuota, 12, 0, 100, '每日记忆配额'),
425
+ // 用模型判断「这轮值不值得记」;关闭则只用启发式。
426
+ useModel: raw.memory?.useModel === true,
427
+ // 是否把记忆注入到提示词。
428
+ inject: raw.memory?.inject !== false,
429
+ },
430
+ };
431
+ }
432
+
433
+ /**
434
+ * 判断一段内容像不像「被写坏的文件」。
435
+ *
436
+ * 断电后常见的损坏形状有两种:长度正常但全是 0x00,或者只剩一堆 NUL 字符。
437
+ * JSON.parse 对这两种都会抛 SyntaxError,但报错信息看不出根因,
438
+ * 所以这里单独识别一下,好给出「可能是断电导致」这种能直接行动的提示。
439
+ */
440
+ function looksCorrupted(text) {
441
+ if (!text) return true;
442
+ if (text.trim() === '') return false; // 空文件是「没写过」,不是损坏
443
+ // 全 0x00 或者有效字符极少
444
+ const printable = [...text].filter((c) => c >= ' ' || c === '\n' || c === '\r' || c === '\t').length;
445
+ return printable / text.length < 0.5;
446
+ }
447
+
448
+ export async function loadConfig(path = defaultConfigPath()) {
449
+ let text;
450
+ try { text = await readFile(path, 'utf8'); }
451
+ catch (error) {
452
+ if (error.code === 'ENOENT') {
453
+ // 带上 code:调用方要区分「还没配置」和其它读取失败。
454
+ // 前者是可恢复的首次安装状态(面板照常出现),后者必须继续抛。
455
+ const wrapped = new Error(`未找到配置 ${path}。请先运行 node cli.mjs setup。`);
456
+ wrapped.code = 'ENOENT';
457
+ throw wrapped;
458
+ }
459
+ throw new Error(`无法读取配置:${error.name}。检查文件权限。`);
460
+ }
461
+
462
+ let raw;
463
+ try {
464
+ raw = JSON.parse(text);
465
+ } catch (error) {
466
+ // 主文件解析失败时先试 .bak —— 原子写每次都会留一份上一版。
467
+ const bakPath = path + '.bak';
468
+ let recovered = null;
469
+ try {
470
+ const bakText = await readFile(bakPath, 'utf8');
471
+ recovered = JSON.parse(bakText);
472
+ } catch { /* 没有备份或备份也坏了 */ }
473
+
474
+ if (recovered) {
475
+ // 备份能用就继续跑,同时把坏文件改名留住,方便事后查。
476
+ try {
477
+ const { rename } = await import('node:fs/promises');
478
+ await rename(path, `${path}.corrupt-${Date.now()}`);
479
+ } catch { /* 改名失败不影响恢复 */ }
480
+ console.warn?.(`[dsh-wechat-access] 配置解析失败,已从 ${bakPath} 恢复。损坏的原文件已保留。`);
481
+ // 把备份写回主文件。
482
+ // 以前只把坏文件改名、用备份内容继续跑,但不写回 config.json ——
483
+ // 进程活着时用的是内存配置,下次启动主文件已经不在,走 ENOENT 分支,
484
+ // 用户看到「未找到配置」,得自己把 .bak 拷回来。
485
+ try {
486
+ const { writeFile, rename: renameFile } = await import('node:fs/promises');
487
+ const tmp = `${path}.restore-${Date.now()}.tmp`;
488
+ await writeFile(tmp, JSON.stringify(recovered, null, 2) + '\n', { mode: 0o600 });
489
+ await renameFile(tmp, path);
490
+ } catch { /* 写回失败不影响本次运行,下次启动仍可从 .bak 恢复 */ }
491
+ return normalizeConfig(recovered, path);
492
+ }
493
+
494
+ const hint = looksCorrupted(text)
495
+ ? '文件内容看起来全是 0x00 或不可打印字符,通常是断电/强制关机导致写盘未完成。'
496
+ : 'JSON 格式有误。';
497
+ throw new Error(`无法读取配置(${path}):${hint} 没有可用的 ${bakPath} 备份,需要手动修复或重新运行 node cli.mjs setup。`);
498
+ }
499
+ return normalizeConfig(raw, path);
500
+ }
501
+
502
+ export function allowConversation(config, kind, peerId, senderId) {
503
+ const a = config.access;
504
+ if (a.blockedUsers.includes(senderId)) return false;
505
+ if (kind === 'group' && a.blockedGroups.includes(peerId)) return false;
506
+ const mode = kind === 'private' ? a.privateMode : a.groupMode;
507
+ const ids = kind === 'private' ? a.privateIds : a.groupIds;
508
+ return mode === 'all' || (mode === 'allowlist' && ids.includes(peerId));
509
+ }