@cmach_socket/opencode-qq-bot 0.9.2 → 0.10.1

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