@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/NOTICE +6 -0
- package/README.md +220 -44
- package/package.json +3 -2
- package/src/access.ts +79 -0
- package/src/chat.ts +0 -20
- package/src/commands.ts +267 -0
- package/src/config.ts +386 -47
- package/src/emoji/command.ts +75 -80
- package/src/emoji/label.ts +16 -0
- package/src/events/notice.ts +139 -0
- package/src/events/store.ts +53 -0
- package/src/index.ts +405 -79
- package/src/instance.ts +50 -1
- package/src/model-view.ts +8 -2
- package/src/naplink/client.ts +12 -1
- package/src/naplink/history.ts +6 -1
- package/src/naplink/render.ts +47 -2
- package/src/outbound.ts +28 -0
- package/src/overrides.ts +322 -0
- package/src/rate-limit.ts +83 -16
- package/src/sensitive.ts +63 -3
- package/src/session/manager.ts +554 -29
- package/src/session/proactive.ts +21 -0
- package/src/session/soul.ts +46 -0
- package/src/tools/ask-guard.ts +3 -4
- package/src/tools/policy-guard.ts +51 -0
- package/src/tools/policy.ts +222 -0
- package/src/tools/qq.ts +169 -10
- package/src/tools/send-guard.ts +8 -2
- package/src/trace.ts +209 -0
- package/src/tui-commands.ts +70 -0
- package/src/unload.ts +39 -0
- package/src/version.ts +12 -0
package/src/session/proactive.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/session/soul.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/tools/ask-guard.ts
CHANGED
|
@@ -24,10 +24,9 @@ export async function registerAskGuard(deps: AskGuardDeps): Promise<{ dispose():
|
|
|
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
|
|
28
|
-
if (!
|
|
29
|
-
|
|
30
|
-
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} 工具,已拒绝`)
|
|
31
30
|
throw new Error(ASK_REFUSAL)
|
|
32
31
|
})
|
|
33
32
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
logger.debug(`${targetLabel(active.target)} 工具策略检查`, {
|
|
38
|
+
role: active.role,
|
|
39
|
+
profile: await policy.profileOf(active.role, targetKey(active.target)),
|
|
40
|
+
tool: event.tool,
|
|
41
|
+
allowed: allowed.size > 0,
|
|
42
|
+
})
|
|
43
|
+
if (allowed.size > 0) return
|
|
44
|
+
logger.warn(
|
|
45
|
+
`${targetLabel(active.target)} 会话里 ${active.role} 尝试调用工具 ${event.tool},已被工具配置拒绝`,
|
|
46
|
+
)
|
|
47
|
+
throw new Error(
|
|
48
|
+
`当前用户不能使用工具 ${event.tool}:工具权限由 tool-profiles.json 按聊天分配。`,
|
|
49
|
+
)
|
|
50
|
+
})
|
|
51
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
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
|
+
* 消息发送者的角色,决定用哪一档工具配置。
|
|
8
|
+
*
|
|
9
|
+
* `proactive` 是机器人主动发起话题时的角色:没有人参与这一轮,
|
|
10
|
+
* 它读到的上下文完全来自聊天内容,所以权限最低。
|
|
11
|
+
*/
|
|
12
|
+
export type Role = "owner" | "admin" | "member" | "proactive"
|
|
13
|
+
|
|
14
|
+
/** 发送者角色:owner 最高,其次 admin,其余按普通成员处理。 */
|
|
15
|
+
export function roleOf(config: QQBotConfig, senderQQ: string): Role {
|
|
16
|
+
const id = Number(senderQQ)
|
|
17
|
+
if (config.ownerQQ !== undefined && id === config.ownerQQ) return "owner"
|
|
18
|
+
if (config.admins.includes(id)) return "admin"
|
|
19
|
+
return "member"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 一档工具配置:allow 命中且 deny 不命中的工具才放行。 */
|
|
23
|
+
export interface ToolProfile {
|
|
24
|
+
allow: string[]
|
|
25
|
+
deny: string[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** `tool-profiles.json` 的结构。 */
|
|
29
|
+
export interface ToolPolicyFile {
|
|
30
|
+
/** 没有按聊天指定的配置时用哪一档。 */
|
|
31
|
+
defaultProfile: string
|
|
32
|
+
/** 配置档:名字 → 允许 / 禁止的工具。 */
|
|
33
|
+
profiles: Record<string, ToolProfile>
|
|
34
|
+
/** 按聊天指定的配置档:`group:100` / `private:200` → 档名。 */
|
|
35
|
+
chats: Record<string, string>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
|
|
39
|
+
export function defaultToolPolicy(): ToolPolicyFile {
|
|
40
|
+
return {
|
|
41
|
+
defaultProfile: "chat",
|
|
42
|
+
profiles: {
|
|
43
|
+
chat: { allow: ["websearch", "webfetch", "qq_*"], deny: [] },
|
|
44
|
+
readonly: { allow: ["read", "glob", "grep", "qq_*"], deny: [] },
|
|
45
|
+
// 主动说话没有人参与,权限不能跟着聊天内容走:与普通聊天同档。
|
|
46
|
+
proactive: { allow: ["websearch", "webfetch", "qq_*"], deny: [] },
|
|
47
|
+
admin: { allow: ["*"], deny: [] },
|
|
48
|
+
},
|
|
49
|
+
chats: {},
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 默认的配置文件位置:当前工作目录下的 `tool-profiles.json`。 */
|
|
54
|
+
export function defaultToolProfilesPath(): string {
|
|
55
|
+
return join(process.cwd(), "tool-profiles.json")
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 判断工具名是否命中通配模式。
|
|
60
|
+
*
|
|
61
|
+
* 只支持 `*`(任意长度)和 `?`(单个字符),大小写敏感,必须整名匹配。
|
|
62
|
+
*/
|
|
63
|
+
export function globMatch(pattern: string, name: string): boolean {
|
|
64
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
65
|
+
const source = escaped.replace(/\*/g, ".*").replace(/\?/g, ".")
|
|
66
|
+
return new RegExp(`^${source}$`).test(name)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readNames(value: unknown, warn: (message: string) => void, where: string): string[] {
|
|
70
|
+
if (value === undefined) return []
|
|
71
|
+
if (!Array.isArray(value)) {
|
|
72
|
+
warn(`${where} 必须是字符串数组`)
|
|
73
|
+
return []
|
|
74
|
+
}
|
|
75
|
+
const names: string[] = []
|
|
76
|
+
for (const entry of value) {
|
|
77
|
+
if (typeof entry !== "string") {
|
|
78
|
+
warn(`${where} 里有非字符串项:${String(entry)}`)
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
const name = entry.trim()
|
|
82
|
+
if (!name || names.includes(name)) continue
|
|
83
|
+
names.push(name)
|
|
84
|
+
}
|
|
85
|
+
return names
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 解析并校验配置内容。
|
|
90
|
+
*
|
|
91
|
+
* 解析失败不抛错:回退到内置默认值并告警,避免一个手写的逗号让机器人失去工具。
|
|
92
|
+
*/
|
|
93
|
+
export function parseToolPolicy(value: unknown, warn: (message: string) => void): ToolPolicyFile {
|
|
94
|
+
const fallback = defaultToolPolicy()
|
|
95
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
96
|
+
warn("工具配置必须是对象,已回退到内置默认值")
|
|
97
|
+
return fallback
|
|
98
|
+
}
|
|
99
|
+
const raw = value as Record<string, unknown>
|
|
100
|
+
const profiles: Record<string, ToolProfile> = {}
|
|
101
|
+
const source = raw.profiles
|
|
102
|
+
if (source !== undefined) {
|
|
103
|
+
if (!source || typeof source !== "object" || Array.isArray(source)) {
|
|
104
|
+
warn("profiles 必须是对象,已回退到内置默认值")
|
|
105
|
+
return fallback
|
|
106
|
+
}
|
|
107
|
+
for (const [name, entry] of Object.entries(source as Record<string, unknown>)) {
|
|
108
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
109
|
+
warn(`工具配置档 ${name} 必须是对象,已忽略`)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
const profile = entry as Record<string, unknown>
|
|
113
|
+
profiles[name] = {
|
|
114
|
+
allow: readNames(profile.allow, warn, `${name}.allow`),
|
|
115
|
+
deny: readNames(profile.deny, warn, `${name}.deny`),
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// 用户没有覆盖的档沿用内置默认值,这样只写一档也能用。
|
|
120
|
+
for (const [name, profile] of Object.entries(fallback.profiles)) {
|
|
121
|
+
if (!profiles[name]) profiles[name] = profile
|
|
122
|
+
}
|
|
123
|
+
const defaultProfile =
|
|
124
|
+
typeof raw.defaultProfile === "string" && raw.defaultProfile.trim()
|
|
125
|
+
? raw.defaultProfile.trim()
|
|
126
|
+
: fallback.defaultProfile
|
|
127
|
+
if (!profiles[defaultProfile]) {
|
|
128
|
+
warn(`defaultProfile 指向不存在的配置档 ${defaultProfile},已回退到 ${fallback.defaultProfile}`)
|
|
129
|
+
}
|
|
130
|
+
const chats: Record<string, string> = {}
|
|
131
|
+
if (raw.chats !== undefined) {
|
|
132
|
+
if (!raw.chats || typeof raw.chats !== "object" || Array.isArray(raw.chats)) {
|
|
133
|
+
warn("chats 必须是对象,已忽略")
|
|
134
|
+
} else {
|
|
135
|
+
for (const [key, name] of Object.entries(raw.chats as Record<string, unknown>)) {
|
|
136
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
137
|
+
warn(`chats.${key} 必须是配置档名字,已忽略`)
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
chats[key] = name.trim()
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
defaultProfile: profiles[defaultProfile] ? defaultProfile : fallback.defaultProfile,
|
|
146
|
+
profiles,
|
|
147
|
+
chats,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 角色对应的配置档名字:owner 与 admin 用管理档,其他按聊天配置。
|
|
153
|
+
*
|
|
154
|
+
* 主动说话(`proactive`)固定用主动说话档:它没有人参与,
|
|
155
|
+
* 不能因为聊天里有 owner 或管理员说过话就借到管理档的全开权限。
|
|
156
|
+
*/
|
|
157
|
+
export function profileNameFor(file: ToolPolicyFile, role: Role, chatKey: string): string {
|
|
158
|
+
if (role === "owner" || role === "admin") {
|
|
159
|
+
return file.profiles.admin ? "admin" : file.defaultProfile
|
|
160
|
+
}
|
|
161
|
+
if (role === "proactive") {
|
|
162
|
+
return file.profiles.proactive ? "proactive" : file.defaultProfile
|
|
163
|
+
}
|
|
164
|
+
const named = file.chats[chatKey]
|
|
165
|
+
if (named && file.profiles[named]) return named
|
|
166
|
+
return file.defaultProfile
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 从工具名列表里筛出该配置档允许的项;deny 优先于 allow。 */
|
|
170
|
+
export function allowedTools(profile: ToolProfile, names: readonly string[]): string[] {
|
|
171
|
+
const allowed = (name: string) =>
|
|
172
|
+
!profile.deny.some((pattern) => globMatch(pattern, name)) &&
|
|
173
|
+
(profile.allow.includes("*") || profile.allow.some((pattern) => globMatch(pattern, name)))
|
|
174
|
+
return names.filter(allowed)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 工具配置的读取与热加载。 */
|
|
178
|
+
export class ToolPolicy {
|
|
179
|
+
private cached?: { mtime: number; file: ToolPolicyFile }
|
|
180
|
+
|
|
181
|
+
constructor(
|
|
182
|
+
private readonly path: string,
|
|
183
|
+
private readonly logger: Logger,
|
|
184
|
+
) {}
|
|
185
|
+
|
|
186
|
+
/** 当前生效的配置;文件改动后按 mtime 重新读取。 */
|
|
187
|
+
async current(): Promise<ToolPolicyFile> {
|
|
188
|
+
const info = await stat(this.path).catch(() => undefined)
|
|
189
|
+
if (!info) {
|
|
190
|
+
if (!this.cached) this.cached = { mtime: 0, file: defaultToolPolicy() }
|
|
191
|
+
return this.cached.file
|
|
192
|
+
}
|
|
193
|
+
if (this.cached && this.cached.mtime === info.mtimeMs) return this.cached.file
|
|
194
|
+
try {
|
|
195
|
+
const text = await readFile(this.path, "utf8")
|
|
196
|
+
const file = parseToolPolicy(JSON.parse(text), (message) => {
|
|
197
|
+
this.logger.warn(`工具配置 ${this.path}:${message}`)
|
|
198
|
+
})
|
|
199
|
+
this.cached = { mtime: info.mtimeMs, file }
|
|
200
|
+
return file
|
|
201
|
+
} catch (error) {
|
|
202
|
+
// 半写或语法错误时保留上一份可用配置,等下一次写入后再加载。
|
|
203
|
+
this.logger.warn(`工具配置 ${this.path} 读取失败,继续沿用上一份配置`, error)
|
|
204
|
+
if (!this.cached) this.cached = { mtime: 0, file: defaultToolPolicy() }
|
|
205
|
+
return this.cached.file
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** 某个角色在某个聊天里能用的工具子集。 */
|
|
210
|
+
async allow(role: Role, chatKey: string, names: readonly string[]): Promise<Set<string>> {
|
|
211
|
+
const file = await this.current()
|
|
212
|
+
const profile = file.profiles[profileNameFor(file, role, chatKey)]
|
|
213
|
+
if (!profile) return new Set(names)
|
|
214
|
+
return new Set(allowedTools(profile, names))
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** 某个角色在某个聊天里生效的配置档名字,用于管理命令展示。 */
|
|
218
|
+
async profileOf(role: Role, chatKey: string): Promise<string> {
|
|
219
|
+
const file = await this.current()
|
|
220
|
+
return profileNameFor(file, role, chatKey)
|
|
221
|
+
}
|
|
222
|
+
}
|
package/src/tools/qq.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode/plugin"
|
|
2
|
-
import {
|
|
2
|
+
import { isTargetAllowed } from "../access"
|
|
3
|
+
import { type ChatTarget, targetKey, targetLabel } from "../chat"
|
|
3
4
|
import type { QQBotConfig } from "../config"
|
|
4
5
|
import {
|
|
5
6
|
CUSTOM_FACE_SUB_TYPE,
|
|
@@ -11,11 +12,12 @@ import type { FavoriteIndex } from "../emoji/favorite-index"
|
|
|
11
12
|
import type { Logger } from "../logger"
|
|
12
13
|
import type { OutboundMedia } from "../media-path"
|
|
13
14
|
import type { QQClient } from "../naplink/client"
|
|
14
|
-
import { splitGraphemes, splitMessage, toPlainText } from "../outbound"
|
|
15
|
+
import { splitGraphemes, splitMessage, segmentDelayMs, toPlainText } from "../outbound"
|
|
15
16
|
import type { RateLimitVerdict, SendRateLimiter } from "../rate-limit"
|
|
16
17
|
import { modelSendScope, pluginSendScope } from "../rate-limit"
|
|
17
18
|
import type { SensitiveChecker } from "../sensitive"
|
|
18
19
|
import type { SessionManager } from "../session/manager"
|
|
20
|
+
import type { Tracer } from "../trace"
|
|
19
21
|
|
|
20
22
|
/** 工具命名空间,最终工具名为 qq_send_message 等。 */
|
|
21
23
|
export const TOOL_NAMESPACE = "qq"
|
|
@@ -36,6 +38,8 @@ export interface ToolDeps {
|
|
|
36
38
|
sensitive: SensitiveChecker
|
|
37
39
|
/** 出站媒体的路径与地址把关。 */
|
|
38
40
|
outbound: OutboundMedia
|
|
41
|
+
/** 调用链追踪器;不传就不记追踪。 */
|
|
42
|
+
tracer?: Tracer
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
interface SendMessageInput {
|
|
@@ -74,6 +78,9 @@ interface MessageIdInput {
|
|
|
74
78
|
/** QQ 单条消息的保守长度上限,超过时按段发送。 */
|
|
75
79
|
export { MAX_MESSAGE_CHARS } from "../outbound"
|
|
76
80
|
|
|
81
|
+
/** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
|
|
82
|
+
const FORWARD_NODE_CHARS = 3000
|
|
83
|
+
|
|
77
84
|
function text(value: string, metadata?: Record<string, unknown>) {
|
|
78
85
|
// 工具返回 error 文本时状态仍是 completed;把失败标记带给发送守卫。
|
|
79
86
|
const marks = { ...(value.startsWith("error:") ? { failed: true } : {}), ...metadata }
|
|
@@ -127,6 +134,36 @@ export async function sendPlainMessage(
|
|
|
127
134
|
return sent
|
|
128
135
|
}
|
|
129
136
|
|
|
137
|
+
/** 命令结果发送通道的配置。 */
|
|
138
|
+
export interface PlainSenderOptions {
|
|
139
|
+
delayMs?: number
|
|
140
|
+
limiter: SendRateLimiter
|
|
141
|
+
logger: Logger
|
|
142
|
+
/** 发送失败时写进日志的说明。 */
|
|
143
|
+
failure: (target: ChatTarget) => string
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 创建命令结果的发送通道。
|
|
148
|
+
*
|
|
149
|
+
* 发送失败只记日志,不往上抛:命令已经执行完,不该因为回执失败再报错。
|
|
150
|
+
*/
|
|
151
|
+
export function createPlainSender(
|
|
152
|
+
client: QQClient,
|
|
153
|
+
options: PlainSenderOptions,
|
|
154
|
+
): (target: ChatTarget, content: string) => Promise<void> {
|
|
155
|
+
return async (target, content) => {
|
|
156
|
+
try {
|
|
157
|
+
await sendPlainMessage(client, target, content, {
|
|
158
|
+
delayMs: options.delayMs,
|
|
159
|
+
limiter: options.limiter,
|
|
160
|
+
})
|
|
161
|
+
} catch (error) {
|
|
162
|
+
options.logger.error(options.failure(target), error)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
130
167
|
/**
|
|
131
168
|
* 注册 QQ 命名空间下的工具。
|
|
132
169
|
*
|
|
@@ -145,17 +182,21 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
145
182
|
limiter,
|
|
146
183
|
sensitive,
|
|
147
184
|
outbound,
|
|
185
|
+
tracer,
|
|
148
186
|
} = deps
|
|
149
187
|
|
|
150
188
|
const requireTarget = (sessionID: string): ChatTarget | undefined => {
|
|
151
189
|
const target = manager.targetForSession(sessionID)
|
|
152
190
|
if (!target) return undefined
|
|
153
|
-
if (!
|
|
154
|
-
logger.warn(`${targetLabel(target)}
|
|
191
|
+
if (!isTargetAllowed(config.access, target, config.ownerQQ)) {
|
|
192
|
+
logger.warn(`${targetLabel(target)} 已不在放行名单里,拒绝工具调用`)
|
|
155
193
|
return undefined
|
|
156
194
|
}
|
|
157
195
|
if (!manager.hasActiveTurn(sessionID)) {
|
|
158
|
-
logger.warn(
|
|
196
|
+
logger.warn(
|
|
197
|
+
`会话 ${sessionID} 当前没有 QQ 消息轮次,拒绝工具调用`,
|
|
198
|
+
manager.describeTurn(sessionID),
|
|
199
|
+
)
|
|
159
200
|
return undefined
|
|
160
201
|
}
|
|
161
202
|
return target
|
|
@@ -165,6 +206,27 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
165
206
|
let operationSeq = 0
|
|
166
207
|
const nextOperation = (): string => `send-${++operationSeq}`
|
|
167
208
|
|
|
209
|
+
/** 当前轮次的追踪 id,用于把这次发送记进调用链。 */
|
|
210
|
+
const traceIdOf = (sessionID: string): string | undefined =>
|
|
211
|
+
manager.activeTurn(sessionID)?.turn.traceId
|
|
212
|
+
|
|
213
|
+
/** 日志里带上追踪 id,方便按一轮排查。 */
|
|
214
|
+
const traceMeta = (sessionID: string): Record<string, unknown> => {
|
|
215
|
+
const traceId = traceIdOf(sessionID)
|
|
216
|
+
return traceId ? { trace_id: traceId } : {}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 记一个“回复已发出”的追踪节点。 */
|
|
220
|
+
const traceSent = async (
|
|
221
|
+
sessionID: string,
|
|
222
|
+
target: ChatTarget,
|
|
223
|
+
attributes: Record<string, unknown>,
|
|
224
|
+
): Promise<void> => {
|
|
225
|
+
const traceId = traceIdOf(sessionID)
|
|
226
|
+
if (!traceId) return
|
|
227
|
+
await tracer?.record("response_sent", traceId, attributes, targetKey(target))
|
|
228
|
+
}
|
|
229
|
+
|
|
168
230
|
/**
|
|
169
231
|
* 申请一次出站发送许可。
|
|
170
232
|
*
|
|
@@ -202,6 +264,23 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
202
264
|
/** base64:// 载荷是二进制数据,按文本扫描既没意义也慢。 */
|
|
203
265
|
const isInlineData = (value: string): boolean => value.startsWith("base64://")
|
|
204
266
|
|
|
267
|
+
/** 内联数据解码后的大小上限:5MB。 */
|
|
268
|
+
const MAX_INLINE_BYTES = 5 * 1024 * 1024
|
|
269
|
+
|
|
270
|
+
/** base64 每 4 个字符解出 3 字节,字符上限按这个比例算。 */
|
|
271
|
+
const MAX_INLINE_CHARS = Math.ceil((MAX_INLINE_BYTES * 4) / 3)
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 内联数据的大小检查。
|
|
275
|
+
*
|
|
276
|
+
* 内联数据不经过路径与网络校验,超大载荷会把内存和对端一起撑爆,这里直接拒掉。
|
|
277
|
+
*/
|
|
278
|
+
const checkInlineSize = (value: string, kind: string): string | undefined => {
|
|
279
|
+
if (!isInlineData(value)) return undefined
|
|
280
|
+
if (value.length <= MAX_INLINE_CHARS) return undefined
|
|
281
|
+
return `error: ${kind}数据过大,超过 ${Math.floor(MAX_INLINE_BYTES / 1024 / 1024)}MB 上限`
|
|
282
|
+
}
|
|
283
|
+
|
|
205
284
|
const sendText = (target: ChatTarget, chunk: string) =>
|
|
206
285
|
target.kind === "group"
|
|
207
286
|
? client.api.sendGroupMessage(target.id, chunk)
|
|
@@ -222,6 +301,58 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
222
301
|
? client.api.sendGroupPoke(target.id, userId)
|
|
223
302
|
: client.api.sendFriendPoke(userId)
|
|
224
303
|
|
|
304
|
+
// 合并转发时机器人自己的昵称,取一次就够。
|
|
305
|
+
let botName: string | undefined
|
|
306
|
+
|
|
307
|
+
/** 机器人在合并转发里的身份。 */
|
|
308
|
+
const botIdentity = async (): Promise<{ userId: number; nickname: string }> => {
|
|
309
|
+
if (!botName) {
|
|
310
|
+
const info = (await client.api.getLoginInfo().catch(() => undefined)) as
|
|
311
|
+
{ nickname?: string } | undefined
|
|
312
|
+
botName = info?.nickname?.trim() || "机器人"
|
|
313
|
+
}
|
|
314
|
+
const userId = Number(client.selfId ?? 0)
|
|
315
|
+
return { userId: Number.isFinite(userId) ? userId : 0, nickname: botName }
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 太长的回复改成合并转发发出去。
|
|
320
|
+
*
|
|
321
|
+
* 一口气刷十几条会把群刷爆,合并转发只占一条消息。
|
|
322
|
+
*/
|
|
323
|
+
const sendAsForward = async (
|
|
324
|
+
sessionID: string,
|
|
325
|
+
target: ChatTarget,
|
|
326
|
+
plain: string,
|
|
327
|
+
operation: string,
|
|
328
|
+
length: number,
|
|
329
|
+
) => {
|
|
330
|
+
const label = targetLabel(target)
|
|
331
|
+
const identity = await botIdentity()
|
|
332
|
+
const nodes = splitMessage(plain, FORWARD_NODE_CHARS).map((chunk) => ({
|
|
333
|
+
user_id: identity.userId,
|
|
334
|
+
nickname: identity.nickname,
|
|
335
|
+
content: [{ type: "text", data: { text: chunk } }],
|
|
336
|
+
}))
|
|
337
|
+
try {
|
|
338
|
+
const verdict = await permit(target, operation)
|
|
339
|
+
if (!verdict.allowed) return refuse(sessionID, verdict, 0, nodes.length)
|
|
340
|
+
const response = await sendForward(target, nodes)
|
|
341
|
+
const messageId = messageIdOf(response)
|
|
342
|
+
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
343
|
+
manager.markMessageSent(sessionID)
|
|
344
|
+
logger.info(
|
|
345
|
+
`${label} 已发送 ${length} 字(合并转发 ${nodes.length} 个节点)`,
|
|
346
|
+
traceMeta(sessionID),
|
|
347
|
+
)
|
|
348
|
+
await traceSent(sessionID, target, { chars: length, mode: "forward", nodes: nodes.length })
|
|
349
|
+
return text("你已成功发送消息,可以选择结束对话")
|
|
350
|
+
} catch (error) {
|
|
351
|
+
logger.error(`${label} 发送合并转发失败`, error)
|
|
352
|
+
return text("error: 消息发送失败", { retryable: true })
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
225
356
|
return await ctx.tool.transform((editor) => {
|
|
226
357
|
editor.namespace({
|
|
227
358
|
name: TOOL_NAMESPACE,
|
|
@@ -276,8 +407,25 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
276
407
|
logger.warn(`send_message 内容长度 ${length} 超过 ${config.warnLength}`)
|
|
277
408
|
}
|
|
278
409
|
|
|
279
|
-
const chunks = splitMessage(plain)
|
|
280
410
|
const operation = nextOperation()
|
|
411
|
+
// 太长的回复改成合并转发,别一口气刷屏。
|
|
412
|
+
const forwardThreshold = config.reply.forwardThresholdChars
|
|
413
|
+
if (forwardThreshold > 0 && length > forwardThreshold) {
|
|
414
|
+
return await sendAsForward(context.sessionID, target, plain, operation, length)
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// 单段超过配置的字数就拆成多段发。
|
|
418
|
+
const chunks = splitMessage(plain, config.reply.segmentChars)
|
|
419
|
+
// 剩余额度不够分段时,宁可合并转发一条,也不要把回复截成半截。
|
|
420
|
+
if (forwardThreshold > 0 && chunks.length > limiter.remaining(modelSendScope(target))) {
|
|
421
|
+
return await sendAsForward(context.sessionID, target, plain, operation, length)
|
|
422
|
+
}
|
|
423
|
+
// 段与段之间的间隔:配了随机区间就在区间里等。
|
|
424
|
+
const wait = segmentDelayMs({
|
|
425
|
+
sendDelayMs: config.sendDelayMs,
|
|
426
|
+
minDelayMs: config.reply.minDelayMs,
|
|
427
|
+
maxDelayMs: config.reply.maxDelayMs,
|
|
428
|
+
})
|
|
281
429
|
let sent = 0
|
|
282
430
|
try {
|
|
283
431
|
for (const [index, chunk] of chunks.entries()) {
|
|
@@ -287,8 +435,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
287
435
|
const messageId = messageIdOf(response)
|
|
288
436
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
289
437
|
sent += 1
|
|
290
|
-
if (index < chunks.length - 1 &&
|
|
291
|
-
await delay(
|
|
438
|
+
if (index < chunks.length - 1 && wait > 0) {
|
|
439
|
+
await delay(wait)
|
|
292
440
|
}
|
|
293
441
|
}
|
|
294
442
|
} catch (error) {
|
|
@@ -298,7 +446,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
298
446
|
return text(`error: 消息只发送了 ${sent}/${chunks.length} 段`, { retryable: sent === 0 })
|
|
299
447
|
}
|
|
300
448
|
manager.markMessageSent(context.sessionID)
|
|
301
|
-
logger.info(`${label} 已发送 ${length}
|
|
449
|
+
logger.info(`${label} 已发送 ${length} 字`, traceMeta(context.sessionID))
|
|
450
|
+
await traceSent(context.sessionID, target, { chars: length, mode: "plain", segments: sent })
|
|
302
451
|
return text("你已成功发送消息,可以选择结束对话")
|
|
303
452
|
},
|
|
304
453
|
})
|
|
@@ -322,6 +471,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
322
471
|
if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
|
|
323
472
|
const file = input.file ?? (input.base64 ? `base64://${input.base64}` : undefined)
|
|
324
473
|
if (!file) return text("error: 缺少 file 或 base64")
|
|
474
|
+
const tooLarge = checkInlineSize(file, "图片")
|
|
475
|
+
if (tooLarge) return text(tooLarge)
|
|
325
476
|
if (!isInlineData(file)) guardOutbound(target, file)
|
|
326
477
|
// 路径白名单在这里就判定:不过就不占发送额度。内联数据不涉及路径与网络。
|
|
327
478
|
const plan = isInlineData(file) ? undefined : await outbound.check(file)
|
|
@@ -382,10 +533,15 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
382
533
|
const url = typeof row.face.url === "string" ? row.face.url : undefined
|
|
383
534
|
if (!url) return text(`error: 编号 ${id} 的收藏表情缺少可用地址`)
|
|
384
535
|
guardOutbound(target, url)
|
|
536
|
+
// 收藏表情的地址同样来自外部,要走和图片一致的路径与地址白名单。
|
|
537
|
+
const plan = await outbound.check(url)
|
|
385
538
|
const verdict = await permit(target, nextOperation())
|
|
386
539
|
if (!verdict.allowed) return refuse(context.sessionID, verdict)
|
|
387
540
|
const response = await sendSegments(target, [
|
|
388
|
-
{
|
|
541
|
+
{
|
|
542
|
+
type: "image",
|
|
543
|
+
data: { file: outbound.materialize(plan), sub_type: CUSTOM_FACE_SUB_TYPE },
|
|
544
|
+
},
|
|
389
545
|
])
|
|
390
546
|
const messageId = messageIdOf(response)
|
|
391
547
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
@@ -411,6 +567,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
411
567
|
const target = requireTarget(context.sessionID)
|
|
412
568
|
if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
|
|
413
569
|
if (!input.file) return text("error: 缺少 file")
|
|
570
|
+
const tooLarge = checkInlineSize(input.file, "语音")
|
|
571
|
+
if (tooLarge) return text(tooLarge)
|
|
414
572
|
if (!isInlineData(input.file)) guardOutbound(target, input.file)
|
|
415
573
|
const plan = isInlineData(input.file) ? undefined : await outbound.check(input.file)
|
|
416
574
|
const verdict = await permit(target, nextOperation())
|
|
@@ -481,6 +639,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
481
639
|
const messageId = messageIdOf(response)
|
|
482
640
|
if (messageId) manager.rememberOutgoing(target, messageId)
|
|
483
641
|
manager.markMessageSent(context.sessionID)
|
|
642
|
+
await traceSent(context.sessionID, target, { mode: "forward", nodes: nodes.length })
|
|
484
643
|
return text("你已成功发送合并转发消息,可以选择结束对话")
|
|
485
644
|
},
|
|
486
645
|
})
|