@linjz/opencode-qqbot 0.3.13 → 0.3.15
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 +43 -7
- package/bin/openqq.js +21 -0
- package/dist/notify-cli.js +579 -0
- package/dist/opencode-qqbot-plugin.js +5 -2
- package/dist/openqq-bot.js +602 -130
- package/package.json +5 -4
- package/src/bridge.ts +43 -16
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +158 -0
- package/src/config.ts +2 -5
- package/src/core/bot-launcher.ts +1 -1
- package/src/core/delivery.ts +14 -9
- package/src/core/form-bridge.ts +2 -2
- package/src/core/inflight-journal.ts +22 -1
- package/src/core/instance-lock.ts +11 -4
- package/src/core/notify-sink.ts +96 -0
- package/src/core/permission.ts +3 -1
- package/src/opencode/client.ts +9 -5
- package/src/plugin-entry.ts +4 -1
- package/src/qq/api.ts +9 -2
- package/src/qq/gateway.ts +1 -1
- package/src/qq/media.ts +5 -1
- package/src/qq/sender.ts +11 -8
package/dist/openqq-bot.js
CHANGED
|
@@ -2939,16 +2939,16 @@ var require_websocket_server = __commonJS(function(exports, module) {
|
|
|
2939
2939
|
});
|
|
2940
2940
|
|
|
2941
2941
|
// src/core/file-log.ts
|
|
2942
|
-
import { appendFileSync, existsSync as
|
|
2943
|
-
import { join as
|
|
2942
|
+
import { appendFileSync, existsSync as existsSync12, mkdirSync as mkdirSync13, renameSync as renameSync6, statSync as statSync8 } from "fs";
|
|
2943
|
+
import { join as join15 } from "path";
|
|
2944
2944
|
function installFileLog(logPath) {
|
|
2945
2945
|
try {
|
|
2946
|
-
|
|
2946
|
+
mkdirSync13(join15(logPath, ".."), { recursive: true });
|
|
2947
2947
|
} catch {}
|
|
2948
2948
|
const write = (level, args) => {
|
|
2949
2949
|
try {
|
|
2950
|
-
if (
|
|
2951
|
-
|
|
2950
|
+
if (existsSync12(logPath) && statSync8(logPath).size > ROTATE_BYTES) {
|
|
2951
|
+
renameSync6(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}
|
|
@@ -3034,8 +3034,7 @@ async function ensureConfig() {
|
|
|
3034
3034
|
`QQ_APP_SECRET=${appSecret}`,
|
|
3035
3035
|
`QQ_SANDBOX=false`,
|
|
3036
3036
|
`# OPENCODE_BASE_URL=http://127.0.0.1:<端口>/api(桌面 2.1.x 端口动态,失联时启动流程会自动发现)`,
|
|
3037
|
-
`ALLOWED_USERS
|
|
3038
|
-
`MAX_REPLY_LENGTH=3000`
|
|
3037
|
+
`ALLOWED_USERS=`
|
|
3039
3038
|
].join(`
|
|
3040
3039
|
`) + `
|
|
3041
3040
|
`;
|
|
@@ -3081,22 +3080,23 @@ function loadConfig() {
|
|
|
3081
3080
|
baseUrl: process.env.OPENCODE_BASE_URL?.trim() || "",
|
|
3082
3081
|
externalUrl: !!process.env.OPENCODE_BASE_URL?.trim()
|
|
3083
3082
|
},
|
|
3084
|
-
allowedUsers
|
|
3085
|
-
maxReplyLength: parseInt(process.env.MAX_REPLY_LENGTH ?? "3000", 10)
|
|
3083
|
+
allowedUsers
|
|
3086
3084
|
};
|
|
3087
3085
|
}
|
|
3088
3086
|
|
|
3089
3087
|
// src/index.ts
|
|
3090
|
-
import { mkdirSync as
|
|
3091
|
-
import { join as
|
|
3092
|
-
import { homedir as
|
|
3088
|
+
import { mkdirSync as mkdirSync14, writeFileSync as writeFileSync15 } from "fs";
|
|
3089
|
+
import { join as join16 } from "path";
|
|
3090
|
+
import { homedir as homedir14 } from "os";
|
|
3093
3091
|
|
|
3094
3092
|
// src/opencode/client.ts
|
|
3095
|
-
|
|
3093
|
+
function turnTimeoutMinutes() {
|
|
3096
3094
|
const n = Number(process.env.OPENCODE_TURN_TIMEOUT_MINUTES ?? "30");
|
|
3097
3095
|
return Number.isFinite(n) && n > 0 ? n : 30;
|
|
3098
|
-
}
|
|
3099
|
-
|
|
3096
|
+
}
|
|
3097
|
+
function responseTimeoutMs() {
|
|
3098
|
+
return turnTimeoutMinutes() * 60 * 1000;
|
|
3099
|
+
}
|
|
3100
3100
|
function collectReplyText(msgs, baseline) {
|
|
3101
3101
|
const latest = msgs.filter((x) => x.type === "assistant" && (x.time?.created ?? 0) >= baseline).sort((a, b) => (b.time?.created ?? 0) - (a.time?.created ?? 0)).find((x) => (x.content ?? []).some((p) => p.type === "text" && p.text?.trim()));
|
|
3102
3102
|
return (latest?.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join(`
|
|
@@ -3297,7 +3297,7 @@ function createClient(baseUrl) {
|
|
|
3297
3297
|
if (options?.onAccepted)
|
|
3298
3298
|
options.onAccepted({ promptId, baseline });
|
|
3299
3299
|
console.log(`[opencode] LLM prompt 已受理 pid=${process.pid} session=${sessionId} user=${promptJson?.data?.id ?? "?"} baseline=${baseline}`);
|
|
3300
|
-
const deadline = Date.now() +
|
|
3300
|
+
const deadline = Date.now() + responseTimeoutMs();
|
|
3301
3301
|
let permissionWaitMs = 0;
|
|
3302
3302
|
const handledPermissions = new Set;
|
|
3303
3303
|
while (Date.now() - permissionWaitMs < deadline) {
|
|
@@ -3346,7 +3346,7 @@ function createClient(baseUrl) {
|
|
|
3346
3346
|
return turn.text || "(AI 未返回内容)";
|
|
3347
3347
|
}
|
|
3348
3348
|
}
|
|
3349
|
-
throw new Error(`AI 响应超时(${
|
|
3349
|
+
throw new Error(`AI 响应超时(${turnTimeoutMinutes()} 分钟)`);
|
|
3350
3350
|
}
|
|
3351
3351
|
};
|
|
3352
3352
|
client = oc;
|
|
@@ -3593,7 +3593,9 @@ function startLinkWatch(deps) {
|
|
|
3593
3593
|
var API_BASE = "https://api.sgroup.qq.com";
|
|
3594
3594
|
var TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
|
|
3595
3595
|
var API_BASE_SANDBOX = "https://sandbox.api.sgroup.qq.com";
|
|
3596
|
-
|
|
3596
|
+
function apiBase() {
|
|
3597
|
+
return process.env.QQ_SANDBOX === "true" ? API_BASE_SANDBOX : API_BASE;
|
|
3598
|
+
}
|
|
3597
3599
|
var cachedToken = null;
|
|
3598
3600
|
var tokenFetchPromise = null;
|
|
3599
3601
|
function maskHeaders(headers) {
|
|
@@ -3681,7 +3683,7 @@ function getNextMsgSeq(_msgId) {
|
|
|
3681
3683
|
var DEFAULT_API_TIMEOUT = 30000;
|
|
3682
3684
|
var FILE_UPLOAD_TIMEOUT = 120000;
|
|
3683
3685
|
async function apiRequest(accessToken, method, path, body, timeoutMs) {
|
|
3684
|
-
const url = `${
|
|
3686
|
+
const url = `${apiBase()}${path}`;
|
|
3685
3687
|
const headers = {
|
|
3686
3688
|
Authorization: `QQBot ${accessToken}`,
|
|
3687
3689
|
"Content-Type": "application/json"
|
|
@@ -4195,7 +4197,7 @@ function briefAttachments(atts) {
|
|
|
4195
4197
|
try {
|
|
4196
4198
|
host = new URL(a.url).hostname;
|
|
4197
4199
|
} catch {}
|
|
4198
|
-
return { host, content_type: a.content_type, size: a.size, filename: a.filename };
|
|
4200
|
+
return { host, content_type: a.content_type, size: a.size, filename: a.filename, asr: a.asr_refer_text ? 1 : 0 };
|
|
4199
4201
|
});
|
|
4200
4202
|
}
|
|
4201
4203
|
function toC2CMessageContext(event) {
|
|
@@ -4465,9 +4467,9 @@ async function startGateway(options) {
|
|
|
4465
4467
|
}
|
|
4466
4468
|
|
|
4467
4469
|
// src/bridge.ts
|
|
4468
|
-
import { existsSync as
|
|
4469
|
-
import { join as
|
|
4470
|
-
import { homedir as
|
|
4470
|
+
import { existsSync as existsSync11, readFileSync as readFileSync13, mkdirSync as mkdirSync11, writeFileSync as writeFileSync13 } from "fs";
|
|
4471
|
+
import { join as join13 } from "path";
|
|
4472
|
+
import { homedir as homedir12 } from "os";
|
|
4471
4473
|
|
|
4472
4474
|
// src/qq/media.ts
|
|
4473
4475
|
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync5 } from "node:fs";
|
|
@@ -4512,7 +4514,8 @@ async function fetchWithTimeout(url, ms, auth) {
|
|
|
4512
4514
|
}
|
|
4513
4515
|
async function downloadQQAttachment(att, getAuth) {
|
|
4514
4516
|
const ctype = (att.content_type || "").toLowerCase();
|
|
4515
|
-
|
|
4517
|
+
const isVoice = ctype.startsWith("audio/") || ctype === "voice" || ctype === "amr" || ctype.endsWith("/amr");
|
|
4518
|
+
if (isVoice && att.asr_refer_text?.trim()) {
|
|
4516
4519
|
return { voice: att.asr_refer_text.trim() };
|
|
4517
4520
|
}
|
|
4518
4521
|
const ext = extForImageMime(att.content_type || "");
|
|
@@ -5718,7 +5721,7 @@ function createPermissionGate(deps) {
|
|
|
5718
5721
|
pendingPermissions.delete(ctx.userId);
|
|
5719
5722
|
savePendingPermMap(pendingPermissions);
|
|
5720
5723
|
resolve("reject");
|
|
5721
|
-
|
|
5724
|
+
safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {});
|
|
5722
5725
|
}
|
|
5723
5726
|
}, PERM_PROMPT_TTL_MS);
|
|
5724
5727
|
pendingPermissions.set(ctx.userId, {
|
|
@@ -5869,7 +5872,6 @@ import { createHash } from "node:crypto";
|
|
|
5869
5872
|
import { homedir as homedir8 } from "os";
|
|
5870
5873
|
|
|
5871
5874
|
// src/qq/sender.ts
|
|
5872
|
-
var DEFAULT_MAX_LENGTH = 3000;
|
|
5873
5875
|
function formatForQQMarkdown(text) {
|
|
5874
5876
|
return text.trim();
|
|
5875
5877
|
}
|
|
@@ -5913,8 +5915,8 @@ function convertTables(text) {
|
|
|
5913
5915
|
return out.join(`
|
|
5914
5916
|
`);
|
|
5915
5917
|
}
|
|
5916
|
-
var MARKDOWN_MAX_BYTES =
|
|
5917
|
-
var PLAIN_MAX_BYTES =
|
|
5918
|
+
var MARKDOWN_MAX_BYTES = 60232;
|
|
5919
|
+
var PLAIN_MAX_BYTES = 60232;
|
|
5918
5920
|
var encoder = new TextEncoder;
|
|
5919
5921
|
function utf8Bytes(s) {
|
|
5920
5922
|
return encoder.encode(s).length;
|
|
@@ -6064,7 +6066,7 @@ async function sendChunk(accessToken, ctx, mdText, plainText, msgSeq) {
|
|
|
6064
6066
|
return await sendC2CMessage(accessToken, ctx.userId, plainText, ctx.msgId, msgSeq, false);
|
|
6065
6067
|
}
|
|
6066
6068
|
}
|
|
6067
|
-
async function replyToQQ(accessToken, ctx, text,
|
|
6069
|
+
async function replyToQQ(accessToken, ctx, text, options) {
|
|
6068
6070
|
const mdFormatted = formatForQQMarkdown(text);
|
|
6069
6071
|
const plainFormatted = formatForQQ(text);
|
|
6070
6072
|
const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES);
|
|
@@ -6259,7 +6261,9 @@ function qqListNormalize(text) {
|
|
|
6259
6261
|
`);
|
|
6260
6262
|
}
|
|
6261
6263
|
var DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
6262
|
-
|
|
6264
|
+
function deliveryDedupeFile() {
|
|
6265
|
+
return process.env.QQ_DELIVERY_DEDUPE_FILE || join9(homedir8(), ".openqq", "delivery-dedupe.json");
|
|
6266
|
+
}
|
|
6263
6267
|
function deliveryAttemptKey(userId, text) {
|
|
6264
6268
|
return `${userId}:${createHash("sha256").update(text).digest("hex")}`;
|
|
6265
6269
|
}
|
|
@@ -6269,9 +6273,9 @@ function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TT
|
|
|
6269
6273
|
function loadDeliveryAttempts() {
|
|
6270
6274
|
const out = new Map;
|
|
6271
6275
|
try {
|
|
6272
|
-
if (!existsSync7(
|
|
6276
|
+
if (!existsSync7(deliveryDedupeFile()))
|
|
6273
6277
|
return out;
|
|
6274
|
-
const raw = JSON.parse(readFileSync9(
|
|
6278
|
+
const raw = JSON.parse(readFileSync9(deliveryDedupeFile(), "utf-8"));
|
|
6275
6279
|
const now = Date.now();
|
|
6276
6280
|
for (const entry of raw) {
|
|
6277
6281
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -6283,11 +6287,11 @@ function loadDeliveryAttempts() {
|
|
|
6283
6287
|
}
|
|
6284
6288
|
function saveDeliveryAttempts(entries) {
|
|
6285
6289
|
const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
|
|
6286
|
-
mkdirSync7(join9(
|
|
6287
|
-
const tmp = `${
|
|
6290
|
+
mkdirSync7(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
6291
|
+
const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6288
6292
|
try {
|
|
6289
6293
|
writeFileSync9(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
|
|
6290
|
-
renameSync2(tmp,
|
|
6294
|
+
renameSync2(tmp, deliveryDedupeFile());
|
|
6291
6295
|
} catch (error) {
|
|
6292
6296
|
try {
|
|
6293
6297
|
unlinkSync3(tmp);
|
|
@@ -6299,8 +6303,8 @@ var DELIVERY_LOCK_STALE_MS = 30000;
|
|
|
6299
6303
|
var DELIVERY_LOCK_WAIT_MS = 5000;
|
|
6300
6304
|
var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6301
6305
|
function withDeliveryLock(fn) {
|
|
6302
|
-
mkdirSync7(join9(
|
|
6303
|
-
const lockPath = `${
|
|
6306
|
+
mkdirSync7(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
6307
|
+
const lockPath = `${deliveryDedupeFile()}.lock`;
|
|
6304
6308
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6305
6309
|
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
|
|
6306
6310
|
for (;; ) {
|
|
@@ -6515,7 +6519,7 @@ function createDelivery(config, lastCtx) {
|
|
|
6515
6519
|
}
|
|
6516
6520
|
async function sendReply(ctx, text) {
|
|
6517
6521
|
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret);
|
|
6518
|
-
const result = await replyToQQ(accessToken, ctx, text,
|
|
6522
|
+
const result = await replyToQQ(accessToken, ctx, text, {
|
|
6519
6523
|
staggerMs: STREAM_STAGGER_MS
|
|
6520
6524
|
});
|
|
6521
6525
|
if (ctx.msgId) {
|
|
@@ -6529,6 +6533,441 @@ function createDelivery(config, lastCtx) {
|
|
|
6529
6533
|
return { enqueuePush, deliver, safeDeliver, sendReply };
|
|
6530
6534
|
}
|
|
6531
6535
|
|
|
6536
|
+
// src/core/outbox.ts
|
|
6537
|
+
import {
|
|
6538
|
+
closeSync as closeSync2,
|
|
6539
|
+
existsSync as existsSync8,
|
|
6540
|
+
mkdirSync as mkdirSync8,
|
|
6541
|
+
openSync as openSync2,
|
|
6542
|
+
readFileSync as readFileSync10,
|
|
6543
|
+
renameSync as renameSync3,
|
|
6544
|
+
statSync as statSync4,
|
|
6545
|
+
unlinkSync as unlinkSync4,
|
|
6546
|
+
writeFileSync as writeFileSync10
|
|
6547
|
+
} from "node:fs";
|
|
6548
|
+
import { homedir as homedir9 } from "node:os";
|
|
6549
|
+
import { dirname, join as join10 } from "node:path";
|
|
6550
|
+
import { randomUUID } from "node:crypto";
|
|
6551
|
+
var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
|
|
6552
|
+
var OUTBOX_SENT_RETENTION_LIMIT = 20;
|
|
6553
|
+
var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
|
|
6554
|
+
var OUTBOX_DEFAULT_RETRY_MAX_MS = 60000;
|
|
6555
|
+
var DEFAULT_POLL_INTERVAL_MS = 1000;
|
|
6556
|
+
var DEFAULT_LEASE_MS = 30000;
|
|
6557
|
+
var DEFAULT_LOCK_WAIT_MS = 5000;
|
|
6558
|
+
var DEFAULT_LOCK_STALE_MS = 30000;
|
|
6559
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6560
|
+
function nonNegative(value, fallback, name) {
|
|
6561
|
+
const resolved = value ?? fallback;
|
|
6562
|
+
if (!Number.isFinite(resolved) || resolved < 0)
|
|
6563
|
+
throw new Error(`${name} 必须是 >= 0 的有限数`);
|
|
6564
|
+
return resolved;
|
|
6565
|
+
}
|
|
6566
|
+
function positive(value, fallback, name) {
|
|
6567
|
+
const resolved = nonNegative(value, fallback, name);
|
|
6568
|
+
if (resolved === 0)
|
|
6569
|
+
throw new Error(`${name} 必须 > 0`);
|
|
6570
|
+
return resolved;
|
|
6571
|
+
}
|
|
6572
|
+
function errorText(error) {
|
|
6573
|
+
return error instanceof Error ? error.message : String(error);
|
|
6574
|
+
}
|
|
6575
|
+
function jsonSnapshot(value, label) {
|
|
6576
|
+
const encoded = JSON.stringify(value);
|
|
6577
|
+
if (encoded === undefined)
|
|
6578
|
+
throw new Error(`Outbox ${label} 必须是可 JSON 序列化的值`);
|
|
6579
|
+
return JSON.parse(encoded);
|
|
6580
|
+
}
|
|
6581
|
+
function delay(ms) {
|
|
6582
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
6583
|
+
}
|
|
6584
|
+
function atomicWrite(filePath, document) {
|
|
6585
|
+
mkdirSync8(dirname(filePath), { recursive: true });
|
|
6586
|
+
const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
|
|
6587
|
+
try {
|
|
6588
|
+
writeFileSync10(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
6589
|
+
renameSync3(temporary, filePath);
|
|
6590
|
+
} catch (error) {
|
|
6591
|
+
try {
|
|
6592
|
+
unlinkSync4(temporary);
|
|
6593
|
+
} catch {}
|
|
6594
|
+
throw error;
|
|
6595
|
+
}
|
|
6596
|
+
}
|
|
6597
|
+
function readDocument(filePath, now) {
|
|
6598
|
+
if (!existsSync8(filePath))
|
|
6599
|
+
return { version: 1, entries: [] };
|
|
6600
|
+
const raw = JSON.parse(readFileSync10(filePath, "utf8"));
|
|
6601
|
+
if (Array.isArray(raw)) {
|
|
6602
|
+
return { version: 1, entries: pruneOutboxEntries(raw, now) };
|
|
6603
|
+
}
|
|
6604
|
+
if (typeof raw !== "object" || raw === null || raw.version !== 1 || !Array.isArray(raw.entries)) {
|
|
6605
|
+
throw new Error(`Outbox 文件格式无效: ${filePath}`);
|
|
6606
|
+
}
|
|
6607
|
+
const entries = raw.entries;
|
|
6608
|
+
return { version: 1, entries: pruneOutboxEntries(entries, now) };
|
|
6609
|
+
}
|
|
6610
|
+
function pruneOutboxEntries(entries, now = Date.now()) {
|
|
6611
|
+
const indexed = entries.map((entry, index) => ({ entry, index }));
|
|
6612
|
+
const retainedSent = new Set(indexed.filter(({ entry }) => entry.state === "sent" && now - entry.updatedAt <= OUTBOX_SENT_RETENTION_MS).sort((a, b) => b.entry.updatedAt - a.entry.updatedAt || b.index - a.index).slice(0, OUTBOX_SENT_RETENTION_LIMIT).map(({ index }) => index));
|
|
6613
|
+
return indexed.filter(({ entry, index }) => entry.state !== "sent" || retainedSent.has(index)).sort((a, b) => a.entry.createdAt - b.entry.createdAt || a.index - b.index).map(({ entry }) => entry);
|
|
6614
|
+
}
|
|
6615
|
+
function createOutbox(options = {}) {
|
|
6616
|
+
const filePath = options.filePath ?? process.env.QQ_OUTBOX_FILE ?? join10(homedir9(), ".openqq", "outbox.json");
|
|
6617
|
+
const pollIntervalMs = nonNegative(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, "pollIntervalMs");
|
|
6618
|
+
const retryBaseMs = nonNegative(options.retryBaseMs, OUTBOX_DEFAULT_RETRY_BASE_MS, "retryBaseMs");
|
|
6619
|
+
const retryMaxMs = nonNegative(options.retryMaxMs, OUTBOX_DEFAULT_RETRY_MAX_MS, "retryMaxMs");
|
|
6620
|
+
const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
|
|
6621
|
+
const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
|
|
6622
|
+
const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
|
|
6623
|
+
const owner = `${process.pid}:${randomUUID()}`;
|
|
6624
|
+
const handlers = new Map;
|
|
6625
|
+
const inFlight = new Map;
|
|
6626
|
+
const automatic = new Set;
|
|
6627
|
+
let timer;
|
|
6628
|
+
let stopped = false;
|
|
6629
|
+
let flushing;
|
|
6630
|
+
function withLock(fn) {
|
|
6631
|
+
mkdirSync8(dirname(filePath), { recursive: true });
|
|
6632
|
+
const lockPath = `${filePath}.lock`;
|
|
6633
|
+
const token = `${owner}:${Date.now()}:${randomUUID()}`;
|
|
6634
|
+
const deadline = Date.now() + lockWaitMs;
|
|
6635
|
+
for (;; ) {
|
|
6636
|
+
try {
|
|
6637
|
+
const fd = openSync2(lockPath, "wx", 384);
|
|
6638
|
+
try {
|
|
6639
|
+
writeFileSync10(fd, token);
|
|
6640
|
+
} finally {
|
|
6641
|
+
closeSync2(fd);
|
|
6642
|
+
}
|
|
6643
|
+
break;
|
|
6644
|
+
} catch (error) {
|
|
6645
|
+
try {
|
|
6646
|
+
if (Date.now() - statSync4(lockPath).mtimeMs > lockStaleMs)
|
|
6647
|
+
unlinkSync4(lockPath);
|
|
6648
|
+
} catch {}
|
|
6649
|
+
if (Date.now() >= deadline)
|
|
6650
|
+
throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
|
|
6651
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
6652
|
+
}
|
|
6653
|
+
}
|
|
6654
|
+
try {
|
|
6655
|
+
return fn();
|
|
6656
|
+
} finally {
|
|
6657
|
+
try {
|
|
6658
|
+
if (readFileSync10(lockPath, "utf8") === token)
|
|
6659
|
+
unlinkSync4(lockPath);
|
|
6660
|
+
} catch {}
|
|
6661
|
+
}
|
|
6662
|
+
}
|
|
6663
|
+
function mutate(fn) {
|
|
6664
|
+
return withLock(() => {
|
|
6665
|
+
const document = readDocument(filePath, Date.now());
|
|
6666
|
+
const result = fn(document.entries);
|
|
6667
|
+
document.entries = pruneOutboxEntries(document.entries);
|
|
6668
|
+
atomicWrite(filePath, document);
|
|
6669
|
+
return result;
|
|
6670
|
+
});
|
|
6671
|
+
}
|
|
6672
|
+
function clone(entry) {
|
|
6673
|
+
return JSON.parse(JSON.stringify(entry));
|
|
6674
|
+
}
|
|
6675
|
+
function clearLease(entry) {
|
|
6676
|
+
delete entry.leaseOwner;
|
|
6677
|
+
delete entry.leaseUntil;
|
|
6678
|
+
}
|
|
6679
|
+
function transitionRecovered(entry, now, maxAttempts) {
|
|
6680
|
+
if (entry.state !== "sending")
|
|
6681
|
+
return false;
|
|
6682
|
+
const exhausted = maxAttempts !== undefined && entry.attempts >= maxAttempts;
|
|
6683
|
+
entry.state = exhausted ? "failed" : "pending";
|
|
6684
|
+
entry.updatedAt = now;
|
|
6685
|
+
entry.nextAttemptAt = now;
|
|
6686
|
+
entry.lastError = exhausted ? `${entry.lastError ? `${entry.lastError}; ` : ""}崩溃恢复后已达到 maxAttempts=${maxAttempts}` : "进程在 sending 期间退出,发送结果未知;按至少一次语义恢复";
|
|
6687
|
+
clearLease(entry);
|
|
6688
|
+
return true;
|
|
6689
|
+
}
|
|
6690
|
+
async function recover(recoverOptions = {}) {
|
|
6691
|
+
const now = Date.now();
|
|
6692
|
+
return mutate((entries) => {
|
|
6693
|
+
const recovered = [];
|
|
6694
|
+
const exhausted = [];
|
|
6695
|
+
for (const entry of entries) {
|
|
6696
|
+
if (entry.state !== "sending")
|
|
6697
|
+
continue;
|
|
6698
|
+
if (inFlight.has(entry.id) && entry.leaseOwner?.startsWith(`${owner}:`))
|
|
6699
|
+
continue;
|
|
6700
|
+
const expired = entry.leaseUntil === undefined || entry.leaseUntil <= now;
|
|
6701
|
+
if (!recoverOptions.ignoreLeases && !expired)
|
|
6702
|
+
continue;
|
|
6703
|
+
transitionRecovered(entry, now, recoverOptions.maxAttempts);
|
|
6704
|
+
const snapshot = clone(entry);
|
|
6705
|
+
if (snapshot.state === "failed")
|
|
6706
|
+
exhausted.push(snapshot);
|
|
6707
|
+
else
|
|
6708
|
+
recovered.push(snapshot);
|
|
6709
|
+
}
|
|
6710
|
+
return { recovered, exhausted };
|
|
6711
|
+
});
|
|
6712
|
+
}
|
|
6713
|
+
async function dispatchInternal(id, dispatchOptions) {
|
|
6714
|
+
const handlerlessSnapshot = readDocument(filePath, Date.now()).entries.find((entry) => entry.id === id);
|
|
6715
|
+
if (!handlerlessSnapshot)
|
|
6716
|
+
return null;
|
|
6717
|
+
const handler = handlers.get(handlerlessSnapshot.kind);
|
|
6718
|
+
if (!handler)
|
|
6719
|
+
return clone(handlerlessSnapshot);
|
|
6720
|
+
const now = Date.now();
|
|
6721
|
+
const token = `${owner}:${randomUUID()}`;
|
|
6722
|
+
const claimed = withLock(() => {
|
|
6723
|
+
const document = readDocument(filePath, now);
|
|
6724
|
+
const entry = document.entries.find((candidate) => candidate.id === id);
|
|
6725
|
+
if (!entry)
|
|
6726
|
+
return { entry: null };
|
|
6727
|
+
if (entry.state === "sent")
|
|
6728
|
+
return { entry: clone(entry) };
|
|
6729
|
+
if (entry.state === "sending" && entry.leaseUntil !== undefined && entry.leaseUntil > now) {
|
|
6730
|
+
return { entry: null };
|
|
6731
|
+
}
|
|
6732
|
+
if ((entry.state === "pending" || entry.state === "failed" || entry.state === "sending") && !dispatchOptions.force && entry.nextAttemptAt > now) {
|
|
6733
|
+
return { entry: clone(entry) };
|
|
6734
|
+
}
|
|
6735
|
+
const maxAttempts = dispatchOptions.maxAttempts;
|
|
6736
|
+
if (maxAttempts !== undefined && entry.attempts >= maxAttempts) {
|
|
6737
|
+
if (entry.state !== "failed") {
|
|
6738
|
+
entry.state = "failed";
|
|
6739
|
+
entry.updatedAt = now;
|
|
6740
|
+
clearLease(entry);
|
|
6741
|
+
atomicWrite(filePath, document);
|
|
6742
|
+
}
|
|
6743
|
+
return { entry: clone(entry) };
|
|
6744
|
+
}
|
|
6745
|
+
entry.state = "sending";
|
|
6746
|
+
entry.attempts += 1;
|
|
6747
|
+
entry.updatedAt = now;
|
|
6748
|
+
entry.leaseOwner = token;
|
|
6749
|
+
entry.leaseUntil = now + leaseMs;
|
|
6750
|
+
delete entry.lastError;
|
|
6751
|
+
atomicWrite(filePath, document);
|
|
6752
|
+
return { entry: clone(entry), token };
|
|
6753
|
+
});
|
|
6754
|
+
if (!claimed.entry || !("token" in claimed))
|
|
6755
|
+
return claimed.entry;
|
|
6756
|
+
try {
|
|
6757
|
+
const receipt = await handler(clone(claimed.entry));
|
|
6758
|
+
const persistedReceipt = receipt === undefined ? null : jsonSnapshot(receipt, "receipt");
|
|
6759
|
+
return mutate((entries) => {
|
|
6760
|
+
const current = entries.find((entry) => entry.id === id);
|
|
6761
|
+
if (!current || current.leaseOwner !== token)
|
|
6762
|
+
return current ? clone(current) : null;
|
|
6763
|
+
const completedAt = Date.now();
|
|
6764
|
+
current.state = "sent";
|
|
6765
|
+
current.updatedAt = completedAt;
|
|
6766
|
+
current.receipt = persistedReceipt;
|
|
6767
|
+
delete current.lastError;
|
|
6768
|
+
clearLease(current);
|
|
6769
|
+
return clone(current);
|
|
6770
|
+
});
|
|
6771
|
+
} catch (error) {
|
|
6772
|
+
const failed = mutate((entries) => {
|
|
6773
|
+
const current = entries.find((entry) => entry.id === id);
|
|
6774
|
+
if (!current || current.leaseOwner !== token)
|
|
6775
|
+
return current ? clone(current) : null;
|
|
6776
|
+
const failedAt = Date.now();
|
|
6777
|
+
current.state = "failed";
|
|
6778
|
+
current.updatedAt = failedAt;
|
|
6779
|
+
current.lastError = errorText(error);
|
|
6780
|
+
current.nextAttemptAt = failedAt + Math.min(retryMaxMs, retryBaseMs * 2 ** Math.max(0, current.attempts - 1));
|
|
6781
|
+
clearLease(current);
|
|
6782
|
+
return clone(current);
|
|
6783
|
+
});
|
|
6784
|
+
if (automatic.has(id))
|
|
6785
|
+
return failed;
|
|
6786
|
+
throw error;
|
|
6787
|
+
}
|
|
6788
|
+
}
|
|
6789
|
+
function dispatch(id, dispatchOptions = {}) {
|
|
6790
|
+
const existing = inFlight.get(id);
|
|
6791
|
+
if (existing)
|
|
6792
|
+
return existing;
|
|
6793
|
+
const promise = dispatchInternal(id, dispatchOptions).finally(() => {
|
|
6794
|
+
if (inFlight.get(id) === promise)
|
|
6795
|
+
inFlight.delete(id);
|
|
6796
|
+
});
|
|
6797
|
+
inFlight.set(id, promise);
|
|
6798
|
+
return promise;
|
|
6799
|
+
}
|
|
6800
|
+
async function flush(flushOptions = {}) {
|
|
6801
|
+
if (flushing)
|
|
6802
|
+
return flushing;
|
|
6803
|
+
const run = (async () => {
|
|
6804
|
+
const results = new Map;
|
|
6805
|
+
for (;; ) {
|
|
6806
|
+
await recover({ maxAttempts: flushOptions.maxAttempts });
|
|
6807
|
+
const entries = readDocument(filePath, Date.now()).entries;
|
|
6808
|
+
const candidates = entries.filter((entry) => {
|
|
6809
|
+
if (entry.state !== "pending" && entry.state !== "failed")
|
|
6810
|
+
return false;
|
|
6811
|
+
if (!handlers.has(entry.kind))
|
|
6812
|
+
return false;
|
|
6813
|
+
if (flushOptions.maxAttempts !== undefined && entry.attempts >= flushOptions.maxAttempts)
|
|
6814
|
+
return false;
|
|
6815
|
+
return flushOptions.force || flushOptions.wait || entry.nextAttemptAt <= Date.now();
|
|
6816
|
+
});
|
|
6817
|
+
const settled = await Promise.all(candidates.map(async (entry) => {
|
|
6818
|
+
const result = await dispatch(entry.id, flushOptions);
|
|
6819
|
+
if (result)
|
|
6820
|
+
results.set(entry.id, result);
|
|
6821
|
+
return result;
|
|
6822
|
+
}));
|
|
6823
|
+
if (!flushOptions.wait)
|
|
6824
|
+
break;
|
|
6825
|
+
const after = readDocument(filePath, Date.now()).entries;
|
|
6826
|
+
const active = after.filter((entry) => (entry.state === "pending" || entry.state === "failed") && handlers.has(entry.kind) && (flushOptions.maxAttempts === undefined || entry.attempts < flushOptions.maxAttempts));
|
|
6827
|
+
const waitingLocal = after.some((entry) => entry.state === "sending" && inFlight.has(entry.id));
|
|
6828
|
+
if (active.length === 0 && !waitingLocal)
|
|
6829
|
+
break;
|
|
6830
|
+
if (settled.length === 0 && !waitingLocal) {
|
|
6831
|
+
const next = active.reduce((minimum, entry) => Math.min(minimum, entry.nextAttemptAt), Number.POSITIVE_INFINITY);
|
|
6832
|
+
if (Number.isFinite(next))
|
|
6833
|
+
await delay(Math.max(1, next - Date.now()));
|
|
6834
|
+
else
|
|
6835
|
+
break;
|
|
6836
|
+
} else {
|
|
6837
|
+
await delay(1);
|
|
6838
|
+
}
|
|
6839
|
+
}
|
|
6840
|
+
return [...results.values()];
|
|
6841
|
+
})();
|
|
6842
|
+
flushing = run;
|
|
6843
|
+
try {
|
|
6844
|
+
return await run;
|
|
6845
|
+
} finally {
|
|
6846
|
+
if (flushing === run)
|
|
6847
|
+
flushing = undefined;
|
|
6848
|
+
}
|
|
6849
|
+
}
|
|
6850
|
+
async function drain() {
|
|
6851
|
+
while (inFlight.size > 0) {
|
|
6852
|
+
const pending = [...inFlight.values()];
|
|
6853
|
+
const outcomes = await Promise.allSettled(pending);
|
|
6854
|
+
const rejection = outcomes.find((outcome) => outcome.status === "rejected");
|
|
6855
|
+
if (rejection)
|
|
6856
|
+
throw rejection.reason;
|
|
6857
|
+
}
|
|
6858
|
+
}
|
|
6859
|
+
return {
|
|
6860
|
+
filePath,
|
|
6861
|
+
register(kind, handler) {
|
|
6862
|
+
if (!kind)
|
|
6863
|
+
throw new Error("Outbox kind 不能为空");
|
|
6864
|
+
handlers.set(kind, handler);
|
|
6865
|
+
return () => {
|
|
6866
|
+
if (handlers.get(kind) === handler)
|
|
6867
|
+
handlers.delete(kind);
|
|
6868
|
+
};
|
|
6869
|
+
},
|
|
6870
|
+
async enqueue(input) {
|
|
6871
|
+
if (!input.kind)
|
|
6872
|
+
throw new Error("Outbox kind 不能为空");
|
|
6873
|
+
if (input.payload === undefined)
|
|
6874
|
+
throw new Error("Outbox payload 必须是 JSON 值,不能为 undefined");
|
|
6875
|
+
if (input.nextAttemptAt !== undefined && !Number.isFinite(input.nextAttemptAt)) {
|
|
6876
|
+
throw new Error("Outbox nextAttemptAt 必须是有限时间戳");
|
|
6877
|
+
}
|
|
6878
|
+
const persistedCtx = jsonSnapshot(input.ctx, "ctx");
|
|
6879
|
+
const persistedPayload = jsonSnapshot(input.payload, "payload");
|
|
6880
|
+
const now = Date.now();
|
|
6881
|
+
const id = input.id ?? randomUUID();
|
|
6882
|
+
const entry = mutate((entries) => {
|
|
6883
|
+
const existing = entries.find((candidate) => candidate.id === id);
|
|
6884
|
+
if (existing)
|
|
6885
|
+
return clone(existing);
|
|
6886
|
+
const created = {
|
|
6887
|
+
id,
|
|
6888
|
+
kind: input.kind,
|
|
6889
|
+
ctx: persistedCtx,
|
|
6890
|
+
payload: persistedPayload,
|
|
6891
|
+
...input.sessionId !== undefined ? { sessionId: input.sessionId } : {},
|
|
6892
|
+
...input.turnId !== undefined ? { turnId: input.turnId } : {},
|
|
6893
|
+
state: "pending",
|
|
6894
|
+
attempts: 0,
|
|
6895
|
+
createdAt: now,
|
|
6896
|
+
updatedAt: now,
|
|
6897
|
+
nextAttemptAt: input.nextAttemptAt ?? now
|
|
6898
|
+
};
|
|
6899
|
+
entries.push(created);
|
|
6900
|
+
return clone(created);
|
|
6901
|
+
});
|
|
6902
|
+
automatic.add(id);
|
|
6903
|
+
dispatch(id).finally(() => automatic.delete(id)).catch(() => {});
|
|
6904
|
+
return entry;
|
|
6905
|
+
},
|
|
6906
|
+
dispatch,
|
|
6907
|
+
recover,
|
|
6908
|
+
flush,
|
|
6909
|
+
async start(startOptions = {}) {
|
|
6910
|
+
stopped = false;
|
|
6911
|
+
if (startOptions.recover !== false)
|
|
6912
|
+
await recover();
|
|
6913
|
+
if (pollIntervalMs === 0 || timer)
|
|
6914
|
+
return;
|
|
6915
|
+
timer = setInterval(() => {
|
|
6916
|
+
if (stopped)
|
|
6917
|
+
return;
|
|
6918
|
+
flush().catch(() => {});
|
|
6919
|
+
}, pollIntervalMs);
|
|
6920
|
+
timer.unref?.();
|
|
6921
|
+
flush().catch(() => {});
|
|
6922
|
+
},
|
|
6923
|
+
stop() {
|
|
6924
|
+
stopped = true;
|
|
6925
|
+
if (timer)
|
|
6926
|
+
clearInterval(timer);
|
|
6927
|
+
timer = undefined;
|
|
6928
|
+
},
|
|
6929
|
+
drain,
|
|
6930
|
+
async list() {
|
|
6931
|
+
return readDocument(filePath, Date.now()).entries.map((entry) => clone(entry));
|
|
6932
|
+
},
|
|
6933
|
+
async get(id) {
|
|
6934
|
+
const entry = readDocument(filePath, Date.now()).entries.find((candidate) => candidate.id === id);
|
|
6935
|
+
return entry ? clone(entry) : undefined;
|
|
6936
|
+
}
|
|
6937
|
+
};
|
|
6938
|
+
}
|
|
6939
|
+
|
|
6940
|
+
// src/core/notify-sink.ts
|
|
6941
|
+
var DEFAULT_NOTIFY_TTL_HOURS = 24;
|
|
6942
|
+
var DEFAULT_NOTIFY_MAX_ATTEMPTS = 8;
|
|
6943
|
+
function createNotifySink(options) {
|
|
6944
|
+
const ttlHours = Number(options.ttlHours ?? process.env.QQ_NOTIFY_TTL_HOURS ?? DEFAULT_NOTIFY_TTL_HOURS);
|
|
6945
|
+
const ttlMs = (Number.isFinite(ttlHours) && ttlHours > 0 ? ttlHours : DEFAULT_NOTIFY_TTL_HOURS) * 60 * 60 * 1000;
|
|
6946
|
+
const maxRaw = Number(options.maxAttempts ?? process.env.QQ_NOTIFY_MAX_ATTEMPTS ?? DEFAULT_NOTIFY_MAX_ATTEMPTS);
|
|
6947
|
+
const maxAttempts = Number.isFinite(maxRaw) && maxRaw > 0 ? Math.floor(maxRaw) : DEFAULT_NOTIFY_MAX_ATTEMPTS;
|
|
6948
|
+
const outbox = createOutbox({ ...options.filePath ? { filePath: options.filePath } : {} });
|
|
6949
|
+
outbox.register("notify", (entry) => {
|
|
6950
|
+
if (Date.now() - entry.createdAt > ttlMs) {
|
|
6951
|
+
return { skipped: "ttl-expired" };
|
|
6952
|
+
}
|
|
6953
|
+
const text = entry.payload?.text;
|
|
6954
|
+
if (typeof text !== "string" || !text.trim()) {
|
|
6955
|
+
return { skipped: "no-text" };
|
|
6956
|
+
}
|
|
6957
|
+
const ctx = entry.ctx;
|
|
6958
|
+
return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }));
|
|
6959
|
+
});
|
|
6960
|
+
outbox.start({ recover: true }).catch((error) => {
|
|
6961
|
+
console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error);
|
|
6962
|
+
});
|
|
6963
|
+
return {
|
|
6964
|
+
outbox,
|
|
6965
|
+
stop() {
|
|
6966
|
+
outbox.stop();
|
|
6967
|
+
}
|
|
6968
|
+
};
|
|
6969
|
+
}
|
|
6970
|
+
|
|
6532
6971
|
// src/core/card-approval.ts
|
|
6533
6972
|
var BUTTON_LABEL_MAX = 10;
|
|
6534
6973
|
function encodeButtonData(data) {
|
|
@@ -6608,24 +7047,24 @@ function handleApprovalInteraction(event, gate) {
|
|
|
6608
7047
|
|
|
6609
7048
|
// src/core/form-journal.ts
|
|
6610
7049
|
import {
|
|
6611
|
-
closeSync as
|
|
6612
|
-
existsSync as
|
|
6613
|
-
mkdirSync as
|
|
6614
|
-
openSync as
|
|
6615
|
-
readFileSync as
|
|
6616
|
-
renameSync as
|
|
6617
|
-
statSync as
|
|
6618
|
-
unlinkSync as
|
|
6619
|
-
writeFileSync as
|
|
7050
|
+
closeSync as closeSync3,
|
|
7051
|
+
existsSync as existsSync9,
|
|
7052
|
+
mkdirSync as mkdirSync9,
|
|
7053
|
+
openSync as openSync3,
|
|
7054
|
+
readFileSync as readFileSync11,
|
|
7055
|
+
renameSync as renameSync4,
|
|
7056
|
+
statSync as statSync5,
|
|
7057
|
+
unlinkSync as unlinkSync5,
|
|
7058
|
+
writeFileSync as writeFileSync11
|
|
6620
7059
|
} from "fs";
|
|
6621
|
-
import { dirname, join as
|
|
6622
|
-
import { homedir as
|
|
7060
|
+
import { dirname as dirname2, join as join11 } from "path";
|
|
7061
|
+
import { homedir as homedir10 } from "os";
|
|
6623
7062
|
var LOCK_STALE_MS = 30000;
|
|
6624
7063
|
var LOCK_WAIT_MS = 5000;
|
|
6625
|
-
var
|
|
7064
|
+
var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
|
|
6626
7065
|
var STATES = new Set(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"]);
|
|
6627
7066
|
function defaultFormJournalPath() {
|
|
6628
|
-
return process.env.QQ_FORM_JOURNAL_FILE ||
|
|
7067
|
+
return process.env.QQ_FORM_JOURNAL_FILE || join11(homedir10(), ".openqq", "forms.json");
|
|
6629
7068
|
}
|
|
6630
7069
|
function minimalFormContext(ctx) {
|
|
6631
7070
|
return {
|
|
@@ -6678,9 +7117,9 @@ function snapshot(entry) {
|
|
|
6678
7117
|
function createFormJournal(path = defaultFormJournalPath()) {
|
|
6679
7118
|
function read() {
|
|
6680
7119
|
try {
|
|
6681
|
-
if (!
|
|
7120
|
+
if (!existsSync9(path))
|
|
6682
7121
|
return [];
|
|
6683
|
-
const raw = JSON.parse(
|
|
7122
|
+
const raw = JSON.parse(readFileSync11(path, "utf-8"));
|
|
6684
7123
|
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
6685
7124
|
const byUser = new Map;
|
|
6686
7125
|
for (const value of values) {
|
|
@@ -6698,50 +7137,50 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
6698
7137
|
}
|
|
6699
7138
|
}
|
|
6700
7139
|
function write(entries) {
|
|
6701
|
-
|
|
7140
|
+
mkdirSync9(dirname2(path), { recursive: true });
|
|
6702
7141
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6703
7142
|
const payload = { version: 1, entries: entries.map(snapshot) };
|
|
6704
7143
|
try {
|
|
6705
|
-
|
|
6706
|
-
|
|
7144
|
+
writeFileSync11(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
|
|
7145
|
+
renameSync4(tmp, path);
|
|
6707
7146
|
} catch (error) {
|
|
6708
7147
|
try {
|
|
6709
|
-
|
|
7148
|
+
unlinkSync5(tmp);
|
|
6710
7149
|
} catch {}
|
|
6711
7150
|
throw error;
|
|
6712
7151
|
}
|
|
6713
7152
|
}
|
|
6714
7153
|
function withLock(fn) {
|
|
6715
|
-
|
|
7154
|
+
mkdirSync9(dirname2(path), { recursive: true });
|
|
6716
7155
|
const lockPath = `${path}.lock`;
|
|
6717
7156
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6718
7157
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
6719
7158
|
for (;; ) {
|
|
6720
7159
|
try {
|
|
6721
|
-
const fd =
|
|
7160
|
+
const fd = openSync3(lockPath, "wx", 384);
|
|
6722
7161
|
try {
|
|
6723
|
-
|
|
7162
|
+
writeFileSync11(fd, token);
|
|
6724
7163
|
} finally {
|
|
6725
|
-
|
|
7164
|
+
closeSync3(fd);
|
|
6726
7165
|
}
|
|
6727
7166
|
break;
|
|
6728
7167
|
} catch (error) {
|
|
6729
7168
|
try {
|
|
6730
|
-
if (Date.now() -
|
|
6731
|
-
|
|
7169
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
7170
|
+
unlinkSync5(lockPath);
|
|
6732
7171
|
} catch {}
|
|
6733
7172
|
if (Date.now() >= deadline) {
|
|
6734
7173
|
throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6735
7174
|
}
|
|
6736
|
-
Atomics.wait(
|
|
7175
|
+
Atomics.wait(sleepArray2, 0, 0, 10);
|
|
6737
7176
|
}
|
|
6738
7177
|
}
|
|
6739
7178
|
try {
|
|
6740
7179
|
return fn();
|
|
6741
7180
|
} finally {
|
|
6742
7181
|
try {
|
|
6743
|
-
if (
|
|
6744
|
-
|
|
7182
|
+
if (readFileSync11(lockPath, "utf-8") === token)
|
|
7183
|
+
unlinkSync5(lockPath);
|
|
6745
7184
|
} catch {}
|
|
6746
7185
|
}
|
|
6747
7186
|
}
|
|
@@ -7014,7 +7453,7 @@ function createFormBridge(deps) {
|
|
|
7014
7453
|
if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
|
|
7015
7454
|
if (isCurrent(userId, entry))
|
|
7016
7455
|
clearEntry(userId, entry);
|
|
7017
|
-
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ
|
|
7456
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效;若 AI 再次询问你会立即收到新卡片,也可回桌面处理");
|
|
7018
7457
|
} else {
|
|
7019
7458
|
await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`);
|
|
7020
7459
|
}
|
|
@@ -7067,7 +7506,7 @@ function createFormBridge(deps) {
|
|
|
7067
7506
|
}
|
|
7068
7507
|
clearEntry(userId, entry);
|
|
7069
7508
|
}
|
|
7070
|
-
await deliver(entry.ctx, "⏰ 选择请求已满 30
|
|
7509
|
+
await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;若 AI 再次询问你会立即收到新卡片,也可回桌面处理");
|
|
7071
7510
|
}
|
|
7072
7511
|
function scheduleExpiry(userId, entry) {
|
|
7073
7512
|
if (!accepting)
|
|
@@ -7303,9 +7742,9 @@ function createFormBridge(deps) {
|
|
|
7303
7742
|
}
|
|
7304
7743
|
|
|
7305
7744
|
// src/core/inflight-journal.ts
|
|
7306
|
-
import { existsSync as
|
|
7307
|
-
import { join as
|
|
7308
|
-
import { homedir as
|
|
7745
|
+
import { existsSync as existsSync10, readFileSync as readFileSync12, writeFileSync as writeFileSync12, mkdirSync as mkdirSync10, renameSync as renameSync5, openSync as openSync4, closeSync as closeSync4, unlinkSync as unlinkSync6, statSync as statSync6 } from "fs";
|
|
7746
|
+
import { join as join12 } from "path";
|
|
7747
|
+
import { homedir as homedir11 } from "os";
|
|
7309
7748
|
|
|
7310
7749
|
// src/core/inbound-dedupe.ts
|
|
7311
7750
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -7338,13 +7777,13 @@ function redispatchMaxAgeMs() {
|
|
|
7338
7777
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7200000;
|
|
7339
7778
|
}
|
|
7340
7779
|
function journalPath() {
|
|
7341
|
-
return process.env.QQ_INFLIGHT_FILE ||
|
|
7780
|
+
return process.env.QQ_INFLIGHT_FILE || join12(homedir11(), ".openqq", "inflight.json");
|
|
7342
7781
|
}
|
|
7343
7782
|
function load() {
|
|
7344
7783
|
let entries = [];
|
|
7345
7784
|
try {
|
|
7346
|
-
if (
|
|
7347
|
-
const raw = JSON.parse(
|
|
7785
|
+
if (existsSync10(journalPath())) {
|
|
7786
|
+
const raw = JSON.parse(readFileSync12(journalPath(), "utf-8"));
|
|
7348
7787
|
if (Array.isArray(raw))
|
|
7349
7788
|
entries = raw;
|
|
7350
7789
|
}
|
|
@@ -7355,54 +7794,54 @@ function load() {
|
|
|
7355
7794
|
}
|
|
7356
7795
|
function save(entries) {
|
|
7357
7796
|
const path = journalPath();
|
|
7358
|
-
|
|
7797
|
+
mkdirSync10(join12(path, ".."), { recursive: true });
|
|
7359
7798
|
const retained = pruneInflightEntries(entries);
|
|
7360
7799
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
7361
7800
|
try {
|
|
7362
|
-
|
|
7363
|
-
|
|
7801
|
+
writeFileSync12(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
|
|
7802
|
+
renameSync5(tmp, path);
|
|
7364
7803
|
} catch (error) {
|
|
7365
7804
|
try {
|
|
7366
|
-
|
|
7805
|
+
unlinkSync6(tmp);
|
|
7367
7806
|
} catch {}
|
|
7368
7807
|
throw error;
|
|
7369
7808
|
}
|
|
7370
7809
|
}
|
|
7371
7810
|
var JOURNAL_LOCK_STALE_MS = 30000;
|
|
7372
7811
|
var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
7373
|
-
var
|
|
7812
|
+
var sleepArray3 = new Int32Array(new SharedArrayBuffer(4));
|
|
7374
7813
|
function withJournalLock(fn) {
|
|
7375
7814
|
const path = journalPath();
|
|
7376
|
-
|
|
7815
|
+
mkdirSync10(join12(path, ".."), { recursive: true });
|
|
7377
7816
|
const lockPath = `${path}.lock`;
|
|
7378
7817
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
7379
7818
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
7380
7819
|
for (;; ) {
|
|
7381
7820
|
try {
|
|
7382
|
-
const fd =
|
|
7821
|
+
const fd = openSync4(lockPath, "wx", 384);
|
|
7383
7822
|
try {
|
|
7384
|
-
|
|
7823
|
+
writeFileSync12(fd, token);
|
|
7385
7824
|
} finally {
|
|
7386
|
-
|
|
7825
|
+
closeSync4(fd);
|
|
7387
7826
|
}
|
|
7388
7827
|
break;
|
|
7389
7828
|
} catch (error) {
|
|
7390
7829
|
try {
|
|
7391
|
-
if (Date.now() -
|
|
7392
|
-
|
|
7830
|
+
if (Date.now() - statSync6(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
7831
|
+
unlinkSync6(lockPath);
|
|
7393
7832
|
} catch {}
|
|
7394
7833
|
if (Date.now() >= deadline) {
|
|
7395
7834
|
throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
7396
7835
|
}
|
|
7397
|
-
Atomics.wait(
|
|
7836
|
+
Atomics.wait(sleepArray3, 0, 0, 10);
|
|
7398
7837
|
}
|
|
7399
7838
|
}
|
|
7400
7839
|
try {
|
|
7401
7840
|
return fn();
|
|
7402
7841
|
} finally {
|
|
7403
7842
|
try {
|
|
7404
|
-
if (
|
|
7405
|
-
|
|
7843
|
+
if (readFileSync12(lockPath, "utf-8") === token)
|
|
7844
|
+
unlinkSync6(lockPath);
|
|
7406
7845
|
} catch {}
|
|
7407
7846
|
}
|
|
7408
7847
|
}
|
|
@@ -7476,9 +7915,10 @@ function markInflightPromptId(msgId, promptId) {
|
|
|
7476
7915
|
});
|
|
7477
7916
|
}
|
|
7478
7917
|
var TIME_ANCHOR_TOLERANCE_MS = 120000;
|
|
7918
|
+
var PROBE_LENGTH = 100;
|
|
7479
7919
|
function classifyInflight(entry, messages) {
|
|
7480
7920
|
const ordered = [...messages].reverse();
|
|
7481
|
-
const probe = entry.text.trim().slice(0,
|
|
7921
|
+
const probe = entry.text.trim().slice(0, PROBE_LENGTH);
|
|
7482
7922
|
let userIdx = -1;
|
|
7483
7923
|
if (probe === "") {
|
|
7484
7924
|
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
@@ -7495,6 +7935,21 @@ function classifyInflight(entry, messages) {
|
|
|
7495
7935
|
}
|
|
7496
7936
|
}
|
|
7497
7937
|
}
|
|
7938
|
+
if (userIdx < 0 && probe === "" && entry.at !== undefined) {
|
|
7939
|
+
let bestIdx = -1;
|
|
7940
|
+
let bestDelta = Number.POSITIVE_INFINITY;
|
|
7941
|
+
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
7942
|
+
if (ordered[i].type !== "user")
|
|
7943
|
+
continue;
|
|
7944
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - entry.at);
|
|
7945
|
+
if (delta < bestDelta) {
|
|
7946
|
+
bestDelta = delta;
|
|
7947
|
+
bestIdx = i;
|
|
7948
|
+
}
|
|
7949
|
+
}
|
|
7950
|
+
if (bestIdx >= 0 && bestDelta <= TIME_ANCHOR_TOLERANCE_MS)
|
|
7951
|
+
userIdx = bestIdx;
|
|
7952
|
+
}
|
|
7498
7953
|
if (userIdx < 0 && entry.at !== undefined) {
|
|
7499
7954
|
let bestIdx = -1;
|
|
7500
7955
|
let bestDelta = Number.POSITIVE_INFINITY;
|
|
@@ -7776,6 +8231,13 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7776
8231
|
}
|
|
7777
8232
|
};
|
|
7778
8233
|
const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(config, lastCtx);
|
|
8234
|
+
const notifyUser = async (ctx, text) => {
|
|
8235
|
+
try {
|
|
8236
|
+
await sendReply(ctx, text);
|
|
8237
|
+
} catch (error) {
|
|
8238
|
+
console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage2(error));
|
|
8239
|
+
}
|
|
8240
|
+
};
|
|
7779
8241
|
const perm = createPermissionGate({
|
|
7780
8242
|
client,
|
|
7781
8243
|
sendReply,
|
|
@@ -7783,6 +8245,11 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7783
8245
|
sendApprovalPrompt: (ctx, request, mainSessionId) => sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId)
|
|
7784
8246
|
});
|
|
7785
8247
|
const mirror = createMirror({ sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers });
|
|
8248
|
+
createNotifySink({
|
|
8249
|
+
config,
|
|
8250
|
+
deliver: (ctx, text) => deliver(ctx, text),
|
|
8251
|
+
...process.env.QQ_OUTBOX_FILE ? { filePath: process.env.QQ_OUTBOX_FILE } : {}
|
|
8252
|
+
});
|
|
7786
8253
|
const formBridge = createFormBridge({
|
|
7787
8254
|
client,
|
|
7788
8255
|
sendReply,
|
|
@@ -7920,7 +8387,8 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7920
8387
|
const intentKey = intentKeyOf(ctx);
|
|
7921
8388
|
try {
|
|
7922
8389
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
7923
|
-
|
|
8390
|
+
console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`);
|
|
8391
|
+
await notifyUser(ctx, "你不在允许使用的名单里");
|
|
7924
8392
|
return;
|
|
7925
8393
|
}
|
|
7926
8394
|
const content = ctx.content.trim();
|
|
@@ -7931,7 +8399,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7931
8399
|
if (!greeted.has(ctx.userId) && !isCommand(content)) {
|
|
7932
8400
|
greeted.add(ctx.userId);
|
|
7933
8401
|
saveGreetedSet(greeted);
|
|
7934
|
-
await
|
|
8402
|
+
await notifyUser(ctx, buildHelpText());
|
|
7935
8403
|
}
|
|
7936
8404
|
const decision = parsePermissionDecision(content);
|
|
7937
8405
|
if (decision && perm.hasPending(ctx.userId)) {
|
|
@@ -7943,17 +8411,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7943
8411
|
}
|
|
7944
8412
|
if (isCommand(content)) {
|
|
7945
8413
|
const reply = await handleCommand(ctx, commandContext);
|
|
7946
|
-
await
|
|
8414
|
+
await notifyUser(ctx, reply);
|
|
7947
8415
|
return;
|
|
7948
8416
|
}
|
|
7949
8417
|
const pendingReply = await maybeHandlePendingSelection(ctx, commandContext);
|
|
7950
8418
|
if (pendingReply !== null) {
|
|
7951
|
-
await
|
|
8419
|
+
await notifyUser(ctx, pendingReply);
|
|
7952
8420
|
return;
|
|
7953
8421
|
}
|
|
7954
8422
|
const pendingPerm = perm.getPending(ctx.userId);
|
|
7955
8423
|
if (pendingPerm) {
|
|
7956
|
-
await
|
|
8424
|
+
await notifyUser(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId));
|
|
7957
8425
|
return;
|
|
7958
8426
|
}
|
|
7959
8427
|
if (ctx.msgId) {
|
|
@@ -7965,7 +8433,9 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7965
8433
|
}
|
|
7966
8434
|
if (admitted === "duplicate-intent") {
|
|
7967
8435
|
console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`);
|
|
7968
|
-
|
|
8436
|
+
const pend = pendingInflight().find((e) => e.fingerprint === messageFingerprint(ctx.userId, intentKey));
|
|
8437
|
+
const digest = pend ? `(在途内容:${previewText(pend.text)})` : "";
|
|
8438
|
+
await notifyUser(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`);
|
|
7969
8439
|
return;
|
|
7970
8440
|
}
|
|
7971
8441
|
claimedContexts.add(ctx);
|
|
@@ -7988,17 +8458,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7988
8458
|
if (!queued) {
|
|
7989
8459
|
if (claimedMsgId)
|
|
7990
8460
|
settleInflight(claimedMsgId);
|
|
7991
|
-
await
|
|
8461
|
+
await notifyUser(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`);
|
|
7992
8462
|
return;
|
|
7993
8463
|
}
|
|
7994
|
-
await
|
|
8464
|
+
await notifyUser(ctx, `已排队 #${queued.job.id}${queued.ahead > 0 ? `(前面还有 ${queued.ahead} 条)` : ""},当前任务结束后自动执行。
|
|
7995
8465
|
发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
|
|
7996
8466
|
return;
|
|
7997
8467
|
}
|
|
7998
8468
|
activeIntents.set(ctx.userId, intentKey);
|
|
7999
8469
|
busyUsers.add(ctx.userId);
|
|
8000
8470
|
if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
|
|
8001
|
-
await
|
|
8471
|
+
await notifyUser(ctx, "✅ 已收到,正在处理,完成后自动回复你");
|
|
8002
8472
|
}
|
|
8003
8473
|
if (ctx.type === "c2c" && ctx.msgId) {
|
|
8004
8474
|
getAccessToken(config.qq.appId, config.qq.clientSecret).then((token) => sendC2CInputNotify(token, ctx.userId, ctx.msgId, 60)).catch(() => {});
|
|
@@ -8038,7 +8508,7 @@ ${promptBody}` : promptBody;
|
|
|
8038
8508
|
safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`);
|
|
8039
8509
|
},
|
|
8040
8510
|
onPermissionConflict: () => {
|
|
8041
|
-
safeDeliver(ctx, "⚠️
|
|
8511
|
+
safeDeliver(ctx, "⚠️ 该审批请求状态不明(可能在桌面端处理或已超时)。如命令未执行,请重新发起原操作");
|
|
8042
8512
|
}
|
|
8043
8513
|
});
|
|
8044
8514
|
if (replyText.trim()) {
|
|
@@ -8145,7 +8615,7 @@ ${cls.answer}`);
|
|
|
8145
8615
|
return;
|
|
8146
8616
|
draining.add(userId);
|
|
8147
8617
|
try {
|
|
8148
|
-
await
|
|
8618
|
+
await notifyUser(job.ctx, `开始执行队列 #${job.id}`);
|
|
8149
8619
|
drainReentries.add(job.ctx);
|
|
8150
8620
|
await handleMessage(job.ctx);
|
|
8151
8621
|
} catch (error) {
|
|
@@ -8201,11 +8671,11 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
8201
8671
|
return false;
|
|
8202
8672
|
return allowedUsers.includes(userId);
|
|
8203
8673
|
}
|
|
8204
|
-
var WATCH_FILE =
|
|
8674
|
+
var WATCH_FILE = join13(homedir12(), ".openqq", "watch.json");
|
|
8205
8675
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
8206
8676
|
try {
|
|
8207
|
-
if (
|
|
8208
|
-
const raw =
|
|
8677
|
+
if (existsSync11(file)) {
|
|
8678
|
+
const raw = readFileSync13(file, "utf-8");
|
|
8209
8679
|
const obj = JSON.parse(raw);
|
|
8210
8680
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
8211
8681
|
const out = {};
|
|
@@ -8220,16 +8690,16 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
8220
8690
|
}
|
|
8221
8691
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
8222
8692
|
try {
|
|
8223
|
-
|
|
8693
|
+
writeFileSync13(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
8224
8694
|
} catch (error) {
|
|
8225
8695
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
8226
8696
|
}
|
|
8227
8697
|
}
|
|
8228
|
-
var GREETED_FILE =
|
|
8698
|
+
var GREETED_FILE = join13(homedir12(), ".openqq", "greeted.json");
|
|
8229
8699
|
function loadGreetedSet() {
|
|
8230
8700
|
try {
|
|
8231
|
-
if (
|
|
8232
|
-
const raw =
|
|
8701
|
+
if (existsSync11(GREETED_FILE)) {
|
|
8702
|
+
const raw = readFileSync13(GREETED_FILE, "utf-8");
|
|
8233
8703
|
const arr = JSON.parse(raw);
|
|
8234
8704
|
if (Array.isArray(arr)) {
|
|
8235
8705
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -8240,8 +8710,8 @@ function loadGreetedSet() {
|
|
|
8240
8710
|
}
|
|
8241
8711
|
function saveGreetedSet(set) {
|
|
8242
8712
|
try {
|
|
8243
|
-
|
|
8244
|
-
|
|
8713
|
+
mkdirSync11(join13(homedir12(), ".openqq"), { recursive: true });
|
|
8714
|
+
writeFileSync13(GREETED_FILE, JSON.stringify([...set]));
|
|
8245
8715
|
} catch (error) {
|
|
8246
8716
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
8247
8717
|
}
|
|
@@ -8292,36 +8762,38 @@ function toErrorMessage2(error) {
|
|
|
8292
8762
|
}
|
|
8293
8763
|
|
|
8294
8764
|
// src/core/instance-lock.ts
|
|
8295
|
-
import { openSync as
|
|
8296
|
-
import { join as
|
|
8297
|
-
import { homedir as
|
|
8765
|
+
import { openSync as openSync5, readFileSync as readFileSync14, writeFileSync as writeFileSync14, closeSync as closeSync5, unlinkSync as unlinkSync7, statSync as statSync7, utimesSync, mkdirSync as mkdirSync12 } from "fs";
|
|
8766
|
+
import { join as join14 } from "path";
|
|
8767
|
+
import { homedir as homedir13 } from "os";
|
|
8298
8768
|
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
8299
8769
|
var LOCK_STALE_MS2 = 30000;
|
|
8300
8770
|
var LOCK_UPDATE_MS = 1e4;
|
|
8301
8771
|
var LOCK_RETRY_MS = 5000;
|
|
8302
8772
|
var LOCK_SELF_CHECK_MS = 60000;
|
|
8303
8773
|
function lockPathOf(appId) {
|
|
8304
|
-
return
|
|
8774
|
+
return join14(homedir13(), ".openqq", `openqq-${appId}.lock`);
|
|
8305
8775
|
}
|
|
8306
8776
|
function touch(path) {
|
|
8307
8777
|
const now = new Date;
|
|
8308
8778
|
utimesSync(path, now, now);
|
|
8309
8779
|
}
|
|
8310
|
-
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
8780
|
+
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
|
|
8781
|
+
const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS;
|
|
8782
|
+
const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS;
|
|
8311
8783
|
try {
|
|
8312
|
-
|
|
8313
|
-
const fd =
|
|
8314
|
-
|
|
8315
|
-
|
|
8784
|
+
mkdirSync12(join14(path, ".."), { recursive: true });
|
|
8785
|
+
const fd = openSync5(path, "wx");
|
|
8786
|
+
writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
8787
|
+
closeSync5(fd);
|
|
8316
8788
|
} catch {
|
|
8317
8789
|
try {
|
|
8318
|
-
const age = Date.now() -
|
|
8790
|
+
const age = Date.now() - statSync7(path).mtimeMs;
|
|
8319
8791
|
if (age <= staleMs)
|
|
8320
8792
|
return null;
|
|
8321
|
-
|
|
8322
|
-
const fd =
|
|
8323
|
-
|
|
8324
|
-
|
|
8793
|
+
unlinkSync7(path);
|
|
8794
|
+
const fd = openSync5(path, "wx");
|
|
8795
|
+
writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
8796
|
+
closeSync5(fd);
|
|
8325
8797
|
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
8326
8798
|
} catch {
|
|
8327
8799
|
return null;
|
|
@@ -8331,11 +8803,11 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
|
8331
8803
|
try {
|
|
8332
8804
|
touch(path);
|
|
8333
8805
|
} catch {}
|
|
8334
|
-
},
|
|
8806
|
+
}, heartbeatMs);
|
|
8335
8807
|
heartbeat.unref?.();
|
|
8336
8808
|
const selfCheck = setInterval(() => {
|
|
8337
8809
|
try {
|
|
8338
|
-
const holder = JSON.parse(
|
|
8810
|
+
const holder = JSON.parse(readFileSync14(path, "utf-8")).pid;
|
|
8339
8811
|
if (holder === process.pid)
|
|
8340
8812
|
return;
|
|
8341
8813
|
try {
|
|
@@ -8347,7 +8819,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
|
8347
8819
|
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
8348
8820
|
process.exit(1);
|
|
8349
8821
|
}
|
|
8350
|
-
},
|
|
8822
|
+
}, selfCheckMs);
|
|
8351
8823
|
selfCheck.unref?.();
|
|
8352
8824
|
let released = false;
|
|
8353
8825
|
return {
|
|
@@ -8358,7 +8830,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
|
8358
8830
|
clearInterval(heartbeat);
|
|
8359
8831
|
clearInterval(selfCheck);
|
|
8360
8832
|
try {
|
|
8361
|
-
|
|
8833
|
+
unlinkSync7(path);
|
|
8362
8834
|
} catch {}
|
|
8363
8835
|
}
|
|
8364
8836
|
};
|
|
@@ -8460,11 +8932,11 @@ async function main() {
|
|
|
8460
8932
|
});
|
|
8461
8933
|
console.log("[index] OpenCode QQ Bot 已启动");
|
|
8462
8934
|
bridge.recoverInflightRounds();
|
|
8463
|
-
const heartbeatFile =
|
|
8935
|
+
const heartbeatFile = join16(homedir14(), ".openqq", "heartbeat");
|
|
8464
8936
|
const touchHeartbeat = () => {
|
|
8465
8937
|
try {
|
|
8466
|
-
|
|
8467
|
-
|
|
8938
|
+
mkdirSync14(join16(homedir14(), ".openqq"), { recursive: true });
|
|
8939
|
+
writeFileSync15(heartbeatFile, String(Date.now()));
|
|
8468
8940
|
} catch (error) {
|
|
8469
8941
|
console.error("[index] 心跳写入失败:", error);
|
|
8470
8942
|
}
|