@cmach_socket/opencode-qq-bot 0.7.0 → 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
@@ -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)