@linjz/opencode-qqbot 0.3.8 → 0.3.10

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.
@@ -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 mkdirSync9, renameSync as renameSync2, statSync as statSync5 } from "fs";
2942
+ import { appendFileSync, existsSync as existsSync9, mkdirSync as mkdirSync10, renameSync as renameSync3, statSync as statSync5 } from "fs";
2943
2943
  import { join as join12 } from "path";
2944
2944
  function installFileLog(logPath) {
2945
2945
  try {
2946
- mkdirSync9(join12(logPath, ".."), { recursive: true });
2946
+ mkdirSync10(join12(logPath, ".."), { recursive: true });
2947
2947
  } catch {}
2948
2948
  const write = (level, args) => {
2949
2949
  try {
2950
2950
  if (existsSync9(logPath) && statSync5(logPath).size > ROTATE_BYTES) {
2951
- renameSync2(logPath, `${logPath}.1`);
2951
+ renameSync3(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,7 +3087,7 @@ function loadConfig() {
3087
3087
  }
3088
3088
 
3089
3089
  // src/index.ts
3090
- import { mkdirSync as mkdirSync10, writeFileSync as writeFileSync12 } from "fs";
3090
+ import { mkdirSync as mkdirSync11, writeFileSync as writeFileSync12 } from "fs";
3091
3091
  import { join as join13 } from "path";
3092
3092
  import { homedir as homedir11 } from "os";
3093
3093
 
@@ -4329,7 +4329,7 @@ async function startGateway(options) {
4329
4329
  }
4330
4330
 
4331
4331
  // src/bridge.ts
4332
- import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync7, writeFileSync as writeFileSync10 } from "fs";
4332
+ import { existsSync as existsSync8, readFileSync as readFileSync10, mkdirSync as mkdirSync8, writeFileSync as writeFileSync10 } from "fs";
4333
4333
  import { join as join10 } from "path";
4334
4334
  import { homedir as homedir9 } from "os";
4335
4335
 
@@ -5223,6 +5223,25 @@ function answerClipLimit() {
5223
5223
  const n = Number(process.env.QQ_DIGEST_ANSWER_MAX_CHARS ?? "0");
5224
5224
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
5225
5225
  }
5226
+ function digestTurnKey(messages) {
5227
+ const ordered = [...messages].reverse();
5228
+ let lastUserIdx = -1;
5229
+ for (let i = ordered.length - 1;i >= 0; i--) {
5230
+ if (ordered[i].type === "user") {
5231
+ lastUserIdx = i;
5232
+ break;
5233
+ }
5234
+ }
5235
+ if (lastUserIdx < 0)
5236
+ return null;
5237
+ for (let i = ordered.length - 1;i > lastUserIdx; i--) {
5238
+ const m = ordered[i];
5239
+ if (m.type !== "assistant" || !(m.content ?? []).some((p) => p.type === "text" && p.text?.trim()))
5240
+ continue;
5241
+ return `${ordered[lastUserIdx].id ?? `user@${lastUserIdx}`}:${m.id ?? `assistant@${i}`}`;
5242
+ }
5243
+ return null;
5244
+ }
5226
5245
  function buildDigest(messages) {
5227
5246
  const ordered = [...messages].reverse();
5228
5247
  let lastUserIdx = -1;
@@ -5303,6 +5322,7 @@ function createMirror(deps) {
5303
5322
  const { sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers } = deps;
5304
5323
  const mirrorUnsubs = new Map;
5305
5324
  const qqTurnActive = new Set;
5325
+ const mirroredTurns = new Map;
5306
5326
  const mirrorState = { enabled: loadMirrorEnabled() };
5307
5327
  function ensureMirrorSubs() {
5308
5328
  if (!mirrorState.enabled)
@@ -5346,11 +5366,19 @@ function createMirror(deps) {
5346
5366
  return;
5347
5367
  }
5348
5368
  const listJson = await client.session.messages({ path: { id: sessionID } });
5349
- const digest = buildDigest(listJson?.data ?? []);
5369
+ const messages = listJson?.data ?? [];
5370
+ const turnKey = digestTurnKey(messages);
5371
+ if (turnKey && mirroredTurns.get(sessionID) === turnKey) {
5372
+ console.log(`[mirror] 跳过:逻辑回合已镜像 session=${sessionID} turn=${turnKey}`);
5373
+ return;
5374
+ }
5375
+ const digest = buildDigest(messages);
5350
5376
  if (!digest) {
5351
5377
  console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`);
5352
5378
  return;
5353
5379
  }
5380
+ if (turnKey)
5381
+ mirroredTurns.set(sessionID, turnKey);
5354
5382
  for (const userId of owners) {
5355
5383
  const recent = lastCtx.get(userId);
5356
5384
  const ctx = recent ?? { type: "c2c", userId, msgId: "", content: "" };
@@ -5691,8 +5719,9 @@ function formatPermissionPrompt(request, mainSessionId) {
5691
5719
  }
5692
5720
 
5693
5721
  // src/core/delivery.ts
5694
- import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "fs";
5722
+ import { existsSync as existsSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync8, mkdirSync as mkdirSync6, renameSync } from "fs";
5695
5723
  import { join as join8 } from "path";
5724
+ import { createHash } from "node:crypto";
5696
5725
  import { homedir as homedir7 } from "os";
5697
5726
 
5698
5727
  // src/qq/sender.ts
@@ -6061,6 +6090,36 @@ function saveQuotaMap(m) {
6061
6090
  }
6062
6091
  var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
6063
6092
  `;
6093
+ 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");
6095
+ function deliveryAttemptKey(userId, text) {
6096
+ return `${userId}:${createHash("sha256").update(text).digest("hex")}`;
6097
+ }
6098
+ function shouldSuppressDuplicate(previous, text, now, ttlMs = DELIVERY_DEDUPE_TTL_MS) {
6099
+ return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs;
6100
+ }
6101
+ function loadDeliveryAttempts() {
6102
+ const out = new Map;
6103
+ try {
6104
+ if (!existsSync6(DELIVERY_DEDUPE_FILE))
6105
+ return out;
6106
+ const raw = JSON.parse(readFileSync8(DELIVERY_DEDUPE_FILE, "utf-8"));
6107
+ const now = Date.now();
6108
+ for (const entry of raw) {
6109
+ if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
6110
+ out.set(entry.key, { text: entry.key, at: entry.at });
6111
+ }
6112
+ }
6113
+ } catch {}
6114
+ return out;
6115
+ }
6116
+ function saveDeliveryAttempts(entries) {
6117
+ 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);
6122
+ }
6064
6123
  function selectRideMsgId(last, ctx, now, windowMs) {
6065
6124
  if (!last?.msgId)
6066
6125
  return;
@@ -6087,6 +6146,7 @@ function createDelivery(config, lastCtx) {
6087
6146
  })();
6088
6147
  const pushQueues = new Map;
6089
6148
  const undelivered = new Set;
6149
+ const recentDeliveries = loadDeliveryAttempts();
6090
6150
  const activeQuota = new Map;
6091
6151
  const passiveLimiter = new ReplyLimiter;
6092
6152
  for (const [uid, q] of Object.entries(loadQuotaMap()))
@@ -6128,11 +6188,21 @@ function createDelivery(config, lastCtx) {
6128
6188
  }
6129
6189
  }
6130
6190
  async function deliver(ctx, text) {
6191
+ const now = Date.now();
6192
+ const attemptKey = deliveryAttemptKey(ctx.userId, text);
6193
+ if (shouldSuppressDuplicate(recentDeliveries.get(attemptKey), attemptKey, now)) {
6194
+ console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`);
6195
+ return;
6196
+ }
6197
+ recentDeliveries.set(attemptKey, { text: attemptKey, at: now });
6131
6198
  const hadNotice = undelivered.delete(ctx.userId);
6132
6199
  const body = hadNotice ? UNDELIVERED_NOTICE + text : text;
6133
6200
  try {
6134
6201
  await deliverCore(ctx, body);
6202
+ saveDeliveryAttempts(recentDeliveries);
6135
6203
  } catch (error) {
6204
+ if (recentDeliveries.get(attemptKey)?.at === now)
6205
+ recentDeliveries.delete(attemptKey);
6136
6206
  if (hadNotice)
6137
6207
  undelivered.add(ctx.userId);
6138
6208
  throw error;
@@ -6547,7 +6617,7 @@ function createFormBridge(deps) {
6547
6617
  }
6548
6618
 
6549
6619
  // src/core/inflight-journal.ts
6550
- import { existsSync as existsSync7, readFileSync as readFileSync9, writeFileSync as writeFileSync9, mkdirSync as mkdirSync6, renameSync, openSync, closeSync, unlinkSync as unlinkSync2, statSync as statSync3 } from "fs";
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";
6551
6621
  import { join as join9 } from "path";
6552
6622
  import { homedir as homedir8 } from "os";
6553
6623
  var INFLIGHT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -6573,11 +6643,11 @@ function load() {
6573
6643
  }
6574
6644
  function save(entries) {
6575
6645
  const path = journalPath();
6576
- mkdirSync6(join9(path, ".."), { recursive: true });
6646
+ mkdirSync7(join9(path, ".."), { recursive: true });
6577
6647
  const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
6578
6648
  try {
6579
6649
  writeFileSync9(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
6580
- renameSync(tmp, path);
6650
+ renameSync2(tmp, path);
6581
6651
  } catch (error) {
6582
6652
  try {
6583
6653
  unlinkSync2(tmp);
@@ -6590,7 +6660,7 @@ var JOURNAL_LOCK_WAIT_MS = 5000;
6590
6660
  var sleepArray = new Int32Array(new SharedArrayBuffer(4));
6591
6661
  function withJournalLock(fn) {
6592
6662
  const path = journalPath();
6593
- mkdirSync6(join9(path, ".."), { recursive: true });
6663
+ mkdirSync7(join9(path, ".."), { recursive: true });
6594
6664
  const lockPath = `${path}.lock`;
6595
6665
  const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
6596
6666
  const deadline = Date.now() + JOURNAL_LOCK_WAIT_MS;
@@ -7314,7 +7384,7 @@ function loadGreetedSet() {
7314
7384
  }
7315
7385
  function saveGreetedSet(set) {
7316
7386
  try {
7317
- mkdirSync7(join10(homedir9(), ".openqq"), { recursive: true });
7387
+ mkdirSync8(join10(homedir9(), ".openqq"), { recursive: true });
7318
7388
  writeFileSync10(GREETED_FILE, JSON.stringify([...set]));
7319
7389
  } catch (error) {
7320
7390
  console.error("[bridge] 保存 greeted 失败:", error);
@@ -7366,7 +7436,7 @@ function toErrorMessage2(error) {
7366
7436
  }
7367
7437
 
7368
7438
  // src/core/instance-lock.ts
7369
- import { openSync as openSync2, writeFileSync as writeFileSync11, closeSync as closeSync2, unlinkSync as unlinkSync3, statSync as statSync4, utimesSync, mkdirSync as mkdirSync8 } from "fs";
7439
+ import { openSync as openSync2, writeFileSync as writeFileSync11, closeSync as closeSync2, unlinkSync as unlinkSync3, statSync as statSync4, utimesSync, mkdirSync as mkdirSync9 } from "fs";
7370
7440
  import { join as join11 } from "path";
7371
7441
  import { homedir as homedir10 } from "os";
7372
7442
  var INSTANCE_LOCK_DISABLED_ENV = "QQ_INSTANCE_LOCK";
@@ -7382,7 +7452,7 @@ function touch(path) {
7382
7452
  }
7383
7453
  function acquireInstanceLockAt(path, staleMs = LOCK_STALE_MS) {
7384
7454
  try {
7385
- mkdirSync8(join11(path, ".."), { recursive: true });
7455
+ mkdirSync9(join11(path, ".."), { recursive: true });
7386
7456
  const fd = openSync2(path, "wx");
7387
7457
  writeFileSync11(fd, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
7388
7458
  closeSync2(fd);
@@ -7519,7 +7589,7 @@ async function main() {
7519
7589
  const heartbeatFile = join13(homedir11(), ".openqq", "heartbeat");
7520
7590
  const touchHeartbeat = () => {
7521
7591
  try {
7522
- mkdirSync10(join13(homedir11(), ".openqq"), { recursive: true });
7592
+ mkdirSync11(join13(homedir11(), ".openqq"), { recursive: true });
7523
7593
  writeFileSync12(heartbeatFile, String(Date.now()));
7524
7594
  } catch (error) {
7525
7595
  console.error("[index] 心跳写入失败:", error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.8",
3
+ "version": "0.3.10",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -2,8 +2,9 @@
2
2
  // @output: createDelivery
3
3
  // @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
4
4
  // 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
5
- import { existsSync, readFileSync, writeFileSync } from "fs"
5
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from "fs"
6
6
  import { join } from "path"
7
+ import { createHash } from "node:crypto"
7
8
  import { homedir } from "os"
8
9
  import type { Config } from "../config.js"
9
10
  import type { MessageContext } from "../qq/types.js"
@@ -56,6 +57,56 @@ function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warne
56
57
  // 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
57
58
  export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
58
59
 
60
+ export interface DeliveryAttempt {
61
+ text: string
62
+ at: number
63
+ }
64
+
65
+ export const DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000
66
+ const DELIVERY_DEDUPE_FILE = process.env.QQ_DELIVERY_DEDUPE_FILE || join(homedir(), ".openqq", "delivery-dedupe.json")
67
+
68
+ function deliveryAttemptKey(userId: string, text: string): string {
69
+ return `${userId}:${createHash("sha256").update(text).digest("hex")}`
70
+ }
71
+
72
+ /** AI 长回复的同文幂等:不同 location/重复回合可产生不同事件 ID,最终统一在出站拦截。 */
73
+ export function shouldSuppressDuplicate(
74
+ previous: DeliveryAttempt | undefined,
75
+ text: string,
76
+ now: number,
77
+ ttlMs = DELIVERY_DEDUPE_TTL_MS,
78
+ ): boolean {
79
+ return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs
80
+ }
81
+
82
+ // 仅存用户键+内容哈希,不把回复正文写进运行数据。跨重启也能识别同文回复。
83
+ function loadDeliveryAttempts(): Map<string, DeliveryAttempt> {
84
+ const out = new Map<string, DeliveryAttempt>()
85
+ try {
86
+ if (!existsSync(DELIVERY_DEDUPE_FILE)) return out
87
+ const raw = JSON.parse(readFileSync(DELIVERY_DEDUPE_FILE, "utf-8")) as Array<{ key: string; at: number }>
88
+ const now = Date.now()
89
+ for (const entry of raw) {
90
+ if (typeof entry?.key === "string" && Number.isFinite(entry.at) && now - entry.at < DELIVERY_DEDUPE_TTL_MS) {
91
+ out.set(entry.key, { text: entry.key, at: entry.at })
92
+ }
93
+ }
94
+ } catch {
95
+ // 损坏则仅本轮无历史去重,不阻塞启动
96
+ }
97
+ return out
98
+ }
99
+
100
+ function saveDeliveryAttempts(entries: ReadonlyMap<string, DeliveryAttempt>): void {
101
+ const raw = [...entries.values()]
102
+ .filter((entry) => Date.now() - entry.at < DELIVERY_DEDUPE_TTL_MS)
103
+ .map((entry) => ({ key: entry.text, at: entry.at }))
104
+ mkdirSync(join(DELIVERY_DEDUPE_FILE, ".."), { recursive: true })
105
+ const tmp = `${DELIVERY_DEDUPE_FILE}.tmp`
106
+ writeFileSync(tmp, JSON.stringify(raw, null, 2), { mode: 0o600 })
107
+ renameSync(tmp, DELIVERY_DEDUPE_FILE)
108
+ }
109
+
59
110
  // B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
60
111
  // 同一聊天类型、时间戳在窗口内才有效;任何不对齐都返回 undefined(回落真主动)。
61
112
  export function selectRideMsgId(
@@ -111,6 +162,8 @@ export function createDelivery(
111
162
  const pushQueues = new Map<string, PushQueue>()
112
163
  // P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
113
164
  const undelivered = new Set<string>()
165
+ // 同文长回复幂等(跨重启 24h);尝试前占位防并发,失败立即释放允许重试。
166
+ const recentDeliveries = loadDeliveryAttempts()
114
167
  const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
115
168
  // B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
116
169
  // 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
@@ -160,11 +213,21 @@ export function createDelivery(
160
213
  // P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
161
214
  // 投递失败则把贴条放回(留待下次),成功才算消化。
162
215
  async function deliver(ctx: MessageContext, text: string): Promise<void> {
216
+ const now = Date.now()
217
+ const attemptKey = deliveryAttemptKey(ctx.userId, text)
218
+ if (shouldSuppressDuplicate(recentDeliveries.get(attemptKey), attemptKey, now)) {
219
+ console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`)
220
+ return
221
+ }
222
+ recentDeliveries.set(attemptKey, { text: attemptKey, at: now })
163
223
  const hadNotice = undelivered.delete(ctx.userId)
164
224
  const body = hadNotice ? UNDELIVERED_NOTICE + text : text
165
225
  try {
166
226
  await deliverCore(ctx, body)
227
+ saveDeliveryAttempts(recentDeliveries)
167
228
  } catch (error) {
229
+ // 发送失败不占去重位,后续恢复/重试仍可送达。
230
+ if (recentDeliveries.get(attemptKey)?.at === now) recentDeliveries.delete(attemptKey)
168
231
  if (hadNotice) undelivered.add(ctx.userId)
169
232
  throw error
170
233
  }
@@ -8,7 +8,7 @@ import { homedir } from "os"
8
8
  import type { MessageContext } from "../qq/types.js"
9
9
  import type { OpencodeClient } from "../opencode/client.js"
10
10
  import { createEventStream } from "../opencode/eventstream.js"
11
- import { buildDigest } from "../opencode/mirror.js"
11
+ import { buildDigest, digestTurnKey } from "../opencode/mirror.js"
12
12
  import type { SessionManager } from "../opencode/sessions.js"
13
13
  import type { MirrorApi } from "../commands.js"
14
14
 
@@ -71,6 +71,7 @@ export function createMirror(deps: MirrorDeps): Mirror {
71
71
  const { sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers } = deps
72
72
  const mirrorUnsubs = new Map<string, () => void>() // 摘要镜像订阅(独立于 /watch)
73
73
  const qqTurnActive = new Set<string>() // QQ 发起的轮次在途(镜像跳过防重复)
74
+ const mirroredTurns = new Map<string, string>() // 逻辑回合幂等:多 location/重复完成事件只投一次
74
75
  const mirrorState = { enabled: loadMirrorEnabled() }
75
76
 
76
77
  // ===== 摘要镜像(E 阶段 A 方案):桌面会话轮次完成 → QQ 摘要卡 =====
@@ -121,11 +122,19 @@ export function createMirror(deps: MirrorDeps): Mirror {
121
122
  return
122
123
  }
123
124
  const listJson = await client.session.messages({ path: { id: sessionID } })
124
- const digest = buildDigest(listJson?.data ?? [])
125
+ const messages = listJson?.data ?? []
126
+ const turnKey = digestTurnKey(messages)
127
+ if (turnKey && mirroredTurns.get(sessionID) === turnKey) {
128
+ console.log(`[mirror] 跳过:逻辑回合已镜像 session=${sessionID} turn=${turnKey}`)
129
+ return
130
+ }
131
+ const digest = buildDigest(messages)
125
132
  if (!digest) {
126
133
  console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`)
127
134
  return
128
135
  }
136
+ // 在投递前占位:两个完成事件并发到达时,后到的回调也会命中同一回合并被去重。
137
+ if (turnKey) mirroredTurns.set(sessionID, turnKey)
129
138
  for (const userId of owners) {
130
139
  // 无最近 ctx(重启后尚未收到新消息)→ 构造主动通道 ctx,
131
140
  // deliver 的被动尝试失败会自然降级为主动消息(D4 配额内)。
@@ -76,6 +76,7 @@ export interface MessagePart {
76
76
  }
77
77
 
78
78
  export interface SessionMessage {
79
+ id?: string
79
80
  type?: string
80
81
  time?: { created?: number; completed?: number }
81
82
  content?: MessagePart[]
@@ -19,6 +19,26 @@ function answerClipLimit(): number {
19
19
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0
20
20
  }
21
21
 
22
+ // 逻辑回合并发幂等键:同一用户消息 + 最终 assistant。不同 location 的
23
+ // execution.succeeded 事件 ID 可以不同,但同一逻辑回合仍只应镜像一次。
24
+ export function digestTurnKey(messages: SessionMessage[]): string | null {
25
+ const ordered = [...messages].reverse()
26
+ let lastUserIdx = -1
27
+ for (let i = ordered.length - 1; i >= 0; i--) {
28
+ if (ordered[i].type === "user") {
29
+ lastUserIdx = i
30
+ break
31
+ }
32
+ }
33
+ if (lastUserIdx < 0) return null
34
+ for (let i = ordered.length - 1; i > lastUserIdx; i--) {
35
+ const m = ordered[i]
36
+ if (m.type !== "assistant" || !(m.content ?? []).some((p) => p.type === "text" && p.text?.trim())) continue
37
+ return `${ordered[lastUserIdx].id ?? `user@${lastUserIdx}`}:${m.id ?? `assistant@${i}`}`
38
+ }
39
+ return null
40
+ }
41
+
22
42
  // 构建最近一轮问答的摘要卡;返回 null = 无可镜像正文。
23
43
  export function buildDigest(messages: SessionMessage[]): string | null {
24
44
  const ordered = [...messages].reverse()