@linjz/opencode-qqbot 0.0.0-stage → 0.3.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.
@@ -0,0 +1,486 @@
1
+ // @input: ws, ./api (getAccessToken, getGatewayUrl, acknowledgeInteraction), ./types (MessageContext, InteractionEvent)
2
+ // @output: startGateway, MessageHandler
3
+ // @pos: qq层 - QQ Bot WebSocket Gateway 状态机 (心跳/重连/消息分发)
4
+ import WebSocket from "ws"
5
+ import { acknowledgeInteraction, clearTokenCache, getAccessToken, getGatewayUrl } from "./api.js"
6
+ import type {
7
+ C2CMessageEvent,
8
+ GatewayHelloData,
9
+ GatewayReadyData,
10
+ GroupMessageEvent,
11
+ InteractionEvent,
12
+ MessageAttachment,
13
+ MessageContext,
14
+ WSPayload,
15
+ } from "./types.js"
16
+
17
+ const GROUP_AND_C2C_EVENT_INTENT = 1 << 25
18
+ // A 项(2026-10-29):按钮互动回调 intent,P0 实证(qqbot-nodejs constants.ts INTERACTION = 1<<26)
19
+ const INTERACTION_INTENT = 1 << 26
20
+ const MAX_RECONNECT_DELAY_MS = 30_000
21
+ const BASE_RECONNECT_DELAY_MS = 1_000
22
+ const INVALID_SESSION_DELAY_MS = 3_000
23
+ // B2(2026-10-29,对齐官方 qqbot-nodejs protocol/gateway/constants.ts):
24
+ // 4008 = 被平台限流,官方语义须长退避 60s(RATE_LIMIT_DELAY),否则重连风暴加重限流
25
+ const RATE_LIMITED_CLOSE_CODE = 4008
26
+ const RATE_LIMITED_RECONNECT_DELAY_MS = 60_000
27
+ const RESUME_RESET_CLOSE_CODES = new Set([4006, 4007, 4009])
28
+ const FATAL_CLOSE_CODES = new Set([4914, 4915])
29
+
30
+ export type MessageHandler = (msg: MessageContext) => Promise<void>
31
+
32
+ export interface GatewayOptions {
33
+ appId: string
34
+ clientSecret: string
35
+ onMessage: MessageHandler
36
+ onReady?: () => void
37
+ /** A 项(2026-10-29):按钮互动回调(INTERACTION_CREATE)——卡片审批的入口 */
38
+ onInteraction?: (event: InteractionEvent) => void | Promise<void>
39
+ }
40
+
41
+ interface GatewayState {
42
+ ws: WebSocket | null
43
+ stopped: boolean
44
+ connecting: boolean
45
+ reconnectAttempt: number
46
+ reconnectTimer: ReturnType<typeof setTimeout> | null
47
+ heartbeatTimer: ReturnType<typeof setInterval> | null
48
+ accessToken: string | null
49
+ sessionId: string | null
50
+ seq: number | null
51
+ heartbeatAcked: boolean
52
+ /** 去重(缺口 3):resume/重连后平台可能重投同一消息,msgId LRU 防重复触发回合 */
53
+ seenMsgIds: Set<string>
54
+ }
55
+
56
+ interface GatewayControl {
57
+ stop: () => void
58
+ }
59
+
60
+ function createInitialState(): GatewayState {
61
+ return {
62
+ ws: null,
63
+ stopped: false,
64
+ connecting: false,
65
+ reconnectAttempt: 0,
66
+ reconnectTimer: null,
67
+ heartbeatTimer: null,
68
+ accessToken: null,
69
+ sessionId: null,
70
+ seq: null,
71
+ heartbeatAcked: true,
72
+ seenMsgIds: new Set(),
73
+ }
74
+ }
75
+
76
+ // 缺口 3:msgId 去重(平台 resume/重投防御)。LRU 上限 500。
77
+ const SEEN_MSGIDS_MAX = 500
78
+ export function markSeenAndFilter(seen: Set<string>, msgId: string): boolean {
79
+ if (seen.has(msgId)) return false
80
+ if (seen.size >= SEEN_MSGIDS_MAX) {
81
+ const first = seen.values().next().value
82
+ if (first !== undefined) seen.delete(first)
83
+ }
84
+ seen.add(msgId)
85
+ return true
86
+ }
87
+
88
+ function cleanupSocket(state: GatewayState): void {
89
+ if (state.heartbeatTimer) {
90
+ clearInterval(state.heartbeatTimer)
91
+ state.heartbeatTimer = null
92
+ }
93
+
94
+ const ws = state.ws
95
+ state.ws = null
96
+
97
+ if (!ws) {
98
+ return
99
+ }
100
+
101
+ ws.removeAllListeners()
102
+
103
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
104
+ ws.close()
105
+ }
106
+ }
107
+
108
+ function scheduleReconnect(state: GatewayState, connect: () => Promise<void>, customDelayMs?: number): void {
109
+ if (state.stopped || state.reconnectTimer) {
110
+ return
111
+ }
112
+
113
+ const attempt = state.reconnectAttempt
114
+ const delayMs = customDelayMs ?? Math.min(BASE_RECONNECT_DELAY_MS * 2 ** attempt, MAX_RECONNECT_DELAY_MS)
115
+ state.reconnectAttempt += 1
116
+
117
+ state.reconnectTimer = setTimeout(() => {
118
+ state.reconnectTimer = null
119
+ void connect()
120
+ }, delayMs)
121
+ }
122
+
123
+ function startHeartbeat(state: GatewayState, intervalMs: number): void {
124
+ if (state.heartbeatTimer) {
125
+ clearInterval(state.heartbeatTimer)
126
+ }
127
+
128
+ state.heartbeatAcked = true
129
+ state.heartbeatTimer = setInterval(() => {
130
+ const ws = state.ws
131
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
132
+ return
133
+ }
134
+
135
+ // 如果上一个心跳一直没收到 ACK,直接断线重连
136
+ if (!state.heartbeatAcked) {
137
+ ws.terminate()
138
+ return
139
+ }
140
+
141
+ state.heartbeatAcked = false
142
+ ws.send(JSON.stringify({ op: 1, d: state.seq }))
143
+ }, intervalMs)
144
+ }
145
+
146
+ function resetResumeState(state: GatewayState): void {
147
+ state.sessionId = null
148
+ state.seq = null
149
+ }
150
+
151
+ function normalizeMessageContent(content: string): string {
152
+ return content.replace(/\r\n/g, "\n").trim()
153
+ }
154
+
155
+ function stripGroupAtPrefix(content: string): string {
156
+ const normalized = normalizeMessageContent(content)
157
+ return normalized.replace(/^<@!?.+?>\s*/u, "").trim()
158
+ }
159
+
160
+ /** 载荷日志打码(R2-P2-1):签名 URL 是短时效凭据不入日志,只留校准
161
+ * 所需的 host/类型/大小/文件名 */
162
+ function briefAttachments(atts: MessageAttachment[]): unknown[] {
163
+ return atts.map((a) => {
164
+ let host = "?"
165
+ try {
166
+ host = new URL(a.url).hostname
167
+ } catch {
168
+ /* 保留 ? */
169
+ }
170
+ return { host, content_type: a.content_type, size: a.size, filename: a.filename }
171
+ })
172
+ }
173
+
174
+ function toC2CMessageContext(event: C2CMessageEvent): MessageContext {
175
+ return {
176
+ type: "c2c",
177
+ userId: event.author.user_openid,
178
+ msgId: event.id,
179
+ content: normalizeMessageContent(event.content),
180
+ referencedMsgId: event.message_reference?.message_id,
181
+ attachments: event.attachments,
182
+ timestamp: event.timestamp,
183
+ rawEvent: event,
184
+ }
185
+ }
186
+
187
+ function toGroupMessageContext(event: GroupMessageEvent): MessageContext {
188
+ return {
189
+ type: "group",
190
+ userId: event.author.member_openid,
191
+ groupId: event.group_openid,
192
+ msgId: event.id,
193
+ content: stripGroupAtPrefix(event.content),
194
+ referencedMsgId: event.message_reference?.message_id,
195
+ attachments: event.attachments,
196
+ timestamp: event.timestamp,
197
+ rawEvent: event,
198
+ }
199
+ }
200
+
201
+ async function refreshGatewayAuth(options: GatewayOptions, state: GatewayState): Promise<{ accessToken: string; gatewayUrl: string }> {
202
+ const accessToken = await getAccessToken(options.appId, options.clientSecret)
203
+ const gatewayUrl = await getGatewayUrl(accessToken)
204
+ state.accessToken = accessToken
205
+ return { accessToken, gatewayUrl }
206
+ }
207
+
208
+ function sendIdentify(ws: WebSocket, accessToken: string): void {
209
+ const payload: WSPayload<{
210
+ token: string
211
+ intents: number
212
+ shard: [number, number]
213
+ properties: Record<string, string>
214
+ }> = {
215
+ op: 2,
216
+ d: {
217
+ token: `QQBot ${accessToken}`,
218
+ intents: GROUP_AND_C2C_EVENT_INTENT | INTERACTION_INTENT,
219
+ shard: [0, 1],
220
+ properties: {
221
+ os: process.platform,
222
+ browser: "opencode_qq_bot",
223
+ device: "opencode_qq_bot",
224
+ },
225
+ },
226
+ }
227
+
228
+ ws.send(JSON.stringify(payload))
229
+ }
230
+
231
+ function sendResume(ws: WebSocket, accessToken: string, sessionId: string, seq: number): void {
232
+ const payload: WSPayload<{
233
+ token: string
234
+ session_id: string
235
+ seq: number
236
+ }> = {
237
+ op: 6,
238
+ d: {
239
+ token: `QQBot ${accessToken}`,
240
+ session_id: sessionId,
241
+ seq,
242
+ },
243
+ }
244
+
245
+ ws.send(JSON.stringify(payload))
246
+ }
247
+
248
+ async function handleDispatchEvent(
249
+ payload: WSPayload,
250
+ options: GatewayOptions,
251
+ state: GatewayState,
252
+ ): Promise<void> {
253
+ switch (payload.t) {
254
+ case "READY": {
255
+ const readyData = payload.d as GatewayReadyData
256
+ state.sessionId = readyData.session_id
257
+ state.reconnectAttempt = 0
258
+ options.onReady?.()
259
+ return
260
+ }
261
+
262
+ case "RESUMED": {
263
+ state.reconnectAttempt = 0
264
+ return
265
+ }
266
+
267
+ case "C2C_MESSAGE_CREATE": {
268
+ const event = payload.d as C2CMessageEvent
269
+ // 缺口 3:重投去重(resume 后同 id 再来不重复触发)
270
+ if (!markSeenAndFilter(state.seenMsgIds, event.id)) return
271
+ const message = toC2CMessageContext(event)
272
+ if (message.attachments?.length) {
273
+ // R2-P2-1:打码载荷(签名 URL 不入日志),host/类型/大小够 B7 校准
274
+ console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)))
275
+ }
276
+ if (!message.content && !message.attachments?.length) {
277
+ return
278
+ }
279
+ await options.onMessage(message)
280
+ return
281
+ }
282
+
283
+ case "GROUP_AT_MESSAGE_CREATE": {
284
+ const event = payload.d as GroupMessageEvent
285
+ if (!markSeenAndFilter(state.seenMsgIds, event.id)) return
286
+ const message = toGroupMessageContext(event)
287
+ if (message.attachments?.length) {
288
+ // R2-P2-1:打码载荷(签名 URL 不入日志)
289
+ console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)))
290
+ }
291
+ if (!message.content && !message.attachments?.length) {
292
+ return
293
+ }
294
+ await options.onMessage(message)
295
+ return
296
+ }
297
+
298
+ case "INTERACTION_CREATE": {
299
+ // A 项(2026-10-29):按钮互动回调。平台要求 3 秒内响应且同 id 只能
300
+ // 响应一次——先立即 ack(不等业务处理结果),再分发业务。
301
+ const interaction = payload.d as InteractionEvent
302
+ if (state.accessToken && interaction?.id) {
303
+ void acknowledgeInteraction(state.accessToken, interaction.id).catch((error) => {
304
+ console.error("[qq-gateway] 互动响应失败:", error instanceof Error ? error.message : error)
305
+ })
306
+ }
307
+ await options.onInteraction?.(interaction)
308
+ return
309
+ }
310
+
311
+ default:
312
+ return
313
+ }
314
+ }
315
+
316
+ async function handlePayload(
317
+ payload: WSPayload,
318
+ ws: WebSocket,
319
+ options: GatewayOptions,
320
+ state: GatewayState,
321
+ connect: () => Promise<void>,
322
+ ): Promise<void> {
323
+ if (typeof payload.s === "number") {
324
+ state.seq = payload.s
325
+ }
326
+
327
+ switch (payload.op) {
328
+ case 10: {
329
+ // Hello:建立心跳,并根据有无 session 决定 Identify/Resume
330
+ const hello = payload.d as GatewayHelloData
331
+ startHeartbeat(state, hello.heartbeat_interval)
332
+
333
+ if (state.accessToken && state.sessionId && state.seq !== null) {
334
+ sendResume(ws, state.accessToken, state.sessionId, state.seq)
335
+ } else if (state.accessToken) {
336
+ sendIdentify(ws, state.accessToken)
337
+ }
338
+ return
339
+ }
340
+
341
+ case 0:
342
+ await handleDispatchEvent(payload, options, state)
343
+ return
344
+
345
+ case 1:
346
+ // 服务端要求立即心跳
347
+ if (ws.readyState === WebSocket.OPEN) {
348
+ ws.send(JSON.stringify({ op: 1, d: state.seq }))
349
+ }
350
+ return
351
+
352
+ case 7:
353
+ // 服务端要求重连,尽量保留 session 走 Resume
354
+ cleanupSocket(state)
355
+ scheduleReconnect(state, connect)
356
+ return
357
+
358
+ case 9: {
359
+ // InvalidSession:不可恢复时清空会话,稍后重新 Identify
360
+ const canResume = Boolean(payload.d)
361
+ if (!canResume) {
362
+ resetResumeState(state)
363
+ }
364
+ cleanupSocket(state)
365
+ scheduleReconnect(state, connect, INVALID_SESSION_DELAY_MS)
366
+ return
367
+ }
368
+
369
+ case 11:
370
+ state.heartbeatAcked = true
371
+ return
372
+
373
+ default:
374
+ return
375
+ }
376
+ }
377
+
378
+ export async function startGateway(options: GatewayOptions): Promise<GatewayControl> {
379
+ const state = createInitialState()
380
+
381
+ const stop = (): void => {
382
+ state.stopped = true
383
+
384
+ if (state.reconnectTimer) {
385
+ clearTimeout(state.reconnectTimer)
386
+ state.reconnectTimer = null
387
+ }
388
+
389
+ cleanupSocket(state)
390
+ }
391
+
392
+ const connect = async (): Promise<void> => {
393
+ if (state.stopped || state.connecting) {
394
+ return
395
+ }
396
+
397
+ state.connecting = true
398
+
399
+ try {
400
+ cleanupSocket(state)
401
+
402
+ const { gatewayUrl } = await refreshGatewayAuth(options, state)
403
+ // 握手超时:若建连握手一直挂着(休眠/断网/NAT 超时),ws 会触发 error,
404
+ // 从而把 connecting 重置并走重连;否则 connecting 会永久卡 true 导致再也不重连。
405
+ const ws = new WebSocket(gatewayUrl, { handshakeTimeout: 15_000 })
406
+ state.ws = ws
407
+
408
+ // 兜底:无论如何 20s 后必须解除 connecting 卡死状态
409
+ const connectGuard = setTimeout(() => {
410
+ if (state.ws === ws && ws.readyState === WebSocket.CONNECTING) {
411
+ console.error("[qq-gateway] 建连超时(20s 未就绪),强制终止")
412
+ ws.terminate()
413
+ }
414
+ if (state.connecting) {
415
+ state.connecting = false
416
+ }
417
+ }, 20_000)
418
+
419
+ ws.on("open", () => {
420
+ clearTimeout(connectGuard)
421
+ state.connecting = false
422
+ })
423
+
424
+ ws.on("message", (data) => {
425
+ void (async () => {
426
+ try {
427
+ const payload = JSON.parse(data.toString()) as WSPayload
428
+ await handlePayload(payload, ws, options, state, connect)
429
+ } catch (error) {
430
+ console.error("[qq-gateway] 处理网关消息失败:", error)
431
+ }
432
+ })()
433
+ })
434
+
435
+ ws.on("close", (code) => {
436
+ clearTimeout(connectGuard)
437
+ state.connecting = false
438
+ cleanupSocket(state)
439
+
440
+ if (state.stopped || code === 1000) {
441
+ return
442
+ }
443
+
444
+ // 这些错误码说明 Resume 已经没意义,直接清空会话重来
445
+ if (RESUME_RESET_CLOSE_CODES.has(code)) {
446
+ resetResumeState(state)
447
+ }
448
+
449
+ // token 失效时强制刷新,避免死循环拿旧 token
450
+ if (code === 4004) {
451
+ clearTokenCache()
452
+ state.accessToken = null
453
+ }
454
+
455
+ // B2:4008 平台限流 → 官方语义 60s 长退避(对齐 qqbot-nodejs RATE_LIMIT_DELAY),
456
+ // 与指数退避(1s 起步 30s 封顶,等价收敛于官方阶梯 [1,2,5,10,30,60])互补
457
+ if (code === RATE_LIMITED_CLOSE_CODE) {
458
+ scheduleReconnect(state, connect, RATE_LIMITED_RECONNECT_DELAY_MS)
459
+ return
460
+ }
461
+
462
+ if (FATAL_CLOSE_CODES.has(code)) {
463
+ return
464
+ }
465
+
466
+ scheduleReconnect(state, connect)
467
+ })
468
+
469
+ ws.on("error", (error) => {
470
+ clearTimeout(connectGuard)
471
+ state.connecting = false
472
+ console.error("[qq-gateway] WebSocket 错误:", error)
473
+ })
474
+ } catch (error) {
475
+ state.connecting = false
476
+ console.error("[qq-gateway] 建连失败:", error)
477
+ clearTokenCache()
478
+ state.accessToken = null
479
+ scheduleReconnect(state, connect)
480
+ }
481
+ }
482
+
483
+ await connect()
484
+
485
+ return { stop }
486
+ }
@@ -0,0 +1,204 @@
1
+ // @input: ./api (getAccessToken), ./types (MessageAttachment), node:fs/os/path
2
+ // @output: extForImageMime, isAllowedDownloadHost, MAX_IMAGE_BYTES, imageDir,
3
+ // downloadQQAttachment, prepareQQAttachments, groupOutcomes,
4
+ // augmentPromptWithAttachments, purgeOldQQImages
5
+ // @pos: qq层 - QQ 图片下载落盘 + prompt 文本/附件合成(原生附件接入 2026-10-14)
6
+ //
7
+ // QQ 图片消息到网关只有 URL(MessageAttachment.url);本模块下载落盘成文件,
8
+ // 再转成 prompt body 的 files({uri, name},v2 PromptInput schema 内字段)。
9
+ // 纯文本桥时代图片被静默丢弃——现在任何失败(下载不通/类型不支持)都转成
10
+ // 可见的文字备注,绝不静默。
11
+
12
+ import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs"
13
+ import { join } from "node:path"
14
+ import { tmpdir } from "node:os"
15
+ import type { MessageAttachment } from "./types.js"
16
+
17
+ export interface PromptFile {
18
+ uri: string
19
+ name?: string
20
+ }
21
+
22
+ export interface PreparedAttachments {
23
+ files: PromptFile[]
24
+ notes: string[]
25
+ }
26
+
27
+ /** 下载结果(纯数据,便于单测分组逻辑) */
28
+ export type AttachmentOutcome =
29
+ | { path: string; name: string }
30
+ | { failed: string }
31
+ | { unsupported: string }
32
+ /** 语音消息:QQ 内置 ASR 免费给 asr_refer_text,零下载零 STT 调用直接转文字(生态观察缺口 2) */
33
+ | { voice: string }
34
+
35
+ export function extForImageMime(mime: string): string | null {
36
+ const m = (mime || "").toLowerCase().split(";")[0].trim()
37
+ if (m === "image/jpeg") return "jpg"
38
+ for (const x of ["png", "gif", "webp", "bmp"]) if (m === `image/${x}`) return x
39
+ return null
40
+ }
41
+
42
+ export const MAX_IMAGE_BYTES = 10 * 1024 * 1024
43
+ const ALLOWED_HOST_SUFFIXES = [".qpic.cn", ".qq.com", ".qq.com.cn"]
44
+
45
+ /** 下载域白名单(R2-P1-2):只信 QQ 自家 CDN 且必须 https——在 fetch 之前
46
+ * 拦截,同时断"access_token 出站"与"SSRF 打内网"两条链;精确匹配或以
47
+ * . 结尾匹配,防 qq.com.evil.com 后缀伪造。 */
48
+ export function isAllowedDownloadHost(url: string): boolean {
49
+ try {
50
+ const u = new URL(url)
51
+ if (u.protocol !== "https:") return false
52
+ const host = u.hostname.toLowerCase()
53
+ return ALLOWED_HOST_SUFFIXES.some((s) => host === s.slice(1) || host.endsWith(s))
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
59
+ export function imageDir(): string {
60
+ return join(tmpdir(), "opencode", "qq-images")
61
+ }
62
+
63
+ async function fetchWithTimeout(url: string, ms: number, auth?: string): Promise<Response> {
64
+ const ctrl = new AbortController()
65
+ const timer = setTimeout(() => ctrl.abort(), ms)
66
+ try {
67
+ return await fetch(url, {
68
+ signal: ctrl.signal,
69
+ headers: auth ? { Authorization: `QQBot ${auth}` } : {},
70
+ })
71
+ } finally {
72
+ clearTimeout(timer)
73
+ }
74
+ }
75
+
76
+ /**
77
+ * 下载 QQ 图片附件到本地。非图片类型返回 unsupported;下载失败返回 failed
78
+ * (脱敏短语,原始 URL/错误只进本机日志)。fetch 前过域白名单(R2-P1-2);
79
+ * 401/403 时带 access_token 重试一次(此时目标必为 QQ 自家域,token 不出站);
80
+ * 10MB 流式上限,超限 cancel 熔断。
81
+ */
82
+ export async function downloadQQAttachment(
83
+ att: MessageAttachment,
84
+ getAuth?: () => Promise<string>,
85
+ ): Promise<AttachmentOutcome> {
86
+ // 语音消息:优先用 QQ 内置 ASR 的 asr_refer_text(免费、零下载);无转写才按附件流程走
87
+ const ctype = (att.content_type || "").toLowerCase()
88
+ if (ctype.startsWith("audio/") && att.asr_refer_text?.trim()) {
89
+ return { voice: att.asr_refer_text.trim() }
90
+ }
91
+ const ext = extForImageMime(att.content_type || "")
92
+ if (!ext) return { unsupported: att.content_type || att.filename || "未知类型" }
93
+ if (!isAllowedDownloadHost(att.url)) return { failed: "下载域不在白名单" }
94
+ try {
95
+ const dir = imageDir()
96
+ mkdirSync(dir, { recursive: true })
97
+ const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`
98
+ let res = await fetchWithTimeout(att.url, 15000)
99
+ if ((res.status === 401 || res.status === 403) && getAuth) {
100
+ try {
101
+ const tok = await getAuth()
102
+ res = await fetchWithTimeout(att.url, 15000, tok)
103
+ } catch {
104
+ /* 鉴权兜底失败:保持原状态,走下方 !res.ok 归 failed */
105
+ }
106
+ }
107
+ if (!res.ok) {
108
+ console.log("[media] 下载失败:", res.status, att.url) // 原始 URL 只进本机日志(B7 校准)
109
+ return { failed: `HTTP ${res.status}` }
110
+ }
111
+ // R2-P1-2:10MB 上限——Content-Length 预检 + 流式逐块计数熔断
112
+ //(无 Content-Length 的分块响应同样有界;超限即 cancel,内存不涨)
113
+ const len = Number(res.headers.get("content-length") || 0)
114
+ if (len > MAX_IMAGE_BYTES) return { failed: "超过10MB" }
115
+ const reader = res.body?.getReader()
116
+ if (!reader) return { failed: "无响应体" }
117
+ const chunks: Uint8Array[] = []
118
+ let total = 0
119
+ for (;;) {
120
+ const { done, value } = await reader.read()
121
+ if (done) break
122
+ total += value.byteLength
123
+ if (total > MAX_IMAGE_BYTES) {
124
+ await reader.cancel()
125
+ return { failed: "超过10MB" }
126
+ }
127
+ chunks.push(value)
128
+ }
129
+ if (total === 0) return { failed: "空响应" }
130
+ const full = join(dir, name)
131
+ writeFileSync(full, Buffer.concat(chunks))
132
+ return { path: full, name }
133
+ } catch (e) {
134
+ // 原始错误只进本机日志;回给用户的备注是脱敏短语(R2-P3)
135
+ console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e)
136
+ return { failed: "网络错误或超时" }
137
+ }
138
+ }
139
+
140
+ /** 下载一组附件并汇总(bridge 的唯一入口) */
141
+ export async function prepareQQAttachments(
142
+ attachments: MessageAttachment[] | undefined,
143
+ getAuth?: () => Promise<string>,
144
+ ): Promise<PreparedAttachments> {
145
+ if (!attachments?.length) return { files: [], notes: [] }
146
+ const outcomes: AttachmentOutcome[] = []
147
+ for (const att of attachments) outcomes.push(await downloadQQAttachment(att, getAuth))
148
+ return groupOutcomes(outcomes)
149
+ }
150
+
151
+ /** 下载结果分组(纯函数,供单测) */
152
+ export function groupOutcomes(outcomes: AttachmentOutcome[]): PreparedAttachments {
153
+ const files: PromptFile[] = []
154
+ const notes: string[] = []
155
+ for (const o of outcomes) {
156
+ if ("path" in o) {
157
+ files.push({ uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
158
+ } else if ("voice" in o) {
159
+ notes.push(`(语音转写:${o.voice})`)
160
+ } else if ("failed" in o) {
161
+ notes.push(`(图片下载失败:${o.failed})`)
162
+ } else {
163
+ notes.push(`(暂不支持的附件类型:${o.unsupported})`)
164
+ }
165
+ }
166
+ return { files, notes }
167
+ }
168
+
169
+ /**
170
+ * 把附件合成进 prompt(纯函数,供单测):
171
+ * - 有文字:文字保留,失败/不支持备注附在其后
172
+ * - 纯图(无文字):占位文字,模型经 files 直接看到图
173
+ * - 纯失败(图没下下来):备注即正文,QQ 端可见而不是静默
174
+ */
175
+ export function augmentPromptWithAttachments(
176
+ rawContent: string,
177
+ prepared: PreparedAttachments,
178
+ ): { text: string; files: PromptFile[] } {
179
+ const base = rawContent.trim()
180
+ const { files, notes } = prepared
181
+ let text = base
182
+ if (!text && files.length > 0) text = "(用户通过 QQ 发来了图片,未附文字)"
183
+ if (!text && notes.length > 0) text = "(用户通过 QQ 发来了内容,但无法处理)"
184
+ if (notes.length > 0) text = text ? `${text}\n\n${notes.join("\n")}` : notes.join("\n")
185
+ return { text, files }
186
+ }
187
+
188
+ /** 启动清理:删掉 7 天前的落盘图片(只在自己的子目录内操作) */
189
+ export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
190
+ try {
191
+ const dir = imageDir()
192
+ const now = Date.now()
193
+ for (const f of readdirSync(dir)) {
194
+ const full = join(dir, f)
195
+ try {
196
+ if (now - statSync(full).mtimeMs > maxAgeMs) unlinkSync(full)
197
+ } catch {
198
+ /* 单文件失败忽略 */
199
+ }
200
+ }
201
+ } catch {
202
+ /* 目录不存在等忽略 */
203
+ }
204
+ }