@linjz/opencode-qqbot 0.3.12 → 0.3.14
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 +12 -7
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +4 -4
- package/dist/openqq-bot.js +1072 -208
- package/package.json +2 -2
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +141 -15
- package/src/commands.ts +554 -554
- package/src/config.ts +118 -121
- package/src/core/bot-launcher.ts +146 -146
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +115 -18
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -33
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +388 -72
- package/src/core/form-journal.ts +214 -0
- package/src/core/gateway-state.ts +68 -0
- package/src/core/inbound-dedupe.ts +43 -0
- package/src/core/inflight-journal.ts +170 -22
- package/src/core/instance-lock.ts +28 -1
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +11 -0
- package/src/core/mirror.ts +182 -182
- package/src/core/outbox.ts +522 -0
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +98 -13
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +85 -85
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +546 -539
- package/src/qq/gateway.ts +69 -20
- package/src/qq/media.ts +219 -219
- package/src/qq/sender.ts +303 -300
- package/src/qq/types.ts +154 -154
- package/tsconfig.json +24 -24
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 existsSync11, mkdirSync as mkdirSync12, renameSync as renameSync5, statSync as statSync7 } from "fs";
|
|
2943
|
+
import { join as join14 } from "path";
|
|
2944
2944
|
function installFileLog(logPath) {
|
|
2945
2945
|
try {
|
|
2946
|
-
|
|
2946
|
+
mkdirSync12(join14(logPath, ".."), { recursive: true });
|
|
2947
2947
|
} catch {}
|
|
2948
2948
|
const write = (level, args) => {
|
|
2949
2949
|
try {
|
|
2950
|
-
if (
|
|
2951
|
-
|
|
2950
|
+
if (existsSync11(logPath) && statSync7(logPath).size > ROTATE_BYTES) {
|
|
2951
|
+
renameSync5(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,27 +3080,78 @@ 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 mkdirSync13, writeFileSync as writeFileSync14 } from "fs";
|
|
3089
|
+
import { join as join15 } from "path";
|
|
3090
|
+
import { homedir as homedir13 } 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(`
|
|
3103
3103
|
`).trim();
|
|
3104
3104
|
}
|
|
3105
|
+
function turnStateOf(msgs, promptId, baseline) {
|
|
3106
|
+
const ordered = [...msgs].sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0));
|
|
3107
|
+
let userIdx = -1;
|
|
3108
|
+
if (promptId)
|
|
3109
|
+
userIdx = ordered.findIndex((m) => m.type === "user" && m.id === promptId);
|
|
3110
|
+
if (userIdx < 0 && baseline > 0) {
|
|
3111
|
+
let best = -1;
|
|
3112
|
+
let bestDelta = Number.POSITIVE_INFINITY;
|
|
3113
|
+
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
3114
|
+
if (ordered[i].type !== "user")
|
|
3115
|
+
continue;
|
|
3116
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - baseline);
|
|
3117
|
+
if (delta < bestDelta) {
|
|
3118
|
+
bestDelta = delta;
|
|
3119
|
+
best = i;
|
|
3120
|
+
}
|
|
3121
|
+
}
|
|
3122
|
+
if (best >= 0 && bestDelta <= 200)
|
|
3123
|
+
userIdx = best;
|
|
3124
|
+
}
|
|
3125
|
+
if (userIdx < 0) {
|
|
3126
|
+
const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline);
|
|
3127
|
+
return { anchored: false, hasIdle: Boolean(idle), text: collectReplyText(msgs, baseline) };
|
|
3128
|
+
}
|
|
3129
|
+
let end = ordered.length;
|
|
3130
|
+
for (let i = userIdx + 1;i < ordered.length; i++) {
|
|
3131
|
+
if (ordered[i].type === "user") {
|
|
3132
|
+
end = i;
|
|
3133
|
+
break;
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
const boundary = ordered.slice(userIdx + 1, end);
|
|
3137
|
+
let text = "";
|
|
3138
|
+
for (let i = boundary.length - 1;i >= 0; i--) {
|
|
3139
|
+
const m = boundary[i];
|
|
3140
|
+
if (m.type !== "assistant")
|
|
3141
|
+
continue;
|
|
3142
|
+
const joined = (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text ?? "").join(`
|
|
3143
|
+
`).trim();
|
|
3144
|
+
if (joined) {
|
|
3145
|
+
text = joined;
|
|
3146
|
+
break;
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
return {
|
|
3150
|
+
anchored: true,
|
|
3151
|
+
hasIdle: boundary.some((m) => m.type === "idle"),
|
|
3152
|
+
text
|
|
3153
|
+
};
|
|
3154
|
+
}
|
|
3105
3155
|
var client = null;
|
|
3106
3156
|
function sleep(ms) {
|
|
3107
3157
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -3192,6 +3242,9 @@ function createClient(baseUrl) {
|
|
|
3192
3242
|
method: "POST",
|
|
3193
3243
|
body: JSON.stringify(opts.body)
|
|
3194
3244
|
}));
|
|
3245
|
+
},
|
|
3246
|
+
async cancel(opts) {
|
|
3247
|
+
return json(await req(`/session/${opts.path.sessionID}/form/${opts.path.formID}`, { method: "DELETE" }));
|
|
3195
3248
|
}
|
|
3196
3249
|
},
|
|
3197
3250
|
app: {
|
|
@@ -3240,7 +3293,11 @@ function createClient(baseUrl) {
|
|
|
3240
3293
|
}
|
|
3241
3294
|
const promptJson = await json(await req(`/session/${sessionId}/prompt`, { method: "POST", body: JSON.stringify(body) }));
|
|
3242
3295
|
const baseline = promptJson?.data?.time?.created ?? 0;
|
|
3243
|
-
const
|
|
3296
|
+
const promptId = promptJson?.data?.id ?? "";
|
|
3297
|
+
if (options?.onAccepted)
|
|
3298
|
+
options.onAccepted({ promptId, baseline });
|
|
3299
|
+
console.log(`[opencode] LLM prompt 已受理 pid=${process.pid} session=${sessionId} user=${promptJson?.data?.id ?? "?"} baseline=${baseline}`);
|
|
3300
|
+
const deadline = Date.now() + responseTimeoutMs();
|
|
3244
3301
|
let permissionWaitMs = 0;
|
|
3245
3302
|
const handledPermissions = new Set;
|
|
3246
3303
|
while (Date.now() - permissionWaitMs < deadline) {
|
|
@@ -3284,13 +3341,12 @@ function createClient(baseUrl) {
|
|
|
3284
3341
|
}
|
|
3285
3342
|
const listJson = await json(await req(`/session/${sessionId}/message`));
|
|
3286
3343
|
const msgs = listJson?.data ?? [];
|
|
3287
|
-
const
|
|
3288
|
-
if (
|
|
3289
|
-
|
|
3290
|
-
return reply || "(AI 未返回内容)";
|
|
3344
|
+
const turn = turnStateOf(msgs, promptId, baseline);
|
|
3345
|
+
if (turn.hasIdle) {
|
|
3346
|
+
return turn.text || "(AI 未返回内容)";
|
|
3291
3347
|
}
|
|
3292
3348
|
}
|
|
3293
|
-
throw new Error(`AI 响应超时(${
|
|
3349
|
+
throw new Error(`AI 响应超时(${turnTimeoutMinutes()} 分钟)`);
|
|
3294
3350
|
}
|
|
3295
3351
|
};
|
|
3296
3352
|
client = oc;
|
|
@@ -3537,7 +3593,9 @@ function startLinkWatch(deps) {
|
|
|
3537
3593
|
var API_BASE = "https://api.sgroup.qq.com";
|
|
3538
3594
|
var TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
|
|
3539
3595
|
var API_BASE_SANDBOX = "https://sandbox.api.sgroup.qq.com";
|
|
3540
|
-
|
|
3596
|
+
function apiBase() {
|
|
3597
|
+
return process.env.QQ_SANDBOX === "true" ? API_BASE_SANDBOX : API_BASE;
|
|
3598
|
+
}
|
|
3541
3599
|
var cachedToken = null;
|
|
3542
3600
|
var tokenFetchPromise = null;
|
|
3543
3601
|
function maskHeaders(headers) {
|
|
@@ -3625,7 +3683,7 @@ function getNextMsgSeq(_msgId) {
|
|
|
3625
3683
|
var DEFAULT_API_TIMEOUT = 30000;
|
|
3626
3684
|
var FILE_UPLOAD_TIMEOUT = 120000;
|
|
3627
3685
|
async function apiRequest(accessToken, method, path, body, timeoutMs) {
|
|
3628
|
-
const url = `${
|
|
3686
|
+
const url = `${apiBase()}${path}`;
|
|
3629
3687
|
const headers = {
|
|
3630
3688
|
Authorization: `QQBot ${accessToken}`,
|
|
3631
3689
|
"Content-Type": "application/json"
|
|
@@ -3988,6 +4046,49 @@ var import_websocket = __toESM(require_websocket(), 1);
|
|
|
3988
4046
|
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
3989
4047
|
var wrapper_default = import_websocket.default;
|
|
3990
4048
|
|
|
4049
|
+
// src/core/gateway-state.ts
|
|
4050
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5, mkdirSync as mkdirSync4, renameSync, unlinkSync } from "fs";
|
|
4051
|
+
import { join as join5 } from "path";
|
|
4052
|
+
import { homedir as homedir5 } from "os";
|
|
4053
|
+
var GATEWAY_STATE_FILE = join5(homedir5(), ".openqq", "gateway-state.json");
|
|
4054
|
+
function gatewayStateMaxAgeMs() {
|
|
4055
|
+
const h = Number(process.env.QQ_GATEWAY_STATE_MAX_HOURS ?? "6");
|
|
4056
|
+
return Number.isFinite(h) && h > 0 ? Math.floor(h * 3600000) : 6 * 3600000;
|
|
4057
|
+
}
|
|
4058
|
+
function loadGatewayState(file = GATEWAY_STATE_FILE, now = Date.now()) {
|
|
4059
|
+
try {
|
|
4060
|
+
if (!existsSync4(file))
|
|
4061
|
+
return null;
|
|
4062
|
+
const raw = JSON.parse(readFileSync4(file, "utf-8"));
|
|
4063
|
+
if (!raw || typeof raw.session_id !== "string" || !raw.session_id)
|
|
4064
|
+
return null;
|
|
4065
|
+
if (typeof raw.seq !== "number" || raw.seq < 0)
|
|
4066
|
+
return null;
|
|
4067
|
+
if (typeof raw.savedAt !== "number" || !Number.isFinite(raw.savedAt))
|
|
4068
|
+
return null;
|
|
4069
|
+
if (now - raw.savedAt > gatewayStateMaxAgeMs())
|
|
4070
|
+
return null;
|
|
4071
|
+
return { session_id: raw.session_id, seq: raw.seq, savedAt: raw.savedAt };
|
|
4072
|
+
} catch {
|
|
4073
|
+
return null;
|
|
4074
|
+
}
|
|
4075
|
+
}
|
|
4076
|
+
function saveGatewayState(sessionId, seq, file = GATEWAY_STATE_FILE) {
|
|
4077
|
+
try {
|
|
4078
|
+
mkdirSync4(join5(file, ".."), { recursive: true });
|
|
4079
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
4080
|
+
writeFileSync5(tmp, JSON.stringify({ session_id: sessionId, seq, savedAt: Date.now() }));
|
|
4081
|
+
renameSync(tmp, file);
|
|
4082
|
+
} catch (error) {
|
|
4083
|
+
console.warn("[gateway-state] 落盘失败:", error instanceof Error ? error.message : error);
|
|
4084
|
+
}
|
|
4085
|
+
}
|
|
4086
|
+
function clearGatewayState(file = GATEWAY_STATE_FILE) {
|
|
4087
|
+
try {
|
|
4088
|
+
unlinkSync(file);
|
|
4089
|
+
} catch {}
|
|
4090
|
+
}
|
|
4091
|
+
|
|
3991
4092
|
// src/qq/gateway.ts
|
|
3992
4093
|
var GROUP_AND_C2C_EVENT_INTENT = 1 << 25;
|
|
3993
4094
|
var INTERACTION_INTENT = 1 << 26;
|
|
@@ -3999,7 +4100,7 @@ var RATE_LIMITED_RECONNECT_DELAY_MS = 60000;
|
|
|
3999
4100
|
var RESUME_RESET_CLOSE_CODES = new Set([4006, 4007, 4009]);
|
|
4000
4101
|
var FATAL_CLOSE_CODES = new Set([4914, 4915]);
|
|
4001
4102
|
function createInitialState() {
|
|
4002
|
-
|
|
4103
|
+
const state = {
|
|
4003
4104
|
ws: null,
|
|
4004
4105
|
stopped: false,
|
|
4005
4106
|
connecting: false,
|
|
@@ -4010,21 +4111,28 @@ function createInitialState() {
|
|
|
4010
4111
|
sessionId: null,
|
|
4011
4112
|
seq: null,
|
|
4012
4113
|
heartbeatAcked: true,
|
|
4013
|
-
|
|
4114
|
+
activeMsgIds: new Set
|
|
4014
4115
|
};
|
|
4116
|
+
const saved = loadGatewayState();
|
|
4117
|
+
if (saved) {
|
|
4118
|
+
state.sessionId = saved.session_id;
|
|
4119
|
+
state.seq = saved.seq;
|
|
4120
|
+
const agoSec = Math.max(0, Math.round((Date.now() - saved.savedAt) / 1000));
|
|
4121
|
+
console.log(`[gateway] 已从磁盘恢复网关状态(${agoSec}s 前),将尝试 RESUME session=${saved.session_id} seq=${saved.seq}`);
|
|
4122
|
+
}
|
|
4123
|
+
return state;
|
|
4015
4124
|
}
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
if (seen.has(msgId))
|
|
4125
|
+
function tryClaimActive(active, msgId) {
|
|
4126
|
+
if (active.has(msgId))
|
|
4019
4127
|
return false;
|
|
4020
|
-
if (
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
seen.delete(first);
|
|
4024
|
-
}
|
|
4025
|
-
seen.add(msgId);
|
|
4128
|
+
if (active.size >= 1000)
|
|
4129
|
+
return true;
|
|
4130
|
+
active.add(msgId);
|
|
4026
4131
|
return true;
|
|
4027
4132
|
}
|
|
4133
|
+
function releaseActive(active, msgId) {
|
|
4134
|
+
active.delete(msgId);
|
|
4135
|
+
}
|
|
4028
4136
|
function cleanupSocket(state) {
|
|
4029
4137
|
if (state.heartbeatTimer) {
|
|
4030
4138
|
clearInterval(state.heartbeatTimer);
|
|
@@ -4073,6 +4181,7 @@ function startHeartbeat(state, intervalMs) {
|
|
|
4073
4181
|
function resetResumeState(state) {
|
|
4074
4182
|
state.sessionId = null;
|
|
4075
4183
|
state.seq = null;
|
|
4184
|
+
clearGatewayState();
|
|
4076
4185
|
}
|
|
4077
4186
|
function normalizeMessageContent(content) {
|
|
4078
4187
|
return content.replace(/\r\n/g, `
|
|
@@ -4154,6 +4263,8 @@ async function handleDispatchEvent(payload, options, state) {
|
|
|
4154
4263
|
case "READY": {
|
|
4155
4264
|
const readyData = payload.d;
|
|
4156
4265
|
state.sessionId = readyData.session_id;
|
|
4266
|
+
if (state.seq !== null)
|
|
4267
|
+
saveGatewayState(state.sessionId, state.seq);
|
|
4157
4268
|
if (state.reconnectAttempt > 0) {
|
|
4158
4269
|
console.log(`[gateway] 重连已就绪(READY,第 ${state.reconnectAttempt} 次尝试)session=${state.sessionId}`);
|
|
4159
4270
|
}
|
|
@@ -4163,45 +4274,59 @@ async function handleDispatchEvent(payload, options, state) {
|
|
|
4163
4274
|
}
|
|
4164
4275
|
case "RESUMED": {
|
|
4165
4276
|
console.log("[gateway] 会话已恢复(RESUMED,断线期间事件已回补)");
|
|
4277
|
+
if (state.sessionId && state.seq !== null)
|
|
4278
|
+
saveGatewayState(state.sessionId, state.seq);
|
|
4166
4279
|
state.reconnectAttempt = 0;
|
|
4167
4280
|
return;
|
|
4168
4281
|
}
|
|
4169
4282
|
case "C2C_MESSAGE_CREATE": {
|
|
4170
4283
|
const event = payload.d;
|
|
4171
|
-
if (!
|
|
4284
|
+
if (!tryClaimActive(state.activeMsgIds, event.id))
|
|
4172
4285
|
return;
|
|
4173
4286
|
const message = toC2CMessageContext(event);
|
|
4174
4287
|
if (message.attachments?.length) {
|
|
4175
4288
|
console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)));
|
|
4176
4289
|
}
|
|
4177
4290
|
if (!message.content && !message.attachments?.length) {
|
|
4291
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4178
4292
|
return;
|
|
4179
4293
|
}
|
|
4180
|
-
|
|
4294
|
+
try {
|
|
4295
|
+
await options.onMessage(message);
|
|
4296
|
+
} finally {
|
|
4297
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4298
|
+
}
|
|
4181
4299
|
return;
|
|
4182
4300
|
}
|
|
4183
4301
|
case "GROUP_AT_MESSAGE_CREATE": {
|
|
4184
4302
|
const event = payload.d;
|
|
4185
|
-
if (!
|
|
4303
|
+
if (!tryClaimActive(state.activeMsgIds, event.id))
|
|
4186
4304
|
return;
|
|
4187
4305
|
const message = toGroupMessageContext(event);
|
|
4188
4306
|
if (message.attachments?.length) {
|
|
4189
4307
|
console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)));
|
|
4190
4308
|
}
|
|
4191
4309
|
if (!message.content && !message.attachments?.length) {
|
|
4310
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4192
4311
|
return;
|
|
4193
4312
|
}
|
|
4194
|
-
|
|
4313
|
+
try {
|
|
4314
|
+
await options.onMessage(message);
|
|
4315
|
+
} finally {
|
|
4316
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4317
|
+
}
|
|
4195
4318
|
return;
|
|
4196
4319
|
}
|
|
4197
4320
|
case "INTERACTION_CREATE": {
|
|
4198
4321
|
const interaction = payload.d;
|
|
4322
|
+
Promise.resolve().then(() => options.onInteraction?.(interaction)).catch((error) => {
|
|
4323
|
+
console.error("[qq-gateway] 互动业务分发失败:", error instanceof Error ? error.message : error);
|
|
4324
|
+
});
|
|
4199
4325
|
if (state.accessToken && interaction?.id) {
|
|
4200
4326
|
acknowledgeInteraction(state.accessToken, interaction.id).catch((error) => {
|
|
4201
4327
|
console.error("[qq-gateway] 互动响应失败:", error instanceof Error ? error.message : error);
|
|
4202
4328
|
});
|
|
4203
4329
|
}
|
|
4204
|
-
await options.onInteraction?.(interaction);
|
|
4205
4330
|
return;
|
|
4206
4331
|
}
|
|
4207
4332
|
default:
|
|
@@ -4210,7 +4335,14 @@ async function handleDispatchEvent(payload, options, state) {
|
|
|
4210
4335
|
}
|
|
4211
4336
|
async function handlePayload(payload, ws, options, state, connect) {
|
|
4212
4337
|
if (typeof payload.s === "number") {
|
|
4338
|
+
const prevSeq = state.seq;
|
|
4213
4339
|
state.seq = payload.s;
|
|
4340
|
+
if (state.sessionId && payload.s !== prevSeq) {
|
|
4341
|
+
if (prevSeq !== null && payload.s > prevSeq + 1) {
|
|
4342
|
+
console.log(`[gateway] seq 回补 ${payload.s - prevSeq - 1} 帧(${prevSeq} → ${payload.s})——断线期间载荷已重放`);
|
|
4343
|
+
}
|
|
4344
|
+
saveGatewayState(state.sessionId, payload.s);
|
|
4345
|
+
}
|
|
4214
4346
|
}
|
|
4215
4347
|
switch (payload.op) {
|
|
4216
4348
|
case 10: {
|
|
@@ -4335,13 +4467,13 @@ async function startGateway(options) {
|
|
|
4335
4467
|
}
|
|
4336
4468
|
|
|
4337
4469
|
// src/bridge.ts
|
|
4338
|
-
import { existsSync as
|
|
4339
|
-
import { join as
|
|
4340
|
-
import { homedir as
|
|
4470
|
+
import { existsSync as existsSync10, readFileSync as readFileSync12, mkdirSync as mkdirSync10, writeFileSync as writeFileSync12 } from "fs";
|
|
4471
|
+
import { join as join12 } from "path";
|
|
4472
|
+
import { homedir as homedir11 } from "os";
|
|
4341
4473
|
|
|
4342
4474
|
// src/qq/media.ts
|
|
4343
|
-
import { mkdirSync as
|
|
4344
|
-
import { join as
|
|
4475
|
+
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync5 } from "node:fs";
|
|
4476
|
+
import { join as join6 } from "node:path";
|
|
4345
4477
|
import { tmpdir } from "node:os";
|
|
4346
4478
|
function extForImageMime(mime) {
|
|
4347
4479
|
const m = (mime || "").toLowerCase().split(";")[0].trim();
|
|
@@ -4366,7 +4498,7 @@ function isAllowedDownloadHost(url) {
|
|
|
4366
4498
|
}
|
|
4367
4499
|
}
|
|
4368
4500
|
function imageDir() {
|
|
4369
|
-
return
|
|
4501
|
+
return join6(tmpdir(), "opencode", "qq-images");
|
|
4370
4502
|
}
|
|
4371
4503
|
async function fetchWithTimeout(url, ms, auth) {
|
|
4372
4504
|
const ctrl = new AbortController;
|
|
@@ -4392,7 +4524,7 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4392
4524
|
return { failed: "下载域不在白名单" };
|
|
4393
4525
|
try {
|
|
4394
4526
|
const dir = imageDir();
|
|
4395
|
-
|
|
4527
|
+
mkdirSync5(dir, { recursive: true });
|
|
4396
4528
|
const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
|
4397
4529
|
let res = await fetchWithTimeout(att.url, 15000);
|
|
4398
4530
|
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
@@ -4426,8 +4558,8 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4426
4558
|
}
|
|
4427
4559
|
if (total === 0)
|
|
4428
4560
|
return { failed: "空响应" };
|
|
4429
|
-
const full =
|
|
4430
|
-
|
|
4561
|
+
const full = join6(dir, name);
|
|
4562
|
+
writeFileSync6(full, Buffer.concat(chunks));
|
|
4431
4563
|
return { path: full, name };
|
|
4432
4564
|
} catch (e) {
|
|
4433
4565
|
console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e);
|
|
@@ -4464,7 +4596,7 @@ function tryImageDataUrl(path, maxBytes) {
|
|
|
4464
4596
|
const st = statSync(path);
|
|
4465
4597
|
if (st.size > maxBytes)
|
|
4466
4598
|
return null;
|
|
4467
|
-
const b =
|
|
4599
|
+
const b = readFileSync5(path);
|
|
4468
4600
|
return `data:image/png;base64,${b.toString("base64")}`;
|
|
4469
4601
|
} catch {
|
|
4470
4602
|
return null;
|
|
@@ -4491,10 +4623,10 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
|
4491
4623
|
const dir = imageDir();
|
|
4492
4624
|
const now = Date.now();
|
|
4493
4625
|
for (const f of readdirSync(dir)) {
|
|
4494
|
-
const full =
|
|
4626
|
+
const full = join6(dir, f);
|
|
4495
4627
|
try {
|
|
4496
4628
|
if (now - statSync(full).mtimeMs > maxAgeMs)
|
|
4497
|
-
|
|
4629
|
+
unlinkSync2(full);
|
|
4498
4630
|
} catch {}
|
|
4499
4631
|
}
|
|
4500
4632
|
} catch {}
|
|
@@ -4732,7 +4864,7 @@ function clip(value, max) {
|
|
|
4732
4864
|
}
|
|
4733
4865
|
|
|
4734
4866
|
// src/core/send-media.ts
|
|
4735
|
-
import { readFileSync as
|
|
4867
|
+
import { readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
|
|
4736
4868
|
import { resolve, extname, basename, sep } from "node:path";
|
|
4737
4869
|
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
4738
4870
|
function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
|
|
@@ -4797,7 +4929,7 @@ async function sendLocalFile(ctx, filePath, deps) {
|
|
|
4797
4929
|
const name = basename(trimmed);
|
|
4798
4930
|
const uploaded = await uploadQQMedia(token, ctx, {
|
|
4799
4931
|
fileType,
|
|
4800
|
-
fileData:
|
|
4932
|
+
fileData: readFileSync6(trimmed).toString("base64"),
|
|
4801
4933
|
fileName: fileType === MediaFileType.FILE ? name : undefined
|
|
4802
4934
|
});
|
|
4803
4935
|
await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
|
|
@@ -5219,9 +5351,9 @@ function toErrorMessage(error) {
|
|
|
5219
5351
|
}
|
|
5220
5352
|
|
|
5221
5353
|
// src/core/mirror.ts
|
|
5222
|
-
import { existsSync as
|
|
5223
|
-
import { join as
|
|
5224
|
-
import { homedir as
|
|
5354
|
+
import { existsSync as existsSync5, readFileSync as readFileSync7, mkdirSync as mkdirSync6, writeFileSync as writeFileSync7 } from "fs";
|
|
5355
|
+
import { join as join7 } from "path";
|
|
5356
|
+
import { homedir as homedir6 } from "os";
|
|
5225
5357
|
|
|
5226
5358
|
// src/opencode/mirror.ts
|
|
5227
5359
|
var USER_CLIP = 160;
|
|
@@ -5294,11 +5426,11 @@ function clip2(value, max) {
|
|
|
5294
5426
|
}
|
|
5295
5427
|
|
|
5296
5428
|
// src/core/mirror.ts
|
|
5297
|
-
var MIRROR_SETTINGS_FILE =
|
|
5429
|
+
var MIRROR_SETTINGS_FILE = join7(homedir6(), ".openqq", "settings.json");
|
|
5298
5430
|
function loadMirrorEnabled() {
|
|
5299
5431
|
try {
|
|
5300
|
-
if (
|
|
5301
|
-
const raw =
|
|
5432
|
+
if (existsSync5(MIRROR_SETTINGS_FILE)) {
|
|
5433
|
+
const raw = readFileSync7(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
|
|
5302
5434
|
const parsed = JSON.parse(raw);
|
|
5303
5435
|
if (typeof parsed?.mirror === "boolean")
|
|
5304
5436
|
return parsed.mirror;
|
|
@@ -5308,18 +5440,18 @@ function loadMirrorEnabled() {
|
|
|
5308
5440
|
}
|
|
5309
5441
|
function saveMirrorEnabled(enabled) {
|
|
5310
5442
|
try {
|
|
5311
|
-
|
|
5443
|
+
mkdirSync6(join7(homedir6(), ".openqq"), { recursive: true });
|
|
5312
5444
|
let existing = {};
|
|
5313
|
-
if (
|
|
5445
|
+
if (existsSync5(MIRROR_SETTINGS_FILE)) {
|
|
5314
5446
|
try {
|
|
5315
|
-
const raw =
|
|
5447
|
+
const raw = readFileSync7(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
|
|
5316
5448
|
const parsed = JSON.parse(raw);
|
|
5317
5449
|
if (parsed && typeof parsed === "object")
|
|
5318
5450
|
existing = parsed;
|
|
5319
5451
|
} catch {}
|
|
5320
5452
|
}
|
|
5321
5453
|
existing.mirror = enabled;
|
|
5322
|
-
|
|
5454
|
+
writeFileSync7(MIRROR_SETTINGS_FILE, JSON.stringify(existing, null, 2), "utf-8");
|
|
5323
5455
|
} catch (error) {
|
|
5324
5456
|
console.error("[mirror] 保存设置失败:", error);
|
|
5325
5457
|
}
|
|
@@ -5426,6 +5558,11 @@ function createMirror(deps) {
|
|
|
5426
5558
|
|
|
5427
5559
|
// src/core/message-queue.ts
|
|
5428
5560
|
var PREVIEW_MAX = 48;
|
|
5561
|
+
function intentKeyOf(ctx) {
|
|
5562
|
+
const text = ctx.content.replace(/\s+/g, " ").trim();
|
|
5563
|
+
const attachments = (ctx.attachments ?? []).map((a) => `${a.content_type}:${a.size}:${a.filename}`).join("|");
|
|
5564
|
+
return JSON.stringify({ text, referenced: ctx.referencedMsgId ?? "", attachments });
|
|
5565
|
+
}
|
|
5429
5566
|
function previewText(text, max = PREVIEW_MAX) {
|
|
5430
5567
|
const flat = text.replace(/\s+/g, " ").trim();
|
|
5431
5568
|
return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)";
|
|
@@ -5456,6 +5593,9 @@ class MessageQueue {
|
|
|
5456
5593
|
this.jobs.set(userId, list);
|
|
5457
5594
|
return { job, ahead: list.length - 1 };
|
|
5458
5595
|
}
|
|
5596
|
+
hasIntent(userId, key) {
|
|
5597
|
+
return (this.jobs.get(userId) ?? []).some((job) => intentKeyOf(job.ctx) === key);
|
|
5598
|
+
}
|
|
5459
5599
|
shift(userId) {
|
|
5460
5600
|
const list = this.jobs.get(userId);
|
|
5461
5601
|
const job = list?.shift();
|
|
@@ -5515,9 +5655,9 @@ function rescueText(kind, rawMessage) {
|
|
|
5515
5655
|
}
|
|
5516
5656
|
|
|
5517
5657
|
// src/core/permission.ts
|
|
5518
|
-
import { existsSync as
|
|
5519
|
-
import { join as
|
|
5520
|
-
import { homedir as
|
|
5658
|
+
import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "fs";
|
|
5659
|
+
import { join as join8 } from "path";
|
|
5660
|
+
import { homedir as homedir7 } from "os";
|
|
5521
5661
|
|
|
5522
5662
|
// src/core/util.ts
|
|
5523
5663
|
function truncate(value, max) {
|
|
@@ -5532,11 +5672,11 @@ var DECISION_LABELS = {
|
|
|
5532
5672
|
always: "总是允许(已存入项目白名单)",
|
|
5533
5673
|
reject: "拒绝"
|
|
5534
5674
|
};
|
|
5535
|
-
var PENDING_PERM_FILE =
|
|
5675
|
+
var PENDING_PERM_FILE = join8(homedir7(), ".openqq", "pending-permissions.json");
|
|
5536
5676
|
function loadPendingPermMap() {
|
|
5537
5677
|
try {
|
|
5538
|
-
if (
|
|
5539
|
-
const raw =
|
|
5678
|
+
if (existsSync6(PENDING_PERM_FILE)) {
|
|
5679
|
+
const raw = readFileSync8(PENDING_PERM_FILE, "utf-8");
|
|
5540
5680
|
const obj = JSON.parse(raw);
|
|
5541
5681
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
5542
5682
|
const out = {};
|
|
@@ -5559,7 +5699,7 @@ function savePendingPermMap(m) {
|
|
|
5559
5699
|
continue;
|
|
5560
5700
|
out[uid] = { request: e.request, mainSessionId: e.mainSessionId, createdAt: e.createdAt, ctx: e.ctx };
|
|
5561
5701
|
}
|
|
5562
|
-
|
|
5702
|
+
writeFileSync8(PENDING_PERM_FILE, JSON.stringify(out));
|
|
5563
5703
|
} catch (error) {
|
|
5564
5704
|
console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error);
|
|
5565
5705
|
}
|
|
@@ -5725,13 +5865,12 @@ function formatPermissionPrompt(request, mainSessionId) {
|
|
|
5725
5865
|
}
|
|
5726
5866
|
|
|
5727
5867
|
// src/core/delivery.ts
|
|
5728
|
-
import { existsSync as
|
|
5729
|
-
import { join as
|
|
5868
|
+
import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync9, mkdirSync as mkdirSync7, renameSync as renameSync2, openSync, closeSync, unlinkSync as unlinkSync3, statSync as statSync3 } from "fs";
|
|
5869
|
+
import { join as join9 } from "path";
|
|
5730
5870
|
import { createHash } from "node:crypto";
|
|
5731
|
-
import { homedir as
|
|
5871
|
+
import { homedir as homedir8 } from "os";
|
|
5732
5872
|
|
|
5733
5873
|
// src/qq/sender.ts
|
|
5734
|
-
var DEFAULT_MAX_LENGTH = 3000;
|
|
5735
5874
|
function formatForQQMarkdown(text) {
|
|
5736
5875
|
return text.trim();
|
|
5737
5876
|
}
|
|
@@ -5775,8 +5914,8 @@ function convertTables(text) {
|
|
|
5775
5914
|
return out.join(`
|
|
5776
5915
|
`);
|
|
5777
5916
|
}
|
|
5778
|
-
var MARKDOWN_MAX_BYTES =
|
|
5779
|
-
var PLAIN_MAX_BYTES =
|
|
5917
|
+
var MARKDOWN_MAX_BYTES = 60232;
|
|
5918
|
+
var PLAIN_MAX_BYTES = 60232;
|
|
5780
5919
|
var encoder = new TextEncoder;
|
|
5781
5920
|
function utf8Bytes(s) {
|
|
5782
5921
|
return encoder.encode(s).length;
|
|
@@ -5926,7 +6065,7 @@ async function sendChunk(accessToken, ctx, mdText, plainText, msgSeq) {
|
|
|
5926
6065
|
return await sendC2CMessage(accessToken, ctx.userId, plainText, ctx.msgId, msgSeq, false);
|
|
5927
6066
|
}
|
|
5928
6067
|
}
|
|
5929
|
-
async function replyToQQ(accessToken, ctx, text,
|
|
6068
|
+
async function replyToQQ(accessToken, ctx, text, options) {
|
|
5930
6069
|
const mdFormatted = formatForQQMarkdown(text);
|
|
5931
6070
|
const plainFormatted = formatForQQ(text);
|
|
5932
6071
|
const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES);
|
|
@@ -6067,11 +6206,11 @@ function extractEmbeddedQuote(event) {
|
|
|
6067
6206
|
}
|
|
6068
6207
|
|
|
6069
6208
|
// src/core/delivery.ts
|
|
6070
|
-
var QUOTA_FILE =
|
|
6209
|
+
var QUOTA_FILE = join9(homedir8(), ".openqq", "quota.json");
|
|
6071
6210
|
function loadQuotaMap() {
|
|
6072
6211
|
try {
|
|
6073
|
-
if (
|
|
6074
|
-
const raw =
|
|
6212
|
+
if (existsSync7(QUOTA_FILE)) {
|
|
6213
|
+
const raw = readFileSync9(QUOTA_FILE, "utf-8");
|
|
6075
6214
|
const obj = JSON.parse(raw);
|
|
6076
6215
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
6077
6216
|
const out = {};
|
|
@@ -6089,27 +6228,53 @@ function loadQuotaMap() {
|
|
|
6089
6228
|
}
|
|
6090
6229
|
function saveQuotaMap(m) {
|
|
6091
6230
|
try {
|
|
6092
|
-
|
|
6231
|
+
writeFileSync9(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)));
|
|
6093
6232
|
} catch (error) {
|
|
6094
6233
|
console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error);
|
|
6095
6234
|
}
|
|
6096
6235
|
}
|
|
6097
6236
|
var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
|
|
6098
6237
|
`;
|
|
6238
|
+
function qqListNormalize(text) {
|
|
6239
|
+
const lines = text.split(`
|
|
6240
|
+
`);
|
|
6241
|
+
let fence = false;
|
|
6242
|
+
let fenceMarker = "";
|
|
6243
|
+
for (let i = 0;i < lines.length; i++) {
|
|
6244
|
+
const fm = lines[i].trim().match(/^(```|~~~)/);
|
|
6245
|
+
if (fm) {
|
|
6246
|
+
if (!fence) {
|
|
6247
|
+
fence = true;
|
|
6248
|
+
fenceMarker = fm[1];
|
|
6249
|
+
} else if (fm[1] === fenceMarker) {
|
|
6250
|
+
fence = false;
|
|
6251
|
+
fenceMarker = "";
|
|
6252
|
+
}
|
|
6253
|
+
continue;
|
|
6254
|
+
}
|
|
6255
|
+
if (fence)
|
|
6256
|
+
continue;
|
|
6257
|
+
lines[i] = lines[i].replace(/^(\s*)(\d+)\. /, "$1$2、");
|
|
6258
|
+
}
|
|
6259
|
+
return lines.join(`
|
|
6260
|
+
`);
|
|
6261
|
+
}
|
|
6099
6262
|
var DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
6100
|
-
|
|
6263
|
+
function deliveryDedupeFile() {
|
|
6264
|
+
return process.env.QQ_DELIVERY_DEDUPE_FILE || join9(homedir8(), ".openqq", "delivery-dedupe.json");
|
|
6265
|
+
}
|
|
6101
6266
|
function deliveryAttemptKey(userId, text) {
|
|
6102
6267
|
return `${userId}:${createHash("sha256").update(text).digest("hex")}`;
|
|
6103
6268
|
}
|
|
6104
|
-
function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TTL_MS) {
|
|
6105
|
-
return text.length >= 200 && previous?.text ===
|
|
6269
|
+
function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TTL_MS, identity = text) {
|
|
6270
|
+
return text.length >= 200 && previous?.text === identity && now - previous.at < ttlMs;
|
|
6106
6271
|
}
|
|
6107
6272
|
function loadDeliveryAttempts() {
|
|
6108
6273
|
const out = new Map;
|
|
6109
6274
|
try {
|
|
6110
|
-
if (!
|
|
6275
|
+
if (!existsSync7(deliveryDedupeFile()))
|
|
6111
6276
|
return out;
|
|
6112
|
-
const raw = JSON.parse(
|
|
6277
|
+
const raw = JSON.parse(readFileSync9(deliveryDedupeFile(), "utf-8"));
|
|
6113
6278
|
const now = Date.now();
|
|
6114
6279
|
for (const entry of raw) {
|
|
6115
6280
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -6121,10 +6286,74 @@ function loadDeliveryAttempts() {
|
|
|
6121
6286
|
}
|
|
6122
6287
|
function saveDeliveryAttempts(entries) {
|
|
6123
6288
|
const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
|
|
6124
|
-
|
|
6125
|
-
const tmp = `${
|
|
6126
|
-
|
|
6127
|
-
|
|
6289
|
+
mkdirSync7(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
6290
|
+
const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6291
|
+
try {
|
|
6292
|
+
writeFileSync9(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
|
|
6293
|
+
renameSync2(tmp, deliveryDedupeFile());
|
|
6294
|
+
} catch (error) {
|
|
6295
|
+
try {
|
|
6296
|
+
unlinkSync3(tmp);
|
|
6297
|
+
} catch {}
|
|
6298
|
+
throw error;
|
|
6299
|
+
}
|
|
6300
|
+
}
|
|
6301
|
+
var DELIVERY_LOCK_STALE_MS = 30000;
|
|
6302
|
+
var DELIVERY_LOCK_WAIT_MS = 5000;
|
|
6303
|
+
var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6304
|
+
function withDeliveryLock(fn) {
|
|
6305
|
+
mkdirSync7(join9(deliveryDedupeFile(), ".."), { recursive: true });
|
|
6306
|
+
const lockPath = `${deliveryDedupeFile()}.lock`;
|
|
6307
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6308
|
+
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
|
|
6309
|
+
for (;; ) {
|
|
6310
|
+
try {
|
|
6311
|
+
const fd = openSync(lockPath, "wx", 384);
|
|
6312
|
+
try {
|
|
6313
|
+
writeFileSync9(fd, token);
|
|
6314
|
+
} finally {
|
|
6315
|
+
closeSync(fd);
|
|
6316
|
+
}
|
|
6317
|
+
break;
|
|
6318
|
+
} catch (error) {
|
|
6319
|
+
try {
|
|
6320
|
+
if (Date.now() - statSync3(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS)
|
|
6321
|
+
unlinkSync3(lockPath);
|
|
6322
|
+
} catch {}
|
|
6323
|
+
if (Date.now() >= deadline)
|
|
6324
|
+
throw new Error(`同文投递锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6325
|
+
Atomics.wait(deliverySleepArray, 0, 0, 10);
|
|
6326
|
+
}
|
|
6327
|
+
}
|
|
6328
|
+
try {
|
|
6329
|
+
return fn();
|
|
6330
|
+
} finally {
|
|
6331
|
+
try {
|
|
6332
|
+
if (readFileSync9(lockPath, "utf-8") === token)
|
|
6333
|
+
unlinkSync3(lockPath);
|
|
6334
|
+
} catch {}
|
|
6335
|
+
}
|
|
6336
|
+
}
|
|
6337
|
+
function reserveDeliveryAttempt(userId, text, now = Date.now()) {
|
|
6338
|
+
const attemptKey = deliveryAttemptKey(userId, text);
|
|
6339
|
+
return withDeliveryLock(() => {
|
|
6340
|
+
const entries = loadDeliveryAttempts();
|
|
6341
|
+
if (shouldSuppressDuplicate(entries.get(attemptKey), text, now, DELIVERY_DEDUPE_TTL_MS, attemptKey))
|
|
6342
|
+
return null;
|
|
6343
|
+
entries.set(attemptKey, { text: attemptKey, at: now });
|
|
6344
|
+
saveDeliveryAttempts(entries);
|
|
6345
|
+
return attemptKey;
|
|
6346
|
+
});
|
|
6347
|
+
}
|
|
6348
|
+
function releaseDeliveryAttempt(userId, text, at) {
|
|
6349
|
+
const attemptKey = deliveryAttemptKey(userId, text);
|
|
6350
|
+
withDeliveryLock(() => {
|
|
6351
|
+
const entries = loadDeliveryAttempts();
|
|
6352
|
+
if (entries.get(attemptKey)?.at === at) {
|
|
6353
|
+
entries.delete(attemptKey);
|
|
6354
|
+
saveDeliveryAttempts(entries);
|
|
6355
|
+
}
|
|
6356
|
+
});
|
|
6128
6357
|
}
|
|
6129
6358
|
function selectRideMsgId(last, ctx, now, windowMs) {
|
|
6130
6359
|
if (!last?.msgId)
|
|
@@ -6152,7 +6381,6 @@ function createDelivery(config, lastCtx) {
|
|
|
6152
6381
|
})();
|
|
6153
6382
|
const pushQueues = new Map;
|
|
6154
6383
|
const undelivered = new Set;
|
|
6155
|
-
const recentDeliveries = loadDeliveryAttempts();
|
|
6156
6384
|
const activeQuota = new Map;
|
|
6157
6385
|
const passiveLimiter = new ReplyLimiter;
|
|
6158
6386
|
for (const [uid, q] of Object.entries(loadQuotaMap()))
|
|
@@ -6195,20 +6423,17 @@ function createDelivery(config, lastCtx) {
|
|
|
6195
6423
|
}
|
|
6196
6424
|
async function deliver(ctx, text) {
|
|
6197
6425
|
const now = Date.now();
|
|
6198
|
-
const attemptKey =
|
|
6199
|
-
if (
|
|
6426
|
+
const attemptKey = reserveDeliveryAttempt(ctx.userId, text, now);
|
|
6427
|
+
if (!attemptKey) {
|
|
6200
6428
|
console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`);
|
|
6201
6429
|
return;
|
|
6202
6430
|
}
|
|
6203
|
-
recentDeliveries.set(attemptKey, { text: attemptKey, at: now });
|
|
6204
6431
|
const hadNotice = undelivered.delete(ctx.userId);
|
|
6205
|
-
const body = hadNotice ? UNDELIVERED_NOTICE + text : text;
|
|
6432
|
+
const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text);
|
|
6206
6433
|
try {
|
|
6207
6434
|
await deliverCore(ctx, body);
|
|
6208
|
-
saveDeliveryAttempts(recentDeliveries);
|
|
6209
6435
|
} catch (error) {
|
|
6210
|
-
|
|
6211
|
-
recentDeliveries.delete(attemptKey);
|
|
6436
|
+
releaseDeliveryAttempt(ctx.userId, text, now);
|
|
6212
6437
|
if (hadNotice)
|
|
6213
6438
|
undelivered.add(ctx.userId);
|
|
6214
6439
|
throw error;
|
|
@@ -6293,7 +6518,7 @@ function createDelivery(config, lastCtx) {
|
|
|
6293
6518
|
}
|
|
6294
6519
|
async function sendReply(ctx, text) {
|
|
6295
6520
|
const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret);
|
|
6296
|
-
const result = await replyToQQ(accessToken, ctx, text,
|
|
6521
|
+
const result = await replyToQQ(accessToken, ctx, text, {
|
|
6297
6522
|
staggerMs: STREAM_STAGGER_MS
|
|
6298
6523
|
});
|
|
6299
6524
|
if (ctx.msgId) {
|
|
@@ -6384,11 +6609,183 @@ function handleApprovalInteraction(event, gate) {
|
|
|
6384
6609
|
return true;
|
|
6385
6610
|
}
|
|
6386
6611
|
|
|
6612
|
+
// src/core/form-journal.ts
|
|
6613
|
+
import {
|
|
6614
|
+
closeSync as closeSync2,
|
|
6615
|
+
existsSync as existsSync8,
|
|
6616
|
+
mkdirSync as mkdirSync8,
|
|
6617
|
+
openSync as openSync2,
|
|
6618
|
+
readFileSync as readFileSync10,
|
|
6619
|
+
renameSync as renameSync3,
|
|
6620
|
+
statSync as statSync4,
|
|
6621
|
+
unlinkSync as unlinkSync4,
|
|
6622
|
+
writeFileSync as writeFileSync10
|
|
6623
|
+
} from "fs";
|
|
6624
|
+
import { dirname, join as join10 } from "path";
|
|
6625
|
+
import { homedir as homedir9 } from "os";
|
|
6626
|
+
var LOCK_STALE_MS = 30000;
|
|
6627
|
+
var LOCK_WAIT_MS = 5000;
|
|
6628
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6629
|
+
var STATES = new Set(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"]);
|
|
6630
|
+
function defaultFormJournalPath() {
|
|
6631
|
+
return process.env.QQ_FORM_JOURNAL_FILE || join10(homedir9(), ".openqq", "forms.json");
|
|
6632
|
+
}
|
|
6633
|
+
function minimalFormContext(ctx) {
|
|
6634
|
+
return {
|
|
6635
|
+
type: ctx.type,
|
|
6636
|
+
userId: ctx.userId,
|
|
6637
|
+
...ctx.type === "group" && ctx.groupId ? { groupId: ctx.groupId } : {},
|
|
6638
|
+
msgId: "",
|
|
6639
|
+
content: "",
|
|
6640
|
+
...ctx.timestamp ? { timestamp: ctx.timestamp } : {}
|
|
6641
|
+
};
|
|
6642
|
+
}
|
|
6643
|
+
function validForm(value) {
|
|
6644
|
+
if (!value || typeof value !== "object")
|
|
6645
|
+
return false;
|
|
6646
|
+
const form = value;
|
|
6647
|
+
return typeof form.id === "string" && typeof form.sessionID === "string" && typeof form.title === "string" && Array.isArray(form.fields);
|
|
6648
|
+
}
|
|
6649
|
+
function normalizeEntry(value) {
|
|
6650
|
+
if (!value || typeof value !== "object")
|
|
6651
|
+
return;
|
|
6652
|
+
const entry = value;
|
|
6653
|
+
if (!validForm(entry.form) || !entry.ctx || entry.ctx.type !== "c2c" && entry.ctx.type !== "group" || typeof entry.userId !== "string" || !entry.userId || typeof entry.createdAt !== "number" || !Number.isFinite(entry.createdAt) || typeof entry.updatedAt !== "number" || !Number.isFinite(entry.updatedAt) || !entry.state || !STATES.has(entry.state)) {
|
|
6654
|
+
return;
|
|
6655
|
+
}
|
|
6656
|
+
return {
|
|
6657
|
+
form: entry.form,
|
|
6658
|
+
ctx: minimalFormContext({ ...entry.ctx, userId: entry.userId }),
|
|
6659
|
+
userId: entry.userId,
|
|
6660
|
+
createdAt: entry.createdAt,
|
|
6661
|
+
state: entry.state,
|
|
6662
|
+
...entry.answer && typeof entry.answer === "object" && !Array.isArray(entry.answer) ? { answer: entry.answer } : {},
|
|
6663
|
+
...typeof entry.display === "string" ? { display: entry.display } : {},
|
|
6664
|
+
...typeof entry.interactionId === "string" ? { interactionId: entry.interactionId } : {},
|
|
6665
|
+
updatedAt: entry.updatedAt
|
|
6666
|
+
};
|
|
6667
|
+
}
|
|
6668
|
+
function snapshot(entry) {
|
|
6669
|
+
return {
|
|
6670
|
+
form: entry.form,
|
|
6671
|
+
ctx: minimalFormContext(entry.ctx),
|
|
6672
|
+
userId: entry.userId,
|
|
6673
|
+
createdAt: entry.createdAt,
|
|
6674
|
+
state: entry.state,
|
|
6675
|
+
...entry.answer ? { answer: entry.answer } : {},
|
|
6676
|
+
...entry.display !== undefined ? { display: entry.display } : {},
|
|
6677
|
+
...entry.interactionId ? { interactionId: entry.interactionId } : {},
|
|
6678
|
+
updatedAt: entry.updatedAt
|
|
6679
|
+
};
|
|
6680
|
+
}
|
|
6681
|
+
function createFormJournal(path = defaultFormJournalPath()) {
|
|
6682
|
+
function read() {
|
|
6683
|
+
try {
|
|
6684
|
+
if (!existsSync8(path))
|
|
6685
|
+
return [];
|
|
6686
|
+
const raw = JSON.parse(readFileSync10(path, "utf-8"));
|
|
6687
|
+
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
6688
|
+
const byUser = new Map;
|
|
6689
|
+
for (const value of values) {
|
|
6690
|
+
const entry = normalizeEntry(value);
|
|
6691
|
+
if (!entry)
|
|
6692
|
+
continue;
|
|
6693
|
+
const previous = byUser.get(entry.userId);
|
|
6694
|
+
if (!previous || previous.updatedAt <= entry.updatedAt)
|
|
6695
|
+
byUser.set(entry.userId, entry);
|
|
6696
|
+
}
|
|
6697
|
+
return [...byUser.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
6698
|
+
} catch (error) {
|
|
6699
|
+
console.warn("[form-journal] 台账读取失败,按空台账处理:", error instanceof Error ? error.message : error);
|
|
6700
|
+
return [];
|
|
6701
|
+
}
|
|
6702
|
+
}
|
|
6703
|
+
function write(entries) {
|
|
6704
|
+
mkdirSync8(dirname(path), { recursive: true });
|
|
6705
|
+
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6706
|
+
const payload = { version: 1, entries: entries.map(snapshot) };
|
|
6707
|
+
try {
|
|
6708
|
+
writeFileSync10(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
|
|
6709
|
+
renameSync3(tmp, path);
|
|
6710
|
+
} catch (error) {
|
|
6711
|
+
try {
|
|
6712
|
+
unlinkSync4(tmp);
|
|
6713
|
+
} catch {}
|
|
6714
|
+
throw error;
|
|
6715
|
+
}
|
|
6716
|
+
}
|
|
6717
|
+
function withLock(fn) {
|
|
6718
|
+
mkdirSync8(dirname(path), { recursive: true });
|
|
6719
|
+
const lockPath = `${path}.lock`;
|
|
6720
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6721
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
6722
|
+
for (;; ) {
|
|
6723
|
+
try {
|
|
6724
|
+
const fd = openSync2(lockPath, "wx", 384);
|
|
6725
|
+
try {
|
|
6726
|
+
writeFileSync10(fd, token);
|
|
6727
|
+
} finally {
|
|
6728
|
+
closeSync2(fd);
|
|
6729
|
+
}
|
|
6730
|
+
break;
|
|
6731
|
+
} catch (error) {
|
|
6732
|
+
try {
|
|
6733
|
+
if (Date.now() - statSync4(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
6734
|
+
unlinkSync4(lockPath);
|
|
6735
|
+
} catch {}
|
|
6736
|
+
if (Date.now() >= deadline) {
|
|
6737
|
+
throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6738
|
+
}
|
|
6739
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
6740
|
+
}
|
|
6741
|
+
}
|
|
6742
|
+
try {
|
|
6743
|
+
return fn();
|
|
6744
|
+
} finally {
|
|
6745
|
+
try {
|
|
6746
|
+
if (readFileSync10(lockPath, "utf-8") === token)
|
|
6747
|
+
unlinkSync4(lockPath);
|
|
6748
|
+
} catch {}
|
|
6749
|
+
}
|
|
6750
|
+
}
|
|
6751
|
+
function mutate(fn) {
|
|
6752
|
+
withLock(() => {
|
|
6753
|
+
const entries = read();
|
|
6754
|
+
fn(entries);
|
|
6755
|
+
write(entries);
|
|
6756
|
+
});
|
|
6757
|
+
}
|
|
6758
|
+
return {
|
|
6759
|
+
path,
|
|
6760
|
+
load: read,
|
|
6761
|
+
put(entry) {
|
|
6762
|
+
mutate((entries) => {
|
|
6763
|
+
const index = entries.findIndex((item) => item.userId === entry.userId);
|
|
6764
|
+
if (index >= 0)
|
|
6765
|
+
entries[index] = snapshot(entry);
|
|
6766
|
+
else
|
|
6767
|
+
entries.push(snapshot(entry));
|
|
6768
|
+
});
|
|
6769
|
+
},
|
|
6770
|
+
remove(userId, formID) {
|
|
6771
|
+
mutate((entries) => {
|
|
6772
|
+
const index = entries.findIndex((item) => item.userId === userId && (!formID || item.form.id === formID));
|
|
6773
|
+
if (index >= 0)
|
|
6774
|
+
entries.splice(index, 1);
|
|
6775
|
+
});
|
|
6776
|
+
},
|
|
6777
|
+
clear() {
|
|
6778
|
+
withLock(() => write([]));
|
|
6779
|
+
}
|
|
6780
|
+
};
|
|
6781
|
+
}
|
|
6782
|
+
|
|
6387
6783
|
// src/core/form-bridge.ts
|
|
6388
6784
|
var FORM_PROMPT_TTL_MS = 30 * 60 * 1000;
|
|
6389
6785
|
var LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
6390
6786
|
var BUTTON_LABEL_MAX2 = 10;
|
|
6391
6787
|
var BUTTONS_PER_ROW = 2;
|
|
6788
|
+
var DEFAULT_DRAIN_TIMEOUT_MS = 5000;
|
|
6392
6789
|
function primaryField(form) {
|
|
6393
6790
|
return form.fields.find((f) => !f.hidden);
|
|
6394
6791
|
}
|
|
@@ -6497,7 +6894,8 @@ function decodeFormButton(raw) {
|
|
|
6497
6894
|
try {
|
|
6498
6895
|
const parsed = JSON.parse(raw);
|
|
6499
6896
|
if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
|
|
6500
|
-
|
|
6897
|
+
const interactionId = typeof parsed.i === "string" ? parsed.i : typeof parsed.interactionId === "string" ? parsed.interactionId : undefined;
|
|
6898
|
+
return { t: "form", f: parsed.f, k: parsed.k, v: parsed.v, ...interactionId ? { i: interactionId } : {} };
|
|
6501
6899
|
}
|
|
6502
6900
|
} catch {}
|
|
6503
6901
|
return;
|
|
@@ -6533,66 +6931,279 @@ function buildFormKeyboard(form, ownerOpenid) {
|
|
|
6533
6931
|
}
|
|
6534
6932
|
function createFormBridge(deps) {
|
|
6535
6933
|
const pending = new Map;
|
|
6536
|
-
|
|
6537
|
-
|
|
6538
|
-
|
|
6539
|
-
|
|
6934
|
+
const journal = deps.journal ?? createFormJournal(deps.journalPath);
|
|
6935
|
+
const now = deps.now ?? Date.now;
|
|
6936
|
+
const ttlMs = deps.ttlMs ?? FORM_PROMPT_TTL_MS;
|
|
6937
|
+
const operations = new Set;
|
|
6938
|
+
let accepting = true;
|
|
6939
|
+
function track(promise) {
|
|
6940
|
+
const tracked = promise.finally(() => operations.delete(tracked));
|
|
6941
|
+
operations.add(tracked);
|
|
6942
|
+
return tracked;
|
|
6943
|
+
}
|
|
6944
|
+
function deliver(ctx, text) {
|
|
6945
|
+
return track(deps.safeDeliver(ctx, text).catch((error) => {
|
|
6946
|
+
console.error("[form-bridge] 回执投递失败:", error instanceof Error ? error.message : error);
|
|
6947
|
+
}));
|
|
6948
|
+
}
|
|
6949
|
+
function journalSnapshot(entry) {
|
|
6950
|
+
return {
|
|
6951
|
+
form: entry.form,
|
|
6952
|
+
ctx: minimalFormContext(entry.ctx),
|
|
6953
|
+
userId: entry.userId,
|
|
6954
|
+
createdAt: entry.createdAt,
|
|
6955
|
+
state: entry.state,
|
|
6956
|
+
...entry.answer ? { answer: entry.answer } : {},
|
|
6957
|
+
...entry.display !== undefined ? { display: entry.display } : {},
|
|
6958
|
+
...entry.interactionId ? { interactionId: entry.interactionId } : {},
|
|
6959
|
+
updatedAt: entry.updatedAt
|
|
6960
|
+
};
|
|
6961
|
+
}
|
|
6962
|
+
function transition(entry, state) {
|
|
6963
|
+
const previous = entry.state;
|
|
6964
|
+
const previousUpdatedAt = entry.updatedAt;
|
|
6965
|
+
entry.state = state;
|
|
6966
|
+
entry.updatedAt = now();
|
|
6967
|
+
try {
|
|
6968
|
+
journal.put(journalSnapshot(entry));
|
|
6969
|
+
} catch (error) {
|
|
6970
|
+
entry.state = previous;
|
|
6971
|
+
entry.updatedAt = previousUpdatedAt;
|
|
6972
|
+
throw error;
|
|
6973
|
+
}
|
|
6974
|
+
}
|
|
6975
|
+
function clearEntry(userId, entry) {
|
|
6976
|
+
if (pending.get(userId) !== entry)
|
|
6977
|
+
return false;
|
|
6540
6978
|
if (entry.timer)
|
|
6541
6979
|
clearTimeout(entry.timer);
|
|
6980
|
+
entry.timer = null;
|
|
6542
6981
|
pending.delete(userId);
|
|
6543
|
-
|
|
6982
|
+
try {
|
|
6983
|
+
journal.remove(userId, entry.form.id);
|
|
6984
|
+
} catch (error) {
|
|
6985
|
+
console.error("[form-bridge] 清理表单台账失败:", error instanceof Error ? error.message : error);
|
|
6986
|
+
}
|
|
6987
|
+
return true;
|
|
6544
6988
|
}
|
|
6545
|
-
function
|
|
6546
|
-
|
|
6547
|
-
|
|
6989
|
+
function isCurrent(userId, entry) {
|
|
6990
|
+
return pending.get(userId) === entry;
|
|
6991
|
+
}
|
|
6992
|
+
function submit(userId, entry, answer, display, interactionId) {
|
|
6993
|
+
if (!isCurrent(userId, entry) || entry.replying || entry.cancelling)
|
|
6994
|
+
return;
|
|
6995
|
+
entry.answer = answer;
|
|
6996
|
+
entry.display = display;
|
|
6997
|
+
if (interactionId)
|
|
6998
|
+
entry.interactionId = interactionId;
|
|
6999
|
+
entry.replying = true;
|
|
7000
|
+
try {
|
|
7001
|
+
transition(entry, "submitting");
|
|
7002
|
+
} catch (error) {
|
|
7003
|
+
entry.replying = false;
|
|
7004
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
7005
|
+
deliver(entry.ctx, `⚠️ 无法保存提交状态,尚未向服务端作答:${msg};请回桌面处理`);
|
|
7006
|
+
return;
|
|
7007
|
+
}
|
|
7008
|
+
const operation = (async () => {
|
|
6548
7009
|
try {
|
|
6549
|
-
await deps.client.form.reply({
|
|
6550
|
-
|
|
6551
|
-
|
|
6552
|
-
}
|
|
6553
|
-
console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${form.id} answer=${display}`);
|
|
7010
|
+
await deps.client.form.reply({
|
|
7011
|
+
path: { sessionID: entry.form.sessionID, formID: entry.form.id },
|
|
7012
|
+
body: { answer }
|
|
7013
|
+
});
|
|
6554
7014
|
} catch (error) {
|
|
7015
|
+
entry.replying = false;
|
|
6555
7016
|
const msg = error instanceof Error ? error.message : String(error);
|
|
6556
|
-
if (
|
|
6557
|
-
|
|
7017
|
+
if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
|
|
7018
|
+
if (isCurrent(userId, entry))
|
|
7019
|
+
clearEntry(userId, entry);
|
|
7020
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效");
|
|
6558
7021
|
} else {
|
|
6559
|
-
|
|
7022
|
+
await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`);
|
|
6560
7023
|
}
|
|
7024
|
+
return;
|
|
6561
7025
|
}
|
|
6562
|
-
|
|
7026
|
+
entry.replying = false;
|
|
7027
|
+
if (isCurrent(userId, entry)) {
|
|
7028
|
+
try {
|
|
7029
|
+
transition(entry, "replied");
|
|
7030
|
+
} catch (error) {
|
|
7031
|
+
console.error("[form-bridge] replied 状态落盘失败:", error instanceof Error ? error.message : error);
|
|
7032
|
+
}
|
|
7033
|
+
clearEntry(userId, entry);
|
|
7034
|
+
}
|
|
7035
|
+
console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${entry.form.id} answer=${display}`);
|
|
7036
|
+
})().catch((error) => {
|
|
7037
|
+
entry.replying = false;
|
|
7038
|
+
console.error("[form-bridge] 提交流程异常:", error instanceof Error ? error.message : error);
|
|
7039
|
+
});
|
|
7040
|
+
track(operation);
|
|
7041
|
+
}
|
|
7042
|
+
async function expireEntry(userId, entry) {
|
|
7043
|
+
if (!isCurrent(userId, entry) || entry.replying || entry.cancelling || entry.state === "expired" && entry.cancelling)
|
|
7044
|
+
return;
|
|
7045
|
+
entry.cancelling = true;
|
|
7046
|
+
if (entry.timer)
|
|
7047
|
+
clearTimeout(entry.timer);
|
|
7048
|
+
entry.timer = null;
|
|
7049
|
+
try {
|
|
7050
|
+
transition(entry, "expired");
|
|
7051
|
+
} catch (error) {
|
|
7052
|
+
entry.cancelling = false;
|
|
7053
|
+
await deliver(entry.ctx, `⚠️ 选择已到期,但取消状态无法落盘;请回桌面处理:${error instanceof Error ? error.message : error}`);
|
|
7054
|
+
return;
|
|
7055
|
+
}
|
|
7056
|
+
try {
|
|
7057
|
+
await deps.client.form.cancel({ path: { sessionID: entry.form.sessionID, formID: entry.form.id } });
|
|
7058
|
+
} catch (error) {
|
|
7059
|
+
entry.cancelling = false;
|
|
7060
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
7061
|
+
await deliver(entry.ctx, `⚠️ 选择请求已到期,但服务端取消失败(${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg});本地已保留恢复记录,请回桌面确认`);
|
|
7062
|
+
return;
|
|
7063
|
+
}
|
|
7064
|
+
entry.cancelling = false;
|
|
7065
|
+
if (isCurrent(userId, entry)) {
|
|
7066
|
+
try {
|
|
7067
|
+
transition(entry, "cancelled");
|
|
7068
|
+
} catch (error) {
|
|
7069
|
+
console.error("[form-bridge] cancelled 状态落盘失败:", error instanceof Error ? error.message : error);
|
|
7070
|
+
}
|
|
7071
|
+
clearEntry(userId, entry);
|
|
7072
|
+
}
|
|
7073
|
+
await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;如需继续请回桌面重试");
|
|
7074
|
+
}
|
|
7075
|
+
function scheduleExpiry(userId, entry) {
|
|
7076
|
+
if (!accepting)
|
|
7077
|
+
return;
|
|
7078
|
+
const remaining = Math.max(0, entry.createdAt + ttlMs - now());
|
|
7079
|
+
entry.timer = setTimeout(() => {
|
|
7080
|
+
track(expireEntry(userId, entry));
|
|
7081
|
+
}, remaining);
|
|
7082
|
+
entry.timer.unref?.();
|
|
7083
|
+
}
|
|
7084
|
+
function restore() {
|
|
7085
|
+
const sessions = new Set;
|
|
7086
|
+
for (const saved of journal.load()) {
|
|
7087
|
+
sessions.add(saved.form.sessionID);
|
|
7088
|
+
if (saved.state === "replied" || saved.state === "cancelled") {
|
|
7089
|
+
try {
|
|
7090
|
+
journal.remove(saved.userId, saved.form.id);
|
|
7091
|
+
} catch {}
|
|
7092
|
+
continue;
|
|
7093
|
+
}
|
|
7094
|
+
const entry = {
|
|
7095
|
+
...saved,
|
|
7096
|
+
ctx: minimalFormContext({ ...saved.ctx, userId: saved.userId }),
|
|
7097
|
+
timer: null,
|
|
7098
|
+
restored: true,
|
|
7099
|
+
replying: false,
|
|
7100
|
+
cancelling: false
|
|
7101
|
+
};
|
|
7102
|
+
const previous = pending.get(saved.userId);
|
|
7103
|
+
if (previous && previous.updatedAt > entry.updatedAt)
|
|
7104
|
+
continue;
|
|
7105
|
+
if (previous?.timer)
|
|
7106
|
+
clearTimeout(previous.timer);
|
|
7107
|
+
pending.set(saved.userId, entry);
|
|
7108
|
+
scheduleExpiry(saved.userId, entry);
|
|
7109
|
+
console.log(`[form-bridge] 恢复本地表单 user=${saved.userId.slice(0, 8)}… form=${saved.form.id} state=${saved.state}`);
|
|
7110
|
+
}
|
|
7111
|
+
return [...sessions];
|
|
7112
|
+
}
|
|
7113
|
+
async function reconcile(sessionID) {
|
|
7114
|
+
let forms;
|
|
7115
|
+
try {
|
|
7116
|
+
forms = (await deps.client.form.list({ sessionID })).data ?? [];
|
|
7117
|
+
} catch (error) {
|
|
7118
|
+
console.error(`[form-bridge] 会话表单对账失败 session=${sessionID}:`, error instanceof Error ? error.message : error);
|
|
7119
|
+
return false;
|
|
7120
|
+
}
|
|
7121
|
+
const candidates = [...pending.entries()].filter(([, entry]) => entry.form.sessionID === sessionID);
|
|
7122
|
+
for (const [userId, entry] of candidates) {
|
|
7123
|
+
if (!isCurrent(userId, entry))
|
|
7124
|
+
continue;
|
|
7125
|
+
const server = forms.find((form) => form.id === entry.form.id);
|
|
7126
|
+
const serverStatus = typeof server?.state === "string" ? server.state : server?.state?.status;
|
|
7127
|
+
const serverPending = server !== undefined && (!serverStatus || serverStatus === "pending");
|
|
7128
|
+
if (!serverPending) {
|
|
7129
|
+
clearEntry(userId, entry);
|
|
7130
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效");
|
|
7131
|
+
continue;
|
|
7132
|
+
}
|
|
7133
|
+
if (entry.state === "expired") {
|
|
7134
|
+
if (!entry.cancelling)
|
|
7135
|
+
await track(expireEntry(userId, entry));
|
|
7136
|
+
} else if ((entry.state === "clickReceived" || entry.state === "submitting") && entry.answer && !entry.replying) {
|
|
7137
|
+
submit(userId, entry, entry.answer, entry.display ?? "已恢复的选择", entry.interactionId);
|
|
7138
|
+
}
|
|
7139
|
+
}
|
|
7140
|
+
return true;
|
|
6563
7141
|
}
|
|
6564
7142
|
function pushForm(userId, ctx, form) {
|
|
7143
|
+
if (!accepting) {
|
|
7144
|
+
deliver(ctx, "⚠️ 表单桥正在停止,暂不接受新的 QQ 作答;请回桌面处理");
|
|
7145
|
+
return;
|
|
7146
|
+
}
|
|
6565
7147
|
if (pending.get(userId)?.form.id === form.id)
|
|
6566
7148
|
return;
|
|
6567
|
-
const
|
|
6568
|
-
|
|
6569
|
-
|
|
7149
|
+
const liveCtx = { ...minimalFormContext(ctx), msgId: ctx.msgId };
|
|
7150
|
+
const timestamp = now();
|
|
7151
|
+
const entry = {
|
|
7152
|
+
form,
|
|
7153
|
+
ctx: liveCtx,
|
|
7154
|
+
userId,
|
|
7155
|
+
createdAt: timestamp,
|
|
7156
|
+
state: "pending",
|
|
7157
|
+
updatedAt: timestamp,
|
|
7158
|
+
timer: null,
|
|
7159
|
+
replying: false,
|
|
7160
|
+
cancelling: false
|
|
7161
|
+
};
|
|
7162
|
+
try {
|
|
7163
|
+
journal.put(journalSnapshot(entry));
|
|
7164
|
+
} catch (error) {
|
|
7165
|
+
console.error("[form-bridge] 表单落盘失败,取消 QQ 推送:", error instanceof Error ? error.message : error);
|
|
7166
|
+
deliver(ctx, "⚠️ 选择请求无法保存恢复记录,本次未推送到 QQ;请回桌面处理");
|
|
7167
|
+
return;
|
|
6570
7168
|
}
|
|
6571
|
-
const
|
|
6572
|
-
|
|
6573
|
-
|
|
6574
|
-
return;
|
|
6575
|
-
clear(userId);
|
|
6576
|
-
deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {});
|
|
6577
|
-
}, FORM_PROMPT_TTL_MS);
|
|
7169
|
+
const previous = pending.get(userId);
|
|
7170
|
+
if (previous?.timer)
|
|
7171
|
+
clearTimeout(previous.timer);
|
|
6578
7172
|
pending.set(userId, entry);
|
|
7173
|
+
scheduleExpiry(userId, entry);
|
|
7174
|
+
if (previous) {
|
|
7175
|
+
deliver(previous.ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)");
|
|
7176
|
+
}
|
|
6579
7177
|
console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`);
|
|
6580
|
-
(async () => {
|
|
6581
|
-
const keyboard = buildFormKeyboard(form,
|
|
7178
|
+
const operation = (async () => {
|
|
7179
|
+
const keyboard = buildFormKeyboard(form, liveCtx.userId);
|
|
6582
7180
|
if (keyboard && deps.sendFormCard) {
|
|
6583
|
-
const sent = await deps.sendFormCard(
|
|
7181
|
+
const sent = await deps.sendFormCard(liveCtx, form, keyboard).catch(() => false);
|
|
6584
7182
|
if (sent)
|
|
6585
7183
|
return;
|
|
6586
7184
|
}
|
|
6587
|
-
await deps.sendReply(
|
|
7185
|
+
await deps.sendReply(liveCtx, renderFormPrompt(form)).catch((error) => {
|
|
6588
7186
|
console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error);
|
|
6589
7187
|
});
|
|
6590
7188
|
})();
|
|
7189
|
+
track(operation);
|
|
6591
7190
|
}
|
|
6592
7191
|
function tryResolveText(userId, text) {
|
|
6593
7192
|
const entry = pending.get(userId);
|
|
6594
7193
|
if (!entry)
|
|
6595
7194
|
return false;
|
|
7195
|
+
if (!accepting) {
|
|
7196
|
+
deliver(entry.ctx, "⚠️ 表单桥正在停止,本次答案未提交;请回桌面处理");
|
|
7197
|
+
return true;
|
|
7198
|
+
}
|
|
7199
|
+
if (entry.state === "expired") {
|
|
7200
|
+
deliver(entry.ctx, "⚠️ 按钮和文字答案已失效,请使用新卡或回桌面处理");
|
|
7201
|
+
return true;
|
|
7202
|
+
}
|
|
7203
|
+
if (entry.replying || entry.cancelling) {
|
|
7204
|
+
deliver(entry.ctx, "⏳ 选择正在提交或取消,请勿重复操作;稍后会给出最终回执");
|
|
7205
|
+
return true;
|
|
7206
|
+
}
|
|
6596
7207
|
const answer = parseFormAnswer(entry.form, text);
|
|
6597
7208
|
if (!answer) {
|
|
6598
7209
|
const field = primaryField(entry.form);
|
|
@@ -6600,9 +7211,21 @@ function createFormBridge(deps) {
|
|
|
6600
7211
|
deps.sendReply(entry.ctx, hint).catch(() => {});
|
|
6601
7212
|
return true;
|
|
6602
7213
|
}
|
|
6603
|
-
submit(userId, entry
|
|
7214
|
+
submit(userId, entry, answer, text.trim());
|
|
6604
7215
|
return true;
|
|
6605
7216
|
}
|
|
7217
|
+
function eventContext(event, userId) {
|
|
7218
|
+
return {
|
|
7219
|
+
type: event.group_member_openid ? "group" : "c2c",
|
|
7220
|
+
userId,
|
|
7221
|
+
...event.group_member_openid && event.group_openid ? { groupId: event.group_openid } : {},
|
|
7222
|
+
msgId: "",
|
|
7223
|
+
content: ""
|
|
7224
|
+
};
|
|
7225
|
+
}
|
|
7226
|
+
function rejectButton(ctx) {
|
|
7227
|
+
deliver(ctx, "⚠️ 按钮已失效、已处理或不属于当前选择,请使用新卡或回桌面处理");
|
|
7228
|
+
}
|
|
6606
7229
|
function handleButton(event) {
|
|
6607
7230
|
const userId = event.user_openid ?? event.group_member_openid;
|
|
6608
7231
|
if (!userId)
|
|
@@ -6611,91 +7234,178 @@ function createFormBridge(deps) {
|
|
|
6611
7234
|
if (!button)
|
|
6612
7235
|
return false;
|
|
6613
7236
|
const entry = pending.get(userId);
|
|
6614
|
-
|
|
7237
|
+
const ctx = entry?.ctx ?? eventContext(event, userId);
|
|
7238
|
+
if (!accepting || !entry || entry.form.id !== button.f || entry.state === "expired") {
|
|
6615
7239
|
console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`);
|
|
7240
|
+
rejectButton(ctx);
|
|
7241
|
+
return true;
|
|
7242
|
+
}
|
|
7243
|
+
if (entry.replying || entry.cancelling) {
|
|
7244
|
+
deliver(ctx, "⏳ 该按钮已受理,正在等待服务端最终结果,请勿重复点击");
|
|
7245
|
+
return true;
|
|
7246
|
+
}
|
|
7247
|
+
const field = entry.form.fields.find((candidate) => candidate.key === button.k && !candidate.hidden);
|
|
7248
|
+
const option = field?.options?.find((candidate) => candidate.value === button.v);
|
|
7249
|
+
if (!field || field.type !== "string" && field.type !== "multiselect" || !option) {
|
|
7250
|
+
rejectButton(ctx);
|
|
7251
|
+
return true;
|
|
7252
|
+
}
|
|
7253
|
+
const interactionId = button.i ?? event.data?.resolved?.button_id ?? event.id;
|
|
7254
|
+
const answer = { [button.k]: field.type === "multiselect" ? [button.v] : button.v };
|
|
7255
|
+
entry.answer = answer;
|
|
7256
|
+
entry.display = button.v;
|
|
7257
|
+
if (interactionId)
|
|
7258
|
+
entry.interactionId = interactionId;
|
|
7259
|
+
try {
|
|
7260
|
+
transition(entry, "clickReceived");
|
|
7261
|
+
} catch (error) {
|
|
7262
|
+
deliver(ctx, `⚠️ 无法保存按钮受理状态,尚未提交:${error instanceof Error ? error.message : error}`);
|
|
6616
7263
|
return true;
|
|
6617
7264
|
}
|
|
6618
|
-
|
|
6619
|
-
|
|
7265
|
+
submit(userId, entry, answer, button.v, interactionId);
|
|
7266
|
+
return true;
|
|
7267
|
+
}
|
|
7268
|
+
async function drainInteractions(timeoutMs = DEFAULT_DRAIN_TIMEOUT_MS) {
|
|
7269
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
7270
|
+
while (operations.size > 0) {
|
|
7271
|
+
const remaining = deadline - Date.now();
|
|
7272
|
+
if (remaining <= 0)
|
|
7273
|
+
return false;
|
|
7274
|
+
let timer;
|
|
7275
|
+
const timeout = new Promise((resolve) => {
|
|
7276
|
+
timer = setTimeout(() => resolve("timeout"), remaining);
|
|
7277
|
+
});
|
|
7278
|
+
const drained = Promise.allSettled([...operations]).then(() => "drained");
|
|
7279
|
+
const result = await Promise.race([drained, timeout]);
|
|
7280
|
+
if (timer)
|
|
7281
|
+
clearTimeout(timer);
|
|
7282
|
+
if (result === "timeout")
|
|
7283
|
+
return false;
|
|
7284
|
+
}
|
|
6620
7285
|
return true;
|
|
6621
7286
|
}
|
|
6622
|
-
|
|
7287
|
+
function stopAccepting() {
|
|
7288
|
+
accepting = false;
|
|
7289
|
+
for (const entry of pending.values()) {
|
|
7290
|
+
if (entry.timer)
|
|
7291
|
+
clearTimeout(entry.timer);
|
|
7292
|
+
entry.timer = null;
|
|
7293
|
+
}
|
|
7294
|
+
}
|
|
7295
|
+
return {
|
|
7296
|
+
pushForm,
|
|
7297
|
+
tryResolveText,
|
|
7298
|
+
handleButton,
|
|
7299
|
+
hasPending: (userId) => pending.has(userId),
|
|
7300
|
+
getPending: (userId) => pending.get(userId),
|
|
7301
|
+
restore,
|
|
7302
|
+
reconcile,
|
|
7303
|
+
drainInteractions,
|
|
7304
|
+
stopAccepting
|
|
7305
|
+
};
|
|
6623
7306
|
}
|
|
6624
7307
|
|
|
6625
7308
|
// src/core/inflight-journal.ts
|
|
6626
|
-
import { existsSync as
|
|
6627
|
-
import { join as
|
|
6628
|
-
import { homedir as
|
|
7309
|
+
import { existsSync as existsSync9, readFileSync as readFileSync11, writeFileSync as writeFileSync11, mkdirSync as mkdirSync9, renameSync as renameSync4, openSync as openSync3, closeSync as closeSync3, unlinkSync as unlinkSync5, statSync as statSync5 } from "fs";
|
|
7310
|
+
import { join as join11 } from "path";
|
|
7311
|
+
import { homedir as homedir10 } from "os";
|
|
7312
|
+
|
|
7313
|
+
// src/core/inbound-dedupe.ts
|
|
7314
|
+
import { createHash as createHash2 } from "crypto";
|
|
7315
|
+
function messageFingerprint(userId, intentKey) {
|
|
7316
|
+
return createHash2("sha256").update(`${userId}\x00${intentKey}`).digest("hex").slice(0, 32);
|
|
7317
|
+
}
|
|
7318
|
+
function admissionDecision(input) {
|
|
7319
|
+
if (input.hasSameMsgIdInflight)
|
|
7320
|
+
return "duplicate-msgid";
|
|
7321
|
+
if (input.fingerprint && input.inflightFingerprints.includes(input.fingerprint)) {
|
|
7322
|
+
return "duplicate-intent";
|
|
7323
|
+
}
|
|
7324
|
+
return "ok";
|
|
7325
|
+
}
|
|
7326
|
+
|
|
7327
|
+
// src/core/inflight-journal.ts
|
|
7328
|
+
function newInflightAttemptId() {
|
|
7329
|
+
return `att-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
7330
|
+
}
|
|
6629
7331
|
var INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
7332
|
+
var SETTLED_RETENTION_MS = INFLIGHT_MAX_AGE_MS;
|
|
7333
|
+
var SETTLED_RETENTION_LIMIT = 20;
|
|
7334
|
+
function pruneInflightEntries(entries, now = Date.now()) {
|
|
7335
|
+
const indexed = entries.map((entry, index) => ({ entry, index }));
|
|
7336
|
+
const retainedSettled = new Set(indexed.filter(({ entry }) => entry.state === "settled" && now - entry.at <= SETTLED_RETENTION_MS).sort((a, b) => b.entry.at - a.entry.at || b.index - a.index).slice(0, SETTLED_RETENTION_LIMIT).map(({ index }) => index));
|
|
7337
|
+
return indexed.filter(({ entry, index }) => entry.state === "inflight" || retainedSettled.has(index)).sort((a, b) => a.entry.at - b.entry.at || a.index - b.index).map(({ entry }) => entry);
|
|
7338
|
+
}
|
|
6630
7339
|
function redispatchMaxAgeMs() {
|
|
6631
7340
|
const n = Number(process.env.QQ_REDISPATCH_MAX_AGE_MS ?? "7200000");
|
|
6632
7341
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7200000;
|
|
6633
7342
|
}
|
|
6634
7343
|
function journalPath() {
|
|
6635
|
-
return process.env.QQ_INFLIGHT_FILE ||
|
|
7344
|
+
return process.env.QQ_INFLIGHT_FILE || join11(homedir10(), ".openqq", "inflight.json");
|
|
6636
7345
|
}
|
|
6637
7346
|
function load() {
|
|
6638
7347
|
let entries = [];
|
|
6639
7348
|
try {
|
|
6640
|
-
if (
|
|
6641
|
-
const raw = JSON.parse(
|
|
7349
|
+
if (existsSync9(journalPath())) {
|
|
7350
|
+
const raw = JSON.parse(readFileSync11(journalPath(), "utf-8"));
|
|
6642
7351
|
if (Array.isArray(raw))
|
|
6643
7352
|
entries = raw;
|
|
6644
7353
|
}
|
|
6645
7354
|
} catch {
|
|
6646
7355
|
entries = [];
|
|
6647
7356
|
}
|
|
6648
|
-
return entries
|
|
7357
|
+
return pruneInflightEntries(entries);
|
|
6649
7358
|
}
|
|
6650
7359
|
function save(entries) {
|
|
6651
7360
|
const path = journalPath();
|
|
6652
|
-
|
|
7361
|
+
mkdirSync9(join11(path, ".."), { recursive: true });
|
|
7362
|
+
const retained = pruneInflightEntries(entries);
|
|
6653
7363
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6654
7364
|
try {
|
|
6655
|
-
|
|
6656
|
-
|
|
7365
|
+
writeFileSync11(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
|
|
7366
|
+
renameSync4(tmp, path);
|
|
6657
7367
|
} catch (error) {
|
|
6658
7368
|
try {
|
|
6659
|
-
|
|
7369
|
+
unlinkSync5(tmp);
|
|
6660
7370
|
} catch {}
|
|
6661
7371
|
throw error;
|
|
6662
7372
|
}
|
|
6663
7373
|
}
|
|
6664
7374
|
var JOURNAL_LOCK_STALE_MS = 30000;
|
|
6665
7375
|
var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
6666
|
-
var
|
|
7376
|
+
var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
|
|
6667
7377
|
function withJournalLock(fn) {
|
|
6668
7378
|
const path = journalPath();
|
|
6669
|
-
|
|
7379
|
+
mkdirSync9(join11(path, ".."), { recursive: true });
|
|
6670
7380
|
const lockPath = `${path}.lock`;
|
|
6671
7381
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6672
7382
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
6673
7383
|
for (;; ) {
|
|
6674
7384
|
try {
|
|
6675
|
-
const fd =
|
|
7385
|
+
const fd = openSync3(lockPath, "wx", 384);
|
|
6676
7386
|
try {
|
|
6677
|
-
|
|
7387
|
+
writeFileSync11(fd, token);
|
|
6678
7388
|
} finally {
|
|
6679
|
-
|
|
7389
|
+
closeSync3(fd);
|
|
6680
7390
|
}
|
|
6681
7391
|
break;
|
|
6682
7392
|
} catch (error) {
|
|
6683
7393
|
try {
|
|
6684
|
-
if (Date.now() -
|
|
6685
|
-
|
|
7394
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
7395
|
+
unlinkSync5(lockPath);
|
|
6686
7396
|
} catch {}
|
|
6687
7397
|
if (Date.now() >= deadline) {
|
|
6688
7398
|
throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6689
7399
|
}
|
|
6690
|
-
Atomics.wait(
|
|
7400
|
+
Atomics.wait(sleepArray2, 0, 0, 10);
|
|
6691
7401
|
}
|
|
6692
7402
|
}
|
|
6693
7403
|
try {
|
|
6694
7404
|
return fn();
|
|
6695
7405
|
} finally {
|
|
6696
7406
|
try {
|
|
6697
|
-
if (
|
|
6698
|
-
|
|
7407
|
+
if (readFileSync11(lockPath, "utf-8") === token)
|
|
7408
|
+
unlinkSync5(lockPath);
|
|
6699
7409
|
} catch {}
|
|
6700
7410
|
}
|
|
6701
7411
|
}
|
|
@@ -6707,38 +7417,72 @@ function mutate(fn) {
|
|
|
6707
7417
|
return result;
|
|
6708
7418
|
});
|
|
6709
7419
|
}
|
|
6710
|
-
function
|
|
7420
|
+
function claimInflightDetailed(entry, opts) {
|
|
6711
7421
|
return mutate((entries) => {
|
|
6712
|
-
|
|
6713
|
-
|
|
6714
|
-
|
|
6715
|
-
|
|
7422
|
+
const fingerprint = opts?.fingerprint ?? entry.fingerprint ?? "";
|
|
7423
|
+
const decision = admissionDecision({
|
|
7424
|
+
hasSameMsgIdInflight: entries.some((e) => e.msgId === entry.msgId && e.state === "inflight"),
|
|
7425
|
+
fingerprint,
|
|
7426
|
+
inflightFingerprints: entries.filter((e) => e.state === "inflight" && e.fingerprint).map((e) => e.fingerprint)
|
|
7427
|
+
});
|
|
7428
|
+
if (decision !== "ok")
|
|
7429
|
+
return decision;
|
|
7430
|
+
const attempt = entry.attemptId ?? newInflightAttemptId();
|
|
7431
|
+
const existing = entries.find((e) => e.msgId === entry.msgId);
|
|
7432
|
+
if (existing) {
|
|
7433
|
+
Object.assign(existing, entry, { fingerprint, attemptId: attempt, state: "inflight" });
|
|
7434
|
+
} else {
|
|
7435
|
+
entries.push({ ...entry, fingerprint, attemptId: attempt, state: "inflight" });
|
|
7436
|
+
}
|
|
7437
|
+
return "ok";
|
|
6716
7438
|
});
|
|
6717
7439
|
}
|
|
6718
7440
|
function recordInflight(entry) {
|
|
6719
7441
|
mutate((entries) => {
|
|
6720
7442
|
const existing = entries.find((e) => e.msgId === entry.msgId);
|
|
6721
7443
|
if (existing) {
|
|
6722
|
-
if (
|
|
6723
|
-
existing.
|
|
7444
|
+
if (existing.state === "inflight") {
|
|
7445
|
+
if (entry.attemptId && existing.attemptId && entry.attemptId !== existing.attemptId)
|
|
7446
|
+
return;
|
|
7447
|
+
if (!existing.sessionId && entry.sessionId)
|
|
7448
|
+
existing.sessionId = entry.sessionId;
|
|
7449
|
+
if (!existing.promptId && entry.promptId)
|
|
7450
|
+
existing.promptId = entry.promptId;
|
|
7451
|
+
return;
|
|
7452
|
+
}
|
|
7453
|
+
const attempt = entry.attemptId ?? newInflightAttemptId();
|
|
7454
|
+
Object.assign(existing, entry, { attemptId: attempt, state: "inflight" });
|
|
6724
7455
|
return;
|
|
6725
7456
|
}
|
|
6726
|
-
entries.push({ ...entry, state: "inflight" });
|
|
7457
|
+
entries.push({ ...entry, attemptId: entry.attemptId ?? newInflightAttemptId(), state: "inflight" });
|
|
6727
7458
|
});
|
|
6728
7459
|
}
|
|
6729
|
-
function settleInflight(msgId) {
|
|
6730
|
-
mutate((entries) => {
|
|
6731
|
-
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
|
|
6732
|
-
if (entry)
|
|
6733
|
-
|
|
7460
|
+
function settleInflight(msgId, attemptId) {
|
|
7461
|
+
return mutate((entries) => {
|
|
7462
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight" && (!attemptId || !e.attemptId || e.attemptId === attemptId));
|
|
7463
|
+
if (!entry)
|
|
7464
|
+
return false;
|
|
7465
|
+
entry.state = "settled";
|
|
7466
|
+
return true;
|
|
6734
7467
|
});
|
|
6735
7468
|
}
|
|
6736
7469
|
function pendingInflight() {
|
|
6737
7470
|
return load().filter((e) => e.state === "inflight");
|
|
6738
7471
|
}
|
|
7472
|
+
function markInflightPromptId(msgId, promptId) {
|
|
7473
|
+
if (!promptId)
|
|
7474
|
+
return;
|
|
7475
|
+
mutate((entries) => {
|
|
7476
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
|
|
7477
|
+
if (entry && !entry.promptId)
|
|
7478
|
+
entry.promptId = promptId;
|
|
7479
|
+
});
|
|
7480
|
+
}
|
|
7481
|
+
var TIME_ANCHOR_TOLERANCE_MS = 120000;
|
|
7482
|
+
var PROBE_LENGTH = 100;
|
|
6739
7483
|
function classifyInflight(entry, messages) {
|
|
6740
7484
|
const ordered = [...messages].reverse();
|
|
6741
|
-
const probe = entry.text.trim().slice(0,
|
|
7485
|
+
const probe = entry.text.trim().slice(0, PROBE_LENGTH);
|
|
6742
7486
|
let userIdx = -1;
|
|
6743
7487
|
if (probe === "") {
|
|
6744
7488
|
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
@@ -6755,6 +7499,36 @@ function classifyInflight(entry, messages) {
|
|
|
6755
7499
|
}
|
|
6756
7500
|
}
|
|
6757
7501
|
}
|
|
7502
|
+
if (userIdx < 0 && probe === "" && entry.at !== undefined) {
|
|
7503
|
+
let bestIdx = -1;
|
|
7504
|
+
let bestDelta = Number.POSITIVE_INFINITY;
|
|
7505
|
+
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
7506
|
+
if (ordered[i].type !== "user")
|
|
7507
|
+
continue;
|
|
7508
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - entry.at);
|
|
7509
|
+
if (delta < bestDelta) {
|
|
7510
|
+
bestDelta = delta;
|
|
7511
|
+
bestIdx = i;
|
|
7512
|
+
}
|
|
7513
|
+
}
|
|
7514
|
+
if (bestIdx >= 0 && bestDelta <= TIME_ANCHOR_TOLERANCE_MS)
|
|
7515
|
+
userIdx = bestIdx;
|
|
7516
|
+
}
|
|
7517
|
+
if (userIdx < 0 && entry.at !== undefined) {
|
|
7518
|
+
let bestIdx = -1;
|
|
7519
|
+
let bestDelta = Number.POSITIVE_INFINITY;
|
|
7520
|
+
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
7521
|
+
if (ordered[i].type !== "user")
|
|
7522
|
+
continue;
|
|
7523
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - entry.at);
|
|
7524
|
+
if (delta < bestDelta) {
|
|
7525
|
+
bestDelta = delta;
|
|
7526
|
+
bestIdx = i;
|
|
7527
|
+
}
|
|
7528
|
+
}
|
|
7529
|
+
if (bestIdx >= 0 && bestDelta <= TIME_ANCHOR_TOLERANCE_MS)
|
|
7530
|
+
userIdx = bestIdx;
|
|
7531
|
+
}
|
|
6758
7532
|
if (userIdx < 0)
|
|
6759
7533
|
return { kind: "lost" };
|
|
6760
7534
|
let turnEnd = ordered.length;
|
|
@@ -6791,6 +7565,12 @@ function evictableIdleSessions(lastActivity, watched, now, idleMs) {
|
|
|
6791
7565
|
}
|
|
6792
7566
|
return out;
|
|
6793
7567
|
}
|
|
7568
|
+
function stallNudgeText(minsExec, s) {
|
|
7569
|
+
const status = !s.anchored ? "状态不明(历史账无归属锚点)" : s.roundRunning ? "已停滞(回合尚未终结,可能被桌面端审批/选择弹窗阻塞)" : "已终结但未回传(异常)";
|
|
7570
|
+
const action = s.lastAction ? `|最近动作:${s.lastAction}` : "";
|
|
7571
|
+
return `⚠️ 后台任务执行超过 ${minsExec} 分钟|状态:${status}|已 ${s.idleMin} 分钟无进展${action}
|
|
7572
|
+
桌面端确实空闲请忽略本提醒;或回复 /stop 中止该回合后重发。`;
|
|
7573
|
+
}
|
|
6794
7574
|
function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, intervalMs, maxNudges) {
|
|
6795
7575
|
if (nudges >= maxNudges)
|
|
6796
7576
|
return "wait";
|
|
@@ -6799,8 +7579,11 @@ function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, int
|
|
|
6799
7579
|
return now - base >= need ? "nudge" : "wait";
|
|
6800
7580
|
}
|
|
6801
7581
|
function createBridge(config, client, sessions) {
|
|
7582
|
+
const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "");
|
|
6802
7583
|
const busyUsers = new Set;
|
|
6803
7584
|
const claimedContexts = new WeakSet;
|
|
7585
|
+
const drainReentries = new WeakSet;
|
|
7586
|
+
const activeIntents = new Map;
|
|
6804
7587
|
const msgQueue = new MessageQueue(QUEUE_MAX);
|
|
6805
7588
|
const draining = new Set;
|
|
6806
7589
|
const greeted = loadGreetedSet();
|
|
@@ -6877,7 +7660,8 @@ function createBridge(config, client, sessions) {
|
|
|
6877
7660
|
const STALL_FIRST_NUDGE_MS = 30 * 60 * 1000;
|
|
6878
7661
|
const STALL_NUDGE_INTERVAL_MS = 30 * 60 * 1000;
|
|
6879
7662
|
const STALL_NUDGE_MAX = 3;
|
|
6880
|
-
function startBackgroundWait(sessionId, ctx, baseline, trackId) {
|
|
7663
|
+
function startBackgroundWait(sessionId, ctx, baseline, trackId, promptId = "") {
|
|
7664
|
+
bgWaits.get(sessionId)?.cancel();
|
|
6881
7665
|
let cancelled = false;
|
|
6882
7666
|
let finished = false;
|
|
6883
7667
|
const startedAt = Date.now();
|
|
@@ -6892,9 +7676,26 @@ function createBridge(config, client, sessions) {
|
|
|
6892
7676
|
bgWaits.delete(sessionId);
|
|
6893
7677
|
mirror.scheduleUnlock(sessionId);
|
|
6894
7678
|
};
|
|
7679
|
+
function classifyNow(listJson) {
|
|
7680
|
+
const msgs = listJson?.data ?? [];
|
|
7681
|
+
const turn = turnStateOf(msgs, promptId, baseline);
|
|
7682
|
+
if (!turn.anchored)
|
|
7683
|
+
return { done: turn.hasIdle, text: collectReplyText(msgs, baseline) };
|
|
7684
|
+
return { done: turn.hasIdle, text: turn.text };
|
|
7685
|
+
}
|
|
6895
7686
|
async function finish(kind) {
|
|
6896
7687
|
if (cancelled || finished)
|
|
6897
7688
|
return;
|
|
7689
|
+
if (kind === "done" && promptId) {
|
|
7690
|
+
try {
|
|
7691
|
+
const probe = await client.session.messages({ path: { id: sessionId } });
|
|
7692
|
+
const turn = turnStateOf(probe?.data ?? [], promptId, baseline);
|
|
7693
|
+
if (turn.anchored && !turn.hasIdle) {
|
|
7694
|
+
console.log(`[bridge] 忽略他回合完成事件(本后台回合尚未结束)session=${sessionId}`);
|
|
7695
|
+
return;
|
|
7696
|
+
}
|
|
7697
|
+
} catch {}
|
|
7698
|
+
}
|
|
6898
7699
|
finished = true;
|
|
6899
7700
|
cleanup();
|
|
6900
7701
|
if (trackId)
|
|
@@ -6907,7 +7708,7 @@ function createBridge(config, client, sessions) {
|
|
|
6907
7708
|
await new Promise((r) => setTimeout(r, 2000));
|
|
6908
7709
|
try {
|
|
6909
7710
|
const listJson = await client.session.messages({ path: { id: sessionId } });
|
|
6910
|
-
const text =
|
|
7711
|
+
const { text } = classifyNow(listJson);
|
|
6911
7712
|
await safeDeliver(ctx, text ? `\uD83D\uDCE4 后台任务完成,结果如下:
|
|
6912
7713
|
|
|
6913
7714
|
${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用 /history 查看");
|
|
@@ -6922,6 +7723,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6922
7723
|
try {
|
|
6923
7724
|
const listJson = await client.session.messages({ path: { id: sessionId } });
|
|
6924
7725
|
const msgs = listJson?.data ?? [];
|
|
7726
|
+
const turn = turnStateOf(msgs, promptId, baseline);
|
|
6925
7727
|
let maxCreated = 0;
|
|
6926
7728
|
for (const m of msgs) {
|
|
6927
7729
|
const created = m.time?.created ?? 0;
|
|
@@ -6936,10 +7738,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6936
7738
|
} else if (stallNudgeDecision(startedAt, lastProgressAt, nudges, now, STALL_FIRST_NUDGE_MS, STALL_NUDGE_INTERVAL_MS, STALL_NUDGE_MAX) === "nudge") {
|
|
6937
7739
|
nudges += 1;
|
|
6938
7740
|
lastProgressAt = now;
|
|
6939
|
-
|
|
6940
|
-
|
|
7741
|
+
const st = turnStats.get(sessionId);
|
|
7742
|
+
const lastAction = st?.lastTool && st?.lastAt ? `${st.lastTool}(${agoLabel(st.lastAt)})` : undefined;
|
|
7743
|
+
console.log(`[bridge] 后台任务状态通告 #${nudges} session=${sessionId} anchored=${turn.anchored}`);
|
|
7744
|
+
safeDeliver(ctx, stallNudgeText(Math.round((now - startedAt) / 60000), {
|
|
7745
|
+
anchored: turn.anchored,
|
|
7746
|
+
roundRunning: turn.anchored && !turn.hasIdle,
|
|
7747
|
+
idleMin: Math.round((now - lastProgressAt) / 60000),
|
|
7748
|
+
lastAction
|
|
7749
|
+
})).catch(() => {});
|
|
6941
7750
|
}
|
|
6942
|
-
if (
|
|
7751
|
+
if (turn.hasIdle) {
|
|
6943
7752
|
await finish("done");
|
|
6944
7753
|
}
|
|
6945
7754
|
} catch (error) {
|
|
@@ -7127,8 +7936,10 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7127
7936
|
purgeOldQQImages();
|
|
7128
7937
|
const handleMessage = async (ctx) => {
|
|
7129
7938
|
let claimedMsgId = "";
|
|
7939
|
+
const intentKey = intentKeyOf(ctx);
|
|
7130
7940
|
try {
|
|
7131
7941
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
7942
|
+
console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`);
|
|
7132
7943
|
await sendReply(ctx, "你不在允许使用的名单里");
|
|
7133
7944
|
return;
|
|
7134
7945
|
}
|
|
@@ -7167,15 +7978,30 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7167
7978
|
}
|
|
7168
7979
|
if (ctx.msgId) {
|
|
7169
7980
|
if (!claimedContexts.has(ctx)) {
|
|
7170
|
-
const
|
|
7171
|
-
if (
|
|
7981
|
+
const admitted = claimInflightDetailed({ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() }, { fingerprint: messageFingerprint(ctx.userId, intentKey) });
|
|
7982
|
+
if (admitted === "duplicate-msgid") {
|
|
7172
7983
|
console.log(`[bridge] 重复消息已跳过 msgId=${ctx.msgId}`);
|
|
7173
7984
|
return;
|
|
7174
7985
|
}
|
|
7986
|
+
if (admitted === "duplicate-intent") {
|
|
7987
|
+
console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`);
|
|
7988
|
+
const pend = pendingInflight().find((e) => e.fingerprint === messageFingerprint(ctx.userId, intentKey));
|
|
7989
|
+
const digest = pend ? `(在途内容:${previewText(pend.text)})` : "";
|
|
7990
|
+
await sendReply(ctx, `你的相同问题正在处理中${digest},本次重发已忽略`);
|
|
7991
|
+
return;
|
|
7992
|
+
}
|
|
7175
7993
|
claimedContexts.add(ctx);
|
|
7176
7994
|
}
|
|
7177
7995
|
claimedMsgId = ctx.msgId;
|
|
7178
7996
|
}
|
|
7997
|
+
if (busyUsers.has(ctx.userId) && !claimedContexts.has(ctx)) {
|
|
7998
|
+
const duplicateIntent = activeIntents.get(ctx.userId) === intentKey || msgQueue.hasIntent(ctx.userId, intentKey);
|
|
7999
|
+
if (duplicateIntent) {
|
|
8000
|
+
settleInflight(ctx.msgId);
|
|
8001
|
+
console.log(`[bridge] 相同意图已在执行/队列,跳过 msgId=${ctx.msgId}`);
|
|
8002
|
+
return;
|
|
8003
|
+
}
|
|
8004
|
+
}
|
|
7179
8005
|
if (busyUsers.has(ctx.userId)) {
|
|
7180
8006
|
if (ctx.attachments?.length && !ctx.preparedAttachments) {
|
|
7181
8007
|
ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
@@ -7191,13 +8017,18 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7191
8017
|
发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
|
|
7192
8018
|
return;
|
|
7193
8019
|
}
|
|
8020
|
+
activeIntents.set(ctx.userId, intentKey);
|
|
7194
8021
|
busyUsers.add(ctx.userId);
|
|
8022
|
+
if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
|
|
8023
|
+
await sendReply(ctx, "✅ 已收到,正在处理,完成后自动回复你");
|
|
8024
|
+
}
|
|
7195
8025
|
if (ctx.type === "c2c" && ctx.msgId) {
|
|
7196
8026
|
getAccessToken(config.qq.appId, config.qq.clientSecret).then((token) => sendC2CInputNotify(token, ctx.userId, ctx.msgId, 60)).catch(() => {});
|
|
7197
8027
|
}
|
|
7198
8028
|
let sessionId = "";
|
|
7199
8029
|
let turnStart = 0;
|
|
7200
8030
|
let trackId = "";
|
|
8031
|
+
let promptId = "";
|
|
7201
8032
|
try {
|
|
7202
8033
|
const session = await sessions.getOrCreate(ctx.userId);
|
|
7203
8034
|
sessionId = session.sessionId;
|
|
@@ -7220,6 +8051,10 @@ ${promptBody}` : promptBody;
|
|
|
7220
8051
|
recordInflight({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() });
|
|
7221
8052
|
const replyText = await client.promptAndWait(sessionId, promptText, {
|
|
7222
8053
|
files: files.length ? files : undefined,
|
|
8054
|
+
onAccepted: (info) => {
|
|
8055
|
+
promptId = info.promptId;
|
|
8056
|
+
markInflightPromptId(trackId, info.promptId);
|
|
8057
|
+
},
|
|
7223
8058
|
onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
|
|
7224
8059
|
onPermissionReplied: (d) => {
|
|
7225
8060
|
safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`);
|
|
@@ -7247,7 +8082,7 @@ ${promptBody}` : promptBody;
|
|
|
7247
8082
|
} catch (error) {
|
|
7248
8083
|
if (sessionId && turnStart > 0 && error instanceof Error && error.message.includes("响应超时")) {
|
|
7249
8084
|
await safeDeliver(ctx, "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。");
|
|
7250
|
-
startBackgroundWait(sessionId, ctx, turnStart, trackId);
|
|
8085
|
+
startBackgroundWait(sessionId, ctx, turnStart, trackId, promptId);
|
|
7251
8086
|
} else {
|
|
7252
8087
|
const errText = toErrorMessage2(error);
|
|
7253
8088
|
const rescue = rescueText(classifyProviderError(errText), errText);
|
|
@@ -7260,12 +8095,16 @@ ${promptBody}` : promptBody;
|
|
|
7260
8095
|
if (sessionId && !bgWaits.has(sessionId))
|
|
7261
8096
|
mirror.scheduleUnlock(sessionId);
|
|
7262
8097
|
busyUsers.delete(ctx.userId);
|
|
8098
|
+
if (activeIntents.get(ctx.userId) === intentKey)
|
|
8099
|
+
activeIntents.delete(ctx.userId);
|
|
7263
8100
|
if (sessionId && !bgWaits.has(sessionId))
|
|
7264
8101
|
drainQueue(ctx.userId);
|
|
7265
8102
|
}
|
|
7266
8103
|
} catch (error) {
|
|
7267
8104
|
if (claimedMsgId)
|
|
7268
8105
|
settleInflight(claimedMsgId);
|
|
8106
|
+
if (activeIntents.get(ctx.userId) === intentKey)
|
|
8107
|
+
activeIntents.delete(ctx.userId);
|
|
7269
8108
|
console.error("[bridge] handleMessage failed:", error);
|
|
7270
8109
|
try {
|
|
7271
8110
|
await sendReply(ctx, `处理消息失败:${toErrorMessage2(error)}`);
|
|
@@ -7286,6 +8125,12 @@ ${promptBody}` : promptBody;
|
|
|
7286
8125
|
continue;
|
|
7287
8126
|
}
|
|
7288
8127
|
const ctx = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text };
|
|
8128
|
+
if (!entry.sessionId) {
|
|
8129
|
+
settleInflight(entry.msgId);
|
|
8130
|
+
await deliver(ctx, `⚠️ 重启前队列里有一条消息未执行(「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」)。为避免重复执行不自动重派,需要的话请重发一次`);
|
|
8131
|
+
console.log(`[bridge] 启动对账:排队空账已通知销账 msgId=${entry.msgId}`);
|
|
8132
|
+
continue;
|
|
8133
|
+
}
|
|
7289
8134
|
try {
|
|
7290
8135
|
const listJson = { data: await fetchRecoveryMessages(client, entry.sessionId) };
|
|
7291
8136
|
const cls = classifyInflight(entry, listJson.data);
|
|
@@ -7297,7 +8142,7 @@ ${cls.answer}`);
|
|
|
7297
8142
|
console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`);
|
|
7298
8143
|
} else if (cls.kind === "running") {
|
|
7299
8144
|
mirror.beginTurn(entry.sessionId);
|
|
7300
|
-
startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId);
|
|
8145
|
+
startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId, entry.promptId ?? "");
|
|
7301
8146
|
console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`);
|
|
7302
8147
|
} else if (ageMs <= redispatchMaxAgeMs()) {
|
|
7303
8148
|
settleInflight(entry.msgId);
|
|
@@ -7323,6 +8168,7 @@ ${cls.answer}`);
|
|
|
7323
8168
|
draining.add(userId);
|
|
7324
8169
|
try {
|
|
7325
8170
|
await sendReply(job.ctx, `开始执行队列 #${job.id}`);
|
|
8171
|
+
drainReentries.add(job.ctx);
|
|
7326
8172
|
await handleMessage(job.ctx);
|
|
7327
8173
|
} catch (error) {
|
|
7328
8174
|
console.error("[bridge] 队列执行失败:", error);
|
|
@@ -7377,11 +8223,11 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
7377
8223
|
return false;
|
|
7378
8224
|
return allowedUsers.includes(userId);
|
|
7379
8225
|
}
|
|
7380
|
-
var WATCH_FILE =
|
|
8226
|
+
var WATCH_FILE = join12(homedir11(), ".openqq", "watch.json");
|
|
7381
8227
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
7382
8228
|
try {
|
|
7383
|
-
if (
|
|
7384
|
-
const raw =
|
|
8229
|
+
if (existsSync10(file)) {
|
|
8230
|
+
const raw = readFileSync12(file, "utf-8");
|
|
7385
8231
|
const obj = JSON.parse(raw);
|
|
7386
8232
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
7387
8233
|
const out = {};
|
|
@@ -7396,16 +8242,16 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
7396
8242
|
}
|
|
7397
8243
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
7398
8244
|
try {
|
|
7399
|
-
|
|
8245
|
+
writeFileSync12(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
7400
8246
|
} catch (error) {
|
|
7401
8247
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
7402
8248
|
}
|
|
7403
8249
|
}
|
|
7404
|
-
var GREETED_FILE =
|
|
8250
|
+
var GREETED_FILE = join12(homedir11(), ".openqq", "greeted.json");
|
|
7405
8251
|
function loadGreetedSet() {
|
|
7406
8252
|
try {
|
|
7407
|
-
if (
|
|
7408
|
-
const raw =
|
|
8253
|
+
if (existsSync10(GREETED_FILE)) {
|
|
8254
|
+
const raw = readFileSync12(GREETED_FILE, "utf-8");
|
|
7409
8255
|
const arr = JSON.parse(raw);
|
|
7410
8256
|
if (Array.isArray(arr)) {
|
|
7411
8257
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -7416,8 +8262,8 @@ function loadGreetedSet() {
|
|
|
7416
8262
|
}
|
|
7417
8263
|
function saveGreetedSet(set) {
|
|
7418
8264
|
try {
|
|
7419
|
-
|
|
7420
|
-
|
|
8265
|
+
mkdirSync10(join12(homedir11(), ".openqq"), { recursive: true });
|
|
8266
|
+
writeFileSync12(GREETED_FILE, JSON.stringify([...set]));
|
|
7421
8267
|
} catch (error) {
|
|
7422
8268
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
7423
8269
|
}
|
|
@@ -7468,35 +8314,36 @@ function toErrorMessage2(error) {
|
|
|
7468
8314
|
}
|
|
7469
8315
|
|
|
7470
8316
|
// src/core/instance-lock.ts
|
|
7471
|
-
import { openSync as
|
|
7472
|
-
import { join as
|
|
7473
|
-
import { homedir as
|
|
8317
|
+
import { openSync as openSync4, readFileSync as readFileSync13, writeFileSync as writeFileSync13, closeSync as closeSync4, unlinkSync as unlinkSync6, statSync as statSync6, utimesSync, mkdirSync as mkdirSync11 } from "fs";
|
|
8318
|
+
import { join as join13 } from "path";
|
|
8319
|
+
import { homedir as homedir12 } from "os";
|
|
7474
8320
|
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
7475
|
-
var
|
|
8321
|
+
var LOCK_STALE_MS2 = 30000;
|
|
7476
8322
|
var LOCK_UPDATE_MS = 1e4;
|
|
7477
8323
|
var LOCK_RETRY_MS = 5000;
|
|
8324
|
+
var LOCK_SELF_CHECK_MS = 60000;
|
|
7478
8325
|
function lockPathOf(appId) {
|
|
7479
|
-
return
|
|
8326
|
+
return join13(homedir12(), ".openqq", `openqq-${appId}.lock`);
|
|
7480
8327
|
}
|
|
7481
8328
|
function touch(path) {
|
|
7482
8329
|
const now = new Date;
|
|
7483
8330
|
utimesSync(path, now, now);
|
|
7484
8331
|
}
|
|
7485
|
-
function acquireInstanceLockAt(path, staleMs =
|
|
8332
|
+
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
7486
8333
|
try {
|
|
7487
|
-
|
|
7488
|
-
const fd =
|
|
7489
|
-
|
|
7490
|
-
|
|
8334
|
+
mkdirSync11(join13(path, ".."), { recursive: true });
|
|
8335
|
+
const fd = openSync4(path, "wx");
|
|
8336
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
8337
|
+
closeSync4(fd);
|
|
7491
8338
|
} catch {
|
|
7492
8339
|
try {
|
|
7493
|
-
const age = Date.now() -
|
|
8340
|
+
const age = Date.now() - statSync6(path).mtimeMs;
|
|
7494
8341
|
if (age <= staleMs)
|
|
7495
8342
|
return null;
|
|
7496
|
-
|
|
7497
|
-
const fd =
|
|
7498
|
-
|
|
7499
|
-
|
|
8343
|
+
unlinkSync6(path);
|
|
8344
|
+
const fd = openSync4(path, "wx");
|
|
8345
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
8346
|
+
closeSync4(fd);
|
|
7500
8347
|
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
7501
8348
|
} catch {
|
|
7502
8349
|
return null;
|
|
@@ -7508,6 +8355,22 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
|
|
|
7508
8355
|
} catch {}
|
|
7509
8356
|
}, LOCK_UPDATE_MS);
|
|
7510
8357
|
heartbeat.unref?.();
|
|
8358
|
+
const selfCheck = setInterval(() => {
|
|
8359
|
+
try {
|
|
8360
|
+
const holder = JSON.parse(readFileSync13(path, "utf-8")).pid;
|
|
8361
|
+
if (holder === process.pid)
|
|
8362
|
+
return;
|
|
8363
|
+
try {
|
|
8364
|
+
process.kill(holder, 0);
|
|
8365
|
+
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活,本实例为残留 believer,自杀退出`);
|
|
8366
|
+
process.exit(1);
|
|
8367
|
+
} catch {}
|
|
8368
|
+
} catch {
|
|
8369
|
+
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
8370
|
+
process.exit(1);
|
|
8371
|
+
}
|
|
8372
|
+
}, LOCK_SELF_CHECK_MS);
|
|
8373
|
+
selfCheck.unref?.();
|
|
7511
8374
|
let released = false;
|
|
7512
8375
|
return {
|
|
7513
8376
|
release: () => {
|
|
@@ -7515,8 +8378,9 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
|
|
|
7515
8378
|
return;
|
|
7516
8379
|
released = true;
|
|
7517
8380
|
clearInterval(heartbeat);
|
|
8381
|
+
clearInterval(selfCheck);
|
|
7518
8382
|
try {
|
|
7519
|
-
|
|
8383
|
+
unlinkSync6(path);
|
|
7520
8384
|
} catch {}
|
|
7521
8385
|
}
|
|
7522
8386
|
};
|
|
@@ -7618,11 +8482,11 @@ async function main() {
|
|
|
7618
8482
|
});
|
|
7619
8483
|
console.log("[index] OpenCode QQ Bot 已启动");
|
|
7620
8484
|
bridge.recoverInflightRounds();
|
|
7621
|
-
const heartbeatFile =
|
|
8485
|
+
const heartbeatFile = join15(homedir13(), ".openqq", "heartbeat");
|
|
7622
8486
|
const touchHeartbeat = () => {
|
|
7623
8487
|
try {
|
|
7624
|
-
|
|
7625
|
-
|
|
8488
|
+
mkdirSync13(join15(homedir13(), ".openqq"), { recursive: true });
|
|
8489
|
+
writeFileSync14(heartbeatFile, String(Date.now()));
|
|
7626
8490
|
} catch (error) {
|
|
7627
8491
|
console.error("[index] 心跳写入失败:", error);
|
|
7628
8492
|
}
|