@cmach_socket/opencode-qq-bot 0.9.2 → 0.10.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.
Files changed (49) hide show
  1. package/NOTICE +0 -1
  2. package/README.md +43 -20
  3. package/chat-overrides.example.json +3 -3
  4. package/package.json +6 -2
  5. package/src/chat.ts +5 -0
  6. package/src/commands.ts +88 -1
  7. package/src/config/fields.ts +68 -5
  8. package/src/config/live.ts +33 -3
  9. package/src/config/registry.ts +32 -0
  10. package/src/config/store.ts +6 -11
  11. package/src/config/types.ts +29 -1
  12. package/src/config.ts +8 -1
  13. package/src/diary/command.ts +21 -20
  14. package/src/diary/format.ts +18 -1
  15. package/src/diary/scheduler.ts +7 -7
  16. package/src/diary/scope.ts +1 -1
  17. package/src/diary/summary.ts +39 -38
  18. package/src/emoji/collection.ts +33 -1
  19. package/src/fs/atomic.ts +82 -0
  20. package/src/home.ts +6 -2
  21. package/src/index.ts +113 -45
  22. package/src/keepalive.ts +60 -2
  23. package/src/known-secrets.ts +20 -0
  24. package/src/logger.ts +19 -3
  25. package/src/model-view.ts +4 -15
  26. package/src/naplink/history.ts +12 -7
  27. package/src/overrides.ts +268 -51
  28. package/src/panel/api.ts +79 -7
  29. package/src/panel/documents.ts +622 -0
  30. package/src/panel/server.ts +18 -1
  31. package/src/panel/status.ts +10 -3
  32. package/src/restartable.ts +74 -0
  33. package/src/safe-object.ts +48 -0
  34. package/src/sensitive.ts +31 -2
  35. package/src/session/find.ts +3 -2
  36. package/src/session/manager.ts +646 -43
  37. package/src/session/proactive.ts +3 -1
  38. package/src/session/prompt.ts +5 -13
  39. package/src/session/soul-guard.ts +162 -0
  40. package/src/session/soul.ts +78 -13
  41. package/src/state-lock.ts +74 -0
  42. package/src/time-format.ts +45 -0
  43. package/src/tools/policy.ts +65 -24
  44. package/src/tools/qq.ts +20 -12
  45. package/web/dist/assets/index-B-3ZGYMq.js +8 -0
  46. package/web/dist/assets/index-C5lRsdbz.css +1 -0
  47. package/web/dist/index.html +2 -2
  48. package/web/dist/assets/index-7eMQEM7-.css +0 -1
  49. package/web/dist/assets/index-DCkgUY7y.js +0 -15
@@ -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.proactiveProbability !== undefined) return override.proactiveProbability
38
+ if (override["proactive.startProbability"] !== undefined) {
39
+ return override["proactive.startProbability"]
40
+ }
39
41
  return proactiveTickProbability(config, silenceSeconds)
40
42
  }
@@ -1,3 +1,5 @@
1
+ import { DEFAULT_TIME_ZONE, formatDateTime } from "../time-format"
2
+
1
3
  /** 发消息用的工具名(命名空间 qq 下的 send_message)。 */
2
4
  export const SEND_MESSAGE_TOOL = "qq_send_message"
3
5
 
@@ -7,7 +9,7 @@ GUIDELINES:
7
9
  对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。
8
10
  <forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。
9
11
  <history>...</history> 里面是本次会话开始之前的历史聊天记录,按时间顺序排列,用来了解之前聊过什么。
10
- 每条消息都是 \`[26-11-07 14:33] 名字: 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面只有 owner 和管理员才有 \`(owner)\`、\`(admin)\` 这样的角色标记,普通成员没有标记;群名片由对方自己填写,标记本身才说明身份。你需要根据这些消息来判断每个用户的意图和情感。
12
+ 每条消息都是 \`[26-11-07 14:33] 名字: 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(按配置的时区),名字后面只有 owner 和管理员才有 \`(owner)\`、\`(admin)\` 这样的角色标记,普通成员没有标记;群名片由对方自己填写,标记本身才说明身份。你需要根据这些消息来判断每个用户的意图和情感。
11
13
  重要!!!发送消息时,**必须**调用发送类工具;任何直接输出的文字都会被**完全丢弃**,不会作为消息内容发送!!!
12
14
  文本回复用 ${SEND_MESSAGE_TOOL};图片、语音、合并转发、戳一戳等用对应的 qq_* 工具,调用成功同样算作已回复。
13
15
  每轮至少调用一个发送类工具;不想回复时把 ${SEND_MESSAGE_TOOL} 的 reply 设成 false(content 可留空),相当于已读不回。群聊里不需要每一条都回复,像人一样选择性回复就行。
@@ -28,17 +30,7 @@ export function buildSystemPrompt(soul: string): string {
28
30
  return base ? `${base}\n${GUIDELINES}` : GUIDELINES.trim()
29
31
  }
30
32
 
31
- const TIME_FORMAT = new Intl.DateTimeFormat("sv-SE", {
32
- year: "numeric",
33
- month: "2-digit",
34
- day: "2-digit",
35
- hour: "2-digit",
36
- minute: "2-digit",
37
- second: "2-digit",
38
- hour12: false,
39
- })
40
-
41
33
  /** 当前时间文本,注入到系统提示里让模型知道现在几点。 */
42
- export function currentTimeText(now = new Date()): string {
43
- return TIME_FORMAT.format(now)
34
+ export function currentTimeText(timeZone = DEFAULT_TIME_ZONE, now = new Date()): string {
35
+ return formatDateTime(now, timeZone)
44
36
  }
@@ -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
+ }
@@ -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
- this.#path = resolveSoulPath(this.options)
136
- this.#text = await loadSoul(this.#path)
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 text = await loadSoul(this.#path)
146
- if (text === this.#text) return false
147
- this.#text = text
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
- const explicit = path?.trim()
228
- if (!explicit) return this.loadDefault()
229
- const absolute = isAbsolute(explicit) ? explicit : resolve(this.options.home, explicit)
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
+ }
@@ -0,0 +1,45 @@
1
+ /** 时间显示用的默认时区:QQ 用户所在的东八区。 */
2
+ export const DEFAULT_TIME_ZONE = "Asia/Shanghai"
3
+
4
+ /** 格式化器缓存:`Intl.DateTimeFormat` 构造开销大,按字段与时区复用。 */
5
+ const TIMESTAMP_FORMATS = new Map<string, Intl.DateTimeFormat>()
6
+ const DATE_TIME_FORMATS = new Map<string, Intl.DateTimeFormat>()
7
+
8
+ function createFormat(
9
+ cache: Map<string, Intl.DateTimeFormat>,
10
+ timeZone: string,
11
+ options: Intl.DateTimeFormatOptions,
12
+ ): Intl.DateTimeFormat {
13
+ let format = cache.get(timeZone)
14
+ if (!format) {
15
+ format = new Intl.DateTimeFormat("sv-SE", { ...options, timeZone })
16
+ cache.set(timeZone, format)
17
+ }
18
+ return format
19
+ }
20
+
21
+ /** 绝对时间标注:指定时区的 `YY-MM-DD HH:MM`;时间无效时返回空串。 */
22
+ export function formatTimestamp(seconds: number, timeZone = DEFAULT_TIME_ZONE): string {
23
+ if (!Number.isFinite(seconds) || seconds <= 0) return ""
24
+ return createFormat(TIMESTAMP_FORMATS, timeZone, {
25
+ year: "2-digit",
26
+ month: "2-digit",
27
+ day: "2-digit",
28
+ hour: "2-digit",
29
+ minute: "2-digit",
30
+ hour12: false,
31
+ }).format(new Date(seconds * 1000))
32
+ }
33
+
34
+ /** 当前时间:指定时区的 `YYYY-MM-DD HH:mm:ss`。 */
35
+ export function formatDateTime(now: Date, timeZone = DEFAULT_TIME_ZONE): string {
36
+ return createFormat(DATE_TIME_FORMATS, timeZone, {
37
+ year: "numeric",
38
+ month: "2-digit",
39
+ day: "2-digit",
40
+ hour: "2-digit",
41
+ minute: "2-digit",
42
+ second: "2-digit",
43
+ hour12: false,
44
+ }).format(now)
45
+ }
@@ -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
- * 用 deny 而不是不放进 allow,是为了用户自定义配置档时也不会误放开。
48
+ * 日记记录聊天内容,发文件能把本地文件送出去,收藏表情会往本机写文件:
49
+ * 三者都只给管理档。用 deny 而不是不放进 allow,
50
+ * 是为了用户自定义配置档时也不会误放开。
49
51
  */
50
- const DIARY_DENY = ["qq_diary_*", "qq_send_file"]
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
- chat: { allow: ["websearch", "webfetch", "qq_*"], deny: [...DIARY_DENY] },
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: Record<string, ToolProfile> = {}
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[name]) profiles[name] = profile
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[defaultProfile]) {
176
+ if (!hasKey(profiles, defaultProfile)) {
150
177
  warn(`defaultProfile 指向不存在的配置档 ${defaultProfile},已回退到 ${fallback.defaultProfile}`)
151
178
  }
152
- const chats: Record<string, string> = {}
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[defaultProfile] ? defaultProfile : fallback.defaultProfile,
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.admin ? "admin" : file.defaultProfile
208
+ return hasKey(file.profiles, "admin") ? "admin" : file.defaultProfile
182
209
  }
183
210
  if (role === "proactive") {
184
- return file.profiles.proactive ? "proactive" : file.defaultProfile
211
+ return hasKey(file.profiles, "proactive") ? "proactive" : file.defaultProfile
185
212
  }
186
213
  const named = file.chats[chatKey]
187
- if (named && file.profiles[named]) return named
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
- !profile.deny.some((pattern) => globMatch(pattern, name)) &&
195
- (profile.allow.includes("*") || profile.allow.some((pattern) => globMatch(pattern, name)))
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 profile = file.profiles[profileNameFor(file, role, chatKey)]
235
- if (!profile) return new Set(names)
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