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.
- package/CHANGELOG.md +56 -0
- package/LICENSE +675 -0
- package/README.md +278 -2
- package/cordis.patch.yml +5 -0
- package/examples/config.example.json +98 -0
- package/index.mjs +123 -0
- package/lib/access.mjs +131 -0
- package/lib/anysearch.mjs +143 -0
- package/lib/capabilities.mjs +312 -0
- package/lib/client.js +2532 -0
- package/lib/config.mjs +509 -0
- package/lib/emotion-store.mjs +352 -0
- package/lib/emotion.mjs +428 -0
- package/lib/endocrine/LICENSE +21 -0
- package/lib/endocrine/README.md +39 -0
- package/lib/endocrine/diseases.js +791 -0
- package/lib/endocrine/engine.mjs +131 -0
- package/lib/endocrine/store.mjs +253 -0
- package/lib/endocrine/upstream.mjs +1230 -0
- package/lib/group-gate.mjs +305 -0
- package/lib/imagegen.mjs +360 -0
- package/lib/lock.mjs +204 -0
- package/lib/meme-classify.mjs +190 -0
- package/lib/memes.mjs +442 -0
- package/lib/memory.mjs +437 -0
- package/lib/normalize.mjs +230 -0
- package/lib/parser.mjs +602 -0
- package/lib/reply-settled.mjs +130 -0
- package/lib/runtime.mjs +3367 -0
- package/lib/startup.mjs +70 -0
- package/lib/steam-binding.mjs +144 -0
- package/lib/steam.mjs +334 -0
- package/lib/store.mjs +259 -0
- package/lib/thoughts.mjs +149 -0
- package/lib/time-context.mjs +182 -0
- package/lib/tools.mjs +583 -0
- package/lib/ui.mjs +997 -0
- package/lib/util.mjs +489 -0
- package/lib/virtual-life-generate.mjs +421 -0
- package/lib/virtual-life.mjs +971 -0
- package/lib/weather.mjs +172 -0
- package/lib/wechat-client.mjs +476 -0
- package/lib/wechat-events.mjs +269 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/lib/ui.mjs
ADDED
|
@@ -0,0 +1,997 @@
|
|
|
1
|
+
import { DEFAULT_INTERESTS } from './group-gate.mjs';
|
|
2
|
+
import { readFile, rename, open, copyFile, mkdir, stat, rm } from 'node:fs/promises';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { bootstrapConfig, normalizeConfig } from './config.mjs';
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 原子地写配置文件,并保留上一份备份。
|
|
11
|
+
*
|
|
12
|
+
* 直接 writeFile 有个致命弱点:断电或硬复位时,文件系统可能只把
|
|
13
|
+
* 「文件长度」这类元数据落盘,数据块还在缓存里 —— 恢复后得到的是一个
|
|
14
|
+
* 长度正常、内容全是 0x00 的文件。2026-11-10 那次 DSH 启动崩溃就是这么来的
|
|
15
|
+
* (profile 下三个配置文件全变 0),不是程序写坏,是断电。
|
|
16
|
+
*
|
|
17
|
+
* 这里做三件事:
|
|
18
|
+
* 1. 写到 .tmp,fsync 之后才 rename —— 数据真正落盘后才替换原文件,
|
|
19
|
+
* 中途断电最多丢掉新内容,旧文件仍然完整。
|
|
20
|
+
* 2. 替换前把旧文件复制成 .bak —— 万一新内容有问题还能回退。
|
|
21
|
+
* 3. 写完再 fsync 一次目录项(Windows 上 rename 已经足够原子)。
|
|
22
|
+
*/
|
|
23
|
+
async function atomicWriteJson(path, text) {
|
|
24
|
+
// 临时文件名必须唯一。以前是固定的 path + '.tmp':两个保存请求并发时,
|
|
25
|
+
// 后一个会先 rename 走同一个临时文件,前一个的 rename 就撞 ENOENT ——
|
|
26
|
+
// 面板上表现为「保存失败」,磁盘上则可能两份修改互相覆盖。
|
|
27
|
+
// 带随机后缀的临时名,写入后再 rename。
|
|
28
|
+
const tmp = `${path}.${randomUUID()}.tmp`;
|
|
29
|
+
const bak = path + '.bak';
|
|
30
|
+
|
|
31
|
+
// 先备份现有文件(不存在就跳过)。
|
|
32
|
+
try { await copyFile(path, bak); } catch (error) {
|
|
33
|
+
// 首次创建时没有旧文件,ENOENT 属于正常。其它错误(文件被占用等)以前被
|
|
34
|
+
// 一起吞掉,结果是一次没有备份的写入被当成成功。
|
|
35
|
+
if (error?.code !== 'ENOENT') console.warn?.(`[dsh-wechat-access] 备份 ${bak} 失败:${error?.code ?? error}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const handle = await open(tmp, 'w');
|
|
39
|
+
try {
|
|
40
|
+
await handle.writeFile(text, 'utf8');
|
|
41
|
+
// fsync 把数据从 OS 缓存刷到磁盘。跳过这一步等于白写临时文件。
|
|
42
|
+
await handle.sync();
|
|
43
|
+
} catch (error) {
|
|
44
|
+
// 写一半失败(磁盘满、权限):临时文件是这次唯一产生的垃圾,顺手清掉。
|
|
45
|
+
try { await handle.close(); } catch { /* 关不掉也只能算了 */ }
|
|
46
|
+
try { await rm(tmp, { force: true }); } catch { /* 清不掉不影响把错误抛上去 */ }
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
await handle.close();
|
|
50
|
+
try { await rename(tmp, path); }
|
|
51
|
+
catch (error) { try { await rm(tmp, { force: true }); } catch { /* 同上 */ } throw error; }
|
|
52
|
+
}
|
|
53
|
+
// 配置写入必须串行。
|
|
54
|
+
//
|
|
55
|
+
// /config 与 /life/targets 都是「读全量 → 改几个字段 → 写回全量」。两个请求
|
|
56
|
+
// 并发(双击保存、两个标签页、保存的同时点了「同步勾选」)时,两边的读会拿到
|
|
57
|
+
// 同一份旧内容,后写的那份把先写的改动整段抹掉 —— 用户看到的是「设置保存了但
|
|
58
|
+
// 刷新又变回去」。唯一临时文件名只解决了文件损坏,解决不了这种逻辑层的丢更新。
|
|
59
|
+
//
|
|
60
|
+
// 单进程单线程下,用一条 Promise 链把所有写操作排成队就够了。
|
|
61
|
+
let writeChain = Promise.resolve();
|
|
62
|
+
function serializeWrite(task) {
|
|
63
|
+
const run = writeChain.then(task, task);
|
|
64
|
+
// 链本身不能因为某次失败而断掉,否则后续写入永远不再执行。
|
|
65
|
+
writeChain = run.then(() => {}, () => {});
|
|
66
|
+
return run;
|
|
67
|
+
}
|
|
68
|
+
const PREFIX = '/dsh-wechat/api';
|
|
69
|
+
|
|
70
|
+
function json(res, code, body) {
|
|
71
|
+
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
72
|
+
res.end(JSON.stringify(body));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* 本机访问要按 **TCP 对端地址** 判断,不能看 Host 头。
|
|
77
|
+
*
|
|
78
|
+
* 以前这里读 req.headers.host:请求只要把 Host 写成 127.0.0.1,
|
|
79
|
+
* 配置读写、改好感、导入表情目录、/state 就全都放行。
|
|
80
|
+
* Host 是客户端自己写的,用它当来源校验等于没校验 ——
|
|
81
|
+
* 能连上端口的非浏览器客户端、以及把 Host 改写成回环的反向代理,都能绕过。
|
|
82
|
+
*/
|
|
83
|
+
function isLoopback(req) {
|
|
84
|
+
const addr = String(req.socket?.remoteAddress ?? '').toLowerCase();
|
|
85
|
+
// ::ffff:127.0.0.1 是 IPv4 映射到 IPv6 的常见形态
|
|
86
|
+
const normalized = addr.startsWith('::ffff:') ? addr.slice(7) : addr;
|
|
87
|
+
return normalized === '127.0.0.1' || normalized === '::1' || normalized === 'localhost';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 面板 API 是否可信。
|
|
92
|
+
*
|
|
93
|
+
* 两道条件都要满足:
|
|
94
|
+
* 1. TCP 对端是本机回环(真正的来源);
|
|
95
|
+
* 2. Host 头也指向回环(挡住 DNS rebinding:域名解析到 127.0.0.1 时
|
|
96
|
+
* 对端地址确实是本机,但 Host 是攻击者的域名)。
|
|
97
|
+
*/
|
|
98
|
+
function hostIsLoopback(req) {
|
|
99
|
+
const host = String(req.headers?.host ?? '').toLowerCase();
|
|
100
|
+
const h = host.startsWith('[') ? host.slice(0, host.indexOf(']') + 1) : host.split(':')[0];
|
|
101
|
+
return h === '127.0.0.1' || h === 'localhost' || h === '[::1]' || h === '::1';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function trusted(req) {
|
|
105
|
+
if (isLoopback(req) && hostIsLoopback(req)) return true;
|
|
106
|
+
// socket 判断已经挡住外部来源;下面这段只用于「本机来源但 Host 不是回环」的
|
|
107
|
+
// 场景(例如通过 127.0.0.1 的端口映射访问),仍然要求 Origin 也指向回环。
|
|
108
|
+
if (!isLoopback(req)) return false;
|
|
109
|
+
const origin = String(req.headers?.origin ?? '');
|
|
110
|
+
try {
|
|
111
|
+
const url = new URL(origin);
|
|
112
|
+
return ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
|
|
113
|
+
} catch { return false; }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function readBody(req) {
|
|
117
|
+
const chunks = [];
|
|
118
|
+
let length = 0;
|
|
119
|
+
for await (const chunk of req) {
|
|
120
|
+
length += chunk.length;
|
|
121
|
+
if (length > 64 * 1024) throw new Error('请求体过大');
|
|
122
|
+
chunks.push(chunk);
|
|
123
|
+
}
|
|
124
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const PATCHABLE = {
|
|
128
|
+
reply: ['private', 'group', 'maxChars', 'contextMessages', 'linkParse', 'linkMaxImages', 'smartThreshold', 'selfNames', 'interests', 'learnInterests', 'idleMs', 'maxLiveSessions', 'debounceMs', 'avoidRepeat', 'repeatThreshold', 'mentionSender', 'maxImages', 'vision', 'timeoutMs', 'commaSplit', 'sharedAgent'],
|
|
129
|
+
access: ['privateMode', 'groupMode', 'privateIds', 'groupIds', 'blockedUsers', 'blockedGroups'],
|
|
130
|
+
wechat: ['baseUrl', 'token', 'accountId', 'timeoutMs', 'resumeEvents'],
|
|
131
|
+
poll: ['enabled', 'intervalMs', 'count'],
|
|
132
|
+
rate: ['segmentMinMs', 'segmentMaxMs', 'segmentPerCharMs', 'globalGapMs', 'peerGapMs', 'maxPerMinute'],
|
|
133
|
+
memes: ['enabled', 'maxEntries', 'autoCollect', 'autoCollectChance', 'requireApproval', 'visionClassify', 'autoSend', 'autoSendChance'],
|
|
134
|
+
search: ['enabled', 'apiKey', 'timeoutMs'],
|
|
135
|
+
life: ['enabled', 'inject', 'autoRefresh', 'proactive', 'proactivePrivate', 'proactiveGroup', 'proactiveMaxPerDay', 'proactiveSpread', 'proactiveMinGapMinutes', 'proactiveJitterMinutes', 'proactiveGraceMinutes', 'proactiveHint', 'proactiveTargets'],
|
|
136
|
+
weather: ['enabled', 'apiHost', 'apiKey', 'latitude', 'longitude', 'city', 'timeoutMs'],
|
|
137
|
+
// Steam:缓存时间可调是用户明确要求的功能 —— 调试时想看实时状态,
|
|
138
|
+
// 正常使用时又不想每条消息都打一次 API。
|
|
139
|
+
steam: ['enabled', 'apiKey', 'cacheTtlMs', 'withGames', 'inject', 'injectProactive', 'privateOnly', 'timeoutMs'],
|
|
140
|
+
// 生图:provider/model 是路由,改了要重启;enabled 和超时每次调用都重新读。
|
|
141
|
+
image: ['enabled', 'provider', 'model', 'timeoutMs', 'maxPerTurn'],
|
|
142
|
+
// image 是嵌套对象:pick() 是浅拷贝,登记键名就会把整个子对象带过去。
|
|
143
|
+
emotion: ['enabled', 'perSession', 'useModel', 'provider', 'model', 'significanceThreshold', 'privacyLevel', 'inject', 'maxProfiles'],
|
|
144
|
+
memory: ['enabled', 'halfLifeDays', 'recallLimit', 'factLimit', 'minScore', 'dailyQuota', 'useModel', 'inject'],
|
|
145
|
+
// 念头:config.mjs 与 runtime 的热重载都早就有它,只有这里漏了 ——
|
|
146
|
+
// 漏了之后面板既读不到、也存不进去,改了等于没改。
|
|
147
|
+
thoughts: ['enabled', 'inject', 'limit', 'maxAgeHours'],
|
|
148
|
+
endocrine: ['enabled', 'inject', 'injectScope', 'autoEvents', 'autoFlare', 'moodFromEmotion', 'cycleLength'],
|
|
149
|
+
|
|
150
|
+
// root 只放「没有独立分段」的散字段。曾经这里也列了 weather/life/memes 等,
|
|
151
|
+
// 但那些字段本来就有自己的分段;两边都登记会让 root 先做一次整体替换,
|
|
152
|
+
// 把分段里没有的键(比如 weather.apiKey)直接抹掉。
|
|
153
|
+
root: ['ownerIds', 'persona', 'retentionDays', 'ownerHarnessTools', 'model'],
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
function pick(source, keys) {
|
|
157
|
+
const out = {};
|
|
158
|
+
if (!source || typeof source !== 'object') return out;
|
|
159
|
+
for (const key of keys) if (key in source) out[key] = source[key];
|
|
160
|
+
return out;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 把密钥换成「是否已保存」的标记,绝不把明文发给浏览器。
|
|
165
|
+
*
|
|
166
|
+
* 面板需要知道「有没有存过 key」,否则用户看不出自己填的到底保存没保存;
|
|
167
|
+
* 但它不需要知道 key 是什么。之前这里直接把 raw.weather 整个回传,
|
|
168
|
+
* 明文 apiKey 会出现在 /state 的响应里,任何能读这个接口的人都拿得到。
|
|
169
|
+
*/
|
|
170
|
+
function maskSecret(section, field = 'apiKey') {
|
|
171
|
+
if (!section || typeof section !== 'object') return {};
|
|
172
|
+
const { [field]: secret, ...rest } = section;
|
|
173
|
+
const flag = 'has' + field.charAt(0).toUpperCase() + field.slice(1);
|
|
174
|
+
return { ...rest, [flag]: Boolean(String(secret ?? '').trim()) };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function publicState(runtime, raw) {
|
|
178
|
+
return {
|
|
179
|
+
ok: true,
|
|
180
|
+
selfId: raw.selfId,
|
|
181
|
+
// 还没有 selfId:面板渲染「未连接」那一屏而不是完整设置。
|
|
182
|
+
loginPending: raw.loginPending === true,
|
|
183
|
+
connected: Boolean(runtime?.connected),
|
|
184
|
+
liveSessions: runtime?.sessions?.size ?? 0,
|
|
185
|
+
configPath: runtime?.config?.configPath,
|
|
186
|
+
config: {
|
|
187
|
+
reply: raw.reply ?? {},
|
|
188
|
+
// 群聊判定用的默认兴趣表,面板要能展示「实际生效的是什么」
|
|
189
|
+
groupGate: { defaultInterests: DEFAULT_INTERESTS },
|
|
190
|
+
access: raw.access ?? {},
|
|
191
|
+
// token 是 agent-wechat 的访问票据,和 apiKey 同级。
|
|
192
|
+
wechat: { ...raw.wechat, token: raw.wechat?.token ? '••••••' : '' },
|
|
193
|
+
poll: raw.poll ?? {},
|
|
194
|
+
rate: raw.rate ?? {},
|
|
195
|
+
ownerIds: raw.ownerIds ?? [],
|
|
196
|
+
persona: raw.persona ?? '',
|
|
197
|
+
// 0 是「永久保存」的哨兵值,必须原样回传给面板,不能回退成 30。
|
|
198
|
+
retentionDays: raw.retentionDays ?? 30,
|
|
199
|
+
ownerHarnessTools: raw.ownerHarnessTools === true,
|
|
200
|
+
// Absent means "follow the Host default"; the panel renders that as a choice.
|
|
201
|
+
model: raw.model ?? null,
|
|
202
|
+
memes: raw.memes ?? {},
|
|
203
|
+
search: maskSecret(raw.search),
|
|
204
|
+
weather: maskSecret(raw.weather),
|
|
205
|
+
steam: maskSecret(raw.steam),
|
|
206
|
+
image: raw.image ?? {},
|
|
207
|
+
life: raw.life ?? {},
|
|
208
|
+
emotion: raw.emotion ?? {},
|
|
209
|
+
memory: raw.memory ?? {},
|
|
210
|
+
thoughts: raw.thoughts ?? {},
|
|
211
|
+
endocrine: raw.endocrine ?? {},
|
|
212
|
+
},
|
|
213
|
+
// 主动消息的运行状态。面板要能直接看到「今天发了几次、还剩几次、下次窗口几点」,
|
|
214
|
+
// 否则只能翻 debug.log 猜她为什么没主动说话。
|
|
215
|
+
proactive: runtime?.proactiveSnapshot?.() ?? { enabled: false },
|
|
216
|
+
poll: runtime ? {
|
|
217
|
+
enabled: runtime.config?.poll?.enabled !== false,
|
|
218
|
+
intervalMs: runtime.config?.poll?.intervalMs ?? null,
|
|
219
|
+
runs: runtime.pollRuns ?? 0,
|
|
220
|
+
lastPollAt: runtime.lastPollAt ?? null,
|
|
221
|
+
} : null,
|
|
222
|
+
endocrineEnabled: Boolean(runtime?.endocrine),
|
|
223
|
+
runtimeClosed: Boolean(runtime?.closed),
|
|
224
|
+
bootError: runtime?.bootError ? {
|
|
225
|
+
code: runtime.bootErrorCode || 'STARTUP',
|
|
226
|
+
stage: runtime.bootStage || '',
|
|
227
|
+
message: runtime.bootError,
|
|
228
|
+
...(runtime.lockOwner ? { lockOwner: runtime.lockOwner } : {}),
|
|
229
|
+
} : null,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function registerUi(ctx, runtime, configPath) {
|
|
234
|
+
const webServer = ctx.get?.('webServer') ?? ctx.webServer;
|
|
235
|
+
if (!webServer || typeof webServer.register !== 'function') return () => {};
|
|
236
|
+
const disposers = [];
|
|
237
|
+
|
|
238
|
+
const register = (path, handler) => {
|
|
239
|
+
disposers.push(webServer.register({
|
|
240
|
+
kind: 'exact',
|
|
241
|
+
path,
|
|
242
|
+
handler: async (req, res) => {
|
|
243
|
+
try { await handler(req, res); }
|
|
244
|
+
catch (error) { try { json(res, 500, { ok: false, error: String(error?.message ?? error) }); } catch {} }
|
|
245
|
+
},
|
|
246
|
+
}));
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const loadRaw = async () => JSON.parse(await readFile(configPath, 'utf8'));
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* 读配置;文件还不存在时返回一份模板并标记 missing。
|
|
253
|
+
*
|
|
254
|
+
* 首次安装就是这个状态:插件被装上了,但用户还没跑过 setup。
|
|
255
|
+
* 以前 apply() 会因此直接抛异常,宿主跳过整个 bundle,面板根本不出现 ——
|
|
256
|
+
* 新用户只能看到一行 stderr,连该填什么都不知道。
|
|
257
|
+
* 现在面板照常挂上,只是渲染成「生成配置」的引导页。
|
|
258
|
+
*/
|
|
259
|
+
const exists = async (path) => {
|
|
260
|
+
try { await stat(path); return true; } catch (error) { if (error?.code === 'ENOENT') return false; throw error; }
|
|
261
|
+
};
|
|
262
|
+
const loadRawOrTemplate = async () => {
|
|
263
|
+
try { return { raw: await loadRaw(), missing: false }; }
|
|
264
|
+
catch (error) {
|
|
265
|
+
if (error?.code === 'ENOENT') return { raw: bootstrapConfig({ accountId: '' }), missing: true };
|
|
266
|
+
// 文件在、但 JSON 坏了(手改漏个引号、编辑器写一半断电、磁盘满留下半截)。
|
|
267
|
+
// 以前这里直接把 SyntaxError 往上抛,/state 返回 500,面板拿不到 state 就
|
|
268
|
+
// 整屏空白 —— 用户既看不到哪一行错了,也没有任何入口去修,只能自己找到
|
|
269
|
+
// config.json 手改。备份坏文件、按模板重建、
|
|
270
|
+
// 并把「配置已损坏」带回面板明说,至少人能看见发生了什么。
|
|
271
|
+
if (error instanceof SyntaxError) {
|
|
272
|
+
const backup = `${configPath}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
273
|
+
try { await rename(configPath, backup); } catch { /* 备份失败也不该让面板打不开 */ }
|
|
274
|
+
return { raw: bootstrapConfig({ accountId: '' }), missing: true, corrupt: { backup, message: String(error.message ?? error) } };
|
|
275
|
+
}
|
|
276
|
+
throw error;
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
register(`${PREFIX}/state`, async (req, res) => {
|
|
281
|
+
if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
282
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
283
|
+
const { raw, missing, corrupt } = await loadRawOrTemplate();
|
|
284
|
+
raw.__path = configPath;
|
|
285
|
+
const state = publicState(runtime, raw);
|
|
286
|
+
// runtimeReady 是面板判断「要不要提示重载」的唯一依据:
|
|
287
|
+
// runtime 为 null 说明插件只是挂了面板,微信接入并没有在跑。
|
|
288
|
+
return json(res, 200, {
|
|
289
|
+
...state,
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
missingConfig: missing,
|
|
293
|
+
// 配置文件损坏过:面板要明说「旧的已备份到哪」,否则用户会以为设置被吞了。
|
|
294
|
+
...(corrupt ? { corruptConfig: corrupt } : {}),
|
|
295
|
+
runtimeReady: Boolean(runtime),
|
|
296
|
+
// 首次登录已经认到账号:配置已写回,但运行中的 runtime 还是旧 selfId,
|
|
297
|
+
// 必须重启 DSH 才会真正接上。面板据此渲染醒目提示。
|
|
298
|
+
...(runtime?.needsRestart ? { needsRestart: runtime.needsRestart } : {}),
|
|
299
|
+
configPath,
|
|
300
|
+
});
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
// 首次配置:只问守护进程地址与管理员号。
|
|
304
|
+
// 面板里不让用户手写密钥 —— 新用户根本没有这些值,让他填等于劝退。
|
|
305
|
+
register(`${PREFIX}/bootstrap`, async (req, res) => {
|
|
306
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
307
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
308
|
+
let body;
|
|
309
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
310
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
311
|
+
// 首次配置只要求填 agent-wechat 的 token:账号 ID 由守护进程给出,
|
|
312
|
+
// 账号 ID 由守护进程给出,用户不需要先知道。
|
|
313
|
+
const selfId = String(body.selfId ?? '').trim();
|
|
314
|
+
const owners = (Array.isArray(body.ownerIds) ? body.ownerIds : [body.ownerId])
|
|
315
|
+
.map((value) => String(value ?? '').trim()).filter(Boolean);
|
|
316
|
+
const template = bootstrapConfig({ selfId, ownerIds: owners });
|
|
317
|
+
// selfId 留空 = 待登录。normalizeConfig 认这个标记,不会报「必须是 5–12 位数字」。
|
|
318
|
+
if (!selfId) template.loginPending = true;
|
|
319
|
+
// 先用 normalizeConfig 过一遍:非法号码在这里就报错,而不是写进磁盘等着插件起不来。
|
|
320
|
+
try { normalizeConfig(template, configPath); }
|
|
321
|
+
catch (error) { return json(res, 400, { ok: false, error: error.message }); }
|
|
322
|
+
// 已经存在就别覆盖:可能是两个标签页都打开了首次配置那一屏。
|
|
323
|
+
// 检查必须和写入放在同一个队列里 —— 否则两个标签页同时点「生成配置」,
|
|
324
|
+
// 两边都能通过检查,后写的那份覆盖前一份的 token,先打开的那个
|
|
325
|
+
// 面板从此扫不上码。
|
|
326
|
+
return serializeWrite(async () => {
|
|
327
|
+
if (await exists(configPath)) {
|
|
328
|
+
return json(res, 409, { ok: false, error: '配置已经存在了:' + configPath + '。刷新面板即可。', missingConfig: false });
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
await mkdir(dirname(configPath), { recursive: true, mode: 0o700 });
|
|
332
|
+
await atomicWriteJson(configPath, JSON.stringify(template, null, 2) + '\n');
|
|
333
|
+
} catch (error) {
|
|
334
|
+
return json(res, 500, { ok: false, error: '写入配置失败:' + String(error?.message ?? error) });
|
|
335
|
+
}
|
|
336
|
+
return json(res, 200, { ok: true, configPath });
|
|
337
|
+
});
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
register(`${PREFIX}/config`, async (req, res) => {
|
|
341
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
342
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
343
|
+
// 从读文件到写回盘之间不能有第二个保存插进来,否则先写的那份会被整段抹掉。
|
|
344
|
+
// 解析请求体留在锁外:那是纯 CPU、和磁盘无关,没必要占着队列。
|
|
345
|
+
// 和 /bootstrap 以及其余 8 个 POST 端点保持一致:畸形请求体回 400,
|
|
346
|
+
// 而不是让 JSON.parse 的 SyntaxError 冒到外层兜底变成 500。
|
|
347
|
+
let body;
|
|
348
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
349
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
350
|
+
const patch = body == null ? {} : (body.patch ?? body);
|
|
351
|
+
return serializeWrite(() => saveConfig(patch, res));
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
async function saveConfig(patch, res) {
|
|
355
|
+
// 还没有配置文件时,保存只能走 /bootstrap:面板里根本没有 selfId 输入框,
|
|
356
|
+
// 拿一份空模板去过 normalizeConfig 只会得到一句「token 未配置」。
|
|
357
|
+
const loaded = await loadRawOrTemplate();
|
|
358
|
+
if (loaded.missing) {
|
|
359
|
+
return json(res, 409, { ok: false, error: '还没有配置文件。请先在页面顶部填写守护进程地址和 token,点「生成配置」。', missingConfig: true });
|
|
360
|
+
}
|
|
361
|
+
const raw = loaded.raw;
|
|
362
|
+
for (const key of PATCHABLE.root) if (key in patch) raw[key] = patch[key];
|
|
363
|
+
// Every section that has a whitelist is patchable. Deriving the list from
|
|
364
|
+
// PATCHABLE means a section can never be silently left out of a save again.
|
|
365
|
+
const sections = Object.keys(PATCHABLE).filter((key) => key !== 'root');
|
|
366
|
+
for (const section of sections) {
|
|
367
|
+
const incoming = pick(patch[section], PATCHABLE[section]);
|
|
368
|
+
if (Object.keys(incoming).length) raw[section] = { ...(raw[section] ?? {}), ...incoming };
|
|
369
|
+
}
|
|
370
|
+
if (Array.isArray(raw.ownerIds)) raw.ownerIds = raw.ownerIds.map(String);
|
|
371
|
+
if (raw.access) {
|
|
372
|
+
for (const key of ['privateIds', 'groupIds', 'blockedUsers', 'blockedGroups']) {
|
|
373
|
+
if (Array.isArray(raw.access[key])) raw.access[key] = raw.access[key].map(String);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
let normalized;
|
|
378
|
+
try { normalized = normalizeConfig(raw, configPath); }
|
|
379
|
+
catch (error) { return json(res, 400, { ok: false, error: error.message }); }
|
|
380
|
+
|
|
381
|
+
const { __path, ...persisted } = raw;
|
|
382
|
+
await atomicWriteJson(configPath, JSON.stringify(persisted, null, 2) + '\n');
|
|
383
|
+
|
|
384
|
+
// Hot-apply the parts the running runtime reads per message; client wiring needs a reload.
|
|
385
|
+
let hot = true;
|
|
386
|
+
// B19:工具注册与 image.enabled 相关,必须在覆盖 config 之前先记下来 ——
|
|
387
|
+
// 覆盖之后两边永远相等,判断就成了死代码(B15 踩过同一个坑)。
|
|
388
|
+
const imageWasEnabled = runtime?.config ? runtime.config.image?.enabled === true : false;
|
|
389
|
+
// sharedAgent 变化必须 drop 所有会话:旧 agent 的 sessionId 格式不同(UUID vs 稳定),
|
|
390
|
+
// 不 dispose 就会一直复用旧 agent,新模式不生效。
|
|
391
|
+
const sharedAgentWas = runtime?.config ? runtime.config.reply?.sharedAgent === true : false;
|
|
392
|
+
const personaWas = runtime?.config ? String(runtime.config.persona ?? "") : null;
|
|
393
|
+
if (runtime?.config) {
|
|
394
|
+
runtime.config.reply = normalized.reply;
|
|
395
|
+
runtime.config.access = normalized.access;
|
|
396
|
+
runtime.config.persona = normalized.persona;
|
|
397
|
+
runtime.config.ownerIds = normalized.ownerIds;
|
|
398
|
+
runtime.config.retentionDays = normalized.retentionDays;
|
|
399
|
+
if (runtime.store) {
|
|
400
|
+
runtime.store.retentionDays = normalized.retentionDays;
|
|
401
|
+
// 从「永久」切回按天时,超期文件应立刻清掉,而不是等下一个 60s 周期。
|
|
402
|
+
runtime.store.prune().catch(() => {});
|
|
403
|
+
}
|
|
404
|
+
const wechatChanged = normalized.wechat.baseUrl !== runtime.config.wechat.baseUrl
|
|
405
|
+
|| normalized.wechat.token !== runtime.config.wechat.token
|
|
406
|
+
|| normalized.wechat.accountId !== runtime.config.wechat.accountId;
|
|
407
|
+
hot = !wechatChanged;
|
|
408
|
+
// Behavioural flags do not rewire the child process, so they can hot-apply.
|
|
409
|
+
const intervalChanged = (runtime.config.poll?.intervalMs ?? 60_000) !== normalized.poll.intervalMs
|
|
410
|
+
|| (runtime.config.poll?.enabled !== false) !== normalized.poll.enabled;
|
|
411
|
+
runtime.config.poll = normalized.poll;
|
|
412
|
+
// 动态调度每次 tick 都重新读配置,直接替换即可即时生效。
|
|
413
|
+
// 念头与其它基础设置:同样每次用的时候现读 runtime.config,直接替换即可。
|
|
414
|
+
// 以前这两段连白名单都没有,面板改了也存不进 —— 现在补上了,热更新也要跟上。
|
|
415
|
+
runtime.config.thoughts = normalized.thoughts;
|
|
416
|
+
runtime.config.endocrine = normalized.endocrine;
|
|
417
|
+
// 情感配置每次读取,直接替换即可;开关变化由 runtime 侧判断。
|
|
418
|
+
runtime.config.emotion = normalized.emotion;
|
|
419
|
+
runtime.config.memory = normalized.memory;
|
|
420
|
+
// 启动时关、现在打开 → 要真的把 store 建出来,否则开关开了也不记。
|
|
421
|
+
// 不 await:面板保存不该因为补建存储而变慢;失败只记日志。
|
|
422
|
+
runtime.applyHotConfig?.(normalized).catch((error) => {
|
|
423
|
+
try { runtime.logger?.warn?.('热更新补建存储失败:' + String(error?.message ?? error)); } catch {}
|
|
424
|
+
});
|
|
425
|
+
// 虚拟人生 / 主动消息:tickProactive 每次 tick 都重新读 runtime.config.life,
|
|
426
|
+
// 直接替换即可即时生效。之前漏了这一行,面板改完写进了磁盘,
|
|
427
|
+
// 但运行中的实例还拿着旧对象,开关和上限都要重启才生效。
|
|
428
|
+
runtime.config.life = normalized.life;
|
|
429
|
+
// 生图:runtime.generateImageFor 每次调用都重新读 this.config.image,
|
|
430
|
+
// 开关/数量/超时直接替换即可。
|
|
431
|
+
//
|
|
432
|
+
// 这里**不需要** dropSessions:生图走的是临时 agent(imagegen.mjs 里
|
|
433
|
+
// 每次 agents.create 一个新的、用完立刻 dispose),不在 this.sessions 里,
|
|
434
|
+
// 所以不存在「旧路由的会话残留」。反倒是 dropSessions 会清掉所有聊天会话,
|
|
435
|
+
// 让每个正在聊的人丢掉上下文 —— 用一个高代价操作去解决一个不存在的问题。
|
|
436
|
+
runtime.config.image = normalized.image;
|
|
437
|
+
// 开关状态变了就要重建工具集:注册表是启动时建的,不重建的话
|
|
438
|
+
// 打开生图她也调不到 wx_generate_image,关掉之后工具又还留着。
|
|
439
|
+
if ((normalized.image?.enabled === true) !== imageWasEnabled) {
|
|
440
|
+
try { runtime.reregisterTools?.(); } catch (error) {
|
|
441
|
+
runtime.logger?.warn?.('生图工具重注册失败:' + String(error?.message ?? error));
|
|
442
|
+
}
|
|
443
|
+
// B13:只重建工具集还不够。
|
|
444
|
+
//
|
|
445
|
+
// 会话在创建时就把 restrict 白名单和人格文案定死了:关掉生图后,
|
|
446
|
+
// 已经在聊的会话人格里还写着「你可以拍照」,工具却已注销;
|
|
447
|
+
// 打开生图后,旧会话的白名单里没有 wx_generate_image,人格也没提,
|
|
448
|
+
// 她仍然拍不了。
|
|
449
|
+
//
|
|
450
|
+
// 这两者都没法原地改,只能让会话重建。代价是这个会话的上下文重来一次,
|
|
451
|
+
// 但用户在改开关时本来就预期行为会变;比「改了没反应」好。
|
|
452
|
+
try {
|
|
453
|
+
const dropped = runtime.dropSessions?.() ?? 0;
|
|
454
|
+
if (dropped) runtime.logger?.info?.('生图开关变化:已重建 ' + dropped + ' 个会话以应用新能力');
|
|
455
|
+
} catch (error) {
|
|
456
|
+
runtime.logger?.warn?.('重建会话失败:' + String(error?.message ?? error));
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
// 表情包:runtime 每次收到图片都重新读 this.config.memes,
|
|
460
|
+
// 直接替换即可。autoSend / autoCollect 这类开关不必重启。
|
|
461
|
+
runtime.config.memes = normalized.memes;
|
|
462
|
+
// 搜索:AnySearchClient 在构造时拷贝了 apiKey/timeoutMs,
|
|
463
|
+
// 光换 config 不够,得同时写回实例字段,否则改了 key 仍然用旧的。
|
|
464
|
+
runtime.config.search = normalized.search;
|
|
465
|
+
if (runtime.search) {
|
|
466
|
+
runtime.search.apiKey = String(normalized.search?.apiKey ?? '').trim();
|
|
467
|
+
runtime.search.timeoutMs = normalized.search.timeoutMs;
|
|
468
|
+
}
|
|
469
|
+
// 天气:和搜索同理,WeatherClient 在构造时拷了 host/key/经纬度,
|
|
470
|
+
// 光换 config 不够,得写回实例,否则改完 key 还在用旧的。
|
|
471
|
+
runtime.config.weather = normalized.weather;
|
|
472
|
+
// Steam:配置对象换掉之后,client 里的 apiKey / 缓存时间也要跟着换。
|
|
473
|
+
// 不调 reconfigure 的话,面板上改了 Key 仍然用旧的,表现是「保存了但不生效」。
|
|
474
|
+
const steamChanged = JSON.stringify(runtime.config.steam) !== JSON.stringify(normalized.steam);
|
|
475
|
+
runtime.config.steam = normalized.steam;
|
|
476
|
+
if (steamChanged) {
|
|
477
|
+
try { runtime.steam?.reconfigure?.(normalized.steam); } catch { /* 热更新失败不影响保存 */ }
|
|
478
|
+
}
|
|
479
|
+
if (runtime.weather) {
|
|
480
|
+
runtime.weather.apiHost = String(normalized.weather?.apiHost ?? '').trim().replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
|
481
|
+
runtime.weather.apiKey = String(normalized.weather?.apiKey ?? '').trim();
|
|
482
|
+
runtime.weather.latitude = normalized.weather?.latitude;
|
|
483
|
+
runtime.weather.longitude = normalized.weather?.longitude;
|
|
484
|
+
runtime.weather.timeoutMs = normalized.weather?.timeoutMs;
|
|
485
|
+
}
|
|
486
|
+
// 分段间隔在每次发送时读取,直接替换即可即时生效。
|
|
487
|
+
runtime.config.rate = normalized.rate;
|
|
488
|
+
// The route is read when an agent is created, so a changed model must also
|
|
489
|
+
// invalidate every cached agent -- otherwise the old model keeps answering.
|
|
490
|
+
const routeChanged = JSON.stringify(normalized.route) !== JSON.stringify(runtime.config.route ?? {});
|
|
491
|
+
runtime.config.route = normalized.route;
|
|
492
|
+
// RateLimiter 在构造时拷贝了配额字段,热更新时一并刷新,否则改 globalGapMs 不生效。
|
|
493
|
+
if (runtime.rate) Object.assign(runtime.rate, {
|
|
494
|
+
globalGapMs: normalized.rate.globalGapMs,
|
|
495
|
+
peerGapMs: normalized.rate.peerGapMs,
|
|
496
|
+
maxPerMinute: normalized.rate.maxPerMinute,
|
|
497
|
+
});
|
|
498
|
+
if (intervalChanged && typeof runtime.armPollTimer === 'function') runtime.armPollTimer();
|
|
499
|
+
if (routeChanged && typeof runtime.dropSessions === 'function') runtime.dropSessions();
|
|
500
|
+
// sharedAgent 或 persona 变化也要 drop 会话。
|
|
501
|
+
// sharedAgent:sessionId 格式变了,旧 agent 必须销毁。
|
|
502
|
+
// persona:system prompt 在 setup 中注入,改了要重建 agent 才生效。
|
|
503
|
+
const sharedAgentIs = normalized.reply?.sharedAgent === true;
|
|
504
|
+
const personaIs = String(normalized.persona ?? "");
|
|
505
|
+
if (sharedAgentIs !== sharedAgentWas || personaIs !== personaWas) {
|
|
506
|
+
try { runtime.dropSessions?.(); } catch (error) {
|
|
507
|
+
runtime.logger?.warn?.("重建会话失败:" + String(error?.message ?? error));
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
return json(res, 200, { ok: true, hot, note: hot ? '已即时生效' : '微信接入相关改动需重载插件后生效' });
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// Every model the Host can currently route, grouped by provider. The panel uses
|
|
516
|
+
// this instead of a hard-coded list so a provider gaining or losing a model is
|
|
517
|
+
// reflected without shipping a new plugin version.
|
|
518
|
+
register(`${PREFIX}/models`, async (req, res) => {
|
|
519
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
520
|
+
const llm = ctx.get?.('llm');
|
|
521
|
+
if (!llm || typeof llm.listProviders !== 'function') {
|
|
522
|
+
return json(res, 200, { ok: true, groups: [], failures: [], note: 'Host 未提供模型目录服务' });
|
|
523
|
+
}
|
|
524
|
+
const defaultSelection = (() => {
|
|
525
|
+
try { return ctx.get?.('agentDefaultModel')?.currentSelection?.() ?? null; } catch { return null; }
|
|
526
|
+
})();
|
|
527
|
+
const groups = [];
|
|
528
|
+
const failures = [];
|
|
529
|
+
for (const provider of llm.listProviders()) {
|
|
530
|
+
try {
|
|
531
|
+
const models = await llm.listModels(provider.id);
|
|
532
|
+
if (!models?.length) continue;
|
|
533
|
+
groups.push({
|
|
534
|
+
id: provider.id,
|
|
535
|
+
name: provider.name ?? provider.id,
|
|
536
|
+
models: models.map(m => ({ id: m.id, name: m.name ?? m.id, ...(m.description ? { description: m.description } : {}) })),
|
|
537
|
+
});
|
|
538
|
+
} catch (error) {
|
|
539
|
+
failures.push({ id: provider.id, name: provider.name ?? provider.id, message: String(error?.message ?? error) });
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return json(res, 200, { ok: true, default: defaultSelection, groups, failures });
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
// ---- sticker library ---------------------------------------------------
|
|
546
|
+
const memes = () => runtime?.memes;
|
|
547
|
+
|
|
548
|
+
// ---- endocrine ---------------------------------------------------------
|
|
549
|
+
register(`${PREFIX}/endocrine`, async (req, res) => {
|
|
550
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
551
|
+
const endocrine = runtime?.endocrine;
|
|
552
|
+
if (!endocrine) return json(res, 200, { ok: true, enabled: false, snapshot: null });
|
|
553
|
+
await endocrine.init();
|
|
554
|
+
return json(res, 200, await endocrine.panelState());
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
register(`${PREFIX}/endocrine/action`, async (req, res) => {
|
|
558
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
559
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
560
|
+
const endocrine = runtime?.endocrine;
|
|
561
|
+
if (!endocrine) return json(res, 400, { ok: false, error: '内分泌模块未启用' });
|
|
562
|
+
let body;
|
|
563
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
564
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
565
|
+
const out = await endocrine.action(body);
|
|
566
|
+
if (!out?.ok) return json(res, 400, out);
|
|
567
|
+
return json(res, 200, await endocrine.panelState());
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
// ---- virtual life ------------------------------------------------------
|
|
571
|
+
register(`${PREFIX}/life`, async (req, res) => {
|
|
572
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
573
|
+
const life = runtime?.life;
|
|
574
|
+
if (!life) return json(res, 200, { ok: true, enabled: false, snapshot: null });
|
|
575
|
+
await life.init();
|
|
576
|
+
return json(res, 200, { ok: true, enabled: true, snapshot: life.snapshot() });
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
// Conversations the user can turn proactive messaging on/off for. Built from the
|
|
580
|
+
// archive so only chats that actually exist are offered.
|
|
581
|
+
register(`${PREFIX}/life/targets`, async (req, res) => {
|
|
582
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
583
|
+
// POST 保存勾选结果;GET 返回可选项。之前只有 GET,勾选只改浏览器内存,
|
|
584
|
+
// 重启就全丢,用户会以为「设置又失效了」。
|
|
585
|
+
if (req.method === 'POST') {
|
|
586
|
+
let body;
|
|
587
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
588
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
589
|
+
const list = Array.isArray(body.targets) ? body.targets : null;
|
|
590
|
+
if (!list) return json(res, 400, { ok: false, error: 'targets 必须是数组' });
|
|
591
|
+
const clean = list.map((entry) => {
|
|
592
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
593
|
+
const kind = entry.kind === 'group' ? 'group' : entry.kind === 'private' ? 'private' : '';
|
|
594
|
+
const peerId = String(entry.peerId ?? '').trim();
|
|
595
|
+
if (!kind || !/^\d{5,12}$/.test(peerId)) return null;
|
|
596
|
+
return { kind, peerId, enabled: entry.enabled !== false };
|
|
597
|
+
}).filter(Boolean).slice(0, 200);
|
|
598
|
+
// 和 /config 共用同一条写队列:两边都是「读全量改几字段写回全量」,
|
|
599
|
+
// 不排队就会互相覆盖。
|
|
600
|
+
return serializeWrite(async () => {
|
|
601
|
+
const { raw } = await loadRawOrTemplate();
|
|
602
|
+
raw.life = { ...(raw.life ?? {}), proactiveTargets: clean };
|
|
603
|
+
const { __path, ...persisted } = raw;
|
|
604
|
+
await atomicWriteJson(configPath, JSON.stringify(persisted, null, 2) + '\n');
|
|
605
|
+
// 运行中的实例立刻用上新列表,不必重启。
|
|
606
|
+
if (runtime?.config?.life) runtime.config.life.proactiveTargets = clean;
|
|
607
|
+
return json(res, 200, { ok: true, saved: clean.length });
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
const life = runtime?.life;
|
|
611
|
+
if (!life) return json(res, 200, { ok: true, enabled: false, conversations: [] });
|
|
612
|
+
const { raw } = await loadRawOrTemplate();
|
|
613
|
+
const configured = new Map(
|
|
614
|
+
(raw.life?.proactiveTargets ?? []).map((t) => [t.kind + ':' + t.peerId, t.enabled !== false]),
|
|
615
|
+
);
|
|
616
|
+
const conversations = (runtime.store?.conversations?.() ?? [])
|
|
617
|
+
.filter((c) => c.kind === 'private' || c.kind === 'group')
|
|
618
|
+
.map((c) => {
|
|
619
|
+
const key = c.kind + ':' + c.peerId;
|
|
620
|
+
return {
|
|
621
|
+
kind: c.kind,
|
|
622
|
+
peerId: String(c.peerId),
|
|
623
|
+
// 旧索引没有 lastAt:从 time(秒)换算,别让面板整列空白。
|
|
624
|
+
lastAt: c.lastAt ?? (Number.isFinite(Number(c.time)) ? Number(c.time) * 1000 : null),
|
|
625
|
+
// Only entries present in the saved list are targets at all.
|
|
626
|
+
selected: configured.has(key),
|
|
627
|
+
enabled: configured.get(key) === true,
|
|
628
|
+
};
|
|
629
|
+
})
|
|
630
|
+
.sort((a, b) => (b.lastAt ?? 0) - (a.lastAt ?? 0))
|
|
631
|
+
.slice(0, 200);
|
|
632
|
+
return json(res, 200, { ok: true, enabled: true, conversations });
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
register(`${PREFIX}/life/action`, async (req, res) => {
|
|
637
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
638
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
639
|
+
const life = runtime?.life;
|
|
640
|
+
if (!life) return json(res, 400, { ok: false, error: '虚拟人生未启用' });
|
|
641
|
+
await life.init();
|
|
642
|
+
let body;
|
|
643
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
644
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
645
|
+
const action = String(body.action ?? '');
|
|
646
|
+
try {
|
|
647
|
+
if (action === 'generate') {
|
|
648
|
+
if (!runtime?.lifeGenerator) return json(res, 400, { ok: false, error: '生成器未启用' });
|
|
649
|
+
// Generation calls a model and can take a while; the panel shows a spinner.
|
|
650
|
+
const result = await runtime.lifeGenerator.generate({ force: body.force === true });
|
|
651
|
+
return json(res, 200, result.ok ? { ...result, snapshot: life.snapshot() } : result);
|
|
652
|
+
}
|
|
653
|
+
if (action === 'clear') {
|
|
654
|
+
const snapshot = await life.reset();
|
|
655
|
+
return json(res, 200, { ok: true, snapshot });
|
|
656
|
+
}
|
|
657
|
+
// 改完上限/离散度/间隔之后,今天的窗口还是按旧参数算的。
|
|
658
|
+
// 这个操作清掉「已触发」记录,让窗口按当前参数重算,不用等到明天。
|
|
659
|
+
if (action === 'reset-today') {
|
|
660
|
+
const result = await life.resetToday();
|
|
661
|
+
return json(res, 200, { ok: true, ...result, proactive: runtime.proactiveSnapshot?.() ?? null });
|
|
662
|
+
}
|
|
663
|
+
// 手动触发一次主动消息,用来验证「开关打开后到底会不会发」。
|
|
664
|
+
// 平时它只由 60 秒轮询驱动,出问题时无法复现,只能等到下一个窗口。
|
|
665
|
+
if (action === 'test-proactive') {
|
|
666
|
+
if (runtime.config.life?.proactive !== true) {
|
|
667
|
+
return json(res, 400, { ok: false, error: '主动消息没开启(life.proactive 不是 true)' });
|
|
668
|
+
}
|
|
669
|
+
if (!runtime.connected) {
|
|
670
|
+
return json(res, 400, { ok: false, error: '微信未连接,先看 wx_status' });
|
|
671
|
+
}
|
|
672
|
+
const before = { sentToday: life.sentCount(new Date()), lastSentAt: life.lastSentAt() };
|
|
673
|
+
const result = await runtime.triggerProactiveForTest();
|
|
674
|
+
const after = { sentToday: life.sentCount(new Date()), lastSentAt: life.lastSentAt() };
|
|
675
|
+
return json(res, 200, { ok: result.ok !== false, ...result, before, after });
|
|
676
|
+
}
|
|
677
|
+
return json(res, 400, { ok: false, error: '未知操作:' + action });
|
|
678
|
+
} catch (error) {
|
|
679
|
+
return json(res, 400, { ok: false, error: String(error?.message ?? error) });
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
// ---- 主动发动态 --------------------------------------------------------
|
|
684
|
+
register(`${PREFIX}/emotion`, async (req, res) => {
|
|
685
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
686
|
+
const store = runtime?.emotion;
|
|
687
|
+
if (!store) return json(res, 200, { ok: true, enabled: false, profiles: [], stats: null });
|
|
688
|
+
await store.init();
|
|
689
|
+
const cfg = runtime.config.emotion ?? {};
|
|
690
|
+
return json(res, 200, {
|
|
691
|
+
ok: true,
|
|
692
|
+
enabled: cfg.enabled === true,
|
|
693
|
+
config: cfg,
|
|
694
|
+
stats: store.stats(),
|
|
695
|
+
profiles: store.list({ limit: cfg.maxProfiles ?? 50 }),
|
|
696
|
+
});
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
register(`${PREFIX}/emotion/action`, async (req, res) => {
|
|
700
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
701
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
702
|
+
const store = runtime?.emotion;
|
|
703
|
+
if (!store) return json(res, 400, { ok: false, error: '情感系统未启用' });
|
|
704
|
+
await store.init();
|
|
705
|
+
let body;
|
|
706
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
707
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
708
|
+
const action = String(body.action ?? '');
|
|
709
|
+
const peerId = String(body.peerId ?? '').trim();
|
|
710
|
+
try {
|
|
711
|
+
if (action === 'reset') {
|
|
712
|
+
if (!peerId) return json(res, 400, { ok: false, error: '缺少 peerId' });
|
|
713
|
+
const key = store.keyFor({ peerId, kind: 'private' });
|
|
714
|
+
const { state, stage } = await store.reset(key);
|
|
715
|
+
return json(res, 200, { ok: true, favor: state.favor, intimacy: state.intimacy, stage: stage.stageName });
|
|
716
|
+
}
|
|
717
|
+
if (action === 'set') {
|
|
718
|
+
if (!peerId) return json(res, 400, { ok: false, error: '缺少 peerId' });
|
|
719
|
+
const patch = {};
|
|
720
|
+
if (body.favor !== undefined) patch.favor = Math.round(Math.min(100, Math.max(-100, Number(body.favor) || 0)));
|
|
721
|
+
if (body.intimacy !== undefined) patch.intimacy = Math.round(Math.min(100, Math.max(0, Number(body.intimacy) || 0)));
|
|
722
|
+
if (body.attitude !== undefined) patch.attitude = String(body.attitude).slice(0, 40);
|
|
723
|
+
if (body.relationship !== undefined) patch.relationship = String(body.relationship).slice(0, 60);
|
|
724
|
+
if (!Object.keys(patch).length) return json(res, 400, { ok: false, error: '没有要修改的字段' });
|
|
725
|
+
const key = store.keyFor({ peerId, kind: 'private' });
|
|
726
|
+
const { state, stage } = await store.set(key, patch);
|
|
727
|
+
return json(res, 200, { ok: true, favor: state.favor, intimacy: state.intimacy, stage: stage.stageName });
|
|
728
|
+
}
|
|
729
|
+
return json(res, 400, { ok: false, error: '未知操作:' + action });
|
|
730
|
+
} catch (error) {
|
|
731
|
+
return json(res, 400, { ok: false, error: String(error?.message ?? error) });
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
|
|
735
|
+
// ---- Steam 绑定 --------------------------------------------------------
|
|
736
|
+
// 绑定只在面板里做:谁能绑 = 谁能打开这个面板(本机 + 管理员私聊)。
|
|
737
|
+
// 不给聊天工具开口子,是因为 SteamID 是公开信息 —— 群里任何人都能拿到
|
|
738
|
+
// 别人的 ID 绑上来,然后她会对着 A 说「你在玩 B 的游戏」。
|
|
739
|
+
register(`${PREFIX}/steam/bindings`, async (req, res) => {
|
|
740
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
741
|
+
const store = runtime?.steamBindings;
|
|
742
|
+
if (!store) return json(res, 200, { ok: true, people: [] });
|
|
743
|
+
try {
|
|
744
|
+
await store.init();
|
|
745
|
+
const people = Object.entries(store.people ?? {}).map(([peer, raw]) => ({
|
|
746
|
+
peerId: peer,
|
|
747
|
+
bindings: store.list(peer).map((b) => ({
|
|
748
|
+
steamId: b.steamId, nickname: b.nickname, boundAt: b.boundAt, source: b.source,
|
|
749
|
+
})),
|
|
750
|
+
}));
|
|
751
|
+
return json(res, 200, { ok: true, people });
|
|
752
|
+
} catch (error) {
|
|
753
|
+
return json(res, 500, { ok: false, error: String(error?.message ?? error) });
|
|
754
|
+
}
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
register(`${PREFIX}/steam/action`, async (req, res) => {
|
|
758
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
759
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
760
|
+
const store = runtime?.steamBindings;
|
|
761
|
+
if (!store) return json(res, 400, { ok: false, error: 'Steam 绑定表未初始化' });
|
|
762
|
+
await store.init();
|
|
763
|
+
let body;
|
|
764
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
765
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
766
|
+
const action = String(body.action ?? '');
|
|
767
|
+
const peer = String(body.qq ?? body.peerId ?? '').trim();
|
|
768
|
+
try {
|
|
769
|
+
if (action === 'bind') {
|
|
770
|
+
if (!peer) return json(res, 400, { ok: false, error: '缺少联系人 ID' });
|
|
771
|
+
// 微信 ID 是字符串(wxid_xxx / 自定义微信号),不能用纯数字校验。
|
|
772
|
+
if (!/^(?:wxid_[A-Za-z0-9_-]{3,64}|[A-Za-z][A-Za-z0-9_-]{1,63})$/.test(peer)) {
|
|
773
|
+
return json(res, 400, { ok: false, error: '联系人 ID 格式不对' });
|
|
774
|
+
}
|
|
775
|
+
const result = await store.bind(peer, String(body.steamId ?? ''), {
|
|
776
|
+
nickname: String(body.nickname ?? ''),
|
|
777
|
+
source: 'panel',
|
|
778
|
+
});
|
|
779
|
+
if (!result.ok) return json(res, 400, { ok: false, error: result.reason });
|
|
780
|
+
// 绑完顺手探一次,把真实 Steam 昵称带回来 —— 面板上能一眼看出
|
|
781
|
+
// 「这个 ID 到底是谁」,而不是只有一串数字。
|
|
782
|
+
let probed = null;
|
|
783
|
+
try {
|
|
784
|
+
const st = await runtime.steam?.probe(result.binding.steamId, {});
|
|
785
|
+
if (st) {
|
|
786
|
+
probed = { nickname: st.nickname, state: st.state, inGame: st.inGame || null };
|
|
787
|
+
if (st.nickname && !result.binding.nickname) {
|
|
788
|
+
await store.bind(peer, result.binding.steamId, { nickname: st.nickname, source: 'panel' });
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
} catch (error) {
|
|
792
|
+
probed = { error: String(error?.message ?? error) };
|
|
793
|
+
}
|
|
794
|
+
return json(res, 200, { ok: true, duplicate: Boolean(result.duplicate), probed });
|
|
795
|
+
}
|
|
796
|
+
if (action === 'unbind') {
|
|
797
|
+
if (!peer) return json(res, 400, { ok: false, error: '缺少联系人 ID' });
|
|
798
|
+
const result = await store.unbind(peer, String(body.steamId ?? ''));
|
|
799
|
+
if (!result.ok) return json(res, 400, { ok: false, error: result.reason });
|
|
800
|
+
return json(res, 200, { ok: true, removed: result.removed });
|
|
801
|
+
}
|
|
802
|
+
if (action === 'probe') {
|
|
803
|
+
const steamId = String(body.steamId ?? '').trim();
|
|
804
|
+
if (!/^\d{17}$/.test(steamId)) return json(res, 400, { ok: false, error: 'SteamID 必须是 17 位数字' });
|
|
805
|
+
const st = await runtime.steam?.probe(steamId, {});
|
|
806
|
+
if (!st) return json(res, 400, { ok: false, error: 'Steam 未启用或查询失败' });
|
|
807
|
+
return json(res, 200, {
|
|
808
|
+
ok: true,
|
|
809
|
+
nickname: st.nickname,
|
|
810
|
+
state: st.state,
|
|
811
|
+
inGame: st.inGame || null,
|
|
812
|
+
recentGames: (st.recentGames ?? []).map((g) => g.name),
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
return json(res, 400, { ok: false, error: '未知操作:' + action });
|
|
816
|
+
} catch (error) {
|
|
817
|
+
return json(res, 400, { ok: false, error: String(error?.message ?? error) });
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
// ---- 长期记忆 ----------------------------------------------------------
|
|
822
|
+
register(`${PREFIX}/memory`, async (req, res) => {
|
|
823
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
824
|
+
const store = runtime?.memory;
|
|
825
|
+
if (!store) return json(res, 200, { ok: true, enabled: false, people: [] });
|
|
826
|
+
await store.init();
|
|
827
|
+
const cfg = runtime.config.memory ?? {};
|
|
828
|
+
return json(res, 200, {
|
|
829
|
+
ok: true,
|
|
830
|
+
enabled: cfg.enabled === true,
|
|
831
|
+
config: cfg,
|
|
832
|
+
...store.snapshot({ limit: 100 }),
|
|
833
|
+
});
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
register(`${PREFIX}/memory/action`, async (req, res) => {
|
|
837
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
838
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
839
|
+
const store = runtime?.memory;
|
|
840
|
+
if (!store) return json(res, 400, { ok: false, error: '长期记忆未启用' });
|
|
841
|
+
await store.init();
|
|
842
|
+
let body;
|
|
843
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
844
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
845
|
+
const action = String(body.action ?? '');
|
|
846
|
+
const personId = String(body.personId ?? '').trim();
|
|
847
|
+
try {
|
|
848
|
+
if (action === 'forget') {
|
|
849
|
+
if (!personId || !body.memoryId) return json(res, 400, { ok: false, error: '缺少 personId 或 memoryId' });
|
|
850
|
+
const ok = await store.forget(personId, String(body.memoryId));
|
|
851
|
+
return json(res, 200, { ok, deleted: ok });
|
|
852
|
+
}
|
|
853
|
+
if (action === 'add') {
|
|
854
|
+
if (!personId || !body.text) return json(res, 400, { ok: false, error: '缺少 personId 或 text' });
|
|
855
|
+
const result = await store.remember(personId, {
|
|
856
|
+
text: String(body.text).slice(0, 400),
|
|
857
|
+
kind: body.kind === 'fact' ? 'fact' : 'event',
|
|
858
|
+
importance: Number(body.importance) || 1,
|
|
859
|
+
factKey: String(body.factKey ?? '').slice(0, 40),
|
|
860
|
+
});
|
|
861
|
+
return json(res, 200, { ok: Boolean(result), id: result?.entry?.id ?? '' });
|
|
862
|
+
}
|
|
863
|
+
return json(res, 400, { ok: false, error: '未知操作:' + action });
|
|
864
|
+
} catch (error) {
|
|
865
|
+
return json(res, 400, { ok: false, error: String(error?.message ?? error) });
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
register(`${PREFIX}/memes`, async (req, res) => {
|
|
870
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
871
|
+
const lib = memes();
|
|
872
|
+
if (!lib) return json(res, 200, { ok: true, enabled: false, stats: null, entries: [], pending: [] });
|
|
873
|
+
await lib.init();
|
|
874
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
875
|
+
const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit')) || 120));
|
|
876
|
+
const pick = (e) => ({
|
|
877
|
+
id: e.id, width: e.width, height: e.height, mediaType: e.mediaType,
|
|
878
|
+
description: e.description ?? '', tags: e.tags ?? [], emotions: e.emotions ?? [],
|
|
879
|
+
note: e.note ?? '', source: e.source ?? '', uses: e.uses ?? 0,
|
|
880
|
+
classified: Boolean(e.classifiedAt), addedAt: e.addedAt,
|
|
881
|
+
});
|
|
882
|
+
return json(res, 200, {
|
|
883
|
+
ok: true,
|
|
884
|
+
enabled: true,
|
|
885
|
+
stats: lib.stats(),
|
|
886
|
+
entries: lib.entries.slice(-limit).reverse().map(pick),
|
|
887
|
+
pending: lib.pending.slice(-limit).reverse().map(pick),
|
|
888
|
+
});
|
|
889
|
+
});
|
|
890
|
+
|
|
891
|
+
register(`${PREFIX}/memes/action`, async (req, res) => {
|
|
892
|
+
if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method_not_allowed' });
|
|
893
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
894
|
+
const lib = memes();
|
|
895
|
+
if (!lib) return json(res, 400, { ok: false, error: '表情包图库未启用' });
|
|
896
|
+
await lib.init();
|
|
897
|
+
let body;
|
|
898
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); }
|
|
899
|
+
catch { return json(res, 400, { ok: false, error: '请求体不是合法 JSON' }); }
|
|
900
|
+
const action = String(body.action ?? '');
|
|
901
|
+
try {
|
|
902
|
+
if (action === 'approve') return json(res, 200, await lib.approve(String(body.id ?? '')));
|
|
903
|
+
if (action === 'reject') return json(res, 200, await lib.reject(String(body.id ?? '')));
|
|
904
|
+
if (action === 'remove') return json(res, 200, await lib.remove(String(body.id ?? '')));
|
|
905
|
+
if (action === 'import') return json(res, 200, await lib.importFolder(String(body.folder ?? ''), { note: String(body.note ?? '') }));
|
|
906
|
+
if (action === 'classify') {
|
|
907
|
+
if (!runtime?.classifier) return json(res, 400, { ok: false, error: '分类器未启用' });
|
|
908
|
+
return json(res, 200, await runtime.classifier.runOnce({ max: Math.min(40, Math.max(1, Number(body.max) || 8)) }));
|
|
909
|
+
}
|
|
910
|
+
return json(res, 400, { ok: false, error: '未知操作:' + action });
|
|
911
|
+
} catch (error) {
|
|
912
|
+
return json(res, 400, { ok: false, error: String(error?.message ?? error) });
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
|
|
916
|
+
// One image, so the panel can show what is in the library without base64 blobs
|
|
917
|
+
// inside the JSON listing.
|
|
918
|
+
register(`${PREFIX}/memes/image`, async (req, res) => {
|
|
919
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
920
|
+
const lib = memes();
|
|
921
|
+
if (!lib) return json(res, 404, { ok: false, error: '表情包图库未启用' });
|
|
922
|
+
await lib.init();
|
|
923
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
924
|
+
const id = String(url.searchParams.get('id') ?? '');
|
|
925
|
+
const pending = url.searchParams.get('pending') === '1';
|
|
926
|
+
const entry = (pending ? lib.pending : lib.entries).find((e) => e.id === id);
|
|
927
|
+
if (!entry) return json(res, 404, { ok: false, error: '找不到这张图' });
|
|
928
|
+
try {
|
|
929
|
+
const bytes = await lib.bytesOf(entry, { pending });
|
|
930
|
+
res.writeHead(200, { 'Content-Type': entry.mediaType, 'Cache-Control': 'max-age=3600' });
|
|
931
|
+
res.end(bytes);
|
|
932
|
+
} catch (error) {
|
|
933
|
+
return json(res, 404, { ok: false, error: String(error?.message ?? error) });
|
|
934
|
+
}
|
|
935
|
+
});
|
|
936
|
+
|
|
937
|
+
register(`${PREFIX}/roster`, async (req, res) => {
|
|
938
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
939
|
+
const cm = ctx.get?.('clientModules');
|
|
940
|
+
if (!cm) return json(res, 200, { ok: false, error: 'clientModules service unavailable' });
|
|
941
|
+
let graph = null;
|
|
942
|
+
try { graph = cm.graph?.() ?? null; } catch (error) { graph = { error: String(error?.message ?? error) }; }
|
|
943
|
+
let path = null;
|
|
944
|
+
try { path = cm.clientPath?.('dsh-wechat-access') ?? null; } catch (error) { path = { error: String(error?.message ?? error) }; }
|
|
945
|
+
const rows = Array.isArray(graph) ? graph.filter((row) => JSON.stringify(row).includes('wechat-access')) : null;
|
|
946
|
+
return json(res, 200, {
|
|
947
|
+
ok: true,
|
|
948
|
+
clientPath: path,
|
|
949
|
+
graphType: Array.isArray(graph) ? 'array' : typeof graph,
|
|
950
|
+
graphSize: Array.isArray(graph) ? graph.length : null,
|
|
951
|
+
wechatAccessRows: rows,
|
|
952
|
+
});
|
|
953
|
+
});
|
|
954
|
+
|
|
955
|
+
// 某一个模型支持哪些推理档位。和 /models 分开是因为它要对每个模型问一次
|
|
956
|
+
// resolveModelInfo;面板只看用户当前选中的那一组,没必要一次问完 38 个。
|
|
957
|
+
register(`${PREFIX}/model-reasoning`, async (req, res) => {
|
|
958
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
959
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
960
|
+
const provider = String(url.searchParams.get('provider') ?? '').trim();
|
|
961
|
+
const model = String(url.searchParams.get('model') ?? '').trim();
|
|
962
|
+
const empty = { ok: true, efforts: [], defaultEffort: null };
|
|
963
|
+
if (!provider || !model) return json(res, 200, empty);
|
|
964
|
+
const llm = ctx.get?.('llm');
|
|
965
|
+
if (!llm || typeof llm.resolveModelInfo !== 'function') {
|
|
966
|
+
return json(res, 200, { ...empty, note: 'Host 未提供模型详情服务' });
|
|
967
|
+
}
|
|
968
|
+
try {
|
|
969
|
+
const info = await llm.resolveModelInfo(provider, model);
|
|
970
|
+
const reasoning = info?.reasoning;
|
|
971
|
+
// 没有 reasoning 段就是这个模型根本不给调,面板要能说出这一点,
|
|
972
|
+
// 而不是显示一个空下拉框让人以为加载失败。
|
|
973
|
+
if (!reasoning) return json(res, 200, { ...empty, supported: false });
|
|
974
|
+
return json(res, 200, {
|
|
975
|
+
ok: true,
|
|
976
|
+
supported: true,
|
|
977
|
+
efforts: (reasoning.efforts ?? []).map((effort) => ({
|
|
978
|
+
id: String(effort.id),
|
|
979
|
+
name: effort.name ?? String(effort.id),
|
|
980
|
+
...(effort.description ? { description: effort.description } : {}),
|
|
981
|
+
})),
|
|
982
|
+
defaultEffort: reasoning.defaultEffort === undefined || reasoning.defaultEffort === null
|
|
983
|
+
? null
|
|
984
|
+
: String(reasoning.defaultEffort),
|
|
985
|
+
});
|
|
986
|
+
} catch (error) {
|
|
987
|
+
return json(res, 200, { ...empty, ok: false, error: String(error?.message ?? error) });
|
|
988
|
+
}
|
|
989
|
+
});
|
|
990
|
+
|
|
991
|
+
register(`${PREFIX}/reload-hint`, async (req, res) => {
|
|
992
|
+
if (!trusted(req)) return json(res, 403, { ok: false, error: '不受信任的访问来源' });
|
|
993
|
+
return json(res, 200, { ok: true, hint: '微信接入、人格与范围之外的持久化项,重载插件后生效' });
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
return () => { for (const dispose of disposers) { try { dispose?.(); } catch {} } };
|
|
997
|
+
}
|