@linjz/opencode-qqbot 0.3.8 → 0.3.9

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.
@@ -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: "" };
@@ -6061,6 +6089,9 @@ function saveQuotaMap(m) {
6061
6089
  }
6062
6090
  var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
6063
6091
  `;
6092
+ function shouldSuppressDuplicate(previous, text, now, ttlMs = 60000) {
6093
+ return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs;
6094
+ }
6064
6095
  function selectRideMsgId(last, ctx, now, windowMs) {
6065
6096
  if (!last?.msgId)
6066
6097
  return;
@@ -6087,6 +6118,7 @@ function createDelivery(config, lastCtx) {
6087
6118
  })();
6088
6119
  const pushQueues = new Map;
6089
6120
  const undelivered = new Set;
6121
+ const recentDeliveries = new Map;
6090
6122
  const activeQuota = new Map;
6091
6123
  const passiveLimiter = new ReplyLimiter;
6092
6124
  for (const [uid, q] of Object.entries(loadQuotaMap()))
@@ -6128,11 +6160,19 @@ function createDelivery(config, lastCtx) {
6128
6160
  }
6129
6161
  }
6130
6162
  async function deliver(ctx, text) {
6163
+ const now = Date.now();
6164
+ if (shouldSuppressDuplicate(recentDeliveries.get(ctx.userId), text, now)) {
6165
+ console.log(`[bridge] 同文长回复已在 60s 内投递,跳过重复出站 user=${ctx.userId}`);
6166
+ return;
6167
+ }
6168
+ recentDeliveries.set(ctx.userId, { text, at: now });
6131
6169
  const hadNotice = undelivered.delete(ctx.userId);
6132
6170
  const body = hadNotice ? UNDELIVERED_NOTICE + text : text;
6133
6171
  try {
6134
6172
  await deliverCore(ctx, body);
6135
6173
  } catch (error) {
6174
+ if (recentDeliveries.get(ctx.userId)?.at === now)
6175
+ recentDeliveries.delete(ctx.userId);
6136
6176
  if (hadNotice)
6137
6177
  undelivered.add(ctx.userId);
6138
6178
  throw 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.9",
4
4
  "type": "module",
5
5
  "description": "QQ Bot for OpenCode AI - chat with AI coding assistant via QQ",
6
6
  "exports": {
@@ -56,6 +56,16 @@ function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warne
56
56
  // 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
57
57
  export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
58
58
 
59
+ export interface DeliveryAttempt {
60
+ text: string
61
+ at: number
62
+ }
63
+
64
+ /** AI 长回复的同文短窗幂等:不同 location/重复回合可产生不同事件 ID,最终统一在出站拦截。 */
65
+ export function shouldSuppressDuplicate(previous: DeliveryAttempt | undefined, text: string, now: number, ttlMs = 60_000): boolean {
66
+ return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs
67
+ }
68
+
59
69
  // B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
60
70
  // 同一聊天类型、时间戳在窗口内才有效;任何不对齐都返回 undefined(回落真主动)。
61
71
  export function selectRideMsgId(
@@ -111,6 +121,8 @@ export function createDelivery(
111
121
  const pushQueues = new Map<string, PushQueue>()
112
122
  // P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
113
123
  const undelivered = new Set<string>()
124
+ // 同文长回复短窗幂等(进程内最后防线);尝试前占位防并发,失败立即释放允许重试。
125
+ const recentDeliveries = new Map<string, DeliveryAttempt>()
114
126
  const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
115
127
  // B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
116
128
  // 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
@@ -160,11 +172,19 @@ export function createDelivery(
160
172
  // P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
161
173
  // 投递失败则把贴条放回(留待下次),成功才算消化。
162
174
  async function deliver(ctx: MessageContext, text: string): Promise<void> {
175
+ const now = Date.now()
176
+ if (shouldSuppressDuplicate(recentDeliveries.get(ctx.userId), text, now)) {
177
+ console.log(`[bridge] 同文长回复已在 60s 内投递,跳过重复出站 user=${ctx.userId}`)
178
+ return
179
+ }
180
+ recentDeliveries.set(ctx.userId, { text, at: now })
163
181
  const hadNotice = undelivered.delete(ctx.userId)
164
182
  const body = hadNotice ? UNDELIVERED_NOTICE + text : text
165
183
  try {
166
184
  await deliverCore(ctx, body)
167
185
  } catch (error) {
186
+ // 发送失败不占去重位,后续恢复/重试仍可送达。
187
+ if (recentDeliveries.get(ctx.userId)?.at === now) recentDeliveries.delete(ctx.userId)
168
188
  if (hadNotice) undelivered.add(ctx.userId)
169
189
  throw error
170
190
  }
@@ -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()