@linjz/opencode-qqbot 0.3.7 → 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.
@@ -3098,7 +3098,8 @@ var TURN_TIMEOUT_MINUTES = (() => {
3098
3098
  })();
3099
3099
  var RESPONSE_TIMEOUT_MS = TURN_TIMEOUT_MINUTES * 60 * 1000;
3100
3100
  function collectReplyText(msgs, baseline) {
3101
- return msgs.filter((x) => x.type === "assistant" && (x.time?.created ?? 0) >= baseline).flatMap((x) => (x.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "")).join(`
3101
+ const latest = msgs.filter((x) => x.type === "assistant" && (x.time?.created ?? 0) >= baseline).sort((a, b) => (b.time?.created ?? 0) - (a.time?.created ?? 0)).find((x) => (x.content ?? []).some((p) => p.type === "text" && p.text?.trim()));
3102
+ return (latest?.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join(`
3102
3103
  `).trim();
3103
3104
  }
3104
3105
  var client = null;
@@ -5222,6 +5223,25 @@ function answerClipLimit() {
5222
5223
  const n = Number(process.env.QQ_DIGEST_ANSWER_MAX_CHARS ?? "0");
5223
5224
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
5224
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
+ }
5225
5245
  function buildDigest(messages) {
5226
5246
  const ordered = [...messages].reverse();
5227
5247
  let lastUserIdx = -1;
@@ -5234,18 +5254,18 @@ function buildDigest(messages) {
5234
5254
  if (lastUserIdx < 0)
5235
5255
  return null;
5236
5256
  const userText = (ordered[lastUserIdx].text ?? "").trim();
5237
- const answerParts = [];
5238
- for (let i = lastUserIdx + 1;i < ordered.length; i++) {
5257
+ let answer = "";
5258
+ for (let i = ordered.length - 1;i > lastUserIdx; i--) {
5239
5259
  const m = ordered[i];
5240
- if (m.type === "assistant") {
5241
- for (const p of m.content ?? []) {
5242
- if (p.type === "text" && p.text?.trim())
5243
- answerParts.push(p.text.trim());
5244
- }
5260
+ if (m.type !== "assistant")
5261
+ continue;
5262
+ const parts = (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text.trim());
5263
+ if (parts.length > 0) {
5264
+ answer = parts.join(`
5265
+ `).trim();
5266
+ break;
5245
5267
  }
5246
5268
  }
5247
- const answer = answerParts.join(`
5248
- `).trim();
5249
5269
  if (!answer)
5250
5270
  return null;
5251
5271
  const lines = ["\uD83D\uDCCB 桌面问答摘要"];
@@ -5302,6 +5322,7 @@ function createMirror(deps) {
5302
5322
  const { sessions, eventStream, client, lastCtx, safeDeliver, bgWaits, busyUsers } = deps;
5303
5323
  const mirrorUnsubs = new Map;
5304
5324
  const qqTurnActive = new Set;
5325
+ const mirroredTurns = new Map;
5305
5326
  const mirrorState = { enabled: loadMirrorEnabled() };
5306
5327
  function ensureMirrorSubs() {
5307
5328
  if (!mirrorState.enabled)
@@ -5345,11 +5366,19 @@ function createMirror(deps) {
5345
5366
  return;
5346
5367
  }
5347
5368
  const listJson = await client.session.messages({ path: { id: sessionID } });
5348
- 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);
5349
5376
  if (!digest) {
5350
5377
  console.log(`[mirror] 跳过:无可摘要内容(空轮/纯工具轮)session=${sessionID}`);
5351
5378
  return;
5352
5379
  }
5380
+ if (turnKey)
5381
+ mirroredTurns.set(sessionID, turnKey);
5353
5382
  for (const userId of owners) {
5354
5383
  const recent = lastCtx.get(userId);
5355
5384
  const ctx = recent ?? { type: "c2c", userId, msgId: "", content: "" };
@@ -6060,6 +6089,9 @@ function saveQuotaMap(m) {
6060
6089
  }
6061
6090
  var UNDELIVERED_NOTICE = `(此前有未能送达的消息)
6062
6091
  `;
6092
+ function shouldSuppressDuplicate(previous, text, now, ttlMs = 60000) {
6093
+ return text.length >= 200 && previous?.text === text && now - previous.at < ttlMs;
6094
+ }
6063
6095
  function selectRideMsgId(last, ctx, now, windowMs) {
6064
6096
  if (!last?.msgId)
6065
6097
  return;
@@ -6086,6 +6118,7 @@ function createDelivery(config, lastCtx) {
6086
6118
  })();
6087
6119
  const pushQueues = new Map;
6088
6120
  const undelivered = new Set;
6121
+ const recentDeliveries = new Map;
6089
6122
  const activeQuota = new Map;
6090
6123
  const passiveLimiter = new ReplyLimiter;
6091
6124
  for (const [uid, q] of Object.entries(loadQuotaMap()))
@@ -6127,11 +6160,19 @@ function createDelivery(config, lastCtx) {
6127
6160
  }
6128
6161
  }
6129
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 });
6130
6169
  const hadNotice = undelivered.delete(ctx.userId);
6131
6170
  const body = hadNotice ? UNDELIVERED_NOTICE + text : text;
6132
6171
  try {
6133
6172
  await deliverCore(ctx, body);
6134
6173
  } catch (error) {
6174
+ if (recentDeliveries.get(ctx.userId)?.at === now)
6175
+ recentDeliveries.delete(ctx.userId);
6135
6176
  if (hadNotice)
6136
6177
  undelivered.add(ctx.userId);
6137
6178
  throw error;
@@ -6678,19 +6719,16 @@ function classifyInflight(entry, messages) {
6678
6719
  const completed = ordered.slice(lastUserIdx + 1).some((m) => m.type === "idle");
6679
6720
  if (!completed)
6680
6721
  return { kind: "running" };
6681
- const answerParts = [];
6682
- for (let i = lastUserIdx + 1;i < ordered.length; i++) {
6722
+ for (let i = ordered.length - 1;i > lastUserIdx; i--) {
6683
6723
  const m = ordered[i];
6684
- if (m.type === "assistant") {
6685
- for (const p of m.content ?? []) {
6686
- if (p.type === "text" && p.text?.trim())
6687
- answerParts.push(p.text.trim());
6688
- }
6689
- }
6690
- }
6691
- const answer = answerParts.join(`
6724
+ if (m.type !== "assistant")
6725
+ continue;
6726
+ const answer = (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text.trim()).join(`
6692
6727
  `).trim();
6693
- return answer ? { kind: "answered", answer } : { kind: "running" };
6728
+ if (answer)
6729
+ return { kind: "answered", answer };
6730
+ }
6731
+ return { kind: "running" };
6694
6732
  }
6695
6733
 
6696
6734
  // src/bridge.ts
@@ -7211,7 +7249,6 @@ ${cls.answer}`);
7211
7249
  console.log(`[bridge] 启动对账:已补投答案 msgId=${entry.msgId}`);
7212
7250
  } else if (cls.kind === "running") {
7213
7251
  mirror.beginTurn(entry.sessionId);
7214
- await deliver(ctx, "\uD83D\uDD04 重启恢复:你之前的任务仍在执行,完成即回传结果");
7215
7252
  startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId);
7216
7253
  console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`);
7217
7254
  } else if (ageMs <= redispatchMaxAgeMs()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linjz/opencode-qqbot",
3
- "version": "0.3.7",
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": {
package/src/bridge.ts CHANGED
@@ -742,7 +742,7 @@ export function createBridge(
742
742
  } else if (cls.kind === "running") {
743
743
  // 跨重启也要保持 QQ 回合同一身份:后台直答完成时,镜像不得再投摘要。
744
744
  mirror.beginTurn(entry.sessionId)
745
- await deliver(ctx, "🔄 重启恢复:你之前的任务仍在执行,完成即回传结果")
745
+ // 不单独发“仍在执行”通知;完成时统一回传最终答案,避免通知也占一条回复。
746
746
  startBackgroundWait(entry.sessionId, ctx, entry.at, entry.msgId)
747
747
  console.log(`[bridge] 启动对账:在途任务已重挂后台等待 msgId=${entry.msgId}`)
748
748
  } else if (ageMs <= redispatchMaxAgeMs()) {
@@ -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
  }
@@ -203,15 +203,16 @@ export function classifyInflight(
203
203
  const completed = ordered.slice(lastUserIdx + 1).some((m) => m.type === "idle")
204
204
  if (!completed) return { kind: "running" }
205
205
 
206
- const answerParts: string[] = []
207
- for (let i = lastUserIdx + 1; i < ordered.length; i++) {
206
+ // 与直答一致:只补投最终 assistant 正文,不把流式进度/阶段前导语重复拼入。
207
+ for (let i = ordered.length - 1; i > lastUserIdx; i--) {
208
208
  const m = ordered[i]
209
- if (m.type === "assistant") {
210
- for (const p of m.content ?? []) {
211
- if (p.type === "text" && p.text?.trim()) answerParts.push(p.text.trim())
212
- }
213
- }
209
+ if (m.type !== "assistant") continue
210
+ const answer = (m.content ?? [])
211
+ .filter((p) => p.type === "text" && p.text?.trim())
212
+ .map((p) => p.text!.trim())
213
+ .join("\n")
214
+ .trim()
215
+ if (answer) return { kind: "answered", answer }
214
216
  }
215
- const answer = answerParts.join("\n").trim()
216
- return answer ? { kind: "answered", answer } : { kind: "running" }
217
+ return { kind: "running" }
217
218
  }
@@ -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[]
@@ -128,12 +129,17 @@ const TURN_TIMEOUT_MINUTES = (() => {
128
129
  })()
129
130
  const RESPONSE_TIMEOUT_MS = TURN_TIMEOUT_MINUTES * 60 * 1000
130
131
 
131
- // 聚合某轮(baseline 之后)所有 assistant 消息的文本部件,丢弃 reasoning/tool 部件。
132
- // promptAndWait 与 bridge 的后台等待共用(后台等待 = 前台超时后不放弃,完成即回传)。
132
+ // 取 baseline 之后最后一个有正文的 assistant 消息,丢弃 reasoning/tool 与阶段前导语。
133
+ // 长回合会产生多条“正在检查/进度总结”assistant 文本;全部拼接会把过程包装成多条
134
+ // 相近答案。promptAndWait 与后台等待都只应交付最终回答。
133
135
  export function collectReplyText(msgs: SessionMessage[], baseline: number): string {
134
- return msgs
136
+ const latest = msgs
135
137
  .filter((x) => x.type === "assistant" && (x.time?.created ?? 0) >= baseline)
136
- .flatMap((x) => (x.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? ""))
138
+ .sort((a, b) => (b.time?.created ?? 0) - (a.time?.created ?? 0))
139
+ .find((x) => (x.content ?? []).some((p) => p.type === "text" && p.text?.trim()))
140
+ return (latest?.content ?? [])
141
+ .filter((p) => p.type === "text")
142
+ .map((p) => p.text ?? "")
137
143
  .join("\n")
138
144
  .trim()
139
145
  }
@@ -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()
@@ -34,16 +54,16 @@ export function buildDigest(messages: SessionMessage[]): string | null {
34
54
 
35
55
  const userText = ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
36
56
 
37
- const answerParts: string[] = []
38
- for (let i = lastUserIdx + 1; i < ordered.length; i++) {
57
+ let answer = ""
58
+ for (let i = ordered.length - 1; i > lastUserIdx; i--) {
39
59
  const m = ordered[i]
40
- if (m.type === "assistant") {
41
- for (const p of m.content ?? []) {
42
- if (p.type === "text" && p.text?.trim()) answerParts.push(p.text.trim())
43
- }
60
+ if (m.type !== "assistant") continue
61
+ const parts = (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text!.trim())
62
+ if (parts.length > 0) {
63
+ answer = parts.join("\n").trim()
64
+ break
44
65
  }
45
66
  }
46
- const answer = answerParts.join("\n").trim()
47
67
  if (!answer) return null
48
68
 
49
69
  const lines = ["📋 桌面问答摘要"]