@cmach_socket/opencode-qq-bot 0.10.0 → 0.11.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
@@ -110,14 +110,14 @@ export interface ToolDeps {
110
110
  }
111
111
 
112
112
  interface SendMessageInput {
113
- content?: string
113
+ content?: string[]
114
114
  reply?: boolean
115
115
  unlimit_length?: boolean
116
116
  }
117
117
 
118
118
  interface MediaInput {
119
- file?: string
120
- base64?: string
119
+ file?: string[]
120
+ base64?: string[]
121
121
  }
122
122
 
123
123
  interface ForwardNodeInput {
@@ -133,7 +133,7 @@ interface UserInput {
133
133
  }
134
134
 
135
135
  interface StickerInput {
136
- id?: number
136
+ id?: number[]
137
137
  }
138
138
 
139
139
  interface CollectStickerInput {
@@ -159,8 +159,29 @@ interface DiaryListInput {
159
159
  }
160
160
 
161
161
  interface FileInput {
162
- file?: string
163
- name?: string
162
+ file?: string[]
163
+ name?: string[]
164
+ }
165
+
166
+ /** 合并转发里的一个节点:发送者固定为机器人自己,正文是纯文本。 */
167
+ interface ForwardNode {
168
+ user_id: number
169
+ nickname: string
170
+ content: { type: "text"; data: { text: string } }[]
171
+ }
172
+
173
+ /** 一条待发消息:纯文本、媒体段,或要合并转发出去的节点。 */
174
+ type Outgoing =
175
+ | { kind: "text"; text: string }
176
+ | { kind: "segments"; payload: unknown[] }
177
+ | { kind: "forward"; nodes: ForwardNode[] }
178
+
179
+ /** 一批发送的文案口径:名目与量词。 */
180
+ interface SendWording {
181
+ /** 名目,如「消息」「图片」。 */
182
+ noun: string
183
+ /** 量词,如「条」「张」。 */
184
+ unit: string
164
185
  }
165
186
 
166
187
  /** 合并转发里单个节点的字数上限,留出余量避免被 NapCat 截断。 */
@@ -175,6 +196,64 @@ function text(value: string, metadata?: Record<string, unknown>) {
175
196
  /** 工具返回值:content 是给模型看的文本,metadata 带失败标记。 */
176
197
  type ToolResult = ReturnType<typeof text>
177
198
 
199
+ /**
200
+ * 把模型给的入参归一成字符串列表。
201
+ *
202
+ * 单个字符串按一条处理:模型偶尔不按 schema 传数组。
203
+ * 空串与空白丢掉:它们不构成一条消息。
204
+ */
205
+ function toStringList(value: unknown): string[] {
206
+ const raw = Array.isArray(value) ? value : [value]
207
+ return raw
208
+ .filter((item): item is string => typeof item === "string")
209
+ .map((item) => item.trim())
210
+ .filter((item) => item.length > 0)
211
+ }
212
+
213
+ /**
214
+ * 把模型给的入参归一成字符串列表,保留原有下标。
215
+ *
216
+ * 用于与 `file` 一一对应的 `name`:空串占位,后面的名字才不会错位。
217
+ */
218
+ function toStringSlots(value: unknown): string[] {
219
+ const raw = Array.isArray(value) ? value : [value]
220
+ return raw.map((item) => (typeof item === "string" ? item.trim() : ""))
221
+ }
222
+
223
+ /** 把模型给的入参归一成整数列表:非整数丢掉。 */
224
+ function toNumberList(value: unknown): number[] {
225
+ const raw = Array.isArray(value) ? value : [value]
226
+ return raw.filter((item): item is number => typeof item === "number" && Number.isInteger(item))
227
+ }
228
+
229
+ /** 消息发送成功的文案:一条按单数说,多条报出条数。 */
230
+ function sentMessageText(count: number): string {
231
+ return count === 1
232
+ ? "你已成功发送消息,可以选择结束对话"
233
+ : `你已成功发送 ${count} 条消息,可以选择结束对话`
234
+ }
235
+
236
+ /** 图片发送成功的文案:一张按单数说,多张报出数量。 */
237
+ function sentImageText(count: number): string {
238
+ return count === 1
239
+ ? "你已成功发送图片,可以选择结束对话"
240
+ : `你已成功发送 ${count} 张图片,可以选择结束对话`
241
+ }
242
+
243
+ /** 语音发送成功的文案:一条按单数说,多条报出数量。 */
244
+ function sentRecordText(count: number): string {
245
+ return count === 1
246
+ ? "你已成功发送语音,可以选择结束对话"
247
+ : `你已成功发送 ${count} 条语音,可以选择结束对话`
248
+ }
249
+
250
+ /** 文件发送成功的文案:一个按单数说,多个报出数量。 */
251
+ function sentFileText(count: number): string {
252
+ return count === 1
253
+ ? "你已成功发送文件,可以选择结束对话"
254
+ : `你已成功发送 ${count} 个文件,可以选择结束对话`
255
+ }
256
+
178
257
  /** 日记正文进模型上下文的固定上限,超出部分截断。 */
179
258
  const DIARY_READ_MAX_CHARS = 4000
180
259
 
@@ -458,7 +537,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
458
537
  /** 限流拒绝时的工具返回值:本轮算已回复,避免模型被反复提醒补发。 */
459
538
  const refuse = (sessionID: string, verdict: RateLimitVerdict, sent = 0, total = 0) => {
460
539
  manager.markMessageSent(sessionID)
461
- const progress = total > 0 ? `(已发送 ${sent}/${total} 段)` : ""
540
+ const progress = total > 0 ? `(已发送 ${sent}/${total} 条)` : ""
462
541
  // 限流拒绝是“请停止发送”,不要因为它允许模型立刻重试。
463
542
  return text(`error: ${verdict.reason}${progress}`, { retryable: false })
464
543
  }
@@ -525,40 +604,99 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
525
604
  }
526
605
 
527
606
  /**
528
- * 太长的回复改成合并转发发出去。
607
+ * 合并转发里的节点:发送者固定为机器人自己,正文按节点字数上限拆开。
529
608
  *
530
609
  * 一口气刷十几条会把群刷爆,合并转发只占一条消息。
531
610
  */
532
- const sendAsForward = async (
533
- sessionID: string,
534
- target: ChatTarget,
535
- plain: string,
536
- operation: string,
537
- length: number,
538
- ) => {
539
- const label = targetLabel(target)
611
+ const buildForwardNodes = async (plain: string): Promise<ForwardNode[]> => {
540
612
  const identity = await botIdentity()
541
- const nodes = splitMessage(plain, FORWARD_NODE_CHARS).map((chunk) => ({
613
+ return splitMessage(plain, FORWARD_NODE_CHARS).map((chunk) => ({
542
614
  user_id: identity.userId,
543
615
  nickname: identity.nickname,
544
616
  content: [{ type: "text", data: { text: chunk } }],
545
617
  }))
618
+ }
619
+
620
+ /** 按消息类型投递出去。 */
621
+ const deliver = async (target: ChatTarget, message: Outgoing) => {
622
+ if (message.kind === "text") return send(target, message.text)
623
+ if (message.kind === "segments") return send(target, message.payload)
624
+ return sendForward(target, message.nodes)
625
+ }
626
+
627
+ /** 一批发送的参数。 */
628
+ interface BatchSend {
629
+ /** 这批消息的出站形式,按发送顺序排列。 */
630
+ messages: Outgoing[]
631
+ /** 名目与量词,用于报错文案。 */
632
+ wording: SendWording
633
+ /** 成功文案;参数是实际发出的条数。 */
634
+ successText: (count: number) => string
635
+ /** 记进追踪的字数;媒体类工具没有字数,不传就不记。 */
636
+ chars?: number
637
+ }
638
+
639
+ /**
640
+ * 按顺序发一批消息。
641
+ *
642
+ * 一条一次出站许可,条与条之间按节奏等待,看起来像人在分条打字;
643
+ * 中途被限流或失败时如实报出已发出几条。
644
+ */
645
+ const sendOutgoing = async (
646
+ sessionID: string,
647
+ target: ChatTarget,
648
+ operation: string,
649
+ batch: BatchSend,
650
+ ): Promise<ToolResult> => {
651
+ const label = targetLabel(target)
652
+ const { messages, wording } = batch
653
+ // 段与段之间的间隔:配了随机区间就在区间里等。
654
+ const wait = segmentDelayMs({
655
+ sendDelayMs: config.sendDelayMs,
656
+ minDelayMs: config.reply.minDelayMs,
657
+ maxDelayMs: config.reply.maxDelayMs,
658
+ })
659
+ let sent = 0
546
660
  try {
547
- const verdict = await permit(target, operation)
548
- if (!verdict.allowed) return refuse(sessionID, verdict, 0, nodes.length)
549
- const response = await sendForward(target, nodes)
550
- trackSent(target, response)
551
- manager.markMessageSent(sessionID)
661
+ for (const [index, message] of messages.entries()) {
662
+ const verdict = await permit(target, operation)
663
+ if (!verdict.allowed) return refuse(sessionID, verdict, sent, messages.length)
664
+ const response = await deliver(target, message)
665
+ trackSent(target, response)
666
+ sent += 1
667
+ if (index < messages.length - 1 && wait > 0) {
668
+ await delay(wait)
669
+ }
670
+ }
671
+ } catch (error) {
672
+ if (sent > 0) manager.markMessageSent(sessionID)
673
+ logger.error(`${label} 发送${wording.noun}失败,已发送 ${sent}/${messages.length}`, error)
674
+ // 已经发出部分消息时不要允许整条重试,否则会重复发送。
675
+ return text(`error: ${wording.noun}只发送了 ${sent}/${messages.length} ${wording.unit}`, {
676
+ retryable: sent === 0,
677
+ })
678
+ }
679
+ manager.markMessageSent(sessionID)
680
+ if (batch.chars !== undefined) {
681
+ const nodes = messages.reduce(
682
+ (sum, message) => sum + (message.kind === "forward" ? message.nodes.length : 0),
683
+ 0,
684
+ )
552
685
  logger.info(
553
- `${label} 已发送 ${length} 字(合并转发 ${nodes.length} 个节点)`,
686
+ nodes > 0
687
+ ? `${label} 已发送 ${batch.chars} 字(合并转发 ${nodes} 个节点)`
688
+ : `${label} 已发送 ${batch.chars} 字`,
554
689
  traceMeta(sessionID),
555
690
  )
556
- await traceSent(sessionID, target, { chars: length, mode: "forward", nodes: nodes.length })
557
- return text("你已成功发送消息,可以选择结束对话")
558
- } catch (error) {
559
- logger.error(`${label} 发送合并转发失败`, error)
560
- return text("error: 消息发送失败", { retryable: true })
691
+ await traceSent(
692
+ sessionID,
693
+ target,
694
+ nodes > 0
695
+ ? { chars: batch.chars, mode: "forward", nodes }
696
+ : { chars: batch.chars, mode: "plain", segments: sent },
697
+ )
561
698
  }
699
+ return text(batch.successText(sent))
562
700
  }
563
701
 
564
702
  const result = await ctx.tool.transform((editor) => {
@@ -611,11 +749,15 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
611
749
  editor.add({
612
750
  name: "send_message",
613
751
  description:
614
- "向当前 QQ 群聊或私聊发送一条消息。每轮必须调用一个发送工具。content: 要发送的文本;reply: true 表示发送,false 表示选择不发送(已读不回);unlimit_length: 设为 true 可解除默认的长度告警限制。",
752
+ "向当前 QQ 群聊或私聊发送消息。content 是文本列表:一条内容发一条消息,要分多条说就一次给全。reply: true 表示发送,false 表示选择不发送(已读不回);unlimit_length: 设为 true 可解除默认的长度告警限制。",
615
753
  input: {
616
754
  type: "object",
617
755
  properties: {
618
- content: { type: "string", description: "要发送的文本内容;reply=false 时可省略" },
756
+ content: {
757
+ type: "array",
758
+ description: "要发送的文本内容列表,一条内容发一条消息;reply=false 时可省略",
759
+ items: { type: "string" },
760
+ },
619
761
  reply: { type: "boolean", description: "true 表示发送,false 表示本轮不回复" },
620
762
  unlimit_length: { type: "boolean", description: "解除默认的消息长度限制" },
621
763
  },
@@ -634,83 +776,78 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
634
776
  manager.markMessageSent(context.sessionID)
635
777
  return text("skipped")
636
778
  }
637
- const content = (input.content ?? "").trim()
638
- if (!content) {
779
+ // 模型偶尔不听话写 markdown,剥成纯文本再发出去。
780
+ const plains = toStringList(input.content)
781
+ .map((item) => toPlainText(item).trim())
782
+ .filter((item) => item.length > 0)
783
+ if (plains.length === 0) {
639
784
  logger.info(`${label} 回复内容为空`)
640
785
  manager.markMessageSent(context.sessionID)
641
786
  return text("skipped")
642
787
  }
643
788
 
644
- // 模型偶尔不听话写 markdown,剥成纯文本再发出去。
645
- const plain = toPlainText(content).trim()
646
- if (!plain) {
647
- logger.info(`${label} 回复内容剥离后为空`)
648
- manager.markMessageSent(context.sessionID)
649
- return text("skipped")
650
- }
651
789
  const denied = checkReplyPermission(context.sessionID, target)
652
790
  if (denied) return text(denied)
653
- guardOutbound(target, plain)
791
+ // 整批先过出站检查:有一条命中敏感信息就整批不发。
792
+ for (const plain of plains) guardOutbound(target, plain)
654
793
 
655
794
  // 长度按字素簇算,和拆段的口径一致:一个 emoji 只算一个。
656
- const length = splitGraphemes(plain).length
657
- if (length > config.warnLength && input.unlimit_length !== true) {
658
- logger.warn(`send_message 内容长度 ${length} 超过 ${config.warnLength}`)
795
+ const chars = plains.reduce((sum, plain) => sum + splitGraphemes(plain).length, 0)
796
+ for (const plain of plains) {
797
+ const length = splitGraphemes(plain).length
798
+ if (length > config.warnLength && input.unlimit_length !== true) {
799
+ logger.warn(`send_message 内容长度 ${length} 超过 ${config.warnLength}`)
800
+ }
659
801
  }
660
802
 
661
803
  const operation = nextOperation()
662
804
  // 太长的回复改成合并转发,别一口气刷屏。
663
805
  const forwardThreshold = config.reply.forwardThresholdChars
664
- if (forwardThreshold > 0 && length > forwardThreshold) {
665
- return await sendAsForward(context.sessionID, target, plain, operation, length)
806
+ const messages: Outgoing[] = []
807
+ for (const plain of plains) {
808
+ const length = splitGraphemes(plain).length
809
+ if (forwardThreshold > 0 && length > forwardThreshold) {
810
+ messages.push({ kind: "forward", nodes: await buildForwardNodes(plain) })
811
+ continue
812
+ }
813
+ // 单条超过配置的字数就拆成多段发。
814
+ for (const chunk of splitMessage(plain, config.reply.segmentChars)) {
815
+ messages.push({ kind: "text", text: chunk })
816
+ }
666
817
  }
667
-
668
- // 单段超过配置的字数就拆成多段发。
669
- const chunks = splitMessage(plain, config.reply.segmentChars)
670
- // 剩余额度不够分段时,宁可合并转发一条,也不要把回复截成半截。
671
- if (forwardThreshold > 0 && chunks.length > limiter.remaining(modelSendScope(target))) {
672
- return await sendAsForward(context.sessionID, target, plain, operation, length)
818
+ // 剩余额度不够时,宁可把整批合成一条合并转发,也不要把回复截成半截。
819
+ if (forwardThreshold > 0 && messages.length > limiter.remaining(modelSendScope(target))) {
820
+ const nodes: ForwardNode[] = []
821
+ for (const plain of plains) nodes.push(...(await buildForwardNodes(plain)))
822
+ messages.length = 0
823
+ messages.push({ kind: "forward", nodes })
673
824
  }
674
- // 段与段之间的间隔:配了随机区间就在区间里等。
675
- const wait = segmentDelayMs({
676
- sendDelayMs: config.sendDelayMs,
677
- minDelayMs: config.reply.minDelayMs,
678
- maxDelayMs: config.reply.maxDelayMs,
825
+ return await sendOutgoing(context.sessionID, target, operation, {
826
+ messages,
827
+ wording: { noun: "消息", unit: "条" },
828
+ successText: sentMessageText,
829
+ chars,
679
830
  })
680
- let sent = 0
681
- try {
682
- for (const [index, chunk] of chunks.entries()) {
683
- const verdict = await permit(target, operation)
684
- if (!verdict.allowed) return refuse(context.sessionID, verdict, sent, chunks.length)
685
- const response = await send(target, chunk)
686
- trackSent(target, response)
687
- sent += 1
688
- if (index < chunks.length - 1 && wait > 0) {
689
- await delay(wait)
690
- }
691
- }
692
- } catch (error) {
693
- if (sent > 0) manager.markMessageSent(context.sessionID)
694
- logger.error(`${label} 发送消息失败,已发送 ${sent}/${chunks.length} 段`, error)
695
- // 已经发出部分段落时不要允许整条重试,否则会重复发送。
696
- return text(`error: 消息只发送了 ${sent}/${chunks.length} 段`, { retryable: sent === 0 })
697
- }
698
- manager.markMessageSent(context.sessionID)
699
- logger.info(`${label} 已发送 ${length} 字`, traceMeta(context.sessionID))
700
- await traceSent(context.sessionID, target, { chars: length, mode: "plain", segments: sent })
701
- return text("你已成功发送消息,可以选择结束对话")
702
831
  },
703
832
  })
704
833
 
705
834
  editor.add({
706
835
  name: "send_image",
707
836
  description:
708
- "向当前 QQ 群聊或私聊发送一张图片。file 可以是本地路径或 http(s) 图片地址;base64 传 base64:// 形式的数据。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
837
+ "向当前 QQ 群聊或私聊发送图片。file 是图片来源列表(本地路径或 http(s) 地址),base64 是 base64 数据列表;两个列表合成一批图片,一条一个。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
709
838
  input: {
710
839
  type: "object",
711
840
  properties: {
712
- file: { type: "string", description: "本地文件路径或图片 URL" },
713
- base64: { type: "string", description: "base64 编码的图片数据" },
841
+ file: {
842
+ type: "array",
843
+ description: "本地文件路径或图片 URL 列表,一条一个",
844
+ items: { type: "string" },
845
+ },
846
+ base64: {
847
+ type: "array",
848
+ description: "base64 编码的图片数据列表,一条一个",
849
+ items: { type: "string" },
850
+ },
714
851
  },
715
852
  additionalProperties: false,
716
853
  },
@@ -722,21 +859,30 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
722
859
  const target = prepared.target
723
860
  const denied = checkReplyPermission(context.sessionID, target)
724
861
  if (denied) return text(denied)
725
- const file = input.file ?? (input.base64 ? `base64://${input.base64}` : undefined)
726
- if (!file) return text("error: 缺少 file 或 base64")
727
- const tooLarge = checkInlineSize(file, "图片")
728
- if (tooLarge) return text(tooLarge)
729
- if (!isInlineData(file)) guardOutbound(target, file)
730
- // 路径白名单在这里就判定:不过就不占发送额度。内联数据不涉及路径与网络。
862
+ const sources = [
863
+ ...toStringList(input.file),
864
+ ...toStringList(input.base64).map((value) =>
865
+ isInlineData(value) ? value : `base64://${value}`,
866
+ ),
867
+ ]
868
+ if (sources.length === 0) return text("error: 缺少 file 或 base64")
869
+ // 整批先校验:一条不过关就整批不发。
731
870
  const mediaCheck = mediaFor(context.sessionID)
732
- const plan = isInlineData(file) ? undefined : await mediaCheck.check(file)
733
- const verdict = await permit(target, nextOperation())
734
- if (!verdict.allowed) return refuse(context.sessionID, verdict)
735
- const media = plan ? mediaCheck.materialize(plan) : file
736
- const response = await send(target, [{ type: "image", data: { file: media } }])
737
- trackSent(target, response)
738
- manager.markMessageSent(context.sessionID)
739
- return text("你已成功发送图片,可以选择结束对话")
871
+ const payloads: unknown[][] = []
872
+ for (const source of sources) {
873
+ const tooLarge = checkInlineSize(source, "图片")
874
+ if (tooLarge) return text(tooLarge)
875
+ if (!isInlineData(source)) guardOutbound(target, source)
876
+ // 路径白名单在这里就判定:不过就不占发送额度。内联数据不涉及路径与网络。
877
+ const plan = isInlineData(source) ? undefined : await mediaCheck.check(source)
878
+ const media = plan ? mediaCheck.materialize(plan) : source
879
+ payloads.push([{ type: "image", data: { file: media } }])
880
+ }
881
+ return await sendOutgoing(context.sessionID, target, nextOperation(), {
882
+ messages: payloads.map((payload) => ({ kind: "segments", payload })),
883
+ wording: { noun: "图片", unit: "张" },
884
+ successText: sentImageText,
885
+ })
740
886
  },
741
887
  })
742
888
 
@@ -813,11 +959,15 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
813
959
  editor.add({
814
960
  name: "send_sticker",
815
961
  description:
816
- "发送一张收藏表情(表情包)。id 是收藏表情编号,先用 qq_favorite_list 查看编号与标签的对应关系。",
962
+ "发送收藏表情(表情包)。id 是收藏表情编号列表,一条编号发一张;先用 qq_favorite_list 查看编号与标签的对应关系。",
817
963
  input: {
818
964
  type: "object",
819
965
  properties: {
820
- id: { type: "number", description: "收藏表情编号" },
966
+ id: {
967
+ type: "array",
968
+ description: "收藏表情编号列表,一条编号发一张",
969
+ items: { type: "number" },
970
+ },
821
971
  },
822
972
  required: ["id"],
823
973
  additionalProperties: false,
@@ -830,46 +980,59 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
830
980
  const target = prepared.target
831
981
  const denied = checkReplyPermission(context.sessionID, target)
832
982
  if (denied) return text(denied)
833
- const id = input.id
834
- if (typeof id !== "number" || !Number.isInteger(id)) {
983
+ const ids = toNumberList(input.id)
984
+ if (ids.length === 0) {
835
985
  return text("error: 缺少 id(收藏表情编号)")
836
986
  }
837
987
  const faces = await favorites.list()
838
988
  const rows = await favoriteIndex.sync(faces, await collection.list())
839
- const row = rows.find((item) => item.id === id)
840
- if (!row) {
841
- return text(`error: 没有找到编号 ${id} 的收藏表情,可用编号:${formatFavoriteIds(rows)}`)
842
- }
843
- const url = typeof row.face.url === "string" ? row.face.url : undefined
844
- if (!url) return text(`error: 编号 ${id} 的收藏表情缺少可用地址`)
845
- guardOutbound(target, url)
846
- // 收藏表情的地址同样来自外部,要走和图片一致的路径与地址白名单。
847
- let plan
848
- try {
849
- plan = await outbound.check(url)
850
- } catch (error) {
851
- return text(`error: ${error instanceof Error ? error.message : String(error)}`)
989
+ // 整批先校验:编号有一个对不上就整批不发。
990
+ const stickers: { id: number; tag: string; payload: unknown[] }[] = []
991
+ for (const id of ids) {
992
+ const row = rows.find((item) => item.id === id)
993
+ if (!row) {
994
+ return text(
995
+ `error: 没有找到编号 ${id} 的收藏表情,可用编号:${formatFavoriteIds(rows)}`,
996
+ )
997
+ }
998
+ const url = typeof row.face.url === "string" ? row.face.url : undefined
999
+ if (!url) return text(`error: 编号 ${id} 的收藏表情缺少可用地址`)
1000
+ guardOutbound(target, url)
1001
+ // 收藏表情的地址同样来自外部,要走和图片一致的路径与地址白名单。
1002
+ let plan
1003
+ try {
1004
+ plan = await outbound.check(url)
1005
+ } catch (error) {
1006
+ return text(`error: ${error instanceof Error ? error.message : String(error)}`)
1007
+ }
1008
+ // QQ 收藏表情带 sub_type=1(KCUSTOM);本机收集的表情不在 QQ 收藏里,按普通图片发。
1009
+ const data: { file: string; sub_type?: number } = { file: outbound.materialize(plan) }
1010
+ if (!row.collected) data.sub_type = CUSTOM_FACE_SUB_TYPE
1011
+ stickers.push({ id, tag: row.tag || "未标注", payload: [{ type: "image", data }] })
852
1012
  }
853
- const verdict = await permit(target, nextOperation())
854
- if (!verdict.allowed) return refuse(context.sessionID, verdict)
855
- // QQ 收藏表情带 sub_type=1(KCUSTOM);本机收集的表情不在 QQ 收藏里,按普通图片发。
856
- const data: { file: string; sub_type?: number } = { file: outbound.materialize(plan) }
857
- if (!row.collected) data.sub_type = CUSTOM_FACE_SUB_TYPE
858
- const response = await send(target, [{ type: "image", data }])
859
- trackSent(target, response)
860
- manager.markMessageSent(context.sessionID)
861
- return text(`你已成功发送收藏表情 ${id}「${row.tag || "未标注"}」,可以选择结束对话`)
1013
+ return await sendOutgoing(context.sessionID, target, nextOperation(), {
1014
+ messages: stickers.map((sticker) => ({ kind: "segments", payload: sticker.payload })),
1015
+ wording: { noun: "收藏表情", unit: "个" },
1016
+ successText: (count) =>
1017
+ count === 1
1018
+ ? `你已成功发送收藏表情 ${stickers[0]?.id}「${stickers[0]?.tag}」,可以选择结束对话`
1019
+ : `你已成功发送 ${count} 个收藏表情,可以选择结束对话`,
1020
+ })
862
1021
  },
863
1022
  })
864
1023
 
865
1024
  editor.add({
866
1025
  name: "send_record",
867
1026
  description:
868
- "向当前 QQ 群聊或私聊发送一条语音。file 可以是本地路径或 http(s) 音频地址。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
1027
+ "向当前 QQ 群聊或私聊发送语音。file 是语音来源列表(本地路径、http(s) 音频地址或 base64:// 数据),一条一个。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录;http(s) 地址只允许公网地址。",
869
1028
  input: {
870
1029
  type: "object",
871
1030
  properties: {
872
- file: { type: "string", description: "本地文件路径或音频 URL" },
1031
+ file: {
1032
+ type: "array",
1033
+ description: "本地文件路径、音频 URL 或 base64:// 数据列表,一条一个",
1034
+ items: { type: "string" },
1035
+ },
873
1036
  },
874
1037
  additionalProperties: false,
875
1038
  },
@@ -881,19 +1044,24 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
881
1044
  const target = prepared.target
882
1045
  const denied = checkReplyPermission(context.sessionID, target)
883
1046
  if (denied) return text(denied)
884
- if (!input.file) return text("error: 缺少 file")
885
- const tooLarge = checkInlineSize(input.file, "语音")
886
- if (tooLarge) return text(tooLarge)
887
- if (!isInlineData(input.file)) guardOutbound(target, input.file)
1047
+ const sources = toStringList(input.file)
1048
+ if (sources.length === 0) return text("error: 缺少 file")
1049
+ // 整批先校验:一条不过关就整批不发。
888
1050
  const mediaCheck = mediaFor(context.sessionID)
889
- const plan = isInlineData(input.file) ? undefined : await mediaCheck.check(input.file)
890
- const verdict = await permit(target, nextOperation())
891
- if (!verdict.allowed) return refuse(context.sessionID, verdict)
892
- const media = plan ? mediaCheck.materialize(plan) : input.file
893
- const response = await send(target, [{ type: "record", data: { file: media } }])
894
- trackSent(target, response)
895
- manager.markMessageSent(context.sessionID)
896
- return text("你已成功发送语音,可以选择结束对话")
1051
+ const payloads: unknown[][] = []
1052
+ for (const source of sources) {
1053
+ const tooLarge = checkInlineSize(source, "语音")
1054
+ if (tooLarge) return text(tooLarge)
1055
+ if (!isInlineData(source)) guardOutbound(target, source)
1056
+ const plan = isInlineData(source) ? undefined : await mediaCheck.check(source)
1057
+ const media = plan ? mediaCheck.materialize(plan) : source
1058
+ payloads.push([{ type: "record", data: { file: media } }])
1059
+ }
1060
+ return await sendOutgoing(context.sessionID, target, nextOperation(), {
1061
+ messages: payloads.map((payload) => ({ kind: "segments", payload })),
1062
+ wording: { noun: "语音", unit: "条" },
1063
+ successText: sentRecordText,
1064
+ })
897
1065
  },
898
1066
  })
899
1067
 
@@ -929,11 +1097,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
929
1097
  const denied = checkReplyPermission(context.sessionID, target)
930
1098
  if (denied) return text(denied)
931
1099
  const identity = await botIdentity()
932
- const nodes: {
933
- user_id: number
934
- nickname: string
935
- content: { type: string; data: { text: string } }[]
936
- }[] = []
1100
+ const nodes: ForwardNode[] = []
937
1101
  for (const node of input.nodes ?? []) {
938
1102
  const body = toPlainText(node.content ?? "").trim()
939
1103
  // 合并转发里每段都要扫:昵称由插件固定,模型只能控制正文。
@@ -1205,12 +1369,20 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1205
1369
  editor.add({
1206
1370
  name: "send_file",
1207
1371
  description:
1208
- "向当前 QQ 群聊或私聊发送一个本地文件。file 是文件路径,只能是机器人允许发送的目录里的普通文件;owner/admin 可用工作目录、媒体目录和配置放开的目录,普通成员只能用媒体目录;name 是对方看到的文件名,省略时用原文件名。",
1372
+ "向当前 QQ 群聊或私聊发送本地文件。file 是文件路径列表,只能是机器人允许发送的目录里的普通文件;name 是对方看到的文件名列表,与 file 一一对应,省略时用原文件名。本地路径:owner/admin 可取工作目录、媒体目录和配置放开的目录,普通成员只能取媒体目录。",
1209
1373
  input: {
1210
1374
  type: "object",
1211
1375
  properties: {
1212
- file: { type: "string", description: "本地文件路径(必填)" },
1213
- name: { type: "string", description: "对方看到的文件名;省略时用原文件名" },
1376
+ file: {
1377
+ type: "array",
1378
+ description: "本地文件路径列表(必填),一条一个",
1379
+ items: { type: "string" },
1380
+ },
1381
+ name: {
1382
+ type: "array",
1383
+ description: "对方看到的文件名列表,与 file 一一对应;省略时用原文件名",
1384
+ items: { type: "string" },
1385
+ },
1214
1386
  },
1215
1387
  required: ["file"],
1216
1388
  additionalProperties: false,
@@ -1223,25 +1395,31 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
1223
1395
  const target = prepared.target
1224
1396
  const denied = checkReplyPermission(context.sessionID, target)
1225
1397
  if (denied) return text(denied)
1226
- const file = input.file?.trim()
1227
- if (!file) return text("error: 缺少 file")
1228
- let plan
1229
- try {
1230
- plan = await mediaFor(context.sessionID).check(file)
1231
- } catch (error) {
1232
- return text(`error: ${error instanceof Error ? error.message : String(error)}`)
1398
+ const files = toStringList(input.file)
1399
+ if (files.length === 0) return text("error: 缺少 file")
1400
+ const names = toStringSlots(input.name)
1401
+ const mediaCheck = mediaFor(context.sessionID)
1402
+ // 整批先校验:一条不过关就整批不发。
1403
+ const payloads: unknown[][] = []
1404
+ for (const [index, file] of files.entries()) {
1405
+ let plan
1406
+ try {
1407
+ plan = await mediaCheck.check(file)
1408
+ } catch (error) {
1409
+ return text(`error: ${error instanceof Error ? error.message : String(error)}`)
1410
+ }
1411
+ if (plan.kind !== "local") return text("error: 只能发送本地文件")
1412
+ const path = plan.path
1413
+ const name = names[index] || basename(path)
1414
+ // 文件内容没法扫描,路径与显示名同样过一遍出站检查。
1415
+ guardOutbound(target, `${name}\n${path}`)
1416
+ payloads.push([{ type: "file", data: { file: path, name } }])
1233
1417
  }
1234
- if (plan.kind !== "local") return text("error: 只能发送本地文件")
1235
- const path = plan.path
1236
- const name = input.name?.trim() || basename(path)
1237
- // 文件内容没法扫描,路径与显示名同样过一遍出站检查。
1238
- guardOutbound(target, `${name}\n${path}`)
1239
- const verdict = await permit(target, nextOperation())
1240
- if (!verdict.allowed) return refuse(context.sessionID, verdict)
1241
- const response = await send(target, [{ type: "file", data: { file: path, name } }])
1242
- trackSent(target, response)
1243
- manager.markMessageSent(context.sessionID)
1244
- return text("你已成功发送文件,可以选择结束对话")
1418
+ return await sendOutgoing(context.sessionID, target, nextOperation(), {
1419
+ messages: payloads.map((payload) => ({ kind: "segments", payload })),
1420
+ wording: { noun: "文件", unit: "个" },
1421
+ successText: sentFileText,
1422
+ })
1245
1423
  },
1246
1424
  })
1247
1425
  })