@linjz/opencode-qqbot 0.3.19 → 0.3.20

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.
@@ -3298,7 +3298,7 @@ function storageFile(name, appId) {
3298
3298
  }
3299
3299
 
3300
3300
  // src/index.ts
3301
- import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync16 } from "fs";
3301
+ import { mkdirSync as mkdirSync16, writeFileSync as writeFileSync17 } from "fs";
3302
3302
  import { join as join14 } from "path";
3303
3303
  import { homedir as homedir8 } from "os";
3304
3304
 
@@ -4320,6 +4320,7 @@ var STORE_FILE = storageFile("sessions.json");
4320
4320
  class SessionManager {
4321
4321
  sessions = new Map;
4322
4322
  client;
4323
+ bindingListeners = new Set;
4323
4324
  storeFile;
4324
4325
  constructor(client, storeFile = STORE_FILE) {
4325
4326
  this.client = client;
@@ -4359,6 +4360,19 @@ class SessionManager {
4359
4360
  console.error("[sessions] 会话映射持久化失败:", error);
4360
4361
  }
4361
4362
  }
4363
+ onBindingChange(listener) {
4364
+ this.bindingListeners.add(listener);
4365
+ return () => this.bindingListeners.delete(listener);
4366
+ }
4367
+ emitBindingChange(userId, sessionId) {
4368
+ for (const listener of this.bindingListeners) {
4369
+ try {
4370
+ listener(userId, sessionId);
4371
+ } catch (error) {
4372
+ console.error("[sessions] 绑定变化通知失败:", error);
4373
+ }
4374
+ }
4375
+ }
4362
4376
  async getOrCreate(userId) {
4363
4377
  const existing = this.sessions.get(userId);
4364
4378
  if (existing)
@@ -4371,6 +4385,7 @@ class SessionManager {
4371
4385
  };
4372
4386
  this.sessions.set(userId, session);
4373
4387
  this.saveSessions();
4388
+ this.emitBindingChange(userId, session.sessionId);
4374
4389
  await this.enforceLocation(userId, session.sessionId, directory);
4375
4390
  return session;
4376
4391
  }
@@ -4388,6 +4403,8 @@ class SessionManager {
4388
4403
  };
4389
4404
  this.sessions.set(userId, session);
4390
4405
  this.saveSessions();
4406
+ if (!prev || prev.sessionId !== session.sessionId)
4407
+ this.emitBindingChange(userId, session.sessionId);
4391
4408
  if (inheritedModel) {
4392
4409
  this.client.session.setModel({ path: { id: session.sessionId }, body: { model: inheritedModel } }).catch((error) => console.error("[sessions] 新会话继承模型失败(映射已存):", error));
4393
4410
  }
@@ -4408,6 +4425,7 @@ class SessionManager {
4408
4425
  });
4409
4426
  this.saveSessions();
4410
4427
  if (changed) {
4428
+ this.emitBindingChange(userId, sessionId);
4411
4429
  this.refreshSettingsFromServer(userId);
4412
4430
  }
4413
4431
  }
@@ -4480,12 +4498,18 @@ class SessionManager {
4480
4498
  }
4481
4499
  }
4482
4500
  all() {
4483
- return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId, directory: s.directory }));
4501
+ return [...this.sessions.entries()].map(([userId, s]) => ({
4502
+ userId,
4503
+ sessionId: s.sessionId,
4504
+ ...s.title ? { title: s.title } : {},
4505
+ directory: s.directory
4506
+ }));
4484
4507
  }
4485
4508
  evict(userId) {
4486
4509
  const had = this.sessions.delete(userId);
4487
4510
  if (had) {
4488
4511
  this.saveSessions();
4512
+ this.emitBindingChange(userId, null);
4489
4513
  console.log(`[sessions] 驱逐失效映射 userId=${userId.slice(0, 8)}…(400/404 三连判死)`);
4490
4514
  }
4491
4515
  return had;
@@ -4708,6 +4732,11 @@ function briefAttachments(atts) {
4708
4732
  return { host, content_type: a.content_type, size: a.size, filename: a.filename, asr: a.asr_refer_text ? 1 : 0 };
4709
4733
  });
4710
4734
  }
4735
+ function referencedMessageId(event) {
4736
+ const prefix = "ref_msg_idx=";
4737
+ const official = event.message_scene?.ext?.find((item) => typeof item === "string" && item.startsWith(prefix))?.slice(prefix.length).trim();
4738
+ return official || event.message_reference?.message_id;
4739
+ }
4711
4740
  function toC2CMessageContext(event) {
4712
4741
  return {
4713
4742
  type: "c2c",
@@ -4715,7 +4744,7 @@ function toC2CMessageContext(event) {
4715
4744
  msgId: event.id,
4716
4745
  content: normalizeMessageContent(event.content),
4717
4746
  ...isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {},
4718
- referencedMsgId: event.message_reference?.message_id,
4747
+ referencedMsgId: referencedMessageId(event),
4719
4748
  attachments: event.attachments,
4720
4749
  timestamp: event.timestamp,
4721
4750
  rawEvent: event
@@ -4729,7 +4758,7 @@ function toGroupMessageContext(event) {
4729
4758
  msgId: event.id,
4730
4759
  content: stripGroupAtPrefix(event.content),
4731
4760
  ...isEmojiOnlyContent(event.content) ? { emojiOnly: true } : {},
4732
- referencedMsgId: event.message_reference?.message_id,
4761
+ referencedMsgId: referencedMessageId(event),
4733
4762
  attachments: event.attachments,
4734
4763
  timestamp: event.timestamp,
4735
4764
  rawEvent: event
@@ -4750,8 +4779,8 @@ function sendIdentify(ws, accessToken) {
4750
4779
  shard: [0, 1],
4751
4780
  properties: {
4752
4781
  os: process.platform,
4753
- browser: "opencode_qq_bot",
4754
- device: "opencode_qq_bot"
4782
+ browser: "opencode_qqbot",
4783
+ device: "opencode_qqbot"
4755
4784
  }
4756
4785
  }
4757
4786
  };
@@ -5004,7 +5033,7 @@ async function startGateway(options) {
5004
5033
  }
5005
5034
 
5006
5035
  // src/bridge.ts
5007
- import { existsSync as existsSync15, readFileSync as readFileSync17, mkdirSync as mkdirSync14, writeFileSync as writeFileSync15 } from "fs";
5036
+ import { existsSync as existsSync16, readFileSync as readFileSync18, mkdirSync as mkdirSync15, writeFileSync as writeFileSync16 } from "fs";
5008
5037
  import { join as join13 } from "path";
5009
5038
  import { homedir as homedir7 } from "os";
5010
5039
 
@@ -6248,6 +6277,27 @@ import { existsSync as existsSync8, readFileSync as readFileSync9, mkdirSync as
6248
6277
 
6249
6278
  // src/opencode/mirror.ts
6250
6279
  var USER_CLIP = 160;
6280
+ var DIGEST_TITLE_MAX_WIDTH = 20;
6281
+ function isWideCodePoint(cp) {
6282
+ return cp >= 4352 && (cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 42191 && cp !== 12351 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 126976 && cp <= 129791 || cp >= 131072 && cp <= 262141);
6283
+ }
6284
+ function clipDigestTitle(value, maxWidth = DIGEST_TITLE_MAX_WIDTH) {
6285
+ const title = (value ?? "").replace(/\s+/g, " ").trim() || "未命名会话";
6286
+ let width = 0;
6287
+ let out = "";
6288
+ for (const char of title) {
6289
+ const cp = char.codePointAt(0) ?? 0;
6290
+ const charWidth = /\p{Mark}/u.test(char) || cp === 8205 || cp >= 65024 && cp <= 65039 ? 0 : isWideCodePoint(cp) ? 2 : 1;
6291
+ if (width + charWidth > maxWidth)
6292
+ return `${out}...`;
6293
+ out += char;
6294
+ width += charWidth;
6295
+ }
6296
+ return out;
6297
+ }
6298
+ function digestSessionLabel(sessionId) {
6299
+ return sessionId.length > 10 ? `${sessionId.slice(0, 10)}…` : sessionId;
6300
+ }
6251
6301
  function answerClipLimit() {
6252
6302
  const n = Number(process.env.QQ_DIGEST_ANSWER_MAX_CHARS ?? "0");
6253
6303
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
@@ -6279,7 +6329,7 @@ function digestTurnKey(messages) {
6279
6329
  }
6280
6330
  return null;
6281
6331
  }
6282
- function buildDigest(messages, goalObjective) {
6332
+ function buildDigest(messages, goalObjective, identity) {
6283
6333
  const ordered = [...messages].reverse();
6284
6334
  let lastUserIdx = -1;
6285
6335
  let goalDriven = false;
@@ -6312,7 +6362,12 @@ function buildDigest(messages, goalObjective) {
6312
6362
  }
6313
6363
  if (!answer)
6314
6364
  return null;
6315
- const lines = [goalDriven ? "\uD83C\uDFAF 目标续跑摘要" : "\uD83D\uDCCB 桌面问答摘要"];
6365
+ const kind = goalDriven ? "\uD83C\uDFAF 目标续跑摘要" : "\uD83D\uDCCB 桌面问答摘要";
6366
+ const lines = [
6367
+ identity ? `${kind} · ${clipDigestTitle(identity.title)} · ${digestSessionLabel(identity.sessionId)}` : kind
6368
+ ];
6369
+ if (identity)
6370
+ lines.push("↩️ 引用回复仅在该会话仍为当前绑定时受理");
6316
6371
  if (userText)
6317
6372
  lines.push(`\uD83E\uDDD1 ${clip2(userText, USER_CLIP)}`);
6318
6373
  const clipLimit = answerClipLimit();
@@ -6528,27 +6583,50 @@ function createMirror(deps) {
6528
6583
  const qqTurnActive = new Set;
6529
6584
  const qqPromptIds = new Map;
6530
6585
  const QQ_PROMPT_ID_CAP = 200;
6586
+ const MIRROR_SESSION_STATE_CAP = 500;
6531
6587
  function markQqPrompt(sessionId, promptId) {
6532
6588
  if (!promptId)
6533
6589
  return;
6534
- let set = qqPromptIds.get(sessionId);
6535
- if (!set) {
6536
- set = new Set;
6537
- qqPromptIds.set(sessionId, set);
6538
- }
6590
+ const set = qqPromptIds.get(sessionId) ?? new Set;
6591
+ qqPromptIds.delete(sessionId);
6539
6592
  if (set.size >= QQ_PROMPT_ID_CAP) {
6540
6593
  const first = set.values().next().value;
6541
6594
  if (first !== undefined)
6542
6595
  set.delete(first);
6543
6596
  }
6544
6597
  set.add(promptId);
6598
+ qqPromptIds.set(sessionId, set);
6599
+ while (qqPromptIds.size > MIRROR_SESSION_STATE_CAP) {
6600
+ const oldest = qqPromptIds.keys().next().value;
6601
+ if (oldest === undefined)
6602
+ break;
6603
+ qqPromptIds.delete(oldest);
6604
+ }
6545
6605
  }
6546
6606
  const mirroredTurns = new Map;
6607
+ function rememberMirroredTurn(sessionId, turnKey) {
6608
+ mirroredTurns.delete(sessionId);
6609
+ mirroredTurns.set(sessionId, turnKey);
6610
+ while (mirroredTurns.size > MIRROR_SESSION_STATE_CAP) {
6611
+ const oldest = mirroredTurns.keys().next().value;
6612
+ if (oldest === undefined)
6613
+ break;
6614
+ mirroredTurns.delete(oldest);
6615
+ }
6616
+ }
6547
6617
  const mirrorState = { enabled: loadMirrorEnabled(deps.settingsFile) };
6548
6618
  function ensureMirrorSubs() {
6549
- if (!mirrorState.enabled)
6550
- return;
6551
- for (const { sessionId } of sessions.all()) {
6619
+ const desired = new Set((mirrorState.enabled ? sessions.all() : []).map((binding) => binding.sessionId));
6620
+ let added = 0;
6621
+ let removed = 0;
6622
+ for (const [sessionId, unsub] of [...mirrorUnsubs]) {
6623
+ if (desired.has(sessionId))
6624
+ continue;
6625
+ unsub();
6626
+ mirrorUnsubs.delete(sessionId);
6627
+ removed++;
6628
+ }
6629
+ for (const sessionId of desired) {
6552
6630
  if (mirrorUnsubs.has(sessionId))
6553
6631
  continue;
6554
6632
  mirrorUnsubs.set(sessionId, eventStream.subscribe(sessionId, (ev) => {
@@ -6562,13 +6640,17 @@ function createMirror(deps) {
6562
6640
  }
6563
6641
  mirrorTurn(sessionId);
6564
6642
  }));
6643
+ added++;
6644
+ }
6645
+ if (added > 0 || removed > 0) {
6646
+ console.log(`[mirror-reconcile] desired=${desired.size} added=${added} removed=${removed} actual=${mirrorUnsubs.size}`);
6565
6647
  }
6566
6648
  }
6567
- function disableMirrorSubs() {
6568
- for (const unsub of mirrorUnsubs.values())
6569
- unsub();
6570
- mirrorUnsubs.clear();
6649
+ if (typeof sessions.onBindingChange === "function") {
6650
+ sessions.onBindingChange(() => ensureMirrorSubs());
6571
6651
  }
6652
+ const reconcileTimer = setInterval(ensureMirrorSubs, 60000);
6653
+ reconcileTimer.unref?.();
6572
6654
  function scheduleMirrorUnlock(sessionId) {
6573
6655
  setTimeout(() => {
6574
6656
  if (bgWaits.has(sessionId))
@@ -6581,11 +6663,19 @@ function createMirror(deps) {
6581
6663
  }
6582
6664
  async function mirrorTurn(sessionID) {
6583
6665
  try {
6584
- const owners = sessions.all().filter((x) => x.sessionId === sessionID).map((x) => x.userId);
6666
+ const bindings = sessions.all().filter((x) => x.sessionId === sessionID);
6667
+ const owners = bindings.map((x) => x.userId);
6585
6668
  if (owners.length === 0) {
6586
6669
  console.log(`[mirror] 跳过:会话无映射主人 session=${sessionID}`);
6587
6670
  return;
6588
6671
  }
6672
+ let title;
6673
+ if (typeof client.session.get === "function") {
6674
+ try {
6675
+ title = (await client.session.get({ path: { id: sessionID } }))?.data?.title;
6676
+ } catch {}
6677
+ }
6678
+ title ??= bindings.find((binding) => binding.title?.trim())?.title;
6589
6679
  const listJson = await client.session.messages({ path: { id: sessionID } });
6590
6680
  const messages = listJson?.data ?? [];
6591
6681
  const turnKey = digestTurnKey(messages);
@@ -6597,16 +6687,19 @@ function createMirror(deps) {
6597
6687
  if (anchorId && qqPromptIds.get(sessionID)?.has(anchorId)) {
6598
6688
  console.log(`[mirror] 跳过:QQ 直答回合(来源身份核对命中)session=${sessionID} prompt=${anchorId}`);
6599
6689
  if (turnKey)
6600
- mirroredTurns.set(sessionID, turnKey);
6690
+ rememberMirroredTurn(sessionID, turnKey);
6601
6691
  return;
6602
6692
  }
6603
- const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID));
6693
+ const digest = buildDigest(messages, deps.goalObjectiveOf?.(sessionID), {
6694
+ sessionId: sessionID,
6695
+ title
6696
+ });
6604
6697
  if (!digest) {
6605
6698
  console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`);
6606
6699
  return;
6607
6700
  }
6608
6701
  if (turnKey)
6609
- mirroredTurns.set(sessionID, turnKey);
6702
+ rememberMirroredTurn(sessionID, turnKey);
6610
6703
  for (const userId of owners) {
6611
6704
  const recent = lastCtx.get(userId);
6612
6705
  const ctx = recent ? { ...recent, anchorSessionId: sessionID } : { type: "c2c", userId, msgId: "", content: "", anchorSessionId: sessionID };
@@ -6614,7 +6707,31 @@ function createMirror(deps) {
6614
6707
  const outText = cronHook ? cronHook(userId, digest) : digest;
6615
6708
  if (!outText.trim())
6616
6709
  continue;
6617
- await safeDeliver(ctx, outText);
6710
+ const onSent = (receipt) => {
6711
+ if (!deps.anchorStore)
6712
+ return;
6713
+ if (!receipt.refIdx) {
6714
+ console.warn(`[mirror-anchor] QQ 未返回 ref_idx,摘要不可安全路由 session=${sessionID} user=${userId.slice(0, 8)}…`);
6715
+ return;
6716
+ }
6717
+ try {
6718
+ deps.anchorStore.record({
6719
+ refIdx: receipt.refIdx,
6720
+ messageId: receipt.id,
6721
+ userId,
6722
+ sessionId: sessionID,
6723
+ title: clipDigestTitle(redactSecrets(title ?? "")),
6724
+ sentAt: Date.now()
6725
+ });
6726
+ console.log(`[mirror-anchor] 已登记 session=${digestSessionLabel(sessionID)} user=${userId.slice(0, 8)}…`);
6727
+ } catch (error) {
6728
+ console.error("[mirror-anchor] 锚点落盘失败,后续引用将 fail-closed:", error);
6729
+ }
6730
+ };
6731
+ await safeDeliver(ctx, outText, onSent, {
6732
+ continuationPrefix: `\uD83D\uDCCB 摘要续 · ${digestSessionLabel(sessionID)}
6733
+ `
6734
+ });
6618
6735
  }
6619
6736
  console.log(`[mirror] 会话 ${sessionID} 摘要已镜像给 ${owners.length} 个用户`);
6620
6737
  } catch (error) {
@@ -6630,13 +6747,17 @@ function createMirror(deps) {
6630
6747
  if (!prev)
6631
6748
  ensureMirrorSubs();
6632
6749
  } else {
6633
- disableMirrorSubs();
6750
+ ensureMirrorSubs();
6634
6751
  }
6635
6752
  return enabled ? "✅ 摘要镜像已开启:桌面会话轮次完成后推送问答摘要" : "\uD83D\uDD07 摘要镜像已关闭(/status mirror on 重新开启)";
6636
6753
  },
6637
6754
  status() {
6638
- const subs = mirrorUnsubs.size;
6639
- return mirrorState.enabled ? `\uD83D\uDCCB 摘要镜像:开(已挂 ${subs} 个会话订阅)` : "\uD83D\uDCCB 摘要镜像:关(/status mirror on 开启)";
6755
+ if (!mirrorState.enabled)
6756
+ return "\uD83D\uDCCB 摘要镜像:关(/status mirror on 开启)";
6757
+ const desired = new Set(sessions.all().map((binding) => binding.sessionId));
6758
+ const actual = mirrorUnsubs.size;
6759
+ const aligned = desired.size === actual && [...desired].every((sessionId) => mirrorUnsubs.has(sessionId));
6760
+ return aligned ? "\uD83D\uDCCB 摘要镜像:开" : `⚠️ 摘要镜像:开 · 订阅对账异常(期望 ${desired.size} / 实际 ${actual})`;
6640
6761
  }
6641
6762
  };
6642
6763
  return {
@@ -6651,6 +6772,118 @@ function createMirror(deps) {
6651
6772
  };
6652
6773
  }
6653
6774
 
6775
+ // src/core/mirror-anchors.ts
6776
+ import {
6777
+ existsSync as existsSync9,
6778
+ mkdirSync as mkdirSync8,
6779
+ readFileSync as readFileSync10,
6780
+ renameSync as renameSync3,
6781
+ unlinkSync as unlinkSync3,
6782
+ writeFileSync as writeFileSync8
6783
+ } from "node:fs";
6784
+ import { dirname as dirname2 } from "node:path";
6785
+ import { randomUUID } from "node:crypto";
6786
+ var MIRROR_ANCHOR_TTL_MS = 24 * 60 * 60 * 1000;
6787
+ var MIRROR_ANCHOR_MAX_PER_USER = 500;
6788
+ function validEntry(value) {
6789
+ const entry = value;
6790
+ return !!entry && typeof entry.refIdx === "string" && !!entry.refIdx && typeof entry.messageId === "string" && !!entry.messageId && typeof entry.userId === "string" && !!entry.userId && typeof entry.sessionId === "string" && !!entry.sessionId && typeof entry.title === "string" && typeof entry.sentAt === "number" && Number.isFinite(entry.sentAt) && entry.sentAt > 0;
6791
+ }
6792
+ function pruneMirrorAnchorEntries(input, now = Date.now()) {
6793
+ const fresh = input.filter((entry) => validEntry(entry) && entry.sentAt <= now && now - entry.sentAt < MIRROR_ANCHOR_TTL_MS);
6794
+ const newestFirst = [...fresh].sort((a, b) => b.sentAt - a.sentAt);
6795
+ const counts = new Map;
6796
+ const seen = new Set;
6797
+ const retained = [];
6798
+ for (const entry of newestFirst) {
6799
+ const identity = `${entry.userId}\x00${entry.refIdx}`;
6800
+ if (seen.has(identity))
6801
+ continue;
6802
+ const count = counts.get(entry.userId) ?? 0;
6803
+ if (count >= MIRROR_ANCHOR_MAX_PER_USER)
6804
+ continue;
6805
+ seen.add(identity);
6806
+ counts.set(entry.userId, count + 1);
6807
+ retained.push(entry);
6808
+ }
6809
+ return retained.sort((a, b) => a.sentAt - b.sentAt);
6810
+ }
6811
+ function createMirrorAnchorStore(filePath) {
6812
+ let entries = [];
6813
+ function save(nextEntries = entries) {
6814
+ const document = { version: 1, entries: nextEntries };
6815
+ mkdirSync8(dirname2(filePath), { recursive: true });
6816
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
6817
+ try {
6818
+ writeFileSync8(temporary, JSON.stringify(document, null, 2), { mode: 384 });
6819
+ renameSync3(temporary, filePath);
6820
+ } catch (error) {
6821
+ try {
6822
+ unlinkSync3(temporary);
6823
+ } catch {}
6824
+ throw error;
6825
+ }
6826
+ }
6827
+ try {
6828
+ if (existsSync9(filePath)) {
6829
+ const parsed = JSON.parse(readFileSync10(filePath, "utf8").replace(/^\uFEFF/, ""));
6830
+ if (parsed.version !== 1 || !Array.isArray(parsed.entries))
6831
+ throw new Error("锚点文件格式无效");
6832
+ const loaded = parsed.entries.filter(validEntry);
6833
+ const pruned = pruneMirrorAnchorEntries(loaded);
6834
+ entries = pruned;
6835
+ if (loaded.length !== parsed.entries.length || pruned.length !== loaded.length)
6836
+ save();
6837
+ }
6838
+ } catch (error) {
6839
+ try {
6840
+ const backup = `${filePath}.corrupt-${Date.now()}`;
6841
+ renameSync3(filePath, backup);
6842
+ console.error(`[mirror-anchor] 锚点文件损坏,已保留诊断副本:${backup}`);
6843
+ } catch (backupError) {
6844
+ console.error("[mirror-anchor] 损坏文件备份失败:", backupError);
6845
+ }
6846
+ entries = [];
6847
+ console.error("[mirror-anchor] 锚点恢复失败,按空表 fail-closed:", error);
6848
+ }
6849
+ return {
6850
+ filePath,
6851
+ record(entry) {
6852
+ if (!validEntry(entry))
6853
+ throw new Error("摘要锚点字段不完整");
6854
+ const next = pruneMirrorAnchorEntries([
6855
+ ...entries.filter((item) => !(item.userId === entry.userId && item.refIdx === entry.refIdx)),
6856
+ entry
6857
+ ]);
6858
+ save(next);
6859
+ entries = next;
6860
+ },
6861
+ resolve(userId, refIdx, now = Date.now()) {
6862
+ if (!refIdx)
6863
+ return;
6864
+ const entry = entries.find((item) => item.userId === userId && item.refIdx === refIdx);
6865
+ if (!entry)
6866
+ return;
6867
+ if (entry.sentAt > now || now - entry.sentAt >= MIRROR_ANCHOR_TTL_MS) {
6868
+ const before = entries.length;
6869
+ entries = pruneMirrorAnchorEntries(entries, now);
6870
+ if (entries.length !== before) {
6871
+ try {
6872
+ save();
6873
+ } catch (error) {
6874
+ console.error("[mirror-anchor] 过期锚点清理失败:", error);
6875
+ }
6876
+ }
6877
+ return;
6878
+ }
6879
+ return { ...entry };
6880
+ },
6881
+ list() {
6882
+ return entries.map((entry) => ({ ...entry }));
6883
+ }
6884
+ };
6885
+ }
6886
+
6654
6887
  // src/core/error-rescue.ts
6655
6888
  function classifyProviderError(message) {
6656
6889
  const m = message.toLowerCase();
@@ -6826,7 +7059,7 @@ function parseGoalState(raw) {
6826
7059
  }
6827
7060
  }
6828
7061
  // src/core/permission.ts
6829
- import { existsSync as existsSync9, readFileSync as readFileSync10, writeFileSync as writeFileSync8 } from "fs";
7062
+ import { existsSync as existsSync10, readFileSync as readFileSync11, writeFileSync as writeFileSync9 } from "fs";
6830
7063
 
6831
7064
  // src/core/util.ts
6832
7065
  function truncate(value, max) {
@@ -6889,8 +7122,8 @@ function classifyApprovalReplyError(error) {
6889
7122
  var PENDING_PERM_FILE = storageFile("pending-permissions.json");
6890
7123
  function loadPendingPermMap(file = PENDING_PERM_FILE) {
6891
7124
  try {
6892
- if (existsSync9(file)) {
6893
- const raw = readFileSync10(file, "utf-8");
7125
+ if (existsSync10(file)) {
7126
+ const raw = readFileSync11(file, "utf-8");
6894
7127
  const obj = JSON.parse(raw);
6895
7128
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
6896
7129
  const out = {};
@@ -6919,7 +7152,7 @@ function savePendingPermMap(m, file = PENDING_PERM_FILE) {
6919
7152
  ...e.origin ? { origin: e.origin } : {}
6920
7153
  };
6921
7154
  }
6922
- writeFileSync8(file, JSON.stringify(out));
7155
+ writeFileSync9(file, JSON.stringify(out));
6923
7156
  } catch (error) {
6924
7157
  console.warn("[perm] 审批态落盘失败:", error instanceof Error ? error.message : error);
6925
7158
  }
@@ -7220,7 +7453,7 @@ function formatPermissionPrompt(request, mainSessionId, origin) {
7220
7453
  }
7221
7454
 
7222
7455
  // src/core/delivery.ts
7223
- import { existsSync as existsSync10, readFileSync as readFileSync11, writeFileSync as writeFileSync9, mkdirSync as mkdirSync8, renameSync as renameSync3, openSync, closeSync, unlinkSync as unlinkSync3, statSync as statSync5 } from "fs";
7456
+ import { existsSync as existsSync11, readFileSync as readFileSync12, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, renameSync as renameSync4, openSync, closeSync, unlinkSync as unlinkSync4, statSync as statSync5 } from "fs";
7224
7457
  import { join as join9 } from "path";
7225
7458
  import { createHash } from "node:crypto";
7226
7459
 
@@ -7473,23 +7706,58 @@ async function sendChunk(accessToken, ctx, mdText, plainText, msgSeq) {
7473
7706
  return await sendC2CMessage(accessToken, ctx.userId, plainText, ctx.msgId, msgSeq, false);
7474
7707
  }
7475
7708
  }
7709
+
7710
+ class PartialReplyError extends Error {
7711
+ receipts;
7712
+ failedChunkIndex;
7713
+ originalError;
7714
+ name = "PartialReplyError";
7715
+ constructor(receipts, failedChunkIndex, originalError) {
7716
+ super(`QQ 分片发送中断:第 ${failedChunkIndex + 1} 片失败,此前已成功 ${receipts.length} 片`);
7717
+ this.receipts = receipts;
7718
+ this.failedChunkIndex = failedChunkIndex;
7719
+ this.originalError = originalError;
7720
+ }
7721
+ }
7476
7722
  async function replyToQQ(accessToken, ctx, text, options) {
7477
7723
  const mdFormatted = formatForQQMarkdown(text);
7478
7724
  const plainFormatted = formatForQQ(text);
7479
- const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES);
7480
- const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES);
7725
+ const continuationPrefix = options?.continuationPrefix ?? "";
7726
+ const continuationBytes = utf8Bytes(continuationPrefix);
7727
+ if (continuationBytes >= Math.min(MARKDOWN_MAX_BYTES, PLAIN_MAX_BYTES) - 1024) {
7728
+ throw new Error("continuationPrefix 过长,无法为正文预留分片空间");
7729
+ }
7730
+ const mdChunks = splitMessage(mdFormatted, MARKDOWN_MAX_BYTES - continuationBytes).map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk);
7731
+ const plainChunks = splitMessage(plainFormatted, PLAIN_MAX_BYTES - continuationBytes).map((chunk, index) => index > 0 ? continuationPrefix + chunk : chunk);
7481
7732
  const delays = staggerDelays(mdChunks.length, options?.staggerMs ?? 0);
7482
- const ids = [];
7733
+ const receipts = [];
7483
7734
  for (let i = 0;i < mdChunks.length; i++) {
7484
7735
  if (i > 0 && delays[i - 1])
7485
7736
  await sleep4(delays[i - 1]);
7486
7737
  const msgSeq = getNextMsgSeq(ctx.msgId);
7487
7738
  const plainChunk = plainChunks[i] ?? plainChunks[plainChunks.length - 1] ?? mdChunks[i];
7488
- const res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq);
7489
- if (res?.id)
7490
- ids.push(res.id);
7739
+ let res;
7740
+ try {
7741
+ res = await sendChunk(accessToken, ctx, mdChunks[i], plainChunk, msgSeq);
7742
+ } catch (error) {
7743
+ if (receipts.length > 0)
7744
+ throw new PartialReplyError(receipts, i, error);
7745
+ throw error;
7746
+ }
7747
+ if (res?.id) {
7748
+ const receipt = {
7749
+ id: res.id,
7750
+ ...res.ext_info?.ref_idx ? { refIdx: res.ext_info.ref_idx } : {}
7751
+ };
7752
+ receipts.push(receipt);
7753
+ try {
7754
+ await options?.onReceipt?.(receipt);
7755
+ } catch (error) {
7756
+ console.error("[qq-sender] 分片回执回调失败:", error);
7757
+ }
7758
+ }
7491
7759
  }
7492
- return { chunks: mdChunks.length, ids };
7760
+ return { chunks: mdChunks.length, ids: receipts.map((receipt) => receipt.id), receipts };
7493
7761
  }
7494
7762
 
7495
7763
  // src/core/reply-limiter.ts
@@ -7617,8 +7885,8 @@ function extractEmbeddedQuote(event) {
7617
7885
  var DEFAULT_QUOTA_FILE = storageFile("quota.json");
7618
7886
  function loadQuotaMap(file) {
7619
7887
  try {
7620
- if (existsSync10(file)) {
7621
- const raw = readFileSync11(file, "utf-8");
7888
+ if (existsSync11(file)) {
7889
+ const raw = readFileSync12(file, "utf-8");
7622
7890
  const obj = JSON.parse(raw);
7623
7891
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
7624
7892
  const out = {};
@@ -7636,13 +7904,14 @@ function loadQuotaMap(file) {
7636
7904
  }
7637
7905
  function saveQuotaMap(file, m) {
7638
7906
  try {
7639
- writeFileSync9(file, JSON.stringify(Object.fromEntries(m)));
7907
+ writeFileSync10(file, JSON.stringify(Object.fromEntries(m)));
7640
7908
  } catch (error) {
7641
7909
  console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error);
7642
7910
  }
7643
7911
  }
7644
7912
  var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
7645
7913
  `;
7914
+ var PARTIAL_DELIVERY_NOTICE = "⚠️ 本轮消息仅部分送达。为避免重复,已阻止自动全文重发;完整结果请发 /history 查看,或重新提问。";
7646
7915
  var QQ_LIST_FORMAT_HINT = `
7647
7916
 
7648
7917
  (输出格式约定:本对话经 QQ 渲染,请用「1、2、3、」顿号或「-」无序列表代替 markdown 有序列表,避免表格;代码块不受影响可正常使用。)`;
@@ -7652,7 +7921,7 @@ function qqPromptHints() {
7652
7921
  const file = join9(storageRoot(), "qq-system-instructions.json");
7653
7922
  const st = statSync5(file);
7654
7923
  if (Date.now() - st.mtimeMs < 15 * 60000) {
7655
- const parsed = JSON.parse(readFileSync11(file, "utf-8"));
7924
+ const parsed = JSON.parse(readFileSync12(file, "utf-8"));
7656
7925
  if (parsed?.mode === "entry" || parsed?.mode === "hook")
7657
7926
  return "";
7658
7927
  }
@@ -7708,9 +7977,9 @@ function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TT
7708
7977
  function loadDeliveryAttempts() {
7709
7978
  const out = new Map;
7710
7979
  try {
7711
- if (!existsSync10(deliveryDedupeFile()))
7980
+ if (!existsSync11(deliveryDedupeFile()))
7712
7981
  return out;
7713
- const raw = JSON.parse(readFileSync11(deliveryDedupeFile(), "utf-8"));
7982
+ const raw = JSON.parse(readFileSync12(deliveryDedupeFile(), "utf-8"));
7714
7983
  const now = Date.now();
7715
7984
  for (const entry of raw) {
7716
7985
  if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
@@ -7722,14 +7991,14 @@ function loadDeliveryAttempts() {
7722
7991
  }
7723
7992
  function saveDeliveryAttempts(entries) {
7724
7993
  const raw = [...entries.values()].filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS).map((entry) => ({ key: entry.text, at: entry.at }));
7725
- mkdirSync8(join9(deliveryDedupeFile(), ".."), { recursive: true });
7994
+ mkdirSync9(join9(deliveryDedupeFile(), ".."), { recursive: true });
7726
7995
  const tmp = `${deliveryDedupeFile()}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
7727
7996
  try {
7728
- writeFileSync9(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
7729
- renameSync3(tmp, deliveryDedupeFile());
7997
+ writeFileSync10(tmp, JSON.stringify(raw, null, 2), { mode: 384 });
7998
+ renameSync4(tmp, deliveryDedupeFile());
7730
7999
  } catch (error) {
7731
8000
  try {
7732
- unlinkSync3(tmp);
8001
+ unlinkSync4(tmp);
7733
8002
  } catch {}
7734
8003
  throw error;
7735
8004
  }
@@ -7738,7 +8007,7 @@ var DELIVERY_LOCK_STALE_MS = 30000;
7738
8007
  var DELIVERY_LOCK_WAIT_MS = 5000;
7739
8008
  var deliverySleepArray = new Int32Array(new SharedArrayBuffer(4));
7740
8009
  function withDeliveryLock(fn) {
7741
- mkdirSync8(join9(deliveryDedupeFile(), ".."), { recursive: true });
8010
+ mkdirSync9(join9(deliveryDedupeFile(), ".."), { recursive: true });
7742
8011
  const lockPath = `${deliveryDedupeFile()}.lock`;
7743
8012
  const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
7744
8013
  const deadline = Date.now() + DELIVERY_LOCK_WAIT_MS;
@@ -7746,7 +8015,7 @@ function withDeliveryLock(fn) {
7746
8015
  try {
7747
8016
  const fd = openSync(lockPath, "wx", 384);
7748
8017
  try {
7749
- writeFileSync9(fd, token);
8018
+ writeFileSync10(fd, token);
7750
8019
  } finally {
7751
8020
  closeSync(fd);
7752
8021
  }
@@ -7754,7 +8023,7 @@ function withDeliveryLock(fn) {
7754
8023
  } catch (error) {
7755
8024
  try {
7756
8025
  if (Date.now() - statSync5(lockPath).mtimeMs > DELIVERY_LOCK_STALE_MS)
7757
- unlinkSync3(lockPath);
8026
+ unlinkSync4(lockPath);
7758
8027
  } catch {}
7759
8028
  if (Date.now() >= deadline)
7760
8029
  throw new Error(`同文投递锁等待超时: ${error instanceof Error ? error.message : error}`);
@@ -7765,8 +8034,8 @@ function withDeliveryLock(fn) {
7765
8034
  return fn();
7766
8035
  } finally {
7767
8036
  try {
7768
- if (readFileSync11(lockPath, "utf-8") === token)
7769
- unlinkSync3(lockPath);
8037
+ if (readFileSync12(lockPath, "utf-8") === token)
8038
+ unlinkSync4(lockPath);
7770
8039
  } catch {}
7771
8040
  }
7772
8041
  }
@@ -7819,6 +8088,7 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
7819
8088
  })();
7820
8089
  const pushQueues = new Map;
7821
8090
  const undelivered = new Set;
8091
+ const partialFailures = new WeakSet;
7822
8092
  const activeQuota = new Map;
7823
8093
  const passiveLimiter = new ReplyLimiter;
7824
8094
  const QUOTA_FILE = quotaFile ?? DEFAULT_QUOTA_FILE;
@@ -7875,7 +8145,21 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
7875
8145
  }
7876
8146
  }
7877
8147
  }
7878
- async function deliver(ctx, text) {
8148
+ function recordSent(scope, text, receipt) {
8149
+ recordMessage(scope, receipt.id, text);
8150
+ if (receipt.refIdx && receipt.refIdx !== receipt.id)
8151
+ recordMessage(scope, receipt.refIdx, text);
8152
+ }
8153
+ async function emitSent(onSent, receipt) {
8154
+ if (!onSent)
8155
+ return;
8156
+ try {
8157
+ await onSent(receipt);
8158
+ } catch (error) {
8159
+ console.error("[delivery] onSent 回执处理失败(QQ 消息已发送):", error);
8160
+ }
8161
+ }
8162
+ async function deliver(ctx, text, onSent, content) {
7879
8163
  if (ctx.anchorSessionId && pushGate && !pushGate(ctx.userId, ctx.anchorSessionId)) {
7880
8164
  console.log(`[push-gate] 出站拦截:绑定已切走 anchor=${ctx.anchorSessionId.slice(0, 12)}… user=${ctx.userId.slice(0, 8)}… chars=${text.length}`);
7881
8165
  return false;
@@ -7889,34 +8173,49 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
7889
8173
  const hadNotice = undelivered.delete(ctx.userId);
7890
8174
  const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text);
7891
8175
  try {
7892
- await deliverCore(ctx, body);
8176
+ await deliverCore(ctx, body, onSent, content);
7893
8177
  return true;
7894
8178
  } catch (error) {
8179
+ if (error instanceof PartialReplyError) {
8180
+ partialFailures.add(ctx);
8181
+ console.error(`[delivery] 分片部分失败,禁止全文降级 sent=${error.receipts.length} failedChunk=${error.failedChunkIndex + 1}`);
8182
+ try {
8183
+ await sendActive(ctx, PARTIAL_DELIVERY_NOTICE);
8184
+ } catch (alertError) {
8185
+ undelivered.add(ctx.userId);
8186
+ console.error("[delivery] 部分失败告警也未能送达:", alertError);
8187
+ }
8188
+ return false;
8189
+ }
7895
8190
  releaseDeliveryAttempt(ctx.userId, text, now);
7896
8191
  if (hadNotice)
7897
8192
  undelivered.add(ctx.userId);
7898
8193
  throw error;
7899
8194
  }
7900
8195
  }
7901
- async function deliverCore(ctx, text) {
8196
+ async function deliverCore(ctx, text, onSent, content) {
7902
8197
  const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null;
7903
8198
  if (passive?.shouldFallbackToProactive) {
7904
8199
  console.log(`[bridge] 被动回复${passive.fallbackReason === "expired" ? "窗口已过期" : "次数已耗尽"},直接走主动通道: msgId=${ctx.msgId}`);
7905
8200
  } else {
7906
8201
  try {
7907
- await sendReply(ctx, text);
8202
+ await sendReply(ctx, text, onSent, content);
7908
8203
  return;
7909
8204
  } catch (error) {
8205
+ if (error instanceof PartialReplyError)
8206
+ throw error;
7910
8207
  console.warn("[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:", error instanceof Error ? error.message : error);
7911
8208
  }
7912
8209
  }
7913
8210
  const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS);
7914
8211
  if (rideMsgId) {
7915
8212
  try {
7916
- const rideIds = await sendActive(ctx, text, rideMsgId);
8213
+ const rideReceipts = await sendActive(ctx, text, rideMsgId);
7917
8214
  passiveLimiter.record(rideMsgId);
7918
- for (const id of rideIds)
7919
- recordMessage(scopeKeyOf(ctx), id, text);
8215
+ for (const receipt of rideReceipts) {
8216
+ recordSent(scopeKeyOf(ctx), text, receipt);
8217
+ await emitSent(onSent, receipt);
8218
+ }
7920
8219
  console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`);
7921
8220
  return;
7922
8221
  } catch {
@@ -7940,15 +8239,17 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
7940
8239
  }
7941
8240
  throw new Error("主动消息已达 QQ 官方日上限,本条无法送达");
7942
8241
  }
7943
- const activeIds = await sendActive(ctx, text);
7944
- for (const id of activeIds)
7945
- recordMessage(scopeKeyOf(ctx), id, text);
8242
+ const activeReceipts = await sendActive(ctx, text);
8243
+ for (const receipt of activeReceipts) {
8244
+ recordSent(scopeKeyOf(ctx), text, receipt);
8245
+ await emitSent(onSent, receipt);
8246
+ }
7946
8247
  q.count++;
7947
8248
  saveQuotaMap(QUOTA_FILE, activeQuota);
7948
8249
  }
7949
- async function safeDeliver(c, text) {
8250
+ async function safeDeliver(c, text, onSent, content) {
7950
8251
  try {
7951
- return await deliver(c, text);
8252
+ return await deliver(c, text, onSent, content);
7952
8253
  } catch (error) {
7953
8254
  undelivered.add(c.userId);
7954
8255
  console.error("[bridge] 消息无法送达(被动+主动均失败):", error);
@@ -7967,58 +8268,76 @@ function createDelivery(config, lastCtx, pushGate, quotaFile) {
7967
8268
  const seq = getNextMsgSeq(passiveMsgId ?? "");
7968
8269
  const isGroup = ctx.type === "group" && ctx.groupId;
7969
8270
  const mdText = normalizeOutboundMarkdown(text);
7970
- const record = (ids) => {
7971
- if (!passiveMsgId && ids.length > 0)
8271
+ const record = (response) => {
8272
+ const receipts = response?.id ? [{
8273
+ id: response.id,
8274
+ ...response.ext_info?.ref_idx ? { refIdx: response.ext_info.ref_idx } : {}
8275
+ }] : [];
8276
+ if (!passiveMsgId && receipts.length > 0)
7972
8277
  logActiveSend(activeMinuteLog, ctx.userId, Date.now());
7973
- return ids;
8278
+ return receipts;
7974
8279
  };
7975
8280
  try {
7976
8281
  if (isGroup) {
7977
8282
  const r = await sendGroupMessage(token, ctx.groupId, mdText, passiveMsgId, seq, true);
7978
- return record(r?.id ? [r.id] : []);
8283
+ return record(r);
7979
8284
  }
7980
8285
  const r = await sendC2CMessage(token, ctx.userId, mdText, passiveMsgId, seq, true);
7981
- return record(r?.id ? [r.id] : []);
8286
+ return record(r);
7982
8287
  } catch (error) {
7983
8288
  console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error);
7984
8289
  }
7985
8290
  if (isGroup) {
7986
8291
  const r = await sendGroupMessage(token, ctx.groupId, text, passiveMsgId, seq, false);
7987
- return record(r?.id ? [r.id] : []);
8292
+ return record(r);
7988
8293
  }
7989
8294
  const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false);
7990
- return record(r?.id ? [r.id] : []);
8295
+ return record(r);
7991
8296
  }
7992
- async function sendReply(ctx, text) {
8297
+ async function sendReply(ctx, text, onSent, content) {
7993
8298
  const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret);
8299
+ const scope = scopeKeyOf(ctx);
7994
8300
  const result = await replyToQQ(accessToken, ctx, text, {
7995
- staggerMs: STREAM_STAGGER_MS
8301
+ staggerMs: STREAM_STAGGER_MS,
8302
+ continuationPrefix: content?.continuationPrefix,
8303
+ onReceipt: async (receipt) => {
8304
+ recordSent(scope, text, receipt);
8305
+ await emitSent(onSent, receipt);
8306
+ }
7996
8307
  });
7997
8308
  if (ctx.msgId) {
7998
8309
  for (let i = 0;i < result.chunks; i++)
7999
8310
  passiveLimiter.record(ctx.msgId);
8000
8311
  }
8001
- const scope = scopeKeyOf(ctx);
8002
- for (const id of result.ids)
8003
- recordMessage(scope, id, text);
8004
8312
  }
8005
- return { enqueuePush, deliver, safeDeliver, sendReply };
8313
+ return {
8314
+ enqueuePush,
8315
+ deliver,
8316
+ safeDeliver,
8317
+ sendReply,
8318
+ consumePartialFailure(ctx) {
8319
+ if (!partialFailures.has(ctx))
8320
+ return false;
8321
+ partialFailures.delete(ctx);
8322
+ return true;
8323
+ }
8324
+ };
8006
8325
  }
8007
8326
 
8008
8327
  // src/core/outbox.ts
8009
8328
  import {
8010
8329
  closeSync as closeSync2,
8011
- existsSync as existsSync11,
8012
- mkdirSync as mkdirSync9,
8330
+ existsSync as existsSync12,
8331
+ mkdirSync as mkdirSync10,
8013
8332
  openSync as openSync2,
8014
- readFileSync as readFileSync12,
8015
- renameSync as renameSync4,
8333
+ readFileSync as readFileSync13,
8334
+ renameSync as renameSync5,
8016
8335
  statSync as statSync6,
8017
- unlinkSync as unlinkSync4,
8018
- writeFileSync as writeFileSync10
8336
+ unlinkSync as unlinkSync5,
8337
+ writeFileSync as writeFileSync11
8019
8338
  } from "node:fs";
8020
- import { dirname as dirname2 } from "node:path";
8021
- import { randomUUID } from "node:crypto";
8339
+ import { dirname as dirname3 } from "node:path";
8340
+ import { randomUUID as randomUUID2 } from "node:crypto";
8022
8341
  var OUTBOX_SENT_RETENTION_MS = 24 * 60 * 60 * 1000;
8023
8342
  var OUTBOX_SENT_RETENTION_LIMIT = 20;
8024
8343
  var OUTBOX_DEFAULT_RETRY_BASE_MS = 1000;
@@ -8053,22 +8372,22 @@ function delay(ms) {
8053
8372
  return new Promise((resolve) => setTimeout(resolve, ms));
8054
8373
  }
8055
8374
  function atomicWrite(filePath, document) {
8056
- mkdirSync9(dirname2(filePath), { recursive: true });
8057
- const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
8375
+ mkdirSync10(dirname3(filePath), { recursive: true });
8376
+ const temporary = `${filePath}.${process.pid}.${randomUUID2()}.tmp`;
8058
8377
  try {
8059
- writeFileSync10(temporary, JSON.stringify(document, null, 2), { mode: 384 });
8060
- renameSync4(temporary, filePath);
8378
+ writeFileSync11(temporary, JSON.stringify(document, null, 2), { mode: 384 });
8379
+ renameSync5(temporary, filePath);
8061
8380
  } catch (error) {
8062
8381
  try {
8063
- unlinkSync4(temporary);
8382
+ unlinkSync5(temporary);
8064
8383
  } catch {}
8065
8384
  throw error;
8066
8385
  }
8067
8386
  }
8068
8387
  function readDocument(filePath, now) {
8069
- if (!existsSync11(filePath))
8388
+ if (!existsSync12(filePath))
8070
8389
  return { version: 1, entries: [] };
8071
- const raw = JSON.parse(readFileSync12(filePath, "utf8"));
8390
+ const raw = JSON.parse(readFileSync13(filePath, "utf8"));
8072
8391
  if (Array.isArray(raw)) {
8073
8392
  return { version: 1, entries: pruneOutboxEntries(raw, now) };
8074
8393
  }
@@ -8091,7 +8410,7 @@ function createOutbox(options = {}) {
8091
8410
  const leaseMs = positive(options.leaseMs, DEFAULT_LEASE_MS, "leaseMs");
8092
8411
  const lockWaitMs = positive(options.lockWaitMs, DEFAULT_LOCK_WAIT_MS, "lockWaitMs");
8093
8412
  const lockStaleMs = positive(options.lockStaleMs, DEFAULT_LOCK_STALE_MS, "lockStaleMs");
8094
- const owner = `${process.pid}:${randomUUID()}`;
8413
+ const owner = `${process.pid}:${randomUUID2()}`;
8095
8414
  const handlers = new Map;
8096
8415
  const inFlight = new Map;
8097
8416
  const automatic = new Set;
@@ -8099,15 +8418,15 @@ function createOutbox(options = {}) {
8099
8418
  let stopped = false;
8100
8419
  let flushing;
8101
8420
  function withLock(fn) {
8102
- mkdirSync9(dirname2(filePath), { recursive: true });
8421
+ mkdirSync10(dirname3(filePath), { recursive: true });
8103
8422
  const lockPath = `${filePath}.lock`;
8104
- const token = `${owner}:${Date.now()}:${randomUUID()}`;
8423
+ const token = `${owner}:${Date.now()}:${randomUUID2()}`;
8105
8424
  const deadline = Date.now() + lockWaitMs;
8106
8425
  for (;; ) {
8107
8426
  try {
8108
8427
  const fd = openSync2(lockPath, "wx", 384);
8109
8428
  try {
8110
- writeFileSync10(fd, token);
8429
+ writeFileSync11(fd, token);
8111
8430
  } finally {
8112
8431
  closeSync2(fd);
8113
8432
  }
@@ -8115,7 +8434,7 @@ function createOutbox(options = {}) {
8115
8434
  } catch (error) {
8116
8435
  try {
8117
8436
  if (Date.now() - statSync6(lockPath).mtimeMs > lockStaleMs)
8118
- unlinkSync4(lockPath);
8437
+ unlinkSync5(lockPath);
8119
8438
  } catch {}
8120
8439
  if (Date.now() >= deadline)
8121
8440
  throw new Error(`Outbox 锁等待超时: ${errorText(error)}`);
@@ -8126,8 +8445,8 @@ function createOutbox(options = {}) {
8126
8445
  return fn();
8127
8446
  } finally {
8128
8447
  try {
8129
- if (readFileSync12(lockPath, "utf8") === token)
8130
- unlinkSync4(lockPath);
8448
+ if (readFileSync13(lockPath, "utf8") === token)
8449
+ unlinkSync5(lockPath);
8131
8450
  } catch {}
8132
8451
  }
8133
8452
  }
@@ -8189,7 +8508,7 @@ function createOutbox(options = {}) {
8189
8508
  if (!handler)
8190
8509
  return clone(handlerlessSnapshot);
8191
8510
  const now = Date.now();
8192
- const token = `${owner}:${randomUUID()}`;
8511
+ const token = `${owner}:${randomUUID2()}`;
8193
8512
  const claimed = withLock(() => {
8194
8513
  const document = readDocument(filePath, now);
8195
8514
  const entry = document.entries.find((candidate) => candidate.id === id);
@@ -8349,7 +8668,7 @@ function createOutbox(options = {}) {
8349
8668
  const persistedCtx = jsonSnapshot(input.ctx, "ctx");
8350
8669
  const persistedPayload = jsonSnapshot(input.payload, "payload");
8351
8670
  const now = Date.now();
8352
- const id = input.id ?? randomUUID();
8671
+ const id = input.id ?? randomUUID2();
8353
8672
  const entry = mutate((entries) => {
8354
8673
  const existing = entries.find((candidate) => candidate.id === id);
8355
8674
  if (existing)
@@ -8426,7 +8745,7 @@ function createNotifySink(options) {
8426
8745
  return { skipped: "no-text" };
8427
8746
  }
8428
8747
  const ctx = entry.ctx;
8429
- return options.deliver(ctx, text).then(() => ({ delivered: true, text: text.slice(0, 120) }));
8748
+ return options.deliver(ctx, text).then((delivered) => ({ delivered, text: text.slice(0, 120) }));
8430
8749
  });
8431
8750
  outbox.start({ recover: true, maxAttempts }).catch((error) => {
8432
8751
  console.error("[notify-sink] 启动恢复失败:", error instanceof Error ? error.message : error);
@@ -8519,16 +8838,16 @@ function handleApprovalInteraction(event, gate) {
8519
8838
  // src/core/form-journal.ts
8520
8839
  import {
8521
8840
  closeSync as closeSync3,
8522
- existsSync as existsSync12,
8523
- mkdirSync as mkdirSync10,
8841
+ existsSync as existsSync13,
8842
+ mkdirSync as mkdirSync11,
8524
8843
  openSync as openSync3,
8525
- readFileSync as readFileSync13,
8526
- renameSync as renameSync5,
8844
+ readFileSync as readFileSync14,
8845
+ renameSync as renameSync6,
8527
8846
  statSync as statSync7,
8528
- unlinkSync as unlinkSync5,
8529
- writeFileSync as writeFileSync11
8847
+ unlinkSync as unlinkSync6,
8848
+ writeFileSync as writeFileSync12
8530
8849
  } from "fs";
8531
- import { dirname as dirname3 } from "path";
8850
+ import { dirname as dirname4 } from "path";
8532
8851
  var LOCK_STALE_MS = 30000;
8533
8852
  var LOCK_WAIT_MS = 5000;
8534
8853
  var sleepArray2 = new Int32Array(new SharedArrayBuffer(4));
@@ -8587,9 +8906,9 @@ function snapshot(entry) {
8587
8906
  function createFormJournal(path = defaultFormJournalPath()) {
8588
8907
  function read() {
8589
8908
  try {
8590
- if (!existsSync12(path))
8909
+ if (!existsSync13(path))
8591
8910
  return [];
8592
- const raw = JSON.parse(readFileSync13(path, "utf-8"));
8911
+ const raw = JSON.parse(readFileSync14(path, "utf-8"));
8593
8912
  const values = Array.isArray(raw) ? raw : raw?.version === 1 && Array.isArray(raw.entries) ? raw.entries : [];
8594
8913
  const byUser = new Map;
8595
8914
  for (const value of values) {
@@ -8607,21 +8926,21 @@ function createFormJournal(path = defaultFormJournalPath()) {
8607
8926
  }
8608
8927
  }
8609
8928
  function write(entries) {
8610
- mkdirSync10(dirname3(path), { recursive: true });
8929
+ mkdirSync11(dirname4(path), { recursive: true });
8611
8930
  const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
8612
8931
  const payload = { version: 1, entries: entries.map(snapshot) };
8613
8932
  try {
8614
- writeFileSync11(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
8615
- renameSync5(tmp, path);
8933
+ writeFileSync12(tmp, JSON.stringify(payload, null, 2), { mode: 384 });
8934
+ renameSync6(tmp, path);
8616
8935
  } catch (error) {
8617
8936
  try {
8618
- unlinkSync5(tmp);
8937
+ unlinkSync6(tmp);
8619
8938
  } catch {}
8620
8939
  throw error;
8621
8940
  }
8622
8941
  }
8623
8942
  function withLock(fn) {
8624
- mkdirSync10(dirname3(path), { recursive: true });
8943
+ mkdirSync11(dirname4(path), { recursive: true });
8625
8944
  const lockPath = `${path}.lock`;
8626
8945
  const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
8627
8946
  const deadline = Date.now() + LOCK_WAIT_MS;
@@ -8629,7 +8948,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
8629
8948
  try {
8630
8949
  const fd = openSync3(lockPath, "wx", 384);
8631
8950
  try {
8632
- writeFileSync11(fd, token);
8951
+ writeFileSync12(fd, token);
8633
8952
  } finally {
8634
8953
  closeSync3(fd);
8635
8954
  }
@@ -8637,7 +8956,7 @@ function createFormJournal(path = defaultFormJournalPath()) {
8637
8956
  } catch (error) {
8638
8957
  try {
8639
8958
  if (Date.now() - statSync7(lockPath).mtimeMs > LOCK_STALE_MS)
8640
- unlinkSync5(lockPath);
8959
+ unlinkSync6(lockPath);
8641
8960
  } catch {}
8642
8961
  if (Date.now() >= deadline) {
8643
8962
  throw new Error(`表单台账锁等待超时: ${error instanceof Error ? error.message : error}`);
@@ -8649,8 +8968,8 @@ function createFormJournal(path = defaultFormJournalPath()) {
8649
8968
  return fn();
8650
8969
  } finally {
8651
8970
  try {
8652
- if (readFileSync13(lockPath, "utf-8") === token)
8653
- unlinkSync5(lockPath);
8971
+ if (readFileSync14(lockPath, "utf-8") === token)
8972
+ unlinkSync6(lockPath);
8654
8973
  } catch {}
8655
8974
  }
8656
8975
  }
@@ -9216,7 +9535,7 @@ function createFormBridge(deps) {
9216
9535
  }
9217
9536
 
9218
9537
  // src/core/inflight-journal.ts
9219
- import { existsSync as existsSync13, readFileSync as readFileSync14, writeFileSync as writeFileSync12, mkdirSync as mkdirSync11, renameSync as renameSync6, openSync as openSync4, closeSync as closeSync4, unlinkSync as unlinkSync6, statSync as statSync8 } from "fs";
9538
+ import { existsSync as existsSync14, readFileSync as readFileSync15, writeFileSync as writeFileSync13, mkdirSync as mkdirSync12, renameSync as renameSync7, openSync as openSync4, closeSync as closeSync4, unlinkSync as unlinkSync7, statSync as statSync8 } from "fs";
9220
9539
  import { join as join10 } from "path";
9221
9540
 
9222
9541
  // src/core/inbound-dedupe.ts
@@ -9256,8 +9575,8 @@ function load(file) {
9256
9575
  let entries = [];
9257
9576
  const path = journalPath(file);
9258
9577
  try {
9259
- if (existsSync13(path)) {
9260
- const raw = JSON.parse(readFileSync14(path, "utf-8"));
9578
+ if (existsSync14(path)) {
9579
+ const raw = JSON.parse(readFileSync15(path, "utf-8"));
9261
9580
  if (Array.isArray(raw))
9262
9581
  entries = raw;
9263
9582
  }
@@ -9268,15 +9587,15 @@ function load(file) {
9268
9587
  }
9269
9588
  function save(file, entries) {
9270
9589
  const path = journalPath(file);
9271
- mkdirSync11(join10(path, ".."), { recursive: true });
9590
+ mkdirSync12(join10(path, ".."), { recursive: true });
9272
9591
  const retained = pruneInflightEntries(entries);
9273
9592
  const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
9274
9593
  try {
9275
- writeFileSync12(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
9276
- renameSync6(tmp, path);
9594
+ writeFileSync13(tmp, JSON.stringify(retained, null, 2), { mode: 384 });
9595
+ renameSync7(tmp, path);
9277
9596
  } catch (error) {
9278
9597
  try {
9279
- unlinkSync6(tmp);
9598
+ unlinkSync7(tmp);
9280
9599
  } catch {}
9281
9600
  throw error;
9282
9601
  }
@@ -9286,7 +9605,7 @@ var JOURNAL_LOCK_WAIT_MS = 5000;
9286
9605
  var sleepArray3 = new Int32Array(new SharedArrayBuffer(4));
9287
9606
  function withJournalLock(file, fn) {
9288
9607
  const path = journalPath(file);
9289
- mkdirSync11(join10(path, ".."), { recursive: true });
9608
+ mkdirSync12(join10(path, ".."), { recursive: true });
9290
9609
  const lockPath = `${path}.lock`;
9291
9610
  const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
9292
9611
  const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
@@ -9294,7 +9613,7 @@ function withJournalLock(file, fn) {
9294
9613
  try {
9295
9614
  const fd = openSync4(lockPath, "wx", 384);
9296
9615
  try {
9297
- writeFileSync12(fd, token);
9616
+ writeFileSync13(fd, token);
9298
9617
  } finally {
9299
9618
  closeSync4(fd);
9300
9619
  }
@@ -9302,7 +9621,7 @@ function withJournalLock(file, fn) {
9302
9621
  } catch (error) {
9303
9622
  try {
9304
9623
  if (Date.now() - statSync8(lockPath).mtimeMs > JOURNAL_LOCK_STALE_MS)
9305
- unlinkSync6(lockPath);
9624
+ unlinkSync7(lockPath);
9306
9625
  } catch {}
9307
9626
  if (Date.now() >= deadline) {
9308
9627
  throw new Error(`在途台账锁等待超时: ${error instanceof Error ? error.message : error}`);
@@ -9314,8 +9633,8 @@ function withJournalLock(file, fn) {
9314
9633
  return fn();
9315
9634
  } finally {
9316
9635
  try {
9317
- if (readFileSync14(lockPath, "utf-8") === token)
9318
- unlinkSync6(lockPath);
9636
+ if (readFileSync15(lockPath, "utf-8") === token)
9637
+ unlinkSync7(lockPath);
9319
9638
  } catch {}
9320
9639
  }
9321
9640
  }
@@ -10018,7 +10337,7 @@ function formatStatusLine(view) {
10018
10337
  init_log_rotate();
10019
10338
 
10020
10339
  // src/core/instance-lock.ts
10021
- import { openSync as openSync5, readFileSync as readFileSync15, readdirSync as readdirSync2, writeFileSync as writeFileSync13, closeSync as closeSync5, unlinkSync as unlinkSync7, statSync as statSync9, utimesSync, mkdirSync as mkdirSync12 } from "fs";
10340
+ import { openSync as openSync5, readFileSync as readFileSync16, readdirSync as readdirSync2, writeFileSync as writeFileSync14, closeSync as closeSync5, unlinkSync as unlinkSync8, statSync as statSync9, utimesSync, mkdirSync as mkdirSync13 } from "fs";
10022
10341
  import { join as join11 } from "path";
10023
10342
  import { homedir as homedir6 } from "os";
10024
10343
  var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
@@ -10037,18 +10356,18 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
10037
10356
  const heartbeatMs = opts?.heartbeatMs ?? LOCK_UPDATE_MS;
10038
10357
  const selfCheckMs = opts?.selfCheckMs ?? LOCK_SELF_CHECK_MS;
10039
10358
  try {
10040
- mkdirSync12(join11(path, ".."), { recursive: true });
10359
+ mkdirSync13(join11(path, ".."), { recursive: true });
10041
10360
  const fd = openSync5(path, "wx");
10042
- writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
10361
+ writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
10043
10362
  closeSync5(fd);
10044
10363
  } catch {
10045
10364
  try {
10046
10365
  const age = Date.now() - statSync9(path).mtimeMs;
10047
10366
  if (age <= staleMs)
10048
10367
  return null;
10049
- unlinkSync7(path);
10368
+ unlinkSync8(path);
10050
10369
  const fd = openSync5(path, "wx");
10051
- writeFileSync13(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
10370
+ writeFileSync14(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now(), tookOverStale: true }));
10052
10371
  closeSync5(fd);
10053
10372
  console.warn(`[instance-lock] 检测到僵尸锁(${Math.round(age / 1000)}s 无心跳),已接管`);
10054
10373
  } catch {
@@ -10063,7 +10382,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
10063
10382
  heartbeat.unref?.();
10064
10383
  const selfCheck = setInterval(() => {
10065
10384
  try {
10066
- const holder = JSON.parse(readFileSync15(path, "utf-8")).pid;
10385
+ const holder = JSON.parse(readFileSync16(path, "utf-8")).pid;
10067
10386
  if (holder === process.pid)
10068
10387
  return;
10069
10388
  try {
@@ -10090,7 +10409,7 @@ function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS2, opts) {
10090
10409
  clearInterval(heartbeat);
10091
10410
  clearInterval(selfCheck);
10092
10411
  try {
10093
- unlinkSync7(path);
10412
+ unlinkSync8(path);
10094
10413
  } catch {}
10095
10414
  }
10096
10415
  };
@@ -10134,7 +10453,7 @@ var DEFAULT_SUPERVISOR_POLICY = {
10134
10453
  };
10135
10454
 
10136
10455
  // src/core/send-requests.ts
10137
- import { existsSync as existsSync14, mkdirSync as mkdirSync13, readdirSync as readdirSync3, readFileSync as readFileSync16, renameSync as renameSync7, statSync as statSync10, writeFileSync as writeFileSync14 } from "node:fs";
10456
+ import { existsSync as existsSync15, mkdirSync as mkdirSync14, readdirSync as readdirSync3, readFileSync as readFileSync17, renameSync as renameSync8, statSync as statSync10, writeFileSync as writeFileSync15 } from "node:fs";
10138
10457
  import { join as join12 } from "node:path";
10139
10458
  function sendRequestsDirFor(appId) {
10140
10459
  return join12(storageRoot(appId), "send-requests");
@@ -10144,18 +10463,18 @@ function startSendRequestConsumer(opts) {
10144
10463
  const intervalMs = opts.intervalMs ?? 1500;
10145
10464
  const log = opts.log ?? (() => {});
10146
10465
  const seen = new Map;
10147
- mkdirSync13(dir, { recursive: true });
10466
+ mkdirSync14(dir, { recursive: true });
10148
10467
  for (const f of readdirSync3(dir)) {
10149
10468
  if (!f.endsWith(".result.json"))
10150
10469
  continue;
10151
10470
  const full = join12(dir, f);
10152
10471
  try {
10153
- const result = JSON.parse(readFileSync16(full, "utf-8"));
10472
+ const result = JSON.parse(readFileSync17(full, "utf-8"));
10154
10473
  const key = result.dedupeKey;
10155
10474
  if (key)
10156
10475
  seen.set(key, result);
10157
10476
  if (Date.now() - statSync10(full).mtimeMs > 24 * 60 * 60000)
10158
- renameSync7(full, full + ".old");
10477
+ renameSync8(full, full + ".old");
10159
10478
  } catch {}
10160
10479
  }
10161
10480
  const sendFile = opts.sendFile ?? ((ctx, path) => sendLocalFile(ctx, path, { getToken: opts.getToken }));
@@ -10163,9 +10482,9 @@ function startSendRequestConsumer(opts) {
10163
10482
  const full = join12(dir, file);
10164
10483
  let req;
10165
10484
  try {
10166
- req = JSON.parse(readFileSync16(full, "utf-8"));
10485
+ req = JSON.parse(readFileSync17(full, "utf-8"));
10167
10486
  } catch {
10168
- renameSync7(full, full + ".bad.json");
10487
+ renameSync8(full, full + ".bad.json");
10169
10488
  log(`[send-requests] 坏请求已隔离: ${file}`);
10170
10489
  return;
10171
10490
  }
@@ -10185,9 +10504,9 @@ function startSendRequestConsumer(opts) {
10185
10504
  seen.set(req.dedupeKey, { ...result, dedupeKey: req.dedupeKey });
10186
10505
  }
10187
10506
  const payload = JSON.stringify({ ...result, dedupeKey: req.dedupeKey });
10188
- writeFileSync14(join12(dir, `${req.id}.result.tmp`), payload, "utf-8");
10189
- renameSync7(join12(dir, `${req.id}.result.tmp`), join12(dir, `${req.id}.result.json`));
10190
- renameSync7(full, full + ".done");
10507
+ writeFileSync15(join12(dir, `${req.id}.result.tmp`), payload, "utf-8");
10508
+ renameSync8(join12(dir, `${req.id}.result.tmp`), join12(dir, `${req.id}.result.json`));
10509
+ renameSync8(full, full + ".done");
10191
10510
  log(`[send-requests] ${result.ok ? "已发送" : "发送失败"}${result.deduped ? "(去重)" : ""} user=${req.userId.slice(0, 8)}… path=${req.path}`);
10192
10511
  }
10193
10512
  const timer = setInterval(() => {
@@ -10212,6 +10531,33 @@ function isSessionBusyError(error) {
10212
10531
  const message = error instanceof Error ? error.message : String(error);
10213
10532
  return /active prompt|[-−]32603/.test(message);
10214
10533
  }
10534
+ function isMirrorDigestText(text) {
10535
+ let value = text?.trim() ?? "";
10536
+ if (value.startsWith(UNDELIVERED_NOTICE.trim())) {
10537
+ value = value.slice(UNDELIVERED_NOTICE.trim().length).trimStart();
10538
+ }
10539
+ return value.startsWith("\uD83D\uDCCB 桌面问答摘要") || value.startsWith("\uD83C\uDFAF 目标续跑摘要") || value.startsWith("\uD83D\uDCCB 摘要续") || value.startsWith("\uD83C\uDFAF 摘要续");
10540
+ }
10541
+ function commandNeedsMirrorAnchorGate(content) {
10542
+ const match = content.trim().match(/^\/(queue|amend|goal|btw)\b([\s\S]*)$/i);
10543
+ if (!match)
10544
+ return false;
10545
+ const args = (match[2] ?? "").trim();
10546
+ if (!args)
10547
+ return false;
10548
+ if (match[1]?.toLowerCase() === "queue" && /^(?:all(?:\s+\d+)?|clear|drop\s+\d+|\d+)$/i.test(args)) {
10549
+ return false;
10550
+ }
10551
+ return true;
10552
+ }
10553
+ function decideMirrorAnchorGate(input) {
10554
+ if (input.anchor) {
10555
+ return input.currentSessionId && input.anchor.sessionId === input.currentSessionId ? { kind: "match", anchor: input.anchor } : { kind: "conflict", anchor: input.anchor };
10556
+ }
10557
+ if (isMirrorDigestText(input.quoteText))
10558
+ return { kind: "unknown" };
10559
+ return { kind: "pass" };
10560
+ }
10215
10561
  function evictableIdleSessions(lastActivity, watched, now, idleMs) {
10216
10562
  const out = [];
10217
10563
  for (const [sid, at] of lastActivity) {
@@ -10385,6 +10731,7 @@ function finalAnswerText(msgs, promptId, baseline) {
10385
10731
  function createBridge(config, client, sessions, storageAppId) {
10386
10732
  const roleFile = (name) => storageFile(name, storageAppId);
10387
10733
  const inflight = createInflightJournal(storageAppId ? roleFile("inflight.json") : undefined);
10734
+ const mirrorAnchors = createMirrorAnchorStore(roleFile("mirror-anchors.json"));
10388
10735
  const ackReceiptEnabled = /^(1|true|on)$/i.test(process.env.QQ_ACK_RECEIPT ?? "");
10389
10736
  const busyUsers = new Set;
10390
10737
  const laneOf = (userId, sessionId) => laneKeyOf(userId, sessionId);
@@ -10732,7 +11079,7 @@ ${promptBody}` : promptBody) + qqPromptHints() + hint;
10732
11079
  return sid ? `\uD83D\uDC41 观察中:${sid}` : "未开启观察";
10733
11080
  }
10734
11081
  };
10735
- const { enqueuePush, safeDeliver, sendReply, deliver } = createDelivery(config, lastCtx, isBoundSession, storageAppId ? roleFile("quota.json") : undefined);
11082
+ const { enqueuePush, safeDeliver, sendReply, deliver, consumePartialFailure } = createDelivery(config, lastCtx, isBoundSession, storageAppId ? roleFile("quota.json") : undefined);
10736
11083
  const notifyUser = async (ctx, text) => {
10737
11084
  if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
10738
11085
  console.log(`[push-gate] 通知拦截:绑定已切走 anchor=${ctx.anchorSessionId.slice(0, 12)}… chars=${text.length}`);
@@ -10744,6 +11091,37 @@ ${promptBody}` : promptBody) + qqPromptHints() + hint;
10744
11091
  console.warn("[bridge] 通知发送失败(不阻断主流程):", toErrorMessage2(error));
10745
11092
  }
10746
11093
  };
11094
+ const mirrorQuoteCache = new WeakMap;
11095
+ function quoteContextOf(ctx) {
11096
+ const cached = mirrorQuoteCache.get(ctx);
11097
+ if (cached)
11098
+ return cached;
11099
+ const embedded = extractEmbeddedQuote(ctx.rawEvent);
11100
+ const quoted = embedded ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null);
11101
+ const result = { embedded, quoted };
11102
+ mirrorQuoteCache.set(ctx, result);
11103
+ return result;
11104
+ }
11105
+ function mirrorAnchorDecision(ctx, currentSessionId) {
11106
+ const { quoted } = quoteContextOf(ctx);
11107
+ const anchor = mirrorAnchors.resolve(ctx.userId, ctx.referencedMsgId);
11108
+ return decideMirrorAnchorGate({ anchor, quoteText: quoted, currentSessionId });
11109
+ }
11110
+ function anchorRejectText(decision, currentSessionId, userId) {
11111
+ if (decision.kind === "unknown") {
11112
+ return "⚠️ 无法确认这条旧摘要所属会话,本次未发送。请去掉引用后重发,或先通过 /sessions 切换到摘要所属会话。";
11113
+ }
11114
+ const source = `${clipDigestTitle(redactSecrets(decision.anchor.title))}(${digestSessionLabel(decision.anchor.sessionId)})`;
11115
+ const current = sessions.getSession(userId);
11116
+ const currentLabel = currentSessionId ? `${clipDigestTitle(redactSecrets(current?.title ?? ""))}(${digestSessionLabel(currentSessionId)})` : "无绑定会话";
11117
+ return `⚠️ 这条回复引用的是 ${source} 的摘要,当前绑定为 ${currentLabel}。
11118
+ 为避免误操作,本次未发送。请用 /sessions 切回该会话后重发;或去掉引用,明确发送到当前会话。`;
11119
+ }
11120
+ async function rejectMirrorAnchor(ctx, decision, currentSessionId) {
11121
+ const anchor = decision.kind === "conflict" ? decision.anchor.sessionId : "unknown";
11122
+ console.log(`[anchor-gate] result=${decision.kind} user=${ctx.userId.slice(0, 8)}… anchor=${anchor === "unknown" ? anchor : digestSessionLabel(anchor)} current=${currentSessionId ? digestSessionLabel(currentSessionId) : "∅"}`);
11123
+ await notifyUser({ ...ctx, anchorSessionId: undefined }, anchorRejectText(decision, currentSessionId, ctx.userId));
11124
+ }
10747
11125
  const cronScheduler = new ReminderScheduler;
10748
11126
  const goalStates = new Map;
10749
11127
  const goalKickoffs = new Map;
@@ -10804,6 +11182,7 @@ ${parsed.message.slice(0, 400)}
10804
11182
  bgWaits,
10805
11183
  busyUsers,
10806
11184
  settingsFile: storageAppId ? roleFile("settings.json") : undefined,
11185
+ anchorStore: mirrorAnchors,
10807
11186
  onDigest: (userId, digest) => {
10808
11187
  const hit = parseCronReminder(digest, Date.now());
10809
11188
  if (!hit)
@@ -11486,6 +11865,12 @@ ${parsed.message}`;
11486
11865
  inflight.settle(ctx.msgId, undefined, reason);
11487
11866
  console.log(`[queue] release-early msg=${shortId(ctx.msgId)} reason=${reason}${note ? ` note=${note}` : ""}`);
11488
11867
  };
11868
+ const releaseAnchorClaim = (note) => {
11869
+ if (ctx.msgId && claimedContexts.has(ctx)) {
11870
+ inflight.markStage(ctx.msgId, "claimed", { lastError: note }, { force: true });
11871
+ }
11872
+ releaseClaimed("blocked", note);
11873
+ };
11489
11874
  try {
11490
11875
  if (!isAllowedUser(ctx.userId, config.allowedUsers)) {
11491
11876
  console.log(`[security] 拒绝非白名单用户:openid=${ctx.userId}(把它加入 ~/.openqq/.env 的 ALLOWED_USERS 后重启即开通)`);
@@ -11517,6 +11902,14 @@ ${parsed.message}`;
11517
11902
  const gateContent = normalizeForCommandGate(content);
11518
11903
  if (isCommand(gateContent)) {
11519
11904
  const gateCtx = gateContent === content ? ctx : { ...ctx, content: gateContent };
11905
+ if (commandNeedsMirrorAnchorGate(gateContent)) {
11906
+ const decision = mirrorAnchorDecision(gateCtx, anchorSid);
11907
+ if (decision.kind === "conflict" || decision.kind === "unknown") {
11908
+ releaseAnchorClaim(decision.kind === "conflict" ? "anchor-conflict" : "anchor-unknown");
11909
+ await rejectMirrorAnchor(ctx, decision, anchorSid);
11910
+ return;
11911
+ }
11912
+ }
11520
11913
  const reply = await handleCommand(gateCtx, commandContext);
11521
11914
  await notifyUser(ctx, reply);
11522
11915
  releaseClaimed("dropped");
@@ -11555,6 +11948,12 @@ ${parsed.message}`;
11555
11948
  }
11556
11949
  claimedMsgId = ctx.msgId;
11557
11950
  }
11951
+ const mirrorGate = mirrorAnchorDecision(ctx, anchorSid);
11952
+ if (mirrorGate.kind === "conflict" || mirrorGate.kind === "unknown") {
11953
+ releaseAnchorClaim(mirrorGate.kind === "conflict" ? "anchor-conflict" : "anchor-unknown");
11954
+ await rejectMirrorAnchor(ctx, mirrorGate, anchorSid);
11955
+ return;
11956
+ }
11558
11957
  if (busyUsers.has(lane) && !claimedContexts.has(ctx)) {
11559
11958
  const duplicateIntent = activeIntents.get(lane) === intentKey || msgQueue.hasIntent(lane, intentKey);
11560
11959
  if (duplicateIntent) {
@@ -11629,8 +12028,7 @@ ${parsed.message}`;
11629
12028
  return;
11630
12029
  }))?.data?.location?.directory ?? anchorDirectory;
11631
12030
  }
11632
- const embeddedQuote = extractEmbeddedQuote(ctx.rawEvent);
11633
- const quoted = embeddedQuote ?? (ctx.referencedMsgId ? resolveQuote(scopeKeyOf(ctx), ctx.referencedMsgId) : null);
12031
+ const { quoted } = quoteContextOf(ctx);
11634
12032
  if (quoted)
11635
12033
  ctx.quoteText = quoted;
11636
12034
  recordMessage(scopeKeyOf(ctx), ctx.msgId, ctx.content);
@@ -11711,6 +12109,9 @@ ${promptBody}` : promptBody) + qqPromptHints();
11711
12109
  if (ctx.anchorSessionId && !isBoundSession(ctx.userId, ctx.anchorSessionId)) {
11712
12110
  console.log(`[push-gate] 回合结果按历史可回读结清 answered msg=${shortId(trackId)}`);
11713
12111
  inflight.settle(trackId, undefined, "answered");
12112
+ } else if (consumePartialFailure(ctx)) {
12113
+ inflight.settle(trackId, undefined, "error");
12114
+ console.log(`[journal] 分片部分失败结清 error msg=${shortId(trackId)}`);
11714
12115
  } else {
11715
12116
  await safeDeliver(ctx, "⚠️ 本轮结果与 24h 内已发送内容重复,已被防重拦截(未重复投递)。如非预期请重发或换个说法");
11716
12117
  inflight.settle(trackId, undefined, "error");
@@ -11982,8 +12383,8 @@ function isAllowedUser(userId, allowedUsers) {
11982
12383
  var WATCH_FILE = storageFile("watch.json");
11983
12384
  function loadWatchedMap(file = WATCH_FILE) {
11984
12385
  try {
11985
- if (existsSync15(file)) {
11986
- const raw = readFileSync17(file, "utf-8");
12386
+ if (existsSync16(file)) {
12387
+ const raw = readFileSync18(file, "utf-8");
11987
12388
  const obj = JSON.parse(raw);
11988
12389
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
11989
12390
  const out = {};
@@ -11998,7 +12399,7 @@ function loadWatchedMap(file = WATCH_FILE) {
11998
12399
  }
11999
12400
  function saveWatchedMap(m, file = WATCH_FILE) {
12000
12401
  try {
12001
- writeFileSync15(file, JSON.stringify(Object.fromEntries(m), null, 2));
12402
+ writeFileSync16(file, JSON.stringify(Object.fromEntries(m), null, 2));
12002
12403
  } catch (error) {
12003
12404
  console.warn("[watch] 持久化失败:", error instanceof Error ? error.message : error);
12004
12405
  }
@@ -12006,8 +12407,8 @@ function saveWatchedMap(m, file = WATCH_FILE) {
12006
12407
  var GREETED_FILE = storageFile("greeted.json");
12007
12408
  function loadGreetedSet(file = GREETED_FILE) {
12008
12409
  try {
12009
- if (existsSync15(file)) {
12010
- const raw = readFileSync17(file, "utf-8");
12410
+ if (existsSync16(file)) {
12411
+ const raw = readFileSync18(file, "utf-8");
12011
12412
  const arr = JSON.parse(raw);
12012
12413
  if (Array.isArray(arr)) {
12013
12414
  return new Set(arr.filter((x) => typeof x === "string"));
@@ -12018,8 +12419,8 @@ function loadGreetedSet(file = GREETED_FILE) {
12018
12419
  }
12019
12420
  function saveGreetedSet(set, file = GREETED_FILE) {
12020
12421
  try {
12021
- mkdirSync14(join13(homedir7(), ".openqq"), { recursive: true });
12022
- writeFileSync15(file, JSON.stringify([...set]));
12422
+ mkdirSync15(join13(homedir7(), ".openqq"), { recursive: true });
12423
+ writeFileSync16(file, JSON.stringify([...set]));
12023
12424
  } catch (error) {
12024
12425
  console.error("[bridge] 保存 greeted 失败:", error);
12025
12426
  }
@@ -12153,8 +12554,8 @@ async function main() {
12153
12554
  const heartbeatFile = join14(homedir8(), ".openqq", "heartbeat");
12154
12555
  const touchHeartbeat = () => {
12155
12556
  try {
12156
- mkdirSync15(join14(homedir8(), ".openqq"), { recursive: true });
12157
- writeFileSync16(heartbeatFile, String(Date.now()));
12557
+ mkdirSync16(join14(homedir8(), ".openqq"), { recursive: true });
12558
+ writeFileSync17(heartbeatFile, String(Date.now()));
12158
12559
  } catch (error) {
12159
12560
  console.error("[index] 心跳写入失败:", error);
12160
12561
  }