@cmach_socket/opencode-qq-bot 0.6.4 → 0.6.7

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 {
@@ -60,6 +61,12 @@ export interface ToolDeps {
60
61
  outbound: OutboundMedia
61
62
  /** 调用链追踪器;不传就不记追踪。 */
62
63
  tracer?: Tracer
64
+ /**
65
+ * 本实例是否持有机器人连接锁。
66
+ *
67
+ * 没有锁说明机器上另一个实例在消费消息,这个实例不能发送。
68
+ */
69
+ canSend?: () => boolean
63
70
  }
64
71
 
65
72
  interface SendMessageInput {
@@ -95,9 +102,6 @@ interface MessageIdInput {
95
102
  message_id?: number | string
96
103
  }
97
104
 
98
- /** QQ 单条消息的保守长度上限,超过时按段发送。 */
99
- export { MAX_MESSAGE_CHARS } from "../outbound"
100
-
101
105
  /** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
102
106
  const FORWARD_NODE_CHARS = 3000
103
107
 
@@ -107,8 +111,14 @@ function text(value: string, metadata?: Record<string, unknown>) {
107
111
  return { content: value, ...(Object.keys(marks).length > 0 ? { metadata: marks } : {}) }
108
112
  }
109
113
 
110
- function delay(ms: number): Promise<void> {
111
- return new Promise((resolve) => setTimeout(resolve, ms))
114
+ /** 工具返回值:content 是给模型看的文本,metadata 带失败标记。 */
115
+ type ToolResult = ReturnType<typeof text>
116
+
117
+ /** 按目标类型把消息投递出去:群聊与私聊走不同的 API。 */
118
+ function sendPayload(client: QQClient, target: ChatTarget, payload: string | unknown[]) {
119
+ return target.kind === "group"
120
+ ? client.api.sendGroupMessage(target.id, payload)
121
+ : client.api.sendPrivateMessage(target.id, payload)
112
122
  }
113
123
 
114
124
  /** 从 OneBot 发送结果里取出 message_id。 */
@@ -141,11 +151,7 @@ export async function sendPlainMessage(
141
151
  let sent = 0
142
152
  for (const [index, chunk] of chunks.entries()) {
143
153
  await options.limiter.pace(pluginSendScope(target), operation)
144
- if (target.kind === "group") {
145
- await client.api.sendGroupMessage(target.id, chunk)
146
- } else {
147
- await client.api.sendPrivateMessage(target.id, chunk)
148
- }
154
+ await sendPayload(client, target, chunk)
149
155
  sent += 1
150
156
  if (index < chunks.length - 1 && (options.delayMs ?? 0) > 0) {
151
157
  await delay(options.delayMs ?? 0)
@@ -215,6 +221,26 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
215
221
  return target
216
222
  }
217
223
 
224
+ /**
225
+ * 发送前的检查:没锁、没连接都不发。
226
+ *
227
+ * 没锁说明这台机器上另一个实例在消费消息,本实例的通道并没有连上 NapCat,
228
+ * 硬发只会得到「连接未建立」。连接断掉时先重连一次,重连不上就明确告诉模型。
229
+ *
230
+ * @returns 可以发送时返回 undefined,否则返回给模型的错误文案。
231
+ */
232
+ const checkSendable = async (): Promise<string | undefined> => {
233
+ if (deps.canSend && !deps.canSend()) {
234
+ logger.warn("本实例没有机器人连接锁,拒绝发送")
235
+ return "error: 本实例没有机器人连接锁(这台机器上已有另一个实例在运行),消息未发送"
236
+ }
237
+ if (!(await client.ensureConnected())) {
238
+ logger.error("NapCat 未连接,放弃发送")
239
+ return "error: NapCat 未连接,消息未发送;请稍后重试"
240
+ }
241
+ return undefined
242
+ }
243
+
218
244
  // 同一次工具调用拆出的多段共用一个操作 id:段与段之间不再额外等间隔。
219
245
  let operationSeq = 0
220
246
  const nextOperation = (): string => `send-${++operationSeq}`
@@ -240,6 +266,42 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
240
266
  await tracer?.record("response_sent", traceId, attributes, targetKey(target))
241
267
  }
242
268
 
269
+ /**
270
+ * 发送类工具的统一前置:解析目标,并确认本实例可以发送。
271
+ *
272
+ * 返回 `error` 时调用方直接把它交给模型;否则 `target` 一定存在。
273
+ */
274
+ const prepareSend = async (
275
+ sessionID: string,
276
+ ): Promise<
277
+ { target: ChatTarget; error?: undefined } | { target?: undefined; error: ToolResult }
278
+ > => {
279
+ const target = requireTarget(sessionID)
280
+ if (!target) return { error: text("error: 当前会话没有绑定 QQ 群聊或私聊") }
281
+ const blocked = await checkSendable()
282
+ if (blocked) return { error: text(blocked) }
283
+ return { target }
284
+ }
285
+
286
+ /**
287
+ * 只读类工具的统一前置:只解析目标,不要求连接可用。
288
+ *
289
+ * 查资料不需要发消息,连接断着也能回答。
290
+ */
291
+ const prepareQuery = (
292
+ sessionID: string,
293
+ ): { target: ChatTarget; error?: undefined } | { target?: undefined; error: ToolResult } => {
294
+ const target = requireTarget(sessionID)
295
+ if (!target) return { error: text("error: 当前会话没有绑定 QQ 群聊或私聊") }
296
+ return { target }
297
+ }
298
+
299
+ /** 记下机器人自己发出的消息 ID,供撤回与重复检测使用。 */
300
+ const trackSent = (target: ChatTarget, response: unknown): void => {
301
+ const messageId = messageIdOf(response)
302
+ if (messageId) manager.rememberOutgoing(target, messageId)
303
+ }
304
+
243
305
  /**
244
306
  * 申请一次出站发送许可。
245
307
  *
@@ -294,15 +356,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
294
356
  return `error: ${kind}数据过大,超过 ${Math.floor(MAX_INLINE_BYTES / 1024 / 1024)}MB 上限`
295
357
  }
296
358
 
297
- const sendText = (target: ChatTarget, chunk: string) =>
298
- target.kind === "group"
299
- ? client.api.sendGroupMessage(target.id, chunk)
300
- : client.api.sendPrivateMessage(target.id, chunk)
301
-
302
- const sendSegments = (target: ChatTarget, segments: unknown[]) =>
303
- target.kind === "group"
304
- ? client.api.sendGroupMessage(target.id, segments)
305
- : client.api.sendPrivateMessage(target.id, segments)
359
+ const send = (target: ChatTarget, payload: string | unknown[]) =>
360
+ sendPayload(client, target, payload)
306
361
 
307
362
  const sendForward = (target: ChatTarget, nodes: unknown[]) =>
308
363
  target.kind === "group"
@@ -351,8 +406,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
351
406
  const verdict = await permit(target, operation)
352
407
  if (!verdict.allowed) return refuse(sessionID, verdict, 0, nodes.length)
353
408
  const response = await sendForward(target, nodes)
354
- const messageId = messageIdOf(response)
355
- if (messageId) manager.rememberOutgoing(target, messageId)
409
+ trackSent(target, response)
356
410
  manager.markMessageSent(sessionID)
357
411
  logger.info(
358
412
  `${label} 已发送 ${length} 字(合并转发 ${nodes.length} 个节点)`,
@@ -394,8 +448,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
394
448
  options: { namespace: TOOL_NAMESPACE, codemode: false },
395
449
  execute: async (raw, context) => {
396
450
  const input = (raw ?? {}) as SendMessageInput
397
- const target = requireTarget(context.sessionID)
398
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
451
+ const prepared = await prepareSend(context.sessionID)
452
+ if (prepared.error) return prepared.error
453
+ const target = prepared.target
399
454
  const label = targetLabel(target)
400
455
 
401
456
  if (input.reply === false) {
@@ -449,9 +504,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
449
504
  for (const [index, chunk] of chunks.entries()) {
450
505
  const verdict = await permit(target, operation)
451
506
  if (!verdict.allowed) return refuse(context.sessionID, verdict, sent, chunks.length)
452
- const response = await sendText(target, chunk)
453
- const messageId = messageIdOf(response)
454
- if (messageId) manager.rememberOutgoing(target, messageId)
507
+ const response = await send(target, chunk)
508
+ trackSent(target, response)
455
509
  sent += 1
456
510
  if (index < chunks.length - 1 && wait > 0) {
457
511
  await delay(wait)
@@ -485,8 +539,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
485
539
  options: { namespace: TOOL_NAMESPACE, codemode: false },
486
540
  execute: async (raw, context) => {
487
541
  const input = (raw ?? {}) as MediaInput
488
- const target = requireTarget(context.sessionID)
489
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
542
+ const prepared = await prepareSend(context.sessionID)
543
+ if (prepared.error) return prepared.error
544
+ const target = prepared.target
490
545
  const file = input.file ?? (input.base64 ? `base64://${input.base64}` : undefined)
491
546
  if (!file) return text("error: 缺少 file 或 base64")
492
547
  const tooLarge = checkInlineSize(file, "图片")
@@ -497,9 +552,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
497
552
  const verdict = await permit(target, nextOperation())
498
553
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
499
554
  const media = plan ? outbound.materialize(plan) : file
500
- const response = await sendSegments(target, [{ type: "image", data: { file: media } }])
501
- const messageId = messageIdOf(response)
502
- if (messageId) manager.rememberOutgoing(target, messageId)
555
+ const response = await send(target, [{ type: "image", data: { file: media } }])
556
+ trackSent(target, response)
503
557
  manager.markMessageSent(context.sessionID)
504
558
  return text("你已成功发送图片,可以选择结束对话")
505
559
  },
@@ -536,8 +590,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
536
590
  options: { namespace: TOOL_NAMESPACE, codemode: false },
537
591
  execute: async (raw, context) => {
538
592
  const input = (raw ?? {}) as StickerInput
539
- const target = requireTarget(context.sessionID)
540
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
593
+ const prepared = await prepareSend(context.sessionID)
594
+ if (prepared.error) return prepared.error
595
+ const target = prepared.target
541
596
  const id = input.id
542
597
  if (typeof id !== "number" || !Number.isInteger(id)) {
543
598
  return text("error: 缺少 id(收藏表情编号)")
@@ -555,14 +610,13 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
555
610
  const plan = await outbound.check(url)
556
611
  const verdict = await permit(target, nextOperation())
557
612
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
558
- const response = await sendSegments(target, [
613
+ const response = await send(target, [
559
614
  {
560
615
  type: "image",
561
616
  data: { file: outbound.materialize(plan), sub_type: CUSTOM_FACE_SUB_TYPE },
562
617
  },
563
618
  ])
564
- const messageId = messageIdOf(response)
565
- if (messageId) manager.rememberOutgoing(target, messageId)
619
+ trackSent(target, response)
566
620
  manager.markMessageSent(context.sessionID)
567
621
  return text(`你已成功发送收藏表情 ${id}「${row.tag || "未标注"}」,可以选择结束对话`)
568
622
  },
@@ -582,8 +636,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
582
636
  options: { namespace: TOOL_NAMESPACE, codemode: false },
583
637
  execute: async (raw, context) => {
584
638
  const input = (raw ?? {}) as MediaInput
585
- const target = requireTarget(context.sessionID)
586
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
639
+ const prepared = await prepareSend(context.sessionID)
640
+ if (prepared.error) return prepared.error
641
+ const target = prepared.target
587
642
  if (!input.file) return text("error: 缺少 file")
588
643
  const tooLarge = checkInlineSize(input.file, "语音")
589
644
  if (tooLarge) return text(tooLarge)
@@ -592,9 +647,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
592
647
  const verdict = await permit(target, nextOperation())
593
648
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
594
649
  const media = plan ? outbound.materialize(plan) : input.file
595
- const response = await sendSegments(target, [{ type: "record", data: { file: media } }])
596
- const messageId = messageIdOf(response)
597
- if (messageId) manager.rememberOutgoing(target, messageId)
650
+ const response = await send(target, [{ type: "record", data: { file: media } }])
651
+ trackSent(target, response)
598
652
  manager.markMessageSent(context.sessionID)
599
653
  return text("你已成功发送语音,可以选择结束对话")
600
654
  },
@@ -628,8 +682,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
628
682
  options: { namespace: TOOL_NAMESPACE, codemode: false },
629
683
  execute: async (raw, context) => {
630
684
  const input = (raw ?? {}) as ForwardInput
631
- const target = requireTarget(context.sessionID)
632
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
685
+ const prepared = await prepareSend(context.sessionID)
686
+ if (prepared.error) return prepared.error
687
+ const target = prepared.target
633
688
  const nodes: {
634
689
  user_id: number
635
690
  nickname: string
@@ -654,8 +709,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
654
709
  const verdict = await permit(target, nextOperation())
655
710
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
656
711
  const response = await sendForward(target, nodes)
657
- const messageId = messageIdOf(response)
658
- if (messageId) manager.rememberOutgoing(target, messageId)
712
+ trackSent(target, response)
659
713
  manager.markMessageSent(context.sessionID)
660
714
  await traceSent(context.sessionID, target, { mode: "forward", nodes: nodes.length })
661
715
  return text("你已成功发送合并转发消息,可以选择结束对话")
@@ -676,8 +730,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
676
730
  options: { namespace: TOOL_NAMESPACE, codemode: false },
677
731
  execute: async (raw, context) => {
678
732
  const input = (raw ?? {}) as UserInput
679
- const target = requireTarget(context.sessionID)
680
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
733
+ const prepared = await prepareSend(context.sessionID)
734
+ if (prepared.error) return prepared.error
735
+ const target = prepared.target
681
736
  if (!input.user_id) return text("error: 缺少 user_id")
682
737
  const verdict = await permit(target, nextOperation())
683
738
  if (!verdict.allowed) return refuse(context.sessionID, verdict)
@@ -701,8 +756,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
701
756
  options: { namespace: TOOL_NAMESPACE, codemode: false },
702
757
  execute: async (raw, context) => {
703
758
  const input = (raw ?? {}) as MessageIdInput
704
- const target = requireTarget(context.sessionID)
705
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
759
+ const prepared = await prepareSend(context.sessionID)
760
+ if (prepared.error) return prepared.error
761
+ const target = prepared.target
706
762
  if (input.message_id === undefined) return text("error: 缺少 message_id")
707
763
  if (!manager.isOutgoing(target, String(input.message_id))) {
708
764
  return text("error: 只能撤回机器人自己发送过的消息")
@@ -726,8 +782,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
726
782
  options: { namespace: TOOL_NAMESPACE, codemode: false },
727
783
  execute: async (raw, context) => {
728
784
  const input = (raw ?? {}) as UserInput
729
- const target = requireTarget(context.sessionID)
730
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
785
+ const prepared = prepareQuery(context.sessionID)
786
+ if (prepared.error) return prepared.error
787
+ const target = prepared.target
731
788
  if (!input.user_id) return text("error: 缺少 user_id")
732
789
  const info =
733
790
  target.kind === "group"
@@ -751,8 +808,9 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
751
808
  options: { namespace: TOOL_NAMESPACE, codemode: false },
752
809
  execute: async (raw, context) => {
753
810
  const input = (raw ?? {}) as MessageIdInput
754
- const target = requireTarget(context.sessionID)
755
- if (!target) return text("error: 当前会话没有绑定 QQ 群聊或私聊")
811
+ const prepared = prepareQuery(context.sessionID)
812
+ if (prepared.error) return prepared.error
813
+ const target = prepared.target
756
814
  if (input.message_id === undefined) return text("error: 缺少 message_id")
757
815
  if (!manager.isKnownMessage(target, String(input.message_id))) {
758
816
  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