@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/gateway.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // @pos: qq层 - QQ Bot WebSocket Gateway 状态机 (心跳/重连/消息分发)
4
4
  import WebSocket from "ws"
5
5
  import { acknowledgeInteraction, clearTokenCache, getAccessToken, getGatewayUrl } from "./api.js"
6
+ import { clearGatewayState, loadGatewayState, saveGatewayState } from "../core/gateway-state.js"
6
7
  import type {
7
8
  C2CMessageEvent,
8
9
  GatewayHelloData,
@@ -49,8 +50,8 @@ interface GatewayState {
49
50
  sessionId: string | null
50
51
  seq: number | null
51
52
  heartbeatAcked: boolean
52
- /** 去重(缺口 3):resume/重连后平台可能重投同一消息,msgId LRU 防重复触发回合 */
53
- seenMsgIds: Set<string>
53
+ /** 仅拦截活跃并发/重入;处理完成后释放,同 msgId 可显式重投 */
54
+ activeMsgIds: Set<string>
54
55
  }
55
56
 
56
57
  interface GatewayControl {
@@ -58,7 +59,7 @@ interface GatewayControl {
58
59
  }
59
60
 
60
61
  function createInitialState(): GatewayState {
61
- return {
62
+ const state: GatewayState = {
62
63
  ws: null,
63
64
  stopped: false,
64
65
  connecting: false,
@@ -69,22 +70,37 @@ function createInitialState(): GatewayState {
69
70
  sessionId: null,
70
71
  seq: null,
71
72
  heartbeatAcked: true,
72
- seenMsgIds: new Set(),
73
+ activeMsgIds: new Set(),
74
+ }
75
+ // 修复②:从磁盘恢复 session/seq——重启优先 RESUME(服务端只补断线窗口的
76
+ // 事件),不再 IDENTIFY 从零重放 backlog。超龄/缺损/RESUME 被拒(op9)时
77
+ // 自动回退 IDENTIFY,无死循环。加载失败静默走老路径,不阻塞启动。
78
+ const saved = loadGatewayState()
79
+ if (saved) {
80
+ state.sessionId = saved.session_id
81
+ state.seq = saved.seq
82
+ const agoSec = Math.max(0, Math.round((Date.now() - saved.savedAt) / 1000))
83
+ console.log(`[gateway] 已从磁盘恢复网关状态(${agoSec}s 前),将尝试 RESUME session=${saved.session_id} seq=${saved.seq}`)
73
84
  }
85
+ return state
74
86
  }
75
87
 
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)
88
+ // msgId 防重改为「活跃期保护」:占位→处理→finally 释放,
89
+ // 同 msgId 并发/重入丢弃(resume 重回补防御);处理完成后可显式重投。
90
+ // 持久兜底(跨重启、排队中)由 bridge 的 inflight 台账负责。
91
+ function tryClaimActive(active: Set<string>, msgId: string): boolean {
92
+ if (active.has(msgId)) return false
93
+ // 防御性上限:正常路径靠 finally 释放不会积累;到达上限说明出现泄漏式积压,
94
+ // 此时放弃新增保护(宁可接受极小概率重投,也不无限吞掉新消息)
95
+ if (active.size >= 1000) return true
96
+ active.add(msgId)
85
97
  return true
86
98
  }
87
99
 
100
+ function releaseActive(active: Set<string>, msgId: string): void {
101
+ active.delete(msgId)
102
+ }
103
+
88
104
  function cleanupSocket(state: GatewayState): void {
89
105
  if (state.heartbeatTimer) {
90
106
  clearInterval(state.heartbeatTimer)
@@ -146,6 +162,9 @@ function startHeartbeat(state: GatewayState, intervalMs: number): void {
146
162
  function resetResumeState(state: GatewayState): void {
147
163
  state.sessionId = null
148
164
  state.seq = null
165
+ // 修复②:服务端明确作废会话(op9 不可恢复/Resume 失效码)→ 持久化状态同步清账,
166
+ // 下次启动不得再拿已作废的 session 去 RESUME。
167
+ clearGatewayState()
149
168
  }
150
169
 
151
170
  function normalizeMessageContent(content: string): string {
@@ -254,6 +273,8 @@ async function handleDispatchEvent(
254
273
  case "READY": {
255
274
  const readyData = payload.d as GatewayReadyData
256
275
  state.sessionId = readyData.session_id
276
+ // 修复②:新会话确立即落盘(含 RESUME 失败回退 IDENTIFY 后的新会话)
277
+ if (state.seq !== null) saveGatewayState(state.sessionId, state.seq)
257
278
  // R 项诊断增强(2026-10-30):首连/重连分界可见——重连后的 READY 打日志,
258
279
  // 下次"消息静默丢失"类事故可直接从日志定位断链窗口
259
280
  if (state.reconnectAttempt > 0) {
@@ -266,51 +287,70 @@ async function handleDispatchEvent(
266
287
 
267
288
  case "RESUMED": {
268
289
  console.log("[gateway] 会话已恢复(RESUMED,断线期间事件已回补)")
290
+ // 修复②:心跳延续,落盘一次刷新 savedAt(防窗口使用过期源)
291
+ if (state.sessionId && state.seq !== null) saveGatewayState(state.sessionId, state.seq)
269
292
  state.reconnectAttempt = 0
270
293
  return
271
294
  }
272
295
 
273
296
  case "C2C_MESSAGE_CREATE": {
274
297
  const event = payload.d as C2CMessageEvent
275
- // 缺口 3:重投去重(resume 后同 id 再来不重复触发)
276
- if (!markSeenAndFilter(state.seenMsgIds, event.id)) return
298
+ // 活跃期防重:同 id 并发/重入丢弃;处理完成后 finally 释放,可显式重投
299
+ if (!tryClaimActive(state.activeMsgIds, event.id)) return
277
300
  const message = toC2CMessageContext(event)
278
301
  if (message.attachments?.length) {
279
302
  // R2-P2-1:打码载荷(签名 URL 不入日志),host/类型/大小够 B7 校准
280
303
  console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)))
281
304
  }
282
305
  if (!message.content && !message.attachments?.length) {
306
+ releaseActive(state.activeMsgIds, event.id)
283
307
  return
284
308
  }
285
- await options.onMessage(message)
309
+ try {
310
+ await options.onMessage(message)
311
+ } finally {
312
+ releaseActive(state.activeMsgIds, event.id)
313
+ }
286
314
  return
287
315
  }
288
316
 
289
317
  case "GROUP_AT_MESSAGE_CREATE": {
290
318
  const event = payload.d as GroupMessageEvent
291
- if (!markSeenAndFilter(state.seenMsgIds, event.id)) return
319
+ if (!tryClaimActive(state.activeMsgIds, event.id)) return
292
320
  const message = toGroupMessageContext(event)
293
321
  if (message.attachments?.length) {
294
322
  // R2-P2-1:打码载荷(签名 URL 不入日志)
295
323
  console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)))
296
324
  }
297
325
  if (!message.content && !message.attachments?.length) {
326
+ releaseActive(state.activeMsgIds, event.id)
298
327
  return
299
328
  }
300
- await options.onMessage(message)
329
+ try {
330
+ await options.onMessage(message)
331
+ } finally {
332
+ releaseActive(state.activeMsgIds, event.id)
333
+ }
301
334
  return
302
335
  }
303
336
 
304
337
  case "INTERACTION_CREATE": {
305
338
  // A 项(2026-10-29):按钮互动回调。平台要求 3 秒内响应且同 id 只能
306
- // 响应一次——先立即 ack(不等业务处理结果),再分发业务。
339
+ // 响应一次。分发先于 ACK:业务的同步前缀(表单点击持久化落盘等)
340
+ // 必须在 ACK 之前完成,否则「ACK 后进程崩溃」可能丢掉这次点击。
341
+ // 不等待其异步结果;同步抛出的异常进入被捕获的 Promise 链:
342
+ // ① 同步分发仍已执行,② ACK 照常发出。
307
343
  const interaction = payload.d as InteractionEvent
344
+ void Promise.resolve()
345
+ .then(() => options.onInteraction?.(interaction))
346
+ .catch((error) => {
347
+ console.error("[qq-gateway] 互动业务分发失败:", error instanceof Error ? error.message : error)
348
+ })
308
349
  if (state.accessToken && interaction?.id) {
309
350
  void acknowledgeInteraction(state.accessToken, interaction.id).catch((error) => {
310
351
  console.error("[qq-gateway] 互动响应失败:", error instanceof Error ? error.message : error)
311
352
  })
312
353
  }
313
- await options.onInteraction?.(interaction)
314
354
  return
315
355
  }
316
356
 
@@ -327,7 +367,16 @@ async function handlePayload(
327
367
  connect: () => Promise<void>,
328
368
  ): Promise<void> {
329
369
  if (typeof payload.s === "number") {
370
+ const prevSeq = state.seq
330
371
  state.seq = payload.s
372
+ // 修复②:session 已确立时把 seq 推进原子落盘(重启恢复窗口的基石)。
373
+ // 跳号>1 经验上=断线窗口被服务端回补(重放可见性,2026-11-03 定案要求观测日志)。
374
+ if (state.sessionId && payload.s !== prevSeq) {
375
+ if (prevSeq !== null && payload.s > prevSeq + 1) {
376
+ console.log(`[gateway] seq 回补 ${payload.s - prevSeq - 1} 帧(${prevSeq} → ${payload.s})——断线期间载荷已重放`)
377
+ }
378
+ saveGatewayState(state.sessionId, payload.s)
379
+ }
331
380
  }
332
381
 
333
382
  switch (payload.op) {
package/src/qq/media.ts CHANGED
@@ -1,219 +1,219 @@
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, readFileSync } 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
- // 桌面 TUI 预览实证通道:≤2MB 的图片用 data: URL(opencode 对 data: 内嵌预览友好);
158
- // 大图/非图保留 file:// 路径(避免 base64 膨胀)。
159
- const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024)
160
- files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
161
- } else if ("voice" in o) {
162
- notes.push(`(语音转写:${o.voice})`)
163
- } else if ("failed" in o) {
164
- notes.push(`(图片下载失败:${o.failed})`)
165
- } else {
166
- notes.push(`(暂不支持的附件类型:${o.unsupported})`)
167
- }
168
- }
169
- return { files, notes }
170
- }
171
-
172
- // 小图转 data: URL(失败回退 null 走 file://),仅用于桌面预览友好化
173
- function tryImageDataUrl(path: string, maxBytes: number): string | null {
174
- try {
175
- const st = statSync(path)
176
- if (st.size > maxBytes) return null
177
- const b = readFileSync(path)
178
- return `data:image/png;base64,${b.toString("base64")}`
179
- } catch {
180
- return null
181
- }
182
- }
183
-
184
- /**
185
- * 把附件合成进 prompt(纯函数,供单测):
186
- * - 有文字:文字保留,失败/不支持备注附在其后
187
- * - 纯图(无文字):占位文字,模型经 files 直接看到图
188
- * - 纯失败(图没下下来):备注即正文,QQ 端可见而不是静默
189
- */
190
- export function augmentPromptWithAttachments(
191
- rawContent: string,
192
- prepared: PreparedAttachments,
193
- ): { text: string; files: PromptFile[] } {
194
- const base = rawContent.trim()
195
- const { files, notes } = prepared
196
- let text = base
197
- if (!text && files.length > 0) text = "(用户通过 QQ 发来了图片,未附文字)"
198
- if (!text && notes.length > 0) text = "(用户通过 QQ 发来了内容,但无法处理)"
199
- if (notes.length > 0) text = text ? `${text}\n\n${notes.join("\n")}` : notes.join("\n")
200
- return { text, files }
201
- }
202
-
203
- /** 启动清理:删掉 7 天前的落盘图片(只在自己的子目录内操作) */
204
- export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
205
- try {
206
- const dir = imageDir()
207
- const now = Date.now()
208
- for (const f of readdirSync(dir)) {
209
- const full = join(dir, f)
210
- try {
211
- if (now - statSync(full).mtimeMs > maxAgeMs) unlinkSync(full)
212
- } catch {
213
- /* 单文件失败忽略 */
214
- }
215
- }
216
- } catch {
217
- /* 目录不存在等忽略 */
218
- }
219
- }
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, readFileSync } 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
+ // 桌面 TUI 预览实证通道:≤2MB 的图片用 data: URL(opencode 对 data: 内嵌预览友好);
158
+ // 大图/非图保留 file:// 路径(避免 base64 膨胀)。
159
+ const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024)
160
+ files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name })
161
+ } else if ("voice" in o) {
162
+ notes.push(`(语音转写:${o.voice})`)
163
+ } else if ("failed" in o) {
164
+ notes.push(`(图片下载失败:${o.failed})`)
165
+ } else {
166
+ notes.push(`(暂不支持的附件类型:${o.unsupported})`)
167
+ }
168
+ }
169
+ return { files, notes }
170
+ }
171
+
172
+ // 小图转 data: URL(失败回退 null 走 file://),仅用于桌面预览友好化
173
+ function tryImageDataUrl(path: string, maxBytes: number): string | null {
174
+ try {
175
+ const st = statSync(path)
176
+ if (st.size > maxBytes) return null
177
+ const b = readFileSync(path)
178
+ return `data:image/png;base64,${b.toString("base64")}`
179
+ } catch {
180
+ return null
181
+ }
182
+ }
183
+
184
+ /**
185
+ * 把附件合成进 prompt(纯函数,供单测):
186
+ * - 有文字:文字保留,失败/不支持备注附在其后
187
+ * - 纯图(无文字):占位文字,模型经 files 直接看到图
188
+ * - 纯失败(图没下下来):备注即正文,QQ 端可见而不是静默
189
+ */
190
+ export function augmentPromptWithAttachments(
191
+ rawContent: string,
192
+ prepared: PreparedAttachments,
193
+ ): { text: string; files: PromptFile[] } {
194
+ const base = rawContent.trim()
195
+ const { files, notes } = prepared
196
+ let text = base
197
+ if (!text && files.length > 0) text = "(用户通过 QQ 发来了图片,未附文字)"
198
+ if (!text && notes.length > 0) text = "(用户通过 QQ 发来了内容,但无法处理)"
199
+ if (notes.length > 0) text = text ? `${text}\n\n${notes.join("\n")}` : notes.join("\n")
200
+ return { text, files }
201
+ }
202
+
203
+ /** 启动清理:删掉 7 天前的落盘图片(只在自己的子目录内操作) */
204
+ export function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000): void {
205
+ try {
206
+ const dir = imageDir()
207
+ const now = Date.now()
208
+ for (const f of readdirSync(dir)) {
209
+ const full = join(dir, f)
210
+ try {
211
+ if (now - statSync(full).mtimeMs > maxAgeMs) unlinkSync(full)
212
+ } catch {
213
+ /* 单文件失败忽略 */
214
+ }
215
+ }
216
+ } catch {
217
+ /* 目录不存在等忽略 */
218
+ }
219
+ }