@linjz/opencode-qqbot 0.3.5 → 0.3.7
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/README.md +74 -39
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +10 -1
- package/dist/openqq-bot.js +365 -70
- package/package.json +69 -61
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +936 -796
- package/src/commands.ts +554 -514
- package/src/config.ts +121 -121
- package/src/core/bot-launcher.ts +146 -134
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +284 -284
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -0
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +304 -304
- package/src/core/inflight-journal.ts +217 -151
- package/src/core/instance-lock.ts +122 -122
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +80 -0
- package/src/core/mirror.ts +173 -173
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +387 -386
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +65 -65
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +539 -539
- package/src/qq/gateway.ts +492 -492
- package/src/qq/media.ts +219 -204
- package/src/qq/sender.ts +300 -300
- package/src/qq/types.ts +154 -152
- package/tsconfig.json +24 -24
package/dist/openqq-bot.js
CHANGED
|
@@ -2939,7 +2939,7 @@ var require_websocket_server = __commonJS(function(exports, module) {
|
|
|
2939
2939
|
});
|
|
2940
2940
|
|
|
2941
2941
|
// src/core/file-log.ts
|
|
2942
|
-
import { appendFileSync, existsSync as existsSync9, mkdirSync as mkdirSync9, renameSync as renameSync2, statSync as
|
|
2942
|
+
import { appendFileSync, existsSync as existsSync9, mkdirSync as mkdirSync9, renameSync as renameSync2, statSync as statSync5 } from "fs";
|
|
2943
2943
|
import { join as join12 } from "path";
|
|
2944
2944
|
function installFileLog(logPath) {
|
|
2945
2945
|
try {
|
|
@@ -2947,12 +2947,12 @@ function installFileLog(logPath) {
|
|
|
2947
2947
|
} catch {}
|
|
2948
2948
|
const write = (level, args) => {
|
|
2949
2949
|
try {
|
|
2950
|
-
if (existsSync9(logPath) &&
|
|
2950
|
+
if (existsSync9(logPath) && statSync5(logPath).size > ROTATE_BYTES) {
|
|
2951
2951
|
renameSync2(logPath, `${logPath}.1`);
|
|
2952
2952
|
}
|
|
2953
2953
|
const line = args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
|
|
2954
2954
|
appendFileSync(logPath, `${new Date().toISOString()} [${level}] ${line}
|
|
2955
|
-
|
|
2955
|
+
`, { mode: 384 });
|
|
2956
2956
|
} catch {}
|
|
2957
2957
|
};
|
|
2958
2958
|
const orig = {
|
|
@@ -3028,7 +3028,7 @@ async function ensureConfig() {
|
|
|
3028
3028
|
if (!appId || !appSecret) {
|
|
3029
3029
|
throw new Error("App ID 和 App Secret 不能为空");
|
|
3030
3030
|
}
|
|
3031
|
-
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
3031
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
|
|
3032
3032
|
const envContent = [
|
|
3033
3033
|
`QQ_APP_ID=${appId}`,
|
|
3034
3034
|
`QQ_APP_SECRET=${appSecret}`,
|
|
@@ -3039,7 +3039,7 @@ async function ensureConfig() {
|
|
|
3039
3039
|
].join(`
|
|
3040
3040
|
`) + `
|
|
3041
3041
|
`;
|
|
3042
|
-
writeFileSync(ENV_FILE, envContent);
|
|
3042
|
+
writeFileSync(ENV_FILE, envContent, { mode: 384 });
|
|
3043
3043
|
console.log(`
|
|
3044
3044
|
配置已保存到 ${ENV_FILE}`);
|
|
3045
3045
|
process.env.QQ_APP_ID = appId;
|
|
@@ -3121,7 +3121,8 @@ function createClient(baseUrl) {
|
|
|
3121
3121
|
async function json(res) {
|
|
3122
3122
|
if (!res.ok) {
|
|
3123
3123
|
const txt = await res.text().catch(() => "");
|
|
3124
|
-
|
|
3124
|
+
const excerpt = txt.length > 200 ? `${txt.substring(0, 200)}…` : txt;
|
|
3125
|
+
throw new Error(`OpenCode API ${res.status}: ${excerpt}`);
|
|
3125
3126
|
}
|
|
3126
3127
|
if (res.status === 204)
|
|
3127
3128
|
return null;
|
|
@@ -3469,7 +3470,7 @@ function startLinkWatch(deps) {
|
|
|
3469
3470
|
inc.lastCheck = nowIso();
|
|
3470
3471
|
if (!alarmOpenSent) {
|
|
3471
3472
|
alarmOpenSent = true;
|
|
3472
|
-
await fire(`⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.slice(0, 80)})。已转入自动自愈:发现新端口会自动切换并通知。`);
|
|
3473
|
+
await fire(`⚠️ OpenCode 链路失联(自 ${inc.since.slice(11, 16)} 起,错误:${msg.length > 80 ? `${msg.slice(0, 80)}…` : msg})。已转入自动自愈:发现新端口会自动切换并通知。`);
|
|
3473
3474
|
}
|
|
3474
3475
|
const found = await discover(password);
|
|
3475
3476
|
if (found && found.baseUrl !== deps.client.baseUrl) {
|
|
@@ -4327,12 +4328,12 @@ async function startGateway(options) {
|
|
|
4327
4328
|
}
|
|
4328
4329
|
|
|
4329
4330
|
// src/bridge.ts
|
|
4330
|
-
import { existsSync as existsSync8, readFileSync as
|
|
4331
|
+
import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "fs";
|
|
4331
4332
|
import { join as join10 } from "path";
|
|
4332
4333
|
import { homedir as homedir9 } from "os";
|
|
4333
4334
|
|
|
4334
4335
|
// src/qq/media.ts
|
|
4335
|
-
import { mkdirSync as mkdirSync4, readdirSync, statSync, unlinkSync, writeFileSync as writeFileSync5 } from "node:fs";
|
|
4336
|
+
import { mkdirSync as mkdirSync4, readdirSync, statSync, unlinkSync, writeFileSync as writeFileSync5, readFileSync as readFileSync4 } from "node:fs";
|
|
4336
4337
|
import { join as join5 } from "node:path";
|
|
4337
4338
|
import { tmpdir } from "node:os";
|
|
4338
4339
|
function extForImageMime(mime) {
|
|
@@ -4439,7 +4440,8 @@ function groupOutcomes(outcomes) {
|
|
|
4439
4440
|
const notes = [];
|
|
4440
4441
|
for (const o of outcomes) {
|
|
4441
4442
|
if ("path" in o) {
|
|
4442
|
-
|
|
4443
|
+
const dataUrl = tryImageDataUrl(o.path, 2 * 1024 * 1024);
|
|
4444
|
+
files.push(dataUrl ? { uri: dataUrl, name: o.name } : { uri: `file:///${o.path.replace(/\\/g, "/")}`, name: o.name });
|
|
4443
4445
|
} else if ("voice" in o) {
|
|
4444
4446
|
notes.push(`(语音转写:${o.voice})`);
|
|
4445
4447
|
} else if ("failed" in o) {
|
|
@@ -4450,6 +4452,17 @@ function groupOutcomes(outcomes) {
|
|
|
4450
4452
|
}
|
|
4451
4453
|
return { files, notes };
|
|
4452
4454
|
}
|
|
4455
|
+
function tryImageDataUrl(path, maxBytes) {
|
|
4456
|
+
try {
|
|
4457
|
+
const st = statSync(path);
|
|
4458
|
+
if (st.size > maxBytes)
|
|
4459
|
+
return null;
|
|
4460
|
+
const b = readFileSync4(path);
|
|
4461
|
+
return `data:image/png;base64,${b.toString("base64")}`;
|
|
4462
|
+
} catch {
|
|
4463
|
+
return null;
|
|
4464
|
+
}
|
|
4465
|
+
}
|
|
4453
4466
|
function augmentPromptWithAttachments(rawContent, prepared) {
|
|
4454
4467
|
const base = rawContent.trim();
|
|
4455
4468
|
const { files, notes } = prepared;
|
|
@@ -4712,8 +4725,8 @@ function clip(value, max) {
|
|
|
4712
4725
|
}
|
|
4713
4726
|
|
|
4714
4727
|
// src/core/send-media.ts
|
|
4715
|
-
import { readFileSync as
|
|
4716
|
-
import { resolve, extname, basename } from "node:path";
|
|
4728
|
+
import { readFileSync as readFileSync5, statSync as statSync2 } from "node:fs";
|
|
4729
|
+
import { resolve, extname, basename, sep } from "node:path";
|
|
4717
4730
|
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
4718
4731
|
function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
|
|
4719
4732
|
const roots = [imageDir(), process.cwd()];
|
|
@@ -4725,7 +4738,7 @@ function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
|
|
|
4725
4738
|
}
|
|
4726
4739
|
function isAllowedSendPath(filePath, roots = allowedSendRoots()) {
|
|
4727
4740
|
const full = resolve(filePath.trim().replace(/^"|"$/g, ""));
|
|
4728
|
-
return roots.some((root) => full === root || full.startsWith(root +
|
|
4741
|
+
return roots.some((root) => full === root || full.startsWith(root + sep));
|
|
4729
4742
|
}
|
|
4730
4743
|
function fileTypeForPath(filePath) {
|
|
4731
4744
|
const ext = extname(filePath).toLowerCase();
|
|
@@ -4777,7 +4790,7 @@ async function sendLocalFile(ctx, filePath, deps) {
|
|
|
4777
4790
|
const name = basename(trimmed);
|
|
4778
4791
|
const uploaded = await uploadQQMedia(token, ctx, {
|
|
4779
4792
|
fileType,
|
|
4780
|
-
fileData:
|
|
4793
|
+
fileData: readFileSync5(trimmed).toString("base64"),
|
|
4781
4794
|
fileName: fileType === MediaFileType.FILE ? name : undefined
|
|
4782
4795
|
});
|
|
4783
4796
|
await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
|
|
@@ -4799,7 +4812,12 @@ async function handleCommand(ctx, cmdCtx) {
|
|
|
4799
4812
|
case "new":
|
|
4800
4813
|
return handleNew(ctx, cmdCtx);
|
|
4801
4814
|
case "stop":
|
|
4815
|
+
case "cancel":
|
|
4802
4816
|
return handleStop(ctx, cmdCtx);
|
|
4817
|
+
case "queue":
|
|
4818
|
+
return handleQueue(ctx, parsed.args, cmdCtx);
|
|
4819
|
+
case "progress":
|
|
4820
|
+
return cmdCtx.progress.query(ctx.userId);
|
|
4803
4821
|
case "status":
|
|
4804
4822
|
return handleStatus(ctx, cmdCtx);
|
|
4805
4823
|
case "sessions":
|
|
@@ -4889,11 +4907,27 @@ async function handleSend(ctx, args, cmdCtx) {
|
|
|
4889
4907
|
}
|
|
4890
4908
|
async function handleStop(ctx, cmdCtx) {
|
|
4891
4909
|
const session = cmdCtx.sessions.getSession(ctx.userId);
|
|
4910
|
+
const cleared = cmdCtx.queue.clear(ctx.userId);
|
|
4911
|
+
const suffix = cleared > 0 ? `,队列中的 ${cleared} 条已清空` : "";
|
|
4892
4912
|
if (!session) {
|
|
4893
|
-
return "当前还没有会话可停止";
|
|
4913
|
+
return cleared > 0 ? `当前没有会话可停止${suffix}` : "当前还没有会话可停止";
|
|
4894
4914
|
}
|
|
4895
4915
|
await cmdCtx.client.session.abort({ path: { id: session.sessionId } });
|
|
4896
|
-
return `已发送停止请求:${session.title ?? session.sessionId}`;
|
|
4916
|
+
return `已发送停止请求:${session.title ?? session.sessionId}${suffix}`;
|
|
4917
|
+
}
|
|
4918
|
+
function handleQueue(ctx, args, cmdCtx) {
|
|
4919
|
+
const sub = args.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
4920
|
+
if (sub === "clear") {
|
|
4921
|
+
const n = cmdCtx.queue.clear(ctx.userId);
|
|
4922
|
+
return n > 0 ? `已清空队列(${n} 条)` : "队列本来就是空的";
|
|
4923
|
+
}
|
|
4924
|
+
if (sub === "drop") {
|
|
4925
|
+
const id = Number(args.trim().split(/\s+/)[1]);
|
|
4926
|
+
if (!Number.isInteger(id) || id <= 0)
|
|
4927
|
+
return "用法:/queue drop <编号>";
|
|
4928
|
+
return cmdCtx.queue.drop(ctx.userId, id);
|
|
4929
|
+
}
|
|
4930
|
+
return cmdCtx.queue.list(ctx.userId);
|
|
4897
4931
|
}
|
|
4898
4932
|
async function handleStatus(ctx, cmdCtx) {
|
|
4899
4933
|
const session = cmdCtx.sessions.getSession(ctx.userId);
|
|
@@ -5140,6 +5174,9 @@ function buildHelpText() {
|
|
|
5140
5174
|
"/watch - 观察当前会话实时过程(工具调用/完成会推送摘要)",
|
|
5141
5175
|
"/watch <会话ID> - 观察指定会话",
|
|
5142
5176
|
"/watch off - 停止观察",
|
|
5177
|
+
"/progress - 手动进度查询(工具调用/失败统计、在途状态,本地事件源零模型调用)",
|
|
5178
|
+
"/queue - 忙碌队列查看;/queue clear 清空;/queue drop <编号> 定点删除",
|
|
5179
|
+
"/cancel - 同 /stop:中止当前 AI 运行并清空忙碌队列",
|
|
5143
5180
|
"/mirror [on|off] - 桌面问答摘要镜像开关(会话轮次完成推送问答摘要)",
|
|
5144
5181
|
"",
|
|
5145
5182
|
"权限审批(AI 请求权限时):",
|
|
@@ -5175,7 +5212,7 @@ function toErrorMessage(error) {
|
|
|
5175
5212
|
}
|
|
5176
5213
|
|
|
5177
5214
|
// src/core/mirror.ts
|
|
5178
|
-
import { existsSync as existsSync4, readFileSync as
|
|
5215
|
+
import { existsSync as existsSync4, readFileSync as readFileSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
|
|
5179
5216
|
import { join as join6 } from "path";
|
|
5180
5217
|
import { homedir as homedir5 } from "os";
|
|
5181
5218
|
|
|
@@ -5235,7 +5272,7 @@ var MIRROR_SETTINGS_FILE = join6(homedir5(), ".openqq", "settings.json");
|
|
|
5235
5272
|
function loadMirrorEnabled() {
|
|
5236
5273
|
try {
|
|
5237
5274
|
if (existsSync4(MIRROR_SETTINGS_FILE)) {
|
|
5238
|
-
const raw =
|
|
5275
|
+
const raw = readFileSync6(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
|
|
5239
5276
|
const parsed = JSON.parse(raw);
|
|
5240
5277
|
if (typeof parsed?.mirror === "boolean")
|
|
5241
5278
|
return parsed.mirror;
|
|
@@ -5249,7 +5286,7 @@ function saveMirrorEnabled(enabled) {
|
|
|
5249
5286
|
let existing = {};
|
|
5250
5287
|
if (existsSync4(MIRROR_SETTINGS_FILE)) {
|
|
5251
5288
|
try {
|
|
5252
|
-
const raw =
|
|
5289
|
+
const raw = readFileSync6(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
|
|
5253
5290
|
const parsed = JSON.parse(raw);
|
|
5254
5291
|
if (parsed && typeof parsed === "object")
|
|
5255
5292
|
existing = parsed;
|
|
@@ -5352,8 +5389,98 @@ function createMirror(deps) {
|
|
|
5352
5389
|
};
|
|
5353
5390
|
}
|
|
5354
5391
|
|
|
5392
|
+
// src/core/message-queue.ts
|
|
5393
|
+
var PREVIEW_MAX = 48;
|
|
5394
|
+
function previewText(text, max = PREVIEW_MAX) {
|
|
5395
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
5396
|
+
return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)";
|
|
5397
|
+
}
|
|
5398
|
+
function agoLabel(at, now = Date.now()) {
|
|
5399
|
+
const seconds = Math.max(0, Math.round((now - at) / 1000));
|
|
5400
|
+
if (seconds < 60)
|
|
5401
|
+
return `${seconds}s 前`;
|
|
5402
|
+
const minutes = Math.floor(seconds / 60);
|
|
5403
|
+
if (minutes < 60)
|
|
5404
|
+
return `${minutes}m 前`;
|
|
5405
|
+
return `${Math.floor(minutes / 60)}h 前`;
|
|
5406
|
+
}
|
|
5407
|
+
|
|
5408
|
+
class MessageQueue {
|
|
5409
|
+
limit;
|
|
5410
|
+
jobs = new Map;
|
|
5411
|
+
nextId = 1;
|
|
5412
|
+
constructor(limit = 20) {
|
|
5413
|
+
this.limit = limit;
|
|
5414
|
+
}
|
|
5415
|
+
push(userId, ctx) {
|
|
5416
|
+
const list = this.jobs.get(userId) ?? [];
|
|
5417
|
+
if (list.length >= this.limit)
|
|
5418
|
+
return null;
|
|
5419
|
+
const job = { id: this.nextId++, userId, ctx, text: ctx.content, enqueuedAt: Date.now() };
|
|
5420
|
+
list.push(job);
|
|
5421
|
+
this.jobs.set(userId, list);
|
|
5422
|
+
return { job, ahead: list.length - 1 };
|
|
5423
|
+
}
|
|
5424
|
+
shift(userId) {
|
|
5425
|
+
const list = this.jobs.get(userId);
|
|
5426
|
+
const job = list?.shift();
|
|
5427
|
+
if (list && list.length === 0)
|
|
5428
|
+
this.jobs.delete(userId);
|
|
5429
|
+
return job;
|
|
5430
|
+
}
|
|
5431
|
+
list(userId) {
|
|
5432
|
+
return this.jobs.get(userId) ?? [];
|
|
5433
|
+
}
|
|
5434
|
+
drop(userId, id) {
|
|
5435
|
+
const list = this.jobs.get(userId);
|
|
5436
|
+
if (!list)
|
|
5437
|
+
return false;
|
|
5438
|
+
const idx = list.findIndex((j) => j.id === id);
|
|
5439
|
+
if (idx < 0)
|
|
5440
|
+
return false;
|
|
5441
|
+
list.splice(idx, 1);
|
|
5442
|
+
if (list.length === 0)
|
|
5443
|
+
this.jobs.delete(userId);
|
|
5444
|
+
return true;
|
|
5445
|
+
}
|
|
5446
|
+
clear(userId) {
|
|
5447
|
+
const n = this.jobs.get(userId)?.length ?? 0;
|
|
5448
|
+
this.jobs.delete(userId);
|
|
5449
|
+
return n;
|
|
5450
|
+
}
|
|
5451
|
+
size(userId) {
|
|
5452
|
+
return this.jobs.get(userId)?.length ?? 0;
|
|
5453
|
+
}
|
|
5454
|
+
}
|
|
5455
|
+
|
|
5456
|
+
// src/core/error-rescue.ts
|
|
5457
|
+
function classifyProviderError(message) {
|
|
5458
|
+
const m = message.toLowerCase();
|
|
5459
|
+
if (/\b402\b|insufficient|balance|余额|额度不足|quota exceeded|credit/i.test(m))
|
|
5460
|
+
return "billing";
|
|
5461
|
+
if (/\b401\b|unauthorized|invalid.{0,20}(key|token)|鉴权|密钥错误|api.?key/i.test(m))
|
|
5462
|
+
return "auth";
|
|
5463
|
+
return null;
|
|
5464
|
+
}
|
|
5465
|
+
function rescueText(kind, rawMessage) {
|
|
5466
|
+
if (!kind)
|
|
5467
|
+
return null;
|
|
5468
|
+
const clipped = rawMessage.replace(/\s+/g, " ").trim();
|
|
5469
|
+
const raw = clipped.length > 200 ? `${clipped.slice(0, 200)}…` : clipped;
|
|
5470
|
+
const head = kind === "billing" ? "❌ 当前模型的余额/额度不足,暂时无法继续对话" : "❌ 当前模型的鉴权信息失效(401/key 无效)";
|
|
5471
|
+
return [
|
|
5472
|
+
head,
|
|
5473
|
+
`服务端原文:${raw}`,
|
|
5474
|
+
"",
|
|
5475
|
+
"恢复方式(都不用等模型在线)——",
|
|
5476
|
+
"1. 换现成模型:发 /model 看列表,或 /model provider/id 直接切换",
|
|
5477
|
+
"2. 更新 key:在桌面端 opencode 里更新该服务的 key 后,直接重发你的问题"
|
|
5478
|
+
].join(`
|
|
5479
|
+
`);
|
|
5480
|
+
}
|
|
5481
|
+
|
|
5355
5482
|
// src/core/permission.ts
|
|
5356
|
-
import { existsSync as existsSync5, readFileSync as
|
|
5483
|
+
import { existsSync as existsSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync7 } from "fs";
|
|
5357
5484
|
import { join as join7 } from "path";
|
|
5358
5485
|
import { homedir as homedir6 } from "os";
|
|
5359
5486
|
|
|
@@ -5374,7 +5501,7 @@ var PENDING_PERM_FILE = join7(homedir6(), ".openqq", "pending-permissions.json")
|
|
|
5374
5501
|
function loadPendingPermMap() {
|
|
5375
5502
|
try {
|
|
5376
5503
|
if (existsSync5(PENDING_PERM_FILE)) {
|
|
5377
|
-
const raw =
|
|
5504
|
+
const raw = readFileSync7(PENDING_PERM_FILE, "utf-8");
|
|
5378
5505
|
const obj = JSON.parse(raw);
|
|
5379
5506
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
5380
5507
|
const out = {};
|
|
@@ -5563,7 +5690,7 @@ function formatPermissionPrompt(request, mainSessionId) {
|
|
|
5563
5690
|
}
|
|
5564
5691
|
|
|
5565
5692
|
// src/core/delivery.ts
|
|
5566
|
-
import { existsSync as existsSync6, readFileSync as
|
|
5693
|
+
import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "fs";
|
|
5567
5694
|
import { join as join8 } from "path";
|
|
5568
5695
|
import { homedir as homedir7 } from "os";
|
|
5569
5696
|
|
|
@@ -5899,8 +6026,8 @@ function extractEmbeddedQuote(event) {
|
|
|
5899
6026
|
};
|
|
5900
6027
|
walk(event.msg_elements, 0);
|
|
5901
6028
|
const text = out.join(`
|
|
5902
|
-
`).trim()
|
|
5903
|
-
return text || null;
|
|
6029
|
+
`).trim();
|
|
6030
|
+
return (text.length > 2000 ? `${text.slice(0, 2000)}…` : text) || null;
|
|
5904
6031
|
}
|
|
5905
6032
|
|
|
5906
6033
|
// src/core/delivery.ts
|
|
@@ -5908,7 +6035,7 @@ var QUOTA_FILE = join8(homedir7(), ".openqq", "quota.json");
|
|
|
5908
6035
|
function loadQuotaMap() {
|
|
5909
6036
|
try {
|
|
5910
6037
|
if (existsSync6(QUOTA_FILE)) {
|
|
5911
|
-
const raw =
|
|
6038
|
+
const raw = readFileSync8(QUOTA_FILE, "utf-8");
|
|
5912
6039
|
const obj = JSON.parse(raw);
|
|
5913
6040
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
5914
6041
|
const out = {};
|
|
@@ -6352,7 +6479,7 @@ function createFormBridge(deps) {
|
|
|
6352
6479
|
if (msg.includes("AlreadySettled") || msg.includes("already")) {
|
|
6353
6480
|
deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {});
|
|
6354
6481
|
} else {
|
|
6355
|
-
deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.slice(0, 120)}`).catch(() => {});
|
|
6482
|
+
deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`).catch(() => {});
|
|
6356
6483
|
}
|
|
6357
6484
|
}
|
|
6358
6485
|
})();
|
|
@@ -6419,7 +6546,7 @@ function createFormBridge(deps) {
|
|
|
6419
6546
|
}
|
|
6420
6547
|
|
|
6421
6548
|
// src/core/inflight-journal.ts
|
|
6422
|
-
import { existsSync as existsSync7, readFileSync as
|
|
6549
|
+
import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync9, mkdirSync as mkdirSync6, renameSync, openSync, closeSync, unlinkSync as unlinkSync2, statSync as statSync3 } from "fs";
|
|
6423
6550
|
import { join as join9 } from "path";
|
|
6424
6551
|
import { homedir as homedir8 } from "os";
|
|
6425
6552
|
var INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
@@ -6430,50 +6557,104 @@ function redispatchMaxAgeMs() {
|
|
|
6430
6557
|
function journalPath() {
|
|
6431
6558
|
return process.env.QQ_INFLIGHT_FILE || join9(homedir8(), ".openqq", "inflight.json");
|
|
6432
6559
|
}
|
|
6433
|
-
var cache = null;
|
|
6434
6560
|
function load() {
|
|
6435
|
-
if (cache)
|
|
6436
|
-
return cache;
|
|
6437
6561
|
let entries = [];
|
|
6438
6562
|
try {
|
|
6439
6563
|
if (existsSync7(journalPath())) {
|
|
6440
|
-
const raw = JSON.parse(
|
|
6564
|
+
const raw = JSON.parse(readFileSync9(journalPath(), "utf-8"));
|
|
6441
6565
|
if (Array.isArray(raw))
|
|
6442
6566
|
entries = raw;
|
|
6443
6567
|
}
|
|
6444
6568
|
} catch {
|
|
6445
6569
|
entries = [];
|
|
6446
6570
|
}
|
|
6447
|
-
|
|
6448
|
-
cache = pruned;
|
|
6449
|
-
if (pruned.length !== entries.length)
|
|
6450
|
-
save();
|
|
6451
|
-
return cache;
|
|
6571
|
+
return entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS);
|
|
6452
6572
|
}
|
|
6453
|
-
function save() {
|
|
6454
|
-
|
|
6455
|
-
|
|
6573
|
+
function save(entries) {
|
|
6574
|
+
const path = journalPath();
|
|
6575
|
+
mkdirSync6(join9(path, ".."), { recursive: true });
|
|
6576
|
+
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6456
6577
|
try {
|
|
6457
|
-
|
|
6458
|
-
mkdirSync6(join9(path, ".."), { recursive: true });
|
|
6459
|
-
const tmp = `${path}.tmp`;
|
|
6460
|
-
writeFileSync9(tmp, JSON.stringify(cache, null, 2));
|
|
6578
|
+
writeFileSync9(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
|
|
6461
6579
|
renameSync(tmp, path);
|
|
6462
6580
|
} catch (error) {
|
|
6463
|
-
|
|
6581
|
+
try {
|
|
6582
|
+
unlinkSync2(tmp);
|
|
6583
|
+
} catch {}
|
|
6584
|
+
throw error;
|
|
6585
|
+
}
|
|
6586
|
+
}
|
|
6587
|
+
var JOURNAL_LOCK_STALE_MS = 30000;
|
|
6588
|
+
var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
6589
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6590
|
+
function withJournalLock(fn) {
|
|
6591
|
+
const path = journalPath();
|
|
6592
|
+
mkdirSync6(join9(path, ".."), { recursive: true });
|
|
6593
|
+
const lockPath = `${path}.lock`;
|
|
6594
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6595
|
+
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
6596
|
+
for (;; ) {
|
|
6597
|
+
try {
|
|
6598
|
+
const fd = openSync(lockPath, "wx", 384);
|
|
6599
|
+
try {
|
|
6600
|
+
writeFileSync9(fd, token);
|
|
6601
|
+
} finally {
|
|
6602
|
+
closeSync(fd);
|
|
6603
|
+
}
|
|
6604
|
+
break;
|
|
6605
|
+
} catch (error) {
|
|
6606
|
+
try {
|
|
6607
|
+
if (Date.now() - statSync3(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
6608
|
+
unlinkSync2(lockPath);
|
|
6609
|
+
} catch {}
|
|
6610
|
+
if (Date.now() >= deadline) {
|
|
6611
|
+
throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6612
|
+
}
|
|
6613
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
6614
|
+
}
|
|
6615
|
+
}
|
|
6616
|
+
try {
|
|
6617
|
+
return fn();
|
|
6618
|
+
} finally {
|
|
6619
|
+
try {
|
|
6620
|
+
if (readFileSync9(lockPath, "utf-8") === token)
|
|
6621
|
+
unlinkSync2(lockPath);
|
|
6622
|
+
} catch {}
|
|
6464
6623
|
}
|
|
6465
6624
|
}
|
|
6625
|
+
function mutate(fn) {
|
|
6626
|
+
return withJournalLock(() => {
|
|
6627
|
+
const entries = load();
|
|
6628
|
+
const result = fn(entries);
|
|
6629
|
+
save(entries);
|
|
6630
|
+
return result;
|
|
6631
|
+
});
|
|
6632
|
+
}
|
|
6633
|
+
function claimInflight(entry) {
|
|
6634
|
+
return mutate((entries) => {
|
|
6635
|
+
if (entries.some((e) => e.msgId === entry.msgId))
|
|
6636
|
+
return false;
|
|
6637
|
+
entries.push({ ...entry, state: "inflight" });
|
|
6638
|
+
return true;
|
|
6639
|
+
});
|
|
6640
|
+
}
|
|
6466
6641
|
function recordInflight(entry) {
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6642
|
+
mutate((entries) => {
|
|
6643
|
+
const existing = entries.find((e) => e.msgId === entry.msgId);
|
|
6644
|
+
if (existing) {
|
|
6645
|
+
if (!existing.sessionId && entry.sessionId)
|
|
6646
|
+
existing.sessionId = entry.sessionId;
|
|
6647
|
+
return;
|
|
6648
|
+
}
|
|
6649
|
+
entries.push({ ...entry, state: "inflight" });
|
|
6650
|
+
});
|
|
6470
6651
|
}
|
|
6471
6652
|
function settleInflight(msgId) {
|
|
6472
|
-
|
|
6473
|
-
|
|
6474
|
-
|
|
6475
|
-
|
|
6476
|
-
|
|
6653
|
+
mutate((entries) => {
|
|
6654
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
|
|
6655
|
+
if (entry)
|
|
6656
|
+
entry.state = "settled";
|
|
6657
|
+
});
|
|
6477
6658
|
}
|
|
6478
6659
|
function pendingInflight() {
|
|
6479
6660
|
return load().filter((e) => e.state === "inflight");
|
|
@@ -6494,6 +6675,9 @@ function classifyInflight(entry, messages) {
|
|
|
6494
6675
|
const matched = probe === "" || userText.includes(probe);
|
|
6495
6676
|
if (!matched)
|
|
6496
6677
|
return { kind: "lost" };
|
|
6678
|
+
const completed = ordered.slice(lastUserIdx + 1).some((m) => m.type === "idle");
|
|
6679
|
+
if (!completed)
|
|
6680
|
+
return { kind: "running" };
|
|
6497
6681
|
const answerParts = [];
|
|
6498
6682
|
for (let i = lastUserIdx + 1;i < ordered.length; i++) {
|
|
6499
6683
|
const m = ordered[i];
|
|
@@ -6510,6 +6694,7 @@ function classifyInflight(entry, messages) {
|
|
|
6510
6694
|
}
|
|
6511
6695
|
|
|
6512
6696
|
// src/bridge.ts
|
|
6697
|
+
var QUEUE_MAX = 20;
|
|
6513
6698
|
function evictableIdleSessions(lastActivity, watched, now, idleMs) {
|
|
6514
6699
|
const out = [];
|
|
6515
6700
|
for (const [sid, at] of lastActivity) {
|
|
@@ -6529,6 +6714,9 @@ function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, int
|
|
|
6529
6714
|
}
|
|
6530
6715
|
function createBridge(config, client, sessions) {
|
|
6531
6716
|
const busyUsers = new Set;
|
|
6717
|
+
const claimedContexts = new WeakSet;
|
|
6718
|
+
const msgQueue = new MessageQueue(QUEUE_MAX);
|
|
6719
|
+
const draining = new Set;
|
|
6532
6720
|
const greeted = loadGreetedSet();
|
|
6533
6721
|
const pendingSelections = new Map;
|
|
6534
6722
|
const eventStream = createEventStream(client.baseUrl);
|
|
@@ -6538,6 +6726,7 @@ function createBridge(config, client, sessions) {
|
|
|
6538
6726
|
const lastCtx = new Map;
|
|
6539
6727
|
const bgWaits = new Map;
|
|
6540
6728
|
const callCache = new Map;
|
|
6729
|
+
const turnStats = new Map;
|
|
6541
6730
|
const sessionLastActivity = new Map;
|
|
6542
6731
|
const IDLE_EVICT_MS = (() => {
|
|
6543
6732
|
const h = Number(process.env.QQ_SESSION_IDLE_HOURS ?? "6");
|
|
@@ -6575,6 +6764,22 @@ function createBridge(config, client, sessions) {
|
|
|
6575
6764
|
}
|
|
6576
6765
|
function onSessionEvent(sessionID, ev) {
|
|
6577
6766
|
sessionLastActivity.set(sessionID, Date.now());
|
|
6767
|
+
const d = ev.data ?? {};
|
|
6768
|
+
if (ev.type === "session.tool.called" || ev.type === "session.tool.success") {
|
|
6769
|
+
const cmd = typeof d.input === "string" ? d.input : d.input?.command;
|
|
6770
|
+
const actionable = ev.type === "session.tool.success" || typeof cmd === "string" && cmd.trim();
|
|
6771
|
+
if (actionable) {
|
|
6772
|
+
const st = turnStats.get(sessionID) ?? { tools: 0, failed: 0, lastTool: "", lastAt: 0 };
|
|
6773
|
+
if (ev.type === "session.tool.called") {
|
|
6774
|
+
st.tools++;
|
|
6775
|
+
st.lastTool = cmd.length > 60 ? `${String(cmd).slice(0, 60)}…` : String(cmd);
|
|
6776
|
+
} else if (typeof d.metadata?.exit === "number" && d.metadata.exit !== 0) {
|
|
6777
|
+
st.failed++;
|
|
6778
|
+
}
|
|
6779
|
+
st.lastAt = Date.now();
|
|
6780
|
+
turnStats.set(sessionID, st);
|
|
6781
|
+
}
|
|
6782
|
+
}
|
|
6578
6783
|
const line = formatMilestone(ev, callCache);
|
|
6579
6784
|
if (!line)
|
|
6580
6785
|
return;
|
|
@@ -6608,6 +6813,7 @@ function createBridge(config, client, sessions) {
|
|
|
6608
6813
|
cleanup();
|
|
6609
6814
|
if (trackId)
|
|
6610
6815
|
settleInflight(trackId);
|
|
6816
|
+
drainQueue(ctx.userId);
|
|
6611
6817
|
if (kind === "giveup") {
|
|
6612
6818
|
await safeDeliver(ctx, "⚠️ 后台任务 24 小时仍未完成,停止自动跟进;结果可随时用 /history 查询");
|
|
6613
6819
|
return;
|
|
@@ -6761,6 +6967,45 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6761
6967
|
console.log(`[interaction-watch] 常驻交互监听已启动(每 ${INTERACTION_WATCH_MS / 1000}s 轮询权限+表单)`);
|
|
6762
6968
|
}
|
|
6763
6969
|
const mirrorApi = mirror.api;
|
|
6970
|
+
const queueApi = {
|
|
6971
|
+
list: (userId) => {
|
|
6972
|
+
const jobs = msgQueue.list(userId);
|
|
6973
|
+
const busy = busyUsers.has(userId) ? "当前任务:处理中(发 /cancel 可中断)" : "当前任务:空闲";
|
|
6974
|
+
if (jobs.length === 0)
|
|
6975
|
+
return `${busy}
|
|
6976
|
+
队列:空`;
|
|
6977
|
+
const lines = jobs.map((j) => ` #${j.id} · ${agoLabel(j.enqueuedAt)} · ${previewText(j.text)}`);
|
|
6978
|
+
return [
|
|
6979
|
+
busy,
|
|
6980
|
+
`队列:${jobs.length} 条(上限 ${QUEUE_MAX})`,
|
|
6981
|
+
...lines,
|
|
6982
|
+
"发 /queue clear 清空,/queue drop <编号> 删除一条。"
|
|
6983
|
+
].join(`
|
|
6984
|
+
`);
|
|
6985
|
+
},
|
|
6986
|
+
clear: (userId) => msgQueue.clear(userId),
|
|
6987
|
+
drop: (userId, id) => msgQueue.drop(userId, id) ? `已删除队列 #${id}` : `队列里没有 #${id}`
|
|
6988
|
+
};
|
|
6989
|
+
const progressApi = {
|
|
6990
|
+
query: (userId) => {
|
|
6991
|
+
const session = sessions.getSession(userId);
|
|
6992
|
+
if (!session)
|
|
6993
|
+
return "当前还没有会话,发消息即可开始";
|
|
6994
|
+
const st = turnStats.get(session.sessionId);
|
|
6995
|
+
const busy = busyUsers.has(userId) ? "处理中" : "空闲";
|
|
6996
|
+
const bg = bgWaits.has(session.sessionId) ? " · 后台等待在途" : "";
|
|
6997
|
+
if (!st)
|
|
6998
|
+
return `当前会话:${busy}${bg}
|
|
6999
|
+
暂无工具调用记录(本会话新起或尚无动作类里程碑)`;
|
|
7000
|
+
return [
|
|
7001
|
+
`当前会话:${busy}${bg}`,
|
|
7002
|
+
`工具调用 ${st.tools} 次(失败 ${st.failed})`,
|
|
7003
|
+
st.lastTool ? `最近:${st.lastTool}` : "",
|
|
7004
|
+
st.lastAt ? `最近活动:${agoLabel(st.lastAt)}` : ""
|
|
7005
|
+
].filter(Boolean).join(`
|
|
7006
|
+
`);
|
|
7007
|
+
}
|
|
7008
|
+
};
|
|
6764
7009
|
const commandContext = {
|
|
6765
7010
|
config,
|
|
6766
7011
|
client,
|
|
@@ -6768,7 +7013,9 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6768
7013
|
getAccessToken: () => getAccessToken(config.qq.appId, config.qq.clientSecret),
|
|
6769
7014
|
pendingSelections,
|
|
6770
7015
|
watch: watchApi,
|
|
6771
|
-
mirror: mirrorApi
|
|
7016
|
+
mirror: mirrorApi,
|
|
7017
|
+
queue: queueApi,
|
|
7018
|
+
progress: progressApi
|
|
6772
7019
|
};
|
|
6773
7020
|
if (config.allowedUsers.length === 0) {
|
|
6774
7021
|
console.warn("[security] ALLOWED_USERS 为空 → 所有消息将被拒绝(fail-closed);请在 ~/.openqq/.env 配置白名单");
|
|
@@ -6793,6 +7040,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6793
7040
|
mirror.ensureSubs();
|
|
6794
7041
|
purgeOldQQImages();
|
|
6795
7042
|
const handleMessage = async (ctx) => {
|
|
7043
|
+
let claimedMsgId = "";
|
|
6796
7044
|
try {
|
|
6797
7045
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
6798
7046
|
await sendReply(ctx, "你不在允许使用的名单里");
|
|
@@ -6803,7 +7051,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6803
7051
|
return;
|
|
6804
7052
|
}
|
|
6805
7053
|
lastCtx.set(ctx.userId, ctx);
|
|
6806
|
-
if (!greeted.has(ctx.userId)) {
|
|
7054
|
+
if (!greeted.has(ctx.userId) && !isCommand(content)) {
|
|
6807
7055
|
greeted.add(ctx.userId);
|
|
6808
7056
|
saveGreetedSet(greeted);
|
|
6809
7057
|
await sendReply(ctx, buildHelpText());
|
|
@@ -6831,8 +7079,30 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6831
7079
|
await sendReply(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId));
|
|
6832
7080
|
return;
|
|
6833
7081
|
}
|
|
7082
|
+
if (ctx.msgId) {
|
|
7083
|
+
if (!claimedContexts.has(ctx)) {
|
|
7084
|
+
const claimed = claimInflight({ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() });
|
|
7085
|
+
if (!claimed) {
|
|
7086
|
+
console.log(`[bridge] 重复消息已跳过 msgId=${ctx.msgId}`);
|
|
7087
|
+
return;
|
|
7088
|
+
}
|
|
7089
|
+
claimedContexts.add(ctx);
|
|
7090
|
+
}
|
|
7091
|
+
claimedMsgId = ctx.msgId;
|
|
7092
|
+
}
|
|
6834
7093
|
if (busyUsers.has(ctx.userId)) {
|
|
6835
|
-
|
|
7094
|
+
if (ctx.attachments?.length && !ctx.preparedAttachments) {
|
|
7095
|
+
ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
7096
|
+
}
|
|
7097
|
+
const queued = msgQueue.push(ctx.userId, ctx);
|
|
7098
|
+
if (!queued) {
|
|
7099
|
+
if (claimedMsgId)
|
|
7100
|
+
settleInflight(claimedMsgId);
|
|
7101
|
+
await sendReply(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`);
|
|
7102
|
+
return;
|
|
7103
|
+
}
|
|
7104
|
+
await sendReply(ctx, `已排队 #${queued.job.id}${queued.ahead > 0 ? `(前面还有 ${queued.ahead} 条)` : ""},当前任务结束后自动执行。
|
|
7105
|
+
发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
|
|
6836
7106
|
return;
|
|
6837
7107
|
}
|
|
6838
7108
|
busyUsers.add(ctx.userId);
|
|
@@ -6855,7 +7125,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6855
7125
|
subscribeSession(sessionId, ctx.userId);
|
|
6856
7126
|
mirror.beginTurn(sessionId);
|
|
6857
7127
|
turnStart = Date.now();
|
|
6858
|
-
const prepared = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
7128
|
+
const prepared = ctx.preparedAttachments ?? await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
6859
7129
|
const { text: promptBody, files } = augmentPromptWithAttachments(content, prepared);
|
|
6860
7130
|
const promptText = ctx.quoteText ? `> 引用上文:${ctx.quoteText}
|
|
6861
7131
|
|
|
@@ -6893,7 +7163,9 @@ ${promptBody}` : promptBody;
|
|
|
6893
7163
|
await safeDeliver(ctx, "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。");
|
|
6894
7164
|
startBackgroundWait(sessionId, ctx, turnStart, trackId);
|
|
6895
7165
|
} else {
|
|
6896
|
-
|
|
7166
|
+
const errText = toErrorMessage2(error);
|
|
7167
|
+
const rescue = rescueText(classifyProviderError(errText), errText);
|
|
7168
|
+
await safeDeliver(ctx, rescue ?? `处理失败:${errText}`);
|
|
6897
7169
|
settleInflight(trackId);
|
|
6898
7170
|
}
|
|
6899
7171
|
} finally {
|
|
@@ -6902,8 +7174,12 @@ ${promptBody}` : promptBody;
|
|
|
6902
7174
|
if (sessionId && !bgWaits.has(sessionId))
|
|
6903
7175
|
mirror.scheduleUnlock(sessionId);
|
|
6904
7176
|
busyUsers.delete(ctx.userId);
|
|
7177
|
+
if (sessionId && !bgWaits.has(sessionId))
|
|
7178
|
+
drainQueue(ctx.userId);
|
|
6905
7179
|
}
|
|
6906
7180
|
} catch (error) {
|
|
7181
|
+
if (claimedMsgId)
|
|
7182
|
+
settleInflight(claimedMsgId);
|
|
6907
7183
|
console.error("[bridge] handleMessage failed:", error);
|
|
6908
7184
|
try {
|
|
6909
7185
|
await sendReply(ctx, `处理消息失败:${toErrorMessage2(error)}`);
|
|
@@ -6934,16 +7210,17 @@ ${cls.answer}`);
|
|
|
6934
7210
|
settleInflight(entry.msgId);
|
|
6935
7211
|
console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`);
|
|
6936
7212
|
} else if (cls.kind === "running") {
|
|
7213
|
+
mirror.beginTurn(entry.sessionId);
|
|
6937
7214
|
await deliver(ctx, "\uD83D\uDD04 重启恢复:你之前的任务仍在执行,完成即回传结果");
|
|
6938
|
-
startBackgroundWait(entry.sessionId, ctx,
|
|
7215
|
+
startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId);
|
|
6939
7216
|
console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`);
|
|
6940
7217
|
} else if (ageMs <= redispatchMaxAgeMs()) {
|
|
6941
7218
|
settleInflight(entry.msgId);
|
|
6942
|
-
await deliver(ctx, `\uD83D\uDD04 重启恢复:重新处理你之前的消息「${entry.text.slice(0, 50)}」`);
|
|
7219
|
+
await deliver(ctx, `\uD83D\uDD04 重启恢复:重新处理你之前的消息「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」`);
|
|
6943
7220
|
handleMessage(ctx);
|
|
6944
7221
|
console.log(`[bridge] 启动对账:丢失消息已重派 msgId=${entry.msgId}`);
|
|
6945
7222
|
} else {
|
|
6946
|
-
await deliver(ctx, `⚠️ 此前重启期间丢失一条你的消息「${entry.text.slice(0, 50)}」(超过自动重派窗口未重发),需要的话请重发一次`);
|
|
7223
|
+
await deliver(ctx, `⚠️ 此前重启期间丢失一条你的消息「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」(超过自动重派窗口未重发),需要的话请重发一次`);
|
|
6947
7224
|
settleInflight(entry.msgId);
|
|
6948
7225
|
console.log(`[bridge] 启动对账:超期消息仅通知 msgId=${entry.msgId}`);
|
|
6949
7226
|
}
|
|
@@ -6952,6 +7229,24 @@ ${cls.answer}`);
|
|
|
6952
7229
|
}
|
|
6953
7230
|
}
|
|
6954
7231
|
}
|
|
7232
|
+
async function drainQueue(userId) {
|
|
7233
|
+
if (draining.has(userId) || busyUsers.has(userId))
|
|
7234
|
+
return;
|
|
7235
|
+
const job = msgQueue.shift(userId);
|
|
7236
|
+
if (!job)
|
|
7237
|
+
return;
|
|
7238
|
+
draining.add(userId);
|
|
7239
|
+
try {
|
|
7240
|
+
await sendReply(job.ctx, `开始执行队列 #${job.id}`);
|
|
7241
|
+
await handleMessage(job.ctx);
|
|
7242
|
+
} catch (error) {
|
|
7243
|
+
console.error("[bridge] 队列执行失败:", error);
|
|
7244
|
+
} finally {
|
|
7245
|
+
draining.delete(userId);
|
|
7246
|
+
if (msgQueue.size(userId) > 0 && !busyUsers.has(userId))
|
|
7247
|
+
drainQueue(userId);
|
|
7248
|
+
}
|
|
7249
|
+
}
|
|
6955
7250
|
return {
|
|
6956
7251
|
handleMessage,
|
|
6957
7252
|
eventStream,
|
|
@@ -6987,7 +7282,7 @@ var WATCH_FILE = join10(homedir9(), ".openqq", "watch.json");
|
|
|
6987
7282
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
6988
7283
|
try {
|
|
6989
7284
|
if (existsSync8(file)) {
|
|
6990
|
-
const raw =
|
|
7285
|
+
const raw = readFileSync10(file, "utf-8");
|
|
6991
7286
|
const obj = JSON.parse(raw);
|
|
6992
7287
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
6993
7288
|
const out = {};
|
|
@@ -7011,7 +7306,7 @@ var GREETED_FILE = join10(homedir9(), ".openqq", "greeted.json");
|
|
|
7011
7306
|
function loadGreetedSet() {
|
|
7012
7307
|
try {
|
|
7013
7308
|
if (existsSync8(GREETED_FILE)) {
|
|
7014
|
-
const raw =
|
|
7309
|
+
const raw = readFileSync10(GREETED_FILE, "utf-8");
|
|
7015
7310
|
const arr = JSON.parse(raw);
|
|
7016
7311
|
if (Array.isArray(arr)) {
|
|
7017
7312
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -7074,7 +7369,7 @@ function toErrorMessage2(error) {
|
|
|
7074
7369
|
}
|
|
7075
7370
|
|
|
7076
7371
|
// src/core/instance-lock.ts
|
|
7077
|
-
import { openSync, writeFileSync as writeFileSync11, closeSync, unlinkSync as
|
|
7372
|
+
import { openSync as openSync2, writeFileSync as writeFileSync11, closeSync as closeSync2, unlinkSync as unlinkSync3, statSync as statSync4, utimesSync, mkdirSync as mkdirSync8 } from "fs";
|
|
7078
7373
|
import { join as join11 } from "path";
|
|
7079
7374
|
import { homedir as homedir10 } from "os";
|
|
7080
7375
|
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
@@ -7091,18 +7386,18 @@ function touch(path) {
|
|
|
7091
7386
|
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
|
|
7092
7387
|
try {
|
|
7093
7388
|
mkdirSync8(join11(path, ".."), { recursive: true });
|
|
7094
|
-
const fd =
|
|
7389
|
+
const fd = openSync2(path, "wx");
|
|
7095
7390
|
writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
7096
|
-
|
|
7391
|
+
closeSync2(fd);
|
|
7097
7392
|
} catch {
|
|
7098
7393
|
try {
|
|
7099
|
-
const age = Date.now() -
|
|
7394
|
+
const age = Date.now() - statSync4(path).mtimeMs;
|
|
7100
7395
|
if (age <= staleMs)
|
|
7101
7396
|
return null;
|
|
7102
|
-
|
|
7103
|
-
const fd =
|
|
7397
|
+
unlinkSync3(path);
|
|
7398
|
+
const fd = openSync2(path, "wx");
|
|
7104
7399
|
writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
7105
|
-
|
|
7400
|
+
closeSync2(fd);
|
|
7106
7401
|
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
7107
7402
|
} catch {
|
|
7108
7403
|
return null;
|
|
@@ -7122,7 +7417,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
|
|
|
7122
7417
|
released = true;
|
|
7123
7418
|
clearInterval(heartbeat);
|
|
7124
7419
|
try {
|
|
7125
|
-
|
|
7420
|
+
unlinkSync3(path);
|
|
7126
7421
|
} catch {}
|
|
7127
7422
|
}
|
|
7128
7423
|
};
|