@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.
@@ -0,0 +1,174 @@
1
+ import removeMd from "remove-markdown"
2
+
3
+ /** QQ 单条消息的保守长度上限,超过时按段发送。 */
4
+ export const MAX_MESSAGE_CHARS = 4000
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
+
34
+ /**
35
+ * 剥离 markdown 的选项。
36
+ *
37
+ * 列表符号全部去掉,只留纯文本;链接与图片保留 URL,
38
+ * 否则用户拿到的是一个没有目标的引用。
39
+ */
40
+ const MARKDOWN_OPTIONS = {
41
+ stripListLeaders: true,
42
+ listUnicodeChar: "",
43
+ separateLinksAndTexts: ": ",
44
+ } as const
45
+
46
+ /** 按字素簇切分,避免把 emoji 序列、肤色修饰符和组合字符切坏。 */
47
+ const segmenter = new Intl.Segmenter("zh", { granularity: "grapheme" })
48
+
49
+ /** 判断一行是不是 markdown 表格的分隔行:每个单元格都只由 - 和 : 组成。 */
50
+ function isTableDelimiter(line: string): boolean {
51
+ const cells = line
52
+ .split("|")
53
+ .map((cell) => cell.trim())
54
+ .filter((cell) => cell.length > 0)
55
+ if (cells.length === 0) return false
56
+ return cells.every((cell) => /^:?-+:?$/.test(cell))
57
+ }
58
+
59
+ /** 一行的单元格数量:去掉首尾竖线带来的空段。 */
60
+ function cellCount(line: string): number {
61
+ const trimmed = line.trim()
62
+ const inner = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed
63
+ const body = inner.endsWith("|") ? inner.slice(0, -1) : inner
64
+ return body.split("|").length
65
+ }
66
+
67
+ /**
68
+ * 判断一行是不是表格行。
69
+ *
70
+ * 只有首尾都带竖线、且列数与表头一致的行才算;
71
+ * 否则表格后面正文里的一个竖线就会把整条正文当成表格行吞掉。
72
+ */
73
+ function isTableRow(line: string, columns: number): boolean {
74
+ const trimmed = line.trim()
75
+ if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) return false
76
+ return cellCount(trimmed) === columns
77
+ }
78
+
79
+ /**
80
+ * 丢弃 markdown 表格:表头、分隔行和数据行整块删掉,QQ 里表格没法看。
81
+ *
82
+ * 只认首尾带竖线的标准表格;表格后面的正文带着竖线也不会被当成数据行。
83
+ */
84
+ export function dropTables(content: string): string {
85
+ const lines = content.split("\n")
86
+ const kept: string[] = []
87
+ let index = 0
88
+ while (index < lines.length) {
89
+ const line = lines[index] ?? ""
90
+ const next = index + 1 < lines.length ? (lines[index + 1] ?? "") : undefined
91
+ const columns = next !== undefined ? cellCount(line) : 0
92
+ // 表头与分隔行的列数一致,才当成一张表。
93
+ if (
94
+ next !== undefined &&
95
+ isTableDelimiter(next) &&
96
+ columns > 0 &&
97
+ cellCount(next) === columns &&
98
+ isTableRow(line, columns)
99
+ ) {
100
+ index += 2
101
+ while (index < lines.length && isTableRow(lines[index] ?? "", columns)) index += 1
102
+ continue
103
+ }
104
+ kept.push(line)
105
+ index += 1
106
+ }
107
+ return kept.join("\n")
108
+ }
109
+
110
+ /** 图片语法降级成普通链接,否则剥离后会残留 markdown 的 ! 前缀。 */
111
+ function normalizeImages(content: string): string {
112
+ return content.replace(/!\[([^\]]*)\]\(/g, "[$1](")
113
+ }
114
+
115
+ /**
116
+ * 把 markdown 剥成 QQ 友好的纯文本。
117
+ *
118
+ * 表格整块丢弃;链接和图片保留 URL;列表符号去掉,只留正文。
119
+ */
120
+ export function toPlainText(content: string): string {
121
+ return removeMd(normalizeImages(dropTables(content)), MARKDOWN_OPTIONS)
122
+ }
123
+
124
+ /** 按字素簇切分文本。 */
125
+ export function splitGraphemes(content: string): string[] {
126
+ return Array.from(segmenter.segment(content), (item) => item.segment)
127
+ }
128
+
129
+ /**
130
+ * 按长度切分消息,保留原有换行与空行。
131
+ *
132
+ * 长度按字素簇计算,不会把 emoji 序列或组合字符切坏。
133
+ * 首部的空行也算内容,不会被吞掉。
134
+ */
135
+ export function splitMessage(content: string, max = MAX_MESSAGE_CHARS): string[] {
136
+ const limit = Math.max(1, max)
137
+ const chunks: string[] = []
138
+ let current = ""
139
+ let currentLength = 0
140
+ // 当前这段已经放了几行:空行长度为 0,只能靠行数区分“还没内容”和“有空行”。
141
+ let currentLines = 0
142
+ for (const line of content.split("\n")) {
143
+ const parts = splitGraphemes(line)
144
+ const separator = currentLines > 0 ? 1 : 0
145
+ const candidateLength = currentLength + separator + parts.length
146
+ if (candidateLength <= limit) {
147
+ current = currentLines > 0 ? `${current}\n${line}` : line
148
+ currentLength = candidateLength
149
+ currentLines += 1
150
+ continue
151
+ }
152
+ if (currentLines > 0) {
153
+ chunks.push(current)
154
+ current = ""
155
+ currentLength = 0
156
+ currentLines = 0
157
+ }
158
+ let rest = parts
159
+ while (rest.length > limit) {
160
+ chunks.push(rest.slice(0, limit).join(""))
161
+ rest = rest.slice(limit)
162
+ }
163
+ current = rest.join("")
164
+ currentLength = rest.length
165
+ currentLines = 1
166
+ }
167
+ if (currentLines > 0 && (current.length > 0 || chunks.length === 0)) chunks.push(current)
168
+ return chunks.length > 0 ? chunks : [content]
169
+ }
170
+
171
+ /** 出站文本的统一处理:剥掉 markdown,再按字素簇切分。 */
172
+ export function prepareOutbound(content: string, max = MAX_MESSAGE_CHARS): string[] {
173
+ return splitMessage(toPlainText(content), max)
174
+ }
@@ -0,0 +1,312 @@
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
+ export function proactiveAllowed(
284
+ override: ChatOverride,
285
+ target: ChatTarget,
286
+ scope?: ProactiveScope,
287
+ ): boolean {
288
+ if (override.proactive === false) return false
289
+ if (chatMuted(override, target)) return false
290
+ // 写死打开的聊天不受白名单限制。
291
+ if (override.proactive === true) return true
292
+ if (!scope) return true
293
+ const list = target.kind === "group" ? scope.allowGroups : scope.allowUsers
294
+ // 名单为空表示这一类不限制。
295
+ if (list.length === 0) return true
296
+ return list.includes(target.id)
297
+ }
298
+
299
+ /** 覆盖配置的简明描述,给 `/status` 看。 */
300
+ export function describeOverride(override: ChatOverride): string {
301
+ const parts: string[] = []
302
+ parts.push(override.wake ? `唤醒 ${override.wake}` : "唤醒 mention(默认)")
303
+ if (override.wake === "prefix") parts.push(`前缀 ${override.prefix ?? "(未设置)"}`)
304
+ parts.push(override.proactive === false ? "不主动说话" : "允许主动说话")
305
+ if (override.proactiveProbability !== undefined) {
306
+ parts.push(`主动概率 ${override.proactiveProbability}`)
307
+ }
308
+ if (override.agent) parts.push(`agent ${override.agent}`)
309
+ if (override.model) parts.push(`模型 ${override.model.providerID}/${override.model.id}`)
310
+ if (override.soul) parts.push(`角色设定 ${override.soul}`)
311
+ return parts.join(",")
312
+ }