@cmach_socket/opencode-qq-bot 0.6.6 → 0.6.8

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,5 +1,6 @@
1
1
  import type { Plugin } from "@opencode/plugin"
2
2
  import { isTargetAllowed } from "../access"
3
+ import { delay } from "../async"
3
4
  import { type ChatTarget, targetKey, targetLabel } from "../chat"
4
5
  import type { QQBotConfig } from "../config"
5
6
  import {
@@ -22,6 +23,14 @@ import type { Tracer } from "../trace"
22
23
  /** 工具命名空间,最终工具名为 qq_send_message 等。 */
23
24
  export const TOOL_NAMESPACE = "qq"
24
25
 
26
+ /**
27
+ * 申请回复权限的工具名。
28
+ *
29
+ * 群里默认没有发送权限:模型得先说明为什么要回复,拿到权限才能发送;
30
+ * 权限只在本轮有效。私聊默认开放,不需要申请。
31
+ */
32
+ export const QQ_REQUEST_REPLY_TOOL = "qq_request_reply"
33
+
25
34
  /**
26
35
  * 暴露给模型的 QQ 工具名。
27
36
  *
@@ -29,6 +38,7 @@ export const TOOL_NAMESPACE = "qq"
29
38
  * `qq_send_message` 是模型发消息的唯一入口。
30
39
  */
31
40
  export const QQ_TOOL_NAMES = [
41
+ "qq_request_reply",
32
42
  "qq_send_message",
33
43
  "qq_send_image",
34
44
  "qq_send_sticker",
@@ -101,9 +111,6 @@ interface MessageIdInput {
101
111
  message_id?: number | string
102
112
  }
103
113
 
104
- /** QQ 单条消息的保守长度上限,超过时按段发送。 */
105
- export { MAX_MESSAGE_CHARS } from "../outbound"
106
-
107
114
  /** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
108
115
  const FORWARD_NODE_CHARS = 3000
109
116
 
@@ -113,8 +120,14 @@ function text(value: string, metadata?: Record<string, unknown>) {
113
120
  return { content: value, ...(Object.keys(marks).length > 0 ? { metadata: marks } : {}) }
114
121
  }
115
122
 
116
- function delay(ms: number): Promise<void> {
117
- return new Promise((resolve) => setTimeout(resolve, ms))
123
+ /** 工具返回值:content 是给模型看的文本,metadata 带失败标记。 */
124
+ type ToolResult = ReturnType<typeof text>
125
+
126
+ /** 按目标类型把消息投递出去:群聊与私聊走不同的 API。 */
127
+ function sendPayload(client: QQClient, target: ChatTarget, payload: string | unknown[]) {
128
+ return target.kind === "group"
129
+ ? client.api.sendGroupMessage(target.id, payload)
130
+ : client.api.sendPrivateMessage(target.id, payload)
118
131
  }
119
132
 
120
133
  /** 从 OneBot 发送结果里取出 message_id。 */
@@ -147,11 +160,7 @@ export async function sendPlainMessage(
147
160
  let sent = 0
148
161
  for (const [index, chunk] of chunks.entries()) {
149
162
  await options.limiter.pace(pluginSendScope(target), operation)
150
- if (target.kind === "group") {
151
- await client.api.sendGroupMessage(target.id, chunk)
152
- } else {
153
- await client.api.sendPrivateMessage(target.id, chunk)
154
- }
163
+ await sendPayload(client, target, chunk)
155
164
  sent += 1
156
165
  if (index < chunks.length - 1 && (options.delayMs ?? 0) > 0) {
157
166
  await delay(options.delayMs ?? 0)
@@ -241,6 +250,22 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
241
250
  return undefined
242
251
  }
243
252
 
253
+ /**
254
+ * 群里发消息前的权限检查。
255
+ *
256
+ * 默认没有发送权限:模型先说明理由才拿得到,权限只在本轮有效。
257
+ * 私聊默认开放,不用申请;选择不回复(`reply=false`)也不需要权限。
258
+ *
259
+ * @returns 可以发送时返回 undefined,否则返回给模型的错误文案。
260
+ */
261
+ const checkReplyPermission = (sessionID: string, target: ChatTarget): string | undefined => {
262
+ if (!config.reply.requirePermission) return undefined
263
+ if (target.kind === "private") return undefined
264
+ if (manager.canReply(sessionID)) return undefined
265
+ logger.warn(`${targetLabel(target)} 本轮还没有回复权限,拒绝发送`, traceMeta(sessionID))
266
+ return `error: 本轮还没有回复权限。要回复用户,先调用 ${QQ_REQUEST_REPLY_TOOL} 说明为什么要回复;拿到权限后才能调用 qq_send_message。`
267
+ }
268
+
244
269
  // 同一次工具调用拆出的多段共用一个操作 id:段与段之间不再额外等间隔。
245
270
  let operationSeq = 0
246
271
  const nextOperation = (): string => `send-${++operationSeq}`
@@ -266,6 +291,42 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
266
291
  await tracer?.record("response_sent", traceId, attributes, targetKey(target))
267
292
  }
268
293
 
294
+ /**
295
+ * 发送类工具的统一前置:解析目标,并确认本实例可以发送。
296
+ *
297
+ * 返回 `error` 时调用方直接把它交给模型;否则 `target` 一定存在。
298
+ */
299
+ const prepareSend = async (
300
+ sessionID: string,
301
+ ): Promise<
302
+ { target: ChatTarget; error?: undefined } | { target?: undefined; error: ToolResult }
303
+ > => {
304
+ const target = requireTarget(sessionID)
305
+ if (!target) return { error: text("error: 当前会话没有绑定 QQ 群聊或私聊") }
306
+ const blocked = await checkSendable()
307
+ if (blocked) return { error: text(blocked) }
308
+ return { target }
309
+ }
310
+
311
+ /**
312
+ * 只读类工具的统一前置:只解析目标,不要求连接可用。
313
+ *
314
+ * 查资料不需要发消息,连接断着也能回答。
315
+ */
316
+ const prepareQuery = (
317
+ sessionID: string,
318
+ ): { target: ChatTarget; error?: undefined } | { target?: undefined; error: ToolResult } => {
319
+ const target = requireTarget(sessionID)
320
+ if (!target) return { error: text("error: 当前会话没有绑定 QQ 群聊或私聊") }
321
+ return { target }
322
+ }
323
+
324
+ /** 记下机器人自己发出的消息 ID,供撤回与重复检测使用。 */
325
+ const trackSent = (target: ChatTarget, response: unknown): void => {
326
+ const messageId = messageIdOf(response)
327
+ if (messageId) manager.rememberOutgoing(target, messageId)
328
+ }
329
+
269
330
  /**
270
331
  * 申请一次出站发送许可。
271
332
  *
@@ -320,15 +381,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
320
381
  return `error: ${kind}数据过大,超过 ${Math.floor(MAX_INLINE_BYTES / 1024 / 1024)}MB 上限`
321
382
  }
322
383
 
323
- const sendText = (target: ChatTarget, chunk: string) =>
324
- target.kind === "group"
325
- ? client.api.sendGroupMessage(target.id, chunk)
326
- : client.api.sendPrivateMessage(target.id, chunk)
327
-
328
- const sendSegments = (target: ChatTarget, segments: unknown[]) =>
329
- target.kind === "group"
330
- ? client.api.sendGroupMessage(target.id, segments)
331
- : client.api.sendPrivateMessage(target.id, segments)
384
+ const send = (target: ChatTarget, payload: string | unknown[]) =>
385
+ sendPayload(client, target, payload)
332
386
 
333
387
  const sendForward = (target: ChatTarget, nodes: unknown[]) =>
334
388
  target.kind === "group"
@@ -377,8 +431,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
377
431
  const verdict = await permit(target, operation)
378
432
  if (!verdict.allowed) return refuse(sessionID, verdict, 0, nodes.length)
379
433
  const response = await sendForward(target, nodes)
380
- const messageId = messageIdOf(response)
381
- if (messageId) manager.rememberOutgoing(target, messageId)
434
+ trackSent(target, response)
382
435
  manager.markMessageSent(sessionID)
383
436
  logger.info(
384
437
  `${label} 已发送 ${length} 字(合并转发 ${nodes.length} 个节点)`,
@@ -404,6 +457,41 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
404
457
  // QQ 工具必须作为独立工具暴露。Code Mode 只给模型一个 execute,
405
458
  // 按聊天配置的 qq_* 规则永远命不中,普通成员会连发消息的能力都没有。
406
459
 
460
+ editor.add({
461
+ name: "request_reply",
462
+ description:
463
+ "申请本轮的回复权限。群里默认没有发送权限:要回复用户,先调用这个工具并说明为什么要回复,拿到权限后才能调用 qq_send_message;权限只在本轮有效,轮次结束就收回。私聊默认就有权限,不用申请。",
464
+ input: {
465
+ type: "object",
466
+ properties: {
467
+ reason: {
468
+ type: "string",
469
+ description: "为什么要回复这条消息(必填):说清楚回复的理由,不要只写「需要回复」",
470
+ },
471
+ },
472
+ required: ["reason"],
473
+ additionalProperties: false,
474
+ },
475
+ options: { namespace: TOOL_NAMESPACE, codemode: false },
476
+ execute: async (raw, context) => {
477
+ const input = (raw ?? {}) as { reason?: unknown }
478
+ const reason = typeof input.reason === "string" ? input.reason.trim() : ""
479
+ if (!reason) return text("error: 必须说明为什么回复(reason 不能为空)")
480
+ const target = manager.targetForSession(context.sessionID)
481
+ if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
482
+ const granted = manager.requestReply(context.sessionID, reason)
483
+ if (!granted.granted) {
484
+ return text("error: 当前没有进行中的 QQ 消息轮次,拿不到回复权限")
485
+ }
486
+ if (target.kind === "private") {
487
+ return text("私聊默认就有回复权限,直接调用 qq_send_message 即可。")
488
+ }
489
+ return text(
490
+ `已获得本轮的回复权限(理由:${reason})。现在可以调用 qq_send_message 回复;权限只在本轮有效。`,
491
+ )
492
+ },
493
+ })
494
+
407
495
  editor.add({
408
496
  name: "send_message",
409
497
  description:
@@ -420,10 +508,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
420
508
  options: { namespace: TOOL_NAMESPACE, codemode: false },
421
509
  execute: async (raw, context) => {
422
510
  const input = (raw ?? {}) as SendMessageInput
423
- const target = requireTarget(context.sessionID)
424
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
425
- const blocked = await checkSendable()
426
- if (blocked) return text(blocked)
511
+ const prepared = await prepareSend(context.sessionID)
512
+ if (prepared.error) return prepared.error
513
+ const target = prepared.target
427
514
  const label = targetLabel(target)
428
515
 
429
516
  if (input.reply === false) {
@@ -445,6 +532,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
445
532
  manager.markMessageSent(context.sessionID)
446
533
  return text("skipped")
447
534
  }
535
+ const denied = checkReplyPermission(context.sessionID, target)
536
+ if (denied) return text(denied)
448
537
  guardOutbound(target, plain)
449
538
 
450
539
  // 长度按字素簇算,和拆段的口径一致:一个 emoji 只算一个。
@@ -477,9 +566,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
477
566
  for (const [index, chunk] of chunks.entries()) {
478
567
  const verdict = await permit(target, operation)
479
568
  if (!verdict.allowed) return refuse(context.sessionID, verdict, sent, chunks.length)
480
- const response = await sendText(target, chunk)
481
- const messageId = messageIdOf(response)
482
- if (messageId) manager.rememberOutgoing(target, messageId)
569
+ const response = await send(target, chunk)
570
+ trackSent(target, response)
483
571
  sent += 1
484
572
  if (index < chunks.length - 1 && wait > 0) {
485
573
  await delay(wait)
@@ -513,10 +601,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
513
601
  options: { namespace: TOOL_NAMESPACE, codemode: false },
514
602
  execute: async (raw, context) => {
515
603
  const input = (raw ?? {}) as MediaInput
516
- const target = requireTarget(context.sessionID)
517
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
518
- const blocked = await checkSendable()
519
- if (blocked) return text(blocked)
604
+ const prepared = await prepareSend(context.sessionID)
605
+ if (prepared.error) return prepared.error
606
+ const target = prepared.target
607
+ const denied = checkReplyPermission(context.sessionID, target)
608
+ if (denied) return text(denied)
520
609
  const file = input.file ?? (input.base64 ? `base64://${input.base64}` : undefined)
521
610
  if (!file) return text("error: 缺少 file 或 base64")
522
611
  const tooLarge = checkInlineSize(file, "图片")
@@ -527,9 +616,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
527
616
  const verdict = await permit(target, nextOperation())
528
617
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
529
618
  const media = plan ? outbound.materialize(plan) : file
530
- const response = await sendSegments(target, [{ type: "image", data: { file: media } }])
531
- const messageId = messageIdOf(response)
532
- if (messageId) manager.rememberOutgoing(target, messageId)
619
+ const response = await send(target, [{ type: "image", data: { file: media } }])
620
+ trackSent(target, response)
533
621
  manager.markMessageSent(context.sessionID)
534
622
  return text("你已成功发送图片,可以选择结束对话")
535
623
  },
@@ -566,10 +654,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
566
654
  options: { namespace: TOOL_NAMESPACE, codemode: false },
567
655
  execute: async (raw, context) => {
568
656
  const input = (raw ?? {}) as StickerInput
569
- const target = requireTarget(context.sessionID)
570
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
571
- const blocked = await checkSendable()
572
- if (blocked) return text(blocked)
657
+ const prepared = await prepareSend(context.sessionID)
658
+ if (prepared.error) return prepared.error
659
+ const target = prepared.target
660
+ const denied = checkReplyPermission(context.sessionID, target)
661
+ if (denied) return text(denied)
573
662
  const id = input.id
574
663
  if (typeof id !== "number" || !Number.isInteger(id)) {
575
664
  return text("error: 缺少 id(收藏表情编号)")
@@ -587,14 +676,13 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
587
676
  const plan = await outbound.check(url)
588
677
  const verdict = await permit(target, nextOperation())
589
678
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
590
- const response = await sendSegments(target, [
679
+ const response = await send(target, [
591
680
  {
592
681
  type: "image",
593
682
  data: { file: outbound.materialize(plan), sub_type: CUSTOM_FACE_SUB_TYPE },
594
683
  },
595
684
  ])
596
- const messageId = messageIdOf(response)
597
- if (messageId) manager.rememberOutgoing(target, messageId)
685
+ trackSent(target, response)
598
686
  manager.markMessageSent(context.sessionID)
599
687
  return text(`你已成功发送收藏表情 ${id}「${row.tag || "未标注"}」,可以选择结束对话`)
600
688
  },
@@ -614,10 +702,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
614
702
  options: { namespace: TOOL_NAMESPACE, codemode: false },
615
703
  execute: async (raw, context) => {
616
704
  const input = (raw ?? {}) as MediaInput
617
- const target = requireTarget(context.sessionID)
618
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
619
- const blocked = await checkSendable()
620
- if (blocked) return text(blocked)
705
+ const prepared = await prepareSend(context.sessionID)
706
+ if (prepared.error) return prepared.error
707
+ const target = prepared.target
708
+ const denied = checkReplyPermission(context.sessionID, target)
709
+ if (denied) return text(denied)
621
710
  if (!input.file) return text("error: 缺少 file")
622
711
  const tooLarge = checkInlineSize(input.file, "语音")
623
712
  if (tooLarge) return text(tooLarge)
@@ -626,9 +715,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
626
715
  const verdict = await permit(target, nextOperation())
627
716
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
628
717
  const media = plan ? outbound.materialize(plan) : input.file
629
- const response = await sendSegments(target, [{ type: "record", data: { file: media } }])
630
- const messageId = messageIdOf(response)
631
- if (messageId) manager.rememberOutgoing(target, messageId)
718
+ const response = await send(target, [{ type: "record", data: { file: media } }])
719
+ trackSent(target, response)
632
720
  manager.markMessageSent(context.sessionID)
633
721
  return text("你已成功发送语音,可以选择结束对话")
634
722
  },
@@ -662,10 +750,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
662
750
  options: { namespace: TOOL_NAMESPACE, codemode: false },
663
751
  execute: async (raw, context) => {
664
752
  const input = (raw ?? {}) as ForwardInput
665
- const target = requireTarget(context.sessionID)
666
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
667
- const blocked = await checkSendable()
668
- if (blocked) return text(blocked)
753
+ const prepared = await prepareSend(context.sessionID)
754
+ if (prepared.error) return prepared.error
755
+ const target = prepared.target
756
+ const denied = checkReplyPermission(context.sessionID, target)
757
+ if (denied) return text(denied)
669
758
  const nodes: {
670
759
  user_id: number
671
760
  nickname: string
@@ -690,8 +779,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
690
779
  const verdict = await permit(target, nextOperation())
691
780
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
692
781
  const response = await sendForward(target, nodes)
693
- const messageId = messageIdOf(response)
694
- if (messageId) manager.rememberOutgoing(target, messageId)
782
+ trackSent(target, response)
695
783
  manager.markMessageSent(context.sessionID)
696
784
  await traceSent(context.sessionID, target, { mode: "forward", nodes: nodes.length })
697
785
  return text("你已成功发送合并转发消息,可以选择结束对话")
@@ -712,10 +800,11 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
712
800
  options: { namespace: TOOL_NAMESPACE, codemode: false },
713
801
  execute: async (raw, context) => {
714
802
  const input = (raw ?? {}) as UserInput
715
- const target = requireTarget(context.sessionID)
716
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
717
- const blocked = await checkSendable()
718
- if (blocked) return text(blocked)
803
+ const prepared = await prepareSend(context.sessionID)
804
+ if (prepared.error) return prepared.error
805
+ const target = prepared.target
806
+ const denied = checkReplyPermission(context.sessionID, target)
807
+ if (denied) return text(denied)
719
808
  if (!input.user_id) return text("error: 缺少 user_id")
720
809
  const verdict = await permit(target, nextOperation())
721
810
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
@@ -739,10 +828,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
739
828
  options: { namespace: TOOL_NAMESPACE, codemode: false },
740
829
  execute: async (raw, context) => {
741
830
  const input = (raw ?? {}) as MessageIdInput
742
- const target = requireTarget(context.sessionID)
743
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
744
- const blocked = await checkSendable()
745
- if (blocked) return text(blocked)
831
+ const prepared = await prepareSend(context.sessionID)
832
+ if (prepared.error) return prepared.error
833
+ const target = prepared.target
746
834
  if (input.message_id === undefined) return text("error: 缺少 message_id")
747
835
  if (!manager.isOutgoing(target, String(input.message_id))) {
748
836
  return text("error: 只能撤回机器人自己发送过的消息")
@@ -766,8 +854,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
766
854
  options: { namespace: TOOL_NAMESPACE, codemode: false },
767
855
  execute: async (raw, context) => {
768
856
  const input = (raw ?? {}) as UserInput
769
- const target = requireTarget(context.sessionID)
770
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
857
+ const prepared = prepareQuery(context.sessionID)
858
+ if (prepared.error) return prepared.error
859
+ const target = prepared.target
771
860
  if (!input.user_id) return text("error: 缺少 user_id")
772
861
  const info =
773
862
  target.kind === "group"
@@ -791,8 +880,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
791
880
  options: { namespace: TOOL_NAMESPACE, codemode: false },
792
881
  execute: async (raw, context) => {
793
882
  const input = (raw ?? {}) as MessageIdInput
794
- const target = requireTarget(context.sessionID)
795
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
883
+ const prepared = prepareQuery(context.sessionID)
884
+ if (prepared.error) return prepared.error
885
+ const target = prepared.target
796
886
  if (input.message_id === undefined) return text("error: 缺少 message_id")
797
887
  if (!manager.isKnownMessage(target, String(input.message_id))) {
798
888
  return text("error: 只能转写当前会话最近收到的消息")
@@ -9,7 +9,7 @@ import type { SessionManager } from "./session/manager"
9
9
  import type { ToolPolicy } from "./tools/policy"
10
10
  import { createPlainSender } from "./tools/qq"
11
11
 
12
- export { TUI_COMMAND_PREFIX, tuiCommandName } from "./commands"
12
+ export { tuiCommandName } from "./commands"
13
13
 
14
14
  export interface TuiCommandDeps {
15
15
  ctx: Plugin.Context
@@ -0,0 +1,21 @@
1
+ {
2
+ "defaultProfile": "chat",
3
+ "profiles": {
4
+ "chat": {
5
+ "allow": ["websearch", "webfetch", "qq_*"],
6
+ "deny": []
7
+ },
8
+ "readonly": {
9
+ "allow": ["read", "glob", "grep", "qq_*"],
10
+ "deny": []
11
+ },
12
+ "admin": {
13
+ "allow": ["*"],
14
+ "deny": []
15
+ }
16
+ },
17
+ "chats": {
18
+ "group:100": "readonly",
19
+ "private:200": "chat"
20
+ }
21
+ }