@linjz/opencode-qqbot 0.3.12 → 0.3.13
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/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +3 -3
- package/dist/openqq-bot.js +1033 -191
- package/package.json +2 -2
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +135 -15
- package/src/commands.ts +554 -554
- package/src/config.ts +121 -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 +105 -13
- 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 +148 -21
- 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 +89 -8
- 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 +539 -539
- package/src/qq/gateway.ts +69 -20
- package/src/qq/media.ts +219 -219
- package/src/qq/sender.ts +300 -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}
|
|
@@ -3087,9 +3087,9 @@ function loadConfig() {
|
|
|
3087
3087
|
}
|
|
3088
3088
|
|
|
3089
3089
|
// src/index.ts
|
|
3090
|
-
import { mkdirSync as
|
|
3091
|
-
import { join as
|
|
3092
|
-
import { homedir as
|
|
3090
|
+
import { mkdirSync as mkdirSync13, writeFileSync as writeFileSync14 } from "fs";
|
|
3091
|
+
import { join as join15 } from "path";
|
|
3092
|
+
import { homedir as homedir13 } from "os";
|
|
3093
3093
|
|
|
3094
3094
|
// src/opencode/client.ts
|
|
3095
3095
|
var TURN_TIMEOUT_MINUTES = (() => {
|
|
@@ -3102,6 +3102,56 @@ function collectReplyText(msgs, baseline) {
|
|
|
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,6 +3293,10 @@ 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;
|
|
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}`);
|
|
3243
3300
|
const deadline = Date.now() + RESPONSE_TIMEOUT_MS;
|
|
3244
3301
|
let permissionWaitMs = 0;
|
|
3245
3302
|
const handledPermissions = new Set;
|
|
@@ -3284,10 +3341,9 @@ 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
3349
|
throw new Error(`AI 响应超时(${TURN_TIMEOUT_MINUTES} 分钟)`);
|
|
@@ -3988,6 +4044,49 @@ var import_websocket = __toESM(require_websocket(), 1);
|
|
|
3988
4044
|
var import_websocket_server = __toESM(require_websocket_server(), 1);
|
|
3989
4045
|
var wrapper_default = import_websocket.default;
|
|
3990
4046
|
|
|
4047
|
+
// src/core/gateway-state.ts
|
|
4048
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync5, mkdirSync as mkdirSync4, renameSync, unlinkSync } from "fs";
|
|
4049
|
+
import { join as join5 } from "path";
|
|
4050
|
+
import { homedir as homedir5 } from "os";
|
|
4051
|
+
var GATEWAY_STATE_FILE = join5(homedir5(), ".openqq", "gateway-state.json");
|
|
4052
|
+
function gatewayStateMaxAgeMs() {
|
|
4053
|
+
const h = Number(process.env.QQ_GATEWAY_STATE_MAX_HOURS ?? "6");
|
|
4054
|
+
return Number.isFinite(h) && h > 0 ? Math.floor(h * 3600000) : 6 * 3600000;
|
|
4055
|
+
}
|
|
4056
|
+
function loadGatewayState(file = GATEWAY_STATE_FILE, now = Date.now()) {
|
|
4057
|
+
try {
|
|
4058
|
+
if (!existsSync4(file))
|
|
4059
|
+
return null;
|
|
4060
|
+
const raw = JSON.parse(readFileSync4(file, "utf-8"));
|
|
4061
|
+
if (!raw || typeof raw.session_id !== "string" || !raw.session_id)
|
|
4062
|
+
return null;
|
|
4063
|
+
if (typeof raw.seq !== "number" || raw.seq < 0)
|
|
4064
|
+
return null;
|
|
4065
|
+
if (typeof raw.savedAt !== "number" || !Number.isFinite(raw.savedAt))
|
|
4066
|
+
return null;
|
|
4067
|
+
if (now - raw.savedAt > gatewayStateMaxAgeMs())
|
|
4068
|
+
return null;
|
|
4069
|
+
return { session_id: raw.session_id, seq: raw.seq, savedAt: raw.savedAt };
|
|
4070
|
+
} catch {
|
|
4071
|
+
return null;
|
|
4072
|
+
}
|
|
4073
|
+
}
|
|
4074
|
+
function saveGatewayState(sessionId, seq, file = GATEWAY_STATE_FILE) {
|
|
4075
|
+
try {
|
|
4076
|
+
mkdirSync4(join5(file, ".."), { recursive: true });
|
|
4077
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
4078
|
+
writeFileSync5(tmp, JSON.stringify({ session_id: sessionId, seq, savedAt: Date.now() }));
|
|
4079
|
+
renameSync(tmp, file);
|
|
4080
|
+
} catch (error) {
|
|
4081
|
+
console.warn("[gateway-state] 落盘失败:", error instanceof Error ? error.message : error);
|
|
4082
|
+
}
|
|
4083
|
+
}
|
|
4084
|
+
function clearGatewayState(file = GATEWAY_STATE_FILE) {
|
|
4085
|
+
try {
|
|
4086
|
+
unlinkSync(file);
|
|
4087
|
+
} catch {}
|
|
4088
|
+
}
|
|
4089
|
+
|
|
3991
4090
|
// src/qq/gateway.ts
|
|
3992
4091
|
var GROUP_AND_C2C_EVENT_INTENT = 1 << 25;
|
|
3993
4092
|
var INTERACTION_INTENT = 1 << 26;
|
|
@@ -3999,7 +4098,7 @@ var RATE_LIMITED_RECONNECT_DELAY_MS = 60000;
|
|
|
3999
4098
|
var RESUME_RESET_CLOSE_CODES = new Set([4006, 4007, 4009]);
|
|
4000
4099
|
var FATAL_CLOSE_CODES = new Set([4914, 4915]);
|
|
4001
4100
|
function createInitialState() {
|
|
4002
|
-
|
|
4101
|
+
const state = {
|
|
4003
4102
|
ws: null,
|
|
4004
4103
|
stopped: false,
|
|
4005
4104
|
connecting: false,
|
|
@@ -4010,21 +4109,28 @@ function createInitialState() {
|
|
|
4010
4109
|
sessionId: null,
|
|
4011
4110
|
seq: null,
|
|
4012
4111
|
heartbeatAcked: true,
|
|
4013
|
-
|
|
4112
|
+
activeMsgIds: new Set
|
|
4014
4113
|
};
|
|
4114
|
+
const saved = loadGatewayState();
|
|
4115
|
+
if (saved) {
|
|
4116
|
+
state.sessionId = saved.session_id;
|
|
4117
|
+
state.seq = saved.seq;
|
|
4118
|
+
const agoSec = Math.max(0, Math.round((Date.now() - saved.savedAt) / 1000));
|
|
4119
|
+
console.log(`[gateway] 已从磁盘恢复网关状态(${agoSec}s 前),将尝试 RESUME session=${saved.session_id} seq=${saved.seq}`);
|
|
4120
|
+
}
|
|
4121
|
+
return state;
|
|
4015
4122
|
}
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
if (seen.has(msgId))
|
|
4123
|
+
function tryClaimActive(active, msgId) {
|
|
4124
|
+
if (active.has(msgId))
|
|
4019
4125
|
return false;
|
|
4020
|
-
if (
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
seen.delete(first);
|
|
4024
|
-
}
|
|
4025
|
-
seen.add(msgId);
|
|
4126
|
+
if (active.size >= 1000)
|
|
4127
|
+
return true;
|
|
4128
|
+
active.add(msgId);
|
|
4026
4129
|
return true;
|
|
4027
4130
|
}
|
|
4131
|
+
function releaseActive(active, msgId) {
|
|
4132
|
+
active.delete(msgId);
|
|
4133
|
+
}
|
|
4028
4134
|
function cleanupSocket(state) {
|
|
4029
4135
|
if (state.heartbeatTimer) {
|
|
4030
4136
|
clearInterval(state.heartbeatTimer);
|
|
@@ -4073,6 +4179,7 @@ function startHeartbeat(state, intervalMs) {
|
|
|
4073
4179
|
function resetResumeState(state) {
|
|
4074
4180
|
state.sessionId = null;
|
|
4075
4181
|
state.seq = null;
|
|
4182
|
+
clearGatewayState();
|
|
4076
4183
|
}
|
|
4077
4184
|
function normalizeMessageContent(content) {
|
|
4078
4185
|
return content.replace(/\r\n/g, `
|
|
@@ -4154,6 +4261,8 @@ async function handleDispatchEvent(payload, options, state) {
|
|
|
4154
4261
|
case "READY": {
|
|
4155
4262
|
const readyData = payload.d;
|
|
4156
4263
|
state.sessionId = readyData.session_id;
|
|
4264
|
+
if (state.seq !== null)
|
|
4265
|
+
saveGatewayState(state.sessionId, state.seq);
|
|
4157
4266
|
if (state.reconnectAttempt > 0) {
|
|
4158
4267
|
console.log(`[gateway] 重连已就绪(READY,第 ${state.reconnectAttempt} 次尝试)session=${state.sessionId}`);
|
|
4159
4268
|
}
|
|
@@ -4163,45 +4272,59 @@ async function handleDispatchEvent(payload, options, state) {
|
|
|
4163
4272
|
}
|
|
4164
4273
|
case "RESUMED": {
|
|
4165
4274
|
console.log("[gateway] 会话已恢复(RESUMED,断线期间事件已回补)");
|
|
4275
|
+
if (state.sessionId && state.seq !== null)
|
|
4276
|
+
saveGatewayState(state.sessionId, state.seq);
|
|
4166
4277
|
state.reconnectAttempt = 0;
|
|
4167
4278
|
return;
|
|
4168
4279
|
}
|
|
4169
4280
|
case "C2C_MESSAGE_CREATE": {
|
|
4170
4281
|
const event = payload.d;
|
|
4171
|
-
if (!
|
|
4282
|
+
if (!tryClaimActive(state.activeMsgIds, event.id))
|
|
4172
4283
|
return;
|
|
4173
4284
|
const message = toC2CMessageContext(event);
|
|
4174
4285
|
if (message.attachments?.length) {
|
|
4175
4286
|
console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)));
|
|
4176
4287
|
}
|
|
4177
4288
|
if (!message.content && !message.attachments?.length) {
|
|
4289
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4178
4290
|
return;
|
|
4179
4291
|
}
|
|
4180
|
-
|
|
4292
|
+
try {
|
|
4293
|
+
await options.onMessage(message);
|
|
4294
|
+
} finally {
|
|
4295
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4296
|
+
}
|
|
4181
4297
|
return;
|
|
4182
4298
|
}
|
|
4183
4299
|
case "GROUP_AT_MESSAGE_CREATE": {
|
|
4184
4300
|
const event = payload.d;
|
|
4185
|
-
if (!
|
|
4301
|
+
if (!tryClaimActive(state.activeMsgIds, event.id))
|
|
4186
4302
|
return;
|
|
4187
4303
|
const message = toGroupMessageContext(event);
|
|
4188
4304
|
if (message.attachments?.length) {
|
|
4189
4305
|
console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)));
|
|
4190
4306
|
}
|
|
4191
4307
|
if (!message.content && !message.attachments?.length) {
|
|
4308
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4192
4309
|
return;
|
|
4193
4310
|
}
|
|
4194
|
-
|
|
4311
|
+
try {
|
|
4312
|
+
await options.onMessage(message);
|
|
4313
|
+
} finally {
|
|
4314
|
+
releaseActive(state.activeMsgIds, event.id);
|
|
4315
|
+
}
|
|
4195
4316
|
return;
|
|
4196
4317
|
}
|
|
4197
4318
|
case "INTERACTION_CREATE": {
|
|
4198
4319
|
const interaction = payload.d;
|
|
4320
|
+
Promise.resolve().then(() => options.onInteraction?.(interaction)).catch((error) => {
|
|
4321
|
+
console.error("[qq-gateway] 互动业务分发失败:", error instanceof Error ? error.message : error);
|
|
4322
|
+
});
|
|
4199
4323
|
if (state.accessToken && interaction?.id) {
|
|
4200
4324
|
acknowledgeInteraction(state.accessToken, interaction.id).catch((error) => {
|
|
4201
4325
|
console.error("[qq-gateway] 互动响应失败:", error instanceof Error ? error.message : error);
|
|
4202
4326
|
});
|
|
4203
4327
|
}
|
|
4204
|
-
await options.onInteraction?.(interaction);
|
|
4205
4328
|
return;
|
|
4206
4329
|
}
|
|
4207
4330
|
default:
|
|
@@ -4210,7 +4333,14 @@ async function handleDispatchEvent(payload, options, state) {
|
|
|
4210
4333
|
}
|
|
4211
4334
|
async function handlePayload(payload, ws, options, state, connect) {
|
|
4212
4335
|
if (typeof payload.s === "number") {
|
|
4336
|
+
const prevSeq = state.seq;
|
|
4213
4337
|
state.seq = payload.s;
|
|
4338
|
+
if (state.sessionId && payload.s !== prevSeq) {
|
|
4339
|
+
if (prevSeq !== null && payload.s > prevSeq + 1) {
|
|
4340
|
+
console.log(`[gateway] seq 回补 ${payload.s - prevSeq - 1} 帧(${prevSeq} → ${payload.s})——断线期间载荷已重放`);
|
|
4341
|
+
}
|
|
4342
|
+
saveGatewayState(state.sessionId, payload.s);
|
|
4343
|
+
}
|
|
4214
4344
|
}
|
|
4215
4345
|
switch (payload.op) {
|
|
4216
4346
|
case 10: {
|
|
@@ -4335,13 +4465,13 @@ async function startGateway(options) {
|
|
|
4335
4465
|
}
|
|
4336
4466
|
|
|
4337
4467
|
// src/bridge.ts
|
|
4338
|
-
import { existsSync as
|
|
4339
|
-
import { join as
|
|
4340
|
-
import { homedir as
|
|
4468
|
+
import { existsSync as existsSync10, readFileSync as readFileSync12, mkdirSync as mkdirSync10, writeFileSync as writeFileSync12 } from "fs";
|
|
4469
|
+
import { join as join12 } from "path";
|
|
4470
|
+
import { homedir as homedir11 } from "os";
|
|
4341
4471
|
|
|
4342
4472
|
// src/qq/media.ts
|
|
4343
|
-
import { mkdirSync as
|
|
4344
|
-
import { join as
|
|
4473
|
+
import { mkdirSync as mkdirSync5, readdirSync, statSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6, readFileSync as readFileSync5 } from "node:fs";
|
|
4474
|
+
import { join as join6 } from "node:path";
|
|
4345
4475
|
import { tmpdir } from "node:os";
|
|
4346
4476
|
function extForImageMime(mime) {
|
|
4347
4477
|
const m = (mime || "").toLowerCase().split(";")[0].trim();
|
|
@@ -4366,7 +4496,7 @@ function isAllowedDownloadHost(url) {
|
|
|
4366
4496
|
}
|
|
4367
4497
|
}
|
|
4368
4498
|
function imageDir() {
|
|
4369
|
-
return
|
|
4499
|
+
return join6(tmpdir(), "opencode", "qq-images");
|
|
4370
4500
|
}
|
|
4371
4501
|
async function fetchWithTimeout(url, ms, auth) {
|
|
4372
4502
|
const ctrl = new AbortController;
|
|
@@ -4392,7 +4522,7 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4392
4522
|
return { failed: "下载域不在白名单" };
|
|
4393
4523
|
try {
|
|
4394
4524
|
const dir = imageDir();
|
|
4395
|
-
|
|
4525
|
+
mkdirSync5(dir, { recursive: true });
|
|
4396
4526
|
const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
|
|
4397
4527
|
let res = await fetchWithTimeout(att.url, 15000);
|
|
4398
4528
|
if ((res.status === 401 || res.status === 403) && getAuth) {
|
|
@@ -4426,8 +4556,8 @@ async function downloadQQAttachment(att, getAuth) {
|
|
|
4426
4556
|
}
|
|
4427
4557
|
if (total === 0)
|
|
4428
4558
|
return { failed: "空响应" };
|
|
4429
|
-
const full =
|
|
4430
|
-
|
|
4559
|
+
const full = join6(dir, name);
|
|
4560
|
+
writeFileSync6(full, Buffer.concat(chunks));
|
|
4431
4561
|
return { path: full, name };
|
|
4432
4562
|
} catch (e) {
|
|
4433
4563
|
console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e);
|
|
@@ -4464,7 +4594,7 @@ function tryImageDataUrl(path, maxBytes) {
|
|
|
4464
4594
|
const st = statSync(path);
|
|
4465
4595
|
if (st.size > maxBytes)
|
|
4466
4596
|
return null;
|
|
4467
|
-
const b =
|
|
4597
|
+
const b = readFileSync5(path);
|
|
4468
4598
|
return `data:image/png;base64,${b.toString("base64")}`;
|
|
4469
4599
|
} catch {
|
|
4470
4600
|
return null;
|
|
@@ -4491,10 +4621,10 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
|
|
|
4491
4621
|
const dir = imageDir();
|
|
4492
4622
|
const now = Date.now();
|
|
4493
4623
|
for (const f of readdirSync(dir)) {
|
|
4494
|
-
const full =
|
|
4624
|
+
const full = join6(dir, f);
|
|
4495
4625
|
try {
|
|
4496
4626
|
if (now - statSync(full).mtimeMs > maxAgeMs)
|
|
4497
|
-
|
|
4627
|
+
unlinkSync2(full);
|
|
4498
4628
|
} catch {}
|
|
4499
4629
|
}
|
|
4500
4630
|
} catch {}
|
|
@@ -4732,7 +4862,7 @@ function clip(value, max) {
|
|
|
4732
4862
|
}
|
|
4733
4863
|
|
|
4734
4864
|
// src/core/send-media.ts
|
|
4735
|
-
import { readFileSync as
|
|
4865
|
+
import { readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
|
|
4736
4866
|
import { resolve, extname, basename, sep } from "node:path";
|
|
4737
4867
|
var MAX_SEND_BYTES = 20 * 1024 * 1024;
|
|
4738
4868
|
function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
|
|
@@ -4797,7 +4927,7 @@ async function sendLocalFile(ctx, filePath, deps) {
|
|
|
4797
4927
|
const name = basename(trimmed);
|
|
4798
4928
|
const uploaded = await uploadQQMedia(token, ctx, {
|
|
4799
4929
|
fileType,
|
|
4800
|
-
fileData:
|
|
4930
|
+
fileData: readFileSync6(trimmed).toString("base64"),
|
|
4801
4931
|
fileName: fileType === MediaFileType.FILE ? name : undefined
|
|
4802
4932
|
});
|
|
4803
4933
|
await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
|
|
@@ -5219,9 +5349,9 @@ function toErrorMessage(error) {
|
|
|
5219
5349
|
}
|
|
5220
5350
|
|
|
5221
5351
|
// src/core/mirror.ts
|
|
5222
|
-
import { existsSync as
|
|
5223
|
-
import { join as
|
|
5224
|
-
import { homedir as
|
|
5352
|
+
import { existsSync as existsSync5, readFileSync as readFileSync7, mkdirSync as mkdirSync6, writeFileSync as writeFileSync7 } from "fs";
|
|
5353
|
+
import { join as join7 } from "path";
|
|
5354
|
+
import { homedir as homedir6 } from "os";
|
|
5225
5355
|
|
|
5226
5356
|
// src/opencode/mirror.ts
|
|
5227
5357
|
var USER_CLIP = 160;
|
|
@@ -5294,11 +5424,11 @@ function clip2(value, max) {
|
|
|
5294
5424
|
}
|
|
5295
5425
|
|
|
5296
5426
|
// src/core/mirror.ts
|
|
5297
|
-
var MIRROR_SETTINGS_FILE =
|
|
5427
|
+
var MIRROR_SETTINGS_FILE = join7(homedir6(), ".openqq", "settings.json");
|
|
5298
5428
|
function loadMirrorEnabled() {
|
|
5299
5429
|
try {
|
|
5300
|
-
if (
|
|
5301
|
-
const raw =
|
|
5430
|
+
if (existsSync5(MIRROR_SETTINGS_FILE)) {
|
|
5431
|
+
const raw = readFileSync7(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
|
|
5302
5432
|
const parsed = JSON.parse(raw);
|
|
5303
5433
|
if (typeof parsed?.mirror === "boolean")
|
|
5304
5434
|
return parsed.mirror;
|
|
@@ -5308,18 +5438,18 @@ function loadMirrorEnabled() {
|
|
|
5308
5438
|
}
|
|
5309
5439
|
function saveMirrorEnabled(enabled) {
|
|
5310
5440
|
try {
|
|
5311
|
-
|
|
5441
|
+
mkdirSync6(join7(homedir6(), ".openqq"), { recursive: true });
|
|
5312
5442
|
let existing = {};
|
|
5313
|
-
if (
|
|
5443
|
+
if (existsSync5(MIRROR_SETTINGS_FILE)) {
|
|
5314
5444
|
try {
|
|
5315
|
-
const raw =
|
|
5445
|
+
const raw = readFileSync7(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
|
|
5316
5446
|
const parsed = JSON.parse(raw);
|
|
5317
5447
|
if (parsed && typeof parsed === "object")
|
|
5318
5448
|
existing = parsed;
|
|
5319
5449
|
} catch {}
|
|
5320
5450
|
}
|
|
5321
5451
|
existing.mirror = enabled;
|
|
5322
|
-
|
|
5452
|
+
writeFileSync7(MIRROR_SETTINGS_FILE, JSON.stringify(existing, null, 2), "utf-8");
|
|
5323
5453
|
} catch (error) {
|
|
5324
5454
|
console.error("[mirror] 保存设置失败:", error);
|
|
5325
5455
|
}
|
|
@@ -5426,6 +5556,11 @@ function createMirror(deps) {
|
|
|
5426
5556
|
|
|
5427
5557
|
// src/core/message-queue.ts
|
|
5428
5558
|
var PREVIEW_MAX = 48;
|
|
5559
|
+
function intentKeyOf(ctx) {
|
|
5560
|
+
const text = ctx.content.replace(/\s+/g, " ").trim();
|
|
5561
|
+
const attachments = (ctx.attachments ?? []).map((a) => `${a.content_type}:${a.size}:${a.filename}`).join("|");
|
|
5562
|
+
return JSON.stringify({ text, referenced: ctx.referencedMsgId ?? "", attachments });
|
|
5563
|
+
}
|
|
5429
5564
|
function previewText(text, max = PREVIEW_MAX) {
|
|
5430
5565
|
const flat = text.replace(/\s+/g, " ").trim();
|
|
5431
5566
|
return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)";
|
|
@@ -5456,6 +5591,9 @@ class MessageQueue {
|
|
|
5456
5591
|
this.jobs.set(userId, list);
|
|
5457
5592
|
return { job, ahead: list.length - 1 };
|
|
5458
5593
|
}
|
|
5594
|
+
hasIntent(userId, key) {
|
|
5595
|
+
return (this.jobs.get(userId) ?? []).some((job) => intentKeyOf(job.ctx) === key);
|
|
5596
|
+
}
|
|
5459
5597
|
shift(userId) {
|
|
5460
5598
|
const list = this.jobs.get(userId);
|
|
5461
5599
|
const job = list?.shift();
|
|
@@ -5515,9 +5653,9 @@ function rescueText(kind, rawMessage) {
|
|
|
5515
5653
|
}
|
|
5516
5654
|
|
|
5517
5655
|
// src/core/permission.ts
|
|
5518
|
-
import { existsSync as
|
|
5519
|
-
import { join as
|
|
5520
|
-
import { homedir as
|
|
5656
|
+
import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "fs";
|
|
5657
|
+
import { join as join8 } from "path";
|
|
5658
|
+
import { homedir as homedir7 } from "os";
|
|
5521
5659
|
|
|
5522
5660
|
// src/core/util.ts
|
|
5523
5661
|
function truncate(value, max) {
|
|
@@ -5532,11 +5670,11 @@ var DECISION_LABELS = {
|
|
|
5532
5670
|
always: "总是允许(已存入项目白名单)",
|
|
5533
5671
|
reject: "拒绝"
|
|
5534
5672
|
};
|
|
5535
|
-
var PENDING_PERM_FILE =
|
|
5673
|
+
var PENDING_PERM_FILE = join8(homedir7(), ".openqq", "pending-permissions.json");
|
|
5536
5674
|
function loadPendingPermMap() {
|
|
5537
5675
|
try {
|
|
5538
|
-
if (
|
|
5539
|
-
const raw =
|
|
5676
|
+
if (existsSync6(PENDING_PERM_FILE)) {
|
|
5677
|
+
const raw = readFileSync8(PENDING_PERM_FILE, "utf-8");
|
|
5540
5678
|
const obj = JSON.parse(raw);
|
|
5541
5679
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
5542
5680
|
const out = {};
|
|
@@ -5559,7 +5697,7 @@ function savePendingPermMap(m) {
|
|
|
5559
5697
|
continue;
|
|
5560
5698
|
out[uid] = { request: e.request, mainSessionId: e.mainSessionId, createdAt: e.createdAt, ctx: e.ctx };
|
|
5561
5699
|
}
|
|
5562
|
-
|
|
5700
|
+
writeFileSync8(PENDING_PERM_FILE, JSON.stringify(out));
|
|
5563
5701
|
} catch (error) {
|
|
5564
5702
|
console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error);
|
|
5565
5703
|
}
|
|
@@ -5725,10 +5863,10 @@ function formatPermissionPrompt(request, mainSessionId) {
|
|
|
5725
5863
|
}
|
|
5726
5864
|
|
|
5727
5865
|
// src/core/delivery.ts
|
|
5728
|
-
import { existsSync as
|
|
5729
|
-
import { join as
|
|
5866
|
+
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";
|
|
5867
|
+
import { join as join9 } from "path";
|
|
5730
5868
|
import { createHash } from "node:crypto";
|
|
5731
|
-
import { homedir as
|
|
5869
|
+
import { homedir as homedir8 } from "os";
|
|
5732
5870
|
|
|
5733
5871
|
// src/qq/sender.ts
|
|
5734
5872
|
var DEFAULT_MAX_LENGTH = 3000;
|
|
@@ -6067,11 +6205,11 @@ function extractEmbeddedQuote(event) {
|
|
|
6067
6205
|
}
|
|
6068
6206
|
|
|
6069
6207
|
// src/core/delivery.ts
|
|
6070
|
-
var QUOTA_FILE =
|
|
6208
|
+
var QUOTA_FILE = join9(homedir8(), ".openqq", "quota.json");
|
|
6071
6209
|
function loadQuotaMap() {
|
|
6072
6210
|
try {
|
|
6073
|
-
if (
|
|
6074
|
-
const raw =
|
|
6211
|
+
if (existsSync7(QUOTA_FILE)) {
|
|
6212
|
+
const raw = readFileSync9(QUOTA_FILE, "utf-8");
|
|
6075
6213
|
const obj = JSON.parse(raw);
|
|
6076
6214
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
6077
6215
|
const out = {};
|
|
@@ -6089,27 +6227,51 @@ function loadQuotaMap() {
|
|
|
6089
6227
|
}
|
|
6090
6228
|
function saveQuotaMap(m) {
|
|
6091
6229
|
try {
|
|
6092
|
-
|
|
6230
|
+
writeFileSync9(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)));
|
|
6093
6231
|
} catch (error) {
|
|
6094
6232
|
console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error);
|
|
6095
6233
|
}
|
|
6096
6234
|
}
|
|
6097
6235
|
var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
|
|
6098
6236
|
`;
|
|
6237
|
+
function qqListNormalize(text) {
|
|
6238
|
+
const lines = text.split(`
|
|
6239
|
+
`);
|
|
6240
|
+
let fence = false;
|
|
6241
|
+
let fenceMarker = "";
|
|
6242
|
+
for (let i = 0;i < lines.length; i++) {
|
|
6243
|
+
const fm = lines[i].trim().match(/^(```|~~~)/);
|
|
6244
|
+
if (fm) {
|
|
6245
|
+
if (!fence) {
|
|
6246
|
+
fence = true;
|
|
6247
|
+
fenceMarker = fm[1];
|
|
6248
|
+
} else if (fm[1] === fenceMarker) {
|
|
6249
|
+
fence = false;
|
|
6250
|
+
fenceMarker = "";
|
|
6251
|
+
}
|
|
6252
|
+
continue;
|
|
6253
|
+
}
|
|
6254
|
+
if (fence)
|
|
6255
|
+
continue;
|
|
6256
|
+
lines[i] = lines[i].replace(/^(\s*)(\d+)\. /, "$1$2、");
|
|
6257
|
+
}
|
|
6258
|
+
return lines.join(`
|
|
6259
|
+
`);
|
|
6260
|
+
}
|
|
6099
6261
|
var DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
6100
|
-
var DELIVERY_DEDUPE_FILE = process.env.QQ_DELIVERY_DEDUPE_FILE ||
|
|
6262
|
+
var DELIVERY_DEDUPE_FILE = process.env.QQ_DELIVERY_DEDUPE_FILE || join9(homedir8(), ".openqq", "delivery-dedupe.json");
|
|
6101
6263
|
function deliveryAttemptKey(userId, text) {
|
|
6102
6264
|
return `${userId}:${createHash("sha256").update(text).digest("hex")}`;
|
|
6103
6265
|
}
|
|
6104
|
-
function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TTL_MS) {
|
|
6105
|
-
return text.length >= 200 && previous?.text ===
|
|
6266
|
+
function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TTL_MS, identity = text) {
|
|
6267
|
+
return text.length >= 200 && previous?.text === identity && now - previous.at < ttlMs;
|
|
6106
6268
|
}
|
|
6107
6269
|
function loadDeliveryAttempts() {
|
|
6108
6270
|
const out = new Map;
|
|
6109
6271
|
try {
|
|
6110
|
-
if (!
|
|
6272
|
+
if (!existsSync7(DELIVERY_DEDUPE_FILE))
|
|
6111
6273
|
return out;
|
|
6112
|
-
const raw = JSON.parse(
|
|
6274
|
+
const raw = JSON.parse(readFileSync9(DELIVERY_DEDUPE_FILE, "utf-8"));
|
|
6113
6275
|
const now = Date.now();
|
|
6114
6276
|
for (const entry of raw) {
|
|
6115
6277
|
if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
|
|
@@ -6121,10 +6283,74 @@ function loadDeliveryAttempts() {
|
|
|
6121
6283
|
}
|
|
6122
6284
|
function saveDeliveryAttempts(entries) {
|
|
6123
6285
|
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 = `${DELIVERY_DEDUPE_FILE}.tmp`;
|
|
6126
|
-
|
|
6127
|
-
|
|
6286
|
+
mkdirSync7(join9(DELIVERY_DEDUPE_FILE, ".."), { recursive: true });
|
|
6287
|
+
const tmp = `${DELIVERY_DEDUPE_FILE}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6288
|
+
try {
|
|
6289
|
+
writeFileSync9(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
|
|
6290
|
+
renameSync2(tmp, DELIVERY_DEDUPE_FILE);
|
|
6291
|
+
} catch (error) {
|
|
6292
|
+
try {
|
|
6293
|
+
unlinkSync3(tmp);
|
|
6294
|
+
} catch {}
|
|
6295
|
+
throw error;
|
|
6296
|
+
}
|
|
6297
|
+
}
|
|
6298
|
+
var DELIVERY_LOCK_STALE_MS = 30000;
|
|
6299
|
+
var DELIVERY_LOCK_WAIT_MS = 5000;
|
|
6300
|
+
var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6301
|
+
function withDeliveryLock(fn) {
|
|
6302
|
+
mkdirSync7(join9(DELIVERY_DEDUPE_FILE, ".."), { recursive: true });
|
|
6303
|
+
const lockPath = `${DELIVERY_DEDUPE_FILE}.lock`;
|
|
6304
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6305
|
+
const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
|
|
6306
|
+
for (;; ) {
|
|
6307
|
+
try {
|
|
6308
|
+
const fd = openSync(lockPath, "wx", 384);
|
|
6309
|
+
try {
|
|
6310
|
+
writeFileSync9(fd, token);
|
|
6311
|
+
} finally {
|
|
6312
|
+
closeSync(fd);
|
|
6313
|
+
}
|
|
6314
|
+
break;
|
|
6315
|
+
} catch (error) {
|
|
6316
|
+
try {
|
|
6317
|
+
if (Date.now() - statSync3(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS)
|
|
6318
|
+
unlinkSync3(lockPath);
|
|
6319
|
+
} catch {}
|
|
6320
|
+
if (Date.now() >= deadline)
|
|
6321
|
+
throw new Error(`同文投递锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6322
|
+
Atomics.wait(deliverySleepArray, 0, 0, 10);
|
|
6323
|
+
}
|
|
6324
|
+
}
|
|
6325
|
+
try {
|
|
6326
|
+
return fn();
|
|
6327
|
+
} finally {
|
|
6328
|
+
try {
|
|
6329
|
+
if (readFileSync9(lockPath, "utf-8") === token)
|
|
6330
|
+
unlinkSync3(lockPath);
|
|
6331
|
+
} catch {}
|
|
6332
|
+
}
|
|
6333
|
+
}
|
|
6334
|
+
function reserveDeliveryAttempt(userId, text, now = Date.now()) {
|
|
6335
|
+
const attemptKey = deliveryAttemptKey(userId, text);
|
|
6336
|
+
return withDeliveryLock(() => {
|
|
6337
|
+
const entries = loadDeliveryAttempts();
|
|
6338
|
+
if (shouldSuppressDuplicate(entries.get(attemptKey), text, now, DELIVERY_DEDUPE_TTL_MS, attemptKey))
|
|
6339
|
+
return null;
|
|
6340
|
+
entries.set(attemptKey, { text: attemptKey, at: now });
|
|
6341
|
+
saveDeliveryAttempts(entries);
|
|
6342
|
+
return attemptKey;
|
|
6343
|
+
});
|
|
6344
|
+
}
|
|
6345
|
+
function releaseDeliveryAttempt(userId, text, at) {
|
|
6346
|
+
const attemptKey = deliveryAttemptKey(userId, text);
|
|
6347
|
+
withDeliveryLock(() => {
|
|
6348
|
+
const entries = loadDeliveryAttempts();
|
|
6349
|
+
if (entries.get(attemptKey)?.at === at) {
|
|
6350
|
+
entries.delete(attemptKey);
|
|
6351
|
+
saveDeliveryAttempts(entries);
|
|
6352
|
+
}
|
|
6353
|
+
});
|
|
6128
6354
|
}
|
|
6129
6355
|
function selectRideMsgId(last, ctx, now, windowMs) {
|
|
6130
6356
|
if (!last?.msgId)
|
|
@@ -6152,7 +6378,6 @@ function createDelivery(config, lastCtx) {
|
|
|
6152
6378
|
})();
|
|
6153
6379
|
const pushQueues = new Map;
|
|
6154
6380
|
const undelivered = new Set;
|
|
6155
|
-
const recentDeliveries = loadDeliveryAttempts();
|
|
6156
6381
|
const activeQuota = new Map;
|
|
6157
6382
|
const passiveLimiter = new ReplyLimiter;
|
|
6158
6383
|
for (const [uid, q] of Object.entries(loadQuotaMap()))
|
|
@@ -6195,20 +6420,17 @@ function createDelivery(config, lastCtx) {
|
|
|
6195
6420
|
}
|
|
6196
6421
|
async function deliver(ctx, text) {
|
|
6197
6422
|
const now = Date.now();
|
|
6198
|
-
const attemptKey =
|
|
6199
|
-
if (
|
|
6423
|
+
const attemptKey = reserveDeliveryAttempt(ctx.userId, text, now);
|
|
6424
|
+
if (!attemptKey) {
|
|
6200
6425
|
console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`);
|
|
6201
6426
|
return;
|
|
6202
6427
|
}
|
|
6203
|
-
recentDeliveries.set(attemptKey, { text: attemptKey, at: now });
|
|
6204
6428
|
const hadNotice = undelivered.delete(ctx.userId);
|
|
6205
|
-
const body = hadNotice ? UNDELIVERED_NOTICE + text : text;
|
|
6429
|
+
const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text);
|
|
6206
6430
|
try {
|
|
6207
6431
|
await deliverCore(ctx, body);
|
|
6208
|
-
saveDeliveryAttempts(recentDeliveries);
|
|
6209
6432
|
} catch (error) {
|
|
6210
|
-
|
|
6211
|
-
recentDeliveries.delete(attemptKey);
|
|
6433
|
+
releaseDeliveryAttempt(ctx.userId, text, now);
|
|
6212
6434
|
if (hadNotice)
|
|
6213
6435
|
undelivered.add(ctx.userId);
|
|
6214
6436
|
throw error;
|
|
@@ -6384,11 +6606,183 @@ function handleApprovalInteraction(event, gate) {
|
|
|
6384
6606
|
return true;
|
|
6385
6607
|
}
|
|
6386
6608
|
|
|
6609
|
+
// src/core/form-journal.ts
|
|
6610
|
+
import {
|
|
6611
|
+
closeSync as closeSync2,
|
|
6612
|
+
existsSync as existsSync8,
|
|
6613
|
+
mkdirSync as mkdirSync8,
|
|
6614
|
+
openSync as openSync2,
|
|
6615
|
+
readFileSync as readFileSync10,
|
|
6616
|
+
renameSync as renameSync3,
|
|
6617
|
+
statSync as statSync4,
|
|
6618
|
+
unlinkSync as unlinkSync4,
|
|
6619
|
+
writeFileSync as writeFileSync10
|
|
6620
|
+
} from "fs";
|
|
6621
|
+
import { dirname, join as join10 } from "path";
|
|
6622
|
+
import { homedir as homedir9 } from "os";
|
|
6623
|
+
var LOCK_STALE_MS = 30000;
|
|
6624
|
+
var LOCK_WAIT_MS = 5000;
|
|
6625
|
+
var sleepArray = new Int32Array(new SharedArrayBuffer(4));
|
|
6626
|
+
var STATES = new Set(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"]);
|
|
6627
|
+
function defaultFormJournalPath() {
|
|
6628
|
+
return process.env.QQ_FORM_JOURNAL_FILE || join10(homedir9(), ".openqq", "forms.json");
|
|
6629
|
+
}
|
|
6630
|
+
function minimalFormContext(ctx) {
|
|
6631
|
+
return {
|
|
6632
|
+
type: ctx.type,
|
|
6633
|
+
userId: ctx.userId,
|
|
6634
|
+
...ctx.type === "group" && ctx.groupId ? { groupId: ctx.groupId } : {},
|
|
6635
|
+
msgId: "",
|
|
6636
|
+
content: "",
|
|
6637
|
+
...ctx.timestamp ? { timestamp: ctx.timestamp } : {}
|
|
6638
|
+
};
|
|
6639
|
+
}
|
|
6640
|
+
function validForm(value) {
|
|
6641
|
+
if (!value || typeof value !== "object")
|
|
6642
|
+
return false;
|
|
6643
|
+
const form = value;
|
|
6644
|
+
return typeof form.id === "string" && typeof form.sessionID === "string" && typeof form.title === "string" && Array.isArray(form.fields);
|
|
6645
|
+
}
|
|
6646
|
+
function normalizeEntry(value) {
|
|
6647
|
+
if (!value || typeof value !== "object")
|
|
6648
|
+
return;
|
|
6649
|
+
const entry = value;
|
|
6650
|
+
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)) {
|
|
6651
|
+
return;
|
|
6652
|
+
}
|
|
6653
|
+
return {
|
|
6654
|
+
form: entry.form,
|
|
6655
|
+
ctx: minimalFormContext({ ...entry.ctx, userId: entry.userId }),
|
|
6656
|
+
userId: entry.userId,
|
|
6657
|
+
createdAt: entry.createdAt,
|
|
6658
|
+
state: entry.state,
|
|
6659
|
+
...entry.answer && typeof entry.answer === "object" && !Array.isArray(entry.answer) ? { answer: entry.answer } : {},
|
|
6660
|
+
...typeof entry.display === "string" ? { display: entry.display } : {},
|
|
6661
|
+
...typeof entry.interactionId === "string" ? { interactionId: entry.interactionId } : {},
|
|
6662
|
+
updatedAt: entry.updatedAt
|
|
6663
|
+
};
|
|
6664
|
+
}
|
|
6665
|
+
function snapshot(entry) {
|
|
6666
|
+
return {
|
|
6667
|
+
form: entry.form,
|
|
6668
|
+
ctx: minimalFormContext(entry.ctx),
|
|
6669
|
+
userId: entry.userId,
|
|
6670
|
+
createdAt: entry.createdAt,
|
|
6671
|
+
state: entry.state,
|
|
6672
|
+
...entry.answer ? { answer: entry.answer } : {},
|
|
6673
|
+
...entry.display !== undefined ? { display: entry.display } : {},
|
|
6674
|
+
...entry.interactionId ? { interactionId: entry.interactionId } : {},
|
|
6675
|
+
updatedAt: entry.updatedAt
|
|
6676
|
+
};
|
|
6677
|
+
}
|
|
6678
|
+
function createFormJournal(path = defaultFormJournalPath()) {
|
|
6679
|
+
function read() {
|
|
6680
|
+
try {
|
|
6681
|
+
if (!existsSync8(path))
|
|
6682
|
+
return [];
|
|
6683
|
+
const raw = JSON.parse(readFileSync10(path, "utf-8"));
|
|
6684
|
+
const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
|
|
6685
|
+
const byUser = new Map;
|
|
6686
|
+
for (const value of values) {
|
|
6687
|
+
const entry = normalizeEntry(value);
|
|
6688
|
+
if (!entry)
|
|
6689
|
+
continue;
|
|
6690
|
+
const previous = byUser.get(entry.userId);
|
|
6691
|
+
if (!previous || previous.updatedAt <= entry.updatedAt)
|
|
6692
|
+
byUser.set(entry.userId, entry);
|
|
6693
|
+
}
|
|
6694
|
+
return [...byUser.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
6695
|
+
} catch (error) {
|
|
6696
|
+
console.warn("[form-journal] 台账读取失败,按空台账处理:", error instanceof Error ? error.message : error);
|
|
6697
|
+
return [];
|
|
6698
|
+
}
|
|
6699
|
+
}
|
|
6700
|
+
function write(entries) {
|
|
6701
|
+
mkdirSync8(dirname(path), { recursive: true });
|
|
6702
|
+
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6703
|
+
const payload = { version: 1, entries: entries.map(snapshot) };
|
|
6704
|
+
try {
|
|
6705
|
+
writeFileSync10(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
|
|
6706
|
+
renameSync3(tmp, path);
|
|
6707
|
+
} catch (error) {
|
|
6708
|
+
try {
|
|
6709
|
+
unlinkSync4(tmp);
|
|
6710
|
+
} catch {}
|
|
6711
|
+
throw error;
|
|
6712
|
+
}
|
|
6713
|
+
}
|
|
6714
|
+
function withLock(fn) {
|
|
6715
|
+
mkdirSync8(dirname(path), { recursive: true });
|
|
6716
|
+
const lockPath = `${path}.lock`;
|
|
6717
|
+
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6718
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
6719
|
+
for (;; ) {
|
|
6720
|
+
try {
|
|
6721
|
+
const fd = openSync2(lockPath, "wx", 384);
|
|
6722
|
+
try {
|
|
6723
|
+
writeFileSync10(fd, token);
|
|
6724
|
+
} finally {
|
|
6725
|
+
closeSync2(fd);
|
|
6726
|
+
}
|
|
6727
|
+
break;
|
|
6728
|
+
} catch (error) {
|
|
6729
|
+
try {
|
|
6730
|
+
if (Date.now() - statSync4(lockPath).mtimeMs > LOCK_STALE_MS)
|
|
6731
|
+
unlinkSync4(lockPath);
|
|
6732
|
+
} catch {}
|
|
6733
|
+
if (Date.now() >= deadline) {
|
|
6734
|
+
throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6735
|
+
}
|
|
6736
|
+
Atomics.wait(sleepArray, 0, 0, 10);
|
|
6737
|
+
}
|
|
6738
|
+
}
|
|
6739
|
+
try {
|
|
6740
|
+
return fn();
|
|
6741
|
+
} finally {
|
|
6742
|
+
try {
|
|
6743
|
+
if (readFileSync10(lockPath, "utf-8") === token)
|
|
6744
|
+
unlinkSync4(lockPath);
|
|
6745
|
+
} catch {}
|
|
6746
|
+
}
|
|
6747
|
+
}
|
|
6748
|
+
function mutate(fn) {
|
|
6749
|
+
withLock(() => {
|
|
6750
|
+
const entries = read();
|
|
6751
|
+
fn(entries);
|
|
6752
|
+
write(entries);
|
|
6753
|
+
});
|
|
6754
|
+
}
|
|
6755
|
+
return {
|
|
6756
|
+
path,
|
|
6757
|
+
load: read,
|
|
6758
|
+
put(entry) {
|
|
6759
|
+
mutate((entries) => {
|
|
6760
|
+
const index = entries.findIndex((item) => item.userId === entry.userId);
|
|
6761
|
+
if (index >= 0)
|
|
6762
|
+
entries[index] = snapshot(entry);
|
|
6763
|
+
else
|
|
6764
|
+
entries.push(snapshot(entry));
|
|
6765
|
+
});
|
|
6766
|
+
},
|
|
6767
|
+
remove(userId, formID) {
|
|
6768
|
+
mutate((entries) => {
|
|
6769
|
+
const index = entries.findIndex((item) => item.userId === userId && (!formID || item.form.id === formID));
|
|
6770
|
+
if (index >= 0)
|
|
6771
|
+
entries.splice(index, 1);
|
|
6772
|
+
});
|
|
6773
|
+
},
|
|
6774
|
+
clear() {
|
|
6775
|
+
withLock(() => write([]));
|
|
6776
|
+
}
|
|
6777
|
+
};
|
|
6778
|
+
}
|
|
6779
|
+
|
|
6387
6780
|
// src/core/form-bridge.ts
|
|
6388
6781
|
var FORM_PROMPT_TTL_MS = 30 * 60 * 1000;
|
|
6389
6782
|
var LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
6390
6783
|
var BUTTON_LABEL_MAX2 = 10;
|
|
6391
6784
|
var BUTTONS_PER_ROW = 2;
|
|
6785
|
+
var DEFAULT_DRAIN_TIMEOUT_MS = 5000;
|
|
6392
6786
|
function primaryField(form) {
|
|
6393
6787
|
return form.fields.find((f) => !f.hidden);
|
|
6394
6788
|
}
|
|
@@ -6497,7 +6891,8 @@ function decodeFormButton(raw) {
|
|
|
6497
6891
|
try {
|
|
6498
6892
|
const parsed = JSON.parse(raw);
|
|
6499
6893
|
if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
|
|
6500
|
-
|
|
6894
|
+
const interactionId = typeof parsed.i === "string" ? parsed.i : typeof parsed.interactionId === "string" ? parsed.interactionId : undefined;
|
|
6895
|
+
return { t: "form", f: parsed.f, k: parsed.k, v: parsed.v, ...interactionId ? { i: interactionId } : {} };
|
|
6501
6896
|
}
|
|
6502
6897
|
} catch {}
|
|
6503
6898
|
return;
|
|
@@ -6533,66 +6928,279 @@ function buildFormKeyboard(form, ownerOpenid) {
|
|
|
6533
6928
|
}
|
|
6534
6929
|
function createFormBridge(deps) {
|
|
6535
6930
|
const pending = new Map;
|
|
6536
|
-
|
|
6537
|
-
|
|
6538
|
-
|
|
6539
|
-
|
|
6931
|
+
const journal = deps.journal ?? createFormJournal(deps.journalPath);
|
|
6932
|
+
const now = deps.now ?? Date.now;
|
|
6933
|
+
const ttlMs = deps.ttlMs ?? FORM_PROMPT_TTL_MS;
|
|
6934
|
+
const operations = new Set;
|
|
6935
|
+
let accepting = true;
|
|
6936
|
+
function track(promise) {
|
|
6937
|
+
const tracked = promise.finally(() => operations.delete(tracked));
|
|
6938
|
+
operations.add(tracked);
|
|
6939
|
+
return tracked;
|
|
6940
|
+
}
|
|
6941
|
+
function deliver(ctx, text) {
|
|
6942
|
+
return track(deps.safeDeliver(ctx, text).catch((error) => {
|
|
6943
|
+
console.error("[form-bridge] 回执投递失败:", error instanceof Error ? error.message : error);
|
|
6944
|
+
}));
|
|
6945
|
+
}
|
|
6946
|
+
function journalSnapshot(entry) {
|
|
6947
|
+
return {
|
|
6948
|
+
form: entry.form,
|
|
6949
|
+
ctx: minimalFormContext(entry.ctx),
|
|
6950
|
+
userId: entry.userId,
|
|
6951
|
+
createdAt: entry.createdAt,
|
|
6952
|
+
state: entry.state,
|
|
6953
|
+
...entry.answer ? { answer: entry.answer } : {},
|
|
6954
|
+
...entry.display !== undefined ? { display: entry.display } : {},
|
|
6955
|
+
...entry.interactionId ? { interactionId: entry.interactionId } : {},
|
|
6956
|
+
updatedAt: entry.updatedAt
|
|
6957
|
+
};
|
|
6958
|
+
}
|
|
6959
|
+
function transition(entry, state) {
|
|
6960
|
+
const previous = entry.state;
|
|
6961
|
+
const previousUpdatedAt = entry.updatedAt;
|
|
6962
|
+
entry.state = state;
|
|
6963
|
+
entry.updatedAt = now();
|
|
6964
|
+
try {
|
|
6965
|
+
journal.put(journalSnapshot(entry));
|
|
6966
|
+
} catch (error) {
|
|
6967
|
+
entry.state = previous;
|
|
6968
|
+
entry.updatedAt = previousUpdatedAt;
|
|
6969
|
+
throw error;
|
|
6970
|
+
}
|
|
6971
|
+
}
|
|
6972
|
+
function clearEntry(userId, entry) {
|
|
6973
|
+
if (pending.get(userId) !== entry)
|
|
6974
|
+
return false;
|
|
6540
6975
|
if (entry.timer)
|
|
6541
6976
|
clearTimeout(entry.timer);
|
|
6977
|
+
entry.timer = null;
|
|
6542
6978
|
pending.delete(userId);
|
|
6543
|
-
|
|
6979
|
+
try {
|
|
6980
|
+
journal.remove(userId, entry.form.id);
|
|
6981
|
+
} catch (error) {
|
|
6982
|
+
console.error("[form-bridge] 清理表单台账失败:", error instanceof Error ? error.message : error);
|
|
6983
|
+
}
|
|
6984
|
+
return true;
|
|
6544
6985
|
}
|
|
6545
|
-
function
|
|
6546
|
-
|
|
6547
|
-
|
|
6986
|
+
function isCurrent(userId, entry) {
|
|
6987
|
+
return pending.get(userId) === entry;
|
|
6988
|
+
}
|
|
6989
|
+
function submit(userId, entry, answer, display, interactionId) {
|
|
6990
|
+
if (!isCurrent(userId, entry) || entry.replying || entry.cancelling)
|
|
6991
|
+
return;
|
|
6992
|
+
entry.answer = answer;
|
|
6993
|
+
entry.display = display;
|
|
6994
|
+
if (interactionId)
|
|
6995
|
+
entry.interactionId = interactionId;
|
|
6996
|
+
entry.replying = true;
|
|
6997
|
+
try {
|
|
6998
|
+
transition(entry, "submitting");
|
|
6999
|
+
} catch (error) {
|
|
7000
|
+
entry.replying = false;
|
|
7001
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
7002
|
+
deliver(entry.ctx, `⚠️ 无法保存提交状态,尚未向服务端作答:${msg};请回桌面处理`);
|
|
7003
|
+
return;
|
|
7004
|
+
}
|
|
7005
|
+
const operation = (async () => {
|
|
6548
7006
|
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}`);
|
|
7007
|
+
await deps.client.form.reply({
|
|
7008
|
+
path: { sessionID: entry.form.sessionID, formID: entry.form.id },
|
|
7009
|
+
body: { answer }
|
|
7010
|
+
});
|
|
6554
7011
|
} catch (error) {
|
|
7012
|
+
entry.replying = false;
|
|
6555
7013
|
const msg = error instanceof Error ? error.message : String(error);
|
|
6556
|
-
if (
|
|
6557
|
-
|
|
7014
|
+
if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
|
|
7015
|
+
if (isCurrent(userId, entry))
|
|
7016
|
+
clearEntry(userId, entry);
|
|
7017
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效");
|
|
6558
7018
|
} else {
|
|
6559
|
-
|
|
7019
|
+
await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`);
|
|
6560
7020
|
}
|
|
7021
|
+
return;
|
|
6561
7022
|
}
|
|
6562
|
-
|
|
7023
|
+
entry.replying = false;
|
|
7024
|
+
if (isCurrent(userId, entry)) {
|
|
7025
|
+
try {
|
|
7026
|
+
transition(entry, "replied");
|
|
7027
|
+
} catch (error) {
|
|
7028
|
+
console.error("[form-bridge] replied 状态落盘失败:", error instanceof Error ? error.message : error);
|
|
7029
|
+
}
|
|
7030
|
+
clearEntry(userId, entry);
|
|
7031
|
+
}
|
|
7032
|
+
console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${entry.form.id} answer=${display}`);
|
|
7033
|
+
})().catch((error) => {
|
|
7034
|
+
entry.replying = false;
|
|
7035
|
+
console.error("[form-bridge] 提交流程异常:", error instanceof Error ? error.message : error);
|
|
7036
|
+
});
|
|
7037
|
+
track(operation);
|
|
7038
|
+
}
|
|
7039
|
+
async function expireEntry(userId, entry) {
|
|
7040
|
+
if (!isCurrent(userId, entry) || entry.replying || entry.cancelling || entry.state === "expired" && entry.cancelling)
|
|
7041
|
+
return;
|
|
7042
|
+
entry.cancelling = true;
|
|
7043
|
+
if (entry.timer)
|
|
7044
|
+
clearTimeout(entry.timer);
|
|
7045
|
+
entry.timer = null;
|
|
7046
|
+
try {
|
|
7047
|
+
transition(entry, "expired");
|
|
7048
|
+
} catch (error) {
|
|
7049
|
+
entry.cancelling = false;
|
|
7050
|
+
await deliver(entry.ctx, `⚠️ 选择已到期,但取消状态无法落盘;请回桌面处理:${error instanceof Error ? error.message : error}`);
|
|
7051
|
+
return;
|
|
7052
|
+
}
|
|
7053
|
+
try {
|
|
7054
|
+
await deps.client.form.cancel({ path: { sessionID: entry.form.sessionID, formID: entry.form.id } });
|
|
7055
|
+
} catch (error) {
|
|
7056
|
+
entry.cancelling = false;
|
|
7057
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
7058
|
+
await deliver(entry.ctx, `⚠️ 选择请求已到期,但服务端取消失败(${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg});本地已保留恢复记录,请回桌面确认`);
|
|
7059
|
+
return;
|
|
7060
|
+
}
|
|
7061
|
+
entry.cancelling = false;
|
|
7062
|
+
if (isCurrent(userId, entry)) {
|
|
7063
|
+
try {
|
|
7064
|
+
transition(entry, "cancelled");
|
|
7065
|
+
} catch (error) {
|
|
7066
|
+
console.error("[form-bridge] cancelled 状态落盘失败:", error instanceof Error ? error.message : error);
|
|
7067
|
+
}
|
|
7068
|
+
clearEntry(userId, entry);
|
|
7069
|
+
}
|
|
7070
|
+
await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;如需继续请回桌面重试");
|
|
7071
|
+
}
|
|
7072
|
+
function scheduleExpiry(userId, entry) {
|
|
7073
|
+
if (!accepting)
|
|
7074
|
+
return;
|
|
7075
|
+
const remaining = Math.max(0, entry.createdAt + ttlMs - now());
|
|
7076
|
+
entry.timer = setTimeout(() => {
|
|
7077
|
+
track(expireEntry(userId, entry));
|
|
7078
|
+
}, remaining);
|
|
7079
|
+
entry.timer.unref?.();
|
|
7080
|
+
}
|
|
7081
|
+
function restore() {
|
|
7082
|
+
const sessions = new Set;
|
|
7083
|
+
for (const saved of journal.load()) {
|
|
7084
|
+
sessions.add(saved.form.sessionID);
|
|
7085
|
+
if (saved.state === "replied" || saved.state === "cancelled") {
|
|
7086
|
+
try {
|
|
7087
|
+
journal.remove(saved.userId, saved.form.id);
|
|
7088
|
+
} catch {}
|
|
7089
|
+
continue;
|
|
7090
|
+
}
|
|
7091
|
+
const entry = {
|
|
7092
|
+
...saved,
|
|
7093
|
+
ctx: minimalFormContext({ ...saved.ctx, userId: saved.userId }),
|
|
7094
|
+
timer: null,
|
|
7095
|
+
restored: true,
|
|
7096
|
+
replying: false,
|
|
7097
|
+
cancelling: false
|
|
7098
|
+
};
|
|
7099
|
+
const previous = pending.get(saved.userId);
|
|
7100
|
+
if (previous && previous.updatedAt > entry.updatedAt)
|
|
7101
|
+
continue;
|
|
7102
|
+
if (previous?.timer)
|
|
7103
|
+
clearTimeout(previous.timer);
|
|
7104
|
+
pending.set(saved.userId, entry);
|
|
7105
|
+
scheduleExpiry(saved.userId, entry);
|
|
7106
|
+
console.log(`[form-bridge] 恢复本地表单 user=${saved.userId.slice(0, 8)}… form=${saved.form.id} state=${saved.state}`);
|
|
7107
|
+
}
|
|
7108
|
+
return [...sessions];
|
|
7109
|
+
}
|
|
7110
|
+
async function reconcile(sessionID) {
|
|
7111
|
+
let forms;
|
|
7112
|
+
try {
|
|
7113
|
+
forms = (await deps.client.form.list({ sessionID })).data ?? [];
|
|
7114
|
+
} catch (error) {
|
|
7115
|
+
console.error(`[form-bridge] 会话表单对账失败 session=${sessionID}:`, error instanceof Error ? error.message : error);
|
|
7116
|
+
return false;
|
|
7117
|
+
}
|
|
7118
|
+
const candidates = [...pending.entries()].filter(([, entry]) => entry.form.sessionID === sessionID);
|
|
7119
|
+
for (const [userId, entry] of candidates) {
|
|
7120
|
+
if (!isCurrent(userId, entry))
|
|
7121
|
+
continue;
|
|
7122
|
+
const server = forms.find((form) => form.id === entry.form.id);
|
|
7123
|
+
const serverStatus = typeof server?.state === "string" ? server.state : server?.state?.status;
|
|
7124
|
+
const serverPending = server !== undefined && (!serverStatus || serverStatus === "pending");
|
|
7125
|
+
if (!serverPending) {
|
|
7126
|
+
clearEntry(userId, entry);
|
|
7127
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效");
|
|
7128
|
+
continue;
|
|
7129
|
+
}
|
|
7130
|
+
if (entry.state === "expired") {
|
|
7131
|
+
if (!entry.cancelling)
|
|
7132
|
+
await track(expireEntry(userId, entry));
|
|
7133
|
+
} else if ((entry.state === "clickReceived" || entry.state === "submitting") && entry.answer && !entry.replying) {
|
|
7134
|
+
submit(userId, entry, entry.answer, entry.display ?? "已恢复的选择", entry.interactionId);
|
|
7135
|
+
}
|
|
7136
|
+
}
|
|
7137
|
+
return true;
|
|
6563
7138
|
}
|
|
6564
7139
|
function pushForm(userId, ctx, form) {
|
|
7140
|
+
if (!accepting) {
|
|
7141
|
+
deliver(ctx, "⚠️ 表单桥正在停止,暂不接受新的 QQ 作答;请回桌面处理");
|
|
7142
|
+
return;
|
|
7143
|
+
}
|
|
6565
7144
|
if (pending.get(userId)?.form.id === form.id)
|
|
6566
7145
|
return;
|
|
6567
|
-
const
|
|
6568
|
-
|
|
6569
|
-
|
|
7146
|
+
const liveCtx = { ...minimalFormContext(ctx), msgId: ctx.msgId };
|
|
7147
|
+
const timestamp = now();
|
|
7148
|
+
const entry = {
|
|
7149
|
+
form,
|
|
7150
|
+
ctx: liveCtx,
|
|
7151
|
+
userId,
|
|
7152
|
+
createdAt: timestamp,
|
|
7153
|
+
state: "pending",
|
|
7154
|
+
updatedAt: timestamp,
|
|
7155
|
+
timer: null,
|
|
7156
|
+
replying: false,
|
|
7157
|
+
cancelling: false
|
|
7158
|
+
};
|
|
7159
|
+
try {
|
|
7160
|
+
journal.put(journalSnapshot(entry));
|
|
7161
|
+
} catch (error) {
|
|
7162
|
+
console.error("[form-bridge] 表单落盘失败,取消 QQ 推送:", error instanceof Error ? error.message : error);
|
|
7163
|
+
deliver(ctx, "⚠️ 选择请求无法保存恢复记录,本次未推送到 QQ;请回桌面处理");
|
|
7164
|
+
return;
|
|
6570
7165
|
}
|
|
6571
|
-
const
|
|
6572
|
-
|
|
6573
|
-
|
|
6574
|
-
return;
|
|
6575
|
-
clear(userId);
|
|
6576
|
-
deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {});
|
|
6577
|
-
}, FORM_PROMPT_TTL_MS);
|
|
7166
|
+
const previous = pending.get(userId);
|
|
7167
|
+
if (previous?.timer)
|
|
7168
|
+
clearTimeout(previous.timer);
|
|
6578
7169
|
pending.set(userId, entry);
|
|
7170
|
+
scheduleExpiry(userId, entry);
|
|
7171
|
+
if (previous) {
|
|
7172
|
+
deliver(previous.ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)");
|
|
7173
|
+
}
|
|
6579
7174
|
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,
|
|
7175
|
+
const operation = (async () => {
|
|
7176
|
+
const keyboard = buildFormKeyboard(form, liveCtx.userId);
|
|
6582
7177
|
if (keyboard && deps.sendFormCard) {
|
|
6583
|
-
const sent = await deps.sendFormCard(
|
|
7178
|
+
const sent = await deps.sendFormCard(liveCtx, form, keyboard).catch(() => false);
|
|
6584
7179
|
if (sent)
|
|
6585
7180
|
return;
|
|
6586
7181
|
}
|
|
6587
|
-
await deps.sendReply(
|
|
7182
|
+
await deps.sendReply(liveCtx, renderFormPrompt(form)).catch((error) => {
|
|
6588
7183
|
console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error);
|
|
6589
7184
|
});
|
|
6590
7185
|
})();
|
|
7186
|
+
track(operation);
|
|
6591
7187
|
}
|
|
6592
7188
|
function tryResolveText(userId, text) {
|
|
6593
7189
|
const entry = pending.get(userId);
|
|
6594
7190
|
if (!entry)
|
|
6595
7191
|
return false;
|
|
7192
|
+
if (!accepting) {
|
|
7193
|
+
deliver(entry.ctx, "⚠️ 表单桥正在停止,本次答案未提交;请回桌面处理");
|
|
7194
|
+
return true;
|
|
7195
|
+
}
|
|
7196
|
+
if (entry.state === "expired") {
|
|
7197
|
+
deliver(entry.ctx, "⚠️ 按钮和文字答案已失效,请使用新卡或回桌面处理");
|
|
7198
|
+
return true;
|
|
7199
|
+
}
|
|
7200
|
+
if (entry.replying || entry.cancelling) {
|
|
7201
|
+
deliver(entry.ctx, "⏳ 选择正在提交或取消,请勿重复操作;稍后会给出最终回执");
|
|
7202
|
+
return true;
|
|
7203
|
+
}
|
|
6596
7204
|
const answer = parseFormAnswer(entry.form, text);
|
|
6597
7205
|
if (!answer) {
|
|
6598
7206
|
const field = primaryField(entry.form);
|
|
@@ -6600,9 +7208,21 @@ function createFormBridge(deps) {
|
|
|
6600
7208
|
deps.sendReply(entry.ctx, hint).catch(() => {});
|
|
6601
7209
|
return true;
|
|
6602
7210
|
}
|
|
6603
|
-
submit(userId, entry
|
|
7211
|
+
submit(userId, entry, answer, text.trim());
|
|
6604
7212
|
return true;
|
|
6605
7213
|
}
|
|
7214
|
+
function eventContext(event, userId) {
|
|
7215
|
+
return {
|
|
7216
|
+
type: event.group_member_openid ? "group" : "c2c",
|
|
7217
|
+
userId,
|
|
7218
|
+
...event.group_member_openid && event.group_openid ? { groupId: event.group_openid } : {},
|
|
7219
|
+
msgId: "",
|
|
7220
|
+
content: ""
|
|
7221
|
+
};
|
|
7222
|
+
}
|
|
7223
|
+
function rejectButton(ctx) {
|
|
7224
|
+
deliver(ctx, "⚠️ 按钮已失效、已处理或不属于当前选择,请使用新卡或回桌面处理");
|
|
7225
|
+
}
|
|
6606
7226
|
function handleButton(event) {
|
|
6607
7227
|
const userId = event.user_openid ?? event.group_member_openid;
|
|
6608
7228
|
if (!userId)
|
|
@@ -6611,91 +7231,178 @@ function createFormBridge(deps) {
|
|
|
6611
7231
|
if (!button)
|
|
6612
7232
|
return false;
|
|
6613
7233
|
const entry = pending.get(userId);
|
|
6614
|
-
|
|
7234
|
+
const ctx = entry?.ctx ?? eventContext(event, userId);
|
|
7235
|
+
if (!accepting || !entry || entry.form.id !== button.f || entry.state === "expired") {
|
|
6615
7236
|
console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`);
|
|
7237
|
+
rejectButton(ctx);
|
|
7238
|
+
return true;
|
|
7239
|
+
}
|
|
7240
|
+
if (entry.replying || entry.cancelling) {
|
|
7241
|
+
deliver(ctx, "⏳ 该按钮已受理,正在等待服务端最终结果,请勿重复点击");
|
|
7242
|
+
return true;
|
|
7243
|
+
}
|
|
7244
|
+
const field = entry.form.fields.find((candidate) => candidate.key === button.k && !candidate.hidden);
|
|
7245
|
+
const option = field?.options?.find((candidate) => candidate.value === button.v);
|
|
7246
|
+
if (!field || field.type !== "string" && field.type !== "multiselect" || !option) {
|
|
7247
|
+
rejectButton(ctx);
|
|
7248
|
+
return true;
|
|
7249
|
+
}
|
|
7250
|
+
const interactionId = button.i ?? event.data?.resolved?.button_id ?? event.id;
|
|
7251
|
+
const answer = { [button.k]: field.type === "multiselect" ? [button.v] : button.v };
|
|
7252
|
+
entry.answer = answer;
|
|
7253
|
+
entry.display = button.v;
|
|
7254
|
+
if (interactionId)
|
|
7255
|
+
entry.interactionId = interactionId;
|
|
7256
|
+
try {
|
|
7257
|
+
transition(entry, "clickReceived");
|
|
7258
|
+
} catch (error) {
|
|
7259
|
+
deliver(ctx, `⚠️ 无法保存按钮受理状态,尚未提交:${error instanceof Error ? error.message : error}`);
|
|
6616
7260
|
return true;
|
|
6617
7261
|
}
|
|
6618
|
-
|
|
6619
|
-
submit(userId, entry.form, entry.ctx, answer, button.v, true);
|
|
7262
|
+
submit(userId, entry, answer, button.v, interactionId);
|
|
6620
7263
|
return true;
|
|
6621
7264
|
}
|
|
6622
|
-
|
|
7265
|
+
async function drainInteractions(timeoutMs = DEFAULT_DRAIN_TIMEOUT_MS) {
|
|
7266
|
+
const deadline = Date.now() + Math.max(0, timeoutMs);
|
|
7267
|
+
while (operations.size > 0) {
|
|
7268
|
+
const remaining = deadline - Date.now();
|
|
7269
|
+
if (remaining <= 0)
|
|
7270
|
+
return false;
|
|
7271
|
+
let timer;
|
|
7272
|
+
const timeout = new Promise((resolve) => {
|
|
7273
|
+
timer = setTimeout(() => resolve("timeout"), remaining);
|
|
7274
|
+
});
|
|
7275
|
+
const drained = Promise.allSettled([...operations]).then(() => "drained");
|
|
7276
|
+
const result = await Promise.race([drained, timeout]);
|
|
7277
|
+
if (timer)
|
|
7278
|
+
clearTimeout(timer);
|
|
7279
|
+
if (result === "timeout")
|
|
7280
|
+
return false;
|
|
7281
|
+
}
|
|
7282
|
+
return true;
|
|
7283
|
+
}
|
|
7284
|
+
function stopAccepting() {
|
|
7285
|
+
accepting = false;
|
|
7286
|
+
for (const entry of pending.values()) {
|
|
7287
|
+
if (entry.timer)
|
|
7288
|
+
clearTimeout(entry.timer);
|
|
7289
|
+
entry.timer = null;
|
|
7290
|
+
}
|
|
7291
|
+
}
|
|
7292
|
+
return {
|
|
7293
|
+
pushForm,
|
|
7294
|
+
tryResolveText,
|
|
7295
|
+
handleButton,
|
|
7296
|
+
hasPending: (userId) => pending.has(userId),
|
|
7297
|
+
getPending: (userId) => pending.get(userId),
|
|
7298
|
+
restore,
|
|
7299
|
+
reconcile,
|
|
7300
|
+
drainInteractions,
|
|
7301
|
+
stopAccepting
|
|
7302
|
+
};
|
|
6623
7303
|
}
|
|
6624
7304
|
|
|
6625
7305
|
// src/core/inflight-journal.ts
|
|
6626
|
-
import { existsSync as
|
|
6627
|
-
import { join as
|
|
6628
|
-
import { homedir as
|
|
7306
|
+
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";
|
|
7307
|
+
import { join as join11 } from "path";
|
|
7308
|
+
import { homedir as homedir10 } from "os";
|
|
7309
|
+
|
|
7310
|
+
// src/core/inbound-dedupe.ts
|
|
7311
|
+
import { createHash as createHash2 } from "crypto";
|
|
7312
|
+
function messageFingerprint(userId, intentKey) {
|
|
7313
|
+
return createHash2("sha256").update(`${userId}\x00${intentKey}`).digest("hex").slice(0, 32);
|
|
7314
|
+
}
|
|
7315
|
+
function admissionDecision(input) {
|
|
7316
|
+
if (input.hasSameMsgIdInflight)
|
|
7317
|
+
return "duplicate-msgid";
|
|
7318
|
+
if (input.fingerprint && input.inflightFingerprints.includes(input.fingerprint)) {
|
|
7319
|
+
return "duplicate-intent";
|
|
7320
|
+
}
|
|
7321
|
+
return "ok";
|
|
7322
|
+
}
|
|
7323
|
+
|
|
7324
|
+
// src/core/inflight-journal.ts
|
|
7325
|
+
function newInflightAttemptId() {
|
|
7326
|
+
return `att-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
7327
|
+
}
|
|
6629
7328
|
var INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
|
7329
|
+
var SETTLED_RETENTION_MS = INFLIGHT_MAX_AGE_MS;
|
|
7330
|
+
var SETTLED_RETENTION_LIMIT = 20;
|
|
7331
|
+
function pruneInflightEntries(entries, now = Date.now()) {
|
|
7332
|
+
const indexed = entries.map((entry, index) => ({ entry, index }));
|
|
7333
|
+
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));
|
|
7334
|
+
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);
|
|
7335
|
+
}
|
|
6630
7336
|
function redispatchMaxAgeMs() {
|
|
6631
7337
|
const n = Number(process.env.QQ_REDISPATCH_MAX_AGE_MS ?? "7200000");
|
|
6632
7338
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7200000;
|
|
6633
7339
|
}
|
|
6634
7340
|
function journalPath() {
|
|
6635
|
-
return process.env.QQ_INFLIGHT_FILE ||
|
|
7341
|
+
return process.env.QQ_INFLIGHT_FILE || join11(homedir10(), ".openqq", "inflight.json");
|
|
6636
7342
|
}
|
|
6637
7343
|
function load() {
|
|
6638
7344
|
let entries = [];
|
|
6639
7345
|
try {
|
|
6640
|
-
if (
|
|
6641
|
-
const raw = JSON.parse(
|
|
7346
|
+
if (existsSync9(journalPath())) {
|
|
7347
|
+
const raw = JSON.parse(readFileSync11(journalPath(), "utf-8"));
|
|
6642
7348
|
if (Array.isArray(raw))
|
|
6643
7349
|
entries = raw;
|
|
6644
7350
|
}
|
|
6645
7351
|
} catch {
|
|
6646
7352
|
entries = [];
|
|
6647
7353
|
}
|
|
6648
|
-
return entries
|
|
7354
|
+
return pruneInflightEntries(entries);
|
|
6649
7355
|
}
|
|
6650
7356
|
function save(entries) {
|
|
6651
7357
|
const path = journalPath();
|
|
6652
|
-
|
|
7358
|
+
mkdirSync9(join11(path, ".."), { recursive: true });
|
|
7359
|
+
const retained = pruneInflightEntries(entries);
|
|
6653
7360
|
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
6654
7361
|
try {
|
|
6655
|
-
|
|
6656
|
-
|
|
7362
|
+
writeFileSync11(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
|
|
7363
|
+
renameSync4(tmp, path);
|
|
6657
7364
|
} catch (error) {
|
|
6658
7365
|
try {
|
|
6659
|
-
|
|
7366
|
+
unlinkSync5(tmp);
|
|
6660
7367
|
} catch {}
|
|
6661
7368
|
throw error;
|
|
6662
7369
|
}
|
|
6663
7370
|
}
|
|
6664
7371
|
var JOURNAL_LOCK_STALE_MS = 30000;
|
|
6665
7372
|
var JOURNAL_LOCK_WAIT_MS = 5000;
|
|
6666
|
-
var
|
|
7373
|
+
var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
|
|
6667
7374
|
function withJournalLock(fn) {
|
|
6668
7375
|
const path = journalPath();
|
|
6669
|
-
|
|
7376
|
+
mkdirSync9(join11(path, ".."), { recursive: true });
|
|
6670
7377
|
const lockPath = `${path}.lock`;
|
|
6671
7378
|
const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
6672
7379
|
const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
|
|
6673
7380
|
for (;; ) {
|
|
6674
7381
|
try {
|
|
6675
|
-
const fd =
|
|
7382
|
+
const fd = openSync3(lockPath, "wx", 384);
|
|
6676
7383
|
try {
|
|
6677
|
-
|
|
7384
|
+
writeFileSync11(fd, token);
|
|
6678
7385
|
} finally {
|
|
6679
|
-
|
|
7386
|
+
closeSync3(fd);
|
|
6680
7387
|
}
|
|
6681
7388
|
break;
|
|
6682
7389
|
} catch (error) {
|
|
6683
7390
|
try {
|
|
6684
|
-
if (Date.now() -
|
|
6685
|
-
|
|
7391
|
+
if (Date.now() - statSync5(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
|
|
7392
|
+
unlinkSync5(lockPath);
|
|
6686
7393
|
} catch {}
|
|
6687
7394
|
if (Date.now() >= deadline) {
|
|
6688
7395
|
throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
|
|
6689
7396
|
}
|
|
6690
|
-
Atomics.wait(
|
|
7397
|
+
Atomics.wait(sleepArray2, 0, 0, 10);
|
|
6691
7398
|
}
|
|
6692
7399
|
}
|
|
6693
7400
|
try {
|
|
6694
7401
|
return fn();
|
|
6695
7402
|
} finally {
|
|
6696
7403
|
try {
|
|
6697
|
-
if (
|
|
6698
|
-
|
|
7404
|
+
if (readFileSync11(lockPath, "utf-8") === token)
|
|
7405
|
+
unlinkSync5(lockPath);
|
|
6699
7406
|
} catch {}
|
|
6700
7407
|
}
|
|
6701
7408
|
}
|
|
@@ -6707,35 +7414,68 @@ function mutate(fn) {
|
|
|
6707
7414
|
return result;
|
|
6708
7415
|
});
|
|
6709
7416
|
}
|
|
6710
|
-
function
|
|
7417
|
+
function claimInflightDetailed(entry, opts) {
|
|
6711
7418
|
return mutate((entries) => {
|
|
6712
|
-
|
|
6713
|
-
|
|
6714
|
-
|
|
6715
|
-
|
|
7419
|
+
const fingerprint = opts?.fingerprint ?? entry.fingerprint ?? "";
|
|
7420
|
+
const decision = admissionDecision({
|
|
7421
|
+
hasSameMsgIdInflight: entries.some((e) => e.msgId === entry.msgId && e.state === "inflight"),
|
|
7422
|
+
fingerprint,
|
|
7423
|
+
inflightFingerprints: entries.filter((e) => e.state === "inflight" && e.fingerprint).map((e) => e.fingerprint)
|
|
7424
|
+
});
|
|
7425
|
+
if (decision !== "ok")
|
|
7426
|
+
return decision;
|
|
7427
|
+
const attempt = entry.attemptId ?? newInflightAttemptId();
|
|
7428
|
+
const existing = entries.find((e) => e.msgId === entry.msgId);
|
|
7429
|
+
if (existing) {
|
|
7430
|
+
Object.assign(existing, entry, { fingerprint, attemptId: attempt, state: "inflight" });
|
|
7431
|
+
} else {
|
|
7432
|
+
entries.push({ ...entry, fingerprint, attemptId: attempt, state: "inflight" });
|
|
7433
|
+
}
|
|
7434
|
+
return "ok";
|
|
6716
7435
|
});
|
|
6717
7436
|
}
|
|
6718
7437
|
function recordInflight(entry) {
|
|
6719
7438
|
mutate((entries) => {
|
|
6720
7439
|
const existing = entries.find((e) => e.msgId === entry.msgId);
|
|
6721
7440
|
if (existing) {
|
|
6722
|
-
if (
|
|
6723
|
-
existing.
|
|
7441
|
+
if (existing.state === "inflight") {
|
|
7442
|
+
if (entry.attemptId && existing.attemptId && entry.attemptId !== existing.attemptId)
|
|
7443
|
+
return;
|
|
7444
|
+
if (!existing.sessionId && entry.sessionId)
|
|
7445
|
+
existing.sessionId = entry.sessionId;
|
|
7446
|
+
if (!existing.promptId && entry.promptId)
|
|
7447
|
+
existing.promptId = entry.promptId;
|
|
7448
|
+
return;
|
|
7449
|
+
}
|
|
7450
|
+
const attempt = entry.attemptId ?? newInflightAttemptId();
|
|
7451
|
+
Object.assign(existing, entry, { attemptId: attempt, state: "inflight" });
|
|
6724
7452
|
return;
|
|
6725
7453
|
}
|
|
6726
|
-
entries.push({ ...entry, state: "inflight" });
|
|
7454
|
+
entries.push({ ...entry, attemptId: entry.attemptId ?? newInflightAttemptId(), state: "inflight" });
|
|
6727
7455
|
});
|
|
6728
7456
|
}
|
|
6729
|
-
function settleInflight(msgId) {
|
|
6730
|
-
mutate((entries) => {
|
|
6731
|
-
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
|
|
6732
|
-
if (entry)
|
|
6733
|
-
|
|
7457
|
+
function settleInflight(msgId, attemptId) {
|
|
7458
|
+
return mutate((entries) => {
|
|
7459
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight" && (!attemptId || !e.attemptId || e.attemptId === attemptId));
|
|
7460
|
+
if (!entry)
|
|
7461
|
+
return false;
|
|
7462
|
+
entry.state = "settled";
|
|
7463
|
+
return true;
|
|
6734
7464
|
});
|
|
6735
7465
|
}
|
|
6736
7466
|
function pendingInflight() {
|
|
6737
7467
|
return load().filter((e) => e.state === "inflight");
|
|
6738
7468
|
}
|
|
7469
|
+
function markInflightPromptId(msgId, promptId) {
|
|
7470
|
+
if (!promptId)
|
|
7471
|
+
return;
|
|
7472
|
+
mutate((entries) => {
|
|
7473
|
+
const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
|
|
7474
|
+
if (entry && !entry.promptId)
|
|
7475
|
+
entry.promptId = promptId;
|
|
7476
|
+
});
|
|
7477
|
+
}
|
|
7478
|
+
var TIME_ANCHOR_TOLERANCE_MS = 120000;
|
|
6739
7479
|
function classifyInflight(entry, messages) {
|
|
6740
7480
|
const ordered = [...messages].reverse();
|
|
6741
7481
|
const probe = entry.text.trim().slice(0, 50);
|
|
@@ -6755,6 +7495,21 @@ function classifyInflight(entry, messages) {
|
|
|
6755
7495
|
}
|
|
6756
7496
|
}
|
|
6757
7497
|
}
|
|
7498
|
+
if (userIdx < 0 && entry.at !== undefined) {
|
|
7499
|
+
let bestIdx = -1;
|
|
7500
|
+
let bestDelta = Number.POSITIVE_INFINITY;
|
|
7501
|
+
for (let i = ordered.length - 1;i >= 0; i--) {
|
|
7502
|
+
if (ordered[i].type !== "user")
|
|
7503
|
+
continue;
|
|
7504
|
+
const delta = Math.abs((ordered[i].time?.created ?? 0) - entry.at);
|
|
7505
|
+
if (delta < bestDelta) {
|
|
7506
|
+
bestDelta = delta;
|
|
7507
|
+
bestIdx = i;
|
|
7508
|
+
}
|
|
7509
|
+
}
|
|
7510
|
+
if (bestIdx >= 0 && bestDelta <= TIME_ANCHOR_TOLERANCE_MS)
|
|
7511
|
+
userIdx = bestIdx;
|
|
7512
|
+
}
|
|
6758
7513
|
if (userIdx < 0)
|
|
6759
7514
|
return { kind: "lost" };
|
|
6760
7515
|
let turnEnd = ordered.length;
|
|
@@ -6791,6 +7546,12 @@ function evictableIdleSessions(lastActivity, watched, now, idleMs) {
|
|
|
6791
7546
|
}
|
|
6792
7547
|
return out;
|
|
6793
7548
|
}
|
|
7549
|
+
function stallNudgeText(minsExec, s) {
|
|
7550
|
+
const status = !s.anchored ? "状态不明(历史账无归属锚点)" : s.roundRunning ? "已停滞(回合尚未终结,可能被桌面端审批/选择弹窗阻塞)" : "已终结但未回传(异常)";
|
|
7551
|
+
const action = s.lastAction ? `|最近动作:${s.lastAction}` : "";
|
|
7552
|
+
return `⚠️ 后台任务执行超过 ${minsExec} 分钟|状态:${status}|已 ${s.idleMin} 分钟无进展${action}
|
|
7553
|
+
桌面端确实空闲请忽略本提醒;或回复 /stop 中止该回合后重发。`;
|
|
7554
|
+
}
|
|
6794
7555
|
function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, intervalMs, maxNudges) {
|
|
6795
7556
|
if (nudges >= maxNudges)
|
|
6796
7557
|
return "wait";
|
|
@@ -6799,8 +7560,11 @@ function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, int
|
|
|
6799
7560
|
return now - base >= need ? "nudge" : "wait";
|
|
6800
7561
|
}
|
|
6801
7562
|
function createBridge(config, client, sessions) {
|
|
7563
|
+
const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "");
|
|
6802
7564
|
const busyUsers = new Set;
|
|
6803
7565
|
const claimedContexts = new WeakSet;
|
|
7566
|
+
const drainReentries = new WeakSet;
|
|
7567
|
+
const activeIntents = new Map;
|
|
6804
7568
|
const msgQueue = new MessageQueue(QUEUE_MAX);
|
|
6805
7569
|
const draining = new Set;
|
|
6806
7570
|
const greeted = loadGreetedSet();
|
|
@@ -6877,7 +7641,8 @@ function createBridge(config, client, sessions) {
|
|
|
6877
7641
|
const STALL_FIRST_NUDGE_MS = 30 * 60 * 1000;
|
|
6878
7642
|
const STALL_NUDGE_INTERVAL_MS = 30 * 60 * 1000;
|
|
6879
7643
|
const STALL_NUDGE_MAX = 3;
|
|
6880
|
-
function startBackgroundWait(sessionId, ctx, baseline, trackId) {
|
|
7644
|
+
function startBackgroundWait(sessionId, ctx, baseline, trackId, promptId = "") {
|
|
7645
|
+
bgWaits.get(sessionId)?.cancel();
|
|
6881
7646
|
let cancelled = false;
|
|
6882
7647
|
let finished = false;
|
|
6883
7648
|
const startedAt = Date.now();
|
|
@@ -6892,9 +7657,26 @@ function createBridge(config, client, sessions) {
|
|
|
6892
7657
|
bgWaits.delete(sessionId);
|
|
6893
7658
|
mirror.scheduleUnlock(sessionId);
|
|
6894
7659
|
};
|
|
7660
|
+
function classifyNow(listJson) {
|
|
7661
|
+
const msgs = listJson?.data ?? [];
|
|
7662
|
+
const turn = turnStateOf(msgs, promptId, baseline);
|
|
7663
|
+
if (!turn.anchored)
|
|
7664
|
+
return { done: turn.hasIdle, text: collectReplyText(msgs, baseline) };
|
|
7665
|
+
return { done: turn.hasIdle, text: turn.text };
|
|
7666
|
+
}
|
|
6895
7667
|
async function finish(kind) {
|
|
6896
7668
|
if (cancelled || finished)
|
|
6897
7669
|
return;
|
|
7670
|
+
if (kind === "done" && promptId) {
|
|
7671
|
+
try {
|
|
7672
|
+
const probe = await client.session.messages({ path: { id: sessionId } });
|
|
7673
|
+
const turn = turnStateOf(probe?.data ?? [], promptId, baseline);
|
|
7674
|
+
if (turn.anchored && !turn.hasIdle) {
|
|
7675
|
+
console.log(`[bridge] 忽略他回合完成事件(本后台回合尚未结束)session=${sessionId}`);
|
|
7676
|
+
return;
|
|
7677
|
+
}
|
|
7678
|
+
} catch {}
|
|
7679
|
+
}
|
|
6898
7680
|
finished = true;
|
|
6899
7681
|
cleanup();
|
|
6900
7682
|
if (trackId)
|
|
@@ -6907,7 +7689,7 @@ function createBridge(config, client, sessions) {
|
|
|
6907
7689
|
await new Promise((r) => setTimeout(r, 2000));
|
|
6908
7690
|
try {
|
|
6909
7691
|
const listJson = await client.session.messages({ path: { id: sessionId } });
|
|
6910
|
-
const text =
|
|
7692
|
+
const { text } = classifyNow(listJson);
|
|
6911
7693
|
await safeDeliver(ctx, text ? `\uD83D\uDCE4 后台任务完成,结果如下:
|
|
6912
7694
|
|
|
6913
7695
|
${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用 /history 查看");
|
|
@@ -6922,6 +7704,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6922
7704
|
try {
|
|
6923
7705
|
const listJson = await client.session.messages({ path: { id: sessionId } });
|
|
6924
7706
|
const msgs = listJson?.data ?? [];
|
|
7707
|
+
const turn = turnStateOf(msgs, promptId, baseline);
|
|
6925
7708
|
let maxCreated = 0;
|
|
6926
7709
|
for (const m of msgs) {
|
|
6927
7710
|
const created = m.time?.created ?? 0;
|
|
@@ -6936,10 +7719,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
6936
7719
|
} else if (stallNudgeDecision(startedAt, lastProgressAt, nudges, now, STALL_FIRST_NUDGE_MS, STALL_NUDGE_INTERVAL_MS, STALL_NUDGE_MAX) === "nudge") {
|
|
6937
7720
|
nudges += 1;
|
|
6938
7721
|
lastProgressAt = now;
|
|
6939
|
-
|
|
6940
|
-
|
|
7722
|
+
const st = turnStats.get(sessionId);
|
|
7723
|
+
const lastAction = st?.lastTool && st?.lastAt ? `${st.lastTool}(${agoLabel(st.lastAt)})` : undefined;
|
|
7724
|
+
console.log(`[bridge] 后台任务状态通告 #${nudges} session=${sessionId} anchored=${turn.anchored}`);
|
|
7725
|
+
safeDeliver(ctx, stallNudgeText(Math.round((now - startedAt) / 60000), {
|
|
7726
|
+
anchored: turn.anchored,
|
|
7727
|
+
roundRunning: turn.anchored && !turn.hasIdle,
|
|
7728
|
+
idleMin: Math.round((now - lastProgressAt) / 60000),
|
|
7729
|
+
lastAction
|
|
7730
|
+
})).catch(() => {});
|
|
6941
7731
|
}
|
|
6942
|
-
if (
|
|
7732
|
+
if (turn.hasIdle) {
|
|
6943
7733
|
await finish("done");
|
|
6944
7734
|
}
|
|
6945
7735
|
} catch (error) {
|
|
@@ -7127,6 +7917,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7127
7917
|
purgeOldQQImages();
|
|
7128
7918
|
const handleMessage = async (ctx) => {
|
|
7129
7919
|
let claimedMsgId = "";
|
|
7920
|
+
const intentKey = intentKeyOf(ctx);
|
|
7130
7921
|
try {
|
|
7131
7922
|
if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
|
|
7132
7923
|
await sendReply(ctx, "你不在允许使用的名单里");
|
|
@@ -7167,15 +7958,28 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7167
7958
|
}
|
|
7168
7959
|
if (ctx.msgId) {
|
|
7169
7960
|
if (!claimedContexts.has(ctx)) {
|
|
7170
|
-
const
|
|
7171
|
-
if (
|
|
7961
|
+
const admitted = claimInflightDetailed({ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() }, { fingerprint: messageFingerprint(ctx.userId, intentKey) });
|
|
7962
|
+
if (admitted === "duplicate-msgid") {
|
|
7172
7963
|
console.log(`[bridge] 重复消息已跳过 msgId=${ctx.msgId}`);
|
|
7173
7964
|
return;
|
|
7174
7965
|
}
|
|
7966
|
+
if (admitted === "duplicate-intent") {
|
|
7967
|
+
console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`);
|
|
7968
|
+
await sendReply(ctx, "你的相同问题正在处理中,本次重发已忽略");
|
|
7969
|
+
return;
|
|
7970
|
+
}
|
|
7175
7971
|
claimedContexts.add(ctx);
|
|
7176
7972
|
}
|
|
7177
7973
|
claimedMsgId = ctx.msgId;
|
|
7178
7974
|
}
|
|
7975
|
+
if (busyUsers.has(ctx.userId) && !claimedContexts.has(ctx)) {
|
|
7976
|
+
const duplicateIntent = activeIntents.get(ctx.userId) === intentKey || msgQueue.hasIntent(ctx.userId, intentKey);
|
|
7977
|
+
if (duplicateIntent) {
|
|
7978
|
+
settleInflight(ctx.msgId);
|
|
7979
|
+
console.log(`[bridge] 相同意图已在执行/队列,跳过 msgId=${ctx.msgId}`);
|
|
7980
|
+
return;
|
|
7981
|
+
}
|
|
7982
|
+
}
|
|
7179
7983
|
if (busyUsers.has(ctx.userId)) {
|
|
7180
7984
|
if (ctx.attachments?.length && !ctx.preparedAttachments) {
|
|
7181
7985
|
ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
|
|
@@ -7191,13 +7995,18 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
|
|
|
7191
7995
|
发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
|
|
7192
7996
|
return;
|
|
7193
7997
|
}
|
|
7998
|
+
activeIntents.set(ctx.userId, intentKey);
|
|
7194
7999
|
busyUsers.add(ctx.userId);
|
|
8000
|
+
if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
|
|
8001
|
+
await sendReply(ctx, "✅ 已收到,正在处理,完成后自动回复你");
|
|
8002
|
+
}
|
|
7195
8003
|
if (ctx.type === "c2c" && ctx.msgId) {
|
|
7196
8004
|
getAccessToken(config.qq.appId, config.qq.clientSecret).then((token) => sendC2CInputNotify(token, ctx.userId, ctx.msgId, 60)).catch(() => {});
|
|
7197
8005
|
}
|
|
7198
8006
|
let sessionId = "";
|
|
7199
8007
|
let turnStart = 0;
|
|
7200
8008
|
let trackId = "";
|
|
8009
|
+
let promptId = "";
|
|
7201
8010
|
try {
|
|
7202
8011
|
const session = await sessions.getOrCreate(ctx.userId);
|
|
7203
8012
|
sessionId = session.sessionId;
|
|
@@ -7220,6 +8029,10 @@ ${promptBody}` : promptBody;
|
|
|
7220
8029
|
recordInflight({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() });
|
|
7221
8030
|
const replyText = await client.promptAndWait(sessionId, promptText, {
|
|
7222
8031
|
files: files.length ? files : undefined,
|
|
8032
|
+
onAccepted: (info) => {
|
|
8033
|
+
promptId = info.promptId;
|
|
8034
|
+
markInflightPromptId(trackId, info.promptId);
|
|
8035
|
+
},
|
|
7223
8036
|
onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
|
|
7224
8037
|
onPermissionReplied: (d) => {
|
|
7225
8038
|
safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`);
|
|
@@ -7247,7 +8060,7 @@ ${promptBody}` : promptBody;
|
|
|
7247
8060
|
} catch (error) {
|
|
7248
8061
|
if (sessionId && turnStart > 0 && error instanceof Error && error.message.includes("响应超时")) {
|
|
7249
8062
|
await safeDeliver(ctx, "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。");
|
|
7250
|
-
startBackgroundWait(sessionId, ctx, turnStart, trackId);
|
|
8063
|
+
startBackgroundWait(sessionId, ctx, turnStart, trackId, promptId);
|
|
7251
8064
|
} else {
|
|
7252
8065
|
const errText = toErrorMessage2(error);
|
|
7253
8066
|
const rescue = rescueText(classifyProviderError(errText), errText);
|
|
@@ -7260,12 +8073,16 @@ ${promptBody}` : promptBody;
|
|
|
7260
8073
|
if (sessionId && !bgWaits.has(sessionId))
|
|
7261
8074
|
mirror.scheduleUnlock(sessionId);
|
|
7262
8075
|
busyUsers.delete(ctx.userId);
|
|
8076
|
+
if (activeIntents.get(ctx.userId) === intentKey)
|
|
8077
|
+
activeIntents.delete(ctx.userId);
|
|
7263
8078
|
if (sessionId && !bgWaits.has(sessionId))
|
|
7264
8079
|
drainQueue(ctx.userId);
|
|
7265
8080
|
}
|
|
7266
8081
|
} catch (error) {
|
|
7267
8082
|
if (claimedMsgId)
|
|
7268
8083
|
settleInflight(claimedMsgId);
|
|
8084
|
+
if (activeIntents.get(ctx.userId) === intentKey)
|
|
8085
|
+
activeIntents.delete(ctx.userId);
|
|
7269
8086
|
console.error("[bridge] handleMessage failed:", error);
|
|
7270
8087
|
try {
|
|
7271
8088
|
await sendReply(ctx, `处理消息失败:${toErrorMessage2(error)}`);
|
|
@@ -7286,6 +8103,12 @@ ${promptBody}` : promptBody;
|
|
|
7286
8103
|
continue;
|
|
7287
8104
|
}
|
|
7288
8105
|
const ctx = { type: "c2c", userId: entry.userId, msgId: "", content: entry.text };
|
|
8106
|
+
if (!entry.sessionId) {
|
|
8107
|
+
settleInflight(entry.msgId);
|
|
8108
|
+
await deliver(ctx, `⚠️ 重启前队列里有一条消息未执行(「${entry.text.length > 50 ? `${entry.text.slice(0, 50)}…` : entry.text}」)。为避免重复执行不自动重派,需要的话请重发一次`);
|
|
8109
|
+
console.log(`[bridge] 启动对账:排队空账已通知销账 msgId=${entry.msgId}`);
|
|
8110
|
+
continue;
|
|
8111
|
+
}
|
|
7289
8112
|
try {
|
|
7290
8113
|
const listJson = { data: await fetchRecoveryMessages(client, entry.sessionId) };
|
|
7291
8114
|
const cls = classifyInflight(entry, listJson.data);
|
|
@@ -7297,7 +8120,7 @@ ${cls.answer}`);
|
|
|
7297
8120
|
console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`);
|
|
7298
8121
|
} else if (cls.kind === "running") {
|
|
7299
8122
|
mirror.beginTurn(entry.sessionId);
|
|
7300
|
-
startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId);
|
|
8123
|
+
startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId, entry.promptId ?? "");
|
|
7301
8124
|
console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`);
|
|
7302
8125
|
} else if (ageMs <= redispatchMaxAgeMs()) {
|
|
7303
8126
|
settleInflight(entry.msgId);
|
|
@@ -7323,6 +8146,7 @@ ${cls.answer}`);
|
|
|
7323
8146
|
draining.add(userId);
|
|
7324
8147
|
try {
|
|
7325
8148
|
await sendReply(job.ctx, `开始执行队列 #${job.id}`);
|
|
8149
|
+
drainReentries.add(job.ctx);
|
|
7326
8150
|
await handleMessage(job.ctx);
|
|
7327
8151
|
} catch (error) {
|
|
7328
8152
|
console.error("[bridge] 队列执行失败:", error);
|
|
@@ -7377,11 +8201,11 @@ function isAllowedUser(userId, allowedUsers) {
|
|
|
7377
8201
|
return false;
|
|
7378
8202
|
return allowedUsers.includes(userId);
|
|
7379
8203
|
}
|
|
7380
|
-
var WATCH_FILE =
|
|
8204
|
+
var WATCH_FILE = join12(homedir11(), ".openqq", "watch.json");
|
|
7381
8205
|
function loadWatchedMap(file = WATCH_FILE) {
|
|
7382
8206
|
try {
|
|
7383
|
-
if (
|
|
7384
|
-
const raw =
|
|
8207
|
+
if (existsSync10(file)) {
|
|
8208
|
+
const raw = readFileSync12(file, "utf-8");
|
|
7385
8209
|
const obj = JSON.parse(raw);
|
|
7386
8210
|
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
7387
8211
|
const out = {};
|
|
@@ -7396,16 +8220,16 @@ function loadWatchedMap(file = WATCH_FILE) {
|
|
|
7396
8220
|
}
|
|
7397
8221
|
function saveWatchedMap(m, file = WATCH_FILE) {
|
|
7398
8222
|
try {
|
|
7399
|
-
|
|
8223
|
+
writeFileSync12(file, JSON.stringify(Object.fromEntries(m), null, 2));
|
|
7400
8224
|
} catch (error) {
|
|
7401
8225
|
console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
|
|
7402
8226
|
}
|
|
7403
8227
|
}
|
|
7404
|
-
var GREETED_FILE =
|
|
8228
|
+
var GREETED_FILE = join12(homedir11(), ".openqq", "greeted.json");
|
|
7405
8229
|
function loadGreetedSet() {
|
|
7406
8230
|
try {
|
|
7407
|
-
if (
|
|
7408
|
-
const raw =
|
|
8231
|
+
if (existsSync10(GREETED_FILE)) {
|
|
8232
|
+
const raw = readFileSync12(GREETED_FILE, "utf-8");
|
|
7409
8233
|
const arr = JSON.parse(raw);
|
|
7410
8234
|
if (Array.isArray(arr)) {
|
|
7411
8235
|
return new Set(arr.filter((x) => typeof x === "string"));
|
|
@@ -7416,8 +8240,8 @@ function loadGreetedSet() {
|
|
|
7416
8240
|
}
|
|
7417
8241
|
function saveGreetedSet(set) {
|
|
7418
8242
|
try {
|
|
7419
|
-
|
|
7420
|
-
|
|
8243
|
+
mkdirSync10(join12(homedir11(), ".openqq"), { recursive: true });
|
|
8244
|
+
writeFileSync12(GREETED_FILE, JSON.stringify([...set]));
|
|
7421
8245
|
} catch (error) {
|
|
7422
8246
|
console.error("[bridge] 保存 greeted 失败:", error);
|
|
7423
8247
|
}
|
|
@@ -7468,35 +8292,36 @@ function toErrorMessage2(error) {
|
|
|
7468
8292
|
}
|
|
7469
8293
|
|
|
7470
8294
|
// src/core/instance-lock.ts
|
|
7471
|
-
import { openSync as
|
|
7472
|
-
import { join as
|
|
7473
|
-
import { homedir as
|
|
8295
|
+
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";
|
|
8296
|
+
import { join as join13 } from "path";
|
|
8297
|
+
import { homedir as homedir12 } from "os";
|
|
7474
8298
|
var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
|
|
7475
|
-
var
|
|
8299
|
+
var LOCK_STALE_MS2 = 30000;
|
|
7476
8300
|
var LOCK_UPDATE_MS = 1e4;
|
|
7477
8301
|
var LOCK_RETRY_MS = 5000;
|
|
8302
|
+
var LOCK_SELF_CHECK_MS = 60000;
|
|
7478
8303
|
function lockPathOf(appId) {
|
|
7479
|
-
return
|
|
8304
|
+
return join13(homedir12(), ".openqq", `openqq-${appId}.lock`);
|
|
7480
8305
|
}
|
|
7481
8306
|
function touch(path) {
|
|
7482
8307
|
const now = new Date;
|
|
7483
8308
|
utimesSync(path, now, now);
|
|
7484
8309
|
}
|
|
7485
|
-
function acquireInstanceLockAt(path, staleMs =
|
|
8310
|
+
function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
|
|
7486
8311
|
try {
|
|
7487
|
-
|
|
7488
|
-
const fd =
|
|
7489
|
-
|
|
7490
|
-
|
|
8312
|
+
mkdirSync11(join13(path, ".."), { recursive: true });
|
|
8313
|
+
const fd = openSync4(path, "wx");
|
|
8314
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
8315
|
+
closeSync4(fd);
|
|
7491
8316
|
} catch {
|
|
7492
8317
|
try {
|
|
7493
|
-
const age = Date.now() -
|
|
8318
|
+
const age = Date.now() - statSync6(path).mtimeMs;
|
|
7494
8319
|
if (age <= staleMs)
|
|
7495
8320
|
return null;
|
|
7496
|
-
|
|
7497
|
-
const fd =
|
|
7498
|
-
|
|
7499
|
-
|
|
8321
|
+
unlinkSync6(path);
|
|
8322
|
+
const fd = openSync4(path, "wx");
|
|
8323
|
+
writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
|
|
8324
|
+
closeSync4(fd);
|
|
7500
8325
|
console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
|
|
7501
8326
|
} catch {
|
|
7502
8327
|
return null;
|
|
@@ -7508,6 +8333,22 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
|
|
|
7508
8333
|
} catch {}
|
|
7509
8334
|
}, LOCK_UPDATE_MS);
|
|
7510
8335
|
heartbeat.unref?.();
|
|
8336
|
+
const selfCheck = setInterval(() => {
|
|
8337
|
+
try {
|
|
8338
|
+
const holder = JSON.parse(readFileSync13(path, "utf-8")).pid;
|
|
8339
|
+
if (holder === process.pid)
|
|
8340
|
+
return;
|
|
8341
|
+
try {
|
|
8342
|
+
process.kill(holder, 0);
|
|
8343
|
+
console.error(`[instance-lock] 自检:锁已被 pid=${holder} 持有且进程存活,本实例为残留 believer,自杀退出`);
|
|
8344
|
+
process.exit(1);
|
|
8345
|
+
} catch {}
|
|
8346
|
+
} catch {
|
|
8347
|
+
console.error("[instance-lock] 自检:锁文件已消失(被接管或强抢流程删除),本实例退出");
|
|
8348
|
+
process.exit(1);
|
|
8349
|
+
}
|
|
8350
|
+
}, LOCK_SELF_CHECK_MS);
|
|
8351
|
+
selfCheck.unref?.();
|
|
7511
8352
|
let released = false;
|
|
7512
8353
|
return {
|
|
7513
8354
|
release: () => {
|
|
@@ -7515,8 +8356,9 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
|
|
|
7515
8356
|
return;
|
|
7516
8357
|
released = true;
|
|
7517
8358
|
clearInterval(heartbeat);
|
|
8359
|
+
clearInterval(selfCheck);
|
|
7518
8360
|
try {
|
|
7519
|
-
|
|
8361
|
+
unlinkSync6(path);
|
|
7520
8362
|
} catch {}
|
|
7521
8363
|
}
|
|
7522
8364
|
};
|
|
@@ -7618,11 +8460,11 @@ async function main() {
|
|
|
7618
8460
|
});
|
|
7619
8461
|
console.log("[index] OpenCode QQ Bot 已启动");
|
|
7620
8462
|
bridge.recoverInflightRounds();
|
|
7621
|
-
const heartbeatFile =
|
|
8463
|
+
const heartbeatFile = join15(homedir13(), ".openqq", "heartbeat");
|
|
7622
8464
|
const touchHeartbeat = () => {
|
|
7623
8465
|
try {
|
|
7624
|
-
|
|
7625
|
-
|
|
8466
|
+
mkdirSync13(join15(homedir13(), ".openqq"), { recursive: true });
|
|
8467
|
+
writeFileSync14(heartbeatFile, String(Date.now()));
|
|
7626
8468
|
} catch (error) {
|
|
7627
8469
|
console.error("[index] 心跳写入失败:", error);
|
|
7628
8470
|
}
|