@cmach_socket/opencode-qq-bot 0.7.0 → 0.9.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.
Files changed (51) hide show
  1. package/NOTICE +48 -15
  2. package/README.md +220 -115
  3. package/package.json +10 -1
  4. package/src/cleanup.ts +1 -0
  5. package/src/commands.ts +2 -0
  6. package/src/config/fields.ts +780 -0
  7. package/src/config/live.ts +161 -0
  8. package/src/config/registry.ts +654 -0
  9. package/src/config/store.ts +175 -0
  10. package/src/config/types.ts +253 -0
  11. package/src/config.ts +77 -1023
  12. package/src/diary/collector.ts +28 -14
  13. package/src/diary/command.ts +24 -2
  14. package/src/diary/paths.ts +27 -0
  15. package/src/diary/scheduler.ts +63 -14
  16. package/src/diary/scope.ts +27 -0
  17. package/src/diary/store.ts +48 -4
  18. package/src/diary/summary.ts +33 -5
  19. package/src/home.ts +11 -16
  20. package/src/index.ts +777 -644
  21. package/src/logger.ts +104 -1
  22. package/src/model-view.ts +3 -1
  23. package/src/naplink/client.ts +16 -0
  24. package/src/panel/api.ts +345 -0
  25. package/src/panel/auth.ts +65 -0
  26. package/src/panel/models.ts +56 -0
  27. package/src/panel/runtime.ts +51 -0
  28. package/src/panel/server.ts +185 -0
  29. package/src/panel/status.ts +201 -0
  30. package/src/rate-limit.ts +46 -0
  31. package/src/runtime/claim.ts +37 -0
  32. package/src/runtime/start.ts +55 -0
  33. package/src/sensitive.ts +6 -1
  34. package/src/session/find.ts +44 -10
  35. package/src/session/manager.ts +118 -19
  36. package/src/session/prompt.ts +1 -1
  37. package/src/text.ts +34 -0
  38. package/src/tools/policy.ts +16 -1
  39. package/src/tools/qq.ts +90 -38
  40. package/src/tools/send-guard.ts +2 -2
  41. package/src/tui-commands.ts +1 -1
  42. package/web/dist/assets/index-7eMQEM7-.css +1 -0
  43. package/web/dist/assets/index-DCkgUY7y.js +15 -0
  44. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  45. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  46. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  47. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  48. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  49. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  50. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  51. package/web/dist/index.html +13 -0
@@ -14,7 +14,7 @@ import type { Tracer } from "../trace"
14
14
  import { limitFiles, type PromptFile } from "../naplink/render"
15
15
  import type { WakeReason } from "../overrides"
16
16
  import { roleForChat, roleOf, type Role } from "../tools/policy"
17
- import { findSession } from "./find"
17
+ import { findSessions, type ListedSession } from "./find"
18
18
 
19
19
  /** 插件存储里保存会话与目标绑定的键。 */
20
20
  const BINDINGS_KEY = "bindings"
@@ -46,6 +46,8 @@ export const FAILURE_NOTICE_INTERVAL_MS = 5 * 60 * 1000
46
46
  export const SESSION_RETIRE_COOLDOWN_MS = 10 * 60 * 1000
47
47
  /** 交接时等在途投递落地的最长时间(毫秒)。 */
48
48
  const HANDOVER_WAIT_MS = 3_000
49
+ /** 找回历史会话时最多比较几个候选。 */
50
+ const SESSION_CANDIDATES = 5
49
51
 
50
52
  /** 插件自己往聊天里补话的通道,失败兜底用。 */
51
53
  export type FailureNotifier = (target: ChatTarget, text: string) => Promise<void>
@@ -1191,6 +1193,10 @@ export class SessionManager {
1191
1193
  state.awaitingSend = true
1192
1194
  // 新的用户轮次重新给一份提醒预算,否则连续几轮不调工具就再也提醒不了。
1193
1195
  state.reminders = 0
1196
+ // 轮次边界:发送许可只在本轮有效。新一轮无条件收回上一轮的许可,
1197
+ // 免得缓冲消息触发的新一轮带着上一轮的许可开跑。
1198
+ state.replyAllowed = false
1199
+ state.replyReason = undefined
1194
1200
  const label = targetLabel(state.target)
1195
1201
  this.logger.debug(`${label} 开始投递一轮`, {
1196
1202
  role,
@@ -1303,10 +1309,10 @@ export class SessionManager {
1303
1309
  ...(reminderRole ? { role: reminderRole } : {}),
1304
1310
  }
1305
1311
  this.logger.warn(`${label} 模型未调用发送工具,提醒第 ${state.reminders} 次`)
1306
- // 群里默认没有发送权限,提醒里得说清楚先申请再发。
1312
+ // 群里按约定不主动发言,提醒里得说清楚先说明理由再发。
1307
1313
  const permissionHint =
1308
1314
  this.config.reply.requirePermission && state.target.kind === "group"
1309
- ? "群里要先调用 qq_request_reply 说明为什么要回复,拿到权限后才能发送。"
1315
+ ? "群里要先调用 qq_request_reply 说明为什么要回复,说明之后才能发送。"
1310
1316
  : ""
1311
1317
  try {
1312
1318
  await this.ctx.session.synthetic({
@@ -1478,7 +1484,17 @@ export class SessionManager {
1478
1484
  await this.applyOverride(state.sessionID, label, agent, model)
1479
1485
  return state.sessionID
1480
1486
  }
1481
- this.unbind(state)
1487
+ // 绑定的会话取不到了:先把同一个聊天上还在的历史会话找回,找不到才新建。
1488
+ // 直接新建等于把上百条历史留在库里当孤儿,机器人再也看不见。
1489
+ const stale = state.sessionID
1490
+ const recovered = await this.recoverSession(state, target, stale)
1491
+ if (recovered) {
1492
+ this.logger.info(`${label} 旧会话 ${stale} 不可用,已改用 ${recovered}`)
1493
+ await this.applyOverride(recovered, label, agent, model)
1494
+ return recovered
1495
+ }
1496
+ // 旧会话确实没了:先松开绑定(不落盘),新建成功后一次性写回,避免中途存下空绑定。
1497
+ this.clearBinding(state)
1482
1498
  }
1483
1499
 
1484
1500
  if (this.config.reuseSession) {
@@ -1519,6 +1535,80 @@ export class SessionManager {
1519
1535
  return created.id
1520
1536
  }
1521
1537
 
1538
+ /**
1539
+ * 找回出问题时仍然存在的历史会话。
1540
+ *
1541
+ * 绑定的会话读不到时,如果直接解绑并新建,这个聊天之前积累的上下文就断了;
1542
+ * 历史会话其实还在库里,只要按 QQ 标记在同一目录里找回来就能接上。
1543
+ *
1544
+ * @returns 找回的会话 ID;没有可用的历史会话时返回 `undefined`。
1545
+ */
1546
+ private async recoverSession(
1547
+ state: ChatState,
1548
+ target: ChatTarget,
1549
+ stale: string,
1550
+ ): Promise<string | undefined> {
1551
+ const candidates = await this.findSessionCandidates(target, stale)
1552
+ if (candidates.length === 0) return undefined
1553
+ // 消息最多的那条才是真正聊过的会话:重建出来的空会话消息更少。
1554
+ const best = await this.pickRichestSession(candidates)
1555
+ if (!best) return undefined
1556
+ // 旧绑定先松开,但不能顺手把存储里的绑定抹掉:抹掉就再也找不回来了。
1557
+ this.clearBinding(state)
1558
+ if (!this.bindSession(state, best.id)) return undefined
1559
+ this.verifiedSessions.add(best.id)
1560
+ this.scheduleSave()
1561
+ return best.id
1562
+ }
1563
+
1564
+ /** 同一个聊天上仍然存在的历史会话,按最近优先。 */
1565
+ private async findSessionCandidates(
1566
+ target: ChatTarget,
1567
+ exclude?: string,
1568
+ ): Promise<ListedSession[]> {
1569
+ return await findSessions(
1570
+ this.ctx,
1571
+ this.location.directory,
1572
+ (session) => {
1573
+ const metadata = session.metadata
1574
+ if (!metadata) return false
1575
+ if (metadata["qqTargetKind"] !== target.kind) return false
1576
+ if (metadata["qqTargetId"] !== target.id) return false
1577
+ return session.id !== exclude
1578
+ },
1579
+ this.logger,
1580
+ `查找历史会话失败 ${targetLabel(target)}`,
1581
+ { limit: SESSION_CANDIDATES },
1582
+ )
1583
+ }
1584
+
1585
+ /** 选出消息最多的那条会话。 */
1586
+ private async pickRichestSession(
1587
+ candidates: ListedSession[],
1588
+ ): Promise<ListedSession | undefined> {
1589
+ let best: ListedSession | undefined
1590
+ let bestCount = -1
1591
+ for (const candidate of candidates) {
1592
+ const count = await this.countMessages(candidate.id)
1593
+ if (count > bestCount) {
1594
+ best = candidate
1595
+ bestCount = count
1596
+ }
1597
+ }
1598
+ return best
1599
+ }
1600
+
1601
+ /** 会话里的消息条数;读不到时按 0 算。 */
1602
+ private async countMessages(sessionID: string): Promise<number> {
1603
+ try {
1604
+ const messages = await this.ctx.session.context({ sessionID })
1605
+ return Array.isArray(messages) ? messages.length : 0
1606
+ } catch (error) {
1607
+ this.logger.warn(`读取会话 ${sessionID} 的消息失败`, error)
1608
+ return 0
1609
+ }
1610
+ }
1611
+
1522
1612
  /**
1523
1613
  * 把 agent / 模型覆盖应用到已有会话。
1524
1614
  *
@@ -1559,15 +1649,29 @@ export class SessionManager {
1559
1649
  this.verifiedSessions.add(sessionID)
1560
1650
  return true
1561
1651
  } catch (error) {
1652
+ // 直查只认 sessionID,列表查询才按目录过滤:两种口径不一致时,
1653
+ // 明明还在的会话会被当成已删除。直查失败后再按目录确认一次。
1654
+ if (await this.sessionInDirectory(sessionID)) {
1655
+ this.logger.warn(`会话 ${sessionID} 直查失败,但目录列表里仍然存在,继续沿用`)
1656
+ this.verifiedSessions.add(sessionID)
1657
+ return true
1658
+ }
1562
1659
  this.logger.warn(`会话 ${sessionID} 已不存在,将重新建立绑定`, error)
1563
1660
  return false
1564
1661
  }
1565
1662
  }
1566
1663
 
1567
- private unbind(state: ChatState): void {
1568
- if (!state.sessionID) return
1569
- this.clearBinding(state)
1570
- this.scheduleSave()
1664
+ /** 会话是否还在机器人的工作目录里;直查口径不一致时的兜底判断。 */
1665
+ private async sessionInDirectory(sessionID: string): Promise<boolean> {
1666
+ const found = await findSessions(
1667
+ this.ctx,
1668
+ this.location.directory,
1669
+ (session) => session.id === sessionID,
1670
+ this.logger,
1671
+ `查找会话 ${sessionID} 失败`,
1672
+ { limit: 1 },
1673
+ )
1674
+ return found.length > 0
1571
1675
  }
1572
1676
 
1573
1677
  /** 清掉会话绑定,不动上游会话。 */
@@ -1599,18 +1703,13 @@ export class SessionManager {
1599
1703
  return true
1600
1704
  }
1601
1705
 
1602
- /** 查找带相同目标标记的历史会话,按最近优先分页查找。 */
1706
+ /** 查找带相同目标标记的历史会话,取最近的那条。 */
1603
1707
  private async findExistingSession(target: ChatTarget): Promise<string | undefined> {
1604
- return await findSession(
1605
- this.ctx,
1606
- this.location.directory,
1607
- (session) => {
1608
- const metadata = session.metadata
1609
- return metadata?.["qqTargetKind"] === target.kind && metadata["qqTargetId"] === target.id
1610
- },
1611
- this.logger,
1612
- `查找历史会话失败 ${targetLabel(target)}`,
1613
- )
1708
+ const candidates = await this.findSessionCandidates(target)
1709
+ if (candidates.length === 0) return undefined
1710
+ // 候选按创建时间倒序,第一条就是「上一次的会话」。
1711
+ // 恢复路径要的才是消息最多的那条,两件事不能混。
1712
+ return candidates[0]?.id
1614
1713
  }
1615
1714
 
1616
1715
  /** 主动说话:向目标对应的会话投递一条合成消息。 */
@@ -7,7 +7,7 @@ GUIDELINES:
7
7
  对于一条消息,<quote>...</quote> 里面的内容是引用的消息,通常是你之前发过的消息或者其他人的消息,你需要根据这些引用来判断当前消息的语境。
8
8
  <forward>...</forward> 里面是合并转发消息的内容,每条前面的名字是转发节点的发送者。
9
9
  <history>...</history> 里面是本次会话开始之前的历史聊天记录,按时间顺序排列,用来了解之前聊过什么。
10
- 每条消息都是 \`[26-11-07 14:33] 名字(QQ号): 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面的括号里是发送者的 QQ 号,用来区分同名的人。你需要根据这些消息来判断每个用户的意图和情感。
10
+ 每条消息都是 \`[26-11-07 14:33] 名字: 正文\` 这样的格式:方括号里是这条消息发出的绝对时间(本地时间),名字后面只有 owner 和管理员才有 \`(owner)\`、\`(admin)\` 这样的角色标记,普通成员没有标记;群名片由对方自己填写,标记本身才说明身份。你需要根据这些消息来判断每个用户的意图和情感。
11
11
  重要!!!发送消息时,**必须**调用发送类工具;任何直接输出的文字都会被**完全丢弃**,不会作为消息内容发送!!!
12
12
  文本回复用 ${SEND_MESSAGE_TOOL};图片、语音、合并转发、戳一戳等用对应的 qq_* 工具,调用成功同样算作已回复。
13
13
  每轮至少调用一个发送类工具;不想回复时把 ${SEND_MESSAGE_TOOL} 的 reply 设成 false(content 可留空),相当于已读不回。群聊里不需要每一条都回复,像人一样选择性回复就行。
package/src/text.ts CHANGED
@@ -5,3 +5,37 @@ export const ZERO_WIDTH = /[\u200B-\u200F\u2060\uFEFF]/g
5
5
  export function truncateForLog(value: string, max = 120): string {
6
6
  return value.length > max ? `${value.slice(0, max)}…` : value
7
7
  }
8
+
9
+ /** 截断标记:告诉读者后面还有内容被截掉了。 */
10
+ export const TRUNCATION_MARKER = "…(已截断)"
11
+
12
+ /**
13
+ * 自然断点,按优先级排列。
14
+ *
15
+ * 先段落、再行、再句子、最后是空格:越靠前越像一个完整的意思单元。
16
+ */
17
+ const BREAKS = ["\n\n", "\n", "。", "!", "?", ";", ",", ".", "!", "?", ";", ",", " "]
18
+
19
+ /**
20
+ * 温和截断:断在自然边界上,并标出被截掉的部分。
21
+ *
22
+ * 按字数硬切会把句子拦腰砍断,读起来像坏掉了。
23
+ * 这里先按码点切出上限,再退回最后一个自然断点,末尾补上标记,
24
+ * 让人一眼看出「后面还有内容」,而不是内容凭空少了半句。
25
+ * 找不到自然断点时(整段没有标点的长串)只能按码点切,标记照常加上。
26
+ */
27
+ export function softTruncate(value: string, max: number, marker = TRUNCATION_MARKER): string {
28
+ const chars = Array.from(value)
29
+ if (chars.length <= max) return value
30
+ const tail = Array.from(marker)
31
+ const budget = max - tail.length
32
+ // 上限比标记还小:留不出标记的位置,只能按码点切。
33
+ if (budget <= 0) return chars.slice(0, Math.max(0, max)).join("")
34
+ const head = chars.slice(0, budget).join("")
35
+ for (const point of BREAKS) {
36
+ const index = head.lastIndexOf(point)
37
+ if (index <= 0) continue
38
+ return `${head.slice(0, index + point.length).trimEnd()}${marker}`
39
+ }
40
+ return `${head.trimEnd()}${marker}`
41
+ }
@@ -49,6 +49,14 @@ export interface ToolPolicyFile {
49
49
  */
50
50
  const DIARY_DENY = ["qq_diary_*", "qq_send_file"]
51
51
 
52
+ /**
53
+ * 只有 owner 能用的工具。
54
+ *
55
+ * owner 与 admin 共用 `admin` 档,所以「admin 不能用日记」只能在这里按角色判定,
56
+ * 不能写进 `admin` 档的 deny:那会把 owner 一起禁掉。
57
+ */
58
+ const OWNER_ONLY = ["qq_diary_*"]
59
+
52
60
  /** 内置默认值:普通聊天只留联网搜索、网页抓取和发消息工具,管理档全开。 */
53
61
  export function defaultToolPolicy(): ToolPolicyFile {
54
62
  return {
@@ -225,7 +233,14 @@ export class ToolPolicy {
225
233
  const file = await this.current()
226
234
  const profile = file.profiles[profileNameFor(file, role, chatKey)]
227
235
  if (!profile) return new Set(names)
228
- return new Set(allowedTools(profile, names))
236
+ const allowed = new Set(allowedTools(profile, names))
237
+ // 配置档只按工具名分配,日记这类只给 owner 的工具要在这里再按角色收一次。
238
+ if (role !== "owner") {
239
+ for (const name of allowed) {
240
+ if (OWNER_ONLY.some((pattern) => globMatch(pattern, name))) allowed.delete(name)
241
+ }
242
+ }
243
+ return allowed
229
244
  }
230
245
 
231
246
  /** 某个角色在某个聊天里生效的配置档名字,用于管理命令展示。 */
package/src/tools/qq.ts CHANGED
@@ -5,6 +5,7 @@ import { delay } from "../async"
5
5
  import { type ChatTarget, targetKey, targetLabel } from "../chat"
6
6
  import type { QQBotConfig } from "../config"
7
7
  import { dateKey, isDateKey } from "../diary/format"
8
+ import { isDiaryScopeChat } from "../diary/scope"
8
9
  import type { DiaryStore } from "../diary/store"
9
10
  import {
10
11
  CUSTOM_FACE_SUB_TYPE,
@@ -23,6 +24,7 @@ import { modelSendScope, pluginSendScope } from "../rate-limit"
23
24
  import type { SensitiveChecker } from "../sensitive"
24
25
  import type { SessionManager } from "../session/manager"
25
26
  import type { Tracer } from "../trace"
27
+ import { softTruncate } from "../text"
26
28
 
27
29
  /** 工具命名空间,最终工具名为 qq_send_message 等。 */
28
30
  export const TOOL_NAMESPACE = "qq"
@@ -76,6 +78,13 @@ export interface ToolDeps {
76
78
  sensitive: SensitiveChecker
77
79
  /** 出站媒体的路径与地址把关。 */
78
80
  outbound: OutboundMedia
81
+ /**
82
+ * 普通成员可用的出站媒体把关,只放开媒体目录。
83
+ *
84
+ * owner/admin 用 `outbound`(工作区 + 媒体目录 + 配置的额外目录),
85
+ * 其他人只能用这个收窄过的实例,避免读到工作区里的源码与配置。
86
+ */
87
+ outboundMember?: OutboundMedia
79
88
  /** 日记读写,供 qq_diary_* 使用;不传就不注册日记工具。 */
80
89
  diary?: DiaryStore
81
90
  /** 调用链追踪器;不传就不记追踪。 */
@@ -100,8 +109,6 @@ interface MediaInput {
100
109
  }
101
110
 
102
111
  interface ForwardNodeInput {
103
- user_id?: number | string
104
- nickname?: string
105
112
  content?: string
106
113
  }
107
114
 
@@ -169,10 +176,10 @@ function sanitizeDiaryBody(body: string): string {
169
176
  return neutralizeStructureTags(lines.join("\n"))
170
177
  }
171
178
 
172
- /** 组装给模型看的日记正文:标题加正文,超长截断。 */
179
+ /** 组装给模型看的日记正文:标题加正文,超长时按自然边界截断。 */
173
180
  function formatDiaryBody(date: string, title: string, body: string): string {
174
181
  const plain = sanitizeDiaryBody(body)
175
- const clipped = Array.from(plain).slice(0, DIARY_READ_MAX_CHARS).join("")
182
+ const clipped = softTruncate(plain, DIARY_READ_MAX_CHARS)
176
183
  return [`${date} 的日记:${sanitizeUntrustedText(title)}`, "", clipped].join("\n")
177
184
  }
178
185
 
@@ -298,10 +305,17 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
298
305
  limiter,
299
306
  sensitive,
300
307
  outbound,
308
+ outboundMember,
301
309
  diary,
302
310
  tracer,
303
311
  } = deps
304
312
 
313
+ /** 按当前会话角色选媒体目录范围:只有 owner/admin 能碰工作区。 */
314
+ const mediaFor = (sessionID: string): OutboundMedia =>
315
+ manager.currentRole(sessionID) === "owner" || manager.currentRole(sessionID) === "admin"
316
+ ? outbound
317
+ : (outboundMember ?? outbound)
318
+
305
319
  const requireTarget = (sessionID: string): ChatTarget | undefined => {
306
320
  const target = manager.targetForSession(sessionID)
307
321
  if (!target) return undefined
@@ -344,8 +358,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
344
358
  if (!config.reply.requirePermission) return undefined
345
359
  if (target.kind === "private") return undefined
346
360
  if (manager.canReply(sessionID)) return undefined
347
- logger.warn(`${targetLabel(target)} 本轮还没有回复权限,拒绝发送`, traceMeta(sessionID))
348
- return `error: 本轮还没有回复权限。要回复用户,先调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;拿到权限后才能调用 qq_send_message。`
361
+ logger.warn(`${targetLabel(target)} 本轮还没有说明回复理由,拒绝发送`, traceMeta(sessionID))
362
+ return `error: 本轮还没有说明回复理由。要回复用户,先调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;说明之后才能调用 qq_send_message。`
349
363
  }
350
364
 
351
365
  // 同一次工具调用拆出的多段共用一个操作 id:段与段之间不再额外等间隔。
@@ -527,7 +541,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
527
541
  }
528
542
  }
529
543
 
530
- return await ctx.tool.transform((editor) => {
544
+ const result = await ctx.tool.transform((editor) => {
531
545
  editor.namespace({
532
546
  name: TOOL_NAMESPACE,
533
547
  description:
@@ -542,7 +556,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
542
556
  editor.add({
543
557
  name: "request_reply",
544
558
  description:
545
- "申请本轮的回复权限。群里默认没有发送权限:要回复用户,先调用这个工具并说明为什么要回复,拿到权限后才能调用 qq_send_message;权限只在本轮有效,轮次结束就收回。私聊默认就有权限,不用申请。",
559
+ "说明本轮为什么要回复。群里按约定不主动发言:要回复用户,先调用这个工具并说明为什么要回复,说明之后才能调用 qq_send_message;这个约定只在本轮有效,轮次结束就作废。私聊默认直接回复,不用说明。",
546
560
  input: {
547
561
  type: "object",
548
562
  properties: {
@@ -563,13 +577,13 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
563
577
  if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
564
578
  const granted = manager.requestReply(context.sessionID, reason)
565
579
  if (!granted.granted) {
566
- return text("error: 当前没有进行中的 QQ 消息轮次,拿不到回复权限")
580
+ return text("error: 当前没有进行中的 QQ 消息轮次,说不了回复理由")
567
581
  }
568
582
  if (target.kind === "private") {
569
- return text("私聊默认就有回复权限,直接调用 qq_send_message 即可。")
583
+ return text("私聊默认就直接回复,不用说明理由。")
570
584
  }
571
585
  return text(
572
- `已获得本轮的回复权限(理由:${reason})。现在可以调用 qq_send_message 回复;权限只在本轮有效。`,
586
+ `已按约定说明本轮回复理由(理由:${reason})。现在可以调用 qq_send_message 回复;这个约定只在本轮有效。`,
573
587
  )
574
588
  },
575
589
  })
@@ -671,7 +685,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
671
685
  editor.add({
672
686
  name: "send_image",
673
687
  description:
674
- "向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64:// 形式的数据。本地路径只能取自机器人工作目录、媒体目录和配置放开的目录;http(s) 地址只允许公网地址。",
688
+ "向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64:// 形式的数据。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
675
689
  input: {
676
690
  type: "object",
677
691
  properties: {
@@ -694,10 +708,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
694
708
  if (tooLarge) return text(tooLarge)
695
709
  if (!isInlineData(file)) guardOutbound(target, file)
696
710
  // 路径白名单在这里就判定:不过就不占发送额度。内联数据不涉及路径与网络。
697
- const plan = isInlineData(file) ? undefined : await outbound.check(file)
711
+ const mediaCheck = mediaFor(context.sessionID)
712
+ const plan = isInlineData(file) ? undefined : await mediaCheck.check(file)
698
713
  const verdict = await permit(target, nextOperation())
699
714
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
700
- const media = plan ? outbound.materialize(plan) : file
715
+ const media = plan ? mediaCheck.materialize(plan) : file
701
716
  const response = await send(target, [{ type: "image", data: { file: media } }])
702
717
  trackSent(target, response)
703
718
  manager.markMessageSent(context.sessionID)
@@ -714,7 +729,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
714
729
  additionalProperties: false,
715
730
  },
716
731
  options: { namespace: TOOL_NAMESPACE, codemode: false },
717
- execute: async () => {
732
+ execute: async (_raw, context) => {
733
+ const prepared = prepareQuery(context.sessionID)
734
+ if (prepared.error) return prepared.error
718
735
  const faces = await favorites.list()
719
736
  const rows = await favoriteIndex.sync(faces)
720
737
  return text(formatFavoriteList(rows))
@@ -773,7 +790,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
773
790
  editor.add({
774
791
  name: "send_record",
775
792
  description:
776
- "向当前 QQ 群聊或私聊发送一条语音。file 可以是本地路径或 http(s) 音频地址。本地路径只能取自机器人工作目录、媒体目录和配置放开的目录;http(s) 地址只允许公网地址。",
793
+ "向当前 QQ 群聊或私聊发送一条语音。file 可以是本地路径或 http(s) 音频地址。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
777
794
  input: {
778
795
  type: "object",
779
796
  properties: {
@@ -793,10 +810,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
793
810
  const tooLarge = checkInlineSize(input.file, "语音")
794
811
  if (tooLarge) return text(tooLarge)
795
812
  if (!isInlineData(input.file)) guardOutbound(target, input.file)
796
- const plan = isInlineData(input.file) ? undefined : await outbound.check(input.file)
813
+ const mediaCheck = mediaFor(context.sessionID)
814
+ const plan = isInlineData(input.file) ? undefined : await mediaCheck.check(input.file)
797
815
  const verdict = await permit(target, nextOperation())
798
816
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
799
- const media = plan ? outbound.materialize(plan) : input.file
817
+ const media = plan ? mediaCheck.materialize(plan) : input.file
800
818
  const response = await send(target, [{ type: "record", data: { file: media } }])
801
819
  trackSent(target, response)
802
820
  manager.markMessageSent(context.sessionID)
@@ -807,7 +825,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
807
825
  editor.add({
808
826
  name: "send_forward",
809
827
  description:
810
- "向当前 QQ 群聊或私聊发送一条合并转发消息。nodes 为节点列表,每个节点包含 user_id、nickname 和纯文本 content。",
828
+ "向当前 QQ 群聊或私聊发送一条合并转发消息。nodes 为节点列表,每个节点只包含纯文本 content;发送者统一显示为机器人自己。",
811
829
  input: {
812
830
  type: "object",
813
831
  properties: {
@@ -817,8 +835,6 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
817
835
  items: {
818
836
  type: "object",
819
837
  properties: {
820
- user_id: { type: "string", description: "发送者 QQ 号" },
821
- nickname: { type: "string", description: "发送者昵称" },
822
838
  content: { type: "string", description: "节点文本内容" },
823
839
  },
824
840
  required: ["content"],
@@ -837,23 +853,19 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
837
853
  const target = prepared.target
838
854
  const denied = checkReplyPermission(context.sessionID, target)
839
855
  if (denied) return text(denied)
856
+ const identity = await botIdentity()
840
857
  const nodes: {
841
858
  user_id: number
842
859
  nickname: string
843
860
  content: { type: string; data: { text: string } }[]
844
861
  }[] = []
845
862
  for (const node of input.nodes ?? []) {
846
- const userId = node.user_id === undefined ? 0 : Number(node.user_id)
847
- if (!Number.isInteger(userId) || userId < 0) {
848
- return text(`error: 非法 user_id:${String(node.user_id)}`)
849
- }
850
863
  const body = toPlainText(node.content ?? "").trim()
851
- const nickname = node.nickname?.trim() || "未知用户"
852
- // 昵称同样发给对方,不能成为凭证外发的盲区。
853
- guardOutbound(target, `${nickname}\n${body}`)
864
+ // 合并转发里每段都要扫:昵称由插件固定,模型只能控制正文。
865
+ guardOutbound(target, body)
854
866
  nodes.push({
855
- user_id: userId,
856
- nickname,
867
+ user_id: identity.userId,
868
+ nickname: identity.nickname,
857
869
  content: [{ type: "text", data: { text: body } }],
858
870
  })
859
871
  }
@@ -913,6 +925,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
913
925
  const prepared = await prepareSend(context.sessionID)
914
926
  if (prepared.error) return prepared.error
915
927
  const target = prepared.target
928
+ const denied = checkReplyPermission(context.sessionID, target)
929
+ if (denied) return text(denied)
916
930
  if (input.message_id === undefined) return text("error: 缺少 message_id")
917
931
  if (!manager.isOutgoing(target, String(input.message_id))) {
918
932
  return text("error: 只能撤回机器人自己发送过的消息")
@@ -983,7 +997,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
983
997
  additionalProperties: false,
984
998
  },
985
999
  options: { namespace: TOOL_NAMESPACE, codemode: false },
986
- execute: async () => {
1000
+ execute: async (_raw, context) => {
1001
+ const prepared = prepareQuery(context.sessionID)
1002
+ if (prepared.error) return prepared.error
987
1003
  const info = await client.api.getLoginInfo()
988
1004
  return text(JSON.stringify(info))
989
1005
  },
@@ -992,8 +1008,25 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
992
1008
  // 日记工具依赖日记存储;没配存储时不注册,免得模型调到一个必然失败的工具。
993
1009
  const diaryStore = diary
994
1010
  if (diaryStore) {
995
- /** 日记工具的目标:必须是当前会话绑定且放行的那个聊天。 */
996
- const diaryTarget = (sessionID: string): ChatTarget | undefined => requireTarget(sessionID)
1011
+ /**
1012
+ * 日记工具的目标:必须是 owner 自己的私聊,且在当前放行名单里。
1013
+ *
1014
+ * owner 与 admin 共用 admin 配置档,只在配置里收权限不够,
1015
+ * 这里按会话实际角色再判一次。
1016
+ */
1017
+ const diaryTarget = (sessionID: string): ChatTarget | undefined => {
1018
+ const target = requireTarget(sessionID)
1019
+ if (!target) return undefined
1020
+ if (!isDiaryScopeChat(config, target)) {
1021
+ logger.warn(`${targetLabel(target)} 不是日记作用域,拒绝日记工具调用`)
1022
+ return undefined
1023
+ }
1024
+ if (manager.currentRole(sessionID) !== "owner") {
1025
+ logger.warn(`${targetLabel(target)} 不是 owner,拒绝日记工具调用`)
1026
+ return undefined
1027
+ }
1028
+ return target
1029
+ }
997
1030
 
998
1031
  /** 找不到日记时把可用的日期一起回给模型,省得它来回试。 */
999
1032
  const diaryMissing = async (chat: string, date: string): Promise<string> => {
@@ -1020,7 +1053,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1020
1053
  execute: async (raw, context) => {
1021
1054
  const input = (raw ?? {}) as DiaryWriteInput
1022
1055
  const target = diaryTarget(context.sessionID)
1023
- if (!target) return text("error: 当前会话没有绑定的聊天,无法读写日记")
1056
+ if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
1024
1057
  const content = (input.content ?? "").trim()
1025
1058
  if (!content) return text("error: 缺少 content")
1026
1059
  const date = input.date?.trim() || dateKey()
@@ -1049,7 +1082,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1049
1082
  execute: async (raw, context) => {
1050
1083
  const input = (raw ?? {}) as DiaryReadInput
1051
1084
  const target = diaryTarget(context.sessionID)
1052
- if (!target) return text("error: 当前会话没有绑定的聊天,无法读写日记")
1085
+ if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
1053
1086
  const chat = targetKey(target)
1054
1087
  const date = input.date?.trim()
1055
1088
  if (!date) {
@@ -1079,7 +1112,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1079
1112
  execute: async (raw, context) => {
1080
1113
  const input = (raw ?? {}) as DiaryListInput
1081
1114
  const target = diaryTarget(context.sessionID)
1082
- if (!target) return text("error: 当前会话没有绑定的聊天,无法读写日记")
1115
+ if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
1083
1116
  const days = Number.isInteger(input.days) && (input.days ?? 0) > 0 ? (input.days ?? 7) : 7
1084
1117
  const entries = await diaryStore.list(targetKey(target), days)
1085
1118
  if (entries.length === 0) return text("这个聊天还没有日记。")
@@ -1091,7 +1124,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1091
1124
  editor.add({
1092
1125
  name: "send_file",
1093
1126
  description:
1094
- "向当前 QQ 群聊或私聊发送一个本地文件。file 是文件路径,只能是机器人允许发送的目录里的普通文件;name 是对方看到的文件名,省略时用原文件名。",
1127
+ "向当前 QQ 群聊或私聊发送一个本地文件。file 是文件路径,只能是机器人允许发送的目录里的普通文件;owner/admin 可用工作目录、媒体目录和配置放开的目录,普通成员只能用媒体目录;name 是对方看到的文件名,省略时用原文件名。",
1095
1128
  input: {
1096
1129
  type: "object",
1097
1130
  properties: {
@@ -1113,7 +1146,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1113
1146
  if (!file) return text("error: 缺少 file")
1114
1147
  let plan
1115
1148
  try {
1116
- plan = await outbound.check(file)
1149
+ plan = await mediaFor(context.sessionID).check(file)
1117
1150
  } catch (error) {
1118
1151
  return text(`error: ${error instanceof Error ? error.message : String(error)}`)
1119
1152
  }
@@ -1131,4 +1164,23 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1131
1164
  },
1132
1165
  })
1133
1166
  })
1167
+
1168
+ // 注册完成后与清单核对一次:新增工具忘了登记,模型就会看到不存在的名字。
1169
+ try {
1170
+ const expected = new Set<string>(QQ_TOOL_NAMES)
1171
+ const actual = (await ctx.tool.list())
1172
+ .map((tool) => tool.id)
1173
+ .filter((id) => id.startsWith("qq_"))
1174
+ // 清单里一个 qq_ 工具都看不到,说明这次 transform 还没落到注册表上:这时候比不出结果。
1175
+ if (actual.length === 0) return result
1176
+ const missing = [...expected].filter((id) => !actual.includes(id))
1177
+ const extra = actual.filter((id) => !expected.has(id))
1178
+ if (missing.length > 0 || extra.length > 0) {
1179
+ logger.warn("QQ 工具清单与实际注册不一致", { missing, extra })
1180
+ }
1181
+ } catch (error) {
1182
+ logger.warn("QQ 工具清单校验失败", error)
1183
+ }
1184
+
1185
+ return result
1134
1186
  }
@@ -6,8 +6,8 @@ import type { SessionManager, Turn } from "../session/manager"
6
6
  export const DUPLICATE_SEND_REFUSAL =
7
7
  "禁止连续调用发送工具:上一步已经发送过消息,再发可能重复。请先调用其它工具(例如查看消息或整理内容),或直接结束本轮。"
8
8
 
9
- /** 匹配 qq_send_message 等发送工具;钩子里可能带或不带命名空间。 */
10
- const SEND_TOOL = /^(?:qq_)?send[_-]/
9
+ /** 匹配 qq_send_message 与 qq_delete_message 等出站动作;钩子里可能带或不带命名空间。 */
10
+ const SEND_TOOL = /^(?:qq_)?(?:send[_-]|delete_message$)/
11
11
 
12
12
  interface LastCall {
13
13
  /** 所属轮次;轮次变化时重新计数,避免上一轮的最后一次发送影响下一轮。 */
@@ -59,7 +59,7 @@ export async function registerTuiCommands(
59
59
  }
60
60
  const args = splitArgs(input.prompt.text ?? "", name)
61
61
  const body = await command.run(
62
- { config, manager, policy, overrides, target, toolNames, commands },
62
+ { config, manager, policy, overrides, target, source: "tui", toolNames, commands },
63
63
  args,
64
64
  )
65
65
  if (body !== undefined) await send(target, body)