@cmach_socket/opencode-qq-bot 0.6.8 → 0.8.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/src/tools/qq.ts CHANGED
@@ -1,8 +1,12 @@
1
+ import { basename } from "node:path"
1
2
  import type { Plugin } from "@opencode/plugin"
2
3
  import { isTargetAllowed } from "../access"
3
4
  import { delay } from "../async"
4
5
  import { type ChatTarget, targetKey, targetLabel } from "../chat"
5
6
  import type { QQBotConfig } from "../config"
7
+ import { dateKey, isDateKey } from "../diary/format"
8
+ import { isDiaryScopeChat } from "../diary/scope"
9
+ import type { DiaryStore } from "../diary/store"
6
10
  import {
7
11
  CUSTOM_FACE_SUB_TYPE,
8
12
  type FavoriteStore,
@@ -12,6 +16,7 @@ import {
12
16
  import type { FavoriteIndex } from "../emoji/favorite-index"
13
17
  import type { Logger } from "../logger"
14
18
  import type { OutboundMedia } from "../media-path"
19
+ import { neutralizeStructureTags, sanitizeUntrustedText } from "../model-view"
15
20
  import type { QQClient } from "../naplink/client"
16
21
  import { splitGraphemes, splitMessage, segmentDelayMs, toPlainText } from "../outbound"
17
22
  import type { RateLimitVerdict, SendRateLimiter } from "../rate-limit"
@@ -19,6 +24,7 @@ import { modelSendScope, pluginSendScope } from "../rate-limit"
19
24
  import type { SensitiveChecker } from "../sensitive"
20
25
  import type { SessionManager } from "../session/manager"
21
26
  import type { Tracer } from "../trace"
27
+ import { softTruncate } from "../text"
22
28
 
23
29
  /** 工具命名空间,最终工具名为 qq_send_message 等。 */
24
30
  export const TOOL_NAMESPACE = "qq"
@@ -50,6 +56,10 @@ export const QQ_TOOL_NAMES = [
50
56
  "qq_get_group_member_info",
51
57
  "qq_fetch_ptt_text",
52
58
  "qq_get_login_info",
59
+ "qq_send_file",
60
+ "qq_diary_write",
61
+ "qq_diary_read",
62
+ "qq_diary_list",
53
63
  ] as const
54
64
 
55
65
  export interface ToolDeps {
@@ -68,6 +78,15 @@ export interface ToolDeps {
68
78
  sensitive: SensitiveChecker
69
79
  /** 出站媒体的路径与地址把关。 */
70
80
  outbound: OutboundMedia
81
+ /**
82
+ * 普通成员可用的出站媒体把关,只放开媒体目录。
83
+ *
84
+ * owner/admin 用 `outbound`(工作区 + 媒体目录 + 配置的额外目录),
85
+ * 其他人只能用这个收窄过的实例,避免读到工作区里的源码与配置。
86
+ */
87
+ outboundMember?: OutboundMedia
88
+ /** 日记读写,供 qq_diary_* 使用;不传就不注册日记工具。 */
89
+ diary?: DiaryStore
71
90
  /** 调用链追踪器;不传就不记追踪。 */
72
91
  tracer?: Tracer
73
92
  /**
@@ -90,8 +109,6 @@ interface MediaInput {
90
109
  }
91
110
 
92
111
  interface ForwardNodeInput {
93
- user_id?: number | string
94
- nickname?: string
95
112
  content?: string
96
113
  }
97
114
 
@@ -111,6 +128,25 @@ interface MessageIdInput {
111
128
  message_id?: number | string
112
129
  }
113
130
 
131
+ interface DiaryWriteInput {
132
+ content?: string
133
+ date?: string
134
+ title?: string
135
+ }
136
+
137
+ interface DiaryReadInput {
138
+ date?: string
139
+ }
140
+
141
+ interface DiaryListInput {
142
+ days?: number
143
+ }
144
+
145
+ interface FileInput {
146
+ file?: string
147
+ name?: string
148
+ }
149
+
114
150
  /** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
115
151
  const FORWARD_NODE_CHARS = 3000
116
152
 
@@ -123,6 +159,30 @@ function text(value: string, metadata?: Record<string, unknown>) {
123
159
  /** 工具返回值:content 是给模型看的文本,metadata 带失败标记。 */
124
160
  type ToolResult = ReturnType<typeof text>
125
161
 
162
+ /** 日记正文进模型上下文的固定上限,超出部分截断。 */
163
+ const DIARY_READ_MAX_CHARS = 4000
164
+
165
+ /**
166
+ * 净化日记正文。
167
+ *
168
+ * 逐行净化再整体中和结构标签:日记是多段文本,
169
+ * 整体净化会把换行压成空格,段落就没了。
170
+ */
171
+ function sanitizeDiaryBody(body: string): string {
172
+ const lines = String(body ?? "")
173
+ .replace(/\r\n/g, "\n")
174
+ .split("\n")
175
+ .map((line) => sanitizeUntrustedText(line))
176
+ return neutralizeStructureTags(lines.join("\n"))
177
+ }
178
+
179
+ /** 组装给模型看的日记正文:标题加正文,超长时按自然边界截断。 */
180
+ function formatDiaryBody(date: string, title: string, body: string): string {
181
+ const plain = sanitizeDiaryBody(body)
182
+ const clipped = softTruncate(plain, DIARY_READ_MAX_CHARS)
183
+ return [`${date} 的日记:${sanitizeUntrustedText(title)}`, "", clipped].join("\n")
184
+ }
185
+
126
186
  /** 按目标类型把消息投递出去:群聊与私聊走不同的 API。 */
127
187
  function sendPayload(client: QQClient, target: ChatTarget, payload: string | unknown[]) {
128
188
  return target.kind === "group"
@@ -199,6 +259,34 @@ export function createPlainSender(
199
259
  }
200
260
  }
201
261
 
262
+ /**
263
+ * 向一个目标发送本地文件。
264
+ *
265
+ * 路径先过出站白名单:只允许白名单目录里的普通文件,软链接指向别处也拒绝。
266
+ * 文件内容不扫描,只看显示名与路径,避免把凭证文件指出去。
267
+ */
268
+ export async function sendFileMessage(
269
+ client: QQClient,
270
+ target: ChatTarget,
271
+ file: string,
272
+ options: {
273
+ /** 对方看到的文件名;不传时用真实文件名。 */
274
+ name?: string
275
+ limiter: SendRateLimiter
276
+ outbound: OutboundMedia
277
+ sensitive: SensitiveChecker
278
+ },
279
+ ): Promise<void> {
280
+ const plan = await options.outbound.check(file)
281
+ if (plan.kind !== "local") throw new Error("只能发送本地文件")
282
+ const path = plan.path
283
+ const name = options.name?.trim() || basename(path)
284
+ const verdict = options.sensitive.check(`${name}\n${path}`)
285
+ if (!verdict.allowed) throw new Error(verdict.reason)
286
+ await options.limiter.pace(pluginSendScope(target), nextPlainOperation())
287
+ await sendPayload(client, target, [{ type: "file", data: { file: path, name } }])
288
+ }
289
+
202
290
  /**
203
291
  * 注册 QQ 命名空间下的工具。
204
292
  *
@@ -217,9 +305,17 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
217
305
  limiter,
218
306
  sensitive,
219
307
  outbound,
308
+ outboundMember,
309
+ diary,
220
310
  tracer,
221
311
  } = deps
222
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
+
223
319
  const requireTarget = (sessionID: string): ChatTarget | undefined => {
224
320
  const target = manager.targetForSession(sessionID)
225
321
  if (!target) return undefined
@@ -262,8 +358,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
262
358
  if (!config.reply.requirePermission) return undefined
263
359
  if (target.kind === "private") return undefined
264
360
  if (manager.canReply(sessionID)) return undefined
265
- logger.warn(`${targetLabel(target)} 本轮还没有回复权限,拒绝发送`, traceMeta(sessionID))
266
- 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。`
267
363
  }
268
364
 
269
365
  // 同一次工具调用拆出的多段共用一个操作 id:段与段之间不再额外等间隔。
@@ -445,7 +541,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
445
541
  }
446
542
  }
447
543
 
448
- return await ctx.tool.transform((editor) => {
544
+ const result = await ctx.tool.transform((editor) => {
449
545
  editor.namespace({
450
546
  name: TOOL_NAMESPACE,
451
547
  description:
@@ -460,7 +556,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
460
556
  editor.add({
461
557
  name: "request_reply",
462
558
  description:
463
- "申请本轮的回复权限。群里默认没有发送权限:要回复用户,先调用这个工具并说明为什么要回复,拿到权限后才能调用 qq_send_message;权限只在本轮有效,轮次结束就收回。私聊默认就有权限,不用申请。",
559
+ "说明本轮为什么要回复。群里按约定不主动发言:要回复用户,先调用这个工具并说明为什么要回复,说明之后才能调用 qq_send_message;这个约定只在本轮有效,轮次结束就作废。私聊默认直接回复,不用说明。",
464
560
  input: {
465
561
  type: "object",
466
562
  properties: {
@@ -481,13 +577,13 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
481
577
  if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
482
578
  const granted = manager.requestReply(context.sessionID, reason)
483
579
  if (!granted.granted) {
484
- return text("error: 当前没有进行中的 QQ 消息轮次,拿不到回复权限")
580
+ return text("error: 当前没有进行中的 QQ 消息轮次,说不了回复理由")
485
581
  }
486
582
  if (target.kind === "private") {
487
- return text("私聊默认就有回复权限,直接调用 qq_send_message 即可。")
583
+ return text("私聊默认就直接回复,不用说明理由。")
488
584
  }
489
585
  return text(
490
- `已获得本轮的回复权限(理由:${reason})。现在可以调用 qq_send_message 回复;权限只在本轮有效。`,
586
+ `已按约定说明本轮回复理由(理由:${reason})。现在可以调用 qq_send_message 回复;这个约定只在本轮有效。`,
491
587
  )
492
588
  },
493
589
  })
@@ -589,7 +685,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
589
685
  editor.add({
590
686
  name: "send_image",
591
687
  description:
592
- "向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64:// 形式的数据。本地路径只能取自机器人工作目录、媒体目录和配置放开的目录;http(s) 地址只允许公网地址。",
688
+ "向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64:// 形式的数据。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
593
689
  input: {
594
690
  type: "object",
595
691
  properties: {
@@ -612,10 +708,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
612
708
  if (tooLarge) return text(tooLarge)
613
709
  if (!isInlineData(file)) guardOutbound(target, file)
614
710
  // 路径白名单在这里就判定:不过就不占发送额度。内联数据不涉及路径与网络。
615
- 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)
616
713
  const verdict = await permit(target, nextOperation())
617
714
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
618
- const media = plan ? outbound.materialize(plan) : file
715
+ const media = plan ? mediaCheck.materialize(plan) : file
619
716
  const response = await send(target, [{ type: "image", data: { file: media } }])
620
717
  trackSent(target, response)
621
718
  manager.markMessageSent(context.sessionID)
@@ -632,7 +729,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
632
729
  additionalProperties: false,
633
730
  },
634
731
  options: { namespace: TOOL_NAMESPACE, codemode: false },
635
- execute: async () => {
732
+ execute: async (_raw, context) => {
733
+ const prepared = prepareQuery(context.sessionID)
734
+ if (prepared.error) return prepared.error
636
735
  const faces = await favorites.list()
637
736
  const rows = await favoriteIndex.sync(faces)
638
737
  return text(formatFavoriteList(rows))
@@ -691,7 +790,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
691
790
  editor.add({
692
791
  name: "send_record",
693
792
  description:
694
- "向当前 QQ 群聊或私聊发送一条语音。file 可以是本地路径或 http(s) 音频地址。本地路径只能取自机器人工作目录、媒体目录和配置放开的目录;http(s) 地址只允许公网地址。",
793
+ "向当前 QQ 群聊或私聊发送一条语音。file 可以是本地路径或 http(s) 音频地址。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
695
794
  input: {
696
795
  type: "object",
697
796
  properties: {
@@ -711,10 +810,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
711
810
  const tooLarge = checkInlineSize(input.file, "语音")
712
811
  if (tooLarge) return text(tooLarge)
713
812
  if (!isInlineData(input.file)) guardOutbound(target, input.file)
714
- 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)
715
815
  const verdict = await permit(target, nextOperation())
716
816
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
717
- const media = plan ? outbound.materialize(plan) : input.file
817
+ const media = plan ? mediaCheck.materialize(plan) : input.file
718
818
  const response = await send(target, [{ type: "record", data: { file: media } }])
719
819
  trackSent(target, response)
720
820
  manager.markMessageSent(context.sessionID)
@@ -725,7 +825,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
725
825
  editor.add({
726
826
  name: "send_forward",
727
827
  description:
728
- "向当前 QQ 群聊或私聊发送一条合并转发消息。nodes 为节点列表,每个节点包含 user_id、nickname 和纯文本 content。",
828
+ "向当前 QQ 群聊或私聊发送一条合并转发消息。nodes 为节点列表,每个节点只包含纯文本 content;发送者统一显示为机器人自己。",
729
829
  input: {
730
830
  type: "object",
731
831
  properties: {
@@ -735,8 +835,6 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
735
835
  items: {
736
836
  type: "object",
737
837
  properties: {
738
- user_id: { type: "string", description: "发送者 QQ 号" },
739
- nickname: { type: "string", description: "发送者昵称" },
740
838
  content: { type: "string", description: "节点文本内容" },
741
839
  },
742
840
  required: ["content"],
@@ -755,23 +853,19 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
755
853
  const target = prepared.target
756
854
  const denied = checkReplyPermission(context.sessionID, target)
757
855
  if (denied) return text(denied)
856
+ const identity = await botIdentity()
758
857
  const nodes: {
759
858
  user_id: number
760
859
  nickname: string
761
860
  content: { type: string; data: { text: string } }[]
762
861
  }[] = []
763
862
  for (const node of input.nodes ?? []) {
764
- const userId = node.user_id === undefined ? 0 : Number(node.user_id)
765
- if (!Number.isInteger(userId) || userId < 0) {
766
- return text(`error: 非法 user_id:${String(node.user_id)}`)
767
- }
768
863
  const body = toPlainText(node.content ?? "").trim()
769
- const nickname = node.nickname?.trim() || "未知用户"
770
- // 昵称同样发给对方,不能成为凭证外发的盲区。
771
- guardOutbound(target, `${nickname}\n${body}`)
864
+ // 合并转发里每段都要扫:昵称由插件固定,模型只能控制正文。
865
+ guardOutbound(target, body)
772
866
  nodes.push({
773
- user_id: userId,
774
- nickname,
867
+ user_id: identity.userId,
868
+ nickname: identity.nickname,
775
869
  content: [{ type: "text", data: { text: body } }],
776
870
  })
777
871
  }
@@ -831,6 +925,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
831
925
  const prepared = await prepareSend(context.sessionID)
832
926
  if (prepared.error) return prepared.error
833
927
  const target = prepared.target
928
+ const denied = checkReplyPermission(context.sessionID, target)
929
+ if (denied) return text(denied)
834
930
  if (input.message_id === undefined) return text("error: 缺少 message_id")
835
931
  if (!manager.isOutgoing(target, String(input.message_id))) {
836
932
  return text("error: 只能撤回机器人自己发送过的消息")
@@ -901,10 +997,190 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
901
997
  additionalProperties: false,
902
998
  },
903
999
  options: { namespace: TOOL_NAMESPACE, codemode: false },
904
- execute: async () => {
1000
+ execute: async (_raw, context) => {
1001
+ const prepared = prepareQuery(context.sessionID)
1002
+ if (prepared.error) return prepared.error
905
1003
  const info = await client.api.getLoginInfo()
906
1004
  return text(JSON.stringify(info))
907
1005
  },
908
1006
  })
1007
+
1008
+ // 日记工具依赖日记存储;没配存储时不注册,免得模型调到一个必然失败的工具。
1009
+ const diaryStore = diary
1010
+ if (diaryStore) {
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
+ }
1030
+
1031
+ /** 找不到日记时把可用的日期一起回给模型,省得它来回试。 */
1032
+ const diaryMissing = async (chat: string, date: string): Promise<string> => {
1033
+ const available = (await diaryStore.list(chat, 10)).map((item) => item.date)
1034
+ const hint = available.length > 0 ? `(可用的日期:${available.join("、")})` : ""
1035
+ return `error: 没有找到 ${date} 的日记${hint}`
1036
+ }
1037
+
1038
+ editor.add({
1039
+ name: "diary_write",
1040
+ description:
1041
+ "给当前 QQ 群聊或私聊写一篇日记。同一个聊天同一天只有一篇日记,重复写会覆盖当天那一篇。content 是日记正文;date 是日期,格式 YYYY-MM-DD,省略表示今天;title 是标题,省略时用日期做标题。",
1042
+ input: {
1043
+ type: "object",
1044
+ properties: {
1045
+ content: { type: "string", description: "日记正文(必填)" },
1046
+ date: { type: "string", description: "日期,格式 YYYY-MM-DD;省略表示今天" },
1047
+ title: { type: "string", description: "日记标题;省略时用日期做标题" },
1048
+ },
1049
+ required: ["content"],
1050
+ additionalProperties: false,
1051
+ },
1052
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1053
+ execute: async (raw, context) => {
1054
+ const input = (raw ?? {}) as DiaryWriteInput
1055
+ const target = diaryTarget(context.sessionID)
1056
+ if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
1057
+ const content = (input.content ?? "").trim()
1058
+ if (!content) return text("error: 缺少 content")
1059
+ const date = input.date?.trim() || dateKey()
1060
+ if (!isDateKey(date)) return text(`error: 日期格式不对:${date},请用 YYYY-MM-DD`)
1061
+ const entry = await diaryStore.write(targetKey(target), date, {
1062
+ title: input.title?.trim() ?? "",
1063
+ body: content,
1064
+ source: "model",
1065
+ })
1066
+ return text(`已写入 ${date} 的日记:${entry.title}`)
1067
+ },
1068
+ })
1069
+
1070
+ editor.add({
1071
+ name: "diary_read",
1072
+ description:
1073
+ "读取当前 QQ 群聊或私聊的日记正文。date 是日期,格式 YYYY-MM-DD;省略时返回最近一篇。返回的是日记文本,不是文件列表。",
1074
+ input: {
1075
+ type: "object",
1076
+ properties: {
1077
+ date: { type: "string", description: "日期,格式 YYYY-MM-DD;省略表示最近一篇" },
1078
+ },
1079
+ additionalProperties: false,
1080
+ },
1081
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1082
+ execute: async (raw, context) => {
1083
+ const input = (raw ?? {}) as DiaryReadInput
1084
+ const target = diaryTarget(context.sessionID)
1085
+ if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
1086
+ const chat = targetKey(target)
1087
+ const date = input.date?.trim()
1088
+ if (!date) {
1089
+ const latest = await diaryStore.latest(chat)
1090
+ if (!latest) return text("error: 这个聊天还没有日记")
1091
+ return text(formatDiaryBody(latest.date, latest.title, latest.body))
1092
+ }
1093
+ if (!isDateKey(date)) return text(`error: 日期格式不对:${date},请用 YYYY-MM-DD`)
1094
+ const entry = await diaryStore.read(chat, date)
1095
+ if (!entry) return text(await diaryMissing(chat, date))
1096
+ return text(formatDiaryBody(entry.date, entry.title, entry.body))
1097
+ },
1098
+ })
1099
+
1100
+ editor.add({
1101
+ name: "diary_list",
1102
+ description:
1103
+ "列出当前 QQ 群聊或私聊最近的日记,只返回日期和标题。days 是看几篇,默认 7 篇。",
1104
+ input: {
1105
+ type: "object",
1106
+ properties: {
1107
+ days: { type: "number", description: "看最近几篇,默认 7" },
1108
+ },
1109
+ additionalProperties: false,
1110
+ },
1111
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1112
+ execute: async (raw, context) => {
1113
+ const input = (raw ?? {}) as DiaryListInput
1114
+ const target = diaryTarget(context.sessionID)
1115
+ if (!target) return text("error: 日记只在 owner 自己的私聊里可用")
1116
+ const days = Number.isInteger(input.days) && (input.days ?? 0) > 0 ? (input.days ?? 7) : 7
1117
+ const entries = await diaryStore.list(targetKey(target), days)
1118
+ if (entries.length === 0) return text("这个聊天还没有日记。")
1119
+ return text(entries.map((entry) => `${entry.date} ${entry.title}`).join("\n"))
1120
+ },
1121
+ })
1122
+ }
1123
+
1124
+ editor.add({
1125
+ name: "send_file",
1126
+ description:
1127
+ "向当前 QQ 群聊或私聊发送一个本地文件。file 是文件路径,只能是机器人允许发送的目录里的普通文件;owner/admin 可用工作目录、媒体目录和配置放开的目录,普通成员只能用媒体目录;name 是对方看到的文件名,省略时用原文件名。",
1128
+ input: {
1129
+ type: "object",
1130
+ properties: {
1131
+ file: { type: "string", description: "本地文件路径(必填)" },
1132
+ name: { type: "string", description: "对方看到的文件名;省略时用原文件名" },
1133
+ },
1134
+ required: ["file"],
1135
+ additionalProperties: false,
1136
+ },
1137
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1138
+ execute: async (raw, context) => {
1139
+ const input = (raw ?? {}) as FileInput
1140
+ const prepared = await prepareSend(context.sessionID)
1141
+ if (prepared.error) return prepared.error
1142
+ const target = prepared.target
1143
+ const denied = checkReplyPermission(context.sessionID, target)
1144
+ if (denied) return text(denied)
1145
+ const file = input.file?.trim()
1146
+ if (!file) return text("error: 缺少 file")
1147
+ let plan
1148
+ try {
1149
+ plan = await mediaFor(context.sessionID).check(file)
1150
+ } catch (error) {
1151
+ return text(`error: ${error instanceof Error ? error.message : String(error)}`)
1152
+ }
1153
+ if (plan.kind !== "local") return text("error: 只能发送本地文件")
1154
+ const path = plan.path
1155
+ const name = input.name?.trim() || basename(path)
1156
+ // 文件内容没法扫描,路径与显示名同样过一遍出站检查。
1157
+ guardOutbound(target, `${name}\n${path}`)
1158
+ const verdict = await permit(target, nextOperation())
1159
+ if (!verdict.allowed) return refuse(context.sessionID, verdict)
1160
+ const response = await send(target, [{ type: "file", data: { file: path, name } }])
1161
+ trackSent(target, response)
1162
+ manager.markMessageSent(context.sessionID)
1163
+ return text("你已成功发送文件,可以选择结束对话")
1164
+ },
1165
+ })
909
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
910
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)
@@ -3,11 +3,15 @@
3
3
  "profiles": {
4
4
  "chat": {
5
5
  "allow": ["websearch", "webfetch", "qq_*"],
6
- "deny": []
6
+ "deny": ["qq_diary_*", "qq_send_file"]
7
7
  },
8
8
  "readonly": {
9
9
  "allow": ["read", "glob", "grep", "qq_*"],
10
- "deny": []
10
+ "deny": ["qq_diary_*", "qq_send_file"]
11
+ },
12
+ "proactive": {
13
+ "allow": ["websearch", "webfetch", "qq_*"],
14
+ "deny": ["qq_diary_*", "qq_send_file"]
11
15
  },
12
16
  "admin": {
13
17
  "allow": ["*"],