@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.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.
package/src/config.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { Model } from "@opencode/schema"
2
2
  import { z } from "zod"
3
+ import type { AccessConfig } from "./access"
4
+ import type { LogLevel } from "./logger"
3
5
 
4
6
  /**
5
7
  * Plugin configuration: merges OpenCode plugin options, environment variables
@@ -12,6 +14,10 @@ import { z } from "zod"
12
14
  const NUMBER = /^-?(?:\d+\.?\d*|\.\d+)$/
13
15
  const TRUTHY = new Set(["1", "true", "yes", "on"])
14
16
  const BOOLEAN_SPELLINGS = ["1", "0", "true", "false", "yes", "no", "on", "off"] as const
17
+ /** 合法的日志级别。 */
18
+ const LOG_LEVELS: readonly string[] = ["debug", "info", "warn", "error"]
19
+ /** 可订阅的事件类别。 */
20
+ export const EVENT_CATEGORIES: readonly string[] = ["message", "notice"]
15
21
 
16
22
  export interface NapcatConfig {
17
23
  /** NapCat 正向 WebSocket 地址,必填。 */
@@ -31,6 +37,46 @@ export interface ProactiveConfig {
31
37
  probabilityPerHour: number
32
38
  /** 心跳间隔(秒)。 */
33
39
  tickSeconds: number
40
+ /** 只在这些群里主动说话;为空表示不限制。 */
41
+ allowGroups: number[]
42
+ /** 只在这些私聊里主动说话;为空表示不限制。 */
43
+ allowUsers: number[]
44
+ }
45
+
46
+ /** 唤醒判定配置:全局的触发条件。 */
47
+ export interface WakeConfig {
48
+ /** 全局唤醒前缀,命中即必回。 */
49
+ prefixes: string[]
50
+ /** 是否忽略 @全体成员。 */
51
+ ignoreAtAll: boolean
52
+ /** 回复机器人自己的消息是否必回。 */
53
+ replyToSelf: boolean
54
+ /** 群里第一条 @ 的是别人时是否不唤醒机器人。 */
55
+ ignoreAtOthers: boolean
56
+ }
57
+
58
+ /** 回复节奏配置:怎么拆段、怎么发。 */
59
+ export interface ReplyConfig {
60
+ /** 分段之间的最小间隔(毫秒)。 */
61
+ minDelayMs: number
62
+ /** 分段之间的最大间隔(毫秒),0 表示沿用 `sendDelayMs`。 */
63
+ maxDelayMs: number
64
+ /** 单条消息超过该字数就拆成多段发送。 */
65
+ segmentChars: number
66
+ /** 单条回复超过该字数就改用合并转发,0 表示关闭。 */
67
+ forwardThresholdChars: number
68
+ }
69
+
70
+ /** 调用链追踪配置。 */
71
+ export interface TraceConfig {
72
+ /** 是否记录调用链追踪。 */
73
+ enabled: boolean
74
+ /** 追踪文件目录,空表示与日志同目录。 */
75
+ dir: string
76
+ /** 追踪文件总容量上限(MB)。 */
77
+ maxSizeMb: number
78
+ /** 追踪文件保留天数。 */
79
+ retentionDays: number
34
80
  }
35
81
 
36
82
  export interface ReminderConfig {
@@ -40,6 +86,64 @@ export interface ReminderConfig {
40
86
  max: number
41
87
  }
42
88
 
89
+ export interface KeepAliveConfig {
90
+ /** 是否启用保活心跳。 */
91
+ enabled: boolean
92
+ /** 保活心跳间隔(秒),必须小于 OpenCode 的 location 空闲超时。 */
93
+ seconds: number
94
+ }
95
+
96
+ export interface HistoryConfig {
97
+ /** 新建会话时补齐的历史消息条数,0 表示关闭。 */
98
+ count: number
99
+ }
100
+
101
+ export interface RateLimitConfig {
102
+ /** 每分钟最多发出多少条消息,0 表示不限制。 */
103
+ maxPerMinute: number
104
+ /** 每小时最多发出多少条消息,0 表示不限制。 */
105
+ maxPerHour: number
106
+ /** 相邻两次发送之间的最小间隔(毫秒),0 表示不限制。 */
107
+ minGapMs: number
108
+ /** 触顶时是否等窗口结束再发;关闭时直接拒绝这次发送。 */
109
+ stall: boolean
110
+ /** 单次等待窗口结束的上限(毫秒)。 */
111
+ stallMaxWaitMs: number
112
+ }
113
+
114
+ export interface SensitiveConfig {
115
+ /** 是否拦截含敏感信息(凭证、令牌)的出站消息。 */
116
+ enabled: boolean
117
+ }
118
+
119
+ /** 日志配置。 */
120
+ export interface LogConfig {
121
+ /** 最低日志级别。 */
122
+ level: LogLevel
123
+ /** 日志目录,空表示用 XDG 状态目录。 */
124
+ dir: string
125
+ /** 单个日志文件的大小上限。 */
126
+ maxSize: string
127
+ /** 保留的历史日志份数。 */
128
+ maxFiles: number
129
+ }
130
+
131
+ /** 事件订阅配置。 */
132
+ export interface EventsConfig {
133
+ /** 订阅哪些事件类别:`message` / `notice`。 */
134
+ subscribe: string[]
135
+ /** notice 类别里具体关心哪些通知;留空表示全收。 */
136
+ notices: string[]
137
+ /** 通知是否注入会话上下文。 */
138
+ inject: boolean
139
+ }
140
+
141
+ /** 媒体配置。 */
142
+ export interface MediaConfig {
143
+ /** 额外允许发送媒体的目录。 */
144
+ allowedDirs: string[]
145
+ }
146
+
43
147
  export interface ModelRef {
44
148
  providerID: string
45
149
  id: string
@@ -48,34 +152,58 @@ export interface ModelRef {
48
152
 
49
153
  export interface QQBotConfig {
50
154
  napcat: NapcatConfig
51
- /** 参与 AI 对话的群号。 */
52
- groups: number[]
53
- /** 参与 AI 对话的私聊 QQ 号。 */
54
- users: number[]
155
+ /** 准入配置:放行名单、拒绝名单与名单为空时的行为。 */
156
+ access: AccessConfig
157
+ /** 机器人所有者 QQ 号:可用管理命令,并拥有全部工具权限。 */
158
+ ownerQQ?: number
159
+ /** 管理员 QQ 号:拥有全部工具权限。 */
160
+ admins: number[]
161
+ /** 工具配置文件路径,空表示当前工作目录下的 `tool-profiles.json`。 */
162
+ toolProfilesPath?: string
163
+ /** 会话行为覆盖文件路径,空表示当前工作目录下的 `chat-overrides.json`。 */
164
+ chatOverridesPath?: string
55
165
  /** 角色设定文件路径,默认使用插件包内的 souls 目录。 */
56
166
  soulPath?: string
57
167
  /** souls 目录里的角色设定文件名,默认 default.txt。 */
58
168
  soulName?: string
169
+ /** 机器人会话统一使用的工作目录,默认使用 XDG 数据目录下的工作区。 */
170
+ home?: string
59
171
  /** QQ 会话使用的 OpenCode agent。 */
60
172
  agent?: string
61
173
  /** QQ 会话使用的模型。 */
62
174
  model?: ModelRef
63
175
  /** 拆行发送时每条消息之间的间隔(毫秒)。 */
64
176
  sendDelayMs: number
65
- /** 单条消息超过该长度时告警(不截断)。 */
177
+ /** 单次发送的内容超过该长度时告警(不截断)。 */
66
178
  warnLength: number
67
179
  /** 重启后是否复用上一次的会话。 */
68
180
  reuseSession: boolean
69
181
  proactive: ProactiveConfig
182
+ wake: WakeConfig
183
+ reply: ReplyConfig
184
+ trace: TraceConfig
70
185
  reminder: ReminderConfig
186
+ keepAlive: KeepAliveConfig
187
+ history: HistoryConfig
188
+ rateLimit: RateLimitConfig
189
+ sensitive: SensitiveConfig
190
+ events: EventsConfig
191
+ log: LogConfig
192
+ media: MediaConfig
71
193
  }
72
194
 
73
195
  /** 除 NapCat 连接信息外的全部默认值。 */
74
196
  export const DEFAULT_CONFIG: Omit<QQBotConfig, "napcat"> = {
75
- groups: [],
76
- users: [],
197
+ access: {
198
+ allow: { groups: [], users: [] },
199
+ deny: { groups: [], users: [] },
200
+ allowAllWhenEmpty: false,
201
+ },
202
+ admins: [],
203
+ toolProfilesPath: "",
204
+ chatOverridesPath: "",
77
205
  sendDelayMs: 1000,
78
- warnLength: 20,
206
+ warnLength: 500,
79
207
  reuseSession: false,
80
208
  proactive: {
81
209
  enabled: true,
@@ -83,15 +211,42 @@ export const DEFAULT_CONFIG: Omit<QQBotConfig, "napcat"> = {
83
211
  startProbability: 0.01,
84
212
  probabilityPerHour: 0.05,
85
213
  tickSeconds: 3600,
214
+ allowGroups: [],
215
+ allowUsers: [],
86
216
  },
217
+ wake: { prefixes: ["/"], ignoreAtAll: true, replyToSelf: true, ignoreAtOthers: true },
218
+ reply: { minDelayMs: 0, maxDelayMs: 0, segmentChars: 150, forwardThresholdChars: 1500 },
219
+ trace: { enabled: true, dir: "", maxSizeMb: 80, retentionDays: 7 },
87
220
  reminder: { enabled: true, max: 2 },
221
+ keepAlive: { enabled: true, seconds: 20 * 60 },
222
+ history: { count: 20 },
223
+ rateLimit: {
224
+ maxPerMinute: 8,
225
+ maxPerHour: 60,
226
+ minGapMs: 1500,
227
+ stall: false,
228
+ stallMaxWaitMs: 60_000,
229
+ },
230
+ sensitive: { enabled: true },
231
+ events: { subscribe: ["message"], notices: [], inject: true },
232
+ log: { level: "info", dir: "", maxSize: "5m", maxFiles: 5 },
233
+ media: { allowedDirs: [] },
234
+ }
235
+
236
+ /** 迁移类告警前缀:启动时用更高等级输出,避免升级用户静默失联。 */
237
+ export const MIGRATION_WARNING_PREFIX = "【迁移】"
238
+
239
+ /** 移除的环境变量与替代项。 */
240
+ const RENAMED_ENV_VARS: Record<string, string> = {
241
+ QQ_TARGET_GROUPS: "QQ_ALLOW_GROUPS",
242
+ QQ_TARGET_USERS: "QQ_ALLOW_USERS",
88
243
  }
89
244
 
90
245
  /** 配置告警回调。 */
91
246
  export type ConfigWarning = (message: string) => void
92
247
 
93
248
  /** 解析 "provider/model" 或 "provider/model/variant",复用 SDK 的模型引用解析。 */
94
- function parseModelRef(value: unknown): ModelRef | undefined {
249
+ export function parseModelRef(value: unknown): ModelRef | undefined {
95
250
  const raw = typeof value === "string" ? value.trim() : ""
96
251
  if (!raw) return undefined
97
252
  const [providerID, id, variant, ...rest] = raw.split("/").filter(Boolean)
@@ -228,28 +383,78 @@ function createConfigSchema(
228
383
  return trimmed
229
384
  })
230
385
 
231
- const groups = z
232
- .unknown()
233
- .optional()
234
- .transform((value) => {
235
- if (value === undefined || value === null) return [...defaults.groups]
236
- const parsed = toIds(value, warn, label("groups"), "群号")
237
- if (!parsed) {
238
- if (present(value)) warn(`${label("groups")} 解析不出群号:${String(value)}`)
239
- return [...defaults.groups]
240
- }
241
- return parsed
242
- })
386
+ /** 必填的字符串:空值或非法值都回退到默认值。 */
387
+ const requiredText = (path: string, fallback: string) =>
388
+ z
389
+ .unknown()
390
+ .optional()
391
+ .transform((value) => {
392
+ if (!present(value)) return fallback
393
+ if (typeof value !== "string") {
394
+ warn(`${label(path)} 必须是字符串:${String(value)}`)
395
+ return fallback
396
+ }
397
+ const trimmed = value.trim()
398
+ if (!trimmed) {
399
+ warn(`${label(path)} 不能为空,已回退到默认值`)
400
+ return fallback
401
+ }
402
+ return trimmed
403
+ })
404
+
405
+ /** 日志级别:只认 debug/info/warn/error,写错就回退到默认值。 */
406
+ const logLevel = (path: string, fallback: LogLevel) =>
407
+ z
408
+ .unknown()
409
+ .optional()
410
+ .transform((value) => {
411
+ if (!present(value)) return fallback
412
+ const raw = typeof value === "string" ? value.trim().toLowerCase() : ""
413
+ if (!raw) {
414
+ warn(`${label(path)} 不能为空,已回退到默认值`)
415
+ return fallback
416
+ }
417
+ if (!LOG_LEVELS.includes(raw)) {
418
+ warn(
419
+ `${label(path)} 不是合法的日志级别:${String(value)}(可用:${LOG_LEVELS.join("/")})`,
420
+ )
421
+ return fallback
422
+ }
423
+ return raw as LogLevel
424
+ })
425
+
426
+ /** 编号名单:数组或逗号分隔字符串。 */
427
+ const idList = (path: string, fallback: readonly number[], noun: string) =>
428
+ z
429
+ .unknown()
430
+ .optional()
431
+ .transform((value) => {
432
+ if (value === undefined || value === null) return [...fallback]
433
+ const parsed = toIds(value, warn, label(path), noun)
434
+ if (!parsed) {
435
+ if (present(value)) warn(`${label(path)} 解析不出${noun}:${String(value)}`)
436
+ return [...fallback]
437
+ }
438
+ return parsed
439
+ })
243
440
 
244
- const users = z
441
+ const admins = idList("admins", defaults.admins, "QQ 号")
442
+
443
+ const ownerQQ = z
245
444
  .unknown()
246
445
  .optional()
247
446
  .transform((value) => {
248
- if (value === undefined || value === null) return [...defaults.users]
249
- const parsed = toIds(value, warn, label("users"), "QQ 号")
250
- if (!parsed) {
251
- if (present(value)) warn(`${label("users")} 解析不出 QQ 号:${String(value)}`)
252
- return [...defaults.users]
447
+ if (!present(value)) return defaults.ownerQQ
448
+ // 只接受数字或非空数字字符串:布尔值经 Number() 会变成 0/1。
449
+ const parsed =
450
+ typeof value === "number"
451
+ ? value
452
+ : typeof value === "string" && value.trim() !== ""
453
+ ? Number(value.trim())
454
+ : Number.NaN
455
+ if (!Number.isInteger(parsed) || parsed <= 0) {
456
+ warn(`${label("ownerQQ")} 不是合法的 QQ 号:${String(value)}`)
457
+ return defaults.ownerQQ
253
458
  }
254
459
  return parsed
255
460
  })
@@ -267,6 +472,61 @@ function createConfigSchema(
267
472
  return parsed
268
473
  })
269
474
 
475
+ /** 字符串列表:数组或逗号分隔字符串。 */
476
+ const stringList = (path: string, fallback: readonly string[]) =>
477
+ z
478
+ .unknown()
479
+ .optional()
480
+ .transform((value) => {
481
+ if (value === undefined || value === null) return [...fallback]
482
+ const source = Array.isArray(value)
483
+ ? value
484
+ : typeof value === "string"
485
+ ? value.split(",")
486
+ : undefined
487
+ if (!source) {
488
+ if (present(value)) {
489
+ warn(`${label(path)} 必须是字符串或字符串数组:${String(value)}`)
490
+ }
491
+ return [...fallback]
492
+ }
493
+ const items: string[] = []
494
+ for (const entry of source) {
495
+ const raw = typeof entry === "string" ? entry.trim() : ""
496
+ if (!raw) continue
497
+ if (items.includes(raw)) continue
498
+ items.push(raw)
499
+ }
500
+ return items
501
+ })
502
+
503
+ /** 允许发送媒体的目录:数组或逗号分隔字符串。 */
504
+ const mediaDirs = z
505
+ .unknown()
506
+ .optional()
507
+ .transform((value) => {
508
+ if (value === undefined || value === null) return [...defaults.media.allowedDirs]
509
+ const source = Array.isArray(value)
510
+ ? value
511
+ : typeof value === "string"
512
+ ? value.split(",")
513
+ : undefined
514
+ if (!source) {
515
+ if (present(value)) {
516
+ warn(`${label("media.allowedDirs")} 必须是字符串或字符串数组:${String(value)}`)
517
+ }
518
+ return [...defaults.media.allowedDirs]
519
+ }
520
+ const dirs: string[] = []
521
+ for (const entry of source) {
522
+ const raw = typeof entry === "string" ? entry.trim() : ""
523
+ if (!raw) continue
524
+ if (dirs.includes(raw)) continue
525
+ dirs.push(raw)
526
+ }
527
+ return dirs
528
+ })
529
+
270
530
  return z.object({
271
531
  napcat: z
272
532
  .object({
@@ -275,10 +535,47 @@ function createConfigSchema(
275
535
  })
276
536
  .prefault({})
277
537
  .catch({ url: napcat.url, token: napcat.token }),
278
- groups,
279
- users,
538
+ access: z
539
+ .object({
540
+ allow: z
541
+ .object({
542
+ groups: idList("access.allow.groups", defaults.access.allow.groups, "群号").default([
543
+ ...defaults.access.allow.groups,
544
+ ]),
545
+ users: idList("access.allow.users", defaults.access.allow.users, "QQ 号").default([
546
+ ...defaults.access.allow.users,
547
+ ]),
548
+ })
549
+ .prefault({})
550
+ .catch({
551
+ groups: [...defaults.access.allow.groups],
552
+ users: [...defaults.access.allow.users],
553
+ }),
554
+ deny: z
555
+ .object({
556
+ groups: idList("access.deny.groups", defaults.access.deny.groups, "群号").default([
557
+ ...defaults.access.deny.groups,
558
+ ]),
559
+ users: idList("access.deny.users", defaults.access.deny.users, "QQ 号").default([
560
+ ...defaults.access.deny.users,
561
+ ]),
562
+ })
563
+ .prefault({})
564
+ .catch({
565
+ groups: [...defaults.access.deny.groups],
566
+ users: [...defaults.access.deny.users],
567
+ }),
568
+ allowAllWhenEmpty: boolean("access.allowAllWhenEmpty", defaults.access.allowAllWhenEmpty),
569
+ })
570
+ .prefault({})
571
+ .catch(defaults.access),
572
+ admins,
573
+ ownerQQ,
574
+ toolProfilesPath: text("toolProfilesPath", defaults.toolProfilesPath),
575
+ chatOverridesPath: text("chatOverridesPath", defaults.chatOverridesPath),
280
576
  soulPath: text("soulPath", defaults.soulPath),
281
577
  soulName: text("soulName", defaults.soulName),
578
+ home: text("home", defaults.home),
282
579
  agent: text("agent", defaults.agent),
283
580
  model,
284
581
  sendDelayMs: nonNegative("sendDelayMs", defaults.sendDelayMs),
@@ -300,9 +597,60 @@ function createConfigSchema(
300
597
  defaults.proactive.probabilityPerHour,
301
598
  ),
302
599
  tickSeconds: positive("proactive.tickSeconds", defaults.proactive.tickSeconds),
600
+ allowGroups: idList(
601
+ "proactive.allowGroups",
602
+ defaults.proactive.allowGroups,
603
+ "群号",
604
+ ).default([...defaults.proactive.allowGroups]),
605
+ allowUsers: idList("proactive.allowUsers", defaults.proactive.allowUsers, "QQ 号").default([
606
+ ...defaults.proactive.allowUsers,
607
+ ]),
303
608
  })
304
609
  .prefault({})
305
610
  .catch(defaults.proactive),
611
+ wake: z
612
+ .object({
613
+ prefixes: stringList("wake.prefixes", defaults.wake.prefixes).default([
614
+ ...defaults.wake.prefixes,
615
+ ]),
616
+ ignoreAtAll: boolean("wake.ignoreAtAll", defaults.wake.ignoreAtAll),
617
+ replyToSelf: boolean("wake.replyToSelf", defaults.wake.replyToSelf),
618
+ ignoreAtOthers: boolean("wake.ignoreAtOthers", defaults.wake.ignoreAtOthers),
619
+ })
620
+ .prefault({})
621
+ .catch(defaults.wake),
622
+ reply: z
623
+ .object({
624
+ minDelayMs: nonNegative("reply.minDelayMs", defaults.reply.minDelayMs),
625
+ maxDelayMs: nonNegative("reply.maxDelayMs", defaults.reply.maxDelayMs),
626
+ segmentChars: integer("reply.segmentChars", defaults.reply.segmentChars, 1),
627
+ forwardThresholdChars: nonNegative(
628
+ "reply.forwardThresholdChars",
629
+ defaults.reply.forwardThresholdChars,
630
+ ),
631
+ })
632
+ .prefault({})
633
+ .catch(defaults.reply),
634
+ trace: z
635
+ .object({
636
+ enabled: boolean("trace.enabled", defaults.trace.enabled),
637
+ dir: z
638
+ .unknown()
639
+ .optional()
640
+ .transform((value) => {
641
+ if (value === undefined || value === null) return defaults.trace.dir
642
+ if (typeof value !== "string") {
643
+ warn(`${label("trace.dir")} 必须是字符串:${String(value)}`)
644
+ return defaults.trace.dir
645
+ }
646
+ // 空目录是有意义的:表示与日志同目录。
647
+ return value.trim()
648
+ }),
649
+ maxSizeMb: positive("trace.maxSizeMb", defaults.trace.maxSizeMb),
650
+ retentionDays: integer("trace.retentionDays", defaults.trace.retentionDays, 1),
651
+ })
652
+ .prefault({})
653
+ .catch(defaults.trace),
306
654
  reminder: z
307
655
  .object({
308
656
  enabled: boolean("reminder.enabled", defaults.reminder.enabled),
@@ -310,16 +658,91 @@ function createConfigSchema(
310
658
  })
311
659
  .prefault({})
312
660
  .catch(defaults.reminder),
661
+ keepAlive: z
662
+ .object({
663
+ enabled: boolean("keepAlive.enabled", defaults.keepAlive.enabled),
664
+ seconds: positive("keepAlive.seconds", defaults.keepAlive.seconds),
665
+ })
666
+ .prefault({})
667
+ .catch(defaults.keepAlive),
668
+ history: z
669
+ .object({
670
+ count: nonNegative("history.count", defaults.history.count),
671
+ })
672
+ .prefault({})
673
+ .catch(defaults.history),
674
+ rateLimit: z
675
+ .object({
676
+ maxPerMinute: nonNegative("rateLimit.maxPerMinute", defaults.rateLimit.maxPerMinute),
677
+ maxPerHour: nonNegative("rateLimit.maxPerHour", defaults.rateLimit.maxPerHour),
678
+ minGapMs: nonNegative("rateLimit.minGapMs", defaults.rateLimit.minGapMs),
679
+ stall: boolean("rateLimit.stall", defaults.rateLimit.stall),
680
+ stallMaxWaitMs: nonNegative("rateLimit.stallMaxWaitMs", defaults.rateLimit.stallMaxWaitMs),
681
+ })
682
+ .prefault({})
683
+ .catch(defaults.rateLimit),
684
+ sensitive: z
685
+ .object({
686
+ enabled: boolean("sensitive.enabled", defaults.sensitive.enabled),
687
+ })
688
+ .prefault({})
689
+ .catch(defaults.sensitive),
690
+ events: z
691
+ .object({
692
+ subscribe: stringList("events.subscribe", defaults.events.subscribe),
693
+ notices: stringList("events.notices", defaults.events.notices),
694
+ inject: boolean("events.inject", defaults.events.inject),
695
+ })
696
+ .prefault({
697
+ subscribe: [...defaults.events.subscribe],
698
+ notices: [...defaults.events.notices],
699
+ })
700
+ .catch(defaults.events),
701
+ log: z
702
+ .object({
703
+ level: logLevel("log.level", defaults.log.level),
704
+ dir: z
705
+ .unknown()
706
+ .optional()
707
+ .transform((value) => {
708
+ if (value === undefined || value === null) return defaults.log.dir
709
+ if (typeof value !== "string") {
710
+ warn(`${label("log.dir")} 必须是字符串:${String(value)}`)
711
+ return defaults.log.dir
712
+ }
713
+ // 空目录是有意义的:表示用 XDG 状态目录。
714
+ return value.trim()
715
+ }),
716
+ maxSize: requiredText("log.maxSize", defaults.log.maxSize),
717
+ maxFiles: integer("log.maxFiles", defaults.log.maxFiles, 1),
718
+ })
719
+ .prefault({})
720
+ .catch(defaults.log),
721
+ media: z
722
+ .object({
723
+ allowedDirs: mediaDirs,
724
+ })
725
+ .prefault({})
726
+ .catch(defaults.media),
313
727
  })
314
728
  }
315
729
 
316
- const ENV_VARS = {
730
+ /** 配置项到环境变量名的映射。 */
731
+ export const ENV_VARS = {
317
732
  "napcat.url": "NAPCAT_WS_URL",
318
733
  "napcat.token": "NAPCAT_WS_TOKEN",
319
- groups: "QQ_TARGET_GROUPS",
320
- users: "QQ_TARGET_USERS",
734
+ "access.allow.groups": "QQ_ALLOW_GROUPS",
735
+ "access.allow.users": "QQ_ALLOW_USERS",
736
+ "access.deny.groups": "QQ_DENY_GROUPS",
737
+ "access.deny.users": "QQ_DENY_USERS",
738
+ "access.allowAllWhenEmpty": "QQ_ALLOW_ALL_WHEN_EMPTY",
739
+ ownerQQ: "QQ_OWNER_QQ",
740
+ admins: "QQ_ADMINS",
741
+ toolProfilesPath: "QQ_TOOL_PROFILES",
742
+ chatOverridesPath: "QQ_CHAT_OVERRIDES",
321
743
  soulPath: "QQ_BOT_SOUL_PATH",
322
744
  soulName: "QQ_BOT_SOUL_NAME",
745
+ home: "QQ_BOT_HOME",
323
746
  agent: "QQ_BOT_AGENT",
324
747
  model: "QQ_BOT_MODEL",
325
748
  sendDelayMs: "QQ_SEND_DELAY_MS",
@@ -330,51 +753,128 @@ const ENV_VARS = {
330
753
  "proactive.startProbability": "QQ_PROACTIVE_P_START",
331
754
  "proactive.probabilityPerHour": "QQ_PROACTIVE_P_SLOPE_PER_HOUR",
332
755
  "proactive.tickSeconds": "QQ_PROACTIVE_TICK_SECONDS",
756
+ "proactive.allowGroups": "QQ_PROACTIVE_ALLOW_GROUPS",
757
+ "proactive.allowUsers": "QQ_PROACTIVE_ALLOW_USERS",
758
+ "wake.prefixes": "QQ_WAKE_PREFIXES",
759
+ "wake.ignoreAtAll": "QQ_WAKE_IGNORE_AT_ALL",
760
+ "wake.replyToSelf": "QQ_WAKE_REPLY_TO_SELF",
761
+ "wake.ignoreAtOthers": "QQ_WAKE_IGNORE_AT_OTHERS",
762
+ "reply.minDelayMs": "QQ_REPLY_MIN_DELAY_MS",
763
+ "reply.maxDelayMs": "QQ_REPLY_MAX_DELAY_MS",
764
+ "reply.segmentChars": "QQ_REPLY_SEGMENT_CHARS",
765
+ "reply.forwardThresholdChars": "QQ_REPLY_FORWARD_THRESHOLD_CHARS",
766
+ "trace.enabled": "QQ_TRACE_ENABLED",
767
+ "trace.dir": "QQ_TRACE_DIR",
768
+ "trace.maxSizeMb": "QQ_TRACE_MAX_SIZE_MB",
769
+ "trace.retentionDays": "QQ_TRACE_RETENTION_DAYS",
333
770
  "reminder.enabled": "QQ_REMINDER_ENABLED",
334
771
  "reminder.max": "QQ_REMINDER_MAX",
772
+ "keepAlive.enabled": "QQ_KEEP_ALIVE_ENABLED",
773
+ "keepAlive.seconds": "QQ_KEEP_ALIVE_SECONDS",
774
+ "history.count": "QQ_HISTORY_COUNT",
775
+ "rateLimit.maxPerMinute": "QQ_RATE_MAX_PER_MINUTE",
776
+ "rateLimit.maxPerHour": "QQ_RATE_MAX_PER_HOUR",
777
+ "rateLimit.minGapMs": "QQ_RATE_MIN_GAP_MS",
778
+ "rateLimit.stall": "QQ_RATE_STALL",
779
+ "rateLimit.stallMaxWaitMs": "QQ_RATE_STALL_MAX_WAIT_MS",
780
+ "sensitive.enabled": "QQ_SENSITIVE_ENABLED",
781
+ "events.subscribe": "QQ_EVENT_SUBSCRIBE",
782
+ "events.notices": "QQ_EVENT_NOTICES",
783
+ "events.inject": "QQ_EVENT_INJECT",
784
+ "log.level": "QQ_LOG_LEVEL",
785
+ "log.dir": "QQ_LOG_DIR",
786
+ "log.maxSize": "QQ_LOG_MAX_SIZE",
787
+ "log.maxFiles": "QQ_LOG_MAX_FILES",
788
+ "media.allowedDirs": "QQ_MEDIA_ALLOWED_DIRS",
335
789
  } as const
336
790
 
337
791
  const OPTION_KEYS = new Set([
338
792
  "napcat",
339
- "groups",
340
- "users",
793
+ "access",
794
+ "ownerQQ",
795
+ "admins",
796
+ "toolProfilesPath",
797
+ "chatOverridesPath",
341
798
  "soulPath",
342
799
  "soulName",
800
+ "home",
343
801
  "agent",
344
802
  "model",
345
803
  "sendDelayMs",
346
804
  "warnLength",
347
805
  "reuseSession",
348
806
  "proactive",
807
+ "wake",
808
+ "reply",
809
+ "trace",
349
810
  "reminder",
811
+ "keepAlive",
812
+ "history",
813
+ "rateLimit",
814
+ "sensitive",
815
+ "events",
816
+ "log",
817
+ "media",
350
818
  ])
351
819
 
352
820
  const NESTED_OPTION_KEYS: Record<string, ReadonlySet<string>> = {
353
821
  napcat: new Set(["url", "token"]),
822
+ access: new Set(["allow", "deny", "allowAllWhenEmpty"]),
823
+ "access.allow": new Set(["groups", "users"]),
824
+ "access.deny": new Set(["groups", "users"]),
354
825
  proactive: new Set([
355
826
  "enabled",
356
827
  "silenceThresholdSeconds",
357
828
  "startProbability",
358
829
  "probabilityPerHour",
359
830
  "tickSeconds",
831
+ "allowGroups",
832
+ "allowUsers",
360
833
  ]),
834
+ wake: new Set(["prefixes", "ignoreAtAll", "replyToSelf", "ignoreAtOthers"]),
835
+ reply: new Set(["minDelayMs", "maxDelayMs", "segmentChars", "forwardThresholdChars"]),
836
+ trace: new Set(["enabled", "dir", "maxSizeMb", "retentionDays"]),
361
837
  reminder: new Set(["enabled", "max"]),
838
+ keepAlive: new Set(["enabled", "seconds"]),
839
+ history: new Set(["count"]),
840
+ rateLimit: new Set(["maxPerMinute", "maxPerHour", "minGapMs", "stall", "stallMaxWaitMs"]),
841
+ sensitive: new Set(["enabled"]),
842
+ events: new Set(["subscribe", "notices", "inject"]),
843
+ log: new Set(["level", "dir", "maxSize", "maxFiles"]),
844
+ media: new Set(["allowedDirs"]),
362
845
  }
363
846
 
364
- /** 报告被 schema 静默剥离的未知配置项。 */
847
+ /** 改过名的配置项:给出迁移提示而不是笼统的“未知配置项”。 */
848
+ const RENAMED_OPTIONS: Record<string, string> = {
849
+ groups: "access.allow.groups",
850
+ users: "access.allow.users",
851
+ }
852
+
853
+ /**
854
+ * 报告被 schema 静默剥离的未知配置项。
855
+ *
856
+ * 按层级逐层检查:`access.allow.groups` 这类嵌套路径也能报出来。
857
+ */
365
858
  function warnUnknownKeys(options: Record<string, unknown>, warn: ConfigWarning): void {
366
- for (const key of Object.keys(options)) {
367
- if (!OPTION_KEYS.has(key)) {
368
- warn(`插件选项 未知配置项:${key}`)
369
- continue
370
- }
371
- const allowed = NESTED_OPTION_KEYS[key]
372
- const value = options[key]
373
- if (!allowed || !value || typeof value !== "object" || Array.isArray(value)) continue
374
- for (const nested of Object.keys(value)) {
375
- if (!allowed.has(nested)) warn(`插件选项 ${key}.${nested} 未知配置项`)
859
+ const walk = (value: Record<string, unknown>, path: string): void => {
860
+ const allowed = path === "" ? OPTION_KEYS : NESTED_OPTION_KEYS[path]
861
+ for (const key of Object.keys(value)) {
862
+ const childPath = path ? `${path}.${key}` : key
863
+ if (allowed && !allowed.has(key)) {
864
+ const renamed = RENAMED_OPTIONS[childPath]
865
+ warn(
866
+ renamed
867
+ ? `${MIGRATION_WARNING_PREFIX} 插件选项 ${childPath} 已移除,请改用 ${renamed}`
868
+ : `插件选项 未知配置项:${childPath}`,
869
+ )
870
+ continue
871
+ }
872
+ const child = value[key]
873
+ if (!child || typeof child !== "object" || Array.isArray(child)) continue
874
+ walk(child as Record<string, unknown>, childPath)
376
875
  }
377
876
  }
877
+ walk(options, "")
378
878
  }
379
879
 
380
880
  function envLabel(path: string): string {
@@ -422,6 +922,32 @@ export function resolveConfig(
422
922
  const optionsSchema = createConfigSchema(base, base.napcat, (path) => `插件选项 ${path}`, warn)
423
923
  const parsed: RawConfig = optionsSchema.parse(options)
424
924
 
925
+ // 只保留认识的事件类别:写错的类别直接告警,不静默失效。
926
+ const subscribe: string[] = []
927
+ for (const category of parsed.events.subscribe) {
928
+ if (!EVENT_CATEGORIES.includes(category)) {
929
+ warn(`events.subscribe 忽略未知类别:${category}`)
930
+ continue
931
+ }
932
+ if (!subscribe.includes(category)) subscribe.push(category)
933
+ }
934
+
935
+ // 旧的名单环境变量已经移除:给出醒目的迁移提示,避免升级后机器人静默失联。
936
+ for (const [name, replacement] of Object.entries(RENAMED_ENV_VARS)) {
937
+ if (env[name] !== undefined) {
938
+ warn(
939
+ `${MIGRATION_WARNING_PREFIX} 环境变量 ${name} 已移除,请改用 ${replacement};未迁移时机器人不会响应任何消息`,
940
+ )
941
+ }
942
+ }
943
+
944
+ // owner 必须能私聊到机器人,否则管理命令无处触发:拒绝名单里的 owner 豁免。
945
+ const denyUsers = [...parsed.access.deny.users]
946
+ if (parsed.ownerQQ !== undefined && denyUsers.includes(parsed.ownerQQ)) {
947
+ warn(`ownerQQ ${parsed.ownerQQ} 在 access.deny.users 里,已豁免:owner 的私聊必须可用`)
948
+ denyUsers.splice(denyUsers.indexOf(parsed.ownerQQ), 1)
949
+ }
950
+
425
951
  // 先输出告警,避免 URL 缺失时把已经发现的问题一起吞掉。
426
952
  for (const warning of warnings) onWarning(warning)
427
953
 
@@ -434,10 +960,38 @@ export function resolveConfig(
434
960
 
435
961
  return {
436
962
  ...parsed,
437
- groups: [...parsed.groups],
438
- users: [...parsed.users],
439
- proactive: { ...parsed.proactive },
963
+ access: {
964
+ allow: {
965
+ groups: [...parsed.access.allow.groups],
966
+ users: [...parsed.access.allow.users],
967
+ },
968
+ deny: {
969
+ groups: [...parsed.access.deny.groups],
970
+ users: denyUsers,
971
+ },
972
+ allowAllWhenEmpty: parsed.access.allowAllWhenEmpty,
973
+ },
974
+ admins: [...parsed.admins],
975
+ proactive: {
976
+ ...parsed.proactive,
977
+ allowGroups: [...parsed.proactive.allowGroups],
978
+ allowUsers: [...parsed.proactive.allowUsers],
979
+ },
980
+ wake: { ...parsed.wake, prefixes: [...parsed.wake.prefixes] },
981
+ reply: { ...parsed.reply },
982
+ trace: { ...parsed.trace },
440
983
  reminder: { ...parsed.reminder },
984
+ keepAlive: { ...parsed.keepAlive },
985
+ history: { ...parsed.history },
986
+ rateLimit: { ...parsed.rateLimit },
987
+ sensitive: { ...parsed.sensitive },
988
+ events: {
989
+ subscribe,
990
+ notices: [...parsed.events.notices],
991
+ inject: parsed.events.inject,
992
+ },
993
+ log: { ...parsed.log },
994
+ media: { allowedDirs: [...parsed.media.allowedDirs] },
441
995
  napcat: { url, token: parsed.napcat.token },
442
996
  }
443
997
  }