@linjz/opencode-qqbot 0.3.15 → 0.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +303 -229
  2. package/README.zh-CN.md +313 -0
  3. package/bin/openqq.js +13 -0
  4. package/dist/notify-cli.js +92 -26
  5. package/dist/opencode-qqbot-plugin.js +1201 -67
  6. package/dist/openqq-bot.js +3963 -893
  7. package/dist/openqq-cli.js +980 -0
  8. package/dist/openqq-watchdog.js +1326 -0
  9. package/package.json +8 -5
  10. package/src/bridge.ts +1599 -150
  11. package/src/cli/notify.ts +170 -158
  12. package/src/cli/openqq-main.ts +95 -0
  13. package/src/cli/service-main.ts +302 -0
  14. package/src/cli/watchdog-main.ts +92 -0
  15. package/src/commands.ts +670 -554
  16. package/src/config.ts +122 -3
  17. package/src/core/bot-config.ts +66 -0
  18. package/src/core/bot-control.ts +166 -0
  19. package/src/core/bot-launcher.ts +110 -15
  20. package/src/core/card-approval.ts +20 -9
  21. package/src/core/cron-reminders.ts +84 -0
  22. package/src/core/delivery.ts +145 -54
  23. package/src/core/discovery.ts +207 -151
  24. package/src/core/error-rescue.ts +1 -1
  25. package/src/core/file-log.ts +50 -9
  26. package/src/core/form-bridge.ts +14 -5
  27. package/src/core/form-journal.ts +4 -4
  28. package/src/core/gateway-state.ts +3 -3
  29. package/src/core/inflight-journal.ts +215 -36
  30. package/src/core/instance-lock.ts +42 -3
  31. package/src/core/linkwatch.ts +3 -4
  32. package/src/core/log-rotate.ts +91 -0
  33. package/src/core/markdown.ts +117 -0
  34. package/src/core/message-queue.ts +242 -91
  35. package/src/core/mirror.ts +228 -182
  36. package/src/core/notices.ts +62 -0
  37. package/src/core/notify-sink.ts +93 -96
  38. package/src/core/outbound-sanitize.ts +29 -0
  39. package/src/core/outbox.ts +10 -9
  40. package/src/core/permission.ts +634 -303
  41. package/src/core/question-form.ts +230 -0
  42. package/src/core/queue-view.ts +662 -0
  43. package/src/core/send-media.ts +61 -2
  44. package/src/core/start-error.ts +26 -0
  45. package/src/core/storage.ts +34 -0
  46. package/src/core/stt.ts +55 -0
  47. package/src/core/supervisor-election.ts +53 -0
  48. package/src/core/watchdog.ts +670 -0
  49. package/src/core/zombie-reaper.ts +127 -0
  50. package/src/index.ts +262 -162
  51. package/src/opencode/client.ts +237 -27
  52. package/src/opencode/eventstream.ts +94 -12
  53. package/src/opencode/history.ts +4 -2
  54. package/src/opencode/mirror.ts +25 -5
  55. package/src/opencode/sessions.ts +135 -37
  56. package/src/plugin-entry.ts +139 -115
  57. package/src/qq/api.ts +165 -61
  58. package/src/qq/gateway.ts +114 -16
  59. package/src/qq/media.ts +21 -0
  60. package/src/qq/sender.ts +79 -18
  61. package/src/qq/types.ts +7 -0
@@ -0,0 +1,84 @@
1
+ // @input: 纯文本(无依赖)+ setTimeout(调度器)
2
+ // @output: parseCronReminder / ReminderScheduler
3
+ // @pos: core - 定时提醒(2026-11-23 学习吸收 Y-1,源=openclaw outbound/cron-scheduler.ts P0)
4
+ //
5
+ // 触发形态(AI 在正文内嵌标记,与 openclaw 同款):
6
+ // QQBOT_PAYLOAD: {"type":"cron_reminder","at":"in 30m","text":"去开评审会"}
7
+ // at 支持:ISO 8601 / Unix ms(>1e12)/ "in Nm/Nh/Nd";过去时刻拒收。
8
+ // 标记从用户可见正文剥离(不留脚手架痕迹);剥完为空则以确认句回执。
9
+ // 单次提醒(setTimeout,进程内存态)——重启即失,与 openclaw 同口径;
10
+ // 每用户同时在册上限防标记轰炸。
11
+
12
+ /** 解析 cron 标记(纯函数供测试)。命中并合法 → 绝对时刻/提醒文本/剥净正文;否则 null。 */
13
+ export function parseCronReminder(
14
+ text: string,
15
+ now: number,
16
+ ): { atMs: number; reminderText: string; cleanedText: string } | null {
17
+ const m = /QQBOT_PAYLOAD:\s*(\{[\s\S]*?\})/.exec(text)
18
+ if (!m) return null
19
+ let payload: { type?: unknown; at?: unknown; text?: unknown }
20
+ try {
21
+ payload = JSON.parse(m[1]) as typeof payload
22
+ } catch {
23
+ return null
24
+ }
25
+ if (payload?.type !== "cron_reminder") return null
26
+ const reminderText = typeof payload.text === "string" ? payload.text.trim().slice(0, 200) : ""
27
+ if (!reminderText) return null
28
+ const atMs = resolveAt(payload.at, now)
29
+ if (atMs === null || atMs <= now + 5_000) return null
30
+ // 剥净:含标记的整行移除,残余空行收敛
31
+ const cleanedText = text
32
+ .split("\n")
33
+ .filter((line) => !line.includes("QQBOT_PAYLOAD:"))
34
+ .join("\n")
35
+ .replace(/\n{3,}/g, "\n\n")
36
+ .trim()
37
+ return { atMs, reminderText, cleanedText }
38
+ }
39
+
40
+ /** at 字段解析(纯函数):ISO / Unix ms / "in Nm|Nh|Nd"。 */
41
+ export function resolveAt(at: unknown, now: number): number | null {
42
+ if (typeof at === "number" && Number.isFinite(at)) {
43
+ return at > 1e12 ? at : null // 小于 1e12 按秒记的可能性不存在于本域,拒收防误用
44
+ }
45
+ if (typeof at !== "string") return null
46
+ const rel = /^in\s+(\d+)\s*([mhd])$/i.exec(at.trim())
47
+ if (rel) {
48
+ const n = Number(rel[1])
49
+ const unit = { m: 60_000, h: 3_600_000, d: 86_400_000 }[rel[2].toLowerCase()] ?? 0
50
+ return now + n * unit
51
+ }
52
+ const t = Date.parse(at)
53
+ return Number.isNaN(t) ? null : t
54
+ }
55
+
56
+ /** 进程内单次提醒调度:每用户同时在册上限(防标记轰炸),到点投递并出册。 */
57
+ export class ReminderScheduler {
58
+ private readonly pending = new Map<string, Set<ReturnType<typeof setTimeout>>>()
59
+ constructor(private readonly maxPerUser = 10) {}
60
+
61
+ /** 注册。返回 false=被拒(超上限/参数非法),调用方如实回执。 */
62
+ schedule(userId: string, atMs: number, text: string, deliver: (userId: string, text: string) => void): boolean {
63
+ if (!userId || !text.trim() || atMs <= Date.now()) return false
64
+ const set = this.pending.get(userId) ?? new Set()
65
+ if (set.size >= this.maxPerUser) return false
66
+ const timer = setTimeout(() => {
67
+ set.delete(timer)
68
+ console.log(`[cron] 提醒到点 user=${userId.slice(0, 8)}… text=${text.slice(0, 30)}`)
69
+ try {
70
+ deliver(userId, `⏰ 提醒:${text}`)
71
+ } catch (error) {
72
+ console.error("[cron] 提醒投递失败:", error)
73
+ }
74
+ }, atMs - Date.now())
75
+ set.add(timer)
76
+ this.pending.set(userId, set)
77
+ return true
78
+ }
79
+
80
+ /** 在册数(测试断言用)。 */
81
+ size(userId: string): number {
82
+ return this.pending.get(userId)?.size ?? 0
83
+ }
84
+ }
@@ -1,32 +1,36 @@
1
- // @input: ../config, ../qq/types, ../qq/api, ../qq/sender, fs/path/os
1
+ // @input: ../config, ../qq/types, ../qq/api, ../qq/sender, fs/path/os
2
2
  // @output: createDelivery
3
3
  // @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
4
4
  // 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
5
+ import { storageFile } from "./storage.js"
5
6
  import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, unlinkSync, statSync } from "fs"
6
7
  import { join } from "path"
7
8
  import { createHash } from "node:crypto"
8
- import { homedir } from "os"
9
9
  import type { Config } from "../config.js"
10
10
  import type { MessageContext } from "../qq/types.js"
11
11
  import { getAccessToken, sendC2CMessage, sendGroupMessage, getNextMsgSeq } from "../qq/api.js"
12
12
  import { replyToQQ } from "../qq/sender.js"
13
+ import { matchFence, normalizeOutboundMarkdown } from "./markdown.js"
13
14
  import { ReplyLimiter } from "./reply-limiter.js"
14
15
  import { recordMessage, scopeKeyOf } from "./context-buffer.js"
15
16
 
16
- // 用户级推送队列:节流合并(主动消息配额记账已移至 activeQuota 共享)
17
+ // 用户级推送队列:节流合并(主动消息配额记账已移至 activeQuota 共享)。
18
+ // 每行带可选锚定会话(owner 2026-11-14 出站推送门):flush 时按锚定分组、逐组校验当前绑定。
17
19
  interface PushQueue {
18
20
  lastSent: number
19
21
  timer: ReturnType<typeof setTimeout> | null
20
- lines: string[]
22
+ lines: Array<{ line: string; anchor?: string }>
21
23
  }
22
24
 
23
25
  // O5(2026-10-15,P2-4b):主动配额落盘——跨重启不归零,防日配额轻微超发。
24
- const QUOTA_FILE = join(homedir(), ".openqq", "quota.json")
26
+ // 多角色(2026-11-17):配额文件可按角色注入(createDelivery 第 4 参),
27
+ // 缺省 legacy 全局路径(storageFile("quota.json"),值不变)。
28
+ const DEFAULT_QUOTA_FILE = storageFile("quota.json")
25
29
 
26
- function loadQuotaMap(): Record<string, { day: string; count: number; warned: boolean }> {
30
+ function loadQuotaMap(file: string): Record<string, { day: string; count: number; warned: boolean }> {
27
31
  try {
28
- if (existsSync(QUOTA_FILE)) {
29
- const raw = readFileSync(QUOTA_FILE, "utf-8")
32
+ if (existsSync(file)) {
33
+ const raw = readFileSync(file, "utf-8")
30
34
  const obj = JSON.parse(raw)
31
35
  if (obj && typeof obj === "object" && !Array.isArray(obj)) {
32
36
  const out: Record<string, { day: string; count: number; warned: boolean }> = {}
@@ -45,9 +49,9 @@ function loadQuotaMap(): Record<string, { day: string; count: number; warned: bo
45
49
  return {}
46
50
  }
47
51
 
48
- function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warned: boolean }>): void {
52
+ function saveQuotaMap(file: string, m: ReadonlyMap<string, { day: string; count: number; warned: boolean }>): void {
49
53
  try {
50
- writeFileSync(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)))
54
+ writeFileSync(file, JSON.stringify(Object.fromEntries(m)))
51
55
  } catch (error) {
52
56
  console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error)
53
57
  }
@@ -67,20 +71,21 @@ export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
67
71
  // 「N.」却被整条消息全局续编(连行内点号数字都会渗染起始值)。所以平面化目标
68
72
  // 从 N) 升级为 N、——与原生顿号列表视觉一致,编号所见即原文。
69
73
  // 变换幂等(N、 再进来不匹配行首 N. 模式,原样通过)。
74
+ // design §3.7 三层对策之第 3 层「提示词约束」:在 prompt 侧引导模型少用 QQ
75
+ // 渲染不稳的 markdown 有序列表/表格(第 1 层=出站平面化 qqListNormalize,第 2 层=
76
+ // markdown 发送失败回落纯文本,见下方 sendMarkdown 回退)。随每条用户消息注入。
77
+ export const QQ_LIST_FORMAT_HINT =
78
+ "\n\n(输出格式约定:本对话经 QQ 渲染,请用「1、2、3、」顿号或「-」无序列表代替 markdown 有序列表,避免表格;代码块不受影响可正常使用。)"
79
+
70
80
  export function qqListNormalize(text: string): string {
71
81
  const lines = text.split("\n")
72
- let fence = false
73
- let fenceMarker = ""
82
+ let fence: { ch: string; len: number } | null = null
74
83
  for (let i = 0; i < lines.length; i++) {
75
- const fm = lines[i].trim().match(/^(```|~~~)/)
84
+ // 围栏识别与出站兜底同源(core/markdown):支持 ``` 与 ~~~、4+ 标记长度。
85
+ const fm = matchFence(lines[i])
76
86
  if (fm) {
77
- if (!fence) {
78
- fence = true
79
- fenceMarker = fm[1]
80
- } else if (fm[1] === fenceMarker) {
81
- fence = false
82
- fenceMarker = ""
83
- }
87
+ if (!fence) fence = { ch: fm.ch, len: fm.len }
88
+ else if (fm.ch === fence.ch && fm.len >= fence.len && fm.info === "") fence = null
84
89
  continue
85
90
  }
86
91
  if (fence) continue
@@ -89,6 +94,36 @@ export function qqListNormalize(text: string): string {
89
94
  return lines.join("\n")
90
95
  }
91
96
 
97
+ /** 主动限额解析(纯函数,导出供测试):空值/非法/非正数回退 fallback(测试逃生门=显式 env)。 */
98
+ export function resolveActiveLimit(envValue: string | undefined, fallback: number): number {
99
+ const n = Number(envValue ?? "")
100
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
101
+ }
102
+
103
+ /**
104
+ * 滚动分钟窗准入(纯函数,导出供测试):给定该用户最近主动发送时刻表,
105
+ * 返回需等待的毫秒数(0 = 立即可发)。窗口满时不拒发——等到最老记录滑出窗口,
106
+ * 严格按官方 20/min 节奏放行,避免触发 40034100。
107
+ */
108
+ export function minuteWindowWaitMs(
109
+ timestamps: readonly number[],
110
+ now: number,
111
+ limit: number,
112
+ windowMs = 60_000,
113
+ ): number {
114
+ const recent = timestamps.filter((t) => now - t < windowMs)
115
+ if (recent.length < limit) return 0
116
+ const oldest = Math.min(...recent)
117
+ return Math.max(0, oldest + windowMs - now)
118
+ }
119
+
120
+ /** 记录一次主动发送并裁剪窗口(只保留窗内时刻)。 */
121
+ function logActiveSend(log: Map<string, number[]>, userId: string, now: number, windowMs = 60_000): void {
122
+ const arr = (log.get(userId) ?? []).filter((t) => now - t < windowMs)
123
+ arr.push(now)
124
+ log.set(userId, arr)
125
+ }
126
+
92
127
  export interface DeliveryAttempt {
93
128
  text: string
94
129
  at: number
@@ -98,7 +133,7 @@ export const DELIVERY_DEDUPE_TTL_MS = 24 * 60 * 60 * 1000
98
133
  // P0 同族修复(2026-11-03):原 const 在模块加载期捕获 QQ_DELIVERY_DEDUPE_FILE,
99
134
  // .env 运行时才注入——测试/多目录重定向永远不生效。改惰性函数。
100
135
  function deliveryDedupeFile(): string {
101
- return process.env.QQ_DELIVERY_DEDUPE_FILE || join(homedir(), ".openqq", "delivery-dedupe.json")
136
+ return process.env.QQ_DELIVERY_DEDUPE_FILE || storageFile("delivery-dedupe.json")
102
137
  }
103
138
 
104
139
  function deliveryAttemptKey(userId: string, text: string): string {
@@ -222,26 +257,39 @@ export function selectRideMsgId(
222
257
  }
223
258
 
224
259
  export interface Delivery {
225
- enqueuePush: (userId: string, line: string) => void
226
- deliver: (ctx: MessageContext, text: string) => Promise<void>
227
- safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
260
+ /** anchorSessionId=该观察行的锚定会话(出站推送门按它校验当前绑定,design §3.4) */
261
+ enqueuePush: (userId: string, line: string, anchorSessionId?: string) => void
262
+ /** 返回 true=实际出站成功;false=24h 去重拦截或推送门拦截(DEF-qqbot-20261110-9:调用方据此刻画销账口径) */
263
+ deliver: (ctx: MessageContext, text: string) => Promise<boolean>
264
+ /** 同 deliver;彻底失败时贴条待下次消化并返回 false */
265
+ safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
228
266
  sendReply: (ctx: MessageContext, text: string) => Promise<void>
229
267
  }
230
268
 
231
269
  // 投递域门面。lastCtx 为跨域共享状态(bridge 拥有写权),本域只读——
232
270
  // 用于推送/批量行的被动窗口内降级判断与主动通道选择。
271
+ // pushGate=出站推送门(owner 2026-11-14):锚定会话≠用户当前绑定即拦截。
233
272
  export function createDelivery(
234
273
  config: Config,
235
274
  lastCtx: ReadonlyMap<string, MessageContext>,
275
+ pushGate?: (userId: string, anchorSessionId: string) => boolean,
276
+ quotaFile?: string,
236
277
  ): Delivery {
237
278
  const PUSH_MIN_GAP_MS = 2000 // 用户级节流:最快 2 秒一批
238
279
  const PUSH_MAX_LINES = 6 // 队列上限:洪峰丢最旧,防积压
239
- // 债务D4(2026-10-13 官方文档查证):主动消息频控 = 单关系 1000 条/天 + 20/qpm,
240
- // Bot 维度认证 10/qps(超限报 40034100)。原自设 15/天过度保守 → 默认 100 留
241
- // 余量,可用 env QQ_ACTIVE_DAILY_LIMIT 覆盖。
242
- const ACTIVE_DAILY_LIMIT = Number(process.env.QQ_ACTIVE_DAILY_LIMIT ?? 100)
243
-
244
- // B-msgid(2026-10-29,吸收 dsh transport/msgid-cache):主动降级前尝试让发送
280
+ // 主动配额(2026-11-18 owner 裁定「严格依据 QQ 官方执行,测试除外」):
281
+ // 官方口径 = 单关系 1000 条/天 + 20 条/分钟(Bot 维度另有 10 次/秒,超限报 40034100;
282
+ // 官方事实见文件头 D4 注释)。据此拆两维执行——
283
+ // ① 日预算默认对齐官方 1000(不再自设 1/10 软预算),耗尽拒发 + 告警一次;
284
+ // ② 分钟维滚动窗口节流(20/min):超限不拒发,睡到最老记录滑出窗口再发——
285
+ // 把官方 40034100 拒绝消灭在出发前。
286
+ // env 逃生门保留(测试造小配额/运维调整):QQ_ACTIVE_DAILY_LIMIT / QQ_ACTIVE_MINUTE_LIMIT。
287
+ const ACTIVE_DAILY_LIMIT = resolveActiveLimit(process.env.QQ_ACTIVE_DAILY_LIMIT, 1000)
288
+ const ACTIVE_MINUTE_LIMIT = resolveActiveLimit(process.env.QQ_ACTIVE_MINUTE_LIMIT, 20)
289
+ // 该用户最近主动发送时刻(滚动 60s 窗,内存态——重启即清空,天预算仍落盘兜底)
290
+ const activeMinuteLog = new Map<string, number[]>()
291
+
292
+ // B-msgid(2026-10-29,吸收自 dsh-qqbot 的 msgid 缓存机制):主动降级前尝试让发送
245
293
  // "骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
246
294
  // 窗口口径保守取 5 分钟(社区亦有 60 分钟说法;骑失败无副作用自动回落真主动,
247
295
  // 故从保守值起步,可用 QQ_PASSIVE_RIDE_WINDOW_MS 调整)。
@@ -266,16 +314,17 @@ export function createDelivery(
266
314
  // 记账点在 sendReply 成功路径(统一出口,bridge 直调与 deliver 共用)。
267
315
  const passiveLimiter = new ReplyLimiter()
268
316
  // O5:恢复落盘配额(非当日条目由 deliver 按 day 字段自然重置)
269
- for (const [uid, q] of Object.entries(loadQuotaMap())) activeQuota.set(uid, q)
317
+ const QUOTA_FILE = quotaFile ?? DEFAULT_QUOTA_FILE
318
+ for (const [uid, q] of Object.entries(loadQuotaMap(QUOTA_FILE))) activeQuota.set(uid, q)
270
319
 
271
- function enqueuePush(userId: string, line: string): void {
320
+ function enqueuePush(userId: string, line: string, anchorSessionId?: string): void {
272
321
  let q = pushQueues.get(userId)
273
322
  if (!q) {
274
323
  q = { lastSent: 0, timer: null, lines: [] }
275
324
  pushQueues.set(userId, q)
276
325
  }
277
326
  if (q.lines.length >= PUSH_MAX_LINES) q.lines.shift()
278
- q.lines.push(line)
327
+ q.lines.push({ line, ...(anchorSessionId ? { anchor: anchorSessionId } : {}) })
279
328
  if (q.timer) return
280
329
  const wait = Math.max(0, PUSH_MIN_GAP_MS - (Date.now() - q.lastSent))
281
330
  q.timer = setTimeout(() => {
@@ -292,13 +341,29 @@ export function createDelivery(
292
341
  q.lines.length = 0
293
342
  return
294
343
  }
295
- const text = q.lines.splice(0, q.lines.length).map((l) => `· ${l}`).join("\n")
344
+ // 按锚定会话分组:同组行合并投递;锚定≠当前绑定的整组被推送门丢弃(历史可回读)。
345
+ const batches: Array<{ anchor?: string; lines: string[] }> = []
346
+ for (const item of q.lines.splice(0, q.lines.length)) {
347
+ const last = batches[batches.length - 1]
348
+ if (last && last.anchor === item.anchor) last.lines.push(item.line)
349
+ else batches.push({ ...(item.anchor ? { anchor: item.anchor } : {}), lines: [item.line] })
350
+ }
296
351
  q.lastSent = Date.now()
297
- try {
298
- await deliver(ctx, text)
299
- } catch (error) {
300
- undelivered.add(userId) // P 项:观察推送彻底失败 → 贴条待下次消化
301
- console.error("[bridge] 观察推送失败(被动+主动均失败,丢弃本批):", error)
352
+ for (const batch of batches) {
353
+ if (batch.anchor && pushGate && !pushGate(userId, batch.anchor)) {
354
+ console.log(
355
+ `[push-gate] 观察推送整组拦截:绑定已切走 anchor=${batch.anchor.slice(0, 12)}… user=${userId.slice(0, 8)}… count=${batch.lines.length}`,
356
+ )
357
+ continue
358
+ }
359
+ const text = batch.lines.map((l) => `· ${l}`).join("\n")
360
+ const outCtx: MessageContext = batch.anchor ? { ...ctx, anchorSessionId: batch.anchor } : ctx
361
+ try {
362
+ await deliver(outCtx, text)
363
+ } catch (error) {
364
+ undelivered.add(userId) // P 项:观察推送彻底失败 → 贴条待下次消化
365
+ console.error("[bridge] 观察推送失败(被动+主动均失败,丢弃本批):", error)
366
+ }
302
367
  }
303
368
  }
304
369
 
@@ -308,19 +373,28 @@ export function createDelivery(
308
373
  //(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
309
374
  // P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
310
375
  // 投递失败则把贴条放回(留待下次),成功才算消化。
311
- async function deliver(ctx: MessageContext, text: string): Promise<void> {
376
+ async function deliver(ctx: MessageContext, text: string): Promise<boolean> {
377
+ // 出站推送门(design §3.4,owner 2026-11-14 会话隔离裁定):QQ 窗只呈现当前绑定
378
+ // 会话——锚定会话≠当前绑定即不推(结果已入锚定会话历史,可经历史/桌面端回读)。
379
+ if (ctx.anchorSessionId && pushGate && !pushGate(ctx.userId, ctx.anchorSessionId)) {
380
+ console.log(
381
+ `[push-gate] 出站拦截:绑定已切走 anchor=${ctx.anchorSessionId.slice(0, 12)}… user=${ctx.userId.slice(0, 8)}… chars=${text.length}`,
382
+ )
383
+ return false
384
+ }
312
385
  const now = Date.now()
313
386
  // 跨进程原子占位:直答/镜像/恢复即使落在不同执行体,同文长回复也只放行一次。
314
387
  const attemptKey = reserveDeliveryAttempt(ctx.userId, text, now)
315
388
  if (!attemptKey) {
316
389
  console.log(`[bridge] 同文长回复已在 24h 内投递,跳过重复出站 user=${ctx.userId}`)
317
- return
390
+ return false
318
391
  }
319
392
  const hadNotice = undelivered.delete(ctx.userId)
320
393
  // QQ 渲染适配:有序列表改写,防 QQ 端跨段落续编(桌面所见=QQ 所见)
321
394
  const body = qqListNormalize(hadNotice ? UNDELIVERED_NOTICE + text : text)
322
395
  try {
323
396
  await deliverCore(ctx, body)
397
+ return true
324
398
  } catch (error) {
325
399
  // 发送失败不占去重位,后续恢复/重试仍可送达。
326
400
  releaseDeliveryAttempt(ctx.userId, text, now)
@@ -373,28 +447,29 @@ export function createDelivery(
373
447
  if (q.count >= ACTIVE_DAILY_LIMIT) {
374
448
  if (!q.warned) {
375
449
  q.warned = true
376
- saveQuotaMap(activeQuota) // O5:告警态也落盘
377
- console.warn(`[bridge] 用户 ${ctx.userId} 今日主动推送配额用尽,窗口外消息无法送达`)
450
+ saveQuotaMap(QUOTA_FILE, activeQuota) // O5:告警态也落盘
451
+ console.warn(`[bridge] 用户 ${ctx.userId} 今日主动消息达 QQ 官方日上限(${ACTIVE_DAILY_LIMIT} 条/关系),窗口外消息无法送达`)
378
452
  try {
379
- await sendActive(ctx, "⚠️ 今日主动推送配额已用尽(QQ 限制),窗口外消息明日恢复送达")
453
+ await sendActive(ctx, `⚠️ 今日主动消息已达 QQ 官方上限(单关系 ${ACTIVE_DAILY_LIMIT} 条/天),窗口外消息明日恢复送达`)
380
454
  } catch {
381
455
  // 告警也发不出去就静默
382
456
  }
383
457
  }
384
- throw new Error("主动消息配额已用尽,本条无法送达")
458
+ throw new Error("主动消息已达 QQ 官方日上限,本条无法送达")
385
459
  }
386
460
  const activeIds = await sendActive(ctx, text)
387
461
  for (const id of activeIds) recordMessage(scopeKeyOf(ctx), id, text)
388
462
  q.count++
389
- saveQuotaMap(activeQuota) // O5:计数落盘,跨重启不归零
463
+ saveQuotaMap(QUOTA_FILE, activeQuota) // O5:计数落盘,跨重启不归零
390
464
  }
391
465
 
392
- async function safeDeliver(c: MessageContext, text: string): Promise<void> {
466
+ async function safeDeliver(c: MessageContext, text: string): Promise<boolean> {
393
467
  try {
394
- await deliver(c, text)
468
+ return await deliver(c, text)
395
469
  } catch (error) {
396
470
  undelivered.add(c.userId) // P 项:最终失败 → 贴条待下次消化
397
471
  console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
472
+ return false
398
473
  }
399
474
  }
400
475
 
@@ -402,25 +477,41 @@ export function createDelivery(
402
477
  // passiveMsgId(B-msgid 2026-10-29):"骑"被动窗口时传入,平台接受则按被动计。
403
478
  // 返回服务端回执消息 id 列表(引用解析缓存登记用)。
404
479
  async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<string[]> {
480
+ // 分钟维节流(官方 20 条/分钟,2026-11-18 严格官方化):滚动窗满 → 睡到窗口滑动再发。
481
+ // 骑被动窗口的投递(passiveMsgId 非空)平台按被动计,不占主动分钟窗。
482
+ if (!passiveMsgId) {
483
+ const waitMs = minuteWindowWaitMs(activeMinuteLog.get(ctx.userId) ?? [], Date.now(), ACTIVE_MINUTE_LIMIT)
484
+ if (waitMs > 0) {
485
+ console.log(`[bridge] 主动消息分钟窗已满(${ACTIVE_MINUTE_LIMIT}/min),等待 ${Math.ceil(waitMs / 1000)}s 后发送 user=${ctx.userId.slice(0, 8)}…`)
486
+ await new Promise((r) => setTimeout(r, waitMs))
487
+ }
488
+ }
405
489
  const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
406
490
  const seq = getNextMsgSeq(passiveMsgId ?? "")
407
491
  const isGroup = ctx.type === "group" && ctx.groupId
492
+ // 主动 markdown 同样走围栏归一(与被动回复同口径,防未闭合/空围栏对渲染成空卡片)
493
+ const mdText = normalizeOutboundMarkdown(text)
494
+ const record = (ids: string[]): string[] => {
495
+ // 发送成功才记主动分钟窗(失败不计,同被动限额器口径)
496
+ if (!passiveMsgId && ids.length > 0) logActiveSend(activeMinuteLog, ctx.userId, Date.now())
497
+ return ids
498
+ }
408
499
  try {
409
500
  if (isGroup) {
410
- const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, true)
411
- return r?.id ? [r.id] : []
501
+ const r = await sendGroupMessage(token, ctx.groupId!, mdText, passiveMsgId, seq, true)
502
+ return record(r?.id ? [r.id] : [])
412
503
  }
413
- const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, true)
414
- return r?.id ? [r.id] : []
504
+ const r = await sendC2CMessage(token, ctx.userId, mdText, passiveMsgId, seq, true)
505
+ return record(r?.id ? [r.id] : [])
415
506
  } catch (error) {
416
507
  console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error)
417
508
  }
418
509
  if (isGroup) {
419
510
  const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, false)
420
- return r?.id ? [r.id] : []
511
+ return record(r?.id ? [r.id] : [])
421
512
  }
422
513
  const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false)
423
- return r?.id ? [r.id] : []
514
+ return record(r?.id ? [r.id] : [])
424
515
  }
425
516
 
426
517
  async function sendReply(ctx: MessageContext, text: string): Promise<void> {