@linjz/opencode-qqbot 0.3.19 → 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.
- package/PRIVACY.md +87 -0
- package/README.md +20 -3
- package/README.zh-CN.md +21 -4
- package/THIRD_PARTY_NOTICES.md +136 -0
- package/bin/openqq.js +1 -1
- package/dist/opencode-qqbot-plugin.js +124 -6
- package/dist/openqq-bot.js +1099 -231
- package/dist/openqq-cli.js +152 -16
- package/dist/openqq-watchdog.js +72 -2
- package/package.json +5 -3
- package/src/bridge.ts +156 -13
- package/src/cli/openqq-main.ts +33 -5
- package/src/core/bot-control.ts +73 -8
- package/src/core/card-approval.ts +14 -3
- package/src/core/context-buffer.ts +6 -6
- package/src/core/cron-reminders.ts +1 -1
- package/src/core/delivery.ts +131 -37
- package/src/core/instance-lock.ts +1 -1
- package/src/core/mirror-anchors.ts +145 -0
- package/src/core/mirror.ts +112 -22
- package/src/core/notices.ts +2 -2
- package/src/core/notify-sink.ts +1 -1
- package/src/core/office-text.ts +234 -0
- package/src/core/outbound-sanitize.ts +3 -1
- package/src/core/permission.ts +157 -26
- package/src/core/reply-limiter.ts +3 -2
- package/src/core/send-media.ts +6 -6
- package/src/core/stt.ts +1 -1
- package/src/core/watchdog.ts +108 -5
- package/src/index.ts +1 -1
- package/src/opencode/mirror.ts +54 -2
- package/src/opencode/sessions.ts +28 -2
- package/src/qq/api.ts +9 -1
- package/src/qq/gateway.ts +16 -5
- package/src/qq/media.ts +154 -55
- package/src/qq/sender.ts +64 -14
- package/src/qq/types.ts +4 -1
package/dist/openqq-bot.js
CHANGED
|
@@ -3298,7 +3298,7 @@ function storageFile(name, appId) {
|
|
|
3298
3298
|
}
|
|
3299
3299
|
|
|
3300
3300
|
// src/index.ts
|
|
3301
|
-
import { mkdirSync as
|
|
3301
|
+
import { mkdirSync as mkdirSync16, writeFileSync as writeFileSync17 } from "fs";
|
|
3302
3302
|
import { join as join14 } from "path";
|
|
3303
3303
|
import { homedir as homedir8 } from "os";
|
|
3304
3304
|
|
|
@@ -4320,6 +4320,7 @@ var STORE_FILE = storageFile("sessions.json");
|
|
|
4320
4320
|
class SessionManager {
|
|
4321
4321
|
sessions = new Map;
|
|
4322
4322
|
client;
|
|
4323
|
+
bindingListeners = new Set;
|
|
4323
4324
|
storeFile;
|
|
4324
4325
|
constructor(client, storeFile = STORE_FILE) {
|
|
4325
4326
|
this.client = client;
|
|
@@ -4359,6 +4360,19 @@ class SessionManager {
|
|
|
4359
4360
|
console.error("[sessions] 会话映射持久化失败:", error);
|
|
4360
4361
|
}
|
|
4361
4362
|
}
|
|
4363
|
+
onBindingChange(listener) {
|
|
4364
|
+
this.bindingListeners.add(listener);
|
|
4365
|
+
return () => this.bindingListeners.delete(listener);
|
|
4366
|
+
}
|
|
4367
|
+
emitBindingChange(userId, sessionId) {
|
|
4368
|
+
for (const listener of this.bindingListeners) {
|
|
4369
|
+
try {
|
|
4370
|
+
listener(userId, sessionId);
|
|
4371
|
+
} catch (error) {
|
|
4372
|
+
console.error("[sessions] 绑定变化通知失败:", error);
|
|
4373
|
+
}
|
|
4374
|
+
}
|
|
4375
|
+
}
|
|
4362
4376
|
async getOrCreate(userId) {
|
|
4363
4377
|
const existing = this.sessions.get(userId);
|
|
4364
4378
|
if (existing)
|
|
@@ -4371,6 +4385,7 @@ class SessionManager {
|
|
|
4371
4385
|
};
|
|
4372
4386
|
this.sessions.set(userId, session);
|
|
4373
4387
|
this.saveSessions();
|
|
4388
|
+
this.emitBindingChange(userId, session.sessionId);
|
|
4374
4389
|
await this.enforceLocation(userId, session.sessionId, directory);
|
|
4375
4390
|
return session;
|
|
4376
4391
|
}
|
|
@@ -4388,6 +4403,8 @@ class SessionManager {
|
|
|
4388
4403
|
};
|
|
4389
4404
|
this.sessions.set(userId, session);
|
|
4390
4405
|
this.saveSessions();
|
|
4406
|
+
if (!prev || prev.sessionId !== session.sessionId)
|
|
4407
|
+
this.emitBindingChange(userId, session.sessionId);
|
|
4391
4408
|
if (inheritedModel) {
|
|
4392
4409
|
this.client.session.setModel({ path: { id: session.sessionId }, body: { model: inheritedModel } }).catch((error) => console.error("[sessions] 新会话继承模型失败(映射已存):", error));
|
|
4393
4410
|
}
|
|
@@ -4408,6 +4425,7 @@ class SessionManager {
|
|
|
4408
4425
|
});
|
|
4409
4426
|
this.saveSessions();
|
|
4410
4427
|
if (changed) {
|
|
4428
|
+
this.emitBindingChange(userId, sessionId);
|
|
4411
4429
|
this.refreshSettingsFromServer(userId);
|
|
4412
4430
|
}
|
|
4413
4431
|
}
|
|
@@ -4480,12 +4498,18 @@ class SessionManager {
|
|
|
4480
4498
|
}
|
|
4481
4499
|
}
|
|
4482
4500
|
all() {
|
|
4483
|
-
return [...this.sessions.entries()].map(([userId, s]) => ({
|
|
4501
|
+
return [...this.sessions.entries()].map(([userId, s]) => ({
|
|
4502
|
+
userId,
|
|
4503
|
+
sessionId: s.sessionId,
|
|
4504
|
+
...s.title ? { title: s.title } : {},
|
|
4505
|
+
directory: s.directory
|
|
4506
|
+
}));
|
|
4484
4507
|
}
|
|
4485
4508
|
evict(userId) {
|
|
4486
4509
|
const had = this.sessions.delete(userId);
|
|
4487
4510
|
if (had) {
|
|
4488
4511
|
this.saveSessions();
|
|
4512
|
+
this.emitBindingChange(userId, null);
|
|
4489
4513
|
console.log(`[sessions] 驱逐失效映射 userId=${userId.slice(0, 8)}…(400/404 三连判死)`);
|
|
4490
4514
|
}
|
|
4491
4515
|
return had;
|
|
@@ -4708,6 +4732,11 @@ function briefAttachments(atts) {
|
|
|
4708
4732
|
return { host, content_type: a.content_type, size: a.size, filename: a.filename, asr: a.asr_refer_text ? 1 : 0 };
|
|
4709
4733
|
});
|
|
4710
4734
|
}
|
|
4735
|
+
function referencedMessageId(event) {
|
|
4736
|
+
const prefix = "ref_msg_idx=";
|
|
4737
|
+
const official = event.message_scene?.ext?.find((item) => typeof item === "string" && item.startsWith(prefix))?.slice(prefix.length).trim();
|
|
4738
|
+
return official || event.message_reference?.message_id;
|
|
4739
|
+
}
|
|
4711
4740
|
function toC2CMessageContext(event) {
|
|
4712
4741
|
return {
|
|
4713
4742
|
type: "c2c",
|
|
@@ -4715,7 +4744,7 @@ function toC2CMessageContext(event) {
|
|
|
4715
4744
|
msgId: event.id,
|
|
4716
4745
|
content: normalizeMessageContent(event.content),
|
|
4717
4746
|
...isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {},
|
|
4718
|
-
referencedMsgId: event
|
|
4747
|
+
referencedMsgId: referencedMessageId(event),
|
|
4719
4748
|
attachments: event.attachments,
|
|
4720
4749
|
timestamp: event.timestamp,
|
|
4721
4750
|
rawEvent: event
|
|
@@ -4729,7 +4758,7 @@ function toGroupMessageContext(event) {
|
|
|
4729
4758
|
msgId: event.id,
|
|
4730
4759
|
content: stripGroupAtPrefix(event.content),
|
|
4731
4760
|
...isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {},
|
|
4732
|
-
referencedMsgId: event
|
|
4761
|
+
referencedMsgId: referencedMessageId(event),
|
|
4733
4762
|
attachments: event.attachments,
|
|
4734
4763
|
timestamp: event.timestamp,
|
|
4735
4764
|
rawEvent: event
|
|
@@ -4750,8 +4779,8 @@ function sendIdentify(ws, accessToken) {
|
|
|
4750
4779
|
shard: [0, 1],
|
|
4751
4780
|
properties: {
|
|
4752
4781
|
os: process.platform,
|
|
4753
|
-
browser: "
|
|
4754
|
-
device: "
|
|
4782
|
+
browser: "opencode_qqbot",
|
|
4783
|
+
device: "opencode_qqbot"
|
|
4755
4784
|
}
|
|
4756
4785
|
}
|
|
4757
4786
|
};
|
|
@@ -5004,12 +5033,12 @@ async function startGateway(options) {
|
|
|
5004
5033
|
}
|
|
5005
5034
|
|
|
5006
5035
|
// src/bridge.ts
|
|
5007
|
-
import { existsSync as
|
|
5036
|
+
import { existsSync as existsSync16, readFileSync as readFileSync19, mkdirSync as mkdirSync15, writeFileSync as writeFileSync16 } from "fs";
|
|
5008
5037
|
import { join as join13 } from "path";
|
|
5009
5038
|
import { homedir as homedir7 } from "os";
|
|
5010
5039
|
|
|
5011
5040
|
// src/qq/media.ts
|
|
5012
|
-
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as
|
|
5041
|
+
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync8 } from "node:fs";
|
|
5013
5042
|
import { join as join6 } from "node:path";
|
|
5014
5043
|
import { tmpdir } from "node:os";
|
|
5015
5044
|
|
|
@@ -5048,6 +5077,221 @@ async function sttTranscribe(bytes, filename, cfg, fetchImpl = fetch) {
|
|
|
5048
5077
|
return text;
|
|
5049
5078
|
}
|
|
5050
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(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/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
|
+
|
|
5051
5295
|
// src/qq/media.ts
|
|
5052
5296
|
function extForImageMime(mime) {
|
|
5053
5297
|
const m = (mime || "").toLowerCase().split(";")[0].trim();
|
|
@@ -5059,6 +5303,7 @@ function extForImageMime(mime) {
|
|
|
5059
5303
|
return null;
|
|
5060
5304
|
}
|
|
5061
5305
|
var MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
5306
|
+
var MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
5062
5307
|
var ALLOWED_HOST_SUFFIXES = [".qpic.cn", ".qq.com", ".qq.com.cn"];
|
|
5063
5308
|
function isAllowedDownloadHost(url) {
|
|
5064
5309
|
try {
|
|
@@ -5074,6 +5319,9 @@ function isAllowedDownloadHost(url) {
|
|
|
5074
5319
|
function imageDir() {
|
|
5075
5320
|
return join6(tmpdir(), "opencode", "qq-images");
|
|
5076
5321
|
}
|
|
5322
|
+
function fileDir() {
|
|
5323
|
+
return join6(tmpdir(), "opencode", "qq-files");
|
|
5324
|
+
}
|
|
5077
5325
|
async function fetchWithTimeout(url, ms, auth) {
|
|
5078
5326
|
const ctrl = new AbortController;
|
|
5079
5327
|
const timer = setTimeout(() => ctrl.abort(), ms);
|
|
@@ -5086,6 +5334,112 @@ async function fetchWithTimeout(url, ms, auth) {
|
|
|
5086
5334
|
clearTimeout(timer);
|
|
5087
5335
|
}
|
|
5088
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
|
+
}
|
|
5089
5443
|
async function downloadQQAttachment(att, getAuth) {
|
|
5090
5444
|
const ctype = (att.content_type || "").toLowerCase();
|
|
5091
5445
|
const isVoice = ctype.startsWith("audio/") || ctype === "voice" || ctype === "amr" || ctype.endsWith("/amr");
|
|
@@ -5112,53 +5466,51 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
5112
5466
|
return { failed: "语音转写失败(外部 STT 未响应或识别为空)" };
|
|
5113
5467
|
}
|
|
5114
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
|
+
}
|
|
5115
5494
|
const ext = extForImageMime(att.content_type || "");
|
|
5116
|
-
if (!ext)
|
|
5495
|
+
if (!ext) {
|
|
5496
|
+
if (isLegacyOfficePath(att.filename || "")) {
|
|
5497
|
+
return { unsupported: "旧版 Office 二进制(请另存为 docx/xlsx/pptx 或导出文本/PDF)" };
|
|
5498
|
+
}
|
|
5117
5499
|
return { unsupported: att.content_type || att.filename || "未知类型" };
|
|
5118
|
-
|
|
5119
|
-
|
|
5500
|
+
}
|
|
5501
|
+
const downloaded = await downloadToBuffer(att, getAuth, MAX_IMAGE_BYTES, "超过10MB");
|
|
5502
|
+
if ("failed" in downloaded)
|
|
5503
|
+
return downloaded;
|
|
5120
5504
|
try {
|
|
5121
5505
|
const dir = imageDir();
|
|
5122
5506
|
mkdirSync5(dir, { recursive: true });
|
|
5123
5507
|
const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
|
5124
|
-
let res = await fetchWithTimeout(att.url, 15000);
|
|
5125
|
-
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
5126
|
-
try {
|
|
5127
|
-
const tok = await getAuth();
|
|
5128
|
-
res = await fetchWithTimeout(att.url, 15000, tok);
|
|
5129
|
-
} catch {}
|
|
5130
|
-
}
|
|
5131
|
-
if (!res.ok) {
|
|
5132
|
-
console.log("[media] 下载失败:", res.status, att.url);
|
|
5133
|
-
return { failed: `HTTP ${res.status}` };
|
|
5134
|
-
}
|
|
5135
|
-
const len = Number(res.headers.get("content-length") || 0);
|
|
5136
|
-
if (len > MAX_IMAGE_BYTES)
|
|
5137
|
-
return { failed: "超过10MB" };
|
|
5138
|
-
const reader = res.body?.getReader();
|
|
5139
|
-
if (!reader)
|
|
5140
|
-
return { failed: "无响应体" };
|
|
5141
|
-
const chunks = [];
|
|
5142
|
-
let total = 0;
|
|
5143
|
-
for (;; ) {
|
|
5144
|
-
const { done, value } = await reader.read();
|
|
5145
|
-
if (done)
|
|
5146
|
-
break;
|
|
5147
|
-
total += value.byteLength;
|
|
5148
|
-
if (total > MAX_IMAGE_BYTES) {
|
|
5149
|
-
await reader.cancel();
|
|
5150
|
-
return { failed: "超过10MB" };
|
|
5151
|
-
}
|
|
5152
|
-
chunks.push(value);
|
|
5153
|
-
}
|
|
5154
|
-
if (total === 0)
|
|
5155
|
-
return { failed: "空响应" };
|
|
5156
5508
|
const full = join6(dir, name);
|
|
5157
|
-
writeFileSync6(full,
|
|
5158
|
-
return { path: full, name };
|
|
5509
|
+
writeFileSync6(full, downloaded.data);
|
|
5510
|
+
return { path: full, name, kind: "image" };
|
|
5159
5511
|
} catch (e) {
|
|
5160
|
-
console.log("[media]
|
|
5161
|
-
return { failed: "
|
|
5512
|
+
console.log("[media] 图片落盘失败:", e instanceof Error ? e.message : e);
|
|
5513
|
+
return { failed: "文件落盘失败" };
|
|
5162
5514
|
}
|
|
5163
5515
|
}
|
|
5164
5516
|
async function prepareQQAttachments(attachments, getAuth) {
|
|
@@ -5174,12 +5526,21 @@ function groupOutcomes(outcomes) {
|
|
|
5174
5526
|
const notes = [];
|
|
5175
5527
|
for (const o of outcomes) {
|
|
5176
5528
|
if ("path" in o) {
|
|
5177
|
-
const
|
|
5178
|
-
|
|
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
|
+
}
|
|
5179
5540
|
} else if ("voice" in o) {
|
|
5180
5541
|
notes.push(`(语音转写:${o.voice})`);
|
|
5181
5542
|
} else if ("failed" in o) {
|
|
5182
|
-
notes.push(
|
|
5543
|
+
notes.push(`(附件下载失败:${o.failed})`);
|
|
5183
5544
|
} else {
|
|
5184
5545
|
notes.push(`(暂不支持的附件类型:${o.unsupported})`);
|
|
5185
5546
|
}
|
|
@@ -5191,18 +5552,24 @@ function tryImageDataUrl(path, maxBytes) {
|
|
|
5191
5552
|
const st = statSync(path);
|
|
5192
5553
|
if (st.size > maxBytes)
|
|
5193
5554
|
return null;
|
|
5194
|
-
const b =
|
|
5555
|
+
const b = readFileSync8(path);
|
|
5195
5556
|
return `data:image/png;base64,${b.toString("base64")}`;
|
|
5196
5557
|
} catch {
|
|
5197
5558
|
return null;
|
|
5198
5559
|
}
|
|
5199
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
|
+
}
|
|
5200
5566
|
function augmentPromptWithAttachments(rawContent, prepared) {
|
|
5201
5567
|
const base = rawContent.trim();
|
|
5202
5568
|
const { files, notes } = prepared;
|
|
5203
5569
|
let text = base;
|
|
5204
|
-
if (!text && files.length > 0)
|
|
5205
|
-
text = "(用户通过 QQ 发来了图片,未附文字)";
|
|
5570
|
+
if (!text && files.length > 0) {
|
|
5571
|
+
text = files.some(isImagePromptFile) ? "(用户通过 QQ 发来了图片,未附文字)" : "(用户通过 QQ 发来了文件,未附文字)";
|
|
5572
|
+
}
|
|
5206
5573
|
if (!text && notes.length > 0)
|
|
5207
5574
|
text = "(用户通过 QQ 发来了内容,但无法处理)";
|
|
5208
5575
|
if (notes.length > 0)
|
|
@@ -5213,9 +5580,8 @@ ${notes.join(`
|
|
|
5213
5580
|
`);
|
|
5214
5581
|
return { text, files };
|
|
5215
5582
|
}
|
|
5216
|
-
function
|
|
5583
|
+
function purgeOldFilesIn(dir, maxAgeMs) {
|
|
5217
5584
|
try {
|
|
5218
|
-
const dir = imageDir();
|
|
5219
5585
|
const now = Date.now();
|
|
5220
5586
|
for (const f of readdirSync(dir)) {
|
|
5221
5587
|
const full = join6(dir, f);
|
|
@@ -5226,6 +5592,12 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
|
5226
5592
|
}
|
|
5227
5593
|
} catch {}
|
|
5228
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
|
+
}
|
|
5229
5601
|
|
|
5230
5602
|
// src/core/zombie-reaper.ts
|
|
5231
5603
|
var REAPER_MIN_AGE_MS = 40 * 60000;
|
|
@@ -5651,7 +6023,7 @@ function clip(value, max) {
|
|
|
5651
6023
|
}
|
|
5652
6024
|
|
|
5653
6025
|
// src/core/send-media.ts
|
|
5654
|
-
import { readFileSync as
|
|
6026
|
+
import { readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
|
|
5655
6027
|
import { resolve, extname, basename, sep, join as join7 } from "node:path";
|
|
5656
6028
|
import { homedir as homedir5 } from "node:os";
|
|
5657
6029
|
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
@@ -5757,7 +6129,7 @@ async function sendLocalFile(ctx, filePath, deps) {
|
|
|
5757
6129
|
const name = basename(trimmed);
|
|
5758
6130
|
const uploaded = await uploadQQMedia(token, ctx, {
|
|
5759
6131
|
fileType,
|
|
5760
|
-
fileData:
|
|
6132
|
+
fileData: readFileSync9(trimmed).toString("base64"),
|
|
5761
6133
|
fileName: fileType === MediaFileType.FILE ? name : undefined
|
|
5762
6134
|
});
|
|
5763
6135
|
await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
|
|
@@ -6244,10 +6616,31 @@ function toErrorMessage(error) {
|
|
|
6244
6616
|
}
|
|
6245
6617
|
|
|
6246
6618
|
// src/core/mirror.ts
|
|
6247
|
-
import { existsSync as existsSync8, readFileSync as
|
|
6619
|
+
import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
|
|
6248
6620
|
|
|
6249
6621
|
// src/opencode/mirror.ts
|
|
6250
6622
|
var USER_CLIP = 160;
|
|
6623
|
+
var DIGEST_TITLE_MAX_WIDTH = 20;
|
|
6624
|
+
function isWideCodePoint(cp) {
|
|
6625
|
+
return cp >= 4352 && (cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 42191 && cp !== 12351 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 126976 && cp <= 129791 || cp >= 131072 && cp <= 262141);
|
|
6626
|
+
}
|
|
6627
|
+
function clipDigestTitle(value, maxWidth = DIGEST_TITLE_MAX_WIDTH) {
|
|
6628
|
+
const title = (value ?? "").replace(/\s+/g, " ").trim() || "未命名会话";
|
|
6629
|
+
let width = 0;
|
|
6630
|
+
let out = "";
|
|
6631
|
+
for (const char of title) {
|
|
6632
|
+
const cp = char.codePointAt(0) ?? 0;
|
|
6633
|
+
const charWidth = /\p{Mark}/u.test(char) || cp === 8205 || cp >= 65024 && cp <= 65039 ? 0 : isWideCodePoint(cp) ? 2 : 1;
|
|
6634
|
+
if (width + charWidth > maxWidth)
|
|
6635
|
+
return `${out}...`;
|
|
6636
|
+
out += char;
|
|
6637
|
+
width += charWidth;
|
|
6638
|
+
}
|
|
6639
|
+
return out;
|
|
6640
|
+
}
|
|
6641
|
+
function digestSessionLabel(sessionId) {
|
|
6642
|
+
return sessionId.length > 10 ? `${sessionId.slice(0, 10)}…` : sessionId;
|
|
6643
|
+
}
|
|
6251
6644
|
function answerClipLimit() {
|
|
6252
6645
|
const n = Number(process.env.QQ_DIGEST_ANSWER_MAX_CHARS ?? "0");
|
|
6253
6646
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
|
@@ -6279,7 +6672,7 @@ function digestTurnKey(messages) {
|
|
|
6279
6672
|
}
|
|
6280
6673
|
return null;
|
|
6281
6674
|
}
|
|
6282
|
-
function buildDigest(messages, goalObjective) {
|
|
6675
|
+
function buildDigest(messages, goalObjective, identity) {
|
|
6283
6676
|
const ordered = [...messages].reverse();
|
|
6284
6677
|
let lastUserIdx = -1;
|
|
6285
6678
|
let goalDriven = false;
|
|
@@ -6312,7 +6705,12 @@ function buildDigest(messages, goalObjective) {
|
|
|
6312
6705
|
}
|
|
6313
6706
|
if (!answer)
|
|
6314
6707
|
return null;
|
|
6315
|
-
const
|
|
6708
|
+
const kind = goalDriven ? "\uD83C\uDFAF 目标续跑摘要" : "\uD83D\uDCCB 桌面问答摘要";
|
|
6709
|
+
const lines = [
|
|
6710
|
+
identity ? `${kind} · ${clipDigestTitle(identity.title)} · ${digestSessionLabel(identity.sessionId)}` : kind
|
|
6711
|
+
];
|
|
6712
|
+
if (identity)
|
|
6713
|
+
lines.push("↩️ 引用回复仅在该会话仍为当前绑定时受理");
|
|
6316
6714
|
if (userText)
|
|
6317
6715
|
lines.push(`\uD83E\uDDD1 ${clip2(userText, USER_CLIP)}`);
|
|
6318
6716
|
const clipLimit = answerClipLimit();
|
|
@@ -6496,7 +6894,7 @@ var MIRROR_SETTINGS_FILE = storageFile("settings.json");
|
|
|
6496
6894
|
function loadMirrorEnabled(file = MIRROR_SETTINGS_FILE) {
|
|
6497
6895
|
try {
|
|
6498
6896
|
if (existsSync8(file)) {
|
|
6499
|
-
const raw =
|
|
6897
|
+
const raw = readFileSync10(file, "utf-8").replace(/^\uFEFF/, "");
|
|
6500
6898
|
const parsed = JSON.parse(raw);
|
|
6501
6899
|
if (typeof parsed?.mirror === "boolean")
|
|
6502
6900
|
return parsed.mirror;
|
|
@@ -6510,7 +6908,7 @@ function saveMirrorEnabled(enabled, file = MIRROR_SETTINGS_FILE) {
|
|
|
6510
6908
|
let existing = {};
|
|
6511
6909
|
if (existsSync8(file)) {
|
|
6512
6910
|
try {
|
|
6513
|
-
const raw =
|
|
6911
|
+
const raw = readFileSync10(file, "utf-8").replace(/^\uFEFF/, "");
|
|
6514
6912
|
const parsed = JSON.parse(raw);
|
|
6515
6913
|
if (parsed && typeof parsed === "object")
|
|
6516
6914
|
existing = parsed;
|
|
@@ -6528,27 +6926,50 @@ function createMirror(deps) {
|
|
|
6528
6926
|
const qqTurnActive = new Set;
|
|
6529
6927
|
const qqPromptIds = new Map;
|
|
6530
6928
|
const QQ_PROMPT_ID_CAP = 200;
|
|
6929
|
+
const MIRROR_SESSION_STATE_CAP = 500;
|
|
6531
6930
|
function markQqPrompt(sessionId, promptId) {
|
|
6532
6931
|
if (!promptId)
|
|
6533
6932
|
return;
|
|
6534
|
-
|
|
6535
|
-
|
|
6536
|
-
set = new Set;
|
|
6537
|
-
qqPromptIds.set(sessionId, set);
|
|
6538
|
-
}
|
|
6933
|
+
const set = qqPromptIds.get(sessionId) ?? new Set;
|
|
6934
|
+
qqPromptIds.delete(sessionId);
|
|
6539
6935
|
if (set.size >= QQ_PROMPT_ID_CAP) {
|
|
6540
6936
|
const first = set.values().next().value;
|
|
6541
6937
|
if (first !== undefined)
|
|
6542
6938
|
set.delete(first);
|
|
6543
6939
|
}
|
|
6544
6940
|
set.add(promptId);
|
|
6941
|
+
qqPromptIds.set(sessionId, set);
|
|
6942
|
+
while (qqPromptIds.size > MIRROR_SESSION_STATE_CAP) {
|
|
6943
|
+
const oldest = qqPromptIds.keys().next().value;
|
|
6944
|
+
if (oldest === undefined)
|
|
6945
|
+
break;
|
|
6946
|
+
qqPromptIds.delete(oldest);
|
|
6947
|
+
}
|
|
6545
6948
|
}
|
|
6546
6949
|
const mirroredTurns = new Map;
|
|
6950
|
+
function rememberMirroredTurn(sessionId, turnKey) {
|
|
6951
|
+
mirroredTurns.delete(sessionId);
|
|
6952
|
+
mirroredTurns.set(sessionId, turnKey);
|
|
6953
|
+
while (mirroredTurns.size > MIRROR_SESSION_STATE_CAP) {
|
|
6954
|
+
const oldest = mirroredTurns.keys().next().value;
|
|
6955
|
+
if (oldest === undefined)
|
|
6956
|
+
break;
|
|
6957
|
+
mirroredTurns.delete(oldest);
|
|
6958
|
+
}
|
|
6959
|
+
}
|
|
6547
6960
|
const mirrorState = { enabled: loadMirrorEnabled(deps.settingsFile) };
|
|
6548
6961
|
function ensureMirrorSubs() {
|
|
6549
|
-
|
|
6550
|
-
|
|
6551
|
-
|
|
6962
|
+
const desired = new Set((mirrorState.enabled ? sessions.all() : []).map((binding) => binding.sessionId));
|
|
6963
|
+
let added = 0;
|
|
6964
|
+
let removed = 0;
|
|
6965
|
+
for (const [sessionId, unsub] of [...mirrorUnsubs]) {
|
|
6966
|
+
if (desired.has(sessionId))
|
|
6967
|
+
continue;
|
|
6968
|
+
unsub();
|
|
6969
|
+
mirrorUnsubs.delete(sessionId);
|
|
6970
|
+
removed++;
|
|
6971
|
+
}
|
|
6972
|
+
for (const sessionId of desired) {
|
|
6552
6973
|
if (mirrorUnsubs.has(sessionId))
|
|
6553
6974
|
continue;
|
|
6554
6975
|
mirrorUnsubs.set(sessionId, eventStream.subscribe(sessionId, (ev) => {
|
|
@@ -6562,13 +6983,17 @@ function createMirror(deps) {
|
|
|
6562
6983
|
}
|
|
6563
6984
|
mirrorTurn(sessionId);
|
|
6564
6985
|
}));
|
|
6986
|
+
added++;
|
|
6987
|
+
}
|
|
6988
|
+
if (added > 0 || removed > 0) {
|
|
6989
|
+
console.log(`[mirror-reconcile] desired=${desired.size} added=${added} removed=${removed} actual=${mirrorUnsubs.size}`);
|
|
6565
6990
|
}
|
|
6566
6991
|
}
|
|
6567
|
-
|
|
6568
|
-
|
|
6569
|
-
unsub();
|
|
6570
|
-
mirrorUnsubs.clear();
|
|
6992
|
+
if (typeof sessions.onBindingChange === "function") {
|
|
6993
|
+
sessions.onBindingChange(() => ensureMirrorSubs());
|
|
6571
6994
|
}
|
|
6995
|
+
const reconcileTimer = setInterval(ensureMirrorSubs, 60000);
|
|
6996
|
+
reconcileTimer.unref?.();
|
|
6572
6997
|
function scheduleMirrorUnlock(sessionId) {
|
|
6573
6998
|
setTimeout(() => {
|
|
6574
6999
|
if (bgWaits.has(sessionId))
|
|
@@ -6581,11 +7006,19 @@ function createMirror(deps) {
|
|
|
6581
7006
|
}
|
|
6582
7007
|
async function mirrorTurn(sessionID) {
|
|
6583
7008
|
try {
|
|
6584
|
-
const
|
|
7009
|
+
const bindings = sessions.all().filter((x) => x.sessionId === sessionID);
|
|
7010
|
+
const owners = bindings.map((x) => x.userId);
|
|
6585
7011
|
if (owners.length === 0) {
|
|
6586
7012
|
console.log(`[mirror] 跳过:会话无映射主人 session=${sessionID}`);
|
|
6587
7013
|
return;
|
|
6588
7014
|
}
|
|
7015
|
+
let title;
|
|
7016
|
+
if (typeof client.session.get === "function") {
|
|
7017
|
+
try {
|
|
7018
|
+
title = (await client.session.get({ path: { id: sessionID } }))?.data?.title;
|
|
7019
|
+
} catch {}
|
|
7020
|
+
}
|
|
7021
|
+
title ??= bindings.find((binding) => binding.title?.trim())?.title;
|
|
6589
7022
|
const listJson = await client.session.messages({ path: { id: sessionID } });
|
|
6590
7023
|
const messages = listJson?.data ?? [];
|
|
6591
7024
|
const turnKey = digestTurnKey(messages);
|
|
@@ -6597,16 +7030,19 @@ function createMirror(deps) {
|
|
|
6597
7030
|
if (anchorId && qqPromptIds.get(sessionID)?.has(anchorId)) {
|
|
6598
7031
|
console.log(`[mirror] 跳过:QQ 直答回合(来源身份核对命中)session=${sessionID} prompt=${anchorId}`);
|
|
6599
7032
|
if (turnKey)
|
|
6600
|
-
|
|
7033
|
+
rememberMirroredTurn(sessionID, turnKey);
|
|
6601
7034
|
return;
|
|
6602
7035
|
}
|
|
6603
|
-
const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID)
|
|
7036
|
+
const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID), {
|
|
7037
|
+
sessionId: sessionID,
|
|
7038
|
+
title
|
|
7039
|
+
});
|
|
6604
7040
|
if (!digest) {
|
|
6605
7041
|
console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`);
|
|
6606
7042
|
return;
|
|
6607
7043
|
}
|
|
6608
7044
|
if (turnKey)
|
|
6609
|
-
|
|
7045
|
+
rememberMirroredTurn(sessionID, turnKey);
|
|
6610
7046
|
for (const userId of owners) {
|
|
6611
7047
|
const recent = lastCtx.get(userId);
|
|
6612
7048
|
const ctx = recent ? { ...recent, anchorSessionId: sessionID } : { type: "c2c", userId, msgId: "", content: "", anchorSessionId: sessionID };
|
|
@@ -6614,7 +7050,31 @@ function createMirror(deps) {
|
|
|
6614
7050
|
const outText = cronHook ? cronHook(userId, digest) : digest;
|
|
6615
7051
|
if (!outText.trim())
|
|
6616
7052
|
continue;
|
|
6617
|
-
|
|
7053
|
+
const onSent = (receipt) => {
|
|
7054
|
+
if (!deps.anchorStore)
|
|
7055
|
+
return;
|
|
7056
|
+
if (!receipt.refIdx) {
|
|
7057
|
+
console.warn(`[mirror-anchor] QQ 未返回 ref_idx,摘要不可安全路由 session=${sessionID} user=${userId.slice(0, 8)}…`);
|
|
7058
|
+
return;
|
|
7059
|
+
}
|
|
7060
|
+
try {
|
|
7061
|
+
deps.anchorStore.record({
|
|
7062
|
+
refIdx: receipt.refIdx,
|
|
7063
|
+
messageId: receipt.id,
|
|
7064
|
+
userId,
|
|
7065
|
+
sessionId: sessionID,
|
|
7066
|
+
title: clipDigestTitle(redactSecrets(title ?? "")),
|
|
7067
|
+
sentAt: Date.now()
|
|
7068
|
+
});
|
|
7069
|
+
console.log(`[mirror-anchor] 已登记 session=${digestSessionLabel(sessionID)} user=${userId.slice(0, 8)}…`);
|
|
7070
|
+
} catch (error) {
|
|
7071
|
+
console.error("[mirror-anchor] 锚点落盘失败,后续引用将 fail-closed:", error);
|
|
7072
|
+
}
|
|
7073
|
+
};
|
|
7074
|
+
await safeDeliver(ctx, outText, onSent, {
|
|
7075
|
+
continuationPrefix: `\uD83D\uDCCB 摘要续 · ${digestSessionLabel(sessionID)}
|
|
7076
|
+
`
|
|
7077
|
+
});
|
|
6618
7078
|
}
|
|
6619
7079
|
console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`);
|
|
6620
7080
|
} catch (error) {
|
|
@@ -6630,13 +7090,17 @@ function createMirror(deps) {
|
|
|
6630
7090
|
if (!prev)
|
|
6631
7091
|
ensureMirrorSubs();
|
|
6632
7092
|
} else {
|
|
6633
|
-
|
|
7093
|
+
ensureMirrorSubs();
|
|
6634
7094
|
}
|
|
6635
7095
|
return enabled ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要" : "\uD83D\uDD07 摘要镜像已关闭(/status mirror on 重新开启)";
|
|
6636
7096
|
},
|
|
6637
7097
|
status() {
|
|
6638
|
-
|
|
6639
|
-
|
|
7098
|
+
if (!mirrorState.enabled)
|
|
7099
|
+
return "\uD83D\uDCCB 摘要镜像:关(/status mirror on 开启)";
|
|
7100
|
+
const desired = new Set(sessions.all().map((binding) => binding.sessionId));
|
|
7101
|
+
const actual = mirrorUnsubs.size;
|
|
7102
|
+
const aligned = desired.size === actual && [...desired].every((sessionId) => mirrorUnsubs.has(sessionId));
|
|
7103
|
+
return aligned ? "\uD83D\uDCCB 摘要镜像:开" : `⚠️ 摘要镜像:开 · 订阅对账异常(期望 ${desired.size} / 实际 ${actual})`;
|
|
6640
7104
|
}
|
|
6641
7105
|
};
|
|
6642
7106
|
return {
|
|
@@ -6651,6 +7115,118 @@ function createMirror(deps) {
|
|
|
6651
7115
|
};
|
|
6652
7116
|
}
|
|
6653
7117
|
|
|
7118
|
+
// src/core/mirror-anchors.ts
|
|
7119
|
+
import {
|
|
7120
|
+
existsSync as existsSync9,
|
|
7121
|
+
mkdirSync as mkdirSync8,
|
|
7122
|
+
readFileSync as readFileSync11,
|
|
7123
|
+
renameSync as renameSync3,
|
|
7124
|
+
unlinkSync as unlinkSync3,
|
|
7125
|
+
writeFileSync as writeFileSync8
|
|
7126
|
+
} from "node:fs";
|
|
7127
|
+
import { dirname as dirname2 } from "node:path";
|
|
7128
|
+
import { randomUUID } from "node:crypto";
|
|
7129
|
+
var MIRROR_ANCHOR_TTL_MS = 24 * 60 * 60 * 1000;
|
|
7130
|
+
var MIRROR_ANCHOR_MAX_PER_USER = 500;
|
|
7131
|
+
function validEntry(value) {
|
|
7132
|
+
const entry = value;
|
|
7133
|
+
return !!entry && typeof entry.refIdx === "string" && !!entry.refIdx && typeof entry.messageId === "string" && !!entry.messageId && typeof entry.userId === "string" && !!entry.userId && typeof entry.sessionId === "string" && !!entry.sessionId && typeof entry.title === "string" && typeof entry.sentAt === "number" && Number.isFinite(entry.sentAt) && entry.sentAt > 0;
|
|
7134
|
+
}
|
|
7135
|
+
function pruneMirrorAnchorEntries(input, now = Date.now()) {
|
|
7136
|
+
const fresh = input.filter((entry) => validEntry(entry) && entry.sentAt <= now && now - entry.sentAt < MIRROR_ANCHOR_TTL_MS);
|
|
7137
|
+
const newestFirst = [...fresh].sort((a, b) => b.sentAt - a.sentAt);
|
|
7138
|
+
const counts = new Map;
|
|
7139
|
+
const seen = new Set;
|
|
7140
|
+
const retained = [];
|
|
7141
|
+
for (const entry of newestFirst) {
|
|
7142
|
+
const identity = `${entry.userId}\x00${entry.refIdx}`;
|
|
7143
|
+
if (seen.has(identity))
|
|
7144
|
+
continue;
|
|
7145
|
+
const count = counts.get(entry.userId) ?? 0;
|
|
7146
|
+
if (count >= MIRROR_ANCHOR_MAX_PER_USER)
|
|
7147
|
+
continue;
|
|
7148
|
+
seen.add(identity);
|
|
7149
|
+
counts.set(entry.userId, count + 1);
|
|
7150
|
+
retained.push(entry);
|
|
7151
|
+
}
|
|
7152
|
+
return retained.sort((a, b) => a.sentAt - b.sentAt);
|
|
7153
|
+
}
|
|
7154
|
+
function createMirrorAnchorStore(filePath) {
|
|
7155
|
+
let entries = [];
|
|
7156
|
+
function save(nextEntries = entries) {
|
|
7157
|
+
const document = { version: 1, entries: nextEntries };
|
|
7158
|
+
mkdirSync8(dirname2(filePath), { recursive: true });
|
|
7159
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
7160
|
+
try {
|
|
7161
|
+
writeFileSync8(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
7162
|
+
renameSync3(temporary, filePath);
|
|
7163
|
+
} catch (error) {
|
|
7164
|
+
try {
|
|
7165
|
+
unlinkSync3(temporary);
|
|
7166
|
+
} catch {}
|
|
7167
|
+
throw error;
|
|
7168
|
+
}
|
|
7169
|
+
}
|
|
7170
|
+
try {
|
|
7171
|
+
if (existsSync9(filePath)) {
|
|
7172
|
+
const parsed = JSON.parse(readFileSync11(filePath, "utf8").replace(/^\uFEFF/, ""));
|
|
7173
|
+
if (parsed.version !== 1 || !Array.isArray(parsed.entries))
|
|
7174
|
+
throw new Error("锚点文件格式无效");
|
|
7175
|
+
const loaded = parsed.entries.filter(validEntry);
|
|
7176
|
+
const pruned = pruneMirrorAnchorEntries(loaded);
|
|
7177
|
+
entries = pruned;
|
|
7178
|
+
if (loaded.length !== parsed.entries.length || pruned.length !== loaded.length)
|
|
7179
|
+
save();
|
|
7180
|
+
}
|
|
7181
|
+
} catch (error) {
|
|
7182
|
+
try {
|
|
7183
|
+
const backup = `${filePath}.corrupt-${Date.now()}`;
|
|
7184
|
+
renameSync3(filePath, backup);
|
|
7185
|
+
console.error(`[mirror-anchor] 锚点文件损坏,已保留诊断副本:${backup}`);
|
|
7186
|
+
} catch (backupError) {
|
|
7187
|
+
console.error("[mirror-anchor] 损坏文件备份失败:", backupError);
|
|
7188
|
+
}
|
|
7189
|
+
entries = [];
|
|
7190
|
+
console.error("[mirror-anchor] 锚点恢复失败,按空表 fail-closed:", error);
|
|
7191
|
+
}
|
|
7192
|
+
return {
|
|
7193
|
+
filePath,
|
|
7194
|
+
record(entry) {
|
|
7195
|
+
if (!validEntry(entry))
|
|
7196
|
+
throw new Error("摘要锚点字段不完整");
|
|
7197
|
+
const next = pruneMirrorAnchorEntries([
|
|
7198
|
+
...entries.filter((item) => !(item.userId === entry.userId && item.refIdx === entry.refIdx)),
|
|
7199
|
+
entry
|
|
7200
|
+
]);
|
|
7201
|
+
save(next);
|
|
7202
|
+
entries = next;
|
|
7203
|
+
},
|
|
7204
|
+
resolve(userId, refIdx, now = Date.now()) {
|
|
7205
|
+
if (!refIdx)
|
|
7206
|
+
return;
|
|
7207
|
+
const entry = entries.find((item) => item.userId === userId && item.refIdx === refIdx);
|
|
7208
|
+
if (!entry)
|
|
7209
|
+
return;
|
|
7210
|
+
if (entry.sentAt > now || now - entry.sentAt >= MIRROR_ANCHOR_TTL_MS) {
|
|
7211
|
+
const before = entries.length;
|
|
7212
|
+
entries = pruneMirrorAnchorEntries(entries, now);
|
|
7213
|
+
if (entries.length !== before) {
|
|
7214
|
+
try {
|
|
7215
|
+
save();
|
|
7216
|
+
} catch (error) {
|
|
7217
|
+
console.error("[mirror-anchor] 过期锚点清理失败:", error);
|
|
7218
|
+
}
|
|
7219
|
+
}
|
|
7220
|
+
return;
|
|
7221
|
+
}
|
|
7222
|
+
return { ...entry };
|
|
7223
|
+
},
|
|
7224
|
+
list() {
|
|
7225
|
+
return entries.map((entry) => ({ ...entry }));
|
|
7226
|
+
}
|
|
7227
|
+
};
|
|
7228
|
+
}
|
|
7229
|
+
|
|
6654
7230
|
// src/core/error-rescue.ts
|
|
6655
7231
|
function classifyProviderError(message) {
|
|
6656
7232
|
const m = message.toLowerCase();
|
|
@@ -6826,7 +7402,7 @@ function parseGoalState(raw) {
|
|
|
6826
7402
|
}
|
|
6827
7403
|
}
|
|
6828
7404
|
// src/core/permission.ts
|
|
6829
|
-
import { existsSync as
|
|
7405
|
+
import { existsSync as existsSync10, readFileSync as readFileSync12, writeFileSync as writeFileSync9 } from "fs";
|
|
6830
7406
|
|
|
6831
7407
|
// src/core/util.ts
|
|
6832
7408
|
function truncate(value, max) {
|
|
@@ -6872,6 +7448,12 @@ function resolvePermDeferMs(envValue) {
|
|
|
6872
7448
|
const n = Number(envValue);
|
|
6873
7449
|
return Number.isFinite(n) && n >= 0 && n <= 1e4 ? n : 500;
|
|
6874
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
|
+
}
|
|
6875
7457
|
var DECISION_LABELS = {
|
|
6876
7458
|
once: "允许(本次)",
|
|
6877
7459
|
always: "总是允许(已存入项目白名单)",
|
|
@@ -6889,8 +7471,8 @@ function classifyApprovalReplyError(error) {
|
|
|
6889
7471
|
var PENDING_PERM_FILE = storageFile("pending-permissions.json");
|
|
6890
7472
|
function loadPendingPermMap(file = PENDING_PERM_FILE) {
|
|
6891
7473
|
try {
|
|
6892
|
-
if (
|
|
6893
|
-
const raw =
|
|
7474
|
+
if (existsSync10(file)) {
|
|
7475
|
+
const raw = readFileSync12(file, "utf-8");
|
|
6894
7476
|
const obj = JSON.parse(raw);
|
|
6895
7477
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
6896
7478
|
const out = {};
|
|
@@ -6919,15 +7501,66 @@ function savePendingPermMap(m, file = PENDING_PERM_FILE) {
|
|
|
6919
7501
|
...e.origin ? { origin: e.origin } : {}
|
|
6920
7502
|
};
|
|
6921
7503
|
}
|
|
6922
|
-
|
|
7504
|
+
writeFileSync9(file, JSON.stringify(out));
|
|
6923
7505
|
} catch (error) {
|
|
6924
7506
|
console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error);
|
|
6925
7507
|
}
|
|
6926
7508
|
}
|
|
6927
7509
|
function createPermissionGate(deps) {
|
|
6928
7510
|
const PERSIST_FILE = deps.persistFile ?? PENDING_PERM_FILE;
|
|
7511
|
+
const SEND_GRACE_MS = deps.sendGraceMs ?? resolvePermSendGraceMs(process.env.QQ_PERM_SEND_GRACE_MS);
|
|
6929
7512
|
const { client, sendReply, safeDeliver } = deps;
|
|
6930
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
|
+
}
|
|
6931
7564
|
const pushedCardIds = new Set;
|
|
6932
7565
|
function claimCardPush(requestId) {
|
|
6933
7566
|
if (pushedCardIds.has(requestId))
|
|
@@ -6977,6 +7610,7 @@ function createPermissionGate(deps) {
|
|
|
6977
7610
|
adopted.alertTimer = startNudgeTimer(ctx.userId, request.id, ctx);
|
|
6978
7611
|
adopted.timer = setTimeout(() => {
|
|
6979
7612
|
if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
|
|
7613
|
+
markResolvedRecently(request.id);
|
|
6980
7614
|
pendingPermissions.delete(ctx.userId);
|
|
6981
7615
|
savePendingPermMap(pendingPermissions, PERSIST_FILE);
|
|
6982
7616
|
deps.onDecision?.(ctx.userId);
|
|
@@ -6997,6 +7631,7 @@ function createPermissionGate(deps) {
|
|
|
6997
7631
|
const alertTimer = startNudgeTimer(ctx.userId, request.id, ctx);
|
|
6998
7632
|
const timer = setTimeout(() => {
|
|
6999
7633
|
if (pendingPermissions.get(ctx.userId)?.request.id === request.id) {
|
|
7634
|
+
markResolvedRecently(request.id);
|
|
7000
7635
|
pendingPermissions.delete(ctx.userId);
|
|
7001
7636
|
savePendingPermMap(pendingPermissions, PERSIST_FILE);
|
|
7002
7637
|
deps.onDecision?.(ctx.userId);
|
|
@@ -7019,9 +7654,28 @@ function createPermissionGate(deps) {
|
|
|
7019
7654
|
savePendingPermMap(pendingPermissions, PERSIST_FILE);
|
|
7020
7655
|
if (claimCardPush(request.id)) {
|
|
7021
7656
|
(async () => {
|
|
7022
|
-
const
|
|
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
|
+
}
|
|
7023
7677
|
if (!sentByCard) {
|
|
7024
|
-
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) => {
|
|
7025
7679
|
console.error("[bridge] 发送审批请求失败:", error);
|
|
7026
7680
|
});
|
|
7027
7681
|
}
|
|
@@ -7033,6 +7687,7 @@ function createPermissionGate(deps) {
|
|
|
7033
7687
|
const entry = pendingPermissions.get(userId);
|
|
7034
7688
|
if (!entry)
|
|
7035
7689
|
return;
|
|
7690
|
+
markResolvedRecently(entry.request.id);
|
|
7036
7691
|
clearTimers(entry);
|
|
7037
7692
|
pendingPermissions.delete(userId);
|
|
7038
7693
|
savePendingPermMap(pendingPermissions, PERSIST_FILE);
|
|
@@ -7101,8 +7756,10 @@ function createPermissionGate(deps) {
|
|
|
7101
7756
|
console.log(`[perm] 恢复重启前挂起的审批 ${uid.slice(0, 8)}… request=${e.request.id}`);
|
|
7102
7757
|
(async () => {
|
|
7103
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);
|
|
7104
7761
|
if (!sentByCard) {
|
|
7105
|
-
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) => {
|
|
7106
7763
|
console.error("[bridge] 恢复审批推送失败:", error);
|
|
7107
7764
|
});
|
|
7108
7765
|
}
|
|
@@ -7120,6 +7777,7 @@ function createPermissionGate(deps) {
|
|
|
7120
7777
|
const timer = setTimeout(() => {
|
|
7121
7778
|
if (pendingPermissions.get(userId)?.request.id !== request.id)
|
|
7122
7779
|
return;
|
|
7780
|
+
markResolvedRecently(request.id);
|
|
7123
7781
|
pendingPermissions.delete(userId);
|
|
7124
7782
|
savePendingPermMap(pendingPermissions, PERSIST_FILE);
|
|
7125
7783
|
deps.onDecision?.(userId);
|
|
@@ -7143,17 +7801,28 @@ function createPermissionGate(deps) {
|
|
|
7143
7801
|
console.log(`[perm] 外部审批已推送 user=${userId.slice(0, 8)}… request=${request.id} action=${request.action} origin=${origin}`);
|
|
7144
7802
|
if (claimCardPush(request.id)) {
|
|
7145
7803
|
(async () => {
|
|
7146
|
-
const
|
|
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);
|
|
7147
7819
|
const stillPending = () => pendingPermissions.get(userId)?.request.id === request.id;
|
|
7148
7820
|
if (!stillPending()) {
|
|
7149
7821
|
console.log(`[perm] 发卡途中槽被清:卡片将迟到(死卡,平台无撤回),request=${request.id}`);
|
|
7822
|
+
return;
|
|
7150
7823
|
}
|
|
7151
7824
|
if (!sentByCard) {
|
|
7152
|
-
|
|
7153
|
-
console.log(`[perm] 文字降级前复查:槽已清(他端已处理),跳过文字菜单 request=${request.id}`);
|
|
7154
|
-
return;
|
|
7155
|
-
}
|
|
7156
|
-
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external")).catch((error) => {
|
|
7825
|
+
await sendReply(ctx, formatPermissionPrompt(request, mainSessionId, "external")).then(() => markPromptDelivered(userId, request.id)).catch((error) => {
|
|
7157
7826
|
console.error("[bridge] 发送审批请求失败:", error);
|
|
7158
7827
|
});
|
|
7159
7828
|
}
|
|
@@ -7167,18 +7836,35 @@ function createPermissionGate(deps) {
|
|
|
7167
7836
|
if (sessionID && entry.request.sessionID && sessionID !== entry.request.sessionID)
|
|
7168
7837
|
continue;
|
|
7169
7838
|
const e = entry;
|
|
7839
|
+
markResolvedRecently(requestID);
|
|
7170
7840
|
clearTimers(e);
|
|
7171
7841
|
pendingPermissions.delete(uid);
|
|
7172
7842
|
savePendingPermMap(pendingPermissions, PERSIST_FILE);
|
|
7173
7843
|
deps.onDecision?.(uid);
|
|
7174
7844
|
const label = reply === "allow" || reply === "once" ? "允许(本次)" : reply === "always" ? "总是允许" : reply === "reject" ? "拒绝" : `已处理(${String(reply ?? "未知")})`;
|
|
7175
7845
|
console.log(`[perm] 联动清槽(源头已解决):uid=${uid.slice(0, 8)}… request=${requestID} reply=${String(reply)}`);
|
|
7176
|
-
|
|
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
|
+
}
|
|
7177
7854
|
return true;
|
|
7178
7855
|
}
|
|
7179
7856
|
return false;
|
|
7180
7857
|
}
|
|
7181
|
-
return {
|
|
7858
|
+
return {
|
|
7859
|
+
hasPending,
|
|
7860
|
+
getPending,
|
|
7861
|
+
waitForDecision,
|
|
7862
|
+
resolve,
|
|
7863
|
+
restore,
|
|
7864
|
+
pushExternal: pushExternalImpl,
|
|
7865
|
+
clearIfResolved,
|
|
7866
|
+
wasResolvedRecently
|
|
7867
|
+
};
|
|
7182
7868
|
}
|
|
7183
7869
|
function parsePermissionDecision(content) {
|
|
7184
7870
|
const t = content.trim().toLowerCase().replace(/^\/(allow|always|deny|reject|ok|yes|no)\s*$/, "$1");
|
|
@@ -7220,7 +7906,7 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
|
|
|
7220
7906
|
}
|
|
7221
7907
|
|
|
7222
7908
|
// src/core/delivery.ts
|
|
7223
|
-
import { existsSync as
|
|
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";
|
|
7224
7910
|
import { join as join9 } from "path";
|
|
7225
7911
|
import { createHash } from "node:crypto";
|
|
7226
7912
|
|
|
@@ -7473,23 +8159,58 @@ async function sendChunk(accessToken, ctx, mdText, plainText, msgSeq) {
|
|
|
7473
8159
|
return await sendC2CMessage(accessToken, ctx.userId, plainText, ctx.msgId, msgSeq, false);
|
|
7474
8160
|
}
|
|
7475
8161
|
}
|
|
8162
|
+
|
|
8163
|
+
class PartialReplyError extends Error {
|
|
8164
|
+
receipts;
|
|
8165
|
+
failedChunkIndex;
|
|
8166
|
+
originalError;
|
|
8167
|
+
name = "PartialReplyError";
|
|
8168
|
+
constructor(receipts, failedChunkIndex, originalError) {
|
|
8169
|
+
super(`QQ 分片发送中断:第 ${failedChunkIndex + 1} 片失败,此前已成功 ${receipts.length} 片`);
|
|
8170
|
+
this.receipts = receipts;
|
|
8171
|
+
this.failedChunkIndex = failedChunkIndex;
|
|
8172
|
+
this.originalError = originalError;
|
|
8173
|
+
}
|
|
8174
|
+
}
|
|
7476
8175
|
async function replyToQQ(accessToken, ctx, text, options) {
|
|
7477
8176
|
const mdFormatted = formatForQQMarkdown(text);
|
|
7478
8177
|
const plainFormatted = formatForQQ(text);
|
|
7479
|
-
const
|
|
7480
|
-
const
|
|
8178
|
+
const continuationPrefix = options?.continuationPrefix ?? "";
|
|
8179
|
+
const continuationBytes = utf8Bytes(continuationPrefix);
|
|
8180
|
+
if (continuationBytes >= Math.min(MARKDOWN_MAX_BYTES, PLAIN_MAX_BYTES) - 1024) {
|
|
8181
|
+
throw new Error("continuationPrefix 过长,无法为正文预留分片空间");
|
|
8182
|
+
}
|
|
8183
|
+
const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES - continuationBytes).map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk);
|
|
8184
|
+
const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES - continuationBytes).map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk);
|
|
7481
8185
|
const delays = staggerDelays(mdChunks.length, options?.staggerMs ?? 0);
|
|
7482
|
-
const
|
|
8186
|
+
const receipts = [];
|
|
7483
8187
|
for (let i = 0;i < mdChunks.length; i++) {
|
|
7484
8188
|
if (i > 0 && delays[i - 1])
|
|
7485
8189
|
await sleep4(delays[i - 1]);
|
|
7486
8190
|
const msgSeq = getNextMsgSeq(ctx.msgId);
|
|
7487
8191
|
const plainChunk = plainChunks[i] ?? plainChunks[plainChunks.length - 1] ?? mdChunks[i];
|
|
7488
|
-
|
|
7489
|
-
|
|
7490
|
-
|
|
8192
|
+
let res;
|
|
8193
|
+
try {
|
|
8194
|
+
res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq);
|
|
8195
|
+
} catch (error) {
|
|
8196
|
+
if (receipts.length > 0)
|
|
8197
|
+
throw new PartialReplyError(receipts, i, error);
|
|
8198
|
+
throw error;
|
|
8199
|
+
}
|
|
8200
|
+
if (res?.id) {
|
|
8201
|
+
const receipt = {
|
|
8202
|
+
id: res.id,
|
|
8203
|
+
...res.ext_info?.ref_idx ? { refIdx: res.ext_info.ref_idx } : {}
|
|
8204
|
+
};
|
|
8205
|
+
receipts.push(receipt);
|
|
8206
|
+
try {
|
|
8207
|
+
await options?.onReceipt?.(receipt);
|
|
8208
|
+
} catch (error) {
|
|
8209
|
+
console.error("[qq-sender] 分片回执回调失败:", error);
|
|
8210
|
+
}
|
|
8211
|
+
}
|
|
7491
8212
|
}
|
|
7492
|
-
return { chunks: mdChunks.length, ids };
|
|
8213
|
+
return { chunks: mdChunks.length, ids: receipts.map((receipt) => receipt.id), receipts };
|
|
7493
8214
|
}
|
|
7494
8215
|
|
|
7495
8216
|
// src/core/reply-limiter.ts
|
|
@@ -7617,8 +8338,8 @@ function extractEmbeddedQuote(event) {
|
|
|
7617
8338
|
var DEFAULT_QUOTA_FILE = storageFile("quota.json");
|
|
7618
8339
|
function loadQuotaMap(file) {
|
|
7619
8340
|
try {
|
|
7620
|
-
if (
|
|
7621
|
-
const raw =
|
|
8341
|
+
if (existsSync11(file)) {
|
|
8342
|
+
const raw = readFileSync13(file, "utf-8");
|
|
7622
8343
|
const obj = JSON.parse(raw);
|
|
7623
8344
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
7624
8345
|
const out = {};
|
|
@@ -7636,13 +8357,14 @@ function loadQuotaMap(file) {
|
|
|
7636
8357
|
}
|
|
7637
8358
|
function saveQuotaMap(file, m) {
|
|
7638
8359
|
try {
|
|
7639
|
-
|
|
8360
|
+
writeFileSync10(file, JSON.stringify(Object.fromEntries(m)));
|
|
7640
8361
|
} catch (error) {
|
|
7641
8362
|
console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error);
|
|
7642
8363
|
}
|
|
7643
8364
|
}
|
|
7644
8365
|
var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
|
|
7645
8366
|
`;
|
|
8367
|
+
var PARTIAL_DELIVERY_NOTICE = "⚠️ 本轮消息仅部分送达。为避免重复,已阻止自动全文重发;完整结果请发 /history 查看,或重新提问。";
|
|
7646
8368
|
var QQ_LIST_FORMAT_HINT = `
|
|
7647
8369
|
|
|
7648
8370
|
(输出格式约定:本对话经 QQ 渲染,请用「1、2、3、」顿号或「-」无序列表代替 markdown 有序列表,避免表格;代码块不受影响可正常使用。)`;
|
|
@@ -7652,7 +8374,7 @@ function qqPromptHints() {
|
|
|
7652
8374
|
const file = join9(storageRoot(), "qq-system-instructions.json");
|
|
7653
8375
|
const st = statSync5(file);
|
|
7654
8376
|
if (Date.now() - st.mtimeMs < 15 * 60000) {
|
|
7655
|
-
const parsed = JSON.parse(
|
|
8377
|
+
const parsed = JSON.parse(readFileSync13(file, "utf-8"));
|
|
7656
8378
|
if (parsed?.mode === "entry" || parsed?.mode === "hook")
|
|
7657
8379
|
return "";
|
|
7658
8380
|
}
|
|
@@ -7708,9 +8430,9 @@ function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TT
|
|
|
7708
8430
|
function loadDeliveryAttempts() {
|
|
7709
8431
|
const out = new Map;
|
|
7710
8432
|
try {
|
|
7711
|
-
if (!
|
|
8433
|
+
if (!existsSync11(deliveryDedupeFile()))
|
|
7712
8434
|
return out;
|
|
7713
|
-
const raw = JSON.parse(
|
|
8435
|
+
const raw = JSON.parse(readFileSync13(deliveryDedupeFile(), "utf-8"));
|
|
7714
8436
|
const now = Date.now();
|
|
7715
8437
|
for (const entry of raw) {
|
|
7716
8438
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -7722,14 +8444,14 @@ function loadDeliveryAttempts() {
|
|
|
7722
8444
|
}
|
|
7723
8445
|
function saveDeliveryAttempts(entries) {
|
|
7724
8446
|
const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
|
|
7725
|
-
|
|
8447
|
+
mkdirSync9(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
7726
8448
|
const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
7727
8449
|
try {
|
|
7728
|
-
|
|
7729
|
-
|
|
8450
|
+
writeFileSync10(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
|
|
8451
|
+
renameSync4(tmp, deliveryDedupeFile());
|
|
7730
8452
|
} catch (error) {
|
|
7731
8453
|
try {
|
|
7732
|
-
|
|
8454
|
+
unlinkSync4(tmp);
|
|
7733
8455
|
} catch {}
|
|
7734
8456
|
throw error;
|
|
7735
8457
|
}
|
|
@@ -7738,7 +8460,7 @@ var DELIVERY_LOCK_STALE_MS = 30000;
|
|
|
7738
8460
|
var DELIVERY_LOCK_WAIT_MS = 5000;
|
|
7739
8461
|
var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
7740
8462
|
function withDeliveryLock(fn) {
|
|
7741
|
-
|
|
8463
|
+
mkdirSync9(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
7742
8464
|
const lockPath = `${deliveryDedupeFile()}.lock`;
|
|
7743
8465
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
7744
8466
|
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
|
|
@@ -7746,7 +8468,7 @@ function withDeliveryLock(fn) {
|
|
|
7746
8468
|
try {
|
|
7747
8469
|
const fd = openSync(lockPath, "wx", 384);
|
|
7748
8470
|
try {
|
|
7749
|
-
|
|
8471
|
+
writeFileSync10(fd, token);
|
|
7750
8472
|
} finally {
|
|
7751
8473
|
closeSync(fd);
|
|
7752
8474
|
}
|
|
@@ -7754,7 +8476,7 @@ function withDeliveryLock(fn) {
|
|
|
7754
8476
|
} catch (error) {
|
|
7755
8477
|
try {
|
|
7756
8478
|
if (Date.now() - statSync5(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS)
|
|
7757
|
-
|
|
8479
|
+
unlinkSync4(lockPath);
|
|
7758
8480
|
} catch {}
|
|
7759
8481
|
if (Date.now() >= deadline)
|
|
7760
8482
|
throw new Error(`同文投递锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
@@ -7765,8 +8487,8 @@ function withDeliveryLock(fn) {
|
|
|
7765
8487
|
return fn();
|
|
7766
8488
|
} finally {
|
|
7767
8489
|
try {
|
|
7768
|
-
if (
|
|
7769
|
-
|
|
8490
|
+
if (readFileSync13(lockPath, "utf-8") === token)
|
|
8491
|
+
unlinkSync4(lockPath);
|
|
7770
8492
|
} catch {}
|
|
7771
8493
|
}
|
|
7772
8494
|
}
|
|
@@ -7819,6 +8541,7 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7819
8541
|
})();
|
|
7820
8542
|
const pushQueues = new Map;
|
|
7821
8543
|
const undelivered = new Set;
|
|
8544
|
+
const partialFailures = new WeakSet;
|
|
7822
8545
|
const activeQuota = new Map;
|
|
7823
8546
|
const passiveLimiter = new ReplyLimiter;
|
|
7824
8547
|
const QUOTA_FILE = quotaFile ?? DEFAULT_QUOTA_FILE;
|
|
@@ -7875,7 +8598,21 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7875
8598
|
}
|
|
7876
8599
|
}
|
|
7877
8600
|
}
|
|
7878
|
-
|
|
8601
|
+
function recordSent(scope, text, receipt) {
|
|
8602
|
+
recordMessage(scope, receipt.id, text);
|
|
8603
|
+
if (receipt.refIdx && receipt.refIdx !== receipt.id)
|
|
8604
|
+
recordMessage(scope, receipt.refIdx, text);
|
|
8605
|
+
}
|
|
8606
|
+
async function emitSent(onSent, receipt) {
|
|
8607
|
+
if (!onSent)
|
|
8608
|
+
return;
|
|
8609
|
+
try {
|
|
8610
|
+
await onSent(receipt);
|
|
8611
|
+
} catch (error) {
|
|
8612
|
+
console.error("[delivery] onSent 回执处理失败(QQ 消息已发送):", error);
|
|
8613
|
+
}
|
|
8614
|
+
}
|
|
8615
|
+
async function deliver(ctx, text, onSent, content) {
|
|
7879
8616
|
if (ctx.anchorSessionId && pushGate && !pushGate(ctx.userId, ctx.anchorSessionId)) {
|
|
7880
8617
|
console.log(`[push-gate] 出站拦截:绑定已切走 anchor=${ctx.anchorSessionId.slice(0, 12)}… user=${ctx.userId.slice(0, 8)}… chars=${text.length}`);
|
|
7881
8618
|
return false;
|
|
@@ -7889,34 +8626,49 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7889
8626
|
const hadNotice = undelivered.delete(ctx.userId);
|
|
7890
8627
|
const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text);
|
|
7891
8628
|
try {
|
|
7892
|
-
await deliverCore(ctx, body);
|
|
8629
|
+
await deliverCore(ctx, body, onSent, content);
|
|
7893
8630
|
return true;
|
|
7894
8631
|
} catch (error) {
|
|
8632
|
+
if (error instanceof PartialReplyError) {
|
|
8633
|
+
partialFailures.add(ctx);
|
|
8634
|
+
console.error(`[delivery] 分片部分失败,禁止全文降级 sent=${error.receipts.length} failedChunk=${error.failedChunkIndex + 1}`);
|
|
8635
|
+
try {
|
|
8636
|
+
await sendActive(ctx, PARTIAL_DELIVERY_NOTICE);
|
|
8637
|
+
} catch (alertError) {
|
|
8638
|
+
undelivered.add(ctx.userId);
|
|
8639
|
+
console.error("[delivery] 部分失败告警也未能送达:", alertError);
|
|
8640
|
+
}
|
|
8641
|
+
return false;
|
|
8642
|
+
}
|
|
7895
8643
|
releaseDeliveryAttempt(ctx.userId, text, now);
|
|
7896
8644
|
if (hadNotice)
|
|
7897
8645
|
undelivered.add(ctx.userId);
|
|
7898
8646
|
throw error;
|
|
7899
8647
|
}
|
|
7900
8648
|
}
|
|
7901
|
-
async function deliverCore(ctx, text) {
|
|
8649
|
+
async function deliverCore(ctx, text, onSent, content) {
|
|
7902
8650
|
const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null;
|
|
7903
8651
|
if (passive?.shouldFallbackToProactive) {
|
|
7904
8652
|
console.log(`[bridge] 被动回复${passive.fallbackReason === "expired" ? "窗口已过期" : "次数已耗尽"},直接走主动通道: msgId=${ctx.msgId}`);
|
|
7905
8653
|
} else {
|
|
7906
8654
|
try {
|
|
7907
|
-
await sendReply(ctx, text);
|
|
8655
|
+
await sendReply(ctx, text, onSent, content);
|
|
7908
8656
|
return;
|
|
7909
8657
|
} catch (error) {
|
|
8658
|
+
if (error instanceof PartialReplyError)
|
|
8659
|
+
throw error;
|
|
7910
8660
|
console.warn("[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:", error instanceof Error ? error.message : error);
|
|
7911
8661
|
}
|
|
7912
8662
|
}
|
|
7913
8663
|
const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS);
|
|
7914
8664
|
if (rideMsgId) {
|
|
7915
8665
|
try {
|
|
7916
|
-
const
|
|
8666
|
+
const rideReceipts = await sendActive(ctx, text, rideMsgId);
|
|
7917
8667
|
passiveLimiter.record(rideMsgId);
|
|
7918
|
-
for (const
|
|
7919
|
-
|
|
8668
|
+
for (const receipt of rideReceipts) {
|
|
8669
|
+
recordSent(scopeKeyOf(ctx), text, receipt);
|
|
8670
|
+
await emitSent(onSent, receipt);
|
|
8671
|
+
}
|
|
7920
8672
|
console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`);
|
|
7921
8673
|
return;
|
|
7922
8674
|
} catch {
|
|
@@ -7940,15 +8692,17 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7940
8692
|
}
|
|
7941
8693
|
throw new Error("主动消息已达 QQ 官方日上限,本条无法送达");
|
|
7942
8694
|
}
|
|
7943
|
-
const
|
|
7944
|
-
for (const
|
|
7945
|
-
|
|
8695
|
+
const activeReceipts = await sendActive(ctx, text);
|
|
8696
|
+
for (const receipt of activeReceipts) {
|
|
8697
|
+
recordSent(scopeKeyOf(ctx), text, receipt);
|
|
8698
|
+
await emitSent(onSent, receipt);
|
|
8699
|
+
}
|
|
7946
8700
|
q.count++;
|
|
7947
8701
|
saveQuotaMap(QUOTA_FILE, activeQuota);
|
|
7948
8702
|
}
|
|
7949
|
-
async function safeDeliver(c, text) {
|
|
8703
|
+
async function safeDeliver(c, text, onSent, content) {
|
|
7950
8704
|
try {
|
|
7951
|
-
return await deliver(c, text);
|
|
8705
|
+
return await deliver(c, text, onSent, content);
|
|
7952
8706
|
} catch (error) {
|
|
7953
8707
|
undelivered.add(c.userId);
|
|
7954
8708
|
console.error("[bridge] 消息无法送达(被动+主动均失败):", error);
|
|
@@ -7967,58 +8721,76 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
|
|
|
7967
8721
|
const seq = getNextMsgSeq(passiveMsgId ?? "");
|
|
7968
8722
|
const isGroup = ctx.type === "group" && ctx.groupId;
|
|
7969
8723
|
const mdText = normalizeOutboundMarkdown(text);
|
|
7970
|
-
const record = (
|
|
7971
|
-
|
|
8724
|
+
const record = (response) => {
|
|
8725
|
+
const receipts = response?.id ? [{
|
|
8726
|
+
id: response.id,
|
|
8727
|
+
...response.ext_info?.ref_idx ? { refIdx: response.ext_info.ref_idx } : {}
|
|
8728
|
+
}] : [];
|
|
8729
|
+
if (!passiveMsgId && receipts.length > 0)
|
|
7972
8730
|
logActiveSend(activeMinuteLog, ctx.userId, Date.now());
|
|
7973
|
-
return
|
|
8731
|
+
return receipts;
|
|
7974
8732
|
};
|
|
7975
8733
|
try {
|
|
7976
8734
|
if (isGroup) {
|
|
7977
8735
|
const r = await sendGroupMessage(token, ctx.groupId, mdText, passiveMsgId, seq, true);
|
|
7978
|
-
return record(r
|
|
8736
|
+
return record(r);
|
|
7979
8737
|
}
|
|
7980
8738
|
const r = await sendC2CMessage(token, ctx.userId, mdText, passiveMsgId, seq, true);
|
|
7981
|
-
return record(r
|
|
8739
|
+
return record(r);
|
|
7982
8740
|
} catch (error) {
|
|
7983
8741
|
console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error);
|
|
7984
8742
|
}
|
|
7985
8743
|
if (isGroup) {
|
|
7986
8744
|
const r = await sendGroupMessage(token, ctx.groupId, text, passiveMsgId, seq, false);
|
|
7987
|
-
return record(r
|
|
8745
|
+
return record(r);
|
|
7988
8746
|
}
|
|
7989
8747
|
const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false);
|
|
7990
|
-
return record(r
|
|
8748
|
+
return record(r);
|
|
7991
8749
|
}
|
|
7992
|
-
async function sendReply(ctx, text) {
|
|
8750
|
+
async function sendReply(ctx, text, onSent, content) {
|
|
7993
8751
|
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret);
|
|
8752
|
+
const scope = scopeKeyOf(ctx);
|
|
7994
8753
|
const result = await replyToQQ(accessToken, ctx, text, {
|
|
7995
|
-
staggerMs: STREAM_STAGGER_MS
|
|
8754
|
+
staggerMs: STREAM_STAGGER_MS,
|
|
8755
|
+
continuationPrefix: content?.continuationPrefix,
|
|
8756
|
+
onReceipt: async (receipt) => {
|
|
8757
|
+
recordSent(scope, text, receipt);
|
|
8758
|
+
await emitSent(onSent, receipt);
|
|
8759
|
+
}
|
|
7996
8760
|
});
|
|
7997
8761
|
if (ctx.msgId) {
|
|
7998
8762
|
for (let i = 0;i < result.chunks; i++)
|
|
7999
8763
|
passiveLimiter.record(ctx.msgId);
|
|
8000
8764
|
}
|
|
8001
|
-
const scope = scopeKeyOf(ctx);
|
|
8002
|
-
for (const id of result.ids)
|
|
8003
|
-
recordMessage(scope, id, text);
|
|
8004
8765
|
}
|
|
8005
|
-
return {
|
|
8766
|
+
return {
|
|
8767
|
+
enqueuePush,
|
|
8768
|
+
deliver,
|
|
8769
|
+
safeDeliver,
|
|
8770
|
+
sendReply,
|
|
8771
|
+
consumePartialFailure(ctx) {
|
|
8772
|
+
if (!partialFailures.has(ctx))
|
|
8773
|
+
return false;
|
|
8774
|
+
partialFailures.delete(ctx);
|
|
8775
|
+
return true;
|
|
8776
|
+
}
|
|
8777
|
+
};
|
|
8006
8778
|
}
|
|
8007
8779
|
|
|
8008
8780
|
// src/core/outbox.ts
|
|
8009
8781
|
import {
|
|
8010
8782
|
closeSync as closeSync2,
|
|
8011
|
-
existsSync as
|
|
8012
|
-
mkdirSync as
|
|
8783
|
+
existsSync as existsSync12,
|
|
8784
|
+
mkdirSync as mkdirSync10,
|
|
8013
8785
|
openSync as openSync2,
|
|
8014
|
-
readFileSync as
|
|
8015
|
-
renameSync as
|
|
8786
|
+
readFileSync as readFileSync14,
|
|
8787
|
+
renameSync as renameSync5,
|
|
8016
8788
|
statSync as statSync6,
|
|
8017
|
-
unlinkSync as
|
|
8018
|
-
writeFileSync as
|
|
8789
|
+
unlinkSync as unlinkSync5,
|
|
8790
|
+
writeFileSync as writeFileSync11
|
|
8019
8791
|
} from "node:fs";
|
|
8020
|
-
import { dirname as
|
|
8021
|
-
import { randomUUID } from "node:crypto";
|
|
8792
|
+
import { dirname as dirname3 } from "node:path";
|
|
8793
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8022
8794
|
var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
8023
8795
|
var OUTBOX_SENT_RETENTION_LIMIT = 20;
|
|
8024
8796
|
var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
|
|
@@ -8053,22 +8825,22 @@ function delay(ms) {
|
|
|
8053
8825
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
8054
8826
|
}
|
|
8055
8827
|
function atomicWrite(filePath, document) {
|
|
8056
|
-
|
|
8057
|
-
const temporary = `${filePath}.${process.pid}.${
|
|
8828
|
+
mkdirSync10(dirname3(filePath), { recursive: true });
|
|
8829
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID2()}.tmp`;
|
|
8058
8830
|
try {
|
|
8059
|
-
|
|
8060
|
-
|
|
8831
|
+
writeFileSync11(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
8832
|
+
renameSync5(temporary, filePath);
|
|
8061
8833
|
} catch (error) {
|
|
8062
8834
|
try {
|
|
8063
|
-
|
|
8835
|
+
unlinkSync5(temporary);
|
|
8064
8836
|
} catch {}
|
|
8065
8837
|
throw error;
|
|
8066
8838
|
}
|
|
8067
8839
|
}
|
|
8068
8840
|
function readDocument(filePath, now) {
|
|
8069
|
-
if (!
|
|
8841
|
+
if (!existsSync12(filePath))
|
|
8070
8842
|
return { version: 1, entries: [] };
|
|
8071
|
-
const raw = JSON.parse(
|
|
8843
|
+
const raw = JSON.parse(readFileSync14(filePath, "utf8"));
|
|
8072
8844
|
if (Array.isArray(raw)) {
|
|
8073
8845
|
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
8074
8846
|
}
|
|
@@ -8091,7 +8863,7 @@ function createOutbox(options = {}) {
|
|
|
8091
8863
|
const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
|
|
8092
8864
|
const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
|
|
8093
8865
|
const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
|
|
8094
|
-
const owner = `${process.pid}:${
|
|
8866
|
+
const owner = `${process.pid}:${randomUUID2()}`;
|
|
8095
8867
|
const handlers = new Map;
|
|
8096
8868
|
const inFlight = new Map;
|
|
8097
8869
|
const automatic = new Set;
|
|
@@ -8099,15 +8871,15 @@ function createOutbox(options = {}) {
|
|
|
8099
8871
|
let stopped = false;
|
|
8100
8872
|
let flushing;
|
|
8101
8873
|
function withLock(fn) {
|
|
8102
|
-
|
|
8874
|
+
mkdirSync10(dirname3(filePath), { recursive: true });
|
|
8103
8875
|
const lockPath = `${filePath}.lock`;
|
|
8104
|
-
const token = `${owner}:${Date.now()}:${
|
|
8876
|
+
const token = `${owner}:${Date.now()}:${randomUUID2()}`;
|
|
8105
8877
|
const deadline = Date.now() + lockWaitMs;
|
|
8106
8878
|
for (;; ) {
|
|
8107
8879
|
try {
|
|
8108
8880
|
const fd = openSync2(lockPath, "wx", 384);
|
|
8109
8881
|
try {
|
|
8110
|
-
|
|
8882
|
+
writeFileSync11(fd, token);
|
|
8111
8883
|
} finally {
|
|
8112
8884
|
closeSync2(fd);
|
|
8113
8885
|
}
|
|
@@ -8115,7 +8887,7 @@ function createOutbox(options = {}) {
|
|
|
8115
8887
|
} catch (error) {
|
|
8116
8888
|
try {
|
|
8117
8889
|
if (Date.now() - statSync6(lockPath).mtimeMs > lockStaleMs)
|
|
8118
|
-
|
|
8890
|
+
unlinkSync5(lockPath);
|
|
8119
8891
|
} catch {}
|
|
8120
8892
|
if (Date.now() >= deadline)
|
|
8121
8893
|
throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
|
|
@@ -8126,8 +8898,8 @@ function createOutbox(options = {}) {
|
|
|
8126
8898
|
return fn();
|
|
8127
8899
|
} finally {
|
|
8128
8900
|
try {
|
|
8129
|
-
if (
|
|
8130
|
-
|
|
8901
|
+
if (readFileSync14(lockPath, "utf8") === token)
|
|
8902
|
+
unlinkSync5(lockPath);
|
|
8131
8903
|
} catch {}
|
|
8132
8904
|
}
|
|
8133
8905
|
}
|
|
@@ -8189,7 +8961,7 @@ function createOutbox(options = {}) {
|
|
|
8189
8961
|
if (!handler)
|
|
8190
8962
|
return clone(handlerlessSnapshot);
|
|
8191
8963
|
const now = Date.now();
|
|
8192
|
-
const token = `${owner}:${
|
|
8964
|
+
const token = `${owner}:${randomUUID2()}`;
|
|
8193
8965
|
const claimed = withLock(() => {
|
|
8194
8966
|
const document = readDocument(filePath, now);
|
|
8195
8967
|
const entry = document.entries.find((candidate) => candidate.id === id);
|
|
@@ -8349,7 +9121,7 @@ function createOutbox(options = {}) {
|
|
|
8349
9121
|
const persistedCtx = jsonSnapshot(input.ctx, "ctx");
|
|
8350
9122
|
const persistedPayload = jsonSnapshot(input.payload, "payload");
|
|
8351
9123
|
const now = Date.now();
|
|
8352
|
-
const id = input.id ??
|
|
9124
|
+
const id = input.id ?? randomUUID2();
|
|
8353
9125
|
const entry = mutate((entries) => {
|
|
8354
9126
|
const existing = entries.find((candidate) => candidate.id === id);
|
|
8355
9127
|
if (existing)
|
|
@@ -8426,7 +9198,7 @@ function createNotifySink(options) {
|
|
|
8426
9198
|
return { skipped: "no-text" };
|
|
8427
9199
|
}
|
|
8428
9200
|
const ctx = entry.ctx;
|
|
8429
|
-
return options.deliver(ctx, text).then(() => ({ delivered
|
|
9201
|
+
return options.deliver(ctx, text).then((delivered) => ({ delivered, text: text.slice(0, 120) }));
|
|
8430
9202
|
});
|
|
8431
9203
|
outbox.start({ recover: true, maxAttempts }).catch((error) => {
|
|
8432
9204
|
console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error);
|
|
@@ -8478,11 +9250,19 @@ function buildApprovalKeyboard(request, ownerOpenid) {
|
|
|
8478
9250
|
}
|
|
8479
9251
|
};
|
|
8480
9252
|
}
|
|
8481
|
-
async function sendApprovalCard(deps, ctx, request, mainSessionId, origin) {
|
|
9253
|
+
async function sendApprovalCard(deps, ctx, request, mainSessionId, origin, isCancelled) {
|
|
8482
9254
|
try {
|
|
8483
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
|
+
}
|
|
8484
9260
|
const keyboard = buildApprovalKeyboard(request, ctx.userId);
|
|
8485
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
|
+
}
|
|
8486
9266
|
if (ctx.type === "group" && ctx.groupId) {
|
|
8487
9267
|
await sendGroupMessage(token, ctx.groupId, text, ctx.msgId, undefined, true, keyboard);
|
|
8488
9268
|
} else {
|
|
@@ -8519,16 +9299,16 @@ function handleApprovalInteraction(event, gate) {
|
|
|
8519
9299
|
// src/core/form-journal.ts
|
|
8520
9300
|
import {
|
|
8521
9301
|
closeSync as closeSync3,
|
|
8522
|
-
existsSync as
|
|
8523
|
-
mkdirSync as
|
|
9302
|
+
existsSync as existsSync13,
|
|
9303
|
+
mkdirSync as mkdirSync11,
|
|
8524
9304
|
openSync as openSync3,
|
|
8525
|
-
readFileSync as
|
|
8526
|
-
renameSync as
|
|
9305
|
+
readFileSync as readFileSync15,
|
|
9306
|
+
renameSync as renameSync6,
|
|
8527
9307
|
statSync as statSync7,
|
|
8528
|
-
unlinkSync as
|
|
8529
|
-
writeFileSync as
|
|
9308
|
+
unlinkSync as unlinkSync6,
|
|
9309
|
+
writeFileSync as writeFileSync12
|
|
8530
9310
|
} from "fs";
|
|
8531
|
-
import { dirname as
|
|
9311
|
+
import { dirname as dirname4 } from "path";
|
|
8532
9312
|
var LOCK_STALE_MS = 30000;
|
|
8533
9313
|
var LOCK_WAIT_MS = 5000;
|
|
8534
9314
|
var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
|
|
@@ -8587,9 +9367,9 @@ function snapshot(entry) {
|
|
|
8587
9367
|
function createFormJournal(path = defaultFormJournalPath()) {
|
|
8588
9368
|
function read() {
|
|
8589
9369
|
try {
|
|
8590
|
-
if (!
|
|
9370
|
+
if (!existsSync13(path))
|
|
8591
9371
|
return [];
|
|
8592
|
-
const raw = JSON.parse(
|
|
9372
|
+
const raw = JSON.parse(readFileSync15(path, "utf-8"));
|
|
8593
9373
|
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
8594
9374
|
const byUser = new Map;
|
|
8595
9375
|
for (const value of values) {
|
|
@@ -8607,21 +9387,21 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8607
9387
|
}
|
|
8608
9388
|
}
|
|
8609
9389
|
function write(entries) {
|
|
8610
|
-
|
|
9390
|
+
mkdirSync11(dirname4(path), { recursive: true });
|
|
8611
9391
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
8612
9392
|
const payload = { version: 1, entries: entries.map(snapshot) };
|
|
8613
9393
|
try {
|
|
8614
|
-
|
|
8615
|
-
|
|
9394
|
+
writeFileSync12(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
|
|
9395
|
+
renameSync6(tmp, path);
|
|
8616
9396
|
} catch (error) {
|
|
8617
9397
|
try {
|
|
8618
|
-
|
|
9398
|
+
unlinkSync6(tmp);
|
|
8619
9399
|
} catch {}
|
|
8620
9400
|
throw error;
|
|
8621
9401
|
}
|
|
8622
9402
|
}
|
|
8623
9403
|
function withLock(fn) {
|
|
8624
|
-
|
|
9404
|
+
mkdirSync11(dirname4(path), { recursive: true });
|
|
8625
9405
|
const lockPath = `${path}.lock`;
|
|
8626
9406
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
8627
9407
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
@@ -8629,7 +9409,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8629
9409
|
try {
|
|
8630
9410
|
const fd = openSync3(lockPath, "wx", 384);
|
|
8631
9411
|
try {
|
|
8632
|
-
|
|
9412
|
+
writeFileSync12(fd, token);
|
|
8633
9413
|
} finally {
|
|
8634
9414
|
closeSync3(fd);
|
|
8635
9415
|
}
|
|
@@ -8637,7 +9417,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8637
9417
|
} catch (error) {
|
|
8638
9418
|
try {
|
|
8639
9419
|
if (Date.now() - statSync7(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
8640
|
-
|
|
9420
|
+
unlinkSync6(lockPath);
|
|
8641
9421
|
} catch {}
|
|
8642
9422
|
if (Date.now() >= deadline) {
|
|
8643
9423
|
throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
@@ -8649,8 +9429,8 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
8649
9429
|
return fn();
|
|
8650
9430
|
} finally {
|
|
8651
9431
|
try {
|
|
8652
|
-
if (
|
|
8653
|
-
|
|
9432
|
+
if (readFileSync15(lockPath, "utf-8") === token)
|
|
9433
|
+
unlinkSync6(lockPath);
|
|
8654
9434
|
} catch {}
|
|
8655
9435
|
}
|
|
8656
9436
|
}
|
|
@@ -9216,7 +9996,7 @@ function createFormBridge(deps) {
|
|
|
9216
9996
|
}
|
|
9217
9997
|
|
|
9218
9998
|
// src/core/inflight-journal.ts
|
|
9219
|
-
import { existsSync as
|
|
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";
|
|
9220
10000
|
import { join as join10 } from "path";
|
|
9221
10001
|
|
|
9222
10002
|
// src/core/inbound-dedupe.ts
|
|
@@ -9256,8 +10036,8 @@ function load(file) {
|
|
|
9256
10036
|
let entries = [];
|
|
9257
10037
|
const path = journalPath(file);
|
|
9258
10038
|
try {
|
|
9259
|
-
if (
|
|
9260
|
-
const raw = JSON.parse(
|
|
10039
|
+
if (existsSync14(path)) {
|
|
10040
|
+
const raw = JSON.parse(readFileSync16(path, "utf-8"));
|
|
9261
10041
|
if (Array.isArray(raw))
|
|
9262
10042
|
entries = raw;
|
|
9263
10043
|
}
|
|
@@ -9268,15 +10048,15 @@ function load(file) {
|
|
|
9268
10048
|
}
|
|
9269
10049
|
function save(file, entries) {
|
|
9270
10050
|
const path = journalPath(file);
|
|
9271
|
-
|
|
10051
|
+
mkdirSync12(join10(path, ".."), { recursive: true });
|
|
9272
10052
|
const retained = pruneInflightEntries(entries);
|
|
9273
10053
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
9274
10054
|
try {
|
|
9275
|
-
|
|
9276
|
-
|
|
10055
|
+
writeFileSync13(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
|
|
10056
|
+
renameSync7(tmp, path);
|
|
9277
10057
|
} catch (error) {
|
|
9278
10058
|
try {
|
|
9279
|
-
|
|
10059
|
+
unlinkSync7(tmp);
|
|
9280
10060
|
} catch {}
|
|
9281
10061
|
throw error;
|
|
9282
10062
|
}
|
|
@@ -9286,7 +10066,7 @@ var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
|
9286
10066
|
var sleepArray3 = new Int32Array(new SharedArrayBuffer(4));
|
|
9287
10067
|
function withJournalLock(file, fn) {
|
|
9288
10068
|
const path = journalPath(file);
|
|
9289
|
-
|
|
10069
|
+
mkdirSync12(join10(path, ".."), { recursive: true });
|
|
9290
10070
|
const lockPath = `${path}.lock`;
|
|
9291
10071
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
9292
10072
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
@@ -9294,7 +10074,7 @@ function withJournalLock(file, fn) {
|
|
|
9294
10074
|
try {
|
|
9295
10075
|
const fd = openSync4(lockPath, "wx", 384);
|
|
9296
10076
|
try {
|
|
9297
|
-
|
|
10077
|
+
writeFileSync13(fd, token);
|
|
9298
10078
|
} finally {
|
|
9299
10079
|
closeSync4(fd);
|
|
9300
10080
|
}
|
|
@@ -9302,7 +10082,7 @@ function withJournalLock(file, fn) {
|
|
|
9302
10082
|
} catch (error) {
|
|
9303
10083
|
try {
|
|
9304
10084
|
if (Date.now() - statSync8(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
9305
|
-
|
|
10085
|
+
unlinkSync7(lockPath);
|
|
9306
10086
|
} catch {}
|
|
9307
10087
|
if (Date.now() >= deadline) {
|
|
9308
10088
|
throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
@@ -9314,8 +10094,8 @@ function withJournalLock(file, fn) {
|
|
|
9314
10094
|
return fn();
|
|
9315
10095
|
} finally {
|
|
9316
10096
|
try {
|
|
9317
|
-
if (
|
|
9318
|
-
|
|
10097
|
+
if (readFileSync16(lockPath, "utf-8") === token)
|
|
10098
|
+
unlinkSync7(lockPath);
|
|
9319
10099
|
} catch {}
|
|
9320
10100
|
}
|
|
9321
10101
|
}
|
|
@@ -10018,7 +10798,7 @@ function formatStatusLine(view) {
|
|
|
10018
10798
|
init_log_rotate();
|
|
10019
10799
|
|
|
10020
10800
|
// src/core/instance-lock.ts
|
|
10021
|
-
import { openSync as openSync5, readFileSync as
|
|
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";
|
|
10022
10802
|
import { join as join11 } from "path";
|
|
10023
10803
|
import { homedir as homedir6 } from "os";
|
|
10024
10804
|
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
@@ -10037,18 +10817,18 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
|
10037
10817
|
const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS;
|
|
10038
10818
|
const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS;
|
|
10039
10819
|
try {
|
|
10040
|
-
|
|
10820
|
+
mkdirSync13(join11(path, ".."), { recursive: true });
|
|
10041
10821
|
const fd = openSync5(path, "wx");
|
|
10042
|
-
|
|
10822
|
+
writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
10043
10823
|
closeSync5(fd);
|
|
10044
10824
|
} catch {
|
|
10045
10825
|
try {
|
|
10046
10826
|
const age = Date.now() - statSync9(path).mtimeMs;
|
|
10047
10827
|
if (age <= staleMs)
|
|
10048
10828
|
return null;
|
|
10049
|
-
|
|
10829
|
+
unlinkSync8(path);
|
|
10050
10830
|
const fd = openSync5(path, "wx");
|
|
10051
|
-
|
|
10831
|
+
writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
10052
10832
|
closeSync5(fd);
|
|
10053
10833
|
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
10054
10834
|
} catch {
|
|
@@ -10063,7 +10843,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
|
10063
10843
|
heartbeat.unref?.();
|
|
10064
10844
|
const selfCheck = setInterval(() => {
|
|
10065
10845
|
try {
|
|
10066
|
-
const holder = JSON.parse(
|
|
10846
|
+
const holder = JSON.parse(readFileSync17(path, "utf-8")).pid;
|
|
10067
10847
|
if (holder === process.pid)
|
|
10068
10848
|
return;
|
|
10069
10849
|
try {
|
|
@@ -10090,7 +10870,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
|
10090
10870
|
clearInterval(heartbeat);
|
|
10091
10871
|
clearInterval(selfCheck);
|
|
10092
10872
|
try {
|
|
10093
|
-
|
|
10873
|
+
unlinkSync8(path);
|
|
10094
10874
|
} catch {}
|
|
10095
10875
|
}
|
|
10096
10876
|
};
|
|
@@ -10134,7 +10914,7 @@ var DEFAULT_SUPERVISOR_POLICY = {
|
|
|
10134
10914
|
};
|
|
10135
10915
|
|
|
10136
10916
|
// src/core/send-requests.ts
|
|
10137
|
-
import { existsSync as
|
|
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";
|
|
10138
10918
|
import { join as join12 } from "node:path";
|
|
10139
10919
|
function sendRequestsDirFor(appId) {
|
|
10140
10920
|
return join12(storageRoot(appId), "send-requests");
|
|
@@ -10144,18 +10924,18 @@ function startSendRequestConsumer(opts) {
|
|
|
10144
10924
|
const intervalMs = opts.intervalMs ?? 1500;
|
|
10145
10925
|
const log = opts.log ?? (() => {});
|
|
10146
10926
|
const seen = new Map;
|
|
10147
|
-
|
|
10927
|
+
mkdirSync14(dir, { recursive: true });
|
|
10148
10928
|
for (const f of readdirSync3(dir)) {
|
|
10149
10929
|
if (!f.endsWith(".result.json"))
|
|
10150
10930
|
continue;
|
|
10151
10931
|
const full = join12(dir, f);
|
|
10152
10932
|
try {
|
|
10153
|
-
const result = JSON.parse(
|
|
10933
|
+
const result = JSON.parse(readFileSync18(full, "utf-8"));
|
|
10154
10934
|
const key = result.dedupeKey;
|
|
10155
10935
|
if (key)
|
|
10156
10936
|
seen.set(key, result);
|
|
10157
10937
|
if (Date.now() - statSync10(full).mtimeMs > 24 * 60 * 60000)
|
|
10158
|
-
|
|
10938
|
+
renameSync8(full, full + ".old");
|
|
10159
10939
|
} catch {}
|
|
10160
10940
|
}
|
|
10161
10941
|
const sendFile = opts.sendFile ?? ((ctx, path) => sendLocalFile(ctx, path, { getToken: opts.getToken }));
|
|
@@ -10163,9 +10943,9 @@ function startSendRequestConsumer(opts) {
|
|
|
10163
10943
|
const full = join12(dir, file);
|
|
10164
10944
|
let req;
|
|
10165
10945
|
try {
|
|
10166
|
-
req = JSON.parse(
|
|
10946
|
+
req = JSON.parse(readFileSync18(full, "utf-8"));
|
|
10167
10947
|
} catch {
|
|
10168
|
-
|
|
10948
|
+
renameSync8(full, full + ".bad.json");
|
|
10169
10949
|
log(`[send-requests] 坏请求已隔离: ${file}`);
|
|
10170
10950
|
return;
|
|
10171
10951
|
}
|
|
@@ -10185,9 +10965,9 @@ function startSendRequestConsumer(opts) {
|
|
|
10185
10965
|
seen.set(req.dedupeKey, { ...result, dedupeKey: req.dedupeKey });
|
|
10186
10966
|
}
|
|
10187
10967
|
const payload = JSON.stringify({ ...result, dedupeKey: req.dedupeKey });
|
|
10188
|
-
|
|
10189
|
-
|
|
10190
|
-
|
|
10968
|
+
writeFileSync15(join12(dir, `${req.id}.result.tmp`), payload, "utf-8");
|
|
10969
|
+
renameSync8(join12(dir, `${req.id}.result.tmp`), join12(dir, `${req.id}.result.json`));
|
|
10970
|
+
renameSync8(full, full + ".done");
|
|
10191
10971
|
log(`[send-requests] ${result.ok ? "已发送" : "发送失败"}${result.deduped ? "(去重)" : ""} user=${req.userId.slice(0, 8)}… path=${req.path}`);
|
|
10192
10972
|
}
|
|
10193
10973
|
const timer = setInterval(() => {
|
|
@@ -10212,6 +10992,33 @@ function isSessionBusyError(error) {
|
|
|
10212
10992
|
const message = error instanceof Error ? error.message : String(error);
|
|
10213
10993
|
return /active prompt|[-−]32603/.test(message);
|
|
10214
10994
|
}
|
|
10995
|
+
function isMirrorDigestText(text) {
|
|
10996
|
+
let value = text?.trim() ?? "";
|
|
10997
|
+
if (value.startsWith(UNDELIVERED_NOTICE.trim())) {
|
|
10998
|
+
value = value.slice(UNDELIVERED_NOTICE.trim().length).trimStart();
|
|
10999
|
+
}
|
|
11000
|
+
return value.startsWith("\uD83D\uDCCB 桌面问答摘要") || value.startsWith("\uD83C\uDFAF 目标续跑摘要") || value.startsWith("\uD83D\uDCCB 摘要续") || value.startsWith("\uD83C\uDFAF 摘要续");
|
|
11001
|
+
}
|
|
11002
|
+
function commandNeedsMirrorAnchorGate(content) {
|
|
11003
|
+
const match = content.trim().match(/^\/(queue|amend|goal|btw)\b([\s\S]*)$/i);
|
|
11004
|
+
if (!match)
|
|
11005
|
+
return false;
|
|
11006
|
+
const args = (match[2] ?? "").trim();
|
|
11007
|
+
if (!args)
|
|
11008
|
+
return false;
|
|
11009
|
+
if (match[1]?.toLowerCase() === "queue" && /^(?:all(?:\s+\d+)?|clear|drop\s+\d+|\d+)$/i.test(args)) {
|
|
11010
|
+
return false;
|
|
11011
|
+
}
|
|
11012
|
+
return true;
|
|
11013
|
+
}
|
|
11014
|
+
function decideMirrorAnchorGate(input) {
|
|
11015
|
+
if (input.anchor) {
|
|
11016
|
+
return input.currentSessionId && input.anchor.sessionId === input.currentSessionId ? { kind: "match", anchor: input.anchor } : { kind: "conflict", anchor: input.anchor };
|
|
11017
|
+
}
|
|
11018
|
+
if (isMirrorDigestText(input.quoteText))
|
|
11019
|
+
return { kind: "unknown" };
|
|
11020
|
+
return { kind: "pass" };
|
|
11021
|
+
}
|
|
10215
11022
|
function evictableIdleSessions(lastActivity, watched, now, idleMs) {
|
|
10216
11023
|
const out = [];
|
|
10217
11024
|
for (const [sid, at] of lastActivity) {
|
|
@@ -10385,6 +11192,7 @@ function finalAnswerText(msgs, promptId, baseline) {
|
|
|
10385
11192
|
function createBridge(config, client, sessions, storageAppId) {
|
|
10386
11193
|
const roleFile = (name) => storageFile(name, storageAppId);
|
|
10387
11194
|
const inflight = createInflightJournal(storageAppId ? roleFile("inflight.json") : undefined);
|
|
11195
|
+
const mirrorAnchors = createMirrorAnchorStore(roleFile("mirror-anchors.json"));
|
|
10388
11196
|
const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "");
|
|
10389
11197
|
const busyUsers = new Set;
|
|
10390
11198
|
const laneOf = (userId, sessionId) => laneKeyOf(userId, sessionId);
|
|
@@ -10732,7 +11540,7 @@ ${promptBody}` : promptBody) + qqPromptHints() + hint;
|
|
|
10732
11540
|
return sid ? `\uD83D\uDC41 观察中:${sid}` : "未开启观察";
|
|
10733
11541
|
}
|
|
10734
11542
|
};
|
|
10735
|
-
const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(config, lastCtx, isBoundSession, storageAppId ? roleFile("quota.json") : undefined);
|
|
11543
|
+
const { enqueuePush, safeDeliver, sendReply, deliver, consumePartialFailure } = createDelivery(config, lastCtx, isBoundSession, storageAppId ? roleFile("quota.json") : undefined);
|
|
10736
11544
|
const notifyUser = async (ctx, text) => {
|
|
10737
11545
|
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
10738
11546
|
console.log(`[push-gate] 通知拦截:绑定已切走 anchor=${ctx.anchorSessionId.slice(0, 12)}… chars=${text.length}`);
|
|
@@ -10744,6 +11552,37 @@ ${promptBody}` : promptBody) + qqPromptHints() + hint;
|
|
|
10744
11552
|
console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage2(error));
|
|
10745
11553
|
}
|
|
10746
11554
|
};
|
|
11555
|
+
const mirrorQuoteCache = new WeakMap;
|
|
11556
|
+
function quoteContextOf(ctx) {
|
|
11557
|
+
const cached = mirrorQuoteCache.get(ctx);
|
|
11558
|
+
if (cached)
|
|
11559
|
+
return cached;
|
|
11560
|
+
const embedded = extractEmbeddedQuote(ctx.rawEvent);
|
|
11561
|
+
const quoted = embedded ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null);
|
|
11562
|
+
const result = { embedded, quoted };
|
|
11563
|
+
mirrorQuoteCache.set(ctx, result);
|
|
11564
|
+
return result;
|
|
11565
|
+
}
|
|
11566
|
+
function mirrorAnchorDecision(ctx, currentSessionId) {
|
|
11567
|
+
const { quoted } = quoteContextOf(ctx);
|
|
11568
|
+
const anchor = mirrorAnchors.resolve(ctx.userId, ctx.referencedMsgId);
|
|
11569
|
+
return decideMirrorAnchorGate({ anchor, quoteText: quoted, currentSessionId });
|
|
11570
|
+
}
|
|
11571
|
+
function anchorRejectText(decision, currentSessionId, userId) {
|
|
11572
|
+
if (decision.kind === "unknown") {
|
|
11573
|
+
return "⚠️ 无法确认这条旧摘要所属会话,本次未发送。请去掉引用后重发,或先通过 /sessions 切换到摘要所属会话。";
|
|
11574
|
+
}
|
|
11575
|
+
const source = `${clipDigestTitle(redactSecrets(decision.anchor.title))}(${digestSessionLabel(decision.anchor.sessionId)})`;
|
|
11576
|
+
const current = sessions.getSession(userId);
|
|
11577
|
+
const currentLabel = currentSessionId ? `${clipDigestTitle(redactSecrets(current?.title ?? ""))}(${digestSessionLabel(currentSessionId)})` : "无绑定会话";
|
|
11578
|
+
return `⚠️ 这条回复引用的是 ${source} 的摘要,当前绑定为 ${currentLabel}。
|
|
11579
|
+
为避免误操作,本次未发送。请用 /sessions 切回该会话后重发;或去掉引用,明确发送到当前会话。`;
|
|
11580
|
+
}
|
|
11581
|
+
async function rejectMirrorAnchor(ctx, decision, currentSessionId) {
|
|
11582
|
+
const anchor = decision.kind === "conflict" ? decision.anchor.sessionId : "unknown";
|
|
11583
|
+
console.log(`[anchor-gate] result=${decision.kind} user=${ctx.userId.slice(0, 8)}… anchor=${anchor === "unknown" ? anchor : digestSessionLabel(anchor)} current=${currentSessionId ? digestSessionLabel(currentSessionId) : "∅"}`);
|
|
11584
|
+
await notifyUser({ ...ctx, anchorSessionId: undefined }, anchorRejectText(decision, currentSessionId, ctx.userId));
|
|
11585
|
+
}
|
|
10747
11586
|
const cronScheduler = new ReminderScheduler;
|
|
10748
11587
|
const goalStates = new Map;
|
|
10749
11588
|
const goalKickoffs = new Map;
|
|
@@ -10792,7 +11631,7 @@ ${parsed.message.slice(0, 400)}
|
|
|
10792
11631
|
for (const lk of msgQueue.laneKeysOf(userId))
|
|
10793
11632
|
drainQueue(userId, sessionIdOfLane(lk));
|
|
10794
11633
|
},
|
|
10795
|
-
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),
|
|
10796
11635
|
persistFile: storageAppId ? roleFile("pending-permissions.json") : undefined
|
|
10797
11636
|
});
|
|
10798
11637
|
const mirror = createMirror({
|
|
@@ -10804,6 +11643,7 @@ ${parsed.message.slice(0, 400)}
|
|
|
10804
11643
|
bgWaits,
|
|
10805
11644
|
busyUsers,
|
|
10806
11645
|
settingsFile: storageAppId ? roleFile("settings.json") : undefined,
|
|
11646
|
+
anchorStore: mirrorAnchors,
|
|
10807
11647
|
onDigest: (userId, digest) => {
|
|
10808
11648
|
const hit = parseCronReminder(digest, Date.now());
|
|
10809
11649
|
if (!hit)
|
|
@@ -10911,7 +11751,8 @@ ${parsed.message.slice(0, 400)}
|
|
|
10911
11751
|
console.log(`[push-gate] 审批卡拦截(轮询兜底):绑定已切走 uid=${uid.slice(0, 8)}… sid=${shortId(req.sessionID)}`);
|
|
10912
11752
|
continue;
|
|
10913
11753
|
}
|
|
10914
|
-
perm.
|
|
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));
|
|
10915
11756
|
}
|
|
10916
11757
|
}
|
|
10917
11758
|
}
|
|
@@ -10966,6 +11807,10 @@ ${parsed.message.slice(0, 400)}
|
|
|
10966
11807
|
}
|
|
10967
11808
|
});
|
|
10968
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
|
+
}
|
|
10969
11814
|
const bound = sessions.getSession(uid);
|
|
10970
11815
|
try {
|
|
10971
11816
|
const res = await client.permission.list({ directory: bound?.directory });
|
|
@@ -11475,6 +12320,7 @@ ${parsed.message}`;
|
|
|
11475
12320
|
perm.restore();
|
|
11476
12321
|
mirror.ensureSubs();
|
|
11477
12322
|
purgeOldQQImages();
|
|
12323
|
+
purgeOldQQFiles();
|
|
11478
12324
|
const handleMessage = async (ctx) => {
|
|
11479
12325
|
let claimedMsgId = "";
|
|
11480
12326
|
const intentKey = intentKeyOf(ctx);
|
|
@@ -11486,6 +12332,12 @@ ${parsed.message}`;
|
|
|
11486
12332
|
inflight.settle(ctx.msgId, undefined, reason);
|
|
11487
12333
|
console.log(`[queue] release-early msg=${shortId(ctx.msgId)} reason=${reason}${note ? ` note=${note}` : ""}`);
|
|
11488
12334
|
};
|
|
12335
|
+
const releaseAnchorClaim = (note) => {
|
|
12336
|
+
if (ctx.msgId && claimedContexts.has(ctx)) {
|
|
12337
|
+
inflight.markStage(ctx.msgId, "claimed", { lastError: note }, { force: true });
|
|
12338
|
+
}
|
|
12339
|
+
releaseClaimed("blocked", note);
|
|
12340
|
+
};
|
|
11489
12341
|
try {
|
|
11490
12342
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
11491
12343
|
console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`);
|
|
@@ -11517,6 +12369,14 @@ ${parsed.message}`;
|
|
|
11517
12369
|
const gateContent = normalizeForCommandGate(content);
|
|
11518
12370
|
if (isCommand(gateContent)) {
|
|
11519
12371
|
const gateCtx = gateContent === content ? ctx : { ...ctx, content: gateContent };
|
|
12372
|
+
if (commandNeedsMirrorAnchorGate(gateContent)) {
|
|
12373
|
+
const decision = mirrorAnchorDecision(gateCtx, anchorSid);
|
|
12374
|
+
if (decision.kind === "conflict" || decision.kind === "unknown") {
|
|
12375
|
+
releaseAnchorClaim(decision.kind === "conflict" ? "anchor-conflict" : "anchor-unknown");
|
|
12376
|
+
await rejectMirrorAnchor(ctx, decision, anchorSid);
|
|
12377
|
+
return;
|
|
12378
|
+
}
|
|
12379
|
+
}
|
|
11520
12380
|
const reply = await handleCommand(gateCtx, commandContext);
|
|
11521
12381
|
await notifyUser(ctx, reply);
|
|
11522
12382
|
releaseClaimed("dropped");
|
|
@@ -11555,6 +12415,12 @@ ${parsed.message}`;
|
|
|
11555
12415
|
}
|
|
11556
12416
|
claimedMsgId = ctx.msgId;
|
|
11557
12417
|
}
|
|
12418
|
+
const mirrorGate = mirrorAnchorDecision(ctx, anchorSid);
|
|
12419
|
+
if (mirrorGate.kind === "conflict" || mirrorGate.kind === "unknown") {
|
|
12420
|
+
releaseAnchorClaim(mirrorGate.kind === "conflict" ? "anchor-conflict" : "anchor-unknown");
|
|
12421
|
+
await rejectMirrorAnchor(ctx, mirrorGate, anchorSid);
|
|
12422
|
+
return;
|
|
12423
|
+
}
|
|
11558
12424
|
if (busyUsers.has(lane) && !claimedContexts.has(ctx)) {
|
|
11559
12425
|
const duplicateIntent = activeIntents.get(lane) === intentKey || msgQueue.hasIntent(lane, intentKey);
|
|
11560
12426
|
if (duplicateIntent) {
|
|
@@ -11629,8 +12495,7 @@ ${parsed.message}`;
|
|
|
11629
12495
|
return;
|
|
11630
12496
|
}))?.data?.location?.directory ?? anchorDirectory;
|
|
11631
12497
|
}
|
|
11632
|
-
const
|
|
11633
|
-
const quoted = embeddedQuote ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null);
|
|
12498
|
+
const { quoted } = quoteContextOf(ctx);
|
|
11634
12499
|
if (quoted)
|
|
11635
12500
|
ctx.quoteText = quoted;
|
|
11636
12501
|
recordMessage(scopeKeyOf(ctx), ctx.msgId, ctx.content);
|
|
@@ -11711,6 +12576,9 @@ ${promptBody}` : promptBody) + qqPromptHints();
|
|
|
11711
12576
|
if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
|
|
11712
12577
|
console.log(`[push-gate] 回合结果按历史可回读结清 answered msg=${shortId(trackId)}`);
|
|
11713
12578
|
inflight.settle(trackId, undefined, "answered");
|
|
12579
|
+
} else if (consumePartialFailure(ctx)) {
|
|
12580
|
+
inflight.settle(trackId, undefined, "error");
|
|
12581
|
+
console.log(`[journal] 分片部分失败结清 error msg=${shortId(trackId)}`);
|
|
11714
12582
|
} else {
|
|
11715
12583
|
await safeDeliver(ctx, "⚠️ 本轮结果与 24h 内已发送内容重复,已被防重拦截(未重复投递)。如非预期请重发或换个说法");
|
|
11716
12584
|
inflight.settle(trackId, undefined, "error");
|
|
@@ -11982,8 +12850,8 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
11982
12850
|
var WATCH_FILE = storageFile("watch.json");
|
|
11983
12851
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
11984
12852
|
try {
|
|
11985
|
-
if (
|
|
11986
|
-
const raw =
|
|
12853
|
+
if (existsSync16(file)) {
|
|
12854
|
+
const raw = readFileSync19(file, "utf-8");
|
|
11987
12855
|
const obj = JSON.parse(raw);
|
|
11988
12856
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
11989
12857
|
const out = {};
|
|
@@ -11998,7 +12866,7 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
11998
12866
|
}
|
|
11999
12867
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
12000
12868
|
try {
|
|
12001
|
-
|
|
12869
|
+
writeFileSync16(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
12002
12870
|
} catch (error) {
|
|
12003
12871
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
12004
12872
|
}
|
|
@@ -12006,8 +12874,8 @@ function saveWatchedMap(m, file = WATCH_FILE) {
|
|
|
12006
12874
|
var GREETED_FILE = storageFile("greeted.json");
|
|
12007
12875
|
function loadGreetedSet(file = GREETED_FILE) {
|
|
12008
12876
|
try {
|
|
12009
|
-
if (
|
|
12010
|
-
const raw =
|
|
12877
|
+
if (existsSync16(file)) {
|
|
12878
|
+
const raw = readFileSync19(file, "utf-8");
|
|
12011
12879
|
const arr = JSON.parse(raw);
|
|
12012
12880
|
if (Array.isArray(arr)) {
|
|
12013
12881
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -12018,8 +12886,8 @@ function loadGreetedSet(file = GREETED_FILE) {
|
|
|
12018
12886
|
}
|
|
12019
12887
|
function saveGreetedSet(set, file = GREETED_FILE) {
|
|
12020
12888
|
try {
|
|
12021
|
-
|
|
12022
|
-
|
|
12889
|
+
mkdirSync15(join13(homedir7(), ".openqq"), { recursive: true });
|
|
12890
|
+
writeFileSync16(file, JSON.stringify([...set]));
|
|
12023
12891
|
} catch (error) {
|
|
12024
12892
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
12025
12893
|
}
|
|
@@ -12153,8 +13021,8 @@ async function main() {
|
|
|
12153
13021
|
const heartbeatFile = join14(homedir8(), ".openqq", "heartbeat");
|
|
12154
13022
|
const touchHeartbeat = () => {
|
|
12155
13023
|
try {
|
|
12156
|
-
|
|
12157
|
-
|
|
13024
|
+
mkdirSync16(join14(homedir8(), ".openqq"), { recursive: true });
|
|
13025
|
+
writeFileSync17(heartbeatFile, String(Date.now()));
|
|
12158
13026
|
} catch (error) {
|
|
12159
13027
|
console.error("[index] 心跳写入失败:", error);
|
|
12160
13028
|
}
|