@cmach_socket/opencode-qq-bot 0.9.2 → 0.10.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/NOTICE +0 -1
- package/README.md +35 -15
- package/chat-overrides.example.json +3 -3
- package/package.json +6 -2
- package/src/chat.ts +5 -0
- package/src/commands.ts +88 -1
- package/src/config/fields.ts +44 -1
- package/src/config/live.ts +33 -3
- package/src/config/store.ts +6 -11
- package/src/config/types.ts +24 -0
- package/src/config.ts +3 -0
- package/src/diary/command.ts +13 -12
- package/src/diary/format.ts +17 -0
- package/src/diary/scheduler.ts +1 -1
- package/src/diary/summary.ts +6 -5
- package/src/emoji/collection.ts +33 -1
- package/src/fs/atomic.ts +82 -0
- package/src/home.ts +6 -2
- package/src/index.ts +31 -23
- package/src/keepalive.ts +60 -2
- package/src/known-secrets.ts +20 -0
- package/src/logger.ts +2 -1
- package/src/overrides.ts +209 -47
- package/src/panel/api.ts +61 -7
- package/src/panel/documents.ts +621 -0
- package/src/panel/server.ts +6 -0
- package/src/panel/status.ts +8 -1
- package/src/safe-object.ts +48 -0
- package/src/sensitive.ts +31 -2
- package/src/session/find.ts +3 -2
- package/src/session/manager.ts +646 -43
- package/src/session/proactive.ts +3 -1
- package/src/session/soul-guard.ts +162 -0
- package/src/session/soul.ts +78 -13
- package/src/state-lock.ts +74 -0
- package/src/tools/policy.ts +65 -24
- package/src/tools/qq.ts +20 -12
- package/web/dist/assets/index-C5lRsdbz.css +1 -0
- package/web/dist/assets/index-YqorZD0I.js +8 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-7eMQEM7-.css +0 -1
- package/web/dist/assets/index-DCkgUY7y.js +0 -15
package/src/session/proactive.ts
CHANGED
|
@@ -35,6 +35,8 @@ export function proactiveProbability(
|
|
|
35
35
|
): number {
|
|
36
36
|
const silenceHours = (silenceSeconds - config.silenceThresholdSeconds) / 3600
|
|
37
37
|
if (silenceHours <= 0) return 0
|
|
38
|
-
if (override.
|
|
38
|
+
if (override["proactive.startProbability"] !== undefined) {
|
|
39
|
+
return override["proactive.startProbability"]
|
|
40
|
+
}
|
|
39
41
|
return proactiveTickProbability(config, silenceSeconds)
|
|
40
42
|
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { readFile, realpath, stat } from "node:fs/promises"
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve } from "node:path"
|
|
3
|
+
import { maskKnownSecrets, SensitiveChecker } from "../sensitive"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 角色设定的边界检查。
|
|
7
|
+
*
|
|
8
|
+
* 角色设定文件的内容会一轮一次地进入系统提示词,也就是随每一轮发给模型服务商。
|
|
9
|
+
* 因此这里做两件事:
|
|
10
|
+
*
|
|
11
|
+
* 1. 路径要落在用户声明的允许根之内:先解析符号链接再判断,`souls/link → /etc/passwd`
|
|
12
|
+
* 这种绕过自然失效;
|
|
13
|
+
* 2. 内容要有闸门:大小上限、凭证检测、已知凭证明文掩码。
|
|
14
|
+
*
|
|
15
|
+
* 允许根默认是机器人工作目录,用户可以自己往外加:边界由用户声明一次,
|
|
16
|
+
* 功能不丢,但越界的文件不会随提示词发出去。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** 角色设定目录名。 */
|
|
20
|
+
export const SOUL_DIR = "souls"
|
|
21
|
+
|
|
22
|
+
/** 角色设定正文的大小上限:64KB。 */
|
|
23
|
+
export const MAX_SOUL_BYTES = 64 * 1024
|
|
24
|
+
|
|
25
|
+
/** 角色设定允许根的来源。 */
|
|
26
|
+
export interface SoulGuardOptions {
|
|
27
|
+
/** 机器人工作目录:默认就在允许范围之内。 */
|
|
28
|
+
home: string
|
|
29
|
+
/** 用户额外声明的允许根目录;相对路径按工作目录解析。 */
|
|
30
|
+
allowedPaths?: readonly string[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 允许根目录:工作目录 + 用户声明的目录。 */
|
|
34
|
+
export function soulRoots(options: SoulGuardOptions): string[] {
|
|
35
|
+
const roots = [resolve(options.home)]
|
|
36
|
+
for (const extra of options.allowedPaths ?? []) {
|
|
37
|
+
const trimmed = extra.trim()
|
|
38
|
+
if (!trimmed) continue
|
|
39
|
+
roots.push(resolve(options.home, trimmed))
|
|
40
|
+
}
|
|
41
|
+
return [...new Set(roots)]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 目标是否在根目录之下。 */
|
|
45
|
+
export function withinRoot(target: string, root: string): boolean {
|
|
46
|
+
if (target === root) return true
|
|
47
|
+
const rel = relative(root, target)
|
|
48
|
+
return rel.length > 0 && !rel.startsWith("..") && !isAbsolute(rel)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 词法判断:路径是否在允许根之内(不解析符号链接)。 */
|
|
52
|
+
export function withinRoots(target: string, roots: readonly string[]): boolean {
|
|
53
|
+
return roots.some((root) => withinRoot(target, root))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 路径检查的结果。 */
|
|
57
|
+
export type SoulPathCheck =
|
|
58
|
+
{ ok: true; path: string } | { ok: false; missing: boolean; reason: string }
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 检查角色设定文件路径能不能用。
|
|
62
|
+
*
|
|
63
|
+
* 路径先解析成绝对路径,再取真实路径(符号链接按目标判断),最后跟允许根比较:
|
|
64
|
+
* 越界的路径直接拒绝,不给「读到了再判断」的机会。
|
|
65
|
+
* 文件还不存在时按「稍后补齐」处理:目录在允许根之内就留着监听。
|
|
66
|
+
*/
|
|
67
|
+
export async function checkSoulPath(
|
|
68
|
+
path: string,
|
|
69
|
+
options: SoulGuardOptions,
|
|
70
|
+
): Promise<SoulPathCheck> {
|
|
71
|
+
const absolute = resolve(options.home, path)
|
|
72
|
+
const roots = await Promise.all(
|
|
73
|
+
soulRoots(options).map((root) => realpath(root).catch(() => root)),
|
|
74
|
+
)
|
|
75
|
+
let real: string | undefined
|
|
76
|
+
let missing = false
|
|
77
|
+
try {
|
|
78
|
+
real = await realpath(absolute)
|
|
79
|
+
} catch (error) {
|
|
80
|
+
missing = (error as NodeJS.ErrnoException).code === "ENOENT"
|
|
81
|
+
}
|
|
82
|
+
if (!real) {
|
|
83
|
+
// 文件还不存在:所在目录要在允许根之内,否则连监听都不该有。
|
|
84
|
+
const parent = await realpath(dirname(absolute)).catch(() => dirname(absolute))
|
|
85
|
+
if (!withinRoots(parent, roots)) {
|
|
86
|
+
return {
|
|
87
|
+
ok: false,
|
|
88
|
+
missing: false,
|
|
89
|
+
reason: `角色设定文件 ${absolute} 不在允许的目录内,已拒绝加载`,
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (!missing) {
|
|
93
|
+
return { ok: false, missing: false, reason: `角色设定文件读不到:${absolute}` }
|
|
94
|
+
}
|
|
95
|
+
return { ok: false, missing: true, reason: `角色设定文件不存在:${absolute}` }
|
|
96
|
+
}
|
|
97
|
+
if (!withinRoots(real, roots)) {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
missing: false,
|
|
101
|
+
reason: `角色设定文件 ${absolute} 不在允许的目录内,已拒绝加载`,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const info = await stat(real).catch(() => undefined)
|
|
105
|
+
if (!info) return { ok: false, missing: false, reason: `角色设定文件读不到:${absolute}` }
|
|
106
|
+
if (!info.isFile())
|
|
107
|
+
return { ok: false, missing: false, reason: `角色设定路径不是普通文件:${absolute}` }
|
|
108
|
+
if (info.size > MAX_SOUL_BYTES) {
|
|
109
|
+
return {
|
|
110
|
+
ok: false,
|
|
111
|
+
missing: false,
|
|
112
|
+
reason: `角色设定文件超过 ${MAX_SOUL_BYTES} 字节:${absolute}`,
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { ok: true, path: real }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 非文本控制字符;换行与制表符保留。 */
|
|
119
|
+
const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]+/g
|
|
120
|
+
|
|
121
|
+
/** 角色设定正文与检查结果。 */
|
|
122
|
+
export interface SoulContent {
|
|
123
|
+
/** 正文;被拒绝时为空串。 */
|
|
124
|
+
text: string
|
|
125
|
+
/** 被拒绝的原因;为空表示加载成功。 */
|
|
126
|
+
reason?: string
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 读取角色设定正文并过一遍闸门。
|
|
131
|
+
*
|
|
132
|
+
* 命中凭证形状(私钥块、密钥样式的内容、指向凭证文件的路径)就整份拒绝:
|
|
133
|
+
* 人格文件里刚好有私钥,不等于私钥可以发出去。
|
|
134
|
+
* 机器人自己的已知凭证明文不拦,抹成 `[REDACTED]` 即可:面板令牌出现在人格文件里
|
|
135
|
+
* 只会是误抄,不必因此丢掉整份设定。
|
|
136
|
+
*/
|
|
137
|
+
export async function readSoulContent(
|
|
138
|
+
path: string,
|
|
139
|
+
secrets: readonly string[],
|
|
140
|
+
): Promise<SoulContent> {
|
|
141
|
+
let text: string
|
|
142
|
+
try {
|
|
143
|
+
text = await readFile(path, "utf-8")
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return {
|
|
146
|
+
text: "",
|
|
147
|
+
reason: `角色设定读取失败:${error instanceof Error ? error.message : String(error)}`,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const checker = new SensitiveChecker({
|
|
151
|
+
// 已知凭证明文走掩码,不走拦截,所以这里不把它们交给检测器。
|
|
152
|
+
knownSecrets: [],
|
|
153
|
+
// 内网地址在人格文件里是常见描述,不算凭证:只留真正的密钥类检测器。
|
|
154
|
+
exclude: ["internal_url"],
|
|
155
|
+
})
|
|
156
|
+
const verdict = checker.check(text)
|
|
157
|
+
if (!verdict.allowed) {
|
|
158
|
+
const detectors = verdict.hits.map((hit) => hit.detector).join("、")
|
|
159
|
+
return { text: "", reason: `角色设定里含疑似凭证(${detectors}),已拒绝加载` }
|
|
160
|
+
}
|
|
161
|
+
return { text: maskKnownSecrets(text, secrets).replace(CONTROL, " ") }
|
|
162
|
+
}
|
package/src/session/soul.ts
CHANGED
|
@@ -5,17 +5,20 @@ import { unrefTimer } from "../async"
|
|
|
5
5
|
import { seedFile } from "../seed"
|
|
6
6
|
import type { Logger } from "../logger"
|
|
7
7
|
import { buildSystemPrompt } from "./prompt"
|
|
8
|
+
import { checkSoulPath, readSoulContent, SOUL_DIR, type SoulGuardOptions } from "./soul-guard"
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
export const SOUL_DIR = "souls"
|
|
10
|
+
export { SOUL_DIR }
|
|
11
11
|
|
|
12
12
|
/** 默认角色设定文件名。 */
|
|
13
13
|
export const DEFAULT_SOUL_NAME = "default.txt"
|
|
14
14
|
|
|
15
|
+
/** 同时缓存多少份角色设定:超出后丢掉最早加载的。 */
|
|
16
|
+
const MAX_SOUL_STORES = 32
|
|
17
|
+
|
|
15
18
|
/** 文件变化后的合并等待时间,避免编辑器连续写盘时重复读取。 */
|
|
16
19
|
const RELOAD_DEBOUNCE_MS = 150
|
|
17
20
|
|
|
18
|
-
export interface SoulOptions {
|
|
21
|
+
export interface SoulOptions extends SoulGuardOptions {
|
|
19
22
|
/** 显式指定的角色设定文件或目录,优先于 soulName。 */
|
|
20
23
|
soulPath?: string
|
|
21
24
|
/** souls 目录里的文件名。 */
|
|
@@ -24,6 +27,8 @@ export interface SoulOptions {
|
|
|
24
27
|
home: string
|
|
25
28
|
/** 插件所在目录,用于查找随包分发的初始角色设定。 */
|
|
26
29
|
moduleDir: string
|
|
30
|
+
/** 已知凭证明文:人格文件里出现就掩码或拒绝加载。 */
|
|
31
|
+
secrets?: readonly string[]
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
/** 工作目录里的角色设定目录。 */
|
|
@@ -132,8 +137,29 @@ export class SoulStore {
|
|
|
132
137
|
|
|
133
138
|
/** 解析路径、读取内容并开始监听文件变化。 */
|
|
134
139
|
async load(): Promise<void> {
|
|
135
|
-
|
|
136
|
-
|
|
140
|
+
const target = resolveSoulPath(this.options)
|
|
141
|
+
const check = await checkSoulPath(target, this.options)
|
|
142
|
+
if (!check.ok) {
|
|
143
|
+
this.#text = ""
|
|
144
|
+
if (check.missing) {
|
|
145
|
+
// 文件还没建好:先盯着所在目录,等它出现再读。
|
|
146
|
+
this.#path = target
|
|
147
|
+
this.#logger.warn(`角色设定还不存在:${target}`)
|
|
148
|
+
this.#watch()
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
this.#path = undefined
|
|
152
|
+
this.#logger.warn(`角色设定不可用:${check.reason}`)
|
|
153
|
+
return
|
|
154
|
+
}
|
|
155
|
+
this.#path = check.path
|
|
156
|
+
const content = await readSoulContent(check.path, this.options.secrets ?? [])
|
|
157
|
+
if (content.reason) {
|
|
158
|
+
this.#text = ""
|
|
159
|
+
this.#logger.warn(`角色设定不可用:${content.reason}`)
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
this.#text = content.text
|
|
137
163
|
if (!this.#text) this.#logger.warn(`角色设定读取失败:${this.#path}`)
|
|
138
164
|
else this.#logger.info(`角色设定已加载:${this.#path}`)
|
|
139
165
|
this.#watch()
|
|
@@ -142,9 +168,18 @@ export class SoulStore {
|
|
|
142
168
|
/** 重新读取角色设定文件,内容有变化时返回 true。 */
|
|
143
169
|
async reload(): Promise<boolean> {
|
|
144
170
|
if (!this.#path) return false
|
|
145
|
-
const
|
|
146
|
-
if (
|
|
147
|
-
|
|
171
|
+
const check = await checkSoulPath(this.#path, this.options)
|
|
172
|
+
if (!check.ok) {
|
|
173
|
+
this.#logger.warn(`角色设定不可用:${check.reason}`)
|
|
174
|
+
return false
|
|
175
|
+
}
|
|
176
|
+
const content = await readSoulContent(check.path, this.options.secrets ?? [])
|
|
177
|
+
if (content.reason) {
|
|
178
|
+
this.#logger.warn(`角色设定不可用:${content.reason}`)
|
|
179
|
+
return false
|
|
180
|
+
}
|
|
181
|
+
if (content.text === this.#text) return false
|
|
182
|
+
this.#text = content.text
|
|
148
183
|
this.#logger.info(`角色设定已更新:${this.#path}`)
|
|
149
184
|
return true
|
|
150
185
|
}
|
|
@@ -204,6 +239,8 @@ export function packageDirectory(): string {
|
|
|
204
239
|
*/
|
|
205
240
|
export class SoulLibrary {
|
|
206
241
|
readonly #stores = new Map<string, SoulStore>()
|
|
242
|
+
/** 路径解析结果的缓存:同一份设定不用每轮都去 stat 一遍。 */
|
|
243
|
+
readonly #resolved = new Map<string, string>()
|
|
207
244
|
#defaultStore: SoulStore | undefined
|
|
208
245
|
|
|
209
246
|
constructor(
|
|
@@ -222,22 +259,50 @@ export class SoulLibrary {
|
|
|
222
259
|
return store
|
|
223
260
|
}
|
|
224
261
|
|
|
225
|
-
/**
|
|
226
|
-
async at(path: string | undefined): Promise<SoulStore> {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
262
|
+
/** 某个路径或名字的角色设定;都没给时用默认档。 */
|
|
263
|
+
async at(path: string | undefined, name?: string): Promise<SoulStore> {
|
|
264
|
+
if (!path?.trim() && !name?.trim()) return this.loadDefault()
|
|
265
|
+
const key = `${path ?? ""}\u0000${name ?? ""}`
|
|
266
|
+
let absolute = this.#resolved.get(key)
|
|
267
|
+
if (!absolute) {
|
|
268
|
+
absolute = resolveSoulPath({ ...this.options, soulPath: path, soulName: name })
|
|
269
|
+
this.#resolved.set(key, absolute)
|
|
270
|
+
this.#evictResolved()
|
|
271
|
+
}
|
|
230
272
|
const cached = this.#stores.get(absolute)
|
|
231
273
|
if (cached) return cached
|
|
232
274
|
const store = new SoulStore({ ...this.options, soulPath: absolute }, this.logger)
|
|
233
275
|
await store.load()
|
|
234
276
|
this.#stores.set(absolute, store)
|
|
277
|
+
this.#evict()
|
|
235
278
|
return store
|
|
236
279
|
}
|
|
237
280
|
|
|
281
|
+
/** 缓存的设定份数有上限:超出后丢掉最早加载的,别让它无界增长。 */
|
|
282
|
+
#evict(): void {
|
|
283
|
+
while (this.#stores.size > MAX_SOUL_STORES) {
|
|
284
|
+
const oldest = this.#stores.keys().next()
|
|
285
|
+
if (oldest.done) break
|
|
286
|
+
const store = this.#stores.get(oldest.value)
|
|
287
|
+
if (store === this.#defaultStore) break
|
|
288
|
+
this.#stores.delete(oldest.value)
|
|
289
|
+
store?.dispose()
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** 路径解析结果的缓存同样有上限:聊天数不封顶时这张表会一直涨。 */
|
|
294
|
+
#evictResolved(): void {
|
|
295
|
+
while (this.#resolved.size > MAX_SOUL_STORES) {
|
|
296
|
+
const oldest = this.#resolved.keys().next()
|
|
297
|
+
if (oldest.done) break
|
|
298
|
+
this.#resolved.delete(oldest.value)
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
238
302
|
dispose(): void {
|
|
239
303
|
for (const store of this.#stores.values()) store.dispose()
|
|
240
304
|
this.#stores.clear()
|
|
305
|
+
this.#resolved.clear()
|
|
241
306
|
this.#defaultStore = undefined
|
|
242
307
|
}
|
|
243
308
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import lockfile from "@bybrave/proper-lockfile2"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 共享会话状态的跨进程写锁。
|
|
5
|
+
*
|
|
6
|
+
* 插件存储是全机器共享的:两个实例同时读-改-写同一张表时,
|
|
7
|
+
* 后写的会拿自己的旧视图覆盖先写的。这里用文件锁把读-改-写串成一段临界区。
|
|
8
|
+
*
|
|
9
|
+
* 锁没有「持有上限」:临界区多长都能继续写。锁被抢走时通过 `onCompromised` 报出来,
|
|
10
|
+
* 调用方要处理这个信号,不要当成没发生。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 锁的过期时间:超过这么久没有心跳,锁可被其他进程接管。
|
|
15
|
+
*
|
|
16
|
+
* 临界区只有几次存储读写,正常情况下毫秒级完成;
|
|
17
|
+
* 窗口取大一些,避免事件循环被长任务阻塞、或者进程被 suspend 时误判成锁失效
|
|
18
|
+
* ——误判会让两个进程同时写同一张表。
|
|
19
|
+
*/
|
|
20
|
+
const STALE_MS = 120_000
|
|
21
|
+
/** 心跳间隔:必须明显小于过期时间。 */
|
|
22
|
+
const UPDATE_MS = 30_000
|
|
23
|
+
|
|
24
|
+
/** 写锁句柄。 */
|
|
25
|
+
export interface StateLock {
|
|
26
|
+
/** 释放锁;必须等待完成,确保锁目录真正清掉。 */
|
|
27
|
+
release(): Promise<void>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 取锁的可选参数。 */
|
|
31
|
+
export interface StateLockOptions {
|
|
32
|
+
/** 抢不到锁时的重试参数。 */
|
|
33
|
+
retries?: { retries?: number; factor?: number; minTimeout?: number; maxTimeout?: number }
|
|
34
|
+
/** 心跳失效时回调:锁已无法保证独占。 */
|
|
35
|
+
onCompromised?: (error: Error) => void
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 拿到共享状态的写锁。
|
|
40
|
+
*
|
|
41
|
+
* @param lockPath 锁路径,锁目录建在这里,父目录必须已经存在。
|
|
42
|
+
* @param options 可选参数,`retries` 决定抢不到锁时等多久。
|
|
43
|
+
* @returns 拿到锁时返回句柄,被占用且重试用尽时返回 undefined。
|
|
44
|
+
*/
|
|
45
|
+
export async function acquireStateLock(
|
|
46
|
+
lockPath: string,
|
|
47
|
+
options: StateLockOptions = {},
|
|
48
|
+
): Promise<StateLock | undefined> {
|
|
49
|
+
try {
|
|
50
|
+
const release = await lockfile.lock(lockPath, {
|
|
51
|
+
lockfilePath: lockPath,
|
|
52
|
+
// 目标文件并不存在,只要锁目录即可,不需要解析真实路径。
|
|
53
|
+
realpath: false,
|
|
54
|
+
stale: STALE_MS,
|
|
55
|
+
update: UPDATE_MS,
|
|
56
|
+
retries: options.retries ?? 0,
|
|
57
|
+
onCompromised: (error) => options.onCompromised?.(error),
|
|
58
|
+
})
|
|
59
|
+
return {
|
|
60
|
+
release: async () => {
|
|
61
|
+
try {
|
|
62
|
+
await release()
|
|
63
|
+
} catch (error) {
|
|
64
|
+
// 锁已经失效时释放会报 ERELEASED,锁目录由接管方清理。
|
|
65
|
+
if ((error as NodeJS.ErrnoException).code !== "ERELEASED") throw error
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
} catch (error) {
|
|
70
|
+
// 锁被占用是正常情况,其它错误交给调用方处理。
|
|
71
|
+
if ((error as NodeJS.ErrnoException).code === "ELOCKED") return undefined
|
|
72
|
+
throw error
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/tools/policy.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { readFile, stat } from "node:fs/promises"
|
|
2
|
-
import { join } from "node:path"
|
|
2
|
+
import { join, resolve } from "node:path"
|
|
3
3
|
import type { ChatTarget } from "../chat"
|
|
4
4
|
import type { QQBotConfig } from "../config"
|
|
5
5
|
import type { Logger } from "../logger"
|
|
6
|
+
import { hasKey, isSafeKey, safeMap } from "../safe-object"
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* 消息发送者的角色,决定用哪一档工具配置。
|
|
@@ -44,10 +45,11 @@ export interface ToolPolicyFile {
|
|
|
44
45
|
/**
|
|
45
46
|
* 只对 owner 与 admin 开放的工具。
|
|
46
47
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
48
|
+
* 日记记录聊天内容,发文件能把本地文件送出去,收藏表情会往本机写文件:
|
|
49
|
+
* 三者都只给管理档。用 deny 而不是不放进 allow,
|
|
50
|
+
* 是为了用户自定义配置档时也不会误放开。
|
|
49
51
|
*/
|
|
50
|
-
const
|
|
52
|
+
const ADMIN_DENY = ["qq_diary_*", "qq_send_file", "qq_collect_sticker"]
|
|
51
53
|
|
|
52
54
|
/**
|
|
53
55
|
* 只有 owner 能用的工具。
|
|
@@ -57,18 +59,25 @@ const DIARY_DENY = ["qq_diary_*", "qq_send_file"]
|
|
|
57
59
|
*/
|
|
58
60
|
const OWNER_ONLY = ["qq_diary_*"]
|
|
59
61
|
|
|
62
|
+
/**
|
|
63
|
+
* 只有管理角色(owner 与 admin)能用的工具。
|
|
64
|
+
*
|
|
65
|
+
* 按角色判定:用户自定义配置档写得多开放,这里也要再收一次。
|
|
66
|
+
*/
|
|
67
|
+
const ADMIN_ONLY = ["qq_collect_sticker"]
|
|
68
|
+
|
|
60
69
|
/** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
|
|
61
70
|
export function defaultToolPolicy(): ToolPolicyFile {
|
|
71
|
+
const profiles = safeMap<ToolProfile>()
|
|
72
|
+
profiles.chat = { allow: ["websearch", "webfetch", "qq_*"], deny: [...ADMIN_DENY] }
|
|
73
|
+
profiles.readonly = { allow: ["read", "glob", "grep", "qq_*"], deny: [...ADMIN_DENY] }
|
|
74
|
+
// 主动说话没有人参与,权限不能跟着聊天内容走:与普通聊天同档。
|
|
75
|
+
profiles.proactive = { allow: ["websearch", "webfetch", "qq_*"], deny: [...ADMIN_DENY] }
|
|
76
|
+
profiles.admin = { allow: ["*"], deny: [] }
|
|
62
77
|
return {
|
|
63
78
|
defaultProfile: "chat",
|
|
64
|
-
profiles
|
|
65
|
-
|
|
66
|
-
readonly: { allow: ["read", "glob", "grep", "qq_*"], deny: [...DIARY_DENY] },
|
|
67
|
-
// 主动说话没有人参与,权限不能跟着聊天内容走:与普通聊天同档。
|
|
68
|
-
proactive: { allow: ["websearch", "webfetch", "qq_*"], deny: [...DIARY_DENY] },
|
|
69
|
-
admin: { allow: ["*"], deny: [] },
|
|
70
|
-
},
|
|
71
|
-
chats: {},
|
|
79
|
+
profiles,
|
|
80
|
+
chats: safeMap<string>(),
|
|
72
81
|
}
|
|
73
82
|
}
|
|
74
83
|
|
|
@@ -77,6 +86,20 @@ export function defaultToolProfilesPath(home: string): string {
|
|
|
77
86
|
return join(home, "tool-profiles.json")
|
|
78
87
|
}
|
|
79
88
|
|
|
89
|
+
/**
|
|
90
|
+
* 解析工具配置文件的实际位置。
|
|
91
|
+
*
|
|
92
|
+
* 配置里写了 `toolProfilesPath` 就按工作目录解析(绝对路径原样使用),
|
|
93
|
+
* 没写就用工作目录下的默认位置。启动与面板共用这一份解析。
|
|
94
|
+
*/
|
|
95
|
+
export function resolveToolProfilesPath(
|
|
96
|
+
config: { toolProfilesPath?: string },
|
|
97
|
+
home: string,
|
|
98
|
+
): string {
|
|
99
|
+
const configured = config.toolProfilesPath?.trim()
|
|
100
|
+
return configured ? resolve(home, configured) : defaultToolProfilesPath(home)
|
|
101
|
+
}
|
|
102
|
+
|
|
80
103
|
/**
|
|
81
104
|
* 判断工具名是否命中通配模式。
|
|
82
105
|
*
|
|
@@ -119,7 +142,7 @@ export function parseToolPolicy(value: unknown, warn: (message: string) => void)
|
|
|
119
142
|
return fallback
|
|
120
143
|
}
|
|
121
144
|
const raw = value as Record<string, unknown>
|
|
122
|
-
const profiles
|
|
145
|
+
const profiles = safeMap<ToolProfile>()
|
|
123
146
|
const source = raw.profiles
|
|
124
147
|
if (source !== undefined) {
|
|
125
148
|
if (!source || typeof source !== "object" || Array.isArray(source)) {
|
|
@@ -127,6 +150,10 @@ export function parseToolPolicy(value: unknown, warn: (message: string) => void)
|
|
|
127
150
|
return fallback
|
|
128
151
|
}
|
|
129
152
|
for (const [name, entry] of Object.entries(source as Record<string, unknown>)) {
|
|
153
|
+
if (!isSafeKey(name)) {
|
|
154
|
+
warn(`工具配置档 ${name} 是保留名,已忽略`)
|
|
155
|
+
continue
|
|
156
|
+
}
|
|
130
157
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
131
158
|
warn(`工具配置档 ${name} 必须是对象,已忽略`)
|
|
132
159
|
continue
|
|
@@ -140,16 +167,16 @@ export function parseToolPolicy(value: unknown, warn: (message: string) => void)
|
|
|
140
167
|
}
|
|
141
168
|
// 用户没有覆盖的档沿用内置默认值,这样只写一档也能用。
|
|
142
169
|
for (const [name, profile] of Object.entries(fallback.profiles)) {
|
|
143
|
-
if (!profiles
|
|
170
|
+
if (!hasKey(profiles, name)) profiles[name] = profile
|
|
144
171
|
}
|
|
145
172
|
const defaultProfile =
|
|
146
173
|
typeof raw.defaultProfile === "string" && raw.defaultProfile.trim()
|
|
147
174
|
? raw.defaultProfile.trim()
|
|
148
175
|
: fallback.defaultProfile
|
|
149
|
-
if (!profiles
|
|
176
|
+
if (!hasKey(profiles, defaultProfile)) {
|
|
150
177
|
warn(`defaultProfile 指向不存在的配置档 ${defaultProfile},已回退到 ${fallback.defaultProfile}`)
|
|
151
178
|
}
|
|
152
|
-
const chats
|
|
179
|
+
const chats = safeMap<string>()
|
|
153
180
|
if (raw.chats !== undefined) {
|
|
154
181
|
if (!raw.chats || typeof raw.chats !== "object" || Array.isArray(raw.chats)) {
|
|
155
182
|
warn("chats 必须是对象,已忽略")
|
|
@@ -164,7 +191,7 @@ export function parseToolPolicy(value: unknown, warn: (message: string) => void)
|
|
|
164
191
|
}
|
|
165
192
|
}
|
|
166
193
|
return {
|
|
167
|
-
defaultProfile: profiles
|
|
194
|
+
defaultProfile: hasKey(profiles, defaultProfile) ? defaultProfile : fallback.defaultProfile,
|
|
168
195
|
profiles,
|
|
169
196
|
chats,
|
|
170
197
|
}
|
|
@@ -178,21 +205,24 @@ export function parseToolPolicy(value: unknown, warn: (message: string) => void)
|
|
|
178
205
|
*/
|
|
179
206
|
export function profileNameFor(file: ToolPolicyFile, role: Role, chatKey: string): string {
|
|
180
207
|
if (role === "owner" || role === "admin") {
|
|
181
|
-
return file.profiles
|
|
208
|
+
return hasKey(file.profiles, "admin") ? "admin" : file.defaultProfile
|
|
182
209
|
}
|
|
183
210
|
if (role === "proactive") {
|
|
184
|
-
return file.profiles
|
|
211
|
+
return hasKey(file.profiles, "proactive") ? "proactive" : file.defaultProfile
|
|
185
212
|
}
|
|
186
213
|
const named = file.chats[chatKey]
|
|
187
|
-
if (named && file.profiles
|
|
214
|
+
if (named && hasKey(file.profiles, named)) return named
|
|
188
215
|
return file.defaultProfile
|
|
189
216
|
}
|
|
190
217
|
|
|
191
218
|
/** 从工具名列表里筛出该配置档允许的项;deny 优先于 allow。 */
|
|
192
219
|
export function allowedTools(profile: ToolProfile, names: readonly string[]): string[] {
|
|
220
|
+
// 配置档可能来自被污染过的文件:字段不是数组时按空列表算,不让整个机器人崩掉。
|
|
221
|
+
const deny = Array.isArray(profile?.deny) ? profile.deny : []
|
|
222
|
+
const allow = Array.isArray(profile?.allow) ? profile.allow : []
|
|
193
223
|
const allowed = (name: string) =>
|
|
194
|
-
!
|
|
195
|
-
(
|
|
224
|
+
!deny.some((pattern) => globMatch(pattern, name)) &&
|
|
225
|
+
(allow.includes("*") || allow.some((pattern) => globMatch(pattern, name)))
|
|
196
226
|
return names.filter(allowed)
|
|
197
227
|
}
|
|
198
228
|
|
|
@@ -231,8 +261,13 @@ export class ToolPolicy {
|
|
|
231
261
|
/** 某个角色在某个聊天里能用的工具子集。 */
|
|
232
262
|
async allow(role: Role, chatKey: string, names: readonly string[]): Promise<Set<string>> {
|
|
233
263
|
const file = await this.current()
|
|
234
|
-
const
|
|
235
|
-
|
|
264
|
+
const name = profileNameFor(file, role, chatKey)
|
|
265
|
+
const profile = hasKey(file.profiles, name) ? file.profiles[name] : undefined
|
|
266
|
+
if (!profile) {
|
|
267
|
+
// 找不到配置档时一律不放行:让配置坏了就等于机器人失去工具,比崩掉好。
|
|
268
|
+
this.logger.warn(`工具配置 ${this.path}:找不到配置档 ${name},本轮不放行任何工具`)
|
|
269
|
+
return new Set<string>()
|
|
270
|
+
}
|
|
236
271
|
const allowed = new Set(allowedTools(profile, names))
|
|
237
272
|
// 配置档只按工具名分配,日记这类只给 owner 的工具要在这里再按角色收一次。
|
|
238
273
|
if (role !== "owner") {
|
|
@@ -240,6 +275,12 @@ export class ToolPolicy {
|
|
|
240
275
|
if (OWNER_ONLY.some((pattern) => globMatch(pattern, name))) allowed.delete(name)
|
|
241
276
|
}
|
|
242
277
|
}
|
|
278
|
+
// 收藏表情会往本机写文件:只有管理角色能用,配置档放开也不行。
|
|
279
|
+
if (role !== "owner" && role !== "admin") {
|
|
280
|
+
for (const name of allowed) {
|
|
281
|
+
if (ADMIN_ONLY.some((pattern) => globMatch(pattern, name))) allowed.delete(name)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
243
284
|
return allowed
|
|
244
285
|
}
|
|
245
286
|
|
package/src/tools/qq.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { isTargetAllowed } from "../access"
|
|
|
4
4
|
import { delay } from "../async"
|
|
5
5
|
import { type ChatTarget, targetKey, targetLabel } from "../chat"
|
|
6
6
|
import type { QQBotConfig } from "../config"
|
|
7
|
-
import { dateKey, isDateKey } from "../diary/format"
|
|
7
|
+
import { chatLabel, dateKey, isDateKey } from "../diary/format"
|
|
8
8
|
import { isDiaryScopeChat } from "../diary/scope"
|
|
9
9
|
import type { DiaryStore } from "../diary/store"
|
|
10
10
|
import {
|
|
@@ -192,11 +192,13 @@ function sanitizeDiaryBody(body: string): string {
|
|
|
192
192
|
return neutralizeStructureTags(lines.join("\n"))
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
-
/**
|
|
196
|
-
function formatDiaryBody(date: string, title: string, body: string): string {
|
|
195
|
+
/** 组装给模型看的日记正文:带聊天标识的标题加正文,超长时按自然边界截断。 */
|
|
196
|
+
function formatDiaryBody(date: string, chat: string, title: string, body: string): string {
|
|
197
197
|
const plain = sanitizeDiaryBody(body)
|
|
198
198
|
const clipped = softTruncate(plain, DIARY_READ_MAX_CHARS)
|
|
199
|
-
return [`${date} 的日记:${sanitizeUntrustedText(title)}`, "", clipped].join(
|
|
199
|
+
return [`${chatLabel(chat)} ${date} 的日记:${sanitizeUntrustedText(title)}`, "", clipped].join(
|
|
200
|
+
"\n",
|
|
201
|
+
)
|
|
200
202
|
}
|
|
201
203
|
|
|
202
204
|
/** 按目标类型把消息投递出去:群聊与私聊走不同的 API。 */
|
|
@@ -1105,7 +1107,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1105
1107
|
const diaryMissing = async (chat: string, date: string): Promise<string> => {
|
|
1106
1108
|
const available = (await diaryStore.list(chat, 10)).map((item) => item.date)
|
|
1107
1109
|
const hint = available.length > 0 ? `(可用的日期:${available.join("、")})` : ""
|
|
1108
|
-
return `error: 没有找到 ${date} 的日记${hint}`
|
|
1110
|
+
return `error: 没有找到 ${chatLabel(chat)} ${date} 的日记${hint}`
|
|
1109
1111
|
}
|
|
1110
1112
|
|
|
1111
1113
|
editor.add({
|
|
@@ -1136,7 +1138,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1136
1138
|
body: content,
|
|
1137
1139
|
source: "model",
|
|
1138
1140
|
})
|
|
1139
|
-
return text(`已写入 ${date} 的日记:${entry.title}`)
|
|
1141
|
+
return text(`已写入 ${chatLabel(targetKey(target))} ${date} 的日记:${entry.title}`)
|
|
1140
1142
|
},
|
|
1141
1143
|
})
|
|
1142
1144
|
|
|
@@ -1160,13 +1162,13 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1160
1162
|
const date = input.date?.trim()
|
|
1161
1163
|
if (!date) {
|
|
1162
1164
|
const latest = await diaryStore.latest(chat)
|
|
1163
|
-
if (!latest) return text(
|
|
1164
|
-
return text(formatDiaryBody(latest.date, latest.title, latest.body))
|
|
1165
|
+
if (!latest) return text(`error: ${chatLabel(chat)} 还没有日记`)
|
|
1166
|
+
return text(formatDiaryBody(latest.date, chat, latest.title, latest.body))
|
|
1165
1167
|
}
|
|
1166
1168
|
if (!isDateKey(date)) return text(`error: 日期格式不对:${date},请用 YYYY-MM-DD`)
|
|
1167
1169
|
const entry = await diaryStore.read(chat, date)
|
|
1168
1170
|
if (!entry) return text(await diaryMissing(chat, date))
|
|
1169
|
-
return text(formatDiaryBody(entry.date, entry.title, entry.body))
|
|
1171
|
+
return text(formatDiaryBody(entry.date, chat, entry.title, entry.body))
|
|
1170
1172
|
},
|
|
1171
1173
|
})
|
|
1172
1174
|
|
|
@@ -1187,9 +1189,15 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1187
1189
|
const target = diaryTarget(context.sessionID)
|
|
1188
1190
|
if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
|
|
1189
1191
|
const days = Number.isInteger(input.days) && (input.days ?? 0) > 0 ? (input.days ?? 7) : 7
|
|
1190
|
-
const
|
|
1191
|
-
|
|
1192
|
-
|
|
1192
|
+
const chat = targetKey(target)
|
|
1193
|
+
const entries = await diaryStore.list(chat, days)
|
|
1194
|
+
if (entries.length === 0) return text(`${chatLabel(chat)} 还没有日记。`)
|
|
1195
|
+
return text(
|
|
1196
|
+
[
|
|
1197
|
+
`${chatLabel(chat)} 最近的日记`,
|
|
1198
|
+
...entries.map((entry) => `${entry.date} ${entry.title}`),
|
|
1199
|
+
].join("\n"),
|
|
1200
|
+
)
|
|
1193
1201
|
},
|
|
1194
1202
|
})
|
|
1195
1203
|
}
|