@linjz/opencode-qqbot 0.3.14 → 0.3.16
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.
- package/README.md +73 -5
- package/bin/openqq.js +34 -0
- package/dist/notify-cli.js +593 -0
- package/dist/opencode-qqbot-plugin.js +938 -65
- package/dist/openqq-bot.js +3585 -717
- package/dist/openqq-cli.js +791 -0
- package/dist/openqq-watchdog.js +1063 -0
- package/package.json +9 -5
- package/src/bridge.ts +1338 -157
- package/src/cli/notify-main.ts +6 -0
- package/src/cli/notify.ts +167 -0
- package/src/cli/openqq-main.ts +95 -0
- package/src/cli/service-main.ts +302 -0
- package/src/cli/watchdog-main.ts +77 -0
- package/src/commands.ts +644 -554
- package/src/config.ts +87 -2
- package/src/core/bot-control.ts +148 -0
- package/src/core/bot-launcher.ts +106 -13
- package/src/core/card-approval.ts +20 -9
- package/src/core/delivery.ts +145 -54
- package/src/core/discovery.ts +22 -4
- package/src/core/file-log.ts +35 -3
- package/src/core/form-bridge.ts +16 -7
- package/src/core/form-journal.ts +4 -4
- package/src/core/gateway-state.ts +3 -3
- package/src/core/inflight-journal.ts +214 -36
- package/src/core/instance-lock.ts +21 -6
- package/src/core/linkwatch.ts +3 -4
- package/src/core/markdown.ts +117 -0
- package/src/core/message-queue.ts +242 -91
- package/src/core/mirror.ts +222 -182
- package/src/core/notify-sink.ts +93 -0
- package/src/core/outbox.ts +10 -9
- package/src/core/permission.ts +627 -301
- package/src/core/question-form.ts +230 -0
- package/src/core/queue-view.ts +661 -0
- package/src/core/send-media.ts +32 -0
- package/src/core/storage.ts +34 -0
- package/src/core/watchdog.ts +513 -0
- package/src/core/zombie-reaper.ts +127 -0
- package/src/index.ts +140 -52
- package/src/opencode/client.ts +206 -27
- package/src/opencode/eventstream.ts +94 -12
- package/src/opencode/history.ts +4 -2
- package/src/opencode/mirror.ts +15 -2
- package/src/opencode/sessions.ts +135 -37
- package/src/plugin-entry.ts +120 -112
- package/src/qq/api.ts +165 -61
- package/src/qq/gateway.ts +80 -17
- package/src/qq/media.ts +5 -1
- package/src/qq/sender.ts +30 -18
- package/src/qq/types.ts +7 -0
package/src/core/delivery.ts
CHANGED
|
@@ -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
|
-
|
|
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(
|
|
29
|
-
const raw = readFileSync(
|
|
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(
|
|
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 =
|
|
73
|
-
let fenceMarker = ""
|
|
82
|
+
let fence: { ch: string; len: number } | null = null
|
|
74
83
|
for (let i = 0; i < lines.length; i++) {
|
|
75
|
-
|
|
84
|
+
// 围栏识别与出站兜底同源(core/markdown):支持 ``` 与 ~~~、4+ 标记长度。
|
|
85
|
+
const fm = matchFence(lines[i])
|
|
76
86
|
if (fm) {
|
|
77
|
-
if (!fence) {
|
|
78
|
-
|
|
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 ||
|
|
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
|
-
|
|
226
|
-
|
|
227
|
-
|
|
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
|
-
//
|
|
240
|
-
//
|
|
241
|
-
//
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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<
|
|
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,
|
|
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<
|
|
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!,
|
|
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,
|
|
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> {
|
package/src/core/discovery.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// 仅匹配 `${port}/api/info`:bot 的 V2 端点契约即 base=.../api(见 client.ts),
|
|
9
9
|
// 无 /api 前缀的形态与本契约不符,不采用。
|
|
10
10
|
// @input: 127.0.0.1 监听口(netstat -ano -p tcp)、/api/info 端点
|
|
11
|
-
// @output: discoverOpencode, probeOpencodeEndpoint, parseListenPorts, isOpencodeInfo, persistDiscovery
|
|
11
|
+
// @output: discoverOpencode, probeOpencodeEndpoint, parseListenPorts, isOpencodeInfo, persistDiscovery, getLastScanUnauthorized
|
|
12
12
|
// @pos: core - 端口发现(HC1,Windows only)
|
|
13
13
|
import { exec } from "node:child_process"
|
|
14
14
|
import { promisify } from "node:util"
|
|
@@ -18,6 +18,16 @@ import { homedir } from "os"
|
|
|
18
18
|
|
|
19
19
|
const execAsync = promisify(exec)
|
|
20
20
|
|
|
21
|
+
// 最近一次扫描里返回 401 的端口数(凭据不匹配诊断)。
|
|
22
|
+
// 2026-11-09 掉线事故:密码失配时每个端口都 401 → 签名全不命中,日志只剩
|
|
23
|
+
// 「无签名命中」,看起来像"服务不存在",排障要多绕很久。计数器让调用方能把
|
|
24
|
+
// 「服务不在」和「服务在但密码错」区分开。
|
|
25
|
+
let lastScanUnauthorized = 0
|
|
26
|
+
|
|
27
|
+
export function getLastScanUnauthorized(): number {
|
|
28
|
+
return lastScanUnauthorized
|
|
29
|
+
}
|
|
30
|
+
|
|
21
31
|
export interface OpencodeDiscovery {
|
|
22
32
|
baseUrl: string
|
|
23
33
|
port: number
|
|
@@ -74,7 +84,9 @@ async function listListenPorts(): Promise<number[]> {
|
|
|
74
84
|
: ["ss -tln", "netstat -tln"]
|
|
75
85
|
for (const cmd of candidates) {
|
|
76
86
|
try {
|
|
77
|
-
|
|
87
|
+
// windowsHide(2026-11-10 静默审计补齐):exec 经 cmd 中转,缺此参数时每次端口探测
|
|
88
|
+
// 弹可见控制台——owner 实证「修订后仍见 DOS 弹窗一闪」的闪现源之一。
|
|
89
|
+
const { stdout } = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024, timeout: 10_000, windowsHide: true })
|
|
78
90
|
const ports = parseListenPorts(stdout)
|
|
79
91
|
if (ports.length > 0) return ports
|
|
80
92
|
} catch (error) {
|
|
@@ -99,7 +111,10 @@ export async function probeOpencodeEndpoint(
|
|
|
99
111
|
headers.Authorization = `Basic ${Buffer.from(`opencode:${opts.password}`).toString("base64")}`
|
|
100
112
|
}
|
|
101
113
|
const res = await fetch(url, { headers, signal: ac.signal, redirect: "manual" })
|
|
102
|
-
if (!res.ok)
|
|
114
|
+
if (!res.ok) {
|
|
115
|
+
if (res.status === 401) lastScanUnauthorized++
|
|
116
|
+
return null
|
|
117
|
+
}
|
|
103
118
|
const body: unknown = JSON.parse(await res.text())
|
|
104
119
|
if (!isOpencodeInfo(body)) return null
|
|
105
120
|
return (body as InfoPayload).version as string
|
|
@@ -121,6 +136,7 @@ export async function discoverOpencode(opts?: {
|
|
|
121
136
|
if (ports.length === 0) return null
|
|
122
137
|
const started = Date.now()
|
|
123
138
|
let probed = 0
|
|
139
|
+
lastScanUnauthorized = 0
|
|
124
140
|
for (const port of ports) {
|
|
125
141
|
probed++
|
|
126
142
|
const version = await probeOpencodeEndpoint(`http://127.0.0.1:${port}/api/info`, opts)
|
|
@@ -132,7 +148,9 @@ export async function discoverOpencode(opts?: {
|
|
|
132
148
|
return hit
|
|
133
149
|
}
|
|
134
150
|
}
|
|
135
|
-
|
|
151
|
+
const unauth = lastScanUnauthorized
|
|
152
|
+
const hint = unauth > 0 ? `(其中 ${unauth} 个返回 401:凭据不匹配,检查 OPENCODE_PASSWORD / OPENCODE_BASE_URL)` : ""
|
|
153
|
+
console.log(`[discovery] 扫描 ${ports.length} 个监听口(${Date.now() - started}ms),无签名命中${hint}`)
|
|
136
154
|
return null
|
|
137
155
|
}
|
|
138
156
|
|
package/src/core/file-log.ts
CHANGED
|
@@ -1,16 +1,44 @@
|
|
|
1
1
|
// @input: fs(追加写)
|
|
2
|
-
// @output: installFileLog
|
|
3
|
-
// @pos: core - 可选文件日志双写(QQ_LOG_FILE
|
|
2
|
+
// @output: installFileLog, fileLogStatus, formatLocalTimestamp
|
|
3
|
+
// @pos: core - 可选文件日志双写(QQ_LOG_FILE 环境变量开启;2026-11-05 起默认开启)
|
|
4
4
|
//
|
|
5
5
|
// 背景(2026-10-30 清债 P2):插件拉起的 detached bot 无控制台,bun 子进程 fd
|
|
6
6
|
// 重定向实测不落盘(bot.out.log 0 字节)——改为 bot 进程内 console 双写,
|
|
7
7
|
// 不依赖 spawn 侧 fd 语义,跨运行时(bun/node)确定生效。
|
|
8
8
|
// 轮转:超 5MB 改名 .1(单代备份足够排障)。
|
|
9
|
+
// 2026-11-05:install 返回卸载函数不变;新增 fileLogStatus() 供 /status 展示
|
|
10
|
+
// 「日志最后写入时间」,堵住"日志 17:17 后无写入却无人发现"的观测缺口。
|
|
9
11
|
import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from "fs"
|
|
10
12
|
import { join } from "path"
|
|
11
13
|
|
|
12
14
|
const ROTATE_BYTES = 5 * 1024 * 1024
|
|
13
15
|
|
|
16
|
+
interface ActiveLog {
|
|
17
|
+
path: string
|
|
18
|
+
lastWriteAt: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let active: ActiveLog | null = null
|
|
22
|
+
|
|
23
|
+
/** 本地时区时间戳(含偏移,如 2026-11-05T21:09:09.292+08:00)——2026-11-05 用户反馈:
|
|
24
|
+
* 日志全是 UTC(Z 结尾),与本地时钟差 8 小时,排障要对表。统一改本地。 */
|
|
25
|
+
export function formatLocalTimestamp(d = new Date()): string {
|
|
26
|
+
const pad = (n: number, w = 2): string => String(n).padStart(w, "0")
|
|
27
|
+
const offMin = -d.getTimezoneOffset() // 本地超前 UTC 的分钟数(中国 = +480)
|
|
28
|
+
const sign = offMin >= 0 ? "+" : "-"
|
|
29
|
+
const abs = Math.abs(offMin)
|
|
30
|
+
return (
|
|
31
|
+
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
|
|
32
|
+
`T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}` +
|
|
33
|
+
`${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
|
|
34
|
+
)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 当前生效的文件日志(未安装返回 null)。 */
|
|
38
|
+
export function fileLogStatus(): { path: string; lastWriteAt: number } | null {
|
|
39
|
+
return active ? { ...active } : null
|
|
40
|
+
}
|
|
41
|
+
|
|
14
42
|
/** console.log/warn/error 双写到文件;返回卸载函数(测试用) */
|
|
15
43
|
export function installFileLog(logPath: string): () => void {
|
|
16
44
|
try {
|
|
@@ -18,13 +46,16 @@ export function installFileLog(logPath: string): () => void {
|
|
|
18
46
|
} catch {
|
|
19
47
|
/* 目录已存在或不可建——写时再兜底 */
|
|
20
48
|
}
|
|
49
|
+
const state: ActiveLog = { path: logPath, lastWriteAt: 0 }
|
|
50
|
+
active = state
|
|
21
51
|
const write = (level: string, args: unknown[]): void => {
|
|
22
52
|
try {
|
|
23
53
|
if (existsSync(logPath) && statSync(logPath).size > ROTATE_BYTES) {
|
|
24
54
|
renameSync(logPath, `${logPath}.1`)
|
|
25
55
|
}
|
|
26
56
|
const line = args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" ")
|
|
27
|
-
appendFileSync(logPath, `${
|
|
57
|
+
appendFileSync(logPath, `${formatLocalTimestamp()} [${level}] ${line}\n`, { mode: 0o600 })
|
|
58
|
+
state.lastWriteAt = Date.now()
|
|
28
59
|
} catch {
|
|
29
60
|
// 日志绝不阻断主流程
|
|
30
61
|
}
|
|
@@ -41,5 +72,6 @@ export function installFileLog(logPath: string): () => void {
|
|
|
41
72
|
console.log = orig.log
|
|
42
73
|
console.warn = orig.warn
|
|
43
74
|
console.error = orig.error
|
|
75
|
+
if (active === state) active = null
|
|
44
76
|
}
|
|
45
77
|
}
|
package/src/core/form-bridge.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext), ./form-journal
|
|
1
|
+
// @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext), ./form-journal
|
|
2
2
|
// @output: renderFormPrompt, parseFormAnswer, createFormBridge, FORM_PROMPT_TTL_MS
|
|
3
3
|
// @pos: core - 表单桥接:QQ 同步、作答回传、跨重启恢复与服务端对账。
|
|
4
4
|
//
|
|
@@ -173,7 +173,7 @@ function clipButtonLabel(text: string): string {
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
/** 单选直接提交字符串;多选按钮与文字路径一致,提交单值数组。 */
|
|
176
|
-
export function buildFormKeyboard(form: FormInfo,
|
|
176
|
+
export function buildFormKeyboard(form: FormInfo, _ownerOpenid: string): InlineKeyboard | null {
|
|
177
177
|
const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
|
|
178
178
|
if (visible.length !== 1) return null
|
|
179
179
|
const field = visible[0] as FieldLike
|
|
@@ -183,9 +183,11 @@ export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKe
|
|
|
183
183
|
const buttons: KeyboardButton[] = opts.slice(0, 20).map((opt) => ({
|
|
184
184
|
id: `form-${form.id}-${opt.value}`.slice(0, 64),
|
|
185
185
|
render_data: { label: clipButtonLabel(opt.label), visited_label: clipButtonLabel(`✓ ${opt.label}`), style: 1 },
|
|
186
|
+
// permission 形状对齐腾讯 P0({type:2} 不带 specify_user_ids,同审批卡;
|
|
187
|
+
// 平台校验收敛后冲突形状会导致客户端不渲染键盘)。
|
|
186
188
|
action: {
|
|
187
189
|
type: 1,
|
|
188
|
-
permission: { type: 2
|
|
190
|
+
permission: { type: 2 },
|
|
189
191
|
data: encodeFormButton({ t: "form", f: form.id, k: field.key, v: opt.value }),
|
|
190
192
|
},
|
|
191
193
|
}))
|
|
@@ -207,7 +209,7 @@ export interface FormInteractionEvent {
|
|
|
207
209
|
export interface FormBridgeDeps {
|
|
208
210
|
client: OpencodeClient
|
|
209
211
|
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
210
|
-
safeDeliver: (ctx: MessageContext, text: string) => Promise<
|
|
212
|
+
safeDeliver: (ctx: MessageContext, text: string) => Promise<boolean>
|
|
211
213
|
sendFormCard?: (ctx: MessageContext, form: FormInfo, keyboard: InlineKeyboard) => Promise<boolean>
|
|
212
214
|
/** 测试/嵌入方可显式指定台账;生产默认 ~/.openqq/forms.json 或 QQ_FORM_JOURNAL_FILE。 */
|
|
213
215
|
journalPath?: string
|
|
@@ -247,9 +249,10 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
247
249
|
return tracked
|
|
248
250
|
}
|
|
249
251
|
|
|
250
|
-
function deliver(ctx: MessageContext, text: string): Promise<
|
|
252
|
+
function deliver(ctx: MessageContext, text: string): Promise<boolean> {
|
|
251
253
|
return track(deps.safeDeliver(ctx, text).catch((error) => {
|
|
252
254
|
console.error("[form-bridge] 回执投递失败:", error instanceof Error ? error.message : error)
|
|
255
|
+
return false
|
|
253
256
|
}))
|
|
254
257
|
}
|
|
255
258
|
|
|
@@ -327,7 +330,7 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
327
330
|
if (/AlreadySettled|already|OpenCode API 404/i.test(msg)) {
|
|
328
331
|
// 桌面端先答/先取消是终态;只有明确的服务端冲突才清理。
|
|
329
332
|
if (isCurrent(userId, entry)) clearEntry(userId, entry)
|
|
330
|
-
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ
|
|
333
|
+
await deliver(entry.ctx, "ℹ️ 该选择已在桌面端处理或取消,QQ 卡片已失效;若 AI 再次询问你会立即收到新卡片,也可回桌面处理")
|
|
331
334
|
} else {
|
|
332
335
|
// submitting + answer 保留在内存和磁盘,可手动重试或由 reconcile 续交。
|
|
333
336
|
await deliver(entry.ctx, `⚠️ 提交失败,选择已保留、可在重启后续交:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`)
|
|
@@ -381,7 +384,7 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
381
384
|
}
|
|
382
385
|
clearEntry(userId, entry)
|
|
383
386
|
}
|
|
384
|
-
await deliver(entry.ctx, "⏰ 选择请求已满 30
|
|
387
|
+
await deliver(entry.ctx, "⏰ 选择请求已满 30 分钟未作答,服务端已确认取消;若 AI 再次询问你会立即收到新卡片,也可回桌面处理")
|
|
385
388
|
}
|
|
386
389
|
|
|
387
390
|
function scheduleExpiry(userId: string, entry: InternalPendingForm): void {
|
|
@@ -483,6 +486,12 @@ export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
|
483
486
|
pending.set(userId, entry)
|
|
484
487
|
scheduleExpiry(userId, entry)
|
|
485
488
|
if (previous) {
|
|
489
|
+
// 举一反三(2026-11-05):被取代的旧表单台账必须同步清理——否则非终态记录
|
|
490
|
+
// 永久残留,每次重启都被 restore 重载(updatedAt 比较能防顶替新槽,但僵尸账
|
|
491
|
+
// 无限累积),与 bgWait superseded 同罪。
|
|
492
|
+
try {
|
|
493
|
+
journal.remove(userId, previous.form.id)
|
|
494
|
+
} catch { /* 下次替换/reconcile 再清理 */ }
|
|
486
495
|
void deliver(previous.ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)")
|
|
487
496
|
}
|
|
488
497
|
console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`)
|
package/src/core/form-journal.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
// @input: fs/path/os, ../opencode/client (FormInfo), ../qq/types (MessageContext)
|
|
1
|
+
// @input: fs/path/os, ../opencode/client (FormInfo), ../qq/types (MessageContext)
|
|
2
2
|
// @output: FormJournalEntry, FormJournal, createFormJournal, defaultFormJournalPath
|
|
3
3
|
// @pos: core - 表单交互恢复台账(同步落盘、原子替换、跨进程短临界区锁)
|
|
4
4
|
//
|
|
5
5
|
// 只保存恢复所需数据:表单定义、最小路由 ctx、答案与回显文本。QQ 原事件、附件、
|
|
6
6
|
// 引用内容和被动回复 msgId 一律不落盘;恢复后的通知必须使用主动消息语义。
|
|
7
|
+
import { storageFile } from "./storage.js"
|
|
7
8
|
import {
|
|
8
9
|
closeSync,
|
|
9
10
|
existsSync,
|
|
@@ -15,8 +16,7 @@ import {
|
|
|
15
16
|
unlinkSync,
|
|
16
17
|
writeFileSync,
|
|
17
18
|
} from "fs"
|
|
18
|
-
import { dirname
|
|
19
|
-
import { homedir } from "os"
|
|
19
|
+
import { dirname } from "path"
|
|
20
20
|
import type { FormInfo } from "../opencode/client.js"
|
|
21
21
|
import type { MessageContext } from "../qq/types.js"
|
|
22
22
|
|
|
@@ -53,7 +53,7 @@ const sleepArray = new Int32Array(new SharedArrayBuffer(4))
|
|
|
53
53
|
const STATES = new Set<FormLifecycleState>(["pending", "clickReceived", "submitting", "replied", "cancelled", "expired"])
|
|
54
54
|
|
|
55
55
|
export function defaultFormJournalPath(): string {
|
|
56
|
-
return process.env.QQ_FORM_JOURNAL_FILE ||
|
|
56
|
+
return process.env.QQ_FORM_JOURNAL_FILE || storageFile("forms.json")
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
/** 只保留恢复路由;空 msgId 明确表达重启后使用主动消息,而非复用过期被动窗口。 */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @input: fs/path/os(落盘)、env(窗口可调)
|
|
1
|
+
// @input: fs/path/os(落盘)、env(窗口可调)
|
|
2
2
|
// @output: loadGatewayState, saveGatewayState, clearGatewayState, GATEWAY_STATE_FILE
|
|
3
3
|
// @pos: core - QQ 网关 session/seq 持久化(修复②:重启不再 IDENTIFY 失忆重刷 backlog)
|
|
4
4
|
//
|
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
// op9 InvalidSession 回退 IDENTIFY(gateway 已有该处理路径,无死循环)。
|
|
9
9
|
// 风控:文件只存 session_id/seq/时间戳,无凭据;损坏/超龄一律作废不阻塞启动;
|
|
10
10
|
// 保存走临时文件原子 rename,与台账同风格。
|
|
11
|
+
import { storageFile } from "./storage.js"
|
|
11
12
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync } from "fs"
|
|
12
13
|
import { join } from "path"
|
|
13
|
-
import { homedir } from "os"
|
|
14
14
|
|
|
15
15
|
export interface GatewayPersistState {
|
|
16
16
|
session_id: string
|
|
@@ -18,7 +18,7 @@ export interface GatewayPersistState {
|
|
|
18
18
|
savedAt: number
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export const GATEWAY_STATE_FILE =
|
|
21
|
+
export const GATEWAY_STATE_FILE = storageFile("gateway-state.json")
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* RESUME 尝试窗口:QQ 网关断线会话 TTL 观测约 1h(427 每小时 RESUMED 实证)。
|