@linjz/opencode-qqbot 0.3.4 → 0.3.6

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 (42) hide show
  1. package/README.md +74 -37
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +10 -1
  5. package/dist/openqq-bot.js +360 -69
  6. package/package.json +69 -59
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +934 -796
  9. package/src/commands.ts +554 -514
  10. package/src/config.ts +121 -121
  11. package/src/core/bot-launcher.ts +146 -134
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +284 -284
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -0
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +304 -304
  19. package/src/core/inflight-journal.ts +212 -151
  20. package/src/core/instance-lock.ts +122 -122
  21. package/src/core/linkwatch.ts +195 -195
  22. package/src/core/message-queue.ts +80 -0
  23. package/src/core/mirror.ts +173 -173
  24. package/src/core/permission.ts +301 -301
  25. package/src/core/reply-limiter.ts +106 -106
  26. package/src/core/send-media.ts +90 -90
  27. package/src/core/util.ts +8 -8
  28. package/src/index.ts +162 -162
  29. package/src/opencode/_FOLDER.md +11 -11
  30. package/src/opencode/client.ts +387 -386
  31. package/src/opencode/eventstream.ts +138 -138
  32. package/src/opencode/history.ts +143 -143
  33. package/src/opencode/mirror.ts +65 -65
  34. package/src/opencode/sessions.ts +158 -158
  35. package/src/plugin-entry.ts +112 -112
  36. package/src/qq/_FOLDER.md +13 -13
  37. package/src/qq/api.ts +539 -539
  38. package/src/qq/gateway.ts +492 -492
  39. package/src/qq/media.ts +219 -204
  40. package/src/qq/sender.ts +300 -300
  41. package/src/qq/types.ts +154 -152
  42. package/tsconfig.json +24 -24
package/src/qq/media.ts CHANGED
@@ -1,204 +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 } 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
- }
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
+ }