@cmach_socket/opencode-qq-bot 0.9.2 → 0.10.0

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.
@@ -0,0 +1,621 @@
1
+ import { mkdir, readFile, stat } from "node:fs/promises"
2
+ import { basename, dirname, join } from "node:path"
3
+ import { parseTargetKey } from "../chat"
4
+ import { backupFile, DIR_MODE, writeJsonAtomic } from "../fs/atomic"
5
+ import { knownSecrets } from "../known-secrets"
6
+ import {
7
+ parseChatOverrides,
8
+ resolveChatOverridesPath,
9
+ type ChatOverride,
10
+ type ChatOverrideParseOptions,
11
+ } from "../overrides"
12
+ import { maskKnownSecrets } from "../sensitive"
13
+ import { copyToSafeMap, hasKey, isSafeKey, safeMap } from "../safe-object"
14
+ import { acquireStateLock } from "../state-lock"
15
+ import { defaultToolPolicy, parseToolPolicy, resolveToolProfilesPath } from "../tools/policy"
16
+ import type { PanelRuntime } from "./runtime"
17
+
18
+ /**
19
+ * 面板里的两个独立配置文件:`chat-overrides.json` 与 `tool-profiles.json`。
20
+ *
21
+ * 两个文件都不是全局配置,粒度与生命周期都不一样,所以各自独立成页。
22
+ * 校验一律复用运行时的解析函数:面板不该自己写一套规则,
23
+ * 否则「面板里能过、机器人不认」的事迟早发生。
24
+ */
25
+
26
+ /** 一个字段上的问题。 */
27
+ export interface DocumentProblem {
28
+ /** 字段路径,例如 `chats.group:100`。 */
29
+ path: string
30
+ /** 出错原因,直接给用户看。 */
31
+ message: string
32
+ }
33
+
34
+ /** 一个文档在接口里的样子。 */
35
+ export interface DocumentView {
36
+ /** 文件的实际位置。 */
37
+ path: string
38
+ /** 文件是否存在。 */
39
+ exists: boolean
40
+ /** 生效值:解析之后的文档。 */
41
+ value: unknown
42
+ /** 文件里的原始内容。 */
43
+ fileValue: unknown
44
+ /** 解析告警:写错的字段只忽略这一项,其余照常生效。 */
45
+ warnings: string[]
46
+ /** 命中已知凭证、被掩码的字段路径。 */
47
+ masked: string[]
48
+ }
49
+
50
+ /** 保存之后的结果。 */
51
+ export interface DocumentSaveResult {
52
+ /** 保存后的文档视图。 */
53
+ document: DocumentView
54
+ /** 这次改动里的告警。 */
55
+ warnings: string[]
56
+ /** 是否需要重启才能生效。 */
57
+ restartRequired: boolean
58
+ /** 生效时机说明。 */
59
+ note: string
60
+ }
61
+
62
+ /** 会话覆盖里允许出现的字段;与 `ChatOverride` 一一对应。 */
63
+ const CHAT_OVERRIDE_FIELDS = [
64
+ "wake",
65
+ "wake.prefixes",
66
+ "proactive.enabled",
67
+ "proactive.startProbability",
68
+ "collect.privateMs",
69
+ "collect.groupMs",
70
+ "agent",
71
+ "model",
72
+ "soulPath",
73
+ "soulName",
74
+ ] as const
75
+
76
+ /** 配置档名字的约束:不为空、不含空格与控制字符、最长 64 个字符。 */
77
+ const PROFILE_NAME = /^[^\s\p{C}]{1,64}$/u
78
+
79
+ /** 内置配置档的名字;这些档不能删,但可以覆盖。 */
80
+ const BUILTIN_PROFILES = Object.keys(defaultToolPolicy().profiles)
81
+
82
+ /** 会话覆盖文件里允许出现的顶层字段。 */
83
+ const CHAT_OVERRIDE_KEYS = ["chats"] as const
84
+
85
+ /** 工具配置文件里允许出现的顶层字段。 */
86
+ const TOOL_POLICY_KEYS = ["defaultProfile", "profiles", "chats"] as const
87
+
88
+ /** 保存文档时的锁重试参数。 */
89
+ const LOCK_RETRIES = { retries: 10, factor: 1.5, minTimeout: 20, maxTimeout: 200 }
90
+
91
+ /**
92
+ * 配置档名字是否可用。
93
+ *
94
+ * 原型上的属性名(`__proto__` 之类)也要挡掉:拿它们索引普通对象会命中
95
+ * `Object.prototype`,「这个档存在吗」这类判断永远为真。
96
+ */
97
+ function isProfileName(name: string): boolean {
98
+ return isSafeKey(name) && PROFILE_NAME.test(name)
99
+ }
100
+
101
+ /** 判断是不是普通对象(数组与 null 都不算)。 */
102
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
103
+ return !!value && typeof value === "object" && !Array.isArray(value)
104
+ }
105
+
106
+ /**
107
+ * 掩码文档里的已知凭证。
108
+ *
109
+ * 命中时只记下字段路径,值换成占位符:面板不把凭证原样回显。
110
+ * 路径取到「属性」一级,数组算一个属性,这样前端能整段跳过不动它。
111
+ */
112
+ function maskDocument(
113
+ value: unknown,
114
+ secrets: readonly string[],
115
+ base: string,
116
+ paths: string[],
117
+ ): { value: unknown; changed: boolean } {
118
+ if (typeof value === "string") {
119
+ const masked = maskKnownSecrets(value, secrets)
120
+ if (masked === value) return { value, changed: false }
121
+ paths.push(base)
122
+ return { value: masked, changed: true }
123
+ }
124
+ if (Array.isArray(value)) {
125
+ let changed = false
126
+ const next = value.map((item) => {
127
+ const masked = maskDocument(item, secrets, base, paths)
128
+ if (masked.changed) changed = true
129
+ return masked.value
130
+ })
131
+ if (changed) {
132
+ paths.push(base)
133
+ return { value: next, changed: true }
134
+ }
135
+ return { value: next, changed: false }
136
+ }
137
+ if (isPlainObject(value)) {
138
+ let changed = false
139
+ const next: Record<string, unknown> = {}
140
+ for (const [key, item] of Object.entries(value)) {
141
+ const path = base ? `${base}.${key}` : key
142
+ const masked = maskDocument(item, secrets, path, paths)
143
+ if (masked.changed) changed = true
144
+ // 用 defineProperty 复制:`__proto__` 这类键走赋值会落到原型上,
145
+ // 键不再是自有属性,序列化时还会被丢掉,面板看到的内容就和磁盘对不上了。
146
+ Object.defineProperty(next, key, {
147
+ value: masked.value,
148
+ enumerable: true,
149
+ writable: true,
150
+ configurable: true,
151
+ })
152
+ }
153
+ return { value: next, changed }
154
+ }
155
+ return { value, changed: false }
156
+ }
157
+
158
+ /** 掩码一份文档,并给出被掩码的字段路径。 */
159
+ function maskView(
160
+ value: unknown,
161
+ secrets: readonly string[],
162
+ ): { value: unknown; masked: string[] } {
163
+ if (secrets.length === 0) return { value, masked: [] }
164
+ const paths: string[] = []
165
+ const masked = maskDocument(value, secrets, "", paths)
166
+ return { value: masked.value, masked: paths }
167
+ }
168
+
169
+ /** 读一个 JSON 文件;不存在或读不了时返回 undefined。 */
170
+ async function readJsonFile(path: string): Promise<{ raw: unknown; exists: boolean }> {
171
+ const info = await stat(path).catch(() => undefined)
172
+ if (!info) return { raw: undefined, exists: false }
173
+ try {
174
+ const text = await readFile(path, "utf8")
175
+ return { raw: JSON.parse(text), exists: true }
176
+ } catch {
177
+ // 文件在但读不了或不是合法 JSON:当作空文档处理,保存时会重写它。
178
+ return { raw: undefined, exists: true }
179
+ }
180
+ }
181
+
182
+ /** 写文件:先备份,再原子写。权限与 `config.json` 一致。 */
183
+ async function writeDocument(path: string, value: unknown): Promise<void> {
184
+ await backupFile(path)
185
+ await writeJsonAtomic(path, value)
186
+ }
187
+
188
+ /** 一次保存的结果:写成功、写不合法,或者锁被占用。 */
189
+ type SaveOutcome<T> = { status: "saved"; result: T } | { status: "invalid" } | { status: "busy" }
190
+
191
+ /**
192
+ * 在文件锁保护下读-改-写一个文档。
193
+ *
194
+ * 面板的保存是「读文件 → 合并 → 写回」:没有互斥的话两个并发请求会互相覆盖,
195
+ * 后写的拿自己的旧视图盖掉先写的改动,而且谁也不报错。
196
+ * 锁文件就放在文档旁边,两份文档各锁各的。
197
+ */
198
+ async function withDocumentLock<T>(
199
+ path: string,
200
+ run: () => Promise<SaveOutcome<T>>,
201
+ ): Promise<SaveOutcome<T>> {
202
+ const lockPath = join(dirname(path), `.${basename(path)}.lock`)
203
+ await mkdir(dirname(lockPath), { recursive: true, mode: DIR_MODE })
204
+ const lock = await acquireStateLock(lockPath, { retries: LOCK_RETRIES })
205
+ if (!lock) return { status: "busy" }
206
+ try {
207
+ return await run()
208
+ } finally {
209
+ await lock.release()
210
+ }
211
+ }
212
+
213
+ /** 角色设定路径的边界选项:允许根来自配置。 */
214
+ function soulParseOptions(runtime: PanelRuntime): ChatOverrideParseOptions {
215
+ return {
216
+ home: runtime.home.directory,
217
+ allowedPaths: runtime.config.soul?.allowedPaths ?? [],
218
+ }
219
+ }
220
+
221
+ /** 面板拿到的会话覆盖文件路径。 */
222
+ export function chatOverridesPath(runtime: PanelRuntime): string {
223
+ return resolveChatOverridesPath(runtime.config, runtime.home.directory)
224
+ }
225
+
226
+ /** 面板拿到的工具配置文件路径。 */
227
+ export function toolProfilesPath(runtime: PanelRuntime): string {
228
+ return resolveToolProfilesPath(runtime.config, runtime.home.directory)
229
+ }
230
+
231
+ /** 读取会话覆盖文件并给出视图。 */
232
+ export async function readChatOverrides(runtime: PanelRuntime): Promise<DocumentView> {
233
+ const path = chatOverridesPath(runtime)
234
+ const { raw, exists } = await readJsonFile(path)
235
+ const warnings: string[] = []
236
+ const value = parseChatOverrides(
237
+ raw,
238
+ (message) => warnings.push(message),
239
+ soulParseOptions(runtime),
240
+ )
241
+ const secrets = knownSecrets(runtime.config)
242
+ const maskedValue = maskView(value, secrets)
243
+ const maskedFile = maskView(raw ?? null, secrets)
244
+ return {
245
+ path,
246
+ exists,
247
+ value: maskedValue.value,
248
+ fileValue: maskedFile.value,
249
+ // 告警去重:同一句话出现两次时,页面上不该挂两个一模一样的条目。
250
+ warnings: [...new Set(warnings)],
251
+ masked: [...new Set([...maskedValue.masked, ...maskedFile.masked])],
252
+ }
253
+ }
254
+
255
+ /** 读取工具配置文件并给出视图。 */
256
+ export async function readToolProfiles(runtime: PanelRuntime): Promise<DocumentView> {
257
+ const path = toolProfilesPath(runtime)
258
+ const { raw, exists } = await readJsonFile(path)
259
+ const warnings: string[] = []
260
+ const value = parseToolPolicy(raw, (message) => warnings.push(message))
261
+ const secrets = knownSecrets(runtime.config)
262
+ const maskedValue = maskView(value, secrets)
263
+ const maskedFile = maskView(raw ?? null, secrets)
264
+ return {
265
+ path,
266
+ exists,
267
+ value: maskedValue.value,
268
+ fileValue: maskedFile.value,
269
+ warnings: [...new Set(warnings)],
270
+ masked: [...new Set([...maskedValue.masked, ...maskedFile.masked])],
271
+ }
272
+ }
273
+
274
+ /**
275
+ * 应用会话覆盖的改动并保存。
276
+ *
277
+ * 改动是稀疏的:只有请求里出现的聊天与字段才会变,
278
+ * 没提到的字段保持原样(被掩码的凭证也就不会被抹掉)。
279
+ */
280
+ export async function saveChatOverrides(
281
+ runtime: PanelRuntime,
282
+ body: unknown,
283
+ ): Promise<{ problems: DocumentProblem[]; result?: DocumentSaveResult }> {
284
+ const problems: DocumentProblem[] = []
285
+ if (!isPlainObject(body)) {
286
+ return { problems: [{ path: "", message: "请求体必须是一个 JSON 对象" }] }
287
+ }
288
+ const patch = body.chats
289
+ if (patch !== undefined && !isPlainObject(patch)) {
290
+ problems.push({ path: "chats", message: "chats 必须是对象" })
291
+ }
292
+ if (problems.length > 0) return { problems }
293
+
294
+ const path = chatOverridesPath(runtime)
295
+ const saved = await withDocumentLock(path, async () => {
296
+ const { raw } = await readJsonFile(path)
297
+ const source = isPlainObject(raw) ? raw : {}
298
+ // 文件里的其它顶层键原样保留:面板只管自己那几个字段,不该把别的抹掉。
299
+ const base = isPlainObject(source.chats) ? copyToSafeMap(source.chats) : safeMap()
300
+ const chats = isPlainObject(patch) ? patch : {}
301
+ const warnings: string[] = []
302
+ for (const key of Object.keys(body)) {
303
+ if (!(CHAT_OVERRIDE_KEYS as readonly string[]).includes(key)) {
304
+ warnings.push(`未知字段 ${key},已忽略`)
305
+ }
306
+ }
307
+
308
+ for (const [key, entry] of Object.entries(chats)) {
309
+ const field = `chats.${key}`
310
+ if (!parseTargetKey(key)) {
311
+ problems.push({ path: field, message: "聊天键必须是 group:<群号> 或 private:<账号>" })
312
+ continue
313
+ }
314
+ if (entry === null) {
315
+ if (!hasKey(base, key)) {
316
+ problems.push({ path: field, message: `会话覆盖 ${key} 不存在` })
317
+ continue
318
+ }
319
+ delete base[key]
320
+ continue
321
+ }
322
+ if (!isPlainObject(entry)) {
323
+ problems.push({ path: field, message: "会话覆盖必须是对象" })
324
+ continue
325
+ }
326
+ const exists = hasKey(base, key)
327
+ const current = isPlainObject(base[key]) ? { ...base[key] } : {}
328
+ const known = Object.entries(entry).filter(([name]) =>
329
+ (CHAT_OVERRIDE_FIELDS as readonly string[]).includes(name),
330
+ )
331
+ for (const [name] of Object.entries(entry)) {
332
+ if (!(CHAT_OVERRIDE_FIELDS as readonly string[]).includes(name)) {
333
+ warnings.push(`会话覆盖 ${key} 的 ${name} 不是支持的字段,已忽略`)
334
+ }
335
+ }
336
+ if (known.length === 0) {
337
+ // 这一条没有能保存的字段:只告警,不动文件。
338
+ warnings.push(`会话覆盖 ${key} 没有可保存的字段,已忽略`)
339
+ continue
340
+ }
341
+ // 键本来就不存在,而这次提交的字段全是「删掉」:这是清空,不是新建。
342
+ if (!exists && known.every(([, value]) => value === null)) {
343
+ problems.push({ path: field, message: `会话覆盖 ${key} 不存在,不能靠清空字段来新建` })
344
+ continue
345
+ }
346
+ for (const [name, value] of known) {
347
+ if (value === null) {
348
+ delete current[name]
349
+ continue
350
+ }
351
+ current[name] = value
352
+ }
353
+ // 字段被删光了:这一条已经没有内容,等同于删掉它。
354
+ if (CHAT_OVERRIDE_FIELDS.every((name) => current[name] === undefined)) {
355
+ delete base[key]
356
+ continue
357
+ }
358
+ if (current.wake === "prefix") {
359
+ const prefixes = current["wake.prefixes"]
360
+ if (!Array.isArray(prefixes) || prefixes.length === 0) {
361
+ problems.push({
362
+ path: `chats.${key}.wake.prefixes`,
363
+ message: "选择 prefix 唤醒时必须写至少一个前缀",
364
+ })
365
+ continue
366
+ }
367
+ }
368
+ // 用解析器把这一条覆盖收拾干净:写错的字段只丢这一项,其余照常写进去。
369
+ const parsed = parseChatOverrides(
370
+ { chats: { [key]: current } },
371
+ (message) => {
372
+ warnings.push(message)
373
+ },
374
+ soulParseOptions(runtime),
375
+ )
376
+ const normalized: ChatOverride = { ...(parsed.chats[key] ?? {}) }
377
+ // 角色设定路径超出允许目录时解析器会丢掉它:文件里保留用户的原意,
378
+ // 运行时不会加载,告警里说清楚。
379
+ if (typeof current.soulPath === "string" && normalized.soulPath === undefined) {
380
+ normalized.soulPath = current.soulPath
381
+ }
382
+ if (typeof current.soulName === "string" && normalized.soulName === undefined) {
383
+ normalized.soulName = current.soulName
384
+ }
385
+ base[key] = normalized
386
+ }
387
+ if (problems.length > 0) return { status: "invalid" }
388
+
389
+ const next = copyToSafeMap(source)
390
+ delete next.chats
391
+ next.chats = base
392
+ await writeDocument(path, next)
393
+
394
+ const document = await readChatOverrides(runtime)
395
+ const expected = parseChatOverrides(next, () => undefined, soulParseOptions(runtime))
396
+ const live = await runtime.overrides?.current()
397
+ const applied = live ? JSON.stringify(live.chats) === JSON.stringify(expected.chats) : false
398
+ const restartRequired = runtime.overrides ? !applied : true
399
+ const note = restartRequired
400
+ ? "已保存,但运行时没有热加载这条配置,需要重启机器人才能生效。"
401
+ : "已保存,会话覆盖会在下一条消息到达时生效,无需重启。"
402
+ return {
403
+ status: "saved",
404
+ result: {
405
+ document,
406
+ warnings: [...new Set([...warnings, ...document.warnings])],
407
+ restartRequired,
408
+ note,
409
+ },
410
+ }
411
+ })
412
+
413
+ if (saved.status === "busy") {
414
+ return { problems: [{ path: "", message: "文件正被其它请求修改,请稍后重试" }] }
415
+ }
416
+ if (saved.status === "invalid") return { problems }
417
+ return { problems: [], result: saved.result }
418
+ }
419
+
420
+ /**
421
+ * 应用工具配置的改动并保存。
422
+ *
423
+ * 改动是稀疏的:只有请求里出现的配置档与聊天映射才会变。
424
+ */
425
+ export async function saveToolProfiles(
426
+ runtime: PanelRuntime,
427
+ body: unknown,
428
+ ): Promise<{ problems: DocumentProblem[]; result?: DocumentSaveResult }> {
429
+ const problems: DocumentProblem[] = []
430
+ if (!isPlainObject(body)) {
431
+ return { problems: [{ path: "", message: "请求体必须是一个 JSON 对象" }] }
432
+ }
433
+ const profilePatch = body.profiles
434
+ const chatPatch = body.chats
435
+ if (profilePatch !== undefined && !isPlainObject(profilePatch)) {
436
+ problems.push({ path: "profiles", message: "profiles 必须是对象" })
437
+ }
438
+ if (chatPatch !== undefined && !isPlainObject(chatPatch)) {
439
+ problems.push({ path: "chats", message: "chats 必须是对象" })
440
+ }
441
+ if (problems.length > 0) return { problems }
442
+
443
+ const path = toolProfilesPath(runtime)
444
+ const saved = await withDocumentLock(path, async () => {
445
+ const { raw } = await readJsonFile(path)
446
+ const source = isPlainObject(raw) ? raw : {}
447
+ const baseProfiles: Record<string, unknown> = isPlainObject(source.profiles)
448
+ ? copyToSafeMap(source.profiles)
449
+ : safeMap()
450
+ const baseChats: Record<string, unknown> = isPlainObject(source.chats)
451
+ ? copyToSafeMap(source.chats)
452
+ : safeMap()
453
+ let defaultProfile = typeof source.defaultProfile === "string" ? source.defaultProfile : ""
454
+ // 置空表示回到内置默认档:文件里干脆不写这个键,界面也就能显示「跟随默认」。
455
+ let omitDefault = false
456
+ const warnings: string[] = []
457
+ for (const key of Object.keys(body)) {
458
+ if (!(TOOL_POLICY_KEYS as readonly string[]).includes(key)) {
459
+ warnings.push(`未知字段 ${key},已忽略`)
460
+ }
461
+ }
462
+ const deletedProfiles = new Set<string>()
463
+
464
+ for (const [name, entry] of Object.entries(isPlainObject(profilePatch) ? profilePatch : {})) {
465
+ const field = `profiles.${name}`
466
+ if (!isProfileName(name)) {
467
+ problems.push({
468
+ path: field,
469
+ message: "配置档名字不能为空、不能含空格或控制字符,最长 64 个字符",
470
+ })
471
+ continue
472
+ }
473
+ if (entry === null) {
474
+ if (BUILTIN_PROFILES.includes(name) && !hasKey(baseProfiles, name)) {
475
+ problems.push({ path: field, message: `内置配置档 ${name} 不能删除` })
476
+ continue
477
+ }
478
+ if (!hasKey(baseProfiles, name)) {
479
+ problems.push({ path: field, message: `配置档 ${name} 不存在` })
480
+ continue
481
+ }
482
+ delete baseProfiles[name]
483
+ deletedProfiles.add(name)
484
+ continue
485
+ }
486
+ if (!isPlainObject(entry)) {
487
+ problems.push({ path: field, message: "配置档必须是对象" })
488
+ continue
489
+ }
490
+ const exists = hasKey(baseProfiles, name)
491
+ const current = isPlainObject(baseProfiles[name]) ? { ...baseProfiles[name] } : {}
492
+ const known: Array<[string, unknown]> = []
493
+ for (const [key, value] of Object.entries(entry)) {
494
+ if (key !== "allow" && key !== "deny") {
495
+ warnings.push(`配置档 ${name} 的 ${key} 不是支持的字段,已忽略`)
496
+ continue
497
+ }
498
+ known.push([key, value])
499
+ }
500
+ if (known.length === 0) {
501
+ // 这一档没有能保存的字段:只告警,不动文件。
502
+ warnings.push(`配置档 ${name} 没有可保存的字段,已忽略`)
503
+ continue
504
+ }
505
+ // 档本来就不存在,而这次提交的字段全是「删掉」:这是清空,不是新建。
506
+ if (!exists && known.every(([, value]) => value === null)) {
507
+ problems.push({ path: field, message: `配置档 ${name} 不存在,不能靠清空字段来新建` })
508
+ continue
509
+ }
510
+ for (const [key, value] of known) {
511
+ if (value === null) {
512
+ delete current[key]
513
+ continue
514
+ }
515
+ current[key] = value
516
+ }
517
+ // 用解析器把这一档收拾干净:列表里的非字符串项按解析器的规则丢掉。
518
+ const parsed = parseToolPolicy({ profiles: { [name]: current } }, (message) => {
519
+ warnings.push(message)
520
+ })
521
+ baseProfiles[name] = parsed.profiles[name] ?? { allow: [], deny: [] }
522
+ }
523
+
524
+ for (const [key, value] of Object.entries(isPlainObject(chatPatch) ? chatPatch : {})) {
525
+ const field = `chats.${key}`
526
+ if (!parseTargetKey(key)) {
527
+ problems.push({ path: field, message: "聊天键必须是 group:<群号> 或 private:<账号>" })
528
+ continue
529
+ }
530
+ if (value === null) {
531
+ if (!hasKey(baseChats, key)) {
532
+ problems.push({ path: field, message: `聊天映射 ${key} 不存在` })
533
+ continue
534
+ }
535
+ delete baseChats[key]
536
+ continue
537
+ }
538
+ if (typeof value !== "string" || !value.trim()) {
539
+ problems.push({ path: field, message: "聊天映射必须是一个配置档名字" })
540
+ continue
541
+ }
542
+ baseChats[key] = value.trim()
543
+ }
544
+
545
+ if (body.defaultProfile !== undefined) {
546
+ if (body.defaultProfile === null) {
547
+ // 置空表示回到内置默认档。
548
+ defaultProfile = ""
549
+ omitDefault = true
550
+ } else if (typeof body.defaultProfile !== "string" || !body.defaultProfile.trim()) {
551
+ problems.push({ path: "defaultProfile", message: "默认配置档必须是一个配置档名字" })
552
+ } else {
553
+ defaultProfile = body.defaultProfile.trim()
554
+ omitDefault = false
555
+ }
556
+ }
557
+ if (problems.length > 0) return { status: "invalid" }
558
+
559
+ // 引用检查:档名必须存在,否则运行时会落到默认档,页面上写的意图等于白写。
560
+ const effective = parseToolPolicy(
561
+ { defaultProfile, profiles: baseProfiles, chats: baseChats },
562
+ (message) => warnings.push(message),
563
+ )
564
+ if (defaultProfile && !hasKey(effective.profiles, defaultProfile)) {
565
+ problems.push({
566
+ path: "defaultProfile",
567
+ message: deletedProfiles.has(defaultProfile)
568
+ ? `配置档 ${defaultProfile} 已被删除,但 defaultProfile 还在用它`
569
+ : `defaultProfile 指向不存在的配置档 ${defaultProfile}`,
570
+ })
571
+ }
572
+ for (const [key, name] of Object.entries(effective.chats)) {
573
+ if (!hasKey(effective.profiles, name)) {
574
+ problems.push({
575
+ path: `chats.${key}`,
576
+ message: deletedProfiles.has(name)
577
+ ? `配置档 ${name} 已被删除,但 chats.${key} 还在引用它`
578
+ : `chats.${key} 指向不存在的配置档 ${name}`,
579
+ })
580
+ }
581
+ }
582
+ if (problems.length > 0) return { status: "invalid" }
583
+
584
+ // 文件里的其它顶层键原样保留:面板只管自己那几个字段,不该把别的抹掉。
585
+ const next = copyToSafeMap(source)
586
+ delete next.defaultProfile
587
+ delete next.profiles
588
+ delete next.chats
589
+ // 默认档没被指定过就不写进文件:写死了就分不清「用户选的」与「内置的」。
590
+ if (!omitDefault && (defaultProfile || hasKey(source, "defaultProfile"))) {
591
+ next.defaultProfile = defaultProfile || effective.defaultProfile
592
+ }
593
+ next.profiles = baseProfiles
594
+ next.chats = baseChats
595
+ await writeDocument(path, next)
596
+
597
+ const document = await readToolProfiles(runtime)
598
+ const expected = parseToolPolicy(next, () => undefined)
599
+ const live = await runtime.policy?.current()
600
+ const applied = live ? JSON.stringify(live) === JSON.stringify(expected) : false
601
+ const restartRequired = runtime.policy ? !applied : true
602
+ const note = restartRequired
603
+ ? "已保存,但运行时没有热加载这条配置,需要重启机器人才能生效。"
604
+ : "已保存,工具配置会在下一次工具调用前生效,无需重启。"
605
+ return {
606
+ status: "saved",
607
+ result: {
608
+ document,
609
+ warnings: [...new Set([...warnings, ...document.warnings])],
610
+ restartRequired,
611
+ note,
612
+ },
613
+ }
614
+ })
615
+
616
+ if (saved.status === "busy") {
617
+ return { problems: [{ path: "", message: "文件正被其它请求修改,请稍后重试" }] }
618
+ }
619
+ if (saved.status === "invalid") return { problems }
620
+ return { problems: [], result: saved.result }
621
+ }
@@ -116,6 +116,12 @@ export class PanelServer {
116
116
  this.auth.rotate(config.panel.token)
117
117
  this.options.logger.info("面板令牌已更新,已签发的会话全部作废")
118
118
  }
119
+ // 令牌被吊销:旧令牌与已登录会话立刻作废,服务也不再对外。
120
+ if (config.panel.tokenRevoked) {
121
+ this.auth.clear()
122
+ await this.closeServer()
123
+ return
124
+ }
119
125
  if (!config.panel.enabled) {
120
126
  await this.closeServer()
121
127
  return
@@ -57,6 +57,8 @@ export interface StatusSnapshot {
57
57
  wake?: string
58
58
  /** 是否允许主动说话。 */
59
59
  proactive?: boolean
60
+ /** 是否正在收集消息(窗口还没到点)。 */
61
+ collecting?: boolean
60
62
  }>
61
63
  /** 出站限流用量。 */
62
64
  rateLimit: Array<{
@@ -119,6 +121,8 @@ interface SessionRow {
119
121
  wake?: string
120
122
  /** 是否允许主动说话。 */
121
123
  proactive?: boolean
124
+ /** 是否正在收集消息(窗口还没到点)。 */
125
+ collecting?: boolean
122
126
  }
123
127
 
124
128
  /**
@@ -194,7 +198,10 @@ async function collectSessions(runtime: PanelRuntime): Promise<SessionRow[]> {
194
198
  buffered: item.buffered,
195
199
  pending: item.pending,
196
200
  ...(override?.wake ? { wake: override.wake } : {}),
197
- ...(override?.proactive !== undefined ? { proactive: override.proactive } : {}),
201
+ ...(override?.["proactive.enabled"] !== undefined
202
+ ? { proactive: override["proactive.enabled"] }
203
+ : {}),
204
+ ...(item.collectUntil !== undefined ? { collecting: true } : {}),
198
205
  })
199
206
  }
200
207
  return result