@linjz/opencode-qqbot 0.3.12 → 0.3.14

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.
Files changed (46) hide show
  1. package/README.md +12 -7
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +4 -4
  5. package/dist/openqq-bot.js +1072 -208
  6. package/package.json +2 -2
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +141 -15
  9. package/src/commands.ts +554 -554
  10. package/src/config.ts +118 -121
  11. package/src/core/bot-launcher.ts +146 -146
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +115 -18
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -33
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +388 -72
  19. package/src/core/form-journal.ts +214 -0
  20. package/src/core/gateway-state.ts +68 -0
  21. package/src/core/inbound-dedupe.ts +43 -0
  22. package/src/core/inflight-journal.ts +170 -22
  23. package/src/core/instance-lock.ts +28 -1
  24. package/src/core/linkwatch.ts +195 -195
  25. package/src/core/message-queue.ts +11 -0
  26. package/src/core/mirror.ts +182 -182
  27. package/src/core/outbox.ts +522 -0
  28. package/src/core/permission.ts +301 -301
  29. package/src/core/reply-limiter.ts +106 -106
  30. package/src/core/send-media.ts +90 -90
  31. package/src/core/util.ts +8 -8
  32. package/src/index.ts +162 -162
  33. package/src/opencode/_FOLDER.md +11 -11
  34. package/src/opencode/client.ts +98 -13
  35. package/src/opencode/eventstream.ts +138 -138
  36. package/src/opencode/history.ts +143 -143
  37. package/src/opencode/mirror.ts +85 -85
  38. package/src/opencode/sessions.ts +158 -158
  39. package/src/plugin-entry.ts +112 -112
  40. package/src/qq/_FOLDER.md +13 -13
  41. package/src/qq/api.ts +546 -539
  42. package/src/qq/gateway.ts +69 -20
  43. package/src/qq/media.ts +219 -219
  44. package/src/qq/sender.ts +303 -300
  45. package/src/qq/types.ts +154 -154
  46. package/tsconfig.json +24 -24
package/src/qq/sender.ts CHANGED
@@ -1,300 +1,303 @@
1
- // @input: ./api (sendC2CMessage, sendGroupMessage), ./types (MessageContext)
2
- // @output: replyToQQ, formatForQQ, formatForQQMarkdown, splitMessage
3
- // @pos: qq层 - 消息发送 (Markdown格式化 + 分割 + 被动回复)
4
- //
5
- // QQ 机器人自定义 Markdown(msg_type=2)已对单聊/群聊全量开放,无需模板。
6
- // QQ markdown 能完整渲染标准语法: 表格、行内代码/代码块、加粗、标题、列表、链接、引用等。
7
- // 因此主路径直接透传 AI 的 markdown 原文,交给 QQ 渲染;仅在发送失败时回退纯文本。
8
- import { sendC2CMessage, sendGroupMessage, getNextMsgSeq, type MessageResponse } from "./api.js"
9
- import type { MessageContext } from "./types.js"
10
-
11
- const DEFAULT_MAX_LENGTH = 3000
12
-
13
- // Markdown 主路径: QQ 原生渲染标准 markdown(含表格/代码),故基本透传,仅做首尾清理。
14
- export function formatForQQMarkdown(text: string): string {
15
- return text.trim()
16
- }
17
-
18
- // 纯文本兜底: 去除所有 markdown 标记(当 markdown 发送失败时使用)
19
- export function formatForQQ(text: string): string {
20
- const codeBlocks: string[] = []
21
-
22
- // 保护围栏代码块,用占位符替换;同时去掉 ```lang 语言标签
23
- let processed = text.replace(/```[^\n]*\n([\s\S]*?)```/g, (_m, code: string) => {
24
- codeBlocks.push(code.replace(/\n$/, ""))
25
- return `\x00CB${codeBlocks.length - 1}\x00`
26
- })
27
-
28
- // 处理表格: 转成 "表头 | 表头" 与 "值 | 值" 的纯文本,去掉分隔行 |---|---|
29
- processed = convertTables(processed)
30
-
31
- // 去除 markdown 标记
32
- processed = processed
33
- .replace(/`([^`]+)`/g, "$1") // `inline code` -> inline code
34
- .replace(/\*\*(.+?)\*\*/g, "$1") // **bold** -> bold
35
- .replace(/\*(.+?)\*/g, "$1") // *italic* -> italic
36
- .replace(/__(.+?)__/g, "$1") // __underline__ -> underline
37
- .replace(/~~(.+?)~~/g, "$1") // ~~strike~~ -> strike
38
- .replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1 ($2)") // [text](url) -> text (url)
39
- .replace(/^#{1,6}\s+/gm, "") // ### heading -> heading
40
- .replace(/^>\s?/gm, "") // > quote -> quote
41
- .replace(/^\s*[-*+]\s+/gm, "• ") // - item -> • item
42
- .replace(/^---$/gm, "----------") // --- -> ----------
43
-
44
- // 还原代码块
45
- for (let i = 0; i < codeBlocks.length; i++) {
46
- processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i])
47
- }
48
-
49
- return processed.trim()
50
- }
51
-
52
- // 把 markdown 表格转成 QQ 可读的纯文本(列用 " | " 连接,丢弃 |---| 分隔行)
53
- function convertTables(text: string): string {
54
- const lines = text.split("\n")
55
- const out: string[] = []
56
- let i = 0
57
-
58
- while (i < lines.length) {
59
- const line = lines[i]
60
- // 表格行: 以 | 开头结尾,且含分隔符
61
- if (/^\s*\|.*\|\s*$/.test(line)) {
62
- const rows: string[][] = []
63
- while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) {
64
- const cells = lines[i].trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim())
65
- rows.push(cells)
66
- i++
67
- }
68
- // 丢弃分隔行(形如 |---|:---:|)
69
- const realRows = rows.filter((r) => !r.every((c) => /^:?-{2,}:?$/.test(c)))
70
- for (const r of realRows) {
71
- out.push(r.join(" | "))
72
- }
73
- out.push("") // 表格后空一行
74
- continue
75
- }
76
- out.push(line)
77
- i++
78
- }
79
-
80
- return out.join("\n")
81
- }
82
-
83
- // QQ markdown 消息 content 上限约 2000 字节(中文=3字节/字),留余量取 1800 字节。
84
- // 注意:必须按 UTF-8 字节切分,不能按字符数——否则中文长消息会超限被 QQ 丢弃(不渲染)。
85
- const MARKDOWN_MAX_BYTES = 1800
86
- const PLAIN_MAX_BYTES = 1900
87
- const encoder = new TextEncoder()
88
-
89
- function utf8Bytes(s: string): number {
90
- return encoder.encode(s).length
91
- }
92
-
93
- // —— 结构化分条(2026-10-29 固化:设计吸收自 dsh-qqbot transport/chunker.ts,P0)——
94
- // dsh 语义:GFM 表格聚成原子单元不跨片拆散 + 按行边界打包;
95
- // 我方在 dsh 之上补两件事:① 字节预算(QQ 按 UTF-8 字节限长,dsh 按字符数会
96
- // 踩中文 3 字节坑)② 围栏修补——在代码块中间切断时给前片补闭合 ```、后片补
97
- // 开围栏(带语言),保证每片 markdown 独立可渲染。
98
- const GFM_TABLE_LINE = /^\s*\|.*\|\s*$/
99
- const CODE_FENCE_OPEN = /^\s*```(\S*)/
100
-
101
- interface LineUnit {
102
- /** 行原文(含结尾 \n,全文末行除外) */
103
- text: string
104
- bytes: number
105
- /** 本行是围栏行时记录语言,否则 null */
106
- fenceLang: string | null
107
- }
108
-
109
- function toLineUnits(text: string): LineUnit[] {
110
- const rawLines = text.split("\n")
111
- const units: LineUnit[] = []
112
- let tableBuf: string[] = []
113
- const flushTable = (isLast: boolean): void => {
114
- if (tableBuf.length === 0) return
115
- const body = tableBuf.join("\n") + (isLast ? "" : "\n")
116
- units.push({ text: body, bytes: utf8Bytes(body), fenceLang: null })
117
- tableBuf = []
118
- }
119
-
120
- rawLines.forEach((line, idx) => {
121
- const isLast = idx === rawLines.length - 1
122
- if (GFM_TABLE_LINE.test(line)) {
123
- tableBuf.push(line)
124
- if (isLast) flushTable(true)
125
- return
126
- }
127
- flushTable(isLast)
128
- const fence = CODE_FENCE_OPEN.exec(line)
129
- const body = line + (isLast ? "" : "\n")
130
- units.push({ text: body, bytes: utf8Bytes(body), fenceLang: fence ? fence[1] : null })
131
- })
132
- return units
133
- }
134
-
135
- // 超大单元(巨型表格行/无换行长行)的字节级兜底切分:
136
- // 优先段落(\n\n)、其次换行(\n)、最后码点边界硬切(不切多字节字符/代理对)。
137
- function splitOversizeUnit(text: string, maxBytes: number): string[] {
138
- const chunks: string[] = []
139
- const total = text.length
140
- let start = 0
141
-
142
- while (start < total) {
143
- if (utf8Bytes(text.slice(start)) <= maxBytes) {
144
- chunks.push(text.slice(start))
145
- break
146
- }
147
- let bytes = 0
148
- let i = start
149
- let lastParaBreak = -1
150
- let lastLineBreak = -1
151
- let hardCut = -1
152
-
153
- while (i < total) {
154
- const cp = text.codePointAt(i)!
155
- const cpStr = String.fromCodePoint(cp)
156
- const cpBytes = utf8Bytes(cpStr)
157
- if (bytes + cpBytes > maxBytes) break
158
- bytes += cpBytes
159
- i += cpStr.length
160
- hardCut = i
161
- if (cp === 0x0a) {
162
- if (i - 2 >= start && text[i - 2] === "\n") lastParaBreak = i
163
- else lastLineBreak = i
164
- }
165
- }
166
-
167
- let splitAt = lastParaBreak > start ? lastParaBreak : lastLineBreak > start ? lastLineBreak : hardCut
168
- if (splitAt <= start) splitAt = hardCut
169
- if (splitAt <= start) splitAt = Math.min(start + 1, total)
170
-
171
- const chunk = text.slice(start, splitAt)
172
- if (chunk.trim()) chunks.push(chunk)
173
- start = splitAt
174
- }
175
- return chunks
176
- }
177
-
178
- export function splitMessage(text: string, maxBytes: number = MARKDOWN_MAX_BYTES): string[] {
179
- if (utf8Bytes(text) <= maxBytes) return [text]
180
-
181
- const units = toLineUnits(text)
182
- const chunks: string[] = []
183
- let cur = ""
184
- let curBytes = 0
185
- let prefix = "" // 围栏内切断时,下一片需补的开围栏(带语言)
186
- let openLang: string | null = null // 原文全局围栏状态(跨片跟踪)
187
-
188
- const flush = (): void => {
189
- const body = cur
190
- cur = ""
191
- curBytes = 0
192
- const inside = openLang !== null
193
- const out = prefix + body + (inside ? (body.endsWith("\n") ? "```\n" : "\n```\n") : "")
194
- prefix = inside ? `\`\`\`${openLang}\n` : ""
195
- if (out.trim()) chunks.push(out)
196
- }
197
-
198
- for (const u of units) {
199
- if (u.bytes > maxBytes) {
200
- // 超大单元:先封当前片,再字节级兜底切(围栏行本身不可能超大,不参与围栏语义)
201
- if (cur) flush()
202
- const parts = splitOversizeUnit(u.text, maxBytes)
203
- for (let k = 0; k < parts.length - 1; k++) chunks.push(parts[k])
204
- cur = parts[parts.length - 1] ?? ""
205
- curBytes = utf8Bytes(cur)
206
- continue
207
- }
208
- const prefixBytes = prefix ? utf8Bytes(prefix) : 0
209
- if (cur && curBytes + prefixBytes + u.bytes > maxBytes) {
210
- flush()
211
- }
212
- cur += u.text
213
- curBytes += u.bytes
214
- if (u.fenceLang !== null) {
215
- openLang = openLang === null ? u.fenceLang : null
216
- }
217
- }
218
- flush()
219
-
220
- return chunks.length > 0 ? chunks : [text]
221
- }
222
-
223
- // J-轻(2026-10-30,伪流式固化):多片错峰发送的延迟计划——片间各睡 staggerMs,
224
- // 单片无延迟。纯函数导出供测试。
225
- export function staggerDelays(chunkCount: number, staggerMs: number): number[] {
226
- if (chunkCount <= 1 || staggerMs <= 0) return []
227
- return Array.from({ length: chunkCount - 1 }, () => staggerMs)
228
- }
229
-
230
- function sleep(ms: number): Promise<void> {
231
- return new Promise((resolve) => setTimeout(resolve, ms))
232
- }
233
-
234
- // 发送单个分片: 先尝试 markdown,失败则回退纯文本。返回服务端消息回执(含 id,
235
- // 供上下文缓存登记——引用解析用)。
236
- async function sendChunk(
237
- accessToken: string,
238
- ctx: MessageContext,
239
- mdText: string,
240
- plainText: string,
241
- msgSeq: number,
242
- ): Promise<MessageResponse | null> {
243
- const isGroup = ctx.type === "group" && ctx.groupId
244
-
245
- try {
246
- if (isGroup) {
247
- return await sendGroupMessage(accessToken, ctx.groupId!, mdText, ctx.msgId, msgSeq, true)
248
- } else {
249
- return await sendC2CMessage(accessToken, ctx.userId, mdText, ctx.msgId, msgSeq, true)
250
- }
251
- } catch (error) {
252
- // markdown 发送失败(如语法不被接受/内容违规)-> 回退纯文本
253
- console.error("[qq-sender] markdown 发送失败,回退纯文本:", error)
254
- }
255
-
256
- if (isGroup) {
257
- return await sendGroupMessage(accessToken, ctx.groupId!, plainText, ctx.msgId, msgSeq, false)
258
- } else {
259
- return await sendC2CMessage(accessToken, ctx.userId, plainText, ctx.msgId, msgSeq, false)
260
- }
261
- }
262
-
263
- export interface ReplyToQQOptions {
264
- /** J-轻(2026-10-30):伪流式错峰——多片发送时片间间隔 ms(默认 0=一次性全发) */
265
- staggerMs?: number
266
- }
267
-
268
- export interface ReplyResult {
269
- chunks: number
270
- /** 服务端回执的消息 id(引用解析缓存登记用) */
271
- ids: string[]
272
- }
273
-
274
- export async function replyToQQ(
275
- accessToken: string,
276
- ctx: MessageContext,
277
- text: string,
278
- _maxLength: number = DEFAULT_MAX_LENGTH,
279
- options?: ReplyToQQOptions,
280
- ): Promise<ReplyResult> {
281
- const mdFormatted = formatForQQMarkdown(text)
282
- const plainFormatted = formatForQQ(text)
283
-
284
- // 关键:按 UTF-8 字节切分(QQ markdown 上限约 2000 字节),不能用字符数 maxLength,
285
- // 否则中文长消息会超限被 QQ 静默丢弃(看似"答非所问",实则是答案没发出去)。
286
- const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES)
287
- const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES)
288
-
289
- const delays = staggerDelays(mdChunks.length, options?.staggerMs ?? 0)
290
- const ids: string[] = []
291
- for (let i = 0; i < mdChunks.length; i++) {
292
- if (i > 0 && delays[i - 1]) await sleep(delays[i - 1])
293
- const msgSeq = getNextMsgSeq(ctx.msgId)
294
- // 纯文本分片可能与 markdown 分片数量不一致,按索引兜底取对应/最后一片
295
- const plainChunk = plainChunks[i] ?? plainChunks[plainChunks.length - 1] ?? mdChunks[i]
296
- const res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq)
297
- if (res?.id) ids.push(res.id)
298
- }
299
- return { chunks: mdChunks.length, ids }
300
- }
1
+ // @input: ./api (sendC2CMessage, sendGroupMessage), ./types (MessageContext)
2
+ // @output: replyToQQ, formatForQQ, formatForQQMarkdown, splitMessage
3
+ // @pos: qq层 - 消息发送 (Markdown格式化 + 分割 + 被动回复)
4
+ //
5
+ // QQ 机器人自定义 Markdown(msg_type=2)已对单聊/群聊全量开放,无需模板。
6
+ // QQ markdown 能完整渲染标准语法: 表格、行内代码/代码块、加粗、标题、列表、链接、引用等。
7
+ // 因此主路径直接透传 AI 的 markdown 原文,交给 QQ 渲染;仅在发送失败时回退纯文本。
8
+ import { sendC2CMessage, sendGroupMessage, getNextMsgSeq, type MessageResponse } from "./api.js"
9
+ import type { MessageContext } from "./types.js"
10
+
11
+ // Markdown 主路径: QQ 原生渲染标准 markdown(含表格/代码),故基本透传,仅做首尾清理。
12
+ export function formatForQQMarkdown(text: string): string {
13
+ return text.trim()
14
+ }
15
+
16
+ // 纯文本兜底: 去除所有 markdown 标记(当 markdown 发送失败时使用)
17
+ export function formatForQQ(text: string): string {
18
+ const codeBlocks: string[] = []
19
+
20
+ // 保护围栏代码块,用占位符替换;同时去掉 ```lang 语言标签
21
+ let processed = text.replace(/```[^\n]*\n([\s\S]*?)```/g, (_m, code: string) => {
22
+ codeBlocks.push(code.replace(/\n$/, ""))
23
+ return `\x00CB${codeBlocks.length - 1}\x00`
24
+ })
25
+
26
+ // 处理表格: 转成 "表头 | 表头" 与 "值 | 值" 的纯文本,去掉分隔行 |---|---|
27
+ processed = convertTables(processed)
28
+
29
+ // 去除 markdown 标记
30
+ processed = processed
31
+ .replace(/`([^`]+)`/g, "$1") // `inline code` -> inline code
32
+ .replace(/\*\*(.+?)\*\*/g, "$1") // **bold** -> bold
33
+ .replace(/\*(.+?)\*/g, "$1") // *italic* -> italic
34
+ .replace(/__(.+?)__/g, "$1") // __underline__ -> underline
35
+ .replace(/~~(.+?)~~/g, "$1") // ~~strike~~ -> strike
36
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1 ($2)") // [text](url) -> text (url)
37
+ .replace(/^#{1,6}\s+/gm, "") // ### heading -> heading
38
+ .replace(/^>\s?/gm, "") // > quote -> quote
39
+ .replace(/^\s*[-*+]\s+/gm, "• ") // - item -> • item
40
+ .replace(/^---$/gm, "----------") // --- -> ----------
41
+
42
+ // 还原代码块
43
+ for (let i = 0; i < codeBlocks.length; i++) {
44
+ processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i])
45
+ }
46
+
47
+ return processed.trim()
48
+ }
49
+
50
+ // 把 markdown 表格转成 QQ 可读的纯文本(列用 " | " 连接,丢弃 |---| 分隔行)
51
+ function convertTables(text: string): string {
52
+ const lines = text.split("\n")
53
+ const out: string[] = []
54
+ let i = 0
55
+
56
+ while (i < lines.length) {
57
+ const line = lines[i]
58
+ // 表格行: 以 | 开头结尾,且含分隔符
59
+ if (/^\s*\|.*\|\s*$/.test(line)) {
60
+ const rows: string[][] = []
61
+ while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) {
62
+ const cells = lines[i].trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim())
63
+ rows.push(cells)
64
+ i++
65
+ }
66
+ // 丢弃分隔行(形如 |---|:---:|)
67
+ const realRows = rows.filter((r) => !r.every((c) => /^:?-{2,}:?$/.test(c)))
68
+ for (const r of realRows) {
69
+ out.push(r.join(" | "))
70
+ }
71
+ out.push("") // 表格后空一行
72
+ continue
73
+ }
74
+ out.push(line)
75
+ i++
76
+ }
77
+
78
+ return out.join("\n")
79
+ }
80
+
81
+ // 分条字节上限(2026-11-03 探针实证修订,替换旧"约 2000 字节"经验值——该值无官方出处且被证伪):
82
+ // - 官方文档(bot.q.qq.com/wiki API v2,2026-10-28 版)未公布 content/markdown.content 数值上限,
83
+ // 仅错误码 40054007「消息长度超限」/40054018「消息过长或异常」证明服务端确有校验;
84
+ // - 本机探针(生产环境发真实消息):纯文本 8 万字/24 万字节、Markdown 60232 字节(2 万字+起止标识)
85
+ // 均 HTTP 200 受理,且 2 万字 Markdown 经用户确认 QQ 客户端完整渲染;
86
+ // - 故上限统一取 2 万字实测值 60232 字节(markdown=plain=60232);
87
+ // 分条逻辑(行边界/表格原子/围栏修补)保留,超 60232 字节仍分片。
88
+ // 注意:必须按 UTF-8 字节切分,不能按字符数——中文 3 字节/字,按字符预算会在字节维度失控。
89
+ const MARKDOWN_MAX_BYTES = 60232
90
+ const PLAIN_MAX_BYTES = 60232
91
+ const encoder = new TextEncoder()
92
+
93
+ function utf8Bytes(s: string): number {
94
+ return encoder.encode(s).length
95
+ }
96
+
97
+ // —— 结构化分条(2026-10-29 固化:设计吸收自 dsh-qqbot transport/chunker.ts,P0)——
98
+ // dsh 语义:GFM 表格聚成原子单元不跨片拆散 + 按行边界打包;
99
+ // 我方在 dsh 之上补两件事:① 字节预算(QQ 按 UTF-8 字节限长,dsh 按字符数会
100
+ // 踩中文 3 字节坑)② 围栏修补——在代码块中间切断时给前片补闭合 ```、后片补
101
+ // 开围栏(带语言),保证每片 markdown 独立可渲染。
102
+ const GFM_TABLE_LINE = /^\s*\|.*\|\s*$/
103
+ const CODE_FENCE_OPEN = /^\s*```(\S*)/
104
+
105
+ interface LineUnit {
106
+ /** 行原文(含结尾 \n,全文末行除外) */
107
+ text: string
108
+ bytes: number
109
+ /** 本行是围栏行时记录语言,否则 null */
110
+ fenceLang: string | null
111
+ }
112
+
113
+ function toLineUnits(text: string): LineUnit[] {
114
+ const rawLines = text.split("\n")
115
+ const units: LineUnit[] = []
116
+ let tableBuf: string[] = []
117
+ const flushTable = (isLast: boolean): void => {
118
+ if (tableBuf.length === 0) return
119
+ const body = tableBuf.join("\n") + (isLast ? "" : "\n")
120
+ units.push({ text: body, bytes: utf8Bytes(body), fenceLang: null })
121
+ tableBuf = []
122
+ }
123
+
124
+ rawLines.forEach((line, idx) => {
125
+ const isLast = idx === rawLines.length - 1
126
+ if (GFM_TABLE_LINE.test(line)) {
127
+ tableBuf.push(line)
128
+ if (isLast) flushTable(true)
129
+ return
130
+ }
131
+ flushTable(isLast)
132
+ const fence = CODE_FENCE_OPEN.exec(line)
133
+ const body = line + (isLast ? "" : "\n")
134
+ units.push({ text: body, bytes: utf8Bytes(body), fenceLang: fence ? fence[1] : null })
135
+ })
136
+ return units
137
+ }
138
+
139
+ // 超大单元(巨型表格行/无换行长行)的字节级兜底切分:
140
+ // 优先段落(\n\n)、其次换行(\n)、最后码点边界硬切(不切多字节字符/代理对)。
141
+ function splitOversizeUnit(text: string, maxBytes: number): string[] {
142
+ const chunks: string[] = []
143
+ const total = text.length
144
+ let start = 0
145
+
146
+ while (start < total) {
147
+ if (utf8Bytes(text.slice(start)) <= maxBytes) {
148
+ chunks.push(text.slice(start))
149
+ break
150
+ }
151
+ let bytes = 0
152
+ let i = start
153
+ let lastParaBreak = -1
154
+ let lastLineBreak = -1
155
+ let hardCut = -1
156
+
157
+ while (i < total) {
158
+ const cp = text.codePointAt(i)!
159
+ const cpStr = String.fromCodePoint(cp)
160
+ const cpBytes = utf8Bytes(cpStr)
161
+ if (bytes + cpBytes > maxBytes) break
162
+ bytes += cpBytes
163
+ i += cpStr.length
164
+ hardCut = i
165
+ if (cp === 0x0a) {
166
+ if (i - 2 >= start && text[i - 2] === "\n") lastParaBreak = i
167
+ else lastLineBreak = i
168
+ }
169
+ }
170
+
171
+ let splitAt = lastParaBreak > start ? lastParaBreak : lastLineBreak > start ? lastLineBreak : hardCut
172
+ if (splitAt <= start) splitAt = hardCut
173
+ if (splitAt <= start) splitAt = Math.min(start + 1, total)
174
+
175
+ const chunk = text.slice(start, splitAt)
176
+ if (chunk.trim()) chunks.push(chunk)
177
+ start = splitAt
178
+ }
179
+ return chunks
180
+ }
181
+
182
+ export function splitMessage(text: string, maxBytes: number = MARKDOWN_MAX_BYTES): string[] {
183
+ if (utf8Bytes(text) <= maxBytes) return [text]
184
+
185
+ const units = toLineUnits(text)
186
+ const chunks: string[] = []
187
+ let cur = ""
188
+ let curBytes = 0
189
+ let prefix = "" // 围栏内切断时,下一片需补的开围栏(带语言)
190
+ let openLang: string | null = null // 原文全局围栏状态(跨片跟踪)
191
+
192
+ const flush = (): void => {
193
+ const body = cur
194
+ cur = ""
195
+ curBytes = 0
196
+ const inside = openLang !== null
197
+ const out = prefix + body + (inside ? (body.endsWith("\n") ? "```\n" : "\n```\n") : "")
198
+ prefix = inside ? `\`\`\`${openLang}\n` : ""
199
+ if (out.trim()) chunks.push(out)
200
+ }
201
+
202
+ for (const u of units) {
203
+ if (u.bytes > maxBytes) {
204
+ // 超大单元:先封当前片,再字节级兜底切(围栏行本身不可能超大,不参与围栏语义)
205
+ if (cur) flush()
206
+ const parts = splitOversizeUnit(u.text, maxBytes)
207
+ for (let k = 0; k < parts.length - 1; k++) chunks.push(parts[k])
208
+ cur = parts[parts.length - 1] ?? ""
209
+ curBytes = utf8Bytes(cur)
210
+ continue
211
+ }
212
+ const prefixBytes = prefix ? utf8Bytes(prefix) : 0
213
+ if (cur && curBytes + prefixBytes + u.bytes > maxBytes) {
214
+ flush()
215
+ }
216
+ cur += u.text
217
+ curBytes += u.bytes
218
+ if (u.fenceLang !== null) {
219
+ openLang = openLang === null ? u.fenceLang : null
220
+ }
221
+ }
222
+ flush()
223
+
224
+ return chunks.length > 0 ? chunks : [text]
225
+ }
226
+
227
+ // J-轻(2026-10-30,伪流式固化):多片错峰发送的延迟计划——片间各睡 staggerMs,
228
+ // 单片无延迟。纯函数导出供测试。
229
+ export function staggerDelays(chunkCount: number, staggerMs: number): number[] {
230
+ if (chunkCount <= 1 || staggerMs <= 0) return []
231
+ return Array.from({ length: chunkCount - 1 }, () => staggerMs)
232
+ }
233
+
234
+ function sleep(ms: number): Promise<void> {
235
+ return new Promise((resolve) => setTimeout(resolve, ms))
236
+ }
237
+
238
+ // 发送单个分片: 先尝试 markdown,失败则回退纯文本。返回服务端消息回执(含 id,
239
+ // 供上下文缓存登记——引用解析用)。
240
+ async function sendChunk(
241
+ accessToken: string,
242
+ ctx: MessageContext,
243
+ mdText: string,
244
+ plainText: string,
245
+ msgSeq: number,
246
+ ): Promise<MessageResponse | null> {
247
+ const isGroup = ctx.type === "group" && ctx.groupId
248
+
249
+ try {
250
+ if (isGroup) {
251
+ return await sendGroupMessage(accessToken, ctx.groupId!, mdText, ctx.msgId, msgSeq, true)
252
+ } else {
253
+ return await sendC2CMessage(accessToken, ctx.userId, mdText, ctx.msgId, msgSeq, true)
254
+ }
255
+ } catch (error) {
256
+ // markdown 发送失败(如语法不被接受/内容违规)-> 回退纯文本
257
+ console.error("[qq-sender] markdown 发送失败,回退纯文本:", error)
258
+ }
259
+
260
+ if (isGroup) {
261
+ return await sendGroupMessage(accessToken, ctx.groupId!, plainText, ctx.msgId, msgSeq, false)
262
+ } else {
263
+ return await sendC2CMessage(accessToken, ctx.userId, plainText, ctx.msgId, msgSeq, false)
264
+ }
265
+ }
266
+
267
+ export interface ReplyToQQOptions {
268
+ /** J-轻(2026-10-30):伪流式错峰——多片发送时片间间隔 ms(默认 0=一次性全发) */
269
+ staggerMs?: number
270
+ }
271
+
272
+ export interface ReplyResult {
273
+ chunks: number
274
+ /** 服务端回执的消息 id(引用解析缓存登记用) */
275
+ ids: string[]
276
+ }
277
+
278
+ export async function replyToQQ(
279
+ accessToken: string,
280
+ ctx: MessageContext,
281
+ text: string,
282
+ options?: ReplyToQQOptions,
283
+ ): Promise<ReplyResult> {
284
+ const mdFormatted = formatForQQMarkdown(text)
285
+ const plainFormatted = formatForQQ(text)
286
+
287
+ // 关键:按 UTF-8 字节切分(上限见文件头考据注释:2 万字实测),不能用字符数 maxLength,
288
+ // 否则中文长消息会超限被 QQ 静默丢弃(看似"答非所问",实则是答案没发出去)。
289
+ const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES)
290
+ const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES)
291
+
292
+ const delays = staggerDelays(mdChunks.length, options?.staggerMs ?? 0)
293
+ const ids: string[] = []
294
+ for (let i = 0; i < mdChunks.length; i++) {
295
+ if (i > 0 && delays[i - 1]) await sleep(delays[i - 1])
296
+ const msgSeq = getNextMsgSeq(ctx.msgId)
297
+ // 纯文本分片可能与 markdown 分片数量不一致,按索引兜底取对应/最后一片
298
+ const plainChunk = plainChunks[i] ?? plainChunks[plainChunks.length - 1] ?? mdChunks[i]
299
+ const res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq)
300
+ if (res?.id) ids.push(res.id)
301
+ }
302
+ return { chunks: mdChunks.length, ids }
303
+ }