@cmach_socket/opencode-qq-bot 0.10.1 → 1.0.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.
@@ -63,7 +63,8 @@ export async function hydrateSegment(
63
63
  const data = segment.data as MediaSegmentData
64
64
  // 已有可用的远程直链时不要覆盖。
65
65
  if (pickRemoteUrl(data.url)) return
66
- const fileId = data.file ?? data.file_id
66
+ // 文件段的 `file` 多是本地路径或文件名,优先用 `file_id` 找直链。
67
+ const fileId = segment.type === "file" ? (data.file_id ?? data.file) : (data.file ?? data.file_id)
67
68
  if (typeof fileId !== "string" || fileId.length === 0) return
68
69
  if (/^(file|base64|data):/i.test(fileId)) return
69
70
 
@@ -4,7 +4,7 @@ import type { Logger } from "../logger"
4
4
  import type { Role } from "../tools/policy"
5
5
  import { formatModelMessage, sanitizeSenderName } from "../model-view"
6
6
  import type { MediaStore } from "./media"
7
- import { createImageBudget, renderMessage, type PromptFile, type RenderContext } from "./render"
7
+ import { createPromptBudget, renderMessage, type PromptFile, type RenderContext } from "./render"
8
8
 
9
9
  /** 已经投递到的位置:消息 ID 与发送时间。 */
10
10
  export interface HistoryPosition {
@@ -77,8 +77,8 @@ export function createHistoryProvider(deps: {
77
77
  : await fetchLatest(ctx, count, options.exclude)
78
78
  if (entries.length === 0) return { text: "", files: [] }
79
79
 
80
- // 整批历史共用一份图片预算,避免单次回填塞爆上下文。
81
- const budget = createImageBudget()
80
+ // 整批历史共用一份附件预算,避免单次回填塞爆上下文。
81
+ const budget = createPromptBudget()
82
82
  const lines: string[] = []
83
83
  const files: PromptFile[] = []
84
84
  for (const entry of entries) {
@@ -13,6 +13,8 @@ export const MAX_IMAGE_BYTES = 5 * 1024 * 1024
13
13
  export const IMAGE_FETCH_TIMEOUT_MS = 15_000
14
14
  /** 临时图片的保留时间。 */
15
15
  export const MEDIA_TTL_MS = 7 * 24 * 60 * 60 * 1000
16
+ /** 单个入站文件(图片以外)的下载字节上限。 */
17
+ export const MAX_DOCUMENT_BYTES = 20 * 1024 * 1024
16
18
 
17
19
  export interface PromptFile {
18
20
  uri: string
@@ -21,11 +23,35 @@ export interface PromptFile {
21
23
  bytes?: number
22
24
  /** 文件来源;file: 引用会标记为 uri。 */
23
25
  source?: { type: "inline" } | { type: "uri"; uri: string }
26
+ /** 附件类型;缺省按图片处理,兼容只带 uri 的旧调用。 */
27
+ kind?: "image" | "file"
28
+ /** 落盘文件的扩展名,不含点。 */
29
+ ext?: string
30
+ /** 落盘文件的内容哈希,用于 `qq_download_file` 定位。 */
31
+ id?: string
24
32
  }
25
33
 
26
34
  export interface StoredImage extends PromptFile {
27
35
  /** 图片扩展名,不含点。 */
28
36
  ext: string
37
+ kind: "image"
38
+ }
39
+
40
+ /** 入站文件的读取结果。 */
41
+ export interface DocumentRead {
42
+ /** 原始字节数。 */
43
+ bytes: number
44
+ /** 文本正文;二进制文件为 undefined。 */
45
+ text?: string
46
+ /** 落盘后的附件;文本文件同样落盘,便于按需分页读取。 */
47
+ file: PromptFile
48
+ }
49
+
50
+ /** 按 id 找到的落盘文件。 */
51
+ export interface StoredFile {
52
+ path: string
53
+ ext: string
54
+ size: number
29
55
  }
30
56
 
31
57
  interface ImageBytes {
@@ -33,6 +59,12 @@ interface ImageBytes {
33
59
  mime: string
34
60
  }
35
61
 
62
+ interface RawBytes {
63
+ bytes: Uint8Array
64
+ /** 响应声明的内容类型,只作参考。 */
65
+ mime?: string
66
+ }
67
+
36
68
  const MIME_EXTENSIONS: Record<string, string> = {
37
69
  "image/png": "png",
38
70
  "image/jpeg": "jpg",
@@ -80,33 +112,82 @@ export function inlineImageBytes(uri: string): number {
80
112
  return Math.floor(((uri.length - comma - 1) * 3) / 4)
81
113
  }
82
114
 
83
- /** 按 Unicode 码点截断,避免切断代理对。 */
115
+ /** 按 Unicode 码点截断,避免切断代理对;大文本也不会先摊平成数组。 */
84
116
  function truncateCodePoints(text: string, max: number): string {
85
- return Array.from(text).slice(0, max).join("")
117
+ if (max <= 0) return ""
118
+ let kept = ""
119
+ let count = 0
120
+ for (const char of text) {
121
+ if (count >= max) break
122
+ kept += char
123
+ count += 1
124
+ }
125
+ return kept
86
126
  }
87
127
 
88
- function decodeBase64Bytes(value: string): Uint8Array | undefined {
128
+ function decodeBase64Bytes(value: string, maxBytes = MAX_IMAGE_BYTES): Uint8Array | undefined {
89
129
  if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(value)) return undefined
90
130
  const bytes = Buffer.from(value, "base64")
91
- return bytes.byteLength > MAX_IMAGE_BYTES ? undefined : new Uint8Array(bytes)
131
+ return bytes.byteLength > maxBytes ? undefined : new Uint8Array(bytes)
132
+ }
133
+
134
+ /**
135
+ * 取一个可以落盘、可以展示的文件名:去掉路径、控制字符与前导点。
136
+ *
137
+ * 文件名会进提示词的占位文本,也会作为附件名交给 OpenCode,
138
+ * 尖括号与引号能伪造结构标签,这里换成全角与单引号。
139
+ */
140
+ export function safeDocumentName(value: string): string {
141
+ const base =
142
+ String(value ?? "")
143
+ .split(/[\\/]/u)
144
+ .pop() ?? ""
145
+ const cleaned = base
146
+ .replace(/[\u0000-\u001F\u007F]/gu, "")
147
+ .replace(/^\.+/u, "")
148
+ .trim()
149
+ const neutralized = cleaned
150
+ .replace(/[<>]/gu, (char) => (char === "<" ? "<" : ">"))
151
+ .replace(/"/gu, "'")
152
+ return Array.from(neutralized).slice(0, 120).join("") || "文件"
153
+ }
154
+
155
+ /** 从文件名里取扩展名;没有可用扩展名时按内容类型回退。 */
156
+ function documentExtension(name: string, mime: string | undefined): string {
157
+ const match = /\.([A-Za-z0-9]{1,10})$/u.exec(name)
158
+ if (match?.[1]) return match[1].toLowerCase()
159
+ return (mime ? MIME_EXTENSIONS[mime] : undefined) ?? "bin"
160
+ }
161
+
162
+ /**
163
+ * 按 UTF-8 解码文本文件,二进制文件返回 `undefined`。
164
+ *
165
+ * NUL 字节是二进制最可靠的信号;UTF-16 文本也会因此按二进制处理。
166
+ * 解码失败(非法 UTF-8)同样按二进制处理。
167
+ */
168
+ export function decodeTextDocument(bytes: Uint8Array): string | undefined {
169
+ if (bytes.byteLength > MAX_DOCUMENT_BYTES) return undefined
170
+ if (bytes.includes(0)) return undefined
171
+ try {
172
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes)
173
+ } catch {
174
+ return undefined
175
+ }
92
176
  }
93
177
 
94
- function parseDataUrl(uri: string, logger: Logger): ImageBytes | undefined {
178
+ interface ParsedDataUrl {
179
+ bytes: Uint8Array
180
+ /** URI 里声明的类型,只作参考。 */
181
+ declared?: string
182
+ }
183
+
184
+ function parseDataUrl(uri: string, maxBytes: number): ParsedDataUrl | undefined {
95
185
  const match = /^data:([^;,]+)?(?:;[^,]*)*;base64,(.*)$/s.exec(uri)
96
186
  if (!match) return undefined
97
- const bytes = decodeBase64Bytes(match[2] ?? "")
187
+ const bytes = decodeBase64Bytes(match[2] ?? "", maxBytes)
98
188
  if (!bytes) return undefined
99
- // 以魔数嗅探为准:URI 里声明的类型由消息发送方控制,不能直接信任。
100
- const mime = mimeFromBytes(bytes)
101
- if (!mime) {
102
- logger.warn("data URL 图片类型无法识别")
103
- return undefined
104
- }
105
189
  const declared = match[1]?.trim()
106
- if (declared && declared !== mime) {
107
- logger.warn(`data URL 声明类型与实际内容不符 declared=${declared} actual=${mime}`)
108
- }
109
- return { bytes, mime }
190
+ return declared ? { bytes, declared } : { bytes }
110
191
  }
111
192
 
112
193
  /**
@@ -134,26 +215,85 @@ export class MediaStore {
134
215
  async storeImage(url: string): Promise<StoredImage | undefined> {
135
216
  const image = await this.readImage(url)
136
217
  if (!image) return undefined
137
- return this.storeBytes(image.bytes, image.mime)
218
+ const ext = MIME_EXTENSIONS[image.mime] ?? "bin"
219
+ const stored = await this.storeBytes(image.bytes, ext, "image")
220
+ return { ...stored, ext, kind: "image" }
221
+ }
222
+
223
+ /**
224
+ * 下载一条入站文件并落盘。
225
+ *
226
+ * 文本文件同样落盘,渲染时能内联就内联,超出额度时留 id 给 `qq_download_file` 定位。
227
+ */
228
+ async storeDocument(url: string, name: string): Promise<DocumentRead | undefined> {
229
+ const raw = await this.readRaw(url, MAX_DOCUMENT_BYTES)
230
+ if (!raw) return undefined
231
+ const text = decodeTextDocument(raw.bytes)
232
+ const safe = safeDocumentName(name)
233
+ const ext = text === undefined ? documentExtension(safe, raw.mime) : "txt"
234
+ const file = await this.storeBytes(raw.bytes, ext, "file", safe)
235
+ return { bytes: raw.bytes.byteLength, file, ...(text === undefined ? {} : { text }) }
236
+ }
237
+
238
+ /** 按 id 前缀定位落盘文件;id 只接受内容哈希的十六进制前缀。 */
239
+ async locate(id: string): Promise<StoredFile | undefined> {
240
+ const prefix = id.trim().toLowerCase()
241
+ if (!/^[0-9a-f]{8,64}$/u.test(prefix)) return undefined
242
+ let entries: string[]
243
+ try {
244
+ entries = await readdir(this.root)
245
+ } catch {
246
+ return undefined
247
+ }
248
+ const matches = entries.filter((entry) => entry.startsWith(prefix))
249
+ if (matches.length !== 1) return undefined
250
+ const file = matches[0] as string
251
+ const path = join(this.root, file)
252
+ try {
253
+ const info = await stat(path)
254
+ if (!info.isFile()) return undefined
255
+ return { path, ext: file.slice(file.lastIndexOf(".") + 1), size: info.size }
256
+ } catch {
257
+ return undefined
258
+ }
138
259
  }
139
260
 
140
261
  private async readImage(url: string): Promise<ImageBytes | undefined> {
262
+ const raw = await this.readRaw(url, MAX_IMAGE_BYTES)
263
+ if (!raw) return undefined
264
+ // 声明类型只能当参考:服务器可能把 HTML 标成 image/png,或返回不支持的 svg。
265
+ const declared = raw.mime
266
+ const mime = mimeFromBytes(raw.bytes)
267
+ if (!mime) {
268
+ this.logger.warn(`图片类型无法识别 url=${truncateForLog(url)} declared=${declared ?? "无"}`)
269
+ return undefined
270
+ }
271
+ if (declared?.startsWith("image/") === true && declared !== mime) {
272
+ this.logger.warn(`图片类型与声明不一致 declared=${declared} actual=${mime} url=${url}`)
273
+ }
274
+ return { bytes: raw.bytes, mime }
275
+ }
276
+
277
+ /** 下载或解码一份内容,按 `maxBytes` 拦截超限内容。 */
278
+ private async readRaw(url: string, maxBytes: number): Promise<RawBytes | undefined> {
141
279
  if (url.startsWith("base64://")) {
142
- const bytes = decodeBase64Bytes(url.slice("base64://".length))
280
+ const bytes = decodeBase64Bytes(url.slice("base64://".length), maxBytes)
143
281
  if (!bytes) {
144
- this.logger.warn("base64 图片无效或超过大小上限")
282
+ this.logger.warn("base64 内容无效或超过大小上限")
145
283
  return undefined
146
284
  }
147
- const mime = mimeFromBytes(bytes)
148
- if (!mime) {
149
- this.logger.warn("base64 图片类型无法识别")
285
+ return { bytes }
286
+ }
287
+ if (url.startsWith("data:")) {
288
+ const parsed = parseDataUrl(url, maxBytes)
289
+ if (!parsed) {
290
+ this.logger.warn("data URL 内容无效或超过大小上限")
150
291
  return undefined
151
292
  }
152
- return { bytes, mime }
293
+ return { bytes: parsed.bytes, ...(parsed.declared ? { mime: parsed.declared } : {}) }
153
294
  }
154
- if (url.startsWith("data:")) return parseDataUrl(url, this.logger)
155
295
  if (!url.startsWith("http://") && !url.startsWith("https://")) {
156
- this.logger.warn(`不支持的图片地址,跳过下载 url=${truncateForLog(url)}`)
296
+ this.logger.warn(`不支持的地址,跳过下载 url=${truncateForLog(url)}`)
157
297
  return undefined
158
298
  }
159
299
 
@@ -164,33 +304,26 @@ export class MediaStore {
164
304
  return undefined
165
305
  }
166
306
  const response = await this.fetcher(parsed, {
167
- maxBytes: MAX_IMAGE_BYTES,
307
+ maxBytes,
168
308
  timeoutMs: IMAGE_FETCH_TIMEOUT_MS,
169
309
  logger: this.logger,
170
310
  })
171
311
  if (!response) return undefined
172
- if (response.bytes.byteLength > MAX_IMAGE_BYTES) {
173
- this.logger.warn(`图片过大,跳过下载 bytes=${response.bytes.byteLength} url=${url}`)
174
- return undefined
175
- }
176
-
177
- // 声明类型只能当参考:服务器可能把 HTML 标成 image/png,或返回不支持的 svg。
178
- const declared = response.contentType?.split(";")[0]?.trim()
179
- const mime = mimeFromBytes(response.bytes)
180
- if (!mime) {
181
- this.logger.warn(`图片类型无法识别 url=${url} declared=${declared ?? "无"}`)
312
+ if (response.bytes.byteLength > maxBytes) {
313
+ this.logger.warn(`内容过大,跳过下载 bytes=${response.bytes.byteLength} url=${url}`)
182
314
  return undefined
183
315
  }
184
- if (declared?.startsWith("image/") === true && declared !== mime) {
185
- this.logger.warn(`图片类型与声明不一致 declared=${declared} actual=${mime} url=${url}`)
186
- }
187
- return { bytes: response.bytes, mime }
316
+ return { bytes: response.bytes, mime: response.contentType?.split(";")[0]?.trim() }
188
317
  }
189
318
 
190
- private async storeBytes(bytes: Uint8Array, mime: string): Promise<StoredImage> {
319
+ private async storeBytes(
320
+ bytes: Uint8Array,
321
+ ext: string,
322
+ kind: "image" | "file",
323
+ name?: string,
324
+ ): Promise<PromptFile> {
191
325
  await this.ensureRoot()
192
326
  const hash = createHash("sha256").update(bytes).digest("hex")
193
- const ext = MIME_EXTENSIONS[mime] ?? "bin"
194
327
  const path = join(this.root, `${hash}.${ext}`)
195
328
  try {
196
329
  await access(path)
@@ -200,10 +333,12 @@ export class MediaStore {
200
333
  const uri = pathToFileURL(path).href
201
334
  return {
202
335
  uri,
203
- name: `qq-image-${hash.slice(0, 8)}.${ext}`,
336
+ name: name ?? `qq-${kind}-${hash.slice(0, 8)}.${ext}`,
204
337
  bytes: bytes.byteLength,
205
338
  source: { type: "uri", uri },
206
339
  ext,
340
+ kind,
341
+ id: hash,
207
342
  }
208
343
  }
209
344