@cmach_socket/opencode-qq-bot 0.6.7 → 0.7.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,11 @@
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 type { DiaryStore } from "../diary/store"
6
9
  import {
7
10
  CUSTOM_FACE_SUB_TYPE,
8
11
  type FavoriteStore,
@@ -12,6 +15,7 @@ import {
12
15
  import type { FavoriteIndex } from "../emoji/favorite-index"
13
16
  import type { Logger } from "../logger"
14
17
  import type { OutboundMedia } from "../media-path"
18
+ import { neutralizeStructureTags, sanitizeUntrustedText } from "../model-view"
15
19
  import type { QQClient } from "../naplink/client"
16
20
  import { splitGraphemes, splitMessage, segmentDelayMs, toPlainText } from "../outbound"
17
21
  import type { RateLimitVerdict, SendRateLimiter } from "../rate-limit"
@@ -23,6 +27,14 @@ import type { Tracer } from "../trace"
23
27
  /** 工具命名空间,最终工具名为 qq_send_message 等。 */
24
28
  export const TOOL_NAMESPACE = "qq"
25
29
 
30
+ /**
31
+ * 申请回复权限的工具名。
32
+ *
33
+ * 群里默认没有发送权限:模型得先说明为什么要回复,拿到权限才能发送;
34
+ * 权限只在本轮有效。私聊默认开放,不需要申请。
35
+ */
36
+ export const QQ_REQUEST_REPLY_TOOL = "qq_request_reply"
37
+
26
38
  /**
27
39
  * 暴露给模型的 QQ 工具名。
28
40
  *
@@ -30,6 +42,7 @@ export const TOOL_NAMESPACE = "qq"
30
42
  * `qq_send_message` 是模型发消息的唯一入口。
31
43
  */
32
44
  export const QQ_TOOL_NAMES = [
45
+ "qq_request_reply",
33
46
  "qq_send_message",
34
47
  "qq_send_image",
35
48
  "qq_send_sticker",
@@ -41,6 +54,10 @@ export const QQ_TOOL_NAMES = [
41
54
  "qq_get_group_member_info",
42
55
  "qq_fetch_ptt_text",
43
56
  "qq_get_login_info",
57
+ "qq_send_file",
58
+ "qq_diary_write",
59
+ "qq_diary_read",
60
+ "qq_diary_list",
44
61
  ] as const
45
62
 
46
63
  export interface ToolDeps {
@@ -59,6 +76,8 @@ export interface ToolDeps {
59
76
  sensitive: SensitiveChecker
60
77
  /** 出站媒体的路径与地址把关。 */
61
78
  outbound: OutboundMedia
79
+ /** 日记读写,供 qq_diary_* 使用;不传就不注册日记工具。 */
80
+ diary?: DiaryStore
62
81
  /** 调用链追踪器;不传就不记追踪。 */
63
82
  tracer?: Tracer
64
83
  /**
@@ -102,6 +121,25 @@ interface MessageIdInput {
102
121
  message_id?: number | string
103
122
  }
104
123
 
124
+ interface DiaryWriteInput {
125
+ content?: string
126
+ date?: string
127
+ title?: string
128
+ }
129
+
130
+ interface DiaryReadInput {
131
+ date?: string
132
+ }
133
+
134
+ interface DiaryListInput {
135
+ days?: number
136
+ }
137
+
138
+ interface FileInput {
139
+ file?: string
140
+ name?: string
141
+ }
142
+
105
143
  /** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
106
144
  const FORWARD_NODE_CHARS = 3000
107
145
 
@@ -114,6 +152,30 @@ function text(value: string, metadata?: Record<string, unknown>) {
114
152
  /** 工具返回值:content 是给模型看的文本,metadata 带失败标记。 */
115
153
  type ToolResult = ReturnType<typeof text>
116
154
 
155
+ /** 日记正文进模型上下文的固定上限,超出部分截断。 */
156
+ const DIARY_READ_MAX_CHARS = 4000
157
+
158
+ /**
159
+ * 净化日记正文。
160
+ *
161
+ * 逐行净化再整体中和结构标签:日记是多段文本,
162
+ * 整体净化会把换行压成空格,段落就没了。
163
+ */
164
+ function sanitizeDiaryBody(body: string): string {
165
+ const lines = String(body ?? "")
166
+ .replace(/\r\n/g, "\n")
167
+ .split("\n")
168
+ .map((line) => sanitizeUntrustedText(line))
169
+ return neutralizeStructureTags(lines.join("\n"))
170
+ }
171
+
172
+ /** 组装给模型看的日记正文:标题加正文,超长截断。 */
173
+ function formatDiaryBody(date: string, title: string, body: string): string {
174
+ const plain = sanitizeDiaryBody(body)
175
+ const clipped = Array.from(plain).slice(0, DIARY_READ_MAX_CHARS).join("")
176
+ return [`${date} 的日记:${sanitizeUntrustedText(title)}`, "", clipped].join("\n")
177
+ }
178
+
117
179
  /** 按目标类型把消息投递出去:群聊与私聊走不同的 API。 */
118
180
  function sendPayload(client: QQClient, target: ChatTarget, payload: string | unknown[]) {
119
181
  return target.kind === "group"
@@ -190,6 +252,34 @@ export function createPlainSender(
190
252
  }
191
253
  }
192
254
 
255
+ /**
256
+ * 向一个目标发送本地文件。
257
+ *
258
+ * 路径先过出站白名单:只允许白名单目录里的普通文件,软链接指向别处也拒绝。
259
+ * 文件内容不扫描,只看显示名与路径,避免把凭证文件指出去。
260
+ */
261
+ export async function sendFileMessage(
262
+ client: QQClient,
263
+ target: ChatTarget,
264
+ file: string,
265
+ options: {
266
+ /** 对方看到的文件名;不传时用真实文件名。 */
267
+ name?: string
268
+ limiter: SendRateLimiter
269
+ outbound: OutboundMedia
270
+ sensitive: SensitiveChecker
271
+ },
272
+ ): Promise<void> {
273
+ const plan = await options.outbound.check(file)
274
+ if (plan.kind !== "local") throw new Error("只能发送本地文件")
275
+ const path = plan.path
276
+ const name = options.name?.trim() || basename(path)
277
+ const verdict = options.sensitive.check(`${name}\n${path}`)
278
+ if (!verdict.allowed) throw new Error(verdict.reason)
279
+ await options.limiter.pace(pluginSendScope(target), nextPlainOperation())
280
+ await sendPayload(client, target, [{ type: "file", data: { file: path, name } }])
281
+ }
282
+
193
283
  /**
194
284
  * 注册 QQ 命名空间下的工具。
195
285
  *
@@ -208,6 +298,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
208
298
  limiter,
209
299
  sensitive,
210
300
  outbound,
301
+ diary,
211
302
  tracer,
212
303
  } = deps
213
304
 
@@ -241,6 +332,22 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
241
332
  return undefined
242
333
  }
243
334
 
335
+ /**
336
+ * 群里发消息前的权限检查。
337
+ *
338
+ * 默认没有发送权限:模型先说明理由才拿得到,权限只在本轮有效。
339
+ * 私聊默认开放,不用申请;选择不回复(`reply=false`)也不需要权限。
340
+ *
341
+ * @returns 可以发送时返回 undefined,否则返回给模型的错误文案。
342
+ */
343
+ const checkReplyPermission = (sessionID: string, target: ChatTarget): string | undefined => {
344
+ if (!config.reply.requirePermission) return undefined
345
+ if (target.kind === "private") return undefined
346
+ if (manager.canReply(sessionID)) return undefined
347
+ logger.warn(`${targetLabel(target)} 本轮还没有回复权限,拒绝发送`, traceMeta(sessionID))
348
+ return `error: 本轮还没有回复权限。要回复用户,先调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;拿到权限后才能调用 qq_send_message。`
349
+ }
350
+
244
351
  // 同一次工具调用拆出的多段共用一个操作 id:段与段之间不再额外等间隔。
245
352
  let operationSeq = 0
246
353
  const nextOperation = (): string => `send-${++operationSeq}`
@@ -432,6 +539,41 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
432
539
  // QQ 工具必须作为独立工具暴露。Code Mode 只给模型一个 execute,
433
540
  // 按聊天配置的 qq_* 规则永远命不中,普通成员会连发消息的能力都没有。
434
541
 
542
+ editor.add({
543
+ name: "request_reply",
544
+ description:
545
+ "申请本轮的回复权限。群里默认没有发送权限:要回复用户,先调用这个工具并说明为什么要回复,拿到权限后才能调用 qq_send_message;权限只在本轮有效,轮次结束就收回。私聊默认就有权限,不用申请。",
546
+ input: {
547
+ type: "object",
548
+ properties: {
549
+ reason: {
550
+ type: "string",
551
+ description: "为什么要回复这条消息(必填):说清楚回复的理由,不要只写「需要回复」",
552
+ },
553
+ },
554
+ required: ["reason"],
555
+ additionalProperties: false,
556
+ },
557
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
558
+ execute: async (raw, context) => {
559
+ const input = (raw ?? {}) as { reason?: unknown }
560
+ const reason = typeof input.reason === "string" ? input.reason.trim() : ""
561
+ if (!reason) return text("error: 必须说明为什么回复(reason 不能为空)")
562
+ const target = manager.targetForSession(context.sessionID)
563
+ if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
564
+ const granted = manager.requestReply(context.sessionID, reason)
565
+ if (!granted.granted) {
566
+ return text("error: 当前没有进行中的 QQ 消息轮次,拿不到回复权限")
567
+ }
568
+ if (target.kind === "private") {
569
+ return text("私聊默认就有回复权限,直接调用 qq_send_message 即可。")
570
+ }
571
+ return text(
572
+ `已获得本轮的回复权限(理由:${reason})。现在可以调用 qq_send_message 回复;权限只在本轮有效。`,
573
+ )
574
+ },
575
+ })
576
+
435
577
  editor.add({
436
578
  name: "send_message",
437
579
  description:
@@ -472,6 +614,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
472
614
  manager.markMessageSent(context.sessionID)
473
615
  return text("skipped")
474
616
  }
617
+ const denied = checkReplyPermission(context.sessionID, target)
618
+ if (denied) return text(denied)
475
619
  guardOutbound(target, plain)
476
620
 
477
621
  // 长度按字素簇算,和拆段的口径一致:一个 emoji 只算一个。
@@ -542,6 +686,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
542
686
  const prepared = await prepareSend(context.sessionID)
543
687
  if (prepared.error) return prepared.error
544
688
  const target = prepared.target
689
+ const denied = checkReplyPermission(context.sessionID, target)
690
+ if (denied) return text(denied)
545
691
  const file = input.file ?? (input.base64 ? `base64://${input.base64}` : undefined)
546
692
  if (!file) return text("error: 缺少 file 或 base64")
547
693
  const tooLarge = checkInlineSize(file, "图片")
@@ -593,6 +739,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
593
739
  const prepared = await prepareSend(context.sessionID)
594
740
  if (prepared.error) return prepared.error
595
741
  const target = prepared.target
742
+ const denied = checkReplyPermission(context.sessionID, target)
743
+ if (denied) return text(denied)
596
744
  const id = input.id
597
745
  if (typeof id !== "number" || !Number.isInteger(id)) {
598
746
  return text("error: 缺少 id(收藏表情编号)")
@@ -639,6 +787,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
639
787
  const prepared = await prepareSend(context.sessionID)
640
788
  if (prepared.error) return prepared.error
641
789
  const target = prepared.target
790
+ const denied = checkReplyPermission(context.sessionID, target)
791
+ if (denied) return text(denied)
642
792
  if (!input.file) return text("error: 缺少 file")
643
793
  const tooLarge = checkInlineSize(input.file, "语音")
644
794
  if (tooLarge) return text(tooLarge)
@@ -685,6 +835,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
685
835
  const prepared = await prepareSend(context.sessionID)
686
836
  if (prepared.error) return prepared.error
687
837
  const target = prepared.target
838
+ const denied = checkReplyPermission(context.sessionID, target)
839
+ if (denied) return text(denied)
688
840
  const nodes: {
689
841
  user_id: number
690
842
  nickname: string
@@ -733,6 +885,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
733
885
  const prepared = await prepareSend(context.sessionID)
734
886
  if (prepared.error) return prepared.error
735
887
  const target = prepared.target
888
+ const denied = checkReplyPermission(context.sessionID, target)
889
+ if (denied) return text(denied)
736
890
  if (!input.user_id) return text("error: 缺少 user_id")
737
891
  const verdict = await permit(target, nextOperation())
738
892
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
@@ -834,5 +988,147 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
834
988
  return text(JSON.stringify(info))
835
989
  },
836
990
  })
991
+
992
+ // 日记工具依赖日记存储;没配存储时不注册,免得模型调到一个必然失败的工具。
993
+ const diaryStore = diary
994
+ if (diaryStore) {
995
+ /** 日记工具的目标:必须是当前会话绑定且放行的那个聊天。 */
996
+ const diaryTarget = (sessionID: string): ChatTarget | undefined => requireTarget(sessionID)
997
+
998
+ /** 找不到日记时把可用的日期一起回给模型,省得它来回试。 */
999
+ const diaryMissing = async (chat: string, date: string): Promise<string> => {
1000
+ const available = (await diaryStore.list(chat, 10)).map((item) => item.date)
1001
+ const hint = available.length > 0 ? `(可用的日期:${available.join("、")})` : ""
1002
+ return `error: 没有找到 ${date} 的日记${hint}`
1003
+ }
1004
+
1005
+ editor.add({
1006
+ name: "diary_write",
1007
+ description:
1008
+ "给当前 QQ 群聊或私聊写一篇日记。同一个聊天同一天只有一篇日记,重复写会覆盖当天那一篇。content 是日记正文;date 是日期,格式 YYYY-MM-DD,省略表示今天;title 是标题,省略时用日期做标题。",
1009
+ input: {
1010
+ type: "object",
1011
+ properties: {
1012
+ content: { type: "string", description: "日记正文(必填)" },
1013
+ date: { type: "string", description: "日期,格式 YYYY-MM-DD;省略表示今天" },
1014
+ title: { type: "string", description: "日记标题;省略时用日期做标题" },
1015
+ },
1016
+ required: ["content"],
1017
+ additionalProperties: false,
1018
+ },
1019
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1020
+ execute: async (raw, context) => {
1021
+ const input = (raw ?? {}) as DiaryWriteInput
1022
+ const target = diaryTarget(context.sessionID)
1023
+ if (!target) return text("error: 当前会话没有绑定的聊天,无法读写日记")
1024
+ const content = (input.content ?? "").trim()
1025
+ if (!content) return text("error: 缺少 content")
1026
+ const date = input.date?.trim() || dateKey()
1027
+ if (!isDateKey(date)) return text(`error: 日期格式不对:${date},请用 YYYY-MM-DD`)
1028
+ const entry = await diaryStore.write(targetKey(target), date, {
1029
+ title: input.title?.trim() ?? "",
1030
+ body: content,
1031
+ source: "model",
1032
+ })
1033
+ return text(`已写入 ${date} 的日记:${entry.title}`)
1034
+ },
1035
+ })
1036
+
1037
+ editor.add({
1038
+ name: "diary_read",
1039
+ description:
1040
+ "读取当前 QQ 群聊或私聊的日记正文。date 是日期,格式 YYYY-MM-DD;省略时返回最近一篇。返回的是日记文本,不是文件列表。",
1041
+ input: {
1042
+ type: "object",
1043
+ properties: {
1044
+ date: { type: "string", description: "日期,格式 YYYY-MM-DD;省略表示最近一篇" },
1045
+ },
1046
+ additionalProperties: false,
1047
+ },
1048
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1049
+ execute: async (raw, context) => {
1050
+ const input = (raw ?? {}) as DiaryReadInput
1051
+ const target = diaryTarget(context.sessionID)
1052
+ if (!target) return text("error: 当前会话没有绑定的聊天,无法读写日记")
1053
+ const chat = targetKey(target)
1054
+ const date = input.date?.trim()
1055
+ if (!date) {
1056
+ const latest = await diaryStore.latest(chat)
1057
+ if (!latest) return text("error: 这个聊天还没有日记")
1058
+ return text(formatDiaryBody(latest.date, latest.title, latest.body))
1059
+ }
1060
+ if (!isDateKey(date)) return text(`error: 日期格式不对:${date},请用 YYYY-MM-DD`)
1061
+ const entry = await diaryStore.read(chat, date)
1062
+ if (!entry) return text(await diaryMissing(chat, date))
1063
+ return text(formatDiaryBody(entry.date, entry.title, entry.body))
1064
+ },
1065
+ })
1066
+
1067
+ editor.add({
1068
+ name: "diary_list",
1069
+ description:
1070
+ "列出当前 QQ 群聊或私聊最近的日记,只返回日期和标题。days 是看几篇,默认 7 篇。",
1071
+ input: {
1072
+ type: "object",
1073
+ properties: {
1074
+ days: { type: "number", description: "看最近几篇,默认 7" },
1075
+ },
1076
+ additionalProperties: false,
1077
+ },
1078
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1079
+ execute: async (raw, context) => {
1080
+ const input = (raw ?? {}) as DiaryListInput
1081
+ const target = diaryTarget(context.sessionID)
1082
+ if (!target) return text("error: 当前会话没有绑定的聊天,无法读写日记")
1083
+ const days = Number.isInteger(input.days) && (input.days ?? 0) > 0 ? (input.days ?? 7) : 7
1084
+ const entries = await diaryStore.list(targetKey(target), days)
1085
+ if (entries.length === 0) return text("这个聊天还没有日记。")
1086
+ return text(entries.map((entry) => `${entry.date} ${entry.title}`).join("\n"))
1087
+ },
1088
+ })
1089
+ }
1090
+
1091
+ editor.add({
1092
+ name: "send_file",
1093
+ description:
1094
+ "向当前 QQ 群聊或私聊发送一个本地文件。file 是文件路径,只能是机器人允许发送的目录里的普通文件;name 是对方看到的文件名,省略时用原文件名。",
1095
+ input: {
1096
+ type: "object",
1097
+ properties: {
1098
+ file: { type: "string", description: "本地文件路径(必填)" },
1099
+ name: { type: "string", description: "对方看到的文件名;省略时用原文件名" },
1100
+ },
1101
+ required: ["file"],
1102
+ additionalProperties: false,
1103
+ },
1104
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
1105
+ execute: async (raw, context) => {
1106
+ const input = (raw ?? {}) as FileInput
1107
+ const prepared = await prepareSend(context.sessionID)
1108
+ if (prepared.error) return prepared.error
1109
+ const target = prepared.target
1110
+ const denied = checkReplyPermission(context.sessionID, target)
1111
+ if (denied) return text(denied)
1112
+ const file = input.file?.trim()
1113
+ if (!file) return text("error: 缺少 file")
1114
+ let plan
1115
+ try {
1116
+ plan = await outbound.check(file)
1117
+ } catch (error) {
1118
+ return text(`error: ${error instanceof Error ? error.message : String(error)}`)
1119
+ }
1120
+ if (plan.kind !== "local") return text("error: 只能发送本地文件")
1121
+ const path = plan.path
1122
+ const name = input.name?.trim() || basename(path)
1123
+ // 文件内容没法扫描,路径与显示名同样过一遍出站检查。
1124
+ guardOutbound(target, `${name}\n${path}`)
1125
+ const verdict = await permit(target, nextOperation())
1126
+ if (!verdict.allowed) return refuse(context.sessionID, verdict)
1127
+ const response = await send(target, [{ type: "file", data: { file: path, name } }])
1128
+ trackSent(target, response)
1129
+ manager.markMessageSent(context.sessionID)
1130
+ return text("你已成功发送文件,可以选择结束对话")
1131
+ },
1132
+ })
837
1133
  })
838
1134
  }
@@ -0,0 +1,25 @@
1
+ {
2
+ "defaultProfile": "chat",
3
+ "profiles": {
4
+ "chat": {
5
+ "allow": ["websearch", "webfetch", "qq_*"],
6
+ "deny": ["qq_diary_*", "qq_send_file"]
7
+ },
8
+ "readonly": {
9
+ "allow": ["read", "glob", "grep", "qq_*"],
10
+ "deny": ["qq_diary_*", "qq_send_file"]
11
+ },
12
+ "proactive": {
13
+ "allow": ["websearch", "webfetch", "qq_*"],
14
+ "deny": ["qq_diary_*", "qq_send_file"]
15
+ },
16
+ "admin": {
17
+ "allow": ["*"],
18
+ "deny": []
19
+ }
20
+ },
21
+ "chats": {
22
+ "group:100": "readonly",
23
+ "private:200": "chat"
24
+ }
25
+ }