@linjz/opencode-qqbot 0.3.14 → 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 +31 -0
- package/bin/openqq.js +21 -0
- package/dist/notify-cli.js +579 -0
- package/dist/opencode-qqbot-plugin.js +4 -1
- package/dist/openqq-bot.js +555 -105
- package/package.json +5 -4
- package/src/bridge.ts +32 -11
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +158 -0
- package/src/config.ts +2 -2
- package/src/core/form-bridge.ts +2 -2
- 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/plugin-entry.ts +4 -1
- package/src/qq/gateway.ts +1 -1
- package/src/qq/media.ts +5 -1
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}
|
|
@@ -3085,9 +3085,9 @@ function loadConfig() {
|
|
|
3085
3085
|
}
|
|
3086
3086
|
|
|
3087
3087
|
// src/index.ts
|
|
3088
|
-
import { mkdirSync as
|
|
3089
|
-
import { join as
|
|
3090
|
-
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";
|
|
3091
3091
|
|
|
3092
3092
|
// src/opencode/client.ts
|
|
3093
3093
|
function turnTimeoutMinutes() {
|
|
@@ -4197,7 +4197,7 @@ function briefAttachments(atts) {
|
|
|
4197
4197
|
try {
|
|
4198
4198
|
host = new URL(a.url).hostname;
|
|
4199
4199
|
} catch {}
|
|
4200
|
-
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 };
|
|
4201
4201
|
});
|
|
4202
4202
|
}
|
|
4203
4203
|
function toC2CMessageContext(event) {
|
|
@@ -4467,9 +4467,9 @@ async function startGateway(options) {
|
|
|
4467
4467
|
}
|
|
4468
4468
|
|
|
4469
4469
|
// src/bridge.ts
|
|
4470
|
-
import { existsSync as
|
|
4471
|
-
import { join as
|
|
4472
|
-
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";
|
|
4473
4473
|
|
|
4474
4474
|
// src/qq/media.ts
|
|
4475
4475
|
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync5 } from "node:fs";
|
|
@@ -4514,7 +4514,8 @@ async function fetchWithTimeout(url, ms, auth) {
|
|
|
4514
4514
|
}
|
|
4515
4515
|
async function downloadQQAttachment(att, getAuth) {
|
|
4516
4516
|
const ctype = (att.content_type || "").toLowerCase();
|
|
4517
|
-
|
|
4517
|
+
const isVoice = ctype.startsWith("audio/") || ctype === "voice" || ctype === "amr" || ctype.endsWith("/amr");
|
|
4518
|
+
if (isVoice && att.asr_refer_text?.trim()) {
|
|
4518
4519
|
return { voice: att.asr_refer_text.trim() };
|
|
4519
4520
|
}
|
|
4520
4521
|
const ext = extForImageMime(att.content_type || "");
|
|
@@ -5720,7 +5721,7 @@ function createPermissionGate(deps) {
|
|
|
5720
5721
|
pendingPermissions.delete(ctx.userId);
|
|
5721
5722
|
savePendingPermMap(pendingPermissions);
|
|
5722
5723
|
resolve("reject");
|
|
5723
|
-
|
|
5724
|
+
safeDeliver(ctx, "审批超时(30 分钟),已自动拒绝该权限请求").catch(() => {});
|
|
5724
5725
|
}
|
|
5725
5726
|
}, PERM_PROMPT_TTL_MS);
|
|
5726
5727
|
pendingPermissions.set(ctx.userId, {
|
|
@@ -6532,6 +6533,441 @@ function createDelivery(config, lastCtx) {
|
|
|
6532
6533
|
return { enqueuePush, deliver, safeDeliver, sendReply };
|
|
6533
6534
|
}
|
|
6534
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
|
+
|
|
6535
6971
|
// src/core/card-approval.ts
|
|
6536
6972
|
var BUTTON_LABEL_MAX = 10;
|
|
6537
6973
|
function encodeButtonData(data) {
|
|
@@ -6611,24 +7047,24 @@ function handleApprovalInteraction(event, gate) {
|
|
|
6611
7047
|
|
|
6612
7048
|
// src/core/form-journal.ts
|
|
6613
7049
|
import {
|
|
6614
|
-
closeSync as
|
|
6615
|
-
existsSync as
|
|
6616
|
-
mkdirSync as
|
|
6617
|
-
openSync as
|
|
6618
|
-
readFileSync as
|
|
6619
|
-
renameSync as
|
|
6620
|
-
statSync as
|
|
6621
|
-
unlinkSync as
|
|
6622
|
-
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
|
|
6623
7059
|
} from "fs";
|
|
6624
|
-
import { dirname, join as
|
|
6625
|
-
import { homedir as
|
|
7060
|
+
import { dirname as dirname2, join as join11 } from "path";
|
|
7061
|
+
import { homedir as homedir10 } from "os";
|
|
6626
7062
|
var LOCK_STALE_MS = 30000;
|
|
6627
7063
|
var LOCK_WAIT_MS = 5000;
|
|
6628
|
-
var
|
|
7064
|
+
var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
|
|
6629
7065
|
var STATES = new Set(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"]);
|
|
6630
7066
|
function defaultFormJournalPath() {
|
|
6631
|
-
return process.env.QQ_FORM_JOURNAL_FILE ||
|
|
7067
|
+
return process.env.QQ_FORM_JOURNAL_FILE || join11(homedir10(), ".openqq", "forms.json");
|
|
6632
7068
|
}
|
|
6633
7069
|
function minimalFormContext(ctx) {
|
|
6634
7070
|
return {
|
|
@@ -6681,9 +7117,9 @@ function snapshot(entry) {
|
|
|
6681
7117
|
function createFormJournal(path = defaultFormJournalPath()) {
|
|
6682
7118
|
function read() {
|
|
6683
7119
|
try {
|
|
6684
|
-
if (!
|
|
7120
|
+
if (!existsSync9(path))
|
|
6685
7121
|
return [];
|
|
6686
|
-
const raw = JSON.parse(
|
|
7122
|
+
const raw = JSON.parse(readFileSync11(path, "utf-8"));
|
|
6687
7123
|
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
6688
7124
|
const byUser = new Map;
|
|
6689
7125
|
for (const value of values) {
|
|
@@ -6701,50 +7137,50 @@ function createFormJournal(path = defaultFormJournalPath()) {
|
|
|
6701
7137
|
}
|
|
6702
7138
|
}
|
|
6703
7139
|
function write(entries) {
|
|
6704
|
-
|
|
7140
|
+
mkdirSync9(dirname2(path), { recursive: true });
|
|
6705
7141
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6706
7142
|
const payload = { version: 1, entries: entries.map(snapshot) };
|
|
6707
7143
|
try {
|
|
6708
|
-
|
|
6709
|
-
|
|
7144
|
+
writeFileSync11(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
|
|
7145
|
+
renameSync4(tmp, path);
|
|
6710
7146
|
} catch (error) {
|
|
6711
7147
|
try {
|
|
6712
|
-
|
|
7148
|
+
unlinkSync5(tmp);
|
|
6713
7149
|
} catch {}
|
|
6714
7150
|
throw error;
|
|
6715
7151
|
}
|
|
6716
7152
|
}
|
|
6717
7153
|
function withLock(fn) {
|
|
6718
|
-
|
|
7154
|
+
mkdirSync9(dirname2(path), { recursive: true });
|
|
6719
7155
|
const lockPath = `${path}.lock`;
|
|
6720
7156
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6721
7157
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
6722
7158
|
for (;; ) {
|
|
6723
7159
|
try {
|
|
6724
|
-
const fd =
|
|
7160
|
+
const fd = openSync3(lockPath, "wx", 384);
|
|
6725
7161
|
try {
|
|
6726
|
-
|
|
7162
|
+
writeFileSync11(fd, token);
|
|
6727
7163
|
} finally {
|
|
6728
|
-
|
|
7164
|
+
closeSync3(fd);
|
|
6729
7165
|
}
|
|
6730
7166
|
break;
|
|
6731
7167
|
} catch (error) {
|
|
6732
7168
|
try {
|
|
6733
|
-
if (Date.now() -
|
|
6734
|
-
|
|
7169
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
7170
|
+
unlinkSync5(lockPath);
|
|
6735
7171
|
} catch {}
|
|
6736
7172
|
if (Date.now() >= deadline) {
|
|
6737
7173
|
throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6738
7174
|
}
|
|
6739
|
-
Atomics.wait(
|
|
7175
|
+
Atomics.wait(sleepArray2, 0, 0, 10);
|
|
6740
7176
|
}
|
|
6741
7177
|
}
|
|
6742
7178
|
try {
|
|
6743
7179
|
return fn();
|
|
6744
7180
|
} finally {
|
|
6745
7181
|
try {
|
|
6746
|
-
if (
|
|
6747
|
-
|
|
7182
|
+
if (readFileSync11(lockPath, "utf-8") === token)
|
|
7183
|
+
unlinkSync5(lockPath);
|
|
6748
7184
|
} catch {}
|
|
6749
7185
|
}
|
|
6750
7186
|
}
|
|
@@ -7017,7 +7453,7 @@ function createFormBridge(deps) {
|
|
|
7017
7453
|
if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
|
|
7018
7454
|
if (isCurrent(userId, entry))
|
|
7019
7455
|
clearEntry(userId, entry);
|
|
7020
|
-
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ
|
|
7456
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效;若 AI 再次询问你会立即收到新卡片,也可回桌面处理");
|
|
7021
7457
|
} else {
|
|
7022
7458
|
await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`);
|
|
7023
7459
|
}
|
|
@@ -7070,7 +7506,7 @@ function createFormBridge(deps) {
|
|
|
7070
7506
|
}
|
|
7071
7507
|
clearEntry(userId, entry);
|
|
7072
7508
|
}
|
|
7073
|
-
await deliver(entry.ctx, "⏰ 选择请求已满 30
|
|
7509
|
+
await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;若 AI 再次询问你会立即收到新卡片,也可回桌面处理");
|
|
7074
7510
|
}
|
|
7075
7511
|
function scheduleExpiry(userId, entry) {
|
|
7076
7512
|
if (!accepting)
|
|
@@ -7306,9 +7742,9 @@ function createFormBridge(deps) {
|
|
|
7306
7742
|
}
|
|
7307
7743
|
|
|
7308
7744
|
// src/core/inflight-journal.ts
|
|
7309
|
-
import { existsSync as
|
|
7310
|
-
import { join as
|
|
7311
|
-
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";
|
|
7312
7748
|
|
|
7313
7749
|
// src/core/inbound-dedupe.ts
|
|
7314
7750
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -7341,13 +7777,13 @@ function redispatchMaxAgeMs() {
|
|
|
7341
7777
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7200000;
|
|
7342
7778
|
}
|
|
7343
7779
|
function journalPath() {
|
|
7344
|
-
return process.env.QQ_INFLIGHT_FILE ||
|
|
7780
|
+
return process.env.QQ_INFLIGHT_FILE || join12(homedir11(), ".openqq", "inflight.json");
|
|
7345
7781
|
}
|
|
7346
7782
|
function load() {
|
|
7347
7783
|
let entries = [];
|
|
7348
7784
|
try {
|
|
7349
|
-
if (
|
|
7350
|
-
const raw = JSON.parse(
|
|
7785
|
+
if (existsSync10(journalPath())) {
|
|
7786
|
+
const raw = JSON.parse(readFileSync12(journalPath(), "utf-8"));
|
|
7351
7787
|
if (Array.isArray(raw))
|
|
7352
7788
|
entries = raw;
|
|
7353
7789
|
}
|
|
@@ -7358,54 +7794,54 @@ function load() {
|
|
|
7358
7794
|
}
|
|
7359
7795
|
function save(entries) {
|
|
7360
7796
|
const path = journalPath();
|
|
7361
|
-
|
|
7797
|
+
mkdirSync10(join12(path, ".."), { recursive: true });
|
|
7362
7798
|
const retained = pruneInflightEntries(entries);
|
|
7363
7799
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
7364
7800
|
try {
|
|
7365
|
-
|
|
7366
|
-
|
|
7801
|
+
writeFileSync12(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
|
|
7802
|
+
renameSync5(tmp, path);
|
|
7367
7803
|
} catch (error) {
|
|
7368
7804
|
try {
|
|
7369
|
-
|
|
7805
|
+
unlinkSync6(tmp);
|
|
7370
7806
|
} catch {}
|
|
7371
7807
|
throw error;
|
|
7372
7808
|
}
|
|
7373
7809
|
}
|
|
7374
7810
|
var JOURNAL_LOCK_STALE_MS = 30000;
|
|
7375
7811
|
var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
7376
|
-
var
|
|
7812
|
+
var sleepArray3 = new Int32Array(new SharedArrayBuffer(4));
|
|
7377
7813
|
function withJournalLock(fn) {
|
|
7378
7814
|
const path = journalPath();
|
|
7379
|
-
|
|
7815
|
+
mkdirSync10(join12(path, ".."), { recursive: true });
|
|
7380
7816
|
const lockPath = `${path}.lock`;
|
|
7381
7817
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
7382
7818
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
7383
7819
|
for (;; ) {
|
|
7384
7820
|
try {
|
|
7385
|
-
const fd =
|
|
7821
|
+
const fd = openSync4(lockPath, "wx", 384);
|
|
7386
7822
|
try {
|
|
7387
|
-
|
|
7823
|
+
writeFileSync12(fd, token);
|
|
7388
7824
|
} finally {
|
|
7389
|
-
|
|
7825
|
+
closeSync4(fd);
|
|
7390
7826
|
}
|
|
7391
7827
|
break;
|
|
7392
7828
|
} catch (error) {
|
|
7393
7829
|
try {
|
|
7394
|
-
if (Date.now() -
|
|
7395
|
-
|
|
7830
|
+
if (Date.now() - statSync6(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
7831
|
+
unlinkSync6(lockPath);
|
|
7396
7832
|
} catch {}
|
|
7397
7833
|
if (Date.now() >= deadline) {
|
|
7398
7834
|
throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
7399
7835
|
}
|
|
7400
|
-
Atomics.wait(
|
|
7836
|
+
Atomics.wait(sleepArray3, 0, 0, 10);
|
|
7401
7837
|
}
|
|
7402
7838
|
}
|
|
7403
7839
|
try {
|
|
7404
7840
|
return fn();
|
|
7405
7841
|
} finally {
|
|
7406
7842
|
try {
|
|
7407
|
-
if (
|
|
7408
|
-
|
|
7843
|
+
if (readFileSync12(lockPath, "utf-8") === token)
|
|
7844
|
+
unlinkSync6(lockPath);
|
|
7409
7845
|
} catch {}
|
|
7410
7846
|
}
|
|
7411
7847
|
}
|
|
@@ -7795,6 +8231,13 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7795
8231
|
}
|
|
7796
8232
|
};
|
|
7797
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
|
+
};
|
|
7798
8241
|
const perm = createPermissionGate({
|
|
7799
8242
|
client,
|
|
7800
8243
|
sendReply,
|
|
@@ -7802,6 +8245,11 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7802
8245
|
sendApprovalPrompt: (ctx, request, mainSessionId) => sendApprovalCard({ appId: config.qq.appId, clientSecret: config.qq.clientSecret }, ctx, request, mainSessionId)
|
|
7803
8246
|
});
|
|
7804
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
|
+
});
|
|
7805
8253
|
const formBridge = createFormBridge({
|
|
7806
8254
|
client,
|
|
7807
8255
|
sendReply,
|
|
@@ -7940,7 +8388,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7940
8388
|
try {
|
|
7941
8389
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
7942
8390
|
console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`);
|
|
7943
|
-
await
|
|
8391
|
+
await notifyUser(ctx, "你不在允许使用的名单里");
|
|
7944
8392
|
return;
|
|
7945
8393
|
}
|
|
7946
8394
|
const content = ctx.content.trim();
|
|
@@ -7951,7 +8399,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7951
8399
|
if (!greeted.has(ctx.userId) && !isCommand(content)) {
|
|
7952
8400
|
greeted.add(ctx.userId);
|
|
7953
8401
|
saveGreetedSet(greeted);
|
|
7954
|
-
await
|
|
8402
|
+
await notifyUser(ctx, buildHelpText());
|
|
7955
8403
|
}
|
|
7956
8404
|
const decision = parsePermissionDecision(content);
|
|
7957
8405
|
if (decision && perm.hasPending(ctx.userId)) {
|
|
@@ -7963,17 +8411,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7963
8411
|
}
|
|
7964
8412
|
if (isCommand(content)) {
|
|
7965
8413
|
const reply = await handleCommand(ctx, commandContext);
|
|
7966
|
-
await
|
|
8414
|
+
await notifyUser(ctx, reply);
|
|
7967
8415
|
return;
|
|
7968
8416
|
}
|
|
7969
8417
|
const pendingReply = await maybeHandlePendingSelection(ctx, commandContext);
|
|
7970
8418
|
if (pendingReply !== null) {
|
|
7971
|
-
await
|
|
8419
|
+
await notifyUser(ctx, pendingReply);
|
|
7972
8420
|
return;
|
|
7973
8421
|
}
|
|
7974
8422
|
const pendingPerm = perm.getPending(ctx.userId);
|
|
7975
8423
|
if (pendingPerm) {
|
|
7976
|
-
await
|
|
8424
|
+
await notifyUser(ctx, formatPermissionPrompt(pendingPerm.request, pendingPerm.mainSessionId));
|
|
7977
8425
|
return;
|
|
7978
8426
|
}
|
|
7979
8427
|
if (ctx.msgId) {
|
|
@@ -7987,7 +8435,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7987
8435
|
console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`);
|
|
7988
8436
|
const pend = pendingInflight().find((e) => e.fingerprint === messageFingerprint(ctx.userId, intentKey));
|
|
7989
8437
|
const digest = pend ? `(在途内容:${previewText(pend.text)})` : "";
|
|
7990
|
-
await
|
|
8438
|
+
await notifyUser(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`);
|
|
7991
8439
|
return;
|
|
7992
8440
|
}
|
|
7993
8441
|
claimedContexts.add(ctx);
|
|
@@ -8010,17 +8458,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
8010
8458
|
if (!queued) {
|
|
8011
8459
|
if (claimedMsgId)
|
|
8012
8460
|
settleInflight(claimedMsgId);
|
|
8013
|
-
await
|
|
8461
|
+
await notifyUser(ctx, `排队已满(${QUEUE_MAX} 条),请稍候再试或 /cancel 中止当前任务`);
|
|
8014
8462
|
return;
|
|
8015
8463
|
}
|
|
8016
|
-
await
|
|
8464
|
+
await notifyUser(ctx, `已排队 #${queued.job.id}${queued.ahead > 0 ? `(前面还有 ${queued.ahead} 条)` : ""},当前任务结束后自动执行。
|
|
8017
8465
|
发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
|
|
8018
8466
|
return;
|
|
8019
8467
|
}
|
|
8020
8468
|
activeIntents.set(ctx.userId, intentKey);
|
|
8021
8469
|
busyUsers.add(ctx.userId);
|
|
8022
8470
|
if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
|
|
8023
|
-
await
|
|
8471
|
+
await notifyUser(ctx, "✅ 已收到,正在处理,完成后自动回复你");
|
|
8024
8472
|
}
|
|
8025
8473
|
if (ctx.type === "c2c" && ctx.msgId) {
|
|
8026
8474
|
getAccessToken(config.qq.appId, config.qq.clientSecret).then((token) => sendC2CInputNotify(token, ctx.userId, ctx.msgId, 60)).catch(() => {});
|
|
@@ -8060,7 +8508,7 @@ ${promptBody}` : promptBody;
|
|
|
8060
8508
|
safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`);
|
|
8061
8509
|
},
|
|
8062
8510
|
onPermissionConflict: () => {
|
|
8063
|
-
safeDeliver(ctx, "⚠️
|
|
8511
|
+
safeDeliver(ctx, "⚠️ 该审批请求状态不明(可能在桌面端处理或已超时)。如命令未执行,请重新发起原操作");
|
|
8064
8512
|
}
|
|
8065
8513
|
});
|
|
8066
8514
|
if (replyText.trim()) {
|
|
@@ -8167,7 +8615,7 @@ ${cls.answer}`);
|
|
|
8167
8615
|
return;
|
|
8168
8616
|
draining.add(userId);
|
|
8169
8617
|
try {
|
|
8170
|
-
await
|
|
8618
|
+
await notifyUser(job.ctx, `开始执行队列 #${job.id}`);
|
|
8171
8619
|
drainReentries.add(job.ctx);
|
|
8172
8620
|
await handleMessage(job.ctx);
|
|
8173
8621
|
} catch (error) {
|
|
@@ -8223,11 +8671,11 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
8223
8671
|
return false;
|
|
8224
8672
|
return allowedUsers.includes(userId);
|
|
8225
8673
|
}
|
|
8226
|
-
var WATCH_FILE =
|
|
8674
|
+
var WATCH_FILE = join13(homedir12(), ".openqq", "watch.json");
|
|
8227
8675
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
8228
8676
|
try {
|
|
8229
|
-
if (
|
|
8230
|
-
const raw =
|
|
8677
|
+
if (existsSync11(file)) {
|
|
8678
|
+
const raw = readFileSync13(file, "utf-8");
|
|
8231
8679
|
const obj = JSON.parse(raw);
|
|
8232
8680
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
8233
8681
|
const out = {};
|
|
@@ -8242,16 +8690,16 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
8242
8690
|
}
|
|
8243
8691
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
8244
8692
|
try {
|
|
8245
|
-
|
|
8693
|
+
writeFileSync13(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
8246
8694
|
} catch (error) {
|
|
8247
8695
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
8248
8696
|
}
|
|
8249
8697
|
}
|
|
8250
|
-
var GREETED_FILE =
|
|
8698
|
+
var GREETED_FILE = join13(homedir12(), ".openqq", "greeted.json");
|
|
8251
8699
|
function loadGreetedSet() {
|
|
8252
8700
|
try {
|
|
8253
|
-
if (
|
|
8254
|
-
const raw =
|
|
8701
|
+
if (existsSync11(GREETED_FILE)) {
|
|
8702
|
+
const raw = readFileSync13(GREETED_FILE, "utf-8");
|
|
8255
8703
|
const arr = JSON.parse(raw);
|
|
8256
8704
|
if (Array.isArray(arr)) {
|
|
8257
8705
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -8262,8 +8710,8 @@ function loadGreetedSet() {
|
|
|
8262
8710
|
}
|
|
8263
8711
|
function saveGreetedSet(set) {
|
|
8264
8712
|
try {
|
|
8265
|
-
|
|
8266
|
-
|
|
8713
|
+
mkdirSync11(join13(homedir12(), ".openqq"), { recursive: true });
|
|
8714
|
+
writeFileSync13(GREETED_FILE, JSON.stringify([...set]));
|
|
8267
8715
|
} catch (error) {
|
|
8268
8716
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
8269
8717
|
}
|
|
@@ -8314,36 +8762,38 @@ function toErrorMessage2(error) {
|
|
|
8314
8762
|
}
|
|
8315
8763
|
|
|
8316
8764
|
// src/core/instance-lock.ts
|
|
8317
|
-
import { openSync as
|
|
8318
|
-
import { join as
|
|
8319
|
-
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";
|
|
8320
8768
|
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
8321
8769
|
var LOCK_STALE_MS2 = 30000;
|
|
8322
8770
|
var LOCK_UPDATE_MS = 1e4;
|
|
8323
8771
|
var LOCK_RETRY_MS = 5000;
|
|
8324
8772
|
var LOCK_SELF_CHECK_MS = 60000;
|
|
8325
8773
|
function lockPathOf(appId) {
|
|
8326
|
-
return
|
|
8774
|
+
return join14(homedir13(), ".openqq", `openqq-${appId}.lock`);
|
|
8327
8775
|
}
|
|
8328
8776
|
function touch(path) {
|
|
8329
8777
|
const now = new Date;
|
|
8330
8778
|
utimesSync(path, now, now);
|
|
8331
8779
|
}
|
|
8332
|
-
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;
|
|
8333
8783
|
try {
|
|
8334
|
-
|
|
8335
|
-
const fd =
|
|
8336
|
-
|
|
8337
|
-
|
|
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);
|
|
8338
8788
|
} catch {
|
|
8339
8789
|
try {
|
|
8340
|
-
const age = Date.now() -
|
|
8790
|
+
const age = Date.now() - statSync7(path).mtimeMs;
|
|
8341
8791
|
if (age <= staleMs)
|
|
8342
8792
|
return null;
|
|
8343
|
-
|
|
8344
|
-
const fd =
|
|
8345
|
-
|
|
8346
|
-
|
|
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);
|
|
8347
8797
|
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
8348
8798
|
} catch {
|
|
8349
8799
|
return null;
|
|
@@ -8353,11 +8803,11 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
|
8353
8803
|
try {
|
|
8354
8804
|
touch(path);
|
|
8355
8805
|
} catch {}
|
|
8356
|
-
},
|
|
8806
|
+
}, heartbeatMs);
|
|
8357
8807
|
heartbeat.unref?.();
|
|
8358
8808
|
const selfCheck = setInterval(() => {
|
|
8359
8809
|
try {
|
|
8360
|
-
const holder = JSON.parse(
|
|
8810
|
+
const holder = JSON.parse(readFileSync14(path, "utf-8")).pid;
|
|
8361
8811
|
if (holder === process.pid)
|
|
8362
8812
|
return;
|
|
8363
8813
|
try {
|
|
@@ -8369,7 +8819,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
|
8369
8819
|
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
8370
8820
|
process.exit(1);
|
|
8371
8821
|
}
|
|
8372
|
-
},
|
|
8822
|
+
}, selfCheckMs);
|
|
8373
8823
|
selfCheck.unref?.();
|
|
8374
8824
|
let released = false;
|
|
8375
8825
|
return {
|
|
@@ -8380,7 +8830,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
|
8380
8830
|
clearInterval(heartbeat);
|
|
8381
8831
|
clearInterval(selfCheck);
|
|
8382
8832
|
try {
|
|
8383
|
-
|
|
8833
|
+
unlinkSync7(path);
|
|
8384
8834
|
} catch {}
|
|
8385
8835
|
}
|
|
8386
8836
|
};
|
|
@@ -8482,11 +8932,11 @@ async function main() {
|
|
|
8482
8932
|
});
|
|
8483
8933
|
console.log("[index] OpenCode QQ Bot 已启动");
|
|
8484
8934
|
bridge.recoverInflightRounds();
|
|
8485
|
-
const heartbeatFile =
|
|
8935
|
+
const heartbeatFile = join16(homedir14(), ".openqq", "heartbeat");
|
|
8486
8936
|
const touchHeartbeat = () => {
|
|
8487
8937
|
try {
|
|
8488
|
-
|
|
8489
|
-
|
|
8938
|
+
mkdirSync14(join16(homedir14(), ".openqq"), { recursive: true });
|
|
8939
|
+
writeFileSync15(heartbeatFile, String(Date.now()));
|
|
8490
8940
|
} catch (error) {
|
|
8491
8941
|
console.error("[index] 心跳写入失败:", error);
|
|
8492
8942
|
}
|