@linjz/opencode-qqbot 0.3.5 → 0.3.6

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 (42) hide show
  1. package/README.md +74 -39
  2. package/bin/openqq-setup.mjs +50 -50
  3. package/bin/openqq.js +47 -47
  4. package/dist/opencode-qqbot-plugin.js +10 -1
  5. package/dist/openqq-bot.js +360 -69
  6. package/package.json +69 -61
  7. package/src/_FOLDER.md +19 -19
  8. package/src/bridge.ts +934 -796
  9. package/src/commands.ts +554 -514
  10. package/src/config.ts +121 -121
  11. package/src/core/bot-launcher.ts +146 -134
  12. package/src/core/card-approval.ts +146 -146
  13. package/src/core/context-buffer.ts +78 -78
  14. package/src/core/delivery.ts +284 -284
  15. package/src/core/discovery.ts +151 -151
  16. package/src/core/error-rescue.ts +33 -0
  17. package/src/core/file-log.ts +45 -45
  18. package/src/core/form-bridge.ts +304 -304
  19. package/src/core/inflight-journal.ts +212 -151
  20. package/src/core/instance-lock.ts +122 -122
  21. package/src/core/linkwatch.ts +195 -195
  22. package/src/core/message-queue.ts +80 -0
  23. package/src/core/mirror.ts +173 -173
  24. package/src/core/permission.ts +301 -301
  25. package/src/core/reply-limiter.ts +106 -106
  26. package/src/core/send-media.ts +90 -90
  27. package/src/core/util.ts +8 -8
  28. package/src/index.ts +162 -162
  29. package/src/opencode/_FOLDER.md +11 -11
  30. package/src/opencode/client.ts +387 -386
  31. package/src/opencode/eventstream.ts +138 -138
  32. package/src/opencode/history.ts +143 -143
  33. package/src/opencode/mirror.ts +65 -65
  34. package/src/opencode/sessions.ts +158 -158
  35. package/src/plugin-entry.ts +112 -112
  36. package/src/qq/_FOLDER.md +13 -13
  37. package/src/qq/api.ts +539 -539
  38. package/src/qq/gateway.ts +492 -492
  39. package/src/qq/media.ts +219 -204
  40. package/src/qq/sender.ts +300 -300
  41. package/src/qq/types.ts +154 -152
  42. package/tsconfig.json +24 -24
@@ -1,284 +1,284 @@
1
- // @input: ../config, ../qq/types, ../qq/api, ../qq/sender, fs/path/os
2
- // @output: createDelivery
3
- // @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
4
- // 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
5
- import { existsSync, readFileSync, writeFileSync } from "fs"
6
- import { join } from "path"
7
- import { homedir } from "os"
8
- import type { Config } from "../config.js"
9
- import type { MessageContext } from "../qq/types.js"
10
- import { getAccessToken, sendC2CMessage, sendGroupMessage, getNextMsgSeq } from "../qq/api.js"
11
- import { replyToQQ } from "../qq/sender.js"
12
- import { ReplyLimiter } from "./reply-limiter.js"
13
- import { recordMessage, scopeKeyOf } from "./context-buffer.js"
14
-
15
- // 用户级推送队列:节流合并(主动消息配额记账已移至 activeQuota 共享)
16
- interface PushQueue {
17
- lastSent: number
18
- timer: ReturnType<typeof setTimeout> | null
19
- lines: string[]
20
- }
21
-
22
- // O5(2026-10-15,P2-4b):主动配额落盘——跨重启不归零,防日配额轻微超发。
23
- const QUOTA_FILE = join(homedir(), ".openqq", "quota.json")
24
-
25
- function loadQuotaMap(): Record<string, { day: string; count: number; warned: boolean }> {
26
- try {
27
- if (existsSync(QUOTA_FILE)) {
28
- const raw = readFileSync(QUOTA_FILE, "utf-8")
29
- const obj = JSON.parse(raw)
30
- if (obj && typeof obj === "object" && !Array.isArray(obj)) {
31
- const out: Record<string, { day: string; count: number; warned: boolean }> = {}
32
- for (const [k, v] of Object.entries(obj)) {
33
- const e = v as { day?: unknown; count?: unknown; warned?: unknown }
34
- if (typeof e?.day === "string" && typeof e.count === "number") {
35
- out[k] = { day: e.day, count: e.count, warned: Boolean(e.warned) }
36
- }
37
- }
38
- return out
39
- }
40
- }
41
- } catch {
42
- // 损坏即空
43
- }
44
- return {}
45
- }
46
-
47
- function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warned: boolean }>): void {
48
- try {
49
- writeFileSync(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)))
50
- } catch (error) {
51
- console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error)
52
- }
53
- }
54
-
55
- // P 项(2026-10-30,吸收竞品 pendingNotice 模式):发送彻底失败不静默——
56
- // 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
57
- export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
58
-
59
- // B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
60
- // 同一聊天类型、时间戳在窗口内才有效;任何不对齐都返回 undefined(回落真主动)。
61
- export function selectRideMsgId(
62
- last: MessageContext | undefined,
63
- ctx: MessageContext,
64
- now: number,
65
- windowMs: number,
66
- ): string | undefined {
67
- if (!last?.msgId) return undefined
68
- if (last.type !== ctx.type) return undefined
69
- const ts = Number(last.timestamp ?? 0)
70
- if (!Number.isFinite(ts) || ts <= 0) return undefined
71
- if (now - ts > windowMs) return undefined
72
- return last.msgId
73
- }
74
-
75
- export interface Delivery {
76
- enqueuePush: (userId: string, line: string) => void
77
- deliver: (ctx: MessageContext, text: string) => Promise<void>
78
- safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
79
- sendReply: (ctx: MessageContext, text: string) => Promise<void>
80
- }
81
-
82
- // 投递域门面。lastCtx 为跨域共享状态(bridge 拥有写权),本域只读——
83
- // 用于推送/批量行的被动窗口内降级判断与主动通道选择。
84
- export function createDelivery(
85
- config: Config,
86
- lastCtx: ReadonlyMap<string, MessageContext>,
87
- ): Delivery {
88
- const PUSH_MIN_GAP_MS = 2000 // 用户级节流:最快 2 秒一批
89
- const PUSH_MAX_LINES = 6 // 队列上限:洪峰丢最旧,防积压
90
- // 债务D4(2026-10-13 官方文档查证):主动消息频控 = 单关系 1000 条/天 + 20/qpm,
91
- // Bot 维度认证 10/qps(超限报 40034100)。原自设 15/天过度保守 → 默认 100 留
92
- // 余量,可用 env QQ_ACTIVE_DAILY_LIMIT 覆盖。
93
- const ACTIVE_DAILY_LIMIT = Number(process.env.QQ_ACTIVE_DAILY_LIMIT ?? 100)
94
-
95
- // B-msgid(2026-10-29,吸收 dsh transport/msgid-cache):主动降级前尝试让发送
96
- // "骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
97
- // 窗口口径保守取 5 分钟(社区亦有 60 分钟说法;骑失败无副作用自动回落真主动,
98
- // 故从保守值起步,可用 QQ_PASSIVE_RIDE_WINDOW_MS 调整)。
99
- const RIDE_WINDOW_MS = (() => {
100
- const n = Number(process.env.QQ_PASSIVE_RIDE_WINDOW_MS ?? "300000")
101
- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 300_000
102
- })()
103
-
104
- // J-轻(2026-10-30,用户拍板固化):伪流式错峰——多片回复片间间隔(默认 300ms),
105
- // 配合 B3 typing 指示,长答案逐段到达体感近打字机;0=关闭恢复一次性全发。
106
- const STREAM_STAGGER_MS = (() => {
107
- const n = Number(process.env.QQ_STREAM_STAGGER_MS ?? "300")
108
- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 300
109
- })()
110
-
111
- const pushQueues = new Map<string, PushQueue>()
112
- // P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
113
- const undelivered = new Set<string>()
114
- const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
115
- // B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
116
- // 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
117
- // 记账点在 sendReply 成功路径(统一出口,bridge 直调与 deliver 共用)。
118
- const passiveLimiter = new ReplyLimiter()
119
- // O5:恢复落盘配额(非当日条目由 deliver 按 day 字段自然重置)
120
- for (const [uid, q] of Object.entries(loadQuotaMap())) activeQuota.set(uid, q)
121
-
122
- function enqueuePush(userId: string, line: string): void {
123
- let q = pushQueues.get(userId)
124
- if (!q) {
125
- q = { lastSent: 0, timer: null, lines: [] }
126
- pushQueues.set(userId, q)
127
- }
128
- if (q.lines.length >= PUSH_MAX_LINES) q.lines.shift()
129
- q.lines.push(line)
130
- if (q.timer) return
131
- const wait = Math.max(0, PUSH_MIN_GAP_MS - (Date.now() - q.lastSent))
132
- q.timer = setTimeout(() => {
133
- q!.timer = null
134
- void flushPush(userId)
135
- }, wait)
136
- }
137
-
138
- async function flushPush(userId: string): Promise<void> {
139
- const q = pushQueues.get(userId)
140
- const ctx = lastCtx.get(userId)
141
- if (!q || q.lines.length === 0) return
142
- if (!ctx) {
143
- q.lines.length = 0
144
- return
145
- }
146
- const text = q.lines.splice(0, q.lines.length).map((l) => `· ${l}`).join("\n")
147
- q.lastSent = Date.now()
148
- try {
149
- await deliver(ctx, text)
150
- } catch (error) {
151
- undelivered.add(userId) // P 项:观察推送彻底失败 → 贴条待下次消化
152
- console.error("[bridge] 观察推送失败(被动+主动均失败,丢弃本批):", error)
153
- }
154
- }
155
-
156
- // 统一投递:被动回复优先(ctx.msg_id,5 分钟窗口内、无配额消耗);
157
- // 窗口过期/失败降级主动消息(计日配额,超限告警一次)。
158
- // 观察推送与最终回复共用——超长回合(>被动窗口)的答案靠它送达
159
- //(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
160
- // P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
161
- // 投递失败则把贴条放回(留待下次),成功才算消化。
162
- async function deliver(ctx: MessageContext, text: string): Promise<void> {
163
- const hadNotice = undelivered.delete(ctx.userId)
164
- const body = hadNotice ? UNDELIVERED_NOTICE + text : text
165
- try {
166
- await deliverCore(ctx, body)
167
- } catch (error) {
168
- if (hadNotice) undelivered.add(ctx.userId)
169
- throw error
170
- }
171
- }
172
-
173
- async function deliverCore(ctx: MessageContext, text: string): Promise<void> {
174
- // B1:被动尝试前预判额度,耗尽/过期直接走主动(避免注定被拒的被动请求)
175
- const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null
176
- if (passive?.shouldFallbackToProactive) {
177
- console.log(
178
- `[bridge] 被动回复${passive.fallbackReason === "expired" ? "窗口已过期" : "次数已耗尽"},直接走主动通道: msgId=${ctx.msgId}`,
179
- )
180
- } else {
181
- try {
182
- await sendReply(ctx, text)
183
- return
184
- } catch (error) {
185
- console.warn(
186
- "[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:",
187
- error instanceof Error ? error.message : error,
188
- )
189
- }
190
- }
191
-
192
- // B-msgid(吸收 dsh msgid-cache,2026-10-29):主动降级前尝试"骑"该用户最近
193
- // 的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额、记 B1 账本);
194
- // 骑失败无副作用,回落下方真主动流程。
195
- const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS)
196
- if (rideMsgId) {
197
- try {
198
- const rideIds = await sendActive(ctx, text, rideMsgId)
199
- passiveLimiter.record(rideMsgId)
200
- for (const id of rideIds) recordMessage(scopeKeyOf(ctx), id, text)
201
- console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`)
202
- return
203
- } catch {
204
- console.log("[bridge] 骑被动窗口失败(窗口可能已过),回落真主动消息")
205
- }
206
- }
207
-
208
- const today = new Date().toISOString().slice(0, 10)
209
- let q = activeQuota.get(ctx.userId)
210
- if (!q || q.day !== today) {
211
- q = { day: today, count: 0, warned: false }
212
- activeQuota.set(ctx.userId, q)
213
- }
214
- if (q.count >= ACTIVE_DAILY_LIMIT) {
215
- if (!q.warned) {
216
- q.warned = true
217
- saveQuotaMap(activeQuota) // O5:告警态也落盘
218
- console.warn(`[bridge] 用户 ${ctx.userId} 今日主动推送配额用尽,窗口外消息无法送达`)
219
- try {
220
- await sendActive(ctx, "⚠️ 今日主动推送配额已用尽(QQ 限制),窗口外消息明日恢复送达")
221
- } catch {
222
- // 告警也发不出去就静默
223
- }
224
- }
225
- throw new Error("主动消息配额已用尽,本条无法送达")
226
- }
227
- const activeIds = await sendActive(ctx, text)
228
- for (const id of activeIds) recordMessage(scopeKeyOf(ctx), id, text)
229
- q.count++
230
- saveQuotaMap(activeQuota) // O5:计数落盘,跨重启不归零
231
- }
232
-
233
- async function safeDeliver(c: MessageContext, text: string): Promise<void> {
234
- try {
235
- await deliver(c, text)
236
- } catch (error) {
237
- undelivered.add(c.userId) // P 项:最终失败 → 贴条待下次消化
238
- console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
239
- }
240
- }
241
-
242
- // 主动消息(不带 msg_id):markdown 优先,失败回退纯文本。
243
- // passiveMsgId(B-msgid 2026-10-29):"骑"被动窗口时传入,平台接受则按被动计。
244
- // 返回服务端回执消息 id 列表(引用解析缓存登记用)。
245
- async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<string[]> {
246
- const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
247
- const seq = getNextMsgSeq(passiveMsgId ?? "")
248
- const isGroup = ctx.type === "group" && ctx.groupId
249
- try {
250
- if (isGroup) {
251
- const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, true)
252
- return r?.id ? [r.id] : []
253
- }
254
- const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, true)
255
- return r?.id ? [r.id] : []
256
- } catch (error) {
257
- console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error)
258
- }
259
- if (isGroup) {
260
- const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, false)
261
- return r?.id ? [r.id] : []
262
- }
263
- const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false)
264
- return r?.id ? [r.id] : []
265
- }
266
-
267
- async function sendReply(ctx: MessageContext, text: string): Promise<void> {
268
- const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret)
269
- // J-轻:伪流式错峰(多片时隔 300ms 逐段到达);replyToQQ 返回片数与服务端消息 id
270
- const result = await replyToQQ(accessToken, ctx, text, config.maxReplyLength, {
271
- staggerMs: STREAM_STAGGER_MS,
272
- })
273
- // B1:被动回复成功才记额度(失败不计,避免虚耗);按片记账——平台限额按"条"计,
274
- // 多片回复此前少计 N-1(J-轻顺手修正);bridge 直调与 deliver 共用此出口
275
- if (ctx.msgId) {
276
- for (let i = 0; i < result.chunks; i++) passiveLimiter.record(ctx.msgId)
277
- }
278
- // 缺口 1:我方出站回复登记进上下文缓存(引用解析可命中 AI 答案)
279
- const scope = scopeKeyOf(ctx)
280
- for (const id of result.ids) recordMessage(scope, id, text)
281
- }
282
-
283
- return { enqueuePush, deliver, safeDeliver, sendReply }
284
- }
1
+ // @input: ../config, ../qq/types, ../qq/api, ../qq/sender, fs/path/os
2
+ // @output: createDelivery
3
+ // @pos: 根层/core - 投递域(O7c 2026-10-15 自 bridge.ts 拆出:统一投递
4
+ // 被动→主动降级、日配额记账与落盘、观察推送节流队列、主动/被动通道发送)
5
+ import { existsSync, readFileSync, writeFileSync } from "fs"
6
+ import { join } from "path"
7
+ import { homedir } from "os"
8
+ import type { Config } from "../config.js"
9
+ import type { MessageContext } from "../qq/types.js"
10
+ import { getAccessToken, sendC2CMessage, sendGroupMessage, getNextMsgSeq } from "../qq/api.js"
11
+ import { replyToQQ } from "../qq/sender.js"
12
+ import { ReplyLimiter } from "./reply-limiter.js"
13
+ import { recordMessage, scopeKeyOf } from "./context-buffer.js"
14
+
15
+ // 用户级推送队列:节流合并(主动消息配额记账已移至 activeQuota 共享)
16
+ interface PushQueue {
17
+ lastSent: number
18
+ timer: ReturnType<typeof setTimeout> | null
19
+ lines: string[]
20
+ }
21
+
22
+ // O5(2026-10-15,P2-4b):主动配额落盘——跨重启不归零,防日配额轻微超发。
23
+ const QUOTA_FILE = join(homedir(), ".openqq", "quota.json")
24
+
25
+ function loadQuotaMap(): Record<string, { day: string; count: number; warned: boolean }> {
26
+ try {
27
+ if (existsSync(QUOTA_FILE)) {
28
+ const raw = readFileSync(QUOTA_FILE, "utf-8")
29
+ const obj = JSON.parse(raw)
30
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) {
31
+ const out: Record<string, { day: string; count: number; warned: boolean }> = {}
32
+ for (const [k, v] of Object.entries(obj)) {
33
+ const e = v as { day?: unknown; count?: unknown; warned?: unknown }
34
+ if (typeof e?.day === "string" && typeof e.count === "number") {
35
+ out[k] = { day: e.day, count: e.count, warned: Boolean(e.warned) }
36
+ }
37
+ }
38
+ return out
39
+ }
40
+ }
41
+ } catch {
42
+ // 损坏即空
43
+ }
44
+ return {}
45
+ }
46
+
47
+ function saveQuotaMap(m: ReadonlyMap<string, { day: string; count: number; warned: boolean }>): void {
48
+ try {
49
+ writeFileSync(QUOTA_FILE, JSON.stringify(Object.fromEntries(m)))
50
+ } catch (error) {
51
+ console.warn("[bridge] 配额落盘失败:", error instanceof Error ? error.message : error)
52
+ }
53
+ }
54
+
55
+ // P 项(2026-10-30,吸收竞品 pendingNotice 模式):发送彻底失败不静默——
56
+ // 记"有未送达消息",下一次成功投递时前缀贴条告知用户(导出供测试)。
57
+ export const UNDELIVERED_NOTICE = "(此前有未能送达的消息)\n"
58
+
59
+ // B-msgid 纯函数(导出供测试,2026-10-29):挑选可"骑"的被动 msg_id——
60
+ // 同一聊天类型、时间戳在窗口内才有效;任何不对齐都返回 undefined(回落真主动)。
61
+ export function selectRideMsgId(
62
+ last: MessageContext | undefined,
63
+ ctx: MessageContext,
64
+ now: number,
65
+ windowMs: number,
66
+ ): string | undefined {
67
+ if (!last?.msgId) return undefined
68
+ if (last.type !== ctx.type) return undefined
69
+ const ts = Number(last.timestamp ?? 0)
70
+ if (!Number.isFinite(ts) || ts <= 0) return undefined
71
+ if (now - ts > windowMs) return undefined
72
+ return last.msgId
73
+ }
74
+
75
+ export interface Delivery {
76
+ enqueuePush: (userId: string, line: string) => void
77
+ deliver: (ctx: MessageContext, text: string) => Promise<void>
78
+ safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
79
+ sendReply: (ctx: MessageContext, text: string) => Promise<void>
80
+ }
81
+
82
+ // 投递域门面。lastCtx 为跨域共享状态(bridge 拥有写权),本域只读——
83
+ // 用于推送/批量行的被动窗口内降级判断与主动通道选择。
84
+ export function createDelivery(
85
+ config: Config,
86
+ lastCtx: ReadonlyMap<string, MessageContext>,
87
+ ): Delivery {
88
+ const PUSH_MIN_GAP_MS = 2000 // 用户级节流:最快 2 秒一批
89
+ const PUSH_MAX_LINES = 6 // 队列上限:洪峰丢最旧,防积压
90
+ // 债务D4(2026-10-13 官方文档查证):主动消息频控 = 单关系 1000 条/天 + 20/qpm,
91
+ // Bot 维度认证 10/qps(超限报 40034100)。原自设 15/天过度保守 → 默认 100 留
92
+ // 余量,可用 env QQ_ACTIVE_DAILY_LIMIT 覆盖。
93
+ const ACTIVE_DAILY_LIMIT = Number(process.env.QQ_ACTIVE_DAILY_LIMIT ?? 100)
94
+
95
+ // B-msgid(2026-10-29,吸收 dsh transport/msgid-cache):主动降级前尝试让发送
96
+ // "骑"该用户最近的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额)。
97
+ // 窗口口径保守取 5 分钟(社区亦有 60 分钟说法;骑失败无副作用自动回落真主动,
98
+ // 故从保守值起步,可用 QQ_PASSIVE_RIDE_WINDOW_MS 调整)。
99
+ const RIDE_WINDOW_MS = (() => {
100
+ const n = Number(process.env.QQ_PASSIVE_RIDE_WINDOW_MS ?? "300000")
101
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 300_000
102
+ })()
103
+
104
+ // J-轻(2026-10-30,用户拍板固化):伪流式错峰——多片回复片间间隔(默认 300ms),
105
+ // 配合 B3 typing 指示,长答案逐段到达体感近打字机;0=关闭恢复一次性全发。
106
+ const STREAM_STAGGER_MS = (() => {
107
+ const n = Number(process.env.QQ_STREAM_STAGGER_MS ?? "300")
108
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 300
109
+ })()
110
+
111
+ const pushQueues = new Map<string, PushQueue>()
112
+ // P 项:彻底投递失败的用户集合(贴条状态),下次成功投递时消化
113
+ const undelivered = new Set<string>()
114
+ const activeQuota = new Map<string, { day: string; count: number; warned: boolean }>()
115
+ // B1(2026-10-29,吸收自 openclaw-qqbot reply-limiter):被动回复限额预判——
116
+ // 单 msgId 4 次/1h 窗口,耗尽/过期直接转主动,省一次注定被拒的 API 往返。
117
+ // 记账点在 sendReply 成功路径(统一出口,bridge 直调与 deliver 共用)。
118
+ const passiveLimiter = new ReplyLimiter()
119
+ // O5:恢复落盘配额(非当日条目由 deliver 按 day 字段自然重置)
120
+ for (const [uid, q] of Object.entries(loadQuotaMap())) activeQuota.set(uid, q)
121
+
122
+ function enqueuePush(userId: string, line: string): void {
123
+ let q = pushQueues.get(userId)
124
+ if (!q) {
125
+ q = { lastSent: 0, timer: null, lines: [] }
126
+ pushQueues.set(userId, q)
127
+ }
128
+ if (q.lines.length >= PUSH_MAX_LINES) q.lines.shift()
129
+ q.lines.push(line)
130
+ if (q.timer) return
131
+ const wait = Math.max(0, PUSH_MIN_GAP_MS - (Date.now() - q.lastSent))
132
+ q.timer = setTimeout(() => {
133
+ q!.timer = null
134
+ void flushPush(userId)
135
+ }, wait)
136
+ }
137
+
138
+ async function flushPush(userId: string): Promise<void> {
139
+ const q = pushQueues.get(userId)
140
+ const ctx = lastCtx.get(userId)
141
+ if (!q || q.lines.length === 0) return
142
+ if (!ctx) {
143
+ q.lines.length = 0
144
+ return
145
+ }
146
+ const text = q.lines.splice(0, q.lines.length).map((l) => `· ${l}`).join("\n")
147
+ q.lastSent = Date.now()
148
+ try {
149
+ await deliver(ctx, text)
150
+ } catch (error) {
151
+ undelivered.add(userId) // P 项:观察推送彻底失败 → 贴条待下次消化
152
+ console.error("[bridge] 观察推送失败(被动+主动均失败,丢弃本批):", error)
153
+ }
154
+ }
155
+
156
+ // 统一投递:被动回复优先(ctx.msg_id,5 分钟窗口内、无配额消耗);
157
+ // 窗口过期/失败降级主动消息(计日配额,超限告警一次)。
158
+ // 观察推送与最终回复共用——超长回合(>被动窗口)的答案靠它送达
159
+ //(2026-10-13 实测教训:回合 >5 分钟时旧路径答案永久丢失)。
160
+ // P 项贴条包装:deliver 入口消化贴条状态——有待贴条则前缀拼入正文;
161
+ // 投递失败则把贴条放回(留待下次),成功才算消化。
162
+ async function deliver(ctx: MessageContext, text: string): Promise<void> {
163
+ const hadNotice = undelivered.delete(ctx.userId)
164
+ const body = hadNotice ? UNDELIVERED_NOTICE + text : text
165
+ try {
166
+ await deliverCore(ctx, body)
167
+ } catch (error) {
168
+ if (hadNotice) undelivered.add(ctx.userId)
169
+ throw error
170
+ }
171
+ }
172
+
173
+ async function deliverCore(ctx: MessageContext, text: string): Promise<void> {
174
+ // B1:被动尝试前预判额度,耗尽/过期直接走主动(避免注定被拒的被动请求)
175
+ const passive = ctx.msgId ? passiveLimiter.checkLimit(ctx.msgId) : null
176
+ if (passive?.shouldFallbackToProactive) {
177
+ console.log(
178
+ `[bridge] 被动回复${passive.fallbackReason === "expired" ? "窗口已过期" : "次数已耗尽"},直接走主动通道: msgId=${ctx.msgId}`,
179
+ )
180
+ } else {
181
+ try {
182
+ await sendReply(ctx, text)
183
+ return
184
+ } catch (error) {
185
+ console.warn(
186
+ "[bridge] 被动回复失败(可能超 5 分钟窗口),降级主动消息:",
187
+ error instanceof Error ? error.message : error,
188
+ )
189
+ }
190
+ }
191
+
192
+ // B-msgid(吸收 dsh msgid-cache,2026-10-29):主动降级前尝试"骑"该用户最近
193
+ // 的被动 msg_id——平台窗口内接受则按被动计(不耗主动配额、记 B1 账本);
194
+ // 骑失败无副作用,回落下方真主动流程。
195
+ const rideMsgId = selectRideMsgId(lastCtx.get(ctx.userId), ctx, Date.now(), RIDE_WINDOW_MS)
196
+ if (rideMsgId) {
197
+ try {
198
+ const rideIds = await sendActive(ctx, text, rideMsgId)
199
+ passiveLimiter.record(rideMsgId)
200
+ for (const id of rideIds) recordMessage(scopeKeyOf(ctx), id, text)
201
+ console.log(`[bridge] 主动降级已骑被动窗口 msgId=${rideMsgId},省一次主动配额`)
202
+ return
203
+ } catch {
204
+ console.log("[bridge] 骑被动窗口失败(窗口可能已过),回落真主动消息")
205
+ }
206
+ }
207
+
208
+ const today = new Date().toISOString().slice(0, 10)
209
+ let q = activeQuota.get(ctx.userId)
210
+ if (!q || q.day !== today) {
211
+ q = { day: today, count: 0, warned: false }
212
+ activeQuota.set(ctx.userId, q)
213
+ }
214
+ if (q.count >= ACTIVE_DAILY_LIMIT) {
215
+ if (!q.warned) {
216
+ q.warned = true
217
+ saveQuotaMap(activeQuota) // O5:告警态也落盘
218
+ console.warn(`[bridge] 用户 ${ctx.userId} 今日主动推送配额用尽,窗口外消息无法送达`)
219
+ try {
220
+ await sendActive(ctx, "⚠️ 今日主动推送配额已用尽(QQ 限制),窗口外消息明日恢复送达")
221
+ } catch {
222
+ // 告警也发不出去就静默
223
+ }
224
+ }
225
+ throw new Error("主动消息配额已用尽,本条无法送达")
226
+ }
227
+ const activeIds = await sendActive(ctx, text)
228
+ for (const id of activeIds) recordMessage(scopeKeyOf(ctx), id, text)
229
+ q.count++
230
+ saveQuotaMap(activeQuota) // O5:计数落盘,跨重启不归零
231
+ }
232
+
233
+ async function safeDeliver(c: MessageContext, text: string): Promise<void> {
234
+ try {
235
+ await deliver(c, text)
236
+ } catch (error) {
237
+ undelivered.add(c.userId) // P 项:最终失败 → 贴条待下次消化
238
+ console.error("[bridge] 消息无法送达(被动+主动均失败):", error)
239
+ }
240
+ }
241
+
242
+ // 主动消息(不带 msg_id):markdown 优先,失败回退纯文本。
243
+ // passiveMsgId(B-msgid 2026-10-29):"骑"被动窗口时传入,平台接受则按被动计。
244
+ // 返回服务端回执消息 id 列表(引用解析缓存登记用)。
245
+ async function sendActive(ctx: MessageContext, text: string, passiveMsgId?: string): Promise<string[]> {
246
+ const token = await getAccessToken(config.qq.appId, config.qq.clientSecret)
247
+ const seq = getNextMsgSeq(passiveMsgId ?? "")
248
+ const isGroup = ctx.type === "group" && ctx.groupId
249
+ try {
250
+ if (isGroup) {
251
+ const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, true)
252
+ return r?.id ? [r.id] : []
253
+ }
254
+ const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, true)
255
+ return r?.id ? [r.id] : []
256
+ } catch (error) {
257
+ console.error("[bridge] 主动 markdown 发送失败,回退纯文本:", error)
258
+ }
259
+ if (isGroup) {
260
+ const r = await sendGroupMessage(token, ctx.groupId!, text, passiveMsgId, seq, false)
261
+ return r?.id ? [r.id] : []
262
+ }
263
+ const r = await sendC2CMessage(token, ctx.userId, text, passiveMsgId, seq, false)
264
+ return r?.id ? [r.id] : []
265
+ }
266
+
267
+ async function sendReply(ctx: MessageContext, text: string): Promise<void> {
268
+ const accessToken = await getAccessToken(config.qq.appId, config.qq.clientSecret)
269
+ // J-轻:伪流式错峰(多片时隔 300ms 逐段到达);replyToQQ 返回片数与服务端消息 id
270
+ const result = await replyToQQ(accessToken, ctx, text, config.maxReplyLength, {
271
+ staggerMs: STREAM_STAGGER_MS,
272
+ })
273
+ // B1:被动回复成功才记额度(失败不计,避免虚耗);按片记账——平台限额按"条"计,
274
+ // 多片回复此前少计 N-1(J-轻顺手修正);bridge 直调与 deliver 共用此出口
275
+ if (ctx.msgId) {
276
+ for (let i = 0; i < result.chunks; i++) passiveLimiter.record(ctx.msgId)
277
+ }
278
+ // 缺口 1:我方出站回复登记进上下文缓存(引用解析可命中 AI 答案)
279
+ const scope = scopeKeyOf(ctx)
280
+ for (const id of result.ids) recordMessage(scope, id, text)
281
+ }
282
+
283
+ return { enqueuePush, deliver, safeDeliver, sendReply }
284
+ }