@linjz/opencode-qqbot 0.3.11 → 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.
Files changed (45) hide show
  1. package/bin/openqq-setup.mjs +50 -50
  2. package/bin/openqq.js +47 -47
  3. package/dist/opencode-qqbot-plugin.js +3 -3
  4. package/dist/openqq-bot.js +1056 -194
  5. package/package.json +2 -2
  6. package/src/_FOLDER.md +19 -19
  7. package/src/bridge.ts +154 -18
  8. package/src/commands.ts +554 -554
  9. package/src/config.ts +121 -121
  10. package/src/core/bot-launcher.ts +146 -146
  11. package/src/core/card-approval.ts +146 -146
  12. package/src/core/context-buffer.ts +78 -78
  13. package/src/core/delivery.ts +105 -13
  14. package/src/core/discovery.ts +151 -151
  15. package/src/core/error-rescue.ts +33 -33
  16. package/src/core/file-log.ts +45 -45
  17. package/src/core/form-bridge.ts +388 -72
  18. package/src/core/form-journal.ts +214 -0
  19. package/src/core/gateway-state.ts +68 -0
  20. package/src/core/inbound-dedupe.ts +43 -0
  21. package/src/core/inflight-journal.ts +148 -21
  22. package/src/core/instance-lock.ts +28 -1
  23. package/src/core/linkwatch.ts +195 -195
  24. package/src/core/message-queue.ts +11 -0
  25. package/src/core/mirror.ts +182 -182
  26. package/src/core/outbox.ts +522 -0
  27. package/src/core/permission.ts +301 -301
  28. package/src/core/reply-limiter.ts +106 -106
  29. package/src/core/send-media.ts +90 -90
  30. package/src/core/util.ts +8 -8
  31. package/src/index.ts +162 -162
  32. package/src/opencode/_FOLDER.md +11 -11
  33. package/src/opencode/client.ts +98 -10
  34. package/src/opencode/eventstream.ts +138 -138
  35. package/src/opencode/history.ts +143 -143
  36. package/src/opencode/mirror.ts +85 -85
  37. package/src/opencode/sessions.ts +158 -158
  38. package/src/plugin-entry.ts +112 -112
  39. package/src/qq/_FOLDER.md +13 -13
  40. package/src/qq/api.ts +539 -539
  41. package/src/qq/gateway.ts +69 -20
  42. package/src/qq/media.ts +219 -219
  43. package/src/qq/sender.ts +300 -300
  44. package/src/qq/types.ts +154 -154
  45. package/tsconfig.json +24 -24
@@ -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 existsSync9, mkdirSync as mkdirSync10, renameSync as renameSync3, statSync as statSync5 } from "fs";
2943
- import { join as join12 } from "path";
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
- mkdirSync10(join12(logPath, ".."), { recursive: true });
2946
+ mkdirSync12(join14(logPath, ".."), { recursive: true });
2947
2947
  } catch {}
2948
2948
  const write = (level, args) => {
2949
2949
  try {
2950
- if (existsSync9(logPath) && statSync5(logPath).size > ROTATE_BYTES) {
2951
- renameSync3(logPath, `${logPath}.1`);
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 mkdirSync11, writeFileSync as writeFileSync12 } from "fs";
3091
- import { join as join13 } from "path";
3092
- import { homedir as homedir11 } from "os";
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));
@@ -3154,7 +3204,13 @@ function createClient(baseUrl) {
3154
3204
  return json(await req(`/session/${opts.path.id}/interrupt`, { method: "POST", body: "{}" }));
3155
3205
  },
3156
3206
  async messages(opts) {
3157
- return json(await req(`/session/${opts.path.id}/message`));
3207
+ const query = new URLSearchParams;
3208
+ if (opts.query?.limit !== undefined)
3209
+ query.set("limit", String(opts.query.limit));
3210
+ if (opts.query?.cursor)
3211
+ query.set("cursor", opts.query.cursor);
3212
+ const suffix = query.size > 0 ? `?${query.toString()}` : "";
3213
+ return json(await req(`/session/${opts.path.id}/message${suffix}`));
3158
3214
  },
3159
3215
  async prompt(opts) {
3160
3216
  return json(await req(`/session/${opts.path.id}/prompt`, { method: "POST", body: JSON.stringify(opts.body) }));
@@ -3186,6 +3242,9 @@ function createClient(baseUrl) {
3186
3242
  method: "POST",
3187
3243
  body: JSON.stringify(opts.body)
3188
3244
  }));
3245
+ },
3246
+ async cancel(opts) {
3247
+ return json(await req(`/session/${opts.path.sessionID}/form/${opts.path.formID}`, { method: "DELETE" }));
3189
3248
  }
3190
3249
  },
3191
3250
  app: {
@@ -3234,6 +3293,10 @@ function createClient(baseUrl) {
3234
3293
  }
3235
3294
  const promptJson = await json(await req(`/session/${sessionId}/prompt`, { method: "POST", body: JSON.stringify(body) }));
3236
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}`);
3237
3300
  const deadline = Date.now() + RESPONSE_TIMEOUT_MS;
3238
3301
  let permissionWaitMs = 0;
3239
3302
  const handledPermissions = new Set;
@@ -3278,10 +3341,9 @@ function createClient(baseUrl) {
3278
3341
  }
3279
3342
  const listJson = await json(await req(`/session/${sessionId}/message`));
3280
3343
  const msgs = listJson?.data ?? [];
3281
- const idle = msgs.find((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline);
3282
- if (idle) {
3283
- const reply = collectReplyText(msgs, baseline);
3284
- return reply || "(AI 未返回内容)";
3344
+ const turn = turnStateOf(msgs, promptId, baseline);
3345
+ if (turn.hasIdle) {
3346
+ return turn.text || "(AI 未返回内容)";
3285
3347
  }
3286
3348
  }
3287
3349
  throw new Error(`AI 响应超时(${TURN_TIMEOUT_MINUTES} 分钟)`);
@@ -3982,6 +4044,49 @@ var import_websocket = __toESM(require_websocket(), 1);
3982
4044
  var import_websocket_server = __toESM(require_websocket_server(), 1);
3983
4045
  var wrapper_default = import_websocket.default;
3984
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
+
3985
4090
  // src/qq/gateway.ts
3986
4091
  var GROUP_AND_C2C_EVENT_INTENT = 1 << 25;
3987
4092
  var INTERACTION_INTENT = 1 << 26;
@@ -3993,7 +4098,7 @@ var RATE_LIMITED_RECONNECT_DELAY_MS = 60000;
3993
4098
  var RESUME_RESET_CLOSE_CODES = new Set([4006, 4007, 4009]);
3994
4099
  var FATAL_CLOSE_CODES = new Set([4914, 4915]);
3995
4100
  function createInitialState() {
3996
- return {
4101
+ const state = {
3997
4102
  ws: null,
3998
4103
  stopped: false,
3999
4104
  connecting: false,
@@ -4004,21 +4109,28 @@ function createInitialState() {
4004
4109
  sessionId: null,
4005
4110
  seq: null,
4006
4111
  heartbeatAcked: true,
4007
- seenMsgIds: new Set
4112
+ activeMsgIds: new Set
4008
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;
4009
4122
  }
4010
- var SEEN_MSGIDS_MAX = 500;
4011
- function markSeenAndFilter(seen, msgId) {
4012
- if (seen.has(msgId))
4123
+ function tryClaimActive(active, msgId) {
4124
+ if (active.has(msgId))
4013
4125
  return false;
4014
- if (seen.size >= SEEN_MSGIDS_MAX) {
4015
- const first = seen.values().next().value;
4016
- if (first !== undefined)
4017
- seen.delete(first);
4018
- }
4019
- seen.add(msgId);
4126
+ if (active.size >= 1000)
4127
+ return true;
4128
+ active.add(msgId);
4020
4129
  return true;
4021
4130
  }
4131
+ function releaseActive(active, msgId) {
4132
+ active.delete(msgId);
4133
+ }
4022
4134
  function cleanupSocket(state) {
4023
4135
  if (state.heartbeatTimer) {
4024
4136
  clearInterval(state.heartbeatTimer);
@@ -4067,6 +4179,7 @@ function startHeartbeat(state, intervalMs) {
4067
4179
  function resetResumeState(state) {
4068
4180
  state.sessionId = null;
4069
4181
  state.seq = null;
4182
+ clearGatewayState();
4070
4183
  }
4071
4184
  function normalizeMessageContent(content) {
4072
4185
  return content.replace(/\r\n/g, `
@@ -4148,6 +4261,8 @@ async function handleDispatchEvent(payload, options, state) {
4148
4261
  case "READY": {
4149
4262
  const readyData = payload.d;
4150
4263
  state.sessionId = readyData.session_id;
4264
+ if (state.seq !== null)
4265
+ saveGatewayState(state.sessionId, state.seq);
4151
4266
  if (state.reconnectAttempt > 0) {
4152
4267
  console.log(`[gateway] 重连已就绪(READY,第 ${state.reconnectAttempt} 次尝试)session=${state.sessionId}`);
4153
4268
  }
@@ -4157,45 +4272,59 @@ async function handleDispatchEvent(payload, options, state) {
4157
4272
  }
4158
4273
  case "RESUMED": {
4159
4274
  console.log("[gateway] 会话已恢复(RESUMED,断线期间事件已回补)");
4275
+ if (state.sessionId && state.seq !== null)
4276
+ saveGatewayState(state.sessionId, state.seq);
4160
4277
  state.reconnectAttempt = 0;
4161
4278
  return;
4162
4279
  }
4163
4280
  case "C2C_MESSAGE_CREATE": {
4164
4281
  const event = payload.d;
4165
- if (!markSeenAndFilter(state.seenMsgIds, event.id))
4282
+ if (!tryClaimActive(state.activeMsgIds, event.id))
4166
4283
  return;
4167
4284
  const message = toC2CMessageContext(event);
4168
4285
  if (message.attachments?.length) {
4169
4286
  console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)));
4170
4287
  }
4171
4288
  if (!message.content && !message.attachments?.length) {
4289
+ releaseActive(state.activeMsgIds, event.id);
4172
4290
  return;
4173
4291
  }
4174
- await options.onMessage(message);
4292
+ try {
4293
+ await options.onMessage(message);
4294
+ } finally {
4295
+ releaseActive(state.activeMsgIds, event.id);
4296
+ }
4175
4297
  return;
4176
4298
  }
4177
4299
  case "GROUP_AT_MESSAGE_CREATE": {
4178
4300
  const event = payload.d;
4179
- if (!markSeenAndFilter(state.seenMsgIds, event.id))
4301
+ if (!tryClaimActive(state.activeMsgIds, event.id))
4180
4302
  return;
4181
4303
  const message = toGroupMessageContext(event);
4182
4304
  if (message.attachments?.length) {
4183
4305
  console.log("[gateway] 附件载荷:", JSON.stringify(briefAttachments(message.attachments)));
4184
4306
  }
4185
4307
  if (!message.content && !message.attachments?.length) {
4308
+ releaseActive(state.activeMsgIds, event.id);
4186
4309
  return;
4187
4310
  }
4188
- await options.onMessage(message);
4311
+ try {
4312
+ await options.onMessage(message);
4313
+ } finally {
4314
+ releaseActive(state.activeMsgIds, event.id);
4315
+ }
4189
4316
  return;
4190
4317
  }
4191
4318
  case "INTERACTION_CREATE": {
4192
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
+ });
4193
4323
  if (state.accessToken && interaction?.id) {
4194
4324
  acknowledgeInteraction(state.accessToken, interaction.id).catch((error) => {
4195
4325
  console.error("[qq-gateway] 互动响应失败:", error instanceof Error ? error.message : error);
4196
4326
  });
4197
4327
  }
4198
- await options.onInteraction?.(interaction);
4199
4328
  return;
4200
4329
  }
4201
4330
  default:
@@ -4204,7 +4333,14 @@ async function handleDispatchEvent(payload, options, state) {
4204
4333
  }
4205
4334
  async function handlePayload(payload, ws, options, state, connect) {
4206
4335
  if (typeof payload.s === "number") {
4336
+ const prevSeq = state.seq;
4207
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
+ }
4208
4344
  }
4209
4345
  switch (payload.op) {
4210
4346
  case 10: {
@@ -4329,13 +4465,13 @@ async function startGateway(options) {
4329
4465
  }
4330
4466
 
4331
4467
  // src/bridge.ts
4332
- import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync8, writeFileSync as writeFileSync10 } from "fs";
4333
- import { join as join10 } from "path";
4334
- import { homedir as homedir9 } from "os";
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";
4335
4471
 
4336
4472
  // src/qq/media.ts
4337
- import { mkdirSync as mkdirSync4, readdirSync, statSync, unlinkSync, writeFileSync as writeFileSync5, readFileSync as readFileSync4 } from "node:fs";
4338
- import { join as join5 } from "node:path";
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";
4339
4475
  import { tmpdir } from "node:os";
4340
4476
  function extForImageMime(mime) {
4341
4477
  const m = (mime || "").toLowerCase().split(";")[0].trim();
@@ -4360,7 +4496,7 @@ function isAllowedDownloadHost(url) {
4360
4496
  }
4361
4497
  }
4362
4498
  function imageDir() {
4363
- return join5(tmpdir(), "opencode", "qq-images");
4499
+ return join6(tmpdir(), "opencode", "qq-images");
4364
4500
  }
4365
4501
  async function fetchWithTimeout(url, ms, auth) {
4366
4502
  const ctrl = new AbortController;
@@ -4386,7 +4522,7 @@ async function downloadQQAttachment(att, getAuth) {
4386
4522
  return { failed: "下载域不在白名单" };
4387
4523
  try {
4388
4524
  const dir = imageDir();
4389
- mkdirSync4(dir, { recursive: true });
4525
+ mkdirSync5(dir, { recursive: true });
4390
4526
  const name = `qq-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
4391
4527
  let res = await fetchWithTimeout(att.url, 15000);
4392
4528
  if ((res.status === 401 || res.status === 403) && getAuth) {
@@ -4420,8 +4556,8 @@ async function downloadQQAttachment(att, getAuth) {
4420
4556
  }
4421
4557
  if (total === 0)
4422
4558
  return { failed: "空响应" };
4423
- const full = join5(dir, name);
4424
- writeFileSync5(full, Buffer.concat(chunks));
4559
+ const full = join6(dir, name);
4560
+ writeFileSync6(full, Buffer.concat(chunks));
4425
4561
  return { path: full, name };
4426
4562
  } catch (e) {
4427
4563
  console.log("[media] 下载失败:", att.url, e instanceof Error ? e.message : e);
@@ -4458,7 +4594,7 @@ function tryImageDataUrl(path, maxBytes) {
4458
4594
  const st = statSync(path);
4459
4595
  if (st.size > maxBytes)
4460
4596
  return null;
4461
- const b = readFileSync4(path);
4597
+ const b = readFileSync5(path);
4462
4598
  return `data:image/png;base64,${b.toString("base64")}`;
4463
4599
  } catch {
4464
4600
  return null;
@@ -4485,10 +4621,10 @@ function purgeOldQQImages(maxAgeMs = 7 * 24 * 60 * 60 * 1000) {
4485
4621
  const dir = imageDir();
4486
4622
  const now = Date.now();
4487
4623
  for (const f of readdirSync(dir)) {
4488
- const full = join5(dir, f);
4624
+ const full = join6(dir, f);
4489
4625
  try {
4490
4626
  if (now - statSync(full).mtimeMs > maxAgeMs)
4491
- unlinkSync(full);
4627
+ unlinkSync2(full);
4492
4628
  } catch {}
4493
4629
  }
4494
4630
  } catch {}
@@ -4726,7 +4862,7 @@ function clip(value, max) {
4726
4862
  }
4727
4863
 
4728
4864
  // src/core/send-media.ts
4729
- import { readFileSync as readFileSync5, statSync as statSync2 } from "node:fs";
4865
+ import { readFileSync as readFileSync6, statSync as statSync2 } from "node:fs";
4730
4866
  import { resolve, extname, basename, sep } from "node:path";
4731
4867
  var MAX_SEND_BYTES = 20 * 1024 * 1024;
4732
4868
  function allowedSendRoots(extraEnv = process.env.QQ_SEND_EXTRA_ROOTS) {
@@ -4791,7 +4927,7 @@ async function sendLocalFile(ctx, filePath, deps) {
4791
4927
  const name = basename(trimmed);
4792
4928
  const uploaded = await uploadQQMedia(token, ctx, {
4793
4929
  fileType,
4794
- fileData: readFileSync5(trimmed).toString("base64"),
4930
+ fileData: readFileSync6(trimmed).toString("base64"),
4795
4931
  fileName: fileType === MediaFileType.FILE ? name : undefined
4796
4932
  });
4797
4933
  await sendQQMediaMessage(token, ctx, uploaded.file_info, name);
@@ -5213,9 +5349,9 @@ function toErrorMessage(error) {
5213
5349
  }
5214
5350
 
5215
5351
  // src/core/mirror.ts
5216
- import { existsSync as existsSync4, readFileSync as readFileSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "fs";
5217
- import { join as join6 } from "path";
5218
- import { homedir as homedir5 } from "os";
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";
5219
5355
 
5220
5356
  // src/opencode/mirror.ts
5221
5357
  var USER_CLIP = 160;
@@ -5288,11 +5424,11 @@ function clip2(value, max) {
5288
5424
  }
5289
5425
 
5290
5426
  // src/core/mirror.ts
5291
- var MIRROR_SETTINGS_FILE = join6(homedir5(), ".openqq", "settings.json");
5427
+ var MIRROR_SETTINGS_FILE = join7(homedir6(), ".openqq", "settings.json");
5292
5428
  function loadMirrorEnabled() {
5293
5429
  try {
5294
- if (existsSync4(MIRROR_SETTINGS_FILE)) {
5295
- const raw = readFileSync6(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5430
+ if (existsSync5(MIRROR_SETTINGS_FILE)) {
5431
+ const raw = readFileSync7(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5296
5432
  const parsed = JSON.parse(raw);
5297
5433
  if (typeof parsed?.mirror === "boolean")
5298
5434
  return parsed.mirror;
@@ -5302,18 +5438,18 @@ function loadMirrorEnabled() {
5302
5438
  }
5303
5439
  function saveMirrorEnabled(enabled) {
5304
5440
  try {
5305
- mkdirSync5(join6(homedir5(), ".openqq"), { recursive: true });
5441
+ mkdirSync6(join7(homedir6(), ".openqq"), { recursive: true });
5306
5442
  let existing = {};
5307
- if (existsSync4(MIRROR_SETTINGS_FILE)) {
5443
+ if (existsSync5(MIRROR_SETTINGS_FILE)) {
5308
5444
  try {
5309
- const raw = readFileSync6(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5445
+ const raw = readFileSync7(MIRROR_SETTINGS_FILE, "utf-8").replace(/^\uFEFF/, "");
5310
5446
  const parsed = JSON.parse(raw);
5311
5447
  if (parsed && typeof parsed === "object")
5312
5448
  existing = parsed;
5313
5449
  } catch {}
5314
5450
  }
5315
5451
  existing.mirror = enabled;
5316
- writeFileSync6(MIRROR_SETTINGS_FILE, JSON.stringify(existing, null, 2), "utf-8");
5452
+ writeFileSync7(MIRROR_SETTINGS_FILE, JSON.stringify(existing, null, 2), "utf-8");
5317
5453
  } catch (error) {
5318
5454
  console.error("[mirror] 保存设置失败:", error);
5319
5455
  }
@@ -5420,6 +5556,11 @@ function createMirror(deps) {
5420
5556
 
5421
5557
  // src/core/message-queue.ts
5422
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
+ }
5423
5564
  function previewText(text, max = PREVIEW_MAX) {
5424
5565
  const flat = text.replace(/\s+/g, " ").trim();
5425
5566
  return flat.length > max ? `${flat.slice(0, max)}…` : flat || "(空消息)";
@@ -5450,6 +5591,9 @@ class MessageQueue {
5450
5591
  this.jobs.set(userId, list);
5451
5592
  return { job, ahead: list.length - 1 };
5452
5593
  }
5594
+ hasIntent(userId, key) {
5595
+ return (this.jobs.get(userId) ?? []).some((job) => intentKeyOf(job.ctx) === key);
5596
+ }
5453
5597
  shift(userId) {
5454
5598
  const list = this.jobs.get(userId);
5455
5599
  const job = list?.shift();
@@ -5509,9 +5653,9 @@ function rescueText(kind, rawMessage) {
5509
5653
  }
5510
5654
 
5511
5655
  // src/core/permission.ts
5512
- import { existsSync as existsSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync7 } from "fs";
5513
- import { join as join7 } from "path";
5514
- import { homedir as homedir6 } from "os";
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";
5515
5659
 
5516
5660
  // src/core/util.ts
5517
5661
  function truncate(value, max) {
@@ -5526,11 +5670,11 @@ var DECISION_LABELS = {
5526
5670
  always: "总是允许(已存入项目白名单)",
5527
5671
  reject: "拒绝"
5528
5672
  };
5529
- var PENDING_PERM_FILE = join7(homedir6(), ".openqq", "pending-permissions.json");
5673
+ var PENDING_PERM_FILE = join8(homedir7(), ".openqq", "pending-permissions.json");
5530
5674
  function loadPendingPermMap() {
5531
5675
  try {
5532
- if (existsSync5(PENDING_PERM_FILE)) {
5533
- const raw = readFileSync7(PENDING_PERM_FILE, "utf-8");
5676
+ if (existsSync6(PENDING_PERM_FILE)) {
5677
+ const raw = readFileSync8(PENDING_PERM_FILE, "utf-8");
5534
5678
  const obj = JSON.parse(raw);
5535
5679
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
5536
5680
  const out = {};
@@ -5553,7 +5697,7 @@ function savePendingPermMap(m) {
5553
5697
  continue;
5554
5698
  out[uid] = { request: e.request, mainSessionId: e.mainSessionId, createdAt: e.createdAt, ctx: e.ctx };
5555
5699
  }
5556
- writeFileSync7(PENDING_PERM_FILE, JSON.stringify(out));
5700
+ writeFileSync8(PENDING_PERM_FILE, JSON.stringify(out));
5557
5701
  } catch (error) {
5558
5702
  console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error);
5559
5703
  }
@@ -5719,10 +5863,10 @@ function formatPermissionPrompt(request, mainSessionId) {
5719
5863
  }
5720
5864
 
5721
5865
  // src/core/delivery.ts
5722
- import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8, mkdirSync as mkdirSync6, renameSync } from "fs";
5723
- import { join as join8 } from "path";
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";
5724
5868
  import { createHash } from "node:crypto";
5725
- import { homedir as homedir7 } from "os";
5869
+ import { homedir as homedir8 } from "os";
5726
5870
 
5727
5871
  // src/qq/sender.ts
5728
5872
  var DEFAULT_MAX_LENGTH = 3000;
@@ -6061,11 +6205,11 @@ function extractEmbeddedQuote(event) {
6061
6205
  }
6062
6206
 
6063
6207
  // src/core/delivery.ts
6064
- var QUOTA_FILE = join8(homedir7(), ".openqq", "quota.json");
6208
+ var QUOTA_FILE = join9(homedir8(), ".openqq", "quota.json");
6065
6209
  function loadQuotaMap() {
6066
6210
  try {
6067
- if (existsSync6(QUOTA_FILE)) {
6068
- const raw = readFileSync8(QUOTA_FILE, "utf-8");
6211
+ if (existsSync7(QUOTA_FILE)) {
6212
+ const raw = readFileSync9(QUOTA_FILE, "utf-8");
6069
6213
  const obj = JSON.parse(raw);
6070
6214
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
6071
6215
  const out = {};
@@ -6083,27 +6227,51 @@ function loadQuotaMap() {
6083
6227
  }
6084
6228
  function saveQuotaMap(m) {
6085
6229
  try {
6086
- writeFileSync8(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)));
6230
+ writeFileSync9(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)));
6087
6231
  } catch (error) {
6088
6232
  console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error);
6089
6233
  }
6090
6234
  }
6091
6235
  var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
6092
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
+ }
6093
6261
  var DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000;
6094
- var DELIVERY_DEDUPE_FILE = process.env.QQ_DELIVERY_DEDUPE_FILE || join8(homedir7(), ".openqq", "delivery-dedupe.json");
6262
+ var DELIVERY_DEDUPE_FILE = process.env.QQ_DELIVERY_DEDUPE_FILE || join9(homedir8(), ".openqq", "delivery-dedupe.json");
6095
6263
  function deliveryAttemptKey(userId, text) {
6096
6264
  return `${userId}:${createHash("sha256").update(text).digest("hex")}`;
6097
6265
  }
6098
- function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TTL_MS) {
6099
- return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs;
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;
6100
6268
  }
6101
6269
  function loadDeliveryAttempts() {
6102
6270
  const out = new Map;
6103
6271
  try {
6104
- if (!existsSync6(DELIVERY_DEDUPE_FILE))
6272
+ if (!existsSync7(DELIVERY_DEDUPE_FILE))
6105
6273
  return out;
6106
- const raw = JSON.parse(readFileSync8(DELIVERY_DEDUPE_FILE, "utf-8"));
6274
+ const raw = JSON.parse(readFileSync9(DELIVERY_DEDUPE_FILE, "utf-8"));
6107
6275
  const now = Date.now();
6108
6276
  for (const entry of raw) {
6109
6277
  if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
@@ -6115,10 +6283,74 @@ function loadDeliveryAttempts() {
6115
6283
  }
6116
6284
  function saveDeliveryAttempts(entries) {
6117
6285
  const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
6118
- mkdirSync6(join8(DELIVERY_DEDUPE_FILE, ".."), { recursive: true });
6119
- const tmp = `${DELIVERY_DEDUPE_FILE}.tmp`;
6120
- writeFileSync8(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
6121
- renameSync(tmp, DELIVERY_DEDUPE_FILE);
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
+ });
6122
6354
  }
6123
6355
  function selectRideMsgId(last, ctx, now, windowMs) {
6124
6356
  if (!last?.msgId)
@@ -6146,7 +6378,6 @@ function createDelivery(config, lastCtx) {
6146
6378
  })();
6147
6379
  const pushQueues = new Map;
6148
6380
  const undelivered = new Set;
6149
- const recentDeliveries = loadDeliveryAttempts();
6150
6381
  const activeQuota = new Map;
6151
6382
  const passiveLimiter = new ReplyLimiter;
6152
6383
  for (const [uid, q] of Object.entries(loadQuotaMap()))
@@ -6189,20 +6420,17 @@ function createDelivery(config, lastCtx) {
6189
6420
  }
6190
6421
  async function deliver(ctx, text) {
6191
6422
  const now = Date.now();
6192
- const attemptKey = deliveryAttemptKey(ctx.userId, text);
6193
- if (shouldSuppressDuplicate(recentDeliveries.get(attemptKey), attemptKey, now)) {
6423
+ const attemptKey = reserveDeliveryAttempt(ctx.userId, text, now);
6424
+ if (!attemptKey) {
6194
6425
  console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`);
6195
6426
  return;
6196
6427
  }
6197
- recentDeliveries.set(attemptKey, { text: attemptKey, at: now });
6198
6428
  const hadNotice = undelivered.delete(ctx.userId);
6199
- const body = hadNotice ? UNDELIVERED_NOTICE + text : text;
6429
+ const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text);
6200
6430
  try {
6201
6431
  await deliverCore(ctx, body);
6202
- saveDeliveryAttempts(recentDeliveries);
6203
6432
  } catch (error) {
6204
- if (recentDeliveries.get(attemptKey)?.at === now)
6205
- recentDeliveries.delete(attemptKey);
6433
+ releaseDeliveryAttempt(ctx.userId, text, now);
6206
6434
  if (hadNotice)
6207
6435
  undelivered.add(ctx.userId);
6208
6436
  throw error;
@@ -6378,11 +6606,183 @@ function handleApprovalInteraction(event, gate) {
6378
6606
  return true;
6379
6607
  }
6380
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
+
6381
6780
  // src/core/form-bridge.ts
6382
6781
  var FORM_PROMPT_TTL_MS = 30 * 60 * 1000;
6383
6782
  var LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
6384
6783
  var BUTTON_LABEL_MAX2 = 10;
6385
6784
  var BUTTONS_PER_ROW = 2;
6785
+ var DEFAULT_DRAIN_TIMEOUT_MS = 5000;
6386
6786
  function primaryField(form) {
6387
6787
  return form.fields.find((f) => !f.hidden);
6388
6788
  }
@@ -6491,7 +6891,8 @@ function decodeFormButton(raw) {
6491
6891
  try {
6492
6892
  const parsed = JSON.parse(raw);
6493
6893
  if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
6494
- return parsed;
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 } : {} };
6495
6896
  }
6496
6897
  } catch {}
6497
6898
  return;
@@ -6527,66 +6928,279 @@ function buildFormKeyboard(form, ownerOpenid) {
6527
6928
  }
6528
6929
  function createFormBridge(deps) {
6529
6930
  const pending = new Map;
6530
- function clear(userId) {
6531
- const entry = pending.get(userId);
6532
- if (!entry)
6533
- return;
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;
6534
6975
  if (entry.timer)
6535
6976
  clearTimeout(entry.timer);
6977
+ entry.timer = null;
6536
6978
  pending.delete(userId);
6537
- return entry;
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;
6538
6985
  }
6539
- function submit(userId, form, ctx, answer, display, silent = false) {
6540
- clear(userId);
6541
- (async () => {
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 () => {
6542
7006
  try {
6543
- await deps.client.form.reply({ path: { sessionID: form.sessionID, formID: form.id }, body: { answer } });
6544
- if (!silent) {
6545
- deps.safeDeliver(ctx, `✅ 已提交选择:${display}`).catch(() => {});
6546
- }
6547
- 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
+ });
6548
7011
  } catch (error) {
7012
+ entry.replying = false;
6549
7013
  const msg = error instanceof Error ? error.message : String(error);
6550
- if (msg.includes("AlreadySettled") || msg.includes("already")) {
6551
- deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {});
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 卡片已失效");
6552
7018
  } else {
6553
- deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`).catch(() => {});
7019
+ await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`);
6554
7020
  }
7021
+ return;
6555
7022
  }
6556
- })();
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;
6557
7138
  }
6558
7139
  function pushForm(userId, ctx, form) {
7140
+ if (!accepting) {
7141
+ deliver(ctx, "⚠️ 表单桥正在停止,暂不接受新的 QQ 作答;请回桌面处理");
7142
+ return;
7143
+ }
6559
7144
  if (pending.get(userId)?.form.id === form.id)
6560
7145
  return;
6561
- const prev = clear(userId);
6562
- if (prev) {
6563
- deps.safeDeliver(ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)").catch(() => {});
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;
6564
7165
  }
6565
- const entry = { form, ctx, timer: null };
6566
- entry.timer = setTimeout(() => {
6567
- if (pending.get(userId)?.form.id !== form.id)
6568
- return;
6569
- clear(userId);
6570
- deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {});
6571
- }, FORM_PROMPT_TTL_MS);
7166
+ const previous = pending.get(userId);
7167
+ if (previous?.timer)
7168
+ clearTimeout(previous.timer);
6572
7169
  pending.set(userId, entry);
7170
+ scheduleExpiry(userId, entry);
7171
+ if (previous) {
7172
+ deliver(previous.ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)");
7173
+ }
6573
7174
  console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`);
6574
- (async () => {
6575
- const keyboard = buildFormKeyboard(form, ctx.userId);
7175
+ const operation = (async () => {
7176
+ const keyboard = buildFormKeyboard(form, liveCtx.userId);
6576
7177
  if (keyboard && deps.sendFormCard) {
6577
- const sent = await deps.sendFormCard(ctx, form, keyboard).catch(() => false);
7178
+ const sent = await deps.sendFormCard(liveCtx, form, keyboard).catch(() => false);
6578
7179
  if (sent)
6579
7180
  return;
6580
7181
  }
6581
- await deps.sendReply(ctx, renderFormPrompt(form)).catch((error) => {
7182
+ await deps.sendReply(liveCtx, renderFormPrompt(form)).catch((error) => {
6582
7183
  console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error);
6583
7184
  });
6584
7185
  })();
7186
+ track(operation);
6585
7187
  }
6586
7188
  function tryResolveText(userId, text) {
6587
7189
  const entry = pending.get(userId);
6588
7190
  if (!entry)
6589
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
+ }
6590
7204
  const answer = parseFormAnswer(entry.form, text);
6591
7205
  if (!answer) {
6592
7206
  const field = primaryField(entry.form);
@@ -6594,9 +7208,21 @@ function createFormBridge(deps) {
6594
7208
  deps.sendReply(entry.ctx, hint).catch(() => {});
6595
7209
  return true;
6596
7210
  }
6597
- submit(userId, entry.form, entry.ctx, answer, text.trim());
7211
+ submit(userId, entry, answer, text.trim());
6598
7212
  return true;
6599
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
+ }
6600
7226
  function handleButton(event) {
6601
7227
  const userId = event.user_openid ?? event.group_member_openid;
6602
7228
  if (!userId)
@@ -6605,91 +7231,178 @@ function createFormBridge(deps) {
6605
7231
  if (!button)
6606
7232
  return false;
6607
7233
  const entry = pending.get(userId);
6608
- if (!entry || entry.form.id !== button.f) {
7234
+ const ctx = entry?.ctx ?? eventContext(event, userId);
7235
+ if (!accepting || !entry || entry.form.id !== button.f || entry.state === "expired") {
6609
7236
  console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`);
7237
+ rejectButton(ctx);
6610
7238
  return true;
6611
7239
  }
6612
- const answer = { [button.k]: button.v };
6613
- submit(userId, entry.form, entry.ctx, answer, button.v, true);
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}`);
7260
+ return true;
7261
+ }
7262
+ submit(userId, entry, answer, button.v, interactionId);
6614
7263
  return true;
6615
7264
  }
6616
- return { pushForm, tryResolveText, handleButton, hasPending: (u) => pending.has(u), getPending: (u) => pending.get(u) };
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
+ };
6617
7303
  }
6618
7304
 
6619
7305
  // src/core/inflight-journal.ts
6620
- import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync9, mkdirSync as mkdirSync7, renameSync as renameSync2, openSync, closeSync, unlinkSync as unlinkSync2, statSync as statSync3 } from "fs";
6621
- import { join as join9 } from "path";
6622
- import { homedir as homedir8 } from "os";
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
+ }
6623
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
+ }
6624
7336
  function redispatchMaxAgeMs() {
6625
7337
  const n = Number(process.env.QQ_REDISPATCH_MAX_AGE_MS ?? "7200000");
6626
7338
  return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 7200000;
6627
7339
  }
6628
7340
  function journalPath() {
6629
- return process.env.QQ_INFLIGHT_FILE || join9(homedir8(), ".openqq", "inflight.json");
7341
+ return process.env.QQ_INFLIGHT_FILE || join11(homedir10(), ".openqq", "inflight.json");
6630
7342
  }
6631
7343
  function load() {
6632
7344
  let entries = [];
6633
7345
  try {
6634
- if (existsSync7(journalPath())) {
6635
- const raw = JSON.parse(readFileSync9(journalPath(), "utf-8"));
7346
+ if (existsSync9(journalPath())) {
7347
+ const raw = JSON.parse(readFileSync11(journalPath(), "utf-8"));
6636
7348
  if (Array.isArray(raw))
6637
7349
  entries = raw;
6638
7350
  }
6639
7351
  } catch {
6640
7352
  entries = [];
6641
7353
  }
6642
- return entries.filter((e) => e.state === "inflight" || Date.now() - e.at <= INFLIGHT_MAX_AGE_MS);
7354
+ return pruneInflightEntries(entries);
6643
7355
  }
6644
7356
  function save(entries) {
6645
7357
  const path = journalPath();
6646
- mkdirSync7(join9(path, ".."), { recursive: true });
7358
+ mkdirSync9(join11(path, ".."), { recursive: true });
7359
+ const retained = pruneInflightEntries(entries);
6647
7360
  const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6648
7361
  try {
6649
- writeFileSync9(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
6650
- renameSync2(tmp, path);
7362
+ writeFileSync11(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
7363
+ renameSync4(tmp, path);
6651
7364
  } catch (error) {
6652
7365
  try {
6653
- unlinkSync2(tmp);
7366
+ unlinkSync5(tmp);
6654
7367
  } catch {}
6655
7368
  throw error;
6656
7369
  }
6657
7370
  }
6658
7371
  var JOURNAL_LOCK_STALE_MS = 30000;
6659
7372
  var JOURNAL_LOCK_WAIT_MS = 5000;
6660
- var sleepArray = new Int32Array(new SharedArrayBuffer(4));
7373
+ var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
6661
7374
  function withJournalLock(fn) {
6662
7375
  const path = journalPath();
6663
- mkdirSync7(join9(path, ".."), { recursive: true });
7376
+ mkdirSync9(join11(path, ".."), { recursive: true });
6664
7377
  const lockPath = `${path}.lock`;
6665
7378
  const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
6666
7379
  const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
6667
7380
  for (;; ) {
6668
7381
  try {
6669
- const fd = openSync(lockPath, "wx", 384);
7382
+ const fd = openSync3(lockPath, "wx", 384);
6670
7383
  try {
6671
- writeFileSync9(fd, token);
7384
+ writeFileSync11(fd, token);
6672
7385
  } finally {
6673
- closeSync(fd);
7386
+ closeSync3(fd);
6674
7387
  }
6675
7388
  break;
6676
7389
  } catch (error) {
6677
7390
  try {
6678
- if (Date.now() - statSync3(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
6679
- unlinkSync2(lockPath);
7391
+ if (Date.now() - statSync5(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
7392
+ unlinkSync5(lockPath);
6680
7393
  } catch {}
6681
7394
  if (Date.now() >= deadline) {
6682
7395
  throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
6683
7396
  }
6684
- Atomics.wait(sleepArray, 0, 0, 10);
7397
+ Atomics.wait(sleepArray2, 0, 0, 10);
6685
7398
  }
6686
7399
  }
6687
7400
  try {
6688
7401
  return fn();
6689
7402
  } finally {
6690
7403
  try {
6691
- if (readFileSync9(lockPath, "utf-8") === token)
6692
- unlinkSync2(lockPath);
7404
+ if (readFileSync11(lockPath, "utf-8") === token)
7405
+ unlinkSync5(lockPath);
6693
7406
  } catch {}
6694
7407
  }
6695
7408
  }
@@ -6701,35 +7414,68 @@ function mutate(fn) {
6701
7414
  return result;
6702
7415
  });
6703
7416
  }
6704
- function claimInflight(entry) {
7417
+ function claimInflightDetailed(entry, opts) {
6705
7418
  return mutate((entries) => {
6706
- if (entries.some((e) => e.msgId === entry.msgId))
6707
- return false;
6708
- entries.push({ ...entry, state: "inflight" });
6709
- return true;
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";
6710
7435
  });
6711
7436
  }
6712
7437
  function recordInflight(entry) {
6713
7438
  mutate((entries) => {
6714
7439
  const existing = entries.find((e) => e.msgId === entry.msgId);
6715
7440
  if (existing) {
6716
- if (!existing.sessionId && entry.sessionId)
6717
- existing.sessionId = entry.sessionId;
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" });
6718
7452
  return;
6719
7453
  }
6720
- entries.push({ ...entry, state: "inflight" });
7454
+ entries.push({ ...entry, attemptId: entry.attemptId ?? newInflightAttemptId(), state: "inflight" });
6721
7455
  });
6722
7456
  }
6723
- function settleInflight(msgId) {
6724
- mutate((entries) => {
6725
- const entry = entries.find((e) => e.msgId === msgId && e.state === "inflight");
6726
- if (entry)
6727
- entry.state = "settled";
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;
6728
7464
  });
6729
7465
  }
6730
7466
  function pendingInflight() {
6731
7467
  return load().filter((e) => e.state === "inflight");
6732
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;
6733
7479
  function classifyInflight(entry, messages) {
6734
7480
  const ordered = [...messages].reverse();
6735
7481
  const probe = entry.text.trim().slice(0, 50);
@@ -6749,6 +7495,21 @@ function classifyInflight(entry, messages) {
6749
7495
  }
6750
7496
  }
6751
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
+ }
6752
7513
  if (userIdx < 0)
6753
7514
  return { kind: "lost" };
6754
7515
  let turnEnd = ordered.length;
@@ -6785,6 +7546,12 @@ function evictableIdleSessions(lastActivity, watched, now, idleMs) {
6785
7546
  }
6786
7547
  return out;
6787
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
+ }
6788
7555
  function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, intervalMs, maxNudges) {
6789
7556
  if (nudges >= maxNudges)
6790
7557
  return "wait";
@@ -6793,8 +7560,11 @@ function stallNudgeDecision(startedAt, lastProgressAt, nudges, now, firstMs, int
6793
7560
  return now - base >= need ? "nudge" : "wait";
6794
7561
  }
6795
7562
  function createBridge(config, client, sessions) {
7563
+ const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "");
6796
7564
  const busyUsers = new Set;
6797
7565
  const claimedContexts = new WeakSet;
7566
+ const drainReentries = new WeakSet;
7567
+ const activeIntents = new Map;
6798
7568
  const msgQueue = new MessageQueue(QUEUE_MAX);
6799
7569
  const draining = new Set;
6800
7570
  const greeted = loadGreetedSet();
@@ -6871,7 +7641,8 @@ function createBridge(config, client, sessions) {
6871
7641
  const STALL_FIRST_NUDGE_MS = 30 * 60 * 1000;
6872
7642
  const STALL_NUDGE_INTERVAL_MS = 30 * 60 * 1000;
6873
7643
  const STALL_NUDGE_MAX = 3;
6874
- function startBackgroundWait(sessionId, ctx, baseline, trackId) {
7644
+ function startBackgroundWait(sessionId, ctx, baseline, trackId, promptId = "") {
7645
+ bgWaits.get(sessionId)?.cancel();
6875
7646
  let cancelled = false;
6876
7647
  let finished = false;
6877
7648
  const startedAt = Date.now();
@@ -6886,9 +7657,26 @@ function createBridge(config, client, sessions) {
6886
7657
  bgWaits.delete(sessionId);
6887
7658
  mirror.scheduleUnlock(sessionId);
6888
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
+ }
6889
7667
  async function finish(kind) {
6890
7668
  if (cancelled || finished)
6891
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
+ }
6892
7680
  finished = true;
6893
7681
  cleanup();
6894
7682
  if (trackId)
@@ -6901,7 +7689,7 @@ function createBridge(config, client, sessions) {
6901
7689
  await new Promise((r) => setTimeout(r, 2000));
6902
7690
  try {
6903
7691
  const listJson = await client.session.messages({ path: { id: sessionId } });
6904
- const text = collectReplyText(listJson?.data ?? [], baseline);
7692
+ const { text } = classifyNow(listJson);
6905
7693
  await safeDeliver(ctx, text ? `\uD83D\uDCE4 后台任务完成,结果如下:
6906
7694
 
6907
7695
  ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用 /history 查看");
@@ -6916,6 +7704,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6916
7704
  try {
6917
7705
  const listJson = await client.session.messages({ path: { id: sessionId } });
6918
7706
  const msgs = listJson?.data ?? [];
7707
+ const turn = turnStateOf(msgs, promptId, baseline);
6919
7708
  let maxCreated = 0;
6920
7709
  for (const m of msgs) {
6921
7710
  const created = m.time?.created ?? 0;
@@ -6930,10 +7719,17 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
6930
7719
  } else if (stallNudgeDecision(startedAt, lastProgressAt, nudges, now, STALL_FIRST_NUDGE_MS, STALL_NUDGE_INTERVAL_MS, STALL_NUDGE_MAX) === "nudge") {
6931
7720
  nudges += 1;
6932
7721
  lastProgressAt = now;
6933
- console.log(`[bridge] 后台任务停滞提醒 #${nudges} session=${sessionId}`);
6934
- safeDeliver(ctx, "⚠️ 后台任务已停滞超过 30 分钟——很可能在桌面端等待确认(审批/选择弹窗无法同步到 QQ)。请到桌面端查看处理;或回复 /stop 终止该任务后重发。").catch(() => {});
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(() => {});
6935
7731
  }
6936
- if (msgs.some((x) => x.type === "idle" && (x.time?.created ?? 0) >= baseline)) {
7732
+ if (turn.hasIdle) {
6937
7733
  await finish("done");
6938
7734
  }
6939
7735
  } catch (error) {
@@ -7121,6 +7917,7 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
7121
7917
  purgeOldQQImages();
7122
7918
  const handleMessage = async (ctx) => {
7123
7919
  let claimedMsgId = "";
7920
+ const intentKey = intentKeyOf(ctx);
7124
7921
  try {
7125
7922
  if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
7126
7923
  await sendReply(ctx, "你不在允许使用的名单里");
@@ -7161,15 +7958,28 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
7161
7958
  }
7162
7959
  if (ctx.msgId) {
7163
7960
  if (!claimedContexts.has(ctx)) {
7164
- const claimed = claimInflight({ msgId: ctx.msgId, userId: ctx.userId, sessionId: "", text: content.slice(0, 300), at: Date.now() });
7165
- if (!claimed) {
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") {
7166
7963
  console.log(`[bridge] 重复消息已跳过 msgId=${ctx.msgId}`);
7167
7964
  return;
7168
7965
  }
7966
+ if (admitted === "duplicate-intent") {
7967
+ console.log(`[admit-dedupe] 同内容意图在途,本次重发已忽略 msgId=${ctx.msgId}`);
7968
+ await sendReply(ctx, "你的相同问题正在处理中,本次重发已忽略");
7969
+ return;
7970
+ }
7169
7971
  claimedContexts.add(ctx);
7170
7972
  }
7171
7973
  claimedMsgId = ctx.msgId;
7172
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
+ }
7173
7983
  if (busyUsers.has(ctx.userId)) {
7174
7984
  if (ctx.attachments?.length && !ctx.preparedAttachments) {
7175
7985
  ctx.preparedAttachments = await prepareQQAttachments(ctx.attachments, () => getAccessToken(config.qq.appId, config.qq.clientSecret));
@@ -7185,13 +7995,18 @@ ${text}` : "\uD83D\uDCE4 后台任务完成(无文本产出),详情可用
7185
7995
  发 /queue 查看队列,/cancel 可中止当前任务并清空队列。`);
7186
7996
  return;
7187
7997
  }
7998
+ activeIntents.set(ctx.userId, intentKey);
7188
7999
  busyUsers.add(ctx.userId);
8000
+ if (ackReceiptEnabled && ctx.msgId && !drainReentries.has(ctx)) {
8001
+ await sendReply(ctx, "✅ 已收到,正在处理,完成后自动回复你");
8002
+ }
7189
8003
  if (ctx.type === "c2c" && ctx.msgId) {
7190
8004
  getAccessToken(config.qq.appId, config.qq.clientSecret).then((token) => sendC2CInputNotify(token, ctx.userId, ctx.msgId, 60)).catch(() => {});
7191
8005
  }
7192
8006
  let sessionId = "";
7193
8007
  let turnStart = 0;
7194
8008
  let trackId = "";
8009
+ let promptId = "";
7195
8010
  try {
7196
8011
  const session = await sessions.getOrCreate(ctx.userId);
7197
8012
  sessionId = session.sessionId;
@@ -7214,6 +8029,10 @@ ${promptBody}` : promptBody;
7214
8029
  recordInflight({ msgId: trackId, userId: ctx.userId, sessionId, text: content.slice(0, 300), at: Date.now() });
7215
8030
  const replyText = await client.promptAndWait(sessionId, promptText, {
7216
8031
  files: files.length ? files : undefined,
8032
+ onAccepted: (info) => {
8033
+ promptId = info.promptId;
8034
+ markInflightPromptId(trackId, info.promptId);
8035
+ },
7217
8036
  onPermission: (req) => perm.waitForDecision(ctx, req, sessionId),
7218
8037
  onPermissionReplied: (d) => {
7219
8038
  safeDeliver(ctx, `已${DECISION_LABELS[d]},AI 将继续执行…`);
@@ -7241,7 +8060,7 @@ ${promptBody}` : promptBody;
7241
8060
  } catch (error) {
7242
8061
  if (sessionId && turnStart > 0 && error instanceof Error && error.message.includes("响应超时")) {
7243
8062
  await safeDeliver(ctx, "⏳ 回合超过前台时限,已转后台等待:任务继续执行,完成即回传结果(最长 24 小时)。期间可用 /history 查看进展。");
7244
- startBackgroundWait(sessionId, ctx, turnStart, trackId);
8063
+ startBackgroundWait(sessionId, ctx, turnStart, trackId, promptId);
7245
8064
  } else {
7246
8065
  const errText = toErrorMessage2(error);
7247
8066
  const rescue = rescueText(classifyProviderError(errText), errText);
@@ -7254,12 +8073,16 @@ ${promptBody}` : promptBody;
7254
8073
  if (sessionId && !bgWaits.has(sessionId))
7255
8074
  mirror.scheduleUnlock(sessionId);
7256
8075
  busyUsers.delete(ctx.userId);
8076
+ if (activeIntents.get(ctx.userId) === intentKey)
8077
+ activeIntents.delete(ctx.userId);
7257
8078
  if (sessionId && !bgWaits.has(sessionId))
7258
8079
  drainQueue(ctx.userId);
7259
8080
  }
7260
8081
  } catch (error) {
7261
8082
  if (claimedMsgId)
7262
8083
  settleInflight(claimedMsgId);
8084
+ if (activeIntents.get(ctx.userId) === intentKey)
8085
+ activeIntents.delete(ctx.userId);
7263
8086
  console.error("[bridge] handleMessage failed:", error);
7264
8087
  try {
7265
8088
  await sendReply(ctx, `处理消息失败:${toErrorMessage2(error)}`);
@@ -7280,9 +8103,15 @@ ${promptBody}` : promptBody;
7280
8103
  continue;
7281
8104
  }
7282
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
+ }
7283
8112
  try {
7284
- const listJson = await client.session.messages({ path: { id: entry.sessionId } });
7285
- const cls = classifyInflight(entry, listJson?.data ?? []);
8113
+ const listJson = { data: await fetchRecoveryMessages(client, entry.sessionId) };
8114
+ const cls = classifyInflight(entry, listJson.data);
7286
8115
  if (cls.kind === "answered") {
7287
8116
  await deliver(ctx, `\uD83D\uDD04 重启补投:你之前的消息已有答案
7288
8117
 
@@ -7291,7 +8120,7 @@ ${cls.answer}`);
7291
8120
  console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`);
7292
8121
  } else if (cls.kind === "running") {
7293
8122
  mirror.beginTurn(entry.sessionId);
7294
- startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId);
8123
+ startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId, entry.promptId ?? "");
7295
8124
  console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`);
7296
8125
  } else if (ageMs <= redispatchMaxAgeMs()) {
7297
8126
  settleInflight(entry.msgId);
@@ -7317,6 +8146,7 @@ ${cls.answer}`);
7317
8146
  draining.add(userId);
7318
8147
  try {
7319
8148
  await sendReply(job.ctx, `开始执行队列 #${job.id}`);
8149
+ drainReentries.add(job.ctx);
7320
8150
  await handleMessage(job.ctx);
7321
8151
  } catch (error) {
7322
8152
  console.error("[bridge] 队列执行失败:", error);
@@ -7337,6 +8167,20 @@ ${cls.answer}`);
7337
8167
  }
7338
8168
  };
7339
8169
  }
8170
+ async function fetchRecoveryMessages(client, sessionId) {
8171
+ const all = [];
8172
+ let cursor;
8173
+ for (let page = 0;page < 10; page++) {
8174
+ const res = await client.session.messages({ path: { id: sessionId }, query: { limit: 200, cursor } });
8175
+ const items = res?.data ?? [];
8176
+ all.push(...items);
8177
+ const next = res?.cursor?.next;
8178
+ if (!next || items.length === 0)
8179
+ break;
8180
+ cursor = next;
8181
+ }
8182
+ return all;
8183
+ }
7340
8184
  async function maybeHandlePendingSelection(ctx, commandContext) {
7341
8185
  const pending = commandContext.pendingSelections.get(ctx.userId);
7342
8186
  if (!pending) {
@@ -7357,11 +8201,11 @@ function isAllowedUser(userId, allowedUsers) {
7357
8201
  return false;
7358
8202
  return allowedUsers.includes(userId);
7359
8203
  }
7360
- var WATCH_FILE = join10(homedir9(), ".openqq", "watch.json");
8204
+ var WATCH_FILE = join12(homedir11(), ".openqq", "watch.json");
7361
8205
  function loadWatchedMap(file = WATCH_FILE) {
7362
8206
  try {
7363
- if (existsSync8(file)) {
7364
- const raw = readFileSync10(file, "utf-8");
8207
+ if (existsSync10(file)) {
8208
+ const raw = readFileSync12(file, "utf-8");
7365
8209
  const obj = JSON.parse(raw);
7366
8210
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
7367
8211
  const out = {};
@@ -7376,16 +8220,16 @@ function loadWatchedMap(file = WATCH_FILE) {
7376
8220
  }
7377
8221
  function saveWatchedMap(m, file = WATCH_FILE) {
7378
8222
  try {
7379
- writeFileSync10(file, JSON.stringify(Object.fromEntries(m), null, 2));
8223
+ writeFileSync12(file, JSON.stringify(Object.fromEntries(m), null, 2));
7380
8224
  } catch (error) {
7381
8225
  console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
7382
8226
  }
7383
8227
  }
7384
- var GREETED_FILE = join10(homedir9(), ".openqq", "greeted.json");
8228
+ var GREETED_FILE = join12(homedir11(), ".openqq", "greeted.json");
7385
8229
  function loadGreetedSet() {
7386
8230
  try {
7387
- if (existsSync8(GREETED_FILE)) {
7388
- const raw = readFileSync10(GREETED_FILE, "utf-8");
8231
+ if (existsSync10(GREETED_FILE)) {
8232
+ const raw = readFileSync12(GREETED_FILE, "utf-8");
7389
8233
  const arr = JSON.parse(raw);
7390
8234
  if (Array.isArray(arr)) {
7391
8235
  return new Set(arr.filter((x) => typeof x === "string"));
@@ -7396,8 +8240,8 @@ function loadGreetedSet() {
7396
8240
  }
7397
8241
  function saveGreetedSet(set) {
7398
8242
  try {
7399
- mkdirSync8(join10(homedir9(), ".openqq"), { recursive: true });
7400
- writeFileSync10(GREETED_FILE, JSON.stringify([...set]));
8243
+ mkdirSync10(join12(homedir11(), ".openqq"), { recursive: true });
8244
+ writeFileSync12(GREETED_FILE, JSON.stringify([...set]));
7401
8245
  } catch (error) {
7402
8246
  console.error("[bridge] 保存 greeted 失败:", error);
7403
8247
  }
@@ -7448,35 +8292,36 @@ function toErrorMessage2(error) {
7448
8292
  }
7449
8293
 
7450
8294
  // src/core/instance-lock.ts
7451
- import { openSync as openSync2, writeFileSync as writeFileSync11, closeSync as closeSync2, unlinkSync as unlinkSync3, statSync as statSync4, utimesSync, mkdirSync as mkdirSync9 } from "fs";
7452
- import { join as join11 } from "path";
7453
- import { homedir as homedir10 } from "os";
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";
7454
8298
  var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
7455
- var LOCK_STALE_MS = 30000;
8299
+ var LOCK_STALE_MS2 = 30000;
7456
8300
  var LOCK_UPDATE_MS = 1e4;
7457
8301
  var LOCK_RETRY_MS = 5000;
8302
+ var LOCK_SELF_CHECK_MS = 60000;
7458
8303
  function lockPathOf(appId) {
7459
- return join11(homedir10(), ".openqq", `openqq-${appId}.lock`);
8304
+ return join13(homedir12(), ".openqq", `openqq-${appId}.lock`);
7460
8305
  }
7461
8306
  function touch(path) {
7462
8307
  const now = new Date;
7463
8308
  utimesSync(path, now, now);
7464
8309
  }
7465
- function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
8310
+ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2) {
7466
8311
  try {
7467
- mkdirSync9(join11(path, ".."), { recursive: true });
7468
- const fd = openSync2(path, "wx");
7469
- writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
7470
- closeSync2(fd);
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);
7471
8316
  } catch {
7472
8317
  try {
7473
- const age = Date.now() - statSync4(path).mtimeMs;
8318
+ const age = Date.now() - statSync6(path).mtimeMs;
7474
8319
  if (age <= staleMs)
7475
8320
  return null;
7476
- unlinkSync3(path);
7477
- const fd = openSync2(path, "wx");
7478
- writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
7479
- closeSync2(fd);
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);
7480
8325
  console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
7481
8326
  } catch {
7482
8327
  return null;
@@ -7488,6 +8333,22 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
7488
8333
  } catch {}
7489
8334
  }, LOCK_UPDATE_MS);
7490
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?.();
7491
8352
  let released = false;
7492
8353
  return {
7493
8354
  release: () => {
@@ -7495,8 +8356,9 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
7495
8356
  return;
7496
8357
  released = true;
7497
8358
  clearInterval(heartbeat);
8359
+ clearInterval(selfCheck);
7498
8360
  try {
7499
- unlinkSync3(path);
8361
+ unlinkSync6(path);
7500
8362
  } catch {}
7501
8363
  }
7502
8364
  };
@@ -7598,11 +8460,11 @@ async function main() {
7598
8460
  });
7599
8461
  console.log("[index] OpenCode QQ Bot 已启动");
7600
8462
  bridge.recoverInflightRounds();
7601
- const heartbeatFile = join13(homedir11(), ".openqq", "heartbeat");
8463
+ const heartbeatFile = join15(homedir13(), ".openqq", "heartbeat");
7602
8464
  const touchHeartbeat = () => {
7603
8465
  try {
7604
- mkdirSync11(join13(homedir11(), ".openqq"), { recursive: true });
7605
- writeFileSync12(heartbeatFile, String(Date.now()));
8466
+ mkdirSync13(join15(homedir13(), ".openqq"), { recursive: true });
8467
+ writeFileSync14(heartbeatFile, String(Date.now()));
7606
8468
  } catch (error) {
7607
8469
  console.error("[index] 心跳写入失败:", error);
7608
8470
  }