@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.
@@ -1,4 +1,5 @@
1
1
  import type { ProactiveConfig } from "../config"
2
+ import type { ChatOverride } from "../overrides"
2
3
 
3
4
  /**
4
5
  * 把“每小时目标概率”换算成单次心跳的触发概率。
@@ -20,3 +21,23 @@ export function proactiveTickProbability(
20
21
  const fraction = Math.min(1, config.tickSeconds / 3600)
21
22
  return 1 - Math.pow(1 - target, fraction)
22
23
  }
24
+
25
+ /**
26
+ * 这个聊天这一轮主动说话的概率。
27
+ *
28
+ * 聊天自己写了概率就用它:那是单次心跳的触发概率,不再随沉默时长增长。
29
+ * 沉默阈值对所有聊天一视同仁,没到阈值就不主动开口。
30
+ */
31
+ export function proactiveProbability(
32
+ override: ChatOverride,
33
+ config: Pick<
34
+ ProactiveConfig,
35
+ "startProbability" | "probabilityPerHour" | "silenceThresholdSeconds" | "tickSeconds"
36
+ >,
37
+ silenceSeconds: number,
38
+ ): number {
39
+ const silenceHours = (silenceSeconds - config.silenceThresholdSeconds) / 3600
40
+ if (silenceHours <= 0) return 0
41
+ if (override.proactiveProbability !== undefined) return override.proactiveProbability
42
+ return proactiveTickProbability(config, silenceSeconds)
43
+ }
@@ -4,7 +4,10 @@ export const SEND_MESSAGE_TOOL = "qq_send_message"
4
4
  const GUIDELINES = `
5
5
  GUIDELINES:
6
6
  你在 QQ 群聊或私聊里,你收到的消息不一定是发给你的,你需要根据上下文和语境来判断是否回复。私聊消息必须回复;群聊里只有被 @ 时才必须回复。
7
- 对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。<forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。user_name : message 是用户发给你的消息, 不同的user_name代表不同的用户,你需要根据这些消息来判断每个用户的意图和情感。
7
+ 对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。
8
+ <forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。
9
+ <history>...</history> 里面是本次会话开始之前的历史聊天记录,按时间顺序排列,用来了解之前聊过什么。
10
+ 每条消息都是 \`[26-11-07 14:33] 名字(QQ号): 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面的括号里是发送者的 QQ 号,用来区分同名的人。你需要根据这些消息来判断每个用户的意图和情感。
8
11
  重要!!!发送消息时,**必须**调用发送类工具;任何直接输出的文字都会被**完全丢弃**,不会作为消息内容发送!!!
9
12
  文本回复用 ${SEND_MESSAGE_TOOL};图片、语音、合并转发、戳一戳等用对应的 qq_* 工具,调用成功同样算作已回复。
10
13
  每轮至少调用一个发送类工具;不想回复时把 ${SEND_MESSAGE_TOOL} 的 reply 设成 false(content 可留空),相当于已读不回。群聊里不需要每一条都回复,像人一样选择性回复就行。
@@ -178,3 +178,49 @@ export class SoulStore {
178
178
  export function packageDirectory(): string {
179
179
  return import.meta.dirname
180
180
  }
181
+
182
+ /**
183
+ * 多份角色设定的持有者:默认档 + 按路径懒加载。
184
+ *
185
+ * 每个聊天可以用覆盖配置指定自己的角色设定文件;同一路径只加载一次,
186
+ * 每份设定各自监听文件变化,改完下一轮即生效。
187
+ */
188
+ export class SoulLibrary {
189
+ readonly #stores = new Map<string, SoulStore>()
190
+ #defaultStore: SoulStore | undefined
191
+
192
+ constructor(
193
+ private readonly options: SoulOptions,
194
+ private readonly logger: Logger,
195
+ ) {}
196
+
197
+ /** 加载并返回默认角色设定。 */
198
+ async loadDefault(): Promise<SoulStore> {
199
+ if (this.#defaultStore) return this.#defaultStore
200
+ const path = resolveSoulPath(this.options)
201
+ const store = new SoulStore({ ...this.options, soulPath: path }, this.logger)
202
+ await store.load()
203
+ this.#defaultStore = store
204
+ this.#stores.set(path, store)
205
+ return store
206
+ }
207
+
208
+ /** 某个路径的角色设定;路径为空时用默认档。 */
209
+ async at(path: string | undefined): Promise<SoulStore> {
210
+ const explicit = path?.trim()
211
+ if (!explicit) return this.loadDefault()
212
+ const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.cwd, explicit)
213
+ const cached = this.#stores.get(absolute)
214
+ if (cached) return cached
215
+ const store = new SoulStore({ ...this.options, soulPath: absolute }, this.logger)
216
+ await store.load()
217
+ this.#stores.set(absolute, store)
218
+ return store
219
+ }
220
+
221
+ dispose(): void {
222
+ for (const store of this.#stores.values()) store.dispose()
223
+ this.#stores.clear()
224
+ this.#defaultStore = undefined
225
+ }
226
+ }
@@ -17,16 +17,16 @@ export interface AskGuardDeps {
17
17
  }
18
18
 
19
19
  /**
20
- * 在 QQ 会话里拦截内置 question 工具,要求模型改用 qq_send_message 询问用户。
21
- * 非 QQ 会话不受影响。
20
+ * 在 QQ 消息轮次执行期间拦截内置 question 工具,要求模型改用 qq_send_message 询问用户。
21
+ * 只绑定 QQ 目标、但没有 QQ 轮次在跑的会话(人工在 TUI 里驱动)不受影响。
22
22
  */
23
23
  export async function registerAskGuard(deps: AskGuardDeps): Promise<{ dispose(): Promise<void> }> {
24
24
  const { ctx, logger, manager } = deps
25
25
  return await ctx.tool.hook("execute.before", async (event) => {
26
26
  if (event.tool !== QUESTION_TOOL) return
27
- const target = manager.targetForSession(event.sessionID)
28
- if (!target) return
29
- logger.warn(`${targetLabel(target)} 会话里模型尝试调用 ${QUESTION_TOOL} 工具,已拒绝`)
27
+ const active = manager.activeTurn(event.sessionID)
28
+ if (!active) return
29
+ logger.warn(`${targetLabel(active.target)} 会话里模型尝试调用 ${QUESTION_TOOL} 工具,已拒绝`)
30
30
  throw new Error(ASK_REFUSAL)
31
31
  })
32
32
  }
@@ -0,0 +1,45 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import { targetKey, targetLabel } from "../chat"
3
+ import type { Logger } from "../logger"
4
+ import type { SessionManager } from "../session/manager"
5
+ import type { ToolPolicy } from "./policy"
6
+
7
+ /** 会开启独立会话的工具名;不同版本分别叫 subagent 与 task。 */
8
+ const SUBAGENT_TOOLS = new Set(["subagent", "task"])
9
+
10
+ export interface ToolPolicyGuardDeps {
11
+ ctx: Plugin.Context
12
+ logger: Logger
13
+ manager: SessionManager
14
+ policy: ToolPolicy
15
+ }
16
+
17
+ /**
18
+ * 按聊天与角色拦截工具调用。
19
+ *
20
+ * 上下文钩子会把不允许的工具从列表里删掉,这里是第二道闸:
21
+ * Code Mode、并发调用或子代理绕过列表时仍然执行不了。
22
+ * 只对正在执行 QQ 轮次的会话生效,人工在 TUI 里驱动的会话不受影响。
23
+ */
24
+ export async function registerToolPolicy(
25
+ deps: ToolPolicyGuardDeps,
26
+ ): Promise<{ dispose(): Promise<void> }> {
27
+ const { ctx, logger, manager, policy } = deps
28
+ return await ctx.tool.hook("execute.before", async (event) => {
29
+ const active = manager.activeTurn(event.sessionID)
30
+ if (!active) return
31
+ // 子代理会开一个不受 QQ 聊天约束的新会话,哪怕配置档放行也一律拒绝。
32
+ if (SUBAGENT_TOOLS.has(event.tool)) {
33
+ logger.warn(`${targetLabel(active.target)} 会话里拒绝创建子代理 ${event.tool}`)
34
+ throw new Error("QQ 聊天会话里不能创建子代理:子会话不会继承按聊天的工具限制。")
35
+ }
36
+ const allowed = await policy.allow(active.role, targetKey(active.target), [event.tool])
37
+ if (allowed.size > 0) return
38
+ logger.warn(
39
+ `${targetLabel(active.target)} 会话里 ${active.role} 尝试调用工具 ${event.tool},已被工具配置拒绝`,
40
+ )
41
+ throw new Error(
42
+ `当前用户不能使用工具 ${event.tool}:工具权限由 tool-profiles.json 按聊天分配。`,
43
+ )
44
+ })
45
+ }
@@ -0,0 +1,205 @@
1
+ import { readFile, stat } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import type { QQBotConfig } from "../config"
4
+ import type { Logger } from "../logger"
5
+
6
+ /** 消息发送者的角色,决定用哪一档工具配置。 */
7
+ export type Role = "owner" | "admin" | "member"
8
+
9
+ /** 发送者角色:owner 最高,其次 admin,其余按普通成员处理。 */
10
+ export function roleOf(config: QQBotConfig, senderQQ: string): Role {
11
+ const id = Number(senderQQ)
12
+ if (config.ownerQQ !== undefined && id === config.ownerQQ) return "owner"
13
+ if (config.admins.includes(id)) return "admin"
14
+ return "member"
15
+ }
16
+
17
+ /** 一档工具配置:allow 命中且 deny 不命中的工具才放行。 */
18
+ export interface ToolProfile {
19
+ allow: string[]
20
+ deny: string[]
21
+ }
22
+
23
+ /** `tool-profiles.json` 的结构。 */
24
+ export interface ToolPolicyFile {
25
+ /** 没有按聊天指定的配置时用哪一档。 */
26
+ defaultProfile: string
27
+ /** 配置档:名字 → 允许 / 禁止的工具。 */
28
+ profiles: Record<string, ToolProfile>
29
+ /** 按聊天指定的配置档:`group:100` / `private:200` → 档名。 */
30
+ chats: Record<string, string>
31
+ }
32
+
33
+ /** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
34
+ export function defaultToolPolicy(): ToolPolicyFile {
35
+ return {
36
+ defaultProfile: "chat",
37
+ profiles: {
38
+ chat: { allow: ["websearch", "webfetch", "qq_*"], deny: [] },
39
+ readonly: { allow: ["read", "glob", "grep", "qq_*"], deny: [] },
40
+ admin: { allow: ["*"], deny: [] },
41
+ },
42
+ chats: {},
43
+ }
44
+ }
45
+
46
+ /** 默认的配置文件位置:当前工作目录下的 `tool-profiles.json`。 */
47
+ export function defaultToolProfilesPath(): string {
48
+ return join(process.cwd(), "tool-profiles.json")
49
+ }
50
+
51
+ /**
52
+ * 判断工具名是否命中通配模式。
53
+ *
54
+ * 只支持 `*`(任意长度)和 `?`(单个字符),大小写敏感,必须整名匹配。
55
+ */
56
+ export function globMatch(pattern: string, name: string): boolean {
57
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&")
58
+ const source = escaped.replace(/\*/g, ".*").replace(/\?/g, ".")
59
+ return new RegExp(`^${source}$`).test(name)
60
+ }
61
+
62
+ function readNames(value: unknown, warn: (message: string) => void, where: string): string[] {
63
+ if (value === undefined) return []
64
+ if (!Array.isArray(value)) {
65
+ warn(`${where} 必须是字符串数组`)
66
+ return []
67
+ }
68
+ const names: string[] = []
69
+ for (const entry of value) {
70
+ if (typeof entry !== "string") {
71
+ warn(`${where} 里有非字符串项:${String(entry)}`)
72
+ continue
73
+ }
74
+ const name = entry.trim()
75
+ if (!name || names.includes(name)) continue
76
+ names.push(name)
77
+ }
78
+ return names
79
+ }
80
+
81
+ /**
82
+ * 解析并校验配置内容。
83
+ *
84
+ * 解析失败不抛错:回退到内置默认值并告警,避免一个手写的逗号让机器人失去工具。
85
+ */
86
+ export function parseToolPolicy(value: unknown, warn: (message: string) => void): ToolPolicyFile {
87
+ const fallback = defaultToolPolicy()
88
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
89
+ warn("工具配置必须是对象,已回退到内置默认值")
90
+ return fallback
91
+ }
92
+ const raw = value as Record<string, unknown>
93
+ const profiles: Record<string, ToolProfile> = {}
94
+ const source = raw.profiles
95
+ if (source !== undefined) {
96
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
97
+ warn("profiles 必须是对象,已回退到内置默认值")
98
+ return fallback
99
+ }
100
+ for (const [name, entry] of Object.entries(source as Record<string, unknown>)) {
101
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
102
+ warn(`工具配置档 ${name} 必须是对象,已忽略`)
103
+ continue
104
+ }
105
+ const profile = entry as Record<string, unknown>
106
+ profiles[name] = {
107
+ allow: readNames(profile.allow, warn, `${name}.allow`),
108
+ deny: readNames(profile.deny, warn, `${name}.deny`),
109
+ }
110
+ }
111
+ }
112
+ // 用户没有覆盖的档沿用内置默认值,这样只写一档也能用。
113
+ for (const [name, profile] of Object.entries(fallback.profiles)) {
114
+ if (!profiles[name]) profiles[name] = profile
115
+ }
116
+ const defaultProfile =
117
+ typeof raw.defaultProfile === "string" && raw.defaultProfile.trim()
118
+ ? raw.defaultProfile.trim()
119
+ : fallback.defaultProfile
120
+ if (!profiles[defaultProfile]) {
121
+ warn(`defaultProfile 指向不存在的配置档 ${defaultProfile},已回退到 ${fallback.defaultProfile}`)
122
+ }
123
+ const chats: Record<string, string> = {}
124
+ if (raw.chats !== undefined) {
125
+ if (!raw.chats || typeof raw.chats !== "object" || Array.isArray(raw.chats)) {
126
+ warn("chats 必须是对象,已忽略")
127
+ } else {
128
+ for (const [key, name] of Object.entries(raw.chats as Record<string, unknown>)) {
129
+ if (typeof name !== "string" || !name.trim()) {
130
+ warn(`chats.${key} 必须是配置档名字,已忽略`)
131
+ continue
132
+ }
133
+ chats[key] = name.trim()
134
+ }
135
+ }
136
+ }
137
+ return {
138
+ defaultProfile: profiles[defaultProfile] ? defaultProfile : fallback.defaultProfile,
139
+ profiles,
140
+ chats,
141
+ }
142
+ }
143
+
144
+ /** 角色对应的配置档名字:owner 与 admin 用管理档,其他按聊天配置。 */
145
+ export function profileNameFor(file: ToolPolicyFile, role: Role, chatKey: string): string {
146
+ if (role !== "member") return file.profiles.admin ? "admin" : file.defaultProfile
147
+ const named = file.chats[chatKey]
148
+ if (named && file.profiles[named]) return named
149
+ return file.defaultProfile
150
+ }
151
+
152
+ /** 从工具名列表里筛出该配置档允许的项;deny 优先于 allow。 */
153
+ export function allowedTools(profile: ToolProfile, names: readonly string[]): string[] {
154
+ const allowed = (name: string) =>
155
+ !profile.deny.some((pattern) => globMatch(pattern, name)) &&
156
+ (profile.allow.includes("*") || profile.allow.some((pattern) => globMatch(pattern, name)))
157
+ return names.filter(allowed)
158
+ }
159
+
160
+ /** 工具配置的读取与热加载。 */
161
+ export class ToolPolicy {
162
+ private cached?: { mtime: number; file: ToolPolicyFile }
163
+
164
+ constructor(
165
+ private readonly path: string,
166
+ private readonly logger: Logger,
167
+ ) {}
168
+
169
+ /** 当前生效的配置;文件改动后按 mtime 重新读取。 */
170
+ async current(): Promise<ToolPolicyFile> {
171
+ const info = await stat(this.path).catch(() => undefined)
172
+ if (!info) {
173
+ if (!this.cached) this.cached = { mtime: 0, file: defaultToolPolicy() }
174
+ return this.cached.file
175
+ }
176
+ if (this.cached && this.cached.mtime === info.mtimeMs) return this.cached.file
177
+ try {
178
+ const text = await readFile(this.path, "utf8")
179
+ const file = parseToolPolicy(JSON.parse(text), (message) => {
180
+ this.logger.warn(`工具配置 ${this.path}:${message}`)
181
+ })
182
+ this.cached = { mtime: info.mtimeMs, file }
183
+ return file
184
+ } catch (error) {
185
+ // 半写或语法错误时保留上一份可用配置,等下一次写入后再加载。
186
+ this.logger.warn(`工具配置 ${this.path} 读取失败,继续沿用上一份配置`, error)
187
+ if (!this.cached) this.cached = { mtime: 0, file: defaultToolPolicy() }
188
+ return this.cached.file
189
+ }
190
+ }
191
+
192
+ /** 某个角色在某个聊天里能用的工具子集。 */
193
+ async allow(role: Role, chatKey: string, names: readonly string[]): Promise<Set<string>> {
194
+ const file = await this.current()
195
+ const profile = file.profiles[profileNameFor(file, role, chatKey)]
196
+ if (!profile) return new Set(names)
197
+ return new Set(allowedTools(profile, names))
198
+ }
199
+
200
+ /** 某个角色在某个聊天里生效的配置档名字,用于管理命令展示。 */
201
+ async profileOf(role: Role, chatKey: string): Promise<string> {
202
+ const file = await this.current()
203
+ return profileNameFor(file, role, chatKey)
204
+ }
205
+ }