@linjz/opencode-qqbot 0.3.20 → 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.
@@ -5033,12 +5033,12 @@ async function startGateway(options) {
5033
5033
  }
5034
5034
 
5035
5035
  // src/bridge.ts
5036
- import { existsSync as existsSync16, readFileSync as readFileSync18, mkdirSync as mkdirSync15, writeFileSync as writeFileSync16 } from "fs";
5036
+ import { existsSync as existsSync16, readFileSync as readFileSync19, mkdirSync as mkdirSync15, writeFileSync as writeFileSync16 } from "fs";
5037
5037
  import { join as join13 } from "path";
5038
5038
  import { homedir as homedir7 } from "os";
5039
5039
 
5040
5040
  // src/qq/media.ts
5041
- import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync7 } from "node:fs";
5041
+ import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync8 } from "node:fs";
5042
5042
  import { join as join6 } from "node:path";
5043
5043
  import { tmpdir } from "node:os";
5044
5044
 
@@ -5077,6 +5077,221 @@ async function sttTranscribe(bytes, filename, cfg, fetchImpl = fetch) {
5077
5077
  return text;
5078
5078
  }
5079
5079
 
5080
+ // src/core/office-text.ts
5081
+ import { readFileSync as readFileSync7 } from "node:fs";
5082
+ import { inflateRawSync } from "node:zlib";
5083
+ var MAX_ENTRY_COUNT = 1e4;
5084
+ var MAX_ENTRY_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;
5085
+ var MAX_OFFICE_TEXT_CHARS = 200000;
5086
+ function officeKindForPath(path) {
5087
+ const ext = path.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? "";
5088
+ if (ext === "docx" || ext === "docm")
5089
+ return "docx";
5090
+ if (ext === "xlsx" || ext === "xlsm")
5091
+ return "xlsx";
5092
+ if (ext === "pptx" || ext === "pptm")
5093
+ return "pptx";
5094
+ return null;
5095
+ }
5096
+ function isLegacyOfficePath(path) {
5097
+ return /\.(doc|xls|ppt)$/i.test(path);
5098
+ }
5099
+ function findEndOfCentralDirectory(buf) {
5100
+ const min = Math.max(0, buf.length - 65557);
5101
+ for (let i = buf.length - 22;i >= min; i--) {
5102
+ if (buf.readUInt32LE(i) === 101010256)
5103
+ return i;
5104
+ }
5105
+ throw new Error("不是有效的 ZIP/OOXML 文件");
5106
+ }
5107
+ function readZipEntries(buf) {
5108
+ const eocd = findEndOfCentralDirectory(buf);
5109
+ const count = buf.readUInt16LE(eocd + 10);
5110
+ const centralOffset = buf.readUInt32LE(eocd + 16);
5111
+ if (count > MAX_ENTRY_COUNT)
5112
+ throw new Error("ZIP 条目过多");
5113
+ const entries = new Map;
5114
+ let offset = centralOffset;
5115
+ for (let i = 0;i < count; i++) {
5116
+ if (offset + 46 > buf.length || buf.readUInt32LE(offset) !== 33639248) {
5117
+ throw new Error("ZIP 中央目录损坏");
5118
+ }
5119
+ const flags = buf.readUInt16LE(offset + 8);
5120
+ const method = buf.readUInt16LE(offset + 10);
5121
+ const compressedSize = buf.readUInt32LE(offset + 20);
5122
+ const uncompressedSize = buf.readUInt32LE(offset + 24);
5123
+ const nameLength = buf.readUInt16LE(offset + 28);
5124
+ const extraLength = buf.readUInt16LE(offset + 30);
5125
+ const commentLength = buf.readUInt16LE(offset + 32);
5126
+ const localHeaderOffset = buf.readUInt32LE(offset + 42);
5127
+ const name = buf.subarray(offset + 46, offset + 46 + nameLength).toString("utf8");
5128
+ if (uncompressedSize > MAX_ENTRY_UNCOMPRESSED_BYTES)
5129
+ throw new Error(`ZIP 条目过大:${name}`);
5130
+ entries.set(name, { name, flags, method, compressedSize, uncompressedSize, localHeaderOffset });
5131
+ offset += 46 + nameLength + extraLength + commentLength;
5132
+ }
5133
+ return entries;
5134
+ }
5135
+ function readZipEntry(buf, entry) {
5136
+ if ((entry.flags & 1) !== 0)
5137
+ throw new Error(`加密 ZIP 条目不支持:${entry.name}`);
5138
+ const offset = entry.localHeaderOffset;
5139
+ if (offset + 30 > buf.length || buf.readUInt32LE(offset) !== 67324752) {
5140
+ throw new Error(`ZIP 本地头损坏:${entry.name}`);
5141
+ }
5142
+ const nameLength = buf.readUInt16LE(offset + 26);
5143
+ const extraLength = buf.readUInt16LE(offset + 28);
5144
+ const dataOffset = offset + 30 + nameLength + extraLength;
5145
+ const dataEnd = dataOffset + entry.compressedSize;
5146
+ if (dataEnd > buf.length)
5147
+ throw new Error(`ZIP 数据越界:${entry.name}`);
5148
+ const data = buf.subarray(dataOffset, dataEnd);
5149
+ if (entry.method === 0)
5150
+ return Buffer.from(data);
5151
+ if (entry.method === 8) {
5152
+ const out = inflateRawSync(data);
5153
+ if (out.length !== entry.uncompressedSize)
5154
+ throw new Error(`ZIP 解压长度不符:${entry.name}`);
5155
+ return out;
5156
+ }
5157
+ throw new Error(`ZIP 压缩方式不支持:${entry.name}`);
5158
+ }
5159
+ function xmlUnescape(value) {
5160
+ return value.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16))).replace(/&#([0-9]+);/g, (_, dec) => String.fromCodePoint(Number.parseInt(dec, 10))).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
5161
+ }
5162
+ function attrs(tag) {
5163
+ const out = {};
5164
+ for (const match of tag.matchAll(/([\w:]+)\s*=\s*"([^"]*)"/g)) {
5165
+ out[match[1]] = xmlUnescape(match[2]);
5166
+ }
5167
+ return out;
5168
+ }
5169
+ function normalizeExtractedText(value) {
5170
+ const cleaned = xmlUnescape(value.replace(/<[^>]+>/g, "")).replace(/\r/g, "").split(`
5171
+ `).map((line) => line.replace(/ +/g, " ").trimEnd()).join(`
5172
+ `).replace(/\n{3,}/g, `
5173
+
5174
+ `).trim();
5175
+ return cleaned.length > MAX_OFFICE_TEXT_CHARS ? `${cleaned.slice(0, MAX_OFFICE_TEXT_CHARS)}
5176
+ …(Office 文档内容过长,已截断)` : cleaned;
5177
+ }
5178
+ function extractDocx(entries, zip) {
5179
+ const entry = entries.get("word/document.xml");
5180
+ if (!entry)
5181
+ throw new Error("DOCX 缺少 word/document.xml");
5182
+ const xml = readZipEntry(zip, entry).toString("utf8");
5183
+ const text = xml.replace(/<w:tab\b[^>]*\/>/g, "\t").replace(/<w:br\b[^>]*\/>/g, `
5184
+ `).replace(/<\/w:p>/g, `
5185
+ `).replace(/<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/g, "$1");
5186
+ return normalizeExtractedText(text);
5187
+ }
5188
+ function extractPptx(entries, zip) {
5189
+ const slides = [...entries.keys()].filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name)).sort((a, b) => Number(a.match(/slide(\d+)\.xml$/)?.[1] ?? 0) - Number(b.match(/slide(\d+)\.xml$/)?.[1] ?? 0));
5190
+ if (slides.length === 0)
5191
+ throw new Error("PPTX 缺少幻灯片 XML");
5192
+ const parts = [];
5193
+ for (const [index, name] of slides.entries()) {
5194
+ const xml = readZipEntry(zip, entries.get(name)).toString("utf8");
5195
+ const text = xml.replace(/<a:br\b[^>]*\/>/g, `
5196
+ `).replace(/<\/a:p>/g, `
5197
+ `).replace(/<a:t(?:\s[^>]*)?>([\s\S]*?)<\/a:t>/g, "$1");
5198
+ const cleaned = normalizeExtractedText(text);
5199
+ if (cleaned)
5200
+ parts.push(`## Slide ${index + 1}
5201
+ ${cleaned}`);
5202
+ }
5203
+ return normalizeExtractedText(parts.join(`
5204
+
5205
+ `));
5206
+ }
5207
+ function sharedStrings(entries, zip) {
5208
+ const entry = entries.get("xl/sharedStrings.xml");
5209
+ if (!entry)
5210
+ return [];
5211
+ const xml = readZipEntry(zip, entry).toString("utf8");
5212
+ const out = [];
5213
+ for (const si of xml.matchAll(/<si\b[^>]*>([\s\S]*?)<\/si>/g)) {
5214
+ const texts = [...si[1].matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => xmlUnescape(m[1]));
5215
+ out.push(texts.join(""));
5216
+ }
5217
+ return out;
5218
+ }
5219
+ function workbookSheets(entries, zip) {
5220
+ const workbookEntry = entries.get("xl/workbook.xml");
5221
+ if (!workbookEntry)
5222
+ throw new Error("XLSX 缺少 xl/workbook.xml");
5223
+ const workbook = readZipEntry(zip, workbookEntry).toString("utf8");
5224
+ const rels = new Map;
5225
+ const relEntry = entries.get("xl/_rels/workbook.xml.rels");
5226
+ if (relEntry) {
5227
+ const relXml = readZipEntry(zip, relEntry).toString("utf8");
5228
+ for (const rel of relXml.matchAll(/<Relationship\b[^>]*>/g)) {
5229
+ const a = attrs(rel[0]);
5230
+ if (a.Id && a.Target)
5231
+ rels.set(a.Id, a.Target.replace(/^\//, ""));
5232
+ }
5233
+ }
5234
+ const sheets = [];
5235
+ for (const sheet of workbook.matchAll(/<sheet\b[^>]*\/>/g)) {
5236
+ const a = attrs(sheet[0]);
5237
+ const rid = a["r:id"] ?? a.id;
5238
+ const target = rid ? rels.get(rid) : undefined;
5239
+ const path = target?.startsWith("xl/") ? target : target ? `xl/${target}` : undefined;
5240
+ if (a.name && path && entries.has(path))
5241
+ sheets.push({ name: a.name, path });
5242
+ }
5243
+ if (sheets.length > 0)
5244
+ return sheets;
5245
+ return [...entries.keys()].filter((name) => /^xl\/worksheets\/sheet\d+\.xml$/.test(name)).sort((a, b) => Number(a.match(/sheet(\d+)\.xml$/)?.[1] ?? 0) - Number(b.match(/sheet(\d+)\.xml$/)?.[1] ?? 0)).map((path, index) => ({ name: `Sheet${index + 1}`, path }));
5246
+ }
5247
+ function cellText(cellTag, body, shared) {
5248
+ const type = attrs(cellTag).t;
5249
+ if (type === "s") {
5250
+ const index = Number(body.match(/<v>(\d+)<\/v>/)?.[1] ?? "-1");
5251
+ return shared[index] ?? "";
5252
+ }
5253
+ if (type === "inlineStr") {
5254
+ return [...body.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((m) => xmlUnescape(m[1])).join("");
5255
+ }
5256
+ const value = body.match(/<v>([\s\S]*?)<\/v>/)?.[1];
5257
+ return value === undefined ? "" : xmlUnescape(value);
5258
+ }
5259
+ function extractXlsx(entries, zip) {
5260
+ const shared = sharedStrings(entries, zip);
5261
+ const parts = [];
5262
+ for (const sheet of workbookSheets(entries, zip)) {
5263
+ const xml = readZipEntry(zip, entries.get(sheet.path)).toString("utf8");
5264
+ const rows = [];
5265
+ for (const row of xml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
5266
+ const cells = [];
5267
+ for (const cell of row[1].matchAll(/<c\b([^>]*)>([\s\S]*?)<\/c>/g)) {
5268
+ cells.push(cellText(`<c ${cell[1]}>`, cell[2], shared));
5269
+ }
5270
+ if (cells.some((cell) => cell.trim()))
5271
+ rows.push(cells.join("\t").trimEnd());
5272
+ }
5273
+ if (rows.length > 0)
5274
+ parts.push(`## Sheet: ${sheet.name}
5275
+ ${rows.join(`
5276
+ `)}`);
5277
+ }
5278
+ return normalizeExtractedText(parts.join(`
5279
+
5280
+ `));
5281
+ }
5282
+ function extractOfficeTextFromFile(filePath) {
5283
+ const kind = officeKindForPath(filePath);
5284
+ if (!kind)
5285
+ throw new Error("不是支持的 Office 文档格式");
5286
+ const zip = readFileSync7(filePath);
5287
+ const entries = readZipEntries(zip);
5288
+ if (kind === "docx")
5289
+ return extractDocx(entries, zip);
5290
+ if (kind === "pptx")
5291
+ return extractPptx(entries, zip);
5292
+ return extractXlsx(entries, zip);
5293
+ }
5294
+
5080
5295
  // src/qq/media.ts
5081
5296
  function extForImageMime(mime) {
5082
5297
  const m = (mime || "").toLowerCase().split(";")[0].trim();
@@ -5088,6 +5303,7 @@ function extForImageMime(mime) {
5088
5303
  return null;
5089
5304
  }
5090
5305
  var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
5306
+ var MAX_FILE_BYTES = 20 * 1024 * 1024;
5091
5307
  var ALLOWED_HOST_SUFFIXES = [".qpic.cn", ".qq.com", ".qq.com.cn"];
5092
5308
  function isAllowedDownloadHost(url) {
5093
5309
  try {
@@ -5103,6 +5319,9 @@ function isAllowedDownloadHost(url) {
5103
5319
  function imageDir() {
5104
5320
  return join6(tmpdir(), "opencode", "qq-images");
5105
5321
  }
5322
+ function fileDir() {
5323
+ return join6(tmpdir(), "opencode", "qq-files");
5324
+ }
5106
5325
  async function fetchWithTimeout(url, ms, auth) {
5107
5326
  const ctrl = new AbortController;
5108
5327
  const timer = setTimeout(() => ctrl.abort(), ms);
@@ -5115,6 +5334,112 @@ async function fetchWithTimeout(url, ms, auth) {
5115
5334
  clearTimeout(timer);
5116
5335
  }
5117
5336
  }
5337
+ var TEXT_FILE_EXTENSIONS = new Set([
5338
+ "txt",
5339
+ "md",
5340
+ "markdown",
5341
+ "json",
5342
+ "jsonc",
5343
+ "log",
5344
+ "csv",
5345
+ "tsv",
5346
+ "xml",
5347
+ "yaml",
5348
+ "yml",
5349
+ "toml",
5350
+ "ini",
5351
+ "cfg",
5352
+ "conf",
5353
+ "js",
5354
+ "mjs",
5355
+ "cjs",
5356
+ "ts",
5357
+ "tsx",
5358
+ "jsx",
5359
+ "py",
5360
+ "java",
5361
+ "go",
5362
+ "rs",
5363
+ "c",
5364
+ "h",
5365
+ "cpp",
5366
+ "hpp",
5367
+ "cs",
5368
+ "sql",
5369
+ "sh",
5370
+ "ps1",
5371
+ "bat",
5372
+ "cmd",
5373
+ "html",
5374
+ "htm",
5375
+ "css",
5376
+ "scss",
5377
+ "less",
5378
+ "vue",
5379
+ "svelte"
5380
+ ]);
5381
+ function classifyFileAttachment(att) {
5382
+ const filename = (att.filename || "").toLowerCase();
5383
+ const contentType = (att.content_type || "").toLowerCase().split(";")[0].trim();
5384
+ if (isLegacyOfficePath(filename))
5385
+ return null;
5386
+ if (officeKindForPath(filename))
5387
+ return "office";
5388
+ if (filename.endsWith(".pdf") || contentType === "application/pdf")
5389
+ return "pdf";
5390
+ const ext = filename.match(/\.([a-z0-9]+)$/)?.[1] ?? "";
5391
+ if (contentType.startsWith("text/") || TEXT_FILE_EXTENSIONS.has(ext))
5392
+ return "text";
5393
+ return null;
5394
+ }
5395
+ function safeAttachmentName(name) {
5396
+ const cleaned = name.replace(/[\\/:*?"<>|\x00-\x1f]/g, "_").trim() || "attachment";
5397
+ if (cleaned.length <= 80)
5398
+ return cleaned;
5399
+ const ext = cleaned.match(/\.[a-z0-9]+$/i)?.[0] ?? "";
5400
+ return `${cleaned.slice(0, Math.max(1, 80 - ext.length))}${ext}`;
5401
+ }
5402
+ async function downloadToBuffer(att, getAuth, maxBytes, tooLargeMessage) {
5403
+ if (!isAllowedDownloadHost(att.url))
5404
+ return { failed: "下载域不在白名单" };
5405
+ try {
5406
+ let res = await fetchWithTimeout(att.url, 15000);
5407
+ if ((res.status === 401 || res.status === 403) && getAuth) {
5408
+ try {
5409
+ res = await fetchWithTimeout(att.url, 15000, await getAuth());
5410
+ } catch {}
5411
+ }
5412
+ if (!res.ok) {
5413
+ console.log("[media] 下载失败:", res.status, att.url);
5414
+ return { failed: `HTTP ${res.status}` };
5415
+ }
5416
+ const len = Number(res.headers.get("content-length") || 0);
5417
+ if (len > maxBytes)
5418
+ return { failed: tooLargeMessage };
5419
+ const reader = res.body?.getReader();
5420
+ if (!reader)
5421
+ return { failed: "无响应体" };
5422
+ const chunks = [];
5423
+ let total = 0;
5424
+ for (;; ) {
5425
+ const { done, value } = await reader.read();
5426
+ if (done)
5427
+ break;
5428
+ total += value.byteLength;
5429
+ if (total > maxBytes) {
5430
+ await reader.cancel();
5431
+ return { failed: tooLargeMessage };
5432
+ }
5433
+ chunks.push(value);
5434
+ }
5435
+ if (total === 0)
5436
+ return { failed: "空响应" };
5437
+ return { data: Buffer.concat(chunks) };
5438
+ } catch (e) {
5439
+ console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e);
5440
+ return { failed: "网络错误或超时" };
5441
+ }
5442
+ }
5118
5443
  async function downloadQQAttachment(att, getAuth) {
5119
5444
  const ctype = (att.content_type || "").toLowerCase();
5120
5445
  const isVoice = ctype.startsWith("audio/") || ctype === "voice" || ctype === "amr" || ctype.endsWith("/amr");
@@ -5141,53 +5466,51 @@ async function downloadQQAttachment(att, getAuth) {
5141
5466
  return { failed: "语音转写失败(外部 STT 未响应或识别为空)" };
5142
5467
  }
5143
5468
  }
5469
+ const fileKind = classifyFileAttachment(att);
5470
+ if (fileKind) {
5471
+ const downloaded = await downloadToBuffer(att, getAuth, MAX_FILE_BYTES, "超过20MB");
5472
+ if ("failed" in downloaded)
5473
+ return downloaded;
5474
+ const dir = fileDir();
5475
+ mkdirSync5(dir, { recursive: true });
5476
+ const safeName = safeAttachmentName(att.filename || `attachment-${Date.now()}`);
5477
+ const storedName = `qq-file-${Date.now()}-${Math.random().toString(36).slice(2, 8)}-${safeName}`;
5478
+ const storedPath = join6(dir, storedName);
5479
+ try {
5480
+ writeFileSync6(storedPath, downloaded.data);
5481
+ if (fileKind === "text")
5482
+ return { path: storedPath, name: safeName, kind: "text" };
5483
+ if (fileKind === "pdf")
5484
+ return { path: storedPath, name: safeName, kind: "pdf" };
5485
+ const extracted = extractOfficeTextFromFile(storedPath);
5486
+ const textPath = `${storedPath}.extracted.txt`;
5487
+ writeFileSync6(textPath, extracted, "utf8");
5488
+ return { path: textPath, name: `${safeName}.txt`, kind: "office-text", sourceName: safeName };
5489
+ } catch (error) {
5490
+ console.log("[media] 文件处理失败:", safeName, error instanceof Error ? error.message : error);
5491
+ return { failed: fileKind === "office" ? "Office 文档解析失败" : "文件处理失败" };
5492
+ }
5493
+ }
5144
5494
  const ext = extForImageMime(att.content_type || "");
5145
- if (!ext)
5495
+ if (!ext) {
5496
+ if (isLegacyOfficePath(att.filename || "")) {
5497
+ return { unsupported: "旧版 Office 二进制(请另存为 docx/xlsx/pptx 或导出文本/PDF)" };
5498
+ }
5146
5499
  return { unsupported: att.content_type || att.filename || "未知类型" };
5147
- if (!isAllowedDownloadHost(att.url))
5148
- return { failed: "下载域不在白名单" };
5500
+ }
5501
+ const downloaded = await downloadToBuffer(att, getAuth, MAX_IMAGE_BYTES, "超过10MB");
5502
+ if ("failed" in downloaded)
5503
+ return downloaded;
5149
5504
  try {
5150
5505
  const dir = imageDir();
5151
5506
  mkdirSync5(dir, { recursive: true });
5152
5507
  const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
5153
- let res = await fetchWithTimeout(att.url, 15000);
5154
- if ((res.status === 401 || res.status === 403) && getAuth) {
5155
- try {
5156
- const tok = await getAuth();
5157
- res = await fetchWithTimeout(att.url, 15000, tok);
5158
- } catch {}
5159
- }
5160
- if (!res.ok) {
5161
- console.log("[media] 下载失败:", res.status, att.url);
5162
- return { failed: `HTTP ${res.status}` };
5163
- }
5164
- const len = Number(res.headers.get("content-length") || 0);
5165
- if (len > MAX_IMAGE_BYTES)
5166
- return { failed: "超过10MB" };
5167
- const reader = res.body?.getReader();
5168
- if (!reader)
5169
- return { failed: "无响应体" };
5170
- const chunks = [];
5171
- let total = 0;
5172
- for (;; ) {
5173
- const { done, value } = await reader.read();
5174
- if (done)
5175
- break;
5176
- total += value.byteLength;
5177
- if (total > MAX_IMAGE_BYTES) {
5178
- await reader.cancel();
5179
- return { failed: "超过10MB" };
5180
- }
5181
- chunks.push(value);
5182
- }
5183
- if (total === 0)
5184
- return { failed: "空响应" };
5185
5508
  const full = join6(dir, name);
5186
- writeFileSync6(full, Buffer.concat(chunks));
5187
- return { path: full, name };
5509
+ writeFileSync6(full, downloaded.data);
5510
+ return { path: full, name, kind: "image" };
5188
5511
  } catch (e) {
5189
- console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e);
5190
- return { failed: "网络错误或超时" };
5512
+ console.log("[media] 图片落盘失败:", e instanceof Error ? e.message : e);
5513
+ return { failed: "文件落盘失败" };
5191
5514
  }
5192
5515
  }
5193
5516
  async function prepareQQAttachments(attachments, getAuth) {
@@ -5203,12 +5526,21 @@ function groupOutcomes(outcomes) {
5203
5526
  const notes = [];
5204
5527
  for (const o of outcomes) {
5205
5528
  if ("path" in o) {
5206
- const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024);
5207
- files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name });
5529
+ const kind = o.kind ?? "image";
5530
+ if (kind === "image") {
5531
+ const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024);
5532
+ files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name });
5533
+ } else {
5534
+ files.push({ uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name });
5535
+ if (kind === "pdf")
5536
+ notes.push(`(PDF 附件已注入:${o.name};需要模型支持 PDF 输入)`);
5537
+ if (kind === "office-text")
5538
+ notes.push(`(Office 文档已提取为文本:${o.sourceName ?? o.name})`);
5539
+ }
5208
5540
  } else if ("voice" in o) {
5209
5541
  notes.push(`(语音转写:${o.voice})`);
5210
5542
  } else if ("failed" in o) {
5211
- notes.push(`(图片下载失败:${o.failed})`);
5543
+ notes.push(`(附件下载失败:${o.failed})`);
5212
5544
  } else {
5213
5545
  notes.push(`(暂不支持的附件类型:${o.unsupported})`);
5214
5546
  }
@@ -5220,18 +5552,24 @@ function tryImageDataUrl(path, maxBytes) {
5220
5552
  const st = statSync(path);
5221
5553
  if (st.size > maxBytes)
5222
5554
  return null;
5223
- const b = readFileSync7(path);
5555
+ const b = readFileSync8(path);
5224
5556
  return `data:image/png;base64,${b.toString("base64")}`;
5225
5557
  } catch {
5226
5558
  return null;
5227
5559
  }
5228
5560
  }
5561
+ function isImagePromptFile(file) {
5562
+ if (file.uri.startsWith("data:image/"))
5563
+ return true;
5564
+ return /\.(png|jpe?g|gif|webp|bmp)$/i.test(file.name ?? "");
5565
+ }
5229
5566
  function augmentPromptWithAttachments(rawContent, prepared) {
5230
5567
  const base = rawContent.trim();
5231
5568
  const { files, notes } = prepared;
5232
5569
  let text = base;
5233
- if (!text && files.length > 0)
5234
- text = "(用户通过 QQ 发来了图片,未附文字)";
5570
+ if (!text && files.length > 0) {
5571
+ text = files.some(isImagePromptFile) ? "(用户通过 QQ 发来了图片,未附文字)" : "(用户通过 QQ 发来了文件,未附文字)";
5572
+ }
5235
5573
  if (!text && notes.length > 0)
5236
5574
  text = "(用户通过 QQ 发来了内容,但无法处理)";
5237
5575
  if (notes.length > 0)
@@ -5242,9 +5580,8 @@ ${notes.join(`
5242
5580
  `);
5243
5581
  return { text, files };
5244
5582
  }
5245
- function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
5583
+ function purgeOldFilesIn(dir, maxAgeMs) {
5246
5584
  try {
5247
- const dir = imageDir();
5248
5585
  const now = Date.now();
5249
5586
  for (const f of readdirSync(dir)) {
5250
5587
  const full = join6(dir, f);
@@ -5255,6 +5592,12 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
5255
5592
  }
5256
5593
  } catch {}
5257
5594
  }
5595
+ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
5596
+ purgeOldFilesIn(imageDir(), maxAgeMs);
5597
+ }
5598
+ function purgeOldQQFiles(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
5599
+ purgeOldFilesIn(fileDir(), maxAgeMs);
5600
+ }
5258
5601
 
5259
5602
  // src/core/zombie-reaper.ts
5260
5603
  var REAPER_MIN_AGE_MS = 40 * 60000;
@@ -5680,7 +6023,7 @@ function clip(value, max) {
5680
6023
  }
5681
6024
 
5682
6025
  // src/core/send-media.ts
5683
- import { readFileSync as readFileSync8, statSync as statSync2 } from "node:fs";
6026
+ import { readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
5684
6027
  import { resolve, extname, basename, sep, join as join7 } from "node:path";
5685
6028
  import { homedir as homedir5 } from "node:os";
5686
6029
  var MAX_SEND_BYTES = 20 * 1024 * 1024;
@@ -5786,7 +6129,7 @@ async function sendLocalFile(ctx, filePath, deps) {
5786
6129
  const name = basename(trimmed);
5787
6130
  const uploaded = await uploadQQMedia(token, ctx, {
5788
6131
  fileType,
5789
- fileData: readFileSync8(trimmed).toString("base64"),
6132
+ fileData: readFileSync9(trimmed).toString("base64"),
5790
6133
  fileName: fileType === MediaFileType.FILE ? name : undefined
5791
6134
  });
5792
6135
  await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
@@ -6273,7 +6616,7 @@ function toErrorMessage(error) {
6273
6616
  }
6274
6617
 
6275
6618
  // src/core/mirror.ts
6276
- import { existsSync as existsSync8, readFileSync as readFileSync9, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
6619
+ import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
6277
6620
 
6278
6621
  // src/opencode/mirror.ts
6279
6622
  var USER_CLIP = 160;
@@ -6551,7 +6894,7 @@ var MIRROR_SETTINGS_FILE = storageFile("settings.json");
6551
6894
  function loadMirrorEnabled(file = MIRROR_SETTINGS_FILE) {
6552
6895
  try {
6553
6896
  if (existsSync8(file)) {
6554
- const raw = readFileSync9(file, "utf-8").replace(/^\uFEFF/, "");
6897
+ const raw = readFileSync10(file, "utf-8").replace(/^\uFEFF/, "");
6555
6898
  const parsed = JSON.parse(raw);
6556
6899
  if (typeof parsed?.mirror === "boolean")
6557
6900
  return parsed.mirror;
@@ -6565,7 +6908,7 @@ function saveMirrorEnabled(enabled, file = MIRROR_SETTINGS_FILE) {
6565
6908
  let existing = {};
6566
6909
  if (existsSync8(file)) {
6567
6910
  try {
6568
- const raw = readFileSync9(file, "utf-8").replace(/^\uFEFF/, "");
6911
+ const raw = readFileSync10(file, "utf-8").replace(/^\uFEFF/, "");
6569
6912
  const parsed = JSON.parse(raw);
6570
6913
  if (parsed && typeof parsed === "object")
6571
6914
  existing = parsed;
@@ -6776,7 +7119,7 @@ function createMirror(deps) {
6776
7119
  import {
6777
7120
  existsSync as existsSync9,
6778
7121
  mkdirSync as mkdirSync8,
6779
- readFileSync as readFileSync10,
7122
+ readFileSync as readFileSync11,
6780
7123
  renameSync as renameSync3,
6781
7124
  unlinkSync as unlinkSync3,
6782
7125
  writeFileSync as writeFileSync8
@@ -6826,7 +7169,7 @@ function createMirrorAnchorStore(filePath) {
6826
7169
  }
6827
7170
  try {
6828
7171
  if (existsSync9(filePath)) {
6829
- const parsed = JSON.parse(readFileSync10(filePath, "utf8").replace(/^\uFEFF/, ""));
7172
+ const parsed = JSON.parse(readFileSync11(filePath, "utf8").replace(/^\uFEFF/, ""));
6830
7173
  if (parsed.version !== 1 || !Array.isArray(parsed.entries))
6831
7174
  throw new Error("锚点文件格式无效");
6832
7175
  const loaded = parsed.entries.filter(validEntry);
@@ -7059,7 +7402,7 @@ function parseGoalState(raw) {
7059
7402
  }
7060
7403
  }
7061
7404
  // src/core/permission.ts
7062
- import { existsSync as existsSync10, readFileSync as readFileSync11, writeFileSync as writeFileSync9 } from "fs";
7405
+ import { existsSync as existsSync10, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "fs";
7063
7406
 
7064
7407
  // src/core/util.ts
7065
7408
  function truncate(value, max) {
@@ -7105,6 +7448,12 @@ function resolvePermDeferMs(envValue) {
7105
7448
  const n = Number(envValue);
7106
7449
  return Number.isFinite(n) && n >= 0 && n <= 1e4 ? n : 500;
7107
7450
  }
7451
+ function resolvePermSendGraceMs(envValue) {
7452
+ if (envValue === undefined || envValue.trim() === "")
7453
+ return 1000;
7454
+ const n = Number(envValue);
7455
+ return Number.isFinite(n) && n >= 0 && n <= 1e4 ? n : 1000;
7456
+ }
7108
7457
  var DECISION_LABELS = {
7109
7458
  once: "允许(本次)",
7110
7459
  always: "总是允许(已存入项目白名单)",
@@ -7123,7 +7472,7 @@ var PENDING_PERM_FILE = storageFile("pending-permissions.json");
7123
7472
  function loadPendingPermMap(file = PENDING_PERM_FILE) {
7124
7473
  try {
7125
7474
  if (existsSync10(file)) {
7126
- const raw = readFileSync11(file, "utf-8");
7475
+ const raw = readFileSync12(file, "utf-8");
7127
7476
  const obj = JSON.parse(raw);
7128
7477
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
7129
7478
  const out = {};
@@ -7159,8 +7508,59 @@ function savePendingPermMap(m, file = PENDING_PERM_FILE) {
7159
7508
  }
7160
7509
  function createPermissionGate(deps) {
7161
7510
  const PERSIST_FILE = deps.persistFile ?? PENDING_PERM_FILE;
7511
+ const SEND_GRACE_MS = deps.sendGraceMs ?? resolvePermSendGraceMs(process.env.QQ_PERM_SEND_GRACE_MS);
7162
7512
  const { client, sendReply, safeDeliver } = deps;
7163
7513
  const pendingPermissions = new Map;
7514
+ const RESOLVED_RECENT_TTL_MS = 5 * 60000;
7515
+ const resolvedRecently = new Map;
7516
+ function markResolvedRecently(requestID) {
7517
+ const prev = resolvedRecently.get(requestID);
7518
+ resolvedRecently.set(requestID, {
7519
+ exp: Date.now() + RESOLVED_RECENT_TTL_MS,
7520
+ ...prev?.notice ? { notice: prev.notice } : {}
7521
+ });
7522
+ if (resolvedRecently.size > 500) {
7523
+ const now = Date.now();
7524
+ for (const [id, e] of resolvedRecently)
7525
+ if (e.exp <= now)
7526
+ resolvedRecently.delete(id);
7527
+ while (resolvedRecently.size > 500) {
7528
+ const first = resolvedRecently.keys().next().value;
7529
+ if (first === undefined)
7530
+ break;
7531
+ resolvedRecently.delete(first);
7532
+ }
7533
+ }
7534
+ }
7535
+ function wasResolvedRecently(requestID) {
7536
+ const e = resolvedRecently.get(requestID);
7537
+ if (e === undefined)
7538
+ return false;
7539
+ if (e.exp <= Date.now()) {
7540
+ resolvedRecently.delete(requestID);
7541
+ return false;
7542
+ }
7543
+ return true;
7544
+ }
7545
+ function markPromptDelivered(userId, requestID) {
7546
+ const cur = pendingPermissions.get(userId);
7547
+ if (cur?.request.id === requestID)
7548
+ cur.promptDelivered = true;
7549
+ const e = resolvedRecently.get(requestID);
7550
+ if (!e?.notice)
7551
+ return;
7552
+ const n = e.notice;
7553
+ e.notice = undefined;
7554
+ safeDeliver(n.ctx, `\uD83D\uDD04 审批 ${requestID.slice(-8)} 已由${n.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${n.label}),QQ 审批自动关闭`).catch(() => {});
7555
+ }
7556
+ async function waitSendGrace() {
7557
+ if (SEND_GRACE_MS <= 0)
7558
+ return;
7559
+ await new Promise((resolve) => {
7560
+ const timer = setTimeout(resolve, SEND_GRACE_MS);
7561
+ timer.unref?.();
7562
+ });
7563
+ }
7164
7564
  const pushedCardIds = new Set;
7165
7565
  function claimCardPush(requestId) {
7166
7566
  if (pushedCardIds.has(requestId))
@@ -7210,6 +7610,7 @@ function createPermissionGate(deps) {
7210
7610
  adopted.alertTimer = startNudgeTimer(ctx.userId, request.id, ctx);
7211
7611
  adopted.timer = setTimeout(() => {
7212
7612
  if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
7613
+ markResolvedRecently(request.id);
7213
7614
  pendingPermissions.delete(ctx.userId);
7214
7615
  savePendingPermMap(pendingPermissions, PERSIST_FILE);
7215
7616
  deps.onDecision?.(ctx.userId);
@@ -7230,6 +7631,7 @@ function createPermissionGate(deps) {
7230
7631
  const alertTimer = startNudgeTimer(ctx.userId, request.id, ctx);
7231
7632
  const timer = setTimeout(() => {
7232
7633
  if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
7634
+ markResolvedRecently(request.id);
7233
7635
  pendingPermissions.delete(ctx.userId);
7234
7636
  savePendingPermMap(pendingPermissions, PERSIST_FILE);
7235
7637
  deps.onDecision?.(ctx.userId);
@@ -7252,9 +7654,28 @@ function createPermissionGate(deps) {
7252
7654
  savePendingPermMap(pendingPermissions, PERSIST_FILE);
7253
7655
  if (claimCardPush(request.id)) {
7254
7656
  (async () => {
7255
- const sentByCard = deps.sendApprovalPrompt ? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot").catch(() => false) : false;
7657
+ const isCancelled = () => wasResolvedRecently(request.id) || pendingPermissions.get(ctx.userId)?.request.id !== request.id;
7658
+ if (isCancelled()) {
7659
+ console.log(`[perm] 发卡前复查:槽已清,放弃发卡 request=${request.id}`);
7660
+ return;
7661
+ }
7662
+ if (SEND_GRACE_MS > 0) {
7663
+ await waitSendGrace();
7664
+ if (isCancelled()) {
7665
+ console.log(`[perm] 发送窗内请求已解决,放弃发卡 request=${request.id}`);
7666
+ return;
7667
+ }
7668
+ }
7669
+ const sentByCard = deps.sendApprovalPrompt ? await deps.sendApprovalPrompt(ctx, request, mainSessionId, "bot", isCancelled).catch(() => false) : false;
7670
+ if (sentByCard)
7671
+ markPromptDelivered(ctx.userId, request.id);
7672
+ const stillPending = () => pendingPermissions.get(ctx.userId)?.request.id === request.id;
7673
+ if (!stillPending()) {
7674
+ console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`);
7675
+ return;
7676
+ }
7256
7677
  if (!sentByCard) {
7257
- await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot")).catch((error) => {
7678
+ await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "bot")).then(() => markPromptDelivered(ctx.userId, request.id)).catch((error) => {
7258
7679
  console.error("[bridge] 发送审批请求失败:", error);
7259
7680
  });
7260
7681
  }
@@ -7266,6 +7687,7 @@ function createPermissionGate(deps) {
7266
7687
  const entry = pendingPermissions.get(userId);
7267
7688
  if (!entry)
7268
7689
  return;
7690
+ markResolvedRecently(entry.request.id);
7269
7691
  clearTimers(entry);
7270
7692
  pendingPermissions.delete(userId);
7271
7693
  savePendingPermMap(pendingPermissions, PERSIST_FILE);
@@ -7334,8 +7756,10 @@ function createPermissionGate(deps) {
7334
7756
  console.log(`[perm] 恢复重启前挂起的审批 ${uid.slice(0, 8)}… request=${e.request.id}`);
7335
7757
  (async () => {
7336
7758
  const sentByCard = deps.sendApprovalPrompt ? await deps.sendApprovalPrompt(e.ctx, e.request, e.mainSessionId, e.origin).catch(() => false) : false;
7759
+ if (sentByCard)
7760
+ markPromptDelivered(uid, e.request.id);
7337
7761
  if (!sentByCard) {
7338
- await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin)).catch((error) => {
7762
+ await sendReply(e.ctx, formatPermissionPrompt(e.request, e.mainSessionId, e.origin)).then(() => markPromptDelivered(uid, e.request.id)).catch((error) => {
7339
7763
  console.error("[bridge] 恢复审批推送失败:", error);
7340
7764
  });
7341
7765
  }
@@ -7353,6 +7777,7 @@ function createPermissionGate(deps) {
7353
7777
  const timer = setTimeout(() => {
7354
7778
  if (pendingPermissions.get(userId)?.request.id !== request.id)
7355
7779
  return;
7780
+ markResolvedRecently(request.id);
7356
7781
  pendingPermissions.delete(userId);
7357
7782
  savePendingPermMap(pendingPermissions, PERSIST_FILE);
7358
7783
  deps.onDecision?.(userId);
@@ -7376,17 +7801,28 @@ function createPermissionGate(deps) {
7376
7801
  console.log(`[perm] 外部审批已推送 user=${userId.slice(0, 8)}… request=${request.id} action=${request.action} origin=${origin}`);
7377
7802
  if (claimCardPush(request.id)) {
7378
7803
  (async () => {
7379
- const sentByCard = deps.sendApprovalPrompt ? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin).catch(() => false) : false;
7804
+ const isCancelled = () => wasResolvedRecently(request.id) || pendingPermissions.get(userId)?.request.id !== request.id;
7805
+ if (isCancelled()) {
7806
+ console.log(`[perm] 发卡前复查:槽已清,放弃发卡 request=${request.id}`);
7807
+ return;
7808
+ }
7809
+ if (SEND_GRACE_MS > 0) {
7810
+ await waitSendGrace();
7811
+ if (isCancelled()) {
7812
+ console.log(`[perm] 发送窗内请求已解决,放弃发卡 request=${request.id}`);
7813
+ return;
7814
+ }
7815
+ }
7816
+ const sentByCard = deps.sendApprovalPrompt ? await deps.sendApprovalPrompt(ctx, request, mainSessionId, origin, isCancelled).catch(() => false) : false;
7817
+ if (sentByCard)
7818
+ markPromptDelivered(userId, request.id);
7380
7819
  const stillPending = () => pendingPermissions.get(userId)?.request.id === request.id;
7381
7820
  if (!stillPending()) {
7382
7821
  console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`);
7822
+ return;
7383
7823
  }
7384
7824
  if (!sentByCard) {
7385
- if (!stillPending()) {
7386
- console.log(`[perm] 文字降级前复查:槽已清(他端已处理),跳过文字菜单 request=${request.id}`);
7387
- return;
7388
- }
7389
- await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external")).catch((error) => {
7825
+ await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external")).then(() => markPromptDelivered(userId, request.id)).catch((error) => {
7390
7826
  console.error("[bridge] 发送审批请求失败:", error);
7391
7827
  });
7392
7828
  }
@@ -7400,18 +7836,35 @@ function createPermissionGate(deps) {
7400
7836
  if (sessionID && entry.request.sessionID && sessionID !== entry.request.sessionID)
7401
7837
  continue;
7402
7838
  const e = entry;
7839
+ markResolvedRecently(requestID);
7403
7840
  clearTimers(e);
7404
7841
  pendingPermissions.delete(uid);
7405
7842
  savePendingPermMap(pendingPermissions, PERSIST_FILE);
7406
7843
  deps.onDecision?.(uid);
7407
7844
  const label = reply === "allow" || reply === "once" ? "允许(本次)" : reply === "always" ? "总是允许" : reply === "reject" ? "拒绝" : `已处理(${String(reply ?? "未知")})`;
7408
7845
  console.log(`[perm] 联动清槽(源头已解决):uid=${uid.slice(0, 8)}… request=${requestID} reply=${String(reply)}`);
7409
- safeDeliver(e.ctx, `\uD83D\uDD04 审批 ${requestID.slice(-8)} 已由${e.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${label}),QQ 审批自动关闭`).catch(() => {});
7846
+ if (e.promptDelivered || e.resumedFromDisk) {
7847
+ safeDeliver(e.ctx, `\uD83D\uDD04 审批 ${requestID.slice(-8)} 已由${e.origin === "bot" ? "机器人回合侧" : "桌面端"}处理(${label}),QQ 审批自动关闭`).catch(() => {});
7848
+ } else {
7849
+ const r = resolvedRecently.get(requestID);
7850
+ if (r)
7851
+ r.notice = { label, origin: e.origin, ctx: e.ctx };
7852
+ console.log(`[perm] 提示未投递(无卡可关),自动关闭回执挂起 request=${requestID}`);
7853
+ }
7410
7854
  return true;
7411
7855
  }
7412
7856
  return false;
7413
7857
  }
7414
- return { hasPending, getPending, waitForDecision, resolve, restore, pushExternal: pushExternalImpl, clearIfResolved };
7858
+ return {
7859
+ hasPending,
7860
+ getPending,
7861
+ waitForDecision,
7862
+ resolve,
7863
+ restore,
7864
+ pushExternal: pushExternalImpl,
7865
+ clearIfResolved,
7866
+ wasResolvedRecently
7867
+ };
7415
7868
  }
7416
7869
  function parsePermissionDecision(content) {
7417
7870
  const t = content.trim().toLowerCase().replace(/^\/(allow|always|deny|reject|ok|yes|no)\s*$/, "$1");
@@ -7453,7 +7906,7 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
7453
7906
  }
7454
7907
 
7455
7908
  // src/core/delivery.ts
7456
- import { existsSync as existsSync11, readFileSync as readFileSync12, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, renameSync as renameSync4, openSync, closeSync, unlinkSync as unlinkSync4, statSync as statSync5 } from "fs";
7909
+ import { existsSync as existsSync11, readFileSync as readFileSync13, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, renameSync as renameSync4, openSync, closeSync, unlinkSync as unlinkSync4, statSync as statSync5 } from "fs";
7457
7910
  import { join as join9 } from "path";
7458
7911
  import { createHash } from "node:crypto";
7459
7912
 
@@ -7886,7 +8339,7 @@ var DEFAULT_QUOTA_FILE = storageFile("quota.json");
7886
8339
  function loadQuotaMap(file) {
7887
8340
  try {
7888
8341
  if (existsSync11(file)) {
7889
- const raw = readFileSync12(file, "utf-8");
8342
+ const raw = readFileSync13(file, "utf-8");
7890
8343
  const obj = JSON.parse(raw);
7891
8344
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
7892
8345
  const out = {};
@@ -7921,7 +8374,7 @@ function qqPromptHints() {
7921
8374
  const file = join9(storageRoot(), "qq-system-instructions.json");
7922
8375
  const st = statSync5(file);
7923
8376
  if (Date.now() - st.mtimeMs < 15 * 60000) {
7924
- const parsed = JSON.parse(readFileSync12(file, "utf-8"));
8377
+ const parsed = JSON.parse(readFileSync13(file, "utf-8"));
7925
8378
  if (parsed?.mode === "entry" || parsed?.mode === "hook")
7926
8379
  return "";
7927
8380
  }
@@ -7979,7 +8432,7 @@ function loadDeliveryAttempts() {
7979
8432
  try {
7980
8433
  if (!existsSync11(deliveryDedupeFile()))
7981
8434
  return out;
7982
- const raw = JSON.parse(readFileSync12(deliveryDedupeFile(), "utf-8"));
8435
+ const raw = JSON.parse(readFileSync13(deliveryDedupeFile(), "utf-8"));
7983
8436
  const now = Date.now();
7984
8437
  for (const entry of raw) {
7985
8438
  if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
@@ -8034,7 +8487,7 @@ function withDeliveryLock(fn) {
8034
8487
  return fn();
8035
8488
  } finally {
8036
8489
  try {
8037
- if (readFileSync12(lockPath, "utf-8") === token)
8490
+ if (readFileSync13(lockPath, "utf-8") === token)
8038
8491
  unlinkSync4(lockPath);
8039
8492
  } catch {}
8040
8493
  }
@@ -8330,7 +8783,7 @@ import {
8330
8783
  existsSync as existsSync12,
8331
8784
  mkdirSync as mkdirSync10,
8332
8785
  openSync as openSync2,
8333
- readFileSync as readFileSync13,
8786
+ readFileSync as readFileSync14,
8334
8787
  renameSync as renameSync5,
8335
8788
  statSync as statSync6,
8336
8789
  unlinkSync as unlinkSync5,
@@ -8387,7 +8840,7 @@ function atomicWrite(filePath, document) {
8387
8840
  function readDocument(filePath, now) {
8388
8841
  if (!existsSync12(filePath))
8389
8842
  return { version: 1, entries: [] };
8390
- const raw = JSON.parse(readFileSync13(filePath, "utf8"));
8843
+ const raw = JSON.parse(readFileSync14(filePath, "utf8"));
8391
8844
  if (Array.isArray(raw)) {
8392
8845
  return { version: 1, entries: pruneOutboxEntries(raw, now) };
8393
8846
  }
@@ -8445,7 +8898,7 @@ function createOutbox(options = {}) {
8445
8898
  return fn();
8446
8899
  } finally {
8447
8900
  try {
8448
- if (readFileSync13(lockPath, "utf8") === token)
8901
+ if (readFileSync14(lockPath, "utf8") === token)
8449
8902
  unlinkSync5(lockPath);
8450
8903
  } catch {}
8451
8904
  }
@@ -8797,11 +9250,19 @@ function buildApprovalKeyboard(request, ownerOpenid) {
8797
9250
  }
8798
9251
  };
8799
9252
  }
8800
- async function sendApprovalCard(deps, ctx, request, mainSessionId, origin) {
9253
+ async function sendApprovalCard(deps, ctx, request, mainSessionId, origin, isCancelled) {
8801
9254
  try {
8802
9255
  const token = await getAccessToken(deps.appId, deps.clientSecret);
9256
+ if (isCancelled?.()) {
9257
+ console.log(`[card-approval] 发卡取消:请求已解决 user=${ctx.userId.slice(0, 8)}… request=${request.id}`);
9258
+ return false;
9259
+ }
8803
9260
  const keyboard = buildApprovalKeyboard(request, ctx.userId);
8804
9261
  const text = formatPermissionPrompt(request, mainSessionId, origin);
9262
+ if (isCancelled?.()) {
9263
+ console.log(`[card-approval] 发卡取消:请求已解决 user=${ctx.userId.slice(0, 8)}… request=${request.id}`);
9264
+ return false;
9265
+ }
8805
9266
  if (ctx.type === "group" && ctx.groupId) {
8806
9267
  await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard);
8807
9268
  } else {
@@ -8841,7 +9302,7 @@ import {
8841
9302
  existsSync as existsSync13,
8842
9303
  mkdirSync as mkdirSync11,
8843
9304
  openSync as openSync3,
8844
- readFileSync as readFileSync14,
9305
+ readFileSync as readFileSync15,
8845
9306
  renameSync as renameSync6,
8846
9307
  statSync as statSync7,
8847
9308
  unlinkSync as unlinkSync6,
@@ -8908,7 +9369,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
8908
9369
  try {
8909
9370
  if (!existsSync13(path))
8910
9371
  return [];
8911
- const raw = JSON.parse(readFileSync14(path, "utf-8"));
9372
+ const raw = JSON.parse(readFileSync15(path, "utf-8"));
8912
9373
  const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
8913
9374
  const byUser = new Map;
8914
9375
  for (const value of values) {
@@ -8968,7 +9429,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
8968
9429
  return fn();
8969
9430
  } finally {
8970
9431
  try {
8971
- if (readFileSync14(lockPath, "utf-8") === token)
9432
+ if (readFileSync15(lockPath, "utf-8") === token)
8972
9433
  unlinkSync6(lockPath);
8973
9434
  } catch {}
8974
9435
  }
@@ -9535,7 +9996,7 @@ function createFormBridge(deps) {
9535
9996
  }
9536
9997
 
9537
9998
  // src/core/inflight-journal.ts
9538
- import { existsSync as existsSync14, readFileSync as readFileSync15, writeFileSync as writeFileSync13, mkdirSync as mkdirSync12, renameSync as renameSync7, openSync as openSync4, closeSync as closeSync4, unlinkSync as unlinkSync7, statSync as statSync8 } from "fs";
9999
+ import { existsSync as existsSync14, readFileSync as readFileSync16, writeFileSync as writeFileSync13, mkdirSync as mkdirSync12, renameSync as renameSync7, openSync as openSync4, closeSync as closeSync4, unlinkSync as unlinkSync7, statSync as statSync8 } from "fs";
9539
10000
  import { join as join10 } from "path";
9540
10001
 
9541
10002
  // src/core/inbound-dedupe.ts
@@ -9576,7 +10037,7 @@ function load(file) {
9576
10037
  const path = journalPath(file);
9577
10038
  try {
9578
10039
  if (existsSync14(path)) {
9579
- const raw = JSON.parse(readFileSync15(path, "utf-8"));
10040
+ const raw = JSON.parse(readFileSync16(path, "utf-8"));
9580
10041
  if (Array.isArray(raw))
9581
10042
  entries = raw;
9582
10043
  }
@@ -9633,7 +10094,7 @@ function withJournalLock(file, fn) {
9633
10094
  return fn();
9634
10095
  } finally {
9635
10096
  try {
9636
- if (readFileSync15(lockPath, "utf-8") === token)
10097
+ if (readFileSync16(lockPath, "utf-8") === token)
9637
10098
  unlinkSync7(lockPath);
9638
10099
  } catch {}
9639
10100
  }
@@ -10337,7 +10798,7 @@ function formatStatusLine(view) {
10337
10798
  init_log_rotate();
10338
10799
 
10339
10800
  // src/core/instance-lock.ts
10340
- import { openSync as openSync5, readFileSync as readFileSync16, readdirSync as readdirSync2, writeFileSync as writeFileSync14, closeSync as closeSync5, unlinkSync as unlinkSync8, statSync as statSync9, utimesSync, mkdirSync as mkdirSync13 } from "fs";
10801
+ import { openSync as openSync5, readFileSync as readFileSync17, readdirSync as readdirSync2, writeFileSync as writeFileSync14, closeSync as closeSync5, unlinkSync as unlinkSync8, statSync as statSync9, utimesSync, mkdirSync as mkdirSync13 } from "fs";
10341
10802
  import { join as join11 } from "path";
10342
10803
  import { homedir as homedir6 } from "os";
10343
10804
  var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
@@ -10382,7 +10843,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
10382
10843
  heartbeat.unref?.();
10383
10844
  const selfCheck = setInterval(() => {
10384
10845
  try {
10385
- const holder = JSON.parse(readFileSync16(path, "utf-8")).pid;
10846
+ const holder = JSON.parse(readFileSync17(path, "utf-8")).pid;
10386
10847
  if (holder === process.pid)
10387
10848
  return;
10388
10849
  try {
@@ -10453,7 +10914,7 @@ var DEFAULT_SUPERVISOR_POLICY = {
10453
10914
  };
10454
10915
 
10455
10916
  // src/core/send-requests.ts
10456
- import { existsSync as existsSync15, mkdirSync as mkdirSync14, readdirSync as readdirSync3, readFileSync as readFileSync17, renameSync as renameSync8, statSync as statSync10, writeFileSync as writeFileSync15 } from "node:fs";
10917
+ import { existsSync as existsSync15, mkdirSync as mkdirSync14, readdirSync as readdirSync3, readFileSync as readFileSync18, renameSync as renameSync8, statSync as statSync10, writeFileSync as writeFileSync15 } from "node:fs";
10457
10918
  import { join as join12 } from "node:path";
10458
10919
  function sendRequestsDirFor(appId) {
10459
10920
  return join12(storageRoot(appId), "send-requests");
@@ -10469,7 +10930,7 @@ function startSendRequestConsumer(opts) {
10469
10930
  continue;
10470
10931
  const full = join12(dir, f);
10471
10932
  try {
10472
- const result = JSON.parse(readFileSync17(full, "utf-8"));
10933
+ const result = JSON.parse(readFileSync18(full, "utf-8"));
10473
10934
  const key = result.dedupeKey;
10474
10935
  if (key)
10475
10936
  seen.set(key, result);
@@ -10482,7 +10943,7 @@ function startSendRequestConsumer(opts) {
10482
10943
  const full = join12(dir, file);
10483
10944
  let req;
10484
10945
  try {
10485
- req = JSON.parse(readFileSync17(full, "utf-8"));
10946
+ req = JSON.parse(readFileSync18(full, "utf-8"));
10486
10947
  } catch {
10487
10948
  renameSync8(full, full + ".bad.json");
10488
10949
  log(`[send-requests] 坏请求已隔离: ${file}`);
@@ -11170,7 +11631,7 @@ ${parsed.message.slice(0, 400)}
11170
11631
  for (const lk of msgQueue.laneKeysOf(userId))
11171
11632
  drainQueue(userId, sessionIdOfLane(lk));
11172
11633
  },
11173
- sendApprovalPrompt: (ctx, request, mainSessionId, origin) => sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId, origin),
11634
+ sendApprovalPrompt: (ctx, request, mainSessionId, origin, isCancelled) => sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId, origin, isCancelled),
11174
11635
  persistFile: storageAppId ? roleFile("pending-permissions.json") : undefined
11175
11636
  });
11176
11637
  const mirror = createMirror({
@@ -11290,7 +11751,8 @@ ${parsed.message.slice(0, 400)}
11290
11751
  console.log(`[push-gate] 审批卡拦截(轮询兜底):绑定已切走 uid=${uid.slice(0, 8)}… sid=${shortId(req.sessionID)}`);
11291
11752
  continue;
11292
11753
  }
11293
- perm.pushExternal(uid, ctxForUser(uid), req, req.sessionID);
11754
+ console.log(`[perm-event] 轮询兜底发现待审(延迟 ${PERM_DEFER_MS}ms 判定)user=${uid.slice(0, 8)}… request=${req.id}`);
11755
+ permPushGate.schedule(uid, req.id, () => void flushPermPush(uid, req));
11294
11756
  }
11295
11757
  }
11296
11758
  }
@@ -11345,6 +11807,10 @@ ${parsed.message.slice(0, 400)}
11345
11807
  }
11346
11808
  });
11347
11809
  async function flushPermPush(uid, req) {
11810
+ if (perm.wasResolvedRecently(req.id)) {
11811
+ console.log(`[perm-event] 延迟判定:请求近期已解决,弃推 user=${uid.slice(0, 8)}… request=${req.id}`);
11812
+ return;
11813
+ }
11348
11814
  const bound = sessions.getSession(uid);
11349
11815
  try {
11350
11816
  const res = await client.permission.list({ directory: bound?.directory });
@@ -11854,6 +12320,7 @@ ${parsed.message}`;
11854
12320
  perm.restore();
11855
12321
  mirror.ensureSubs();
11856
12322
  purgeOldQQImages();
12323
+ purgeOldQQFiles();
11857
12324
  const handleMessage = async (ctx) => {
11858
12325
  let claimedMsgId = "";
11859
12326
  const intentKey = intentKeyOf(ctx);
@@ -12384,7 +12851,7 @@ var WATCH_FILE = storageFile("watch.json");
12384
12851
  function loadWatchedMap(file = WATCH_FILE) {
12385
12852
  try {
12386
12853
  if (existsSync16(file)) {
12387
- const raw = readFileSync18(file, "utf-8");
12854
+ const raw = readFileSync19(file, "utf-8");
12388
12855
  const obj = JSON.parse(raw);
12389
12856
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
12390
12857
  const out = {};
@@ -12408,7 +12875,7 @@ var GREETED_FILE = storageFile("greeted.json");
12408
12875
  function loadGreetedSet(file = GREETED_FILE) {
12409
12876
  try {
12410
12877
  if (existsSync16(file)) {
12411
- const raw = readFileSync18(file, "utf-8");
12878
+ const raw = readFileSync19(file, "utf-8");
12412
12879
  const arr = JSON.parse(raw);
12413
12880
  if (Array.isArray(arr)) {
12414
12881
  return new Set(arr.filter((x) => typeof x === "string"));