@cmach_socket/opencode-qq-bot 0.5.1 → 0.6.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.
package/src/instance.ts CHANGED
@@ -7,8 +7,13 @@
7
7
  *
8
8
  * 槽位绑定到机器人固定的工作目录:只有同一目录的实例才能互相接管,
9
9
  * 否则会话上下文会落在不同项目里。
10
+ *
11
+ * 接管时旧实例把在途状态留在注册表里,新实例取走并继续,
12
+ * 免得正在跑的那一轮在上游白跑、回复丢掉。
10
13
  */
11
14
 
15
+ import type { HandoverState } from "./session/manager"
16
+
12
17
  export interface PluginInstance {
13
18
  dispose?: () => Promise<void>
14
19
  /** 实例来源描述,仅用于日志。 */
@@ -20,6 +25,14 @@ export interface InstanceLease {
20
25
  setDispose(dispose: () => Promise<void>): void
21
26
  /** Clears the slot only when this lease still owns it. */
22
27
  release(): void
28
+ /** 本实例是否已经被更新的实例接管。 */
29
+ superseded(): boolean
30
+ /**
31
+ * 把在途状态留给接管本实例的新实例。
32
+ *
33
+ * 只有真的被接管时才留:正常卸载没有接手方,留着也没用。
34
+ */
35
+ handover(states: readonly HandoverState[]): void
23
36
  }
24
37
 
25
38
  export interface InstanceClaim {
@@ -32,6 +45,8 @@ export interface InstanceClaim {
32
45
 
33
46
  interface Host {
34
47
  active?: { directory: string; instance: PluginInstance }
48
+ /** 上一实例留下的在途状态,由接管它的新实例取走。 */
49
+ handover?: HandoverState[]
35
50
  }
36
51
 
37
52
  const HOST_KEY = "__opencodeQQBotHost__"
@@ -45,6 +60,18 @@ function host(): Host {
45
60
  return created
46
61
  }
47
62
 
63
+ /**
64
+ * 取走上一实例留下的在途状态。
65
+ *
66
+ * 取走即清空,避免陈旧的状态被后来的实例误当成自己的。
67
+ */
68
+ export function takeHandover(): HandoverState[] {
69
+ const state = host()
70
+ const handover = state.handover ?? []
71
+ state.handover = undefined
72
+ return handover
73
+ }
74
+
48
75
  /**
49
76
  * 占用进程内唯一的实例槽位。
50
77
  *
@@ -55,7 +82,17 @@ export function claimInstance(directory: string, label: string): InstanceClaim {
55
82
  const state = host()
56
83
  const active = state.active
57
84
  if (active && active.directory !== directory) {
58
- return { occupied: active.directory, lease: { setDispose() {}, release() {} } }
85
+ return {
86
+ occupied: active.directory,
87
+ lease: {
88
+ setDispose() {},
89
+ release() {},
90
+ superseded() {
91
+ return false
92
+ },
93
+ handover() {},
94
+ },
95
+ }
59
96
  }
60
97
  const instance: PluginInstance = { label }
61
98
  state.active = { directory, instance }
@@ -68,6 +105,18 @@ export function claimInstance(directory: string, label: string): InstanceClaim {
68
105
  release() {
69
106
  if (state.active?.instance === instance) state.active = undefined
70
107
  },
108
+ superseded() {
109
+ const active = state.active
110
+ return active !== undefined && active.instance !== instance
111
+ },
112
+ handover(states) {
113
+ // 已经有新实例接管时,这轮状态留给它;正常卸载没有接手方,留着也没用。
114
+ const active = state.active
115
+ if (!active || active.instance === instance) return
116
+ // 空状态不用覆盖:前面可能有别的实例已经留下了要交接的东西。
117
+ if (states.length === 0) return
118
+ state.handover = [...(state.handover ?? []), ...states]
119
+ },
71
120
  },
72
121
  }
73
122
  }
package/src/model-view.ts CHANGED
@@ -107,6 +107,8 @@ export function formatTimestamp(seconds: number): string {
107
107
  return TIMESTAMP_FORMAT.format(new Date(seconds * 1000))
108
108
  }
109
109
 
110
+ import type { Role } from "./tools/policy"
111
+
110
112
  /** 一条消息的模型视图。 */
111
113
  export interface ModelMessage {
112
114
  /** 发送者显示名。 */
@@ -117,14 +119,18 @@ export interface ModelMessage {
117
119
  text: string
118
120
  /** 发送时间(Unix 秒)。 */
119
121
  time: number
122
+ /** 发送者角色;owner / admin 会在模型视图里带上对应的角色标记。 */
123
+ role?: Role
120
124
  }
121
125
 
122
- /** 拼成一行模型视图消息:`[绝对时间] 名字(QQ号): 正文`。 */
126
+ /** 拼成一行模型视图消息:`[绝对时间] 名字(owner): 正文`;普通成员没有角色标记。 */
123
127
  export function formatModelMessage(message: ModelMessage): string {
124
128
  // QQ 号来自 QQ 服务,但仍是外部输入,按显示名净化一遍。
125
129
  const userId = sanitizeSenderName(message.userId)
126
130
  const name = sanitizeSenderName(message.sender) || userId || "未知用户"
127
131
  const stamp = formatTimestamp(message.time)
128
132
  const prefix = stamp ? `[${stamp}] ` : ""
129
- return `${prefix}${name}(${userId}): ${message.text.trim()}`
133
+ // 只给 owner / admin 加角色标记,让模型知道这句话是谁说的。
134
+ const role = message.role === "owner" ? "(owner)" : message.role === "admin" ? "(admin)" : ""
135
+ return `${prefix}${name}${role}: ${message.text.trim()}`
130
136
  }
@@ -2,11 +2,13 @@ import {
2
2
  NapLink,
3
3
  type GroupMessageEvent,
4
4
  type MessageSegment,
5
+ type NoticeEvent,
5
6
  type OneBotApi,
6
7
  type PrivateMessageEvent,
7
8
  } from "@naplink/naplink"
8
9
  import type { Logger } from "../logger"
9
10
  import type { NapcatConfig } from "../config"
11
+ import { redactUrl } from "../sensitive"
10
12
 
11
13
  const MEDIA_SEGMENT_TYPES = ["image", "video", "record", "audio", "file"] as const
12
14
 
@@ -101,7 +103,11 @@ export class QQClient {
101
103
  // 每次(重)连成功都刷新机器人 QQ 号,自动重连后 selfId 依然可用。
102
104
  this.link.on("connect", () => {
103
105
  void this.refreshBotId().then(() => {
104
- this.logger.info("NapCat 已连接", this.config.url, this.botId ? `bot=${this.botId}` : "")
106
+ this.logger.info(
107
+ "NapCat 已连接",
108
+ redactUrl(this.config.url),
109
+ this.botId ? `bot=${this.botId}` : "",
110
+ )
105
111
  })
106
112
  })
107
113
  }
@@ -179,6 +185,11 @@ export class QQClient {
179
185
  this.link.on("message.private", handler)
180
186
  }
181
187
 
188
+ /** 订阅通知类事件(撤回、进退群、戳一戳等)。 */
189
+ onNotice(handler: (event: NoticeEvent) => void): void {
190
+ this.link.on("notice", handler)
191
+ }
192
+
182
193
  /** 机器人自己的 QQ 号,未连接时返回 undefined。 */
183
194
  get selfId(): string | undefined {
184
195
  return this.botId
@@ -1,6 +1,7 @@
1
1
  import type { MessageEvent, MessageSegment, OneBotApi } from "@naplink/naplink"
2
2
  import type { ChatTarget } from "../chat"
3
3
  import type { Logger } from "../logger"
4
+ import type { Role } from "../tools/policy"
4
5
  import { formatModelMessage, sanitizeSenderName } from "../model-view"
5
6
  import type { MediaStore } from "./media"
6
7
  import { createImageBudget, renderMessage, type PromptFile, type RenderContext } from "./render"
@@ -60,6 +61,8 @@ export function createHistoryProvider(deps: {
60
61
  logger: Logger
61
62
  media: MediaStore
62
63
  names?: Map<string, { name: string; expires: number }>
64
+ /** 发送者角色,用来给 owner 的历史消息加同样的标记。 */
65
+ roleOf?: (userId: string) => Role
63
66
  }): HistoryProvider {
64
67
  return {
65
68
  async fetch(target, options) {
@@ -80,12 +83,14 @@ export function createHistoryProvider(deps: {
80
83
  const rendered = await renderMessage(ctx, toEvent(entry), budget)
81
84
  const text = rendered.text.trim()
82
85
  if (!text && rendered.files.length === 0) continue
86
+ const userId = String(entry.sender?.user_id ?? entry.user_id ?? "")
83
87
  lines.push(
84
88
  formatModelMessage({
85
89
  sender: senderName(entry),
86
- userId: String(entry.sender?.user_id ?? entry.user_id ?? ""),
90
+ userId,
87
91
  text: rendered.text,
88
92
  time: entry.time ?? 0,
93
+ ...(deps.roleOf ? { role: deps.roleOf(userId) } : {}),
89
94
  }),
90
95
  )
91
96
  for (const file of rendered.files) {
@@ -41,6 +41,8 @@ export interface RenderedMessage {
41
41
  text: string
42
42
  /** 图片附件,交给 OpenCode 作为多模态输入。 */
43
43
  files: PromptFile[]
44
+ /** 这条消息回复的是机器人自己。 */
45
+ replyToSelf?: boolean
44
46
  }
45
47
 
46
48
  export interface RenderContext {
@@ -49,6 +51,8 @@ export interface RenderContext {
49
51
  logger: Logger
50
52
  /** 受控临时图片存储。 */
51
53
  media: MediaStore
54
+ /** 机器人自己的 QQ 号,用来判断回复的是不是自己。 */
55
+ selfId?: string
52
56
  /** 用户显示名缓存,避免每条消息都请求一次 API。 */
53
57
  names?: Map<string, { name: string; expires: number }>
54
58
  }
@@ -116,6 +120,43 @@ export function mentionsUser(
116
120
  )
117
121
  }
118
122
 
123
+ /** 消息里的 @ 指向谁。 */
124
+ export interface MentionInfo {
125
+ /** @ 了机器人自己。 */
126
+ mentioned: boolean
127
+ /** @ 了全体成员。 */
128
+ atAll: boolean
129
+ /** 第一个 @ 指向的是别人。 */
130
+ atOthersFirst: boolean
131
+ }
132
+
133
+ /**
134
+ * 看清消息里的 @ 指向谁。
135
+ *
136
+ * @全体成员 在 NapCat 里是 `qq = "all"`;第一个 @ 指向别人时,
137
+ * 这条消息多半不是在跟机器人说话。
138
+ */
139
+ export function describeMentions(
140
+ message: readonly MessageSegment[],
141
+ selfId: string | undefined,
142
+ ): MentionInfo {
143
+ let mentioned = false
144
+ let atAll = false
145
+ let atOthersFirst = false
146
+ let seen = false
147
+ for (const segment of segments(message)) {
148
+ if (segment.type !== "at") continue
149
+ const qq = String(segment.data.qq)
150
+ if (!seen) {
151
+ seen = true
152
+ if (qq !== "all" && (!selfId || qq !== selfId)) atOthersFirst = true
153
+ }
154
+ if (qq === "all") atAll = true
155
+ else if (selfId && qq === selfId) mentioned = true
156
+ }
157
+ return { mentioned, atAll, atOthersFirst }
158
+ }
159
+
119
160
  /** 图片引用的预算:数量与原始字节总量,渲染过程中边用边扣。 */
120
161
  export interface ImageBudget {
121
162
  images: number
@@ -162,7 +203,8 @@ export async function resolveUserName(ctx: RenderContext, userId: string): Promi
162
203
  ? await ctx.api.getGroupMemberInfo(ctx.target.id, userId)
163
204
  : await ctx.api.getStrangerInfo(userId)
164
205
  ) as { card?: string; nickname?: string } | undefined
165
- const name = info?.card?.trim() || info?.nickname?.trim() || "未知用户"
206
+ // 群名片由群友自由填写,净化后才允许进入提示词或系统提示。
207
+ const name = sanitizeSenderName(info?.card?.trim() || info?.nickname?.trim() || "未知用户")
166
208
  ctx.names?.set(key, { name, expires: Date.now() + USER_NAME_TTL_MS })
167
209
  return name
168
210
  } catch (error) {
@@ -382,6 +424,7 @@ export async function renderMessage(
382
424
  let imageIndex = 0
383
425
 
384
426
  const replySegments = message.filter((segment) => segment.type === "reply")
427
+ let replyToSelf = false
385
428
  if (replySegments.length > 0) {
386
429
  const quoteLines = [guard.protect("<quote>")]
387
430
  for (const segment of replySegments) {
@@ -393,6 +436,8 @@ export async function renderMessage(
393
436
  const name = data.sender?.user_id
394
437
  ? sanitizeSenderName(await resolveUserName(ctx, String(data.sender.user_id)))
395
438
  : "未知用户"
439
+ // 引用的是机器人自己:这条消息是在跟机器人说话。
440
+ if (ctx.selfId && String(data.sender?.user_id ?? "") === ctx.selfId) replyToSelf = true
396
441
  const quoted = await renderForwardSegments(
397
442
  ctx,
398
443
  data.message ?? [],
@@ -505,5 +550,5 @@ export async function renderMessage(
505
550
  // 整条消息拼好之后再整体净化:群友把结构标签拆成两段发过来,
506
551
  // 逐段净化匹配不到,只有整体净化才拦得住。
507
552
  const text = guard.restore(neutralizeStructureTags(textBuffer.join("")))
508
- return { text, files }
553
+ return { text, files, ...(replyToSelf ? { replyToSelf: true } : {}) }
509
554
  }
package/src/outbound.ts CHANGED
@@ -3,6 +3,34 @@ import removeMd from "remove-markdown"
3
3
  /** QQ 单条消息的保守长度上限,超过时按段发送。 */
4
4
  export const MAX_MESSAGE_CHARS = 4000
5
5
 
6
+ /** 分段发送的节奏参数。 */
7
+ export interface ReplyRhythm {
8
+ /** 固定间隔(毫秒),兼容旧的 `sendDelayMs`。 */
9
+ sendDelayMs: number
10
+ /** 随机间隔下限(毫秒)。 */
11
+ minDelayMs: number
12
+ /** 随机间隔上限(毫秒)。 */
13
+ maxDelayMs: number
14
+ }
15
+
16
+ /**
17
+ * 算出两段之间要等多久。
18
+ *
19
+ * 配了随机区间就在区间里等,看起来更像人在分条打字;
20
+ * 没配随机区间就沿用旧的固定间隔,不改变原有行为。
21
+ */
22
+ export function segmentDelayMs(rhythm: ReplyRhythm, random: () => number = Math.random): number {
23
+ const min = Math.max(0, Math.floor(rhythm.minDelayMs))
24
+ const max = Math.max(0, Math.floor(rhythm.maxDelayMs))
25
+ if (max > 0) {
26
+ const low = Math.min(min, max)
27
+ if (max === low) return low
28
+ return low + Math.floor(random() * (max - low + 1))
29
+ }
30
+ if (min > 0) return min
31
+ return Math.max(0, Math.floor(rhythm.sendDelayMs))
32
+ }
33
+
6
34
  /**
7
35
  * 剥离 markdown 的选项。
8
36
  *
@@ -0,0 +1,322 @@
1
+ import { readFile, stat } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { type ChatTarget, targetKey } from "./chat"
4
+ import { parseModelRef, type ModelRef } from "./config"
5
+ import type { Logger } from "./logger"
6
+
7
+ /** 唤醒方式:决定群里的消息要不要让模型必须回复。 */
8
+ export type WakeMode = "all" | "mention" | "prefix" | "none"
9
+
10
+ /** 全部合法的唤醒方式。 */
11
+ export const WAKE_MODES: readonly WakeMode[] = ["all", "mention", "prefix", "none"]
12
+
13
+ /** 触发必回的原因,给模型一句准确的话。 */
14
+ export type WakeReason = "private" | "all" | "mention" | "prefix" | "at_all" | "reply"
15
+
16
+ /** 一次唤醒判定需要的消息特征。 */
17
+ export interface WakeContext {
18
+ /** 消息里 @ 了机器人。 */
19
+ mentioned: boolean
20
+ /** 消息里 @ 了全体成员。 */
21
+ atAll: boolean
22
+ /** 消息里第一个 @ 指向的是别人。 */
23
+ atOthersFirst: boolean
24
+ /** 这条消息回复的是机器人自己。 */
25
+ replyToSelf: boolean
26
+ /** 消息正文。 */
27
+ text: string
28
+ }
29
+
30
+ /** 全局唤醒策略。 */
31
+ export interface WakePolicy {
32
+ /** 全局唤醒前缀,命中即必回。 */
33
+ prefixes: string[]
34
+ /** 是否忽略 @全体成员。 */
35
+ ignoreAtAll: boolean
36
+ /** 回复机器人自己的消息是否必回。 */
37
+ replyToSelf: boolean
38
+ /** 群里第一个 @ 指向别人时是否不唤醒机器人。 */
39
+ ignoreAtOthers: boolean
40
+ }
41
+
42
+ /** 内置的全局唤醒策略。 */
43
+ export const DEFAULT_WAKE_POLICY: WakePolicy = {
44
+ prefixes: ["/"],
45
+ ignoreAtAll: true,
46
+ replyToSelf: true,
47
+ ignoreAtOthers: true,
48
+ }
49
+
50
+ /** 唤醒判定的结果。 */
51
+ export interface WakeDecision {
52
+ /** 本轮是否必须回复。 */
53
+ required: boolean
54
+ /** 触发必回的原因。 */
55
+ reason?: WakeReason
56
+ /** 这条消息明确不是在跟机器人说话,别插话。 */
57
+ suppress?: boolean
58
+ }
59
+
60
+ /** 主动说话的白名单。 */
61
+ export interface ProactiveScope {
62
+ /** 只在这些群里主动说话;为空表示一个都不放行。 */
63
+ allowGroups: number[]
64
+ /** 只在这些私聊里主动说话;为空表示一个都不放行。 */
65
+ allowUsers: number[]
66
+ }
67
+
68
+ /** 单个聊天的行为覆盖。 */
69
+ export interface ChatOverride {
70
+ /** 唤醒方式,缺省按被 @ 才必回。 */
71
+ wake?: WakeMode
72
+ /** 唤醒前缀,`wake` 为 `prefix` 时用。 */
73
+ prefix?: string
74
+ /** 是否允许主动说话,false 表示这个聊天不主动开口。 */
75
+ proactive?: boolean
76
+ /** 这个聊天主动说话的概率,0 到 1;缺省按全局公式计算。 */
77
+ proactiveProbability?: number
78
+ /** 覆盖该聊天使用的 OpenCode agent。 */
79
+ agent?: string
80
+ /** 覆盖该聊天使用的模型,格式 `provider/model[/variant]`。 */
81
+ model?: ModelRef
82
+ /** 覆盖该聊天使用的角色设定文件路径。 */
83
+ soul?: string
84
+ }
85
+
86
+ /** `chat-overrides.json` 的结构。 */
87
+ export interface ChatOverridesFile {
88
+ /** 按聊天指定的行为覆盖:`group:100` / `private:200`。 */
89
+ chats: Record<string, ChatOverride>
90
+ }
91
+
92
+ /** 内置默认值:没有任何覆盖,全部按默认行为走。 */
93
+ export function defaultChatOverrides(): ChatOverridesFile {
94
+ return { chats: {} }
95
+ }
96
+
97
+ /** 默认的配置文件位置:当前工作目录下的 `chat-overrides.json`。 */
98
+ export function defaultChatOverridesPath(): string {
99
+ return join(process.cwd(), "chat-overrides.json")
100
+ }
101
+
102
+ /**
103
+ * 解析并校验覆盖配置。
104
+ *
105
+ * 写错的字段只忽略这一项并告警,其余照常生效:一处笔误不该让整个文件失效。
106
+ */
107
+ export function parseChatOverrides(
108
+ value: unknown,
109
+ warn: (message: string) => void,
110
+ ): ChatOverridesFile {
111
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
112
+ warn("会话覆盖必须是对象,已忽略")
113
+ return defaultChatOverrides()
114
+ }
115
+ const raw = value as Record<string, unknown>
116
+ const source = raw.chats
117
+ if (source === undefined) return defaultChatOverrides()
118
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
119
+ warn("chats 必须是对象,已忽略")
120
+ return defaultChatOverrides()
121
+ }
122
+ const chats: Record<string, ChatOverride> = {}
123
+ for (const [key, entry] of Object.entries(source as Record<string, unknown>)) {
124
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
125
+ warn(`会话覆盖 ${key} 必须是对象,已忽略`)
126
+ continue
127
+ }
128
+ const record = entry as Record<string, unknown>
129
+ const override: ChatOverride = {}
130
+ if (record.wake !== undefined) {
131
+ if (typeof record.wake === "string" && WAKE_MODES.includes(record.wake as WakeMode)) {
132
+ override.wake = record.wake as WakeMode
133
+ } else {
134
+ warn(`会话覆盖 ${key} 的 wake 只能是 ${WAKE_MODES.join(" / ")},已忽略`)
135
+ }
136
+ }
137
+ if (record.prefix !== undefined) {
138
+ if (typeof record.prefix === "string") {
139
+ const prefix = record.prefix.trim()
140
+ if (prefix) override.prefix = prefix
141
+ } else {
142
+ warn(`会话覆盖 ${key} 的 prefix 必须是字符串,已忽略`)
143
+ }
144
+ }
145
+ if (record.proactive !== undefined) {
146
+ if (typeof record.proactive === "boolean") {
147
+ override.proactive = record.proactive
148
+ } else {
149
+ warn(`会话覆盖 ${key} 的 proactive 必须是布尔值,已忽略`)
150
+ }
151
+ }
152
+ if (record.proactiveProbability !== undefined) {
153
+ const raw = record.proactiveProbability
154
+ const value =
155
+ typeof raw === "number"
156
+ ? raw
157
+ : typeof raw === "string" && raw.trim()
158
+ ? Number(raw.trim())
159
+ : Number.NaN
160
+ if (Number.isFinite(value) && value >= 0 && value <= 1) {
161
+ override.proactiveProbability = value
162
+ } else {
163
+ warn(`会话覆盖 ${key} 的 proactiveProbability 必须是 0 到 1 之间的数字,已忽略`)
164
+ }
165
+ }
166
+ if (record.agent !== undefined) {
167
+ if (typeof record.agent === "string" && record.agent.trim()) {
168
+ override.agent = record.agent.trim()
169
+ } else {
170
+ warn(`会话覆盖 ${key} 的 agent 必须是非空字符串,已忽略`)
171
+ }
172
+ }
173
+ if (record.model !== undefined) {
174
+ const model = parseModelRef(record.model)
175
+ if (model) override.model = model
176
+ else warn(`会话覆盖 ${key} 的 model 必须是 provider/model[/variant],已忽略`)
177
+ }
178
+ if (record.soul !== undefined) {
179
+ if (typeof record.soul === "string" && record.soul.trim()) {
180
+ override.soul = record.soul.trim()
181
+ } else {
182
+ warn(`会话覆盖 ${key} 的 soul 必须是非空字符串,已忽略`)
183
+ }
184
+ }
185
+ if (override.wake === "prefix" && !override.prefix) {
186
+ // 没有前缀就没法判断,改回被 @ 才必回,别让群变成完全不回话。
187
+ warn(`会话覆盖 ${key} 使用 prefix 唤醒但没有写 prefix,已按被 @ 才必回处理`)
188
+ delete override.wake
189
+ }
190
+ chats[key] = override
191
+ }
192
+ return { chats }
193
+ }
194
+
195
+ /** 会话覆盖的读取与热加载。 */
196
+ export class ChatOverrides {
197
+ private cached?: { mtime: number; file: ChatOverridesFile }
198
+
199
+ constructor(
200
+ private readonly path: string,
201
+ private readonly logger: Logger,
202
+ ) {}
203
+
204
+ /** 当前生效的覆盖配置;文件改动后按 mtime 重新读取。 */
205
+ async current(): Promise<ChatOverridesFile> {
206
+ const info = await stat(this.path).catch(() => undefined)
207
+ if (!info) {
208
+ if (!this.cached) this.cached = { mtime: 0, file: defaultChatOverrides() }
209
+ return this.cached.file
210
+ }
211
+ if (this.cached && this.cached.mtime === info.mtimeMs) return this.cached.file
212
+ try {
213
+ const text = await readFile(this.path, "utf8")
214
+ const file = parseChatOverrides(JSON.parse(text), (message) => {
215
+ this.logger.warn(`会话覆盖 ${this.path}:${message}`)
216
+ })
217
+ this.cached = { mtime: info.mtimeMs, file }
218
+ return file
219
+ } catch (error) {
220
+ // 半写或语法错误时保留上一份可用配置,等下一次写入后再加载。
221
+ this.logger.warn(`会话覆盖 ${this.path} 读取失败,继续沿用上一份配置`, error)
222
+ if (!this.cached) this.cached = { mtime: 0, file: defaultChatOverrides() }
223
+ return this.cached.file
224
+ }
225
+ }
226
+
227
+ /** 某个聊天生效的覆盖配置。 */
228
+ async for(target: ChatTarget): Promise<ChatOverride> {
229
+ const file = await this.current()
230
+ return file.chats[targetKey(target)] ?? {}
231
+ }
232
+ }
233
+
234
+ /** 这个聊天是不是完全不响应了:群里把 wake 设成 none 就是。 */
235
+ export function chatMuted(override: ChatOverride, target: ChatTarget): boolean {
236
+ return target.kind === "group" && override.wake === "none"
237
+ }
238
+
239
+ /**
240
+ * 这次要不要让模型必须回复,以及为什么。
241
+ *
242
+ * 判定顺序:私聊必回;聊天自己写死的唤醒方式优先;被直接 @ 一定回;
243
+ * 群里第一个 @ 指向别人时这条消息不是跟机器人说的;
244
+ * 其余看全局前缀、@全体成员与回复机器人自己。
245
+ */
246
+ export function wakeDecision(
247
+ override: ChatOverride,
248
+ target: ChatTarget,
249
+ context: WakeContext,
250
+ policy: WakePolicy = DEFAULT_WAKE_POLICY,
251
+ ): WakeDecision {
252
+ // 私聊都是冲着机器人来的,永远必回。
253
+ if (target.kind === "private") return { required: true, reason: "private" }
254
+ // 静音的群完全不理。
255
+ if (override.wake === "none") return { required: false }
256
+ // 逐条回复的群每条都要回:写死的配置优先于其它规则。
257
+ if (override.wake === "all") return { required: true, reason: "all" }
258
+ // 被直接 @ 时一定回,不管这个聊天配了什么。
259
+ if (context.mentioned) return { required: true, reason: "mention" }
260
+ // 群里第一个 @ 的是别人:这条消息不是跟机器人说的,别插话。
261
+ if (policy.ignoreAtOthers && context.atOthersFirst) return { required: false, suppress: true }
262
+ // 前缀模式只看这个聊天自己的前缀。
263
+ if (override.wake === "prefix") {
264
+ const prefix = override.prefix
265
+ return prefix && context.text.trimStart().startsWith(prefix)
266
+ ? { required: true, reason: "prefix" }
267
+ : { required: false }
268
+ }
269
+ // 全局前缀。
270
+ for (const prefix of policy.prefixes) {
271
+ if (prefix && context.text.trimStart().startsWith(prefix)) {
272
+ return { required: true, reason: "prefix" }
273
+ }
274
+ }
275
+ // @全体成员:默认忽略,群里点名全体成员多半不是在跟机器人说话。
276
+ if (context.atAll && !policy.ignoreAtAll) return { required: true, reason: "at_all" }
277
+ // 回复了机器人自己:顺着回。
278
+ if (context.replyToSelf && policy.replyToSelf) return { required: true, reason: "reply" }
279
+ return { required: false }
280
+ }
281
+
282
+ /**
283
+ * 这个聊天允不允许主动说话。
284
+ *
285
+ * 默认拒绝:白名单为空表示一个都不放行,必须显式配置才会主动开口。
286
+ * 聊天自己的覆盖里写了 `proactive: true` 才算显式打开,那一条不受白名单限制。
287
+ */
288
+ export function proactiveAllowed(
289
+ override: ChatOverride,
290
+ target: ChatTarget,
291
+ scope: ProactiveScope,
292
+ ): boolean {
293
+ if (override.proactive === false) return false
294
+ if (chatMuted(override, target)) return false
295
+ // 写死打开的聊天不受白名单限制。
296
+ if (override.proactive === true) return true
297
+ const list = target.kind === "group" ? scope.allowGroups : scope.allowUsers
298
+ // 名单为空表示这一类一个都不放行。
299
+ if (list.length === 0) return false
300
+ return list.includes(target.id)
301
+ }
302
+
303
+ /** 覆盖配置的简明描述,给 `/status` 看。 */
304
+ export function describeOverride(override: ChatOverride): string {
305
+ const parts: string[] = []
306
+ parts.push(override.wake ? `唤醒 ${override.wake}` : "唤醒 mention(默认)")
307
+ if (override.wake === "prefix") parts.push(`前缀 ${override.prefix ?? "(未设置)"}`)
308
+ parts.push(
309
+ override.proactive === true
310
+ ? "主动说话"
311
+ : override.proactive === false
312
+ ? "不主动说话"
313
+ : "主动说话跟随白名单",
314
+ )
315
+ if (override.proactiveProbability !== undefined) {
316
+ parts.push(`主动概率 ${override.proactiveProbability}`)
317
+ }
318
+ if (override.agent) parts.push(`agent ${override.agent}`)
319
+ if (override.model) parts.push(`模型 ${override.model.providerID}/${override.model.id}`)
320
+ if (override.soul) parts.push(`角色设定 ${override.soul}`)
321
+ return parts.join(",")
322
+ }