@linjz/opencode-qqbot 0.0.0-stage → 0.3.1

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.
@@ -0,0 +1,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
+ 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
+ }
@@ -0,0 +1,146 @@
1
+ // @input: (none)
2
+ // @output: MessageContext, C2CMessageEvent, GroupMessageEvent, WSPayload, QQBotConfig
3
+ // @pos: qq层 - QQ Bot 消息事件和协议类型定义
4
+ export interface QQBotConfig {
5
+ appId: string
6
+ clientSecret: string
7
+ }
8
+
9
+ /**
10
+ * 富媒体附件
11
+ */
12
+ export interface MessageAttachment {
13
+ content_type: string
14
+ filename?: string
15
+ height?: number
16
+ width?: number
17
+ size?: number
18
+ url: string
19
+ voice_wav_url?: string
20
+ /** 语音消息的 QQ 内置 ASR 转写文本(免费,省下载省 STT 调用) */
21
+ asr_refer_text?: string
22
+ }
23
+
24
+ /**
25
+ * C2C 消息事件
26
+ */
27
+ export interface C2CMessageEvent {
28
+ author: {
29
+ id: string
30
+ union_openid: string
31
+ user_openid: string
32
+ }
33
+ content: string
34
+ id: string
35
+ timestamp: string
36
+ message_scene?: {
37
+ source: string
38
+ }
39
+ attachments?: MessageAttachment[]
40
+ /** 长按回复引用的消息 id(QQ 客户端引用消息) */
41
+ message_reference?: { message_id: string }
42
+ }
43
+
44
+ /**
45
+ * 频道 AT 消息事件
46
+ */
47
+ export interface GuildMessageEvent {
48
+ id: string
49
+ channel_id: string
50
+ guild_id: string
51
+ content: string
52
+ timestamp: string
53
+ author: {
54
+ id: string
55
+ username?: string
56
+ bot?: boolean
57
+ }
58
+ member?: {
59
+ nick?: string
60
+ joined_at?: string
61
+ }
62
+ attachments?: MessageAttachment[]
63
+ }
64
+
65
+ /**
66
+ * 群聊 AT 消息事件
67
+ */
68
+ export interface GroupMessageEvent {
69
+ author: {
70
+ id: string
71
+ member_openid: string
72
+ }
73
+ content: string
74
+ id: string
75
+ timestamp: string
76
+ group_id: string
77
+ group_openid: string
78
+ attachments?: MessageAttachment[]
79
+ /** 长按回复引用的消息 id(QQ 客户端引用消息) */
80
+ message_reference?: { message_id: string }
81
+ }
82
+
83
+ /**
84
+ * Hello 事件数据
85
+ */
86
+ export interface GatewayHelloData {
87
+ heartbeat_interval: number
88
+ }
89
+
90
+ /**
91
+ * READY 事件数据
92
+ */
93
+ export interface GatewayReadyData {
94
+ session_id: string
95
+ }
96
+
97
+ /**
98
+ * WebSocket 事件负载
99
+ */
100
+ export interface WSPayload<T = unknown> {
101
+
102
+ op: number
103
+ d?: T
104
+ s?: number
105
+ t?: string
106
+ }
107
+
108
+ /**
109
+ * 按钮交互回调事件(INTERACTION_CREATE)——A 项卡片审批(2026-10-29)。
110
+ * 形状对齐 P0 官方 @tencent-connect/qqbot-nodejs protocol/types.ts。
111
+ */
112
+ export interface InteractionButtonResolved {
113
+ button_id?: string
114
+ button_data?: string
115
+ }
116
+
117
+ export interface InteractionEvent {
118
+ id: string
119
+ type?: number
120
+ scene?: string
121
+ user_openid?: string
122
+ group_openid?: string
123
+ /** 群场景点击者身份(自我评审 2026-10-29:挂起槽对群用户用 member_openid 索引,
124
+ * 只认 user_openid 会导致群按钮点击被静默拒识) */
125
+ group_member_openid?: string
126
+ data?: { type?: number; resolved?: InteractionButtonResolved }
127
+ }
128
+
129
+ /**
130
+ * 桥接层统一使用的消息上下文
131
+ */
132
+ export interface MessageContext {
133
+ type: "c2c" | "group"
134
+ userId: string
135
+ groupId?: string
136
+ msgId: string
137
+ content: string
138
+ /** 长按回复引用的消息 id(经 message_reference 透传) */
139
+ referencedMsgId?: string
140
+ /** 解析后的引用上文(bridge 从 context-buffer 解析得到,注入 prompt 前缀) */
141
+ quoteText?: string
142
+ /** 图片等富媒体附件(原生附件接入 2026-10-14;此前在网关被静默丢弃) */
143
+ attachments?: MessageAttachment[]
144
+ timestamp?: string
145
+ rawEvent?: C2CMessageEvent | GroupMessageEvent
146
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2022"],
7
+ "outDir": "dist",
8
+ "rootDir": "src",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+ "resolveJsonModule": true,
14
+ "declaration": true,
15
+ "declarationMap": true,
16
+ "sourceMap": true,
17
+ "noUnusedLocals": true,
18
+ "noUnusedParameters": true,
19
+ "noFallthroughCasesInSwitch": true,
20
+ "types": ["node"]
21
+ },
22
+ "include": ["src/**/*.ts"],
23
+ "exclude": ["node_modules", "dist"]
24
+ }