@linjz/opencode-qqbot 0.3.19 → 0.3.21
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/PRIVACY.md +87 -0
- package/README.md +20 -3
- package/README.zh-CN.md +21 -4
- package/THIRD_PARTY_NOTICES.md +136 -0
- package/bin/openqq.js +1 -1
- package/dist/opencode-qqbot-plugin.js +124 -6
- package/dist/openqq-bot.js +1099 -231
- package/dist/openqq-cli.js +152 -16
- package/dist/openqq-watchdog.js +72 -2
- package/package.json +5 -3
- package/src/bridge.ts +156 -13
- package/src/cli/openqq-main.ts +33 -5
- package/src/core/bot-control.ts +73 -8
- package/src/core/card-approval.ts +14 -3
- package/src/core/context-buffer.ts +6 -6
- package/src/core/cron-reminders.ts +1 -1
- package/src/core/delivery.ts +131 -37
- package/src/core/instance-lock.ts +1 -1
- package/src/core/mirror-anchors.ts +145 -0
- package/src/core/mirror.ts +112 -22
- package/src/core/notices.ts +2 -2
- package/src/core/notify-sink.ts +1 -1
- package/src/core/office-text.ts +234 -0
- package/src/core/outbound-sanitize.ts +3 -1
- package/src/core/permission.ts +157 -26
- package/src/core/reply-limiter.ts +3 -2
- package/src/core/send-media.ts +6 -6
- package/src/core/stt.ts +1 -1
- package/src/core/watchdog.ts +108 -5
- package/src/index.ts +1 -1
- package/src/opencode/mirror.ts +54 -2
- package/src/opencode/sessions.ts +28 -2
- package/src/qq/api.ts +9 -1
- package/src/qq/gateway.ts +16 -5
- package/src/qq/media.ts +154 -55
- package/src/qq/sender.ts +64 -14
- package/src/qq/types.ts +4 -1
package/src/opencode/sessions.ts
CHANGED
|
@@ -18,9 +18,12 @@ interface UserSession {
|
|
|
18
18
|
|
|
19
19
|
const STORE_FILE = storageFile("sessions.json")
|
|
20
20
|
|
|
21
|
+
export type SessionBindingListener = (userId: string, sessionId: string | null) => void
|
|
22
|
+
|
|
21
23
|
export class SessionManager {
|
|
22
24
|
private sessions = new Map<string, UserSession>()
|
|
23
25
|
private client: OpencodeClient
|
|
26
|
+
private readonly bindingListeners = new Set<SessionBindingListener>()
|
|
24
27
|
/** DEF-qqbot-20261112-7:持久化路径可注入——单测必须写临时文件,禁写生产映射
|
|
25
28
|
* (2026-11-12 实证:session-model/status-title 套件直写 ~/.openqq/sessions.json,
|
|
26
29
|
* 夹具 u1-u4/sid2-4 垃圾入库;多管理器陈旧整图回写还把 owner 绑定顶回去) */
|
|
@@ -67,6 +70,20 @@ export class SessionManager {
|
|
|
67
70
|
}
|
|
68
71
|
}
|
|
69
72
|
|
|
73
|
+
/** 绑定目标变化通知:只在新增、换绑、驱逐后触发;标题/目录/模型回写不触发。 */
|
|
74
|
+
onBindingChange(listener: SessionBindingListener): () => void {
|
|
75
|
+
this.bindingListeners.add(listener)
|
|
76
|
+
return () => this.bindingListeners.delete(listener)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private emitBindingChange(userId: string, sessionId: string | null): void {
|
|
80
|
+
for (const listener of this.bindingListeners) {
|
|
81
|
+
try { listener(userId, sessionId) } catch (error) {
|
|
82
|
+
console.error("[sessions] 绑定变化通知失败:", error)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
70
87
|
async getOrCreate(userId: string): Promise<UserSession> {
|
|
71
88
|
const existing = this.sessions.get(userId)
|
|
72
89
|
if (existing) return existing
|
|
@@ -79,6 +96,7 @@ export class SessionManager {
|
|
|
79
96
|
}
|
|
80
97
|
this.sessions.set(userId, session)
|
|
81
98
|
this.saveSessions()
|
|
99
|
+
this.emitBindingChange(userId, session.sessionId)
|
|
82
100
|
await this.enforceLocation(userId, session.sessionId, directory)
|
|
83
101
|
return session
|
|
84
102
|
}
|
|
@@ -99,6 +117,7 @@ export class SessionManager {
|
|
|
99
117
|
}
|
|
100
118
|
this.sessions.set(userId, session)
|
|
101
119
|
this.saveSessions()
|
|
120
|
+
if (!prev || prev.sessionId !== session.sessionId) this.emitBindingChange(userId, session.sessionId)
|
|
102
121
|
if (inheritedModel) {
|
|
103
122
|
void this.client.session
|
|
104
123
|
.setModel({ path: { id: session.sessionId }, body: { model: inheritedModel } })
|
|
@@ -132,6 +151,7 @@ export class SessionManager {
|
|
|
132
151
|
// 是会话级状态(桌面端同语义),不得用本用户在此前会话的偏好覆盖目标会话;
|
|
133
152
|
// 反向从目标会话回读真实设置写回映射(/status 与后续 /model 以目标为准)。
|
|
134
153
|
if (changed) {
|
|
154
|
+
this.emitBindingChange(userId, sessionId)
|
|
135
155
|
void this.refreshSettingsFromServer(userId)
|
|
136
156
|
}
|
|
137
157
|
}
|
|
@@ -219,8 +239,13 @@ export class SessionManager {
|
|
|
219
239
|
}
|
|
220
240
|
|
|
221
241
|
// 枚举全部映射(摘要镜像订阅、会话→用户反查、interactionTick 权限分仓轮询用)
|
|
222
|
-
all(): Array<{ userId: string; sessionId: string; directory?: string }> {
|
|
223
|
-
return [...this.sessions.entries()].map(([userId, s]) => ({
|
|
242
|
+
all(): Array<{ userId: string; sessionId: string; title?: string; directory?: string }> {
|
|
243
|
+
return [...this.sessions.entries()].map(([userId, s]) => ({
|
|
244
|
+
userId,
|
|
245
|
+
sessionId: s.sessionId,
|
|
246
|
+
...(s.title ? { title: s.title } : {}),
|
|
247
|
+
directory: s.directory,
|
|
248
|
+
}))
|
|
224
249
|
}
|
|
225
250
|
|
|
226
251
|
/**
|
|
@@ -231,6 +256,7 @@ export class SessionManager {
|
|
|
231
256
|
const had = this.sessions.delete(userId)
|
|
232
257
|
if (had) {
|
|
233
258
|
this.saveSessions()
|
|
259
|
+
this.emitBindingChange(userId, null)
|
|
234
260
|
console.log(`[sessions] 驱逐失效映射 userId=${userId.slice(0, 8)}…(400/404 三连判死)`)
|
|
235
261
|
}
|
|
236
262
|
return had
|
package/src/qq/api.ts
CHANGED
|
@@ -263,7 +263,7 @@ export async function apiRequest<T = unknown>(
|
|
|
263
263
|
console.log("[qqbot-api] >>> Body:", JSON.stringify(logBody, null, 2))
|
|
264
264
|
}
|
|
265
265
|
|
|
266
|
-
// O 项(2026-10-30
|
|
266
|
+
// O 项(2026-10-30,参考竞品 opencode-qq-v2 postWithRetry):HTTP 429 限流时
|
|
267
267
|
// 尊重 Retry-After 退避重试(最多再试 2 次,单次等待封顶 30s);其余错误不重试。
|
|
268
268
|
// 429 语义=请求被拒绝未生效,重试无副作用。
|
|
269
269
|
let res: Response | undefined
|
|
@@ -346,8 +346,16 @@ export async function getGatewayUrl(accessToken: string): Promise<string> {
|
|
|
346
346
|
* QQ 发消息成功后的通用响应结构。
|
|
347
347
|
*/
|
|
348
348
|
export interface MessageResponse {
|
|
349
|
+
/** 新发出的 QQ 消息 ID(撤回等用途),不是后续引用 lookup 的键。 */
|
|
349
350
|
id: string
|
|
350
351
|
timestamp: number | string
|
|
352
|
+
/** 官方引用索引:机器人消息被长按回复时,入站 ref_msg_idx 对应此 ref_idx。 */
|
|
353
|
+
ext_info?: { ref_idx?: string }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export interface SentMessageReceipt {
|
|
357
|
+
id: string
|
|
358
|
+
refIdx?: string
|
|
351
359
|
}
|
|
352
360
|
|
|
353
361
|
/**
|
package/src/qq/gateway.ts
CHANGED
|
@@ -144,7 +144,7 @@ function scheduleReconnect(state: GatewayState, connect: () => Promise<void>, cu
|
|
|
144
144
|
}, delayMs)
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
-
// —— AB:快断连风暴守卫(2026-11-23
|
|
147
|
+
// —— AB:快断连风暴守卫(2026-11-23 学习参考,源=hermes-agent adapter.py P0 邻接)——
|
|
148
148
|
// 背景:指数退避(1s→30s)只放缓单个重连,挡不住「坏凭据/网络抖动」的无限循环——
|
|
149
149
|
// bot 会在 1~30s 档永远空转且日志无声。守卫口径:窗口内快断连(建连后秒挂)累计
|
|
150
150
|
// 达上限 → 升级 5min 静默冷却 + 高声错误日志(排障信号),冷却后再犯重新累计。
|
|
@@ -248,6 +248,17 @@ function briefAttachments(atts: MessageAttachment[]): unknown[] {
|
|
|
248
248
|
})
|
|
249
249
|
}
|
|
250
250
|
|
|
251
|
+
export function referencedMessageId(
|
|
252
|
+
event: Pick<C2CMessageEvent, "message_scene" | "message_reference">,
|
|
253
|
+
): string | undefined {
|
|
254
|
+
const prefix = "ref_msg_idx="
|
|
255
|
+
const official = event.message_scene?.ext
|
|
256
|
+
?.find((item) => typeof item === "string" && item.startsWith(prefix))
|
|
257
|
+
?.slice(prefix.length)
|
|
258
|
+
.trim()
|
|
259
|
+
return official || event.message_reference?.message_id
|
|
260
|
+
}
|
|
261
|
+
|
|
251
262
|
function toC2CMessageContext(event: C2CMessageEvent): MessageContext {
|
|
252
263
|
return {
|
|
253
264
|
type: "c2c",
|
|
@@ -256,7 +267,7 @@ function toC2CMessageContext(event: C2CMessageEvent): MessageContext {
|
|
|
256
267
|
content: normalizeMessageContent(event.content),
|
|
257
268
|
// DEF-qqbot-20261111-P2:纯表情标记随 ctx 传递,bridge 丢弃点据此刻回有据提示(不再静默吞)
|
|
258
269
|
...(isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {}),
|
|
259
|
-
referencedMsgId: event
|
|
270
|
+
referencedMsgId: referencedMessageId(event),
|
|
260
271
|
attachments: event.attachments,
|
|
261
272
|
timestamp: event.timestamp,
|
|
262
273
|
rawEvent: event,
|
|
@@ -272,7 +283,7 @@ function toGroupMessageContext(event: GroupMessageEvent): MessageContext {
|
|
|
272
283
|
content: stripGroupAtPrefix(event.content),
|
|
273
284
|
// DEF-qqbot-20261111-P2:群聊同口径(纯表情有据提示不静默)
|
|
274
285
|
...(isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {}),
|
|
275
|
-
referencedMsgId: event
|
|
286
|
+
referencedMsgId: referencedMessageId(event),
|
|
276
287
|
attachments: event.attachments,
|
|
277
288
|
timestamp: event.timestamp,
|
|
278
289
|
rawEvent: event,
|
|
@@ -300,8 +311,8 @@ function sendIdentify(ws: WebSocket, accessToken: string): void {
|
|
|
300
311
|
shard: [0, 1],
|
|
301
312
|
properties: {
|
|
302
313
|
os: process.platform,
|
|
303
|
-
browser: "
|
|
304
|
-
device: "
|
|
314
|
+
browser: "opencode_qqbot",
|
|
315
|
+
device: "opencode_qqbot",
|
|
305
316
|
},
|
|
306
317
|
},
|
|
307
318
|
}
|
package/src/qq/media.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// @input: ./api (getAccessToken), ./types (MessageAttachment), node:fs/os/path
|
|
2
|
-
// @output: extForImageMime, isAllowedDownloadHost, MAX_IMAGE_BYTES,
|
|
3
|
-
//
|
|
4
|
-
// augmentPromptWithAttachments,
|
|
5
|
-
//
|
|
2
|
+
// @output: extForImageMime, isAllowedDownloadHost, MAX_IMAGE_BYTES, MAX_FILE_BYTES,
|
|
3
|
+
// imageDir, fileDir, classifyFileAttachment, downloadQQAttachment,
|
|
4
|
+
// prepareQQAttachments, groupOutcomes, augmentPromptWithAttachments,
|
|
5
|
+
// purgeOldQQImages, purgeOldQQFiles
|
|
6
|
+
// @pos: qq层 - QQ 图片/文件下载落盘 + prompt 文本/附件合成(原生附件接入 2026-10-14)
|
|
6
7
|
//
|
|
7
8
|
// QQ 图片消息到网关只有 URL(MessageAttachment.url);本模块下载落盘成文件,
|
|
8
9
|
// 再转成 prompt body 的 files({uri, name},v2 PromptInput schema 内字段)。
|
|
@@ -14,6 +15,7 @@ import { join } from "node:path"
|
|
|
14
15
|
import { tmpdir } from "node:os"
|
|
15
16
|
import type { MessageAttachment } from "./types.js"
|
|
16
17
|
import { sttConfigured, sttTranscribe } from "../core/stt.js"
|
|
18
|
+
import { extractOfficeTextFromFile, isLegacyOfficePath, officeKindForPath } from "../core/office-text.js"
|
|
17
19
|
|
|
18
20
|
export interface PromptFile {
|
|
19
21
|
uri: string
|
|
@@ -27,7 +29,7 @@ export interface PreparedAttachments {
|
|
|
27
29
|
|
|
28
30
|
/** 下载结果(纯数据,便于单测分组逻辑) */
|
|
29
31
|
export type AttachmentOutcome =
|
|
30
|
-
| { path: string; name: string }
|
|
32
|
+
| { path: string; name: string; kind?: "image" | "text" | "pdf" | "office-text"; sourceName?: string }
|
|
31
33
|
| { failed: string }
|
|
32
34
|
| { unsupported: string }
|
|
33
35
|
/** 语音消息:QQ 内置 ASR 免费给 asr_refer_text,零下载零 STT 调用直接转文字(生态观察缺口 2) */
|
|
@@ -41,6 +43,7 @@ export function extForImageMime(mime: string): string | null {
|
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
export const MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
|
46
|
+
export const MAX_FILE_BYTES = 20 * 1024 * 1024
|
|
44
47
|
const ALLOWED_HOST_SUFFIXES = [".qpic.cn", ".qq.com", ".qq.com.cn"]
|
|
45
48
|
|
|
46
49
|
/** 下载域白名单(R2-P1-2):只信 QQ 自家 CDN 且必须 https——在 fetch 之前
|
|
@@ -61,6 +64,10 @@ export function imageDir(): string {
|
|
|
61
64
|
return join(tmpdir(), "opencode", "qq-images")
|
|
62
65
|
}
|
|
63
66
|
|
|
67
|
+
export function fileDir(): string {
|
|
68
|
+
return join(tmpdir(), "opencode", "qq-files")
|
|
69
|
+
}
|
|
70
|
+
|
|
64
71
|
async function fetchWithTimeout(url: string, ms: number, auth?: string): Promise<Response> {
|
|
65
72
|
const ctrl = new AbortController()
|
|
66
73
|
const timer = setTimeout(() => ctrl.abort(), ms)
|
|
@@ -74,8 +81,80 @@ async function fetchWithTimeout(url: string, ms: number, auth?: string): Promise
|
|
|
74
81
|
}
|
|
75
82
|
}
|
|
76
83
|
|
|
84
|
+
export type IncomingFileKind = "text" | "pdf" | "office"
|
|
85
|
+
|
|
86
|
+
const TEXT_FILE_EXTENSIONS = new Set([
|
|
87
|
+
"txt", "md", "markdown", "json", "jsonc", "log", "csv", "tsv", "xml", "yaml", "yml",
|
|
88
|
+
"toml", "ini", "cfg", "conf", "js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "java",
|
|
89
|
+
"go", "rs", "c", "h", "cpp", "hpp", "cs", "sql", "sh", "ps1", "bat", "cmd", "html",
|
|
90
|
+
"htm", "css", "scss", "less", "vue", "svelte",
|
|
91
|
+
])
|
|
92
|
+
|
|
93
|
+
/** QQ file 附件分类:按官方 content_type=file 为入口,文件名扩展名决定可处理形态。 */
|
|
94
|
+
export function classifyFileAttachment(att: MessageAttachment): IncomingFileKind | null {
|
|
95
|
+
const filename = (att.filename || "").toLowerCase()
|
|
96
|
+
const contentType = (att.content_type || "").toLowerCase().split(";")[0].trim()
|
|
97
|
+
if (isLegacyOfficePath(filename)) return null // 由调用方给出专门的 legacy 指引
|
|
98
|
+
if (officeKindForPath(filename)) return "office"
|
|
99
|
+
if (filename.endsWith(".pdf") || contentType === "application/pdf") return "pdf"
|
|
100
|
+
const ext = filename.match(/\.([a-z0-9]+)$/)?.[1] ?? ""
|
|
101
|
+
if (contentType.startsWith("text/") || TEXT_FILE_EXTENSIONS.has(ext)) return "text"
|
|
102
|
+
return null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function safeAttachmentName(name: string): string {
|
|
106
|
+
const cleaned = name.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").trim() || "attachment"
|
|
107
|
+
if (cleaned.length <= 80) return cleaned
|
|
108
|
+
const ext = cleaned.match(/\.[a-z0-9]+$/i)?.[0] ?? ""
|
|
109
|
+
return `${cleaned.slice(0, Math.max(1, 80 - ext.length))}${ext}`
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function downloadToBuffer(
|
|
113
|
+
att: MessageAttachment,
|
|
114
|
+
getAuth: (() => Promise<string>) | undefined,
|
|
115
|
+
maxBytes: number,
|
|
116
|
+
tooLargeMessage: string,
|
|
117
|
+
): Promise<{ data: Buffer } | { failed: string }> {
|
|
118
|
+
if (!isAllowedDownloadHost(att.url)) return { failed: "下载域不在白名单" }
|
|
119
|
+
try {
|
|
120
|
+
let res = await fetchWithTimeout(att.url, 15000)
|
|
121
|
+
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
122
|
+
try {
|
|
123
|
+
res = await fetchWithTimeout(att.url, 15000, await getAuth())
|
|
124
|
+
} catch {
|
|
125
|
+
/* 鉴权兜底失败:保持原状态,走下方 !res.ok 归 failed */
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
console.log("[media] 下载失败:", res.status, att.url) // 原始 URL 只进本机日志(B7 校准)
|
|
130
|
+
return { failed: `HTTP ${res.status}` }
|
|
131
|
+
}
|
|
132
|
+
const len = Number(res.headers.get("content-length") || 0)
|
|
133
|
+
if (len > maxBytes) return { failed: tooLargeMessage }
|
|
134
|
+
const reader = res.body?.getReader()
|
|
135
|
+
if (!reader) return { failed: "无响应体" }
|
|
136
|
+
const chunks: Uint8Array[] = []
|
|
137
|
+
let total = 0
|
|
138
|
+
for (;;) {
|
|
139
|
+
const { done, value } = await reader.read()
|
|
140
|
+
if (done) break
|
|
141
|
+
total += value.byteLength
|
|
142
|
+
if (total > maxBytes) {
|
|
143
|
+
await reader.cancel()
|
|
144
|
+
return { failed: tooLargeMessage }
|
|
145
|
+
}
|
|
146
|
+
chunks.push(value)
|
|
147
|
+
}
|
|
148
|
+
if (total === 0) return { failed: "空响应" }
|
|
149
|
+
return { data: Buffer.concat(chunks) }
|
|
150
|
+
} catch (e) {
|
|
151
|
+
console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e)
|
|
152
|
+
return { failed: "网络错误或超时" }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
77
156
|
/**
|
|
78
|
-
* 下载 QQ
|
|
157
|
+
* 下载 QQ 图片/文件附件到本地。非支持类型返回 unsupported;下载失败返回 failed
|
|
79
158
|
* (脱敏短语,原始 URL/错误只进本机日志)。fetch 前过域白名单(R2-P1-2);
|
|
80
159
|
* 401/403 时带 access_token 重试一次(此时目标必为 QQ 自家域,token 不出站);
|
|
81
160
|
* 10MB 流式上限,超限 cancel 熔断。
|
|
@@ -93,7 +172,7 @@ export async function downloadQQAttachment(
|
|
|
93
172
|
if (isVoice && att.asr_refer_text?.trim()) {
|
|
94
173
|
return { voice: att.asr_refer_text.trim() }
|
|
95
174
|
}
|
|
96
|
-
// AD(2026-11-23
|
|
175
|
+
// AD(2026-11-23 学习参考):QQ 内置 ASR 无转写 → 外部 STT 回退(hermes 双级链同款)。
|
|
97
176
|
// 需 QQ_STT_BASE_URL+QQ_STT_API_KEY 齐配(QQ_STT_MODEL 默认 whisper-1);未配置保持
|
|
98
177
|
// 既有「不支持」路径零变化。音频仍走 QQ 域白名单+token 重试,10MB 上限同图片口径。
|
|
99
178
|
if (isVoice && sttConfigured()) {
|
|
@@ -113,52 +192,48 @@ export async function downloadQQAttachment(
|
|
|
113
192
|
return { failed: "语音转写失败(外部 STT 未响应或识别为空)" }
|
|
114
193
|
}
|
|
115
194
|
}
|
|
195
|
+
const fileKind = classifyFileAttachment(att)
|
|
196
|
+
if (fileKind) {
|
|
197
|
+
const downloaded = await downloadToBuffer(att, getAuth, MAX_FILE_BYTES, "超过20MB")
|
|
198
|
+
if ("failed" in downloaded) return downloaded
|
|
199
|
+
const dir = fileDir()
|
|
200
|
+
mkdirSync(dir, { recursive: true })
|
|
201
|
+
const safeName = safeAttachmentName(att.filename || `attachment-${Date.now()}`)
|
|
202
|
+
const storedName = `qq-file-${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${safeName}`
|
|
203
|
+
const storedPath = join(dir, storedName)
|
|
204
|
+
try {
|
|
205
|
+
writeFileSync(storedPath, downloaded.data)
|
|
206
|
+
if (fileKind === "text") return { path: storedPath, name: safeName, kind: "text" }
|
|
207
|
+
if (fileKind === "pdf") return { path: storedPath, name: safeName, kind: "pdf" }
|
|
208
|
+
const extracted = extractOfficeTextFromFile(storedPath)
|
|
209
|
+
const textPath = `${storedPath}.extracted.txt`
|
|
210
|
+
writeFileSync(textPath, extracted, "utf8")
|
|
211
|
+
return { path: textPath, name: `${safeName}.txt`, kind: "office-text", sourceName: safeName }
|
|
212
|
+
} catch (error) {
|
|
213
|
+
console.log("[media] 文件处理失败:", safeName, error instanceof Error ? error.message : error)
|
|
214
|
+
return { failed: fileKind === "office" ? "Office 文档解析失败" : "文件处理失败" }
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
116
218
|
const ext = extForImageMime(att.content_type || "")
|
|
117
|
-
if (!ext)
|
|
118
|
-
|
|
219
|
+
if (!ext) {
|
|
220
|
+
if (isLegacyOfficePath(att.filename || "")) {
|
|
221
|
+
return { unsupported: "旧版 Office 二进制(请另存为 docx/xlsx/pptx 或导出文本/PDF)" }
|
|
222
|
+
}
|
|
223
|
+
return { unsupported: att.content_type || att.filename || "未知类型" }
|
|
224
|
+
}
|
|
225
|
+
const downloaded = await downloadToBuffer(att, getAuth, MAX_IMAGE_BYTES, "超过10MB")
|
|
226
|
+
if ("failed" in downloaded) return downloaded
|
|
119
227
|
try {
|
|
120
228
|
const dir = imageDir()
|
|
121
229
|
mkdirSync(dir, { recursive: true })
|
|
122
230
|
const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`
|
|
123
|
-
let res = await fetchWithTimeout(att.url, 15000)
|
|
124
|
-
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
125
|
-
try {
|
|
126
|
-
const tok = await getAuth()
|
|
127
|
-
res = await fetchWithTimeout(att.url, 15000, tok)
|
|
128
|
-
} catch {
|
|
129
|
-
/* 鉴权兜底失败:保持原状态,走下方 !res.ok 归 failed */
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
if (!res.ok) {
|
|
133
|
-
console.log("[media] 下载失败:", res.status, att.url) // 原始 URL 只进本机日志(B7 校准)
|
|
134
|
-
return { failed: `HTTP ${res.status}` }
|
|
135
|
-
}
|
|
136
|
-
// R2-P1-2:10MB 上限——Content-Length 预检 + 流式逐块计数熔断
|
|
137
|
-
//(无 Content-Length 的分块响应同样有界;超限即 cancel,内存不涨)
|
|
138
|
-
const len = Number(res.headers.get("content-length") || 0)
|
|
139
|
-
if (len > MAX_IMAGE_BYTES) return { failed: "超过10MB" }
|
|
140
|
-
const reader = res.body?.getReader()
|
|
141
|
-
if (!reader) return { failed: "无响应体" }
|
|
142
|
-
const chunks: Uint8Array[] = []
|
|
143
|
-
let total = 0
|
|
144
|
-
for (;;) {
|
|
145
|
-
const { done, value } = await reader.read()
|
|
146
|
-
if (done) break
|
|
147
|
-
total += value.byteLength
|
|
148
|
-
if (total > MAX_IMAGE_BYTES) {
|
|
149
|
-
await reader.cancel()
|
|
150
|
-
return { failed: "超过10MB" }
|
|
151
|
-
}
|
|
152
|
-
chunks.push(value)
|
|
153
|
-
}
|
|
154
|
-
if (total === 0) return { failed: "空响应" }
|
|
155
231
|
const full = join(dir, name)
|
|
156
|
-
writeFileSync(full,
|
|
157
|
-
return { path: full, name }
|
|
232
|
+
writeFileSync(full, downloaded.data)
|
|
233
|
+
return { path: full, name, kind: "image" }
|
|
158
234
|
} catch (e) {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
return { failed: "网络错误或超时" }
|
|
235
|
+
console.log("[media] 图片落盘失败:", e instanceof Error ? e.message : e)
|
|
236
|
+
return { failed: "文件落盘失败" }
|
|
162
237
|
}
|
|
163
238
|
}
|
|
164
239
|
|
|
@@ -179,14 +254,21 @@ export function groupOutcomes(outcomes: AttachmentOutcome[]): PreparedAttachment
|
|
|
179
254
|
const notes: string[] = []
|
|
180
255
|
for (const o of outcomes) {
|
|
181
256
|
if ("path" in o) {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
257
|
+
const kind = o.kind ?? "image"
|
|
258
|
+
if (kind === "image") {
|
|
259
|
+
// 桌面 TUI 预览实证通道:≤2MB 的图片用 data: URL(opencode 对 data: 内嵌预览友好);
|
|
260
|
+
// 大图保留 file:// 路径(避免 base64 膨胀)。
|
|
261
|
+
const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024)
|
|
262
|
+
files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
|
|
263
|
+
} else {
|
|
264
|
+
files.push({ uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
|
|
265
|
+
if (kind === "pdf") notes.push(`(PDF 附件已注入:${o.name};需要模型支持 PDF 输入)`)
|
|
266
|
+
if (kind === "office-text") notes.push(`(Office 文档已提取为文本:${o.sourceName ?? o.name})`)
|
|
267
|
+
}
|
|
186
268
|
} else if ("voice" in o) {
|
|
187
269
|
notes.push(`(语音转写:${o.voice})`)
|
|
188
270
|
} else if ("failed" in o) {
|
|
189
|
-
notes.push(
|
|
271
|
+
notes.push(`(附件下载失败:${o.failed})`)
|
|
190
272
|
} else {
|
|
191
273
|
notes.push(`(暂不支持的附件类型:${o.unsupported})`)
|
|
192
274
|
}
|
|
@@ -212,6 +294,11 @@ function tryImageDataUrl(path: string, maxBytes: number): string | null {
|
|
|
212
294
|
* - 纯图(无文字):占位文字,模型经 files 直接看到图
|
|
213
295
|
* - 纯失败(图没下下来):备注即正文,QQ 端可见而不是静默
|
|
214
296
|
*/
|
|
297
|
+
function isImagePromptFile(file: PromptFile): boolean {
|
|
298
|
+
if (file.uri.startsWith("data:image/")) return true
|
|
299
|
+
return /\.(png|jpe?g|gif|webp|bmp)$/i.test(file.name ?? "")
|
|
300
|
+
}
|
|
301
|
+
|
|
215
302
|
export function augmentPromptWithAttachments(
|
|
216
303
|
rawContent: string,
|
|
217
304
|
prepared: PreparedAttachments,
|
|
@@ -219,16 +306,18 @@ export function augmentPromptWithAttachments(
|
|
|
219
306
|
const base = rawContent.trim()
|
|
220
307
|
const { files, notes } = prepared
|
|
221
308
|
let text = base
|
|
222
|
-
if (!text && files.length > 0)
|
|
309
|
+
if (!text && files.length > 0) {
|
|
310
|
+
text = files.some(isImagePromptFile)
|
|
311
|
+
? "(用户通过 QQ 发来了图片,未附文字)"
|
|
312
|
+
: "(用户通过 QQ 发来了文件,未附文字)"
|
|
313
|
+
}
|
|
223
314
|
if (!text && notes.length > 0) text = "(用户通过 QQ 发来了内容,但无法处理)"
|
|
224
315
|
if (notes.length > 0) text = text ? `${text}\n\n${notes.join("\n")}` : notes.join("\n")
|
|
225
316
|
return { text, files }
|
|
226
317
|
}
|
|
227
318
|
|
|
228
|
-
|
|
229
|
-
export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
319
|
+
function purgeOldFilesIn(dir: string, maxAgeMs: number): void {
|
|
230
320
|
try {
|
|
231
|
-
const dir = imageDir()
|
|
232
321
|
const now = Date.now()
|
|
233
322
|
for (const f of readdirSync(dir)) {
|
|
234
323
|
const full = join(dir, f)
|
|
@@ -242,3 +331,13 @@ export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
|
242
331
|
/* 目录不存在等忽略 */
|
|
243
332
|
}
|
|
244
333
|
}
|
|
334
|
+
|
|
335
|
+
/** 启动清理:删掉 7 天前的落盘图片(只在自己的子目录内操作) */
|
|
336
|
+
export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
337
|
+
purgeOldFilesIn(imageDir(), maxAgeMs)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** 启动清理:删掉 7 天前的落盘文件附件与 Office 提取文本。 */
|
|
341
|
+
export function purgeOldQQFiles(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
|
|
342
|
+
purgeOldFilesIn(fileDir(), maxAgeMs)
|
|
343
|
+
}
|
package/src/qq/sender.ts
CHANGED
|
@@ -5,7 +5,13 @@
|
|
|
5
5
|
// QQ 机器人自定义 Markdown(msg_type=2)已对单聊/群聊全量开放,无需模板。
|
|
6
6
|
// QQ markdown 能完整渲染标准语法: 表格、行内代码/代码块、加粗、标题、列表、链接、引用等。
|
|
7
7
|
// 因此主路径直接透传 AI 的 markdown 原文,交给 QQ 渲染;仅在发送失败时回退纯文本。
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
sendC2CMessage,
|
|
10
|
+
sendGroupMessage,
|
|
11
|
+
getNextMsgSeq,
|
|
12
|
+
type MessageResponse,
|
|
13
|
+
type SentMessageReceipt,
|
|
14
|
+
} from "./api.js"
|
|
9
15
|
import type { MessageContext } from "./types.js"
|
|
10
16
|
import { normalizeOutboundMarkdown, matchFence, type FenceToken } from "../core/markdown.js"
|
|
11
17
|
import { stripInteractionTags } from "../core/notices.js"
|
|
@@ -82,7 +88,7 @@ export function formatForQQ(text: string): string {
|
|
|
82
88
|
processed = processed.replace(`\x00CB${i}\x00`, codeBlocks[i])
|
|
83
89
|
}
|
|
84
90
|
|
|
85
|
-
// 交互标签兜底剥离(2026-11-22
|
|
91
|
+
// 交互标签兜底剥离(2026-11-22 学习参考):<qqbot-cmd-input> 等仅 markdown 消息生效,
|
|
86
92
|
// 纯文本通道必须把标签降级为可读文本,否则尖括号原样糊给用户(AstrBot#8755 同款坑)。
|
|
87
93
|
// 围栏内是代码字面量,不动。
|
|
88
94
|
let inStripFence = false
|
|
@@ -145,12 +151,13 @@ function utf8Bytes(s: string): number {
|
|
|
145
151
|
return encoder.encode(s).length
|
|
146
152
|
}
|
|
147
153
|
|
|
148
|
-
// —— 结构化分条(2026-10-29
|
|
149
|
-
// dsh
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
//
|
|
154
|
+
// —— 结构化分条(2026-10-29 固化)——
|
|
155
|
+
// 设计参考 dsh-qqbot 的 chunker:GFM 表格作为原子单元并按行边界打包。
|
|
156
|
+
// 本实现按项目需求独立扩展:① UTF-8 字节预算,避免中文字符数与字节数不一致;
|
|
157
|
+
// ② 代码块跨片时前片补闭合、后片补开围栏(带语言),使每片独立可渲染;
|
|
158
|
+
// ③ 超长单元按段落/换行/码点分级切分。围栏识别与出站兜底共用 core/markdown
|
|
153
159
|
// (2026-11-10:补 ~~~ 与 4+ 标记长度,避免波浪围栏被当正文切碎)。
|
|
160
|
+
// 上游来源与许可见 THIRD_PARTY_NOTICES.md。
|
|
154
161
|
const GFM_TABLE_LINE = /^\s*\|.*\|\s*$/
|
|
155
162
|
|
|
156
163
|
interface LineUnit {
|
|
@@ -328,12 +335,29 @@ async function sendChunk(
|
|
|
328
335
|
export interface ReplyToQQOptions {
|
|
329
336
|
/** J-轻(2026-10-30):伪流式错峰——多片发送时片间间隔 ms(默认 0=一次性全发) */
|
|
330
337
|
staggerMs?: number
|
|
338
|
+
/** 每片真实发送成功立即回调;后续分片失败也不丢已发分片的锚点。 */
|
|
339
|
+
onReceipt?: (receipt: SentMessageReceipt) => void | Promise<void>
|
|
340
|
+
/** 第 2 片起的受控身份前缀;先预留字节、切分后再添加。 */
|
|
341
|
+
continuationPrefix?: string
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export class PartialReplyError extends Error {
|
|
345
|
+
readonly name = "PartialReplyError"
|
|
346
|
+
constructor(
|
|
347
|
+
readonly receipts: readonly SentMessageReceipt[],
|
|
348
|
+
readonly failedChunkIndex: number,
|
|
349
|
+
readonly originalError: unknown,
|
|
350
|
+
) {
|
|
351
|
+
super(`QQ 分片发送中断:第 ${failedChunkIndex + 1} 片失败,此前已成功 ${receipts.length} 片`)
|
|
352
|
+
}
|
|
331
353
|
}
|
|
332
354
|
|
|
333
355
|
export interface ReplyResult {
|
|
334
356
|
chunks: number
|
|
335
|
-
/** 服务端回执的消息 id
|
|
357
|
+
/** 服务端回执的消息 id(兼容既有引用缓存调用方) */
|
|
336
358
|
ids: string[]
|
|
359
|
+
/** 每个真实分片的完整回执:refIdx 才是摘要锚点 lookup 键。 */
|
|
360
|
+
receipts: SentMessageReceipt[]
|
|
337
361
|
}
|
|
338
362
|
|
|
339
363
|
export async function replyToQQ(
|
|
@@ -347,18 +371,44 @@ export async function replyToQQ(
|
|
|
347
371
|
|
|
348
372
|
// 关键:按 UTF-8 字节切分(上限见文件头考据注释:2 万字实测),不能用字符数 maxLength,
|
|
349
373
|
// 否则中文长消息会超限被 QQ 静默丢弃(看似"答非所问",实则是答案没发出去)。
|
|
350
|
-
const
|
|
351
|
-
const
|
|
374
|
+
const continuationPrefix = options?.continuationPrefix ?? ""
|
|
375
|
+
const continuationBytes = utf8Bytes(continuationPrefix)
|
|
376
|
+
if (continuationBytes >= Math.min(MARKDOWN_MAX_BYTES, PLAIN_MAX_BYTES) - 1024) {
|
|
377
|
+
throw new Error("continuationPrefix 过长,无法为正文预留分片空间")
|
|
378
|
+
}
|
|
379
|
+
// 所有片都预留续片前缀字节,续片在切分后再加标记——身份绝不会被切到上一片。
|
|
380
|
+
const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES - continuationBytes)
|
|
381
|
+
.map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk)
|
|
382
|
+
const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES - continuationBytes)
|
|
383
|
+
.map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk)
|
|
352
384
|
|
|
353
385
|
const delays = staggerDelays(mdChunks.length, options?.staggerMs ?? 0)
|
|
354
|
-
const
|
|
386
|
+
const receipts: SentMessageReceipt[] = []
|
|
355
387
|
for (let i = 0; i < mdChunks.length; i++) {
|
|
356
388
|
if (i > 0 && delays[i - 1]) await sleep(delays[i - 1])
|
|
357
389
|
const msgSeq = getNextMsgSeq(ctx.msgId)
|
|
358
390
|
// 纯文本分片可能与 markdown 分片数量不一致,按索引兜底取对应/最后一片
|
|
359
391
|
const plainChunk = plainChunks[i] ?? plainChunks[plainChunks.length - 1] ?? mdChunks[i]
|
|
360
|
-
|
|
361
|
-
|
|
392
|
+
let res: MessageResponse | null
|
|
393
|
+
try {
|
|
394
|
+
res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq)
|
|
395
|
+
} catch (error) {
|
|
396
|
+
if (receipts.length > 0) throw new PartialReplyError(receipts, i, error)
|
|
397
|
+
throw error
|
|
398
|
+
}
|
|
399
|
+
if (res?.id) {
|
|
400
|
+
const receipt: SentMessageReceipt = {
|
|
401
|
+
id: res.id,
|
|
402
|
+
...(res.ext_info?.ref_idx ? { refIdx: res.ext_info.ref_idx } : {}),
|
|
403
|
+
}
|
|
404
|
+
receipts.push(receipt)
|
|
405
|
+
try {
|
|
406
|
+
await options?.onReceipt?.(receipt)
|
|
407
|
+
} catch (error) {
|
|
408
|
+
// 已发分片的簿记错误不得中断后续发送,更不能触发上层降级重发。
|
|
409
|
+
console.error("[qq-sender] 分片回执回调失败:", error)
|
|
410
|
+
}
|
|
411
|
+
}
|
|
362
412
|
}
|
|
363
|
-
return { chunks: mdChunks.length, ids }
|
|
413
|
+
return { chunks: mdChunks.length, ids: receipts.map((receipt) => receipt.id), receipts }
|
|
364
414
|
}
|
package/src/qq/types.ts
CHANGED
|
@@ -35,6 +35,8 @@ export interface C2CMessageEvent {
|
|
|
35
35
|
timestamp: string
|
|
36
36
|
message_scene?: {
|
|
37
37
|
source: string
|
|
38
|
+
/** 官方 103 引用事件:ref_msg_idx=<发送响应 ext_info.ref_idx> */
|
|
39
|
+
ext?: string[]
|
|
38
40
|
}
|
|
39
41
|
attachments?: MessageAttachment[]
|
|
40
42
|
/** 长按回复引用的消息 id(QQ 客户端引用消息) */
|
|
@@ -78,6 +80,7 @@ export interface GroupMessageEvent {
|
|
|
78
80
|
timestamp: string
|
|
79
81
|
group_id: string
|
|
80
82
|
group_openid: string
|
|
83
|
+
message_scene?: { source: string; ext?: string[] }
|
|
81
84
|
attachments?: MessageAttachment[]
|
|
82
85
|
/** 长按回复引用的消息 id(QQ 客户端引用消息) */
|
|
83
86
|
message_reference?: { message_id: string }
|
|
@@ -141,7 +144,7 @@ export interface MessageContext {
|
|
|
141
144
|
groupId?: string
|
|
142
145
|
msgId: string
|
|
143
146
|
content: string
|
|
144
|
-
/**
|
|
147
|
+
/** 长按回复的引用索引:官方 ref_msg_idx 优先,兼容 message_reference.message_id */
|
|
145
148
|
referencedMsgId?: string
|
|
146
149
|
/** 解析后的引用上文(bridge 从 context-buffer 解析得到,注入 prompt 前缀) */
|
|
147
150
|
quoteText?: string
|